compiler-sfc.cjs.js 684 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780578157825783578457855786578757885789579057915792579357945795579657975798579958005801580258035804580558065807580858095810581158125813581458155816581758185819582058215822582358245825582658275828582958305831583258335834583558365837583858395840584158425843584458455846584758485849585058515852585358545855585658575858585958605861586258635864586558665867586858695870587158725873587458755876587758785879588058815882588358845885588658875888588958905891589258935894589558965897589858995900590159025903590459055906590759085909591059115912591359145915591659175918591959205921592259235924592559265927592859295930593159325933593459355936593759385939594059415942594359445945594659475948594959505951595259535954595559565957595859595960596159625963596459655966596759685969597059715972597359745975597659775978597959805981598259835984598559865987598859895990599159925993599459955996599759985999600060016002600360046005600660076008600960106011601260136014601560166017601860196020602160226023602460256026602760286029603060316032603360346035603660376038603960406041604260436044604560466047604860496050605160526053605460556056605760586059606060616062606360646065606660676068606960706071607260736074607560766077607860796080608160826083608460856086608760886089609060916092609360946095609660976098609961006101610261036104610561066107610861096110611161126113611461156116611761186119612061216122612361246125612661276128612961306131613261336134613561366137613861396140614161426143614461456146614761486149615061516152615361546155615661576158615961606161616261636164616561666167616861696170617161726173617461756176617761786179618061816182618361846185618661876188618961906191619261936194619561966197619861996200620162026203620462056206620762086209621062116212621362146215621662176218621962206221622262236224622562266227622862296230623162326233623462356236623762386239624062416242624362446245624662476248624962506251625262536254625562566257625862596260626162626263626462656266626762686269627062716272627362746275627662776278627962806281628262836284628562866287628862896290629162926293629462956296629762986299630063016302630363046305630663076308630963106311631263136314631563166317631863196320632163226323632463256326632763286329633063316332633363346335633663376338633963406341634263436344634563466347634863496350635163526353635463556356635763586359636063616362636363646365636663676368636963706371637263736374637563766377637863796380638163826383638463856386638763886389639063916392639363946395639663976398639964006401640264036404640564066407640864096410641164126413641464156416641764186419642064216422642364246425642664276428642964306431643264336434643564366437643864396440644164426443644464456446644764486449645064516452645364546455645664576458645964606461646264636464646564666467646864696470647164726473647464756476647764786479648064816482648364846485648664876488648964906491649264936494649564966497649864996500650165026503650465056506650765086509651065116512651365146515651665176518651965206521652265236524652565266527652865296530653165326533653465356536653765386539654065416542654365446545654665476548654965506551655265536554655565566557655865596560656165626563656465656566656765686569657065716572657365746575657665776578657965806581658265836584658565866587658865896590659165926593659465956596659765986599660066016602660366046605660666076608660966106611661266136614661566166617661866196620662166226623662466256626662766286629663066316632663366346635663666376638663966406641664266436644664566466647664866496650665166526653665466556656665766586659666066616662666366646665666666676668666966706671667266736674667566766677667866796680668166826683668466856686668766886689669066916692669366946695669666976698669967006701670267036704670567066707670867096710671167126713671467156716671767186719672067216722672367246725672667276728672967306731673267336734673567366737673867396740674167426743674467456746674767486749675067516752675367546755675667576758675967606761676267636764676567666767676867696770677167726773677467756776677767786779678067816782678367846785678667876788678967906791679267936794679567966797679867996800680168026803680468056806680768086809681068116812681368146815681668176818681968206821682268236824682568266827682868296830683168326833683468356836683768386839684068416842684368446845684668476848684968506851685268536854685568566857685868596860686168626863686468656866686768686869687068716872687368746875687668776878687968806881688268836884688568866887688868896890689168926893689468956896689768986899690069016902690369046905690669076908690969106911691269136914691569166917691869196920692169226923692469256926692769286929693069316932693369346935693669376938693969406941694269436944694569466947694869496950695169526953695469556956695769586959696069616962696369646965696669676968696969706971697269736974697569766977697869796980698169826983698469856986698769886989699069916992699369946995699669976998699970007001700270037004700570067007700870097010701170127013701470157016701770187019702070217022702370247025702670277028702970307031703270337034703570367037703870397040704170427043704470457046704770487049705070517052705370547055705670577058705970607061706270637064706570667067706870697070707170727073707470757076707770787079708070817082708370847085708670877088708970907091709270937094709570967097709870997100710171027103710471057106710771087109711071117112711371147115711671177118711971207121712271237124712571267127712871297130713171327133713471357136713771387139714071417142714371447145714671477148714971507151715271537154715571567157715871597160716171627163716471657166716771687169717071717172717371747175717671777178717971807181718271837184718571867187718871897190719171927193719471957196719771987199720072017202720372047205720672077208720972107211721272137214721572167217721872197220722172227223722472257226722772287229723072317232723372347235723672377238723972407241724272437244724572467247724872497250725172527253725472557256725772587259726072617262726372647265726672677268726972707271727272737274727572767277727872797280728172827283728472857286728772887289729072917292729372947295729672977298729973007301730273037304730573067307730873097310731173127313731473157316731773187319732073217322732373247325732673277328732973307331733273337334733573367337733873397340734173427343734473457346734773487349735073517352735373547355735673577358735973607361736273637364736573667367736873697370737173727373737473757376737773787379738073817382738373847385738673877388738973907391739273937394739573967397739873997400740174027403740474057406740774087409741074117412741374147415741674177418741974207421742274237424742574267427742874297430743174327433743474357436743774387439744074417442744374447445744674477448744974507451745274537454745574567457745874597460746174627463746474657466746774687469747074717472747374747475747674777478747974807481748274837484748574867487748874897490749174927493749474957496749774987499750075017502750375047505750675077508750975107511751275137514751575167517751875197520752175227523752475257526752775287529753075317532753375347535753675377538753975407541754275437544754575467547754875497550755175527553755475557556755775587559756075617562756375647565756675677568756975707571757275737574757575767577757875797580758175827583758475857586758775887589759075917592759375947595759675977598759976007601760276037604760576067607760876097610761176127613761476157616761776187619762076217622762376247625762676277628762976307631763276337634763576367637763876397640764176427643764476457646764776487649765076517652765376547655765676577658765976607661766276637664766576667667766876697670767176727673767476757676767776787679768076817682768376847685768676877688768976907691769276937694769576967697769876997700770177027703770477057706770777087709771077117712771377147715771677177718771977207721772277237724772577267727772877297730773177327733773477357736773777387739774077417742774377447745774677477748774977507751775277537754775577567757775877597760776177627763776477657766776777687769777077717772777377747775777677777778777977807781778277837784778577867787778877897790779177927793779477957796779777987799780078017802780378047805780678077808780978107811781278137814781578167817781878197820782178227823782478257826782778287829783078317832783378347835783678377838783978407841784278437844784578467847784878497850785178527853785478557856785778587859786078617862786378647865786678677868786978707871787278737874787578767877787878797880788178827883788478857886788778887889789078917892789378947895789678977898789979007901790279037904790579067907790879097910791179127913791479157916791779187919792079217922792379247925792679277928792979307931793279337934793579367937793879397940794179427943794479457946794779487949795079517952795379547955795679577958795979607961796279637964796579667967796879697970797179727973797479757976797779787979798079817982798379847985798679877988798979907991799279937994799579967997799879998000800180028003800480058006800780088009801080118012801380148015801680178018801980208021802280238024802580268027802880298030803180328033803480358036803780388039804080418042804380448045804680478048804980508051805280538054805580568057805880598060806180628063806480658066806780688069807080718072807380748075807680778078807980808081808280838084808580868087808880898090809180928093809480958096809780988099810081018102810381048105810681078108810981108111811281138114811581168117811881198120812181228123812481258126812781288129813081318132813381348135813681378138813981408141814281438144814581468147814881498150815181528153815481558156815781588159816081618162816381648165816681678168816981708171817281738174817581768177817881798180818181828183818481858186818781888189819081918192819381948195819681978198819982008201820282038204820582068207820882098210821182128213821482158216821782188219822082218222822382248225822682278228822982308231823282338234823582368237823882398240824182428243824482458246824782488249825082518252825382548255825682578258825982608261826282638264826582668267826882698270827182728273827482758276827782788279828082818282828382848285828682878288828982908291829282938294829582968297829882998300830183028303830483058306830783088309831083118312831383148315831683178318831983208321832283238324832583268327832883298330833183328333833483358336833783388339834083418342834383448345834683478348834983508351835283538354835583568357835883598360836183628363836483658366836783688369837083718372837383748375837683778378837983808381838283838384838583868387838883898390839183928393839483958396839783988399840084018402840384048405840684078408840984108411841284138414841584168417841884198420842184228423842484258426842784288429843084318432843384348435843684378438843984408441844284438444844584468447844884498450845184528453845484558456845784588459846084618462846384648465846684678468846984708471847284738474847584768477847884798480848184828483848484858486848784888489849084918492849384948495849684978498849985008501850285038504850585068507850885098510851185128513851485158516851785188519852085218522852385248525852685278528852985308531853285338534853585368537853885398540854185428543854485458546854785488549855085518552855385548555855685578558855985608561856285638564856585668567856885698570857185728573857485758576857785788579858085818582858385848585858685878588858985908591859285938594859585968597859885998600860186028603860486058606860786088609861086118612861386148615861686178618861986208621862286238624862586268627862886298630863186328633863486358636863786388639864086418642864386448645864686478648864986508651865286538654865586568657865886598660866186628663866486658666866786688669867086718672867386748675867686778678867986808681868286838684868586868687868886898690869186928693869486958696869786988699870087018702870387048705870687078708870987108711871287138714871587168717871887198720872187228723872487258726872787288729873087318732873387348735873687378738873987408741874287438744874587468747874887498750875187528753875487558756875787588759876087618762876387648765876687678768876987708771877287738774877587768777877887798780878187828783878487858786878787888789879087918792879387948795879687978798879988008801880288038804880588068807880888098810881188128813881488158816881788188819882088218822882388248825882688278828882988308831883288338834883588368837883888398840884188428843884488458846884788488849885088518852885388548855885688578858885988608861886288638864886588668867886888698870887188728873887488758876887788788879888088818882888388848885888688878888888988908891889288938894889588968897889888998900890189028903890489058906890789088909891089118912891389148915891689178918891989208921892289238924892589268927892889298930893189328933893489358936893789388939894089418942894389448945894689478948894989508951895289538954895589568957895889598960896189628963896489658966896789688969897089718972897389748975897689778978897989808981898289838984898589868987898889898990899189928993899489958996899789988999900090019002900390049005900690079008900990109011901290139014901590169017901890199020902190229023902490259026902790289029903090319032903390349035903690379038903990409041904290439044904590469047904890499050905190529053905490559056905790589059906090619062906390649065906690679068906990709071907290739074907590769077907890799080908190829083908490859086908790889089909090919092909390949095909690979098909991009101910291039104910591069107910891099110911191129113911491159116911791189119912091219122912391249125912691279128912991309131913291339134913591369137913891399140914191429143914491459146914791489149915091519152915391549155915691579158915991609161916291639164916591669167916891699170917191729173917491759176917791789179918091819182918391849185918691879188918991909191919291939194919591969197919891999200920192029203920492059206920792089209921092119212921392149215921692179218921992209221922292239224922592269227922892299230923192329233923492359236923792389239924092419242924392449245924692479248924992509251925292539254925592569257925892599260926192629263926492659266926792689269927092719272927392749275927692779278927992809281928292839284928592869287928892899290929192929293929492959296929792989299930093019302930393049305930693079308930993109311931293139314931593169317931893199320932193229323932493259326932793289329933093319332933393349335933693379338933993409341934293439344934593469347934893499350935193529353935493559356935793589359936093619362936393649365936693679368936993709371937293739374937593769377937893799380938193829383938493859386938793889389939093919392939393949395939693979398939994009401940294039404940594069407940894099410941194129413941494159416941794189419942094219422942394249425942694279428942994309431943294339434943594369437943894399440944194429443944494459446944794489449945094519452945394549455945694579458945994609461946294639464946594669467946894699470947194729473947494759476947794789479948094819482948394849485948694879488948994909491949294939494949594969497949894999500950195029503950495059506950795089509951095119512951395149515951695179518951995209521952295239524952595269527952895299530953195329533953495359536953795389539954095419542954395449545954695479548954995509551955295539554955595569557955895599560956195629563956495659566956795689569957095719572957395749575957695779578957995809581958295839584958595869587958895899590959195929593959495959596959795989599960096019602960396049605960696079608960996109611961296139614961596169617961896199620962196229623962496259626962796289629963096319632963396349635963696379638963996409641964296439644964596469647964896499650965196529653965496559656965796589659966096619662966396649665966696679668966996709671967296739674967596769677967896799680968196829683968496859686968796889689969096919692969396949695969696979698969997009701970297039704970597069707970897099710971197129713971497159716971797189719972097219722972397249725972697279728972997309731973297339734973597369737973897399740974197429743974497459746974797489749975097519752975397549755975697579758975997609761976297639764976597669767976897699770977197729773977497759776977797789779978097819782978397849785978697879788978997909791979297939794979597969797979897999800980198029803980498059806980798089809981098119812981398149815981698179818981998209821982298239824982598269827982898299830983198329833983498359836983798389839984098419842984398449845984698479848984998509851985298539854985598569857985898599860986198629863986498659866986798689869987098719872987398749875987698779878987998809881988298839884988598869887988898899890989198929893989498959896989798989899990099019902990399049905990699079908990999109911991299139914991599169917991899199920992199229923992499259926992799289929993099319932993399349935993699379938993999409941994299439944994599469947994899499950995199529953995499559956995799589959996099619962996399649965996699679968996999709971997299739974997599769977997899799980998199829983998499859986998799889989999099919992999399949995999699979998999910000100011000210003100041000510006100071000810009100101001110012100131001410015100161001710018100191002010021100221002310024100251002610027100281002910030100311003210033100341003510036100371003810039100401004110042100431004410045100461004710048100491005010051100521005310054100551005610057100581005910060100611006210063100641006510066100671006810069100701007110072100731007410075100761007710078100791008010081100821008310084100851008610087100881008910090100911009210093100941009510096100971009810099101001010110102101031010410105101061010710108101091011010111101121011310114101151011610117101181011910120101211012210123101241012510126101271012810129101301013110132101331013410135101361013710138101391014010141101421014310144101451014610147101481014910150101511015210153101541015510156101571015810159101601016110162101631016410165101661016710168101691017010171101721017310174101751017610177101781017910180101811018210183101841018510186101871018810189101901019110192101931019410195101961019710198101991020010201102021020310204102051020610207102081020910210102111021210213102141021510216102171021810219102201022110222102231022410225102261022710228102291023010231102321023310234102351023610237102381023910240102411024210243102441024510246102471024810249102501025110252102531025410255102561025710258102591026010261102621026310264102651026610267102681026910270102711027210273102741027510276102771027810279102801028110282102831028410285102861028710288102891029010291102921029310294102951029610297102981029910300103011030210303103041030510306103071030810309103101031110312103131031410315103161031710318103191032010321103221032310324103251032610327103281032910330103311033210333103341033510336103371033810339103401034110342103431034410345103461034710348103491035010351103521035310354103551035610357103581035910360103611036210363103641036510366103671036810369103701037110372103731037410375103761037710378103791038010381103821038310384103851038610387103881038910390103911039210393103941039510396103971039810399104001040110402104031040410405104061040710408104091041010411104121041310414104151041610417104181041910420104211042210423104241042510426104271042810429104301043110432104331043410435104361043710438104391044010441104421044310444104451044610447104481044910450104511045210453104541045510456104571045810459104601046110462104631046410465104661046710468104691047010471104721047310474104751047610477104781047910480104811048210483104841048510486104871048810489104901049110492104931049410495104961049710498104991050010501105021050310504105051050610507105081050910510105111051210513105141051510516105171051810519105201052110522105231052410525105261052710528105291053010531105321053310534105351053610537105381053910540105411054210543105441054510546105471054810549105501055110552105531055410555105561055710558105591056010561105621056310564105651056610567105681056910570105711057210573105741057510576105771057810579105801058110582105831058410585105861058710588105891059010591105921059310594105951059610597105981059910600106011060210603106041060510606106071060810609106101061110612106131061410615106161061710618106191062010621106221062310624106251062610627106281062910630106311063210633106341063510636106371063810639106401064110642106431064410645106461064710648106491065010651106521065310654106551065610657106581065910660106611066210663106641066510666106671066810669106701067110672106731067410675106761067710678106791068010681106821068310684106851068610687106881068910690106911069210693106941069510696106971069810699107001070110702107031070410705107061070710708107091071010711107121071310714107151071610717107181071910720107211072210723107241072510726107271072810729107301073110732107331073410735107361073710738107391074010741107421074310744107451074610747107481074910750107511075210753107541075510756107571075810759107601076110762107631076410765107661076710768107691077010771107721077310774107751077610777107781077910780107811078210783107841078510786107871078810789107901079110792107931079410795107961079710798107991080010801108021080310804108051080610807108081080910810108111081210813108141081510816108171081810819108201082110822108231082410825108261082710828108291083010831108321083310834108351083610837108381083910840108411084210843108441084510846108471084810849108501085110852108531085410855108561085710858108591086010861108621086310864108651086610867108681086910870108711087210873108741087510876108771087810879108801088110882108831088410885108861088710888108891089010891108921089310894108951089610897108981089910900109011090210903109041090510906109071090810909109101091110912109131091410915109161091710918109191092010921109221092310924109251092610927109281092910930109311093210933109341093510936109371093810939109401094110942109431094410945109461094710948109491095010951109521095310954109551095610957109581095910960109611096210963109641096510966109671096810969109701097110972109731097410975109761097710978109791098010981109821098310984109851098610987109881098910990109911099210993109941099510996109971099810999110001100111002110031100411005110061100711008110091101011011110121101311014110151101611017110181101911020110211102211023110241102511026110271102811029110301103111032110331103411035110361103711038110391104011041110421104311044110451104611047110481104911050110511105211053110541105511056110571105811059110601106111062110631106411065110661106711068110691107011071110721107311074110751107611077110781107911080110811108211083110841108511086110871108811089110901109111092110931109411095110961109711098110991110011101111021110311104111051110611107111081110911110111111111211113111141111511116111171111811119111201112111122111231112411125111261112711128111291113011131111321113311134111351113611137111381113911140111411114211143111441114511146111471114811149111501115111152111531115411155111561115711158111591116011161111621116311164111651116611167111681116911170111711117211173111741117511176111771117811179111801118111182111831118411185111861118711188111891119011191111921119311194111951119611197111981119911200112011120211203112041120511206112071120811209112101121111212112131121411215112161121711218112191122011221112221122311224112251122611227112281122911230112311123211233112341123511236112371123811239112401124111242112431124411245112461124711248112491125011251112521125311254112551125611257112581125911260112611126211263112641126511266112671126811269112701127111272112731127411275112761127711278112791128011281112821128311284112851128611287112881128911290112911129211293112941129511296112971129811299113001130111302113031130411305113061130711308113091131011311113121131311314113151131611317113181131911320113211132211323113241132511326113271132811329113301133111332113331133411335113361133711338113391134011341113421134311344113451134611347113481134911350113511135211353113541135511356113571135811359113601136111362113631136411365113661136711368113691137011371113721137311374113751137611377113781137911380113811138211383113841138511386113871138811389113901139111392113931139411395113961139711398113991140011401114021140311404114051140611407114081140911410114111141211413114141141511416114171141811419114201142111422114231142411425114261142711428114291143011431114321143311434114351143611437114381143911440114411144211443114441144511446114471144811449114501145111452114531145411455114561145711458114591146011461114621146311464114651146611467114681146911470114711147211473114741147511476114771147811479114801148111482114831148411485114861148711488114891149011491114921149311494114951149611497114981149911500115011150211503115041150511506115071150811509115101151111512115131151411515115161151711518115191152011521115221152311524115251152611527115281152911530115311153211533115341153511536115371153811539115401154111542115431154411545115461154711548115491155011551115521155311554115551155611557115581155911560115611156211563115641156511566115671156811569115701157111572115731157411575115761157711578115791158011581115821158311584115851158611587115881158911590115911159211593115941159511596115971159811599116001160111602116031160411605116061160711608116091161011611116121161311614116151161611617116181161911620116211162211623116241162511626116271162811629116301163111632116331163411635116361163711638116391164011641116421164311644116451164611647116481164911650116511165211653116541165511656116571165811659116601166111662116631166411665116661166711668116691167011671116721167311674116751167611677116781167911680116811168211683116841168511686116871168811689116901169111692116931169411695116961169711698116991170011701117021170311704117051170611707117081170911710117111171211713117141171511716117171171811719117201172111722117231172411725117261172711728117291173011731117321173311734117351173611737117381173911740117411174211743117441174511746117471174811749117501175111752117531175411755117561175711758117591176011761117621176311764117651176611767117681176911770117711177211773117741177511776117771177811779117801178111782117831178411785117861178711788117891179011791117921179311794117951179611797117981179911800118011180211803118041180511806118071180811809118101181111812118131181411815118161181711818118191182011821118221182311824118251182611827118281182911830118311183211833118341183511836118371183811839118401184111842118431184411845118461184711848118491185011851118521185311854118551185611857118581185911860118611186211863118641186511866118671186811869118701187111872118731187411875118761187711878118791188011881118821188311884118851188611887118881188911890118911189211893118941189511896118971189811899119001190111902119031190411905119061190711908119091191011911119121191311914119151191611917119181191911920119211192211923119241192511926119271192811929119301193111932119331193411935119361193711938119391194011941119421194311944119451194611947119481194911950119511195211953119541195511956119571195811959119601196111962119631196411965119661196711968119691197011971119721197311974119751197611977119781197911980119811198211983119841198511986119871198811989119901199111992119931199411995119961199711998119991200012001120021200312004120051200612007120081200912010120111201212013120141201512016120171201812019120201202112022120231202412025120261202712028120291203012031120321203312034120351203612037120381203912040120411204212043120441204512046120471204812049120501205112052120531205412055120561205712058120591206012061120621206312064120651206612067120681206912070120711207212073120741207512076120771207812079120801208112082120831208412085120861208712088120891209012091120921209312094120951209612097120981209912100121011210212103121041210512106121071210812109121101211112112121131211412115121161211712118121191212012121121221212312124121251212612127121281212912130121311213212133121341213512136121371213812139121401214112142121431214412145121461214712148121491215012151121521215312154121551215612157121581215912160121611216212163121641216512166121671216812169121701217112172121731217412175121761217712178121791218012181121821218312184121851218612187121881218912190121911219212193121941219512196121971219812199122001220112202122031220412205122061220712208122091221012211122121221312214122151221612217122181221912220122211222212223122241222512226122271222812229122301223112232122331223412235122361223712238122391224012241122421224312244122451224612247122481224912250122511225212253122541225512256122571225812259122601226112262122631226412265122661226712268122691227012271122721227312274122751227612277122781227912280122811228212283122841228512286122871228812289122901229112292122931229412295122961229712298122991230012301123021230312304123051230612307123081230912310123111231212313123141231512316123171231812319123201232112322123231232412325123261232712328123291233012331123321233312334123351233612337123381233912340123411234212343123441234512346123471234812349123501235112352123531235412355123561235712358123591236012361123621236312364123651236612367123681236912370123711237212373123741237512376123771237812379123801238112382123831238412385123861238712388123891239012391123921239312394123951239612397123981239912400124011240212403124041240512406124071240812409124101241112412124131241412415124161241712418124191242012421124221242312424124251242612427124281242912430124311243212433124341243512436124371243812439124401244112442124431244412445124461244712448124491245012451124521245312454124551245612457124581245912460124611246212463124641246512466124671246812469124701247112472124731247412475124761247712478124791248012481124821248312484124851248612487124881248912490124911249212493124941249512496124971249812499125001250112502125031250412505125061250712508125091251012511125121251312514125151251612517125181251912520125211252212523125241252512526125271252812529125301253112532125331253412535125361253712538125391254012541125421254312544125451254612547125481254912550125511255212553125541255512556125571255812559125601256112562125631256412565125661256712568125691257012571125721257312574125751257612577125781257912580125811258212583125841258512586125871258812589125901259112592125931259412595125961259712598125991260012601126021260312604126051260612607126081260912610126111261212613126141261512616126171261812619126201262112622126231262412625126261262712628126291263012631126321263312634126351263612637126381263912640126411264212643126441264512646126471264812649126501265112652126531265412655126561265712658126591266012661126621266312664126651266612667126681266912670126711267212673126741267512676126771267812679126801268112682126831268412685126861268712688126891269012691126921269312694126951269612697126981269912700127011270212703127041270512706127071270812709127101271112712127131271412715127161271712718127191272012721127221272312724127251272612727127281272912730127311273212733127341273512736127371273812739127401274112742127431274412745127461274712748127491275012751127521275312754127551275612757127581275912760127611276212763127641276512766127671276812769127701277112772127731277412775127761277712778127791278012781127821278312784127851278612787127881278912790127911279212793127941279512796127971279812799128001280112802128031280412805128061280712808128091281012811128121281312814128151281612817128181281912820128211282212823128241282512826128271282812829128301283112832128331283412835128361283712838128391284012841128421284312844128451284612847128481284912850128511285212853128541285512856128571285812859128601286112862128631286412865128661286712868128691287012871128721287312874128751287612877128781287912880128811288212883128841288512886128871288812889128901289112892128931289412895128961289712898128991290012901129021290312904129051290612907129081290912910129111291212913129141291512916129171291812919129201292112922129231292412925129261292712928129291293012931129321293312934129351293612937129381293912940129411294212943129441294512946129471294812949129501295112952129531295412955129561295712958129591296012961129621296312964129651296612967129681296912970129711297212973129741297512976129771297812979129801298112982129831298412985129861298712988129891299012991129921299312994129951299612997129981299913000130011300213003130041300513006130071300813009130101301113012130131301413015130161301713018130191302013021130221302313024130251302613027130281302913030130311303213033130341303513036130371303813039130401304113042130431304413045130461304713048130491305013051130521305313054130551305613057130581305913060130611306213063130641306513066130671306813069130701307113072130731307413075130761307713078130791308013081130821308313084130851308613087130881308913090130911309213093130941309513096130971309813099131001310113102131031310413105131061310713108131091311013111131121311313114131151311613117131181311913120131211312213123131241312513126131271312813129131301313113132131331313413135131361313713138131391314013141131421314313144131451314613147131481314913150131511315213153131541315513156131571315813159131601316113162131631316413165131661316713168131691317013171131721317313174131751317613177131781317913180131811318213183131841318513186131871318813189131901319113192131931319413195131961319713198131991320013201132021320313204132051320613207132081320913210132111321213213132141321513216132171321813219132201322113222132231322413225132261322713228132291323013231132321323313234132351323613237132381323913240132411324213243132441324513246132471324813249132501325113252132531325413255132561325713258132591326013261132621326313264132651326613267132681326913270132711327213273132741327513276132771327813279132801328113282132831328413285132861328713288132891329013291132921329313294132951329613297132981329913300133011330213303133041330513306133071330813309133101331113312133131331413315133161331713318133191332013321133221332313324133251332613327133281332913330133311333213333133341333513336133371333813339133401334113342133431334413345133461334713348133491335013351133521335313354133551335613357133581335913360133611336213363133641336513366133671336813369133701337113372133731337413375133761337713378133791338013381133821338313384133851338613387133881338913390133911339213393133941339513396133971339813399134001340113402134031340413405134061340713408134091341013411134121341313414134151341613417134181341913420134211342213423134241342513426134271342813429134301343113432134331343413435134361343713438134391344013441134421344313444134451344613447134481344913450134511345213453134541345513456134571345813459134601346113462134631346413465134661346713468134691347013471134721347313474134751347613477134781347913480134811348213483134841348513486134871348813489134901349113492134931349413495134961349713498134991350013501135021350313504135051350613507135081350913510135111351213513135141351513516135171351813519135201352113522135231352413525135261352713528135291353013531135321353313534135351353613537135381353913540135411354213543135441354513546135471354813549135501355113552135531355413555135561355713558135591356013561135621356313564135651356613567135681356913570135711357213573135741357513576135771357813579135801358113582135831358413585135861358713588135891359013591135921359313594135951359613597135981359913600136011360213603136041360513606136071360813609136101361113612136131361413615136161361713618136191362013621136221362313624136251362613627136281362913630136311363213633136341363513636136371363813639136401364113642136431364413645136461364713648136491365013651136521365313654136551365613657136581365913660136611366213663136641366513666136671366813669136701367113672136731367413675136761367713678136791368013681136821368313684136851368613687136881368913690136911369213693136941369513696136971369813699137001370113702137031370413705137061370713708137091371013711137121371313714137151371613717137181371913720137211372213723137241372513726137271372813729137301373113732137331373413735137361373713738137391374013741137421374313744137451374613747137481374913750137511375213753137541375513756137571375813759137601376113762137631376413765137661376713768137691377013771137721377313774137751377613777137781377913780137811378213783137841378513786137871378813789137901379113792137931379413795137961379713798137991380013801138021380313804138051380613807138081380913810138111381213813138141381513816138171381813819138201382113822138231382413825138261382713828138291383013831138321383313834138351383613837138381383913840138411384213843138441384513846138471384813849138501385113852138531385413855138561385713858138591386013861138621386313864138651386613867138681386913870138711387213873138741387513876138771387813879138801388113882138831388413885138861388713888138891389013891138921389313894138951389613897138981389913900139011390213903139041390513906139071390813909139101391113912139131391413915139161391713918139191392013921139221392313924139251392613927139281392913930139311393213933139341393513936139371393813939139401394113942139431394413945139461394713948139491395013951139521395313954139551395613957139581395913960139611396213963139641396513966139671396813969139701397113972139731397413975139761397713978139791398013981139821398313984139851398613987139881398913990139911399213993139941399513996139971399813999140001400114002140031400414005140061400714008140091401014011140121401314014140151401614017140181401914020140211402214023140241402514026140271402814029140301403114032140331403414035140361403714038140391404014041140421404314044140451404614047140481404914050140511405214053140541405514056140571405814059140601406114062140631406414065140661406714068140691407014071140721407314074140751407614077140781407914080140811408214083140841408514086140871408814089140901409114092140931409414095140961409714098140991410014101141021410314104141051410614107141081410914110141111411214113141141411514116141171411814119141201412114122141231412414125141261412714128141291413014131141321413314134141351413614137141381413914140141411414214143141441414514146141471414814149141501415114152141531415414155141561415714158141591416014161141621416314164141651416614167141681416914170141711417214173141741417514176141771417814179141801418114182141831418414185141861418714188141891419014191141921419314194141951419614197141981419914200142011420214203142041420514206142071420814209142101421114212142131421414215142161421714218142191422014221142221422314224142251422614227142281422914230142311423214233142341423514236142371423814239142401424114242142431424414245142461424714248142491425014251142521425314254142551425614257142581425914260142611426214263142641426514266142671426814269142701427114272142731427414275142761427714278142791428014281142821428314284142851428614287142881428914290142911429214293142941429514296142971429814299143001430114302143031430414305143061430714308143091431014311143121431314314143151431614317143181431914320143211432214323143241432514326143271432814329143301433114332143331433414335143361433714338143391434014341143421434314344143451434614347143481434914350143511435214353143541435514356143571435814359143601436114362143631436414365143661436714368143691437014371143721437314374143751437614377143781437914380143811438214383143841438514386143871438814389143901439114392143931439414395143961439714398143991440014401144021440314404144051440614407144081440914410144111441214413144141441514416144171441814419144201442114422144231442414425144261442714428144291443014431144321443314434144351443614437144381443914440144411444214443144441444514446144471444814449144501445114452144531445414455144561445714458144591446014461144621446314464144651446614467144681446914470144711447214473144741447514476144771447814479144801448114482144831448414485144861448714488144891449014491144921449314494144951449614497144981449914500145011450214503145041450514506145071450814509145101451114512145131451414515145161451714518145191452014521145221452314524145251452614527145281452914530145311453214533145341453514536145371453814539145401454114542145431454414545145461454714548145491455014551145521455314554145551455614557145581455914560145611456214563145641456514566145671456814569145701457114572145731457414575145761457714578145791458014581145821458314584145851458614587145881458914590145911459214593145941459514596145971459814599146001460114602146031460414605146061460714608146091461014611146121461314614146151461614617146181461914620146211462214623146241462514626146271462814629146301463114632146331463414635146361463714638146391464014641146421464314644146451464614647146481464914650146511465214653146541465514656146571465814659146601466114662146631466414665146661466714668146691467014671146721467314674146751467614677146781467914680146811468214683146841468514686146871468814689146901469114692146931469414695146961469714698146991470014701147021470314704147051470614707147081470914710147111471214713147141471514716147171471814719147201472114722147231472414725147261472714728147291473014731147321473314734147351473614737147381473914740147411474214743147441474514746147471474814749147501475114752147531475414755147561475714758147591476014761147621476314764147651476614767147681476914770147711477214773147741477514776147771477814779147801478114782147831478414785147861478714788147891479014791147921479314794147951479614797147981479914800148011480214803148041480514806148071480814809148101481114812148131481414815148161481714818148191482014821148221482314824148251482614827148281482914830148311483214833148341483514836148371483814839148401484114842148431484414845148461484714848148491485014851148521485314854148551485614857148581485914860148611486214863148641486514866148671486814869148701487114872148731487414875148761487714878148791488014881148821488314884148851488614887148881488914890148911489214893148941489514896148971489814899149001490114902149031490414905149061490714908149091491014911149121491314914149151491614917149181491914920149211492214923149241492514926149271492814929149301493114932149331493414935149361493714938149391494014941149421494314944149451494614947149481494914950149511495214953149541495514956149571495814959149601496114962149631496414965149661496714968149691497014971149721497314974149751497614977149781497914980149811498214983149841498514986149871498814989149901499114992149931499414995149961499714998149991500015001150021500315004150051500615007150081500915010150111501215013150141501515016150171501815019150201502115022150231502415025150261502715028150291503015031150321503315034150351503615037150381503915040150411504215043150441504515046150471504815049150501505115052150531505415055150561505715058150591506015061150621506315064150651506615067150681506915070150711507215073150741507515076150771507815079150801508115082150831508415085150861508715088150891509015091150921509315094150951509615097150981509915100151011510215103151041510515106151071510815109151101511115112151131511415115151161511715118151191512015121151221512315124151251512615127151281512915130151311513215133151341513515136151371513815139151401514115142151431514415145151461514715148151491515015151151521515315154151551515615157151581515915160151611516215163151641516515166151671516815169151701517115172151731517415175151761517715178151791518015181151821518315184151851518615187151881518915190151911519215193151941519515196151971519815199152001520115202152031520415205152061520715208152091521015211152121521315214152151521615217152181521915220152211522215223152241522515226152271522815229152301523115232152331523415235152361523715238152391524015241152421524315244152451524615247152481524915250152511525215253152541525515256152571525815259152601526115262152631526415265152661526715268152691527015271152721527315274152751527615277152781527915280152811528215283152841528515286152871528815289152901529115292152931529415295152961529715298152991530015301153021530315304153051530615307153081530915310153111531215313153141531515316153171531815319153201532115322153231532415325153261532715328153291533015331153321533315334153351533615337153381533915340153411534215343153441534515346153471534815349153501535115352153531535415355153561535715358153591536015361153621536315364153651536615367153681536915370153711537215373153741537515376153771537815379153801538115382153831538415385153861538715388153891539015391153921539315394153951539615397153981539915400154011540215403154041540515406154071540815409154101541115412154131541415415154161541715418154191542015421154221542315424154251542615427154281542915430154311543215433154341543515436154371543815439154401544115442154431544415445154461544715448154491545015451154521545315454154551545615457154581545915460154611546215463154641546515466154671546815469154701547115472154731547415475154761547715478154791548015481154821548315484154851548615487154881548915490154911549215493154941549515496154971549815499155001550115502155031550415505155061550715508155091551015511155121551315514155151551615517155181551915520155211552215523155241552515526155271552815529155301553115532155331553415535155361553715538155391554015541155421554315544155451554615547155481554915550155511555215553155541555515556155571555815559155601556115562155631556415565155661556715568155691557015571155721557315574155751557615577155781557915580155811558215583155841558515586155871558815589155901559115592155931559415595155961559715598155991560015601156021560315604156051560615607156081560915610156111561215613156141561515616156171561815619156201562115622156231562415625156261562715628156291563015631156321563315634156351563615637156381563915640156411564215643156441564515646156471564815649156501565115652156531565415655156561565715658156591566015661156621566315664156651566615667156681566915670156711567215673156741567515676156771567815679156801568115682156831568415685156861568715688156891569015691156921569315694156951569615697156981569915700157011570215703157041570515706157071570815709157101571115712157131571415715157161571715718157191572015721157221572315724157251572615727157281572915730157311573215733157341573515736157371573815739157401574115742157431574415745157461574715748157491575015751157521575315754157551575615757157581575915760157611576215763157641576515766157671576815769157701577115772157731577415775157761577715778157791578015781157821578315784157851578615787157881578915790157911579215793157941579515796157971579815799158001580115802158031580415805158061580715808158091581015811158121581315814158151581615817158181581915820158211582215823158241582515826158271582815829158301583115832158331583415835158361583715838158391584015841158421584315844158451584615847158481584915850158511585215853158541585515856158571585815859158601586115862158631586415865158661586715868158691587015871158721587315874158751587615877158781587915880158811588215883158841588515886158871588815889158901589115892158931589415895158961589715898158991590015901159021590315904159051590615907159081590915910159111591215913159141591515916159171591815919159201592115922159231592415925159261592715928159291593015931159321593315934159351593615937159381593915940159411594215943159441594515946159471594815949159501595115952159531595415955159561595715958159591596015961159621596315964159651596615967159681596915970159711597215973159741597515976159771597815979159801598115982159831598415985159861598715988159891599015991159921599315994159951599615997159981599916000160011600216003160041600516006160071600816009160101601116012160131601416015160161601716018160191602016021160221602316024160251602616027160281602916030160311603216033160341603516036160371603816039160401604116042160431604416045160461604716048160491605016051160521605316054160551605616057160581605916060160611606216063160641606516066160671606816069160701607116072160731607416075160761607716078160791608016081160821608316084160851608616087160881608916090160911609216093160941609516096160971609816099161001610116102161031610416105161061610716108161091611016111161121611316114161151611616117161181611916120161211612216123161241612516126161271612816129161301613116132161331613416135161361613716138161391614016141161421614316144161451614616147161481614916150161511615216153161541615516156161571615816159161601616116162161631616416165161661616716168161691617016171161721617316174161751617616177161781617916180161811618216183161841618516186161871618816189161901619116192161931619416195161961619716198161991620016201162021620316204162051620616207162081620916210162111621216213162141621516216162171621816219162201622116222162231622416225162261622716228162291623016231162321623316234162351623616237162381623916240162411624216243162441624516246162471624816249162501625116252162531625416255162561625716258162591626016261162621626316264162651626616267162681626916270162711627216273162741627516276162771627816279162801628116282162831628416285162861628716288162891629016291162921629316294162951629616297162981629916300163011630216303163041630516306163071630816309163101631116312163131631416315163161631716318163191632016321163221632316324163251632616327163281632916330163311633216333163341633516336163371633816339163401634116342163431634416345163461634716348163491635016351163521635316354163551635616357163581635916360163611636216363163641636516366163671636816369163701637116372163731637416375163761637716378163791638016381163821638316384163851638616387163881638916390163911639216393163941639516396163971639816399164001640116402164031640416405164061640716408164091641016411164121641316414164151641616417164181641916420164211642216423164241642516426164271642816429164301643116432164331643416435164361643716438164391644016441164421644316444164451644616447164481644916450164511645216453164541645516456164571645816459164601646116462164631646416465164661646716468164691647016471164721647316474164751647616477164781647916480164811648216483164841648516486164871648816489164901649116492164931649416495164961649716498164991650016501165021650316504165051650616507165081650916510165111651216513165141651516516165171651816519165201652116522165231652416525165261652716528165291653016531165321653316534165351653616537165381653916540165411654216543165441654516546165471654816549165501655116552165531655416555165561655716558165591656016561165621656316564165651656616567165681656916570165711657216573165741657516576165771657816579165801658116582165831658416585165861658716588165891659016591165921659316594165951659616597165981659916600166011660216603166041660516606166071660816609166101661116612166131661416615166161661716618166191662016621166221662316624166251662616627166281662916630166311663216633166341663516636166371663816639166401664116642166431664416645166461664716648166491665016651166521665316654166551665616657166581665916660166611666216663166641666516666166671666816669166701667116672166731667416675166761667716678166791668016681166821668316684166851668616687166881668916690166911669216693166941669516696166971669816699167001670116702167031670416705167061670716708167091671016711167121671316714167151671616717167181671916720167211672216723167241672516726167271672816729167301673116732167331673416735167361673716738167391674016741167421674316744167451674616747167481674916750167511675216753167541675516756167571675816759167601676116762167631676416765167661676716768167691677016771167721677316774167751677616777167781677916780167811678216783167841678516786167871678816789167901679116792167931679416795167961679716798167991680016801168021680316804168051680616807168081680916810168111681216813168141681516816168171681816819168201682116822168231682416825168261682716828168291683016831168321683316834168351683616837168381683916840168411684216843168441684516846168471684816849168501685116852168531685416855168561685716858168591686016861168621686316864168651686616867168681686916870168711687216873168741687516876168771687816879168801688116882168831688416885168861688716888168891689016891168921689316894168951689616897168981689916900169011690216903169041690516906169071690816909169101691116912169131691416915169161691716918169191692016921169221692316924169251692616927169281692916930169311693216933169341693516936169371693816939169401694116942169431694416945169461694716948169491695016951169521695316954169551695616957169581695916960169611696216963169641696516966169671696816969169701697116972169731697416975169761697716978169791698016981169821698316984169851698616987169881698916990169911699216993169941699516996169971699816999170001700117002170031700417005170061700717008170091701017011170121701317014170151701617017170181701917020170211702217023170241702517026170271702817029170301703117032170331703417035170361703717038170391704017041170421704317044170451704617047170481704917050170511705217053170541705517056170571705817059170601706117062170631706417065170661706717068170691707017071170721707317074170751707617077170781707917080170811708217083170841708517086170871708817089170901709117092170931709417095170961709717098170991710017101171021710317104171051710617107171081710917110171111711217113171141711517116171171711817119171201712117122171231712417125171261712717128171291713017131171321713317134171351713617137171381713917140171411714217143171441714517146171471714817149171501715117152171531715417155171561715717158171591716017161171621716317164171651716617167171681716917170171711717217173171741717517176171771717817179171801718117182171831718417185171861718717188171891719017191171921719317194171951719617197171981719917200172011720217203172041720517206172071720817209172101721117212172131721417215172161721717218172191722017221172221722317224172251722617227172281722917230172311723217233172341723517236172371723817239172401724117242172431724417245172461724717248172491725017251172521725317254172551725617257172581725917260172611726217263172641726517266172671726817269172701727117272172731727417275172761727717278172791728017281172821728317284172851728617287172881728917290172911729217293172941729517296172971729817299173001730117302173031730417305173061730717308173091731017311173121731317314173151731617317173181731917320173211732217323173241732517326173271732817329173301733117332173331733417335173361733717338173391734017341173421734317344173451734617347173481734917350173511735217353173541735517356173571735817359173601736117362173631736417365173661736717368173691737017371173721737317374173751737617377173781737917380173811738217383173841738517386173871738817389173901739117392173931739417395173961739717398173991740017401174021740317404174051740617407174081740917410174111741217413174141741517416174171741817419174201742117422174231742417425174261742717428174291743017431174321743317434174351743617437174381743917440174411744217443174441744517446174471744817449174501745117452174531745417455174561745717458174591746017461174621746317464174651746617467174681746917470174711747217473174741747517476174771747817479174801748117482174831748417485174861748717488174891749017491174921749317494174951749617497174981749917500175011750217503175041750517506175071750817509175101751117512175131751417515175161751717518175191752017521175221752317524175251752617527175281752917530175311753217533175341753517536175371753817539175401754117542175431754417545175461754717548175491755017551175521755317554175551755617557175581755917560175611756217563175641756517566175671756817569175701757117572175731757417575175761757717578175791758017581175821758317584175851758617587175881758917590175911759217593175941759517596175971759817599176001760117602176031760417605176061760717608176091761017611176121761317614176151761617617176181761917620176211762217623176241762517626176271762817629176301763117632176331763417635176361763717638176391764017641176421764317644176451764617647176481764917650176511765217653176541765517656176571765817659176601766117662176631766417665176661766717668176691767017671176721767317674176751767617677176781767917680176811768217683176841768517686176871768817689176901769117692176931769417695176961769717698176991770017701177021770317704177051770617707177081770917710177111771217713177141771517716177171771817719177201772117722177231772417725177261772717728177291773017731177321773317734177351773617737177381773917740177411774217743177441774517746177471774817749177501775117752177531775417755177561775717758177591776017761177621776317764177651776617767177681776917770177711777217773177741777517776177771777817779177801778117782177831778417785177861778717788177891779017791177921779317794177951779617797177981779917800178011780217803178041780517806178071780817809178101781117812178131781417815178161781717818178191782017821178221782317824178251782617827178281782917830178311783217833178341783517836178371783817839178401784117842178431784417845178461784717848178491785017851178521785317854178551785617857178581785917860178611786217863178641786517866178671786817869178701787117872178731787417875178761787717878178791788017881178821788317884178851788617887178881788917890178911789217893178941789517896178971789817899179001790117902179031790417905179061790717908179091791017911179121791317914179151791617917179181791917920179211792217923179241792517926179271792817929179301793117932179331793417935179361793717938179391794017941179421794317944179451794617947179481794917950179511795217953179541795517956179571795817959179601796117962179631796417965179661796717968179691797017971179721797317974179751797617977179781797917980179811798217983179841798517986179871798817989179901799117992179931799417995179961799717998179991800018001180021800318004180051800618007180081800918010180111801218013180141801518016180171801818019180201802118022180231802418025180261802718028180291803018031180321803318034180351803618037180381803918040180411804218043180441804518046180471804818049180501805118052180531805418055180561805718058180591806018061180621806318064180651806618067180681806918070180711807218073180741807518076180771807818079180801808118082180831808418085180861808718088180891809018091180921809318094180951809618097180981809918100181011810218103181041810518106181071810818109181101811118112181131811418115181161811718118181191812018121181221812318124181251812618127181281812918130181311813218133181341813518136181371813818139181401814118142181431814418145181461814718148181491815018151181521815318154181551815618157181581815918160181611816218163181641816518166181671816818169181701817118172181731817418175181761817718178181791818018181181821818318184181851818618187181881818918190181911819218193181941819518196181971819818199182001820118202182031820418205182061820718208182091821018211182121821318214182151821618217182181821918220182211822218223182241822518226182271822818229182301823118232182331823418235182361823718238182391824018241182421824318244182451824618247182481824918250182511825218253182541825518256182571825818259182601826118262182631826418265182661826718268182691827018271182721827318274182751827618277182781827918280182811828218283182841828518286182871828818289182901829118292182931829418295182961829718298182991830018301183021830318304183051830618307183081830918310183111831218313183141831518316183171831818319183201832118322183231832418325183261832718328183291833018331183321833318334183351833618337183381833918340183411834218343183441834518346183471834818349183501835118352183531835418355183561835718358183591836018361183621836318364183651836618367183681836918370183711837218373183741837518376183771837818379183801838118382183831838418385183861838718388183891839018391183921839318394183951839618397183981839918400184011840218403184041840518406184071840818409184101841118412184131841418415184161841718418184191842018421184221842318424184251842618427184281842918430184311843218433184341843518436184371843818439184401844118442184431844418445184461844718448184491845018451184521845318454184551845618457184581845918460184611846218463184641846518466184671846818469184701847118472184731847418475184761847718478184791848018481184821848318484184851848618487184881848918490184911849218493184941849518496184971849818499185001850118502185031850418505185061850718508185091851018511185121851318514185151851618517185181851918520185211852218523185241852518526185271852818529185301853118532185331853418535185361853718538185391854018541185421854318544185451854618547185481854918550185511855218553185541855518556185571855818559185601856118562185631856418565185661856718568185691857018571185721857318574185751857618577185781857918580185811858218583185841858518586185871858818589185901859118592185931859418595185961859718598185991860018601186021860318604186051860618607186081860918610186111861218613186141861518616186171861818619186201862118622186231862418625186261862718628186291863018631186321863318634186351863618637186381863918640186411864218643186441864518646186471864818649186501865118652186531865418655186561865718658186591866018661186621866318664186651866618667186681866918670186711867218673186741867518676186771867818679186801868118682186831868418685186861868718688186891869018691186921869318694186951869618697186981869918700187011870218703187041870518706187071870818709187101871118712187131871418715187161871718718187191872018721187221872318724187251872618727187281872918730187311873218733187341873518736187371873818739187401874118742187431874418745187461874718748187491875018751187521875318754187551875618757187581875918760187611876218763187641876518766187671876818769187701877118772187731877418775187761877718778187791878018781187821878318784187851878618787187881878918790187911879218793187941879518796187971879818799188001880118802188031880418805188061880718808188091881018811188121881318814188151881618817188181881918820188211882218823188241882518826188271882818829188301883118832188331883418835188361883718838188391884018841188421884318844188451884618847188481884918850188511885218853188541885518856188571885818859188601886118862188631886418865188661886718868188691887018871188721887318874188751887618877188781887918880188811888218883188841888518886188871888818889188901889118892188931889418895188961889718898188991890018901189021890318904189051890618907189081890918910189111891218913189141891518916189171891818919189201892118922189231892418925189261892718928189291893018931189321893318934189351893618937189381893918940189411894218943189441894518946189471894818949189501895118952189531895418955189561895718958189591896018961189621896318964189651896618967189681896918970189711897218973189741897518976189771897818979189801898118982189831898418985189861898718988189891899018991189921899318994189951899618997189981899919000190011900219003190041900519006190071900819009190101901119012190131901419015190161901719018190191902019021190221902319024190251902619027190281902919030190311903219033190341903519036190371903819039190401904119042190431904419045190461904719048190491905019051190521905319054190551905619057190581905919060190611906219063190641906519066190671906819069190701907119072190731907419075190761907719078190791908019081190821908319084190851908619087190881908919090190911909219093190941909519096190971909819099191001910119102191031910419105191061910719108191091911019111191121911319114191151911619117191181911919120191211912219123191241912519126191271912819129191301913119132191331913419135191361913719138191391914019141191421914319144191451914619147191481914919150191511915219153191541915519156191571915819159191601916119162191631916419165191661916719168191691917019171191721917319174191751917619177191781917919180191811918219183191841918519186191871918819189191901919119192191931919419195191961919719198191991920019201192021920319204192051920619207192081920919210192111921219213192141921519216192171921819219192201922119222192231922419225192261922719228192291923019231192321923319234192351923619237192381923919240192411924219243192441924519246192471924819249192501925119252192531925419255192561925719258192591926019261192621926319264192651926619267192681926919270192711927219273192741927519276192771927819279192801928119282192831928419285192861928719288192891929019291192921929319294192951929619297192981929919300193011930219303193041930519306193071930819309193101931119312193131931419315193161931719318193191932019321193221932319324193251932619327193281932919330193311933219333193341933519336193371933819339193401934119342193431934419345193461934719348193491935019351193521935319354193551935619357193581935919360193611936219363193641936519366193671936819369193701937119372193731937419375193761937719378193791938019381193821938319384193851938619387193881938919390193911939219393193941939519396193971939819399194001940119402194031940419405194061940719408194091941019411194121941319414194151941619417194181941919420194211942219423194241942519426194271942819429194301943119432194331943419435194361943719438194391944019441194421944319444194451944619447194481944919450194511945219453194541945519456194571945819459194601946119462194631946419465194661946719468194691947019471194721947319474194751947619477194781947919480194811948219483194841948519486194871948819489194901949119492194931949419495194961949719498194991950019501195021950319504195051950619507195081950919510195111951219513195141951519516195171951819519195201952119522195231952419525195261952719528195291953019531195321953319534195351953619537195381953919540195411954219543195441954519546195471954819549195501955119552195531955419555195561955719558195591956019561195621956319564195651956619567195681956919570195711957219573195741957519576195771957819579195801958119582195831958419585195861958719588195891959019591195921959319594195951959619597195981959919600196011960219603196041960519606196071960819609196101961119612196131961419615196161961719618196191962019621196221962319624196251962619627196281962919630196311963219633196341963519636196371963819639196401964119642196431964419645196461964719648196491965019651196521965319654196551965619657196581965919660196611966219663196641966519666196671966819669196701967119672196731967419675196761967719678196791968019681196821968319684196851968619687196881968919690196911969219693196941969519696196971969819699197001970119702197031970419705197061970719708197091971019711197121971319714197151971619717197181971919720197211972219723197241972519726197271972819729197301973119732197331973419735197361973719738197391974019741197421974319744197451974619747197481974919750197511975219753197541975519756197571975819759197601976119762197631976419765197661976719768197691977019771197721977319774197751977619777197781977919780197811978219783197841978519786197871978819789197901979119792197931979419795197961979719798197991980019801198021980319804198051980619807198081980919810198111981219813198141981519816198171981819819198201982119822198231982419825198261982719828198291983019831198321983319834198351983619837198381983919840198411984219843198441984519846198471984819849198501985119852198531985419855198561985719858198591986019861198621986319864198651986619867198681986919870198711987219873198741987519876198771987819879198801988119882198831988419885198861988719888198891989019891198921989319894198951989619897198981989919900199011990219903199041990519906199071990819909199101991119912199131991419915199161991719918199191992019921199221992319924199251992619927199281992919930199311993219933199341993519936199371993819939199401994119942199431994419945199461994719948199491995019951199521995319954199551995619957199581995919960199611996219963199641996519966199671996819969199701997119972199731997419975199761997719978199791998019981199821998319984199851998619987199881998919990199911999219993199941999519996199971999819999200002000120002200032000420005200062000720008200092001020011200122001320014200152001620017200182001920020200212002220023200242002520026200272002820029200302003120032200332003420035200362003720038200392004020041200422004320044200452004620047200482004920050200512005220053200542005520056200572005820059200602006120062200632006420065200662006720068200692007020071200722007320074200752007620077200782007920080200812008220083200842008520086200872008820089200902009120092200932009420095200962009720098200992010020101201022010320104201052010620107201082010920110201112011220113201142011520116201172011820119201202012120122201232012420125201262012720128201292013020131201322013320134201352013620137201382013920140201412014220143201442014520146201472014820149201502015120152201532015420155201562015720158201592016020161201622016320164201652016620167201682016920170201712017220173201742017520176201772017820179201802018120182201832018420185201862018720188201892019020191201922019320194201952019620197201982019920200202012020220203202042020520206202072020820209202102021120212202132021420215202162021720218202192022020221202222022320224202252022620227202282022920230202312023220233202342023520236202372023820239202402024120242202432024420245202462024720248202492025020251202522025320254202552025620257202582025920260202612026220263202642026520266202672026820269202702027120272202732027420275202762027720278202792028020281202822028320284202852028620287202882028920290202912029220293202942029520296202972029820299203002030120302203032030420305203062030720308203092031020311203122031320314203152031620317203182031920320203212032220323203242032520326203272032820329203302033120332203332033420335203362033720338203392034020341203422034320344203452034620347203482034920350203512035220353203542035520356203572035820359203602036120362203632036420365203662036720368203692037020371203722037320374203752037620377203782037920380203812038220383203842038520386203872038820389203902039120392203932039420395203962039720398203992040020401204022040320404204052040620407204082040920410204112041220413204142041520416204172041820419204202042120422204232042420425204262042720428204292043020431204322043320434204352043620437204382043920440204412044220443204442044520446204472044820449204502045120452204532045420455204562045720458204592046020461204622046320464204652046620467204682046920470204712047220473204742047520476204772047820479204802048120482204832048420485204862048720488204892049020491204922049320494204952049620497204982049920500205012050220503205042050520506205072050820509205102051120512205132051420515205162051720518205192052020521205222052320524205252052620527205282052920530205312053220533205342053520536205372053820539205402054120542205432054420545205462054720548205492055020551205522055320554205552055620557205582055920560205612056220563205642056520566205672056820569205702057120572205732057420575205762057720578205792058020581205822058320584205852058620587205882058920590205912059220593205942059520596205972059820599206002060120602206032060420605206062060720608206092061020611206122061320614206152061620617206182061920620206212062220623206242062520626206272062820629206302063120632206332063420635206362063720638206392064020641206422064320644206452064620647206482064920650206512065220653206542065520656206572065820659206602066120662206632066420665206662066720668206692067020671206722067320674206752067620677206782067920680206812068220683206842068520686206872068820689206902069120692206932069420695206962069720698206992070020701207022070320704207052070620707207082070920710207112071220713207142071520716207172071820719207202072120722207232072420725207262072720728207292073020731207322073320734207352073620737207382073920740207412074220743207442074520746207472074820749207502075120752207532075420755207562075720758207592076020761207622076320764207652076620767207682076920770207712077220773207742077520776207772077820779207802078120782207832078420785207862078720788207892079020791207922079320794207952079620797207982079920800208012080220803208042080520806208072080820809208102081120812208132081420815208162081720818208192082020821208222082320824208252082620827208282082920830208312083220833208342083520836208372083820839208402084120842208432084420845208462084720848208492085020851208522085320854208552085620857208582085920860208612086220863208642086520866208672086820869208702087120872208732087420875208762087720878208792088020881208822088320884208852088620887208882088920890208912089220893208942089520896208972089820899209002090120902209032090420905209062090720908209092091020911209122091320914209152091620917209182091920920209212092220923209242092520926209272092820929209302093120932209332093420935209362093720938209392094020941209422094320944209452094620947209482094920950209512095220953209542095520956209572095820959209602096120962209632096420965209662096720968209692097020971209722097320974209752097620977209782097920980209812098220983209842098520986209872098820989209902099120992209932099420995209962099720998209992100021001210022100321004210052100621007210082100921010210112101221013210142101521016210172101821019210202102121022210232102421025210262102721028210292103021031210322103321034210352103621037210382103921040210412104221043210442104521046210472104821049210502105121052210532105421055210562105721058210592106021061210622106321064210652106621067210682106921070210712107221073210742107521076210772107821079210802108121082210832108421085210862108721088210892109021091210922109321094210952109621097210982109921100211012110221103211042110521106211072110821109211102111121112211132111421115211162111721118211192112021121211222112321124211252112621127211282112921130211312113221133211342113521136211372113821139211402114121142211432114421145211462114721148211492115021151211522115321154211552115621157211582115921160211612116221163211642116521166211672116821169211702117121172211732117421175211762117721178211792118021181211822118321184211852118621187211882118921190211912119221193211942119521196211972119821199212002120121202212032120421205212062120721208212092121021211212122121321214212152121621217212182121921220212212122221223212242122521226212272122821229212302123121232212332123421235212362123721238212392124021241212422124321244212452124621247212482124921250212512125221253212542125521256212572125821259212602126121262212632126421265212662126721268212692127021271212722127321274212752127621277212782127921280212812128221283212842128521286212872128821289212902129121292212932129421295212962129721298212992130021301213022130321304213052130621307213082130921310213112131221313213142131521316213172131821319213202132121322213232132421325213262132721328213292133021331213322133321334213352133621337213382133921340213412134221343213442134521346213472134821349213502135121352213532135421355213562135721358213592136021361213622136321364213652136621367213682136921370213712137221373213742137521376213772137821379213802138121382213832138421385213862138721388213892139021391213922139321394213952139621397213982139921400214012140221403214042140521406214072140821409214102141121412214132141421415214162141721418214192142021421214222142321424214252142621427214282142921430214312143221433214342143521436214372143821439214402144121442214432144421445214462144721448214492145021451214522145321454214552145621457214582145921460214612146221463214642146521466214672146821469214702147121472214732147421475214762147721478214792148021481214822148321484214852148621487214882148921490214912149221493
  1. /**
  2. * @vue/compiler-sfc v3.5.12
  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$1 = 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) => `"${isSSR ? `--` : ``}${genVarName(id, key, isProd, isSSR)}": (${key})`
  111. ).join(",\n ")}
  112. }`;
  113. }
  114. function genVarName(id, raw, isProd, isSSR = false) {
  115. if (isProd) {
  116. return hash(id + raw);
  117. } else {
  118. return `${id}-${shared.getEscapedCssVarName(raw, isSSR)}`;
  119. }
  120. }
  121. function normalizeExpression(exp) {
  122. exp = exp.trim();
  123. if (exp[0] === `'` && exp[exp.length - 1] === `'` || exp[0] === `"` && exp[exp.length - 1] === `"`) {
  124. return exp.slice(1, -1);
  125. }
  126. return exp;
  127. }
  128. const vBindRE = /v-bind\s*\(/g;
  129. function parseCssVars(sfc) {
  130. const vars = [];
  131. sfc.styles.forEach((style) => {
  132. let match;
  133. const content = style.content.replace(/\/\*([\s\S]*?)\*\/|\/\/.*/g, "");
  134. while (match = vBindRE.exec(content)) {
  135. const start = match.index + match[0].length;
  136. const end = lexBinding(content, start);
  137. if (end !== null) {
  138. const variable = normalizeExpression(content.slice(start, end));
  139. if (!vars.includes(variable)) {
  140. vars.push(variable);
  141. }
  142. }
  143. }
  144. });
  145. return vars;
  146. }
  147. function lexBinding(content, start) {
  148. let state = 0 /* inParens */;
  149. let parenDepth = 0;
  150. for (let i = start; i < content.length; i++) {
  151. const char = content.charAt(i);
  152. switch (state) {
  153. case 0 /* inParens */:
  154. if (char === `'`) {
  155. state = 1 /* inSingleQuoteString */;
  156. } else if (char === `"`) {
  157. state = 2 /* inDoubleQuoteString */;
  158. } else if (char === `(`) {
  159. parenDepth++;
  160. } else if (char === `)`) {
  161. if (parenDepth > 0) {
  162. parenDepth--;
  163. } else {
  164. return i;
  165. }
  166. }
  167. break;
  168. case 1 /* inSingleQuoteString */:
  169. if (char === `'`) {
  170. state = 0 /* inParens */;
  171. }
  172. break;
  173. case 2 /* inDoubleQuoteString */:
  174. if (char === `"`) {
  175. state = 0 /* inParens */;
  176. }
  177. break;
  178. }
  179. }
  180. return null;
  181. }
  182. const cssVarsPlugin = (opts) => {
  183. const { id, isProd } = opts;
  184. return {
  185. postcssPlugin: "vue-sfc-vars",
  186. Declaration(decl) {
  187. const value = decl.value;
  188. if (vBindRE.test(value)) {
  189. vBindRE.lastIndex = 0;
  190. let transformed = "";
  191. let lastIndex = 0;
  192. let match;
  193. while (match = vBindRE.exec(value)) {
  194. const start = match.index + match[0].length;
  195. const end = lexBinding(value, start);
  196. if (end !== null) {
  197. const variable = normalizeExpression(value.slice(start, end));
  198. transformed += value.slice(lastIndex, match.index) + `var(--${genVarName(id, variable, isProd)})`;
  199. lastIndex = end + 1;
  200. }
  201. }
  202. decl.value = transformed + value.slice(lastIndex);
  203. }
  204. }
  205. };
  206. };
  207. cssVarsPlugin.postcss = true;
  208. function genCssVarsCode(vars, bindings, id, isProd) {
  209. const varsExp = genCssVarsFromList(vars, id, isProd);
  210. const exp = CompilerDOM.createSimpleExpression(varsExp, false);
  211. const context = CompilerDOM.createTransformContext(CompilerDOM.createRoot([]), {
  212. prefixIdentifiers: true,
  213. inline: true,
  214. bindingMetadata: bindings.__isScriptSetup === false ? void 0 : bindings
  215. });
  216. const transformed = CompilerDOM.processExpression(exp, context);
  217. const transformedString = transformed.type === 4 ? transformed.content : transformed.children.map((c) => {
  218. return typeof c === "string" ? c : c.content;
  219. }).join("");
  220. return `_${CSS_VARS_HELPER}(_ctx => (${transformedString}))`;
  221. }
  222. function genNormalScriptCssVarsCode(cssVars, bindings, id, isProd, defaultVar) {
  223. return `
  224. import { ${CSS_VARS_HELPER} as _${CSS_VARS_HELPER} } from 'vue'
  225. const __injectCSSVars__ = () => {
  226. ${genCssVarsCode(
  227. cssVars,
  228. bindings,
  229. id,
  230. isProd
  231. )}}
  232. const __setup__ = ${defaultVar}.setup
  233. ${defaultVar}.setup = __setup__
  234. ? (props, ctx) => { __injectCSSVars__();return __setup__(props, ctx) }
  235. : __injectCSSVars__
  236. `;
  237. }
  238. /**
  239. * @module LRUCache
  240. */
  241. const perf = typeof performance === 'object' &&
  242. performance &&
  243. typeof performance.now === 'function'
  244. ? performance
  245. : Date;
  246. const warned = new Set();
  247. /* c8 ignore start */
  248. const PROCESS = (typeof process === 'object' && !!process ? process : {});
  249. /* c8 ignore start */
  250. const emitWarning = (msg, type, code, fn) => {
  251. typeof PROCESS.emitWarning === 'function'
  252. ? PROCESS.emitWarning(msg, type, code, fn)
  253. : console.error(`[${code}] ${type}: ${msg}`);
  254. };
  255. let AC = globalThis.AbortController;
  256. let AS = globalThis.AbortSignal;
  257. /* c8 ignore start */
  258. if (typeof AC === 'undefined') {
  259. //@ts-ignore
  260. AS = class AbortSignal {
  261. onabort;
  262. _onabort = [];
  263. reason;
  264. aborted = false;
  265. addEventListener(_, fn) {
  266. this._onabort.push(fn);
  267. }
  268. };
  269. //@ts-ignore
  270. AC = class AbortController {
  271. constructor() {
  272. warnACPolyfill();
  273. }
  274. signal = new AS();
  275. abort(reason) {
  276. if (this.signal.aborted)
  277. return;
  278. //@ts-ignore
  279. this.signal.reason = reason;
  280. //@ts-ignore
  281. this.signal.aborted = true;
  282. //@ts-ignore
  283. for (const fn of this.signal._onabort) {
  284. fn(reason);
  285. }
  286. this.signal.onabort?.(reason);
  287. }
  288. };
  289. let printACPolyfillWarning = PROCESS.env?.LRU_CACHE_IGNORE_AC_WARNING !== '1';
  290. const warnACPolyfill = () => {
  291. if (!printACPolyfillWarning)
  292. return;
  293. printACPolyfillWarning = false;
  294. emitWarning('AbortController is not defined. If using lru-cache in ' +
  295. 'node 14, load an AbortController polyfill from the ' +
  296. '`node-abort-controller` package. A minimal polyfill is ' +
  297. 'provided for use by LRUCache.fetch(), but it should not be ' +
  298. 'relied upon in other contexts (eg, passing it to other APIs that ' +
  299. 'use AbortController/AbortSignal might have undesirable effects). ' +
  300. 'You may disable this with LRU_CACHE_IGNORE_AC_WARNING=1 in the env.', 'NO_ABORT_CONTROLLER', 'ENOTSUP', warnACPolyfill);
  301. };
  302. }
  303. /* c8 ignore stop */
  304. const shouldWarn = (code) => !warned.has(code);
  305. const isPosInt = (n) => n && n === Math.floor(n) && n > 0 && isFinite(n);
  306. /* c8 ignore start */
  307. // This is a little bit ridiculous, tbh.
  308. // The maximum array length is 2^32-1 or thereabouts on most JS impls.
  309. // And well before that point, you're caching the entire world, I mean,
  310. // that's ~32GB of just integers for the next/prev links, plus whatever
  311. // else to hold that many keys and values. Just filling the memory with
  312. // zeroes at init time is brutal when you get that big.
  313. // But why not be complete?
  314. // Maybe in the future, these limits will have expanded.
  315. const getUintArray = (max) => !isPosInt(max)
  316. ? null
  317. : max <= Math.pow(2, 8)
  318. ? Uint8Array
  319. : max <= Math.pow(2, 16)
  320. ? Uint16Array
  321. : max <= Math.pow(2, 32)
  322. ? Uint32Array
  323. : max <= Number.MAX_SAFE_INTEGER
  324. ? ZeroArray
  325. : null;
  326. /* c8 ignore stop */
  327. class ZeroArray extends Array {
  328. constructor(size) {
  329. super(size);
  330. this.fill(0);
  331. }
  332. }
  333. class Stack {
  334. heap;
  335. length;
  336. // private constructor
  337. static #constructing = false;
  338. static create(max) {
  339. const HeapCls = getUintArray(max);
  340. if (!HeapCls)
  341. return [];
  342. Stack.#constructing = true;
  343. const s = new Stack(max, HeapCls);
  344. Stack.#constructing = false;
  345. return s;
  346. }
  347. constructor(max, HeapCls) {
  348. /* c8 ignore start */
  349. if (!Stack.#constructing) {
  350. throw new TypeError('instantiate Stack using Stack.create(n)');
  351. }
  352. /* c8 ignore stop */
  353. this.heap = new HeapCls(max);
  354. this.length = 0;
  355. }
  356. push(n) {
  357. this.heap[this.length++] = n;
  358. }
  359. pop() {
  360. return this.heap[--this.length];
  361. }
  362. }
  363. /**
  364. * Default export, the thing you're using this module to get.
  365. *
  366. * All properties from the options object (with the exception of
  367. * {@link OptionsBase.max} and {@link OptionsBase.maxSize}) are added as
  368. * normal public members. (`max` and `maxBase` are read-only getters.)
  369. * Changing any of these will alter the defaults for subsequent method calls,
  370. * but is otherwise safe.
  371. */
  372. class LRUCache {
  373. // properties coming in from the options of these, only max and maxSize
  374. // really *need* to be protected. The rest can be modified, as they just
  375. // set defaults for various methods.
  376. #max;
  377. #maxSize;
  378. #dispose;
  379. #disposeAfter;
  380. #fetchMethod;
  381. /**
  382. * {@link LRUCache.OptionsBase.ttl}
  383. */
  384. ttl;
  385. /**
  386. * {@link LRUCache.OptionsBase.ttlResolution}
  387. */
  388. ttlResolution;
  389. /**
  390. * {@link LRUCache.OptionsBase.ttlAutopurge}
  391. */
  392. ttlAutopurge;
  393. /**
  394. * {@link LRUCache.OptionsBase.updateAgeOnGet}
  395. */
  396. updateAgeOnGet;
  397. /**
  398. * {@link LRUCache.OptionsBase.updateAgeOnHas}
  399. */
  400. updateAgeOnHas;
  401. /**
  402. * {@link LRUCache.OptionsBase.allowStale}
  403. */
  404. allowStale;
  405. /**
  406. * {@link LRUCache.OptionsBase.noDisposeOnSet}
  407. */
  408. noDisposeOnSet;
  409. /**
  410. * {@link LRUCache.OptionsBase.noUpdateTTL}
  411. */
  412. noUpdateTTL;
  413. /**
  414. * {@link LRUCache.OptionsBase.maxEntrySize}
  415. */
  416. maxEntrySize;
  417. /**
  418. * {@link LRUCache.OptionsBase.sizeCalculation}
  419. */
  420. sizeCalculation;
  421. /**
  422. * {@link LRUCache.OptionsBase.noDeleteOnFetchRejection}
  423. */
  424. noDeleteOnFetchRejection;
  425. /**
  426. * {@link LRUCache.OptionsBase.noDeleteOnStaleGet}
  427. */
  428. noDeleteOnStaleGet;
  429. /**
  430. * {@link LRUCache.OptionsBase.allowStaleOnFetchAbort}
  431. */
  432. allowStaleOnFetchAbort;
  433. /**
  434. * {@link LRUCache.OptionsBase.allowStaleOnFetchRejection}
  435. */
  436. allowStaleOnFetchRejection;
  437. /**
  438. * {@link LRUCache.OptionsBase.ignoreFetchAbort}
  439. */
  440. ignoreFetchAbort;
  441. // computed properties
  442. #size;
  443. #calculatedSize;
  444. #keyMap;
  445. #keyList;
  446. #valList;
  447. #next;
  448. #prev;
  449. #head;
  450. #tail;
  451. #free;
  452. #disposed;
  453. #sizes;
  454. #starts;
  455. #ttls;
  456. #hasDispose;
  457. #hasFetchMethod;
  458. #hasDisposeAfter;
  459. /**
  460. * Do not call this method unless you need to inspect the
  461. * inner workings of the cache. If anything returned by this
  462. * object is modified in any way, strange breakage may occur.
  463. *
  464. * These fields are private for a reason!
  465. *
  466. * @internal
  467. */
  468. static unsafeExposeInternals(c) {
  469. return {
  470. // properties
  471. starts: c.#starts,
  472. ttls: c.#ttls,
  473. sizes: c.#sizes,
  474. keyMap: c.#keyMap,
  475. keyList: c.#keyList,
  476. valList: c.#valList,
  477. next: c.#next,
  478. prev: c.#prev,
  479. get head() {
  480. return c.#head;
  481. },
  482. get tail() {
  483. return c.#tail;
  484. },
  485. free: c.#free,
  486. // methods
  487. isBackgroundFetch: (p) => c.#isBackgroundFetch(p),
  488. backgroundFetch: (k, index, options, context) => c.#backgroundFetch(k, index, options, context),
  489. moveToTail: (index) => c.#moveToTail(index),
  490. indexes: (options) => c.#indexes(options),
  491. rindexes: (options) => c.#rindexes(options),
  492. isStale: (index) => c.#isStale(index),
  493. };
  494. }
  495. // Protected read-only members
  496. /**
  497. * {@link LRUCache.OptionsBase.max} (read-only)
  498. */
  499. get max() {
  500. return this.#max;
  501. }
  502. /**
  503. * {@link LRUCache.OptionsBase.maxSize} (read-only)
  504. */
  505. get maxSize() {
  506. return this.#maxSize;
  507. }
  508. /**
  509. * The total computed size of items in the cache (read-only)
  510. */
  511. get calculatedSize() {
  512. return this.#calculatedSize;
  513. }
  514. /**
  515. * The number of items stored in the cache (read-only)
  516. */
  517. get size() {
  518. return this.#size;
  519. }
  520. /**
  521. * {@link LRUCache.OptionsBase.fetchMethod} (read-only)
  522. */
  523. get fetchMethod() {
  524. return this.#fetchMethod;
  525. }
  526. /**
  527. * {@link LRUCache.OptionsBase.dispose} (read-only)
  528. */
  529. get dispose() {
  530. return this.#dispose;
  531. }
  532. /**
  533. * {@link LRUCache.OptionsBase.disposeAfter} (read-only)
  534. */
  535. get disposeAfter() {
  536. return this.#disposeAfter;
  537. }
  538. constructor(options) {
  539. 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;
  540. if (max !== 0 && !isPosInt(max)) {
  541. throw new TypeError('max option must be a nonnegative integer');
  542. }
  543. const UintArray = max ? getUintArray(max) : Array;
  544. if (!UintArray) {
  545. throw new Error('invalid max value: ' + max);
  546. }
  547. this.#max = max;
  548. this.#maxSize = maxSize;
  549. this.maxEntrySize = maxEntrySize || this.#maxSize;
  550. this.sizeCalculation = sizeCalculation;
  551. if (this.sizeCalculation) {
  552. if (!this.#maxSize && !this.maxEntrySize) {
  553. throw new TypeError('cannot set sizeCalculation without setting maxSize or maxEntrySize');
  554. }
  555. if (typeof this.sizeCalculation !== 'function') {
  556. throw new TypeError('sizeCalculation set to non-function');
  557. }
  558. }
  559. if (fetchMethod !== undefined &&
  560. typeof fetchMethod !== 'function') {
  561. throw new TypeError('fetchMethod must be a function if specified');
  562. }
  563. this.#fetchMethod = fetchMethod;
  564. this.#hasFetchMethod = !!fetchMethod;
  565. this.#keyMap = new Map();
  566. this.#keyList = new Array(max).fill(undefined);
  567. this.#valList = new Array(max).fill(undefined);
  568. this.#next = new UintArray(max);
  569. this.#prev = new UintArray(max);
  570. this.#head = 0;
  571. this.#tail = 0;
  572. this.#free = Stack.create(max);
  573. this.#size = 0;
  574. this.#calculatedSize = 0;
  575. if (typeof dispose === 'function') {
  576. this.#dispose = dispose;
  577. }
  578. if (typeof disposeAfter === 'function') {
  579. this.#disposeAfter = disposeAfter;
  580. this.#disposed = [];
  581. }
  582. else {
  583. this.#disposeAfter = undefined;
  584. this.#disposed = undefined;
  585. }
  586. this.#hasDispose = !!this.#dispose;
  587. this.#hasDisposeAfter = !!this.#disposeAfter;
  588. this.noDisposeOnSet = !!noDisposeOnSet;
  589. this.noUpdateTTL = !!noUpdateTTL;
  590. this.noDeleteOnFetchRejection = !!noDeleteOnFetchRejection;
  591. this.allowStaleOnFetchRejection = !!allowStaleOnFetchRejection;
  592. this.allowStaleOnFetchAbort = !!allowStaleOnFetchAbort;
  593. this.ignoreFetchAbort = !!ignoreFetchAbort;
  594. // NB: maxEntrySize is set to maxSize if it's set
  595. if (this.maxEntrySize !== 0) {
  596. if (this.#maxSize !== 0) {
  597. if (!isPosInt(this.#maxSize)) {
  598. throw new TypeError('maxSize must be a positive integer if specified');
  599. }
  600. }
  601. if (!isPosInt(this.maxEntrySize)) {
  602. throw new TypeError('maxEntrySize must be a positive integer if specified');
  603. }
  604. this.#initializeSizeTracking();
  605. }
  606. this.allowStale = !!allowStale;
  607. this.noDeleteOnStaleGet = !!noDeleteOnStaleGet;
  608. this.updateAgeOnGet = !!updateAgeOnGet;
  609. this.updateAgeOnHas = !!updateAgeOnHas;
  610. this.ttlResolution =
  611. isPosInt(ttlResolution) || ttlResolution === 0
  612. ? ttlResolution
  613. : 1;
  614. this.ttlAutopurge = !!ttlAutopurge;
  615. this.ttl = ttl || 0;
  616. if (this.ttl) {
  617. if (!isPosInt(this.ttl)) {
  618. throw new TypeError('ttl must be a positive integer if specified');
  619. }
  620. this.#initializeTTLTracking();
  621. }
  622. // do not allow completely unbounded caches
  623. if (this.#max === 0 && this.ttl === 0 && this.#maxSize === 0) {
  624. throw new TypeError('At least one of max, maxSize, or ttl is required');
  625. }
  626. if (!this.ttlAutopurge && !this.#max && !this.#maxSize) {
  627. const code = 'LRU_CACHE_UNBOUNDED';
  628. if (shouldWarn(code)) {
  629. warned.add(code);
  630. const msg = 'TTL caching without ttlAutopurge, max, or maxSize can ' +
  631. 'result in unbounded memory consumption.';
  632. emitWarning(msg, 'UnboundedCacheWarning', code, LRUCache);
  633. }
  634. }
  635. }
  636. /**
  637. * Return the remaining TTL time for a given entry key
  638. */
  639. getRemainingTTL(key) {
  640. return this.#keyMap.has(key) ? Infinity : 0;
  641. }
  642. #initializeTTLTracking() {
  643. const ttls = new ZeroArray(this.#max);
  644. const starts = new ZeroArray(this.#max);
  645. this.#ttls = ttls;
  646. this.#starts = starts;
  647. this.#setItemTTL = (index, ttl, start = perf.now()) => {
  648. starts[index] = ttl !== 0 ? start : 0;
  649. ttls[index] = ttl;
  650. if (ttl !== 0 && this.ttlAutopurge) {
  651. const t = setTimeout(() => {
  652. if (this.#isStale(index)) {
  653. this.delete(this.#keyList[index]);
  654. }
  655. }, ttl + 1);
  656. // unref() not supported on all platforms
  657. /* c8 ignore start */
  658. if (t.unref) {
  659. t.unref();
  660. }
  661. /* c8 ignore stop */
  662. }
  663. };
  664. this.#updateItemAge = index => {
  665. starts[index] = ttls[index] !== 0 ? perf.now() : 0;
  666. };
  667. this.#statusTTL = (status, index) => {
  668. if (ttls[index]) {
  669. const ttl = ttls[index];
  670. const start = starts[index];
  671. /* c8 ignore next */
  672. if (!ttl || !start)
  673. return;
  674. status.ttl = ttl;
  675. status.start = start;
  676. status.now = cachedNow || getNow();
  677. const age = status.now - start;
  678. status.remainingTTL = ttl - age;
  679. }
  680. };
  681. // debounce calls to perf.now() to 1s so we're not hitting
  682. // that costly call repeatedly.
  683. let cachedNow = 0;
  684. const getNow = () => {
  685. const n = perf.now();
  686. if (this.ttlResolution > 0) {
  687. cachedNow = n;
  688. const t = setTimeout(() => (cachedNow = 0), this.ttlResolution);
  689. // not available on all platforms
  690. /* c8 ignore start */
  691. if (t.unref) {
  692. t.unref();
  693. }
  694. /* c8 ignore stop */
  695. }
  696. return n;
  697. };
  698. this.getRemainingTTL = key => {
  699. const index = this.#keyMap.get(key);
  700. if (index === undefined) {
  701. return 0;
  702. }
  703. const ttl = ttls[index];
  704. const start = starts[index];
  705. if (!ttl || !start) {
  706. return Infinity;
  707. }
  708. const age = (cachedNow || getNow()) - start;
  709. return ttl - age;
  710. };
  711. this.#isStale = index => {
  712. const s = starts[index];
  713. const t = ttls[index];
  714. return !!t && !!s && (cachedNow || getNow()) - s > t;
  715. };
  716. }
  717. // conditionally set private methods related to TTL
  718. #updateItemAge = () => { };
  719. #statusTTL = () => { };
  720. #setItemTTL = () => { };
  721. /* c8 ignore stop */
  722. #isStale = () => false;
  723. #initializeSizeTracking() {
  724. const sizes = new ZeroArray(this.#max);
  725. this.#calculatedSize = 0;
  726. this.#sizes = sizes;
  727. this.#removeItemSize = index => {
  728. this.#calculatedSize -= sizes[index];
  729. sizes[index] = 0;
  730. };
  731. this.#requireSize = (k, v, size, sizeCalculation) => {
  732. // provisionally accept background fetches.
  733. // actual value size will be checked when they return.
  734. if (this.#isBackgroundFetch(v)) {
  735. return 0;
  736. }
  737. if (!isPosInt(size)) {
  738. if (sizeCalculation) {
  739. if (typeof sizeCalculation !== 'function') {
  740. throw new TypeError('sizeCalculation must be a function');
  741. }
  742. size = sizeCalculation(v, k);
  743. if (!isPosInt(size)) {
  744. throw new TypeError('sizeCalculation return invalid (expect positive integer)');
  745. }
  746. }
  747. else {
  748. throw new TypeError('invalid size value (must be positive integer). ' +
  749. 'When maxSize or maxEntrySize is used, sizeCalculation ' +
  750. 'or size must be set.');
  751. }
  752. }
  753. return size;
  754. };
  755. this.#addItemSize = (index, size, status) => {
  756. sizes[index] = size;
  757. if (this.#maxSize) {
  758. const maxSize = this.#maxSize - sizes[index];
  759. while (this.#calculatedSize > maxSize) {
  760. this.#evict(true);
  761. }
  762. }
  763. this.#calculatedSize += sizes[index];
  764. if (status) {
  765. status.entrySize = size;
  766. status.totalCalculatedSize = this.#calculatedSize;
  767. }
  768. };
  769. }
  770. #removeItemSize = _i => { };
  771. #addItemSize = (_i, _s, _st) => { };
  772. #requireSize = (_k, _v, size, sizeCalculation) => {
  773. if (size || sizeCalculation) {
  774. throw new TypeError('cannot set size without setting maxSize or maxEntrySize on cache');
  775. }
  776. return 0;
  777. };
  778. *#indexes({ allowStale = this.allowStale } = {}) {
  779. if (this.#size) {
  780. for (let i = this.#tail; true;) {
  781. if (!this.#isValidIndex(i)) {
  782. break;
  783. }
  784. if (allowStale || !this.#isStale(i)) {
  785. yield i;
  786. }
  787. if (i === this.#head) {
  788. break;
  789. }
  790. else {
  791. i = this.#prev[i];
  792. }
  793. }
  794. }
  795. }
  796. *#rindexes({ allowStale = this.allowStale } = {}) {
  797. if (this.#size) {
  798. for (let i = this.#head; true;) {
  799. if (!this.#isValidIndex(i)) {
  800. break;
  801. }
  802. if (allowStale || !this.#isStale(i)) {
  803. yield i;
  804. }
  805. if (i === this.#tail) {
  806. break;
  807. }
  808. else {
  809. i = this.#next[i];
  810. }
  811. }
  812. }
  813. }
  814. #isValidIndex(index) {
  815. return (index !== undefined &&
  816. this.#keyMap.get(this.#keyList[index]) === index);
  817. }
  818. /**
  819. * Return a generator yielding `[key, value]` pairs,
  820. * in order from most recently used to least recently used.
  821. */
  822. *entries() {
  823. for (const i of this.#indexes()) {
  824. if (this.#valList[i] !== undefined &&
  825. this.#keyList[i] !== undefined &&
  826. !this.#isBackgroundFetch(this.#valList[i])) {
  827. yield [this.#keyList[i], this.#valList[i]];
  828. }
  829. }
  830. }
  831. /**
  832. * Inverse order version of {@link LRUCache.entries}
  833. *
  834. * Return a generator yielding `[key, value]` pairs,
  835. * in order from least recently used to most recently used.
  836. */
  837. *rentries() {
  838. for (const i of this.#rindexes()) {
  839. if (this.#valList[i] !== undefined &&
  840. this.#keyList[i] !== undefined &&
  841. !this.#isBackgroundFetch(this.#valList[i])) {
  842. yield [this.#keyList[i], this.#valList[i]];
  843. }
  844. }
  845. }
  846. /**
  847. * Return a generator yielding the keys in the cache,
  848. * in order from most recently used to least recently used.
  849. */
  850. *keys() {
  851. for (const i of this.#indexes()) {
  852. const k = this.#keyList[i];
  853. if (k !== undefined &&
  854. !this.#isBackgroundFetch(this.#valList[i])) {
  855. yield k;
  856. }
  857. }
  858. }
  859. /**
  860. * Inverse order version of {@link LRUCache.keys}
  861. *
  862. * Return a generator yielding the keys in the cache,
  863. * in order from least recently used to most recently used.
  864. */
  865. *rkeys() {
  866. for (const i of this.#rindexes()) {
  867. const k = this.#keyList[i];
  868. if (k !== undefined &&
  869. !this.#isBackgroundFetch(this.#valList[i])) {
  870. yield k;
  871. }
  872. }
  873. }
  874. /**
  875. * Return a generator yielding the values in the cache,
  876. * in order from most recently used to least recently used.
  877. */
  878. *values() {
  879. for (const i of this.#indexes()) {
  880. const v = this.#valList[i];
  881. if (v !== undefined &&
  882. !this.#isBackgroundFetch(this.#valList[i])) {
  883. yield this.#valList[i];
  884. }
  885. }
  886. }
  887. /**
  888. * Inverse order version of {@link LRUCache.values}
  889. *
  890. * Return a generator yielding the values in the cache,
  891. * in order from least recently used to most recently used.
  892. */
  893. *rvalues() {
  894. for (const i of this.#rindexes()) {
  895. const v = this.#valList[i];
  896. if (v !== undefined &&
  897. !this.#isBackgroundFetch(this.#valList[i])) {
  898. yield this.#valList[i];
  899. }
  900. }
  901. }
  902. /**
  903. * Iterating over the cache itself yields the same results as
  904. * {@link LRUCache.entries}
  905. */
  906. [Symbol.iterator]() {
  907. return this.entries();
  908. }
  909. /**
  910. * Find a value for which the supplied fn method returns a truthy value,
  911. * similar to Array.find(). fn is called as fn(value, key, cache).
  912. */
  913. find(fn, getOptions = {}) {
  914. for (const i of this.#indexes()) {
  915. const v = this.#valList[i];
  916. const value = this.#isBackgroundFetch(v)
  917. ? v.__staleWhileFetching
  918. : v;
  919. if (value === undefined)
  920. continue;
  921. if (fn(value, this.#keyList[i], this)) {
  922. return this.get(this.#keyList[i], getOptions);
  923. }
  924. }
  925. }
  926. /**
  927. * Call the supplied function on each item in the cache, in order from
  928. * most recently used to least recently used. fn is called as
  929. * fn(value, key, cache). Does not update age or recenty of use.
  930. * Does not iterate over stale values.
  931. */
  932. forEach(fn, thisp = this) {
  933. for (const i of this.#indexes()) {
  934. const v = this.#valList[i];
  935. const value = this.#isBackgroundFetch(v)
  936. ? v.__staleWhileFetching
  937. : v;
  938. if (value === undefined)
  939. continue;
  940. fn.call(thisp, value, this.#keyList[i], this);
  941. }
  942. }
  943. /**
  944. * The same as {@link LRUCache.forEach} but items are iterated over in
  945. * reverse order. (ie, less recently used items are iterated over first.)
  946. */
  947. rforEach(fn, thisp = this) {
  948. for (const i of this.#rindexes()) {
  949. const v = this.#valList[i];
  950. const value = this.#isBackgroundFetch(v)
  951. ? v.__staleWhileFetching
  952. : v;
  953. if (value === undefined)
  954. continue;
  955. fn.call(thisp, value, this.#keyList[i], this);
  956. }
  957. }
  958. /**
  959. * Delete any stale entries. Returns true if anything was removed,
  960. * false otherwise.
  961. */
  962. purgeStale() {
  963. let deleted = false;
  964. for (const i of this.#rindexes({ allowStale: true })) {
  965. if (this.#isStale(i)) {
  966. this.delete(this.#keyList[i]);
  967. deleted = true;
  968. }
  969. }
  970. return deleted;
  971. }
  972. /**
  973. * Get the extended info about a given entry, to get its value, size, and
  974. * TTL info simultaneously. Like {@link LRUCache#dump}, but just for a
  975. * single key. Always returns stale values, if their info is found in the
  976. * cache, so be sure to check for expired TTLs if relevant.
  977. */
  978. info(key) {
  979. const i = this.#keyMap.get(key);
  980. if (i === undefined)
  981. return undefined;
  982. const v = this.#valList[i];
  983. const value = this.#isBackgroundFetch(v)
  984. ? v.__staleWhileFetching
  985. : v;
  986. if (value === undefined)
  987. return undefined;
  988. const entry = { value };
  989. if (this.#ttls && this.#starts) {
  990. const ttl = this.#ttls[i];
  991. const start = this.#starts[i];
  992. if (ttl && start) {
  993. const remain = ttl - (perf.now() - start);
  994. entry.ttl = remain;
  995. entry.start = Date.now();
  996. }
  997. }
  998. if (this.#sizes) {
  999. entry.size = this.#sizes[i];
  1000. }
  1001. return entry;
  1002. }
  1003. /**
  1004. * Return an array of [key, {@link LRUCache.Entry}] tuples which can be
  1005. * passed to cache.load()
  1006. */
  1007. dump() {
  1008. const arr = [];
  1009. for (const i of this.#indexes({ allowStale: true })) {
  1010. const key = this.#keyList[i];
  1011. const v = this.#valList[i];
  1012. const value = this.#isBackgroundFetch(v)
  1013. ? v.__staleWhileFetching
  1014. : v;
  1015. if (value === undefined || key === undefined)
  1016. continue;
  1017. const entry = { value };
  1018. if (this.#ttls && this.#starts) {
  1019. entry.ttl = this.#ttls[i];
  1020. // always dump the start relative to a portable timestamp
  1021. // it's ok for this to be a bit slow, it's a rare operation.
  1022. const age = perf.now() - this.#starts[i];
  1023. entry.start = Math.floor(Date.now() - age);
  1024. }
  1025. if (this.#sizes) {
  1026. entry.size = this.#sizes[i];
  1027. }
  1028. arr.unshift([key, entry]);
  1029. }
  1030. return arr;
  1031. }
  1032. /**
  1033. * Reset the cache and load in the items in entries in the order listed.
  1034. * Note that the shape of the resulting cache may be different if the
  1035. * same options are not used in both caches.
  1036. */
  1037. load(arr) {
  1038. this.clear();
  1039. for (const [key, entry] of arr) {
  1040. if (entry.start) {
  1041. // entry.start is a portable timestamp, but we may be using
  1042. // node's performance.now(), so calculate the offset, so that
  1043. // we get the intended remaining TTL, no matter how long it's
  1044. // been on ice.
  1045. //
  1046. // it's ok for this to be a bit slow, it's a rare operation.
  1047. const age = Date.now() - entry.start;
  1048. entry.start = perf.now() - age;
  1049. }
  1050. this.set(key, entry.value, entry);
  1051. }
  1052. }
  1053. /**
  1054. * Add a value to the cache.
  1055. *
  1056. * Note: if `undefined` is specified as a value, this is an alias for
  1057. * {@link LRUCache#delete}
  1058. */
  1059. set(k, v, setOptions = {}) {
  1060. if (v === undefined) {
  1061. this.delete(k);
  1062. return this;
  1063. }
  1064. const { ttl = this.ttl, start, noDisposeOnSet = this.noDisposeOnSet, sizeCalculation = this.sizeCalculation, status, } = setOptions;
  1065. let { noUpdateTTL = this.noUpdateTTL } = setOptions;
  1066. const size = this.#requireSize(k, v, setOptions.size || 0, sizeCalculation);
  1067. // if the item doesn't fit, don't do anything
  1068. // NB: maxEntrySize set to maxSize by default
  1069. if (this.maxEntrySize && size > this.maxEntrySize) {
  1070. if (status) {
  1071. status.set = 'miss';
  1072. status.maxEntrySizeExceeded = true;
  1073. }
  1074. // have to delete, in case something is there already.
  1075. this.delete(k);
  1076. return this;
  1077. }
  1078. let index = this.#size === 0 ? undefined : this.#keyMap.get(k);
  1079. if (index === undefined) {
  1080. // addition
  1081. index = (this.#size === 0
  1082. ? this.#tail
  1083. : this.#free.length !== 0
  1084. ? this.#free.pop()
  1085. : this.#size === this.#max
  1086. ? this.#evict(false)
  1087. : this.#size);
  1088. this.#keyList[index] = k;
  1089. this.#valList[index] = v;
  1090. this.#keyMap.set(k, index);
  1091. this.#next[this.#tail] = index;
  1092. this.#prev[index] = this.#tail;
  1093. this.#tail = index;
  1094. this.#size++;
  1095. this.#addItemSize(index, size, status);
  1096. if (status)
  1097. status.set = 'add';
  1098. noUpdateTTL = false;
  1099. }
  1100. else {
  1101. // update
  1102. this.#moveToTail(index);
  1103. const oldVal = this.#valList[index];
  1104. if (v !== oldVal) {
  1105. if (this.#hasFetchMethod && this.#isBackgroundFetch(oldVal)) {
  1106. oldVal.__abortController.abort(new Error('replaced'));
  1107. const { __staleWhileFetching: s } = oldVal;
  1108. if (s !== undefined && !noDisposeOnSet) {
  1109. if (this.#hasDispose) {
  1110. this.#dispose?.(s, k, 'set');
  1111. }
  1112. if (this.#hasDisposeAfter) {
  1113. this.#disposed?.push([s, k, 'set']);
  1114. }
  1115. }
  1116. }
  1117. else if (!noDisposeOnSet) {
  1118. if (this.#hasDispose) {
  1119. this.#dispose?.(oldVal, k, 'set');
  1120. }
  1121. if (this.#hasDisposeAfter) {
  1122. this.#disposed?.push([oldVal, k, 'set']);
  1123. }
  1124. }
  1125. this.#removeItemSize(index);
  1126. this.#addItemSize(index, size, status);
  1127. this.#valList[index] = v;
  1128. if (status) {
  1129. status.set = 'replace';
  1130. const oldValue = oldVal && this.#isBackgroundFetch(oldVal)
  1131. ? oldVal.__staleWhileFetching
  1132. : oldVal;
  1133. if (oldValue !== undefined)
  1134. status.oldValue = oldValue;
  1135. }
  1136. }
  1137. else if (status) {
  1138. status.set = 'update';
  1139. }
  1140. }
  1141. if (ttl !== 0 && !this.#ttls) {
  1142. this.#initializeTTLTracking();
  1143. }
  1144. if (this.#ttls) {
  1145. if (!noUpdateTTL) {
  1146. this.#setItemTTL(index, ttl, start);
  1147. }
  1148. if (status)
  1149. this.#statusTTL(status, index);
  1150. }
  1151. if (!noDisposeOnSet && this.#hasDisposeAfter && this.#disposed) {
  1152. const dt = this.#disposed;
  1153. let task;
  1154. while ((task = dt?.shift())) {
  1155. this.#disposeAfter?.(...task);
  1156. }
  1157. }
  1158. return this;
  1159. }
  1160. /**
  1161. * Evict the least recently used item, returning its value or
  1162. * `undefined` if cache is empty.
  1163. */
  1164. pop() {
  1165. try {
  1166. while (this.#size) {
  1167. const val = this.#valList[this.#head];
  1168. this.#evict(true);
  1169. if (this.#isBackgroundFetch(val)) {
  1170. if (val.__staleWhileFetching) {
  1171. return val.__staleWhileFetching;
  1172. }
  1173. }
  1174. else if (val !== undefined) {
  1175. return val;
  1176. }
  1177. }
  1178. }
  1179. finally {
  1180. if (this.#hasDisposeAfter && this.#disposed) {
  1181. const dt = this.#disposed;
  1182. let task;
  1183. while ((task = dt?.shift())) {
  1184. this.#disposeAfter?.(...task);
  1185. }
  1186. }
  1187. }
  1188. }
  1189. #evict(free) {
  1190. const head = this.#head;
  1191. const k = this.#keyList[head];
  1192. const v = this.#valList[head];
  1193. if (this.#hasFetchMethod && this.#isBackgroundFetch(v)) {
  1194. v.__abortController.abort(new Error('evicted'));
  1195. }
  1196. else if (this.#hasDispose || this.#hasDisposeAfter) {
  1197. if (this.#hasDispose) {
  1198. this.#dispose?.(v, k, 'evict');
  1199. }
  1200. if (this.#hasDisposeAfter) {
  1201. this.#disposed?.push([v, k, 'evict']);
  1202. }
  1203. }
  1204. this.#removeItemSize(head);
  1205. // if we aren't about to use the index, then null these out
  1206. if (free) {
  1207. this.#keyList[head] = undefined;
  1208. this.#valList[head] = undefined;
  1209. this.#free.push(head);
  1210. }
  1211. if (this.#size === 1) {
  1212. this.#head = this.#tail = 0;
  1213. this.#free.length = 0;
  1214. }
  1215. else {
  1216. this.#head = this.#next[head];
  1217. }
  1218. this.#keyMap.delete(k);
  1219. this.#size--;
  1220. return head;
  1221. }
  1222. /**
  1223. * Check if a key is in the cache, without updating the recency of use.
  1224. * Will return false if the item is stale, even though it is technically
  1225. * in the cache.
  1226. *
  1227. * Will not update item age unless
  1228. * {@link LRUCache.OptionsBase.updateAgeOnHas} is set.
  1229. */
  1230. has(k, hasOptions = {}) {
  1231. const { updateAgeOnHas = this.updateAgeOnHas, status } = hasOptions;
  1232. const index = this.#keyMap.get(k);
  1233. if (index !== undefined) {
  1234. const v = this.#valList[index];
  1235. if (this.#isBackgroundFetch(v) &&
  1236. v.__staleWhileFetching === undefined) {
  1237. return false;
  1238. }
  1239. if (!this.#isStale(index)) {
  1240. if (updateAgeOnHas) {
  1241. this.#updateItemAge(index);
  1242. }
  1243. if (status) {
  1244. status.has = 'hit';
  1245. this.#statusTTL(status, index);
  1246. }
  1247. return true;
  1248. }
  1249. else if (status) {
  1250. status.has = 'stale';
  1251. this.#statusTTL(status, index);
  1252. }
  1253. }
  1254. else if (status) {
  1255. status.has = 'miss';
  1256. }
  1257. return false;
  1258. }
  1259. /**
  1260. * Like {@link LRUCache#get} but doesn't update recency or delete stale
  1261. * items.
  1262. *
  1263. * Returns `undefined` if the item is stale, unless
  1264. * {@link LRUCache.OptionsBase.allowStale} is set.
  1265. */
  1266. peek(k, peekOptions = {}) {
  1267. const { allowStale = this.allowStale } = peekOptions;
  1268. const index = this.#keyMap.get(k);
  1269. if (index === undefined ||
  1270. (!allowStale && this.#isStale(index))) {
  1271. return;
  1272. }
  1273. const v = this.#valList[index];
  1274. // either stale and allowed, or forcing a refresh of non-stale value
  1275. return this.#isBackgroundFetch(v) ? v.__staleWhileFetching : v;
  1276. }
  1277. #backgroundFetch(k, index, options, context) {
  1278. const v = index === undefined ? undefined : this.#valList[index];
  1279. if (this.#isBackgroundFetch(v)) {
  1280. return v;
  1281. }
  1282. const ac = new AC();
  1283. const { signal } = options;
  1284. // when/if our AC signals, then stop listening to theirs.
  1285. signal?.addEventListener('abort', () => ac.abort(signal.reason), {
  1286. signal: ac.signal,
  1287. });
  1288. const fetchOpts = {
  1289. signal: ac.signal,
  1290. options,
  1291. context,
  1292. };
  1293. const cb = (v, updateCache = false) => {
  1294. const { aborted } = ac.signal;
  1295. const ignoreAbort = options.ignoreFetchAbort && v !== undefined;
  1296. if (options.status) {
  1297. if (aborted && !updateCache) {
  1298. options.status.fetchAborted = true;
  1299. options.status.fetchError = ac.signal.reason;
  1300. if (ignoreAbort)
  1301. options.status.fetchAbortIgnored = true;
  1302. }
  1303. else {
  1304. options.status.fetchResolved = true;
  1305. }
  1306. }
  1307. if (aborted && !ignoreAbort && !updateCache) {
  1308. return fetchFail(ac.signal.reason);
  1309. }
  1310. // either we didn't abort, and are still here, or we did, and ignored
  1311. const bf = p;
  1312. if (this.#valList[index] === p) {
  1313. if (v === undefined) {
  1314. if (bf.__staleWhileFetching) {
  1315. this.#valList[index] = bf.__staleWhileFetching;
  1316. }
  1317. else {
  1318. this.delete(k);
  1319. }
  1320. }
  1321. else {
  1322. if (options.status)
  1323. options.status.fetchUpdated = true;
  1324. this.set(k, v, fetchOpts.options);
  1325. }
  1326. }
  1327. return v;
  1328. };
  1329. const eb = (er) => {
  1330. if (options.status) {
  1331. options.status.fetchRejected = true;
  1332. options.status.fetchError = er;
  1333. }
  1334. return fetchFail(er);
  1335. };
  1336. const fetchFail = (er) => {
  1337. const { aborted } = ac.signal;
  1338. const allowStaleAborted = aborted && options.allowStaleOnFetchAbort;
  1339. const allowStale = allowStaleAborted || options.allowStaleOnFetchRejection;
  1340. const noDelete = allowStale || options.noDeleteOnFetchRejection;
  1341. const bf = p;
  1342. if (this.#valList[index] === p) {
  1343. // if we allow stale on fetch rejections, then we need to ensure that
  1344. // the stale value is not removed from the cache when the fetch fails.
  1345. const del = !noDelete || bf.__staleWhileFetching === undefined;
  1346. if (del) {
  1347. this.delete(k);
  1348. }
  1349. else if (!allowStaleAborted) {
  1350. // still replace the *promise* with the stale value,
  1351. // since we are done with the promise at this point.
  1352. // leave it untouched if we're still waiting for an
  1353. // aborted background fetch that hasn't yet returned.
  1354. this.#valList[index] = bf.__staleWhileFetching;
  1355. }
  1356. }
  1357. if (allowStale) {
  1358. if (options.status && bf.__staleWhileFetching !== undefined) {
  1359. options.status.returnedStale = true;
  1360. }
  1361. return bf.__staleWhileFetching;
  1362. }
  1363. else if (bf.__returned === bf) {
  1364. throw er;
  1365. }
  1366. };
  1367. const pcall = (res, rej) => {
  1368. const fmp = this.#fetchMethod?.(k, v, fetchOpts);
  1369. if (fmp && fmp instanceof Promise) {
  1370. fmp.then(v => res(v === undefined ? undefined : v), rej);
  1371. }
  1372. // ignored, we go until we finish, regardless.
  1373. // defer check until we are actually aborting,
  1374. // so fetchMethod can override.
  1375. ac.signal.addEventListener('abort', () => {
  1376. if (!options.ignoreFetchAbort ||
  1377. options.allowStaleOnFetchAbort) {
  1378. res(undefined);
  1379. // when it eventually resolves, update the cache.
  1380. if (options.allowStaleOnFetchAbort) {
  1381. res = v => cb(v, true);
  1382. }
  1383. }
  1384. });
  1385. };
  1386. if (options.status)
  1387. options.status.fetchDispatched = true;
  1388. const p = new Promise(pcall).then(cb, eb);
  1389. const bf = Object.assign(p, {
  1390. __abortController: ac,
  1391. __staleWhileFetching: v,
  1392. __returned: undefined,
  1393. });
  1394. if (index === undefined) {
  1395. // internal, don't expose status.
  1396. this.set(k, bf, { ...fetchOpts.options, status: undefined });
  1397. index = this.#keyMap.get(k);
  1398. }
  1399. else {
  1400. this.#valList[index] = bf;
  1401. }
  1402. return bf;
  1403. }
  1404. #isBackgroundFetch(p) {
  1405. if (!this.#hasFetchMethod)
  1406. return false;
  1407. const b = p;
  1408. return (!!b &&
  1409. b instanceof Promise &&
  1410. b.hasOwnProperty('__staleWhileFetching') &&
  1411. b.__abortController instanceof AC);
  1412. }
  1413. async fetch(k, fetchOptions = {}) {
  1414. const {
  1415. // get options
  1416. allowStale = this.allowStale, updateAgeOnGet = this.updateAgeOnGet, noDeleteOnStaleGet = this.noDeleteOnStaleGet,
  1417. // set options
  1418. ttl = this.ttl, noDisposeOnSet = this.noDisposeOnSet, size = 0, sizeCalculation = this.sizeCalculation, noUpdateTTL = this.noUpdateTTL,
  1419. // fetch exclusive options
  1420. noDeleteOnFetchRejection = this.noDeleteOnFetchRejection, allowStaleOnFetchRejection = this.allowStaleOnFetchRejection, ignoreFetchAbort = this.ignoreFetchAbort, allowStaleOnFetchAbort = this.allowStaleOnFetchAbort, context, forceRefresh = false, status, signal, } = fetchOptions;
  1421. if (!this.#hasFetchMethod) {
  1422. if (status)
  1423. status.fetch = 'get';
  1424. return this.get(k, {
  1425. allowStale,
  1426. updateAgeOnGet,
  1427. noDeleteOnStaleGet,
  1428. status,
  1429. });
  1430. }
  1431. const options = {
  1432. allowStale,
  1433. updateAgeOnGet,
  1434. noDeleteOnStaleGet,
  1435. ttl,
  1436. noDisposeOnSet,
  1437. size,
  1438. sizeCalculation,
  1439. noUpdateTTL,
  1440. noDeleteOnFetchRejection,
  1441. allowStaleOnFetchRejection,
  1442. allowStaleOnFetchAbort,
  1443. ignoreFetchAbort,
  1444. status,
  1445. signal,
  1446. };
  1447. let index = this.#keyMap.get(k);
  1448. if (index === undefined) {
  1449. if (status)
  1450. status.fetch = 'miss';
  1451. const p = this.#backgroundFetch(k, index, options, context);
  1452. return (p.__returned = p);
  1453. }
  1454. else {
  1455. // in cache, maybe already fetching
  1456. const v = this.#valList[index];
  1457. if (this.#isBackgroundFetch(v)) {
  1458. const stale = allowStale && v.__staleWhileFetching !== undefined;
  1459. if (status) {
  1460. status.fetch = 'inflight';
  1461. if (stale)
  1462. status.returnedStale = true;
  1463. }
  1464. return stale ? v.__staleWhileFetching : (v.__returned = v);
  1465. }
  1466. // if we force a refresh, that means do NOT serve the cached value,
  1467. // unless we are already in the process of refreshing the cache.
  1468. const isStale = this.#isStale(index);
  1469. if (!forceRefresh && !isStale) {
  1470. if (status)
  1471. status.fetch = 'hit';
  1472. this.#moveToTail(index);
  1473. if (updateAgeOnGet) {
  1474. this.#updateItemAge(index);
  1475. }
  1476. if (status)
  1477. this.#statusTTL(status, index);
  1478. return v;
  1479. }
  1480. // ok, it is stale or a forced refresh, and not already fetching.
  1481. // refresh the cache.
  1482. const p = this.#backgroundFetch(k, index, options, context);
  1483. const hasStale = p.__staleWhileFetching !== undefined;
  1484. const staleVal = hasStale && allowStale;
  1485. if (status) {
  1486. status.fetch = isStale ? 'stale' : 'refresh';
  1487. if (staleVal && isStale)
  1488. status.returnedStale = true;
  1489. }
  1490. return staleVal ? p.__staleWhileFetching : (p.__returned = p);
  1491. }
  1492. }
  1493. /**
  1494. * Return a value from the cache. Will update the recency of the cache
  1495. * entry found.
  1496. *
  1497. * If the key is not found, get() will return `undefined`.
  1498. */
  1499. get(k, getOptions = {}) {
  1500. const { allowStale = this.allowStale, updateAgeOnGet = this.updateAgeOnGet, noDeleteOnStaleGet = this.noDeleteOnStaleGet, status, } = getOptions;
  1501. const index = this.#keyMap.get(k);
  1502. if (index !== undefined) {
  1503. const value = this.#valList[index];
  1504. const fetching = this.#isBackgroundFetch(value);
  1505. if (status)
  1506. this.#statusTTL(status, index);
  1507. if (this.#isStale(index)) {
  1508. if (status)
  1509. status.get = 'stale';
  1510. // delete only if not an in-flight background fetch
  1511. if (!fetching) {
  1512. if (!noDeleteOnStaleGet) {
  1513. this.delete(k);
  1514. }
  1515. if (status && allowStale)
  1516. status.returnedStale = true;
  1517. return allowStale ? value : undefined;
  1518. }
  1519. else {
  1520. if (status &&
  1521. allowStale &&
  1522. value.__staleWhileFetching !== undefined) {
  1523. status.returnedStale = true;
  1524. }
  1525. return allowStale ? value.__staleWhileFetching : undefined;
  1526. }
  1527. }
  1528. else {
  1529. if (status)
  1530. status.get = 'hit';
  1531. // if we're currently fetching it, we don't actually have it yet
  1532. // it's not stale, which means this isn't a staleWhileRefetching.
  1533. // If it's not stale, and fetching, AND has a __staleWhileFetching
  1534. // value, then that means the user fetched with {forceRefresh:true},
  1535. // so it's safe to return that value.
  1536. if (fetching) {
  1537. return value.__staleWhileFetching;
  1538. }
  1539. this.#moveToTail(index);
  1540. if (updateAgeOnGet) {
  1541. this.#updateItemAge(index);
  1542. }
  1543. return value;
  1544. }
  1545. }
  1546. else if (status) {
  1547. status.get = 'miss';
  1548. }
  1549. }
  1550. #connect(p, n) {
  1551. this.#prev[n] = p;
  1552. this.#next[p] = n;
  1553. }
  1554. #moveToTail(index) {
  1555. // if tail already, nothing to do
  1556. // if head, move head to next[index]
  1557. // else
  1558. // move next[prev[index]] to next[index] (head has no prev)
  1559. // move prev[next[index]] to prev[index]
  1560. // prev[index] = tail
  1561. // next[tail] = index
  1562. // tail = index
  1563. if (index !== this.#tail) {
  1564. if (index === this.#head) {
  1565. this.#head = this.#next[index];
  1566. }
  1567. else {
  1568. this.#connect(this.#prev[index], this.#next[index]);
  1569. }
  1570. this.#connect(this.#tail, index);
  1571. this.#tail = index;
  1572. }
  1573. }
  1574. /**
  1575. * Deletes a key out of the cache.
  1576. * Returns true if the key was deleted, false otherwise.
  1577. */
  1578. delete(k) {
  1579. let deleted = false;
  1580. if (this.#size !== 0) {
  1581. const index = this.#keyMap.get(k);
  1582. if (index !== undefined) {
  1583. deleted = true;
  1584. if (this.#size === 1) {
  1585. this.clear();
  1586. }
  1587. else {
  1588. this.#removeItemSize(index);
  1589. const v = this.#valList[index];
  1590. if (this.#isBackgroundFetch(v)) {
  1591. v.__abortController.abort(new Error('deleted'));
  1592. }
  1593. else if (this.#hasDispose || this.#hasDisposeAfter) {
  1594. if (this.#hasDispose) {
  1595. this.#dispose?.(v, k, 'delete');
  1596. }
  1597. if (this.#hasDisposeAfter) {
  1598. this.#disposed?.push([v, k, 'delete']);
  1599. }
  1600. }
  1601. this.#keyMap.delete(k);
  1602. this.#keyList[index] = undefined;
  1603. this.#valList[index] = undefined;
  1604. if (index === this.#tail) {
  1605. this.#tail = this.#prev[index];
  1606. }
  1607. else if (index === this.#head) {
  1608. this.#head = this.#next[index];
  1609. }
  1610. else {
  1611. const pi = this.#prev[index];
  1612. this.#next[pi] = this.#next[index];
  1613. const ni = this.#next[index];
  1614. this.#prev[ni] = this.#prev[index];
  1615. }
  1616. this.#size--;
  1617. this.#free.push(index);
  1618. }
  1619. }
  1620. }
  1621. if (this.#hasDisposeAfter && this.#disposed?.length) {
  1622. const dt = this.#disposed;
  1623. let task;
  1624. while ((task = dt?.shift())) {
  1625. this.#disposeAfter?.(...task);
  1626. }
  1627. }
  1628. return deleted;
  1629. }
  1630. /**
  1631. * Clear the cache entirely, throwing away all values.
  1632. */
  1633. clear() {
  1634. for (const index of this.#rindexes({ allowStale: true })) {
  1635. const v = this.#valList[index];
  1636. if (this.#isBackgroundFetch(v)) {
  1637. v.__abortController.abort(new Error('deleted'));
  1638. }
  1639. else {
  1640. const k = this.#keyList[index];
  1641. if (this.#hasDispose) {
  1642. this.#dispose?.(v, k, 'delete');
  1643. }
  1644. if (this.#hasDisposeAfter) {
  1645. this.#disposed?.push([v, k, 'delete']);
  1646. }
  1647. }
  1648. }
  1649. this.#keyMap.clear();
  1650. this.#valList.fill(undefined);
  1651. this.#keyList.fill(undefined);
  1652. if (this.#ttls && this.#starts) {
  1653. this.#ttls.fill(0);
  1654. this.#starts.fill(0);
  1655. }
  1656. if (this.#sizes) {
  1657. this.#sizes.fill(0);
  1658. }
  1659. this.#head = 0;
  1660. this.#tail = 0;
  1661. this.#free.length = 0;
  1662. this.#calculatedSize = 0;
  1663. this.#size = 0;
  1664. if (this.#hasDisposeAfter && this.#disposed) {
  1665. const dt = this.#disposed;
  1666. let task;
  1667. while ((task = dt?.shift())) {
  1668. this.#disposeAfter?.(...task);
  1669. }
  1670. }
  1671. }
  1672. }
  1673. function createCache(max = 500) {
  1674. return new LRUCache({ max });
  1675. }
  1676. function isImportUsed(local, sfc) {
  1677. return resolveTemplateUsedIdentifiers(sfc).has(local);
  1678. }
  1679. const templateUsageCheckCache = createCache();
  1680. function resolveTemplateUsedIdentifiers(sfc) {
  1681. const { content, ast } = sfc.template;
  1682. const cached = templateUsageCheckCache.get(content);
  1683. if (cached) {
  1684. return cached;
  1685. }
  1686. const ids = /* @__PURE__ */ new Set();
  1687. ast.children.forEach(walk);
  1688. function walk(node) {
  1689. var _a;
  1690. switch (node.type) {
  1691. case 1:
  1692. let tag = node.tag;
  1693. if (tag.includes(".")) tag = tag.split(".")[0].trim();
  1694. if (!CompilerDOM.parserOptions.isNativeTag(tag) && !CompilerDOM.parserOptions.isBuiltInComponent(tag)) {
  1695. ids.add(shared.camelize(tag));
  1696. ids.add(shared.capitalize(shared.camelize(tag)));
  1697. }
  1698. for (let i = 0; i < node.props.length; i++) {
  1699. const prop = node.props[i];
  1700. if (prop.type === 7) {
  1701. if (!shared.isBuiltInDirective(prop.name)) {
  1702. ids.add(`v${shared.capitalize(shared.camelize(prop.name))}`);
  1703. }
  1704. if (prop.arg && !prop.arg.isStatic) {
  1705. extractIdentifiers(ids, prop.arg);
  1706. }
  1707. if (prop.name === "for") {
  1708. extractIdentifiers(ids, prop.forParseResult.source);
  1709. } else if (prop.exp) {
  1710. extractIdentifiers(ids, prop.exp);
  1711. } else if (prop.name === "bind" && !prop.exp) {
  1712. ids.add(shared.camelize(prop.arg.content));
  1713. }
  1714. }
  1715. if (prop.type === 6 && prop.name === "ref" && ((_a = prop.value) == null ? void 0 : _a.content)) {
  1716. ids.add(prop.value.content);
  1717. }
  1718. }
  1719. node.children.forEach(walk);
  1720. break;
  1721. case 5:
  1722. extractIdentifiers(ids, node.content);
  1723. break;
  1724. }
  1725. }
  1726. templateUsageCheckCache.set(content, ids);
  1727. return ids;
  1728. }
  1729. function extractIdentifiers(ids, node) {
  1730. if (node.ast) {
  1731. CompilerDOM.walkIdentifiers(node.ast, (n) => ids.add(n.name));
  1732. } else if (node.ast === null) {
  1733. ids.add(node.content);
  1734. }
  1735. }
  1736. const DEFAULT_FILENAME = "anonymous.vue";
  1737. const parseCache$1 = createCache();
  1738. function parse$1(source, options = {}) {
  1739. var _a;
  1740. const sourceKey = shared.genCacheKey(source, {
  1741. ...options,
  1742. compiler: { parse: (_a = options.compiler) == null ? void 0 : _a.parse }
  1743. });
  1744. const cache = parseCache$1.get(sourceKey);
  1745. if (cache) {
  1746. return cache;
  1747. }
  1748. const {
  1749. sourceMap = true,
  1750. filename = DEFAULT_FILENAME,
  1751. sourceRoot = "",
  1752. pad = false,
  1753. ignoreEmpty = true,
  1754. compiler = CompilerDOM__namespace,
  1755. templateParseOptions = {}
  1756. } = options;
  1757. const descriptor = {
  1758. filename,
  1759. source,
  1760. template: null,
  1761. script: null,
  1762. scriptSetup: null,
  1763. styles: [],
  1764. customBlocks: [],
  1765. cssVars: [],
  1766. slotted: false,
  1767. shouldForceReload: (prevImports) => hmrShouldReload(prevImports, descriptor)
  1768. };
  1769. const errors = [];
  1770. const ast = compiler.parse(source, {
  1771. parseMode: "sfc",
  1772. prefixIdentifiers: true,
  1773. ...templateParseOptions,
  1774. onError: (e) => {
  1775. errors.push(e);
  1776. }
  1777. });
  1778. ast.children.forEach((node) => {
  1779. if (node.type !== 1) {
  1780. return;
  1781. }
  1782. if (ignoreEmpty && node.tag !== "template" && isEmpty(node) && !hasSrc(node)) {
  1783. return;
  1784. }
  1785. switch (node.tag) {
  1786. case "template":
  1787. if (!descriptor.template) {
  1788. const templateBlock = descriptor.template = createBlock(
  1789. node,
  1790. source,
  1791. false
  1792. );
  1793. if (!templateBlock.attrs.src) {
  1794. templateBlock.ast = compilerCore.createRoot(node.children, source);
  1795. }
  1796. if (templateBlock.attrs.functional) {
  1797. const err = new SyntaxError(
  1798. `<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.`
  1799. );
  1800. err.loc = node.props.find(
  1801. (p) => p.type === 6 && p.name === "functional"
  1802. ).loc;
  1803. errors.push(err);
  1804. }
  1805. } else {
  1806. errors.push(createDuplicateBlockError(node));
  1807. }
  1808. break;
  1809. case "script":
  1810. const scriptBlock = createBlock(node, source, pad);
  1811. const isSetup = !!scriptBlock.attrs.setup;
  1812. if (isSetup && !descriptor.scriptSetup) {
  1813. descriptor.scriptSetup = scriptBlock;
  1814. break;
  1815. }
  1816. if (!isSetup && !descriptor.script) {
  1817. descriptor.script = scriptBlock;
  1818. break;
  1819. }
  1820. errors.push(createDuplicateBlockError(node, isSetup));
  1821. break;
  1822. case "style":
  1823. const styleBlock = createBlock(node, source, pad);
  1824. if (styleBlock.attrs.vars) {
  1825. errors.push(
  1826. new SyntaxError(
  1827. `<style vars> has been replaced by a new proposal: https://github.com/vuejs/rfcs/pull/231`
  1828. )
  1829. );
  1830. }
  1831. descriptor.styles.push(styleBlock);
  1832. break;
  1833. default:
  1834. descriptor.customBlocks.push(createBlock(node, source, pad));
  1835. break;
  1836. }
  1837. });
  1838. if (!descriptor.template && !descriptor.script && !descriptor.scriptSetup) {
  1839. errors.push(
  1840. new SyntaxError(
  1841. `At least one <template> or <script> is required in a single file component. ${descriptor.filename}`
  1842. )
  1843. );
  1844. }
  1845. if (descriptor.scriptSetup) {
  1846. if (descriptor.scriptSetup.src) {
  1847. errors.push(
  1848. new SyntaxError(
  1849. `<script setup> cannot use the "src" attribute because its syntax will be ambiguous outside of the component.`
  1850. )
  1851. );
  1852. descriptor.scriptSetup = null;
  1853. }
  1854. if (descriptor.script && descriptor.script.src) {
  1855. errors.push(
  1856. new SyntaxError(
  1857. `<script> cannot use the "src" attribute when <script setup> is also present because they must be processed together.`
  1858. )
  1859. );
  1860. descriptor.script = null;
  1861. }
  1862. }
  1863. let templateColumnOffset = 0;
  1864. if (descriptor.template && (descriptor.template.lang === "pug" || descriptor.template.lang === "jade")) {
  1865. [descriptor.template.content, templateColumnOffset] = dedent(
  1866. descriptor.template.content
  1867. );
  1868. }
  1869. if (sourceMap) {
  1870. const genMap = (block, columnOffset = 0) => {
  1871. if (block && !block.src) {
  1872. block.map = generateSourceMap(
  1873. filename,
  1874. source,
  1875. block.content,
  1876. sourceRoot,
  1877. !pad || block.type === "template" ? block.loc.start.line - 1 : 0,
  1878. columnOffset
  1879. );
  1880. }
  1881. };
  1882. genMap(descriptor.template, templateColumnOffset);
  1883. genMap(descriptor.script);
  1884. descriptor.styles.forEach((s) => genMap(s));
  1885. descriptor.customBlocks.forEach((s) => genMap(s));
  1886. }
  1887. descriptor.cssVars = parseCssVars(descriptor);
  1888. const slottedRE = /(?:::v-|:)slotted\(/;
  1889. descriptor.slotted = descriptor.styles.some(
  1890. (s) => s.scoped && slottedRE.test(s.content)
  1891. );
  1892. const result = {
  1893. descriptor,
  1894. errors
  1895. };
  1896. parseCache$1.set(sourceKey, result);
  1897. return result;
  1898. }
  1899. function createDuplicateBlockError(node, isScriptSetup = false) {
  1900. const err = new SyntaxError(
  1901. `Single file component can contain only one <${node.tag}${isScriptSetup ? ` setup` : ``}> element`
  1902. );
  1903. err.loc = node.loc;
  1904. return err;
  1905. }
  1906. function createBlock(node, source, pad) {
  1907. const type = node.tag;
  1908. const loc = node.innerLoc;
  1909. const attrs = {};
  1910. const block = {
  1911. type,
  1912. content: source.slice(loc.start.offset, loc.end.offset),
  1913. loc,
  1914. attrs
  1915. };
  1916. if (pad) {
  1917. block.content = padContent(source, block, pad) + block.content;
  1918. }
  1919. node.props.forEach((p) => {
  1920. if (p.type === 6) {
  1921. const name = p.name;
  1922. attrs[name] = p.value ? p.value.content || true : true;
  1923. if (name === "lang") {
  1924. block.lang = p.value && p.value.content;
  1925. } else if (name === "src") {
  1926. block.src = p.value && p.value.content;
  1927. } else if (type === "style") {
  1928. if (name === "scoped") {
  1929. block.scoped = true;
  1930. } else if (name === "module") {
  1931. block.module = attrs[name];
  1932. }
  1933. } else if (type === "script" && name === "setup") {
  1934. block.setup = attrs.setup;
  1935. }
  1936. }
  1937. });
  1938. return block;
  1939. }
  1940. const splitRE = /\r?\n/g;
  1941. const emptyRE = /^(?:\/\/)?\s*$/;
  1942. const replaceRE = /./g;
  1943. function generateSourceMap(filename, source, generated, sourceRoot, lineOffset, columnOffset) {
  1944. const map = new sourceMapJs.SourceMapGenerator({
  1945. file: filename.replace(/\\/g, "/"),
  1946. sourceRoot: sourceRoot.replace(/\\/g, "/")
  1947. });
  1948. map.setSourceContent(filename, source);
  1949. map._sources.add(filename);
  1950. generated.split(splitRE).forEach((line, index) => {
  1951. if (!emptyRE.test(line)) {
  1952. const originalLine = index + 1 + lineOffset;
  1953. const generatedLine = index + 1;
  1954. for (let i = 0; i < line.length; i++) {
  1955. if (!/\s/.test(line[i])) {
  1956. map._mappings.add({
  1957. originalLine,
  1958. originalColumn: i + columnOffset,
  1959. generatedLine,
  1960. generatedColumn: i,
  1961. source: filename,
  1962. name: null
  1963. });
  1964. }
  1965. }
  1966. }
  1967. });
  1968. return map.toJSON();
  1969. }
  1970. function padContent(content, block, pad) {
  1971. content = content.slice(0, block.loc.start.offset);
  1972. if (pad === "space") {
  1973. return content.replace(replaceRE, " ");
  1974. } else {
  1975. const offset = content.split(splitRE).length;
  1976. const padChar = block.type === "script" && !block.lang ? "//\n" : "\n";
  1977. return Array(offset).join(padChar);
  1978. }
  1979. }
  1980. function hasSrc(node) {
  1981. return node.props.some((p) => {
  1982. if (p.type !== 6) {
  1983. return false;
  1984. }
  1985. return p.name === "src";
  1986. });
  1987. }
  1988. function isEmpty(node) {
  1989. for (let i = 0; i < node.children.length; i++) {
  1990. const child = node.children[i];
  1991. if (child.type !== 2 || child.content.trim() !== "") {
  1992. return false;
  1993. }
  1994. }
  1995. return true;
  1996. }
  1997. function hmrShouldReload(prevImports, next) {
  1998. if (!next.scriptSetup || next.scriptSetup.lang !== "ts" && next.scriptSetup.lang !== "tsx") {
  1999. return false;
  2000. }
  2001. for (const key in prevImports) {
  2002. if (!prevImports[key].isUsedInTemplate && isImportUsed(key, next)) {
  2003. return true;
  2004. }
  2005. }
  2006. return false;
  2007. }
  2008. function dedent(s) {
  2009. const lines = s.split("\n");
  2010. const minIndent = lines.reduce(function(minIndent2, line) {
  2011. var _a, _b;
  2012. if (line.trim() === "") {
  2013. return minIndent2;
  2014. }
  2015. const indent = ((_b = (_a = line.match(/^\s*/)) == null ? void 0 : _a[0]) == null ? void 0 : _b.length) || 0;
  2016. return Math.min(indent, minIndent2);
  2017. }, Infinity);
  2018. if (minIndent === 0) {
  2019. return [s, minIndent];
  2020. }
  2021. return [
  2022. lines.map(function(line) {
  2023. return line.slice(minIndent);
  2024. }).join("\n"),
  2025. minIndent
  2026. ];
  2027. }
  2028. function isRelativeUrl(url) {
  2029. const firstChar = url.charAt(0);
  2030. return firstChar === "." || firstChar === "~" || firstChar === "@";
  2031. }
  2032. const externalRE = /^(https?:)?\/\//;
  2033. function isExternalUrl(url) {
  2034. return externalRE.test(url);
  2035. }
  2036. const dataUrlRE = /^\s*data:/i;
  2037. function isDataUrl(url) {
  2038. return dataUrlRE.test(url);
  2039. }
  2040. function parseUrl(url) {
  2041. const firstChar = url.charAt(0);
  2042. if (firstChar === "~") {
  2043. const secondChar = url.charAt(1);
  2044. url = url.slice(secondChar === "/" ? 2 : 1);
  2045. }
  2046. return parseUriParts(url);
  2047. }
  2048. function parseUriParts(urlString) {
  2049. return url.parse(shared.isString(urlString) ? urlString : "", false, true);
  2050. }
  2051. const defaultAssetUrlOptions = {
  2052. base: null,
  2053. includeAbsolute: false,
  2054. tags: {
  2055. video: ["src", "poster"],
  2056. source: ["src"],
  2057. img: ["src"],
  2058. image: ["xlink:href", "href"],
  2059. use: ["xlink:href", "href"]
  2060. }
  2061. };
  2062. const normalizeOptions = (options) => {
  2063. if (Object.keys(options).some((key) => shared.isArray(options[key]))) {
  2064. return {
  2065. ...defaultAssetUrlOptions,
  2066. tags: options
  2067. };
  2068. }
  2069. return {
  2070. ...defaultAssetUrlOptions,
  2071. ...options
  2072. };
  2073. };
  2074. const createAssetUrlTransformWithOptions = (options) => {
  2075. return (node, context) => transformAssetUrl(node, context, options);
  2076. };
  2077. const transformAssetUrl = (node, context, options = defaultAssetUrlOptions) => {
  2078. if (node.type === 1) {
  2079. if (!node.props.length) {
  2080. return;
  2081. }
  2082. const tags = options.tags || defaultAssetUrlOptions.tags;
  2083. const attrs = tags[node.tag];
  2084. const wildCardAttrs = tags["*"];
  2085. if (!attrs && !wildCardAttrs) {
  2086. return;
  2087. }
  2088. const assetAttrs = (attrs || []).concat(wildCardAttrs || []);
  2089. node.props.forEach((attr, index) => {
  2090. 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)) {
  2091. return;
  2092. }
  2093. const url = parseUrl(attr.value.content);
  2094. if (options.base && attr.value.content[0] === ".") {
  2095. const base = parseUrl(options.base);
  2096. const protocol = base.protocol || "";
  2097. const host = base.host ? protocol + "//" + base.host : "";
  2098. const basePath = base.path || "/";
  2099. attr.value.content = host + (path$1.posix || path$1).join(basePath, url.path + (url.hash || ""));
  2100. return;
  2101. }
  2102. const exp = getImportsExpressionExp(url.path, url.hash, attr.loc, context);
  2103. node.props[index] = {
  2104. type: 7,
  2105. name: "bind",
  2106. arg: compilerCore.createSimpleExpression(attr.name, true, attr.loc),
  2107. exp,
  2108. modifiers: [],
  2109. loc: attr.loc
  2110. };
  2111. });
  2112. }
  2113. };
  2114. function getImportsExpressionExp(path2, hash, loc, context) {
  2115. if (path2) {
  2116. let name;
  2117. let exp;
  2118. const existingIndex = context.imports.findIndex((i) => i.path === path2);
  2119. if (existingIndex > -1) {
  2120. name = `_imports_${existingIndex}`;
  2121. exp = context.imports[existingIndex].exp;
  2122. } else {
  2123. name = `_imports_${context.imports.length}`;
  2124. exp = compilerCore.createSimpleExpression(
  2125. name,
  2126. false,
  2127. loc,
  2128. 3
  2129. );
  2130. context.imports.push({
  2131. exp,
  2132. path: decodeURIComponent(path2)
  2133. });
  2134. }
  2135. if (!hash) {
  2136. return exp;
  2137. }
  2138. const hashExp = `${name} + '${hash}'`;
  2139. const finalExp = compilerCore.createSimpleExpression(
  2140. hashExp,
  2141. false,
  2142. loc,
  2143. 3
  2144. );
  2145. if (!context.hoistStatic) {
  2146. return finalExp;
  2147. }
  2148. const existingHoistIndex = context.hoists.findIndex((h) => {
  2149. return h && h.type === 4 && !h.isStatic && h.content === hashExp;
  2150. });
  2151. if (existingHoistIndex > -1) {
  2152. return compilerCore.createSimpleExpression(
  2153. `_hoisted_${existingHoistIndex + 1}`,
  2154. false,
  2155. loc,
  2156. 3
  2157. );
  2158. }
  2159. return context.hoist(finalExp);
  2160. } else {
  2161. return compilerCore.createSimpleExpression(`''`, false, loc, 3);
  2162. }
  2163. }
  2164. const srcsetTags = ["img", "source"];
  2165. const escapedSpaceCharacters = /( |\\t|\\n|\\f|\\r)+/g;
  2166. const createSrcsetTransformWithOptions = (options) => {
  2167. return (node, context) => transformSrcset(node, context, options);
  2168. };
  2169. const transformSrcset = (node, context, options = defaultAssetUrlOptions) => {
  2170. if (node.type === 1) {
  2171. if (srcsetTags.includes(node.tag) && node.props.length) {
  2172. node.props.forEach((attr, index) => {
  2173. if (attr.name === "srcset" && attr.type === 6) {
  2174. if (!attr.value) return;
  2175. const value = attr.value.content;
  2176. if (!value) return;
  2177. const imageCandidates = value.split(",").map((s) => {
  2178. const [url, descriptor] = s.replace(escapedSpaceCharacters, " ").trim().split(" ", 2);
  2179. return { url, descriptor };
  2180. });
  2181. for (let i = 0; i < imageCandidates.length; i++) {
  2182. const { url } = imageCandidates[i];
  2183. if (isDataUrl(url)) {
  2184. imageCandidates[i + 1].url = url + "," + imageCandidates[i + 1].url;
  2185. imageCandidates.splice(i, 1);
  2186. }
  2187. }
  2188. const shouldProcessUrl = (url) => {
  2189. return !isExternalUrl(url) && !isDataUrl(url) && (options.includeAbsolute || isRelativeUrl(url));
  2190. };
  2191. if (!imageCandidates.some(({ url }) => shouldProcessUrl(url))) {
  2192. return;
  2193. }
  2194. if (options.base) {
  2195. const base = options.base;
  2196. const set = [];
  2197. let needImportTransform = false;
  2198. imageCandidates.forEach((candidate) => {
  2199. let { url, descriptor } = candidate;
  2200. descriptor = descriptor ? ` ${descriptor}` : ``;
  2201. if (url[0] === ".") {
  2202. candidate.url = (path$1.posix || path$1).join(base, url);
  2203. set.push(candidate.url + descriptor);
  2204. } else if (shouldProcessUrl(url)) {
  2205. needImportTransform = true;
  2206. } else {
  2207. set.push(url + descriptor);
  2208. }
  2209. });
  2210. if (!needImportTransform) {
  2211. attr.value.content = set.join(", ");
  2212. return;
  2213. }
  2214. }
  2215. const compoundExpression = compilerCore.createCompoundExpression([], attr.loc);
  2216. imageCandidates.forEach(({ url, descriptor }, index2) => {
  2217. if (shouldProcessUrl(url)) {
  2218. const { path: path2 } = parseUrl(url);
  2219. let exp2;
  2220. if (path2) {
  2221. const existingImportsIndex = context.imports.findIndex(
  2222. (i) => i.path === path2
  2223. );
  2224. if (existingImportsIndex > -1) {
  2225. exp2 = compilerCore.createSimpleExpression(
  2226. `_imports_${existingImportsIndex}`,
  2227. false,
  2228. attr.loc,
  2229. 3
  2230. );
  2231. } else {
  2232. exp2 = compilerCore.createSimpleExpression(
  2233. `_imports_${context.imports.length}`,
  2234. false,
  2235. attr.loc,
  2236. 3
  2237. );
  2238. context.imports.push({ exp: exp2, path: path2 });
  2239. }
  2240. compoundExpression.children.push(exp2);
  2241. }
  2242. } else {
  2243. const exp2 = compilerCore.createSimpleExpression(
  2244. `"${url}"`,
  2245. false,
  2246. attr.loc,
  2247. 3
  2248. );
  2249. compoundExpression.children.push(exp2);
  2250. }
  2251. const isNotLast = imageCandidates.length - 1 > index2;
  2252. if (descriptor && isNotLast) {
  2253. compoundExpression.children.push(` + ' ${descriptor}, ' + `);
  2254. } else if (descriptor) {
  2255. compoundExpression.children.push(` + ' ${descriptor}'`);
  2256. } else if (isNotLast) {
  2257. compoundExpression.children.push(` + ', ' + `);
  2258. }
  2259. });
  2260. let exp = compoundExpression;
  2261. if (context.hoistStatic) {
  2262. exp = context.hoist(compoundExpression);
  2263. exp.constType = 3;
  2264. }
  2265. node.props[index] = {
  2266. type: 7,
  2267. name: "bind",
  2268. arg: compilerCore.createSimpleExpression("srcset", true, attr.loc),
  2269. exp,
  2270. modifiers: [],
  2271. loc: attr.loc
  2272. };
  2273. }
  2274. });
  2275. }
  2276. }
  2277. };
  2278. function commonjsRequire(path) {
  2279. 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.');
  2280. }
  2281. var consolidate$2 = {exports: {}};
  2282. var hasRequiredConsolidate$1;
  2283. function requireConsolidate$1 () {
  2284. if (hasRequiredConsolidate$1) return consolidate$2.exports;
  2285. hasRequiredConsolidate$1 = 1;
  2286. (function (module, exports) {
  2287. /*
  2288. * Engines which do not support caching of their file contents
  2289. * should use the `read()` function defined in consolidate.js
  2290. * On top of this, when an engine compiles to a `Function`,
  2291. * these functions should either be cached within consolidate.js
  2292. * or the engine itself via `options.cache`. This will allow
  2293. * users and frameworks to pass `options.cache = true` for
  2294. * `NODE_ENV=production`, however edit the file(s) without
  2295. * re-loading the application in development.
  2296. */
  2297. /**
  2298. * Module dependencies.
  2299. */
  2300. var fs = require$$0;
  2301. var path = path$1;
  2302. var util = require$$2;
  2303. var join = path.join;
  2304. var resolve = path.resolve;
  2305. var extname = path.extname;
  2306. var dirname = path.dirname;
  2307. var isAbsolute = path.isAbsolute;
  2308. var readCache = {};
  2309. /**
  2310. * Require cache.
  2311. */
  2312. var cacheStore = {};
  2313. /**
  2314. * Require cache.
  2315. */
  2316. var requires = {};
  2317. /**
  2318. * Clear the cache.
  2319. *
  2320. * @api public
  2321. */
  2322. exports.clearCache = function() {
  2323. readCache = {};
  2324. cacheStore = {};
  2325. };
  2326. /**
  2327. * Conditionally cache `compiled` template based
  2328. * on the `options` filename and `.cache` boolean.
  2329. *
  2330. * @param {Object} options
  2331. * @param {Function} compiled
  2332. * @return {Function}
  2333. * @api private
  2334. */
  2335. function cache(options, compiled) {
  2336. // cachable
  2337. if (compiled && options.filename && options.cache) {
  2338. delete readCache[options.filename];
  2339. cacheStore[options.filename] = compiled;
  2340. return compiled;
  2341. }
  2342. // check cache
  2343. if (options.filename && options.cache) {
  2344. return cacheStore[options.filename];
  2345. }
  2346. return compiled;
  2347. }
  2348. /**
  2349. * Read `path` with `options` with
  2350. * callback `(err, str)`. When `options.cache`
  2351. * is true the template string will be cached.
  2352. *
  2353. * @param {String} options
  2354. * @param {Function} cb
  2355. * @api private
  2356. */
  2357. function read(path, options, cb) {
  2358. var str = readCache[path];
  2359. var cached = options.cache && str && typeof str === 'string';
  2360. // cached (only if cached is a string and not a compiled template function)
  2361. if (cached) return cb(null, str);
  2362. // read
  2363. fs.readFile(path, 'utf8', function(err, str) {
  2364. if (err) return cb(err);
  2365. // remove extraneous utf8 BOM marker
  2366. str = str.replace(/^\uFEFF/, '');
  2367. if (options.cache) readCache[path] = str;
  2368. cb(null, str);
  2369. });
  2370. }
  2371. /**
  2372. * Read `path` with `options` with
  2373. * callback `(err, str)`. When `options.cache`
  2374. * is true the partial string will be cached.
  2375. *
  2376. * @param {String} options
  2377. * @param {Function} fn
  2378. * @api private
  2379. */
  2380. function readPartials(path, options, cb) {
  2381. if (!options.partials) return cb();
  2382. var keys = Object.keys(options.partials);
  2383. var partials = {};
  2384. function next(index) {
  2385. if (index === keys.length) return cb(null, partials);
  2386. var key = keys[index];
  2387. var partialPath = options.partials[key];
  2388. if (partialPath === undefined || partialPath === null || partialPath === false) {
  2389. return next(++index);
  2390. }
  2391. var file;
  2392. if (isAbsolute(partialPath)) {
  2393. if (extname(partialPath) !== '') {
  2394. file = partialPath;
  2395. } else {
  2396. file = join(partialPath + extname(path));
  2397. }
  2398. } else {
  2399. file = join(dirname(path), partialPath + extname(path));
  2400. }
  2401. read(file, options, function(err, str) {
  2402. if (err) return cb(err);
  2403. partials[key] = str;
  2404. next(++index);
  2405. });
  2406. }
  2407. next(0);
  2408. }
  2409. /**
  2410. * promisify
  2411. */
  2412. function promisify(cb, fn) {
  2413. return new Promise(function(resolve, reject) {
  2414. cb = cb || function(err, html) {
  2415. if (err) {
  2416. return reject(err);
  2417. }
  2418. resolve(html);
  2419. };
  2420. fn(cb);
  2421. });
  2422. }
  2423. /**
  2424. * fromStringRenderer
  2425. */
  2426. function fromStringRenderer(name) {
  2427. return function(path, options, cb) {
  2428. options.filename = path;
  2429. return promisify(cb, function(cb) {
  2430. readPartials(path, options, function(err, partials) {
  2431. var extend = (requires.extend || (requires.extend = require$$2._extend));
  2432. var opts = extend({}, options);
  2433. opts.partials = partials;
  2434. if (err) return cb(err);
  2435. if (cache(opts)) {
  2436. exports[name].render('', opts, cb);
  2437. } else {
  2438. read(path, opts, function(err, str) {
  2439. if (err) return cb(err);
  2440. exports[name].render(str, opts, cb);
  2441. });
  2442. }
  2443. });
  2444. });
  2445. };
  2446. }
  2447. /**
  2448. * velocity support.
  2449. */
  2450. exports.velocityjs = fromStringRenderer('velocityjs');
  2451. /**
  2452. * velocity string support.
  2453. */
  2454. exports.velocityjs.render = function(str, options, cb) {
  2455. return promisify(cb, function(cb) {
  2456. var engine = requires.velocityjs || (requires.velocityjs = require('velocityjs'));
  2457. try {
  2458. options.locals = options;
  2459. cb(null, engine.render(str, options).trimLeft());
  2460. } catch (err) {
  2461. cb(err);
  2462. }
  2463. });
  2464. };
  2465. /**
  2466. * Liquid support.
  2467. */
  2468. exports.liquid = fromStringRenderer('liquid');
  2469. /**
  2470. * Liquid string support.
  2471. */
  2472. /**
  2473. * Note that in order to get filters and custom tags we've had to push
  2474. * all user-defined locals down into @locals. However, just to make things
  2475. * backwards-compatible, any property of `options` that is left after
  2476. * processing and removing `locals`, `meta`, `filters`, `customTags` and
  2477. * `includeDir` will also become a local.
  2478. */
  2479. function _renderTinyliquid(engine, str, options, cb) {
  2480. var context = engine.newContext();
  2481. var k;
  2482. /**
  2483. * Note that there's a bug in the library that doesn't allow us to pass
  2484. * the locals to newContext(), hence looping through the keys:
  2485. */
  2486. if (options.locals) {
  2487. for (k in options.locals) {
  2488. context.setLocals(k, options.locals[k]);
  2489. }
  2490. delete options.locals;
  2491. }
  2492. if (options.meta) {
  2493. context.setLocals('page', options.meta);
  2494. delete options.meta;
  2495. }
  2496. /**
  2497. * Add any defined filters:
  2498. */
  2499. if (options.filters) {
  2500. for (k in options.filters) {
  2501. context.setFilter(k, options.filters[k]);
  2502. }
  2503. delete options.filters;
  2504. }
  2505. /**
  2506. * Set up a callback for the include directory:
  2507. */
  2508. var includeDir = options.includeDir || process.cwd();
  2509. context.onInclude(function(name, callback) {
  2510. var extname = path.extname(name) ? '' : '.liquid';
  2511. var filename = path.resolve(includeDir, name + extname);
  2512. fs.readFile(filename, {encoding: 'utf8'}, function(err, data) {
  2513. if (err) return callback(err);
  2514. callback(null, engine.parse(data));
  2515. });
  2516. });
  2517. delete options.includeDir;
  2518. /**
  2519. * The custom tag functions need to have their results pushed back
  2520. * through the parser, so set up a shim before calling the provided
  2521. * callback:
  2522. */
  2523. var compileOptions = {
  2524. customTags: {}
  2525. };
  2526. if (options.customTags) {
  2527. var tagFunctions = options.customTags;
  2528. for (k in options.customTags) {
  2529. /*Tell jshint there's no problem with having this function in the loop */
  2530. /*jshint -W083 */
  2531. compileOptions.customTags[k] = function(context, name, body) {
  2532. var tpl = tagFunctions[name](body.trim());
  2533. context.astStack.push(engine.parse(tpl));
  2534. };
  2535. /*jshint +W083 */
  2536. }
  2537. delete options.customTags;
  2538. }
  2539. /**
  2540. * Now anything left in `options` becomes a local:
  2541. */
  2542. for (k in options) {
  2543. context.setLocals(k, options[k]);
  2544. }
  2545. /**
  2546. * Finally, execute the template:
  2547. */
  2548. var tmpl = cache(context) || cache(context, engine.compile(str, compileOptions));
  2549. tmpl(context, cb);
  2550. }
  2551. exports.liquid.render = function(str, options, cb) {
  2552. return promisify(cb, function(cb) {
  2553. var engine = requires.liquid;
  2554. var Liquid;
  2555. try {
  2556. // set up tinyliquid engine
  2557. engine = requires.liquid = require('tinyliquid');
  2558. // use tinyliquid engine
  2559. _renderTinyliquid(engine, str, options, cb);
  2560. return;
  2561. } catch (err) {
  2562. // set up liquid-node engine
  2563. try {
  2564. Liquid = requires.liquid = require('liquid-node');
  2565. engine = new Liquid.Engine();
  2566. } catch (err) {
  2567. throw err;
  2568. }
  2569. }
  2570. // use liquid-node engine
  2571. try {
  2572. var locals = options.locals || {};
  2573. if (options.meta) {
  2574. locals.pages = options.meta;
  2575. delete options.meta;
  2576. }
  2577. /**
  2578. * Add any defined filters:
  2579. */
  2580. if (options.filters) {
  2581. engine.registerFilters(options.filters);
  2582. delete options.filters;
  2583. }
  2584. /**
  2585. * Set up a callback for the include directory:
  2586. */
  2587. var includeDir = options.includeDir || process.cwd();
  2588. engine.fileSystem = new Liquid.LocalFileSystem(includeDir, 'liquid');
  2589. delete options.includeDir;
  2590. /**
  2591. * The custom tag functions need to have their results pushed back
  2592. * through the parser, so set up a shim before calling the provided
  2593. * callback:
  2594. */
  2595. if (options.customTags) {
  2596. var tagFunctions = options.customTags;
  2597. for (k in options.customTags) {
  2598. engine.registerTag(k, tagFunctions[k]);
  2599. }
  2600. delete options.customTags;
  2601. }
  2602. /**
  2603. * Now anything left in `options` becomes a local:
  2604. */
  2605. for (var k in options) {
  2606. locals[k] = options[k];
  2607. }
  2608. /**
  2609. * Finally, execute the template:
  2610. */
  2611. return engine
  2612. .parseAndRender(str, locals)
  2613. .nodeify(function(err, result) {
  2614. if (err) {
  2615. throw new Error(err);
  2616. } else {
  2617. return cb(null, result);
  2618. }
  2619. });
  2620. } catch (err) {
  2621. cb(err);
  2622. }
  2623. });
  2624. };
  2625. /**
  2626. * Jade support.
  2627. */
  2628. exports.jade = function(path, options, cb) {
  2629. return promisify(cb, function(cb) {
  2630. var engine = requires.jade;
  2631. if (!engine) {
  2632. try {
  2633. engine = requires.jade = require('jade');
  2634. } catch (err) {
  2635. try {
  2636. engine = requires.jade = require('then-jade');
  2637. } catch (otherError) {
  2638. throw err;
  2639. }
  2640. }
  2641. }
  2642. try {
  2643. var tmpl = cache(options) || cache(options, engine.compileFile(path, options));
  2644. cb(null, tmpl(options));
  2645. } catch (err) {
  2646. cb(err);
  2647. }
  2648. });
  2649. };
  2650. /**
  2651. * Jade string support.
  2652. */
  2653. exports.jade.render = function(str, options, cb) {
  2654. return promisify(cb, function(cb) {
  2655. var engine = requires.jade;
  2656. if (!engine) {
  2657. try {
  2658. engine = requires.jade = require('jade');
  2659. } catch (err) {
  2660. try {
  2661. engine = requires.jade = require('then-jade');
  2662. } catch (otherError) {
  2663. throw err;
  2664. }
  2665. }
  2666. }
  2667. try {
  2668. var tmpl = cache(options) || cache(options, engine.compile(str, options));
  2669. cb(null, tmpl(options));
  2670. } catch (err) {
  2671. cb(err);
  2672. }
  2673. });
  2674. };
  2675. /**
  2676. * Dust support.
  2677. */
  2678. exports.dust = fromStringRenderer('dust');
  2679. /**
  2680. * Dust string support.
  2681. */
  2682. exports.dust.render = function(str, options, cb) {
  2683. return promisify(cb, function(cb) {
  2684. var engine = requires.dust;
  2685. if (!engine) {
  2686. try {
  2687. engine = requires.dust = require('dust');
  2688. } catch (err) {
  2689. try {
  2690. engine = requires.dust = require('dustjs-helpers');
  2691. } catch (err) {
  2692. engine = requires.dust = require('dustjs-linkedin');
  2693. }
  2694. }
  2695. }
  2696. var ext = 'dust';
  2697. var views = '.';
  2698. if (options) {
  2699. if (options.ext) ext = options.ext;
  2700. if (options.views) views = options.views;
  2701. if (options.settings && options.settings.views) views = options.settings.views;
  2702. }
  2703. if (!options || (options && !options.cache)) engine.cache = {};
  2704. engine.onLoad = function(path, callback) {
  2705. if (extname(path) === '') path += '.' + ext;
  2706. if (path[0] !== '/') path = views + '/' + path;
  2707. read(path, options, callback);
  2708. };
  2709. try {
  2710. var templateName;
  2711. if (options.filename) {
  2712. templateName = options.filename.replace(new RegExp('^' + views + '/'), '').replace(new RegExp('\\.' + ext), '');
  2713. }
  2714. var tmpl = cache(options) || cache(options, engine.compileFn(str, templateName));
  2715. tmpl(options, cb);
  2716. } catch (err) {
  2717. cb(err);
  2718. }
  2719. });
  2720. };
  2721. /**
  2722. * Swig support.
  2723. */
  2724. exports.swig = fromStringRenderer('swig');
  2725. /**
  2726. * Swig string support.
  2727. */
  2728. exports.swig.render = function(str, options, cb) {
  2729. return promisify(cb, function(cb) {
  2730. var engine = requires.swig;
  2731. if (!engine) {
  2732. try {
  2733. engine = requires.swig = require('swig');
  2734. } catch (err) {
  2735. try {
  2736. engine = requires.swig = require('swig-templates');
  2737. } catch (otherError) {
  2738. throw err;
  2739. }
  2740. }
  2741. }
  2742. try {
  2743. if (options.cache === true) options.cache = 'memory';
  2744. engine.setDefaults({ cache: options.cache });
  2745. var tmpl = cache(options) || cache(options, engine.compile(str, options));
  2746. cb(null, tmpl(options));
  2747. } catch (err) {
  2748. cb(err);
  2749. }
  2750. });
  2751. };
  2752. /**
  2753. * Razor support.
  2754. */
  2755. exports.razor = function(path, options, cb) {
  2756. return promisify(cb, function(cb) {
  2757. var engine = requires.razor;
  2758. if (!engine) {
  2759. try {
  2760. engine = requires.razor = require('razor-tmpl');
  2761. } catch (err) {
  2762. throw err;
  2763. }
  2764. }
  2765. try {
  2766. var tmpl = cache(options) || cache(options, (locals) => {
  2767. console.log('Rendering razor file', path);
  2768. return engine.renderFileSync(path, locals);
  2769. });
  2770. cb(null, tmpl(options));
  2771. } catch (err) {
  2772. cb(err);
  2773. }
  2774. });
  2775. };
  2776. /**
  2777. * razor string support.
  2778. */
  2779. exports.razor.render = function(str, options, cb) {
  2780. return promisify(cb, function(cb) {
  2781. try {
  2782. var engine = requires.razor = require('razor-tmpl');
  2783. } catch (err) {
  2784. throw err;
  2785. }
  2786. try {
  2787. var tf = engine.compile(str);
  2788. var tmpl = cache(options) || cache(options, tf);
  2789. cb(null, tmpl(options));
  2790. } catch (err) {
  2791. cb(err);
  2792. }
  2793. });
  2794. };
  2795. /**
  2796. * Atpl support.
  2797. */
  2798. exports.atpl = fromStringRenderer('atpl');
  2799. /**
  2800. * Atpl string support.
  2801. */
  2802. exports.atpl.render = function(str, options, cb) {
  2803. return promisify(cb, function(cb) {
  2804. var engine = requires.atpl || (requires.atpl = require('atpl'));
  2805. try {
  2806. var tmpl = cache(options) || cache(options, engine.compile(str, options));
  2807. cb(null, tmpl(options));
  2808. } catch (err) {
  2809. cb(err);
  2810. }
  2811. });
  2812. };
  2813. /**
  2814. * Liquor support,
  2815. */
  2816. exports.liquor = fromStringRenderer('liquor');
  2817. /**
  2818. * Liquor string support.
  2819. */
  2820. exports.liquor.render = function(str, options, cb) {
  2821. return promisify(cb, function(cb) {
  2822. var engine = requires.liquor || (requires.liquor = require('liquor'));
  2823. try {
  2824. var tmpl = cache(options) || cache(options, engine.compile(str, options));
  2825. cb(null, tmpl(options));
  2826. } catch (err) {
  2827. cb(err);
  2828. }
  2829. });
  2830. };
  2831. /**
  2832. * Twig support.
  2833. */
  2834. exports.twig = fromStringRenderer('twig');
  2835. /**
  2836. * Twig string support.
  2837. */
  2838. exports.twig.render = function(str, options, cb) {
  2839. return promisify(cb, function(cb) {
  2840. var engine = requires.twig || (requires.twig = require('twig').twig);
  2841. var templateData = {
  2842. data: str,
  2843. allowInlineIncludes: options.allowInlineIncludes,
  2844. namespaces: options.namespaces,
  2845. path: options.path
  2846. };
  2847. try {
  2848. var tmpl = cache(templateData) || cache(templateData, engine(templateData));
  2849. cb(null, tmpl.render(options));
  2850. } catch (err) {
  2851. cb(err);
  2852. }
  2853. });
  2854. };
  2855. /**
  2856. * EJS support.
  2857. */
  2858. exports.ejs = fromStringRenderer('ejs');
  2859. /**
  2860. * EJS string support.
  2861. */
  2862. exports.ejs.render = function(str, options, cb) {
  2863. return promisify(cb, function(cb) {
  2864. var engine = requires.ejs || (requires.ejs = require('ejs'));
  2865. try {
  2866. var tmpl = cache(options) || cache(options, engine.compile(str, options));
  2867. cb(null, tmpl(options));
  2868. } catch (err) {
  2869. cb(err);
  2870. }
  2871. });
  2872. };
  2873. /**
  2874. * Eco support.
  2875. */
  2876. exports.eco = fromStringRenderer('eco');
  2877. /**
  2878. * Eco string support.
  2879. */
  2880. exports.eco.render = function(str, options, cb) {
  2881. return promisify(cb, function(cb) {
  2882. var engine = requires.eco || (requires.eco = require('eco'));
  2883. try {
  2884. cb(null, engine.render(str, options));
  2885. } catch (err) {
  2886. cb(err);
  2887. }
  2888. });
  2889. };
  2890. /**
  2891. * Jazz support.
  2892. */
  2893. exports.jazz = fromStringRenderer('jazz');
  2894. /**
  2895. * Jazz string support.
  2896. */
  2897. exports.jazz.render = function(str, options, cb) {
  2898. return promisify(cb, function(cb) {
  2899. var engine = requires.jazz || (requires.jazz = require('jazz'));
  2900. try {
  2901. var tmpl = cache(options) || cache(options, engine.compile(str, options));
  2902. tmpl.eval(options, function(str) {
  2903. cb(null, str);
  2904. });
  2905. } catch (err) {
  2906. cb(err);
  2907. }
  2908. });
  2909. };
  2910. /**
  2911. * JQTPL support.
  2912. */
  2913. exports.jqtpl = fromStringRenderer('jqtpl');
  2914. /**
  2915. * JQTPL string support.
  2916. */
  2917. exports.jqtpl.render = function(str, options, cb) {
  2918. return promisify(cb, function(cb) {
  2919. var engine = requires.jqtpl || (requires.jqtpl = require('jqtpl'));
  2920. try {
  2921. engine.template(str, str);
  2922. cb(null, engine.tmpl(str, options));
  2923. } catch (err) {
  2924. cb(err);
  2925. }
  2926. });
  2927. };
  2928. /**
  2929. * Haml support.
  2930. */
  2931. exports.haml = fromStringRenderer('haml');
  2932. /**
  2933. * Haml string support.
  2934. */
  2935. exports.haml.render = function(str, options, cb) {
  2936. return promisify(cb, function(cb) {
  2937. var engine = requires.haml || (requires.haml = require('hamljs'));
  2938. try {
  2939. options.locals = options;
  2940. cb(null, engine.render(str, options).trimLeft());
  2941. } catch (err) {
  2942. cb(err);
  2943. }
  2944. });
  2945. };
  2946. /**
  2947. * Hamlet support.
  2948. */
  2949. exports.hamlet = fromStringRenderer('hamlet');
  2950. /**
  2951. * Hamlet string support.
  2952. */
  2953. exports.hamlet.render = function(str, options, cb) {
  2954. return promisify(cb, function(cb) {
  2955. var engine = requires.hamlet || (requires.hamlet = require('hamlet'));
  2956. try {
  2957. options.locals = options;
  2958. cb(null, engine.render(str, options).trimLeft());
  2959. } catch (err) {
  2960. cb(err);
  2961. }
  2962. });
  2963. };
  2964. /**
  2965. * Whiskers support.
  2966. */
  2967. exports.whiskers = function(path, options, cb) {
  2968. return promisify(cb, function(cb) {
  2969. var engine = requires.whiskers || (requires.whiskers = require('whiskers'));
  2970. engine.__express(path, options, cb);
  2971. });
  2972. };
  2973. /**
  2974. * Whiskers string support.
  2975. */
  2976. exports.whiskers.render = function(str, options, cb) {
  2977. return promisify(cb, function(cb) {
  2978. var engine = requires.whiskers || (requires.whiskers = require('whiskers'));
  2979. try {
  2980. cb(null, engine.render(str, options));
  2981. } catch (err) {
  2982. cb(err);
  2983. }
  2984. });
  2985. };
  2986. /**
  2987. * Coffee-HAML support.
  2988. */
  2989. exports['haml-coffee'] = fromStringRenderer('haml-coffee');
  2990. /**
  2991. * Coffee-HAML string support.
  2992. */
  2993. exports['haml-coffee'].render = function(str, options, cb) {
  2994. return promisify(cb, function(cb) {
  2995. var engine = requires['haml-coffee'] || (requires['haml-coffee'] = require('haml-coffee'));
  2996. try {
  2997. var tmpl = cache(options) || cache(options, engine.compile(str, options));
  2998. cb(null, tmpl(options));
  2999. } catch (err) {
  3000. cb(err);
  3001. }
  3002. });
  3003. };
  3004. /**
  3005. * Hogan support.
  3006. */
  3007. exports.hogan = fromStringRenderer('hogan');
  3008. /**
  3009. * Hogan string support.
  3010. */
  3011. exports.hogan.render = function(str, options, cb) {
  3012. return promisify(cb, function(cb) {
  3013. var engine = requires.hogan || (requires.hogan = require('hogan.js'));
  3014. try {
  3015. var tmpl = cache(options) || cache(options, engine.compile(str, options));
  3016. cb(null, tmpl.render(options, options.partials));
  3017. } catch (err) {
  3018. cb(err);
  3019. }
  3020. });
  3021. };
  3022. /**
  3023. * templayed.js support.
  3024. */
  3025. exports.templayed = fromStringRenderer('templayed');
  3026. /**
  3027. * templayed.js string support.
  3028. */
  3029. exports.templayed.render = function(str, options, cb) {
  3030. return promisify(cb, function(cb) {
  3031. var engine = requires.templayed || (requires.templayed = require('templayed'));
  3032. try {
  3033. var tmpl = cache(options) || cache(options, engine(str));
  3034. cb(null, tmpl(options));
  3035. } catch (err) {
  3036. cb(err);
  3037. }
  3038. });
  3039. };
  3040. /**
  3041. * Handlebars support.
  3042. */
  3043. exports.handlebars = fromStringRenderer('handlebars');
  3044. /**
  3045. * Handlebars string support.
  3046. */
  3047. exports.handlebars.render = function(str, options, cb) {
  3048. return promisify(cb, function(cb) {
  3049. var engine = requires.handlebars || (requires.handlebars = require('handlebars'));
  3050. try {
  3051. for (var partial in options.partials) {
  3052. engine.registerPartial(partial, options.partials[partial]);
  3053. }
  3054. for (var helper in options.helpers) {
  3055. engine.registerHelper(helper, options.helpers[helper]);
  3056. }
  3057. var tmpl = cache(options) || cache(options, engine.compile(str, options));
  3058. cb(null, tmpl(options));
  3059. } catch (err) {
  3060. cb(err);
  3061. }
  3062. });
  3063. };
  3064. /**
  3065. * Underscore support.
  3066. */
  3067. exports.underscore = fromStringRenderer('underscore');
  3068. /**
  3069. * Underscore string support.
  3070. */
  3071. exports.underscore.render = function(str, options, cb) {
  3072. return promisify(cb, function(cb) {
  3073. var engine = requires.underscore || (requires.underscore = require('underscore'));
  3074. try {
  3075. const partials = {};
  3076. for (var partial in options.partials) {
  3077. partials[partial] = engine.template(options.partials[partial]);
  3078. }
  3079. options.partials = partials;
  3080. var tmpl = cache(options) || cache(options, engine.template(str, null, options));
  3081. cb(null, tmpl(options).replace(/\n$/, ''));
  3082. } catch (err) {
  3083. cb(err);
  3084. }
  3085. });
  3086. };
  3087. /**
  3088. * Lodash support.
  3089. */
  3090. exports.lodash = fromStringRenderer('lodash');
  3091. /**
  3092. * Lodash string support.
  3093. */
  3094. exports.lodash.render = function(str, options, cb) {
  3095. return promisify(cb, function(cb) {
  3096. var engine = requires.lodash || (requires.lodash = require('lodash'));
  3097. try {
  3098. var tmpl = cache(options) || cache(options, engine.template(str, options));
  3099. cb(null, tmpl(options).replace(/\n$/, ''));
  3100. } catch (err) {
  3101. cb(err);
  3102. }
  3103. });
  3104. };
  3105. /**
  3106. * Pug support. (formerly Jade)
  3107. */
  3108. exports.pug = function(path, options, cb) {
  3109. return promisify(cb, function(cb) {
  3110. var engine = requires.pug;
  3111. if (!engine) {
  3112. try {
  3113. engine = requires.pug = require('pug');
  3114. } catch (err) {
  3115. try {
  3116. engine = requires.pug = require('then-pug');
  3117. } catch (otherError) {
  3118. throw err;
  3119. }
  3120. }
  3121. }
  3122. try {
  3123. var tmpl = cache(options) || cache(options, engine.compileFile(path, options));
  3124. cb(null, tmpl(options));
  3125. } catch (err) {
  3126. cb(err);
  3127. }
  3128. });
  3129. };
  3130. /**
  3131. * Pug string support.
  3132. */
  3133. exports.pug.render = function(str, options, cb) {
  3134. return promisify(cb, function(cb) {
  3135. var engine = requires.pug;
  3136. if (!engine) {
  3137. try {
  3138. engine = requires.pug = require('pug');
  3139. } catch (err) {
  3140. try {
  3141. engine = requires.pug = require('then-pug');
  3142. } catch (otherError) {
  3143. throw err;
  3144. }
  3145. }
  3146. }
  3147. try {
  3148. var tmpl = cache(options) || cache(options, engine.compile(str, options));
  3149. cb(null, tmpl(options));
  3150. } catch (err) {
  3151. cb(err);
  3152. }
  3153. });
  3154. };
  3155. /**
  3156. * QEJS support.
  3157. */
  3158. exports.qejs = fromStringRenderer('qejs');
  3159. /**
  3160. * QEJS string support.
  3161. */
  3162. exports.qejs.render = function(str, options, cb) {
  3163. return promisify(cb, function(cb) {
  3164. try {
  3165. var engine = requires.qejs || (requires.qejs = require('qejs'));
  3166. engine.render(str, options).then(function(result) {
  3167. cb(null, result);
  3168. }, function(err) {
  3169. cb(err);
  3170. }).done();
  3171. } catch (err) {
  3172. cb(err);
  3173. }
  3174. });
  3175. };
  3176. /**
  3177. * Walrus support.
  3178. */
  3179. exports.walrus = fromStringRenderer('walrus');
  3180. /**
  3181. * Walrus string support.
  3182. */
  3183. exports.walrus.render = function(str, options, cb) {
  3184. return promisify(cb, function(cb) {
  3185. var engine = requires.walrus || (requires.walrus = require('walrus'));
  3186. try {
  3187. var tmpl = cache(options) || cache(options, engine.parse(str));
  3188. cb(null, tmpl.compile(options));
  3189. } catch (err) {
  3190. cb(err);
  3191. }
  3192. });
  3193. };
  3194. /**
  3195. * Mustache support.
  3196. */
  3197. exports.mustache = fromStringRenderer('mustache');
  3198. /**
  3199. * Mustache string support.
  3200. */
  3201. exports.mustache.render = function(str, options, cb) {
  3202. return promisify(cb, function(cb) {
  3203. var engine = requires.mustache || (requires.mustache = require('mustache'));
  3204. try {
  3205. cb(null, engine.render(str, options, options.partials));
  3206. } catch (err) {
  3207. cb(err);
  3208. }
  3209. });
  3210. };
  3211. /**
  3212. * Just support.
  3213. */
  3214. exports.just = function(path, options, cb) {
  3215. return promisify(cb, function(cb) {
  3216. var engine = requires.just;
  3217. if (!engine) {
  3218. var JUST = require('just');
  3219. engine = requires.just = new JUST();
  3220. }
  3221. engine.configure({ useCache: options.cache });
  3222. engine.render(path, options, cb);
  3223. });
  3224. };
  3225. /**
  3226. * Just string support.
  3227. */
  3228. exports.just.render = function(str, options, cb) {
  3229. return promisify(cb, function(cb) {
  3230. var JUST = require('just');
  3231. var engine = new JUST({ root: { page: str }});
  3232. engine.render('page', options, cb);
  3233. });
  3234. };
  3235. /**
  3236. * ECT support.
  3237. */
  3238. exports.ect = function(path, options, cb) {
  3239. return promisify(cb, function(cb) {
  3240. var engine = requires.ect;
  3241. if (!engine) {
  3242. var ECT = require('ect');
  3243. engine = requires.ect = new ECT(options);
  3244. }
  3245. engine.configure({ cache: options.cache });
  3246. engine.render(path, options, cb);
  3247. });
  3248. };
  3249. /**
  3250. * ECT string support.
  3251. */
  3252. exports.ect.render = function(str, options, cb) {
  3253. return promisify(cb, function(cb) {
  3254. var ECT = require('ect');
  3255. var engine = new ECT({ root: { page: str }});
  3256. engine.render('page', options, cb);
  3257. });
  3258. };
  3259. /**
  3260. * mote support.
  3261. */
  3262. exports.mote = fromStringRenderer('mote');
  3263. /**
  3264. * mote string support.
  3265. */
  3266. exports.mote.render = function(str, options, cb) {
  3267. return promisify(cb, function(cb) {
  3268. var engine = requires.mote || (requires.mote = require('mote'));
  3269. try {
  3270. var tmpl = cache(options) || cache(options, engine.compile(str));
  3271. cb(null, tmpl(options));
  3272. } catch (err) {
  3273. cb(err);
  3274. }
  3275. });
  3276. };
  3277. /**
  3278. * Toffee support.
  3279. */
  3280. exports.toffee = function(path, options, cb) {
  3281. return promisify(cb, function(cb) {
  3282. var toffee = requires.toffee || (requires.toffee = require('toffee'));
  3283. toffee.__consolidate_engine_render(path, options, cb);
  3284. });
  3285. };
  3286. /**
  3287. * Toffee string support.
  3288. */
  3289. exports.toffee.render = function(str, options, cb) {
  3290. return promisify(cb, function(cb) {
  3291. var engine = requires.toffee || (requires.toffee = require('toffee'));
  3292. try {
  3293. engine.str_render(str, options, cb);
  3294. } catch (err) {
  3295. cb(err);
  3296. }
  3297. });
  3298. };
  3299. /**
  3300. * doT support.
  3301. */
  3302. exports.dot = fromStringRenderer('dot');
  3303. /**
  3304. * doT string support.
  3305. */
  3306. exports.dot.render = function(str, options, cb) {
  3307. return promisify(cb, function(cb) {
  3308. var engine = requires.dot || (requires.dot = require('dot'));
  3309. var extend = (requires.extend || (requires.extend = require$$2._extend));
  3310. try {
  3311. var settings = {};
  3312. settings = extend(settings, engine.templateSettings);
  3313. settings = extend(settings, options ? options.dot : {});
  3314. var tmpl = cache(options) || cache(options, engine.template(str, settings, options));
  3315. cb(null, tmpl(options));
  3316. } catch (err) {
  3317. cb(err);
  3318. }
  3319. });
  3320. };
  3321. /**
  3322. * bracket support.
  3323. */
  3324. exports.bracket = fromStringRenderer('bracket');
  3325. /**
  3326. * bracket string support.
  3327. */
  3328. exports.bracket.render = function(str, options, cb) {
  3329. return promisify(cb, function(cb) {
  3330. var engine = requires.bracket || (requires.bracket = require('bracket-template'));
  3331. try {
  3332. var tmpl = cache(options) || cache(options, engine.default.compile(str, options));
  3333. cb(null, tmpl(options));
  3334. } catch (err) {
  3335. cb(err);
  3336. }
  3337. });
  3338. };
  3339. /**
  3340. * Ractive support.
  3341. */
  3342. exports.ractive = fromStringRenderer('ractive');
  3343. /**
  3344. * Ractive string support.
  3345. */
  3346. exports.ractive.render = function(str, options, cb) {
  3347. return promisify(cb, function(cb) {
  3348. var Engine = requires.ractive || (requires.ractive = require('ractive'));
  3349. var template = cache(options) || cache(options, Engine.parse(str));
  3350. options.template = template;
  3351. if (options.data === null || options.data === undefined) {
  3352. var extend = (requires.extend || (requires.extend = require$$2._extend));
  3353. // Shallow clone the options object
  3354. options.data = extend({}, options);
  3355. // Remove consolidate-specific properties from the clone
  3356. var i;
  3357. var length;
  3358. var properties = ['template', 'filename', 'cache', 'partials'];
  3359. for (i = 0, length = properties.length; i < length; i++) {
  3360. var property = properties[i];
  3361. delete options.data[property];
  3362. }
  3363. }
  3364. try {
  3365. cb(null, new Engine(options).toHTML());
  3366. } catch (err) {
  3367. cb(err);
  3368. }
  3369. });
  3370. };
  3371. /**
  3372. * Nunjucks support.
  3373. */
  3374. exports.nunjucks = fromStringRenderer('nunjucks');
  3375. /**
  3376. * Nunjucks string support.
  3377. */
  3378. exports.nunjucks.render = function(str, options, cb) {
  3379. return promisify(cb, function(cb) {
  3380. try {
  3381. var engine = options.nunjucksEnv || requires.nunjucks || (requires.nunjucks = require('nunjucks'));
  3382. var env = engine;
  3383. // deprecated fallback support for express
  3384. // <https://github.com/tj/consolidate.js/pull/152>
  3385. // <https://github.com/tj/consolidate.js/pull/224>
  3386. if (options.settings && options.settings.views) {
  3387. env = engine.configure(options.settings.views);
  3388. } else if (options.nunjucks && options.nunjucks.configure) {
  3389. env = engine.configure.apply(engine, options.nunjucks.configure);
  3390. }
  3391. //
  3392. // because `renderString` does not initiate loaders
  3393. // we must manually create a loader for it based off
  3394. // either `options.settings.views` or `options.nunjucks` or `options.nunjucks.root`
  3395. //
  3396. // <https://github.com/mozilla/nunjucks/issues/730>
  3397. // <https://github.com/crocodilejs/node-email-templates/issues/182>
  3398. //
  3399. // so instead we simply check if we passed a custom loader
  3400. // otherwise we create a simple file based loader
  3401. if (options.loader) {
  3402. env = new engine.Environment(options.loader);
  3403. } else if (options.settings && options.settings.views) {
  3404. env = new engine.Environment(
  3405. new engine.FileSystemLoader(options.settings.views)
  3406. );
  3407. } else if (options.nunjucks && options.nunjucks.loader) {
  3408. if (typeof options.nunjucks.loader === 'string') {
  3409. env = new engine.Environment(new engine.FileSystemLoader(options.nunjucks.loader));
  3410. } else {
  3411. env = new engine.Environment(
  3412. new engine.FileSystemLoader(
  3413. options.nunjucks.loader[0],
  3414. options.nunjucks.loader[1]
  3415. )
  3416. );
  3417. }
  3418. }
  3419. env.renderString(str, options, cb);
  3420. } catch (err) {
  3421. throw cb(err);
  3422. }
  3423. });
  3424. };
  3425. /**
  3426. * HTMLing support.
  3427. */
  3428. exports.htmling = fromStringRenderer('htmling');
  3429. /**
  3430. * HTMLing string support.
  3431. */
  3432. exports.htmling.render = function(str, options, cb) {
  3433. return promisify(cb, function(cb) {
  3434. var engine = requires.htmling || (requires.htmling = require('htmling'));
  3435. try {
  3436. var tmpl = cache(options) || cache(options, engine.string(str));
  3437. cb(null, tmpl.render(options));
  3438. } catch (err) {
  3439. cb(err);
  3440. }
  3441. });
  3442. };
  3443. /**
  3444. * Rendering function
  3445. */
  3446. function requireReact(module, filename) {
  3447. var babel = requires.babel || (requires.babel = require('babel-core'));
  3448. var compiled = babel.transformFileSync(filename, { presets: [ 'react' ] }).code;
  3449. return module._compile(compiled, filename);
  3450. }
  3451. exports.requireReact = requireReact;
  3452. /**
  3453. * Converting a string into a node module.
  3454. */
  3455. function requireReactString(src, filename) {
  3456. var babel = requires.babel || (requires.babel = require('babel-core'));
  3457. if (!filename) filename = '';
  3458. var m = new module.constructor();
  3459. filename = filename || '';
  3460. // Compile Using React
  3461. var compiled = babel.transform(src, { presets: [ 'react' ] }).code;
  3462. // Compile as a module
  3463. m.paths = module.paths;
  3464. m._compile(compiled, filename);
  3465. return m.exports;
  3466. }
  3467. /**
  3468. * A naive helper to replace {{tags}} with options.tags content
  3469. */
  3470. function reactBaseTmpl(data, options) {
  3471. var exp;
  3472. var regex;
  3473. // Iterates through the keys in file object
  3474. // and interpolate / replace {{key}} with it's value
  3475. for (var k in options) {
  3476. if (options.hasOwnProperty(k)) {
  3477. exp = '{{' + k + '}}';
  3478. regex = new RegExp(exp, 'g');
  3479. if (data.match(regex)) {
  3480. data = data.replace(regex, options[k]);
  3481. }
  3482. }
  3483. }
  3484. return data;
  3485. }
  3486. /**
  3487. * Plates Support.
  3488. */
  3489. exports.plates = fromStringRenderer('plates');
  3490. /**
  3491. * Plates string support.
  3492. */
  3493. exports.plates.render = function(str, options, cb) {
  3494. return promisify(cb, function(cb) {
  3495. var engine = requires.plates || (requires.plates = require('plates'));
  3496. var map = options.map || undefined;
  3497. try {
  3498. var tmpl = engine.bind(str, options, map);
  3499. cb(null, tmpl);
  3500. } catch (err) {
  3501. cb(err);
  3502. }
  3503. });
  3504. };
  3505. /**
  3506. * The main render parser for React bsaed templates
  3507. */
  3508. function reactRenderer(type) {
  3509. if (commonjsRequire.extensions) {
  3510. // Ensure JSX is transformed on require
  3511. if (!commonjsRequire.extensions['.jsx']) {
  3512. commonjsRequire.extensions['.jsx'] = requireReact;
  3513. }
  3514. // Supporting .react extension as well as test cases
  3515. // Using .react extension is not recommended.
  3516. if (!commonjsRequire.extensions['.react']) {
  3517. commonjsRequire.extensions['.react'] = requireReact;
  3518. }
  3519. }
  3520. // Return rendering fx
  3521. return function(str, options, cb) {
  3522. return promisify(cb, function(cb) {
  3523. // React Import
  3524. var ReactDOM = requires.ReactDOM || (requires.ReactDOM = require('react-dom/server'));
  3525. var react = requires.react || (requires.react = require('react'));
  3526. // Assign HTML Base
  3527. var base = options.base;
  3528. delete options.base;
  3529. var enableCache = options.cache;
  3530. delete options.cache;
  3531. var isNonStatic = options.isNonStatic;
  3532. delete options.isNonStatic;
  3533. // Start Conversion
  3534. try {
  3535. var Code;
  3536. var Factory;
  3537. var baseStr;
  3538. var content;
  3539. var parsed;
  3540. if (!cache(options)) {
  3541. // Parsing
  3542. if (type === 'path') {
  3543. var path = resolve(str);
  3544. delete require.cache[path];
  3545. Code = commonjsRequire(path);
  3546. } else {
  3547. Code = requireReactString(str);
  3548. }
  3549. Factory = cache(options, react.createFactory(Code));
  3550. } else {
  3551. Factory = cache(options);
  3552. }
  3553. parsed = new Factory(options);
  3554. content = (isNonStatic) ? ReactDOM.renderToString(parsed) : ReactDOM.renderToStaticMarkup(parsed);
  3555. if (base) {
  3556. baseStr = readCache[str] || fs.readFileSync(resolve(base), 'utf8');
  3557. if (enableCache) {
  3558. readCache[str] = baseStr;
  3559. }
  3560. options.content = content;
  3561. content = reactBaseTmpl(baseStr, options);
  3562. }
  3563. cb(null, content);
  3564. } catch (err) {
  3565. cb(err);
  3566. }
  3567. });
  3568. };
  3569. }
  3570. /**
  3571. * React JS Support
  3572. */
  3573. exports.react = reactRenderer('path');
  3574. /**
  3575. * React JS string support.
  3576. */
  3577. exports.react.render = reactRenderer('string');
  3578. /**
  3579. * ARC-templates support.
  3580. */
  3581. exports['arc-templates'] = fromStringRenderer('arc-templates');
  3582. /**
  3583. * ARC-templates string support.
  3584. */
  3585. exports['arc-templates'].render = function(str, options, cb) {
  3586. var readFileWithOptions = util.promisify(read);
  3587. var consolidateFileSystem = {};
  3588. consolidateFileSystem.readFile = function(path) {
  3589. return readFileWithOptions(path, options);
  3590. };
  3591. return promisify(cb, function(cb) {
  3592. try {
  3593. var engine = requires['arc-templates'];
  3594. if (!engine) {
  3595. var Engine = require('arc-templates/dist/es5');
  3596. engine = requires['arc-templates'] = new Engine({ filesystem: consolidateFileSystem });
  3597. }
  3598. var compiler = cache(options) || cache(options, engine.compileString(str, options.filename));
  3599. compiler.then(function(func) { return func(options); })
  3600. .then(function(result) { cb(null, result.content); })
  3601. .catch(cb);
  3602. } catch (err) {
  3603. cb(err);
  3604. }
  3605. });
  3606. };
  3607. /**
  3608. * Vash support
  3609. */
  3610. exports.vash = fromStringRenderer('vash');
  3611. /**
  3612. * Vash string support
  3613. */
  3614. exports.vash.render = function(str, options, cb) {
  3615. return promisify(cb, function(cb) {
  3616. var engine = requires.vash || (requires.vash = require('vash'));
  3617. try {
  3618. // helper system : https://github.com/kirbysayshi/vash#helper-system
  3619. if (options.helpers) {
  3620. for (var key in options.helpers) {
  3621. if (!options.helpers.hasOwnProperty(key) || typeof options.helpers[key] !== 'function') {
  3622. continue;
  3623. }
  3624. engine.helpers[key] = options.helpers[key];
  3625. }
  3626. }
  3627. var tmpl = cache(options) || cache(options, engine.compile(str, options));
  3628. tmpl(options, function sealLayout(err, ctx) {
  3629. if (err) cb(err);
  3630. ctx.finishLayout();
  3631. cb(null, ctx.toString().replace(/\n$/, ''));
  3632. });
  3633. } catch (err) {
  3634. cb(err);
  3635. }
  3636. });
  3637. };
  3638. /**
  3639. * Slm support.
  3640. */
  3641. exports.slm = fromStringRenderer('slm');
  3642. /**
  3643. * Slm string support.
  3644. */
  3645. exports.slm.render = function(str, options, cb) {
  3646. return promisify(cb, function(cb) {
  3647. var engine = requires.slm || (requires.slm = require('slm'));
  3648. try {
  3649. var tmpl = cache(options) || cache(options, engine.compile(str, options));
  3650. cb(null, tmpl(options));
  3651. } catch (err) {
  3652. cb(err);
  3653. }
  3654. });
  3655. };
  3656. /**
  3657. * Marko support.
  3658. */
  3659. exports.marko = function(path, options, cb) {
  3660. return promisify(cb, function(cb) {
  3661. var engine = requires.marko || (requires.marko = require('marko'));
  3662. options.writeToDisk = !!options.cache;
  3663. try {
  3664. var tmpl = cache(options) || cache(options, engine.load(path, options));
  3665. tmpl.renderToString(options, cb);
  3666. } catch (err) {
  3667. cb(err);
  3668. }
  3669. });
  3670. };
  3671. /**
  3672. * Marko string support.
  3673. */
  3674. exports.marko.render = function(str, options, cb) {
  3675. return promisify(cb, function(cb) {
  3676. var engine = requires.marko || (requires.marko = require('marko'));
  3677. options.writeToDisk = !!options.cache;
  3678. options.filename = options.filename || 'string.marko';
  3679. try {
  3680. var tmpl = cache(options) || cache(options, engine.load(options.filename, str, options));
  3681. tmpl.renderToString(options, cb);
  3682. } catch (err) {
  3683. cb(err);
  3684. }
  3685. });
  3686. };
  3687. /**
  3688. * Teacup support.
  3689. */
  3690. exports.teacup = function(path, options, cb) {
  3691. return promisify(cb, function(cb) {
  3692. var engine = requires.teacup || (requires.teacup = require('teacup/lib/express'));
  3693. commonjsRequire.extensions['.teacup'] = commonjsRequire.extensions['.coffee'];
  3694. if (path[0] !== '/') {
  3695. path = join(process.cwd(), path);
  3696. }
  3697. if (!options.cache) {
  3698. var callback = cb;
  3699. cb = function() {
  3700. delete require.cache[path];
  3701. callback.apply(this, arguments);
  3702. };
  3703. }
  3704. engine.renderFile(path, options, cb);
  3705. });
  3706. };
  3707. /**
  3708. * Teacup string support.
  3709. */
  3710. exports.teacup.render = function(str, options, cb) {
  3711. var coffee = require('coffee-script');
  3712. var vm = require('vm');
  3713. var sandbox = {
  3714. module: {exports: {}},
  3715. require: commonjsRequire
  3716. };
  3717. return promisify(cb, function(cb) {
  3718. vm.runInNewContext(coffee.compile(str), sandbox);
  3719. var tmpl = sandbox.module.exports;
  3720. cb(null, tmpl(options));
  3721. });
  3722. };
  3723. /**
  3724. * Squirrelly support.
  3725. */
  3726. exports.squirrelly = fromStringRenderer('squirrelly');
  3727. /**
  3728. * Squirrelly string support.
  3729. */
  3730. exports.squirrelly.render = function(str, options, cb) {
  3731. return promisify(cb, function(cb) {
  3732. var engine = requires.squirrelly || (requires.squirrelly = require('squirrelly'));
  3733. try {
  3734. for (var partial in options.partials) {
  3735. engine.definePartial(partial, options.partials[partial]);
  3736. }
  3737. for (var helper in options.helpers) {
  3738. engine.defineHelper(helper, options.helpers[helper]);
  3739. }
  3740. var tmpl = cache(options) || cache(options, engine.Compile(str, options));
  3741. cb(null, tmpl(options, engine));
  3742. } catch (err) {
  3743. cb(err);
  3744. }
  3745. });
  3746. };
  3747. /**
  3748. * Twing support.
  3749. */
  3750. exports.twing = fromStringRenderer('twing');
  3751. /**
  3752. * Twing string support.
  3753. */
  3754. exports.twing.render = function(str, options, cb) {
  3755. return promisify(cb, function(cb) {
  3756. var engine = requires.twing || (requires.twing = require('twing'));
  3757. try {
  3758. new engine.TwingEnvironment(new engine.TwingLoaderNull()).createTemplate(str).then((twingTemplate) => {
  3759. twingTemplate.render(options).then((rendTmpl) => {
  3760. var tmpl = cache(options) || cache(options, rendTmpl);
  3761. cb(null, tmpl);
  3762. });
  3763. });
  3764. } catch (err) {
  3765. cb(err);
  3766. }
  3767. });
  3768. };
  3769. /**
  3770. * expose the instance of the engine
  3771. */
  3772. exports.requires = requires;
  3773. } (consolidate$2, consolidate$2.exports));
  3774. return consolidate$2.exports;
  3775. }
  3776. var consolidate$1;
  3777. var hasRequiredConsolidate;
  3778. function requireConsolidate () {
  3779. if (hasRequiredConsolidate) return consolidate$1;
  3780. hasRequiredConsolidate = 1;
  3781. consolidate$1 = /*@__PURE__*/ requireConsolidate$1();
  3782. return consolidate$1;
  3783. }
  3784. var consolidateExports = /*@__PURE__*/ requireConsolidate();
  3785. var consolidate = /*@__PURE__*/getDefaultExportFromCjs(consolidateExports);
  3786. const hasWarned = {};
  3787. function warnOnce(msg) {
  3788. const isNodeProd = typeof process !== "undefined" && process.env.NODE_ENV === "production";
  3789. if (!isNodeProd && true && !hasWarned[msg]) {
  3790. hasWarned[msg] = true;
  3791. warn(msg);
  3792. }
  3793. }
  3794. function warn(msg) {
  3795. console.warn(
  3796. `\x1B[1m\x1B[33m[@vue/compiler-sfc]\x1B[0m\x1B[33m ${msg}\x1B[0m
  3797. `
  3798. );
  3799. }
  3800. function preprocess$1({ source, filename, preprocessOptions }, preprocessor) {
  3801. let res = "";
  3802. let err = null;
  3803. preprocessor.render(
  3804. source,
  3805. { filename, ...preprocessOptions },
  3806. (_err, _res) => {
  3807. if (_err) err = _err;
  3808. res = _res;
  3809. }
  3810. );
  3811. if (err) throw err;
  3812. return res;
  3813. }
  3814. function compileTemplate(options) {
  3815. const { preprocessLang, preprocessCustomRequire } = options;
  3816. const preprocessor = preprocessLang ? preprocessCustomRequire ? preprocessCustomRequire(preprocessLang) : consolidate[preprocessLang] : false;
  3817. if (preprocessor) {
  3818. try {
  3819. return doCompileTemplate({
  3820. ...options,
  3821. source: preprocess$1(options, preprocessor),
  3822. ast: void 0
  3823. // invalidate AST if template goes through preprocessor
  3824. });
  3825. } catch (e) {
  3826. return {
  3827. code: `export default function render() {}`,
  3828. source: options.source,
  3829. tips: [],
  3830. errors: [e]
  3831. };
  3832. }
  3833. } else if (preprocessLang) {
  3834. return {
  3835. code: `export default function render() {}`,
  3836. source: options.source,
  3837. tips: [
  3838. `Component ${options.filename} uses lang ${preprocessLang} for template. Please install the language preprocessor.`
  3839. ],
  3840. errors: [
  3841. `Component ${options.filename} uses lang ${preprocessLang} for template, however it is not installed.`
  3842. ]
  3843. };
  3844. } else {
  3845. return doCompileTemplate(options);
  3846. }
  3847. }
  3848. function doCompileTemplate({
  3849. filename,
  3850. id,
  3851. scoped,
  3852. slotted,
  3853. inMap,
  3854. source,
  3855. ast: inAST,
  3856. ssr = false,
  3857. ssrCssVars,
  3858. isProd = false,
  3859. compiler,
  3860. compilerOptions = {},
  3861. transformAssetUrls
  3862. }) {
  3863. const errors = [];
  3864. const warnings = [];
  3865. let nodeTransforms = [];
  3866. if (shared.isObject(transformAssetUrls)) {
  3867. const assetOptions = normalizeOptions(transformAssetUrls);
  3868. nodeTransforms = [
  3869. createAssetUrlTransformWithOptions(assetOptions),
  3870. createSrcsetTransformWithOptions(assetOptions)
  3871. ];
  3872. } else if (transformAssetUrls !== false) {
  3873. nodeTransforms = [transformAssetUrl, transformSrcset];
  3874. }
  3875. if (ssr && !ssrCssVars) {
  3876. warnOnce(
  3877. `compileTemplate is called with \`ssr: true\` but no corresponding \`cssVars\` option.`
  3878. );
  3879. }
  3880. if (!id) {
  3881. warnOnce(`compileTemplate now requires the \`id\` option.`);
  3882. id = "";
  3883. }
  3884. const shortId = id.replace(/^data-v-/, "");
  3885. const longId = `data-v-${shortId}`;
  3886. const defaultCompiler = ssr ? CompilerSSR__namespace : CompilerDOM__namespace;
  3887. compiler = compiler || defaultCompiler;
  3888. if (compiler !== defaultCompiler) {
  3889. inAST = void 0;
  3890. }
  3891. if (inAST == null ? void 0 : inAST.transformed) {
  3892. const newAST = (ssr ? CompilerDOM__namespace : compiler).parse(inAST.source, {
  3893. prefixIdentifiers: true,
  3894. ...compilerOptions,
  3895. parseMode: "sfc",
  3896. onError: (e) => errors.push(e)
  3897. });
  3898. const template = newAST.children.find(
  3899. (node) => node.type === 1 && node.tag === "template"
  3900. );
  3901. inAST = compilerCore.createRoot(template.children, inAST.source);
  3902. }
  3903. let { code, ast, preamble, map } = compiler.compile(inAST || source, {
  3904. mode: "module",
  3905. prefixIdentifiers: true,
  3906. hoistStatic: true,
  3907. cacheHandlers: true,
  3908. ssrCssVars: ssr && ssrCssVars && ssrCssVars.length ? genCssVarsFromList(ssrCssVars, shortId, isProd, true) : "",
  3909. scopeId: scoped ? longId : void 0,
  3910. slotted,
  3911. sourceMap: true,
  3912. ...compilerOptions,
  3913. hmr: !isProd,
  3914. nodeTransforms: nodeTransforms.concat(compilerOptions.nodeTransforms || []),
  3915. filename,
  3916. onError: (e) => errors.push(e),
  3917. onWarn: (w) => warnings.push(w)
  3918. });
  3919. if (inMap && !inAST) {
  3920. if (map) {
  3921. map = mapLines(inMap, map);
  3922. }
  3923. if (errors.length) {
  3924. patchErrors(errors, source, inMap);
  3925. }
  3926. }
  3927. const tips = warnings.map((w) => {
  3928. let msg = w.message;
  3929. if (w.loc) {
  3930. msg += `
  3931. ${shared.generateCodeFrame(
  3932. (inAST == null ? void 0 : inAST.source) || source,
  3933. w.loc.start.offset,
  3934. w.loc.end.offset
  3935. )}`;
  3936. }
  3937. return msg;
  3938. });
  3939. return { code, ast, preamble, source, errors, tips, map };
  3940. }
  3941. function mapLines(oldMap, newMap) {
  3942. if (!oldMap) return newMap;
  3943. if (!newMap) return oldMap;
  3944. const oldMapConsumer = new sourceMapJs.SourceMapConsumer(oldMap);
  3945. const newMapConsumer = new sourceMapJs.SourceMapConsumer(newMap);
  3946. const mergedMapGenerator = new sourceMapJs.SourceMapGenerator();
  3947. newMapConsumer.eachMapping((m) => {
  3948. if (m.originalLine == null) {
  3949. return;
  3950. }
  3951. const origPosInOldMap = oldMapConsumer.originalPositionFor({
  3952. line: m.originalLine,
  3953. column: m.originalColumn
  3954. });
  3955. if (origPosInOldMap.source == null) {
  3956. return;
  3957. }
  3958. mergedMapGenerator.addMapping({
  3959. generated: {
  3960. line: m.generatedLine,
  3961. column: m.generatedColumn
  3962. },
  3963. original: {
  3964. line: origPosInOldMap.line,
  3965. // map line
  3966. // use current column, since the oldMap produced by @vue/compiler-sfc
  3967. // does not
  3968. column: m.originalColumn
  3969. },
  3970. source: origPosInOldMap.source,
  3971. name: origPosInOldMap.name
  3972. });
  3973. });
  3974. const generator = mergedMapGenerator;
  3975. oldMapConsumer.sources.forEach((sourceFile) => {
  3976. generator._sources.add(sourceFile);
  3977. const sourceContent = oldMapConsumer.sourceContentFor(sourceFile);
  3978. if (sourceContent != null) {
  3979. mergedMapGenerator.setSourceContent(sourceFile, sourceContent);
  3980. }
  3981. });
  3982. generator._sourceRoot = oldMap.sourceRoot;
  3983. generator._file = oldMap.file;
  3984. return generator.toJSON();
  3985. }
  3986. function patchErrors(errors, source, inMap) {
  3987. const originalSource = inMap.sourcesContent[0];
  3988. const offset = originalSource.indexOf(source);
  3989. const lineOffset = originalSource.slice(0, offset).split(/\r?\n/).length - 1;
  3990. errors.forEach((err) => {
  3991. if (err.loc) {
  3992. err.loc.start.line += lineOffset;
  3993. err.loc.start.offset += offset;
  3994. if (err.loc.end !== err.loc.start) {
  3995. err.loc.end.line += lineOffset;
  3996. err.loc.end.offset += offset;
  3997. }
  3998. }
  3999. });
  4000. }
  4001. const trimPlugin = () => {
  4002. return {
  4003. postcssPlugin: "vue-sfc-trim",
  4004. Once(root) {
  4005. root.walk(({ type, raws }) => {
  4006. if (type === "rule" || type === "atrule") {
  4007. if (raws.before) raws.before = "\n";
  4008. if ("after" in raws && raws.after) raws.after = "\n";
  4009. }
  4010. });
  4011. }
  4012. };
  4013. };
  4014. trimPlugin.postcss = true;
  4015. var dist = {exports: {}};
  4016. var processor = {exports: {}};
  4017. var parser = {exports: {}};
  4018. var root = {exports: {}};
  4019. var container = {exports: {}};
  4020. var node$1 = {exports: {}};
  4021. var util$1 = {};
  4022. var unesc = {exports: {}};
  4023. var hasRequiredUnesc;
  4024. function requireUnesc () {
  4025. if (hasRequiredUnesc) return unesc.exports;
  4026. hasRequiredUnesc = 1;
  4027. (function (module, exports) {
  4028. exports.__esModule = true;
  4029. exports["default"] = unesc;
  4030. // Many thanks for this post which made this migration much easier.
  4031. // https://mathiasbynens.be/notes/css-escapes
  4032. /**
  4033. *
  4034. * @param {string} str
  4035. * @returns {[string, number]|undefined}
  4036. */
  4037. function gobbleHex(str) {
  4038. var lower = str.toLowerCase();
  4039. var hex = '';
  4040. var spaceTerminated = false;
  4041. for (var i = 0; i < 6 && lower[i] !== undefined; i++) {
  4042. var code = lower.charCodeAt(i);
  4043. // check to see if we are dealing with a valid hex char [a-f|0-9]
  4044. var valid = code >= 97 && code <= 102 || code >= 48 && code <= 57;
  4045. // https://drafts.csswg.org/css-syntax/#consume-escaped-code-point
  4046. spaceTerminated = code === 32;
  4047. if (!valid) {
  4048. break;
  4049. }
  4050. hex += lower[i];
  4051. }
  4052. if (hex.length === 0) {
  4053. return undefined;
  4054. }
  4055. var codePoint = parseInt(hex, 16);
  4056. var isSurrogate = codePoint >= 0xD800 && codePoint <= 0xDFFF;
  4057. // Add special case for
  4058. // "If this number is zero, or is for a surrogate, or is greater than the maximum allowed code point"
  4059. // https://drafts.csswg.org/css-syntax/#maximum-allowed-code-point
  4060. if (isSurrogate || codePoint === 0x0000 || codePoint > 0x10FFFF) {
  4061. return ["\uFFFD", hex.length + (spaceTerminated ? 1 : 0)];
  4062. }
  4063. return [String.fromCodePoint(codePoint), hex.length + (spaceTerminated ? 1 : 0)];
  4064. }
  4065. var CONTAINS_ESCAPE = /\\/;
  4066. function unesc(str) {
  4067. var needToProcess = CONTAINS_ESCAPE.test(str);
  4068. if (!needToProcess) {
  4069. return str;
  4070. }
  4071. var ret = "";
  4072. for (var i = 0; i < str.length; i++) {
  4073. if (str[i] === "\\") {
  4074. var gobbled = gobbleHex(str.slice(i + 1, i + 7));
  4075. if (gobbled !== undefined) {
  4076. ret += gobbled[0];
  4077. i += gobbled[1];
  4078. continue;
  4079. }
  4080. // Retain a pair of \\ if double escaped `\\\\`
  4081. // https://github.com/postcss/postcss-selector-parser/commit/268c9a7656fb53f543dc620aa5b73a30ec3ff20e
  4082. if (str[i + 1] === "\\") {
  4083. ret += "\\";
  4084. i++;
  4085. continue;
  4086. }
  4087. // if \\ is at the end of the string retain it
  4088. // https://github.com/postcss/postcss-selector-parser/commit/01a6b346e3612ce1ab20219acc26abdc259ccefb
  4089. if (str.length === i + 1) {
  4090. ret += str[i];
  4091. }
  4092. continue;
  4093. }
  4094. ret += str[i];
  4095. }
  4096. return ret;
  4097. }
  4098. module.exports = exports.default;
  4099. } (unesc, unesc.exports));
  4100. return unesc.exports;
  4101. }
  4102. var getProp = {exports: {}};
  4103. var hasRequiredGetProp;
  4104. function requireGetProp () {
  4105. if (hasRequiredGetProp) return getProp.exports;
  4106. hasRequiredGetProp = 1;
  4107. (function (module, exports) {
  4108. exports.__esModule = true;
  4109. exports["default"] = getProp;
  4110. function getProp(obj) {
  4111. for (var _len = arguments.length, props = new Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++) {
  4112. props[_key - 1] = arguments[_key];
  4113. }
  4114. while (props.length > 0) {
  4115. var prop = props.shift();
  4116. if (!obj[prop]) {
  4117. return undefined;
  4118. }
  4119. obj = obj[prop];
  4120. }
  4121. return obj;
  4122. }
  4123. module.exports = exports.default;
  4124. } (getProp, getProp.exports));
  4125. return getProp.exports;
  4126. }
  4127. var ensureObject = {exports: {}};
  4128. var hasRequiredEnsureObject;
  4129. function requireEnsureObject () {
  4130. if (hasRequiredEnsureObject) return ensureObject.exports;
  4131. hasRequiredEnsureObject = 1;
  4132. (function (module, exports) {
  4133. exports.__esModule = true;
  4134. exports["default"] = ensureObject;
  4135. function ensureObject(obj) {
  4136. for (var _len = arguments.length, props = new Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++) {
  4137. props[_key - 1] = arguments[_key];
  4138. }
  4139. while (props.length > 0) {
  4140. var prop = props.shift();
  4141. if (!obj[prop]) {
  4142. obj[prop] = {};
  4143. }
  4144. obj = obj[prop];
  4145. }
  4146. }
  4147. module.exports = exports.default;
  4148. } (ensureObject, ensureObject.exports));
  4149. return ensureObject.exports;
  4150. }
  4151. var stripComments = {exports: {}};
  4152. var hasRequiredStripComments;
  4153. function requireStripComments () {
  4154. if (hasRequiredStripComments) return stripComments.exports;
  4155. hasRequiredStripComments = 1;
  4156. (function (module, exports) {
  4157. exports.__esModule = true;
  4158. exports["default"] = stripComments;
  4159. function stripComments(str) {
  4160. var s = "";
  4161. var commentStart = str.indexOf("/*");
  4162. var lastEnd = 0;
  4163. while (commentStart >= 0) {
  4164. s = s + str.slice(lastEnd, commentStart);
  4165. var commentEnd = str.indexOf("*/", commentStart + 2);
  4166. if (commentEnd < 0) {
  4167. return s;
  4168. }
  4169. lastEnd = commentEnd + 2;
  4170. commentStart = str.indexOf("/*", lastEnd);
  4171. }
  4172. s = s + str.slice(lastEnd);
  4173. return s;
  4174. }
  4175. module.exports = exports.default;
  4176. } (stripComments, stripComments.exports));
  4177. return stripComments.exports;
  4178. }
  4179. var hasRequiredUtil$1;
  4180. function requireUtil$1 () {
  4181. if (hasRequiredUtil$1) return util$1;
  4182. hasRequiredUtil$1 = 1;
  4183. util$1.__esModule = true;
  4184. util$1.unesc = util$1.stripComments = util$1.getProp = util$1.ensureObject = void 0;
  4185. var _unesc = _interopRequireDefault(/*@__PURE__*/ requireUnesc());
  4186. util$1.unesc = _unesc["default"];
  4187. var _getProp = _interopRequireDefault(/*@__PURE__*/ requireGetProp());
  4188. util$1.getProp = _getProp["default"];
  4189. var _ensureObject = _interopRequireDefault(/*@__PURE__*/ requireEnsureObject());
  4190. util$1.ensureObject = _ensureObject["default"];
  4191. var _stripComments = _interopRequireDefault(/*@__PURE__*/ requireStripComments());
  4192. util$1.stripComments = _stripComments["default"];
  4193. function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; }
  4194. return util$1;
  4195. }
  4196. var hasRequiredNode$1;
  4197. function requireNode$1 () {
  4198. if (hasRequiredNode$1) return node$1.exports;
  4199. hasRequiredNode$1 = 1;
  4200. (function (module, exports) {
  4201. exports.__esModule = true;
  4202. exports["default"] = void 0;
  4203. var _util = /*@__PURE__*/ requireUtil$1();
  4204. 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); } }
  4205. function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); Object.defineProperty(Constructor, "prototype", { writable: false }); return Constructor; }
  4206. var cloneNode = function cloneNode(obj, parent) {
  4207. if (typeof obj !== 'object' || obj === null) {
  4208. return obj;
  4209. }
  4210. var cloned = new obj.constructor();
  4211. for (var i in obj) {
  4212. if (!obj.hasOwnProperty(i)) {
  4213. continue;
  4214. }
  4215. var value = obj[i];
  4216. var type = typeof value;
  4217. if (i === 'parent' && type === 'object') {
  4218. if (parent) {
  4219. cloned[i] = parent;
  4220. }
  4221. } else if (value instanceof Array) {
  4222. cloned[i] = value.map(function (j) {
  4223. return cloneNode(j, cloned);
  4224. });
  4225. } else {
  4226. cloned[i] = cloneNode(value, cloned);
  4227. }
  4228. }
  4229. return cloned;
  4230. };
  4231. var Node = /*#__PURE__*/function () {
  4232. function Node(opts) {
  4233. if (opts === void 0) {
  4234. opts = {};
  4235. }
  4236. Object.assign(this, opts);
  4237. this.spaces = this.spaces || {};
  4238. this.spaces.before = this.spaces.before || '';
  4239. this.spaces.after = this.spaces.after || '';
  4240. }
  4241. var _proto = Node.prototype;
  4242. _proto.remove = function remove() {
  4243. if (this.parent) {
  4244. this.parent.removeChild(this);
  4245. }
  4246. this.parent = undefined;
  4247. return this;
  4248. };
  4249. _proto.replaceWith = function replaceWith() {
  4250. if (this.parent) {
  4251. for (var index in arguments) {
  4252. this.parent.insertBefore(this, arguments[index]);
  4253. }
  4254. this.remove();
  4255. }
  4256. return this;
  4257. };
  4258. _proto.next = function next() {
  4259. return this.parent.at(this.parent.index(this) + 1);
  4260. };
  4261. _proto.prev = function prev() {
  4262. return this.parent.at(this.parent.index(this) - 1);
  4263. };
  4264. _proto.clone = function clone(overrides) {
  4265. if (overrides === void 0) {
  4266. overrides = {};
  4267. }
  4268. var cloned = cloneNode(this);
  4269. for (var name in overrides) {
  4270. cloned[name] = overrides[name];
  4271. }
  4272. return cloned;
  4273. }
  4274. /**
  4275. * Some non-standard syntax doesn't follow normal escaping rules for css.
  4276. * This allows non standard syntax to be appended to an existing property
  4277. * by specifying the escaped value. By specifying the escaped value,
  4278. * illegal characters are allowed to be directly inserted into css output.
  4279. * @param {string} name the property to set
  4280. * @param {any} value the unescaped value of the property
  4281. * @param {string} valueEscaped optional. the escaped value of the property.
  4282. */;
  4283. _proto.appendToPropertyAndEscape = function appendToPropertyAndEscape(name, value, valueEscaped) {
  4284. if (!this.raws) {
  4285. this.raws = {};
  4286. }
  4287. var originalValue = this[name];
  4288. var originalEscaped = this.raws[name];
  4289. this[name] = originalValue + value; // this may trigger a setter that updates raws, so it has to be set first.
  4290. if (originalEscaped || valueEscaped !== value) {
  4291. this.raws[name] = (originalEscaped || originalValue) + valueEscaped;
  4292. } else {
  4293. delete this.raws[name]; // delete any escaped value that was created by the setter.
  4294. }
  4295. }
  4296. /**
  4297. * Some non-standard syntax doesn't follow normal escaping rules for css.
  4298. * This allows the escaped value to be specified directly, allowing illegal
  4299. * characters to be directly inserted into css output.
  4300. * @param {string} name the property to set
  4301. * @param {any} value the unescaped value of the property
  4302. * @param {string} valueEscaped the escaped value of the property.
  4303. */;
  4304. _proto.setPropertyAndEscape = function setPropertyAndEscape(name, value, valueEscaped) {
  4305. if (!this.raws) {
  4306. this.raws = {};
  4307. }
  4308. this[name] = value; // this may trigger a setter that updates raws, so it has to be set first.
  4309. this.raws[name] = valueEscaped;
  4310. }
  4311. /**
  4312. * When you want a value to passed through to CSS directly. This method
  4313. * deletes the corresponding raw value causing the stringifier to fallback
  4314. * to the unescaped value.
  4315. * @param {string} name the property to set.
  4316. * @param {any} value The value that is both escaped and unescaped.
  4317. */;
  4318. _proto.setPropertyWithoutEscape = function setPropertyWithoutEscape(name, value) {
  4319. this[name] = value; // this may trigger a setter that updates raws, so it has to be set first.
  4320. if (this.raws) {
  4321. delete this.raws[name];
  4322. }
  4323. }
  4324. /**
  4325. *
  4326. * @param {number} line The number (starting with 1)
  4327. * @param {number} column The column number (starting with 1)
  4328. */;
  4329. _proto.isAtPosition = function isAtPosition(line, column) {
  4330. if (this.source && this.source.start && this.source.end) {
  4331. if (this.source.start.line > line) {
  4332. return false;
  4333. }
  4334. if (this.source.end.line < line) {
  4335. return false;
  4336. }
  4337. if (this.source.start.line === line && this.source.start.column > column) {
  4338. return false;
  4339. }
  4340. if (this.source.end.line === line && this.source.end.column < column) {
  4341. return false;
  4342. }
  4343. return true;
  4344. }
  4345. return undefined;
  4346. };
  4347. _proto.stringifyProperty = function stringifyProperty(name) {
  4348. return this.raws && this.raws[name] || this[name];
  4349. };
  4350. _proto.valueToString = function valueToString() {
  4351. return String(this.stringifyProperty("value"));
  4352. };
  4353. _proto.toString = function toString() {
  4354. return [this.rawSpaceBefore, this.valueToString(), this.rawSpaceAfter].join('');
  4355. };
  4356. _createClass(Node, [{
  4357. key: "rawSpaceBefore",
  4358. get: function get() {
  4359. var rawSpace = this.raws && this.raws.spaces && this.raws.spaces.before;
  4360. if (rawSpace === undefined) {
  4361. rawSpace = this.spaces && this.spaces.before;
  4362. }
  4363. return rawSpace || "";
  4364. },
  4365. set: function set(raw) {
  4366. (0, _util.ensureObject)(this, "raws", "spaces");
  4367. this.raws.spaces.before = raw;
  4368. }
  4369. }, {
  4370. key: "rawSpaceAfter",
  4371. get: function get() {
  4372. var rawSpace = this.raws && this.raws.spaces && this.raws.spaces.after;
  4373. if (rawSpace === undefined) {
  4374. rawSpace = this.spaces.after;
  4375. }
  4376. return rawSpace || "";
  4377. },
  4378. set: function set(raw) {
  4379. (0, _util.ensureObject)(this, "raws", "spaces");
  4380. this.raws.spaces.after = raw;
  4381. }
  4382. }]);
  4383. return Node;
  4384. }();
  4385. exports["default"] = Node;
  4386. module.exports = exports.default;
  4387. } (node$1, node$1.exports));
  4388. return node$1.exports;
  4389. }
  4390. var types$1 = {};
  4391. var hasRequiredTypes;
  4392. function requireTypes () {
  4393. if (hasRequiredTypes) return types$1;
  4394. hasRequiredTypes = 1;
  4395. types$1.__esModule = true;
  4396. 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;
  4397. var TAG = 'tag';
  4398. types$1.TAG = TAG;
  4399. var STRING = 'string';
  4400. types$1.STRING = STRING;
  4401. var SELECTOR = 'selector';
  4402. types$1.SELECTOR = SELECTOR;
  4403. var ROOT = 'root';
  4404. types$1.ROOT = ROOT;
  4405. var PSEUDO = 'pseudo';
  4406. types$1.PSEUDO = PSEUDO;
  4407. var NESTING = 'nesting';
  4408. types$1.NESTING = NESTING;
  4409. var ID = 'id';
  4410. types$1.ID = ID;
  4411. var COMMENT = 'comment';
  4412. types$1.COMMENT = COMMENT;
  4413. var COMBINATOR = 'combinator';
  4414. types$1.COMBINATOR = COMBINATOR;
  4415. var CLASS = 'class';
  4416. types$1.CLASS = CLASS;
  4417. var ATTRIBUTE = 'attribute';
  4418. types$1.ATTRIBUTE = ATTRIBUTE;
  4419. var UNIVERSAL = 'universal';
  4420. types$1.UNIVERSAL = UNIVERSAL;
  4421. return types$1;
  4422. }
  4423. var hasRequiredContainer;
  4424. function requireContainer () {
  4425. if (hasRequiredContainer) return container.exports;
  4426. hasRequiredContainer = 1;
  4427. (function (module, exports) {
  4428. exports.__esModule = true;
  4429. exports["default"] = void 0;
  4430. var _node = _interopRequireDefault(/*@__PURE__*/ requireNode$1());
  4431. var types = _interopRequireWildcard(/*@__PURE__*/ requireTypes());
  4432. 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); }
  4433. 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; }
  4434. function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; }
  4435. 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."); }
  4436. 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); }
  4437. 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; }
  4438. 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); } }
  4439. function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); Object.defineProperty(Constructor, "prototype", { writable: false }); return Constructor; }
  4440. function _inheritsLoose(subClass, superClass) { subClass.prototype = Object.create(superClass.prototype); subClass.prototype.constructor = subClass; _setPrototypeOf(subClass, superClass); }
  4441. function _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf ? Object.setPrototypeOf.bind() : function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); }
  4442. var Container = /*#__PURE__*/function (_Node) {
  4443. _inheritsLoose(Container, _Node);
  4444. function Container(opts) {
  4445. var _this;
  4446. _this = _Node.call(this, opts) || this;
  4447. if (!_this.nodes) {
  4448. _this.nodes = [];
  4449. }
  4450. return _this;
  4451. }
  4452. var _proto = Container.prototype;
  4453. _proto.append = function append(selector) {
  4454. selector.parent = this;
  4455. this.nodes.push(selector);
  4456. return this;
  4457. };
  4458. _proto.prepend = function prepend(selector) {
  4459. selector.parent = this;
  4460. this.nodes.unshift(selector);
  4461. return this;
  4462. };
  4463. _proto.at = function at(index) {
  4464. return this.nodes[index];
  4465. };
  4466. _proto.index = function index(child) {
  4467. if (typeof child === 'number') {
  4468. return child;
  4469. }
  4470. return this.nodes.indexOf(child);
  4471. };
  4472. _proto.removeChild = function removeChild(child) {
  4473. child = this.index(child);
  4474. this.at(child).parent = undefined;
  4475. this.nodes.splice(child, 1);
  4476. var index;
  4477. for (var id in this.indexes) {
  4478. index = this.indexes[id];
  4479. if (index >= child) {
  4480. this.indexes[id] = index - 1;
  4481. }
  4482. }
  4483. return this;
  4484. };
  4485. _proto.removeAll = function removeAll() {
  4486. for (var _iterator = _createForOfIteratorHelperLoose(this.nodes), _step; !(_step = _iterator()).done;) {
  4487. var node = _step.value;
  4488. node.parent = undefined;
  4489. }
  4490. this.nodes = [];
  4491. return this;
  4492. };
  4493. _proto.empty = function empty() {
  4494. return this.removeAll();
  4495. };
  4496. _proto.insertAfter = function insertAfter(oldNode, newNode) {
  4497. newNode.parent = this;
  4498. var oldIndex = this.index(oldNode);
  4499. this.nodes.splice(oldIndex + 1, 0, newNode);
  4500. newNode.parent = this;
  4501. var index;
  4502. for (var id in this.indexes) {
  4503. index = this.indexes[id];
  4504. if (oldIndex <= index) {
  4505. this.indexes[id] = index + 1;
  4506. }
  4507. }
  4508. return this;
  4509. };
  4510. _proto.insertBefore = function insertBefore(oldNode, newNode) {
  4511. newNode.parent = this;
  4512. var oldIndex = this.index(oldNode);
  4513. this.nodes.splice(oldIndex, 0, newNode);
  4514. newNode.parent = this;
  4515. var index;
  4516. for (var id in this.indexes) {
  4517. index = this.indexes[id];
  4518. if (index <= oldIndex) {
  4519. this.indexes[id] = index + 1;
  4520. }
  4521. }
  4522. return this;
  4523. };
  4524. _proto._findChildAtPosition = function _findChildAtPosition(line, col) {
  4525. var found = undefined;
  4526. this.each(function (node) {
  4527. if (node.atPosition) {
  4528. var foundChild = node.atPosition(line, col);
  4529. if (foundChild) {
  4530. found = foundChild;
  4531. return false;
  4532. }
  4533. } else if (node.isAtPosition(line, col)) {
  4534. found = node;
  4535. return false;
  4536. }
  4537. });
  4538. return found;
  4539. }
  4540. /**
  4541. * Return the most specific node at the line and column number given.
  4542. * The source location is based on the original parsed location, locations aren't
  4543. * updated as selector nodes are mutated.
  4544. *
  4545. * Note that this location is relative to the location of the first character
  4546. * of the selector, and not the location of the selector in the overall document
  4547. * when used in conjunction with postcss.
  4548. *
  4549. * If not found, returns undefined.
  4550. * @param {number} line The line number of the node to find. (1-based index)
  4551. * @param {number} col The column number of the node to find. (1-based index)
  4552. */;
  4553. _proto.atPosition = function atPosition(line, col) {
  4554. if (this.isAtPosition(line, col)) {
  4555. return this._findChildAtPosition(line, col) || this;
  4556. } else {
  4557. return undefined;
  4558. }
  4559. };
  4560. _proto._inferEndPosition = function _inferEndPosition() {
  4561. if (this.last && this.last.source && this.last.source.end) {
  4562. this.source = this.source || {};
  4563. this.source.end = this.source.end || {};
  4564. Object.assign(this.source.end, this.last.source.end);
  4565. }
  4566. };
  4567. _proto.each = function each(callback) {
  4568. if (!this.lastEach) {
  4569. this.lastEach = 0;
  4570. }
  4571. if (!this.indexes) {
  4572. this.indexes = {};
  4573. }
  4574. this.lastEach++;
  4575. var id = this.lastEach;
  4576. this.indexes[id] = 0;
  4577. if (!this.length) {
  4578. return undefined;
  4579. }
  4580. var index, result;
  4581. while (this.indexes[id] < this.length) {
  4582. index = this.indexes[id];
  4583. result = callback(this.at(index), index);
  4584. if (result === false) {
  4585. break;
  4586. }
  4587. this.indexes[id] += 1;
  4588. }
  4589. delete this.indexes[id];
  4590. if (result === false) {
  4591. return false;
  4592. }
  4593. };
  4594. _proto.walk = function walk(callback) {
  4595. return this.each(function (node, i) {
  4596. var result = callback(node, i);
  4597. if (result !== false && node.length) {
  4598. result = node.walk(callback);
  4599. }
  4600. if (result === false) {
  4601. return false;
  4602. }
  4603. });
  4604. };
  4605. _proto.walkAttributes = function walkAttributes(callback) {
  4606. var _this2 = this;
  4607. return this.walk(function (selector) {
  4608. if (selector.type === types.ATTRIBUTE) {
  4609. return callback.call(_this2, selector);
  4610. }
  4611. });
  4612. };
  4613. _proto.walkClasses = function walkClasses(callback) {
  4614. var _this3 = this;
  4615. return this.walk(function (selector) {
  4616. if (selector.type === types.CLASS) {
  4617. return callback.call(_this3, selector);
  4618. }
  4619. });
  4620. };
  4621. _proto.walkCombinators = function walkCombinators(callback) {
  4622. var _this4 = this;
  4623. return this.walk(function (selector) {
  4624. if (selector.type === types.COMBINATOR) {
  4625. return callback.call(_this4, selector);
  4626. }
  4627. });
  4628. };
  4629. _proto.walkComments = function walkComments(callback) {
  4630. var _this5 = this;
  4631. return this.walk(function (selector) {
  4632. if (selector.type === types.COMMENT) {
  4633. return callback.call(_this5, selector);
  4634. }
  4635. });
  4636. };
  4637. _proto.walkIds = function walkIds(callback) {
  4638. var _this6 = this;
  4639. return this.walk(function (selector) {
  4640. if (selector.type === types.ID) {
  4641. return callback.call(_this6, selector);
  4642. }
  4643. });
  4644. };
  4645. _proto.walkNesting = function walkNesting(callback) {
  4646. var _this7 = this;
  4647. return this.walk(function (selector) {
  4648. if (selector.type === types.NESTING) {
  4649. return callback.call(_this7, selector);
  4650. }
  4651. });
  4652. };
  4653. _proto.walkPseudos = function walkPseudos(callback) {
  4654. var _this8 = this;
  4655. return this.walk(function (selector) {
  4656. if (selector.type === types.PSEUDO) {
  4657. return callback.call(_this8, selector);
  4658. }
  4659. });
  4660. };
  4661. _proto.walkTags = function walkTags(callback) {
  4662. var _this9 = this;
  4663. return this.walk(function (selector) {
  4664. if (selector.type === types.TAG) {
  4665. return callback.call(_this9, selector);
  4666. }
  4667. });
  4668. };
  4669. _proto.walkUniversals = function walkUniversals(callback) {
  4670. var _this10 = this;
  4671. return this.walk(function (selector) {
  4672. if (selector.type === types.UNIVERSAL) {
  4673. return callback.call(_this10, selector);
  4674. }
  4675. });
  4676. };
  4677. _proto.split = function split(callback) {
  4678. var _this11 = this;
  4679. var current = [];
  4680. return this.reduce(function (memo, node, index) {
  4681. var split = callback.call(_this11, node);
  4682. current.push(node);
  4683. if (split) {
  4684. memo.push(current);
  4685. current = [];
  4686. } else if (index === _this11.length - 1) {
  4687. memo.push(current);
  4688. }
  4689. return memo;
  4690. }, []);
  4691. };
  4692. _proto.map = function map(callback) {
  4693. return this.nodes.map(callback);
  4694. };
  4695. _proto.reduce = function reduce(callback, memo) {
  4696. return this.nodes.reduce(callback, memo);
  4697. };
  4698. _proto.every = function every(callback) {
  4699. return this.nodes.every(callback);
  4700. };
  4701. _proto.some = function some(callback) {
  4702. return this.nodes.some(callback);
  4703. };
  4704. _proto.filter = function filter(callback) {
  4705. return this.nodes.filter(callback);
  4706. };
  4707. _proto.sort = function sort(callback) {
  4708. return this.nodes.sort(callback);
  4709. };
  4710. _proto.toString = function toString() {
  4711. return this.map(String).join('');
  4712. };
  4713. _createClass(Container, [{
  4714. key: "first",
  4715. get: function get() {
  4716. return this.at(0);
  4717. }
  4718. }, {
  4719. key: "last",
  4720. get: function get() {
  4721. return this.at(this.length - 1);
  4722. }
  4723. }, {
  4724. key: "length",
  4725. get: function get() {
  4726. return this.nodes.length;
  4727. }
  4728. }]);
  4729. return Container;
  4730. }(_node["default"]);
  4731. exports["default"] = Container;
  4732. module.exports = exports.default;
  4733. } (container, container.exports));
  4734. return container.exports;
  4735. }
  4736. var hasRequiredRoot;
  4737. function requireRoot () {
  4738. if (hasRequiredRoot) return root.exports;
  4739. hasRequiredRoot = 1;
  4740. (function (module, exports) {
  4741. exports.__esModule = true;
  4742. exports["default"] = void 0;
  4743. var _container = _interopRequireDefault(/*@__PURE__*/ requireContainer());
  4744. var _types = /*@__PURE__*/ requireTypes();
  4745. function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; }
  4746. 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); } }
  4747. function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); Object.defineProperty(Constructor, "prototype", { writable: false }); return Constructor; }
  4748. function _inheritsLoose(subClass, superClass) { subClass.prototype = Object.create(superClass.prototype); subClass.prototype.constructor = subClass; _setPrototypeOf(subClass, superClass); }
  4749. function _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf ? Object.setPrototypeOf.bind() : function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); }
  4750. var Root = /*#__PURE__*/function (_Container) {
  4751. _inheritsLoose(Root, _Container);
  4752. function Root(opts) {
  4753. var _this;
  4754. _this = _Container.call(this, opts) || this;
  4755. _this.type = _types.ROOT;
  4756. return _this;
  4757. }
  4758. var _proto = Root.prototype;
  4759. _proto.toString = function toString() {
  4760. var str = this.reduce(function (memo, selector) {
  4761. memo.push(String(selector));
  4762. return memo;
  4763. }, []).join(',');
  4764. return this.trailingComma ? str + ',' : str;
  4765. };
  4766. _proto.error = function error(message, options) {
  4767. if (this._error) {
  4768. return this._error(message, options);
  4769. } else {
  4770. return new Error(message);
  4771. }
  4772. };
  4773. _createClass(Root, [{
  4774. key: "errorGenerator",
  4775. set: function set(handler) {
  4776. this._error = handler;
  4777. }
  4778. }]);
  4779. return Root;
  4780. }(_container["default"]);
  4781. exports["default"] = Root;
  4782. module.exports = exports.default;
  4783. } (root, root.exports));
  4784. return root.exports;
  4785. }
  4786. var selector = {exports: {}};
  4787. var hasRequiredSelector;
  4788. function requireSelector () {
  4789. if (hasRequiredSelector) return selector.exports;
  4790. hasRequiredSelector = 1;
  4791. (function (module, exports) {
  4792. exports.__esModule = true;
  4793. exports["default"] = void 0;
  4794. var _container = _interopRequireDefault(/*@__PURE__*/ requireContainer());
  4795. var _types = /*@__PURE__*/ requireTypes();
  4796. function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; }
  4797. function _inheritsLoose(subClass, superClass) { subClass.prototype = Object.create(superClass.prototype); subClass.prototype.constructor = subClass; _setPrototypeOf(subClass, superClass); }
  4798. function _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf ? Object.setPrototypeOf.bind() : function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); }
  4799. var Selector = /*#__PURE__*/function (_Container) {
  4800. _inheritsLoose(Selector, _Container);
  4801. function Selector(opts) {
  4802. var _this;
  4803. _this = _Container.call(this, opts) || this;
  4804. _this.type = _types.SELECTOR;
  4805. return _this;
  4806. }
  4807. return Selector;
  4808. }(_container["default"]);
  4809. exports["default"] = Selector;
  4810. module.exports = exports.default;
  4811. } (selector, selector.exports));
  4812. return selector.exports;
  4813. }
  4814. var className = {exports: {}};
  4815. /*! https://mths.be/cssesc v3.0.0 by @mathias */
  4816. var cssesc_1;
  4817. var hasRequiredCssesc;
  4818. function requireCssesc () {
  4819. if (hasRequiredCssesc) return cssesc_1;
  4820. hasRequiredCssesc = 1;
  4821. var object = {};
  4822. var hasOwnProperty = object.hasOwnProperty;
  4823. var merge = function merge(options, defaults) {
  4824. if (!options) {
  4825. return defaults;
  4826. }
  4827. var result = {};
  4828. for (var key in defaults) {
  4829. // `if (defaults.hasOwnProperty(key) { … }` is not needed here, since
  4830. // only recognized option names are used.
  4831. result[key] = hasOwnProperty.call(options, key) ? options[key] : defaults[key];
  4832. }
  4833. return result;
  4834. };
  4835. var regexAnySingleEscape = /[ -,\.\/:-@\[-\^`\{-~]/;
  4836. var regexSingleEscape = /[ -,\.\/:-@\[\]\^`\{-~]/;
  4837. var regexExcessiveSpaces = /(^|\\+)?(\\[A-F0-9]{1,6})\x20(?![a-fA-F0-9\x20])/g;
  4838. // https://mathiasbynens.be/notes/css-escapes#css
  4839. var cssesc = function cssesc(string, options) {
  4840. options = merge(options, cssesc.options);
  4841. if (options.quotes != 'single' && options.quotes != 'double') {
  4842. options.quotes = 'single';
  4843. }
  4844. var quote = options.quotes == 'double' ? '"' : '\'';
  4845. var isIdentifier = options.isIdentifier;
  4846. var firstChar = string.charAt(0);
  4847. var output = '';
  4848. var counter = 0;
  4849. var length = string.length;
  4850. while (counter < length) {
  4851. var character = string.charAt(counter++);
  4852. var codePoint = character.charCodeAt();
  4853. var value = void 0;
  4854. // If it’s not a printable ASCII character…
  4855. if (codePoint < 0x20 || codePoint > 0x7E) {
  4856. if (codePoint >= 0xD800 && codePoint <= 0xDBFF && counter < length) {
  4857. // It’s a high surrogate, and there is a next character.
  4858. var extra = string.charCodeAt(counter++);
  4859. if ((extra & 0xFC00) == 0xDC00) {
  4860. // next character is low surrogate
  4861. codePoint = ((codePoint & 0x3FF) << 10) + (extra & 0x3FF) + 0x10000;
  4862. } else {
  4863. // It’s an unmatched surrogate; only append this code unit, in case
  4864. // the next code unit is the high surrogate of a surrogate pair.
  4865. counter--;
  4866. }
  4867. }
  4868. value = '\\' + codePoint.toString(16).toUpperCase() + ' ';
  4869. } else {
  4870. if (options.escapeEverything) {
  4871. if (regexAnySingleEscape.test(character)) {
  4872. value = '\\' + character;
  4873. } else {
  4874. value = '\\' + codePoint.toString(16).toUpperCase() + ' ';
  4875. }
  4876. } else if (/[\t\n\f\r\x0B]/.test(character)) {
  4877. value = '\\' + codePoint.toString(16).toUpperCase() + ' ';
  4878. } else if (character == '\\' || !isIdentifier && (character == '"' && quote == character || character == '\'' && quote == character) || isIdentifier && regexSingleEscape.test(character)) {
  4879. value = '\\' + character;
  4880. } else {
  4881. value = character;
  4882. }
  4883. }
  4884. output += value;
  4885. }
  4886. if (isIdentifier) {
  4887. if (/^-[-\d]/.test(output)) {
  4888. output = '\\-' + output.slice(1);
  4889. } else if (/\d/.test(firstChar)) {
  4890. output = '\\3' + firstChar + ' ' + output.slice(1);
  4891. }
  4892. }
  4893. // Remove spaces after `\HEX` escapes that are not followed by a hex digit,
  4894. // since they’re redundant. Note that this is only possible if the escape
  4895. // sequence isn’t preceded by an odd number of backslashes.
  4896. output = output.replace(regexExcessiveSpaces, function ($0, $1, $2) {
  4897. if ($1 && $1.length % 2) {
  4898. // It’s not safe to remove the space, so don’t.
  4899. return $0;
  4900. }
  4901. // Strip the space.
  4902. return ($1 || '') + $2;
  4903. });
  4904. if (!isIdentifier && options.wrap) {
  4905. return quote + output + quote;
  4906. }
  4907. return output;
  4908. };
  4909. // Expose default options (so they can be overridden globally).
  4910. cssesc.options = {
  4911. 'escapeEverything': false,
  4912. 'isIdentifier': false,
  4913. 'quotes': 'single',
  4914. 'wrap': false
  4915. };
  4916. cssesc.version = '3.0.0';
  4917. cssesc_1 = cssesc;
  4918. return cssesc_1;
  4919. }
  4920. var hasRequiredClassName;
  4921. function requireClassName () {
  4922. if (hasRequiredClassName) return className.exports;
  4923. hasRequiredClassName = 1;
  4924. (function (module, exports) {
  4925. exports.__esModule = true;
  4926. exports["default"] = void 0;
  4927. var _cssesc = _interopRequireDefault(/*@__PURE__*/ requireCssesc());
  4928. var _util = /*@__PURE__*/ requireUtil$1();
  4929. var _node = _interopRequireDefault(/*@__PURE__*/ requireNode$1());
  4930. var _types = /*@__PURE__*/ requireTypes();
  4931. function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; }
  4932. 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); } }
  4933. function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); Object.defineProperty(Constructor, "prototype", { writable: false }); return Constructor; }
  4934. function _inheritsLoose(subClass, superClass) { subClass.prototype = Object.create(superClass.prototype); subClass.prototype.constructor = subClass; _setPrototypeOf(subClass, superClass); }
  4935. function _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf ? Object.setPrototypeOf.bind() : function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); }
  4936. var ClassName = /*#__PURE__*/function (_Node) {
  4937. _inheritsLoose(ClassName, _Node);
  4938. function ClassName(opts) {
  4939. var _this;
  4940. _this = _Node.call(this, opts) || this;
  4941. _this.type = _types.CLASS;
  4942. _this._constructed = true;
  4943. return _this;
  4944. }
  4945. var _proto = ClassName.prototype;
  4946. _proto.valueToString = function valueToString() {
  4947. return '.' + _Node.prototype.valueToString.call(this);
  4948. };
  4949. _createClass(ClassName, [{
  4950. key: "value",
  4951. get: function get() {
  4952. return this._value;
  4953. },
  4954. set: function set(v) {
  4955. if (this._constructed) {
  4956. var escaped = (0, _cssesc["default"])(v, {
  4957. isIdentifier: true
  4958. });
  4959. if (escaped !== v) {
  4960. (0, _util.ensureObject)(this, "raws");
  4961. this.raws.value = escaped;
  4962. } else if (this.raws) {
  4963. delete this.raws.value;
  4964. }
  4965. }
  4966. this._value = v;
  4967. }
  4968. }]);
  4969. return ClassName;
  4970. }(_node["default"]);
  4971. exports["default"] = ClassName;
  4972. module.exports = exports.default;
  4973. } (className, className.exports));
  4974. return className.exports;
  4975. }
  4976. var comment = {exports: {}};
  4977. var hasRequiredComment;
  4978. function requireComment () {
  4979. if (hasRequiredComment) return comment.exports;
  4980. hasRequiredComment = 1;
  4981. (function (module, exports) {
  4982. exports.__esModule = true;
  4983. exports["default"] = void 0;
  4984. var _node = _interopRequireDefault(/*@__PURE__*/ requireNode$1());
  4985. var _types = /*@__PURE__*/ requireTypes();
  4986. function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; }
  4987. function _inheritsLoose(subClass, superClass) { subClass.prototype = Object.create(superClass.prototype); subClass.prototype.constructor = subClass; _setPrototypeOf(subClass, superClass); }
  4988. function _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf ? Object.setPrototypeOf.bind() : function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); }
  4989. var Comment = /*#__PURE__*/function (_Node) {
  4990. _inheritsLoose(Comment, _Node);
  4991. function Comment(opts) {
  4992. var _this;
  4993. _this = _Node.call(this, opts) || this;
  4994. _this.type = _types.COMMENT;
  4995. return _this;
  4996. }
  4997. return Comment;
  4998. }(_node["default"]);
  4999. exports["default"] = Comment;
  5000. module.exports = exports.default;
  5001. } (comment, comment.exports));
  5002. return comment.exports;
  5003. }
  5004. var id = {exports: {}};
  5005. var hasRequiredId;
  5006. function requireId () {
  5007. if (hasRequiredId) return id.exports;
  5008. hasRequiredId = 1;
  5009. (function (module, exports) {
  5010. exports.__esModule = true;
  5011. exports["default"] = void 0;
  5012. var _node = _interopRequireDefault(/*@__PURE__*/ requireNode$1());
  5013. var _types = /*@__PURE__*/ requireTypes();
  5014. function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; }
  5015. function _inheritsLoose(subClass, superClass) { subClass.prototype = Object.create(superClass.prototype); subClass.prototype.constructor = subClass; _setPrototypeOf(subClass, superClass); }
  5016. function _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf ? Object.setPrototypeOf.bind() : function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); }
  5017. var ID = /*#__PURE__*/function (_Node) {
  5018. _inheritsLoose(ID, _Node);
  5019. function ID(opts) {
  5020. var _this;
  5021. _this = _Node.call(this, opts) || this;
  5022. _this.type = _types.ID;
  5023. return _this;
  5024. }
  5025. var _proto = ID.prototype;
  5026. _proto.valueToString = function valueToString() {
  5027. return '#' + _Node.prototype.valueToString.call(this);
  5028. };
  5029. return ID;
  5030. }(_node["default"]);
  5031. exports["default"] = ID;
  5032. module.exports = exports.default;
  5033. } (id, id.exports));
  5034. return id.exports;
  5035. }
  5036. var tag = {exports: {}};
  5037. var namespace = {exports: {}};
  5038. var hasRequiredNamespace;
  5039. function requireNamespace () {
  5040. if (hasRequiredNamespace) return namespace.exports;
  5041. hasRequiredNamespace = 1;
  5042. (function (module, exports) {
  5043. exports.__esModule = true;
  5044. exports["default"] = void 0;
  5045. var _cssesc = _interopRequireDefault(/*@__PURE__*/ requireCssesc());
  5046. var _util = /*@__PURE__*/ requireUtil$1();
  5047. var _node = _interopRequireDefault(/*@__PURE__*/ requireNode$1());
  5048. function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; }
  5049. 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); } }
  5050. function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); Object.defineProperty(Constructor, "prototype", { writable: false }); return Constructor; }
  5051. function _inheritsLoose(subClass, superClass) { subClass.prototype = Object.create(superClass.prototype); subClass.prototype.constructor = subClass; _setPrototypeOf(subClass, superClass); }
  5052. function _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf ? Object.setPrototypeOf.bind() : function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); }
  5053. var Namespace = /*#__PURE__*/function (_Node) {
  5054. _inheritsLoose(Namespace, _Node);
  5055. function Namespace() {
  5056. return _Node.apply(this, arguments) || this;
  5057. }
  5058. var _proto = Namespace.prototype;
  5059. _proto.qualifiedName = function qualifiedName(value) {
  5060. if (this.namespace) {
  5061. return this.namespaceString + "|" + value;
  5062. } else {
  5063. return value;
  5064. }
  5065. };
  5066. _proto.valueToString = function valueToString() {
  5067. return this.qualifiedName(_Node.prototype.valueToString.call(this));
  5068. };
  5069. _createClass(Namespace, [{
  5070. key: "namespace",
  5071. get: function get() {
  5072. return this._namespace;
  5073. },
  5074. set: function set(namespace) {
  5075. if (namespace === true || namespace === "*" || namespace === "&") {
  5076. this._namespace = namespace;
  5077. if (this.raws) {
  5078. delete this.raws.namespace;
  5079. }
  5080. return;
  5081. }
  5082. var escaped = (0, _cssesc["default"])(namespace, {
  5083. isIdentifier: true
  5084. });
  5085. this._namespace = namespace;
  5086. if (escaped !== namespace) {
  5087. (0, _util.ensureObject)(this, "raws");
  5088. this.raws.namespace = escaped;
  5089. } else if (this.raws) {
  5090. delete this.raws.namespace;
  5091. }
  5092. }
  5093. }, {
  5094. key: "ns",
  5095. get: function get() {
  5096. return this._namespace;
  5097. },
  5098. set: function set(namespace) {
  5099. this.namespace = namespace;
  5100. }
  5101. }, {
  5102. key: "namespaceString",
  5103. get: function get() {
  5104. if (this.namespace) {
  5105. var ns = this.stringifyProperty("namespace");
  5106. if (ns === true) {
  5107. return '';
  5108. } else {
  5109. return ns;
  5110. }
  5111. } else {
  5112. return '';
  5113. }
  5114. }
  5115. }]);
  5116. return Namespace;
  5117. }(_node["default"]);
  5118. exports["default"] = Namespace;
  5119. module.exports = exports.default;
  5120. } (namespace, namespace.exports));
  5121. return namespace.exports;
  5122. }
  5123. var hasRequiredTag;
  5124. function requireTag () {
  5125. if (hasRequiredTag) return tag.exports;
  5126. hasRequiredTag = 1;
  5127. (function (module, exports) {
  5128. exports.__esModule = true;
  5129. exports["default"] = void 0;
  5130. var _namespace = _interopRequireDefault(/*@__PURE__*/ requireNamespace());
  5131. var _types = /*@__PURE__*/ requireTypes();
  5132. function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; }
  5133. function _inheritsLoose(subClass, superClass) { subClass.prototype = Object.create(superClass.prototype); subClass.prototype.constructor = subClass; _setPrototypeOf(subClass, superClass); }
  5134. function _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf ? Object.setPrototypeOf.bind() : function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); }
  5135. var Tag = /*#__PURE__*/function (_Namespace) {
  5136. _inheritsLoose(Tag, _Namespace);
  5137. function Tag(opts) {
  5138. var _this;
  5139. _this = _Namespace.call(this, opts) || this;
  5140. _this.type = _types.TAG;
  5141. return _this;
  5142. }
  5143. return Tag;
  5144. }(_namespace["default"]);
  5145. exports["default"] = Tag;
  5146. module.exports = exports.default;
  5147. } (tag, tag.exports));
  5148. return tag.exports;
  5149. }
  5150. var string = {exports: {}};
  5151. var hasRequiredString;
  5152. function requireString () {
  5153. if (hasRequiredString) return string.exports;
  5154. hasRequiredString = 1;
  5155. (function (module, exports) {
  5156. exports.__esModule = true;
  5157. exports["default"] = void 0;
  5158. var _node = _interopRequireDefault(/*@__PURE__*/ requireNode$1());
  5159. var _types = /*@__PURE__*/ requireTypes();
  5160. function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; }
  5161. function _inheritsLoose(subClass, superClass) { subClass.prototype = Object.create(superClass.prototype); subClass.prototype.constructor = subClass; _setPrototypeOf(subClass, superClass); }
  5162. function _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf ? Object.setPrototypeOf.bind() : function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); }
  5163. var String = /*#__PURE__*/function (_Node) {
  5164. _inheritsLoose(String, _Node);
  5165. function String(opts) {
  5166. var _this;
  5167. _this = _Node.call(this, opts) || this;
  5168. _this.type = _types.STRING;
  5169. return _this;
  5170. }
  5171. return String;
  5172. }(_node["default"]);
  5173. exports["default"] = String;
  5174. module.exports = exports.default;
  5175. } (string, string.exports));
  5176. return string.exports;
  5177. }
  5178. var pseudo = {exports: {}};
  5179. var hasRequiredPseudo;
  5180. function requirePseudo () {
  5181. if (hasRequiredPseudo) return pseudo.exports;
  5182. hasRequiredPseudo = 1;
  5183. (function (module, exports) {
  5184. exports.__esModule = true;
  5185. exports["default"] = void 0;
  5186. var _container = _interopRequireDefault(/*@__PURE__*/ requireContainer());
  5187. var _types = /*@__PURE__*/ requireTypes();
  5188. function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; }
  5189. function _inheritsLoose(subClass, superClass) { subClass.prototype = Object.create(superClass.prototype); subClass.prototype.constructor = subClass; _setPrototypeOf(subClass, superClass); }
  5190. function _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf ? Object.setPrototypeOf.bind() : function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); }
  5191. var Pseudo = /*#__PURE__*/function (_Container) {
  5192. _inheritsLoose(Pseudo, _Container);
  5193. function Pseudo(opts) {
  5194. var _this;
  5195. _this = _Container.call(this, opts) || this;
  5196. _this.type = _types.PSEUDO;
  5197. return _this;
  5198. }
  5199. var _proto = Pseudo.prototype;
  5200. _proto.toString = function toString() {
  5201. var params = this.length ? '(' + this.map(String).join(',') + ')' : '';
  5202. return [this.rawSpaceBefore, this.stringifyProperty("value"), params, this.rawSpaceAfter].join('');
  5203. };
  5204. return Pseudo;
  5205. }(_container["default"]);
  5206. exports["default"] = Pseudo;
  5207. module.exports = exports.default;
  5208. } (pseudo, pseudo.exports));
  5209. return pseudo.exports;
  5210. }
  5211. var attribute = {};
  5212. var node;
  5213. var hasRequiredNode;
  5214. function requireNode () {
  5215. if (hasRequiredNode) return node;
  5216. hasRequiredNode = 1;
  5217. /**
  5218. * For Node.js, simply re-export the core `util.deprecate` function.
  5219. */
  5220. node = require$$2.deprecate;
  5221. return node;
  5222. }
  5223. var hasRequiredAttribute;
  5224. function requireAttribute () {
  5225. if (hasRequiredAttribute) return attribute;
  5226. hasRequiredAttribute = 1;
  5227. (function (exports) {
  5228. exports.__esModule = true;
  5229. exports["default"] = void 0;
  5230. exports.unescapeValue = unescapeValue;
  5231. var _cssesc = _interopRequireDefault(/*@__PURE__*/ requireCssesc());
  5232. var _unesc = _interopRequireDefault(/*@__PURE__*/ requireUnesc());
  5233. var _namespace = _interopRequireDefault(/*@__PURE__*/ requireNamespace());
  5234. var _types = /*@__PURE__*/ requireTypes();
  5235. var _CSSESC_QUOTE_OPTIONS;
  5236. function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; }
  5237. 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); } }
  5238. function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); Object.defineProperty(Constructor, "prototype", { writable: false }); return Constructor; }
  5239. function _inheritsLoose(subClass, superClass) { subClass.prototype = Object.create(superClass.prototype); subClass.prototype.constructor = subClass; _setPrototypeOf(subClass, superClass); }
  5240. function _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf ? Object.setPrototypeOf.bind() : function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); }
  5241. var deprecate = /*@__PURE__*/ requireNode();
  5242. var WRAPPED_IN_QUOTES = /^('|")([^]*)\1$/;
  5243. var warnOfDeprecatedValueAssignment = deprecate(function () {}, "Assigning an attribute a value containing characters that might need to be escaped is deprecated. " + "Call attribute.setValue() instead.");
  5244. var warnOfDeprecatedQuotedAssignment = deprecate(function () {}, "Assigning attr.quoted is deprecated and has no effect. Assign to attr.quoteMark instead.");
  5245. var warnOfDeprecatedConstructor = deprecate(function () {}, "Constructing an Attribute selector with a value without specifying quoteMark is deprecated. Note: The value should be unescaped now.");
  5246. function unescapeValue(value) {
  5247. var deprecatedUsage = false;
  5248. var quoteMark = null;
  5249. var unescaped = value;
  5250. var m = unescaped.match(WRAPPED_IN_QUOTES);
  5251. if (m) {
  5252. quoteMark = m[1];
  5253. unescaped = m[2];
  5254. }
  5255. unescaped = (0, _unesc["default"])(unescaped);
  5256. if (unescaped !== value) {
  5257. deprecatedUsage = true;
  5258. }
  5259. return {
  5260. deprecatedUsage: deprecatedUsage,
  5261. unescaped: unescaped,
  5262. quoteMark: quoteMark
  5263. };
  5264. }
  5265. function handleDeprecatedContructorOpts(opts) {
  5266. if (opts.quoteMark !== undefined) {
  5267. return opts;
  5268. }
  5269. if (opts.value === undefined) {
  5270. return opts;
  5271. }
  5272. warnOfDeprecatedConstructor();
  5273. var _unescapeValue = unescapeValue(opts.value),
  5274. quoteMark = _unescapeValue.quoteMark,
  5275. unescaped = _unescapeValue.unescaped;
  5276. if (!opts.raws) {
  5277. opts.raws = {};
  5278. }
  5279. if (opts.raws.value === undefined) {
  5280. opts.raws.value = opts.value;
  5281. }
  5282. opts.value = unescaped;
  5283. opts.quoteMark = quoteMark;
  5284. return opts;
  5285. }
  5286. var Attribute = /*#__PURE__*/function (_Namespace) {
  5287. _inheritsLoose(Attribute, _Namespace);
  5288. function Attribute(opts) {
  5289. var _this;
  5290. if (opts === void 0) {
  5291. opts = {};
  5292. }
  5293. _this = _Namespace.call(this, handleDeprecatedContructorOpts(opts)) || this;
  5294. _this.type = _types.ATTRIBUTE;
  5295. _this.raws = _this.raws || {};
  5296. Object.defineProperty(_this.raws, 'unquoted', {
  5297. get: deprecate(function () {
  5298. return _this.value;
  5299. }, "attr.raws.unquoted is deprecated. Call attr.value instead."),
  5300. set: deprecate(function () {
  5301. return _this.value;
  5302. }, "Setting attr.raws.unquoted is deprecated and has no effect. attr.value is unescaped by default now.")
  5303. });
  5304. _this._constructed = true;
  5305. return _this;
  5306. }
  5307. /**
  5308. * Returns the Attribute's value quoted such that it would be legal to use
  5309. * in the value of a css file. The original value's quotation setting
  5310. * used for stringification is left unchanged. See `setValue(value, options)`
  5311. * if you want to control the quote settings of a new value for the attribute.
  5312. *
  5313. * You can also change the quotation used for the current value by setting quoteMark.
  5314. *
  5315. * Options:
  5316. * * quoteMark {'"' | "'" | null} - Use this value to quote the value. If this
  5317. * option is not set, the original value for quoteMark will be used. If
  5318. * indeterminate, a double quote is used. The legal values are:
  5319. * * `null` - the value will be unquoted and characters will be escaped as necessary.
  5320. * * `'` - the value will be quoted with a single quote and single quotes are escaped.
  5321. * * `"` - the value will be quoted with a double quote and double quotes are escaped.
  5322. * * preferCurrentQuoteMark {boolean} - if true, prefer the source quote mark
  5323. * over the quoteMark option value.
  5324. * * smart {boolean} - if true, will select a quote mark based on the value
  5325. * and the other options specified here. See the `smartQuoteMark()`
  5326. * method.
  5327. **/
  5328. var _proto = Attribute.prototype;
  5329. _proto.getQuotedValue = function getQuotedValue(options) {
  5330. if (options === void 0) {
  5331. options = {};
  5332. }
  5333. var quoteMark = this._determineQuoteMark(options);
  5334. var cssescopts = CSSESC_QUOTE_OPTIONS[quoteMark];
  5335. var escaped = (0, _cssesc["default"])(this._value, cssescopts);
  5336. return escaped;
  5337. };
  5338. _proto._determineQuoteMark = function _determineQuoteMark(options) {
  5339. return options.smart ? this.smartQuoteMark(options) : this.preferredQuoteMark(options);
  5340. }
  5341. /**
  5342. * Set the unescaped value with the specified quotation options. The value
  5343. * provided must not include any wrapping quote marks -- those quotes will
  5344. * be interpreted as part of the value and escaped accordingly.
  5345. */;
  5346. _proto.setValue = function setValue(value, options) {
  5347. if (options === void 0) {
  5348. options = {};
  5349. }
  5350. this._value = value;
  5351. this._quoteMark = this._determineQuoteMark(options);
  5352. this._syncRawValue();
  5353. }
  5354. /**
  5355. * Intelligently select a quoteMark value based on the value's contents. If
  5356. * the value is a legal CSS ident, it will not be quoted. Otherwise a quote
  5357. * mark will be picked that minimizes the number of escapes.
  5358. *
  5359. * If there's no clear winner, the quote mark from these options is used,
  5360. * then the source quote mark (this is inverted if `preferCurrentQuoteMark` is
  5361. * true). If the quoteMark is unspecified, a double quote is used.
  5362. *
  5363. * @param options This takes the quoteMark and preferCurrentQuoteMark options
  5364. * from the quoteValue method.
  5365. */;
  5366. _proto.smartQuoteMark = function smartQuoteMark(options) {
  5367. var v = this.value;
  5368. var numSingleQuotes = v.replace(/[^']/g, '').length;
  5369. var numDoubleQuotes = v.replace(/[^"]/g, '').length;
  5370. if (numSingleQuotes + numDoubleQuotes === 0) {
  5371. var escaped = (0, _cssesc["default"])(v, {
  5372. isIdentifier: true
  5373. });
  5374. if (escaped === v) {
  5375. return Attribute.NO_QUOTE;
  5376. } else {
  5377. var pref = this.preferredQuoteMark(options);
  5378. if (pref === Attribute.NO_QUOTE) {
  5379. // pick a quote mark that isn't none and see if it's smaller
  5380. var quote = this.quoteMark || options.quoteMark || Attribute.DOUBLE_QUOTE;
  5381. var opts = CSSESC_QUOTE_OPTIONS[quote];
  5382. var quoteValue = (0, _cssesc["default"])(v, opts);
  5383. if (quoteValue.length < escaped.length) {
  5384. return quote;
  5385. }
  5386. }
  5387. return pref;
  5388. }
  5389. } else if (numDoubleQuotes === numSingleQuotes) {
  5390. return this.preferredQuoteMark(options);
  5391. } else if (numDoubleQuotes < numSingleQuotes) {
  5392. return Attribute.DOUBLE_QUOTE;
  5393. } else {
  5394. return Attribute.SINGLE_QUOTE;
  5395. }
  5396. }
  5397. /**
  5398. * Selects the preferred quote mark based on the options and the current quote mark value.
  5399. * If you want the quote mark to depend on the attribute value, call `smartQuoteMark(opts)`
  5400. * instead.
  5401. */;
  5402. _proto.preferredQuoteMark = function preferredQuoteMark(options) {
  5403. var quoteMark = options.preferCurrentQuoteMark ? this.quoteMark : options.quoteMark;
  5404. if (quoteMark === undefined) {
  5405. quoteMark = options.preferCurrentQuoteMark ? options.quoteMark : this.quoteMark;
  5406. }
  5407. if (quoteMark === undefined) {
  5408. quoteMark = Attribute.DOUBLE_QUOTE;
  5409. }
  5410. return quoteMark;
  5411. };
  5412. _proto._syncRawValue = function _syncRawValue() {
  5413. var rawValue = (0, _cssesc["default"])(this._value, CSSESC_QUOTE_OPTIONS[this.quoteMark]);
  5414. if (rawValue === this._value) {
  5415. if (this.raws) {
  5416. delete this.raws.value;
  5417. }
  5418. } else {
  5419. this.raws.value = rawValue;
  5420. }
  5421. };
  5422. _proto._handleEscapes = function _handleEscapes(prop, value) {
  5423. if (this._constructed) {
  5424. var escaped = (0, _cssesc["default"])(value, {
  5425. isIdentifier: true
  5426. });
  5427. if (escaped !== value) {
  5428. this.raws[prop] = escaped;
  5429. } else {
  5430. delete this.raws[prop];
  5431. }
  5432. }
  5433. };
  5434. _proto._spacesFor = function _spacesFor(name) {
  5435. var attrSpaces = {
  5436. before: '',
  5437. after: ''
  5438. };
  5439. var spaces = this.spaces[name] || {};
  5440. var rawSpaces = this.raws.spaces && this.raws.spaces[name] || {};
  5441. return Object.assign(attrSpaces, spaces, rawSpaces);
  5442. };
  5443. _proto._stringFor = function _stringFor(name, spaceName, concat) {
  5444. if (spaceName === void 0) {
  5445. spaceName = name;
  5446. }
  5447. if (concat === void 0) {
  5448. concat = defaultAttrConcat;
  5449. }
  5450. var attrSpaces = this._spacesFor(spaceName);
  5451. return concat(this.stringifyProperty(name), attrSpaces);
  5452. }
  5453. /**
  5454. * returns the offset of the attribute part specified relative to the
  5455. * start of the node of the output string.
  5456. *
  5457. * * "ns" - alias for "namespace"
  5458. * * "namespace" - the namespace if it exists.
  5459. * * "attribute" - the attribute name
  5460. * * "attributeNS" - the start of the attribute or its namespace
  5461. * * "operator" - the match operator of the attribute
  5462. * * "value" - The value (string or identifier)
  5463. * * "insensitive" - the case insensitivity flag;
  5464. * @param part One of the possible values inside an attribute.
  5465. * @returns -1 if the name is invalid or the value doesn't exist in this attribute.
  5466. */;
  5467. _proto.offsetOf = function offsetOf(name) {
  5468. var count = 1;
  5469. var attributeSpaces = this._spacesFor("attribute");
  5470. count += attributeSpaces.before.length;
  5471. if (name === "namespace" || name === "ns") {
  5472. return this.namespace ? count : -1;
  5473. }
  5474. if (name === "attributeNS") {
  5475. return count;
  5476. }
  5477. count += this.namespaceString.length;
  5478. if (this.namespace) {
  5479. count += 1;
  5480. }
  5481. if (name === "attribute") {
  5482. return count;
  5483. }
  5484. count += this.stringifyProperty("attribute").length;
  5485. count += attributeSpaces.after.length;
  5486. var operatorSpaces = this._spacesFor("operator");
  5487. count += operatorSpaces.before.length;
  5488. var operator = this.stringifyProperty("operator");
  5489. if (name === "operator") {
  5490. return operator ? count : -1;
  5491. }
  5492. count += operator.length;
  5493. count += operatorSpaces.after.length;
  5494. var valueSpaces = this._spacesFor("value");
  5495. count += valueSpaces.before.length;
  5496. var value = this.stringifyProperty("value");
  5497. if (name === "value") {
  5498. return value ? count : -1;
  5499. }
  5500. count += value.length;
  5501. count += valueSpaces.after.length;
  5502. var insensitiveSpaces = this._spacesFor("insensitive");
  5503. count += insensitiveSpaces.before.length;
  5504. if (name === "insensitive") {
  5505. return this.insensitive ? count : -1;
  5506. }
  5507. return -1;
  5508. };
  5509. _proto.toString = function toString() {
  5510. var _this2 = this;
  5511. var selector = [this.rawSpaceBefore, '['];
  5512. selector.push(this._stringFor('qualifiedAttribute', 'attribute'));
  5513. if (this.operator && (this.value || this.value === '')) {
  5514. selector.push(this._stringFor('operator'));
  5515. selector.push(this._stringFor('value'));
  5516. selector.push(this._stringFor('insensitiveFlag', 'insensitive', function (attrValue, attrSpaces) {
  5517. if (attrValue.length > 0 && !_this2.quoted && attrSpaces.before.length === 0 && !(_this2.spaces.value && _this2.spaces.value.after)) {
  5518. attrSpaces.before = " ";
  5519. }
  5520. return defaultAttrConcat(attrValue, attrSpaces);
  5521. }));
  5522. }
  5523. selector.push(']');
  5524. selector.push(this.rawSpaceAfter);
  5525. return selector.join('');
  5526. };
  5527. _createClass(Attribute, [{
  5528. key: "quoted",
  5529. get: function get() {
  5530. var qm = this.quoteMark;
  5531. return qm === "'" || qm === '"';
  5532. },
  5533. set: function set(value) {
  5534. warnOfDeprecatedQuotedAssignment();
  5535. }
  5536. /**
  5537. * returns a single (`'`) or double (`"`) quote character if the value is quoted.
  5538. * returns `null` if the value is not quoted.
  5539. * returns `undefined` if the quotation state is unknown (this can happen when
  5540. * the attribute is constructed without specifying a quote mark.)
  5541. */
  5542. }, {
  5543. key: "quoteMark",
  5544. get: function get() {
  5545. return this._quoteMark;
  5546. }
  5547. /**
  5548. * Set the quote mark to be used by this attribute's value.
  5549. * If the quote mark changes, the raw (escaped) value at `attr.raws.value` of the attribute
  5550. * value is updated accordingly.
  5551. *
  5552. * @param {"'" | '"' | null} quoteMark The quote mark or `null` if the value should be unquoted.
  5553. */,
  5554. set: function set(quoteMark) {
  5555. if (!this._constructed) {
  5556. this._quoteMark = quoteMark;
  5557. return;
  5558. }
  5559. if (this._quoteMark !== quoteMark) {
  5560. this._quoteMark = quoteMark;
  5561. this._syncRawValue();
  5562. }
  5563. }
  5564. }, {
  5565. key: "qualifiedAttribute",
  5566. get: function get() {
  5567. return this.qualifiedName(this.raws.attribute || this.attribute);
  5568. }
  5569. }, {
  5570. key: "insensitiveFlag",
  5571. get: function get() {
  5572. return this.insensitive ? 'i' : '';
  5573. }
  5574. }, {
  5575. key: "value",
  5576. get: function get() {
  5577. return this._value;
  5578. },
  5579. set:
  5580. /**
  5581. * Before 3.0, the value had to be set to an escaped value including any wrapped
  5582. * quote marks. In 3.0, the semantics of `Attribute.value` changed so that the value
  5583. * is unescaped during parsing and any quote marks are removed.
  5584. *
  5585. * Because the ambiguity of this semantic change, if you set `attr.value = newValue`,
  5586. * a deprecation warning is raised when the new value contains any characters that would
  5587. * require escaping (including if it contains wrapped quotes).
  5588. *
  5589. * Instead, you should call `attr.setValue(newValue, opts)` and pass options that describe
  5590. * how the new value is quoted.
  5591. */
  5592. function set(v) {
  5593. if (this._constructed) {
  5594. var _unescapeValue2 = unescapeValue(v),
  5595. deprecatedUsage = _unescapeValue2.deprecatedUsage,
  5596. unescaped = _unescapeValue2.unescaped,
  5597. quoteMark = _unescapeValue2.quoteMark;
  5598. if (deprecatedUsage) {
  5599. warnOfDeprecatedValueAssignment();
  5600. }
  5601. if (unescaped === this._value && quoteMark === this._quoteMark) {
  5602. return;
  5603. }
  5604. this._value = unescaped;
  5605. this._quoteMark = quoteMark;
  5606. this._syncRawValue();
  5607. } else {
  5608. this._value = v;
  5609. }
  5610. }
  5611. }, {
  5612. key: "insensitive",
  5613. get: function get() {
  5614. return this._insensitive;
  5615. }
  5616. /**
  5617. * Set the case insensitive flag.
  5618. * If the case insensitive flag changes, the raw (escaped) value at `attr.raws.insensitiveFlag`
  5619. * of the attribute is updated accordingly.
  5620. *
  5621. * @param {true | false} insensitive true if the attribute should match case-insensitively.
  5622. */,
  5623. set: function set(insensitive) {
  5624. if (!insensitive) {
  5625. this._insensitive = false;
  5626. // "i" and "I" can be used in "this.raws.insensitiveFlag" to store the original notation.
  5627. // When setting `attr.insensitive = false` both should be erased to ensure correct serialization.
  5628. if (this.raws && (this.raws.insensitiveFlag === 'I' || this.raws.insensitiveFlag === 'i')) {
  5629. this.raws.insensitiveFlag = undefined;
  5630. }
  5631. }
  5632. this._insensitive = insensitive;
  5633. }
  5634. }, {
  5635. key: "attribute",
  5636. get: function get() {
  5637. return this._attribute;
  5638. },
  5639. set: function set(name) {
  5640. this._handleEscapes("attribute", name);
  5641. this._attribute = name;
  5642. }
  5643. }]);
  5644. return Attribute;
  5645. }(_namespace["default"]);
  5646. exports["default"] = Attribute;
  5647. Attribute.NO_QUOTE = null;
  5648. Attribute.SINGLE_QUOTE = "'";
  5649. Attribute.DOUBLE_QUOTE = '"';
  5650. var CSSESC_QUOTE_OPTIONS = (_CSSESC_QUOTE_OPTIONS = {
  5651. "'": {
  5652. quotes: 'single',
  5653. wrap: true
  5654. },
  5655. '"': {
  5656. quotes: 'double',
  5657. wrap: true
  5658. }
  5659. }, _CSSESC_QUOTE_OPTIONS[null] = {
  5660. isIdentifier: true
  5661. }, _CSSESC_QUOTE_OPTIONS);
  5662. function defaultAttrConcat(attrValue, attrSpaces) {
  5663. return "" + attrSpaces.before + attrValue + attrSpaces.after;
  5664. }
  5665. } (attribute));
  5666. return attribute;
  5667. }
  5668. var universal = {exports: {}};
  5669. var hasRequiredUniversal;
  5670. function requireUniversal () {
  5671. if (hasRequiredUniversal) return universal.exports;
  5672. hasRequiredUniversal = 1;
  5673. (function (module, exports) {
  5674. exports.__esModule = true;
  5675. exports["default"] = void 0;
  5676. var _namespace = _interopRequireDefault(/*@__PURE__*/ requireNamespace());
  5677. var _types = /*@__PURE__*/ requireTypes();
  5678. function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; }
  5679. function _inheritsLoose(subClass, superClass) { subClass.prototype = Object.create(superClass.prototype); subClass.prototype.constructor = subClass; _setPrototypeOf(subClass, superClass); }
  5680. function _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf ? Object.setPrototypeOf.bind() : function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); }
  5681. var Universal = /*#__PURE__*/function (_Namespace) {
  5682. _inheritsLoose(Universal, _Namespace);
  5683. function Universal(opts) {
  5684. var _this;
  5685. _this = _Namespace.call(this, opts) || this;
  5686. _this.type = _types.UNIVERSAL;
  5687. _this.value = '*';
  5688. return _this;
  5689. }
  5690. return Universal;
  5691. }(_namespace["default"]);
  5692. exports["default"] = Universal;
  5693. module.exports = exports.default;
  5694. } (universal, universal.exports));
  5695. return universal.exports;
  5696. }
  5697. var combinator = {exports: {}};
  5698. var hasRequiredCombinator;
  5699. function requireCombinator () {
  5700. if (hasRequiredCombinator) return combinator.exports;
  5701. hasRequiredCombinator = 1;
  5702. (function (module, exports) {
  5703. exports.__esModule = true;
  5704. exports["default"] = void 0;
  5705. var _node = _interopRequireDefault(/*@__PURE__*/ requireNode$1());
  5706. var _types = /*@__PURE__*/ requireTypes();
  5707. function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; }
  5708. function _inheritsLoose(subClass, superClass) { subClass.prototype = Object.create(superClass.prototype); subClass.prototype.constructor = subClass; _setPrototypeOf(subClass, superClass); }
  5709. function _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf ? Object.setPrototypeOf.bind() : function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); }
  5710. var Combinator = /*#__PURE__*/function (_Node) {
  5711. _inheritsLoose(Combinator, _Node);
  5712. function Combinator(opts) {
  5713. var _this;
  5714. _this = _Node.call(this, opts) || this;
  5715. _this.type = _types.COMBINATOR;
  5716. return _this;
  5717. }
  5718. return Combinator;
  5719. }(_node["default"]);
  5720. exports["default"] = Combinator;
  5721. module.exports = exports.default;
  5722. } (combinator, combinator.exports));
  5723. return combinator.exports;
  5724. }
  5725. var nesting = {exports: {}};
  5726. var hasRequiredNesting;
  5727. function requireNesting () {
  5728. if (hasRequiredNesting) return nesting.exports;
  5729. hasRequiredNesting = 1;
  5730. (function (module, exports) {
  5731. exports.__esModule = true;
  5732. exports["default"] = void 0;
  5733. var _node = _interopRequireDefault(/*@__PURE__*/ requireNode$1());
  5734. var _types = /*@__PURE__*/ requireTypes();
  5735. function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; }
  5736. function _inheritsLoose(subClass, superClass) { subClass.prototype = Object.create(superClass.prototype); subClass.prototype.constructor = subClass; _setPrototypeOf(subClass, superClass); }
  5737. function _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf ? Object.setPrototypeOf.bind() : function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); }
  5738. var Nesting = /*#__PURE__*/function (_Node) {
  5739. _inheritsLoose(Nesting, _Node);
  5740. function Nesting(opts) {
  5741. var _this;
  5742. _this = _Node.call(this, opts) || this;
  5743. _this.type = _types.NESTING;
  5744. _this.value = '&';
  5745. return _this;
  5746. }
  5747. return Nesting;
  5748. }(_node["default"]);
  5749. exports["default"] = Nesting;
  5750. module.exports = exports.default;
  5751. } (nesting, nesting.exports));
  5752. return nesting.exports;
  5753. }
  5754. var sortAscending = {exports: {}};
  5755. var hasRequiredSortAscending;
  5756. function requireSortAscending () {
  5757. if (hasRequiredSortAscending) return sortAscending.exports;
  5758. hasRequiredSortAscending = 1;
  5759. (function (module, exports) {
  5760. exports.__esModule = true;
  5761. exports["default"] = sortAscending;
  5762. function sortAscending(list) {
  5763. return list.sort(function (a, b) {
  5764. return a - b;
  5765. });
  5766. }
  5767. module.exports = exports.default;
  5768. } (sortAscending, sortAscending.exports));
  5769. return sortAscending.exports;
  5770. }
  5771. var tokenize = {};
  5772. var tokenTypes = {};
  5773. var hasRequiredTokenTypes;
  5774. function requireTokenTypes () {
  5775. if (hasRequiredTokenTypes) return tokenTypes;
  5776. hasRequiredTokenTypes = 1;
  5777. tokenTypes.__esModule = true;
  5778. 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;
  5779. var ampersand = 38; // `&`.charCodeAt(0);
  5780. tokenTypes.ampersand = ampersand;
  5781. var asterisk = 42; // `*`.charCodeAt(0);
  5782. tokenTypes.asterisk = asterisk;
  5783. var at = 64; // `@`.charCodeAt(0);
  5784. tokenTypes.at = at;
  5785. var comma = 44; // `,`.charCodeAt(0);
  5786. tokenTypes.comma = comma;
  5787. var colon = 58; // `:`.charCodeAt(0);
  5788. tokenTypes.colon = colon;
  5789. var semicolon = 59; // `;`.charCodeAt(0);
  5790. tokenTypes.semicolon = semicolon;
  5791. var openParenthesis = 40; // `(`.charCodeAt(0);
  5792. tokenTypes.openParenthesis = openParenthesis;
  5793. var closeParenthesis = 41; // `)`.charCodeAt(0);
  5794. tokenTypes.closeParenthesis = closeParenthesis;
  5795. var openSquare = 91; // `[`.charCodeAt(0);
  5796. tokenTypes.openSquare = openSquare;
  5797. var closeSquare = 93; // `]`.charCodeAt(0);
  5798. tokenTypes.closeSquare = closeSquare;
  5799. var dollar = 36; // `$`.charCodeAt(0);
  5800. tokenTypes.dollar = dollar;
  5801. var tilde = 126; // `~`.charCodeAt(0);
  5802. tokenTypes.tilde = tilde;
  5803. var caret = 94; // `^`.charCodeAt(0);
  5804. tokenTypes.caret = caret;
  5805. var plus = 43; // `+`.charCodeAt(0);
  5806. tokenTypes.plus = plus;
  5807. var equals = 61; // `=`.charCodeAt(0);
  5808. tokenTypes.equals = equals;
  5809. var pipe = 124; // `|`.charCodeAt(0);
  5810. tokenTypes.pipe = pipe;
  5811. var greaterThan = 62; // `>`.charCodeAt(0);
  5812. tokenTypes.greaterThan = greaterThan;
  5813. var space = 32; // ` `.charCodeAt(0);
  5814. tokenTypes.space = space;
  5815. var singleQuote = 39; // `'`.charCodeAt(0);
  5816. tokenTypes.singleQuote = singleQuote;
  5817. var doubleQuote = 34; // `"`.charCodeAt(0);
  5818. tokenTypes.doubleQuote = doubleQuote;
  5819. var slash = 47; // `/`.charCodeAt(0);
  5820. tokenTypes.slash = slash;
  5821. var bang = 33; // `!`.charCodeAt(0);
  5822. tokenTypes.bang = bang;
  5823. var backslash = 92; // '\\'.charCodeAt(0);
  5824. tokenTypes.backslash = backslash;
  5825. var cr = 13; // '\r'.charCodeAt(0);
  5826. tokenTypes.cr = cr;
  5827. var feed = 12; // '\f'.charCodeAt(0);
  5828. tokenTypes.feed = feed;
  5829. var newline = 10; // '\n'.charCodeAt(0);
  5830. tokenTypes.newline = newline;
  5831. var tab = 9; // '\t'.charCodeAt(0);
  5832. // Expose aliases primarily for readability.
  5833. tokenTypes.tab = tab;
  5834. var str = singleQuote;
  5835. // No good single character representation!
  5836. tokenTypes.str = str;
  5837. var comment = -1;
  5838. tokenTypes.comment = comment;
  5839. var word = -2;
  5840. tokenTypes.word = word;
  5841. var combinator = -3;
  5842. tokenTypes.combinator = combinator;
  5843. return tokenTypes;
  5844. }
  5845. var hasRequiredTokenize;
  5846. function requireTokenize () {
  5847. if (hasRequiredTokenize) return tokenize;
  5848. hasRequiredTokenize = 1;
  5849. (function (exports) {
  5850. exports.__esModule = true;
  5851. exports.FIELDS = void 0;
  5852. exports["default"] = tokenize;
  5853. var t = _interopRequireWildcard(/*@__PURE__*/ requireTokenTypes());
  5854. var _unescapable, _wordDelimiters;
  5855. 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); }
  5856. 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; }
  5857. var unescapable = (_unescapable = {}, _unescapable[t.tab] = true, _unescapable[t.newline] = true, _unescapable[t.cr] = true, _unescapable[t.feed] = true, _unescapable);
  5858. 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);
  5859. var hex = {};
  5860. var hexChars = "0123456789abcdefABCDEF";
  5861. for (var i = 0; i < hexChars.length; i++) {
  5862. hex[hexChars.charCodeAt(i)] = true;
  5863. }
  5864. /**
  5865. * Returns the last index of the bar css word
  5866. * @param {string} css The string in which the word begins
  5867. * @param {number} start The index into the string where word's first letter occurs
  5868. */
  5869. function consumeWord(css, start) {
  5870. var next = start;
  5871. var code;
  5872. do {
  5873. code = css.charCodeAt(next);
  5874. if (wordDelimiters[code]) {
  5875. return next - 1;
  5876. } else if (code === t.backslash) {
  5877. next = consumeEscape(css, next) + 1;
  5878. } else {
  5879. // All other characters are part of the word
  5880. next++;
  5881. }
  5882. } while (next < css.length);
  5883. return next - 1;
  5884. }
  5885. /**
  5886. * Returns the last index of the escape sequence
  5887. * @param {string} css The string in which the sequence begins
  5888. * @param {number} start The index into the string where escape character (`\`) occurs.
  5889. */
  5890. function consumeEscape(css, start) {
  5891. var next = start;
  5892. var code = css.charCodeAt(next + 1);
  5893. if (unescapable[code]) ; else if (hex[code]) {
  5894. var hexDigits = 0;
  5895. // consume up to 6 hex chars
  5896. do {
  5897. next++;
  5898. hexDigits++;
  5899. code = css.charCodeAt(next + 1);
  5900. } while (hex[code] && hexDigits < 6);
  5901. // if fewer than 6 hex chars, a trailing space ends the escape
  5902. if (hexDigits < 6 && code === t.space) {
  5903. next++;
  5904. }
  5905. } else {
  5906. // the next char is part of the current word
  5907. next++;
  5908. }
  5909. return next;
  5910. }
  5911. var FIELDS = {
  5912. TYPE: 0,
  5913. START_LINE: 1,
  5914. START_COL: 2,
  5915. END_LINE: 3,
  5916. END_COL: 4,
  5917. START_POS: 5,
  5918. END_POS: 6
  5919. };
  5920. exports.FIELDS = FIELDS;
  5921. function tokenize(input) {
  5922. var tokens = [];
  5923. var css = input.css.valueOf();
  5924. var _css = css,
  5925. length = _css.length;
  5926. var offset = -1;
  5927. var line = 1;
  5928. var start = 0;
  5929. var end = 0;
  5930. var code, content, endColumn, endLine, escaped, escapePos, last, lines, next, nextLine, nextOffset, quote, tokenType;
  5931. function unclosed(what, fix) {
  5932. if (input.safe) {
  5933. // fyi: this is never set to true.
  5934. css += fix;
  5935. next = css.length - 1;
  5936. } else {
  5937. throw input.error('Unclosed ' + what, line, start - offset, start);
  5938. }
  5939. }
  5940. while (start < length) {
  5941. code = css.charCodeAt(start);
  5942. if (code === t.newline) {
  5943. offset = start;
  5944. line += 1;
  5945. }
  5946. switch (code) {
  5947. case t.space:
  5948. case t.tab:
  5949. case t.newline:
  5950. case t.cr:
  5951. case t.feed:
  5952. next = start;
  5953. do {
  5954. next += 1;
  5955. code = css.charCodeAt(next);
  5956. if (code === t.newline) {
  5957. offset = next;
  5958. line += 1;
  5959. }
  5960. } while (code === t.space || code === t.newline || code === t.tab || code === t.cr || code === t.feed);
  5961. tokenType = t.space;
  5962. endLine = line;
  5963. endColumn = next - offset - 1;
  5964. end = next;
  5965. break;
  5966. case t.plus:
  5967. case t.greaterThan:
  5968. case t.tilde:
  5969. case t.pipe:
  5970. next = start;
  5971. do {
  5972. next += 1;
  5973. code = css.charCodeAt(next);
  5974. } while (code === t.plus || code === t.greaterThan || code === t.tilde || code === t.pipe);
  5975. tokenType = t.combinator;
  5976. endLine = line;
  5977. endColumn = start - offset;
  5978. end = next;
  5979. break;
  5980. // Consume these characters as single tokens.
  5981. case t.asterisk:
  5982. case t.ampersand:
  5983. case t.bang:
  5984. case t.comma:
  5985. case t.equals:
  5986. case t.dollar:
  5987. case t.caret:
  5988. case t.openSquare:
  5989. case t.closeSquare:
  5990. case t.colon:
  5991. case t.semicolon:
  5992. case t.openParenthesis:
  5993. case t.closeParenthesis:
  5994. next = start;
  5995. tokenType = code;
  5996. endLine = line;
  5997. endColumn = start - offset;
  5998. end = next + 1;
  5999. break;
  6000. case t.singleQuote:
  6001. case t.doubleQuote:
  6002. quote = code === t.singleQuote ? "'" : '"';
  6003. next = start;
  6004. do {
  6005. escaped = false;
  6006. next = css.indexOf(quote, next + 1);
  6007. if (next === -1) {
  6008. unclosed('quote', quote);
  6009. }
  6010. escapePos = next;
  6011. while (css.charCodeAt(escapePos - 1) === t.backslash) {
  6012. escapePos -= 1;
  6013. escaped = !escaped;
  6014. }
  6015. } while (escaped);
  6016. tokenType = t.str;
  6017. endLine = line;
  6018. endColumn = start - offset;
  6019. end = next + 1;
  6020. break;
  6021. default:
  6022. if (code === t.slash && css.charCodeAt(start + 1) === t.asterisk) {
  6023. next = css.indexOf('*/', start + 2) + 1;
  6024. if (next === 0) {
  6025. unclosed('comment', '*/');
  6026. }
  6027. content = css.slice(start, next + 1);
  6028. lines = content.split('\n');
  6029. last = lines.length - 1;
  6030. if (last > 0) {
  6031. nextLine = line + last;
  6032. nextOffset = next - lines[last].length;
  6033. } else {
  6034. nextLine = line;
  6035. nextOffset = offset;
  6036. }
  6037. tokenType = t.comment;
  6038. line = nextLine;
  6039. endLine = nextLine;
  6040. endColumn = next - nextOffset;
  6041. } else if (code === t.slash) {
  6042. next = start;
  6043. tokenType = code;
  6044. endLine = line;
  6045. endColumn = start - offset;
  6046. end = next + 1;
  6047. } else {
  6048. next = consumeWord(css, start);
  6049. tokenType = t.word;
  6050. endLine = line;
  6051. endColumn = next - offset;
  6052. }
  6053. end = next + 1;
  6054. break;
  6055. }
  6056. // Ensure that the token structure remains consistent
  6057. tokens.push([tokenType,
  6058. // [0] Token type
  6059. line,
  6060. // [1] Starting line
  6061. start - offset,
  6062. // [2] Starting column
  6063. endLine,
  6064. // [3] Ending line
  6065. endColumn,
  6066. // [4] Ending column
  6067. start,
  6068. // [5] Start position / Source index
  6069. end // [6] End position
  6070. ]);
  6071. // Reset offset for the next token
  6072. if (nextOffset) {
  6073. offset = nextOffset;
  6074. nextOffset = null;
  6075. }
  6076. start = end;
  6077. }
  6078. return tokens;
  6079. }
  6080. } (tokenize));
  6081. return tokenize;
  6082. }
  6083. var hasRequiredParser$1;
  6084. function requireParser$1 () {
  6085. if (hasRequiredParser$1) return parser.exports;
  6086. hasRequiredParser$1 = 1;
  6087. (function (module, exports) {
  6088. exports.__esModule = true;
  6089. exports["default"] = void 0;
  6090. var _root = _interopRequireDefault(/*@__PURE__*/ requireRoot());
  6091. var _selector = _interopRequireDefault(/*@__PURE__*/ requireSelector());
  6092. var _className = _interopRequireDefault(/*@__PURE__*/ requireClassName());
  6093. var _comment = _interopRequireDefault(/*@__PURE__*/ requireComment());
  6094. var _id = _interopRequireDefault(/*@__PURE__*/ requireId());
  6095. var _tag = _interopRequireDefault(/*@__PURE__*/ requireTag());
  6096. var _string = _interopRequireDefault(/*@__PURE__*/ requireString());
  6097. var _pseudo = _interopRequireDefault(/*@__PURE__*/ requirePseudo());
  6098. var _attribute = _interopRequireWildcard(/*@__PURE__*/ requireAttribute());
  6099. var _universal = _interopRequireDefault(/*@__PURE__*/ requireUniversal());
  6100. var _combinator = _interopRequireDefault(/*@__PURE__*/ requireCombinator());
  6101. var _nesting = _interopRequireDefault(/*@__PURE__*/ requireNesting());
  6102. var _sortAscending = _interopRequireDefault(/*@__PURE__*/ requireSortAscending());
  6103. var _tokenize = _interopRequireWildcard(/*@__PURE__*/ requireTokenize());
  6104. var tokens = _interopRequireWildcard(/*@__PURE__*/ requireTokenTypes());
  6105. var types = _interopRequireWildcard(/*@__PURE__*/ requireTypes());
  6106. var _util = /*@__PURE__*/ requireUtil$1();
  6107. var _WHITESPACE_TOKENS, _Object$assign;
  6108. 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); }
  6109. 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; }
  6110. function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; }
  6111. 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); } }
  6112. function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); Object.defineProperty(Constructor, "prototype", { writable: false }); return Constructor; }
  6113. 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);
  6114. var WHITESPACE_EQUIV_TOKENS = Object.assign({}, WHITESPACE_TOKENS, (_Object$assign = {}, _Object$assign[tokens.comment] = true, _Object$assign));
  6115. function tokenStart(token) {
  6116. return {
  6117. line: token[_tokenize.FIELDS.START_LINE],
  6118. column: token[_tokenize.FIELDS.START_COL]
  6119. };
  6120. }
  6121. function tokenEnd(token) {
  6122. return {
  6123. line: token[_tokenize.FIELDS.END_LINE],
  6124. column: token[_tokenize.FIELDS.END_COL]
  6125. };
  6126. }
  6127. function getSource(startLine, startColumn, endLine, endColumn) {
  6128. return {
  6129. start: {
  6130. line: startLine,
  6131. column: startColumn
  6132. },
  6133. end: {
  6134. line: endLine,
  6135. column: endColumn
  6136. }
  6137. };
  6138. }
  6139. function getTokenSource(token) {
  6140. return getSource(token[_tokenize.FIELDS.START_LINE], token[_tokenize.FIELDS.START_COL], token[_tokenize.FIELDS.END_LINE], token[_tokenize.FIELDS.END_COL]);
  6141. }
  6142. function getTokenSourceSpan(startToken, endToken) {
  6143. if (!startToken) {
  6144. return undefined;
  6145. }
  6146. return getSource(startToken[_tokenize.FIELDS.START_LINE], startToken[_tokenize.FIELDS.START_COL], endToken[_tokenize.FIELDS.END_LINE], endToken[_tokenize.FIELDS.END_COL]);
  6147. }
  6148. function unescapeProp(node, prop) {
  6149. var value = node[prop];
  6150. if (typeof value !== "string") {
  6151. return;
  6152. }
  6153. if (value.indexOf("\\") !== -1) {
  6154. (0, _util.ensureObject)(node, 'raws');
  6155. node[prop] = (0, _util.unesc)(value);
  6156. if (node.raws[prop] === undefined) {
  6157. node.raws[prop] = value;
  6158. }
  6159. }
  6160. return node;
  6161. }
  6162. function indexesOf(array, item) {
  6163. var i = -1;
  6164. var indexes = [];
  6165. while ((i = array.indexOf(item, i + 1)) !== -1) {
  6166. indexes.push(i);
  6167. }
  6168. return indexes;
  6169. }
  6170. function uniqs() {
  6171. var list = Array.prototype.concat.apply([], arguments);
  6172. return list.filter(function (item, i) {
  6173. return i === list.indexOf(item);
  6174. });
  6175. }
  6176. var Parser = /*#__PURE__*/function () {
  6177. function Parser(rule, options) {
  6178. if (options === void 0) {
  6179. options = {};
  6180. }
  6181. this.rule = rule;
  6182. this.options = Object.assign({
  6183. lossy: false,
  6184. safe: false
  6185. }, options);
  6186. this.position = 0;
  6187. this.css = typeof this.rule === 'string' ? this.rule : this.rule.selector;
  6188. this.tokens = (0, _tokenize["default"])({
  6189. css: this.css,
  6190. error: this._errorGenerator(),
  6191. safe: this.options.safe
  6192. });
  6193. var rootSource = getTokenSourceSpan(this.tokens[0], this.tokens[this.tokens.length - 1]);
  6194. this.root = new _root["default"]({
  6195. source: rootSource
  6196. });
  6197. this.root.errorGenerator = this._errorGenerator();
  6198. var selector = new _selector["default"]({
  6199. source: {
  6200. start: {
  6201. line: 1,
  6202. column: 1
  6203. }
  6204. },
  6205. sourceIndex: 0
  6206. });
  6207. this.root.append(selector);
  6208. this.current = selector;
  6209. this.loop();
  6210. }
  6211. var _proto = Parser.prototype;
  6212. _proto._errorGenerator = function _errorGenerator() {
  6213. var _this = this;
  6214. return function (message, errorOptions) {
  6215. if (typeof _this.rule === 'string') {
  6216. return new Error(message);
  6217. }
  6218. return _this.rule.error(message, errorOptions);
  6219. };
  6220. };
  6221. _proto.attribute = function attribute() {
  6222. var attr = [];
  6223. var startingToken = this.currToken;
  6224. this.position++;
  6225. while (this.position < this.tokens.length && this.currToken[_tokenize.FIELDS.TYPE] !== tokens.closeSquare) {
  6226. attr.push(this.currToken);
  6227. this.position++;
  6228. }
  6229. if (this.currToken[_tokenize.FIELDS.TYPE] !== tokens.closeSquare) {
  6230. return this.expected('closing square bracket', this.currToken[_tokenize.FIELDS.START_POS]);
  6231. }
  6232. var len = attr.length;
  6233. var node = {
  6234. source: getSource(startingToken[1], startingToken[2], this.currToken[3], this.currToken[4]),
  6235. sourceIndex: startingToken[_tokenize.FIELDS.START_POS]
  6236. };
  6237. if (len === 1 && !~[tokens.word].indexOf(attr[0][_tokenize.FIELDS.TYPE])) {
  6238. return this.expected('attribute', attr[0][_tokenize.FIELDS.START_POS]);
  6239. }
  6240. var pos = 0;
  6241. var spaceBefore = '';
  6242. var commentBefore = '';
  6243. var lastAdded = null;
  6244. var spaceAfterMeaningfulToken = false;
  6245. while (pos < len) {
  6246. var token = attr[pos];
  6247. var content = this.content(token);
  6248. var next = attr[pos + 1];
  6249. switch (token[_tokenize.FIELDS.TYPE]) {
  6250. case tokens.space:
  6251. // if (
  6252. // len === 1 ||
  6253. // pos === 0 && this.content(next) === '|'
  6254. // ) {
  6255. // return this.expected('attribute', token[TOKEN.START_POS], content);
  6256. // }
  6257. spaceAfterMeaningfulToken = true;
  6258. if (this.options.lossy) {
  6259. break;
  6260. }
  6261. if (lastAdded) {
  6262. (0, _util.ensureObject)(node, 'spaces', lastAdded);
  6263. var prevContent = node.spaces[lastAdded].after || '';
  6264. node.spaces[lastAdded].after = prevContent + content;
  6265. var existingComment = (0, _util.getProp)(node, 'raws', 'spaces', lastAdded, 'after') || null;
  6266. if (existingComment) {
  6267. node.raws.spaces[lastAdded].after = existingComment + content;
  6268. }
  6269. } else {
  6270. spaceBefore = spaceBefore + content;
  6271. commentBefore = commentBefore + content;
  6272. }
  6273. break;
  6274. case tokens.asterisk:
  6275. if (next[_tokenize.FIELDS.TYPE] === tokens.equals) {
  6276. node.operator = content;
  6277. lastAdded = 'operator';
  6278. } else if ((!node.namespace || lastAdded === "namespace" && !spaceAfterMeaningfulToken) && next) {
  6279. if (spaceBefore) {
  6280. (0, _util.ensureObject)(node, 'spaces', 'attribute');
  6281. node.spaces.attribute.before = spaceBefore;
  6282. spaceBefore = '';
  6283. }
  6284. if (commentBefore) {
  6285. (0, _util.ensureObject)(node, 'raws', 'spaces', 'attribute');
  6286. node.raws.spaces.attribute.before = spaceBefore;
  6287. commentBefore = '';
  6288. }
  6289. node.namespace = (node.namespace || "") + content;
  6290. var rawValue = (0, _util.getProp)(node, 'raws', 'namespace') || null;
  6291. if (rawValue) {
  6292. node.raws.namespace += content;
  6293. }
  6294. lastAdded = 'namespace';
  6295. }
  6296. spaceAfterMeaningfulToken = false;
  6297. break;
  6298. case tokens.dollar:
  6299. if (lastAdded === "value") {
  6300. var oldRawValue = (0, _util.getProp)(node, 'raws', 'value');
  6301. node.value += "$";
  6302. if (oldRawValue) {
  6303. node.raws.value = oldRawValue + "$";
  6304. }
  6305. break;
  6306. }
  6307. // Falls through
  6308. case tokens.caret:
  6309. if (next[_tokenize.FIELDS.TYPE] === tokens.equals) {
  6310. node.operator = content;
  6311. lastAdded = 'operator';
  6312. }
  6313. spaceAfterMeaningfulToken = false;
  6314. break;
  6315. case tokens.combinator:
  6316. if (content === '~' && next[_tokenize.FIELDS.TYPE] === tokens.equals) {
  6317. node.operator = content;
  6318. lastAdded = 'operator';
  6319. }
  6320. if (content !== '|') {
  6321. spaceAfterMeaningfulToken = false;
  6322. break;
  6323. }
  6324. if (next[_tokenize.FIELDS.TYPE] === tokens.equals) {
  6325. node.operator = content;
  6326. lastAdded = 'operator';
  6327. } else if (!node.namespace && !node.attribute) {
  6328. node.namespace = true;
  6329. }
  6330. spaceAfterMeaningfulToken = false;
  6331. break;
  6332. case tokens.word:
  6333. if (next && this.content(next) === '|' && attr[pos + 2] && attr[pos + 2][_tokenize.FIELDS.TYPE] !== tokens.equals &&
  6334. // this look-ahead probably fails with comment nodes involved.
  6335. !node.operator && !node.namespace) {
  6336. node.namespace = content;
  6337. lastAdded = 'namespace';
  6338. } else if (!node.attribute || lastAdded === "attribute" && !spaceAfterMeaningfulToken) {
  6339. if (spaceBefore) {
  6340. (0, _util.ensureObject)(node, 'spaces', 'attribute');
  6341. node.spaces.attribute.before = spaceBefore;
  6342. spaceBefore = '';
  6343. }
  6344. if (commentBefore) {
  6345. (0, _util.ensureObject)(node, 'raws', 'spaces', 'attribute');
  6346. node.raws.spaces.attribute.before = commentBefore;
  6347. commentBefore = '';
  6348. }
  6349. node.attribute = (node.attribute || "") + content;
  6350. var _rawValue = (0, _util.getProp)(node, 'raws', 'attribute') || null;
  6351. if (_rawValue) {
  6352. node.raws.attribute += content;
  6353. }
  6354. lastAdded = 'attribute';
  6355. } else if (!node.value && node.value !== "" || lastAdded === "value" && !(spaceAfterMeaningfulToken || node.quoteMark)) {
  6356. var _unescaped = (0, _util.unesc)(content);
  6357. var _oldRawValue = (0, _util.getProp)(node, 'raws', 'value') || '';
  6358. var oldValue = node.value || '';
  6359. node.value = oldValue + _unescaped;
  6360. node.quoteMark = null;
  6361. if (_unescaped !== content || _oldRawValue) {
  6362. (0, _util.ensureObject)(node, 'raws');
  6363. node.raws.value = (_oldRawValue || oldValue) + content;
  6364. }
  6365. lastAdded = 'value';
  6366. } else {
  6367. var insensitive = content === 'i' || content === "I";
  6368. if ((node.value || node.value === '') && (node.quoteMark || spaceAfterMeaningfulToken)) {
  6369. node.insensitive = insensitive;
  6370. if (!insensitive || content === "I") {
  6371. (0, _util.ensureObject)(node, 'raws');
  6372. node.raws.insensitiveFlag = content;
  6373. }
  6374. lastAdded = 'insensitive';
  6375. if (spaceBefore) {
  6376. (0, _util.ensureObject)(node, 'spaces', 'insensitive');
  6377. node.spaces.insensitive.before = spaceBefore;
  6378. spaceBefore = '';
  6379. }
  6380. if (commentBefore) {
  6381. (0, _util.ensureObject)(node, 'raws', 'spaces', 'insensitive');
  6382. node.raws.spaces.insensitive.before = commentBefore;
  6383. commentBefore = '';
  6384. }
  6385. } else if (node.value || node.value === '') {
  6386. lastAdded = 'value';
  6387. node.value += content;
  6388. if (node.raws.value) {
  6389. node.raws.value += content;
  6390. }
  6391. }
  6392. }
  6393. spaceAfterMeaningfulToken = false;
  6394. break;
  6395. case tokens.str:
  6396. if (!node.attribute || !node.operator) {
  6397. return this.error("Expected an attribute followed by an operator preceding the string.", {
  6398. index: token[_tokenize.FIELDS.START_POS]
  6399. });
  6400. }
  6401. var _unescapeValue = (0, _attribute.unescapeValue)(content),
  6402. unescaped = _unescapeValue.unescaped,
  6403. quoteMark = _unescapeValue.quoteMark;
  6404. node.value = unescaped;
  6405. node.quoteMark = quoteMark;
  6406. lastAdded = 'value';
  6407. (0, _util.ensureObject)(node, 'raws');
  6408. node.raws.value = content;
  6409. spaceAfterMeaningfulToken = false;
  6410. break;
  6411. case tokens.equals:
  6412. if (!node.attribute) {
  6413. return this.expected('attribute', token[_tokenize.FIELDS.START_POS], content);
  6414. }
  6415. if (node.value) {
  6416. return this.error('Unexpected "=" found; an operator was already defined.', {
  6417. index: token[_tokenize.FIELDS.START_POS]
  6418. });
  6419. }
  6420. node.operator = node.operator ? node.operator + content : content;
  6421. lastAdded = 'operator';
  6422. spaceAfterMeaningfulToken = false;
  6423. break;
  6424. case tokens.comment:
  6425. if (lastAdded) {
  6426. if (spaceAfterMeaningfulToken || next && next[_tokenize.FIELDS.TYPE] === tokens.space || lastAdded === 'insensitive') {
  6427. var lastComment = (0, _util.getProp)(node, 'spaces', lastAdded, 'after') || '';
  6428. var rawLastComment = (0, _util.getProp)(node, 'raws', 'spaces', lastAdded, 'after') || lastComment;
  6429. (0, _util.ensureObject)(node, 'raws', 'spaces', lastAdded);
  6430. node.raws.spaces[lastAdded].after = rawLastComment + content;
  6431. } else {
  6432. var lastValue = node[lastAdded] || '';
  6433. var rawLastValue = (0, _util.getProp)(node, 'raws', lastAdded) || lastValue;
  6434. (0, _util.ensureObject)(node, 'raws');
  6435. node.raws[lastAdded] = rawLastValue + content;
  6436. }
  6437. } else {
  6438. commentBefore = commentBefore + content;
  6439. }
  6440. break;
  6441. default:
  6442. return this.error("Unexpected \"" + content + "\" found.", {
  6443. index: token[_tokenize.FIELDS.START_POS]
  6444. });
  6445. }
  6446. pos++;
  6447. }
  6448. unescapeProp(node, "attribute");
  6449. unescapeProp(node, "namespace");
  6450. this.newNode(new _attribute["default"](node));
  6451. this.position++;
  6452. }
  6453. /**
  6454. * return a node containing meaningless garbage up to (but not including) the specified token position.
  6455. * if the token position is negative, all remaining tokens are consumed.
  6456. *
  6457. * This returns an array containing a single string node if all whitespace,
  6458. * otherwise an array of comment nodes with space before and after.
  6459. *
  6460. * These tokens are not added to the current selector, the caller can add them or use them to amend
  6461. * a previous node's space metadata.
  6462. *
  6463. * In lossy mode, this returns only comments.
  6464. */;
  6465. _proto.parseWhitespaceEquivalentTokens = function parseWhitespaceEquivalentTokens(stopPosition) {
  6466. if (stopPosition < 0) {
  6467. stopPosition = this.tokens.length;
  6468. }
  6469. var startPosition = this.position;
  6470. var nodes = [];
  6471. var space = "";
  6472. var lastComment = undefined;
  6473. do {
  6474. if (WHITESPACE_TOKENS[this.currToken[_tokenize.FIELDS.TYPE]]) {
  6475. if (!this.options.lossy) {
  6476. space += this.content();
  6477. }
  6478. } else if (this.currToken[_tokenize.FIELDS.TYPE] === tokens.comment) {
  6479. var spaces = {};
  6480. if (space) {
  6481. spaces.before = space;
  6482. space = "";
  6483. }
  6484. lastComment = new _comment["default"]({
  6485. value: this.content(),
  6486. source: getTokenSource(this.currToken),
  6487. sourceIndex: this.currToken[_tokenize.FIELDS.START_POS],
  6488. spaces: spaces
  6489. });
  6490. nodes.push(lastComment);
  6491. }
  6492. } while (++this.position < stopPosition);
  6493. if (space) {
  6494. if (lastComment) {
  6495. lastComment.spaces.after = space;
  6496. } else if (!this.options.lossy) {
  6497. var firstToken = this.tokens[startPosition];
  6498. var lastToken = this.tokens[this.position - 1];
  6499. nodes.push(new _string["default"]({
  6500. value: '',
  6501. source: getSource(firstToken[_tokenize.FIELDS.START_LINE], firstToken[_tokenize.FIELDS.START_COL], lastToken[_tokenize.FIELDS.END_LINE], lastToken[_tokenize.FIELDS.END_COL]),
  6502. sourceIndex: firstToken[_tokenize.FIELDS.START_POS],
  6503. spaces: {
  6504. before: space,
  6505. after: ''
  6506. }
  6507. }));
  6508. }
  6509. }
  6510. return nodes;
  6511. }
  6512. /**
  6513. *
  6514. * @param {*} nodes
  6515. */;
  6516. _proto.convertWhitespaceNodesToSpace = function convertWhitespaceNodesToSpace(nodes, requiredSpace) {
  6517. var _this2 = this;
  6518. if (requiredSpace === void 0) {
  6519. requiredSpace = false;
  6520. }
  6521. var space = "";
  6522. var rawSpace = "";
  6523. nodes.forEach(function (n) {
  6524. var spaceBefore = _this2.lossySpace(n.spaces.before, requiredSpace);
  6525. var rawSpaceBefore = _this2.lossySpace(n.rawSpaceBefore, requiredSpace);
  6526. space += spaceBefore + _this2.lossySpace(n.spaces.after, requiredSpace && spaceBefore.length === 0);
  6527. rawSpace += spaceBefore + n.value + _this2.lossySpace(n.rawSpaceAfter, requiredSpace && rawSpaceBefore.length === 0);
  6528. });
  6529. if (rawSpace === space) {
  6530. rawSpace = undefined;
  6531. }
  6532. var result = {
  6533. space: space,
  6534. rawSpace: rawSpace
  6535. };
  6536. return result;
  6537. };
  6538. _proto.isNamedCombinator = function isNamedCombinator(position) {
  6539. if (position === void 0) {
  6540. position = this.position;
  6541. }
  6542. 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;
  6543. };
  6544. _proto.namedCombinator = function namedCombinator() {
  6545. if (this.isNamedCombinator()) {
  6546. var nameRaw = this.content(this.tokens[this.position + 1]);
  6547. var name = (0, _util.unesc)(nameRaw).toLowerCase();
  6548. var raws = {};
  6549. if (name !== nameRaw) {
  6550. raws.value = "/" + nameRaw + "/";
  6551. }
  6552. var node = new _combinator["default"]({
  6553. value: "/" + name + "/",
  6554. 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]),
  6555. sourceIndex: this.currToken[_tokenize.FIELDS.START_POS],
  6556. raws: raws
  6557. });
  6558. this.position = this.position + 3;
  6559. return node;
  6560. } else {
  6561. this.unexpected();
  6562. }
  6563. };
  6564. _proto.combinator = function combinator() {
  6565. var _this3 = this;
  6566. if (this.content() === '|') {
  6567. return this.namespace();
  6568. }
  6569. // We need to decide between a space that's a descendant combinator and meaningless whitespace at the end of a selector.
  6570. var nextSigTokenPos = this.locateNextMeaningfulToken(this.position);
  6571. if (nextSigTokenPos < 0 || this.tokens[nextSigTokenPos][_tokenize.FIELDS.TYPE] === tokens.comma || this.tokens[nextSigTokenPos][_tokenize.FIELDS.TYPE] === tokens.closeParenthesis) {
  6572. var nodes = this.parseWhitespaceEquivalentTokens(nextSigTokenPos);
  6573. if (nodes.length > 0) {
  6574. var last = this.current.last;
  6575. if (last) {
  6576. var _this$convertWhitespa = this.convertWhitespaceNodesToSpace(nodes),
  6577. space = _this$convertWhitespa.space,
  6578. rawSpace = _this$convertWhitespa.rawSpace;
  6579. if (rawSpace !== undefined) {
  6580. last.rawSpaceAfter += rawSpace;
  6581. }
  6582. last.spaces.after += space;
  6583. } else {
  6584. nodes.forEach(function (n) {
  6585. return _this3.newNode(n);
  6586. });
  6587. }
  6588. }
  6589. return;
  6590. }
  6591. var firstToken = this.currToken;
  6592. var spaceOrDescendantSelectorNodes = undefined;
  6593. if (nextSigTokenPos > this.position) {
  6594. spaceOrDescendantSelectorNodes = this.parseWhitespaceEquivalentTokens(nextSigTokenPos);
  6595. }
  6596. var node;
  6597. if (this.isNamedCombinator()) {
  6598. node = this.namedCombinator();
  6599. } else if (this.currToken[_tokenize.FIELDS.TYPE] === tokens.combinator) {
  6600. node = new _combinator["default"]({
  6601. value: this.content(),
  6602. source: getTokenSource(this.currToken),
  6603. sourceIndex: this.currToken[_tokenize.FIELDS.START_POS]
  6604. });
  6605. this.position++;
  6606. } else if (WHITESPACE_TOKENS[this.currToken[_tokenize.FIELDS.TYPE]]) ; else if (!spaceOrDescendantSelectorNodes) {
  6607. this.unexpected();
  6608. }
  6609. if (node) {
  6610. if (spaceOrDescendantSelectorNodes) {
  6611. var _this$convertWhitespa2 = this.convertWhitespaceNodesToSpace(spaceOrDescendantSelectorNodes),
  6612. _space = _this$convertWhitespa2.space,
  6613. _rawSpace = _this$convertWhitespa2.rawSpace;
  6614. node.spaces.before = _space;
  6615. node.rawSpaceBefore = _rawSpace;
  6616. }
  6617. } else {
  6618. // descendant combinator
  6619. var _this$convertWhitespa3 = this.convertWhitespaceNodesToSpace(spaceOrDescendantSelectorNodes, true),
  6620. _space2 = _this$convertWhitespa3.space,
  6621. _rawSpace2 = _this$convertWhitespa3.rawSpace;
  6622. if (!_rawSpace2) {
  6623. _rawSpace2 = _space2;
  6624. }
  6625. var spaces = {};
  6626. var raws = {
  6627. spaces: {}
  6628. };
  6629. if (_space2.endsWith(' ') && _rawSpace2.endsWith(' ')) {
  6630. spaces.before = _space2.slice(0, _space2.length - 1);
  6631. raws.spaces.before = _rawSpace2.slice(0, _rawSpace2.length - 1);
  6632. } else if (_space2.startsWith(' ') && _rawSpace2.startsWith(' ')) {
  6633. spaces.after = _space2.slice(1);
  6634. raws.spaces.after = _rawSpace2.slice(1);
  6635. } else {
  6636. raws.value = _rawSpace2;
  6637. }
  6638. node = new _combinator["default"]({
  6639. value: ' ',
  6640. source: getTokenSourceSpan(firstToken, this.tokens[this.position - 1]),
  6641. sourceIndex: firstToken[_tokenize.FIELDS.START_POS],
  6642. spaces: spaces,
  6643. raws: raws
  6644. });
  6645. }
  6646. if (this.currToken && this.currToken[_tokenize.FIELDS.TYPE] === tokens.space) {
  6647. node.spaces.after = this.optionalSpace(this.content());
  6648. this.position++;
  6649. }
  6650. return this.newNode(node);
  6651. };
  6652. _proto.comma = function comma() {
  6653. if (this.position === this.tokens.length - 1) {
  6654. this.root.trailingComma = true;
  6655. this.position++;
  6656. return;
  6657. }
  6658. this.current._inferEndPosition();
  6659. var selector = new _selector["default"]({
  6660. source: {
  6661. start: tokenStart(this.tokens[this.position + 1])
  6662. },
  6663. sourceIndex: this.tokens[this.position + 1][_tokenize.FIELDS.START_POS]
  6664. });
  6665. this.current.parent.append(selector);
  6666. this.current = selector;
  6667. this.position++;
  6668. };
  6669. _proto.comment = function comment() {
  6670. var current = this.currToken;
  6671. this.newNode(new _comment["default"]({
  6672. value: this.content(),
  6673. source: getTokenSource(current),
  6674. sourceIndex: current[_tokenize.FIELDS.START_POS]
  6675. }));
  6676. this.position++;
  6677. };
  6678. _proto.error = function error(message, opts) {
  6679. throw this.root.error(message, opts);
  6680. };
  6681. _proto.missingBackslash = function missingBackslash() {
  6682. return this.error('Expected a backslash preceding the semicolon.', {
  6683. index: this.currToken[_tokenize.FIELDS.START_POS]
  6684. });
  6685. };
  6686. _proto.missingParenthesis = function missingParenthesis() {
  6687. return this.expected('opening parenthesis', this.currToken[_tokenize.FIELDS.START_POS]);
  6688. };
  6689. _proto.missingSquareBracket = function missingSquareBracket() {
  6690. return this.expected('opening square bracket', this.currToken[_tokenize.FIELDS.START_POS]);
  6691. };
  6692. _proto.unexpected = function unexpected() {
  6693. return this.error("Unexpected '" + this.content() + "'. Escaping special characters with \\ may help.", this.currToken[_tokenize.FIELDS.START_POS]);
  6694. };
  6695. _proto.unexpectedPipe = function unexpectedPipe() {
  6696. return this.error("Unexpected '|'.", this.currToken[_tokenize.FIELDS.START_POS]);
  6697. };
  6698. _proto.namespace = function namespace() {
  6699. var before = this.prevToken && this.content(this.prevToken) || true;
  6700. if (this.nextToken[_tokenize.FIELDS.TYPE] === tokens.word) {
  6701. this.position++;
  6702. return this.word(before);
  6703. } else if (this.nextToken[_tokenize.FIELDS.TYPE] === tokens.asterisk) {
  6704. this.position++;
  6705. return this.universal(before);
  6706. }
  6707. this.unexpectedPipe();
  6708. };
  6709. _proto.nesting = function nesting() {
  6710. if (this.nextToken) {
  6711. var nextContent = this.content(this.nextToken);
  6712. if (nextContent === "|") {
  6713. this.position++;
  6714. return;
  6715. }
  6716. }
  6717. var current = this.currToken;
  6718. this.newNode(new _nesting["default"]({
  6719. value: this.content(),
  6720. source: getTokenSource(current),
  6721. sourceIndex: current[_tokenize.FIELDS.START_POS]
  6722. }));
  6723. this.position++;
  6724. };
  6725. _proto.parentheses = function parentheses() {
  6726. var last = this.current.last;
  6727. var unbalanced = 1;
  6728. this.position++;
  6729. if (last && last.type === types.PSEUDO) {
  6730. var selector = new _selector["default"]({
  6731. source: {
  6732. start: tokenStart(this.tokens[this.position])
  6733. },
  6734. sourceIndex: this.tokens[this.position][_tokenize.FIELDS.START_POS]
  6735. });
  6736. var cache = this.current;
  6737. last.append(selector);
  6738. this.current = selector;
  6739. while (this.position < this.tokens.length && unbalanced) {
  6740. if (this.currToken[_tokenize.FIELDS.TYPE] === tokens.openParenthesis) {
  6741. unbalanced++;
  6742. }
  6743. if (this.currToken[_tokenize.FIELDS.TYPE] === tokens.closeParenthesis) {
  6744. unbalanced--;
  6745. }
  6746. if (unbalanced) {
  6747. this.parse();
  6748. } else {
  6749. this.current.source.end = tokenEnd(this.currToken);
  6750. this.current.parent.source.end = tokenEnd(this.currToken);
  6751. this.position++;
  6752. }
  6753. }
  6754. this.current = cache;
  6755. } else {
  6756. // I think this case should be an error. It's used to implement a basic parse of media queries
  6757. // but I don't think it's a good idea.
  6758. var parenStart = this.currToken;
  6759. var parenValue = "(";
  6760. var parenEnd;
  6761. while (this.position < this.tokens.length && unbalanced) {
  6762. if (this.currToken[_tokenize.FIELDS.TYPE] === tokens.openParenthesis) {
  6763. unbalanced++;
  6764. }
  6765. if (this.currToken[_tokenize.FIELDS.TYPE] === tokens.closeParenthesis) {
  6766. unbalanced--;
  6767. }
  6768. parenEnd = this.currToken;
  6769. parenValue += this.parseParenthesisToken(this.currToken);
  6770. this.position++;
  6771. }
  6772. if (last) {
  6773. last.appendToPropertyAndEscape("value", parenValue, parenValue);
  6774. } else {
  6775. this.newNode(new _string["default"]({
  6776. value: parenValue,
  6777. source: getSource(parenStart[_tokenize.FIELDS.START_LINE], parenStart[_tokenize.FIELDS.START_COL], parenEnd[_tokenize.FIELDS.END_LINE], parenEnd[_tokenize.FIELDS.END_COL]),
  6778. sourceIndex: parenStart[_tokenize.FIELDS.START_POS]
  6779. }));
  6780. }
  6781. }
  6782. if (unbalanced) {
  6783. return this.expected('closing parenthesis', this.currToken[_tokenize.FIELDS.START_POS]);
  6784. }
  6785. };
  6786. _proto.pseudo = function pseudo() {
  6787. var _this4 = this;
  6788. var pseudoStr = '';
  6789. var startingToken = this.currToken;
  6790. while (this.currToken && this.currToken[_tokenize.FIELDS.TYPE] === tokens.colon) {
  6791. pseudoStr += this.content();
  6792. this.position++;
  6793. }
  6794. if (!this.currToken) {
  6795. return this.expected(['pseudo-class', 'pseudo-element'], this.position - 1);
  6796. }
  6797. if (this.currToken[_tokenize.FIELDS.TYPE] === tokens.word) {
  6798. this.splitWord(false, function (first, length) {
  6799. pseudoStr += first;
  6800. _this4.newNode(new _pseudo["default"]({
  6801. value: pseudoStr,
  6802. source: getTokenSourceSpan(startingToken, _this4.currToken),
  6803. sourceIndex: startingToken[_tokenize.FIELDS.START_POS]
  6804. }));
  6805. if (length > 1 && _this4.nextToken && _this4.nextToken[_tokenize.FIELDS.TYPE] === tokens.openParenthesis) {
  6806. _this4.error('Misplaced parenthesis.', {
  6807. index: _this4.nextToken[_tokenize.FIELDS.START_POS]
  6808. });
  6809. }
  6810. });
  6811. } else {
  6812. return this.expected(['pseudo-class', 'pseudo-element'], this.currToken[_tokenize.FIELDS.START_POS]);
  6813. }
  6814. };
  6815. _proto.space = function space() {
  6816. var content = this.content();
  6817. // Handle space before and after the selector
  6818. if (this.position === 0 || this.prevToken[_tokenize.FIELDS.TYPE] === tokens.comma || this.prevToken[_tokenize.FIELDS.TYPE] === tokens.openParenthesis || this.current.nodes.every(function (node) {
  6819. return node.type === 'comment';
  6820. })) {
  6821. this.spaces = this.optionalSpace(content);
  6822. this.position++;
  6823. } else if (this.position === this.tokens.length - 1 || this.nextToken[_tokenize.FIELDS.TYPE] === tokens.comma || this.nextToken[_tokenize.FIELDS.TYPE] === tokens.closeParenthesis) {
  6824. this.current.last.spaces.after = this.optionalSpace(content);
  6825. this.position++;
  6826. } else {
  6827. this.combinator();
  6828. }
  6829. };
  6830. _proto.string = function string() {
  6831. var current = this.currToken;
  6832. this.newNode(new _string["default"]({
  6833. value: this.content(),
  6834. source: getTokenSource(current),
  6835. sourceIndex: current[_tokenize.FIELDS.START_POS]
  6836. }));
  6837. this.position++;
  6838. };
  6839. _proto.universal = function universal(namespace) {
  6840. var nextToken = this.nextToken;
  6841. if (nextToken && this.content(nextToken) === '|') {
  6842. this.position++;
  6843. return this.namespace();
  6844. }
  6845. var current = this.currToken;
  6846. this.newNode(new _universal["default"]({
  6847. value: this.content(),
  6848. source: getTokenSource(current),
  6849. sourceIndex: current[_tokenize.FIELDS.START_POS]
  6850. }), namespace);
  6851. this.position++;
  6852. };
  6853. _proto.splitWord = function splitWord(namespace, firstCallback) {
  6854. var _this5 = this;
  6855. var nextToken = this.nextToken;
  6856. var word = this.content();
  6857. while (nextToken && ~[tokens.dollar, tokens.caret, tokens.equals, tokens.word].indexOf(nextToken[_tokenize.FIELDS.TYPE])) {
  6858. this.position++;
  6859. var current = this.content();
  6860. word += current;
  6861. if (current.lastIndexOf('\\') === current.length - 1) {
  6862. var next = this.nextToken;
  6863. if (next && next[_tokenize.FIELDS.TYPE] === tokens.space) {
  6864. word += this.requiredSpace(this.content(next));
  6865. this.position++;
  6866. }
  6867. }
  6868. nextToken = this.nextToken;
  6869. }
  6870. var hasClass = indexesOf(word, '.').filter(function (i) {
  6871. // Allow escaped dot within class name
  6872. var escapedDot = word[i - 1] === '\\';
  6873. // Allow decimal numbers percent in @keyframes
  6874. var isKeyframesPercent = /^\d+\.\d+%$/.test(word);
  6875. return !escapedDot && !isKeyframesPercent;
  6876. });
  6877. var hasId = indexesOf(word, '#').filter(function (i) {
  6878. return word[i - 1] !== '\\';
  6879. });
  6880. // Eliminate Sass interpolations from the list of id indexes
  6881. var interpolations = indexesOf(word, '#{');
  6882. if (interpolations.length) {
  6883. hasId = hasId.filter(function (hashIndex) {
  6884. return !~interpolations.indexOf(hashIndex);
  6885. });
  6886. }
  6887. var indices = (0, _sortAscending["default"])(uniqs([0].concat(hasClass, hasId)));
  6888. indices.forEach(function (ind, i) {
  6889. var index = indices[i + 1] || word.length;
  6890. var value = word.slice(ind, index);
  6891. if (i === 0 && firstCallback) {
  6892. return firstCallback.call(_this5, value, indices.length);
  6893. }
  6894. var node;
  6895. var current = _this5.currToken;
  6896. var sourceIndex = current[_tokenize.FIELDS.START_POS] + indices[i];
  6897. var source = getSource(current[1], current[2] + ind, current[3], current[2] + (index - 1));
  6898. if (~hasClass.indexOf(ind)) {
  6899. var classNameOpts = {
  6900. value: value.slice(1),
  6901. source: source,
  6902. sourceIndex: sourceIndex
  6903. };
  6904. node = new _className["default"](unescapeProp(classNameOpts, "value"));
  6905. } else if (~hasId.indexOf(ind)) {
  6906. var idOpts = {
  6907. value: value.slice(1),
  6908. source: source,
  6909. sourceIndex: sourceIndex
  6910. };
  6911. node = new _id["default"](unescapeProp(idOpts, "value"));
  6912. } else {
  6913. var tagOpts = {
  6914. value: value,
  6915. source: source,
  6916. sourceIndex: sourceIndex
  6917. };
  6918. unescapeProp(tagOpts, "value");
  6919. node = new _tag["default"](tagOpts);
  6920. }
  6921. _this5.newNode(node, namespace);
  6922. // Ensure that the namespace is used only once
  6923. namespace = null;
  6924. });
  6925. this.position++;
  6926. };
  6927. _proto.word = function word(namespace) {
  6928. var nextToken = this.nextToken;
  6929. if (nextToken && this.content(nextToken) === '|') {
  6930. this.position++;
  6931. return this.namespace();
  6932. }
  6933. return this.splitWord(namespace);
  6934. };
  6935. _proto.loop = function loop() {
  6936. while (this.position < this.tokens.length) {
  6937. this.parse(true);
  6938. }
  6939. this.current._inferEndPosition();
  6940. return this.root;
  6941. };
  6942. _proto.parse = function parse(throwOnParenthesis) {
  6943. switch (this.currToken[_tokenize.FIELDS.TYPE]) {
  6944. case tokens.space:
  6945. this.space();
  6946. break;
  6947. case tokens.comment:
  6948. this.comment();
  6949. break;
  6950. case tokens.openParenthesis:
  6951. this.parentheses();
  6952. break;
  6953. case tokens.closeParenthesis:
  6954. if (throwOnParenthesis) {
  6955. this.missingParenthesis();
  6956. }
  6957. break;
  6958. case tokens.openSquare:
  6959. this.attribute();
  6960. break;
  6961. case tokens.dollar:
  6962. case tokens.caret:
  6963. case tokens.equals:
  6964. case tokens.word:
  6965. this.word();
  6966. break;
  6967. case tokens.colon:
  6968. this.pseudo();
  6969. break;
  6970. case tokens.comma:
  6971. this.comma();
  6972. break;
  6973. case tokens.asterisk:
  6974. this.universal();
  6975. break;
  6976. case tokens.ampersand:
  6977. this.nesting();
  6978. break;
  6979. case tokens.slash:
  6980. case tokens.combinator:
  6981. this.combinator();
  6982. break;
  6983. case tokens.str:
  6984. this.string();
  6985. break;
  6986. // These cases throw; no break needed.
  6987. case tokens.closeSquare:
  6988. this.missingSquareBracket();
  6989. case tokens.semicolon:
  6990. this.missingBackslash();
  6991. default:
  6992. this.unexpected();
  6993. }
  6994. }
  6995. /**
  6996. * Helpers
  6997. */;
  6998. _proto.expected = function expected(description, index, found) {
  6999. if (Array.isArray(description)) {
  7000. var last = description.pop();
  7001. description = description.join(', ') + " or " + last;
  7002. }
  7003. var an = /^[aeiou]/.test(description[0]) ? 'an' : 'a';
  7004. if (!found) {
  7005. return this.error("Expected " + an + " " + description + ".", {
  7006. index: index
  7007. });
  7008. }
  7009. return this.error("Expected " + an + " " + description + ", found \"" + found + "\" instead.", {
  7010. index: index
  7011. });
  7012. };
  7013. _proto.requiredSpace = function requiredSpace(space) {
  7014. return this.options.lossy ? ' ' : space;
  7015. };
  7016. _proto.optionalSpace = function optionalSpace(space) {
  7017. return this.options.lossy ? '' : space;
  7018. };
  7019. _proto.lossySpace = function lossySpace(space, required) {
  7020. if (this.options.lossy) {
  7021. return required ? ' ' : '';
  7022. } else {
  7023. return space;
  7024. }
  7025. };
  7026. _proto.parseParenthesisToken = function parseParenthesisToken(token) {
  7027. var content = this.content(token);
  7028. if (token[_tokenize.FIELDS.TYPE] === tokens.space) {
  7029. return this.requiredSpace(content);
  7030. } else {
  7031. return content;
  7032. }
  7033. };
  7034. _proto.newNode = function newNode(node, namespace) {
  7035. if (namespace) {
  7036. if (/^ +$/.test(namespace)) {
  7037. if (!this.options.lossy) {
  7038. this.spaces = (this.spaces || '') + namespace;
  7039. }
  7040. namespace = true;
  7041. }
  7042. node.namespace = namespace;
  7043. unescapeProp(node, "namespace");
  7044. }
  7045. if (this.spaces) {
  7046. node.spaces.before = this.spaces;
  7047. this.spaces = '';
  7048. }
  7049. return this.current.append(node);
  7050. };
  7051. _proto.content = function content(token) {
  7052. if (token === void 0) {
  7053. token = this.currToken;
  7054. }
  7055. return this.css.slice(token[_tokenize.FIELDS.START_POS], token[_tokenize.FIELDS.END_POS]);
  7056. };
  7057. /**
  7058. * returns the index of the next non-whitespace, non-comment token.
  7059. * returns -1 if no meaningful token is found.
  7060. */
  7061. _proto.locateNextMeaningfulToken = function locateNextMeaningfulToken(startPosition) {
  7062. if (startPosition === void 0) {
  7063. startPosition = this.position + 1;
  7064. }
  7065. var searchPosition = startPosition;
  7066. while (searchPosition < this.tokens.length) {
  7067. if (WHITESPACE_EQUIV_TOKENS[this.tokens[searchPosition][_tokenize.FIELDS.TYPE]]) {
  7068. searchPosition++;
  7069. continue;
  7070. } else {
  7071. return searchPosition;
  7072. }
  7073. }
  7074. return -1;
  7075. };
  7076. _createClass(Parser, [{
  7077. key: "currToken",
  7078. get: function get() {
  7079. return this.tokens[this.position];
  7080. }
  7081. }, {
  7082. key: "nextToken",
  7083. get: function get() {
  7084. return this.tokens[this.position + 1];
  7085. }
  7086. }, {
  7087. key: "prevToken",
  7088. get: function get() {
  7089. return this.tokens[this.position - 1];
  7090. }
  7091. }]);
  7092. return Parser;
  7093. }();
  7094. exports["default"] = Parser;
  7095. module.exports = exports.default;
  7096. } (parser, parser.exports));
  7097. return parser.exports;
  7098. }
  7099. var hasRequiredProcessor;
  7100. function requireProcessor () {
  7101. if (hasRequiredProcessor) return processor.exports;
  7102. hasRequiredProcessor = 1;
  7103. (function (module, exports) {
  7104. exports.__esModule = true;
  7105. exports["default"] = void 0;
  7106. var _parser = _interopRequireDefault(/*@__PURE__*/ requireParser$1());
  7107. function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; }
  7108. var Processor = /*#__PURE__*/function () {
  7109. function Processor(func, options) {
  7110. this.func = func || function noop() {};
  7111. this.funcRes = null;
  7112. this.options = options;
  7113. }
  7114. var _proto = Processor.prototype;
  7115. _proto._shouldUpdateSelector = function _shouldUpdateSelector(rule, options) {
  7116. if (options === void 0) {
  7117. options = {};
  7118. }
  7119. var merged = Object.assign({}, this.options, options);
  7120. if (merged.updateSelector === false) {
  7121. return false;
  7122. } else {
  7123. return typeof rule !== "string";
  7124. }
  7125. };
  7126. _proto._isLossy = function _isLossy(options) {
  7127. if (options === void 0) {
  7128. options = {};
  7129. }
  7130. var merged = Object.assign({}, this.options, options);
  7131. if (merged.lossless === false) {
  7132. return true;
  7133. } else {
  7134. return false;
  7135. }
  7136. };
  7137. _proto._root = function _root(rule, options) {
  7138. if (options === void 0) {
  7139. options = {};
  7140. }
  7141. var parser = new _parser["default"](rule, this._parseOptions(options));
  7142. return parser.root;
  7143. };
  7144. _proto._parseOptions = function _parseOptions(options) {
  7145. return {
  7146. lossy: this._isLossy(options)
  7147. };
  7148. };
  7149. _proto._run = function _run(rule, options) {
  7150. var _this = this;
  7151. if (options === void 0) {
  7152. options = {};
  7153. }
  7154. return new Promise(function (resolve, reject) {
  7155. try {
  7156. var root = _this._root(rule, options);
  7157. Promise.resolve(_this.func(root)).then(function (transform) {
  7158. var string = undefined;
  7159. if (_this._shouldUpdateSelector(rule, options)) {
  7160. string = root.toString();
  7161. rule.selector = string;
  7162. }
  7163. return {
  7164. transform: transform,
  7165. root: root,
  7166. string: string
  7167. };
  7168. }).then(resolve, reject);
  7169. } catch (e) {
  7170. reject(e);
  7171. return;
  7172. }
  7173. });
  7174. };
  7175. _proto._runSync = function _runSync(rule, options) {
  7176. if (options === void 0) {
  7177. options = {};
  7178. }
  7179. var root = this._root(rule, options);
  7180. var transform = this.func(root);
  7181. if (transform && typeof transform.then === "function") {
  7182. throw new Error("Selector processor returned a promise to a synchronous call.");
  7183. }
  7184. var string = undefined;
  7185. if (options.updateSelector && typeof rule !== "string") {
  7186. string = root.toString();
  7187. rule.selector = string;
  7188. }
  7189. return {
  7190. transform: transform,
  7191. root: root,
  7192. string: string
  7193. };
  7194. }
  7195. /**
  7196. * Process rule into a selector AST.
  7197. *
  7198. * @param rule {postcss.Rule | string} The css selector to be processed
  7199. * @param options The options for processing
  7200. * @returns {Promise<parser.Root>} The AST of the selector after processing it.
  7201. */;
  7202. _proto.ast = function ast(rule, options) {
  7203. return this._run(rule, options).then(function (result) {
  7204. return result.root;
  7205. });
  7206. }
  7207. /**
  7208. * Process rule into a selector AST synchronously.
  7209. *
  7210. * @param rule {postcss.Rule | string} The css selector to be processed
  7211. * @param options The options for processing
  7212. * @returns {parser.Root} The AST of the selector after processing it.
  7213. */;
  7214. _proto.astSync = function astSync(rule, options) {
  7215. return this._runSync(rule, options).root;
  7216. }
  7217. /**
  7218. * Process a selector into a transformed value asynchronously
  7219. *
  7220. * @param rule {postcss.Rule | string} The css selector to be processed
  7221. * @param options The options for processing
  7222. * @returns {Promise<any>} The value returned by the processor.
  7223. */;
  7224. _proto.transform = function transform(rule, options) {
  7225. return this._run(rule, options).then(function (result) {
  7226. return result.transform;
  7227. });
  7228. }
  7229. /**
  7230. * Process a selector into a transformed value synchronously.
  7231. *
  7232. * @param rule {postcss.Rule | string} The css selector to be processed
  7233. * @param options The options for processing
  7234. * @returns {any} The value returned by the processor.
  7235. */;
  7236. _proto.transformSync = function transformSync(rule, options) {
  7237. return this._runSync(rule, options).transform;
  7238. }
  7239. /**
  7240. * Process a selector into a new selector string asynchronously.
  7241. *
  7242. * @param rule {postcss.Rule | string} The css selector to be processed
  7243. * @param options The options for processing
  7244. * @returns {string} the selector after processing.
  7245. */;
  7246. _proto.process = function process(rule, options) {
  7247. return this._run(rule, options).then(function (result) {
  7248. return result.string || result.root.toString();
  7249. });
  7250. }
  7251. /**
  7252. * Process a selector into a new selector string synchronously.
  7253. *
  7254. * @param rule {postcss.Rule | string} The css selector to be processed
  7255. * @param options The options for processing
  7256. * @returns {string} the selector after processing.
  7257. */;
  7258. _proto.processSync = function processSync(rule, options) {
  7259. var result = this._runSync(rule, options);
  7260. return result.string || result.root.toString();
  7261. };
  7262. return Processor;
  7263. }();
  7264. exports["default"] = Processor;
  7265. module.exports = exports.default;
  7266. } (processor, processor.exports));
  7267. return processor.exports;
  7268. }
  7269. var selectors = {};
  7270. var constructors = {};
  7271. var hasRequiredConstructors;
  7272. function requireConstructors () {
  7273. if (hasRequiredConstructors) return constructors;
  7274. hasRequiredConstructors = 1;
  7275. constructors.__esModule = true;
  7276. 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;
  7277. var _attribute = _interopRequireDefault(/*@__PURE__*/ requireAttribute());
  7278. var _className = _interopRequireDefault(/*@__PURE__*/ requireClassName());
  7279. var _combinator = _interopRequireDefault(/*@__PURE__*/ requireCombinator());
  7280. var _comment = _interopRequireDefault(/*@__PURE__*/ requireComment());
  7281. var _id = _interopRequireDefault(/*@__PURE__*/ requireId());
  7282. var _nesting = _interopRequireDefault(/*@__PURE__*/ requireNesting());
  7283. var _pseudo = _interopRequireDefault(/*@__PURE__*/ requirePseudo());
  7284. var _root = _interopRequireDefault(/*@__PURE__*/ requireRoot());
  7285. var _selector = _interopRequireDefault(/*@__PURE__*/ requireSelector());
  7286. var _string = _interopRequireDefault(/*@__PURE__*/ requireString());
  7287. var _tag = _interopRequireDefault(/*@__PURE__*/ requireTag());
  7288. var _universal = _interopRequireDefault(/*@__PURE__*/ requireUniversal());
  7289. function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; }
  7290. var attribute = function attribute(opts) {
  7291. return new _attribute["default"](opts);
  7292. };
  7293. constructors.attribute = attribute;
  7294. var className = function className(opts) {
  7295. return new _className["default"](opts);
  7296. };
  7297. constructors.className = className;
  7298. var combinator = function combinator(opts) {
  7299. return new _combinator["default"](opts);
  7300. };
  7301. constructors.combinator = combinator;
  7302. var comment = function comment(opts) {
  7303. return new _comment["default"](opts);
  7304. };
  7305. constructors.comment = comment;
  7306. var id = function id(opts) {
  7307. return new _id["default"](opts);
  7308. };
  7309. constructors.id = id;
  7310. var nesting = function nesting(opts) {
  7311. return new _nesting["default"](opts);
  7312. };
  7313. constructors.nesting = nesting;
  7314. var pseudo = function pseudo(opts) {
  7315. return new _pseudo["default"](opts);
  7316. };
  7317. constructors.pseudo = pseudo;
  7318. var root = function root(opts) {
  7319. return new _root["default"](opts);
  7320. };
  7321. constructors.root = root;
  7322. var selector = function selector(opts) {
  7323. return new _selector["default"](opts);
  7324. };
  7325. constructors.selector = selector;
  7326. var string = function string(opts) {
  7327. return new _string["default"](opts);
  7328. };
  7329. constructors.string = string;
  7330. var tag = function tag(opts) {
  7331. return new _tag["default"](opts);
  7332. };
  7333. constructors.tag = tag;
  7334. var universal = function universal(opts) {
  7335. return new _universal["default"](opts);
  7336. };
  7337. constructors.universal = universal;
  7338. return constructors;
  7339. }
  7340. var guards = {};
  7341. var hasRequiredGuards;
  7342. function requireGuards () {
  7343. if (hasRequiredGuards) return guards;
  7344. hasRequiredGuards = 1;
  7345. guards.__esModule = true;
  7346. guards.isComment = guards.isCombinator = guards.isClassName = guards.isAttribute = void 0;
  7347. guards.isContainer = isContainer;
  7348. guards.isIdentifier = void 0;
  7349. guards.isNamespace = isNamespace;
  7350. guards.isNesting = void 0;
  7351. guards.isNode = isNode;
  7352. guards.isPseudo = void 0;
  7353. guards.isPseudoClass = isPseudoClass;
  7354. guards.isPseudoElement = isPseudoElement;
  7355. guards.isUniversal = guards.isTag = guards.isString = guards.isSelector = guards.isRoot = void 0;
  7356. var _types = /*@__PURE__*/ requireTypes();
  7357. var _IS_TYPE;
  7358. 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);
  7359. function isNode(node) {
  7360. return typeof node === "object" && IS_TYPE[node.type];
  7361. }
  7362. function isNodeType(type, node) {
  7363. return isNode(node) && node.type === type;
  7364. }
  7365. var isAttribute = isNodeType.bind(null, _types.ATTRIBUTE);
  7366. guards.isAttribute = isAttribute;
  7367. var isClassName = isNodeType.bind(null, _types.CLASS);
  7368. guards.isClassName = isClassName;
  7369. var isCombinator = isNodeType.bind(null, _types.COMBINATOR);
  7370. guards.isCombinator = isCombinator;
  7371. var isComment = isNodeType.bind(null, _types.COMMENT);
  7372. guards.isComment = isComment;
  7373. var isIdentifier = isNodeType.bind(null, _types.ID);
  7374. guards.isIdentifier = isIdentifier;
  7375. var isNesting = isNodeType.bind(null, _types.NESTING);
  7376. guards.isNesting = isNesting;
  7377. var isPseudo = isNodeType.bind(null, _types.PSEUDO);
  7378. guards.isPseudo = isPseudo;
  7379. var isRoot = isNodeType.bind(null, _types.ROOT);
  7380. guards.isRoot = isRoot;
  7381. var isSelector = isNodeType.bind(null, _types.SELECTOR);
  7382. guards.isSelector = isSelector;
  7383. var isString = isNodeType.bind(null, _types.STRING);
  7384. guards.isString = isString;
  7385. var isTag = isNodeType.bind(null, _types.TAG);
  7386. guards.isTag = isTag;
  7387. var isUniversal = isNodeType.bind(null, _types.UNIVERSAL);
  7388. guards.isUniversal = isUniversal;
  7389. function isPseudoElement(node) {
  7390. 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");
  7391. }
  7392. function isPseudoClass(node) {
  7393. return isPseudo(node) && !isPseudoElement(node);
  7394. }
  7395. function isContainer(node) {
  7396. return !!(isNode(node) && node.walk);
  7397. }
  7398. function isNamespace(node) {
  7399. return isAttribute(node) || isTag(node);
  7400. }
  7401. return guards;
  7402. }
  7403. var hasRequiredSelectors;
  7404. function requireSelectors () {
  7405. if (hasRequiredSelectors) return selectors;
  7406. hasRequiredSelectors = 1;
  7407. (function (exports) {
  7408. exports.__esModule = true;
  7409. var _types = /*@__PURE__*/ requireTypes();
  7410. Object.keys(_types).forEach(function (key) {
  7411. if (key === "default" || key === "__esModule") return;
  7412. if (key in exports && exports[key] === _types[key]) return;
  7413. exports[key] = _types[key];
  7414. });
  7415. var _constructors = /*@__PURE__*/ requireConstructors();
  7416. Object.keys(_constructors).forEach(function (key) {
  7417. if (key === "default" || key === "__esModule") return;
  7418. if (key in exports && exports[key] === _constructors[key]) return;
  7419. exports[key] = _constructors[key];
  7420. });
  7421. var _guards = /*@__PURE__*/ requireGuards();
  7422. Object.keys(_guards).forEach(function (key) {
  7423. if (key === "default" || key === "__esModule") return;
  7424. if (key in exports && exports[key] === _guards[key]) return;
  7425. exports[key] = _guards[key];
  7426. });
  7427. } (selectors));
  7428. return selectors;
  7429. }
  7430. var hasRequiredDist;
  7431. function requireDist () {
  7432. if (hasRequiredDist) return dist.exports;
  7433. hasRequiredDist = 1;
  7434. (function (module, exports) {
  7435. exports.__esModule = true;
  7436. exports["default"] = void 0;
  7437. var _processor = _interopRequireDefault(/*@__PURE__*/ requireProcessor());
  7438. var selectors = _interopRequireWildcard(/*@__PURE__*/ requireSelectors());
  7439. 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); }
  7440. 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; }
  7441. function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; }
  7442. var parser = function parser(processor) {
  7443. return new _processor["default"](processor);
  7444. };
  7445. Object.assign(parser, selectors);
  7446. delete parser.__esModule;
  7447. var _default = parser;
  7448. exports["default"] = _default;
  7449. module.exports = exports.default;
  7450. } (dist, dist.exports));
  7451. return dist.exports;
  7452. }
  7453. var distExports = /*@__PURE__*/ requireDist();
  7454. var selectorParser = /*@__PURE__*/getDefaultExportFromCjs(distExports);
  7455. const animationNameRE = /^(-\w+-)?animation-name$/;
  7456. const animationRE = /^(-\w+-)?animation$/;
  7457. const scopedPlugin = (id = "") => {
  7458. const keyframes = /* @__PURE__ */ Object.create(null);
  7459. const shortId = id.replace(/^data-v-/, "");
  7460. return {
  7461. postcssPlugin: "vue-sfc-scoped",
  7462. Rule(rule) {
  7463. processRule(id, rule);
  7464. },
  7465. AtRule(node) {
  7466. if (/-?keyframes$/.test(node.name) && !node.params.endsWith(`-${shortId}`)) {
  7467. keyframes[node.params] = node.params = node.params + "-" + shortId;
  7468. }
  7469. },
  7470. OnceExit(root) {
  7471. if (Object.keys(keyframes).length) {
  7472. root.walkDecls((decl) => {
  7473. if (animationNameRE.test(decl.prop)) {
  7474. decl.value = decl.value.split(",").map((v) => keyframes[v.trim()] || v.trim()).join(",");
  7475. }
  7476. if (animationRE.test(decl.prop)) {
  7477. decl.value = decl.value.split(",").map((v) => {
  7478. const vals = v.trim().split(/\s+/);
  7479. const i = vals.findIndex((val) => keyframes[val]);
  7480. if (i !== -1) {
  7481. vals.splice(i, 1, keyframes[vals[i]]);
  7482. return vals.join(" ");
  7483. } else {
  7484. return v;
  7485. }
  7486. }).join(",");
  7487. }
  7488. });
  7489. }
  7490. }
  7491. };
  7492. };
  7493. const processedRules = /* @__PURE__ */ new WeakSet();
  7494. function processRule(id, rule) {
  7495. if (processedRules.has(rule) || rule.parent && rule.parent.type === "atrule" && /-?keyframes$/.test(rule.parent.name)) {
  7496. return;
  7497. }
  7498. processedRules.add(rule);
  7499. let deep = false;
  7500. let parent = rule.parent;
  7501. while (parent && parent.type !== "root") {
  7502. if (parent.__deep) {
  7503. deep = true;
  7504. break;
  7505. }
  7506. parent = parent.parent;
  7507. }
  7508. rule.selector = selectorParser((selectorRoot) => {
  7509. selectorRoot.each((selector) => {
  7510. rewriteSelector(id, rule, selector, selectorRoot, deep);
  7511. });
  7512. }).processSync(rule.selector);
  7513. }
  7514. function rewriteSelector(id, rule, selector, selectorRoot, deep, slotted = false) {
  7515. let node = null;
  7516. let shouldInject = !deep;
  7517. selector.each((n) => {
  7518. if (n.type === "combinator" && (n.value === ">>>" || n.value === "/deep/")) {
  7519. n.value = " ";
  7520. n.spaces.before = n.spaces.after = "";
  7521. warn(
  7522. `the >>> and /deep/ combinators have been deprecated. Use :deep() instead.`
  7523. );
  7524. return false;
  7525. }
  7526. if (n.type === "pseudo") {
  7527. const { value } = n;
  7528. if (value === ":deep" || value === "::v-deep") {
  7529. rule.__deep = true;
  7530. if (n.nodes.length) {
  7531. let last = n;
  7532. n.nodes[0].each((ss) => {
  7533. selector.insertAfter(last, ss);
  7534. last = ss;
  7535. });
  7536. const prev = selector.at(selector.index(n) - 1);
  7537. if (!prev || !isSpaceCombinator(prev)) {
  7538. selector.insertAfter(
  7539. n,
  7540. selectorParser.combinator({
  7541. value: " "
  7542. })
  7543. );
  7544. }
  7545. selector.removeChild(n);
  7546. } else {
  7547. warn(
  7548. `${value} usage as a combinator has been deprecated. Use :deep(<inner-selector>) instead of ${value} <inner-selector>.`
  7549. );
  7550. const prev = selector.at(selector.index(n) - 1);
  7551. if (prev && isSpaceCombinator(prev)) {
  7552. selector.removeChild(prev);
  7553. }
  7554. selector.removeChild(n);
  7555. }
  7556. return false;
  7557. }
  7558. if (value === ":slotted" || value === "::v-slotted") {
  7559. rewriteSelector(
  7560. id,
  7561. rule,
  7562. n.nodes[0],
  7563. selectorRoot,
  7564. deep,
  7565. true
  7566. );
  7567. let last = n;
  7568. n.nodes[0].each((ss) => {
  7569. selector.insertAfter(last, ss);
  7570. last = ss;
  7571. });
  7572. selector.removeChild(n);
  7573. shouldInject = false;
  7574. return false;
  7575. }
  7576. if (value === ":global" || value === "::v-global") {
  7577. selectorRoot.insertAfter(selector, n.nodes[0]);
  7578. selectorRoot.removeChild(selector);
  7579. return false;
  7580. }
  7581. }
  7582. if (n.type === "universal") {
  7583. const prev = selector.at(selector.index(n) - 1);
  7584. const next = selector.at(selector.index(n) + 1);
  7585. if (!prev) {
  7586. if (next) {
  7587. if (next.type === "combinator" && next.value === " ") {
  7588. selector.removeChild(next);
  7589. }
  7590. selector.removeChild(n);
  7591. return;
  7592. } else {
  7593. node = selectorParser.combinator({
  7594. value: ""
  7595. });
  7596. selector.insertBefore(n, node);
  7597. selector.removeChild(n);
  7598. return false;
  7599. }
  7600. }
  7601. if (node) return;
  7602. }
  7603. if (n.type !== "pseudo" && n.type !== "combinator" || n.type === "pseudo" && (n.value === ":is" || n.value === ":where") && !node) {
  7604. node = n;
  7605. }
  7606. });
  7607. if (rule.nodes.some((node2) => node2.type === "rule")) {
  7608. const deep2 = rule.__deep;
  7609. if (!deep2) {
  7610. extractAndWrapNodes(rule);
  7611. const atruleNodes = rule.nodes.filter((node2) => node2.type === "atrule");
  7612. for (const atnode of atruleNodes) {
  7613. extractAndWrapNodes(atnode);
  7614. }
  7615. }
  7616. shouldInject = deep2;
  7617. }
  7618. if (node) {
  7619. const { type, value } = node;
  7620. if (type === "pseudo" && (value === ":is" || value === ":where")) {
  7621. node.nodes.forEach(
  7622. (value2) => rewriteSelector(id, rule, value2, selectorRoot, deep, slotted)
  7623. );
  7624. shouldInject = false;
  7625. }
  7626. }
  7627. if (node) {
  7628. node.spaces.after = "";
  7629. } else {
  7630. selector.first.spaces.before = "";
  7631. }
  7632. if (shouldInject) {
  7633. const idToAdd = slotted ? id + "-s" : id;
  7634. selector.insertAfter(
  7635. // If node is null it means we need to inject [id] at the start
  7636. // insertAfter can handle `null` here
  7637. node,
  7638. selectorParser.attribute({
  7639. attribute: idToAdd,
  7640. value: idToAdd,
  7641. raws: {},
  7642. quoteMark: `"`
  7643. })
  7644. );
  7645. }
  7646. }
  7647. function isSpaceCombinator(node) {
  7648. return node.type === "combinator" && /^\s+$/.test(node.value);
  7649. }
  7650. function extractAndWrapNodes(parentNode) {
  7651. if (!parentNode.nodes) return;
  7652. const nodes = parentNode.nodes.filter(
  7653. (node) => node.type === "decl" || node.type === "comment"
  7654. );
  7655. if (nodes.length) {
  7656. for (const node of nodes) {
  7657. parentNode.removeChild(node);
  7658. }
  7659. const wrappedRule = new require$$0$1.Rule({
  7660. nodes,
  7661. selector: "&"
  7662. });
  7663. parentNode.prepend(wrappedRule);
  7664. }
  7665. }
  7666. scopedPlugin.postcss = true;
  7667. var sourceMap = {};
  7668. var sourceMapGenerator = {};
  7669. var base64Vlq = {};
  7670. var base64 = {};
  7671. /* -*- Mode: js; js-indent-level: 2; -*- */
  7672. var hasRequiredBase64;
  7673. function requireBase64 () {
  7674. if (hasRequiredBase64) return base64;
  7675. hasRequiredBase64 = 1;
  7676. /*
  7677. * Copyright 2011 Mozilla Foundation and contributors
  7678. * Licensed under the New BSD license. See LICENSE or:
  7679. * http://opensource.org/licenses/BSD-3-Clause
  7680. */
  7681. var intToCharMap = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/'.split('');
  7682. /**
  7683. * Encode an integer in the range of 0 to 63 to a single base 64 digit.
  7684. */
  7685. base64.encode = function (number) {
  7686. if (0 <= number && number < intToCharMap.length) {
  7687. return intToCharMap[number];
  7688. }
  7689. throw new TypeError("Must be between 0 and 63: " + number);
  7690. };
  7691. /**
  7692. * Decode a single base 64 character code digit to an integer. Returns -1 on
  7693. * failure.
  7694. */
  7695. base64.decode = function (charCode) {
  7696. var bigA = 65; // 'A'
  7697. var bigZ = 90; // 'Z'
  7698. var littleA = 97; // 'a'
  7699. var littleZ = 122; // 'z'
  7700. var zero = 48; // '0'
  7701. var nine = 57; // '9'
  7702. var plus = 43; // '+'
  7703. var slash = 47; // '/'
  7704. var littleOffset = 26;
  7705. var numberOffset = 52;
  7706. // 0 - 25: ABCDEFGHIJKLMNOPQRSTUVWXYZ
  7707. if (bigA <= charCode && charCode <= bigZ) {
  7708. return (charCode - bigA);
  7709. }
  7710. // 26 - 51: abcdefghijklmnopqrstuvwxyz
  7711. if (littleA <= charCode && charCode <= littleZ) {
  7712. return (charCode - littleA + littleOffset);
  7713. }
  7714. // 52 - 61: 0123456789
  7715. if (zero <= charCode && charCode <= nine) {
  7716. return (charCode - zero + numberOffset);
  7717. }
  7718. // 62: +
  7719. if (charCode == plus) {
  7720. return 62;
  7721. }
  7722. // 63: /
  7723. if (charCode == slash) {
  7724. return 63;
  7725. }
  7726. // Invalid base64 digit.
  7727. return -1;
  7728. };
  7729. return base64;
  7730. }
  7731. /* -*- Mode: js; js-indent-level: 2; -*- */
  7732. var hasRequiredBase64Vlq;
  7733. function requireBase64Vlq () {
  7734. if (hasRequiredBase64Vlq) return base64Vlq;
  7735. hasRequiredBase64Vlq = 1;
  7736. /*
  7737. * Copyright 2011 Mozilla Foundation and contributors
  7738. * Licensed under the New BSD license. See LICENSE or:
  7739. * http://opensource.org/licenses/BSD-3-Clause
  7740. *
  7741. * Based on the Base 64 VLQ implementation in Closure Compiler:
  7742. * https://code.google.com/p/closure-compiler/source/browse/trunk/src/com/google/debugging/sourcemap/Base64VLQ.java
  7743. *
  7744. * Copyright 2011 The Closure Compiler Authors. All rights reserved.
  7745. * Redistribution and use in source and binary forms, with or without
  7746. * modification, are permitted provided that the following conditions are
  7747. * met:
  7748. *
  7749. * * Redistributions of source code must retain the above copyright
  7750. * notice, this list of conditions and the following disclaimer.
  7751. * * Redistributions in binary form must reproduce the above
  7752. * copyright notice, this list of conditions and the following
  7753. * disclaimer in the documentation and/or other materials provided
  7754. * with the distribution.
  7755. * * Neither the name of Google Inc. nor the names of its
  7756. * contributors may be used to endorse or promote products derived
  7757. * from this software without specific prior written permission.
  7758. *
  7759. * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
  7760. * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
  7761. * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
  7762. * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
  7763. * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
  7764. * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
  7765. * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
  7766. * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
  7767. * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
  7768. * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
  7769. * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  7770. */
  7771. var base64 = /*@__PURE__*/ requireBase64();
  7772. // A single base 64 digit can contain 6 bits of data. For the base 64 variable
  7773. // length quantities we use in the source map spec, the first bit is the sign,
  7774. // the next four bits are the actual value, and the 6th bit is the
  7775. // continuation bit. The continuation bit tells us whether there are more
  7776. // digits in this value following this digit.
  7777. //
  7778. // Continuation
  7779. // | Sign
  7780. // | |
  7781. // V V
  7782. // 101011
  7783. var VLQ_BASE_SHIFT = 5;
  7784. // binary: 100000
  7785. var VLQ_BASE = 1 << VLQ_BASE_SHIFT;
  7786. // binary: 011111
  7787. var VLQ_BASE_MASK = VLQ_BASE - 1;
  7788. // binary: 100000
  7789. var VLQ_CONTINUATION_BIT = VLQ_BASE;
  7790. /**
  7791. * Converts from a two-complement value to a value where the sign bit is
  7792. * placed in the least significant bit. For example, as decimals:
  7793. * 1 becomes 2 (10 binary), -1 becomes 3 (11 binary)
  7794. * 2 becomes 4 (100 binary), -2 becomes 5 (101 binary)
  7795. */
  7796. function toVLQSigned(aValue) {
  7797. return aValue < 0
  7798. ? ((-aValue) << 1) + 1
  7799. : (aValue << 1) + 0;
  7800. }
  7801. /**
  7802. * Converts to a two-complement value from a value where the sign bit is
  7803. * placed in the least significant bit. For example, as decimals:
  7804. * 2 (10 binary) becomes 1, 3 (11 binary) becomes -1
  7805. * 4 (100 binary) becomes 2, 5 (101 binary) becomes -2
  7806. */
  7807. function fromVLQSigned(aValue) {
  7808. var isNegative = (aValue & 1) === 1;
  7809. var shifted = aValue >> 1;
  7810. return isNegative
  7811. ? -shifted
  7812. : shifted;
  7813. }
  7814. /**
  7815. * Returns the base 64 VLQ encoded value.
  7816. */
  7817. base64Vlq.encode = function base64VLQ_encode(aValue) {
  7818. var encoded = "";
  7819. var digit;
  7820. var vlq = toVLQSigned(aValue);
  7821. do {
  7822. digit = vlq & VLQ_BASE_MASK;
  7823. vlq >>>= VLQ_BASE_SHIFT;
  7824. if (vlq > 0) {
  7825. // There are still more digits in this value, so we must make sure the
  7826. // continuation bit is marked.
  7827. digit |= VLQ_CONTINUATION_BIT;
  7828. }
  7829. encoded += base64.encode(digit);
  7830. } while (vlq > 0);
  7831. return encoded;
  7832. };
  7833. /**
  7834. * Decodes the next base 64 VLQ value from the given string and returns the
  7835. * value and the rest of the string via the out parameter.
  7836. */
  7837. base64Vlq.decode = function base64VLQ_decode(aStr, aIndex, aOutParam) {
  7838. var strLen = aStr.length;
  7839. var result = 0;
  7840. var shift = 0;
  7841. var continuation, digit;
  7842. do {
  7843. if (aIndex >= strLen) {
  7844. throw new Error("Expected more digits in base 64 VLQ value.");
  7845. }
  7846. digit = base64.decode(aStr.charCodeAt(aIndex++));
  7847. if (digit === -1) {
  7848. throw new Error("Invalid base64 digit: " + aStr.charAt(aIndex - 1));
  7849. }
  7850. continuation = !!(digit & VLQ_CONTINUATION_BIT);
  7851. digit &= VLQ_BASE_MASK;
  7852. result = result + (digit << shift);
  7853. shift += VLQ_BASE_SHIFT;
  7854. } while (continuation);
  7855. aOutParam.value = fromVLQSigned(result);
  7856. aOutParam.rest = aIndex;
  7857. };
  7858. return base64Vlq;
  7859. }
  7860. var util = {};
  7861. /* -*- Mode: js; js-indent-level: 2; -*- */
  7862. var hasRequiredUtil;
  7863. function requireUtil () {
  7864. if (hasRequiredUtil) return util;
  7865. hasRequiredUtil = 1;
  7866. (function (exports) {
  7867. /*
  7868. * Copyright 2011 Mozilla Foundation and contributors
  7869. * Licensed under the New BSD license. See LICENSE or:
  7870. * http://opensource.org/licenses/BSD-3-Clause
  7871. */
  7872. /**
  7873. * This is a helper function for getting values from parameter/options
  7874. * objects.
  7875. *
  7876. * @param args The object we are extracting values from
  7877. * @param name The name of the property we are getting.
  7878. * @param defaultValue An optional value to return if the property is missing
  7879. * from the object. If this is not specified and the property is missing, an
  7880. * error will be thrown.
  7881. */
  7882. function getArg(aArgs, aName, aDefaultValue) {
  7883. if (aName in aArgs) {
  7884. return aArgs[aName];
  7885. } else if (arguments.length === 3) {
  7886. return aDefaultValue;
  7887. } else {
  7888. throw new Error('"' + aName + '" is a required argument.');
  7889. }
  7890. }
  7891. exports.getArg = getArg;
  7892. var urlRegexp = /^(?:([\w+\-.]+):)?\/\/(?:(\w+:\w+)@)?([\w.-]*)(?::(\d+))?(.*)$/;
  7893. var dataUrlRegexp = /^data:.+\,.+$/;
  7894. function urlParse(aUrl) {
  7895. var match = aUrl.match(urlRegexp);
  7896. if (!match) {
  7897. return null;
  7898. }
  7899. return {
  7900. scheme: match[1],
  7901. auth: match[2],
  7902. host: match[3],
  7903. port: match[4],
  7904. path: match[5]
  7905. };
  7906. }
  7907. exports.urlParse = urlParse;
  7908. function urlGenerate(aParsedUrl) {
  7909. var url = '';
  7910. if (aParsedUrl.scheme) {
  7911. url += aParsedUrl.scheme + ':';
  7912. }
  7913. url += '//';
  7914. if (aParsedUrl.auth) {
  7915. url += aParsedUrl.auth + '@';
  7916. }
  7917. if (aParsedUrl.host) {
  7918. url += aParsedUrl.host;
  7919. }
  7920. if (aParsedUrl.port) {
  7921. url += ":" + aParsedUrl.port;
  7922. }
  7923. if (aParsedUrl.path) {
  7924. url += aParsedUrl.path;
  7925. }
  7926. return url;
  7927. }
  7928. exports.urlGenerate = urlGenerate;
  7929. /**
  7930. * Normalizes a path, or the path portion of a URL:
  7931. *
  7932. * - Replaces consecutive slashes with one slash.
  7933. * - Removes unnecessary '.' parts.
  7934. * - Removes unnecessary '<dir>/..' parts.
  7935. *
  7936. * Based on code in the Node.js 'path' core module.
  7937. *
  7938. * @param aPath The path or url to normalize.
  7939. */
  7940. function normalize(aPath) {
  7941. var path = aPath;
  7942. var url = urlParse(aPath);
  7943. if (url) {
  7944. if (!url.path) {
  7945. return aPath;
  7946. }
  7947. path = url.path;
  7948. }
  7949. var isAbsolute = exports.isAbsolute(path);
  7950. var parts = path.split(/\/+/);
  7951. for (var part, up = 0, i = parts.length - 1; i >= 0; i--) {
  7952. part = parts[i];
  7953. if (part === '.') {
  7954. parts.splice(i, 1);
  7955. } else if (part === '..') {
  7956. up++;
  7957. } else if (up > 0) {
  7958. if (part === '') {
  7959. // The first part is blank if the path is absolute. Trying to go
  7960. // above the root is a no-op. Therefore we can remove all '..' parts
  7961. // directly after the root.
  7962. parts.splice(i + 1, up);
  7963. up = 0;
  7964. } else {
  7965. parts.splice(i, 2);
  7966. up--;
  7967. }
  7968. }
  7969. }
  7970. path = parts.join('/');
  7971. if (path === '') {
  7972. path = isAbsolute ? '/' : '.';
  7973. }
  7974. if (url) {
  7975. url.path = path;
  7976. return urlGenerate(url);
  7977. }
  7978. return path;
  7979. }
  7980. exports.normalize = normalize;
  7981. /**
  7982. * Joins two paths/URLs.
  7983. *
  7984. * @param aRoot The root path or URL.
  7985. * @param aPath The path or URL to be joined with the root.
  7986. *
  7987. * - If aPath is a URL or a data URI, aPath is returned, unless aPath is a
  7988. * scheme-relative URL: Then the scheme of aRoot, if any, is prepended
  7989. * first.
  7990. * - Otherwise aPath is a path. If aRoot is a URL, then its path portion
  7991. * is updated with the result and aRoot is returned. Otherwise the result
  7992. * is returned.
  7993. * - If aPath is absolute, the result is aPath.
  7994. * - Otherwise the two paths are joined with a slash.
  7995. * - Joining for example 'http://' and 'www.example.com' is also supported.
  7996. */
  7997. function join(aRoot, aPath) {
  7998. if (aRoot === "") {
  7999. aRoot = ".";
  8000. }
  8001. if (aPath === "") {
  8002. aPath = ".";
  8003. }
  8004. var aPathUrl = urlParse(aPath);
  8005. var aRootUrl = urlParse(aRoot);
  8006. if (aRootUrl) {
  8007. aRoot = aRootUrl.path || '/';
  8008. }
  8009. // `join(foo, '//www.example.org')`
  8010. if (aPathUrl && !aPathUrl.scheme) {
  8011. if (aRootUrl) {
  8012. aPathUrl.scheme = aRootUrl.scheme;
  8013. }
  8014. return urlGenerate(aPathUrl);
  8015. }
  8016. if (aPathUrl || aPath.match(dataUrlRegexp)) {
  8017. return aPath;
  8018. }
  8019. // `join('http://', 'www.example.com')`
  8020. if (aRootUrl && !aRootUrl.host && !aRootUrl.path) {
  8021. aRootUrl.host = aPath;
  8022. return urlGenerate(aRootUrl);
  8023. }
  8024. var joined = aPath.charAt(0) === '/'
  8025. ? aPath
  8026. : normalize(aRoot.replace(/\/+$/, '') + '/' + aPath);
  8027. if (aRootUrl) {
  8028. aRootUrl.path = joined;
  8029. return urlGenerate(aRootUrl);
  8030. }
  8031. return joined;
  8032. }
  8033. exports.join = join;
  8034. exports.isAbsolute = function (aPath) {
  8035. return aPath.charAt(0) === '/' || urlRegexp.test(aPath);
  8036. };
  8037. /**
  8038. * Make a path relative to a URL or another path.
  8039. *
  8040. * @param aRoot The root path or URL.
  8041. * @param aPath The path or URL to be made relative to aRoot.
  8042. */
  8043. function relative(aRoot, aPath) {
  8044. if (aRoot === "") {
  8045. aRoot = ".";
  8046. }
  8047. aRoot = aRoot.replace(/\/$/, '');
  8048. // It is possible for the path to be above the root. In this case, simply
  8049. // checking whether the root is a prefix of the path won't work. Instead, we
  8050. // need to remove components from the root one by one, until either we find
  8051. // a prefix that fits, or we run out of components to remove.
  8052. var level = 0;
  8053. while (aPath.indexOf(aRoot + '/') !== 0) {
  8054. var index = aRoot.lastIndexOf("/");
  8055. if (index < 0) {
  8056. return aPath;
  8057. }
  8058. // If the only part of the root that is left is the scheme (i.e. http://,
  8059. // file:///, etc.), one or more slashes (/), or simply nothing at all, we
  8060. // have exhausted all components, so the path is not relative to the root.
  8061. aRoot = aRoot.slice(0, index);
  8062. if (aRoot.match(/^([^\/]+:\/)?\/*$/)) {
  8063. return aPath;
  8064. }
  8065. ++level;
  8066. }
  8067. // Make sure we add a "../" for each component we removed from the root.
  8068. return Array(level + 1).join("../") + aPath.substr(aRoot.length + 1);
  8069. }
  8070. exports.relative = relative;
  8071. var supportsNullProto = (function () {
  8072. var obj = Object.create(null);
  8073. return !('__proto__' in obj);
  8074. }());
  8075. function identity (s) {
  8076. return s;
  8077. }
  8078. /**
  8079. * Because behavior goes wacky when you set `__proto__` on objects, we
  8080. * have to prefix all the strings in our set with an arbitrary character.
  8081. *
  8082. * See https://github.com/mozilla/source-map/pull/31 and
  8083. * https://github.com/mozilla/source-map/issues/30
  8084. *
  8085. * @param String aStr
  8086. */
  8087. function toSetString(aStr) {
  8088. if (isProtoString(aStr)) {
  8089. return '$' + aStr;
  8090. }
  8091. return aStr;
  8092. }
  8093. exports.toSetString = supportsNullProto ? identity : toSetString;
  8094. function fromSetString(aStr) {
  8095. if (isProtoString(aStr)) {
  8096. return aStr.slice(1);
  8097. }
  8098. return aStr;
  8099. }
  8100. exports.fromSetString = supportsNullProto ? identity : fromSetString;
  8101. function isProtoString(s) {
  8102. if (!s) {
  8103. return false;
  8104. }
  8105. var length = s.length;
  8106. if (length < 9 /* "__proto__".length */) {
  8107. return false;
  8108. }
  8109. if (s.charCodeAt(length - 1) !== 95 /* '_' */ ||
  8110. s.charCodeAt(length - 2) !== 95 /* '_' */ ||
  8111. s.charCodeAt(length - 3) !== 111 /* 'o' */ ||
  8112. s.charCodeAt(length - 4) !== 116 /* 't' */ ||
  8113. s.charCodeAt(length - 5) !== 111 /* 'o' */ ||
  8114. s.charCodeAt(length - 6) !== 114 /* 'r' */ ||
  8115. s.charCodeAt(length - 7) !== 112 /* 'p' */ ||
  8116. s.charCodeAt(length - 8) !== 95 /* '_' */ ||
  8117. s.charCodeAt(length - 9) !== 95 /* '_' */) {
  8118. return false;
  8119. }
  8120. for (var i = length - 10; i >= 0; i--) {
  8121. if (s.charCodeAt(i) !== 36 /* '$' */) {
  8122. return false;
  8123. }
  8124. }
  8125. return true;
  8126. }
  8127. /**
  8128. * Comparator between two mappings where the original positions are compared.
  8129. *
  8130. * Optionally pass in `true` as `onlyCompareGenerated` to consider two
  8131. * mappings with the same original source/line/column, but different generated
  8132. * line and column the same. Useful when searching for a mapping with a
  8133. * stubbed out mapping.
  8134. */
  8135. function compareByOriginalPositions(mappingA, mappingB, onlyCompareOriginal) {
  8136. var cmp = strcmp(mappingA.source, mappingB.source);
  8137. if (cmp !== 0) {
  8138. return cmp;
  8139. }
  8140. cmp = mappingA.originalLine - mappingB.originalLine;
  8141. if (cmp !== 0) {
  8142. return cmp;
  8143. }
  8144. cmp = mappingA.originalColumn - mappingB.originalColumn;
  8145. if (cmp !== 0 || onlyCompareOriginal) {
  8146. return cmp;
  8147. }
  8148. cmp = mappingA.generatedColumn - mappingB.generatedColumn;
  8149. if (cmp !== 0) {
  8150. return cmp;
  8151. }
  8152. cmp = mappingA.generatedLine - mappingB.generatedLine;
  8153. if (cmp !== 0) {
  8154. return cmp;
  8155. }
  8156. return strcmp(mappingA.name, mappingB.name);
  8157. }
  8158. exports.compareByOriginalPositions = compareByOriginalPositions;
  8159. /**
  8160. * Comparator between two mappings with deflated source and name indices where
  8161. * the generated positions are compared.
  8162. *
  8163. * Optionally pass in `true` as `onlyCompareGenerated` to consider two
  8164. * mappings with the same generated line and column, but different
  8165. * source/name/original line and column the same. Useful when searching for a
  8166. * mapping with a stubbed out mapping.
  8167. */
  8168. function compareByGeneratedPositionsDeflated(mappingA, mappingB, onlyCompareGenerated) {
  8169. var cmp = mappingA.generatedLine - mappingB.generatedLine;
  8170. if (cmp !== 0) {
  8171. return cmp;
  8172. }
  8173. cmp = mappingA.generatedColumn - mappingB.generatedColumn;
  8174. if (cmp !== 0 || onlyCompareGenerated) {
  8175. return cmp;
  8176. }
  8177. cmp = strcmp(mappingA.source, mappingB.source);
  8178. if (cmp !== 0) {
  8179. return cmp;
  8180. }
  8181. cmp = mappingA.originalLine - mappingB.originalLine;
  8182. if (cmp !== 0) {
  8183. return cmp;
  8184. }
  8185. cmp = mappingA.originalColumn - mappingB.originalColumn;
  8186. if (cmp !== 0) {
  8187. return cmp;
  8188. }
  8189. return strcmp(mappingA.name, mappingB.name);
  8190. }
  8191. exports.compareByGeneratedPositionsDeflated = compareByGeneratedPositionsDeflated;
  8192. function strcmp(aStr1, aStr2) {
  8193. if (aStr1 === aStr2) {
  8194. return 0;
  8195. }
  8196. if (aStr1 === null) {
  8197. return 1; // aStr2 !== null
  8198. }
  8199. if (aStr2 === null) {
  8200. return -1; // aStr1 !== null
  8201. }
  8202. if (aStr1 > aStr2) {
  8203. return 1;
  8204. }
  8205. return -1;
  8206. }
  8207. /**
  8208. * Comparator between two mappings with inflated source and name strings where
  8209. * the generated positions are compared.
  8210. */
  8211. function compareByGeneratedPositionsInflated(mappingA, mappingB) {
  8212. var cmp = mappingA.generatedLine - mappingB.generatedLine;
  8213. if (cmp !== 0) {
  8214. return cmp;
  8215. }
  8216. cmp = mappingA.generatedColumn - mappingB.generatedColumn;
  8217. if (cmp !== 0) {
  8218. return cmp;
  8219. }
  8220. cmp = strcmp(mappingA.source, mappingB.source);
  8221. if (cmp !== 0) {
  8222. return cmp;
  8223. }
  8224. cmp = mappingA.originalLine - mappingB.originalLine;
  8225. if (cmp !== 0) {
  8226. return cmp;
  8227. }
  8228. cmp = mappingA.originalColumn - mappingB.originalColumn;
  8229. if (cmp !== 0) {
  8230. return cmp;
  8231. }
  8232. return strcmp(mappingA.name, mappingB.name);
  8233. }
  8234. exports.compareByGeneratedPositionsInflated = compareByGeneratedPositionsInflated;
  8235. /**
  8236. * Strip any JSON XSSI avoidance prefix from the string (as documented
  8237. * in the source maps specification), and then parse the string as
  8238. * JSON.
  8239. */
  8240. function parseSourceMapInput(str) {
  8241. return JSON.parse(str.replace(/^\)]}'[^\n]*\n/, ''));
  8242. }
  8243. exports.parseSourceMapInput = parseSourceMapInput;
  8244. /**
  8245. * Compute the URL of a source given the the source root, the source's
  8246. * URL, and the source map's URL.
  8247. */
  8248. function computeSourceURL(sourceRoot, sourceURL, sourceMapURL) {
  8249. sourceURL = sourceURL || '';
  8250. if (sourceRoot) {
  8251. // This follows what Chrome does.
  8252. if (sourceRoot[sourceRoot.length - 1] !== '/' && sourceURL[0] !== '/') {
  8253. sourceRoot += '/';
  8254. }
  8255. // The spec says:
  8256. // Line 4: An optional source root, useful for relocating source
  8257. // files on a server or removing repeated values in the
  8258. // “sources” entry. This value is prepended to the individual
  8259. // entries in the “source” field.
  8260. sourceURL = sourceRoot + sourceURL;
  8261. }
  8262. // Historically, SourceMapConsumer did not take the sourceMapURL as
  8263. // a parameter. This mode is still somewhat supported, which is why
  8264. // this code block is conditional. However, it's preferable to pass
  8265. // the source map URL to SourceMapConsumer, so that this function
  8266. // can implement the source URL resolution algorithm as outlined in
  8267. // the spec. This block is basically the equivalent of:
  8268. // new URL(sourceURL, sourceMapURL).toString()
  8269. // ... except it avoids using URL, which wasn't available in the
  8270. // older releases of node still supported by this library.
  8271. //
  8272. // The spec says:
  8273. // If the sources are not absolute URLs after prepending of the
  8274. // “sourceRoot”, the sources are resolved relative to the
  8275. // SourceMap (like resolving script src in a html document).
  8276. if (sourceMapURL) {
  8277. var parsed = urlParse(sourceMapURL);
  8278. if (!parsed) {
  8279. throw new Error("sourceMapURL could not be parsed");
  8280. }
  8281. if (parsed.path) {
  8282. // Strip the last path component, but keep the "/".
  8283. var index = parsed.path.lastIndexOf('/');
  8284. if (index >= 0) {
  8285. parsed.path = parsed.path.substring(0, index + 1);
  8286. }
  8287. }
  8288. sourceURL = join(urlGenerate(parsed), sourceURL);
  8289. }
  8290. return normalize(sourceURL);
  8291. }
  8292. exports.computeSourceURL = computeSourceURL;
  8293. } (util));
  8294. return util;
  8295. }
  8296. var arraySet = {};
  8297. /* -*- Mode: js; js-indent-level: 2; -*- */
  8298. var hasRequiredArraySet;
  8299. function requireArraySet () {
  8300. if (hasRequiredArraySet) return arraySet;
  8301. hasRequiredArraySet = 1;
  8302. /*
  8303. * Copyright 2011 Mozilla Foundation and contributors
  8304. * Licensed under the New BSD license. See LICENSE or:
  8305. * http://opensource.org/licenses/BSD-3-Clause
  8306. */
  8307. var util = /*@__PURE__*/ requireUtil();
  8308. var has = Object.prototype.hasOwnProperty;
  8309. var hasNativeMap = typeof Map !== "undefined";
  8310. /**
  8311. * A data structure which is a combination of an array and a set. Adding a new
  8312. * member is O(1), testing for membership is O(1), and finding the index of an
  8313. * element is O(1). Removing elements from the set is not supported. Only
  8314. * strings are supported for membership.
  8315. */
  8316. function ArraySet() {
  8317. this._array = [];
  8318. this._set = hasNativeMap ? new Map() : Object.create(null);
  8319. }
  8320. /**
  8321. * Static method for creating ArraySet instances from an existing array.
  8322. */
  8323. ArraySet.fromArray = function ArraySet_fromArray(aArray, aAllowDuplicates) {
  8324. var set = new ArraySet();
  8325. for (var i = 0, len = aArray.length; i < len; i++) {
  8326. set.add(aArray[i], aAllowDuplicates);
  8327. }
  8328. return set;
  8329. };
  8330. /**
  8331. * Return how many unique items are in this ArraySet. If duplicates have been
  8332. * added, than those do not count towards the size.
  8333. *
  8334. * @returns Number
  8335. */
  8336. ArraySet.prototype.size = function ArraySet_size() {
  8337. return hasNativeMap ? this._set.size : Object.getOwnPropertyNames(this._set).length;
  8338. };
  8339. /**
  8340. * Add the given string to this set.
  8341. *
  8342. * @param String aStr
  8343. */
  8344. ArraySet.prototype.add = function ArraySet_add(aStr, aAllowDuplicates) {
  8345. var sStr = hasNativeMap ? aStr : util.toSetString(aStr);
  8346. var isDuplicate = hasNativeMap ? this.has(aStr) : has.call(this._set, sStr);
  8347. var idx = this._array.length;
  8348. if (!isDuplicate || aAllowDuplicates) {
  8349. this._array.push(aStr);
  8350. }
  8351. if (!isDuplicate) {
  8352. if (hasNativeMap) {
  8353. this._set.set(aStr, idx);
  8354. } else {
  8355. this._set[sStr] = idx;
  8356. }
  8357. }
  8358. };
  8359. /**
  8360. * Is the given string a member of this set?
  8361. *
  8362. * @param String aStr
  8363. */
  8364. ArraySet.prototype.has = function ArraySet_has(aStr) {
  8365. if (hasNativeMap) {
  8366. return this._set.has(aStr);
  8367. } else {
  8368. var sStr = util.toSetString(aStr);
  8369. return has.call(this._set, sStr);
  8370. }
  8371. };
  8372. /**
  8373. * What is the index of the given string in the array?
  8374. *
  8375. * @param String aStr
  8376. */
  8377. ArraySet.prototype.indexOf = function ArraySet_indexOf(aStr) {
  8378. if (hasNativeMap) {
  8379. var idx = this._set.get(aStr);
  8380. if (idx >= 0) {
  8381. return idx;
  8382. }
  8383. } else {
  8384. var sStr = util.toSetString(aStr);
  8385. if (has.call(this._set, sStr)) {
  8386. return this._set[sStr];
  8387. }
  8388. }
  8389. throw new Error('"' + aStr + '" is not in the set.');
  8390. };
  8391. /**
  8392. * What is the element at the given index?
  8393. *
  8394. * @param Number aIdx
  8395. */
  8396. ArraySet.prototype.at = function ArraySet_at(aIdx) {
  8397. if (aIdx >= 0 && aIdx < this._array.length) {
  8398. return this._array[aIdx];
  8399. }
  8400. throw new Error('No element indexed by ' + aIdx);
  8401. };
  8402. /**
  8403. * Returns the array representation of this set (which has the proper indices
  8404. * indicated by indexOf). Note that this is a copy of the internal array used
  8405. * for storing the members so that no one can mess with internal state.
  8406. */
  8407. ArraySet.prototype.toArray = function ArraySet_toArray() {
  8408. return this._array.slice();
  8409. };
  8410. arraySet.ArraySet = ArraySet;
  8411. return arraySet;
  8412. }
  8413. var mappingList = {};
  8414. /* -*- Mode: js; js-indent-level: 2; -*- */
  8415. var hasRequiredMappingList;
  8416. function requireMappingList () {
  8417. if (hasRequiredMappingList) return mappingList;
  8418. hasRequiredMappingList = 1;
  8419. /*
  8420. * Copyright 2014 Mozilla Foundation and contributors
  8421. * Licensed under the New BSD license. See LICENSE or:
  8422. * http://opensource.org/licenses/BSD-3-Clause
  8423. */
  8424. var util = /*@__PURE__*/ requireUtil();
  8425. /**
  8426. * Determine whether mappingB is after mappingA with respect to generated
  8427. * position.
  8428. */
  8429. function generatedPositionAfter(mappingA, mappingB) {
  8430. // Optimized for most common case
  8431. var lineA = mappingA.generatedLine;
  8432. var lineB = mappingB.generatedLine;
  8433. var columnA = mappingA.generatedColumn;
  8434. var columnB = mappingB.generatedColumn;
  8435. return lineB > lineA || lineB == lineA && columnB >= columnA ||
  8436. util.compareByGeneratedPositionsInflated(mappingA, mappingB) <= 0;
  8437. }
  8438. /**
  8439. * A data structure to provide a sorted view of accumulated mappings in a
  8440. * performance conscious manner. It trades a neglibable overhead in general
  8441. * case for a large speedup in case of mappings being added in order.
  8442. */
  8443. function MappingList() {
  8444. this._array = [];
  8445. this._sorted = true;
  8446. // Serves as infimum
  8447. this._last = {generatedLine: -1, generatedColumn: 0};
  8448. }
  8449. /**
  8450. * Iterate through internal items. This method takes the same arguments that
  8451. * `Array.prototype.forEach` takes.
  8452. *
  8453. * NOTE: The order of the mappings is NOT guaranteed.
  8454. */
  8455. MappingList.prototype.unsortedForEach =
  8456. function MappingList_forEach(aCallback, aThisArg) {
  8457. this._array.forEach(aCallback, aThisArg);
  8458. };
  8459. /**
  8460. * Add the given source mapping.
  8461. *
  8462. * @param Object aMapping
  8463. */
  8464. MappingList.prototype.add = function MappingList_add(aMapping) {
  8465. if (generatedPositionAfter(this._last, aMapping)) {
  8466. this._last = aMapping;
  8467. this._array.push(aMapping);
  8468. } else {
  8469. this._sorted = false;
  8470. this._array.push(aMapping);
  8471. }
  8472. };
  8473. /**
  8474. * Returns the flat, sorted array of mappings. The mappings are sorted by
  8475. * generated position.
  8476. *
  8477. * WARNING: This method returns internal data without copying, for
  8478. * performance. The return value must NOT be mutated, and should be treated as
  8479. * an immutable borrow. If you want to take ownership, you must make your own
  8480. * copy.
  8481. */
  8482. MappingList.prototype.toArray = function MappingList_toArray() {
  8483. if (!this._sorted) {
  8484. this._array.sort(util.compareByGeneratedPositionsInflated);
  8485. this._sorted = true;
  8486. }
  8487. return this._array;
  8488. };
  8489. mappingList.MappingList = MappingList;
  8490. return mappingList;
  8491. }
  8492. /* -*- Mode: js; js-indent-level: 2; -*- */
  8493. var hasRequiredSourceMapGenerator;
  8494. function requireSourceMapGenerator () {
  8495. if (hasRequiredSourceMapGenerator) return sourceMapGenerator;
  8496. hasRequiredSourceMapGenerator = 1;
  8497. /*
  8498. * Copyright 2011 Mozilla Foundation and contributors
  8499. * Licensed under the New BSD license. See LICENSE or:
  8500. * http://opensource.org/licenses/BSD-3-Clause
  8501. */
  8502. var base64VLQ = /*@__PURE__*/ requireBase64Vlq();
  8503. var util = /*@__PURE__*/ requireUtil();
  8504. var ArraySet = /*@__PURE__*/ requireArraySet().ArraySet;
  8505. var MappingList = /*@__PURE__*/ requireMappingList().MappingList;
  8506. /**
  8507. * An instance of the SourceMapGenerator represents a source map which is
  8508. * being built incrementally. You may pass an object with the following
  8509. * properties:
  8510. *
  8511. * - file: The filename of the generated source.
  8512. * - sourceRoot: A root for all relative URLs in this source map.
  8513. */
  8514. function SourceMapGenerator(aArgs) {
  8515. if (!aArgs) {
  8516. aArgs = {};
  8517. }
  8518. this._file = util.getArg(aArgs, 'file', null);
  8519. this._sourceRoot = util.getArg(aArgs, 'sourceRoot', null);
  8520. this._skipValidation = util.getArg(aArgs, 'skipValidation', false);
  8521. this._sources = new ArraySet();
  8522. this._names = new ArraySet();
  8523. this._mappings = new MappingList();
  8524. this._sourcesContents = null;
  8525. }
  8526. SourceMapGenerator.prototype._version = 3;
  8527. /**
  8528. * Creates a new SourceMapGenerator based on a SourceMapConsumer
  8529. *
  8530. * @param aSourceMapConsumer The SourceMap.
  8531. */
  8532. SourceMapGenerator.fromSourceMap =
  8533. function SourceMapGenerator_fromSourceMap(aSourceMapConsumer) {
  8534. var sourceRoot = aSourceMapConsumer.sourceRoot;
  8535. var generator = new SourceMapGenerator({
  8536. file: aSourceMapConsumer.file,
  8537. sourceRoot: sourceRoot
  8538. });
  8539. aSourceMapConsumer.eachMapping(function (mapping) {
  8540. var newMapping = {
  8541. generated: {
  8542. line: mapping.generatedLine,
  8543. column: mapping.generatedColumn
  8544. }
  8545. };
  8546. if (mapping.source != null) {
  8547. newMapping.source = mapping.source;
  8548. if (sourceRoot != null) {
  8549. newMapping.source = util.relative(sourceRoot, newMapping.source);
  8550. }
  8551. newMapping.original = {
  8552. line: mapping.originalLine,
  8553. column: mapping.originalColumn
  8554. };
  8555. if (mapping.name != null) {
  8556. newMapping.name = mapping.name;
  8557. }
  8558. }
  8559. generator.addMapping(newMapping);
  8560. });
  8561. aSourceMapConsumer.sources.forEach(function (sourceFile) {
  8562. var sourceRelative = sourceFile;
  8563. if (sourceRoot !== null) {
  8564. sourceRelative = util.relative(sourceRoot, sourceFile);
  8565. }
  8566. if (!generator._sources.has(sourceRelative)) {
  8567. generator._sources.add(sourceRelative);
  8568. }
  8569. var content = aSourceMapConsumer.sourceContentFor(sourceFile);
  8570. if (content != null) {
  8571. generator.setSourceContent(sourceFile, content);
  8572. }
  8573. });
  8574. return generator;
  8575. };
  8576. /**
  8577. * Add a single mapping from original source line and column to the generated
  8578. * source's line and column for this source map being created. The mapping
  8579. * object should have the following properties:
  8580. *
  8581. * - generated: An object with the generated line and column positions.
  8582. * - original: An object with the original line and column positions.
  8583. * - source: The original source file (relative to the sourceRoot).
  8584. * - name: An optional original token name for this mapping.
  8585. */
  8586. SourceMapGenerator.prototype.addMapping =
  8587. function SourceMapGenerator_addMapping(aArgs) {
  8588. var generated = util.getArg(aArgs, 'generated');
  8589. var original = util.getArg(aArgs, 'original', null);
  8590. var source = util.getArg(aArgs, 'source', null);
  8591. var name = util.getArg(aArgs, 'name', null);
  8592. if (!this._skipValidation) {
  8593. this._validateMapping(generated, original, source, name);
  8594. }
  8595. if (source != null) {
  8596. source = String(source);
  8597. if (!this._sources.has(source)) {
  8598. this._sources.add(source);
  8599. }
  8600. }
  8601. if (name != null) {
  8602. name = String(name);
  8603. if (!this._names.has(name)) {
  8604. this._names.add(name);
  8605. }
  8606. }
  8607. this._mappings.add({
  8608. generatedLine: generated.line,
  8609. generatedColumn: generated.column,
  8610. originalLine: original != null && original.line,
  8611. originalColumn: original != null && original.column,
  8612. source: source,
  8613. name: name
  8614. });
  8615. };
  8616. /**
  8617. * Set the source content for a source file.
  8618. */
  8619. SourceMapGenerator.prototype.setSourceContent =
  8620. function SourceMapGenerator_setSourceContent(aSourceFile, aSourceContent) {
  8621. var source = aSourceFile;
  8622. if (this._sourceRoot != null) {
  8623. source = util.relative(this._sourceRoot, source);
  8624. }
  8625. if (aSourceContent != null) {
  8626. // Add the source content to the _sourcesContents map.
  8627. // Create a new _sourcesContents map if the property is null.
  8628. if (!this._sourcesContents) {
  8629. this._sourcesContents = Object.create(null);
  8630. }
  8631. this._sourcesContents[util.toSetString(source)] = aSourceContent;
  8632. } else if (this._sourcesContents) {
  8633. // Remove the source file from the _sourcesContents map.
  8634. // If the _sourcesContents map is empty, set the property to null.
  8635. delete this._sourcesContents[util.toSetString(source)];
  8636. if (Object.keys(this._sourcesContents).length === 0) {
  8637. this._sourcesContents = null;
  8638. }
  8639. }
  8640. };
  8641. /**
  8642. * Applies the mappings of a sub-source-map for a specific source file to the
  8643. * source map being generated. Each mapping to the supplied source file is
  8644. * rewritten using the supplied source map. Note: The resolution for the
  8645. * resulting mappings is the minimium of this map and the supplied map.
  8646. *
  8647. * @param aSourceMapConsumer The source map to be applied.
  8648. * @param aSourceFile Optional. The filename of the source file.
  8649. * If omitted, SourceMapConsumer's file property will be used.
  8650. * @param aSourceMapPath Optional. The dirname of the path to the source map
  8651. * to be applied. If relative, it is relative to the SourceMapConsumer.
  8652. * This parameter is needed when the two source maps aren't in the same
  8653. * directory, and the source map to be applied contains relative source
  8654. * paths. If so, those relative source paths need to be rewritten
  8655. * relative to the SourceMapGenerator.
  8656. */
  8657. SourceMapGenerator.prototype.applySourceMap =
  8658. function SourceMapGenerator_applySourceMap(aSourceMapConsumer, aSourceFile, aSourceMapPath) {
  8659. var sourceFile = aSourceFile;
  8660. // If aSourceFile is omitted, we will use the file property of the SourceMap
  8661. if (aSourceFile == null) {
  8662. if (aSourceMapConsumer.file == null) {
  8663. throw new Error(
  8664. 'SourceMapGenerator.prototype.applySourceMap requires either an explicit source file, ' +
  8665. 'or the source map\'s "file" property. Both were omitted.'
  8666. );
  8667. }
  8668. sourceFile = aSourceMapConsumer.file;
  8669. }
  8670. var sourceRoot = this._sourceRoot;
  8671. // Make "sourceFile" relative if an absolute Url is passed.
  8672. if (sourceRoot != null) {
  8673. sourceFile = util.relative(sourceRoot, sourceFile);
  8674. }
  8675. // Applying the SourceMap can add and remove items from the sources and
  8676. // the names array.
  8677. var newSources = new ArraySet();
  8678. var newNames = new ArraySet();
  8679. // Find mappings for the "sourceFile"
  8680. this._mappings.unsortedForEach(function (mapping) {
  8681. if (mapping.source === sourceFile && mapping.originalLine != null) {
  8682. // Check if it can be mapped by the source map, then update the mapping.
  8683. var original = aSourceMapConsumer.originalPositionFor({
  8684. line: mapping.originalLine,
  8685. column: mapping.originalColumn
  8686. });
  8687. if (original.source != null) {
  8688. // Copy mapping
  8689. mapping.source = original.source;
  8690. if (aSourceMapPath != null) {
  8691. mapping.source = util.join(aSourceMapPath, mapping.source);
  8692. }
  8693. if (sourceRoot != null) {
  8694. mapping.source = util.relative(sourceRoot, mapping.source);
  8695. }
  8696. mapping.originalLine = original.line;
  8697. mapping.originalColumn = original.column;
  8698. if (original.name != null) {
  8699. mapping.name = original.name;
  8700. }
  8701. }
  8702. }
  8703. var source = mapping.source;
  8704. if (source != null && !newSources.has(source)) {
  8705. newSources.add(source);
  8706. }
  8707. var name = mapping.name;
  8708. if (name != null && !newNames.has(name)) {
  8709. newNames.add(name);
  8710. }
  8711. }, this);
  8712. this._sources = newSources;
  8713. this._names = newNames;
  8714. // Copy sourcesContents of applied map.
  8715. aSourceMapConsumer.sources.forEach(function (sourceFile) {
  8716. var content = aSourceMapConsumer.sourceContentFor(sourceFile);
  8717. if (content != null) {
  8718. if (aSourceMapPath != null) {
  8719. sourceFile = util.join(aSourceMapPath, sourceFile);
  8720. }
  8721. if (sourceRoot != null) {
  8722. sourceFile = util.relative(sourceRoot, sourceFile);
  8723. }
  8724. this.setSourceContent(sourceFile, content);
  8725. }
  8726. }, this);
  8727. };
  8728. /**
  8729. * A mapping can have one of the three levels of data:
  8730. *
  8731. * 1. Just the generated position.
  8732. * 2. The Generated position, original position, and original source.
  8733. * 3. Generated and original position, original source, as well as a name
  8734. * token.
  8735. *
  8736. * To maintain consistency, we validate that any new mapping being added falls
  8737. * in to one of these categories.
  8738. */
  8739. SourceMapGenerator.prototype._validateMapping =
  8740. function SourceMapGenerator_validateMapping(aGenerated, aOriginal, aSource,
  8741. aName) {
  8742. // When aOriginal is truthy but has empty values for .line and .column,
  8743. // it is most likely a programmer error. In this case we throw a very
  8744. // specific error message to try to guide them the right way.
  8745. // For example: https://github.com/Polymer/polymer-bundler/pull/519
  8746. if (aOriginal && typeof aOriginal.line !== 'number' && typeof aOriginal.column !== 'number') {
  8747. throw new Error(
  8748. 'original.line and original.column are not numbers -- you probably meant to omit ' +
  8749. 'the original mapping entirely and only map the generated position. If so, pass ' +
  8750. 'null for the original mapping instead of an object with empty or null values.'
  8751. );
  8752. }
  8753. if (aGenerated && 'line' in aGenerated && 'column' in aGenerated
  8754. && aGenerated.line > 0 && aGenerated.column >= 0
  8755. && !aOriginal && !aSource && !aName) {
  8756. // Case 1.
  8757. return;
  8758. }
  8759. else if (aGenerated && 'line' in aGenerated && 'column' in aGenerated
  8760. && aOriginal && 'line' in aOriginal && 'column' in aOriginal
  8761. && aGenerated.line > 0 && aGenerated.column >= 0
  8762. && aOriginal.line > 0 && aOriginal.column >= 0
  8763. && aSource) {
  8764. // Cases 2 and 3.
  8765. return;
  8766. }
  8767. else {
  8768. throw new Error('Invalid mapping: ' + JSON.stringify({
  8769. generated: aGenerated,
  8770. source: aSource,
  8771. original: aOriginal,
  8772. name: aName
  8773. }));
  8774. }
  8775. };
  8776. /**
  8777. * Serialize the accumulated mappings in to the stream of base 64 VLQs
  8778. * specified by the source map format.
  8779. */
  8780. SourceMapGenerator.prototype._serializeMappings =
  8781. function SourceMapGenerator_serializeMappings() {
  8782. var previousGeneratedColumn = 0;
  8783. var previousGeneratedLine = 1;
  8784. var previousOriginalColumn = 0;
  8785. var previousOriginalLine = 0;
  8786. var previousName = 0;
  8787. var previousSource = 0;
  8788. var result = '';
  8789. var next;
  8790. var mapping;
  8791. var nameIdx;
  8792. var sourceIdx;
  8793. var mappings = this._mappings.toArray();
  8794. for (var i = 0, len = mappings.length; i < len; i++) {
  8795. mapping = mappings[i];
  8796. next = '';
  8797. if (mapping.generatedLine !== previousGeneratedLine) {
  8798. previousGeneratedColumn = 0;
  8799. while (mapping.generatedLine !== previousGeneratedLine) {
  8800. next += ';';
  8801. previousGeneratedLine++;
  8802. }
  8803. }
  8804. else {
  8805. if (i > 0) {
  8806. if (!util.compareByGeneratedPositionsInflated(mapping, mappings[i - 1])) {
  8807. continue;
  8808. }
  8809. next += ',';
  8810. }
  8811. }
  8812. next += base64VLQ.encode(mapping.generatedColumn
  8813. - previousGeneratedColumn);
  8814. previousGeneratedColumn = mapping.generatedColumn;
  8815. if (mapping.source != null) {
  8816. sourceIdx = this._sources.indexOf(mapping.source);
  8817. next += base64VLQ.encode(sourceIdx - previousSource);
  8818. previousSource = sourceIdx;
  8819. // lines are stored 0-based in SourceMap spec version 3
  8820. next += base64VLQ.encode(mapping.originalLine - 1
  8821. - previousOriginalLine);
  8822. previousOriginalLine = mapping.originalLine - 1;
  8823. next += base64VLQ.encode(mapping.originalColumn
  8824. - previousOriginalColumn);
  8825. previousOriginalColumn = mapping.originalColumn;
  8826. if (mapping.name != null) {
  8827. nameIdx = this._names.indexOf(mapping.name);
  8828. next += base64VLQ.encode(nameIdx - previousName);
  8829. previousName = nameIdx;
  8830. }
  8831. }
  8832. result += next;
  8833. }
  8834. return result;
  8835. };
  8836. SourceMapGenerator.prototype._generateSourcesContent =
  8837. function SourceMapGenerator_generateSourcesContent(aSources, aSourceRoot) {
  8838. return aSources.map(function (source) {
  8839. if (!this._sourcesContents) {
  8840. return null;
  8841. }
  8842. if (aSourceRoot != null) {
  8843. source = util.relative(aSourceRoot, source);
  8844. }
  8845. var key = util.toSetString(source);
  8846. return Object.prototype.hasOwnProperty.call(this._sourcesContents, key)
  8847. ? this._sourcesContents[key]
  8848. : null;
  8849. }, this);
  8850. };
  8851. /**
  8852. * Externalize the source map.
  8853. */
  8854. SourceMapGenerator.prototype.toJSON =
  8855. function SourceMapGenerator_toJSON() {
  8856. var map = {
  8857. version: this._version,
  8858. sources: this._sources.toArray(),
  8859. names: this._names.toArray(),
  8860. mappings: this._serializeMappings()
  8861. };
  8862. if (this._file != null) {
  8863. map.file = this._file;
  8864. }
  8865. if (this._sourceRoot != null) {
  8866. map.sourceRoot = this._sourceRoot;
  8867. }
  8868. if (this._sourcesContents) {
  8869. map.sourcesContent = this._generateSourcesContent(map.sources, map.sourceRoot);
  8870. }
  8871. return map;
  8872. };
  8873. /**
  8874. * Render the source map being generated to a string.
  8875. */
  8876. SourceMapGenerator.prototype.toString =
  8877. function SourceMapGenerator_toString() {
  8878. return JSON.stringify(this.toJSON());
  8879. };
  8880. sourceMapGenerator.SourceMapGenerator = SourceMapGenerator;
  8881. return sourceMapGenerator;
  8882. }
  8883. var sourceMapConsumer = {};
  8884. var binarySearch = {};
  8885. /* -*- Mode: js; js-indent-level: 2; -*- */
  8886. var hasRequiredBinarySearch;
  8887. function requireBinarySearch () {
  8888. if (hasRequiredBinarySearch) return binarySearch;
  8889. hasRequiredBinarySearch = 1;
  8890. (function (exports) {
  8891. /*
  8892. * Copyright 2011 Mozilla Foundation and contributors
  8893. * Licensed under the New BSD license. See LICENSE or:
  8894. * http://opensource.org/licenses/BSD-3-Clause
  8895. */
  8896. exports.GREATEST_LOWER_BOUND = 1;
  8897. exports.LEAST_UPPER_BOUND = 2;
  8898. /**
  8899. * Recursive implementation of binary search.
  8900. *
  8901. * @param aLow Indices here and lower do not contain the needle.
  8902. * @param aHigh Indices here and higher do not contain the needle.
  8903. * @param aNeedle The element being searched for.
  8904. * @param aHaystack The non-empty array being searched.
  8905. * @param aCompare Function which takes two elements and returns -1, 0, or 1.
  8906. * @param aBias Either 'binarySearch.GREATEST_LOWER_BOUND' or
  8907. * 'binarySearch.LEAST_UPPER_BOUND'. Specifies whether to return the
  8908. * closest element that is smaller than or greater than the one we are
  8909. * searching for, respectively, if the exact element cannot be found.
  8910. */
  8911. function recursiveSearch(aLow, aHigh, aNeedle, aHaystack, aCompare, aBias) {
  8912. // This function terminates when one of the following is true:
  8913. //
  8914. // 1. We find the exact element we are looking for.
  8915. //
  8916. // 2. We did not find the exact element, but we can return the index of
  8917. // the next-closest element.
  8918. //
  8919. // 3. We did not find the exact element, and there is no next-closest
  8920. // element than the one we are searching for, so we return -1.
  8921. var mid = Math.floor((aHigh - aLow) / 2) + aLow;
  8922. var cmp = aCompare(aNeedle, aHaystack[mid], true);
  8923. if (cmp === 0) {
  8924. // Found the element we are looking for.
  8925. return mid;
  8926. }
  8927. else if (cmp > 0) {
  8928. // Our needle is greater than aHaystack[mid].
  8929. if (aHigh - mid > 1) {
  8930. // The element is in the upper half.
  8931. return recursiveSearch(mid, aHigh, aNeedle, aHaystack, aCompare, aBias);
  8932. }
  8933. // The exact needle element was not found in this haystack. Determine if
  8934. // we are in termination case (3) or (2) and return the appropriate thing.
  8935. if (aBias == exports.LEAST_UPPER_BOUND) {
  8936. return aHigh < aHaystack.length ? aHigh : -1;
  8937. } else {
  8938. return mid;
  8939. }
  8940. }
  8941. else {
  8942. // Our needle is less than aHaystack[mid].
  8943. if (mid - aLow > 1) {
  8944. // The element is in the lower half.
  8945. return recursiveSearch(aLow, mid, aNeedle, aHaystack, aCompare, aBias);
  8946. }
  8947. // we are in termination case (3) or (2) and return the appropriate thing.
  8948. if (aBias == exports.LEAST_UPPER_BOUND) {
  8949. return mid;
  8950. } else {
  8951. return aLow < 0 ? -1 : aLow;
  8952. }
  8953. }
  8954. }
  8955. /**
  8956. * This is an implementation of binary search which will always try and return
  8957. * the index of the closest element if there is no exact hit. This is because
  8958. * mappings between original and generated line/col pairs are single points,
  8959. * and there is an implicit region between each of them, so a miss just means
  8960. * that you aren't on the very start of a region.
  8961. *
  8962. * @param aNeedle The element you are looking for.
  8963. * @param aHaystack The array that is being searched.
  8964. * @param aCompare A function which takes the needle and an element in the
  8965. * array and returns -1, 0, or 1 depending on whether the needle is less
  8966. * than, equal to, or greater than the element, respectively.
  8967. * @param aBias Either 'binarySearch.GREATEST_LOWER_BOUND' or
  8968. * 'binarySearch.LEAST_UPPER_BOUND'. Specifies whether to return the
  8969. * closest element that is smaller than or greater than the one we are
  8970. * searching for, respectively, if the exact element cannot be found.
  8971. * Defaults to 'binarySearch.GREATEST_LOWER_BOUND'.
  8972. */
  8973. exports.search = function search(aNeedle, aHaystack, aCompare, aBias) {
  8974. if (aHaystack.length === 0) {
  8975. return -1;
  8976. }
  8977. var index = recursiveSearch(-1, aHaystack.length, aNeedle, aHaystack,
  8978. aCompare, aBias || exports.GREATEST_LOWER_BOUND);
  8979. if (index < 0) {
  8980. return -1;
  8981. }
  8982. // We have found either the exact element, or the next-closest element than
  8983. // the one we are searching for. However, there may be more than one such
  8984. // element. Make sure we always return the smallest of these.
  8985. while (index - 1 >= 0) {
  8986. if (aCompare(aHaystack[index], aHaystack[index - 1], true) !== 0) {
  8987. break;
  8988. }
  8989. --index;
  8990. }
  8991. return index;
  8992. };
  8993. } (binarySearch));
  8994. return binarySearch;
  8995. }
  8996. var quickSort = {};
  8997. /* -*- Mode: js; js-indent-level: 2; -*- */
  8998. var hasRequiredQuickSort;
  8999. function requireQuickSort () {
  9000. if (hasRequiredQuickSort) return quickSort;
  9001. hasRequiredQuickSort = 1;
  9002. /*
  9003. * Copyright 2011 Mozilla Foundation and contributors
  9004. * Licensed under the New BSD license. See LICENSE or:
  9005. * http://opensource.org/licenses/BSD-3-Clause
  9006. */
  9007. // It turns out that some (most?) JavaScript engines don't self-host
  9008. // `Array.prototype.sort`. This makes sense because C++ will likely remain
  9009. // faster than JS when doing raw CPU-intensive sorting. However, when using a
  9010. // custom comparator function, calling back and forth between the VM's C++ and
  9011. // JIT'd JS is rather slow *and* loses JIT type information, resulting in
  9012. // worse generated code for the comparator function than would be optimal. In
  9013. // fact, when sorting with a comparator, these costs outweigh the benefits of
  9014. // sorting in C++. By using our own JS-implemented Quick Sort (below), we get
  9015. // a ~3500ms mean speed-up in `bench/bench.html`.
  9016. /**
  9017. * Swap the elements indexed by `x` and `y` in the array `ary`.
  9018. *
  9019. * @param {Array} ary
  9020. * The array.
  9021. * @param {Number} x
  9022. * The index of the first item.
  9023. * @param {Number} y
  9024. * The index of the second item.
  9025. */
  9026. function swap(ary, x, y) {
  9027. var temp = ary[x];
  9028. ary[x] = ary[y];
  9029. ary[y] = temp;
  9030. }
  9031. /**
  9032. * Returns a random integer within the range `low .. high` inclusive.
  9033. *
  9034. * @param {Number} low
  9035. * The lower bound on the range.
  9036. * @param {Number} high
  9037. * The upper bound on the range.
  9038. */
  9039. function randomIntInRange(low, high) {
  9040. return Math.round(low + (Math.random() * (high - low)));
  9041. }
  9042. /**
  9043. * The Quick Sort algorithm.
  9044. *
  9045. * @param {Array} ary
  9046. * An array to sort.
  9047. * @param {function} comparator
  9048. * Function to use to compare two items.
  9049. * @param {Number} p
  9050. * Start index of the array
  9051. * @param {Number} r
  9052. * End index of the array
  9053. */
  9054. function doQuickSort(ary, comparator, p, r) {
  9055. // If our lower bound is less than our upper bound, we (1) partition the
  9056. // array into two pieces and (2) recurse on each half. If it is not, this is
  9057. // the empty array and our base case.
  9058. if (p < r) {
  9059. // (1) Partitioning.
  9060. //
  9061. // The partitioning chooses a pivot between `p` and `r` and moves all
  9062. // elements that are less than or equal to the pivot to the before it, and
  9063. // all the elements that are greater than it after it. The effect is that
  9064. // once partition is done, the pivot is in the exact place it will be when
  9065. // the array is put in sorted order, and it will not need to be moved
  9066. // again. This runs in O(n) time.
  9067. // Always choose a random pivot so that an input array which is reverse
  9068. // sorted does not cause O(n^2) running time.
  9069. var pivotIndex = randomIntInRange(p, r);
  9070. var i = p - 1;
  9071. swap(ary, pivotIndex, r);
  9072. var pivot = ary[r];
  9073. // Immediately after `j` is incremented in this loop, the following hold
  9074. // true:
  9075. //
  9076. // * Every element in `ary[p .. i]` is less than or equal to the pivot.
  9077. //
  9078. // * Every element in `ary[i+1 .. j-1]` is greater than the pivot.
  9079. for (var j = p; j < r; j++) {
  9080. if (comparator(ary[j], pivot) <= 0) {
  9081. i += 1;
  9082. swap(ary, i, j);
  9083. }
  9084. }
  9085. swap(ary, i + 1, j);
  9086. var q = i + 1;
  9087. // (2) Recurse on each half.
  9088. doQuickSort(ary, comparator, p, q - 1);
  9089. doQuickSort(ary, comparator, q + 1, r);
  9090. }
  9091. }
  9092. /**
  9093. * Sort the given array in-place with the given comparator function.
  9094. *
  9095. * @param {Array} ary
  9096. * An array to sort.
  9097. * @param {function} comparator
  9098. * Function to use to compare two items.
  9099. */
  9100. quickSort.quickSort = function (ary, comparator) {
  9101. doQuickSort(ary, comparator, 0, ary.length - 1);
  9102. };
  9103. return quickSort;
  9104. }
  9105. /* -*- Mode: js; js-indent-level: 2; -*- */
  9106. var hasRequiredSourceMapConsumer;
  9107. function requireSourceMapConsumer () {
  9108. if (hasRequiredSourceMapConsumer) return sourceMapConsumer;
  9109. hasRequiredSourceMapConsumer = 1;
  9110. /*
  9111. * Copyright 2011 Mozilla Foundation and contributors
  9112. * Licensed under the New BSD license. See LICENSE or:
  9113. * http://opensource.org/licenses/BSD-3-Clause
  9114. */
  9115. var util = /*@__PURE__*/ requireUtil();
  9116. var binarySearch = /*@__PURE__*/ requireBinarySearch();
  9117. var ArraySet = /*@__PURE__*/ requireArraySet().ArraySet;
  9118. var base64VLQ = /*@__PURE__*/ requireBase64Vlq();
  9119. var quickSort = /*@__PURE__*/ requireQuickSort().quickSort;
  9120. function SourceMapConsumer(aSourceMap, aSourceMapURL) {
  9121. var sourceMap = aSourceMap;
  9122. if (typeof aSourceMap === 'string') {
  9123. sourceMap = util.parseSourceMapInput(aSourceMap);
  9124. }
  9125. return sourceMap.sections != null
  9126. ? new IndexedSourceMapConsumer(sourceMap, aSourceMapURL)
  9127. : new BasicSourceMapConsumer(sourceMap, aSourceMapURL);
  9128. }
  9129. SourceMapConsumer.fromSourceMap = function(aSourceMap, aSourceMapURL) {
  9130. return BasicSourceMapConsumer.fromSourceMap(aSourceMap, aSourceMapURL);
  9131. };
  9132. /**
  9133. * The version of the source mapping spec that we are consuming.
  9134. */
  9135. SourceMapConsumer.prototype._version = 3;
  9136. // `__generatedMappings` and `__originalMappings` are arrays that hold the
  9137. // parsed mapping coordinates from the source map's "mappings" attribute. They
  9138. // are lazily instantiated, accessed via the `_generatedMappings` and
  9139. // `_originalMappings` getters respectively, and we only parse the mappings
  9140. // and create these arrays once queried for a source location. We jump through
  9141. // these hoops because there can be many thousands of mappings, and parsing
  9142. // them is expensive, so we only want to do it if we must.
  9143. //
  9144. // Each object in the arrays is of the form:
  9145. //
  9146. // {
  9147. // generatedLine: The line number in the generated code,
  9148. // generatedColumn: The column number in the generated code,
  9149. // source: The path to the original source file that generated this
  9150. // chunk of code,
  9151. // originalLine: The line number in the original source that
  9152. // corresponds to this chunk of generated code,
  9153. // originalColumn: The column number in the original source that
  9154. // corresponds to this chunk of generated code,
  9155. // name: The name of the original symbol which generated this chunk of
  9156. // code.
  9157. // }
  9158. //
  9159. // All properties except for `generatedLine` and `generatedColumn` can be
  9160. // `null`.
  9161. //
  9162. // `_generatedMappings` is ordered by the generated positions.
  9163. //
  9164. // `_originalMappings` is ordered by the original positions.
  9165. SourceMapConsumer.prototype.__generatedMappings = null;
  9166. Object.defineProperty(SourceMapConsumer.prototype, '_generatedMappings', {
  9167. configurable: true,
  9168. enumerable: true,
  9169. get: function () {
  9170. if (!this.__generatedMappings) {
  9171. this._parseMappings(this._mappings, this.sourceRoot);
  9172. }
  9173. return this.__generatedMappings;
  9174. }
  9175. });
  9176. SourceMapConsumer.prototype.__originalMappings = null;
  9177. Object.defineProperty(SourceMapConsumer.prototype, '_originalMappings', {
  9178. configurable: true,
  9179. enumerable: true,
  9180. get: function () {
  9181. if (!this.__originalMappings) {
  9182. this._parseMappings(this._mappings, this.sourceRoot);
  9183. }
  9184. return this.__originalMappings;
  9185. }
  9186. });
  9187. SourceMapConsumer.prototype._charIsMappingSeparator =
  9188. function SourceMapConsumer_charIsMappingSeparator(aStr, index) {
  9189. var c = aStr.charAt(index);
  9190. return c === ";" || c === ",";
  9191. };
  9192. /**
  9193. * Parse the mappings in a string in to a data structure which we can easily
  9194. * query (the ordered arrays in the `this.__generatedMappings` and
  9195. * `this.__originalMappings` properties).
  9196. */
  9197. SourceMapConsumer.prototype._parseMappings =
  9198. function SourceMapConsumer_parseMappings(aStr, aSourceRoot) {
  9199. throw new Error("Subclasses must implement _parseMappings");
  9200. };
  9201. SourceMapConsumer.GENERATED_ORDER = 1;
  9202. SourceMapConsumer.ORIGINAL_ORDER = 2;
  9203. SourceMapConsumer.GREATEST_LOWER_BOUND = 1;
  9204. SourceMapConsumer.LEAST_UPPER_BOUND = 2;
  9205. /**
  9206. * Iterate over each mapping between an original source/line/column and a
  9207. * generated line/column in this source map.
  9208. *
  9209. * @param Function aCallback
  9210. * The function that is called with each mapping.
  9211. * @param Object aContext
  9212. * Optional. If specified, this object will be the value of `this` every
  9213. * time that `aCallback` is called.
  9214. * @param aOrder
  9215. * Either `SourceMapConsumer.GENERATED_ORDER` or
  9216. * `SourceMapConsumer.ORIGINAL_ORDER`. Specifies whether you want to
  9217. * iterate over the mappings sorted by the generated file's line/column
  9218. * order or the original's source/line/column order, respectively. Defaults to
  9219. * `SourceMapConsumer.GENERATED_ORDER`.
  9220. */
  9221. SourceMapConsumer.prototype.eachMapping =
  9222. function SourceMapConsumer_eachMapping(aCallback, aContext, aOrder) {
  9223. var context = aContext || null;
  9224. var order = aOrder || SourceMapConsumer.GENERATED_ORDER;
  9225. var mappings;
  9226. switch (order) {
  9227. case SourceMapConsumer.GENERATED_ORDER:
  9228. mappings = this._generatedMappings;
  9229. break;
  9230. case SourceMapConsumer.ORIGINAL_ORDER:
  9231. mappings = this._originalMappings;
  9232. break;
  9233. default:
  9234. throw new Error("Unknown order of iteration.");
  9235. }
  9236. var sourceRoot = this.sourceRoot;
  9237. mappings.map(function (mapping) {
  9238. var source = mapping.source === null ? null : this._sources.at(mapping.source);
  9239. source = util.computeSourceURL(sourceRoot, source, this._sourceMapURL);
  9240. return {
  9241. source: source,
  9242. generatedLine: mapping.generatedLine,
  9243. generatedColumn: mapping.generatedColumn,
  9244. originalLine: mapping.originalLine,
  9245. originalColumn: mapping.originalColumn,
  9246. name: mapping.name === null ? null : this._names.at(mapping.name)
  9247. };
  9248. }, this).forEach(aCallback, context);
  9249. };
  9250. /**
  9251. * Returns all generated line and column information for the original source,
  9252. * line, and column provided. If no column is provided, returns all mappings
  9253. * corresponding to a either the line we are searching for or the next
  9254. * closest line that has any mappings. Otherwise, returns all mappings
  9255. * corresponding to the given line and either the column we are searching for
  9256. * or the next closest column that has any offsets.
  9257. *
  9258. * The only argument is an object with the following properties:
  9259. *
  9260. * - source: The filename of the original source.
  9261. * - line: The line number in the original source. The line number is 1-based.
  9262. * - column: Optional. the column number in the original source.
  9263. * The column number is 0-based.
  9264. *
  9265. * and an array of objects is returned, each with the following properties:
  9266. *
  9267. * - line: The line number in the generated source, or null. The
  9268. * line number is 1-based.
  9269. * - column: The column number in the generated source, or null.
  9270. * The column number is 0-based.
  9271. */
  9272. SourceMapConsumer.prototype.allGeneratedPositionsFor =
  9273. function SourceMapConsumer_allGeneratedPositionsFor(aArgs) {
  9274. var line = util.getArg(aArgs, 'line');
  9275. // When there is no exact match, BasicSourceMapConsumer.prototype._findMapping
  9276. // returns the index of the closest mapping less than the needle. By
  9277. // setting needle.originalColumn to 0, we thus find the last mapping for
  9278. // the given line, provided such a mapping exists.
  9279. var needle = {
  9280. source: util.getArg(aArgs, 'source'),
  9281. originalLine: line,
  9282. originalColumn: util.getArg(aArgs, 'column', 0)
  9283. };
  9284. needle.source = this._findSourceIndex(needle.source);
  9285. if (needle.source < 0) {
  9286. return [];
  9287. }
  9288. var mappings = [];
  9289. var index = this._findMapping(needle,
  9290. this._originalMappings,
  9291. "originalLine",
  9292. "originalColumn",
  9293. util.compareByOriginalPositions,
  9294. binarySearch.LEAST_UPPER_BOUND);
  9295. if (index >= 0) {
  9296. var mapping = this._originalMappings[index];
  9297. if (aArgs.column === undefined) {
  9298. var originalLine = mapping.originalLine;
  9299. // Iterate until either we run out of mappings, or we run into
  9300. // a mapping for a different line than the one we found. Since
  9301. // mappings are sorted, this is guaranteed to find all mappings for
  9302. // the line we found.
  9303. while (mapping && mapping.originalLine === originalLine) {
  9304. mappings.push({
  9305. line: util.getArg(mapping, 'generatedLine', null),
  9306. column: util.getArg(mapping, 'generatedColumn', null),
  9307. lastColumn: util.getArg(mapping, 'lastGeneratedColumn', null)
  9308. });
  9309. mapping = this._originalMappings[++index];
  9310. }
  9311. } else {
  9312. var originalColumn = mapping.originalColumn;
  9313. // Iterate until either we run out of mappings, or we run into
  9314. // a mapping for a different line than the one we were searching for.
  9315. // Since mappings are sorted, this is guaranteed to find all mappings for
  9316. // the line we are searching for.
  9317. while (mapping &&
  9318. mapping.originalLine === line &&
  9319. mapping.originalColumn == originalColumn) {
  9320. mappings.push({
  9321. line: util.getArg(mapping, 'generatedLine', null),
  9322. column: util.getArg(mapping, 'generatedColumn', null),
  9323. lastColumn: util.getArg(mapping, 'lastGeneratedColumn', null)
  9324. });
  9325. mapping = this._originalMappings[++index];
  9326. }
  9327. }
  9328. }
  9329. return mappings;
  9330. };
  9331. sourceMapConsumer.SourceMapConsumer = SourceMapConsumer;
  9332. /**
  9333. * A BasicSourceMapConsumer instance represents a parsed source map which we can
  9334. * query for information about the original file positions by giving it a file
  9335. * position in the generated source.
  9336. *
  9337. * The first parameter is the raw source map (either as a JSON string, or
  9338. * already parsed to an object). According to the spec, source maps have the
  9339. * following attributes:
  9340. *
  9341. * - version: Which version of the source map spec this map is following.
  9342. * - sources: An array of URLs to the original source files.
  9343. * - names: An array of identifiers which can be referrenced by individual mappings.
  9344. * - sourceRoot: Optional. The URL root from which all sources are relative.
  9345. * - sourcesContent: Optional. An array of contents of the original source files.
  9346. * - mappings: A string of base64 VLQs which contain the actual mappings.
  9347. * - file: Optional. The generated file this source map is associated with.
  9348. *
  9349. * Here is an example source map, taken from the source map spec[0]:
  9350. *
  9351. * {
  9352. * version : 3,
  9353. * file: "out.js",
  9354. * sourceRoot : "",
  9355. * sources: ["foo.js", "bar.js"],
  9356. * names: ["src", "maps", "are", "fun"],
  9357. * mappings: "AA,AB;;ABCDE;"
  9358. * }
  9359. *
  9360. * The second parameter, if given, is a string whose value is the URL
  9361. * at which the source map was found. This URL is used to compute the
  9362. * sources array.
  9363. *
  9364. * [0]: https://docs.google.com/document/d/1U1RGAehQwRypUTovF1KRlpiOFze0b-_2gc6fAH0KY0k/edit?pli=1#
  9365. */
  9366. function BasicSourceMapConsumer(aSourceMap, aSourceMapURL) {
  9367. var sourceMap = aSourceMap;
  9368. if (typeof aSourceMap === 'string') {
  9369. sourceMap = util.parseSourceMapInput(aSourceMap);
  9370. }
  9371. var version = util.getArg(sourceMap, 'version');
  9372. var sources = util.getArg(sourceMap, 'sources');
  9373. // Sass 3.3 leaves out the 'names' array, so we deviate from the spec (which
  9374. // requires the array) to play nice here.
  9375. var names = util.getArg(sourceMap, 'names', []);
  9376. var sourceRoot = util.getArg(sourceMap, 'sourceRoot', null);
  9377. var sourcesContent = util.getArg(sourceMap, 'sourcesContent', null);
  9378. var mappings = util.getArg(sourceMap, 'mappings');
  9379. var file = util.getArg(sourceMap, 'file', null);
  9380. // Once again, Sass deviates from the spec and supplies the version as a
  9381. // string rather than a number, so we use loose equality checking here.
  9382. if (version != this._version) {
  9383. throw new Error('Unsupported version: ' + version);
  9384. }
  9385. if (sourceRoot) {
  9386. sourceRoot = util.normalize(sourceRoot);
  9387. }
  9388. sources = sources
  9389. .map(String)
  9390. // Some source maps produce relative source paths like "./foo.js" instead of
  9391. // "foo.js". Normalize these first so that future comparisons will succeed.
  9392. // See bugzil.la/1090768.
  9393. .map(util.normalize)
  9394. // Always ensure that absolute sources are internally stored relative to
  9395. // the source root, if the source root is absolute. Not doing this would
  9396. // be particularly problematic when the source root is a prefix of the
  9397. // source (valid, but why??). See github issue #199 and bugzil.la/1188982.
  9398. .map(function (source) {
  9399. return sourceRoot && util.isAbsolute(sourceRoot) && util.isAbsolute(source)
  9400. ? util.relative(sourceRoot, source)
  9401. : source;
  9402. });
  9403. // Pass `true` below to allow duplicate names and sources. While source maps
  9404. // are intended to be compressed and deduplicated, the TypeScript compiler
  9405. // sometimes generates source maps with duplicates in them. See Github issue
  9406. // #72 and bugzil.la/889492.
  9407. this._names = ArraySet.fromArray(names.map(String), true);
  9408. this._sources = ArraySet.fromArray(sources, true);
  9409. this._absoluteSources = this._sources.toArray().map(function (s) {
  9410. return util.computeSourceURL(sourceRoot, s, aSourceMapURL);
  9411. });
  9412. this.sourceRoot = sourceRoot;
  9413. this.sourcesContent = sourcesContent;
  9414. this._mappings = mappings;
  9415. this._sourceMapURL = aSourceMapURL;
  9416. this.file = file;
  9417. }
  9418. BasicSourceMapConsumer.prototype = Object.create(SourceMapConsumer.prototype);
  9419. BasicSourceMapConsumer.prototype.consumer = SourceMapConsumer;
  9420. /**
  9421. * Utility function to find the index of a source. Returns -1 if not
  9422. * found.
  9423. */
  9424. BasicSourceMapConsumer.prototype._findSourceIndex = function(aSource) {
  9425. var relativeSource = aSource;
  9426. if (this.sourceRoot != null) {
  9427. relativeSource = util.relative(this.sourceRoot, relativeSource);
  9428. }
  9429. if (this._sources.has(relativeSource)) {
  9430. return this._sources.indexOf(relativeSource);
  9431. }
  9432. // Maybe aSource is an absolute URL as returned by |sources|. In
  9433. // this case we can't simply undo the transform.
  9434. var i;
  9435. for (i = 0; i < this._absoluteSources.length; ++i) {
  9436. if (this._absoluteSources[i] == aSource) {
  9437. return i;
  9438. }
  9439. }
  9440. return -1;
  9441. };
  9442. /**
  9443. * Create a BasicSourceMapConsumer from a SourceMapGenerator.
  9444. *
  9445. * @param SourceMapGenerator aSourceMap
  9446. * The source map that will be consumed.
  9447. * @param String aSourceMapURL
  9448. * The URL at which the source map can be found (optional)
  9449. * @returns BasicSourceMapConsumer
  9450. */
  9451. BasicSourceMapConsumer.fromSourceMap =
  9452. function SourceMapConsumer_fromSourceMap(aSourceMap, aSourceMapURL) {
  9453. var smc = Object.create(BasicSourceMapConsumer.prototype);
  9454. var names = smc._names = ArraySet.fromArray(aSourceMap._names.toArray(), true);
  9455. var sources = smc._sources = ArraySet.fromArray(aSourceMap._sources.toArray(), true);
  9456. smc.sourceRoot = aSourceMap._sourceRoot;
  9457. smc.sourcesContent = aSourceMap._generateSourcesContent(smc._sources.toArray(),
  9458. smc.sourceRoot);
  9459. smc.file = aSourceMap._file;
  9460. smc._sourceMapURL = aSourceMapURL;
  9461. smc._absoluteSources = smc._sources.toArray().map(function (s) {
  9462. return util.computeSourceURL(smc.sourceRoot, s, aSourceMapURL);
  9463. });
  9464. // Because we are modifying the entries (by converting string sources and
  9465. // names to indices into the sources and names ArraySets), we have to make
  9466. // a copy of the entry or else bad things happen. Shared mutable state
  9467. // strikes again! See github issue #191.
  9468. var generatedMappings = aSourceMap._mappings.toArray().slice();
  9469. var destGeneratedMappings = smc.__generatedMappings = [];
  9470. var destOriginalMappings = smc.__originalMappings = [];
  9471. for (var i = 0, length = generatedMappings.length; i < length; i++) {
  9472. var srcMapping = generatedMappings[i];
  9473. var destMapping = new Mapping;
  9474. destMapping.generatedLine = srcMapping.generatedLine;
  9475. destMapping.generatedColumn = srcMapping.generatedColumn;
  9476. if (srcMapping.source) {
  9477. destMapping.source = sources.indexOf(srcMapping.source);
  9478. destMapping.originalLine = srcMapping.originalLine;
  9479. destMapping.originalColumn = srcMapping.originalColumn;
  9480. if (srcMapping.name) {
  9481. destMapping.name = names.indexOf(srcMapping.name);
  9482. }
  9483. destOriginalMappings.push(destMapping);
  9484. }
  9485. destGeneratedMappings.push(destMapping);
  9486. }
  9487. quickSort(smc.__originalMappings, util.compareByOriginalPositions);
  9488. return smc;
  9489. };
  9490. /**
  9491. * The version of the source mapping spec that we are consuming.
  9492. */
  9493. BasicSourceMapConsumer.prototype._version = 3;
  9494. /**
  9495. * The list of original sources.
  9496. */
  9497. Object.defineProperty(BasicSourceMapConsumer.prototype, 'sources', {
  9498. get: function () {
  9499. return this._absoluteSources.slice();
  9500. }
  9501. });
  9502. /**
  9503. * Provide the JIT with a nice shape / hidden class.
  9504. */
  9505. function Mapping() {
  9506. this.generatedLine = 0;
  9507. this.generatedColumn = 0;
  9508. this.source = null;
  9509. this.originalLine = null;
  9510. this.originalColumn = null;
  9511. this.name = null;
  9512. }
  9513. /**
  9514. * Parse the mappings in a string in to a data structure which we can easily
  9515. * query (the ordered arrays in the `this.__generatedMappings` and
  9516. * `this.__originalMappings` properties).
  9517. */
  9518. BasicSourceMapConsumer.prototype._parseMappings =
  9519. function SourceMapConsumer_parseMappings(aStr, aSourceRoot) {
  9520. var generatedLine = 1;
  9521. var previousGeneratedColumn = 0;
  9522. var previousOriginalLine = 0;
  9523. var previousOriginalColumn = 0;
  9524. var previousSource = 0;
  9525. var previousName = 0;
  9526. var length = aStr.length;
  9527. var index = 0;
  9528. var cachedSegments = {};
  9529. var temp = {};
  9530. var originalMappings = [];
  9531. var generatedMappings = [];
  9532. var mapping, str, segment, end, value;
  9533. while (index < length) {
  9534. if (aStr.charAt(index) === ';') {
  9535. generatedLine++;
  9536. index++;
  9537. previousGeneratedColumn = 0;
  9538. }
  9539. else if (aStr.charAt(index) === ',') {
  9540. index++;
  9541. }
  9542. else {
  9543. mapping = new Mapping();
  9544. mapping.generatedLine = generatedLine;
  9545. // Because each offset is encoded relative to the previous one,
  9546. // many segments often have the same encoding. We can exploit this
  9547. // fact by caching the parsed variable length fields of each segment,
  9548. // allowing us to avoid a second parse if we encounter the same
  9549. // segment again.
  9550. for (end = index; end < length; end++) {
  9551. if (this._charIsMappingSeparator(aStr, end)) {
  9552. break;
  9553. }
  9554. }
  9555. str = aStr.slice(index, end);
  9556. segment = cachedSegments[str];
  9557. if (segment) {
  9558. index += str.length;
  9559. } else {
  9560. segment = [];
  9561. while (index < end) {
  9562. base64VLQ.decode(aStr, index, temp);
  9563. value = temp.value;
  9564. index = temp.rest;
  9565. segment.push(value);
  9566. }
  9567. if (segment.length === 2) {
  9568. throw new Error('Found a source, but no line and column');
  9569. }
  9570. if (segment.length === 3) {
  9571. throw new Error('Found a source and line, but no column');
  9572. }
  9573. cachedSegments[str] = segment;
  9574. }
  9575. // Generated column.
  9576. mapping.generatedColumn = previousGeneratedColumn + segment[0];
  9577. previousGeneratedColumn = mapping.generatedColumn;
  9578. if (segment.length > 1) {
  9579. // Original source.
  9580. mapping.source = previousSource + segment[1];
  9581. previousSource += segment[1];
  9582. // Original line.
  9583. mapping.originalLine = previousOriginalLine + segment[2];
  9584. previousOriginalLine = mapping.originalLine;
  9585. // Lines are stored 0-based
  9586. mapping.originalLine += 1;
  9587. // Original column.
  9588. mapping.originalColumn = previousOriginalColumn + segment[3];
  9589. previousOriginalColumn = mapping.originalColumn;
  9590. if (segment.length > 4) {
  9591. // Original name.
  9592. mapping.name = previousName + segment[4];
  9593. previousName += segment[4];
  9594. }
  9595. }
  9596. generatedMappings.push(mapping);
  9597. if (typeof mapping.originalLine === 'number') {
  9598. originalMappings.push(mapping);
  9599. }
  9600. }
  9601. }
  9602. quickSort(generatedMappings, util.compareByGeneratedPositionsDeflated);
  9603. this.__generatedMappings = generatedMappings;
  9604. quickSort(originalMappings, util.compareByOriginalPositions);
  9605. this.__originalMappings = originalMappings;
  9606. };
  9607. /**
  9608. * Find the mapping that best matches the hypothetical "needle" mapping that
  9609. * we are searching for in the given "haystack" of mappings.
  9610. */
  9611. BasicSourceMapConsumer.prototype._findMapping =
  9612. function SourceMapConsumer_findMapping(aNeedle, aMappings, aLineName,
  9613. aColumnName, aComparator, aBias) {
  9614. // To return the position we are searching for, we must first find the
  9615. // mapping for the given position and then return the opposite position it
  9616. // points to. Because the mappings are sorted, we can use binary search to
  9617. // find the best mapping.
  9618. if (aNeedle[aLineName] <= 0) {
  9619. throw new TypeError('Line must be greater than or equal to 1, got '
  9620. + aNeedle[aLineName]);
  9621. }
  9622. if (aNeedle[aColumnName] < 0) {
  9623. throw new TypeError('Column must be greater than or equal to 0, got '
  9624. + aNeedle[aColumnName]);
  9625. }
  9626. return binarySearch.search(aNeedle, aMappings, aComparator, aBias);
  9627. };
  9628. /**
  9629. * Compute the last column for each generated mapping. The last column is
  9630. * inclusive.
  9631. */
  9632. BasicSourceMapConsumer.prototype.computeColumnSpans =
  9633. function SourceMapConsumer_computeColumnSpans() {
  9634. for (var index = 0; index < this._generatedMappings.length; ++index) {
  9635. var mapping = this._generatedMappings[index];
  9636. // Mappings do not contain a field for the last generated columnt. We
  9637. // can come up with an optimistic estimate, however, by assuming that
  9638. // mappings are contiguous (i.e. given two consecutive mappings, the
  9639. // first mapping ends where the second one starts).
  9640. if (index + 1 < this._generatedMappings.length) {
  9641. var nextMapping = this._generatedMappings[index + 1];
  9642. if (mapping.generatedLine === nextMapping.generatedLine) {
  9643. mapping.lastGeneratedColumn = nextMapping.generatedColumn - 1;
  9644. continue;
  9645. }
  9646. }
  9647. // The last mapping for each line spans the entire line.
  9648. mapping.lastGeneratedColumn = Infinity;
  9649. }
  9650. };
  9651. /**
  9652. * Returns the original source, line, and column information for the generated
  9653. * source's line and column positions provided. The only argument is an object
  9654. * with the following properties:
  9655. *
  9656. * - line: The line number in the generated source. The line number
  9657. * is 1-based.
  9658. * - column: The column number in the generated source. The column
  9659. * number is 0-based.
  9660. * - bias: Either 'SourceMapConsumer.GREATEST_LOWER_BOUND' or
  9661. * 'SourceMapConsumer.LEAST_UPPER_BOUND'. Specifies whether to return the
  9662. * closest element that is smaller than or greater than the one we are
  9663. * searching for, respectively, if the exact element cannot be found.
  9664. * Defaults to 'SourceMapConsumer.GREATEST_LOWER_BOUND'.
  9665. *
  9666. * and an object is returned with the following properties:
  9667. *
  9668. * - source: The original source file, or null.
  9669. * - line: The line number in the original source, or null. The
  9670. * line number is 1-based.
  9671. * - column: The column number in the original source, or null. The
  9672. * column number is 0-based.
  9673. * - name: The original identifier, or null.
  9674. */
  9675. BasicSourceMapConsumer.prototype.originalPositionFor =
  9676. function SourceMapConsumer_originalPositionFor(aArgs) {
  9677. var needle = {
  9678. generatedLine: util.getArg(aArgs, 'line'),
  9679. generatedColumn: util.getArg(aArgs, 'column')
  9680. };
  9681. var index = this._findMapping(
  9682. needle,
  9683. this._generatedMappings,
  9684. "generatedLine",
  9685. "generatedColumn",
  9686. util.compareByGeneratedPositionsDeflated,
  9687. util.getArg(aArgs, 'bias', SourceMapConsumer.GREATEST_LOWER_BOUND)
  9688. );
  9689. if (index >= 0) {
  9690. var mapping = this._generatedMappings[index];
  9691. if (mapping.generatedLine === needle.generatedLine) {
  9692. var source = util.getArg(mapping, 'source', null);
  9693. if (source !== null) {
  9694. source = this._sources.at(source);
  9695. source = util.computeSourceURL(this.sourceRoot, source, this._sourceMapURL);
  9696. }
  9697. var name = util.getArg(mapping, 'name', null);
  9698. if (name !== null) {
  9699. name = this._names.at(name);
  9700. }
  9701. return {
  9702. source: source,
  9703. line: util.getArg(mapping, 'originalLine', null),
  9704. column: util.getArg(mapping, 'originalColumn', null),
  9705. name: name
  9706. };
  9707. }
  9708. }
  9709. return {
  9710. source: null,
  9711. line: null,
  9712. column: null,
  9713. name: null
  9714. };
  9715. };
  9716. /**
  9717. * Return true if we have the source content for every source in the source
  9718. * map, false otherwise.
  9719. */
  9720. BasicSourceMapConsumer.prototype.hasContentsOfAllSources =
  9721. function BasicSourceMapConsumer_hasContentsOfAllSources() {
  9722. if (!this.sourcesContent) {
  9723. return false;
  9724. }
  9725. return this.sourcesContent.length >= this._sources.size() &&
  9726. !this.sourcesContent.some(function (sc) { return sc == null; });
  9727. };
  9728. /**
  9729. * Returns the original source content. The only argument is the url of the
  9730. * original source file. Returns null if no original source content is
  9731. * available.
  9732. */
  9733. BasicSourceMapConsumer.prototype.sourceContentFor =
  9734. function SourceMapConsumer_sourceContentFor(aSource, nullOnMissing) {
  9735. if (!this.sourcesContent) {
  9736. return null;
  9737. }
  9738. var index = this._findSourceIndex(aSource);
  9739. if (index >= 0) {
  9740. return this.sourcesContent[index];
  9741. }
  9742. var relativeSource = aSource;
  9743. if (this.sourceRoot != null) {
  9744. relativeSource = util.relative(this.sourceRoot, relativeSource);
  9745. }
  9746. var url;
  9747. if (this.sourceRoot != null
  9748. && (url = util.urlParse(this.sourceRoot))) {
  9749. // XXX: file:// URIs and absolute paths lead to unexpected behavior for
  9750. // many users. We can help them out when they expect file:// URIs to
  9751. // behave like it would if they were running a local HTTP server. See
  9752. // https://bugzilla.mozilla.org/show_bug.cgi?id=885597.
  9753. var fileUriAbsPath = relativeSource.replace(/^file:\/\//, "");
  9754. if (url.scheme == "file"
  9755. && this._sources.has(fileUriAbsPath)) {
  9756. return this.sourcesContent[this._sources.indexOf(fileUriAbsPath)]
  9757. }
  9758. if ((!url.path || url.path == "/")
  9759. && this._sources.has("/" + relativeSource)) {
  9760. return this.sourcesContent[this._sources.indexOf("/" + relativeSource)];
  9761. }
  9762. }
  9763. // This function is used recursively from
  9764. // IndexedSourceMapConsumer.prototype.sourceContentFor. In that case, we
  9765. // don't want to throw if we can't find the source - we just want to
  9766. // return null, so we provide a flag to exit gracefully.
  9767. if (nullOnMissing) {
  9768. return null;
  9769. }
  9770. else {
  9771. throw new Error('"' + relativeSource + '" is not in the SourceMap.');
  9772. }
  9773. };
  9774. /**
  9775. * Returns the generated line and column information for the original source,
  9776. * line, and column positions provided. The only argument is an object with
  9777. * the following properties:
  9778. *
  9779. * - source: The filename of the original source.
  9780. * - line: The line number in the original source. The line number
  9781. * is 1-based.
  9782. * - column: The column number in the original source. The column
  9783. * number is 0-based.
  9784. * - bias: Either 'SourceMapConsumer.GREATEST_LOWER_BOUND' or
  9785. * 'SourceMapConsumer.LEAST_UPPER_BOUND'. Specifies whether to return the
  9786. * closest element that is smaller than or greater than the one we are
  9787. * searching for, respectively, if the exact element cannot be found.
  9788. * Defaults to 'SourceMapConsumer.GREATEST_LOWER_BOUND'.
  9789. *
  9790. * and an object is returned with the following properties:
  9791. *
  9792. * - line: The line number in the generated source, or null. The
  9793. * line number is 1-based.
  9794. * - column: The column number in the generated source, or null.
  9795. * The column number is 0-based.
  9796. */
  9797. BasicSourceMapConsumer.prototype.generatedPositionFor =
  9798. function SourceMapConsumer_generatedPositionFor(aArgs) {
  9799. var source = util.getArg(aArgs, 'source');
  9800. source = this._findSourceIndex(source);
  9801. if (source < 0) {
  9802. return {
  9803. line: null,
  9804. column: null,
  9805. lastColumn: null
  9806. };
  9807. }
  9808. var needle = {
  9809. source: source,
  9810. originalLine: util.getArg(aArgs, 'line'),
  9811. originalColumn: util.getArg(aArgs, 'column')
  9812. };
  9813. var index = this._findMapping(
  9814. needle,
  9815. this._originalMappings,
  9816. "originalLine",
  9817. "originalColumn",
  9818. util.compareByOriginalPositions,
  9819. util.getArg(aArgs, 'bias', SourceMapConsumer.GREATEST_LOWER_BOUND)
  9820. );
  9821. if (index >= 0) {
  9822. var mapping = this._originalMappings[index];
  9823. if (mapping.source === needle.source) {
  9824. return {
  9825. line: util.getArg(mapping, 'generatedLine', null),
  9826. column: util.getArg(mapping, 'generatedColumn', null),
  9827. lastColumn: util.getArg(mapping, 'lastGeneratedColumn', null)
  9828. };
  9829. }
  9830. }
  9831. return {
  9832. line: null,
  9833. column: null,
  9834. lastColumn: null
  9835. };
  9836. };
  9837. sourceMapConsumer.BasicSourceMapConsumer = BasicSourceMapConsumer;
  9838. /**
  9839. * An IndexedSourceMapConsumer instance represents a parsed source map which
  9840. * we can query for information. It differs from BasicSourceMapConsumer in
  9841. * that it takes "indexed" source maps (i.e. ones with a "sections" field) as
  9842. * input.
  9843. *
  9844. * The first parameter is a raw source map (either as a JSON string, or already
  9845. * parsed to an object). According to the spec for indexed source maps, they
  9846. * have the following attributes:
  9847. *
  9848. * - version: Which version of the source map spec this map is following.
  9849. * - file: Optional. The generated file this source map is associated with.
  9850. * - sections: A list of section definitions.
  9851. *
  9852. * Each value under the "sections" field has two fields:
  9853. * - offset: The offset into the original specified at which this section
  9854. * begins to apply, defined as an object with a "line" and "column"
  9855. * field.
  9856. * - map: A source map definition. This source map could also be indexed,
  9857. * but doesn't have to be.
  9858. *
  9859. * Instead of the "map" field, it's also possible to have a "url" field
  9860. * specifying a URL to retrieve a source map from, but that's currently
  9861. * unsupported.
  9862. *
  9863. * Here's an example source map, taken from the source map spec[0], but
  9864. * modified to omit a section which uses the "url" field.
  9865. *
  9866. * {
  9867. * version : 3,
  9868. * file: "app.js",
  9869. * sections: [{
  9870. * offset: {line:100, column:10},
  9871. * map: {
  9872. * version : 3,
  9873. * file: "section.js",
  9874. * sources: ["foo.js", "bar.js"],
  9875. * names: ["src", "maps", "are", "fun"],
  9876. * mappings: "AAAA,E;;ABCDE;"
  9877. * }
  9878. * }],
  9879. * }
  9880. *
  9881. * The second parameter, if given, is a string whose value is the URL
  9882. * at which the source map was found. This URL is used to compute the
  9883. * sources array.
  9884. *
  9885. * [0]: https://docs.google.com/document/d/1U1RGAehQwRypUTovF1KRlpiOFze0b-_2gc6fAH0KY0k/edit#heading=h.535es3xeprgt
  9886. */
  9887. function IndexedSourceMapConsumer(aSourceMap, aSourceMapURL) {
  9888. var sourceMap = aSourceMap;
  9889. if (typeof aSourceMap === 'string') {
  9890. sourceMap = util.parseSourceMapInput(aSourceMap);
  9891. }
  9892. var version = util.getArg(sourceMap, 'version');
  9893. var sections = util.getArg(sourceMap, 'sections');
  9894. if (version != this._version) {
  9895. throw new Error('Unsupported version: ' + version);
  9896. }
  9897. this._sources = new ArraySet();
  9898. this._names = new ArraySet();
  9899. var lastOffset = {
  9900. line: -1,
  9901. column: 0
  9902. };
  9903. this._sections = sections.map(function (s) {
  9904. if (s.url) {
  9905. // The url field will require support for asynchronicity.
  9906. // See https://github.com/mozilla/source-map/issues/16
  9907. throw new Error('Support for url field in sections not implemented.');
  9908. }
  9909. var offset = util.getArg(s, 'offset');
  9910. var offsetLine = util.getArg(offset, 'line');
  9911. var offsetColumn = util.getArg(offset, 'column');
  9912. if (offsetLine < lastOffset.line ||
  9913. (offsetLine === lastOffset.line && offsetColumn < lastOffset.column)) {
  9914. throw new Error('Section offsets must be ordered and non-overlapping.');
  9915. }
  9916. lastOffset = offset;
  9917. return {
  9918. generatedOffset: {
  9919. // The offset fields are 0-based, but we use 1-based indices when
  9920. // encoding/decoding from VLQ.
  9921. generatedLine: offsetLine + 1,
  9922. generatedColumn: offsetColumn + 1
  9923. },
  9924. consumer: new SourceMapConsumer(util.getArg(s, 'map'), aSourceMapURL)
  9925. }
  9926. });
  9927. }
  9928. IndexedSourceMapConsumer.prototype = Object.create(SourceMapConsumer.prototype);
  9929. IndexedSourceMapConsumer.prototype.constructor = SourceMapConsumer;
  9930. /**
  9931. * The version of the source mapping spec that we are consuming.
  9932. */
  9933. IndexedSourceMapConsumer.prototype._version = 3;
  9934. /**
  9935. * The list of original sources.
  9936. */
  9937. Object.defineProperty(IndexedSourceMapConsumer.prototype, 'sources', {
  9938. get: function () {
  9939. var sources = [];
  9940. for (var i = 0; i < this._sections.length; i++) {
  9941. for (var j = 0; j < this._sections[i].consumer.sources.length; j++) {
  9942. sources.push(this._sections[i].consumer.sources[j]);
  9943. }
  9944. }
  9945. return sources;
  9946. }
  9947. });
  9948. /**
  9949. * Returns the original source, line, and column information for the generated
  9950. * source's line and column positions provided. The only argument is an object
  9951. * with the following properties:
  9952. *
  9953. * - line: The line number in the generated source. The line number
  9954. * is 1-based.
  9955. * - column: The column number in the generated source. The column
  9956. * number is 0-based.
  9957. *
  9958. * and an object is returned with the following properties:
  9959. *
  9960. * - source: The original source file, or null.
  9961. * - line: The line number in the original source, or null. The
  9962. * line number is 1-based.
  9963. * - column: The column number in the original source, or null. The
  9964. * column number is 0-based.
  9965. * - name: The original identifier, or null.
  9966. */
  9967. IndexedSourceMapConsumer.prototype.originalPositionFor =
  9968. function IndexedSourceMapConsumer_originalPositionFor(aArgs) {
  9969. var needle = {
  9970. generatedLine: util.getArg(aArgs, 'line'),
  9971. generatedColumn: util.getArg(aArgs, 'column')
  9972. };
  9973. // Find the section containing the generated position we're trying to map
  9974. // to an original position.
  9975. var sectionIndex = binarySearch.search(needle, this._sections,
  9976. function(needle, section) {
  9977. var cmp = needle.generatedLine - section.generatedOffset.generatedLine;
  9978. if (cmp) {
  9979. return cmp;
  9980. }
  9981. return (needle.generatedColumn -
  9982. section.generatedOffset.generatedColumn);
  9983. });
  9984. var section = this._sections[sectionIndex];
  9985. if (!section) {
  9986. return {
  9987. source: null,
  9988. line: null,
  9989. column: null,
  9990. name: null
  9991. };
  9992. }
  9993. return section.consumer.originalPositionFor({
  9994. line: needle.generatedLine -
  9995. (section.generatedOffset.generatedLine - 1),
  9996. column: needle.generatedColumn -
  9997. (section.generatedOffset.generatedLine === needle.generatedLine
  9998. ? section.generatedOffset.generatedColumn - 1
  9999. : 0),
  10000. bias: aArgs.bias
  10001. });
  10002. };
  10003. /**
  10004. * Return true if we have the source content for every source in the source
  10005. * map, false otherwise.
  10006. */
  10007. IndexedSourceMapConsumer.prototype.hasContentsOfAllSources =
  10008. function IndexedSourceMapConsumer_hasContentsOfAllSources() {
  10009. return this._sections.every(function (s) {
  10010. return s.consumer.hasContentsOfAllSources();
  10011. });
  10012. };
  10013. /**
  10014. * Returns the original source content. The only argument is the url of the
  10015. * original source file. Returns null if no original source content is
  10016. * available.
  10017. */
  10018. IndexedSourceMapConsumer.prototype.sourceContentFor =
  10019. function IndexedSourceMapConsumer_sourceContentFor(aSource, nullOnMissing) {
  10020. for (var i = 0; i < this._sections.length; i++) {
  10021. var section = this._sections[i];
  10022. var content = section.consumer.sourceContentFor(aSource, true);
  10023. if (content) {
  10024. return content;
  10025. }
  10026. }
  10027. if (nullOnMissing) {
  10028. return null;
  10029. }
  10030. else {
  10031. throw new Error('"' + aSource + '" is not in the SourceMap.');
  10032. }
  10033. };
  10034. /**
  10035. * Returns the generated line and column information for the original source,
  10036. * line, and column positions provided. The only argument is an object with
  10037. * the following properties:
  10038. *
  10039. * - source: The filename of the original source.
  10040. * - line: The line number in the original source. The line number
  10041. * is 1-based.
  10042. * - column: The column number in the original source. The column
  10043. * number is 0-based.
  10044. *
  10045. * and an object is returned with the following properties:
  10046. *
  10047. * - line: The line number in the generated source, or null. The
  10048. * line number is 1-based.
  10049. * - column: The column number in the generated source, or null.
  10050. * The column number is 0-based.
  10051. */
  10052. IndexedSourceMapConsumer.prototype.generatedPositionFor =
  10053. function IndexedSourceMapConsumer_generatedPositionFor(aArgs) {
  10054. for (var i = 0; i < this._sections.length; i++) {
  10055. var section = this._sections[i];
  10056. // Only consider this section if the requested source is in the list of
  10057. // sources of the consumer.
  10058. if (section.consumer._findSourceIndex(util.getArg(aArgs, 'source')) === -1) {
  10059. continue;
  10060. }
  10061. var generatedPosition = section.consumer.generatedPositionFor(aArgs);
  10062. if (generatedPosition) {
  10063. var ret = {
  10064. line: generatedPosition.line +
  10065. (section.generatedOffset.generatedLine - 1),
  10066. column: generatedPosition.column +
  10067. (section.generatedOffset.generatedLine === generatedPosition.line
  10068. ? section.generatedOffset.generatedColumn - 1
  10069. : 0)
  10070. };
  10071. return ret;
  10072. }
  10073. }
  10074. return {
  10075. line: null,
  10076. column: null
  10077. };
  10078. };
  10079. /**
  10080. * Parse the mappings in a string in to a data structure which we can easily
  10081. * query (the ordered arrays in the `this.__generatedMappings` and
  10082. * `this.__originalMappings` properties).
  10083. */
  10084. IndexedSourceMapConsumer.prototype._parseMappings =
  10085. function IndexedSourceMapConsumer_parseMappings(aStr, aSourceRoot) {
  10086. this.__generatedMappings = [];
  10087. this.__originalMappings = [];
  10088. for (var i = 0; i < this._sections.length; i++) {
  10089. var section = this._sections[i];
  10090. var sectionMappings = section.consumer._generatedMappings;
  10091. for (var j = 0; j < sectionMappings.length; j++) {
  10092. var mapping = sectionMappings[j];
  10093. var source = section.consumer._sources.at(mapping.source);
  10094. source = util.computeSourceURL(section.consumer.sourceRoot, source, this._sourceMapURL);
  10095. this._sources.add(source);
  10096. source = this._sources.indexOf(source);
  10097. var name = null;
  10098. if (mapping.name) {
  10099. name = section.consumer._names.at(mapping.name);
  10100. this._names.add(name);
  10101. name = this._names.indexOf(name);
  10102. }
  10103. // The mappings coming from the consumer for the section have
  10104. // generated positions relative to the start of the section, so we
  10105. // need to offset them to be relative to the start of the concatenated
  10106. // generated file.
  10107. var adjustedMapping = {
  10108. source: source,
  10109. generatedLine: mapping.generatedLine +
  10110. (section.generatedOffset.generatedLine - 1),
  10111. generatedColumn: mapping.generatedColumn +
  10112. (section.generatedOffset.generatedLine === mapping.generatedLine
  10113. ? section.generatedOffset.generatedColumn - 1
  10114. : 0),
  10115. originalLine: mapping.originalLine,
  10116. originalColumn: mapping.originalColumn,
  10117. name: name
  10118. };
  10119. this.__generatedMappings.push(adjustedMapping);
  10120. if (typeof adjustedMapping.originalLine === 'number') {
  10121. this.__originalMappings.push(adjustedMapping);
  10122. }
  10123. }
  10124. }
  10125. quickSort(this.__generatedMappings, util.compareByGeneratedPositionsDeflated);
  10126. quickSort(this.__originalMappings, util.compareByOriginalPositions);
  10127. };
  10128. sourceMapConsumer.IndexedSourceMapConsumer = IndexedSourceMapConsumer;
  10129. return sourceMapConsumer;
  10130. }
  10131. var sourceNode = {};
  10132. /* -*- Mode: js; js-indent-level: 2; -*- */
  10133. var hasRequiredSourceNode;
  10134. function requireSourceNode () {
  10135. if (hasRequiredSourceNode) return sourceNode;
  10136. hasRequiredSourceNode = 1;
  10137. /*
  10138. * Copyright 2011 Mozilla Foundation and contributors
  10139. * Licensed under the New BSD license. See LICENSE or:
  10140. * http://opensource.org/licenses/BSD-3-Clause
  10141. */
  10142. var SourceMapGenerator = /*@__PURE__*/ requireSourceMapGenerator().SourceMapGenerator;
  10143. var util = /*@__PURE__*/ requireUtil();
  10144. // Matches a Windows-style `\r\n` newline or a `\n` newline used by all other
  10145. // operating systems these days (capturing the result).
  10146. var REGEX_NEWLINE = /(\r?\n)/;
  10147. // Newline character code for charCodeAt() comparisons
  10148. var NEWLINE_CODE = 10;
  10149. // Private symbol for identifying `SourceNode`s when multiple versions of
  10150. // the source-map library are loaded. This MUST NOT CHANGE across
  10151. // versions!
  10152. var isSourceNode = "$$$isSourceNode$$$";
  10153. /**
  10154. * SourceNodes provide a way to abstract over interpolating/concatenating
  10155. * snippets of generated JavaScript source code while maintaining the line and
  10156. * column information associated with the original source code.
  10157. *
  10158. * @param aLine The original line number.
  10159. * @param aColumn The original column number.
  10160. * @param aSource The original source's filename.
  10161. * @param aChunks Optional. An array of strings which are snippets of
  10162. * generated JS, or other SourceNodes.
  10163. * @param aName The original identifier.
  10164. */
  10165. function SourceNode(aLine, aColumn, aSource, aChunks, aName) {
  10166. this.children = [];
  10167. this.sourceContents = {};
  10168. this.line = aLine == null ? null : aLine;
  10169. this.column = aColumn == null ? null : aColumn;
  10170. this.source = aSource == null ? null : aSource;
  10171. this.name = aName == null ? null : aName;
  10172. this[isSourceNode] = true;
  10173. if (aChunks != null) this.add(aChunks);
  10174. }
  10175. /**
  10176. * Creates a SourceNode from generated code and a SourceMapConsumer.
  10177. *
  10178. * @param aGeneratedCode The generated code
  10179. * @param aSourceMapConsumer The SourceMap for the generated code
  10180. * @param aRelativePath Optional. The path that relative sources in the
  10181. * SourceMapConsumer should be relative to.
  10182. */
  10183. SourceNode.fromStringWithSourceMap =
  10184. function SourceNode_fromStringWithSourceMap(aGeneratedCode, aSourceMapConsumer, aRelativePath) {
  10185. // The SourceNode we want to fill with the generated code
  10186. // and the SourceMap
  10187. var node = new SourceNode();
  10188. // All even indices of this array are one line of the generated code,
  10189. // while all odd indices are the newlines between two adjacent lines
  10190. // (since `REGEX_NEWLINE` captures its match).
  10191. // Processed fragments are accessed by calling `shiftNextLine`.
  10192. var remainingLines = aGeneratedCode.split(REGEX_NEWLINE);
  10193. var remainingLinesIndex = 0;
  10194. var shiftNextLine = function() {
  10195. var lineContents = getNextLine();
  10196. // The last line of a file might not have a newline.
  10197. var newLine = getNextLine() || "";
  10198. return lineContents + newLine;
  10199. function getNextLine() {
  10200. return remainingLinesIndex < remainingLines.length ?
  10201. remainingLines[remainingLinesIndex++] : undefined;
  10202. }
  10203. };
  10204. // We need to remember the position of "remainingLines"
  10205. var lastGeneratedLine = 1, lastGeneratedColumn = 0;
  10206. // The generate SourceNodes we need a code range.
  10207. // To extract it current and last mapping is used.
  10208. // Here we store the last mapping.
  10209. var lastMapping = null;
  10210. aSourceMapConsumer.eachMapping(function (mapping) {
  10211. if (lastMapping !== null) {
  10212. // We add the code from "lastMapping" to "mapping":
  10213. // First check if there is a new line in between.
  10214. if (lastGeneratedLine < mapping.generatedLine) {
  10215. // Associate first line with "lastMapping"
  10216. addMappingWithCode(lastMapping, shiftNextLine());
  10217. lastGeneratedLine++;
  10218. lastGeneratedColumn = 0;
  10219. // The remaining code is added without mapping
  10220. } else {
  10221. // There is no new line in between.
  10222. // Associate the code between "lastGeneratedColumn" and
  10223. // "mapping.generatedColumn" with "lastMapping"
  10224. var nextLine = remainingLines[remainingLinesIndex] || '';
  10225. var code = nextLine.substr(0, mapping.generatedColumn -
  10226. lastGeneratedColumn);
  10227. remainingLines[remainingLinesIndex] = nextLine.substr(mapping.generatedColumn -
  10228. lastGeneratedColumn);
  10229. lastGeneratedColumn = mapping.generatedColumn;
  10230. addMappingWithCode(lastMapping, code);
  10231. // No more remaining code, continue
  10232. lastMapping = mapping;
  10233. return;
  10234. }
  10235. }
  10236. // We add the generated code until the first mapping
  10237. // to the SourceNode without any mapping.
  10238. // Each line is added as separate string.
  10239. while (lastGeneratedLine < mapping.generatedLine) {
  10240. node.add(shiftNextLine());
  10241. lastGeneratedLine++;
  10242. }
  10243. if (lastGeneratedColumn < mapping.generatedColumn) {
  10244. var nextLine = remainingLines[remainingLinesIndex] || '';
  10245. node.add(nextLine.substr(0, mapping.generatedColumn));
  10246. remainingLines[remainingLinesIndex] = nextLine.substr(mapping.generatedColumn);
  10247. lastGeneratedColumn = mapping.generatedColumn;
  10248. }
  10249. lastMapping = mapping;
  10250. }, this);
  10251. // We have processed all mappings.
  10252. if (remainingLinesIndex < remainingLines.length) {
  10253. if (lastMapping) {
  10254. // Associate the remaining code in the current line with "lastMapping"
  10255. addMappingWithCode(lastMapping, shiftNextLine());
  10256. }
  10257. // and add the remaining lines without any mapping
  10258. node.add(remainingLines.splice(remainingLinesIndex).join(""));
  10259. }
  10260. // Copy sourcesContent into SourceNode
  10261. aSourceMapConsumer.sources.forEach(function (sourceFile) {
  10262. var content = aSourceMapConsumer.sourceContentFor(sourceFile);
  10263. if (content != null) {
  10264. if (aRelativePath != null) {
  10265. sourceFile = util.join(aRelativePath, sourceFile);
  10266. }
  10267. node.setSourceContent(sourceFile, content);
  10268. }
  10269. });
  10270. return node;
  10271. function addMappingWithCode(mapping, code) {
  10272. if (mapping === null || mapping.source === undefined) {
  10273. node.add(code);
  10274. } else {
  10275. var source = aRelativePath
  10276. ? util.join(aRelativePath, mapping.source)
  10277. : mapping.source;
  10278. node.add(new SourceNode(mapping.originalLine,
  10279. mapping.originalColumn,
  10280. source,
  10281. code,
  10282. mapping.name));
  10283. }
  10284. }
  10285. };
  10286. /**
  10287. * Add a chunk of generated JS to this source node.
  10288. *
  10289. * @param aChunk A string snippet of generated JS code, another instance of
  10290. * SourceNode, or an array where each member is one of those things.
  10291. */
  10292. SourceNode.prototype.add = function SourceNode_add(aChunk) {
  10293. if (Array.isArray(aChunk)) {
  10294. aChunk.forEach(function (chunk) {
  10295. this.add(chunk);
  10296. }, this);
  10297. }
  10298. else if (aChunk[isSourceNode] || typeof aChunk === "string") {
  10299. if (aChunk) {
  10300. this.children.push(aChunk);
  10301. }
  10302. }
  10303. else {
  10304. throw new TypeError(
  10305. "Expected a SourceNode, string, or an array of SourceNodes and strings. Got " + aChunk
  10306. );
  10307. }
  10308. return this;
  10309. };
  10310. /**
  10311. * Add a chunk of generated JS to the beginning of this source node.
  10312. *
  10313. * @param aChunk A string snippet of generated JS code, another instance of
  10314. * SourceNode, or an array where each member is one of those things.
  10315. */
  10316. SourceNode.prototype.prepend = function SourceNode_prepend(aChunk) {
  10317. if (Array.isArray(aChunk)) {
  10318. for (var i = aChunk.length-1; i >= 0; i--) {
  10319. this.prepend(aChunk[i]);
  10320. }
  10321. }
  10322. else if (aChunk[isSourceNode] || typeof aChunk === "string") {
  10323. this.children.unshift(aChunk);
  10324. }
  10325. else {
  10326. throw new TypeError(
  10327. "Expected a SourceNode, string, or an array of SourceNodes and strings. Got " + aChunk
  10328. );
  10329. }
  10330. return this;
  10331. };
  10332. /**
  10333. * Walk over the tree of JS snippets in this node and its children. The
  10334. * walking function is called once for each snippet of JS and is passed that
  10335. * snippet and the its original associated source's line/column location.
  10336. *
  10337. * @param aFn The traversal function.
  10338. */
  10339. SourceNode.prototype.walk = function SourceNode_walk(aFn) {
  10340. var chunk;
  10341. for (var i = 0, len = this.children.length; i < len; i++) {
  10342. chunk = this.children[i];
  10343. if (chunk[isSourceNode]) {
  10344. chunk.walk(aFn);
  10345. }
  10346. else {
  10347. if (chunk !== '') {
  10348. aFn(chunk, { source: this.source,
  10349. line: this.line,
  10350. column: this.column,
  10351. name: this.name });
  10352. }
  10353. }
  10354. }
  10355. };
  10356. /**
  10357. * Like `String.prototype.join` except for SourceNodes. Inserts `aStr` between
  10358. * each of `this.children`.
  10359. *
  10360. * @param aSep The separator.
  10361. */
  10362. SourceNode.prototype.join = function SourceNode_join(aSep) {
  10363. var newChildren;
  10364. var i;
  10365. var len = this.children.length;
  10366. if (len > 0) {
  10367. newChildren = [];
  10368. for (i = 0; i < len-1; i++) {
  10369. newChildren.push(this.children[i]);
  10370. newChildren.push(aSep);
  10371. }
  10372. newChildren.push(this.children[i]);
  10373. this.children = newChildren;
  10374. }
  10375. return this;
  10376. };
  10377. /**
  10378. * Call String.prototype.replace on the very right-most source snippet. Useful
  10379. * for trimming whitespace from the end of a source node, etc.
  10380. *
  10381. * @param aPattern The pattern to replace.
  10382. * @param aReplacement The thing to replace the pattern with.
  10383. */
  10384. SourceNode.prototype.replaceRight = function SourceNode_replaceRight(aPattern, aReplacement) {
  10385. var lastChild = this.children[this.children.length - 1];
  10386. if (lastChild[isSourceNode]) {
  10387. lastChild.replaceRight(aPattern, aReplacement);
  10388. }
  10389. else if (typeof lastChild === 'string') {
  10390. this.children[this.children.length - 1] = lastChild.replace(aPattern, aReplacement);
  10391. }
  10392. else {
  10393. this.children.push(''.replace(aPattern, aReplacement));
  10394. }
  10395. return this;
  10396. };
  10397. /**
  10398. * Set the source content for a source file. This will be added to the SourceMapGenerator
  10399. * in the sourcesContent field.
  10400. *
  10401. * @param aSourceFile The filename of the source file
  10402. * @param aSourceContent The content of the source file
  10403. */
  10404. SourceNode.prototype.setSourceContent =
  10405. function SourceNode_setSourceContent(aSourceFile, aSourceContent) {
  10406. this.sourceContents[util.toSetString(aSourceFile)] = aSourceContent;
  10407. };
  10408. /**
  10409. * Walk over the tree of SourceNodes. The walking function is called for each
  10410. * source file content and is passed the filename and source content.
  10411. *
  10412. * @param aFn The traversal function.
  10413. */
  10414. SourceNode.prototype.walkSourceContents =
  10415. function SourceNode_walkSourceContents(aFn) {
  10416. for (var i = 0, len = this.children.length; i < len; i++) {
  10417. if (this.children[i][isSourceNode]) {
  10418. this.children[i].walkSourceContents(aFn);
  10419. }
  10420. }
  10421. var sources = Object.keys(this.sourceContents);
  10422. for (var i = 0, len = sources.length; i < len; i++) {
  10423. aFn(util.fromSetString(sources[i]), this.sourceContents[sources[i]]);
  10424. }
  10425. };
  10426. /**
  10427. * Return the string representation of this source node. Walks over the tree
  10428. * and concatenates all the various snippets together to one string.
  10429. */
  10430. SourceNode.prototype.toString = function SourceNode_toString() {
  10431. var str = "";
  10432. this.walk(function (chunk) {
  10433. str += chunk;
  10434. });
  10435. return str;
  10436. };
  10437. /**
  10438. * Returns the string representation of this source node along with a source
  10439. * map.
  10440. */
  10441. SourceNode.prototype.toStringWithSourceMap = function SourceNode_toStringWithSourceMap(aArgs) {
  10442. var generated = {
  10443. code: "",
  10444. line: 1,
  10445. column: 0
  10446. };
  10447. var map = new SourceMapGenerator(aArgs);
  10448. var sourceMappingActive = false;
  10449. var lastOriginalSource = null;
  10450. var lastOriginalLine = null;
  10451. var lastOriginalColumn = null;
  10452. var lastOriginalName = null;
  10453. this.walk(function (chunk, original) {
  10454. generated.code += chunk;
  10455. if (original.source !== null
  10456. && original.line !== null
  10457. && original.column !== null) {
  10458. if(lastOriginalSource !== original.source
  10459. || lastOriginalLine !== original.line
  10460. || lastOriginalColumn !== original.column
  10461. || lastOriginalName !== original.name) {
  10462. map.addMapping({
  10463. source: original.source,
  10464. original: {
  10465. line: original.line,
  10466. column: original.column
  10467. },
  10468. generated: {
  10469. line: generated.line,
  10470. column: generated.column
  10471. },
  10472. name: original.name
  10473. });
  10474. }
  10475. lastOriginalSource = original.source;
  10476. lastOriginalLine = original.line;
  10477. lastOriginalColumn = original.column;
  10478. lastOriginalName = original.name;
  10479. sourceMappingActive = true;
  10480. } else if (sourceMappingActive) {
  10481. map.addMapping({
  10482. generated: {
  10483. line: generated.line,
  10484. column: generated.column
  10485. }
  10486. });
  10487. lastOriginalSource = null;
  10488. sourceMappingActive = false;
  10489. }
  10490. for (var idx = 0, length = chunk.length; idx < length; idx++) {
  10491. if (chunk.charCodeAt(idx) === NEWLINE_CODE) {
  10492. generated.line++;
  10493. generated.column = 0;
  10494. // Mappings end at eol
  10495. if (idx + 1 === length) {
  10496. lastOriginalSource = null;
  10497. sourceMappingActive = false;
  10498. } else if (sourceMappingActive) {
  10499. map.addMapping({
  10500. source: original.source,
  10501. original: {
  10502. line: original.line,
  10503. column: original.column
  10504. },
  10505. generated: {
  10506. line: generated.line,
  10507. column: generated.column
  10508. },
  10509. name: original.name
  10510. });
  10511. }
  10512. } else {
  10513. generated.column++;
  10514. }
  10515. }
  10516. });
  10517. this.walkSourceContents(function (sourceFile, sourceContent) {
  10518. map.setSourceContent(sourceFile, sourceContent);
  10519. });
  10520. return { code: generated.code, map: map };
  10521. };
  10522. sourceNode.SourceNode = SourceNode;
  10523. return sourceNode;
  10524. }
  10525. /*
  10526. * Copyright 2009-2011 Mozilla Foundation and contributors
  10527. * Licensed under the New BSD license. See LICENSE.txt or:
  10528. * http://opensource.org/licenses/BSD-3-Clause
  10529. */
  10530. var hasRequiredSourceMap;
  10531. function requireSourceMap () {
  10532. if (hasRequiredSourceMap) return sourceMap;
  10533. hasRequiredSourceMap = 1;
  10534. sourceMap.SourceMapGenerator = /*@__PURE__*/ requireSourceMapGenerator().SourceMapGenerator;
  10535. sourceMap.SourceMapConsumer = /*@__PURE__*/ requireSourceMapConsumer().SourceMapConsumer;
  10536. sourceMap.SourceNode = /*@__PURE__*/ requireSourceNode().SourceNode;
  10537. return sourceMap;
  10538. }
  10539. var mergeSourceMap;
  10540. var hasRequiredMergeSourceMap;
  10541. function requireMergeSourceMap () {
  10542. if (hasRequiredMergeSourceMap) return mergeSourceMap;
  10543. hasRequiredMergeSourceMap = 1;
  10544. var sourceMap = /*@__PURE__*/ requireSourceMap();
  10545. var SourceMapConsumer = sourceMap.SourceMapConsumer;
  10546. var SourceMapGenerator = sourceMap.SourceMapGenerator;
  10547. mergeSourceMap = merge;
  10548. /**
  10549. * Merge old source map and new source map and return merged.
  10550. * If old or new source map value is falsy, return another one as it is.
  10551. *
  10552. * @param {object|string} [oldMap] old source map object
  10553. * @param {object|string} [newmap] new source map object
  10554. * @return {object|undefined} merged source map object, or undefined when both old and new source map are undefined
  10555. */
  10556. function merge(oldMap, newMap) {
  10557. if (!oldMap) return newMap
  10558. if (!newMap) return oldMap
  10559. var oldMapConsumer = new SourceMapConsumer(oldMap);
  10560. var newMapConsumer = new SourceMapConsumer(newMap);
  10561. var mergedMapGenerator = new SourceMapGenerator();
  10562. // iterate on new map and overwrite original position of new map with one of old map
  10563. newMapConsumer.eachMapping(function(m) {
  10564. // pass when `originalLine` is null.
  10565. // It occurs in case that the node does not have origin in original code.
  10566. if (m.originalLine == null) return
  10567. var origPosInOldMap = oldMapConsumer.originalPositionFor({
  10568. line: m.originalLine,
  10569. column: m.originalColumn
  10570. });
  10571. if (origPosInOldMap.source == null) return
  10572. mergedMapGenerator.addMapping({
  10573. original: {
  10574. line: origPosInOldMap.line,
  10575. column: origPosInOldMap.column
  10576. },
  10577. generated: {
  10578. line: m.generatedLine,
  10579. column: m.generatedColumn
  10580. },
  10581. source: origPosInOldMap.source,
  10582. name: origPosInOldMap.name
  10583. });
  10584. });
  10585. var consumers = [oldMapConsumer, newMapConsumer];
  10586. consumers.forEach(function(consumer) {
  10587. consumer.sources.forEach(function(sourceFile) {
  10588. mergedMapGenerator._sources.add(sourceFile);
  10589. var sourceContent = consumer.sourceContentFor(sourceFile);
  10590. if (sourceContent != null) {
  10591. mergedMapGenerator.setSourceContent(sourceFile, sourceContent);
  10592. }
  10593. });
  10594. });
  10595. mergedMapGenerator._sourceRoot = oldMap.sourceRoot;
  10596. mergedMapGenerator._file = oldMap.file;
  10597. return JSON.parse(mergedMapGenerator.toString())
  10598. }
  10599. return mergeSourceMap;
  10600. }
  10601. var mergeSourceMapExports = /*@__PURE__*/ requireMergeSourceMap();
  10602. var merge = /*@__PURE__*/getDefaultExportFromCjs(mergeSourceMapExports);
  10603. const scss = (source, map, options, load = require) => {
  10604. const nodeSass = load("sass");
  10605. const { compileString, renderSync } = nodeSass;
  10606. const data = getSource(source, options.filename, options.additionalData);
  10607. let css;
  10608. let dependencies;
  10609. let sourceMap;
  10610. try {
  10611. if (compileString) {
  10612. const { pathToFileURL, fileURLToPath } = load("url");
  10613. const result = compileString(data, {
  10614. ...options,
  10615. url: pathToFileURL(options.filename),
  10616. sourceMap: !!map
  10617. });
  10618. css = result.css;
  10619. dependencies = result.loadedUrls.map((url) => fileURLToPath(url));
  10620. sourceMap = map ? result.sourceMap : void 0;
  10621. } else {
  10622. const result = renderSync({
  10623. ...options,
  10624. data,
  10625. file: options.filename,
  10626. outFile: options.filename,
  10627. sourceMap: !!map
  10628. });
  10629. css = result.css.toString();
  10630. dependencies = result.stats.includedFiles;
  10631. sourceMap = map ? JSON.parse(result.map.toString()) : void 0;
  10632. }
  10633. if (map) {
  10634. return {
  10635. code: css,
  10636. errors: [],
  10637. dependencies,
  10638. map: merge(map, sourceMap)
  10639. };
  10640. }
  10641. return { code: css, errors: [], dependencies };
  10642. } catch (e) {
  10643. return { code: "", errors: [e], dependencies: [] };
  10644. }
  10645. };
  10646. const sass = (source, map, options, load) => scss(
  10647. source,
  10648. map,
  10649. {
  10650. ...options,
  10651. indentedSyntax: true
  10652. },
  10653. load
  10654. );
  10655. const less = (source, map, options, load = require) => {
  10656. const nodeLess = load("less");
  10657. let result;
  10658. let error = null;
  10659. nodeLess.render(
  10660. getSource(source, options.filename, options.additionalData),
  10661. { ...options, syncImport: true },
  10662. (err, output) => {
  10663. error = err;
  10664. result = output;
  10665. }
  10666. );
  10667. if (error) return { code: "", errors: [error], dependencies: [] };
  10668. const dependencies = result.imports;
  10669. if (map) {
  10670. return {
  10671. code: result.css.toString(),
  10672. map: merge(map, result.map),
  10673. errors: [],
  10674. dependencies
  10675. };
  10676. }
  10677. return {
  10678. code: result.css.toString(),
  10679. errors: [],
  10680. dependencies
  10681. };
  10682. };
  10683. const styl = (source, map, options, load = require) => {
  10684. const nodeStylus = load("stylus");
  10685. try {
  10686. const ref = nodeStylus(source, options);
  10687. if (map) ref.set("sourcemap", { inline: false, comment: false });
  10688. const result = ref.render();
  10689. const dependencies = ref.deps();
  10690. if (map) {
  10691. return {
  10692. code: result,
  10693. map: merge(map, ref.sourcemap),
  10694. errors: [],
  10695. dependencies
  10696. };
  10697. }
  10698. return { code: result, errors: [], dependencies };
  10699. } catch (e) {
  10700. return { code: "", errors: [e], dependencies: [] };
  10701. }
  10702. };
  10703. function getSource(source, filename, additionalData) {
  10704. if (!additionalData) return source;
  10705. if (shared.isFunction(additionalData)) {
  10706. return additionalData(source, filename);
  10707. }
  10708. return additionalData + source;
  10709. }
  10710. const processors = {
  10711. less,
  10712. sass,
  10713. scss,
  10714. styl,
  10715. stylus: styl
  10716. };
  10717. var build = {exports: {}};
  10718. var fs = {};
  10719. var hasRequiredFs;
  10720. function requireFs () {
  10721. if (hasRequiredFs) return fs;
  10722. hasRequiredFs = 1;
  10723. Object.defineProperty(fs, "__esModule", {
  10724. value: true
  10725. });
  10726. fs.getFileSystem = getFileSystem;
  10727. fs.setFileSystem = setFileSystem;
  10728. let fileSystem = {
  10729. readFile: () => {
  10730. throw Error("readFile not implemented");
  10731. },
  10732. writeFile: () => {
  10733. throw Error("writeFile not implemented");
  10734. }
  10735. };
  10736. function setFileSystem(fs) {
  10737. fileSystem.readFile = fs.readFile;
  10738. fileSystem.writeFile = fs.writeFile;
  10739. }
  10740. function getFileSystem() {
  10741. return fileSystem;
  10742. }
  10743. return fs;
  10744. }
  10745. var pluginFactory = {};
  10746. var unquote = {};
  10747. var hasRequiredUnquote;
  10748. function requireUnquote () {
  10749. if (hasRequiredUnquote) return unquote;
  10750. hasRequiredUnquote = 1;
  10751. Object.defineProperty(unquote, "__esModule", {
  10752. value: true
  10753. });
  10754. unquote.default = unquote$1;
  10755. // copied from https://github.com/lakenen/node-unquote
  10756. const reg = /['"]/;
  10757. function unquote$1(str) {
  10758. if (!str) {
  10759. return "";
  10760. }
  10761. if (reg.test(str.charAt(0))) {
  10762. str = str.substr(1);
  10763. }
  10764. if (reg.test(str.charAt(str.length - 1))) {
  10765. str = str.substr(0, str.length - 1);
  10766. }
  10767. return str;
  10768. }
  10769. return unquote;
  10770. }
  10771. var Parser = {};
  10772. var replaceValueSymbols_1;
  10773. var hasRequiredReplaceValueSymbols;
  10774. function requireReplaceValueSymbols () {
  10775. if (hasRequiredReplaceValueSymbols) return replaceValueSymbols_1;
  10776. hasRequiredReplaceValueSymbols = 1;
  10777. const matchValueName = /[$]?[\w-]+/g;
  10778. const replaceValueSymbols = (value, replacements) => {
  10779. let matches;
  10780. while ((matches = matchValueName.exec(value))) {
  10781. const replacement = replacements[matches[0]];
  10782. if (replacement) {
  10783. value =
  10784. value.slice(0, matches.index) +
  10785. replacement +
  10786. value.slice(matchValueName.lastIndex);
  10787. matchValueName.lastIndex -= matches[0].length - replacement.length;
  10788. }
  10789. }
  10790. return value;
  10791. };
  10792. replaceValueSymbols_1 = replaceValueSymbols;
  10793. return replaceValueSymbols_1;
  10794. }
  10795. var replaceSymbols_1;
  10796. var hasRequiredReplaceSymbols;
  10797. function requireReplaceSymbols () {
  10798. if (hasRequiredReplaceSymbols) return replaceSymbols_1;
  10799. hasRequiredReplaceSymbols = 1;
  10800. const replaceValueSymbols = /*@__PURE__*/ requireReplaceValueSymbols();
  10801. const replaceSymbols = (css, replacements) => {
  10802. css.walk((node) => {
  10803. if (node.type === "decl" && node.value) {
  10804. node.value = replaceValueSymbols(node.value.toString(), replacements);
  10805. } else if (node.type === "rule" && node.selector) {
  10806. node.selector = replaceValueSymbols(
  10807. node.selector.toString(),
  10808. replacements
  10809. );
  10810. } else if (node.type === "atrule" && node.params) {
  10811. node.params = replaceValueSymbols(node.params.toString(), replacements);
  10812. }
  10813. });
  10814. };
  10815. replaceSymbols_1 = replaceSymbols;
  10816. return replaceSymbols_1;
  10817. }
  10818. var extractICSS_1;
  10819. var hasRequiredExtractICSS;
  10820. function requireExtractICSS () {
  10821. if (hasRequiredExtractICSS) return extractICSS_1;
  10822. hasRequiredExtractICSS = 1;
  10823. const importPattern = /^:import\(("[^"]*"|'[^']*'|[^"']+)\)$/;
  10824. const balancedQuotes = /^("[^"]*"|'[^']*'|[^"']+)$/;
  10825. const getDeclsObject = (rule) => {
  10826. const object = {};
  10827. rule.walkDecls((decl) => {
  10828. const before = decl.raws.before ? decl.raws.before.trim() : "";
  10829. object[before + decl.prop] = decl.value;
  10830. });
  10831. return object;
  10832. };
  10833. /**
  10834. *
  10835. * @param {string} css
  10836. * @param {boolean} removeRules
  10837. * @param {'auto' | 'rule' | 'at-rule'} mode
  10838. */
  10839. const extractICSS = (css, removeRules = true, mode = "auto") => {
  10840. const icssImports = {};
  10841. const icssExports = {};
  10842. function addImports(node, path) {
  10843. const unquoted = path.replace(/'|"/g, "");
  10844. icssImports[unquoted] = Object.assign(
  10845. icssImports[unquoted] || {},
  10846. getDeclsObject(node)
  10847. );
  10848. if (removeRules) {
  10849. node.remove();
  10850. }
  10851. }
  10852. function addExports(node) {
  10853. Object.assign(icssExports, getDeclsObject(node));
  10854. if (removeRules) {
  10855. node.remove();
  10856. }
  10857. }
  10858. css.each((node) => {
  10859. if (node.type === "rule" && mode !== "at-rule") {
  10860. if (node.selector.slice(0, 7) === ":import") {
  10861. const matches = importPattern.exec(node.selector);
  10862. if (matches) {
  10863. addImports(node, matches[1]);
  10864. }
  10865. }
  10866. if (node.selector === ":export") {
  10867. addExports(node);
  10868. }
  10869. }
  10870. if (node.type === "atrule" && mode !== "rule") {
  10871. if (node.name === "icss-import") {
  10872. const matches = balancedQuotes.exec(node.params);
  10873. if (matches) {
  10874. addImports(node, matches[1]);
  10875. }
  10876. }
  10877. if (node.name === "icss-export") {
  10878. addExports(node);
  10879. }
  10880. }
  10881. });
  10882. return { icssImports, icssExports };
  10883. };
  10884. extractICSS_1 = extractICSS;
  10885. return extractICSS_1;
  10886. }
  10887. var createICSSRules_1;
  10888. var hasRequiredCreateICSSRules;
  10889. function requireCreateICSSRules () {
  10890. if (hasRequiredCreateICSSRules) return createICSSRules_1;
  10891. hasRequiredCreateICSSRules = 1;
  10892. const createImports = (imports, postcss, mode = "rule") => {
  10893. return Object.keys(imports).map((path) => {
  10894. const aliases = imports[path];
  10895. const declarations = Object.keys(aliases).map((key) =>
  10896. postcss.decl({
  10897. prop: key,
  10898. value: aliases[key],
  10899. raws: { before: "\n " },
  10900. })
  10901. );
  10902. const hasDeclarations = declarations.length > 0;
  10903. const rule =
  10904. mode === "rule"
  10905. ? postcss.rule({
  10906. selector: `:import('${path}')`,
  10907. raws: { after: hasDeclarations ? "\n" : "" },
  10908. })
  10909. : postcss.atRule({
  10910. name: "icss-import",
  10911. params: `'${path}'`,
  10912. raws: { after: hasDeclarations ? "\n" : "" },
  10913. });
  10914. if (hasDeclarations) {
  10915. rule.append(declarations);
  10916. }
  10917. return rule;
  10918. });
  10919. };
  10920. const createExports = (exports, postcss, mode = "rule") => {
  10921. const declarations = Object.keys(exports).map((key) =>
  10922. postcss.decl({
  10923. prop: key,
  10924. value: exports[key],
  10925. raws: { before: "\n " },
  10926. })
  10927. );
  10928. if (declarations.length === 0) {
  10929. return [];
  10930. }
  10931. const rule =
  10932. mode === "rule"
  10933. ? postcss.rule({
  10934. selector: `:export`,
  10935. raws: { after: "\n" },
  10936. })
  10937. : postcss.atRule({
  10938. name: "icss-export",
  10939. raws: { after: "\n" },
  10940. });
  10941. rule.append(declarations);
  10942. return [rule];
  10943. };
  10944. const createICSSRules = (imports, exports, postcss, mode) => [
  10945. ...createImports(imports, postcss, mode),
  10946. ...createExports(exports, postcss, mode),
  10947. ];
  10948. createICSSRules_1 = createICSSRules;
  10949. return createICSSRules_1;
  10950. }
  10951. var src$4;
  10952. var hasRequiredSrc$4;
  10953. function requireSrc$4 () {
  10954. if (hasRequiredSrc$4) return src$4;
  10955. hasRequiredSrc$4 = 1;
  10956. const replaceValueSymbols = /*@__PURE__*/ requireReplaceValueSymbols();
  10957. const replaceSymbols = /*@__PURE__*/ requireReplaceSymbols();
  10958. const extractICSS = /*@__PURE__*/ requireExtractICSS();
  10959. const createICSSRules = /*@__PURE__*/ requireCreateICSSRules();
  10960. src$4 = {
  10961. replaceValueSymbols,
  10962. replaceSymbols,
  10963. extractICSS,
  10964. createICSSRules,
  10965. };
  10966. return src$4;
  10967. }
  10968. var hasRequiredParser;
  10969. function requireParser () {
  10970. if (hasRequiredParser) return Parser;
  10971. hasRequiredParser = 1;
  10972. Object.defineProperty(Parser, "__esModule", {
  10973. value: true
  10974. });
  10975. Parser.default = void 0;
  10976. var _icssUtils = /*@__PURE__*/ requireSrc$4();
  10977. // Initially copied from https://github.com/css-modules/css-modules-loader-core
  10978. const importRegexp = /^:import\((.+)\)$/;
  10979. let Parser$1 = class Parser {
  10980. constructor(pathFetcher, trace) {
  10981. this.pathFetcher = pathFetcher;
  10982. this.plugin = this.plugin.bind(this);
  10983. this.exportTokens = {};
  10984. this.translations = {};
  10985. this.trace = trace;
  10986. }
  10987. plugin() {
  10988. const parser = this;
  10989. return {
  10990. postcssPlugin: "css-modules-parser",
  10991. async OnceExit(css) {
  10992. await Promise.all(parser.fetchAllImports(css));
  10993. parser.linkImportedSymbols(css);
  10994. return parser.extractExports(css);
  10995. }
  10996. };
  10997. }
  10998. fetchAllImports(css) {
  10999. let imports = [];
  11000. css.each(node => {
  11001. if (node.type == "rule" && node.selector.match(importRegexp)) {
  11002. imports.push(this.fetchImport(node, css.source.input.from, imports.length));
  11003. }
  11004. });
  11005. return imports;
  11006. }
  11007. linkImportedSymbols(css) {
  11008. (0, _icssUtils.replaceSymbols)(css, this.translations);
  11009. }
  11010. extractExports(css) {
  11011. css.each(node => {
  11012. if (node.type == "rule" && node.selector == ":export") this.handleExport(node);
  11013. });
  11014. }
  11015. handleExport(exportNode) {
  11016. exportNode.each(decl => {
  11017. if (decl.type == "decl") {
  11018. Object.keys(this.translations).forEach(translation => {
  11019. decl.value = decl.value.replace(translation, this.translations[translation]);
  11020. });
  11021. this.exportTokens[decl.prop] = decl.value;
  11022. }
  11023. });
  11024. exportNode.remove();
  11025. }
  11026. async fetchImport(importNode, relativeTo, depNr) {
  11027. const file = importNode.selector.match(importRegexp)[1];
  11028. const depTrace = this.trace + String.fromCharCode(depNr);
  11029. const exports = await this.pathFetcher(file, relativeTo, depTrace);
  11030. try {
  11031. importNode.each(decl => {
  11032. if (decl.type == "decl") {
  11033. this.translations[decl.prop] = exports[decl.value];
  11034. }
  11035. });
  11036. importNode.remove();
  11037. } catch (err) {
  11038. console.log(err);
  11039. }
  11040. }
  11041. };
  11042. Parser.default = Parser$1;
  11043. return Parser;
  11044. }
  11045. var saveJSON = {};
  11046. var hasRequiredSaveJSON;
  11047. function requireSaveJSON () {
  11048. if (hasRequiredSaveJSON) return saveJSON;
  11049. hasRequiredSaveJSON = 1;
  11050. Object.defineProperty(saveJSON, "__esModule", {
  11051. value: true
  11052. });
  11053. saveJSON.default = saveJSON$1;
  11054. var _fs = /*@__PURE__*/ requireFs();
  11055. function saveJSON$1(cssFile, json) {
  11056. return new Promise((resolve, reject) => {
  11057. const {
  11058. writeFile
  11059. } = (0, _fs.getFileSystem)();
  11060. writeFile(`${cssFile}.json`, JSON.stringify(json), e => e ? reject(e) : resolve(json));
  11061. });
  11062. }
  11063. return saveJSON;
  11064. }
  11065. var localsConvention = {};
  11066. /**
  11067. * lodash (Custom Build) <https://lodash.com/>
  11068. * Build: `lodash modularize exports="npm" -o ./`
  11069. * Copyright jQuery Foundation and other contributors <https://jquery.org/>
  11070. * Released under MIT license <https://lodash.com/license>
  11071. * Based on Underscore.js 1.8.3 <http://underscorejs.org/LICENSE>
  11072. * Copyright Jeremy Ashkenas, DocumentCloud and Investigative Reporters & Editors
  11073. */
  11074. var lodash_camelcase;
  11075. var hasRequiredLodash_camelcase;
  11076. function requireLodash_camelcase () {
  11077. if (hasRequiredLodash_camelcase) return lodash_camelcase;
  11078. hasRequiredLodash_camelcase = 1;
  11079. /** Used as references for various `Number` constants. */
  11080. var INFINITY = 1 / 0;
  11081. /** `Object#toString` result references. */
  11082. var symbolTag = '[object Symbol]';
  11083. /** Used to match words composed of alphanumeric characters. */
  11084. var reAsciiWord = /[^\x00-\x2f\x3a-\x40\x5b-\x60\x7b-\x7f]+/g;
  11085. /** Used to match Latin Unicode letters (excluding mathematical operators). */
  11086. var reLatin = /[\xc0-\xd6\xd8-\xf6\xf8-\xff\u0100-\u017f]/g;
  11087. /** Used to compose unicode character classes. */
  11088. var rsAstralRange = '\\ud800-\\udfff',
  11089. rsComboMarksRange = '\\u0300-\\u036f\\ufe20-\\ufe23',
  11090. rsComboSymbolsRange = '\\u20d0-\\u20f0',
  11091. rsDingbatRange = '\\u2700-\\u27bf',
  11092. rsLowerRange = 'a-z\\xdf-\\xf6\\xf8-\\xff',
  11093. rsMathOpRange = '\\xac\\xb1\\xd7\\xf7',
  11094. rsNonCharRange = '\\x00-\\x2f\\x3a-\\x40\\x5b-\\x60\\x7b-\\xbf',
  11095. rsPunctuationRange = '\\u2000-\\u206f',
  11096. 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',
  11097. rsUpperRange = 'A-Z\\xc0-\\xd6\\xd8-\\xde',
  11098. rsVarRange = '\\ufe0e\\ufe0f',
  11099. rsBreakRange = rsMathOpRange + rsNonCharRange + rsPunctuationRange + rsSpaceRange;
  11100. /** Used to compose unicode capture groups. */
  11101. var rsApos = "['\u2019]",
  11102. rsAstral = '[' + rsAstralRange + ']',
  11103. rsBreak = '[' + rsBreakRange + ']',
  11104. rsCombo = '[' + rsComboMarksRange + rsComboSymbolsRange + ']',
  11105. rsDigits = '\\d+',
  11106. rsDingbat = '[' + rsDingbatRange + ']',
  11107. rsLower = '[' + rsLowerRange + ']',
  11108. rsMisc = '[^' + rsAstralRange + rsBreakRange + rsDigits + rsDingbatRange + rsLowerRange + rsUpperRange + ']',
  11109. rsFitz = '\\ud83c[\\udffb-\\udfff]',
  11110. rsModifier = '(?:' + rsCombo + '|' + rsFitz + ')',
  11111. rsNonAstral = '[^' + rsAstralRange + ']',
  11112. rsRegional = '(?:\\ud83c[\\udde6-\\uddff]){2}',
  11113. rsSurrPair = '[\\ud800-\\udbff][\\udc00-\\udfff]',
  11114. rsUpper = '[' + rsUpperRange + ']',
  11115. rsZWJ = '\\u200d';
  11116. /** Used to compose unicode regexes. */
  11117. var rsLowerMisc = '(?:' + rsLower + '|' + rsMisc + ')',
  11118. rsUpperMisc = '(?:' + rsUpper + '|' + rsMisc + ')',
  11119. rsOptLowerContr = '(?:' + rsApos + '(?:d|ll|m|re|s|t|ve))?',
  11120. rsOptUpperContr = '(?:' + rsApos + '(?:D|LL|M|RE|S|T|VE))?',
  11121. reOptMod = rsModifier + '?',
  11122. rsOptVar = '[' + rsVarRange + ']?',
  11123. rsOptJoin = '(?:' + rsZWJ + '(?:' + [rsNonAstral, rsRegional, rsSurrPair].join('|') + ')' + rsOptVar + reOptMod + ')*',
  11124. rsSeq = rsOptVar + reOptMod + rsOptJoin,
  11125. rsEmoji = '(?:' + [rsDingbat, rsRegional, rsSurrPair].join('|') + ')' + rsSeq,
  11126. rsSymbol = '(?:' + [rsNonAstral + rsCombo + '?', rsCombo, rsRegional, rsSurrPair, rsAstral].join('|') + ')';
  11127. /** Used to match apostrophes. */
  11128. var reApos = RegExp(rsApos, 'g');
  11129. /**
  11130. * Used to match [combining diacritical marks](https://en.wikipedia.org/wiki/Combining_Diacritical_Marks) and
  11131. * [combining diacritical marks for symbols](https://en.wikipedia.org/wiki/Combining_Diacritical_Marks_for_Symbols).
  11132. */
  11133. var reComboMark = RegExp(rsCombo, 'g');
  11134. /** Used to match [string symbols](https://mathiasbynens.be/notes/javascript-unicode). */
  11135. var reUnicode = RegExp(rsFitz + '(?=' + rsFitz + ')|' + rsSymbol + rsSeq, 'g');
  11136. /** Used to match complex or compound words. */
  11137. var reUnicodeWord = RegExp([
  11138. rsUpper + '?' + rsLower + '+' + rsOptLowerContr + '(?=' + [rsBreak, rsUpper, '$'].join('|') + ')',
  11139. rsUpperMisc + '+' + rsOptUpperContr + '(?=' + [rsBreak, rsUpper + rsLowerMisc, '$'].join('|') + ')',
  11140. rsUpper + '?' + rsLowerMisc + '+' + rsOptLowerContr,
  11141. rsUpper + '+' + rsOptUpperContr,
  11142. rsDigits,
  11143. rsEmoji
  11144. ].join('|'), 'g');
  11145. /** 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/). */
  11146. var reHasUnicode = RegExp('[' + rsZWJ + rsAstralRange + rsComboMarksRange + rsComboSymbolsRange + rsVarRange + ']');
  11147. /** Used to detect strings that need a more robust regexp to match words. */
  11148. 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 ]/;
  11149. /** Used to map Latin Unicode letters to basic Latin letters. */
  11150. var deburredLetters = {
  11151. // Latin-1 Supplement block.
  11152. '\xc0': 'A', '\xc1': 'A', '\xc2': 'A', '\xc3': 'A', '\xc4': 'A', '\xc5': 'A',
  11153. '\xe0': 'a', '\xe1': 'a', '\xe2': 'a', '\xe3': 'a', '\xe4': 'a', '\xe5': 'a',
  11154. '\xc7': 'C', '\xe7': 'c',
  11155. '\xd0': 'D', '\xf0': 'd',
  11156. '\xc8': 'E', '\xc9': 'E', '\xca': 'E', '\xcb': 'E',
  11157. '\xe8': 'e', '\xe9': 'e', '\xea': 'e', '\xeb': 'e',
  11158. '\xcc': 'I', '\xcd': 'I', '\xce': 'I', '\xcf': 'I',
  11159. '\xec': 'i', '\xed': 'i', '\xee': 'i', '\xef': 'i',
  11160. '\xd1': 'N', '\xf1': 'n',
  11161. '\xd2': 'O', '\xd3': 'O', '\xd4': 'O', '\xd5': 'O', '\xd6': 'O', '\xd8': 'O',
  11162. '\xf2': 'o', '\xf3': 'o', '\xf4': 'o', '\xf5': 'o', '\xf6': 'o', '\xf8': 'o',
  11163. '\xd9': 'U', '\xda': 'U', '\xdb': 'U', '\xdc': 'U',
  11164. '\xf9': 'u', '\xfa': 'u', '\xfb': 'u', '\xfc': 'u',
  11165. '\xdd': 'Y', '\xfd': 'y', '\xff': 'y',
  11166. '\xc6': 'Ae', '\xe6': 'ae',
  11167. '\xde': 'Th', '\xfe': 'th',
  11168. '\xdf': 'ss',
  11169. // Latin Extended-A block.
  11170. '\u0100': 'A', '\u0102': 'A', '\u0104': 'A',
  11171. '\u0101': 'a', '\u0103': 'a', '\u0105': 'a',
  11172. '\u0106': 'C', '\u0108': 'C', '\u010a': 'C', '\u010c': 'C',
  11173. '\u0107': 'c', '\u0109': 'c', '\u010b': 'c', '\u010d': 'c',
  11174. '\u010e': 'D', '\u0110': 'D', '\u010f': 'd', '\u0111': 'd',
  11175. '\u0112': 'E', '\u0114': 'E', '\u0116': 'E', '\u0118': 'E', '\u011a': 'E',
  11176. '\u0113': 'e', '\u0115': 'e', '\u0117': 'e', '\u0119': 'e', '\u011b': 'e',
  11177. '\u011c': 'G', '\u011e': 'G', '\u0120': 'G', '\u0122': 'G',
  11178. '\u011d': 'g', '\u011f': 'g', '\u0121': 'g', '\u0123': 'g',
  11179. '\u0124': 'H', '\u0126': 'H', '\u0125': 'h', '\u0127': 'h',
  11180. '\u0128': 'I', '\u012a': 'I', '\u012c': 'I', '\u012e': 'I', '\u0130': 'I',
  11181. '\u0129': 'i', '\u012b': 'i', '\u012d': 'i', '\u012f': 'i', '\u0131': 'i',
  11182. '\u0134': 'J', '\u0135': 'j',
  11183. '\u0136': 'K', '\u0137': 'k', '\u0138': 'k',
  11184. '\u0139': 'L', '\u013b': 'L', '\u013d': 'L', '\u013f': 'L', '\u0141': 'L',
  11185. '\u013a': 'l', '\u013c': 'l', '\u013e': 'l', '\u0140': 'l', '\u0142': 'l',
  11186. '\u0143': 'N', '\u0145': 'N', '\u0147': 'N', '\u014a': 'N',
  11187. '\u0144': 'n', '\u0146': 'n', '\u0148': 'n', '\u014b': 'n',
  11188. '\u014c': 'O', '\u014e': 'O', '\u0150': 'O',
  11189. '\u014d': 'o', '\u014f': 'o', '\u0151': 'o',
  11190. '\u0154': 'R', '\u0156': 'R', '\u0158': 'R',
  11191. '\u0155': 'r', '\u0157': 'r', '\u0159': 'r',
  11192. '\u015a': 'S', '\u015c': 'S', '\u015e': 'S', '\u0160': 'S',
  11193. '\u015b': 's', '\u015d': 's', '\u015f': 's', '\u0161': 's',
  11194. '\u0162': 'T', '\u0164': 'T', '\u0166': 'T',
  11195. '\u0163': 't', '\u0165': 't', '\u0167': 't',
  11196. '\u0168': 'U', '\u016a': 'U', '\u016c': 'U', '\u016e': 'U', '\u0170': 'U', '\u0172': 'U',
  11197. '\u0169': 'u', '\u016b': 'u', '\u016d': 'u', '\u016f': 'u', '\u0171': 'u', '\u0173': 'u',
  11198. '\u0174': 'W', '\u0175': 'w',
  11199. '\u0176': 'Y', '\u0177': 'y', '\u0178': 'Y',
  11200. '\u0179': 'Z', '\u017b': 'Z', '\u017d': 'Z',
  11201. '\u017a': 'z', '\u017c': 'z', '\u017e': 'z',
  11202. '\u0132': 'IJ', '\u0133': 'ij',
  11203. '\u0152': 'Oe', '\u0153': 'oe',
  11204. '\u0149': "'n", '\u017f': 'ss'
  11205. };
  11206. /** Detect free variable `global` from Node.js. */
  11207. var freeGlobal = typeof commonjsGlobal == 'object' && commonjsGlobal && commonjsGlobal.Object === Object && commonjsGlobal;
  11208. /** Detect free variable `self`. */
  11209. var freeSelf = typeof self == 'object' && self && self.Object === Object && self;
  11210. /** Used as a reference to the global object. */
  11211. var root = freeGlobal || freeSelf || Function('return this')();
  11212. /**
  11213. * A specialized version of `_.reduce` for arrays without support for
  11214. * iteratee shorthands.
  11215. *
  11216. * @private
  11217. * @param {Array} [array] The array to iterate over.
  11218. * @param {Function} iteratee The function invoked per iteration.
  11219. * @param {*} [accumulator] The initial value.
  11220. * @param {boolean} [initAccum] Specify using the first element of `array` as
  11221. * the initial value.
  11222. * @returns {*} Returns the accumulated value.
  11223. */
  11224. function arrayReduce(array, iteratee, accumulator, initAccum) {
  11225. var index = -1,
  11226. length = array ? array.length : 0;
  11227. while (++index < length) {
  11228. accumulator = iteratee(accumulator, array[index], index, array);
  11229. }
  11230. return accumulator;
  11231. }
  11232. /**
  11233. * Converts an ASCII `string` to an array.
  11234. *
  11235. * @private
  11236. * @param {string} string The string to convert.
  11237. * @returns {Array} Returns the converted array.
  11238. */
  11239. function asciiToArray(string) {
  11240. return string.split('');
  11241. }
  11242. /**
  11243. * Splits an ASCII `string` into an array of its words.
  11244. *
  11245. * @private
  11246. * @param {string} The string to inspect.
  11247. * @returns {Array} Returns the words of `string`.
  11248. */
  11249. function asciiWords(string) {
  11250. return string.match(reAsciiWord) || [];
  11251. }
  11252. /**
  11253. * The base implementation of `_.propertyOf` without support for deep paths.
  11254. *
  11255. * @private
  11256. * @param {Object} object The object to query.
  11257. * @returns {Function} Returns the new accessor function.
  11258. */
  11259. function basePropertyOf(object) {
  11260. return function(key) {
  11261. return object == null ? undefined : object[key];
  11262. };
  11263. }
  11264. /**
  11265. * Used by `_.deburr` to convert Latin-1 Supplement and Latin Extended-A
  11266. * letters to basic Latin letters.
  11267. *
  11268. * @private
  11269. * @param {string} letter The matched letter to deburr.
  11270. * @returns {string} Returns the deburred letter.
  11271. */
  11272. var deburrLetter = basePropertyOf(deburredLetters);
  11273. /**
  11274. * Checks if `string` contains Unicode symbols.
  11275. *
  11276. * @private
  11277. * @param {string} string The string to inspect.
  11278. * @returns {boolean} Returns `true` if a symbol is found, else `false`.
  11279. */
  11280. function hasUnicode(string) {
  11281. return reHasUnicode.test(string);
  11282. }
  11283. /**
  11284. * Checks if `string` contains a word composed of Unicode symbols.
  11285. *
  11286. * @private
  11287. * @param {string} string The string to inspect.
  11288. * @returns {boolean} Returns `true` if a word is found, else `false`.
  11289. */
  11290. function hasUnicodeWord(string) {
  11291. return reHasUnicodeWord.test(string);
  11292. }
  11293. /**
  11294. * Converts `string` to an array.
  11295. *
  11296. * @private
  11297. * @param {string} string The string to convert.
  11298. * @returns {Array} Returns the converted array.
  11299. */
  11300. function stringToArray(string) {
  11301. return hasUnicode(string)
  11302. ? unicodeToArray(string)
  11303. : asciiToArray(string);
  11304. }
  11305. /**
  11306. * Converts a Unicode `string` to an array.
  11307. *
  11308. * @private
  11309. * @param {string} string The string to convert.
  11310. * @returns {Array} Returns the converted array.
  11311. */
  11312. function unicodeToArray(string) {
  11313. return string.match(reUnicode) || [];
  11314. }
  11315. /**
  11316. * Splits a Unicode `string` into an array of its words.
  11317. *
  11318. * @private
  11319. * @param {string} The string to inspect.
  11320. * @returns {Array} Returns the words of `string`.
  11321. */
  11322. function unicodeWords(string) {
  11323. return string.match(reUnicodeWord) || [];
  11324. }
  11325. /** Used for built-in method references. */
  11326. var objectProto = Object.prototype;
  11327. /**
  11328. * Used to resolve the
  11329. * [`toStringTag`](http://ecma-international.org/ecma-262/7.0/#sec-object.prototype.tostring)
  11330. * of values.
  11331. */
  11332. var objectToString = objectProto.toString;
  11333. /** Built-in value references. */
  11334. var Symbol = root.Symbol;
  11335. /** Used to convert symbols to primitives and strings. */
  11336. var symbolProto = Symbol ? Symbol.prototype : undefined,
  11337. symbolToString = symbolProto ? symbolProto.toString : undefined;
  11338. /**
  11339. * The base implementation of `_.slice` without an iteratee call guard.
  11340. *
  11341. * @private
  11342. * @param {Array} array The array to slice.
  11343. * @param {number} [start=0] The start position.
  11344. * @param {number} [end=array.length] The end position.
  11345. * @returns {Array} Returns the slice of `array`.
  11346. */
  11347. function baseSlice(array, start, end) {
  11348. var index = -1,
  11349. length = array.length;
  11350. if (start < 0) {
  11351. start = -start > length ? 0 : (length + start);
  11352. }
  11353. end = end > length ? length : end;
  11354. if (end < 0) {
  11355. end += length;
  11356. }
  11357. length = start > end ? 0 : ((end - start) >>> 0);
  11358. start >>>= 0;
  11359. var result = Array(length);
  11360. while (++index < length) {
  11361. result[index] = array[index + start];
  11362. }
  11363. return result;
  11364. }
  11365. /**
  11366. * The base implementation of `_.toString` which doesn't convert nullish
  11367. * values to empty strings.
  11368. *
  11369. * @private
  11370. * @param {*} value The value to process.
  11371. * @returns {string} Returns the string.
  11372. */
  11373. function baseToString(value) {
  11374. // Exit early for strings to avoid a performance hit in some environments.
  11375. if (typeof value == 'string') {
  11376. return value;
  11377. }
  11378. if (isSymbol(value)) {
  11379. return symbolToString ? symbolToString.call(value) : '';
  11380. }
  11381. var result = (value + '');
  11382. return (result == '0' && (1 / value) == -INFINITY) ? '-0' : result;
  11383. }
  11384. /**
  11385. * Casts `array` to a slice if it's needed.
  11386. *
  11387. * @private
  11388. * @param {Array} array The array to inspect.
  11389. * @param {number} start The start position.
  11390. * @param {number} [end=array.length] The end position.
  11391. * @returns {Array} Returns the cast slice.
  11392. */
  11393. function castSlice(array, start, end) {
  11394. var length = array.length;
  11395. end = end === undefined ? length : end;
  11396. return (!start && end >= length) ? array : baseSlice(array, start, end);
  11397. }
  11398. /**
  11399. * Creates a function like `_.lowerFirst`.
  11400. *
  11401. * @private
  11402. * @param {string} methodName The name of the `String` case method to use.
  11403. * @returns {Function} Returns the new case function.
  11404. */
  11405. function createCaseFirst(methodName) {
  11406. return function(string) {
  11407. string = toString(string);
  11408. var strSymbols = hasUnicode(string)
  11409. ? stringToArray(string)
  11410. : undefined;
  11411. var chr = strSymbols
  11412. ? strSymbols[0]
  11413. : string.charAt(0);
  11414. var trailing = strSymbols
  11415. ? castSlice(strSymbols, 1).join('')
  11416. : string.slice(1);
  11417. return chr[methodName]() + trailing;
  11418. };
  11419. }
  11420. /**
  11421. * Creates a function like `_.camelCase`.
  11422. *
  11423. * @private
  11424. * @param {Function} callback The function to combine each word.
  11425. * @returns {Function} Returns the new compounder function.
  11426. */
  11427. function createCompounder(callback) {
  11428. return function(string) {
  11429. return arrayReduce(words(deburr(string).replace(reApos, '')), callback, '');
  11430. };
  11431. }
  11432. /**
  11433. * Checks if `value` is object-like. A value is object-like if it's not `null`
  11434. * and has a `typeof` result of "object".
  11435. *
  11436. * @static
  11437. * @memberOf _
  11438. * @since 4.0.0
  11439. * @category Lang
  11440. * @param {*} value The value to check.
  11441. * @returns {boolean} Returns `true` if `value` is object-like, else `false`.
  11442. * @example
  11443. *
  11444. * _.isObjectLike({});
  11445. * // => true
  11446. *
  11447. * _.isObjectLike([1, 2, 3]);
  11448. * // => true
  11449. *
  11450. * _.isObjectLike(_.noop);
  11451. * // => false
  11452. *
  11453. * _.isObjectLike(null);
  11454. * // => false
  11455. */
  11456. function isObjectLike(value) {
  11457. return !!value && typeof value == 'object';
  11458. }
  11459. /**
  11460. * Checks if `value` is classified as a `Symbol` primitive or object.
  11461. *
  11462. * @static
  11463. * @memberOf _
  11464. * @since 4.0.0
  11465. * @category Lang
  11466. * @param {*} value The value to check.
  11467. * @returns {boolean} Returns `true` if `value` is a symbol, else `false`.
  11468. * @example
  11469. *
  11470. * _.isSymbol(Symbol.iterator);
  11471. * // => true
  11472. *
  11473. * _.isSymbol('abc');
  11474. * // => false
  11475. */
  11476. function isSymbol(value) {
  11477. return typeof value == 'symbol' ||
  11478. (isObjectLike(value) && objectToString.call(value) == symbolTag);
  11479. }
  11480. /**
  11481. * Converts `value` to a string. An empty string is returned for `null`
  11482. * and `undefined` values. The sign of `-0` is preserved.
  11483. *
  11484. * @static
  11485. * @memberOf _
  11486. * @since 4.0.0
  11487. * @category Lang
  11488. * @param {*} value The value to process.
  11489. * @returns {string} Returns the string.
  11490. * @example
  11491. *
  11492. * _.toString(null);
  11493. * // => ''
  11494. *
  11495. * _.toString(-0);
  11496. * // => '-0'
  11497. *
  11498. * _.toString([1, 2, 3]);
  11499. * // => '1,2,3'
  11500. */
  11501. function toString(value) {
  11502. return value == null ? '' : baseToString(value);
  11503. }
  11504. /**
  11505. * Converts `string` to [camel case](https://en.wikipedia.org/wiki/CamelCase).
  11506. *
  11507. * @static
  11508. * @memberOf _
  11509. * @since 3.0.0
  11510. * @category String
  11511. * @param {string} [string=''] The string to convert.
  11512. * @returns {string} Returns the camel cased string.
  11513. * @example
  11514. *
  11515. * _.camelCase('Foo Bar');
  11516. * // => 'fooBar'
  11517. *
  11518. * _.camelCase('--foo-bar--');
  11519. * // => 'fooBar'
  11520. *
  11521. * _.camelCase('__FOO_BAR__');
  11522. * // => 'fooBar'
  11523. */
  11524. var camelCase = createCompounder(function(result, word, index) {
  11525. word = word.toLowerCase();
  11526. return result + (index ? capitalize(word) : word);
  11527. });
  11528. /**
  11529. * Converts the first character of `string` to upper case and the remaining
  11530. * to lower case.
  11531. *
  11532. * @static
  11533. * @memberOf _
  11534. * @since 3.0.0
  11535. * @category String
  11536. * @param {string} [string=''] The string to capitalize.
  11537. * @returns {string} Returns the capitalized string.
  11538. * @example
  11539. *
  11540. * _.capitalize('FRED');
  11541. * // => 'Fred'
  11542. */
  11543. function capitalize(string) {
  11544. return upperFirst(toString(string).toLowerCase());
  11545. }
  11546. /**
  11547. * Deburrs `string` by converting
  11548. * [Latin-1 Supplement](https://en.wikipedia.org/wiki/Latin-1_Supplement_(Unicode_block)#Character_table)
  11549. * and [Latin Extended-A](https://en.wikipedia.org/wiki/Latin_Extended-A)
  11550. * letters to basic Latin letters and removing
  11551. * [combining diacritical marks](https://en.wikipedia.org/wiki/Combining_Diacritical_Marks).
  11552. *
  11553. * @static
  11554. * @memberOf _
  11555. * @since 3.0.0
  11556. * @category String
  11557. * @param {string} [string=''] The string to deburr.
  11558. * @returns {string} Returns the deburred string.
  11559. * @example
  11560. *
  11561. * _.deburr('déjà vu');
  11562. * // => 'deja vu'
  11563. */
  11564. function deburr(string) {
  11565. string = toString(string);
  11566. return string && string.replace(reLatin, deburrLetter).replace(reComboMark, '');
  11567. }
  11568. /**
  11569. * Converts the first character of `string` to upper case.
  11570. *
  11571. * @static
  11572. * @memberOf _
  11573. * @since 4.0.0
  11574. * @category String
  11575. * @param {string} [string=''] The string to convert.
  11576. * @returns {string} Returns the converted string.
  11577. * @example
  11578. *
  11579. * _.upperFirst('fred');
  11580. * // => 'Fred'
  11581. *
  11582. * _.upperFirst('FRED');
  11583. * // => 'FRED'
  11584. */
  11585. var upperFirst = createCaseFirst('toUpperCase');
  11586. /**
  11587. * Splits `string` into an array of its words.
  11588. *
  11589. * @static
  11590. * @memberOf _
  11591. * @since 3.0.0
  11592. * @category String
  11593. * @param {string} [string=''] The string to inspect.
  11594. * @param {RegExp|string} [pattern] The pattern to match words.
  11595. * @param- {Object} [guard] Enables use as an iteratee for methods like `_.map`.
  11596. * @returns {Array} Returns the words of `string`.
  11597. * @example
  11598. *
  11599. * _.words('fred, barney, & pebbles');
  11600. * // => ['fred', 'barney', 'pebbles']
  11601. *
  11602. * _.words('fred, barney, & pebbles', /[^, ]+/g);
  11603. * // => ['fred', 'barney', '&', 'pebbles']
  11604. */
  11605. function words(string, pattern, guard) {
  11606. string = toString(string);
  11607. pattern = pattern;
  11608. if (pattern === undefined) {
  11609. return hasUnicodeWord(string) ? unicodeWords(string) : asciiWords(string);
  11610. }
  11611. return string.match(pattern) || [];
  11612. }
  11613. lodash_camelcase = camelCase;
  11614. return lodash_camelcase;
  11615. }
  11616. var hasRequiredLocalsConvention;
  11617. function requireLocalsConvention () {
  11618. if (hasRequiredLocalsConvention) return localsConvention;
  11619. hasRequiredLocalsConvention = 1;
  11620. Object.defineProperty(localsConvention, "__esModule", {
  11621. value: true
  11622. });
  11623. localsConvention.makeLocalsConventionReducer = makeLocalsConventionReducer;
  11624. var _lodash = _interopRequireDefault(/*@__PURE__*/ requireLodash_camelcase());
  11625. function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
  11626. function dashesCamelCase(string) {
  11627. return string.replace(/-+(\w)/g, (_, firstLetter) => firstLetter.toUpperCase());
  11628. }
  11629. function makeLocalsConventionReducer(localsConvention, inputFile) {
  11630. const isFunc = typeof localsConvention === "function";
  11631. return (tokens, [className, value]) => {
  11632. if (isFunc) {
  11633. const convention = localsConvention(className, value, inputFile);
  11634. tokens[convention] = value;
  11635. return tokens;
  11636. }
  11637. switch (localsConvention) {
  11638. case "camelCase":
  11639. tokens[className] = value;
  11640. tokens[(0, _lodash.default)(className)] = value;
  11641. break;
  11642. case "camelCaseOnly":
  11643. tokens[(0, _lodash.default)(className)] = value;
  11644. break;
  11645. case "dashes":
  11646. tokens[className] = value;
  11647. tokens[dashesCamelCase(className)] = value;
  11648. break;
  11649. case "dashesOnly":
  11650. tokens[dashesCamelCase(className)] = value;
  11651. break;
  11652. }
  11653. return tokens;
  11654. };
  11655. }
  11656. return localsConvention;
  11657. }
  11658. var FileSystemLoader = {};
  11659. var hasRequiredFileSystemLoader;
  11660. function requireFileSystemLoader () {
  11661. if (hasRequiredFileSystemLoader) return FileSystemLoader;
  11662. hasRequiredFileSystemLoader = 1;
  11663. Object.defineProperty(FileSystemLoader, "__esModule", {
  11664. value: true
  11665. });
  11666. FileSystemLoader.default = void 0;
  11667. var _postcss = _interopRequireDefault(require$$0$1);
  11668. var _path = _interopRequireDefault(path$1);
  11669. var _Parser = _interopRequireDefault(/*@__PURE__*/ requireParser());
  11670. var _fs = /*@__PURE__*/ requireFs();
  11671. function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
  11672. // Initially copied from https://github.com/css-modules/css-modules-loader-core
  11673. class Core {
  11674. constructor(plugins) {
  11675. this.plugins = plugins || Core.defaultPlugins;
  11676. }
  11677. async load(sourceString, sourcePath, trace, pathFetcher) {
  11678. const parser = new _Parser.default(pathFetcher, trace);
  11679. const plugins = this.plugins.concat([parser.plugin()]);
  11680. const result = await (0, _postcss.default)(plugins).process(sourceString, {
  11681. from: sourcePath
  11682. });
  11683. return {
  11684. injectableSource: result.css,
  11685. exportTokens: parser.exportTokens
  11686. };
  11687. }
  11688. } // Sorts dependencies in the following way:
  11689. // AAA comes before AA and A
  11690. // AB comes after AA and before A
  11691. // All Bs come after all As
  11692. // This ensures that the files are always returned in the following order:
  11693. // - In the order they were required, except
  11694. // - After all their dependencies
  11695. const traceKeySorter = (a, b) => {
  11696. if (a.length < b.length) {
  11697. return a < b.substring(0, a.length) ? -1 : 1;
  11698. }
  11699. if (a.length > b.length) {
  11700. return a.substring(0, b.length) <= b ? -1 : 1;
  11701. }
  11702. return a < b ? -1 : 1;
  11703. };
  11704. let FileSystemLoader$1 = class FileSystemLoader {
  11705. constructor(root, plugins, fileResolve) {
  11706. if (root === "/" && process.platform === "win32") {
  11707. const cwdDrive = process.cwd().slice(0, 3);
  11708. if (!/^[A-Za-z]:\\$/.test(cwdDrive)) {
  11709. throw new Error(`Failed to obtain root from "${process.cwd()}".`);
  11710. }
  11711. root = cwdDrive;
  11712. }
  11713. this.root = root;
  11714. this.fileResolve = fileResolve;
  11715. this.sources = {};
  11716. this.traces = {};
  11717. this.importNr = 0;
  11718. this.core = new Core(plugins);
  11719. this.tokensByFile = {};
  11720. this.fs = (0, _fs.getFileSystem)();
  11721. }
  11722. async fetch(_newPath, relativeTo, _trace) {
  11723. const newPath = _newPath.replace(/^["']|["']$/g, "");
  11724. const trace = _trace || String.fromCharCode(this.importNr++);
  11725. const useFileResolve = typeof this.fileResolve === "function";
  11726. const fileResolvedPath = useFileResolve ? await this.fileResolve(newPath, relativeTo) : await Promise.resolve();
  11727. if (fileResolvedPath && !_path.default.isAbsolute(fileResolvedPath)) {
  11728. throw new Error('The returned path from the "fileResolve" option must be absolute.');
  11729. }
  11730. const relativeDir = _path.default.dirname(relativeTo);
  11731. const rootRelativePath = fileResolvedPath || _path.default.resolve(relativeDir, newPath);
  11732. 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
  11733. if (!useFileResolve && newPath[0] !== "." && !_path.default.isAbsolute(newPath)) {
  11734. try {
  11735. fileRelativePath = require.resolve(newPath);
  11736. } catch (e) {// noop
  11737. }
  11738. }
  11739. const tokens = this.tokensByFile[fileRelativePath];
  11740. if (tokens) return tokens;
  11741. return new Promise((resolve, reject) => {
  11742. this.fs.readFile(fileRelativePath, "utf-8", async (err, source) => {
  11743. if (err) reject(err);
  11744. const {
  11745. injectableSource,
  11746. exportTokens
  11747. } = await this.core.load(source, rootRelativePath, trace, this.fetch.bind(this));
  11748. this.sources[fileRelativePath] = injectableSource;
  11749. this.traces[trace] = fileRelativePath;
  11750. this.tokensByFile[fileRelativePath] = exportTokens;
  11751. resolve(exportTokens);
  11752. });
  11753. });
  11754. }
  11755. get finalSource() {
  11756. const traces = this.traces;
  11757. const sources = this.sources;
  11758. let written = new Set();
  11759. return Object.keys(traces).sort(traceKeySorter).map(key => {
  11760. const filename = traces[key];
  11761. if (written.has(filename)) {
  11762. return null;
  11763. }
  11764. written.add(filename);
  11765. return sources[filename];
  11766. }).join("");
  11767. }
  11768. };
  11769. FileSystemLoader.default = FileSystemLoader$1;
  11770. return FileSystemLoader;
  11771. }
  11772. var scoping = {};
  11773. var src$3 = {exports: {}};
  11774. var topologicalSort_1;
  11775. var hasRequiredTopologicalSort;
  11776. function requireTopologicalSort () {
  11777. if (hasRequiredTopologicalSort) return topologicalSort_1;
  11778. hasRequiredTopologicalSort = 1;
  11779. const PERMANENT_MARKER = 2;
  11780. const TEMPORARY_MARKER = 1;
  11781. function createError(node, graph) {
  11782. const er = new Error("Nondeterministic import's order");
  11783. const related = graph[node];
  11784. const relatedNode = related.find(
  11785. (relatedNode) => graph[relatedNode].indexOf(node) > -1
  11786. );
  11787. er.nodes = [node, relatedNode];
  11788. return er;
  11789. }
  11790. function walkGraph(node, graph, state, result, strict) {
  11791. if (state[node] === PERMANENT_MARKER) {
  11792. return;
  11793. }
  11794. if (state[node] === TEMPORARY_MARKER) {
  11795. if (strict) {
  11796. return createError(node, graph);
  11797. }
  11798. return;
  11799. }
  11800. state[node] = TEMPORARY_MARKER;
  11801. const children = graph[node];
  11802. const length = children.length;
  11803. for (let i = 0; i < length; ++i) {
  11804. const error = walkGraph(children[i], graph, state, result, strict);
  11805. if (error instanceof Error) {
  11806. return error;
  11807. }
  11808. }
  11809. state[node] = PERMANENT_MARKER;
  11810. result.push(node);
  11811. }
  11812. function topologicalSort(graph, strict) {
  11813. const result = [];
  11814. const state = {};
  11815. const nodes = Object.keys(graph);
  11816. const length = nodes.length;
  11817. for (let i = 0; i < length; ++i) {
  11818. const er = walkGraph(nodes[i], graph, state, result, strict);
  11819. if (er instanceof Error) {
  11820. return er;
  11821. }
  11822. }
  11823. return result;
  11824. }
  11825. topologicalSort_1 = topologicalSort;
  11826. return topologicalSort_1;
  11827. }
  11828. var hasRequiredSrc$3;
  11829. function requireSrc$3 () {
  11830. if (hasRequiredSrc$3) return src$3.exports;
  11831. hasRequiredSrc$3 = 1;
  11832. const topologicalSort = /*@__PURE__*/ requireTopologicalSort();
  11833. const matchImports = /^(.+?)\s+from\s+(?:"([^"]+)"|'([^']+)'|(global))$/;
  11834. const icssImport = /^:import\((?:"([^"]+)"|'([^']+)')\)/;
  11835. const VISITED_MARKER = 1;
  11836. /**
  11837. * :import('G') {}
  11838. *
  11839. * Rule
  11840. * composes: ... from 'A'
  11841. * composes: ... from 'B'
  11842. * Rule
  11843. * composes: ... from 'A'
  11844. * composes: ... from 'A'
  11845. * composes: ... from 'C'
  11846. *
  11847. * Results in:
  11848. *
  11849. * graph: {
  11850. * G: [],
  11851. * A: [],
  11852. * B: ['A'],
  11853. * C: ['A'],
  11854. * }
  11855. */
  11856. function addImportToGraph(importId, parentId, graph, visited) {
  11857. const siblingsId = parentId + "_" + "siblings";
  11858. const visitedId = parentId + "_" + importId;
  11859. if (visited[visitedId] !== VISITED_MARKER) {
  11860. if (!Array.isArray(visited[siblingsId])) {
  11861. visited[siblingsId] = [];
  11862. }
  11863. const siblings = visited[siblingsId];
  11864. if (Array.isArray(graph[importId])) {
  11865. graph[importId] = graph[importId].concat(siblings);
  11866. } else {
  11867. graph[importId] = siblings.slice();
  11868. }
  11869. visited[visitedId] = VISITED_MARKER;
  11870. siblings.push(importId);
  11871. }
  11872. }
  11873. src$3.exports = (options = {}) => {
  11874. let importIndex = 0;
  11875. const createImportedName =
  11876. typeof options.createImportedName !== "function"
  11877. ? (importName /*, path*/) =>
  11878. `i__imported_${importName.replace(/\W/g, "_")}_${importIndex++}`
  11879. : options.createImportedName;
  11880. const failOnWrongOrder = options.failOnWrongOrder;
  11881. return {
  11882. postcssPlugin: "postcss-modules-extract-imports",
  11883. prepare() {
  11884. const graph = {};
  11885. const visited = {};
  11886. const existingImports = {};
  11887. const importDecls = {};
  11888. const imports = {};
  11889. return {
  11890. Once(root, postcss) {
  11891. // Check the existing imports order and save refs
  11892. root.walkRules((rule) => {
  11893. const matches = icssImport.exec(rule.selector);
  11894. if (matches) {
  11895. const [, /*match*/ doubleQuotePath, singleQuotePath] = matches;
  11896. const importPath = doubleQuotePath || singleQuotePath;
  11897. addImportToGraph(importPath, "root", graph, visited);
  11898. existingImports[importPath] = rule;
  11899. }
  11900. });
  11901. root.walkDecls(/^composes$/, (declaration) => {
  11902. const multiple = declaration.value.split(",");
  11903. const values = [];
  11904. multiple.forEach((value) => {
  11905. const matches = value.trim().match(matchImports);
  11906. if (!matches) {
  11907. values.push(value);
  11908. return;
  11909. }
  11910. let tmpSymbols;
  11911. let [
  11912. ,
  11913. /*match*/ symbols,
  11914. doubleQuotePath,
  11915. singleQuotePath,
  11916. global,
  11917. ] = matches;
  11918. if (global) {
  11919. // Composing globals simply means changing these classes to wrap them in global(name)
  11920. tmpSymbols = symbols.split(/\s+/).map((s) => `global(${s})`);
  11921. } else {
  11922. const importPath = doubleQuotePath || singleQuotePath;
  11923. let parent = declaration.parent;
  11924. let parentIndexes = "";
  11925. while (parent.type !== "root") {
  11926. parentIndexes =
  11927. parent.parent.index(parent) + "_" + parentIndexes;
  11928. parent = parent.parent;
  11929. }
  11930. const { selector } = declaration.parent;
  11931. const parentRule = `_${parentIndexes}${selector}`;
  11932. addImportToGraph(importPath, parentRule, graph, visited);
  11933. importDecls[importPath] = declaration;
  11934. imports[importPath] = imports[importPath] || {};
  11935. tmpSymbols = symbols.split(/\s+/).map((s) => {
  11936. if (!imports[importPath][s]) {
  11937. imports[importPath][s] = createImportedName(s, importPath);
  11938. }
  11939. return imports[importPath][s];
  11940. });
  11941. }
  11942. values.push(tmpSymbols.join(" "));
  11943. });
  11944. declaration.value = values.join(", ");
  11945. });
  11946. const importsOrder = topologicalSort(graph, failOnWrongOrder);
  11947. if (importsOrder instanceof Error) {
  11948. const importPath = importsOrder.nodes.find((importPath) =>
  11949. // eslint-disable-next-line no-prototype-builtins
  11950. importDecls.hasOwnProperty(importPath)
  11951. );
  11952. const decl = importDecls[importPath];
  11953. throw decl.error(
  11954. "Failed to resolve order of composed modules " +
  11955. importsOrder.nodes
  11956. .map((importPath) => "`" + importPath + "`")
  11957. .join(", ") +
  11958. ".",
  11959. {
  11960. plugin: "postcss-modules-extract-imports",
  11961. word: "composes",
  11962. }
  11963. );
  11964. }
  11965. let lastImportRule;
  11966. importsOrder.forEach((path) => {
  11967. const importedSymbols = imports[path];
  11968. let rule = existingImports[path];
  11969. if (!rule && importedSymbols) {
  11970. rule = postcss.rule({
  11971. selector: `:import("${path}")`,
  11972. raws: { after: "\n" },
  11973. });
  11974. if (lastImportRule) {
  11975. root.insertAfter(lastImportRule, rule);
  11976. } else {
  11977. root.prepend(rule);
  11978. }
  11979. }
  11980. lastImportRule = rule;
  11981. if (!importedSymbols) {
  11982. return;
  11983. }
  11984. Object.keys(importedSymbols).forEach((importedSymbol) => {
  11985. rule.append(
  11986. postcss.decl({
  11987. value: importedSymbol,
  11988. prop: importedSymbols[importedSymbol],
  11989. raws: { before: "\n " },
  11990. })
  11991. );
  11992. });
  11993. });
  11994. },
  11995. };
  11996. },
  11997. };
  11998. };
  11999. src$3.exports.postcss = true;
  12000. return src$3.exports;
  12001. }
  12002. var wasmHash = {exports: {}};
  12003. /*
  12004. MIT License http://www.opensource.org/licenses/mit-license.php
  12005. Author Tobias Koppers @sokra
  12006. */
  12007. var hasRequiredWasmHash;
  12008. function requireWasmHash () {
  12009. if (hasRequiredWasmHash) return wasmHash.exports;
  12010. hasRequiredWasmHash = 1;
  12011. // 65536 is the size of a wasm memory page
  12012. // 64 is the maximum chunk size for every possible wasm hash implementation
  12013. // 4 is the maximum number of bytes per char for string encoding (max is utf-8)
  12014. // ~3 makes sure that it's always a block of 4 chars, so avoid partially encoded bytes for base64
  12015. const MAX_SHORT_STRING = Math.floor((65536 - 64) / 4) & ~3;
  12016. class WasmHash {
  12017. /**
  12018. * @param {WebAssembly.Instance} instance wasm instance
  12019. * @param {WebAssembly.Instance[]} instancesPool pool of instances
  12020. * @param {number} chunkSize size of data chunks passed to wasm
  12021. * @param {number} digestSize size of digest returned by wasm
  12022. */
  12023. constructor(instance, instancesPool, chunkSize, digestSize) {
  12024. const exports = /** @type {any} */ (instance.exports);
  12025. exports.init();
  12026. this.exports = exports;
  12027. this.mem = Buffer.from(exports.memory.buffer, 0, 65536);
  12028. this.buffered = 0;
  12029. this.instancesPool = instancesPool;
  12030. this.chunkSize = chunkSize;
  12031. this.digestSize = digestSize;
  12032. }
  12033. reset() {
  12034. this.buffered = 0;
  12035. this.exports.init();
  12036. }
  12037. /**
  12038. * @param {Buffer | string} data data
  12039. * @param {BufferEncoding=} encoding encoding
  12040. * @returns {this} itself
  12041. */
  12042. update(data, encoding) {
  12043. if (typeof data === "string") {
  12044. while (data.length > MAX_SHORT_STRING) {
  12045. this._updateWithShortString(data.slice(0, MAX_SHORT_STRING), encoding);
  12046. data = data.slice(MAX_SHORT_STRING);
  12047. }
  12048. this._updateWithShortString(data, encoding);
  12049. return this;
  12050. }
  12051. this._updateWithBuffer(data);
  12052. return this;
  12053. }
  12054. /**
  12055. * @param {string} data data
  12056. * @param {BufferEncoding=} encoding encoding
  12057. * @returns {void}
  12058. */
  12059. _updateWithShortString(data, encoding) {
  12060. const { exports, buffered, mem, chunkSize } = this;
  12061. let endPos;
  12062. if (data.length < 70) {
  12063. if (!encoding || encoding === "utf-8" || encoding === "utf8") {
  12064. endPos = buffered;
  12065. for (let i = 0; i < data.length; i++) {
  12066. const cc = data.charCodeAt(i);
  12067. if (cc < 0x80) {
  12068. mem[endPos++] = cc;
  12069. } else if (cc < 0x800) {
  12070. mem[endPos] = (cc >> 6) | 0xc0;
  12071. mem[endPos + 1] = (cc & 0x3f) | 0x80;
  12072. endPos += 2;
  12073. } else {
  12074. // bail-out for weird chars
  12075. endPos += mem.write(data.slice(i), endPos, encoding);
  12076. break;
  12077. }
  12078. }
  12079. } else if (encoding === "latin1") {
  12080. endPos = buffered;
  12081. for (let i = 0; i < data.length; i++) {
  12082. const cc = data.charCodeAt(i);
  12083. mem[endPos++] = cc;
  12084. }
  12085. } else {
  12086. endPos = buffered + mem.write(data, buffered, encoding);
  12087. }
  12088. } else {
  12089. endPos = buffered + mem.write(data, buffered, encoding);
  12090. }
  12091. if (endPos < chunkSize) {
  12092. this.buffered = endPos;
  12093. } else {
  12094. const l = endPos & ~(this.chunkSize - 1);
  12095. exports.update(l);
  12096. const newBuffered = endPos - l;
  12097. this.buffered = newBuffered;
  12098. if (newBuffered > 0) {
  12099. mem.copyWithin(0, l, endPos);
  12100. }
  12101. }
  12102. }
  12103. /**
  12104. * @param {Buffer} data data
  12105. * @returns {void}
  12106. */
  12107. _updateWithBuffer(data) {
  12108. const { exports, buffered, mem } = this;
  12109. const length = data.length;
  12110. if (buffered + length < this.chunkSize) {
  12111. data.copy(mem, buffered, 0, length);
  12112. this.buffered += length;
  12113. } else {
  12114. const l = (buffered + length) & ~(this.chunkSize - 1);
  12115. if (l > 65536) {
  12116. let i = 65536 - buffered;
  12117. data.copy(mem, buffered, 0, i);
  12118. exports.update(65536);
  12119. const stop = l - buffered - 65536;
  12120. while (i < stop) {
  12121. data.copy(mem, 0, i, i + 65536);
  12122. exports.update(65536);
  12123. i += 65536;
  12124. }
  12125. data.copy(mem, 0, i, l - buffered);
  12126. exports.update(l - buffered - i);
  12127. } else {
  12128. data.copy(mem, buffered, 0, l - buffered);
  12129. exports.update(l);
  12130. }
  12131. const newBuffered = length + buffered - l;
  12132. this.buffered = newBuffered;
  12133. if (newBuffered > 0) {
  12134. data.copy(mem, 0, length - newBuffered, length);
  12135. }
  12136. }
  12137. }
  12138. digest(type) {
  12139. const { exports, buffered, mem, digestSize } = this;
  12140. exports.final(buffered);
  12141. this.instancesPool.push(this);
  12142. const hex = mem.toString("latin1", 0, digestSize);
  12143. if (type === "hex") {
  12144. return hex;
  12145. }
  12146. if (type === "binary" || !type) {
  12147. return Buffer.from(hex, "hex");
  12148. }
  12149. return Buffer.from(hex, "hex").toString(type);
  12150. }
  12151. }
  12152. const create = (wasmModule, instancesPool, chunkSize, digestSize) => {
  12153. if (instancesPool.length > 0) {
  12154. const old = instancesPool.pop();
  12155. old.reset();
  12156. return old;
  12157. } else {
  12158. return new WasmHash(
  12159. new WebAssembly.Instance(wasmModule),
  12160. instancesPool,
  12161. chunkSize,
  12162. digestSize
  12163. );
  12164. }
  12165. };
  12166. wasmHash.exports = create;
  12167. wasmHash.exports.MAX_SHORT_STRING = MAX_SHORT_STRING;
  12168. return wasmHash.exports;
  12169. }
  12170. /*
  12171. MIT License http://www.opensource.org/licenses/mit-license.php
  12172. Author Tobias Koppers @sokra
  12173. */
  12174. var xxhash64_1;
  12175. var hasRequiredXxhash64;
  12176. function requireXxhash64 () {
  12177. if (hasRequiredXxhash64) return xxhash64_1;
  12178. hasRequiredXxhash64 = 1;
  12179. const create = /*@__PURE__*/ requireWasmHash();
  12180. //#region wasm code: xxhash64 (../../../assembly/hash/xxhash64.asm.ts) --initialMemory 1
  12181. const xxhash64 = new WebAssembly.Module(
  12182. Buffer.from(
  12183. // 1173 bytes
  12184. "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",
  12185. "base64"
  12186. )
  12187. );
  12188. //#endregion
  12189. xxhash64_1 = create.bind(null, xxhash64, [], 32, 16);
  12190. return xxhash64_1;
  12191. }
  12192. var BatchedHash_1;
  12193. var hasRequiredBatchedHash;
  12194. function requireBatchedHash () {
  12195. if (hasRequiredBatchedHash) return BatchedHash_1;
  12196. hasRequiredBatchedHash = 1;
  12197. const MAX_SHORT_STRING = /*@__PURE__*/ requireWasmHash().MAX_SHORT_STRING;
  12198. class BatchedHash {
  12199. constructor(hash) {
  12200. this.string = undefined;
  12201. this.encoding = undefined;
  12202. this.hash = hash;
  12203. }
  12204. /**
  12205. * Update hash {@link https://nodejs.org/api/crypto.html#crypto_hash_update_data_inputencoding}
  12206. * @param {string|Buffer} data data
  12207. * @param {string=} inputEncoding data encoding
  12208. * @returns {this} updated hash
  12209. */
  12210. update(data, inputEncoding) {
  12211. if (this.string !== undefined) {
  12212. if (
  12213. typeof data === "string" &&
  12214. inputEncoding === this.encoding &&
  12215. this.string.length + data.length < MAX_SHORT_STRING
  12216. ) {
  12217. this.string += data;
  12218. return this;
  12219. }
  12220. this.hash.update(this.string, this.encoding);
  12221. this.string = undefined;
  12222. }
  12223. if (typeof data === "string") {
  12224. if (
  12225. data.length < MAX_SHORT_STRING &&
  12226. // base64 encoding is not valid since it may contain padding chars
  12227. (!inputEncoding || !inputEncoding.startsWith("ba"))
  12228. ) {
  12229. this.string = data;
  12230. this.encoding = inputEncoding;
  12231. } else {
  12232. this.hash.update(data, inputEncoding);
  12233. }
  12234. } else {
  12235. this.hash.update(data);
  12236. }
  12237. return this;
  12238. }
  12239. /**
  12240. * Calculates the digest {@link https://nodejs.org/api/crypto.html#crypto_hash_digest_encoding}
  12241. * @param {string=} encoding encoding of the return value
  12242. * @returns {string|Buffer} digest
  12243. */
  12244. digest(encoding) {
  12245. if (this.string !== undefined) {
  12246. this.hash.update(this.string, this.encoding);
  12247. }
  12248. return this.hash.digest(encoding);
  12249. }
  12250. }
  12251. BatchedHash_1 = BatchedHash;
  12252. return BatchedHash_1;
  12253. }
  12254. /*
  12255. MIT License http://www.opensource.org/licenses/mit-license.php
  12256. Author Tobias Koppers @sokra
  12257. */
  12258. var md4_1;
  12259. var hasRequiredMd4;
  12260. function requireMd4 () {
  12261. if (hasRequiredMd4) return md4_1;
  12262. hasRequiredMd4 = 1;
  12263. const create = /*@__PURE__*/ requireWasmHash();
  12264. //#region wasm code: md4 (../../../assembly/hash/md4.asm.ts) --initialMemory 1
  12265. const md4 = new WebAssembly.Module(
  12266. Buffer.from(
  12267. // 2150 bytes
  12268. "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=",
  12269. "base64"
  12270. )
  12271. );
  12272. //#endregion
  12273. md4_1 = create.bind(null, md4, [], 64, 32);
  12274. return md4_1;
  12275. }
  12276. var BulkUpdateDecorator_1;
  12277. var hasRequiredBulkUpdateDecorator;
  12278. function requireBulkUpdateDecorator () {
  12279. if (hasRequiredBulkUpdateDecorator) return BulkUpdateDecorator_1;
  12280. hasRequiredBulkUpdateDecorator = 1;
  12281. const BULK_SIZE = 2000;
  12282. // We are using an object instead of a Map as this will stay static during the runtime
  12283. // so access to it can be optimized by v8
  12284. const digestCaches = {};
  12285. class BulkUpdateDecorator {
  12286. /**
  12287. * @param {Hash | function(): Hash} hashOrFactory function to create a hash
  12288. * @param {string=} hashKey key for caching
  12289. */
  12290. constructor(hashOrFactory, hashKey) {
  12291. this.hashKey = hashKey;
  12292. if (typeof hashOrFactory === "function") {
  12293. this.hashFactory = hashOrFactory;
  12294. this.hash = undefined;
  12295. } else {
  12296. this.hashFactory = undefined;
  12297. this.hash = hashOrFactory;
  12298. }
  12299. this.buffer = "";
  12300. }
  12301. /**
  12302. * Update hash {@link https://nodejs.org/api/crypto.html#crypto_hash_update_data_inputencoding}
  12303. * @param {string|Buffer} data data
  12304. * @param {string=} inputEncoding data encoding
  12305. * @returns {this} updated hash
  12306. */
  12307. update(data, inputEncoding) {
  12308. if (
  12309. inputEncoding !== undefined ||
  12310. typeof data !== "string" ||
  12311. data.length > BULK_SIZE
  12312. ) {
  12313. if (this.hash === undefined) {
  12314. this.hash = this.hashFactory();
  12315. }
  12316. if (this.buffer.length > 0) {
  12317. this.hash.update(this.buffer);
  12318. this.buffer = "";
  12319. }
  12320. this.hash.update(data, inputEncoding);
  12321. } else {
  12322. this.buffer += data;
  12323. if (this.buffer.length > BULK_SIZE) {
  12324. if (this.hash === undefined) {
  12325. this.hash = this.hashFactory();
  12326. }
  12327. this.hash.update(this.buffer);
  12328. this.buffer = "";
  12329. }
  12330. }
  12331. return this;
  12332. }
  12333. /**
  12334. * Calculates the digest {@link https://nodejs.org/api/crypto.html#crypto_hash_digest_encoding}
  12335. * @param {string=} encoding encoding of the return value
  12336. * @returns {string|Buffer} digest
  12337. */
  12338. digest(encoding) {
  12339. let digestCache;
  12340. const buffer = this.buffer;
  12341. if (this.hash === undefined) {
  12342. // short data for hash, we can use caching
  12343. const cacheKey = `${this.hashKey}-${encoding}`;
  12344. digestCache = digestCaches[cacheKey];
  12345. if (digestCache === undefined) {
  12346. digestCache = digestCaches[cacheKey] = new Map();
  12347. }
  12348. const cacheEntry = digestCache.get(buffer);
  12349. if (cacheEntry !== undefined) {
  12350. return cacheEntry;
  12351. }
  12352. this.hash = this.hashFactory();
  12353. }
  12354. if (buffer.length > 0) {
  12355. this.hash.update(buffer);
  12356. }
  12357. const digestResult = this.hash.digest(encoding);
  12358. if (digestCache !== undefined) {
  12359. digestCache.set(buffer, digestResult);
  12360. }
  12361. return digestResult;
  12362. }
  12363. }
  12364. BulkUpdateDecorator_1 = BulkUpdateDecorator;
  12365. return BulkUpdateDecorator_1;
  12366. }
  12367. var getHashDigest_1;
  12368. var hasRequiredGetHashDigest;
  12369. function requireGetHashDigest () {
  12370. if (hasRequiredGetHashDigest) return getHashDigest_1;
  12371. hasRequiredGetHashDigest = 1;
  12372. const baseEncodeTables = {
  12373. 26: "abcdefghijklmnopqrstuvwxyz",
  12374. 32: "123456789abcdefghjkmnpqrstuvwxyz", // no 0lio
  12375. 36: "0123456789abcdefghijklmnopqrstuvwxyz",
  12376. 49: "abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ", // no lIO
  12377. 52: "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ",
  12378. 58: "123456789abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ", // no 0lIO
  12379. 62: "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ",
  12380. 64: "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ-_",
  12381. };
  12382. /**
  12383. * @param {Uint32Array} uint32Array Treated as a long base-0x100000000 number, little endian
  12384. * @param {number} divisor The divisor
  12385. * @return {number} Modulo (remainder) of the division
  12386. */
  12387. function divmod32(uint32Array, divisor) {
  12388. let carry = 0;
  12389. for (let i = uint32Array.length - 1; i >= 0; i--) {
  12390. const value = carry * 0x100000000 + uint32Array[i];
  12391. carry = value % divisor;
  12392. uint32Array[i] = Math.floor(value / divisor);
  12393. }
  12394. return carry;
  12395. }
  12396. function encodeBufferToBase(buffer, base, length) {
  12397. const encodeTable = baseEncodeTables[base];
  12398. if (!encodeTable) {
  12399. throw new Error("Unknown encoding base" + base);
  12400. }
  12401. // Input bits are only enough to generate this many characters
  12402. const limit = Math.ceil((buffer.length * 8) / Math.log2(base));
  12403. length = Math.min(length, limit);
  12404. // Most of the crypto digests (if not all) has length a multiple of 4 bytes.
  12405. // Fewer numbers in the array means faster math.
  12406. const uint32Array = new Uint32Array(Math.ceil(buffer.length / 4));
  12407. // Make sure the input buffer data is copied and is not mutated by reference.
  12408. // divmod32() would corrupt the BulkUpdateDecorator cache otherwise.
  12409. buffer.copy(Buffer.from(uint32Array.buffer));
  12410. let output = "";
  12411. for (let i = 0; i < length; i++) {
  12412. output = encodeTable[divmod32(uint32Array, base)] + output;
  12413. }
  12414. return output;
  12415. }
  12416. let crypto = undefined;
  12417. let createXXHash64 = undefined;
  12418. let createMd4 = undefined;
  12419. let BatchedHash = undefined;
  12420. let BulkUpdateDecorator = undefined;
  12421. function getHashDigest(buffer, algorithm, digestType, maxLength) {
  12422. algorithm = algorithm || "xxhash64";
  12423. maxLength = maxLength || 9999;
  12424. let hash;
  12425. if (algorithm === "xxhash64") {
  12426. if (createXXHash64 === undefined) {
  12427. createXXHash64 = /*@__PURE__*/ requireXxhash64();
  12428. if (BatchedHash === undefined) {
  12429. BatchedHash = /*@__PURE__*/ requireBatchedHash();
  12430. }
  12431. }
  12432. hash = new BatchedHash(createXXHash64());
  12433. } else if (algorithm === "md4") {
  12434. if (createMd4 === undefined) {
  12435. createMd4 = /*@__PURE__*/ requireMd4();
  12436. if (BatchedHash === undefined) {
  12437. BatchedHash = /*@__PURE__*/ requireBatchedHash();
  12438. }
  12439. }
  12440. hash = new BatchedHash(createMd4());
  12441. } else if (algorithm === "native-md4") {
  12442. if (typeof crypto === "undefined") {
  12443. crypto = require("crypto");
  12444. if (BulkUpdateDecorator === undefined) {
  12445. BulkUpdateDecorator = /*@__PURE__*/ requireBulkUpdateDecorator();
  12446. }
  12447. }
  12448. hash = new BulkUpdateDecorator(() => crypto.createHash("md4"), "md4");
  12449. } else {
  12450. if (typeof crypto === "undefined") {
  12451. crypto = require("crypto");
  12452. if (BulkUpdateDecorator === undefined) {
  12453. BulkUpdateDecorator = /*@__PURE__*/ requireBulkUpdateDecorator();
  12454. }
  12455. }
  12456. hash = new BulkUpdateDecorator(
  12457. () => crypto.createHash(algorithm),
  12458. algorithm
  12459. );
  12460. }
  12461. hash.update(buffer);
  12462. if (
  12463. digestType === "base26" ||
  12464. digestType === "base32" ||
  12465. digestType === "base36" ||
  12466. digestType === "base49" ||
  12467. digestType === "base52" ||
  12468. digestType === "base58" ||
  12469. digestType === "base62" ||
  12470. digestType === "base64safe"
  12471. ) {
  12472. return encodeBufferToBase(
  12473. hash.digest(),
  12474. digestType === "base64safe" ? 64 : digestType.substr(4),
  12475. maxLength
  12476. );
  12477. }
  12478. return hash.digest(digestType || "hex").substr(0, maxLength);
  12479. }
  12480. getHashDigest_1 = getHashDigest;
  12481. return getHashDigest_1;
  12482. }
  12483. var interpolateName_1;
  12484. var hasRequiredInterpolateName;
  12485. function requireInterpolateName () {
  12486. if (hasRequiredInterpolateName) return interpolateName_1;
  12487. hasRequiredInterpolateName = 1;
  12488. const path = path$1;
  12489. const getHashDigest = /*@__PURE__*/ requireGetHashDigest();
  12490. function interpolateName(loaderContext, name, options = {}) {
  12491. let filename;
  12492. const hasQuery =
  12493. loaderContext.resourceQuery && loaderContext.resourceQuery.length > 1;
  12494. if (typeof name === "function") {
  12495. filename = name(
  12496. loaderContext.resourcePath,
  12497. hasQuery ? loaderContext.resourceQuery : undefined
  12498. );
  12499. } else {
  12500. filename = name || "[hash].[ext]";
  12501. }
  12502. const context = options.context;
  12503. const content = options.content;
  12504. const regExp = options.regExp;
  12505. let ext = "bin";
  12506. let basename = "file";
  12507. let directory = "";
  12508. let folder = "";
  12509. let query = "";
  12510. if (loaderContext.resourcePath) {
  12511. const parsed = path.parse(loaderContext.resourcePath);
  12512. let resourcePath = loaderContext.resourcePath;
  12513. if (parsed.ext) {
  12514. ext = parsed.ext.substr(1);
  12515. }
  12516. if (parsed.dir) {
  12517. basename = parsed.name;
  12518. resourcePath = parsed.dir + path.sep;
  12519. }
  12520. if (typeof context !== "undefined") {
  12521. directory = path
  12522. .relative(context, resourcePath + "_")
  12523. .replace(/\\/g, "/")
  12524. .replace(/\.\.(\/)?/g, "_$1");
  12525. directory = directory.substr(0, directory.length - 1);
  12526. } else {
  12527. directory = resourcePath.replace(/\\/g, "/").replace(/\.\.(\/)?/g, "_$1");
  12528. }
  12529. if (directory.length <= 1) {
  12530. directory = "";
  12531. } else {
  12532. // directory.length > 1
  12533. folder = path.basename(directory);
  12534. }
  12535. }
  12536. if (loaderContext.resourceQuery && loaderContext.resourceQuery.length > 1) {
  12537. query = loaderContext.resourceQuery;
  12538. const hashIdx = query.indexOf("#");
  12539. if (hashIdx >= 0) {
  12540. query = query.substr(0, hashIdx);
  12541. }
  12542. }
  12543. let url = filename;
  12544. if (content) {
  12545. // Match hash template
  12546. url = url
  12547. // `hash` and `contenthash` are same in `loader-utils` context
  12548. // let's keep `hash` for backward compatibility
  12549. .replace(
  12550. /\[(?:([^[:\]]+):)?(?:hash|contenthash)(?::([a-z]+\d*(?:safe)?))?(?::(\d+))?\]/gi,
  12551. (all, hashType, digestType, maxLength) =>
  12552. getHashDigest(content, hashType, digestType, parseInt(maxLength, 10))
  12553. );
  12554. }
  12555. url = url
  12556. .replace(/\[ext\]/gi, () => ext)
  12557. .replace(/\[name\]/gi, () => basename)
  12558. .replace(/\[path\]/gi, () => directory)
  12559. .replace(/\[folder\]/gi, () => folder)
  12560. .replace(/\[query\]/gi, () => query);
  12561. if (regExp && loaderContext.resourcePath) {
  12562. const match = loaderContext.resourcePath.match(new RegExp(regExp));
  12563. match &&
  12564. match.forEach((matched, i) => {
  12565. url = url.replace(new RegExp("\\[" + i + "\\]", "ig"), matched);
  12566. });
  12567. }
  12568. if (
  12569. typeof loaderContext.options === "object" &&
  12570. typeof loaderContext.options.customInterpolateName === "function"
  12571. ) {
  12572. url = loaderContext.options.customInterpolateName.call(
  12573. loaderContext,
  12574. url,
  12575. name,
  12576. options
  12577. );
  12578. }
  12579. return url;
  12580. }
  12581. interpolateName_1 = interpolateName;
  12582. return interpolateName_1;
  12583. }
  12584. var genericNames;
  12585. var hasRequiredGenericNames;
  12586. function requireGenericNames () {
  12587. if (hasRequiredGenericNames) return genericNames;
  12588. hasRequiredGenericNames = 1;
  12589. var interpolateName = /*@__PURE__*/ requireInterpolateName();
  12590. var path = path$1;
  12591. /**
  12592. * @param {string} pattern
  12593. * @param {object} options
  12594. * @param {string} options.context
  12595. * @param {string} options.hashPrefix
  12596. * @return {function}
  12597. */
  12598. genericNames = function createGenerator(pattern, options) {
  12599. options = options || {};
  12600. var context =
  12601. options && typeof options.context === "string"
  12602. ? options.context
  12603. : process.cwd();
  12604. var hashPrefix =
  12605. options && typeof options.hashPrefix === "string" ? options.hashPrefix : "";
  12606. /**
  12607. * @param {string} localName Usually a class name
  12608. * @param {string} filepath Absolute path
  12609. * @return {string}
  12610. */
  12611. return function generate(localName, filepath) {
  12612. var name = pattern.replace(/\[local\]/gi, localName);
  12613. var loaderContext = {
  12614. resourcePath: filepath,
  12615. };
  12616. var loaderOptions = {
  12617. content:
  12618. hashPrefix +
  12619. path.relative(context, filepath).replace(/\\/g, "/") +
  12620. "\x00" +
  12621. localName,
  12622. context: context,
  12623. };
  12624. var genericName = interpolateName(loaderContext, name, loaderOptions);
  12625. return genericName
  12626. .replace(new RegExp("[^a-zA-Z0-9\\-_\u00A0-\uFFFF]", "g"), "-")
  12627. .replace(/^((-?[0-9])|--)/, "_$1");
  12628. };
  12629. };
  12630. return genericNames;
  12631. }
  12632. var src$2 = {exports: {}};
  12633. var parse;
  12634. var hasRequiredParse;
  12635. function requireParse () {
  12636. if (hasRequiredParse) return parse;
  12637. hasRequiredParse = 1;
  12638. var openParentheses = "(".charCodeAt(0);
  12639. var closeParentheses = ")".charCodeAt(0);
  12640. var singleQuote = "'".charCodeAt(0);
  12641. var doubleQuote = '"'.charCodeAt(0);
  12642. var backslash = "\\".charCodeAt(0);
  12643. var slash = "/".charCodeAt(0);
  12644. var comma = ",".charCodeAt(0);
  12645. var colon = ":".charCodeAt(0);
  12646. var star = "*".charCodeAt(0);
  12647. var uLower = "u".charCodeAt(0);
  12648. var uUpper = "U".charCodeAt(0);
  12649. var plus = "+".charCodeAt(0);
  12650. var isUnicodeRange = /^[a-f0-9?-]+$/i;
  12651. parse = function(input) {
  12652. var tokens = [];
  12653. var value = input;
  12654. var next,
  12655. quote,
  12656. prev,
  12657. token,
  12658. escape,
  12659. escapePos,
  12660. whitespacePos,
  12661. parenthesesOpenPos;
  12662. var pos = 0;
  12663. var code = value.charCodeAt(pos);
  12664. var max = value.length;
  12665. var stack = [{ nodes: tokens }];
  12666. var balanced = 0;
  12667. var parent;
  12668. var name = "";
  12669. var before = "";
  12670. var after = "";
  12671. while (pos < max) {
  12672. // Whitespaces
  12673. if (code <= 32) {
  12674. next = pos;
  12675. do {
  12676. next += 1;
  12677. code = value.charCodeAt(next);
  12678. } while (code <= 32);
  12679. token = value.slice(pos, next);
  12680. prev = tokens[tokens.length - 1];
  12681. if (code === closeParentheses && balanced) {
  12682. after = token;
  12683. } else if (prev && prev.type === "div") {
  12684. prev.after = token;
  12685. prev.sourceEndIndex += token.length;
  12686. } else if (
  12687. code === comma ||
  12688. code === colon ||
  12689. (code === slash &&
  12690. value.charCodeAt(next + 1) !== star &&
  12691. (!parent ||
  12692. (parent && parent.type === "function" && parent.value !== "calc")))
  12693. ) {
  12694. before = token;
  12695. } else {
  12696. tokens.push({
  12697. type: "space",
  12698. sourceIndex: pos,
  12699. sourceEndIndex: next,
  12700. value: token
  12701. });
  12702. }
  12703. pos = next;
  12704. // Quotes
  12705. } else if (code === singleQuote || code === doubleQuote) {
  12706. next = pos;
  12707. quote = code === singleQuote ? "'" : '"';
  12708. token = {
  12709. type: "string",
  12710. sourceIndex: pos,
  12711. quote: quote
  12712. };
  12713. do {
  12714. escape = false;
  12715. next = value.indexOf(quote, next + 1);
  12716. if (~next) {
  12717. escapePos = next;
  12718. while (value.charCodeAt(escapePos - 1) === backslash) {
  12719. escapePos -= 1;
  12720. escape = !escape;
  12721. }
  12722. } else {
  12723. value += quote;
  12724. next = value.length - 1;
  12725. token.unclosed = true;
  12726. }
  12727. } while (escape);
  12728. token.value = value.slice(pos + 1, next);
  12729. token.sourceEndIndex = token.unclosed ? next : next + 1;
  12730. tokens.push(token);
  12731. pos = next + 1;
  12732. code = value.charCodeAt(pos);
  12733. // Comments
  12734. } else if (code === slash && value.charCodeAt(pos + 1) === star) {
  12735. next = value.indexOf("*/", pos);
  12736. token = {
  12737. type: "comment",
  12738. sourceIndex: pos,
  12739. sourceEndIndex: next + 2
  12740. };
  12741. if (next === -1) {
  12742. token.unclosed = true;
  12743. next = value.length;
  12744. token.sourceEndIndex = next;
  12745. }
  12746. token.value = value.slice(pos + 2, next);
  12747. tokens.push(token);
  12748. pos = next + 2;
  12749. code = value.charCodeAt(pos);
  12750. // Operation within calc
  12751. } else if (
  12752. (code === slash || code === star) &&
  12753. parent &&
  12754. parent.type === "function" &&
  12755. parent.value === "calc"
  12756. ) {
  12757. token = value[pos];
  12758. tokens.push({
  12759. type: "word",
  12760. sourceIndex: pos - before.length,
  12761. sourceEndIndex: pos + token.length,
  12762. value: token
  12763. });
  12764. pos += 1;
  12765. code = value.charCodeAt(pos);
  12766. // Dividers
  12767. } else if (code === slash || code === comma || code === colon) {
  12768. token = value[pos];
  12769. tokens.push({
  12770. type: "div",
  12771. sourceIndex: pos - before.length,
  12772. sourceEndIndex: pos + token.length,
  12773. value: token,
  12774. before: before,
  12775. after: ""
  12776. });
  12777. before = "";
  12778. pos += 1;
  12779. code = value.charCodeAt(pos);
  12780. // Open parentheses
  12781. } else if (openParentheses === code) {
  12782. // Whitespaces after open parentheses
  12783. next = pos;
  12784. do {
  12785. next += 1;
  12786. code = value.charCodeAt(next);
  12787. } while (code <= 32);
  12788. parenthesesOpenPos = pos;
  12789. token = {
  12790. type: "function",
  12791. sourceIndex: pos - name.length,
  12792. value: name,
  12793. before: value.slice(parenthesesOpenPos + 1, next)
  12794. };
  12795. pos = next;
  12796. if (name === "url" && code !== singleQuote && code !== doubleQuote) {
  12797. next -= 1;
  12798. do {
  12799. escape = false;
  12800. next = value.indexOf(")", next + 1);
  12801. if (~next) {
  12802. escapePos = next;
  12803. while (value.charCodeAt(escapePos - 1) === backslash) {
  12804. escapePos -= 1;
  12805. escape = !escape;
  12806. }
  12807. } else {
  12808. value += ")";
  12809. next = value.length - 1;
  12810. token.unclosed = true;
  12811. }
  12812. } while (escape);
  12813. // Whitespaces before closed
  12814. whitespacePos = next;
  12815. do {
  12816. whitespacePos -= 1;
  12817. code = value.charCodeAt(whitespacePos);
  12818. } while (code <= 32);
  12819. if (parenthesesOpenPos < whitespacePos) {
  12820. if (pos !== whitespacePos + 1) {
  12821. token.nodes = [
  12822. {
  12823. type: "word",
  12824. sourceIndex: pos,
  12825. sourceEndIndex: whitespacePos + 1,
  12826. value: value.slice(pos, whitespacePos + 1)
  12827. }
  12828. ];
  12829. } else {
  12830. token.nodes = [];
  12831. }
  12832. if (token.unclosed && whitespacePos + 1 !== next) {
  12833. token.after = "";
  12834. token.nodes.push({
  12835. type: "space",
  12836. sourceIndex: whitespacePos + 1,
  12837. sourceEndIndex: next,
  12838. value: value.slice(whitespacePos + 1, next)
  12839. });
  12840. } else {
  12841. token.after = value.slice(whitespacePos + 1, next);
  12842. token.sourceEndIndex = next;
  12843. }
  12844. } else {
  12845. token.after = "";
  12846. token.nodes = [];
  12847. }
  12848. pos = next + 1;
  12849. token.sourceEndIndex = token.unclosed ? next : pos;
  12850. code = value.charCodeAt(pos);
  12851. tokens.push(token);
  12852. } else {
  12853. balanced += 1;
  12854. token.after = "";
  12855. token.sourceEndIndex = pos + 1;
  12856. tokens.push(token);
  12857. stack.push(token);
  12858. tokens = token.nodes = [];
  12859. parent = token;
  12860. }
  12861. name = "";
  12862. // Close parentheses
  12863. } else if (closeParentheses === code && balanced) {
  12864. pos += 1;
  12865. code = value.charCodeAt(pos);
  12866. parent.after = after;
  12867. parent.sourceEndIndex += after.length;
  12868. after = "";
  12869. balanced -= 1;
  12870. stack[stack.length - 1].sourceEndIndex = pos;
  12871. stack.pop();
  12872. parent = stack[balanced];
  12873. tokens = parent.nodes;
  12874. // Words
  12875. } else {
  12876. next = pos;
  12877. do {
  12878. if (code === backslash) {
  12879. next += 1;
  12880. }
  12881. next += 1;
  12882. code = value.charCodeAt(next);
  12883. } while (
  12884. next < max &&
  12885. !(
  12886. code <= 32 ||
  12887. code === singleQuote ||
  12888. code === doubleQuote ||
  12889. code === comma ||
  12890. code === colon ||
  12891. code === slash ||
  12892. code === openParentheses ||
  12893. (code === star &&
  12894. parent &&
  12895. parent.type === "function" &&
  12896. parent.value === "calc") ||
  12897. (code === slash &&
  12898. parent.type === "function" &&
  12899. parent.value === "calc") ||
  12900. (code === closeParentheses && balanced)
  12901. )
  12902. );
  12903. token = value.slice(pos, next);
  12904. if (openParentheses === code) {
  12905. name = token;
  12906. } else if (
  12907. (uLower === token.charCodeAt(0) || uUpper === token.charCodeAt(0)) &&
  12908. plus === token.charCodeAt(1) &&
  12909. isUnicodeRange.test(token.slice(2))
  12910. ) {
  12911. tokens.push({
  12912. type: "unicode-range",
  12913. sourceIndex: pos,
  12914. sourceEndIndex: next,
  12915. value: token
  12916. });
  12917. } else {
  12918. tokens.push({
  12919. type: "word",
  12920. sourceIndex: pos,
  12921. sourceEndIndex: next,
  12922. value: token
  12923. });
  12924. }
  12925. pos = next;
  12926. }
  12927. }
  12928. for (pos = stack.length - 1; pos; pos -= 1) {
  12929. stack[pos].unclosed = true;
  12930. stack[pos].sourceEndIndex = value.length;
  12931. }
  12932. return stack[0].nodes;
  12933. };
  12934. return parse;
  12935. }
  12936. var walk$1;
  12937. var hasRequiredWalk;
  12938. function requireWalk () {
  12939. if (hasRequiredWalk) return walk$1;
  12940. hasRequiredWalk = 1;
  12941. walk$1 = function walk(nodes, cb, bubble) {
  12942. var i, max, node, result;
  12943. for (i = 0, max = nodes.length; i < max; i += 1) {
  12944. node = nodes[i];
  12945. if (!bubble) {
  12946. result = cb(node, i, nodes);
  12947. }
  12948. if (
  12949. result !== false &&
  12950. node.type === "function" &&
  12951. Array.isArray(node.nodes)
  12952. ) {
  12953. walk(node.nodes, cb, bubble);
  12954. }
  12955. if (bubble) {
  12956. cb(node, i, nodes);
  12957. }
  12958. }
  12959. };
  12960. return walk$1;
  12961. }
  12962. var stringify_1;
  12963. var hasRequiredStringify;
  12964. function requireStringify () {
  12965. if (hasRequiredStringify) return stringify_1;
  12966. hasRequiredStringify = 1;
  12967. function stringifyNode(node, custom) {
  12968. var type = node.type;
  12969. var value = node.value;
  12970. var buf;
  12971. var customResult;
  12972. if (custom && (customResult = custom(node)) !== undefined) {
  12973. return customResult;
  12974. } else if (type === "word" || type === "space") {
  12975. return value;
  12976. } else if (type === "string") {
  12977. buf = node.quote || "";
  12978. return buf + value + (node.unclosed ? "" : buf);
  12979. } else if (type === "comment") {
  12980. return "/*" + value + (node.unclosed ? "" : "*/");
  12981. } else if (type === "div") {
  12982. return (node.before || "") + value + (node.after || "");
  12983. } else if (Array.isArray(node.nodes)) {
  12984. buf = stringify(node.nodes, custom);
  12985. if (type !== "function") {
  12986. return buf;
  12987. }
  12988. return (
  12989. value +
  12990. "(" +
  12991. (node.before || "") +
  12992. buf +
  12993. (node.after || "") +
  12994. (node.unclosed ? "" : ")")
  12995. );
  12996. }
  12997. return value;
  12998. }
  12999. function stringify(nodes, custom) {
  13000. var result, i;
  13001. if (Array.isArray(nodes)) {
  13002. result = "";
  13003. for (i = nodes.length - 1; ~i; i -= 1) {
  13004. result = stringifyNode(nodes[i], custom) + result;
  13005. }
  13006. return result;
  13007. }
  13008. return stringifyNode(nodes, custom);
  13009. }
  13010. stringify_1 = stringify;
  13011. return stringify_1;
  13012. }
  13013. var unit;
  13014. var hasRequiredUnit;
  13015. function requireUnit () {
  13016. if (hasRequiredUnit) return unit;
  13017. hasRequiredUnit = 1;
  13018. var minus = "-".charCodeAt(0);
  13019. var plus = "+".charCodeAt(0);
  13020. var dot = ".".charCodeAt(0);
  13021. var exp = "e".charCodeAt(0);
  13022. var EXP = "E".charCodeAt(0);
  13023. // Check if three code points would start a number
  13024. // https://www.w3.org/TR/css-syntax-3/#starts-with-a-number
  13025. function likeNumber(value) {
  13026. var code = value.charCodeAt(0);
  13027. var nextCode;
  13028. if (code === plus || code === minus) {
  13029. nextCode = value.charCodeAt(1);
  13030. if (nextCode >= 48 && nextCode <= 57) {
  13031. return true;
  13032. }
  13033. var nextNextCode = value.charCodeAt(2);
  13034. if (nextCode === dot && nextNextCode >= 48 && nextNextCode <= 57) {
  13035. return true;
  13036. }
  13037. return false;
  13038. }
  13039. if (code === dot) {
  13040. nextCode = value.charCodeAt(1);
  13041. if (nextCode >= 48 && nextCode <= 57) {
  13042. return true;
  13043. }
  13044. return false;
  13045. }
  13046. if (code >= 48 && code <= 57) {
  13047. return true;
  13048. }
  13049. return false;
  13050. }
  13051. // Consume a number
  13052. // https://www.w3.org/TR/css-syntax-3/#consume-number
  13053. unit = function(value) {
  13054. var pos = 0;
  13055. var length = value.length;
  13056. var code;
  13057. var nextCode;
  13058. var nextNextCode;
  13059. if (length === 0 || !likeNumber(value)) {
  13060. return false;
  13061. }
  13062. code = value.charCodeAt(pos);
  13063. if (code === plus || code === minus) {
  13064. pos++;
  13065. }
  13066. while (pos < length) {
  13067. code = value.charCodeAt(pos);
  13068. if (code < 48 || code > 57) {
  13069. break;
  13070. }
  13071. pos += 1;
  13072. }
  13073. code = value.charCodeAt(pos);
  13074. nextCode = value.charCodeAt(pos + 1);
  13075. if (code === dot && nextCode >= 48 && nextCode <= 57) {
  13076. pos += 2;
  13077. while (pos < length) {
  13078. code = value.charCodeAt(pos);
  13079. if (code < 48 || code > 57) {
  13080. break;
  13081. }
  13082. pos += 1;
  13083. }
  13084. }
  13085. code = value.charCodeAt(pos);
  13086. nextCode = value.charCodeAt(pos + 1);
  13087. nextNextCode = value.charCodeAt(pos + 2);
  13088. if (
  13089. (code === exp || code === EXP) &&
  13090. ((nextCode >= 48 && nextCode <= 57) ||
  13091. ((nextCode === plus || nextCode === minus) &&
  13092. nextNextCode >= 48 &&
  13093. nextNextCode <= 57))
  13094. ) {
  13095. pos += nextCode === plus || nextCode === minus ? 3 : 2;
  13096. while (pos < length) {
  13097. code = value.charCodeAt(pos);
  13098. if (code < 48 || code > 57) {
  13099. break;
  13100. }
  13101. pos += 1;
  13102. }
  13103. }
  13104. return {
  13105. number: value.slice(0, pos),
  13106. unit: value.slice(pos)
  13107. };
  13108. };
  13109. return unit;
  13110. }
  13111. var lib;
  13112. var hasRequiredLib;
  13113. function requireLib () {
  13114. if (hasRequiredLib) return lib;
  13115. hasRequiredLib = 1;
  13116. var parse = /*@__PURE__*/ requireParse();
  13117. var walk = /*@__PURE__*/ requireWalk();
  13118. var stringify = /*@__PURE__*/ requireStringify();
  13119. function ValueParser(value) {
  13120. if (this instanceof ValueParser) {
  13121. this.nodes = parse(value);
  13122. return this;
  13123. }
  13124. return new ValueParser(value);
  13125. }
  13126. ValueParser.prototype.toString = function() {
  13127. return Array.isArray(this.nodes) ? stringify(this.nodes) : "";
  13128. };
  13129. ValueParser.prototype.walk = function(cb, bubble) {
  13130. walk(this.nodes, cb, bubble);
  13131. return this;
  13132. };
  13133. ValueParser.unit = /*@__PURE__*/ requireUnit();
  13134. ValueParser.walk = walk;
  13135. ValueParser.stringify = stringify;
  13136. lib = ValueParser;
  13137. return lib;
  13138. }
  13139. var hasRequiredSrc$2;
  13140. function requireSrc$2 () {
  13141. if (hasRequiredSrc$2) return src$2.exports;
  13142. hasRequiredSrc$2 = 1;
  13143. const selectorParser = /*@__PURE__*/ requireDist();
  13144. const valueParser = /*@__PURE__*/ requireLib();
  13145. const { extractICSS } = /*@__PURE__*/ requireSrc$4();
  13146. const isSpacing = (node) => node.type === "combinator" && node.value === " ";
  13147. function normalizeNodeArray(nodes) {
  13148. const array = [];
  13149. nodes.forEach((x) => {
  13150. if (Array.isArray(x)) {
  13151. normalizeNodeArray(x).forEach((item) => {
  13152. array.push(item);
  13153. });
  13154. } else if (x) {
  13155. array.push(x);
  13156. }
  13157. });
  13158. if (array.length > 0 && isSpacing(array[array.length - 1])) {
  13159. array.pop();
  13160. }
  13161. return array;
  13162. }
  13163. function localizeNode(rule, mode, localAliasMap) {
  13164. const transform = (node, context) => {
  13165. if (context.ignoreNextSpacing && !isSpacing(node)) {
  13166. throw new Error("Missing whitespace after " + context.ignoreNextSpacing);
  13167. }
  13168. if (context.enforceNoSpacing && isSpacing(node)) {
  13169. throw new Error("Missing whitespace before " + context.enforceNoSpacing);
  13170. }
  13171. let newNodes;
  13172. switch (node.type) {
  13173. case "root": {
  13174. let resultingGlobal;
  13175. context.hasPureGlobals = false;
  13176. newNodes = node.nodes.map((n) => {
  13177. const nContext = {
  13178. global: context.global,
  13179. lastWasSpacing: true,
  13180. hasLocals: false,
  13181. explicit: false,
  13182. };
  13183. n = transform(n, nContext);
  13184. if (typeof resultingGlobal === "undefined") {
  13185. resultingGlobal = nContext.global;
  13186. } else if (resultingGlobal !== nContext.global) {
  13187. throw new Error(
  13188. 'Inconsistent rule global/local result in rule "' +
  13189. node +
  13190. '" (multiple selectors must result in the same mode for the rule)'
  13191. );
  13192. }
  13193. if (!nContext.hasLocals) {
  13194. context.hasPureGlobals = true;
  13195. }
  13196. return n;
  13197. });
  13198. context.global = resultingGlobal;
  13199. node.nodes = normalizeNodeArray(newNodes);
  13200. break;
  13201. }
  13202. case "selector": {
  13203. newNodes = node.map((childNode) => transform(childNode, context));
  13204. node = node.clone();
  13205. node.nodes = normalizeNodeArray(newNodes);
  13206. break;
  13207. }
  13208. case "combinator": {
  13209. if (isSpacing(node)) {
  13210. if (context.ignoreNextSpacing) {
  13211. context.ignoreNextSpacing = false;
  13212. context.lastWasSpacing = false;
  13213. context.enforceNoSpacing = false;
  13214. return null;
  13215. }
  13216. context.lastWasSpacing = true;
  13217. return node;
  13218. }
  13219. break;
  13220. }
  13221. case "pseudo": {
  13222. let childContext;
  13223. const isNested = !!node.length;
  13224. const isScoped = node.value === ":local" || node.value === ":global";
  13225. const isImportExport =
  13226. node.value === ":import" || node.value === ":export";
  13227. if (isImportExport) {
  13228. context.hasLocals = true;
  13229. // :local(.foo)
  13230. } else if (isNested) {
  13231. if (isScoped) {
  13232. if (node.nodes.length === 0) {
  13233. throw new Error(`${node.value}() can't be empty`);
  13234. }
  13235. if (context.inside) {
  13236. throw new Error(
  13237. `A ${node.value} is not allowed inside of a ${context.inside}(...)`
  13238. );
  13239. }
  13240. childContext = {
  13241. global: node.value === ":global",
  13242. inside: node.value,
  13243. hasLocals: false,
  13244. explicit: true,
  13245. };
  13246. newNodes = node
  13247. .map((childNode) => transform(childNode, childContext))
  13248. .reduce((acc, next) => acc.concat(next.nodes), []);
  13249. if (newNodes.length) {
  13250. const { before, after } = node.spaces;
  13251. const first = newNodes[0];
  13252. const last = newNodes[newNodes.length - 1];
  13253. first.spaces = { before, after: first.spaces.after };
  13254. last.spaces = { before: last.spaces.before, after };
  13255. }
  13256. node = newNodes;
  13257. break;
  13258. } else {
  13259. childContext = {
  13260. global: context.global,
  13261. inside: context.inside,
  13262. lastWasSpacing: true,
  13263. hasLocals: false,
  13264. explicit: context.explicit,
  13265. };
  13266. newNodes = node.map((childNode) => {
  13267. const newContext = {
  13268. ...childContext,
  13269. enforceNoSpacing: false,
  13270. };
  13271. const result = transform(childNode, newContext);
  13272. childContext.global = newContext.global;
  13273. childContext.hasLocals = newContext.hasLocals;
  13274. return result;
  13275. });
  13276. node = node.clone();
  13277. node.nodes = normalizeNodeArray(newNodes);
  13278. if (childContext.hasLocals) {
  13279. context.hasLocals = true;
  13280. }
  13281. }
  13282. break;
  13283. //:local .foo .bar
  13284. } else if (isScoped) {
  13285. if (context.inside) {
  13286. throw new Error(
  13287. `A ${node.value} is not allowed inside of a ${context.inside}(...)`
  13288. );
  13289. }
  13290. const addBackSpacing = !!node.spaces.before;
  13291. context.ignoreNextSpacing = context.lastWasSpacing
  13292. ? node.value
  13293. : false;
  13294. context.enforceNoSpacing = context.lastWasSpacing
  13295. ? false
  13296. : node.value;
  13297. context.global = node.value === ":global";
  13298. context.explicit = true;
  13299. // because this node has spacing that is lost when we remove it
  13300. // we make up for it by adding an extra combinator in since adding
  13301. // spacing on the parent selector doesn't work
  13302. return addBackSpacing
  13303. ? selectorParser.combinator({ value: " " })
  13304. : null;
  13305. }
  13306. break;
  13307. }
  13308. case "id":
  13309. case "class": {
  13310. if (!node.value) {
  13311. throw new Error("Invalid class or id selector syntax");
  13312. }
  13313. if (context.global) {
  13314. break;
  13315. }
  13316. const isImportedValue = localAliasMap.has(node.value);
  13317. const isImportedWithExplicitScope = isImportedValue && context.explicit;
  13318. if (!isImportedValue || isImportedWithExplicitScope) {
  13319. const innerNode = node.clone();
  13320. innerNode.spaces = { before: "", after: "" };
  13321. node = selectorParser.pseudo({
  13322. value: ":local",
  13323. nodes: [innerNode],
  13324. spaces: node.spaces,
  13325. });
  13326. context.hasLocals = true;
  13327. }
  13328. break;
  13329. }
  13330. case "nesting": {
  13331. if (node.value === "&") {
  13332. context.hasLocals = true;
  13333. }
  13334. }
  13335. }
  13336. context.lastWasSpacing = false;
  13337. context.ignoreNextSpacing = false;
  13338. context.enforceNoSpacing = false;
  13339. return node;
  13340. };
  13341. const rootContext = {
  13342. global: mode === "global",
  13343. hasPureGlobals: false,
  13344. };
  13345. rootContext.selector = selectorParser((root) => {
  13346. transform(root, rootContext);
  13347. }).processSync(rule, { updateSelector: false, lossless: true });
  13348. return rootContext;
  13349. }
  13350. function localizeDeclNode(node, context) {
  13351. switch (node.type) {
  13352. case "word":
  13353. if (context.localizeNextItem) {
  13354. if (!context.localAliasMap.has(node.value)) {
  13355. node.value = ":local(" + node.value + ")";
  13356. context.localizeNextItem = false;
  13357. }
  13358. }
  13359. break;
  13360. case "function":
  13361. if (
  13362. context.options &&
  13363. context.options.rewriteUrl &&
  13364. node.value.toLowerCase() === "url"
  13365. ) {
  13366. node.nodes.map((nestedNode) => {
  13367. if (nestedNode.type !== "string" && nestedNode.type !== "word") {
  13368. return;
  13369. }
  13370. let newUrl = context.options.rewriteUrl(
  13371. context.global,
  13372. nestedNode.value
  13373. );
  13374. switch (nestedNode.type) {
  13375. case "string":
  13376. if (nestedNode.quote === "'") {
  13377. newUrl = newUrl.replace(/(\\)/g, "\\$1").replace(/'/g, "\\'");
  13378. }
  13379. if (nestedNode.quote === '"') {
  13380. newUrl = newUrl.replace(/(\\)/g, "\\$1").replace(/"/g, '\\"');
  13381. }
  13382. break;
  13383. case "word":
  13384. newUrl = newUrl.replace(/("|'|\)|\\)/g, "\\$1");
  13385. break;
  13386. }
  13387. nestedNode.value = newUrl;
  13388. });
  13389. }
  13390. break;
  13391. }
  13392. return node;
  13393. }
  13394. // `none` is special value, other is global values
  13395. const specialKeywords = [
  13396. "none",
  13397. "inherit",
  13398. "initial",
  13399. "revert",
  13400. "revert-layer",
  13401. "unset",
  13402. ];
  13403. function localizeDeclarationValues(localize, declaration, context) {
  13404. const valueNodes = valueParser(declaration.value);
  13405. valueNodes.walk((node, index, nodes) => {
  13406. if (
  13407. node.type === "function" &&
  13408. (node.value.toLowerCase() === "var" || node.value.toLowerCase() === "env")
  13409. ) {
  13410. return false;
  13411. }
  13412. if (
  13413. node.type === "word" &&
  13414. specialKeywords.includes(node.value.toLowerCase())
  13415. ) {
  13416. return;
  13417. }
  13418. const subContext = {
  13419. options: context.options,
  13420. global: context.global,
  13421. localizeNextItem: localize && !context.global,
  13422. localAliasMap: context.localAliasMap,
  13423. };
  13424. nodes[index] = localizeDeclNode(node, subContext);
  13425. });
  13426. declaration.value = valueNodes.toString();
  13427. }
  13428. function localizeDeclaration(declaration, context) {
  13429. const isAnimation = /animation$/i.test(declaration.prop);
  13430. if (isAnimation) {
  13431. // letter
  13432. // An uppercase letter or a lowercase letter.
  13433. //
  13434. // ident-start code point
  13435. // A letter, a non-ASCII code point, or U+005F LOW LINE (_).
  13436. //
  13437. // ident code point
  13438. // An ident-start code point, a digit, or U+002D HYPHEN-MINUS (-).
  13439. // We don't validate `hex digits`, because we don't need it, it is work of linters.
  13440. const validIdent =
  13441. /^-?([a-z\u0080-\uFFFF_]|(\\[^\r\n\f])|-(?![0-9]))((\\[^\r\n\f])|[a-z\u0080-\uFFFF_0-9-])*$/i;
  13442. /*
  13443. The spec defines some keywords that you can use to describe properties such as the timing
  13444. function. These are still valid animation names, so as long as there is a property that accepts
  13445. a keyword, it is given priority. Only when all the properties that can take a keyword are
  13446. exhausted can the animation name be set to the keyword. I.e.
  13447. animation: infinite infinite;
  13448. The animation will repeat an infinite number of times from the first argument, and will have an
  13449. animation name of infinite from the second.
  13450. */
  13451. const animationKeywords = {
  13452. // animation-direction
  13453. $normal: 1,
  13454. $reverse: 1,
  13455. $alternate: 1,
  13456. "$alternate-reverse": 1,
  13457. // animation-fill-mode
  13458. $forwards: 1,
  13459. $backwards: 1,
  13460. $both: 1,
  13461. // animation-iteration-count
  13462. $infinite: 1,
  13463. // animation-play-state
  13464. $paused: 1,
  13465. $running: 1,
  13466. // animation-timing-function
  13467. $ease: 1,
  13468. "$ease-in": 1,
  13469. "$ease-out": 1,
  13470. "$ease-in-out": 1,
  13471. $linear: 1,
  13472. "$step-end": 1,
  13473. "$step-start": 1,
  13474. // Special
  13475. $none: Infinity, // No matter how many times you write none, it will never be an animation name
  13476. // Global values
  13477. $initial: Infinity,
  13478. $inherit: Infinity,
  13479. $unset: Infinity,
  13480. $revert: Infinity,
  13481. "$revert-layer": Infinity,
  13482. };
  13483. let parsedAnimationKeywords = {};
  13484. const valueNodes = valueParser(declaration.value).walk((node) => {
  13485. // If div-token appeared (represents as comma ','), a possibility of an animation-keywords should be reflesh.
  13486. if (node.type === "div") {
  13487. parsedAnimationKeywords = {};
  13488. return;
  13489. }
  13490. // Do not handle nested functions
  13491. else if (node.type === "function") {
  13492. return false;
  13493. }
  13494. // Ignore all except word
  13495. else if (node.type !== "word") {
  13496. return;
  13497. }
  13498. const value = node.type === "word" ? node.value.toLowerCase() : null;
  13499. let shouldParseAnimationName = false;
  13500. if (value && validIdent.test(value)) {
  13501. if ("$" + value in animationKeywords) {
  13502. parsedAnimationKeywords["$" + value] =
  13503. "$" + value in parsedAnimationKeywords
  13504. ? parsedAnimationKeywords["$" + value] + 1
  13505. : 0;
  13506. shouldParseAnimationName =
  13507. parsedAnimationKeywords["$" + value] >=
  13508. animationKeywords["$" + value];
  13509. } else {
  13510. shouldParseAnimationName = true;
  13511. }
  13512. }
  13513. const subContext = {
  13514. options: context.options,
  13515. global: context.global,
  13516. localizeNextItem: shouldParseAnimationName && !context.global,
  13517. localAliasMap: context.localAliasMap,
  13518. };
  13519. return localizeDeclNode(node, subContext);
  13520. });
  13521. declaration.value = valueNodes.toString();
  13522. return;
  13523. }
  13524. const isAnimationName = /animation(-name)?$/i.test(declaration.prop);
  13525. if (isAnimationName) {
  13526. return localizeDeclarationValues(true, declaration, context);
  13527. }
  13528. const hasUrl = /url\(/i.test(declaration.value);
  13529. if (hasUrl) {
  13530. return localizeDeclarationValues(false, declaration, context);
  13531. }
  13532. }
  13533. src$2.exports = (options = {}) => {
  13534. if (
  13535. options &&
  13536. options.mode &&
  13537. options.mode !== "global" &&
  13538. options.mode !== "local" &&
  13539. options.mode !== "pure"
  13540. ) {
  13541. throw new Error(
  13542. 'options.mode must be either "global", "local" or "pure" (default "local")'
  13543. );
  13544. }
  13545. const pureMode = options && options.mode === "pure";
  13546. const globalMode = options && options.mode === "global";
  13547. return {
  13548. postcssPlugin: "postcss-modules-local-by-default",
  13549. prepare() {
  13550. const localAliasMap = new Map();
  13551. return {
  13552. Once(root) {
  13553. const { icssImports } = extractICSS(root, false);
  13554. Object.keys(icssImports).forEach((key) => {
  13555. Object.keys(icssImports[key]).forEach((prop) => {
  13556. localAliasMap.set(prop, icssImports[key][prop]);
  13557. });
  13558. });
  13559. root.walkAtRules((atRule) => {
  13560. if (/keyframes$/i.test(atRule.name)) {
  13561. const globalMatch = /^\s*:global\s*\((.+)\)\s*$/.exec(
  13562. atRule.params
  13563. );
  13564. const localMatch = /^\s*:local\s*\((.+)\)\s*$/.exec(
  13565. atRule.params
  13566. );
  13567. let globalKeyframes = globalMode;
  13568. if (globalMatch) {
  13569. if (pureMode) {
  13570. throw atRule.error(
  13571. "@keyframes :global(...) is not allowed in pure mode"
  13572. );
  13573. }
  13574. atRule.params = globalMatch[1];
  13575. globalKeyframes = true;
  13576. } else if (localMatch) {
  13577. atRule.params = localMatch[0];
  13578. globalKeyframes = false;
  13579. } else if (
  13580. atRule.params &&
  13581. !globalMode &&
  13582. !localAliasMap.has(atRule.params)
  13583. ) {
  13584. atRule.params = ":local(" + atRule.params + ")";
  13585. }
  13586. atRule.walkDecls((declaration) => {
  13587. localizeDeclaration(declaration, {
  13588. localAliasMap,
  13589. options: options,
  13590. global: globalKeyframes,
  13591. });
  13592. });
  13593. } else if (/scope$/i.test(atRule.name)) {
  13594. if (atRule.params) {
  13595. atRule.params = atRule.params
  13596. .split("to")
  13597. .map((item) => {
  13598. const selector = item.trim().slice(1, -1).trim();
  13599. const context = localizeNode(
  13600. selector,
  13601. options.mode,
  13602. localAliasMap
  13603. );
  13604. context.options = options;
  13605. context.localAliasMap = localAliasMap;
  13606. if (pureMode && context.hasPureGlobals) {
  13607. throw atRule.error(
  13608. 'Selector in at-rule"' +
  13609. selector +
  13610. '" is not pure ' +
  13611. "(pure selectors must contain at least one local class or id)"
  13612. );
  13613. }
  13614. return `(${context.selector})`;
  13615. })
  13616. .join(" to ");
  13617. }
  13618. atRule.nodes.forEach((declaration) => {
  13619. if (declaration.type === "decl") {
  13620. localizeDeclaration(declaration, {
  13621. localAliasMap,
  13622. options: options,
  13623. global: globalMode,
  13624. });
  13625. }
  13626. });
  13627. } else if (atRule.nodes) {
  13628. atRule.nodes.forEach((declaration) => {
  13629. if (declaration.type === "decl") {
  13630. localizeDeclaration(declaration, {
  13631. localAliasMap,
  13632. options: options,
  13633. global: globalMode,
  13634. });
  13635. }
  13636. });
  13637. }
  13638. });
  13639. root.walkRules((rule) => {
  13640. if (
  13641. rule.parent &&
  13642. rule.parent.type === "atrule" &&
  13643. /keyframes$/i.test(rule.parent.name)
  13644. ) {
  13645. // ignore keyframe rules
  13646. return;
  13647. }
  13648. const context = localizeNode(rule, options.mode, localAliasMap);
  13649. context.options = options;
  13650. context.localAliasMap = localAliasMap;
  13651. if (pureMode && context.hasPureGlobals) {
  13652. throw rule.error(
  13653. 'Selector "' +
  13654. rule.selector +
  13655. '" is not pure ' +
  13656. "(pure selectors must contain at least one local class or id)"
  13657. );
  13658. }
  13659. rule.selector = context.selector;
  13660. // Less-syntax mixins parse as rules with no nodes
  13661. if (rule.nodes) {
  13662. rule.nodes.forEach((declaration) =>
  13663. localizeDeclaration(declaration, context)
  13664. );
  13665. }
  13666. });
  13667. },
  13668. };
  13669. },
  13670. };
  13671. };
  13672. src$2.exports.postcss = true;
  13673. return src$2.exports;
  13674. }
  13675. var src$1;
  13676. var hasRequiredSrc$1;
  13677. function requireSrc$1 () {
  13678. if (hasRequiredSrc$1) return src$1;
  13679. hasRequiredSrc$1 = 1;
  13680. const selectorParser = /*@__PURE__*/ requireDist();
  13681. const hasOwnProperty = Object.prototype.hasOwnProperty;
  13682. function isNestedRule(rule) {
  13683. if (!rule.parent || rule.parent.type === "root") {
  13684. return false;
  13685. }
  13686. if (rule.parent.type === "rule") {
  13687. return true;
  13688. }
  13689. return isNestedRule(rule.parent);
  13690. }
  13691. function getSingleLocalNamesForComposes(root, rule) {
  13692. if (isNestedRule(rule)) {
  13693. throw new Error(`composition is not allowed in nested rule \n\n${rule}`);
  13694. }
  13695. return root.nodes.map((node) => {
  13696. if (node.type !== "selector" || node.nodes.length !== 1) {
  13697. throw new Error(
  13698. `composition is only allowed when selector is single :local class name not in "${root}"`
  13699. );
  13700. }
  13701. node = node.nodes[0];
  13702. if (
  13703. node.type !== "pseudo" ||
  13704. node.value !== ":local" ||
  13705. node.nodes.length !== 1
  13706. ) {
  13707. throw new Error(
  13708. 'composition is only allowed when selector is single :local class name not in "' +
  13709. root +
  13710. '", "' +
  13711. node +
  13712. '" is weird'
  13713. );
  13714. }
  13715. node = node.first;
  13716. if (node.type !== "selector" || node.length !== 1) {
  13717. throw new Error(
  13718. 'composition is only allowed when selector is single :local class name not in "' +
  13719. root +
  13720. '", "' +
  13721. node +
  13722. '" is weird'
  13723. );
  13724. }
  13725. node = node.first;
  13726. if (node.type !== "class") {
  13727. // 'id' is not possible, because you can't compose ids
  13728. throw new Error(
  13729. 'composition is only allowed when selector is single :local class name not in "' +
  13730. root +
  13731. '", "' +
  13732. node +
  13733. '" is weird'
  13734. );
  13735. }
  13736. return node.value;
  13737. });
  13738. }
  13739. const whitespace = "[\\x20\\t\\r\\n\\f]";
  13740. const unescapeRegExp = new RegExp(
  13741. "\\\\([\\da-f]{1,6}" + whitespace + "?|(" + whitespace + ")|.)",
  13742. "ig"
  13743. );
  13744. function unescape(str) {
  13745. return str.replace(unescapeRegExp, (_, escaped, escapedWhitespace) => {
  13746. const high = "0x" + escaped - 0x10000;
  13747. // NaN means non-codepoint
  13748. // Workaround erroneous numeric interpretation of +"0x"
  13749. return high !== high || escapedWhitespace
  13750. ? escaped
  13751. : high < 0
  13752. ? // BMP codepoint
  13753. String.fromCharCode(high + 0x10000)
  13754. : // Supplemental Plane codepoint (surrogate pair)
  13755. String.fromCharCode((high >> 10) | 0xd800, (high & 0x3ff) | 0xdc00);
  13756. });
  13757. }
  13758. const plugin = (options = {}) => {
  13759. const generateScopedName =
  13760. (options && options.generateScopedName) || plugin.generateScopedName;
  13761. const generateExportEntry =
  13762. (options && options.generateExportEntry) || plugin.generateExportEntry;
  13763. const exportGlobals = options && options.exportGlobals;
  13764. return {
  13765. postcssPlugin: "postcss-modules-scope",
  13766. Once(root, { rule }) {
  13767. const exports = Object.create(null);
  13768. function exportScopedName(name, rawName, node) {
  13769. const scopedName = generateScopedName(
  13770. rawName ? rawName : name,
  13771. root.source.input.from,
  13772. root.source.input.css,
  13773. node
  13774. );
  13775. const exportEntry = generateExportEntry(
  13776. rawName ? rawName : name,
  13777. scopedName,
  13778. root.source.input.from,
  13779. root.source.input.css,
  13780. node
  13781. );
  13782. const { key, value } = exportEntry;
  13783. exports[key] = exports[key] || [];
  13784. if (exports[key].indexOf(value) < 0) {
  13785. exports[key].push(value);
  13786. }
  13787. return scopedName;
  13788. }
  13789. function localizeNode(node) {
  13790. switch (node.type) {
  13791. case "selector":
  13792. node.nodes = node.map((item) => localizeNode(item));
  13793. return node;
  13794. case "class":
  13795. return selectorParser.className({
  13796. value: exportScopedName(
  13797. node.value,
  13798. node.raws && node.raws.value ? node.raws.value : null,
  13799. node
  13800. ),
  13801. });
  13802. case "id": {
  13803. return selectorParser.id({
  13804. value: exportScopedName(
  13805. node.value,
  13806. node.raws && node.raws.value ? node.raws.value : null,
  13807. node
  13808. ),
  13809. });
  13810. }
  13811. case "attribute": {
  13812. if (node.attribute === "class" && node.operator === "=") {
  13813. return selectorParser.attribute({
  13814. attribute: node.attribute,
  13815. operator: node.operator,
  13816. quoteMark: "'",
  13817. value: exportScopedName(node.value, null, null),
  13818. });
  13819. }
  13820. }
  13821. }
  13822. throw new Error(
  13823. `${node.type} ("${node}") is not allowed in a :local block`
  13824. );
  13825. }
  13826. function traverseNode(node) {
  13827. switch (node.type) {
  13828. case "pseudo":
  13829. if (node.value === ":local") {
  13830. if (node.nodes.length !== 1) {
  13831. throw new Error('Unexpected comma (",") in :local block');
  13832. }
  13833. const selector = localizeNode(node.first);
  13834. // move the spaces that were around the pseudo selector to the first
  13835. // non-container node
  13836. selector.first.spaces = node.spaces;
  13837. const nextNode = node.next();
  13838. if (
  13839. nextNode &&
  13840. nextNode.type === "combinator" &&
  13841. nextNode.value === " " &&
  13842. /\\[A-F0-9]{1,6}$/.test(selector.last.value)
  13843. ) {
  13844. selector.last.spaces.after = " ";
  13845. }
  13846. node.replaceWith(selector);
  13847. return;
  13848. }
  13849. /* falls through */
  13850. case "root":
  13851. case "selector": {
  13852. node.each((item) => traverseNode(item));
  13853. break;
  13854. }
  13855. case "id":
  13856. case "class":
  13857. if (exportGlobals) {
  13858. exports[node.value] = [node.value];
  13859. }
  13860. break;
  13861. }
  13862. return node;
  13863. }
  13864. // Find any :import and remember imported names
  13865. const importedNames = {};
  13866. root.walkRules(/^:import\(.+\)$/, (rule) => {
  13867. rule.walkDecls((decl) => {
  13868. importedNames[decl.prop] = true;
  13869. });
  13870. });
  13871. // Find any :local selectors
  13872. root.walkRules((rule) => {
  13873. let parsedSelector = selectorParser().astSync(rule);
  13874. rule.selector = traverseNode(parsedSelector.clone()).toString();
  13875. rule.walkDecls(/^(composes|compose-with)$/i, (decl) => {
  13876. const localNames = getSingleLocalNamesForComposes(
  13877. parsedSelector,
  13878. decl.parent
  13879. );
  13880. const multiple = decl.value.split(",");
  13881. multiple.forEach((value) => {
  13882. const classes = value.trim().split(/\s+/);
  13883. classes.forEach((className) => {
  13884. const global = /^global\(([^)]+)\)$/.exec(className);
  13885. if (global) {
  13886. localNames.forEach((exportedName) => {
  13887. exports[exportedName].push(global[1]);
  13888. });
  13889. } else if (hasOwnProperty.call(importedNames, className)) {
  13890. localNames.forEach((exportedName) => {
  13891. exports[exportedName].push(className);
  13892. });
  13893. } else if (hasOwnProperty.call(exports, className)) {
  13894. localNames.forEach((exportedName) => {
  13895. exports[className].forEach((item) => {
  13896. exports[exportedName].push(item);
  13897. });
  13898. });
  13899. } else {
  13900. throw decl.error(
  13901. `referenced class name "${className}" in ${decl.prop} not found`
  13902. );
  13903. }
  13904. });
  13905. });
  13906. decl.remove();
  13907. });
  13908. // Find any :local values
  13909. rule.walkDecls((decl) => {
  13910. if (!/:local\s*\((.+?)\)/.test(decl.value)) {
  13911. return;
  13912. }
  13913. let tokens = decl.value.split(/(,|'[^']*'|"[^"]*")/);
  13914. tokens = tokens.map((token, idx) => {
  13915. if (idx === 0 || tokens[idx - 1] === ",") {
  13916. let result = token;
  13917. const localMatch = /:local\s*\((.+?)\)/.exec(token);
  13918. if (localMatch) {
  13919. const input = localMatch.input;
  13920. const matchPattern = localMatch[0];
  13921. const matchVal = localMatch[1];
  13922. const newVal = exportScopedName(matchVal);
  13923. result = input.replace(matchPattern, newVal);
  13924. } else {
  13925. return token;
  13926. }
  13927. return result;
  13928. } else {
  13929. return token;
  13930. }
  13931. });
  13932. decl.value = tokens.join("");
  13933. });
  13934. });
  13935. // Find any :local keyframes
  13936. root.walkAtRules(/keyframes$/i, (atRule) => {
  13937. const localMatch = /^\s*:local\s*\((.+?)\)\s*$/.exec(atRule.params);
  13938. if (!localMatch) {
  13939. return;
  13940. }
  13941. atRule.params = exportScopedName(localMatch[1]);
  13942. });
  13943. root.walkAtRules(/scope$/i, (atRule) => {
  13944. if (atRule.params) {
  13945. atRule.params = atRule.params
  13946. .split("to")
  13947. .map((item) => {
  13948. const selector = item.trim().slice(1, -1).trim();
  13949. const localMatch = /^\s*:local\s*\((.+?)\)\s*$/.exec(selector);
  13950. if (!localMatch) {
  13951. return `(${selector})`;
  13952. }
  13953. let parsedSelector = selectorParser().astSync(selector);
  13954. return `(${traverseNode(parsedSelector).toString()})`;
  13955. })
  13956. .join(" to ");
  13957. }
  13958. });
  13959. // If we found any :locals, insert an :export rule
  13960. const exportedNames = Object.keys(exports);
  13961. if (exportedNames.length > 0) {
  13962. const exportRule = rule({ selector: ":export" });
  13963. exportedNames.forEach((exportedName) =>
  13964. exportRule.append({
  13965. prop: exportedName,
  13966. value: exports[exportedName].join(" "),
  13967. raws: { before: "\n " },
  13968. })
  13969. );
  13970. root.append(exportRule);
  13971. }
  13972. },
  13973. };
  13974. };
  13975. plugin.postcss = true;
  13976. plugin.generateScopedName = function (name, path) {
  13977. const sanitisedPath = path
  13978. .replace(/\.[^./\\]+$/, "")
  13979. .replace(/[\W_]+/g, "_")
  13980. .replace(/^_|_$/g, "");
  13981. return `_${sanitisedPath}__${name}`.trim();
  13982. };
  13983. plugin.generateExportEntry = function (name, scopedName) {
  13984. return {
  13985. key: unescape(name),
  13986. value: unescape(scopedName),
  13987. };
  13988. };
  13989. src$1 = plugin;
  13990. return src$1;
  13991. }
  13992. var stringHash;
  13993. var hasRequiredStringHash;
  13994. function requireStringHash () {
  13995. if (hasRequiredStringHash) return stringHash;
  13996. hasRequiredStringHash = 1;
  13997. function hash(str) {
  13998. var hash = 5381,
  13999. i = str.length;
  14000. while(i) {
  14001. hash = (hash * 33) ^ str.charCodeAt(--i);
  14002. }
  14003. /* JavaScript does bitwise operations (like XOR, above) on 32-bit signed
  14004. * integers. Since we want the results to be always positive, convert the
  14005. * signed int to an unsigned by doing an unsigned bitshift. */
  14006. return hash >>> 0;
  14007. }
  14008. stringHash = hash;
  14009. return stringHash;
  14010. }
  14011. var src = {exports: {}};
  14012. var hasRequiredSrc;
  14013. function requireSrc () {
  14014. if (hasRequiredSrc) return src.exports;
  14015. hasRequiredSrc = 1;
  14016. const ICSSUtils = /*@__PURE__*/ requireSrc$4();
  14017. const matchImports = /^(.+?|\([\s\S]+?\))\s+from\s+("[^"]*"|'[^']*'|[\w-]+)$/;
  14018. const matchValueDefinition = /(?:\s+|^)([\w-]+):?(.*?)$/;
  14019. const matchImport = /^([\w-]+)(?:\s+as\s+([\w-]+))?/;
  14020. src.exports = (options) => {
  14021. let importIndex = 0;
  14022. const createImportedName =
  14023. (options && options.createImportedName) ||
  14024. ((importName /*, path*/) =>
  14025. `i__const_${importName.replace(/\W/g, "_")}_${importIndex++}`);
  14026. return {
  14027. postcssPlugin: "postcss-modules-values",
  14028. prepare(result) {
  14029. const importAliases = [];
  14030. const definitions = {};
  14031. return {
  14032. Once(root, postcss) {
  14033. root.walkAtRules(/value/i, (atRule) => {
  14034. const matches = atRule.params.match(matchImports);
  14035. if (matches) {
  14036. let [, /*match*/ aliases, path] = matches;
  14037. // We can use constants for path names
  14038. if (definitions[path]) {
  14039. path = definitions[path];
  14040. }
  14041. const imports = aliases
  14042. .replace(/^\(\s*([\s\S]+)\s*\)$/, "$1")
  14043. .split(/\s*,\s*/)
  14044. .map((alias) => {
  14045. const tokens = matchImport.exec(alias);
  14046. if (tokens) {
  14047. const [, /*match*/ theirName, myName = theirName] = tokens;
  14048. const importedName = createImportedName(myName);
  14049. definitions[myName] = importedName;
  14050. return { theirName, importedName };
  14051. } else {
  14052. throw new Error(`@import statement "${alias}" is invalid!`);
  14053. }
  14054. });
  14055. importAliases.push({ path, imports });
  14056. atRule.remove();
  14057. return;
  14058. }
  14059. if (atRule.params.indexOf("@value") !== -1) {
  14060. result.warn("Invalid value definition: " + atRule.params);
  14061. }
  14062. let [, key, value] = `${atRule.params}${atRule.raws.between}`.match(
  14063. matchValueDefinition
  14064. );
  14065. const normalizedValue = value.replace(/\/\*((?!\*\/).*?)\*\//g, "");
  14066. if (normalizedValue.length === 0) {
  14067. result.warn("Invalid value definition: " + atRule.params);
  14068. atRule.remove();
  14069. return;
  14070. }
  14071. let isOnlySpace = /^\s+$/.test(normalizedValue);
  14072. if (!isOnlySpace) {
  14073. value = value.trim();
  14074. }
  14075. // Add to the definitions, knowing that values can refer to each other
  14076. definitions[key] = ICSSUtils.replaceValueSymbols(
  14077. value,
  14078. definitions
  14079. );
  14080. atRule.remove();
  14081. });
  14082. /* If we have no definitions, don't continue */
  14083. if (!Object.keys(definitions).length) {
  14084. return;
  14085. }
  14086. /* Perform replacements */
  14087. ICSSUtils.replaceSymbols(root, definitions);
  14088. /* 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 */
  14089. const exportDeclarations = Object.keys(definitions).map((key) =>
  14090. postcss.decl({
  14091. value: definitions[key],
  14092. prop: key,
  14093. raws: { before: "\n " },
  14094. })
  14095. );
  14096. /* Add export rules if any */
  14097. if (exportDeclarations.length > 0) {
  14098. const exportRule = postcss.rule({
  14099. selector: ":export",
  14100. raws: { after: "\n" },
  14101. });
  14102. exportRule.append(exportDeclarations);
  14103. root.prepend(exportRule);
  14104. }
  14105. /* Add import rules */
  14106. importAliases.reverse().forEach(({ path, imports }) => {
  14107. const importRule = postcss.rule({
  14108. selector: `:import(${path})`,
  14109. raws: { after: "\n" },
  14110. });
  14111. imports.forEach(({ theirName, importedName }) => {
  14112. importRule.append({
  14113. value: theirName,
  14114. prop: importedName,
  14115. raws: { before: "\n " },
  14116. });
  14117. });
  14118. root.prepend(importRule);
  14119. });
  14120. },
  14121. };
  14122. },
  14123. };
  14124. };
  14125. src.exports.postcss = true;
  14126. return src.exports;
  14127. }
  14128. var hasRequiredScoping;
  14129. function requireScoping () {
  14130. if (hasRequiredScoping) return scoping;
  14131. hasRequiredScoping = 1;
  14132. Object.defineProperty(scoping, "__esModule", {
  14133. value: true
  14134. });
  14135. scoping.behaviours = void 0;
  14136. scoping.getDefaultPlugins = getDefaultPlugins;
  14137. scoping.getDefaultScopeBehaviour = getDefaultScopeBehaviour;
  14138. scoping.getScopedNameGenerator = getScopedNameGenerator;
  14139. var _postcssModulesExtractImports = _interopRequireDefault(/*@__PURE__*/ requireSrc$3());
  14140. var _genericNames = _interopRequireDefault(/*@__PURE__*/ requireGenericNames());
  14141. var _postcssModulesLocalByDefault = _interopRequireDefault(/*@__PURE__*/ requireSrc$2());
  14142. var _postcssModulesScope = _interopRequireDefault(/*@__PURE__*/ requireSrc$1());
  14143. var _stringHash = _interopRequireDefault(/*@__PURE__*/ requireStringHash());
  14144. var _postcssModulesValues = _interopRequireDefault(/*@__PURE__*/ requireSrc());
  14145. function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
  14146. const behaviours = {
  14147. LOCAL: "local",
  14148. GLOBAL: "global"
  14149. };
  14150. scoping.behaviours = behaviours;
  14151. function getDefaultPlugins({
  14152. behaviour,
  14153. generateScopedName,
  14154. exportGlobals
  14155. }) {
  14156. const scope = (0, _postcssModulesScope.default)({
  14157. generateScopedName,
  14158. exportGlobals
  14159. });
  14160. const plugins = {
  14161. [behaviours.LOCAL]: [_postcssModulesValues.default, (0, _postcssModulesLocalByDefault.default)({
  14162. mode: "local"
  14163. }), _postcssModulesExtractImports.default, scope],
  14164. [behaviours.GLOBAL]: [_postcssModulesValues.default, (0, _postcssModulesLocalByDefault.default)({
  14165. mode: "global"
  14166. }), _postcssModulesExtractImports.default, scope]
  14167. };
  14168. return plugins[behaviour];
  14169. }
  14170. function isValidBehaviour(behaviour) {
  14171. return Object.keys(behaviours).map(key => behaviours[key]).indexOf(behaviour) > -1;
  14172. }
  14173. function getDefaultScopeBehaviour(scopeBehaviour) {
  14174. return scopeBehaviour && isValidBehaviour(scopeBehaviour) ? scopeBehaviour : behaviours.LOCAL;
  14175. }
  14176. function generateScopedNameDefault(name, filename, css) {
  14177. const i = css.indexOf(`.${name}`);
  14178. const lineNumber = css.substr(0, i).split(/[\r\n]/).length;
  14179. const hash = (0, _stringHash.default)(css).toString(36).substr(0, 5);
  14180. return `_${name}_${hash}_${lineNumber}`;
  14181. }
  14182. function getScopedNameGenerator(generateScopedName, hashPrefix) {
  14183. const scopedNameGenerator = generateScopedName || generateScopedNameDefault;
  14184. if (typeof scopedNameGenerator === "function") {
  14185. return scopedNameGenerator;
  14186. }
  14187. return (0, _genericNames.default)(scopedNameGenerator, {
  14188. context: process.cwd(),
  14189. hashPrefix: hashPrefix
  14190. });
  14191. }
  14192. return scoping;
  14193. }
  14194. var hasRequiredPluginFactory;
  14195. function requirePluginFactory () {
  14196. if (hasRequiredPluginFactory) return pluginFactory;
  14197. hasRequiredPluginFactory = 1;
  14198. Object.defineProperty(pluginFactory, "__esModule", {
  14199. value: true
  14200. });
  14201. pluginFactory.makePlugin = makePlugin;
  14202. var _postcss = _interopRequireDefault(require$$0$1);
  14203. var _unquote = _interopRequireDefault(/*@__PURE__*/ requireUnquote());
  14204. var _Parser = _interopRequireDefault(/*@__PURE__*/ requireParser());
  14205. var _saveJSON = _interopRequireDefault(/*@__PURE__*/ requireSaveJSON());
  14206. var _localsConvention = /*@__PURE__*/ requireLocalsConvention();
  14207. var _FileSystemLoader = _interopRequireDefault(/*@__PURE__*/ requireFileSystemLoader());
  14208. var _scoping = /*@__PURE__*/ requireScoping();
  14209. function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
  14210. const PLUGIN_NAME = "postcss-modules";
  14211. function isGlobalModule(globalModules, inputFile) {
  14212. return globalModules.some(regex => inputFile.match(regex));
  14213. }
  14214. function getDefaultPluginsList(opts, inputFile) {
  14215. const globalModulesList = opts.globalModulePaths || null;
  14216. const exportGlobals = opts.exportGlobals || false;
  14217. const defaultBehaviour = (0, _scoping.getDefaultScopeBehaviour)(opts.scopeBehaviour);
  14218. const generateScopedName = (0, _scoping.getScopedNameGenerator)(opts.generateScopedName, opts.hashPrefix);
  14219. if (globalModulesList && isGlobalModule(globalModulesList, inputFile)) {
  14220. return (0, _scoping.getDefaultPlugins)({
  14221. behaviour: _scoping.behaviours.GLOBAL,
  14222. generateScopedName,
  14223. exportGlobals
  14224. });
  14225. }
  14226. return (0, _scoping.getDefaultPlugins)({
  14227. behaviour: defaultBehaviour,
  14228. generateScopedName,
  14229. exportGlobals
  14230. });
  14231. }
  14232. function getLoader(opts, plugins) {
  14233. const root = typeof opts.root === "undefined" ? "/" : opts.root;
  14234. return typeof opts.Loader === "function" ? new opts.Loader(root, plugins, opts.resolve) : new _FileSystemLoader.default(root, plugins, opts.resolve);
  14235. }
  14236. function isOurPlugin(plugin) {
  14237. return plugin.postcssPlugin === PLUGIN_NAME;
  14238. }
  14239. function makePlugin(opts) {
  14240. return {
  14241. postcssPlugin: PLUGIN_NAME,
  14242. async OnceExit(css, {
  14243. result
  14244. }) {
  14245. const getJSON = opts.getJSON || _saveJSON.default;
  14246. const inputFile = css.source.input.file;
  14247. const pluginList = getDefaultPluginsList(opts, inputFile);
  14248. const resultPluginIndex = result.processor.plugins.findIndex(plugin => isOurPlugin(plugin));
  14249. if (resultPluginIndex === -1) {
  14250. throw new Error("Plugin missing from options.");
  14251. }
  14252. const earlierPlugins = result.processor.plugins.slice(0, resultPluginIndex);
  14253. const loaderPlugins = [...earlierPlugins, ...pluginList];
  14254. const loader = getLoader(opts, loaderPlugins);
  14255. const fetcher = async (file, relativeTo, depTrace) => {
  14256. const unquoteFile = (0, _unquote.default)(file);
  14257. return loader.fetch.call(loader, unquoteFile, relativeTo, depTrace);
  14258. };
  14259. const parser = new _Parser.default(fetcher);
  14260. await (0, _postcss.default)([...pluginList, parser.plugin()]).process(css, {
  14261. from: inputFile
  14262. });
  14263. const out = loader.finalSource;
  14264. if (out) css.prepend(out);
  14265. if (opts.localsConvention) {
  14266. const reducer = (0, _localsConvention.makeLocalsConventionReducer)(opts.localsConvention, inputFile);
  14267. parser.exportTokens = Object.entries(parser.exportTokens).reduce(reducer, {});
  14268. }
  14269. result.messages.push({
  14270. type: "export",
  14271. plugin: "postcss-modules",
  14272. exportTokens: parser.exportTokens
  14273. }); // getJSON may return a promise
  14274. return getJSON(css.source.input.file, parser.exportTokens, result.opts.to);
  14275. }
  14276. };
  14277. }
  14278. return pluginFactory;
  14279. }
  14280. var hasRequiredBuild;
  14281. function requireBuild () {
  14282. if (hasRequiredBuild) return build.exports;
  14283. hasRequiredBuild = 1;
  14284. var _fs = require$$0;
  14285. var _fs2 = /*@__PURE__*/ requireFs();
  14286. var _pluginFactory = /*@__PURE__*/ requirePluginFactory();
  14287. (0, _fs2.setFileSystem)({
  14288. readFile: _fs.readFile,
  14289. writeFile: _fs.writeFile
  14290. });
  14291. build.exports = (opts = {}) => (0, _pluginFactory.makePlugin)(opts);
  14292. build.exports.postcss = true;
  14293. return build.exports;
  14294. }
  14295. var buildExports = /*@__PURE__*/ requireBuild();
  14296. var postcssModules = /*@__PURE__*/getDefaultExportFromCjs(buildExports);
  14297. function compileStyle(options) {
  14298. return doCompileStyle({
  14299. ...options,
  14300. isAsync: false
  14301. });
  14302. }
  14303. function compileStyleAsync(options) {
  14304. return doCompileStyle({
  14305. ...options,
  14306. isAsync: true
  14307. });
  14308. }
  14309. function doCompileStyle(options) {
  14310. const {
  14311. filename,
  14312. id,
  14313. scoped = false,
  14314. trim = true,
  14315. isProd = false,
  14316. modules = false,
  14317. modulesOptions = {},
  14318. preprocessLang,
  14319. postcssOptions,
  14320. postcssPlugins
  14321. } = options;
  14322. const preprocessor = preprocessLang && processors[preprocessLang];
  14323. const preProcessedSource = preprocessor && preprocess(options, preprocessor);
  14324. const map = preProcessedSource ? preProcessedSource.map : options.inMap || options.map;
  14325. const source = preProcessedSource ? preProcessedSource.code : options.source;
  14326. const shortId = id.replace(/^data-v-/, "");
  14327. const longId = `data-v-${shortId}`;
  14328. const plugins = (postcssPlugins || []).slice();
  14329. plugins.unshift(cssVarsPlugin({ id: shortId, isProd }));
  14330. if (trim) {
  14331. plugins.push(trimPlugin());
  14332. }
  14333. if (scoped) {
  14334. plugins.push(scopedPlugin(longId));
  14335. }
  14336. let cssModules;
  14337. if (modules) {
  14338. if (!options.isAsync) {
  14339. throw new Error(
  14340. "[@vue/compiler-sfc] `modules` option can only be used with compileStyleAsync()."
  14341. );
  14342. }
  14343. plugins.push(
  14344. postcssModules({
  14345. ...modulesOptions,
  14346. getJSON: (_cssFileName, json) => {
  14347. cssModules = json;
  14348. }
  14349. })
  14350. );
  14351. }
  14352. const postCSSOptions = {
  14353. ...postcssOptions,
  14354. to: filename,
  14355. from: filename
  14356. };
  14357. if (map) {
  14358. postCSSOptions.map = {
  14359. inline: false,
  14360. annotation: false,
  14361. prev: map
  14362. };
  14363. }
  14364. let result;
  14365. let code;
  14366. let outMap;
  14367. const dependencies = new Set(
  14368. preProcessedSource ? preProcessedSource.dependencies : []
  14369. );
  14370. dependencies.delete(filename);
  14371. const errors = [];
  14372. if (preProcessedSource && preProcessedSource.errors.length) {
  14373. errors.push(...preProcessedSource.errors);
  14374. }
  14375. const recordPlainCssDependencies = (messages) => {
  14376. messages.forEach((msg) => {
  14377. if (msg.type === "dependency") {
  14378. dependencies.add(msg.file);
  14379. }
  14380. });
  14381. return dependencies;
  14382. };
  14383. try {
  14384. result = require$$0$1(plugins).process(source, postCSSOptions);
  14385. if (options.isAsync) {
  14386. return result.then((result2) => ({
  14387. code: result2.css || "",
  14388. map: result2.map && result2.map.toJSON(),
  14389. errors,
  14390. modules: cssModules,
  14391. rawResult: result2,
  14392. dependencies: recordPlainCssDependencies(result2.messages)
  14393. })).catch((error) => ({
  14394. code: "",
  14395. map: void 0,
  14396. errors: [...errors, error],
  14397. rawResult: void 0,
  14398. dependencies
  14399. }));
  14400. }
  14401. recordPlainCssDependencies(result.messages);
  14402. code = result.css;
  14403. outMap = result.map;
  14404. } catch (e) {
  14405. errors.push(e);
  14406. }
  14407. return {
  14408. code: code || ``,
  14409. map: outMap && outMap.toJSON(),
  14410. errors,
  14411. rawResult: result,
  14412. dependencies
  14413. };
  14414. }
  14415. function preprocess(options, preprocessor) {
  14416. return preprocessor(
  14417. options.source,
  14418. options.inMap || options.map,
  14419. {
  14420. filename: options.filename,
  14421. ...options.preprocessOptions
  14422. },
  14423. options.preprocessCustomRequire
  14424. );
  14425. }
  14426. const UNKNOWN_TYPE = "Unknown";
  14427. function resolveObjectKey(node, computed) {
  14428. switch (node.type) {
  14429. case "StringLiteral":
  14430. case "NumericLiteral":
  14431. return String(node.value);
  14432. case "Identifier":
  14433. if (!computed) return node.name;
  14434. }
  14435. return void 0;
  14436. }
  14437. function concatStrings(strs) {
  14438. return strs.filter((s) => !!s).join(", ");
  14439. }
  14440. function isLiteralNode(node) {
  14441. return node.type.endsWith("Literal");
  14442. }
  14443. function isCallOf(node, test) {
  14444. return !!(node && test && node.type === "CallExpression" && node.callee.type === "Identifier" && (typeof test === "string" ? node.callee.name === test : test(node.callee.name)));
  14445. }
  14446. function toRuntimeTypeString(types) {
  14447. return types.length > 1 ? `[${types.join(", ")}]` : types[0];
  14448. }
  14449. function getImportedName(specifier) {
  14450. if (specifier.type === "ImportSpecifier")
  14451. return specifier.imported.type === "Identifier" ? specifier.imported.name : specifier.imported.value;
  14452. else if (specifier.type === "ImportNamespaceSpecifier") return "*";
  14453. return "default";
  14454. }
  14455. function getId(node) {
  14456. return node.type === "Identifier" ? node.name : node.type === "StringLiteral" ? node.value : null;
  14457. }
  14458. const identity = (str) => str;
  14459. const fileNameLowerCaseRegExp = /[^\u0130\u0131\u00DFa-z0-9\\/:\-_\. ]+/g;
  14460. const toLowerCase = (str) => str.toLowerCase();
  14461. function toFileNameLowerCase(x) {
  14462. return fileNameLowerCaseRegExp.test(x) ? x.replace(fileNameLowerCaseRegExp, toLowerCase) : x;
  14463. }
  14464. function createGetCanonicalFileName(useCaseSensitiveFileNames) {
  14465. return useCaseSensitiveFileNames ? identity : toFileNameLowerCase;
  14466. }
  14467. const normalize = (path$1.posix || path$1).normalize;
  14468. const windowsSlashRE = /\\/g;
  14469. function normalizePath(p) {
  14470. return normalize(p.replace(windowsSlashRE, "/"));
  14471. }
  14472. const joinPaths = (path$1.posix || path$1).join;
  14473. const propNameEscapeSymbolsRE = /[ !"#$%&'()*+,./:;<=>?@[\\\]^`{|}~\-]/;
  14474. function getEscapedPropName(key) {
  14475. return propNameEscapeSymbolsRE.test(key) ? JSON.stringify(key) : key;
  14476. }
  14477. function analyzeScriptBindings(ast) {
  14478. for (const node of ast) {
  14479. if (node.type === "ExportDefaultDeclaration" && node.declaration.type === "ObjectExpression") {
  14480. return analyzeBindingsFromOptions(node.declaration);
  14481. }
  14482. }
  14483. return {};
  14484. }
  14485. function analyzeBindingsFromOptions(node) {
  14486. const bindings = {};
  14487. Object.defineProperty(bindings, "__isScriptSetup", {
  14488. enumerable: false,
  14489. value: false
  14490. });
  14491. for (const property of node.properties) {
  14492. if (property.type === "ObjectProperty" && !property.computed && property.key.type === "Identifier") {
  14493. if (property.key.name === "props") {
  14494. for (const key of getObjectOrArrayExpressionKeys(property.value)) {
  14495. bindings[key] = "props";
  14496. }
  14497. } else if (property.key.name === "inject") {
  14498. for (const key of getObjectOrArrayExpressionKeys(property.value)) {
  14499. bindings[key] = "options";
  14500. }
  14501. } else if (property.value.type === "ObjectExpression" && (property.key.name === "computed" || property.key.name === "methods")) {
  14502. for (const key of getObjectExpressionKeys(property.value)) {
  14503. bindings[key] = "options";
  14504. }
  14505. }
  14506. } else if (property.type === "ObjectMethod" && property.key.type === "Identifier" && (property.key.name === "setup" || property.key.name === "data")) {
  14507. for (const bodyItem of property.body.body) {
  14508. if (bodyItem.type === "ReturnStatement" && bodyItem.argument && bodyItem.argument.type === "ObjectExpression") {
  14509. for (const key of getObjectExpressionKeys(bodyItem.argument)) {
  14510. bindings[key] = property.key.name === "setup" ? "setup-maybe-ref" : "data";
  14511. }
  14512. }
  14513. }
  14514. }
  14515. }
  14516. return bindings;
  14517. }
  14518. function getObjectExpressionKeys(node) {
  14519. const keys = [];
  14520. for (const prop of node.properties) {
  14521. if (prop.type === "SpreadElement") continue;
  14522. const key = resolveObjectKey(prop.key, prop.computed);
  14523. if (key) keys.push(String(key));
  14524. }
  14525. return keys;
  14526. }
  14527. function getArrayExpressionKeys(node) {
  14528. const keys = [];
  14529. for (const element of node.elements) {
  14530. if (element && element.type === "StringLiteral") {
  14531. keys.push(element.value);
  14532. }
  14533. }
  14534. return keys;
  14535. }
  14536. function getObjectOrArrayExpressionKeys(value) {
  14537. if (value.type === "ArrayExpression") {
  14538. return getArrayExpressionKeys(value);
  14539. }
  14540. if (value.type === "ObjectExpression") {
  14541. return getObjectExpressionKeys(value);
  14542. }
  14543. return [];
  14544. }
  14545. var _a, _b;
  14546. class ScriptCompileContext {
  14547. constructor(descriptor, options) {
  14548. this.descriptor = descriptor;
  14549. this.options = options;
  14550. this.isCE = false;
  14551. this.source = this.descriptor.source;
  14552. this.filename = this.descriptor.filename;
  14553. this.s = new MagicString(this.source);
  14554. this.startOffset = (_a = this.descriptor.scriptSetup) == null ? void 0 : _a.loc.start.offset;
  14555. this.endOffset = (_b = this.descriptor.scriptSetup) == null ? void 0 : _b.loc.end.offset;
  14556. this.userImports = /* @__PURE__ */ Object.create(null);
  14557. // macros presence check
  14558. this.hasDefinePropsCall = false;
  14559. this.hasDefineEmitCall = false;
  14560. this.hasDefineExposeCall = false;
  14561. this.hasDefaultExportName = false;
  14562. this.hasDefaultExportRender = false;
  14563. this.hasDefineOptionsCall = false;
  14564. this.hasDefineSlotsCall = false;
  14565. this.hasDefineModelCall = false;
  14566. this.propsDestructuredBindings = /* @__PURE__ */ Object.create(null);
  14567. // defineModel
  14568. this.modelDecls = /* @__PURE__ */ Object.create(null);
  14569. // codegen
  14570. this.bindingMetadata = {};
  14571. this.helperImports = /* @__PURE__ */ new Set();
  14572. const { script, scriptSetup } = descriptor;
  14573. const scriptLang = script && script.lang;
  14574. const scriptSetupLang = scriptSetup && scriptSetup.lang;
  14575. this.isJS = scriptLang === "js" || scriptLang === "jsx" || scriptSetupLang === "js" || scriptSetupLang === "jsx";
  14576. this.isTS = scriptLang === "ts" || scriptLang === "tsx" || scriptSetupLang === "ts" || scriptSetupLang === "tsx";
  14577. const customElement = options.customElement;
  14578. const filename = this.descriptor.filename;
  14579. if (customElement) {
  14580. this.isCE = typeof customElement === "boolean" ? customElement : customElement(filename);
  14581. }
  14582. const plugins = resolveParserPlugins(
  14583. scriptLang || scriptSetupLang,
  14584. options.babelParserPlugins
  14585. );
  14586. function parse(input, offset) {
  14587. try {
  14588. return parser$1.parse(input, {
  14589. plugins,
  14590. sourceType: "module"
  14591. }).program;
  14592. } catch (e) {
  14593. e.message = `[vue/compiler-sfc] ${e.message}
  14594. ${descriptor.filename}
  14595. ${shared.generateCodeFrame(
  14596. descriptor.source,
  14597. e.pos + offset,
  14598. e.pos + offset + 1
  14599. )}`;
  14600. throw e;
  14601. }
  14602. }
  14603. this.scriptAst = descriptor.script && parse(descriptor.script.content, descriptor.script.loc.start.offset);
  14604. this.scriptSetupAst = descriptor.scriptSetup && parse(descriptor.scriptSetup.content, this.startOffset);
  14605. }
  14606. helper(key) {
  14607. this.helperImports.add(key);
  14608. return `_${key}`;
  14609. }
  14610. getString(node, scriptSetup = true) {
  14611. const block = scriptSetup ? this.descriptor.scriptSetup : this.descriptor.script;
  14612. return block.content.slice(node.start, node.end);
  14613. }
  14614. warn(msg, node, scope) {
  14615. warn(generateError(msg, node, this, scope));
  14616. }
  14617. error(msg, node, scope) {
  14618. throw new Error(
  14619. `[@vue/compiler-sfc] ${generateError(msg, node, this, scope)}`
  14620. );
  14621. }
  14622. }
  14623. function generateError(msg, node, ctx, scope) {
  14624. const offset = scope ? scope.offset : ctx.startOffset;
  14625. return `${msg}
  14626. ${(scope || ctx.descriptor).filename}
  14627. ${shared.generateCodeFrame(
  14628. (scope || ctx.descriptor).source,
  14629. node.start + offset,
  14630. node.end + offset
  14631. )}`;
  14632. }
  14633. function resolveParserPlugins(lang, userPlugins, dts = false) {
  14634. const plugins = [];
  14635. if (!userPlugins || !userPlugins.some(
  14636. (p) => p === "importAssertions" || p === "importAttributes" || shared.isArray(p) && p[0] === "importAttributes"
  14637. )) {
  14638. plugins.push("importAttributes");
  14639. }
  14640. if (lang === "jsx" || lang === "tsx" || lang === "mtsx") {
  14641. plugins.push("jsx");
  14642. } else if (userPlugins) {
  14643. userPlugins = userPlugins.filter((p) => p !== "jsx");
  14644. }
  14645. if (lang === "ts" || lang === "mts" || lang === "tsx" || lang === "mtsx") {
  14646. plugins.push(["typescript", { dts }], "explicitResourceManagement");
  14647. if (!userPlugins || !userPlugins.includes("decorators")) {
  14648. plugins.push("decorators-legacy");
  14649. }
  14650. }
  14651. if (userPlugins) {
  14652. plugins.push(...userPlugins);
  14653. }
  14654. return plugins;
  14655. }
  14656. function rewriteDefault(input, as, parserPlugins) {
  14657. const ast = parser$1.parse(input, {
  14658. sourceType: "module",
  14659. plugins: resolveParserPlugins("js", parserPlugins)
  14660. }).program.body;
  14661. const s = new MagicString(input);
  14662. rewriteDefaultAST(ast, s, as);
  14663. return s.toString();
  14664. }
  14665. function rewriteDefaultAST(ast, s, as) {
  14666. if (!hasDefaultExport(ast)) {
  14667. s.append(`
  14668. const ${as} = {}`);
  14669. return;
  14670. }
  14671. ast.forEach((node) => {
  14672. if (node.type === "ExportDefaultDeclaration") {
  14673. if (node.declaration.type === "ClassDeclaration" && node.declaration.id) {
  14674. let start = node.declaration.decorators && node.declaration.decorators.length > 0 ? node.declaration.decorators[node.declaration.decorators.length - 1].end : node.start;
  14675. s.overwrite(start, node.declaration.id.start, ` class `);
  14676. s.append(`
  14677. const ${as} = ${node.declaration.id.name}`);
  14678. } else {
  14679. s.overwrite(node.start, node.declaration.start, `const ${as} = `);
  14680. }
  14681. } else if (node.type === "ExportNamedDeclaration") {
  14682. for (const specifier of node.specifiers) {
  14683. if (specifier.type === "ExportSpecifier" && specifier.exported.type === "Identifier" && specifier.exported.name === "default") {
  14684. if (node.source) {
  14685. if (specifier.local.name === "default") {
  14686. s.prepend(
  14687. `import { default as __VUE_DEFAULT__ } from '${node.source.value}'
  14688. `
  14689. );
  14690. const end2 = specifierEnd(s, specifier.local.end, node.end);
  14691. s.remove(specifier.start, end2);
  14692. s.append(`
  14693. const ${as} = __VUE_DEFAULT__`);
  14694. continue;
  14695. } else {
  14696. s.prepend(
  14697. `import { ${s.slice(
  14698. specifier.local.start,
  14699. specifier.local.end
  14700. )} as __VUE_DEFAULT__ } from '${node.source.value}'
  14701. `
  14702. );
  14703. const end2 = specifierEnd(s, specifier.exported.end, node.end);
  14704. s.remove(specifier.start, end2);
  14705. s.append(`
  14706. const ${as} = __VUE_DEFAULT__`);
  14707. continue;
  14708. }
  14709. }
  14710. const end = specifierEnd(s, specifier.end, node.end);
  14711. s.remove(specifier.start, end);
  14712. s.append(`
  14713. const ${as} = ${specifier.local.name}`);
  14714. }
  14715. }
  14716. }
  14717. });
  14718. }
  14719. function hasDefaultExport(ast) {
  14720. for (const stmt of ast) {
  14721. if (stmt.type === "ExportDefaultDeclaration") {
  14722. return true;
  14723. } else if (stmt.type === "ExportNamedDeclaration" && stmt.specifiers.some(
  14724. (spec) => spec.exported.name === "default"
  14725. )) {
  14726. return true;
  14727. }
  14728. }
  14729. return false;
  14730. }
  14731. function specifierEnd(s, end, nodeEnd) {
  14732. let hasCommas = false;
  14733. let oldEnd = end;
  14734. while (end < nodeEnd) {
  14735. if (/\s/.test(s.slice(end, end + 1))) {
  14736. end++;
  14737. } else if (s.slice(end, end + 1) === ",") {
  14738. end++;
  14739. hasCommas = true;
  14740. break;
  14741. } else if (s.slice(end, end + 1) === "}") {
  14742. break;
  14743. }
  14744. }
  14745. return hasCommas ? end : oldEnd;
  14746. }
  14747. const normalScriptDefaultVar = `__default__`;
  14748. function processNormalScript(ctx, scopeId) {
  14749. var _a;
  14750. const script = ctx.descriptor.script;
  14751. if (script.lang && !ctx.isJS && !ctx.isTS) {
  14752. return script;
  14753. }
  14754. try {
  14755. let content = script.content;
  14756. let map = script.map;
  14757. const scriptAst = ctx.scriptAst;
  14758. const bindings = analyzeScriptBindings(scriptAst.body);
  14759. const { cssVars } = ctx.descriptor;
  14760. const { genDefaultAs, isProd } = ctx.options;
  14761. if (cssVars.length || genDefaultAs) {
  14762. const defaultVar = genDefaultAs || normalScriptDefaultVar;
  14763. const s = new MagicString(content);
  14764. rewriteDefaultAST(scriptAst.body, s, defaultVar);
  14765. content = s.toString();
  14766. if (cssVars.length && !((_a = ctx.options.templateOptions) == null ? void 0 : _a.ssr)) {
  14767. content += genNormalScriptCssVarsCode(
  14768. cssVars,
  14769. bindings,
  14770. scopeId,
  14771. !!isProd,
  14772. defaultVar
  14773. );
  14774. }
  14775. if (!genDefaultAs) {
  14776. content += `
  14777. export default ${defaultVar}`;
  14778. }
  14779. }
  14780. return {
  14781. ...script,
  14782. content,
  14783. map,
  14784. bindings,
  14785. scriptAst: scriptAst.body
  14786. };
  14787. } catch (e) {
  14788. return script;
  14789. }
  14790. }
  14791. var balancedMatch;
  14792. var hasRequiredBalancedMatch;
  14793. function requireBalancedMatch () {
  14794. if (hasRequiredBalancedMatch) return balancedMatch;
  14795. hasRequiredBalancedMatch = 1;
  14796. balancedMatch = balanced;
  14797. function balanced(a, b, str) {
  14798. if (a instanceof RegExp) a = maybeMatch(a, str);
  14799. if (b instanceof RegExp) b = maybeMatch(b, str);
  14800. var r = range(a, b, str);
  14801. return r && {
  14802. start: r[0],
  14803. end: r[1],
  14804. pre: str.slice(0, r[0]),
  14805. body: str.slice(r[0] + a.length, r[1]),
  14806. post: str.slice(r[1] + b.length)
  14807. };
  14808. }
  14809. function maybeMatch(reg, str) {
  14810. var m = str.match(reg);
  14811. return m ? m[0] : null;
  14812. }
  14813. balanced.range = range;
  14814. function range(a, b, str) {
  14815. var begs, beg, left, right, result;
  14816. var ai = str.indexOf(a);
  14817. var bi = str.indexOf(b, ai + 1);
  14818. var i = ai;
  14819. if (ai >= 0 && bi > 0) {
  14820. if(a===b) {
  14821. return [ai, bi];
  14822. }
  14823. begs = [];
  14824. left = str.length;
  14825. while (i >= 0 && !result) {
  14826. if (i == ai) {
  14827. begs.push(i);
  14828. ai = str.indexOf(a, i + 1);
  14829. } else if (begs.length == 1) {
  14830. result = [ begs.pop(), bi ];
  14831. } else {
  14832. beg = begs.pop();
  14833. if (beg < left) {
  14834. left = beg;
  14835. right = bi;
  14836. }
  14837. bi = str.indexOf(b, i + 1);
  14838. }
  14839. i = ai < bi && ai >= 0 ? ai : bi;
  14840. }
  14841. if (begs.length) {
  14842. result = [ left, right ];
  14843. }
  14844. }
  14845. return result;
  14846. }
  14847. return balancedMatch;
  14848. }
  14849. var braceExpansion;
  14850. var hasRequiredBraceExpansion;
  14851. function requireBraceExpansion () {
  14852. if (hasRequiredBraceExpansion) return braceExpansion;
  14853. hasRequiredBraceExpansion = 1;
  14854. var balanced = /*@__PURE__*/ requireBalancedMatch();
  14855. braceExpansion = expandTop;
  14856. var escSlash = '\0SLASH'+Math.random()+'\0';
  14857. var escOpen = '\0OPEN'+Math.random()+'\0';
  14858. var escClose = '\0CLOSE'+Math.random()+'\0';
  14859. var escComma = '\0COMMA'+Math.random()+'\0';
  14860. var escPeriod = '\0PERIOD'+Math.random()+'\0';
  14861. function numeric(str) {
  14862. return parseInt(str, 10) == str
  14863. ? parseInt(str, 10)
  14864. : str.charCodeAt(0);
  14865. }
  14866. function escapeBraces(str) {
  14867. return str.split('\\\\').join(escSlash)
  14868. .split('\\{').join(escOpen)
  14869. .split('\\}').join(escClose)
  14870. .split('\\,').join(escComma)
  14871. .split('\\.').join(escPeriod);
  14872. }
  14873. function unescapeBraces(str) {
  14874. return str.split(escSlash).join('\\')
  14875. .split(escOpen).join('{')
  14876. .split(escClose).join('}')
  14877. .split(escComma).join(',')
  14878. .split(escPeriod).join('.');
  14879. }
  14880. // Basically just str.split(","), but handling cases
  14881. // where we have nested braced sections, which should be
  14882. // treated as individual members, like {a,{b,c},d}
  14883. function parseCommaParts(str) {
  14884. if (!str)
  14885. return [''];
  14886. var parts = [];
  14887. var m = balanced('{', '}', str);
  14888. if (!m)
  14889. return str.split(',');
  14890. var pre = m.pre;
  14891. var body = m.body;
  14892. var post = m.post;
  14893. var p = pre.split(',');
  14894. p[p.length-1] += '{' + body + '}';
  14895. var postParts = parseCommaParts(post);
  14896. if (post.length) {
  14897. p[p.length-1] += postParts.shift();
  14898. p.push.apply(p, postParts);
  14899. }
  14900. parts.push.apply(parts, p);
  14901. return parts;
  14902. }
  14903. function expandTop(str) {
  14904. if (!str)
  14905. return [];
  14906. // I don't know why Bash 4.3 does this, but it does.
  14907. // Anything starting with {} will have the first two bytes preserved
  14908. // but *only* at the top level, so {},a}b will not expand to anything,
  14909. // but a{},b}c will be expanded to [a}c,abc].
  14910. // One could argue that this is a bug in Bash, but since the goal of
  14911. // this module is to match Bash's rules, we escape a leading {}
  14912. if (str.substr(0, 2) === '{}') {
  14913. str = '\\{\\}' + str.substr(2);
  14914. }
  14915. return expand(escapeBraces(str), true).map(unescapeBraces);
  14916. }
  14917. function embrace(str) {
  14918. return '{' + str + '}';
  14919. }
  14920. function isPadded(el) {
  14921. return /^-?0\d/.test(el);
  14922. }
  14923. function lte(i, y) {
  14924. return i <= y;
  14925. }
  14926. function gte(i, y) {
  14927. return i >= y;
  14928. }
  14929. function expand(str, isTop) {
  14930. var expansions = [];
  14931. var m = balanced('{', '}', str);
  14932. if (!m) return [str];
  14933. // no need to expand pre, since it is guaranteed to be free of brace-sets
  14934. var pre = m.pre;
  14935. var post = m.post.length
  14936. ? expand(m.post, false)
  14937. : [''];
  14938. if (/\$$/.test(m.pre)) {
  14939. for (var k = 0; k < post.length; k++) {
  14940. var expansion = pre+ '{' + m.body + '}' + post[k];
  14941. expansions.push(expansion);
  14942. }
  14943. } else {
  14944. var isNumericSequence = /^-?\d+\.\.-?\d+(?:\.\.-?\d+)?$/.test(m.body);
  14945. var isAlphaSequence = /^[a-zA-Z]\.\.[a-zA-Z](?:\.\.-?\d+)?$/.test(m.body);
  14946. var isSequence = isNumericSequence || isAlphaSequence;
  14947. var isOptions = m.body.indexOf(',') >= 0;
  14948. if (!isSequence && !isOptions) {
  14949. // {a},b}
  14950. if (m.post.match(/,.*\}/)) {
  14951. str = m.pre + '{' + m.body + escClose + m.post;
  14952. return expand(str);
  14953. }
  14954. return [str];
  14955. }
  14956. var n;
  14957. if (isSequence) {
  14958. n = m.body.split(/\.\./);
  14959. } else {
  14960. n = parseCommaParts(m.body);
  14961. if (n.length === 1) {
  14962. // x{{a,b}}y ==> x{a}y x{b}y
  14963. n = expand(n[0], false).map(embrace);
  14964. if (n.length === 1) {
  14965. return post.map(function(p) {
  14966. return m.pre + n[0] + p;
  14967. });
  14968. }
  14969. }
  14970. }
  14971. // at this point, n is the parts, and we know it's not a comma set
  14972. // with a single entry.
  14973. var N;
  14974. if (isSequence) {
  14975. var x = numeric(n[0]);
  14976. var y = numeric(n[1]);
  14977. var width = Math.max(n[0].length, n[1].length);
  14978. var incr = n.length == 3
  14979. ? Math.abs(numeric(n[2]))
  14980. : 1;
  14981. var test = lte;
  14982. var reverse = y < x;
  14983. if (reverse) {
  14984. incr *= -1;
  14985. test = gte;
  14986. }
  14987. var pad = n.some(isPadded);
  14988. N = [];
  14989. for (var i = x; test(i, y); i += incr) {
  14990. var c;
  14991. if (isAlphaSequence) {
  14992. c = String.fromCharCode(i);
  14993. if (c === '\\')
  14994. c = '';
  14995. } else {
  14996. c = String(i);
  14997. if (pad) {
  14998. var need = width - c.length;
  14999. if (need > 0) {
  15000. var z = new Array(need + 1).join('0');
  15001. if (i < 0)
  15002. c = '-' + z + c.slice(1);
  15003. else
  15004. c = z + c;
  15005. }
  15006. }
  15007. }
  15008. N.push(c);
  15009. }
  15010. } else {
  15011. N = [];
  15012. for (var j = 0; j < n.length; j++) {
  15013. N.push.apply(N, expand(n[j], false));
  15014. }
  15015. }
  15016. for (var j = 0; j < N.length; j++) {
  15017. for (var k = 0; k < post.length; k++) {
  15018. var expansion = pre + N[j] + post[k];
  15019. if (!isTop || isSequence || expansion)
  15020. expansions.push(expansion);
  15021. }
  15022. }
  15023. }
  15024. return expansions;
  15025. }
  15026. return braceExpansion;
  15027. }
  15028. var braceExpansionExports = /*@__PURE__*/ requireBraceExpansion();
  15029. var expand = /*@__PURE__*/getDefaultExportFromCjs(braceExpansionExports);
  15030. const MAX_PATTERN_LENGTH = 1024 * 64;
  15031. const assertValidPattern = (pattern) => {
  15032. if (typeof pattern !== 'string') {
  15033. throw new TypeError('invalid pattern');
  15034. }
  15035. if (pattern.length > MAX_PATTERN_LENGTH) {
  15036. throw new TypeError('pattern is too long');
  15037. }
  15038. };
  15039. // translate the various posix character classes into unicode properties
  15040. // this works across all unicode locales
  15041. // { <posix class>: [<translation>, /u flag required, negated]
  15042. const posixClasses = {
  15043. '[:alnum:]': ['\\p{L}\\p{Nl}\\p{Nd}', true],
  15044. '[:alpha:]': ['\\p{L}\\p{Nl}', true],
  15045. '[:ascii:]': ['\\x' + '00-\\x' + '7f', false],
  15046. '[:blank:]': ['\\p{Zs}\\t', true],
  15047. '[:cntrl:]': ['\\p{Cc}', true],
  15048. '[:digit:]': ['\\p{Nd}', true],
  15049. '[:graph:]': ['\\p{Z}\\p{C}', true, true],
  15050. '[:lower:]': ['\\p{Ll}', true],
  15051. '[:print:]': ['\\p{C}', true],
  15052. '[:punct:]': ['\\p{P}', true],
  15053. '[:space:]': ['\\p{Z}\\t\\r\\n\\v\\f', true],
  15054. '[:upper:]': ['\\p{Lu}', true],
  15055. '[:word:]': ['\\p{L}\\p{Nl}\\p{Nd}\\p{Pc}', true],
  15056. '[:xdigit:]': ['A-Fa-f0-9', false],
  15057. };
  15058. // only need to escape a few things inside of brace expressions
  15059. // escapes: [ \ ] -
  15060. const braceEscape = (s) => s.replace(/[[\]\\-]/g, '\\$&');
  15061. // escape all regexp magic characters
  15062. const regexpEscape = (s) => s.replace(/[-[\]{}()*+?.,\\^$|#\s]/g, '\\$&');
  15063. // everything has already been escaped, we just have to join
  15064. const rangesToString = (ranges) => ranges.join('');
  15065. // takes a glob string at a posix brace expression, and returns
  15066. // an equivalent regular expression source, and boolean indicating
  15067. // whether the /u flag needs to be applied, and the number of chars
  15068. // consumed to parse the character class.
  15069. // This also removes out of order ranges, and returns ($.) if the
  15070. // entire class just no good.
  15071. const parseClass = (glob, position) => {
  15072. const pos = position;
  15073. /* c8 ignore start */
  15074. if (glob.charAt(pos) !== '[') {
  15075. throw new Error('not in a brace expression');
  15076. }
  15077. /* c8 ignore stop */
  15078. const ranges = [];
  15079. const negs = [];
  15080. let i = pos + 1;
  15081. let sawStart = false;
  15082. let uflag = false;
  15083. let escaping = false;
  15084. let negate = false;
  15085. let endPos = pos;
  15086. let rangeStart = '';
  15087. WHILE: while (i < glob.length) {
  15088. const c = glob.charAt(i);
  15089. if ((c === '!' || c === '^') && i === pos + 1) {
  15090. negate = true;
  15091. i++;
  15092. continue;
  15093. }
  15094. if (c === ']' && sawStart && !escaping) {
  15095. endPos = i + 1;
  15096. break;
  15097. }
  15098. sawStart = true;
  15099. if (c === '\\') {
  15100. if (!escaping) {
  15101. escaping = true;
  15102. i++;
  15103. continue;
  15104. }
  15105. // escaped \ char, fall through and treat like normal char
  15106. }
  15107. if (c === '[' && !escaping) {
  15108. // either a posix class, a collation equivalent, or just a [
  15109. for (const [cls, [unip, u, neg]] of Object.entries(posixClasses)) {
  15110. if (glob.startsWith(cls, i)) {
  15111. // invalid, [a-[] is fine, but not [a-[:alpha]]
  15112. if (rangeStart) {
  15113. return ['$.', false, glob.length - pos, true];
  15114. }
  15115. i += cls.length;
  15116. if (neg)
  15117. negs.push(unip);
  15118. else
  15119. ranges.push(unip);
  15120. uflag = uflag || u;
  15121. continue WHILE;
  15122. }
  15123. }
  15124. }
  15125. // now it's just a normal character, effectively
  15126. escaping = false;
  15127. if (rangeStart) {
  15128. // throw this range away if it's not valid, but others
  15129. // can still match.
  15130. if (c > rangeStart) {
  15131. ranges.push(braceEscape(rangeStart) + '-' + braceEscape(c));
  15132. }
  15133. else if (c === rangeStart) {
  15134. ranges.push(braceEscape(c));
  15135. }
  15136. rangeStart = '';
  15137. i++;
  15138. continue;
  15139. }
  15140. // now might be the start of a range.
  15141. // can be either c-d or c-] or c<more...>] or c] at this point
  15142. if (glob.startsWith('-]', i + 1)) {
  15143. ranges.push(braceEscape(c + '-'));
  15144. i += 2;
  15145. continue;
  15146. }
  15147. if (glob.startsWith('-', i + 1)) {
  15148. rangeStart = c;
  15149. i += 2;
  15150. continue;
  15151. }
  15152. // not the start of a range, just a single character
  15153. ranges.push(braceEscape(c));
  15154. i++;
  15155. }
  15156. if (endPos < i) {
  15157. // didn't see the end of the class, not a valid class,
  15158. // but might still be valid as a literal match.
  15159. return ['', false, 0, false];
  15160. }
  15161. // if we got no ranges and no negates, then we have a range that
  15162. // cannot possibly match anything, and that poisons the whole glob
  15163. if (!ranges.length && !negs.length) {
  15164. return ['$.', false, glob.length - pos, true];
  15165. }
  15166. // if we got one positive range, and it's a single character, then that's
  15167. // not actually a magic pattern, it's just that one literal character.
  15168. // we should not treat that as "magic", we should just return the literal
  15169. // character. [_] is a perfectly valid way to escape glob magic chars.
  15170. if (negs.length === 0 &&
  15171. ranges.length === 1 &&
  15172. /^\\?.$/.test(ranges[0]) &&
  15173. !negate) {
  15174. const r = ranges[0].length === 2 ? ranges[0].slice(-1) : ranges[0];
  15175. return [regexpEscape(r), false, endPos - pos, false];
  15176. }
  15177. const sranges = '[' + (negate ? '^' : '') + rangesToString(ranges) + ']';
  15178. const snegs = '[' + (negate ? '' : '^') + rangesToString(negs) + ']';
  15179. const comb = ranges.length && negs.length
  15180. ? '(' + sranges + '|' + snegs + ')'
  15181. : ranges.length
  15182. ? sranges
  15183. : snegs;
  15184. return [comb, uflag, endPos - pos, true];
  15185. };
  15186. /**
  15187. * Un-escape a string that has been escaped with {@link escape}.
  15188. *
  15189. * If the {@link windowsPathsNoEscape} option is used, then square-brace
  15190. * escapes are removed, but not backslash escapes. For example, it will turn
  15191. * the string `'[*]'` into `*`, but it will not turn `'\\*'` into `'*'`,
  15192. * becuase `\` is a path separator in `windowsPathsNoEscape` mode.
  15193. *
  15194. * When `windowsPathsNoEscape` is not set, then both brace escapes and
  15195. * backslash escapes are removed.
  15196. *
  15197. * Slashes (and backslashes in `windowsPathsNoEscape` mode) cannot be escaped
  15198. * or unescaped.
  15199. */
  15200. const unescape = (s, { windowsPathsNoEscape = false, } = {}) => {
  15201. return windowsPathsNoEscape
  15202. ? s.replace(/\[([^\/\\])\]/g, '$1')
  15203. : s.replace(/((?!\\).|^)\[([^\/\\])\]/g, '$1$2').replace(/\\([^\/])/g, '$1');
  15204. };
  15205. // parse a single path portion
  15206. const types = new Set(['!', '?', '+', '*', '@']);
  15207. const isExtglobType = (c) => types.has(c);
  15208. // Patterns that get prepended to bind to the start of either the
  15209. // entire string, or just a single path portion, to prevent dots
  15210. // and/or traversal patterns, when needed.
  15211. // Exts don't need the ^ or / bit, because the root binds that already.
  15212. const startNoTraversal = '(?!(?:^|/)\\.\\.?(?:$|/))';
  15213. const startNoDot = '(?!\\.)';
  15214. // characters that indicate a start of pattern needs the "no dots" bit,
  15215. // because a dot *might* be matched. ( is not in the list, because in
  15216. // the case of a child extglob, it will handle the prevention itself.
  15217. const addPatternStart = new Set(['[', '.']);
  15218. // cases where traversal is A-OK, no dot prevention needed
  15219. const justDots = new Set(['..', '.']);
  15220. const reSpecials = new Set('().*{}+?[]^$\\!');
  15221. const regExpEscape$1 = (s) => s.replace(/[-[\]{}()*+?.,\\^$|#\s]/g, '\\$&');
  15222. // any single thing other than /
  15223. const qmark$1 = '[^/]';
  15224. // * => any number of characters
  15225. const star$1 = qmark$1 + '*?';
  15226. // use + when we need to ensure that *something* matches, because the * is
  15227. // the only thing in the path portion.
  15228. const starNoEmpty = qmark$1 + '+?';
  15229. // remove the \ chars that we added if we end up doing a nonmagic compare
  15230. // const deslash = (s: string) => s.replace(/\\(.)/g, '$1')
  15231. class AST {
  15232. type;
  15233. #root;
  15234. #hasMagic;
  15235. #uflag = false;
  15236. #parts = [];
  15237. #parent;
  15238. #parentIndex;
  15239. #negs;
  15240. #filledNegs = false;
  15241. #options;
  15242. #toString;
  15243. // set to true if it's an extglob with no children
  15244. // (which really means one child of '')
  15245. #emptyExt = false;
  15246. constructor(type, parent, options = {}) {
  15247. this.type = type;
  15248. // extglobs are inherently magical
  15249. if (type)
  15250. this.#hasMagic = true;
  15251. this.#parent = parent;
  15252. this.#root = this.#parent ? this.#parent.#root : this;
  15253. this.#options = this.#root === this ? options : this.#root.#options;
  15254. this.#negs = this.#root === this ? [] : this.#root.#negs;
  15255. if (type === '!' && !this.#root.#filledNegs)
  15256. this.#negs.push(this);
  15257. this.#parentIndex = this.#parent ? this.#parent.#parts.length : 0;
  15258. }
  15259. get hasMagic() {
  15260. /* c8 ignore start */
  15261. if (this.#hasMagic !== undefined)
  15262. return this.#hasMagic;
  15263. /* c8 ignore stop */
  15264. for (const p of this.#parts) {
  15265. if (typeof p === 'string')
  15266. continue;
  15267. if (p.type || p.hasMagic)
  15268. return (this.#hasMagic = true);
  15269. }
  15270. // note: will be undefined until we generate the regexp src and find out
  15271. return this.#hasMagic;
  15272. }
  15273. // reconstructs the pattern
  15274. toString() {
  15275. if (this.#toString !== undefined)
  15276. return this.#toString;
  15277. if (!this.type) {
  15278. return (this.#toString = this.#parts.map(p => String(p)).join(''));
  15279. }
  15280. else {
  15281. return (this.#toString =
  15282. this.type + '(' + this.#parts.map(p => String(p)).join('|') + ')');
  15283. }
  15284. }
  15285. #fillNegs() {
  15286. /* c8 ignore start */
  15287. if (this !== this.#root)
  15288. throw new Error('should only call on root');
  15289. if (this.#filledNegs)
  15290. return this;
  15291. /* c8 ignore stop */
  15292. // call toString() once to fill this out
  15293. this.toString();
  15294. this.#filledNegs = true;
  15295. let n;
  15296. while ((n = this.#negs.pop())) {
  15297. if (n.type !== '!')
  15298. continue;
  15299. // walk up the tree, appending everthing that comes AFTER parentIndex
  15300. let p = n;
  15301. let pp = p.#parent;
  15302. while (pp) {
  15303. for (let i = p.#parentIndex + 1; !pp.type && i < pp.#parts.length; i++) {
  15304. for (const part of n.#parts) {
  15305. /* c8 ignore start */
  15306. if (typeof part === 'string') {
  15307. throw new Error('string part in extglob AST??');
  15308. }
  15309. /* c8 ignore stop */
  15310. part.copyIn(pp.#parts[i]);
  15311. }
  15312. }
  15313. p = pp;
  15314. pp = p.#parent;
  15315. }
  15316. }
  15317. return this;
  15318. }
  15319. push(...parts) {
  15320. for (const p of parts) {
  15321. if (p === '')
  15322. continue;
  15323. /* c8 ignore start */
  15324. if (typeof p !== 'string' && !(p instanceof AST && p.#parent === this)) {
  15325. throw new Error('invalid part: ' + p);
  15326. }
  15327. /* c8 ignore stop */
  15328. this.#parts.push(p);
  15329. }
  15330. }
  15331. toJSON() {
  15332. const ret = this.type === null
  15333. ? this.#parts.slice().map(p => (typeof p === 'string' ? p : p.toJSON()))
  15334. : [this.type, ...this.#parts.map(p => p.toJSON())];
  15335. if (this.isStart() && !this.type)
  15336. ret.unshift([]);
  15337. if (this.isEnd() &&
  15338. (this === this.#root ||
  15339. (this.#root.#filledNegs && this.#parent?.type === '!'))) {
  15340. ret.push({});
  15341. }
  15342. return ret;
  15343. }
  15344. isStart() {
  15345. if (this.#root === this)
  15346. return true;
  15347. // if (this.type) return !!this.#parent?.isStart()
  15348. if (!this.#parent?.isStart())
  15349. return false;
  15350. if (this.#parentIndex === 0)
  15351. return true;
  15352. // if everything AHEAD of this is a negation, then it's still the "start"
  15353. const p = this.#parent;
  15354. for (let i = 0; i < this.#parentIndex; i++) {
  15355. const pp = p.#parts[i];
  15356. if (!(pp instanceof AST && pp.type === '!')) {
  15357. return false;
  15358. }
  15359. }
  15360. return true;
  15361. }
  15362. isEnd() {
  15363. if (this.#root === this)
  15364. return true;
  15365. if (this.#parent?.type === '!')
  15366. return true;
  15367. if (!this.#parent?.isEnd())
  15368. return false;
  15369. if (!this.type)
  15370. return this.#parent?.isEnd();
  15371. // if not root, it'll always have a parent
  15372. /* c8 ignore start */
  15373. const pl = this.#parent ? this.#parent.#parts.length : 0;
  15374. /* c8 ignore stop */
  15375. return this.#parentIndex === pl - 1;
  15376. }
  15377. copyIn(part) {
  15378. if (typeof part === 'string')
  15379. this.push(part);
  15380. else
  15381. this.push(part.clone(this));
  15382. }
  15383. clone(parent) {
  15384. const c = new AST(this.type, parent);
  15385. for (const p of this.#parts) {
  15386. c.copyIn(p);
  15387. }
  15388. return c;
  15389. }
  15390. static #parseAST(str, ast, pos, opt) {
  15391. let escaping = false;
  15392. let inBrace = false;
  15393. let braceStart = -1;
  15394. let braceNeg = false;
  15395. if (ast.type === null) {
  15396. // outside of a extglob, append until we find a start
  15397. let i = pos;
  15398. let acc = '';
  15399. while (i < str.length) {
  15400. const c = str.charAt(i++);
  15401. // still accumulate escapes at this point, but we do ignore
  15402. // starts that are escaped
  15403. if (escaping || c === '\\') {
  15404. escaping = !escaping;
  15405. acc += c;
  15406. continue;
  15407. }
  15408. if (inBrace) {
  15409. if (i === braceStart + 1) {
  15410. if (c === '^' || c === '!') {
  15411. braceNeg = true;
  15412. }
  15413. }
  15414. else if (c === ']' && !(i === braceStart + 2 && braceNeg)) {
  15415. inBrace = false;
  15416. }
  15417. acc += c;
  15418. continue;
  15419. }
  15420. else if (c === '[') {
  15421. inBrace = true;
  15422. braceStart = i;
  15423. braceNeg = false;
  15424. acc += c;
  15425. continue;
  15426. }
  15427. if (!opt.noext && isExtglobType(c) && str.charAt(i) === '(') {
  15428. ast.push(acc);
  15429. acc = '';
  15430. const ext = new AST(c, ast);
  15431. i = AST.#parseAST(str, ext, i, opt);
  15432. ast.push(ext);
  15433. continue;
  15434. }
  15435. acc += c;
  15436. }
  15437. ast.push(acc);
  15438. return i;
  15439. }
  15440. // some kind of extglob, pos is at the (
  15441. // find the next | or )
  15442. let i = pos + 1;
  15443. let part = new AST(null, ast);
  15444. const parts = [];
  15445. let acc = '';
  15446. while (i < str.length) {
  15447. const c = str.charAt(i++);
  15448. // still accumulate escapes at this point, but we do ignore
  15449. // starts that are escaped
  15450. if (escaping || c === '\\') {
  15451. escaping = !escaping;
  15452. acc += c;
  15453. continue;
  15454. }
  15455. if (inBrace) {
  15456. if (i === braceStart + 1) {
  15457. if (c === '^' || c === '!') {
  15458. braceNeg = true;
  15459. }
  15460. }
  15461. else if (c === ']' && !(i === braceStart + 2 && braceNeg)) {
  15462. inBrace = false;
  15463. }
  15464. acc += c;
  15465. continue;
  15466. }
  15467. else if (c === '[') {
  15468. inBrace = true;
  15469. braceStart = i;
  15470. braceNeg = false;
  15471. acc += c;
  15472. continue;
  15473. }
  15474. if (isExtglobType(c) && str.charAt(i) === '(') {
  15475. part.push(acc);
  15476. acc = '';
  15477. const ext = new AST(c, part);
  15478. part.push(ext);
  15479. i = AST.#parseAST(str, ext, i, opt);
  15480. continue;
  15481. }
  15482. if (c === '|') {
  15483. part.push(acc);
  15484. acc = '';
  15485. parts.push(part);
  15486. part = new AST(null, ast);
  15487. continue;
  15488. }
  15489. if (c === ')') {
  15490. if (acc === '' && ast.#parts.length === 0) {
  15491. ast.#emptyExt = true;
  15492. }
  15493. part.push(acc);
  15494. acc = '';
  15495. ast.push(...parts, part);
  15496. return i;
  15497. }
  15498. acc += c;
  15499. }
  15500. // unfinished extglob
  15501. // if we got here, it was a malformed extglob! not an extglob, but
  15502. // maybe something else in there.
  15503. ast.type = null;
  15504. ast.#hasMagic = undefined;
  15505. ast.#parts = [str.substring(pos - 1)];
  15506. return i;
  15507. }
  15508. static fromGlob(pattern, options = {}) {
  15509. const ast = new AST(null, undefined, options);
  15510. AST.#parseAST(pattern, ast, 0, options);
  15511. return ast;
  15512. }
  15513. // returns the regular expression if there's magic, or the unescaped
  15514. // string if not.
  15515. toMMPattern() {
  15516. // should only be called on root
  15517. /* c8 ignore start */
  15518. if (this !== this.#root)
  15519. return this.#root.toMMPattern();
  15520. /* c8 ignore stop */
  15521. const glob = this.toString();
  15522. const [re, body, hasMagic, uflag] = this.toRegExpSource();
  15523. // if we're in nocase mode, and not nocaseMagicOnly, then we do
  15524. // still need a regular expression if we have to case-insensitively
  15525. // match capital/lowercase characters.
  15526. const anyMagic = hasMagic ||
  15527. this.#hasMagic ||
  15528. (this.#options.nocase &&
  15529. !this.#options.nocaseMagicOnly &&
  15530. glob.toUpperCase() !== glob.toLowerCase());
  15531. if (!anyMagic) {
  15532. return body;
  15533. }
  15534. const flags = (this.#options.nocase ? 'i' : '') + (uflag ? 'u' : '');
  15535. return Object.assign(new RegExp(`^${re}$`, flags), {
  15536. _src: re,
  15537. _glob: glob,
  15538. });
  15539. }
  15540. get options() {
  15541. return this.#options;
  15542. }
  15543. // returns the string match, the regexp source, whether there's magic
  15544. // in the regexp (so a regular expression is required) and whether or
  15545. // not the uflag is needed for the regular expression (for posix classes)
  15546. // TODO: instead of injecting the start/end at this point, just return
  15547. // the BODY of the regexp, along with the start/end portions suitable
  15548. // for binding the start/end in either a joined full-path makeRe context
  15549. // (where we bind to (^|/), or a standalone matchPart context (where
  15550. // we bind to ^, and not /). Otherwise slashes get duped!
  15551. //
  15552. // In part-matching mode, the start is:
  15553. // - if not isStart: nothing
  15554. // - if traversal possible, but not allowed: ^(?!\.\.?$)
  15555. // - if dots allowed or not possible: ^
  15556. // - if dots possible and not allowed: ^(?!\.)
  15557. // end is:
  15558. // - if not isEnd(): nothing
  15559. // - else: $
  15560. //
  15561. // In full-path matching mode, we put the slash at the START of the
  15562. // pattern, so start is:
  15563. // - if first pattern: same as part-matching mode
  15564. // - if not isStart(): nothing
  15565. // - if traversal possible, but not allowed: /(?!\.\.?(?:$|/))
  15566. // - if dots allowed or not possible: /
  15567. // - if dots possible and not allowed: /(?!\.)
  15568. // end is:
  15569. // - if last pattern, same as part-matching mode
  15570. // - else nothing
  15571. //
  15572. // Always put the (?:$|/) on negated tails, though, because that has to be
  15573. // there to bind the end of the negated pattern portion, and it's easier to
  15574. // just stick it in now rather than try to inject it later in the middle of
  15575. // the pattern.
  15576. //
  15577. // We can just always return the same end, and leave it up to the caller
  15578. // to know whether it's going to be used joined or in parts.
  15579. // And, if the start is adjusted slightly, can do the same there:
  15580. // - if not isStart: nothing
  15581. // - if traversal possible, but not allowed: (?:/|^)(?!\.\.?$)
  15582. // - if dots allowed or not possible: (?:/|^)
  15583. // - if dots possible and not allowed: (?:/|^)(?!\.)
  15584. //
  15585. // But it's better to have a simpler binding without a conditional, for
  15586. // performance, so probably better to return both start options.
  15587. //
  15588. // Then the caller just ignores the end if it's not the first pattern,
  15589. // and the start always gets applied.
  15590. //
  15591. // But that's always going to be $ if it's the ending pattern, or nothing,
  15592. // so the caller can just attach $ at the end of the pattern when building.
  15593. //
  15594. // So the todo is:
  15595. // - better detect what kind of start is needed
  15596. // - return both flavors of starting pattern
  15597. // - attach $ at the end of the pattern when creating the actual RegExp
  15598. //
  15599. // Ah, but wait, no, that all only applies to the root when the first pattern
  15600. // is not an extglob. If the first pattern IS an extglob, then we need all
  15601. // that dot prevention biz to live in the extglob portions, because eg
  15602. // +(*|.x*) can match .xy but not .yx.
  15603. //
  15604. // So, return the two flavors if it's #root and the first child is not an
  15605. // AST, otherwise leave it to the child AST to handle it, and there,
  15606. // use the (?:^|/) style of start binding.
  15607. //
  15608. // Even simplified further:
  15609. // - Since the start for a join is eg /(?!\.) and the start for a part
  15610. // is ^(?!\.), we can just prepend (?!\.) to the pattern (either root
  15611. // or start or whatever) and prepend ^ or / at the Regexp construction.
  15612. toRegExpSource(allowDot) {
  15613. const dot = allowDot ?? !!this.#options.dot;
  15614. if (this.#root === this)
  15615. this.#fillNegs();
  15616. if (!this.type) {
  15617. const noEmpty = this.isStart() && this.isEnd();
  15618. const src = this.#parts
  15619. .map(p => {
  15620. const [re, _, hasMagic, uflag] = typeof p === 'string'
  15621. ? AST.#parseGlob(p, this.#hasMagic, noEmpty)
  15622. : p.toRegExpSource(allowDot);
  15623. this.#hasMagic = this.#hasMagic || hasMagic;
  15624. this.#uflag = this.#uflag || uflag;
  15625. return re;
  15626. })
  15627. .join('');
  15628. let start = '';
  15629. if (this.isStart()) {
  15630. if (typeof this.#parts[0] === 'string') {
  15631. // this is the string that will match the start of the pattern,
  15632. // so we need to protect against dots and such.
  15633. // '.' and '..' cannot match unless the pattern is that exactly,
  15634. // even if it starts with . or dot:true is set.
  15635. const dotTravAllowed = this.#parts.length === 1 && justDots.has(this.#parts[0]);
  15636. if (!dotTravAllowed) {
  15637. const aps = addPatternStart;
  15638. // check if we have a possibility of matching . or ..,
  15639. // and prevent that.
  15640. const needNoTrav =
  15641. // dots are allowed, and the pattern starts with [ or .
  15642. (dot && aps.has(src.charAt(0))) ||
  15643. // the pattern starts with \., and then [ or .
  15644. (src.startsWith('\\.') && aps.has(src.charAt(2))) ||
  15645. // the pattern starts with \.\., and then [ or .
  15646. (src.startsWith('\\.\\.') && aps.has(src.charAt(4)));
  15647. // no need to prevent dots if it can't match a dot, or if a
  15648. // sub-pattern will be preventing it anyway.
  15649. const needNoDot = !dot && !allowDot && aps.has(src.charAt(0));
  15650. start = needNoTrav ? startNoTraversal : needNoDot ? startNoDot : '';
  15651. }
  15652. }
  15653. }
  15654. // append the "end of path portion" pattern to negation tails
  15655. let end = '';
  15656. if (this.isEnd() &&
  15657. this.#root.#filledNegs &&
  15658. this.#parent?.type === '!') {
  15659. end = '(?:$|\\/)';
  15660. }
  15661. const final = start + src + end;
  15662. return [
  15663. final,
  15664. unescape(src),
  15665. (this.#hasMagic = !!this.#hasMagic),
  15666. this.#uflag,
  15667. ];
  15668. }
  15669. // We need to calculate the body *twice* if it's a repeat pattern
  15670. // at the start, once in nodot mode, then again in dot mode, so a
  15671. // pattern like *(?) can match 'x.y'
  15672. const repeated = this.type === '*' || this.type === '+';
  15673. // some kind of extglob
  15674. const start = this.type === '!' ? '(?:(?!(?:' : '(?:';
  15675. let body = this.#partsToRegExp(dot);
  15676. if (this.isStart() && this.isEnd() && !body && this.type !== '!') {
  15677. // invalid extglob, has to at least be *something* present, if it's
  15678. // the entire path portion.
  15679. const s = this.toString();
  15680. this.#parts = [s];
  15681. this.type = null;
  15682. this.#hasMagic = undefined;
  15683. return [s, unescape(this.toString()), false, false];
  15684. }
  15685. // XXX abstract out this map method
  15686. let bodyDotAllowed = !repeated || allowDot || dot || !startNoDot
  15687. ? ''
  15688. : this.#partsToRegExp(true);
  15689. if (bodyDotAllowed === body) {
  15690. bodyDotAllowed = '';
  15691. }
  15692. if (bodyDotAllowed) {
  15693. body = `(?:${body})(?:${bodyDotAllowed})*?`;
  15694. }
  15695. // an empty !() is exactly equivalent to a starNoEmpty
  15696. let final = '';
  15697. if (this.type === '!' && this.#emptyExt) {
  15698. final = (this.isStart() && !dot ? startNoDot : '') + starNoEmpty;
  15699. }
  15700. else {
  15701. const close = this.type === '!'
  15702. ? // !() must match something,but !(x) can match ''
  15703. '))' +
  15704. (this.isStart() && !dot && !allowDot ? startNoDot : '') +
  15705. star$1 +
  15706. ')'
  15707. : this.type === '@'
  15708. ? ')'
  15709. : this.type === '?'
  15710. ? ')?'
  15711. : this.type === '+' && bodyDotAllowed
  15712. ? ')'
  15713. : this.type === '*' && bodyDotAllowed
  15714. ? `)?`
  15715. : `)${this.type}`;
  15716. final = start + body + close;
  15717. }
  15718. return [
  15719. final,
  15720. unescape(body),
  15721. (this.#hasMagic = !!this.#hasMagic),
  15722. this.#uflag,
  15723. ];
  15724. }
  15725. #partsToRegExp(dot) {
  15726. return this.#parts
  15727. .map(p => {
  15728. // extglob ASTs should only contain parent ASTs
  15729. /* c8 ignore start */
  15730. if (typeof p === 'string') {
  15731. throw new Error('string type in extglob ast??');
  15732. }
  15733. /* c8 ignore stop */
  15734. // can ignore hasMagic, because extglobs are already always magic
  15735. const [re, _, _hasMagic, uflag] = p.toRegExpSource(dot);
  15736. this.#uflag = this.#uflag || uflag;
  15737. return re;
  15738. })
  15739. .filter(p => !(this.isStart() && this.isEnd()) || !!p)
  15740. .join('|');
  15741. }
  15742. static #parseGlob(glob, hasMagic, noEmpty = false) {
  15743. let escaping = false;
  15744. let re = '';
  15745. let uflag = false;
  15746. for (let i = 0; i < glob.length; i++) {
  15747. const c = glob.charAt(i);
  15748. if (escaping) {
  15749. escaping = false;
  15750. re += (reSpecials.has(c) ? '\\' : '') + c;
  15751. continue;
  15752. }
  15753. if (c === '\\') {
  15754. if (i === glob.length - 1) {
  15755. re += '\\\\';
  15756. }
  15757. else {
  15758. escaping = true;
  15759. }
  15760. continue;
  15761. }
  15762. if (c === '[') {
  15763. const [src, needUflag, consumed, magic] = parseClass(glob, i);
  15764. if (consumed) {
  15765. re += src;
  15766. uflag = uflag || needUflag;
  15767. i += consumed - 1;
  15768. hasMagic = hasMagic || magic;
  15769. continue;
  15770. }
  15771. }
  15772. if (c === '*') {
  15773. if (noEmpty && glob === '*')
  15774. re += starNoEmpty;
  15775. else
  15776. re += star$1;
  15777. hasMagic = true;
  15778. continue;
  15779. }
  15780. if (c === '?') {
  15781. re += qmark$1;
  15782. hasMagic = true;
  15783. continue;
  15784. }
  15785. re += regExpEscape$1(c);
  15786. }
  15787. return [re, unescape(glob), !!hasMagic, uflag];
  15788. }
  15789. }
  15790. /**
  15791. * Escape all magic characters in a glob pattern.
  15792. *
  15793. * If the {@link windowsPathsNoEscape | GlobOptions.windowsPathsNoEscape}
  15794. * option is used, then characters are escaped by wrapping in `[]`, because
  15795. * a magic character wrapped in a character class can only be satisfied by
  15796. * that exact character. In this mode, `\` is _not_ escaped, because it is
  15797. * not interpreted as a magic character, but instead as a path separator.
  15798. */
  15799. const escape = (s, { windowsPathsNoEscape = false, } = {}) => {
  15800. // don't need to escape +@! because we escape the parens
  15801. // that make those magic, and escaping ! as [!] isn't valid,
  15802. // because [!]] is a valid glob class meaning not ']'.
  15803. return windowsPathsNoEscape
  15804. ? s.replace(/[?*()[\]]/g, '[$&]')
  15805. : s.replace(/[?*()[\]\\]/g, '\\$&');
  15806. };
  15807. const minimatch = (p, pattern, options = {}) => {
  15808. assertValidPattern(pattern);
  15809. // shortcut: comments match nothing.
  15810. if (!options.nocomment && pattern.charAt(0) === '#') {
  15811. return false;
  15812. }
  15813. return new Minimatch(pattern, options).match(p);
  15814. };
  15815. // Optimized checking for the most common glob patterns.
  15816. const starDotExtRE = /^\*+([^+@!?\*\[\(]*)$/;
  15817. const starDotExtTest = (ext) => (f) => !f.startsWith('.') && f.endsWith(ext);
  15818. const starDotExtTestDot = (ext) => (f) => f.endsWith(ext);
  15819. const starDotExtTestNocase = (ext) => {
  15820. ext = ext.toLowerCase();
  15821. return (f) => !f.startsWith('.') && f.toLowerCase().endsWith(ext);
  15822. };
  15823. const starDotExtTestNocaseDot = (ext) => {
  15824. ext = ext.toLowerCase();
  15825. return (f) => f.toLowerCase().endsWith(ext);
  15826. };
  15827. const starDotStarRE = /^\*+\.\*+$/;
  15828. const starDotStarTest = (f) => !f.startsWith('.') && f.includes('.');
  15829. const starDotStarTestDot = (f) => f !== '.' && f !== '..' && f.includes('.');
  15830. const dotStarRE = /^\.\*+$/;
  15831. const dotStarTest = (f) => f !== '.' && f !== '..' && f.startsWith('.');
  15832. const starRE = /^\*+$/;
  15833. const starTest = (f) => f.length !== 0 && !f.startsWith('.');
  15834. const starTestDot = (f) => f.length !== 0 && f !== '.' && f !== '..';
  15835. const qmarksRE = /^\?+([^+@!?\*\[\(]*)?$/;
  15836. const qmarksTestNocase = ([$0, ext = '']) => {
  15837. const noext = qmarksTestNoExt([$0]);
  15838. if (!ext)
  15839. return noext;
  15840. ext = ext.toLowerCase();
  15841. return (f) => noext(f) && f.toLowerCase().endsWith(ext);
  15842. };
  15843. const qmarksTestNocaseDot = ([$0, ext = '']) => {
  15844. const noext = qmarksTestNoExtDot([$0]);
  15845. if (!ext)
  15846. return noext;
  15847. ext = ext.toLowerCase();
  15848. return (f) => noext(f) && f.toLowerCase().endsWith(ext);
  15849. };
  15850. const qmarksTestDot = ([$0, ext = '']) => {
  15851. const noext = qmarksTestNoExtDot([$0]);
  15852. return !ext ? noext : (f) => noext(f) && f.endsWith(ext);
  15853. };
  15854. const qmarksTest = ([$0, ext = '']) => {
  15855. const noext = qmarksTestNoExt([$0]);
  15856. return !ext ? noext : (f) => noext(f) && f.endsWith(ext);
  15857. };
  15858. const qmarksTestNoExt = ([$0]) => {
  15859. const len = $0.length;
  15860. return (f) => f.length === len && !f.startsWith('.');
  15861. };
  15862. const qmarksTestNoExtDot = ([$0]) => {
  15863. const len = $0.length;
  15864. return (f) => f.length === len && f !== '.' && f !== '..';
  15865. };
  15866. /* c8 ignore start */
  15867. const defaultPlatform = (typeof process === 'object' && process
  15868. ? (typeof process.env === 'object' &&
  15869. process.env &&
  15870. process.env.__MINIMATCH_TESTING_PLATFORM__) ||
  15871. process.platform
  15872. : 'posix');
  15873. const path = {
  15874. win32: { sep: '\\' },
  15875. posix: { sep: '/' },
  15876. };
  15877. /* c8 ignore stop */
  15878. const sep = defaultPlatform === 'win32' ? path.win32.sep : path.posix.sep;
  15879. minimatch.sep = sep;
  15880. const GLOBSTAR = Symbol('globstar **');
  15881. minimatch.GLOBSTAR = GLOBSTAR;
  15882. // any single thing other than /
  15883. // don't need to escape / when using new RegExp()
  15884. const qmark = '[^/]';
  15885. // * => any number of characters
  15886. const star = qmark + '*?';
  15887. // ** when dots are allowed. Anything goes, except .. and .
  15888. // not (^ or / followed by one or two dots followed by $ or /),
  15889. // followed by anything, any number of times.
  15890. const twoStarDot = '(?:(?!(?:\\/|^)(?:\\.{1,2})($|\\/)).)*?';
  15891. // not a ^ or / followed by a dot,
  15892. // followed by anything, any number of times.
  15893. const twoStarNoDot = '(?:(?!(?:\\/|^)\\.).)*?';
  15894. const filter = (pattern, options = {}) => (p) => minimatch(p, pattern, options);
  15895. minimatch.filter = filter;
  15896. const ext = (a, b = {}) => Object.assign({}, a, b);
  15897. const defaults = (def) => {
  15898. if (!def || typeof def !== 'object' || !Object.keys(def).length) {
  15899. return minimatch;
  15900. }
  15901. const orig = minimatch;
  15902. const m = (p, pattern, options = {}) => orig(p, pattern, ext(def, options));
  15903. return Object.assign(m, {
  15904. Minimatch: class Minimatch extends orig.Minimatch {
  15905. constructor(pattern, options = {}) {
  15906. super(pattern, ext(def, options));
  15907. }
  15908. static defaults(options) {
  15909. return orig.defaults(ext(def, options)).Minimatch;
  15910. }
  15911. },
  15912. AST: class AST extends orig.AST {
  15913. /* c8 ignore start */
  15914. constructor(type, parent, options = {}) {
  15915. super(type, parent, ext(def, options));
  15916. }
  15917. /* c8 ignore stop */
  15918. static fromGlob(pattern, options = {}) {
  15919. return orig.AST.fromGlob(pattern, ext(def, options));
  15920. }
  15921. },
  15922. unescape: (s, options = {}) => orig.unescape(s, ext(def, options)),
  15923. escape: (s, options = {}) => orig.escape(s, ext(def, options)),
  15924. filter: (pattern, options = {}) => orig.filter(pattern, ext(def, options)),
  15925. defaults: (options) => orig.defaults(ext(def, options)),
  15926. makeRe: (pattern, options = {}) => orig.makeRe(pattern, ext(def, options)),
  15927. braceExpand: (pattern, options = {}) => orig.braceExpand(pattern, ext(def, options)),
  15928. match: (list, pattern, options = {}) => orig.match(list, pattern, ext(def, options)),
  15929. sep: orig.sep,
  15930. GLOBSTAR: GLOBSTAR,
  15931. });
  15932. };
  15933. minimatch.defaults = defaults;
  15934. // Brace expansion:
  15935. // a{b,c}d -> abd acd
  15936. // a{b,}c -> abc ac
  15937. // a{0..3}d -> a0d a1d a2d a3d
  15938. // a{b,c{d,e}f}g -> abg acdfg acefg
  15939. // a{b,c}d{e,f}g -> abdeg acdeg abdeg abdfg
  15940. //
  15941. // Invalid sets are not expanded.
  15942. // a{2..}b -> a{2..}b
  15943. // a{b}c -> a{b}c
  15944. const braceExpand = (pattern, options = {}) => {
  15945. assertValidPattern(pattern);
  15946. // Thanks to Yeting Li <https://github.com/yetingli> for
  15947. // improving this regexp to avoid a ReDOS vulnerability.
  15948. if (options.nobrace || !/\{(?:(?!\{).)*\}/.test(pattern)) {
  15949. // shortcut. no need to expand.
  15950. return [pattern];
  15951. }
  15952. return expand(pattern);
  15953. };
  15954. minimatch.braceExpand = braceExpand;
  15955. // parse a component of the expanded set.
  15956. // At this point, no pattern may contain "/" in it
  15957. // so we're going to return a 2d array, where each entry is the full
  15958. // pattern, split on '/', and then turned into a regular expression.
  15959. // A regexp is made at the end which joins each array with an
  15960. // escaped /, and another full one which joins each regexp with |.
  15961. //
  15962. // Following the lead of Bash 4.1, note that "**" only has special meaning
  15963. // when it is the *only* thing in a path portion. Otherwise, any series
  15964. // of * is equivalent to a single *. Globstar behavior is enabled by
  15965. // default, and can be disabled by setting options.noglobstar.
  15966. const makeRe = (pattern, options = {}) => new Minimatch(pattern, options).makeRe();
  15967. minimatch.makeRe = makeRe;
  15968. const match = (list, pattern, options = {}) => {
  15969. const mm = new Minimatch(pattern, options);
  15970. list = list.filter(f => mm.match(f));
  15971. if (mm.options.nonull && !list.length) {
  15972. list.push(pattern);
  15973. }
  15974. return list;
  15975. };
  15976. minimatch.match = match;
  15977. // replace stuff like \* with *
  15978. const globMagic = /[?*]|[+@!]\(.*?\)|\[|\]/;
  15979. const regExpEscape = (s) => s.replace(/[-[\]{}()*+?.,\\^$|#\s]/g, '\\$&');
  15980. class Minimatch {
  15981. options;
  15982. set;
  15983. pattern;
  15984. windowsPathsNoEscape;
  15985. nonegate;
  15986. negate;
  15987. comment;
  15988. empty;
  15989. preserveMultipleSlashes;
  15990. partial;
  15991. globSet;
  15992. globParts;
  15993. nocase;
  15994. isWindows;
  15995. platform;
  15996. windowsNoMagicRoot;
  15997. regexp;
  15998. constructor(pattern, options = {}) {
  15999. assertValidPattern(pattern);
  16000. options = options || {};
  16001. this.options = options;
  16002. this.pattern = pattern;
  16003. this.platform = options.platform || defaultPlatform;
  16004. this.isWindows = this.platform === 'win32';
  16005. this.windowsPathsNoEscape =
  16006. !!options.windowsPathsNoEscape || options.allowWindowsEscape === false;
  16007. if (this.windowsPathsNoEscape) {
  16008. this.pattern = this.pattern.replace(/\\/g, '/');
  16009. }
  16010. this.preserveMultipleSlashes = !!options.preserveMultipleSlashes;
  16011. this.regexp = null;
  16012. this.negate = false;
  16013. this.nonegate = !!options.nonegate;
  16014. this.comment = false;
  16015. this.empty = false;
  16016. this.partial = !!options.partial;
  16017. this.nocase = !!this.options.nocase;
  16018. this.windowsNoMagicRoot =
  16019. options.windowsNoMagicRoot !== undefined
  16020. ? options.windowsNoMagicRoot
  16021. : !!(this.isWindows && this.nocase);
  16022. this.globSet = [];
  16023. this.globParts = [];
  16024. this.set = [];
  16025. // make the set of regexps etc.
  16026. this.make();
  16027. }
  16028. hasMagic() {
  16029. if (this.options.magicalBraces && this.set.length > 1) {
  16030. return true;
  16031. }
  16032. for (const pattern of this.set) {
  16033. for (const part of pattern) {
  16034. if (typeof part !== 'string')
  16035. return true;
  16036. }
  16037. }
  16038. return false;
  16039. }
  16040. debug(..._) { }
  16041. make() {
  16042. const pattern = this.pattern;
  16043. const options = this.options;
  16044. // empty patterns and comments match nothing.
  16045. if (!options.nocomment && pattern.charAt(0) === '#') {
  16046. this.comment = true;
  16047. return;
  16048. }
  16049. if (!pattern) {
  16050. this.empty = true;
  16051. return;
  16052. }
  16053. // step 1: figure out negation, etc.
  16054. this.parseNegate();
  16055. // step 2: expand braces
  16056. this.globSet = [...new Set(this.braceExpand())];
  16057. if (options.debug) {
  16058. this.debug = (...args) => console.error(...args);
  16059. }
  16060. this.debug(this.pattern, this.globSet);
  16061. // step 3: now we have a set, so turn each one into a series of
  16062. // path-portion matching patterns.
  16063. // These will be regexps, except in the case of "**", which is
  16064. // set to the GLOBSTAR object for globstar behavior,
  16065. // and will not contain any / characters
  16066. //
  16067. // First, we preprocess to make the glob pattern sets a bit simpler
  16068. // and deduped. There are some perf-killing patterns that can cause
  16069. // problems with a glob walk, but we can simplify them down a bit.
  16070. const rawGlobParts = this.globSet.map(s => this.slashSplit(s));
  16071. this.globParts = this.preprocess(rawGlobParts);
  16072. this.debug(this.pattern, this.globParts);
  16073. // glob --> regexps
  16074. let set = this.globParts.map((s, _, __) => {
  16075. if (this.isWindows && this.windowsNoMagicRoot) {
  16076. // check if it's a drive or unc path.
  16077. const isUNC = s[0] === '' &&
  16078. s[1] === '' &&
  16079. (s[2] === '?' || !globMagic.test(s[2])) &&
  16080. !globMagic.test(s[3]);
  16081. const isDrive = /^[a-z]:/i.test(s[0]);
  16082. if (isUNC) {
  16083. return [...s.slice(0, 4), ...s.slice(4).map(ss => this.parse(ss))];
  16084. }
  16085. else if (isDrive) {
  16086. return [s[0], ...s.slice(1).map(ss => this.parse(ss))];
  16087. }
  16088. }
  16089. return s.map(ss => this.parse(ss));
  16090. });
  16091. this.debug(this.pattern, set);
  16092. // filter out everything that didn't compile properly.
  16093. this.set = set.filter(s => s.indexOf(false) === -1);
  16094. // do not treat the ? in UNC paths as magic
  16095. if (this.isWindows) {
  16096. for (let i = 0; i < this.set.length; i++) {
  16097. const p = this.set[i];
  16098. if (p[0] === '' &&
  16099. p[1] === '' &&
  16100. this.globParts[i][2] === '?' &&
  16101. typeof p[3] === 'string' &&
  16102. /^[a-z]:$/i.test(p[3])) {
  16103. p[2] = '?';
  16104. }
  16105. }
  16106. }
  16107. this.debug(this.pattern, this.set);
  16108. }
  16109. // various transforms to equivalent pattern sets that are
  16110. // faster to process in a filesystem walk. The goal is to
  16111. // eliminate what we can, and push all ** patterns as far
  16112. // to the right as possible, even if it increases the number
  16113. // of patterns that we have to process.
  16114. preprocess(globParts) {
  16115. // if we're not in globstar mode, then turn all ** into *
  16116. if (this.options.noglobstar) {
  16117. for (let i = 0; i < globParts.length; i++) {
  16118. for (let j = 0; j < globParts[i].length; j++) {
  16119. if (globParts[i][j] === '**') {
  16120. globParts[i][j] = '*';
  16121. }
  16122. }
  16123. }
  16124. }
  16125. const { optimizationLevel = 1 } = this.options;
  16126. if (optimizationLevel >= 2) {
  16127. // aggressive optimization for the purpose of fs walking
  16128. globParts = this.firstPhasePreProcess(globParts);
  16129. globParts = this.secondPhasePreProcess(globParts);
  16130. }
  16131. else if (optimizationLevel >= 1) {
  16132. // just basic optimizations to remove some .. parts
  16133. globParts = this.levelOneOptimize(globParts);
  16134. }
  16135. else {
  16136. // just collapse multiple ** portions into one
  16137. globParts = this.adjascentGlobstarOptimize(globParts);
  16138. }
  16139. return globParts;
  16140. }
  16141. // just get rid of adjascent ** portions
  16142. adjascentGlobstarOptimize(globParts) {
  16143. return globParts.map(parts => {
  16144. let gs = -1;
  16145. while (-1 !== (gs = parts.indexOf('**', gs + 1))) {
  16146. let i = gs;
  16147. while (parts[i + 1] === '**') {
  16148. i++;
  16149. }
  16150. if (i !== gs) {
  16151. parts.splice(gs, i - gs);
  16152. }
  16153. }
  16154. return parts;
  16155. });
  16156. }
  16157. // get rid of adjascent ** and resolve .. portions
  16158. levelOneOptimize(globParts) {
  16159. return globParts.map(parts => {
  16160. parts = parts.reduce((set, part) => {
  16161. const prev = set[set.length - 1];
  16162. if (part === '**' && prev === '**') {
  16163. return set;
  16164. }
  16165. if (part === '..') {
  16166. if (prev && prev !== '..' && prev !== '.' && prev !== '**') {
  16167. set.pop();
  16168. return set;
  16169. }
  16170. }
  16171. set.push(part);
  16172. return set;
  16173. }, []);
  16174. return parts.length === 0 ? [''] : parts;
  16175. });
  16176. }
  16177. levelTwoFileOptimize(parts) {
  16178. if (!Array.isArray(parts)) {
  16179. parts = this.slashSplit(parts);
  16180. }
  16181. let didSomething = false;
  16182. do {
  16183. didSomething = false;
  16184. // <pre>/<e>/<rest> -> <pre>/<rest>
  16185. if (!this.preserveMultipleSlashes) {
  16186. for (let i = 1; i < parts.length - 1; i++) {
  16187. const p = parts[i];
  16188. // don't squeeze out UNC patterns
  16189. if (i === 1 && p === '' && parts[0] === '')
  16190. continue;
  16191. if (p === '.' || p === '') {
  16192. didSomething = true;
  16193. parts.splice(i, 1);
  16194. i--;
  16195. }
  16196. }
  16197. if (parts[0] === '.' &&
  16198. parts.length === 2 &&
  16199. (parts[1] === '.' || parts[1] === '')) {
  16200. didSomething = true;
  16201. parts.pop();
  16202. }
  16203. }
  16204. // <pre>/<p>/../<rest> -> <pre>/<rest>
  16205. let dd = 0;
  16206. while (-1 !== (dd = parts.indexOf('..', dd + 1))) {
  16207. const p = parts[dd - 1];
  16208. if (p && p !== '.' && p !== '..' && p !== '**') {
  16209. didSomething = true;
  16210. parts.splice(dd - 1, 2);
  16211. dd -= 2;
  16212. }
  16213. }
  16214. } while (didSomething);
  16215. return parts.length === 0 ? [''] : parts;
  16216. }
  16217. // First phase: single-pattern processing
  16218. // <pre> is 1 or more portions
  16219. // <rest> is 1 or more portions
  16220. // <p> is any portion other than ., .., '', or **
  16221. // <e> is . or ''
  16222. //
  16223. // **/.. is *brutal* for filesystem walking performance, because
  16224. // it effectively resets the recursive walk each time it occurs,
  16225. // and ** cannot be reduced out by a .. pattern part like a regexp
  16226. // or most strings (other than .., ., and '') can be.
  16227. //
  16228. // <pre>/**/../<p>/<p>/<rest> -> {<pre>/../<p>/<p>/<rest>,<pre>/**/<p>/<p>/<rest>}
  16229. // <pre>/<e>/<rest> -> <pre>/<rest>
  16230. // <pre>/<p>/../<rest> -> <pre>/<rest>
  16231. // **/**/<rest> -> **/<rest>
  16232. //
  16233. // **/*/<rest> -> */**/<rest> <== not valid because ** doesn't follow
  16234. // this WOULD be allowed if ** did follow symlinks, or * didn't
  16235. firstPhasePreProcess(globParts) {
  16236. let didSomething = false;
  16237. do {
  16238. didSomething = false;
  16239. // <pre>/**/../<p>/<p>/<rest> -> {<pre>/../<p>/<p>/<rest>,<pre>/**/<p>/<p>/<rest>}
  16240. for (let parts of globParts) {
  16241. let gs = -1;
  16242. while (-1 !== (gs = parts.indexOf('**', gs + 1))) {
  16243. let gss = gs;
  16244. while (parts[gss + 1] === '**') {
  16245. // <pre>/**/**/<rest> -> <pre>/**/<rest>
  16246. gss++;
  16247. }
  16248. // eg, if gs is 2 and gss is 4, that means we have 3 **
  16249. // parts, and can remove 2 of them.
  16250. if (gss > gs) {
  16251. parts.splice(gs + 1, gss - gs);
  16252. }
  16253. let next = parts[gs + 1];
  16254. const p = parts[gs + 2];
  16255. const p2 = parts[gs + 3];
  16256. if (next !== '..')
  16257. continue;
  16258. if (!p ||
  16259. p === '.' ||
  16260. p === '..' ||
  16261. !p2 ||
  16262. p2 === '.' ||
  16263. p2 === '..') {
  16264. continue;
  16265. }
  16266. didSomething = true;
  16267. // edit parts in place, and push the new one
  16268. parts.splice(gs, 1);
  16269. const other = parts.slice(0);
  16270. other[gs] = '**';
  16271. globParts.push(other);
  16272. gs--;
  16273. }
  16274. // <pre>/<e>/<rest> -> <pre>/<rest>
  16275. if (!this.preserveMultipleSlashes) {
  16276. for (let i = 1; i < parts.length - 1; i++) {
  16277. const p = parts[i];
  16278. // don't squeeze out UNC patterns
  16279. if (i === 1 && p === '' && parts[0] === '')
  16280. continue;
  16281. if (p === '.' || p === '') {
  16282. didSomething = true;
  16283. parts.splice(i, 1);
  16284. i--;
  16285. }
  16286. }
  16287. if (parts[0] === '.' &&
  16288. parts.length === 2 &&
  16289. (parts[1] === '.' || parts[1] === '')) {
  16290. didSomething = true;
  16291. parts.pop();
  16292. }
  16293. }
  16294. // <pre>/<p>/../<rest> -> <pre>/<rest>
  16295. let dd = 0;
  16296. while (-1 !== (dd = parts.indexOf('..', dd + 1))) {
  16297. const p = parts[dd - 1];
  16298. if (p && p !== '.' && p !== '..' && p !== '**') {
  16299. didSomething = true;
  16300. const needDot = dd === 1 && parts[dd + 1] === '**';
  16301. const splin = needDot ? ['.'] : [];
  16302. parts.splice(dd - 1, 2, ...splin);
  16303. if (parts.length === 0)
  16304. parts.push('');
  16305. dd -= 2;
  16306. }
  16307. }
  16308. }
  16309. } while (didSomething);
  16310. return globParts;
  16311. }
  16312. // second phase: multi-pattern dedupes
  16313. // {<pre>/*/<rest>,<pre>/<p>/<rest>} -> <pre>/*/<rest>
  16314. // {<pre>/<rest>,<pre>/<rest>} -> <pre>/<rest>
  16315. // {<pre>/**/<rest>,<pre>/<rest>} -> <pre>/**/<rest>
  16316. //
  16317. // {<pre>/**/<rest>,<pre>/**/<p>/<rest>} -> <pre>/**/<rest>
  16318. // ^-- not valid because ** doens't follow symlinks
  16319. secondPhasePreProcess(globParts) {
  16320. for (let i = 0; i < globParts.length - 1; i++) {
  16321. for (let j = i + 1; j < globParts.length; j++) {
  16322. const matched = this.partsMatch(globParts[i], globParts[j], !this.preserveMultipleSlashes);
  16323. if (matched) {
  16324. globParts[i] = [];
  16325. globParts[j] = matched;
  16326. break;
  16327. }
  16328. }
  16329. }
  16330. return globParts.filter(gs => gs.length);
  16331. }
  16332. partsMatch(a, b, emptyGSMatch = false) {
  16333. let ai = 0;
  16334. let bi = 0;
  16335. let result = [];
  16336. let which = '';
  16337. while (ai < a.length && bi < b.length) {
  16338. if (a[ai] === b[bi]) {
  16339. result.push(which === 'b' ? b[bi] : a[ai]);
  16340. ai++;
  16341. bi++;
  16342. }
  16343. else if (emptyGSMatch && a[ai] === '**' && b[bi] === a[ai + 1]) {
  16344. result.push(a[ai]);
  16345. ai++;
  16346. }
  16347. else if (emptyGSMatch && b[bi] === '**' && a[ai] === b[bi + 1]) {
  16348. result.push(b[bi]);
  16349. bi++;
  16350. }
  16351. else if (a[ai] === '*' &&
  16352. b[bi] &&
  16353. (this.options.dot || !b[bi].startsWith('.')) &&
  16354. b[bi] !== '**') {
  16355. if (which === 'b')
  16356. return false;
  16357. which = 'a';
  16358. result.push(a[ai]);
  16359. ai++;
  16360. bi++;
  16361. }
  16362. else if (b[bi] === '*' &&
  16363. a[ai] &&
  16364. (this.options.dot || !a[ai].startsWith('.')) &&
  16365. a[ai] !== '**') {
  16366. if (which === 'a')
  16367. return false;
  16368. which = 'b';
  16369. result.push(b[bi]);
  16370. ai++;
  16371. bi++;
  16372. }
  16373. else {
  16374. return false;
  16375. }
  16376. }
  16377. // if we fall out of the loop, it means they two are identical
  16378. // as long as their lengths match
  16379. return a.length === b.length && result;
  16380. }
  16381. parseNegate() {
  16382. if (this.nonegate)
  16383. return;
  16384. const pattern = this.pattern;
  16385. let negate = false;
  16386. let negateOffset = 0;
  16387. for (let i = 0; i < pattern.length && pattern.charAt(i) === '!'; i++) {
  16388. negate = !negate;
  16389. negateOffset++;
  16390. }
  16391. if (negateOffset)
  16392. this.pattern = pattern.slice(negateOffset);
  16393. this.negate = negate;
  16394. }
  16395. // set partial to true to test if, for example,
  16396. // "/a/b" matches the start of "/*/b/*/d"
  16397. // Partial means, if you run out of file before you run
  16398. // out of pattern, then that's fine, as long as all
  16399. // the parts match.
  16400. matchOne(file, pattern, partial = false) {
  16401. const options = this.options;
  16402. // UNC paths like //?/X:/... can match X:/... and vice versa
  16403. // Drive letters in absolute drive or unc paths are always compared
  16404. // case-insensitively.
  16405. if (this.isWindows) {
  16406. const fileDrive = typeof file[0] === 'string' && /^[a-z]:$/i.test(file[0]);
  16407. const fileUNC = !fileDrive &&
  16408. file[0] === '' &&
  16409. file[1] === '' &&
  16410. file[2] === '?' &&
  16411. /^[a-z]:$/i.test(file[3]);
  16412. const patternDrive = typeof pattern[0] === 'string' && /^[a-z]:$/i.test(pattern[0]);
  16413. const patternUNC = !patternDrive &&
  16414. pattern[0] === '' &&
  16415. pattern[1] === '' &&
  16416. pattern[2] === '?' &&
  16417. typeof pattern[3] === 'string' &&
  16418. /^[a-z]:$/i.test(pattern[3]);
  16419. const fdi = fileUNC ? 3 : fileDrive ? 0 : undefined;
  16420. const pdi = patternUNC ? 3 : patternDrive ? 0 : undefined;
  16421. if (typeof fdi === 'number' && typeof pdi === 'number') {
  16422. const [fd, pd] = [file[fdi], pattern[pdi]];
  16423. if (fd.toLowerCase() === pd.toLowerCase()) {
  16424. pattern[pdi] = fd;
  16425. if (pdi > fdi) {
  16426. pattern = pattern.slice(pdi);
  16427. }
  16428. else if (fdi > pdi) {
  16429. file = file.slice(fdi);
  16430. }
  16431. }
  16432. }
  16433. }
  16434. // resolve and reduce . and .. portions in the file as well.
  16435. // dont' need to do the second phase, because it's only one string[]
  16436. const { optimizationLevel = 1 } = this.options;
  16437. if (optimizationLevel >= 2) {
  16438. file = this.levelTwoFileOptimize(file);
  16439. }
  16440. this.debug('matchOne', this, { file, pattern });
  16441. this.debug('matchOne', file.length, pattern.length);
  16442. for (var fi = 0, pi = 0, fl = file.length, pl = pattern.length; fi < fl && pi < pl; fi++, pi++) {
  16443. this.debug('matchOne loop');
  16444. var p = pattern[pi];
  16445. var f = file[fi];
  16446. this.debug(pattern, p, f);
  16447. // should be impossible.
  16448. // some invalid regexp stuff in the set.
  16449. /* c8 ignore start */
  16450. if (p === false) {
  16451. return false;
  16452. }
  16453. /* c8 ignore stop */
  16454. if (p === GLOBSTAR) {
  16455. this.debug('GLOBSTAR', [pattern, p, f]);
  16456. // "**"
  16457. // a/**/b/**/c would match the following:
  16458. // a/b/x/y/z/c
  16459. // a/x/y/z/b/c
  16460. // a/b/x/b/x/c
  16461. // a/b/c
  16462. // To do this, take the rest of the pattern after
  16463. // the **, and see if it would match the file remainder.
  16464. // If so, return success.
  16465. // If not, the ** "swallows" a segment, and try again.
  16466. // This is recursively awful.
  16467. //
  16468. // a/**/b/**/c matching a/b/x/y/z/c
  16469. // - a matches a
  16470. // - doublestar
  16471. // - matchOne(b/x/y/z/c, b/**/c)
  16472. // - b matches b
  16473. // - doublestar
  16474. // - matchOne(x/y/z/c, c) -> no
  16475. // - matchOne(y/z/c, c) -> no
  16476. // - matchOne(z/c, c) -> no
  16477. // - matchOne(c, c) yes, hit
  16478. var fr = fi;
  16479. var pr = pi + 1;
  16480. if (pr === pl) {
  16481. this.debug('** at the end');
  16482. // a ** at the end will just swallow the rest.
  16483. // We have found a match.
  16484. // however, it will not swallow /.x, unless
  16485. // options.dot is set.
  16486. // . and .. are *never* matched by **, for explosively
  16487. // exponential reasons.
  16488. for (; fi < fl; fi++) {
  16489. if (file[fi] === '.' ||
  16490. file[fi] === '..' ||
  16491. (!options.dot && file[fi].charAt(0) === '.'))
  16492. return false;
  16493. }
  16494. return true;
  16495. }
  16496. // ok, let's see if we can swallow whatever we can.
  16497. while (fr < fl) {
  16498. var swallowee = file[fr];
  16499. this.debug('\nglobstar while', file, fr, pattern, pr, swallowee);
  16500. // XXX remove this slice. Just pass the start index.
  16501. if (this.matchOne(file.slice(fr), pattern.slice(pr), partial)) {
  16502. this.debug('globstar found match!', fr, fl, swallowee);
  16503. // found a match.
  16504. return true;
  16505. }
  16506. else {
  16507. // can't swallow "." or ".." ever.
  16508. // can only swallow ".foo" when explicitly asked.
  16509. if (swallowee === '.' ||
  16510. swallowee === '..' ||
  16511. (!options.dot && swallowee.charAt(0) === '.')) {
  16512. this.debug('dot detected!', file, fr, pattern, pr);
  16513. break;
  16514. }
  16515. // ** swallows a segment, and continue.
  16516. this.debug('globstar swallow a segment, and continue');
  16517. fr++;
  16518. }
  16519. }
  16520. // no match was found.
  16521. // However, in partial mode, we can't say this is necessarily over.
  16522. /* c8 ignore start */
  16523. if (partial) {
  16524. // ran out of file
  16525. this.debug('\n>>> no match, partial?', file, fr, pattern, pr);
  16526. if (fr === fl) {
  16527. return true;
  16528. }
  16529. }
  16530. /* c8 ignore stop */
  16531. return false;
  16532. }
  16533. // something other than **
  16534. // non-magic patterns just have to match exactly
  16535. // patterns with magic have been turned into regexps.
  16536. let hit;
  16537. if (typeof p === 'string') {
  16538. hit = f === p;
  16539. this.debug('string match', p, f, hit);
  16540. }
  16541. else {
  16542. hit = p.test(f);
  16543. this.debug('pattern match', p, f, hit);
  16544. }
  16545. if (!hit)
  16546. return false;
  16547. }
  16548. // Note: ending in / means that we'll get a final ""
  16549. // at the end of the pattern. This can only match a
  16550. // corresponding "" at the end of the file.
  16551. // If the file ends in /, then it can only match a
  16552. // a pattern that ends in /, unless the pattern just
  16553. // doesn't have any more for it. But, a/b/ should *not*
  16554. // match "a/b/*", even though "" matches against the
  16555. // [^/]*? pattern, except in partial mode, where it might
  16556. // simply not be reached yet.
  16557. // However, a/b/ should still satisfy a/*
  16558. // now either we fell off the end of the pattern, or we're done.
  16559. if (fi === fl && pi === pl) {
  16560. // ran out of pattern and filename at the same time.
  16561. // an exact hit!
  16562. return true;
  16563. }
  16564. else if (fi === fl) {
  16565. // ran out of file, but still had pattern left.
  16566. // this is ok if we're doing the match as part of
  16567. // a glob fs traversal.
  16568. return partial;
  16569. }
  16570. else if (pi === pl) {
  16571. // ran out of pattern, still have file left.
  16572. // this is only acceptable if we're on the very last
  16573. // empty segment of a file with a trailing slash.
  16574. // a/* should match a/b/
  16575. return fi === fl - 1 && file[fi] === '';
  16576. /* c8 ignore start */
  16577. }
  16578. else {
  16579. // should be unreachable.
  16580. throw new Error('wtf?');
  16581. }
  16582. /* c8 ignore stop */
  16583. }
  16584. braceExpand() {
  16585. return braceExpand(this.pattern, this.options);
  16586. }
  16587. parse(pattern) {
  16588. assertValidPattern(pattern);
  16589. const options = this.options;
  16590. // shortcuts
  16591. if (pattern === '**')
  16592. return GLOBSTAR;
  16593. if (pattern === '')
  16594. return '';
  16595. // far and away, the most common glob pattern parts are
  16596. // *, *.*, and *.<ext> Add a fast check method for those.
  16597. let m;
  16598. let fastTest = null;
  16599. if ((m = pattern.match(starRE))) {
  16600. fastTest = options.dot ? starTestDot : starTest;
  16601. }
  16602. else if ((m = pattern.match(starDotExtRE))) {
  16603. fastTest = (options.nocase
  16604. ? options.dot
  16605. ? starDotExtTestNocaseDot
  16606. : starDotExtTestNocase
  16607. : options.dot
  16608. ? starDotExtTestDot
  16609. : starDotExtTest)(m[1]);
  16610. }
  16611. else if ((m = pattern.match(qmarksRE))) {
  16612. fastTest = (options.nocase
  16613. ? options.dot
  16614. ? qmarksTestNocaseDot
  16615. : qmarksTestNocase
  16616. : options.dot
  16617. ? qmarksTestDot
  16618. : qmarksTest)(m);
  16619. }
  16620. else if ((m = pattern.match(starDotStarRE))) {
  16621. fastTest = options.dot ? starDotStarTestDot : starDotStarTest;
  16622. }
  16623. else if ((m = pattern.match(dotStarRE))) {
  16624. fastTest = dotStarTest;
  16625. }
  16626. const re = AST.fromGlob(pattern, this.options).toMMPattern();
  16627. if (fastTest && typeof re === 'object') {
  16628. // Avoids overriding in frozen environments
  16629. Reflect.defineProperty(re, 'test', { value: fastTest });
  16630. }
  16631. return re;
  16632. }
  16633. makeRe() {
  16634. if (this.regexp || this.regexp === false)
  16635. return this.regexp;
  16636. // at this point, this.set is a 2d array of partial
  16637. // pattern strings, or "**".
  16638. //
  16639. // It's better to use .match(). This function shouldn't
  16640. // be used, really, but it's pretty convenient sometimes,
  16641. // when you just want to work with a regex.
  16642. const set = this.set;
  16643. if (!set.length) {
  16644. this.regexp = false;
  16645. return this.regexp;
  16646. }
  16647. const options = this.options;
  16648. const twoStar = options.noglobstar
  16649. ? star
  16650. : options.dot
  16651. ? twoStarDot
  16652. : twoStarNoDot;
  16653. const flags = new Set(options.nocase ? ['i'] : []);
  16654. // regexpify non-globstar patterns
  16655. // if ** is only item, then we just do one twoStar
  16656. // if ** is first, and there are more, prepend (\/|twoStar\/)? to next
  16657. // if ** is last, append (\/twoStar|) to previous
  16658. // if ** is in the middle, append (\/|\/twoStar\/) to previous
  16659. // then filter out GLOBSTAR symbols
  16660. let re = set
  16661. .map(pattern => {
  16662. const pp = pattern.map(p => {
  16663. if (p instanceof RegExp) {
  16664. for (const f of p.flags.split(''))
  16665. flags.add(f);
  16666. }
  16667. return typeof p === 'string'
  16668. ? regExpEscape(p)
  16669. : p === GLOBSTAR
  16670. ? GLOBSTAR
  16671. : p._src;
  16672. });
  16673. pp.forEach((p, i) => {
  16674. const next = pp[i + 1];
  16675. const prev = pp[i - 1];
  16676. if (p !== GLOBSTAR || prev === GLOBSTAR) {
  16677. return;
  16678. }
  16679. if (prev === undefined) {
  16680. if (next !== undefined && next !== GLOBSTAR) {
  16681. pp[i + 1] = '(?:\\/|' + twoStar + '\\/)?' + next;
  16682. }
  16683. else {
  16684. pp[i] = twoStar;
  16685. }
  16686. }
  16687. else if (next === undefined) {
  16688. pp[i - 1] = prev + '(?:\\/|' + twoStar + ')?';
  16689. }
  16690. else if (next !== GLOBSTAR) {
  16691. pp[i - 1] = prev + '(?:\\/|\\/' + twoStar + '\\/)' + next;
  16692. pp[i + 1] = GLOBSTAR;
  16693. }
  16694. });
  16695. return pp.filter(p => p !== GLOBSTAR).join('/');
  16696. })
  16697. .join('|');
  16698. // need to wrap in parens if we had more than one thing with |,
  16699. // otherwise only the first will be anchored to ^ and the last to $
  16700. const [open, close] = set.length > 1 ? ['(?:', ')'] : ['', ''];
  16701. // must match entire pattern
  16702. // ending in a * or ** will make it less strict.
  16703. re = '^' + open + re + close + '$';
  16704. // can match anything, as long as it's not this.
  16705. if (this.negate)
  16706. re = '^(?!' + re + ').+$';
  16707. try {
  16708. this.regexp = new RegExp(re, [...flags].join(''));
  16709. /* c8 ignore start */
  16710. }
  16711. catch (ex) {
  16712. // should be impossible
  16713. this.regexp = false;
  16714. }
  16715. /* c8 ignore stop */
  16716. return this.regexp;
  16717. }
  16718. slashSplit(p) {
  16719. // if p starts with // on windows, we preserve that
  16720. // so that UNC paths aren't broken. Otherwise, any number of
  16721. // / characters are coalesced into one, unless
  16722. // preserveMultipleSlashes is set to true.
  16723. if (this.preserveMultipleSlashes) {
  16724. return p.split('/');
  16725. }
  16726. else if (this.isWindows && /^\/\/[^\/]+/.test(p)) {
  16727. // add an extra '' for the one we lose
  16728. return ['', ...p.split(/\/+/)];
  16729. }
  16730. else {
  16731. return p.split(/\/+/);
  16732. }
  16733. }
  16734. match(f, partial = this.partial) {
  16735. this.debug('match', f, this.pattern);
  16736. // short-circuit in the case of busted things.
  16737. // comments, etc.
  16738. if (this.comment) {
  16739. return false;
  16740. }
  16741. if (this.empty) {
  16742. return f === '';
  16743. }
  16744. if (f === '/' && partial) {
  16745. return true;
  16746. }
  16747. const options = this.options;
  16748. // windows: need to use /, not \
  16749. if (this.isWindows) {
  16750. f = f.split('\\').join('/');
  16751. }
  16752. // treat the test path as a set of pathparts.
  16753. const ff = this.slashSplit(f);
  16754. this.debug(this.pattern, 'split', ff);
  16755. // just ONE of the pattern sets in this.set needs to match
  16756. // in order for it to be valid. If negating, then just one
  16757. // match means that we have failed.
  16758. // Either way, return on the first hit.
  16759. const set = this.set;
  16760. this.debug(this.pattern, 'set', set);
  16761. // Find the basename of the path by looking for the last non-empty segment
  16762. let filename = ff[ff.length - 1];
  16763. if (!filename) {
  16764. for (let i = ff.length - 2; !filename && i >= 0; i--) {
  16765. filename = ff[i];
  16766. }
  16767. }
  16768. for (let i = 0; i < set.length; i++) {
  16769. const pattern = set[i];
  16770. let file = ff;
  16771. if (options.matchBase && pattern.length === 1) {
  16772. file = [filename];
  16773. }
  16774. const hit = this.matchOne(file, pattern, partial);
  16775. if (hit) {
  16776. if (options.flipNegate) {
  16777. return true;
  16778. }
  16779. return !this.negate;
  16780. }
  16781. }
  16782. // didn't get any hits. this is success if it's a negative
  16783. // pattern, failure otherwise.
  16784. if (options.flipNegate) {
  16785. return false;
  16786. }
  16787. return this.negate;
  16788. }
  16789. static defaults(def) {
  16790. return minimatch.defaults(def).Minimatch;
  16791. }
  16792. }
  16793. /* c8 ignore stop */
  16794. minimatch.AST = AST;
  16795. minimatch.Minimatch = Minimatch;
  16796. minimatch.escape = escape;
  16797. minimatch.unescape = unescape;
  16798. class TypeScope {
  16799. constructor(filename, source, offset = 0, imports = /* @__PURE__ */ Object.create(null), types = /* @__PURE__ */ Object.create(null), declares = /* @__PURE__ */ Object.create(null)) {
  16800. this.filename = filename;
  16801. this.source = source;
  16802. this.offset = offset;
  16803. this.imports = imports;
  16804. this.types = types;
  16805. this.declares = declares;
  16806. this.isGenericScope = false;
  16807. this.resolvedImportSources = /* @__PURE__ */ Object.create(null);
  16808. this.exportedTypes = /* @__PURE__ */ Object.create(null);
  16809. this.exportedDeclares = /* @__PURE__ */ Object.create(null);
  16810. }
  16811. }
  16812. function resolveTypeElements(ctx, node, scope, typeParameters) {
  16813. const canCache = !typeParameters;
  16814. if (canCache && node._resolvedElements) {
  16815. return node._resolvedElements;
  16816. }
  16817. const resolved = innerResolveTypeElements(
  16818. ctx,
  16819. node,
  16820. node._ownerScope || scope || ctxToScope(ctx),
  16821. typeParameters
  16822. );
  16823. return canCache ? node._resolvedElements = resolved : resolved;
  16824. }
  16825. function innerResolveTypeElements(ctx, node, scope, typeParameters) {
  16826. var _a, _b;
  16827. if (node.leadingComments && node.leadingComments.some((c) => c.value.includes("@vue-ignore"))) {
  16828. return { props: {} };
  16829. }
  16830. switch (node.type) {
  16831. case "TSTypeLiteral":
  16832. return typeElementsToMap(ctx, node.members, scope, typeParameters);
  16833. case "TSInterfaceDeclaration":
  16834. return resolveInterfaceMembers(ctx, node, scope, typeParameters);
  16835. case "TSTypeAliasDeclaration":
  16836. case "TSTypeAnnotation":
  16837. case "TSParenthesizedType":
  16838. return resolveTypeElements(
  16839. ctx,
  16840. node.typeAnnotation,
  16841. scope,
  16842. typeParameters
  16843. );
  16844. case "TSFunctionType": {
  16845. return { props: {}, calls: [node] };
  16846. }
  16847. case "TSUnionType":
  16848. case "TSIntersectionType":
  16849. return mergeElements(
  16850. node.types.map((t) => resolveTypeElements(ctx, t, scope, typeParameters)),
  16851. node.type
  16852. );
  16853. case "TSMappedType":
  16854. return resolveMappedType(ctx, node, scope, typeParameters);
  16855. case "TSIndexedAccessType": {
  16856. const types = resolveIndexType(ctx, node, scope);
  16857. return mergeElements(
  16858. types.map((t) => resolveTypeElements(ctx, t, t._ownerScope)),
  16859. "TSUnionType"
  16860. );
  16861. }
  16862. case "TSExpressionWithTypeArguments":
  16863. // referenced by interface extends
  16864. case "TSTypeReference": {
  16865. const typeName = getReferenceName(node);
  16866. if ((typeName === "ExtractPropTypes" || typeName === "ExtractPublicPropTypes") && node.typeParameters && ((_a = scope.imports[typeName]) == null ? void 0 : _a.source) === "vue") {
  16867. return resolveExtractPropTypes(
  16868. resolveTypeElements(
  16869. ctx,
  16870. node.typeParameters.params[0],
  16871. scope,
  16872. typeParameters
  16873. ),
  16874. scope
  16875. );
  16876. }
  16877. const resolved = resolveTypeReference(ctx, node, scope);
  16878. if (resolved) {
  16879. let typeParams;
  16880. if ((resolved.type === "TSTypeAliasDeclaration" || resolved.type === "TSInterfaceDeclaration") && resolved.typeParameters && node.typeParameters) {
  16881. typeParams = /* @__PURE__ */ Object.create(null);
  16882. resolved.typeParameters.params.forEach((p, i) => {
  16883. let param = typeParameters && typeParameters[p.name];
  16884. if (!param) param = node.typeParameters.params[i];
  16885. typeParams[p.name] = param;
  16886. });
  16887. }
  16888. return resolveTypeElements(
  16889. ctx,
  16890. resolved,
  16891. resolved._ownerScope,
  16892. typeParams
  16893. );
  16894. } else {
  16895. if (typeof typeName === "string") {
  16896. if (typeParameters && typeParameters[typeName]) {
  16897. return resolveTypeElements(
  16898. ctx,
  16899. typeParameters[typeName],
  16900. scope,
  16901. typeParameters
  16902. );
  16903. }
  16904. if (
  16905. // @ts-expect-error
  16906. SupportedBuiltinsSet.has(typeName)
  16907. ) {
  16908. return resolveBuiltin(
  16909. ctx,
  16910. node,
  16911. typeName,
  16912. scope,
  16913. typeParameters
  16914. );
  16915. } else if (typeName === "ReturnType" && node.typeParameters) {
  16916. const ret = resolveReturnType(
  16917. ctx,
  16918. node.typeParameters.params[0],
  16919. scope
  16920. );
  16921. if (ret) {
  16922. return resolveTypeElements(ctx, ret, scope);
  16923. }
  16924. }
  16925. }
  16926. return ctx.error(
  16927. `Unresolvable type reference or unsupported built-in utility type`,
  16928. node,
  16929. scope
  16930. );
  16931. }
  16932. }
  16933. case "TSImportType": {
  16934. if (getId(node.argument) === "vue" && ((_b = node.qualifier) == null ? void 0 : _b.type) === "Identifier" && node.qualifier.name === "ExtractPropTypes" && node.typeParameters) {
  16935. return resolveExtractPropTypes(
  16936. resolveTypeElements(ctx, node.typeParameters.params[0], scope),
  16937. scope
  16938. );
  16939. }
  16940. const sourceScope = importSourceToScope(
  16941. ctx,
  16942. node.argument,
  16943. scope,
  16944. node.argument.value
  16945. );
  16946. const resolved = resolveTypeReference(ctx, node, sourceScope);
  16947. if (resolved) {
  16948. return resolveTypeElements(ctx, resolved, resolved._ownerScope);
  16949. }
  16950. break;
  16951. }
  16952. case "TSTypeQuery":
  16953. {
  16954. const resolved = resolveTypeReference(ctx, node, scope);
  16955. if (resolved) {
  16956. return resolveTypeElements(ctx, resolved, resolved._ownerScope);
  16957. }
  16958. }
  16959. break;
  16960. }
  16961. return ctx.error(`Unresolvable type: ${node.type}`, node, scope);
  16962. }
  16963. function typeElementsToMap(ctx, elements, scope = ctxToScope(ctx), typeParameters) {
  16964. const res = { props: {} };
  16965. for (const e of elements) {
  16966. if (e.type === "TSPropertySignature" || e.type === "TSMethodSignature") {
  16967. if (typeParameters) {
  16968. scope = createChildScope(scope);
  16969. scope.isGenericScope = true;
  16970. Object.assign(scope.types, typeParameters);
  16971. }
  16972. e._ownerScope = scope;
  16973. const name = getId(e.key);
  16974. if (name && !e.computed) {
  16975. res.props[name] = e;
  16976. } else if (e.key.type === "TemplateLiteral") {
  16977. for (const key of resolveTemplateKeys(ctx, e.key, scope)) {
  16978. res.props[key] = e;
  16979. }
  16980. } else {
  16981. ctx.error(
  16982. `Unsupported computed key in type referenced by a macro`,
  16983. e.key,
  16984. scope
  16985. );
  16986. }
  16987. } else if (e.type === "TSCallSignatureDeclaration") {
  16988. (res.calls || (res.calls = [])).push(e);
  16989. }
  16990. }
  16991. return res;
  16992. }
  16993. function mergeElements(maps, type) {
  16994. if (maps.length === 1) return maps[0];
  16995. const res = { props: {} };
  16996. const { props: baseProps } = res;
  16997. for (const { props, calls } of maps) {
  16998. for (const key in props) {
  16999. if (!shared.hasOwn(baseProps, key)) {
  17000. baseProps[key] = props[key];
  17001. } else {
  17002. baseProps[key] = createProperty(
  17003. baseProps[key].key,
  17004. {
  17005. type,
  17006. // @ts-expect-error
  17007. types: [baseProps[key], props[key]]
  17008. },
  17009. baseProps[key]._ownerScope,
  17010. baseProps[key].optional || props[key].optional
  17011. );
  17012. }
  17013. }
  17014. if (calls) {
  17015. (res.calls || (res.calls = [])).push(...calls);
  17016. }
  17017. }
  17018. return res;
  17019. }
  17020. function createProperty(key, typeAnnotation, scope, optional) {
  17021. return {
  17022. type: "TSPropertySignature",
  17023. key,
  17024. kind: "get",
  17025. optional,
  17026. typeAnnotation: {
  17027. type: "TSTypeAnnotation",
  17028. typeAnnotation
  17029. },
  17030. _ownerScope: scope
  17031. };
  17032. }
  17033. function resolveInterfaceMembers(ctx, node, scope, typeParameters) {
  17034. const base = typeElementsToMap(
  17035. ctx,
  17036. node.body.body,
  17037. node._ownerScope,
  17038. typeParameters
  17039. );
  17040. if (node.extends) {
  17041. for (const ext of node.extends) {
  17042. try {
  17043. const { props, calls } = resolveTypeElements(ctx, ext, scope);
  17044. for (const key in props) {
  17045. if (!shared.hasOwn(base.props, key)) {
  17046. base.props[key] = props[key];
  17047. }
  17048. }
  17049. if (calls) {
  17050. ;
  17051. (base.calls || (base.calls = [])).push(...calls);
  17052. }
  17053. } catch (e) {
  17054. ctx.error(
  17055. `Failed to resolve extends base type.
  17056. If this previously worked in 3.2, you can instruct the compiler to ignore this extend by adding /* @vue-ignore */ before it, for example:
  17057. interface Props extends /* @vue-ignore */ Base {}
  17058. Note: both in 3.2 or with the ignore, the properties in the base type are treated as fallthrough attrs at runtime.`,
  17059. ext,
  17060. scope
  17061. );
  17062. }
  17063. }
  17064. }
  17065. return base;
  17066. }
  17067. function resolveMappedType(ctx, node, scope, typeParameters) {
  17068. const res = { props: {} };
  17069. let keys;
  17070. if (node.nameType) {
  17071. const { name, constraint } = node.typeParameter;
  17072. scope = createChildScope(scope);
  17073. Object.assign(scope.types, { ...typeParameters, [name]: constraint });
  17074. keys = resolveStringType(ctx, node.nameType, scope);
  17075. } else {
  17076. keys = resolveStringType(ctx, node.typeParameter.constraint, scope);
  17077. }
  17078. for (const key of keys) {
  17079. res.props[key] = createProperty(
  17080. {
  17081. type: "Identifier",
  17082. name: key
  17083. },
  17084. node.typeAnnotation,
  17085. scope,
  17086. !!node.optional
  17087. );
  17088. }
  17089. return res;
  17090. }
  17091. function resolveIndexType(ctx, node, scope) {
  17092. var _a, _b;
  17093. if (node.indexType.type === "TSNumberKeyword") {
  17094. return resolveArrayElementType(ctx, node.objectType, scope);
  17095. }
  17096. const { indexType, objectType } = node;
  17097. const types = [];
  17098. let keys;
  17099. let resolved;
  17100. if (indexType.type === "TSStringKeyword") {
  17101. resolved = resolveTypeElements(ctx, objectType, scope);
  17102. keys = Object.keys(resolved.props);
  17103. } else {
  17104. keys = resolveStringType(ctx, indexType, scope);
  17105. resolved = resolveTypeElements(ctx, objectType, scope);
  17106. }
  17107. for (const key of keys) {
  17108. const targetType = (_b = (_a = resolved.props[key]) == null ? void 0 : _a.typeAnnotation) == null ? void 0 : _b.typeAnnotation;
  17109. if (targetType) {
  17110. targetType._ownerScope = resolved.props[key]._ownerScope;
  17111. types.push(targetType);
  17112. }
  17113. }
  17114. return types;
  17115. }
  17116. function resolveArrayElementType(ctx, node, scope) {
  17117. if (node.type === "TSArrayType") {
  17118. return [node.elementType];
  17119. }
  17120. if (node.type === "TSTupleType") {
  17121. return node.elementTypes.map(
  17122. (t) => t.type === "TSNamedTupleMember" ? t.elementType : t
  17123. );
  17124. }
  17125. if (node.type === "TSTypeReference") {
  17126. if (getReferenceName(node) === "Array" && node.typeParameters) {
  17127. return node.typeParameters.params;
  17128. } else {
  17129. const resolved = resolveTypeReference(ctx, node, scope);
  17130. if (resolved) {
  17131. return resolveArrayElementType(ctx, resolved, scope);
  17132. }
  17133. }
  17134. }
  17135. return ctx.error(
  17136. "Failed to resolve element type from target type",
  17137. node,
  17138. scope
  17139. );
  17140. }
  17141. function resolveStringType(ctx, node, scope) {
  17142. switch (node.type) {
  17143. case "StringLiteral":
  17144. return [node.value];
  17145. case "TSLiteralType":
  17146. return resolveStringType(ctx, node.literal, scope);
  17147. case "TSUnionType":
  17148. return node.types.map((t) => resolveStringType(ctx, t, scope)).flat();
  17149. case "TemplateLiteral": {
  17150. return resolveTemplateKeys(ctx, node, scope);
  17151. }
  17152. case "TSTypeReference": {
  17153. const resolved = resolveTypeReference(ctx, node, scope);
  17154. if (resolved) {
  17155. return resolveStringType(ctx, resolved, scope);
  17156. }
  17157. if (node.typeName.type === "Identifier") {
  17158. const getParam = (index = 0) => resolveStringType(ctx, node.typeParameters.params[index], scope);
  17159. switch (node.typeName.name) {
  17160. case "Extract":
  17161. return getParam(1);
  17162. case "Exclude": {
  17163. const excluded = getParam(1);
  17164. return getParam().filter((s) => !excluded.includes(s));
  17165. }
  17166. case "Uppercase":
  17167. return getParam().map((s) => s.toUpperCase());
  17168. case "Lowercase":
  17169. return getParam().map((s) => s.toLowerCase());
  17170. case "Capitalize":
  17171. return getParam().map(shared.capitalize);
  17172. case "Uncapitalize":
  17173. return getParam().map((s) => s[0].toLowerCase() + s.slice(1));
  17174. default:
  17175. ctx.error(
  17176. "Unsupported type when resolving index type",
  17177. node.typeName,
  17178. scope
  17179. );
  17180. }
  17181. }
  17182. }
  17183. }
  17184. return ctx.error("Failed to resolve index type into finite keys", node, scope);
  17185. }
  17186. function resolveTemplateKeys(ctx, node, scope) {
  17187. if (!node.expressions.length) {
  17188. return [node.quasis[0].value.raw];
  17189. }
  17190. const res = [];
  17191. const e = node.expressions[0];
  17192. const q = node.quasis[0];
  17193. const leading = q ? q.value.raw : ``;
  17194. const resolved = resolveStringType(ctx, e, scope);
  17195. const restResolved = resolveTemplateKeys(
  17196. ctx,
  17197. {
  17198. ...node,
  17199. expressions: node.expressions.slice(1),
  17200. quasis: q ? node.quasis.slice(1) : node.quasis
  17201. },
  17202. scope
  17203. );
  17204. for (const r of resolved) {
  17205. for (const rr of restResolved) {
  17206. res.push(leading + r + rr);
  17207. }
  17208. }
  17209. return res;
  17210. }
  17211. const SupportedBuiltinsSet = /* @__PURE__ */ new Set([
  17212. "Partial",
  17213. "Required",
  17214. "Readonly",
  17215. "Pick",
  17216. "Omit"
  17217. ]);
  17218. function resolveBuiltin(ctx, node, name, scope, typeParameters) {
  17219. const t = resolveTypeElements(
  17220. ctx,
  17221. node.typeParameters.params[0],
  17222. scope,
  17223. typeParameters
  17224. );
  17225. switch (name) {
  17226. case "Partial": {
  17227. const res2 = { props: {}, calls: t.calls };
  17228. Object.keys(t.props).forEach((key) => {
  17229. res2.props[key] = { ...t.props[key], optional: true };
  17230. });
  17231. return res2;
  17232. }
  17233. case "Required": {
  17234. const res2 = { props: {}, calls: t.calls };
  17235. Object.keys(t.props).forEach((key) => {
  17236. res2.props[key] = { ...t.props[key], optional: false };
  17237. });
  17238. return res2;
  17239. }
  17240. case "Readonly":
  17241. return t;
  17242. case "Pick": {
  17243. const picked = resolveStringType(
  17244. ctx,
  17245. node.typeParameters.params[1],
  17246. scope
  17247. );
  17248. const res2 = { props: {}, calls: t.calls };
  17249. for (const key of picked) {
  17250. res2.props[key] = t.props[key];
  17251. }
  17252. return res2;
  17253. }
  17254. case "Omit":
  17255. const omitted = resolveStringType(
  17256. ctx,
  17257. node.typeParameters.params[1],
  17258. scope
  17259. );
  17260. const res = { props: {}, calls: t.calls };
  17261. for (const key in t.props) {
  17262. if (!omitted.includes(key)) {
  17263. res.props[key] = t.props[key];
  17264. }
  17265. }
  17266. return res;
  17267. }
  17268. }
  17269. function resolveTypeReference(ctx, node, scope, name, onlyExported = false) {
  17270. const canCache = !(scope == null ? void 0 : scope.isGenericScope);
  17271. if (canCache && node._resolvedReference) {
  17272. return node._resolvedReference;
  17273. }
  17274. const resolved = innerResolveTypeReference(
  17275. ctx,
  17276. scope || ctxToScope(ctx),
  17277. name || getReferenceName(node),
  17278. node,
  17279. onlyExported
  17280. );
  17281. return canCache ? node._resolvedReference = resolved : resolved;
  17282. }
  17283. function innerResolveTypeReference(ctx, scope, name, node, onlyExported) {
  17284. if (typeof name === "string") {
  17285. if (scope.imports[name]) {
  17286. return resolveTypeFromImport(ctx, node, name, scope);
  17287. } else {
  17288. const lookupSource = node.type === "TSTypeQuery" ? onlyExported ? scope.exportedDeclares : scope.declares : onlyExported ? scope.exportedTypes : scope.types;
  17289. if (lookupSource[name]) {
  17290. return lookupSource[name];
  17291. } else {
  17292. const globalScopes = resolveGlobalScope(ctx);
  17293. if (globalScopes) {
  17294. for (const s of globalScopes) {
  17295. const src = node.type === "TSTypeQuery" ? s.declares : s.types;
  17296. if (src[name]) {
  17297. (ctx.deps || (ctx.deps = /* @__PURE__ */ new Set())).add(s.filename);
  17298. return src[name];
  17299. }
  17300. }
  17301. }
  17302. }
  17303. }
  17304. } else {
  17305. let ns = innerResolveTypeReference(ctx, scope, name[0], node, onlyExported);
  17306. if (ns) {
  17307. if (ns.type !== "TSModuleDeclaration") {
  17308. ns = ns._ns;
  17309. }
  17310. if (ns) {
  17311. const childScope = moduleDeclToScope(ctx, ns, ns._ownerScope || scope);
  17312. return innerResolveTypeReference(
  17313. ctx,
  17314. childScope,
  17315. name.length > 2 ? name.slice(1) : name[name.length - 1],
  17316. node,
  17317. !ns.declare
  17318. );
  17319. }
  17320. }
  17321. }
  17322. }
  17323. function getReferenceName(node) {
  17324. const ref = node.type === "TSTypeReference" ? node.typeName : node.type === "TSExpressionWithTypeArguments" ? node.expression : node.type === "TSImportType" ? node.qualifier : node.exprName;
  17325. if ((ref == null ? void 0 : ref.type) === "Identifier") {
  17326. return ref.name;
  17327. } else if ((ref == null ? void 0 : ref.type) === "TSQualifiedName") {
  17328. return qualifiedNameToPath(ref);
  17329. } else {
  17330. return "default";
  17331. }
  17332. }
  17333. function qualifiedNameToPath(node) {
  17334. if (node.type === "Identifier") {
  17335. return [node.name];
  17336. } else {
  17337. return [...qualifiedNameToPath(node.left), node.right.name];
  17338. }
  17339. }
  17340. function resolveGlobalScope(ctx) {
  17341. if (ctx.options.globalTypeFiles) {
  17342. const fs = resolveFS(ctx);
  17343. if (!fs) {
  17344. throw new Error("[vue/compiler-sfc] globalTypeFiles requires fs access.");
  17345. }
  17346. return ctx.options.globalTypeFiles.map(
  17347. (file) => fileToScope(ctx, normalizePath(file), true)
  17348. );
  17349. }
  17350. }
  17351. let ts;
  17352. let loadTS;
  17353. function registerTS(_loadTS) {
  17354. loadTS = () => {
  17355. try {
  17356. return _loadTS();
  17357. } catch (err) {
  17358. if (typeof err.message === "string" && err.message.includes("Cannot find module")) {
  17359. throw new Error(
  17360. 'Failed to load TypeScript, which is required for resolving imported types. Please make sure "typescript" is installed as a project dependency.'
  17361. );
  17362. } else {
  17363. throw new Error(
  17364. "Failed to load TypeScript for resolving imported types."
  17365. );
  17366. }
  17367. }
  17368. };
  17369. }
  17370. function resolveFS(ctx) {
  17371. if (ctx.fs) {
  17372. return ctx.fs;
  17373. }
  17374. if (!ts && loadTS) {
  17375. ts = loadTS();
  17376. }
  17377. const fs = ctx.options.fs || (ts == null ? void 0 : ts.sys);
  17378. if (!fs) {
  17379. return;
  17380. }
  17381. return ctx.fs = {
  17382. fileExists(file) {
  17383. if (file.endsWith(".vue.ts")) {
  17384. file = file.replace(/\.ts$/, "");
  17385. }
  17386. return fs.fileExists(file);
  17387. },
  17388. readFile(file) {
  17389. if (file.endsWith(".vue.ts")) {
  17390. file = file.replace(/\.ts$/, "");
  17391. }
  17392. return fs.readFile(file);
  17393. },
  17394. realpath: fs.realpath
  17395. };
  17396. }
  17397. function resolveTypeFromImport(ctx, node, name, scope) {
  17398. const { source, imported } = scope.imports[name];
  17399. const sourceScope = importSourceToScope(ctx, node, scope, source);
  17400. return resolveTypeReference(ctx, node, sourceScope, imported, true);
  17401. }
  17402. function importSourceToScope(ctx, node, scope, source) {
  17403. let fs;
  17404. try {
  17405. fs = resolveFS(ctx);
  17406. } catch (err) {
  17407. return ctx.error(err.message, node, scope);
  17408. }
  17409. if (!fs) {
  17410. return ctx.error(
  17411. `No fs option provided to \`compileScript\` in non-Node environment. File system access is required for resolving imported types.`,
  17412. node,
  17413. scope
  17414. );
  17415. }
  17416. let resolved = scope.resolvedImportSources[source];
  17417. if (!resolved) {
  17418. if (source.startsWith("..")) {
  17419. const osSpecificJoinFn = process__namespace.platform === "win32" ? path$1.join : joinPaths;
  17420. const filename = osSpecificJoinFn(path$1.dirname(scope.filename), source);
  17421. resolved = resolveExt(filename, fs);
  17422. } else if (source[0] === ".") {
  17423. const filename = joinPaths(path$1.dirname(scope.filename), source);
  17424. resolved = resolveExt(filename, fs);
  17425. } else {
  17426. if (!ts) {
  17427. if (loadTS) ts = loadTS();
  17428. if (!ts) {
  17429. return ctx.error(
  17430. `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.`,
  17431. node,
  17432. scope
  17433. );
  17434. }
  17435. }
  17436. resolved = resolveWithTS(scope.filename, source, ts, fs);
  17437. }
  17438. if (resolved) {
  17439. resolved = scope.resolvedImportSources[source] = normalizePath(resolved);
  17440. }
  17441. }
  17442. if (resolved) {
  17443. (ctx.deps || (ctx.deps = /* @__PURE__ */ new Set())).add(resolved);
  17444. return fileToScope(ctx, resolved);
  17445. } else {
  17446. return ctx.error(
  17447. `Failed to resolve import source ${JSON.stringify(source)}.`,
  17448. node,
  17449. scope
  17450. );
  17451. }
  17452. }
  17453. function resolveExt(filename, fs) {
  17454. filename = filename.replace(/\.js$/, "");
  17455. const tryResolve = (filename2) => {
  17456. if (fs.fileExists(filename2)) return filename2;
  17457. };
  17458. 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`));
  17459. }
  17460. const tsConfigCache = createCache();
  17461. const tsConfigRefMap = /* @__PURE__ */ new Map();
  17462. function resolveWithTS(containingFile, source, ts2, fs) {
  17463. var _a, _b;
  17464. const configPath = ts2.findConfigFile(containingFile, fs.fileExists);
  17465. let tsCompilerOptions;
  17466. let tsResolveCache;
  17467. if (configPath) {
  17468. let configs;
  17469. const normalizedConfigPath = normalizePath(configPath);
  17470. const cached = tsConfigCache.get(normalizedConfigPath);
  17471. if (!cached) {
  17472. configs = loadTSConfig(configPath, ts2, fs).map((config) => ({ config }));
  17473. tsConfigCache.set(normalizedConfigPath, configs);
  17474. } else {
  17475. configs = cached;
  17476. }
  17477. let matchedConfig;
  17478. if (configs.length === 1) {
  17479. matchedConfig = configs[0];
  17480. } else {
  17481. for (const c of configs) {
  17482. const base = normalizePath(
  17483. c.config.options.pathsBasePath || path$1.dirname(c.config.options.configFilePath)
  17484. );
  17485. const included = (_a = c.config.raw) == null ? void 0 : _a.include;
  17486. const excluded = (_b = c.config.raw) == null ? void 0 : _b.exclude;
  17487. if (!included && (!base || containingFile.startsWith(base)) || (included == null ? void 0 : included.some((p) => minimatch(containingFile, joinPaths(base, p))))) {
  17488. if (excluded && excluded.some((p) => minimatch(containingFile, joinPaths(base, p)))) {
  17489. continue;
  17490. }
  17491. matchedConfig = c;
  17492. break;
  17493. }
  17494. }
  17495. if (!matchedConfig) {
  17496. matchedConfig = configs[configs.length - 1];
  17497. }
  17498. }
  17499. tsCompilerOptions = matchedConfig.config.options;
  17500. tsResolveCache = matchedConfig.cache || (matchedConfig.cache = ts2.createModuleResolutionCache(
  17501. process__namespace.cwd(),
  17502. createGetCanonicalFileName(ts2.sys.useCaseSensitiveFileNames),
  17503. tsCompilerOptions
  17504. ));
  17505. } else {
  17506. tsCompilerOptions = {};
  17507. }
  17508. const res = ts2.resolveModuleName(
  17509. source,
  17510. containingFile,
  17511. tsCompilerOptions,
  17512. fs,
  17513. tsResolveCache
  17514. );
  17515. if (res.resolvedModule) {
  17516. let filename = res.resolvedModule.resolvedFileName;
  17517. if (filename.endsWith(".vue.ts")) {
  17518. filename = filename.replace(/\.ts$/, "");
  17519. }
  17520. return fs.realpath ? fs.realpath(filename) : filename;
  17521. }
  17522. }
  17523. function loadTSConfig(configPath, ts2, fs, visited = /* @__PURE__ */ new Set()) {
  17524. const parseConfigHost = ts2.sys;
  17525. const config = ts2.parseJsonConfigFileContent(
  17526. ts2.readConfigFile(configPath, fs.readFile).config,
  17527. parseConfigHost,
  17528. path$1.dirname(configPath),
  17529. void 0,
  17530. configPath
  17531. );
  17532. const res = [config];
  17533. visited.add(configPath);
  17534. if (config.projectReferences) {
  17535. for (const ref of config.projectReferences) {
  17536. const refPath = ts2.resolveProjectReferencePath(ref);
  17537. if (visited.has(refPath) || !fs.fileExists(refPath)) {
  17538. continue;
  17539. }
  17540. tsConfigRefMap.set(refPath, configPath);
  17541. res.unshift(...loadTSConfig(refPath, ts2, fs, visited));
  17542. }
  17543. }
  17544. return res;
  17545. }
  17546. const fileToScopeCache = createCache();
  17547. function invalidateTypeCache(filename) {
  17548. filename = normalizePath(filename);
  17549. fileToScopeCache.delete(filename);
  17550. tsConfigCache.delete(filename);
  17551. const affectedConfig = tsConfigRefMap.get(filename);
  17552. if (affectedConfig) tsConfigCache.delete(affectedConfig);
  17553. }
  17554. function fileToScope(ctx, filename, asGlobal = false) {
  17555. const cached = fileToScopeCache.get(filename);
  17556. if (cached) {
  17557. return cached;
  17558. }
  17559. const fs = resolveFS(ctx);
  17560. const source = fs.readFile(filename) || "";
  17561. const body = parseFile(filename, source, ctx.options.babelParserPlugins);
  17562. const scope = new TypeScope(filename, source, 0, recordImports(body));
  17563. recordTypes(ctx, body, scope, asGlobal);
  17564. fileToScopeCache.set(filename, scope);
  17565. return scope;
  17566. }
  17567. function parseFile(filename, content, parserPlugins) {
  17568. const ext = path$1.extname(filename);
  17569. if (ext === ".ts" || ext === ".mts" || ext === ".tsx" || ext === ".mtsx") {
  17570. return parser$1.parse(content, {
  17571. plugins: resolveParserPlugins(
  17572. ext.slice(1),
  17573. parserPlugins,
  17574. /\.d\.m?ts$/.test(filename)
  17575. ),
  17576. sourceType: "module"
  17577. }).program.body;
  17578. } else if (ext === ".vue") {
  17579. const {
  17580. descriptor: { script, scriptSetup }
  17581. } = parse$1(content);
  17582. if (!script && !scriptSetup) {
  17583. return [];
  17584. }
  17585. const scriptOffset = script ? script.loc.start.offset : Infinity;
  17586. const scriptSetupOffset = scriptSetup ? scriptSetup.loc.start.offset : Infinity;
  17587. const firstBlock = scriptOffset < scriptSetupOffset ? script : scriptSetup;
  17588. const secondBlock = scriptOffset < scriptSetupOffset ? scriptSetup : script;
  17589. let scriptContent = " ".repeat(Math.min(scriptOffset, scriptSetupOffset)) + firstBlock.content;
  17590. if (secondBlock) {
  17591. scriptContent += " ".repeat(secondBlock.loc.start.offset - script.loc.end.offset) + secondBlock.content;
  17592. }
  17593. const lang = (script == null ? void 0 : script.lang) || (scriptSetup == null ? void 0 : scriptSetup.lang);
  17594. return parser$1.parse(scriptContent, {
  17595. plugins: resolveParserPlugins(lang, parserPlugins),
  17596. sourceType: "module"
  17597. }).program.body;
  17598. }
  17599. return [];
  17600. }
  17601. function ctxToScope(ctx) {
  17602. if (ctx.scope) {
  17603. return ctx.scope;
  17604. }
  17605. const body = "ast" in ctx ? ctx.ast : ctx.scriptAst ? [...ctx.scriptAst.body, ...ctx.scriptSetupAst.body] : ctx.scriptSetupAst.body;
  17606. const scope = new TypeScope(
  17607. ctx.filename,
  17608. ctx.source,
  17609. "startOffset" in ctx ? ctx.startOffset : 0,
  17610. "userImports" in ctx ? Object.create(ctx.userImports) : recordImports(body)
  17611. );
  17612. recordTypes(ctx, body, scope);
  17613. return ctx.scope = scope;
  17614. }
  17615. function moduleDeclToScope(ctx, node, parentScope) {
  17616. if (node._resolvedChildScope) {
  17617. return node._resolvedChildScope;
  17618. }
  17619. const scope = createChildScope(parentScope);
  17620. if (node.body.type === "TSModuleDeclaration") {
  17621. const decl = node.body;
  17622. decl._ownerScope = scope;
  17623. const id = getId(decl.id);
  17624. scope.types[id] = scope.exportedTypes[id] = decl;
  17625. } else {
  17626. recordTypes(ctx, node.body.body, scope);
  17627. }
  17628. return node._resolvedChildScope = scope;
  17629. }
  17630. function createChildScope(parentScope) {
  17631. return new TypeScope(
  17632. parentScope.filename,
  17633. parentScope.source,
  17634. parentScope.offset,
  17635. Object.create(parentScope.imports),
  17636. Object.create(parentScope.types),
  17637. Object.create(parentScope.declares)
  17638. );
  17639. }
  17640. const importExportRE = /^Import|^Export/;
  17641. function recordTypes(ctx, body, scope, asGlobal = false) {
  17642. const { types, declares, exportedTypes, exportedDeclares, imports } = scope;
  17643. const isAmbient = asGlobal ? !body.some((s) => importExportRE.test(s.type)) : false;
  17644. for (const stmt of body) {
  17645. if (asGlobal) {
  17646. if (isAmbient) {
  17647. if (stmt.declare) {
  17648. recordType(stmt, types, declares);
  17649. }
  17650. } else if (stmt.type === "TSModuleDeclaration" && stmt.global) {
  17651. for (const s of stmt.body.body) {
  17652. recordType(s, types, declares);
  17653. }
  17654. }
  17655. } else {
  17656. recordType(stmt, types, declares);
  17657. }
  17658. }
  17659. if (!asGlobal) {
  17660. for (const stmt of body) {
  17661. if (stmt.type === "ExportNamedDeclaration") {
  17662. if (stmt.declaration) {
  17663. recordType(stmt.declaration, types, declares);
  17664. recordType(stmt.declaration, exportedTypes, exportedDeclares);
  17665. } else {
  17666. for (const spec of stmt.specifiers) {
  17667. if (spec.type === "ExportSpecifier") {
  17668. const local = spec.local.name;
  17669. const exported = getId(spec.exported);
  17670. if (stmt.source) {
  17671. imports[exported] = {
  17672. source: stmt.source.value,
  17673. imported: local
  17674. };
  17675. exportedTypes[exported] = {
  17676. type: "TSTypeReference",
  17677. typeName: {
  17678. type: "Identifier",
  17679. name: local
  17680. },
  17681. _ownerScope: scope
  17682. };
  17683. } else if (types[local]) {
  17684. exportedTypes[exported] = types[local];
  17685. }
  17686. }
  17687. }
  17688. }
  17689. } else if (stmt.type === "ExportAllDeclaration") {
  17690. const sourceScope = importSourceToScope(
  17691. ctx,
  17692. stmt.source,
  17693. scope,
  17694. stmt.source.value
  17695. );
  17696. Object.assign(scope.exportedTypes, sourceScope.exportedTypes);
  17697. } else if (stmt.type === "ExportDefaultDeclaration" && stmt.declaration) {
  17698. if (stmt.declaration.type !== "Identifier") {
  17699. recordType(stmt.declaration, types, declares, "default");
  17700. recordType(
  17701. stmt.declaration,
  17702. exportedTypes,
  17703. exportedDeclares,
  17704. "default"
  17705. );
  17706. } else if (types[stmt.declaration.name]) {
  17707. exportedTypes["default"] = types[stmt.declaration.name];
  17708. }
  17709. }
  17710. }
  17711. }
  17712. for (const key of Object.keys(types)) {
  17713. const node = types[key];
  17714. node._ownerScope = scope;
  17715. if (node._ns) node._ns._ownerScope = scope;
  17716. }
  17717. for (const key of Object.keys(declares)) {
  17718. declares[key]._ownerScope = scope;
  17719. }
  17720. }
  17721. function recordType(node, types, declares, overwriteId) {
  17722. switch (node.type) {
  17723. case "TSInterfaceDeclaration":
  17724. case "TSEnumDeclaration":
  17725. case "TSModuleDeclaration": {
  17726. const id = overwriteId || getId(node.id);
  17727. let existing = types[id];
  17728. if (existing) {
  17729. if (node.type === "TSModuleDeclaration") {
  17730. if (existing.type === "TSModuleDeclaration") {
  17731. mergeNamespaces(existing, node);
  17732. } else {
  17733. attachNamespace(existing, node);
  17734. }
  17735. break;
  17736. }
  17737. if (existing.type === "TSModuleDeclaration") {
  17738. types[id] = node;
  17739. attachNamespace(node, existing);
  17740. break;
  17741. }
  17742. if (existing.type !== node.type) {
  17743. break;
  17744. }
  17745. if (node.type === "TSInterfaceDeclaration") {
  17746. existing.body.body.push(...node.body.body);
  17747. } else {
  17748. existing.members.push(...node.members);
  17749. }
  17750. } else {
  17751. types[id] = node;
  17752. }
  17753. break;
  17754. }
  17755. case "ClassDeclaration":
  17756. if (overwriteId || node.id) types[overwriteId || getId(node.id)] = node;
  17757. break;
  17758. case "TSTypeAliasDeclaration":
  17759. types[node.id.name] = node.typeParameters ? node : node.typeAnnotation;
  17760. break;
  17761. case "TSDeclareFunction":
  17762. if (node.id) declares[node.id.name] = node;
  17763. break;
  17764. case "VariableDeclaration": {
  17765. if (node.declare) {
  17766. for (const decl of node.declarations) {
  17767. if (decl.id.type === "Identifier" && decl.id.typeAnnotation) {
  17768. declares[decl.id.name] = decl.id.typeAnnotation.typeAnnotation;
  17769. }
  17770. }
  17771. }
  17772. break;
  17773. }
  17774. }
  17775. }
  17776. function mergeNamespaces(to, from) {
  17777. const toBody = to.body;
  17778. const fromBody = from.body;
  17779. if (toBody.type === "TSModuleDeclaration") {
  17780. if (fromBody.type === "TSModuleDeclaration") {
  17781. mergeNamespaces(toBody, fromBody);
  17782. } else {
  17783. fromBody.body.push({
  17784. type: "ExportNamedDeclaration",
  17785. declaration: toBody,
  17786. exportKind: "type",
  17787. specifiers: []
  17788. });
  17789. }
  17790. } else if (fromBody.type === "TSModuleDeclaration") {
  17791. toBody.body.push({
  17792. type: "ExportNamedDeclaration",
  17793. declaration: fromBody,
  17794. exportKind: "type",
  17795. specifiers: []
  17796. });
  17797. } else {
  17798. toBody.body.push(...fromBody.body);
  17799. }
  17800. }
  17801. function attachNamespace(to, ns) {
  17802. if (!to._ns) {
  17803. to._ns = ns;
  17804. } else {
  17805. mergeNamespaces(to._ns, ns);
  17806. }
  17807. }
  17808. function recordImports(body) {
  17809. const imports = /* @__PURE__ */ Object.create(null);
  17810. for (const s of body) {
  17811. recordImport(s, imports);
  17812. }
  17813. return imports;
  17814. }
  17815. function recordImport(node, imports) {
  17816. if (node.type !== "ImportDeclaration") {
  17817. return;
  17818. }
  17819. for (const s of node.specifiers) {
  17820. imports[s.local.name] = {
  17821. imported: getImportedName(s),
  17822. source: node.source.value
  17823. };
  17824. }
  17825. }
  17826. function inferRuntimeType(ctx, node, scope = node._ownerScope || ctxToScope(ctx), isKeyOf = false) {
  17827. try {
  17828. switch (node.type) {
  17829. case "TSStringKeyword":
  17830. return ["String"];
  17831. case "TSNumberKeyword":
  17832. return ["Number"];
  17833. case "TSBooleanKeyword":
  17834. return ["Boolean"];
  17835. case "TSObjectKeyword":
  17836. return ["Object"];
  17837. case "TSNullKeyword":
  17838. return ["null"];
  17839. case "TSTypeLiteral":
  17840. case "TSInterfaceDeclaration": {
  17841. const types = /* @__PURE__ */ new Set();
  17842. const members = node.type === "TSTypeLiteral" ? node.members : node.body.body;
  17843. for (const m of members) {
  17844. if (isKeyOf) {
  17845. if (m.type === "TSPropertySignature" && m.key.type === "NumericLiteral") {
  17846. types.add("Number");
  17847. } else if (m.type === "TSIndexSignature") {
  17848. const annotation = m.parameters[0].typeAnnotation;
  17849. if (annotation && annotation.type !== "Noop") {
  17850. const type = inferRuntimeType(
  17851. ctx,
  17852. annotation.typeAnnotation,
  17853. scope
  17854. )[0];
  17855. if (type === UNKNOWN_TYPE) return [UNKNOWN_TYPE];
  17856. types.add(type);
  17857. }
  17858. } else {
  17859. types.add("String");
  17860. }
  17861. } else if (m.type === "TSCallSignatureDeclaration" || m.type === "TSConstructSignatureDeclaration") {
  17862. types.add("Function");
  17863. } else {
  17864. types.add("Object");
  17865. }
  17866. }
  17867. return types.size ? Array.from(types) : [isKeyOf ? UNKNOWN_TYPE : "Object"];
  17868. }
  17869. case "TSPropertySignature":
  17870. if (node.typeAnnotation) {
  17871. return inferRuntimeType(
  17872. ctx,
  17873. node.typeAnnotation.typeAnnotation,
  17874. scope
  17875. );
  17876. }
  17877. break;
  17878. case "TSMethodSignature":
  17879. case "TSFunctionType":
  17880. return ["Function"];
  17881. case "TSArrayType":
  17882. case "TSTupleType":
  17883. return ["Array"];
  17884. case "TSLiteralType":
  17885. switch (node.literal.type) {
  17886. case "StringLiteral":
  17887. return ["String"];
  17888. case "BooleanLiteral":
  17889. return ["Boolean"];
  17890. case "NumericLiteral":
  17891. case "BigIntLiteral":
  17892. return ["Number"];
  17893. default:
  17894. return [UNKNOWN_TYPE];
  17895. }
  17896. case "TSTypeReference": {
  17897. const resolved = resolveTypeReference(ctx, node, scope);
  17898. if (resolved) {
  17899. return inferRuntimeType(ctx, resolved, resolved._ownerScope, isKeyOf);
  17900. }
  17901. if (node.typeName.type === "Identifier") {
  17902. if (isKeyOf) {
  17903. switch (node.typeName.name) {
  17904. case "String":
  17905. case "Array":
  17906. case "ArrayLike":
  17907. case "Parameters":
  17908. case "ConstructorParameters":
  17909. case "ReadonlyArray":
  17910. return ["String", "Number"];
  17911. // TS built-in utility types
  17912. case "Record":
  17913. case "Partial":
  17914. case "Required":
  17915. case "Readonly":
  17916. if (node.typeParameters && node.typeParameters.params[0]) {
  17917. return inferRuntimeType(
  17918. ctx,
  17919. node.typeParameters.params[0],
  17920. scope,
  17921. true
  17922. );
  17923. }
  17924. break;
  17925. case "Pick":
  17926. case "Extract":
  17927. if (node.typeParameters && node.typeParameters.params[1]) {
  17928. return inferRuntimeType(
  17929. ctx,
  17930. node.typeParameters.params[1],
  17931. scope
  17932. );
  17933. }
  17934. break;
  17935. case "Function":
  17936. case "Object":
  17937. case "Set":
  17938. case "Map":
  17939. case "WeakSet":
  17940. case "WeakMap":
  17941. case "Date":
  17942. case "Promise":
  17943. case "Error":
  17944. case "Uppercase":
  17945. case "Lowercase":
  17946. case "Capitalize":
  17947. case "Uncapitalize":
  17948. case "ReadonlyMap":
  17949. case "ReadonlySet":
  17950. return ["String"];
  17951. }
  17952. } else {
  17953. switch (node.typeName.name) {
  17954. case "Array":
  17955. case "Function":
  17956. case "Object":
  17957. case "Set":
  17958. case "Map":
  17959. case "WeakSet":
  17960. case "WeakMap":
  17961. case "Date":
  17962. case "Promise":
  17963. case "Error":
  17964. return [node.typeName.name];
  17965. // TS built-in utility types
  17966. // https://www.typescriptlang.org/docs/handbook/utility-types.html
  17967. case "Partial":
  17968. case "Required":
  17969. case "Readonly":
  17970. case "Record":
  17971. case "Pick":
  17972. case "Omit":
  17973. case "InstanceType":
  17974. return ["Object"];
  17975. case "Uppercase":
  17976. case "Lowercase":
  17977. case "Capitalize":
  17978. case "Uncapitalize":
  17979. return ["String"];
  17980. case "Parameters":
  17981. case "ConstructorParameters":
  17982. case "ReadonlyArray":
  17983. return ["Array"];
  17984. case "ReadonlyMap":
  17985. return ["Map"];
  17986. case "ReadonlySet":
  17987. return ["Set"];
  17988. case "NonNullable":
  17989. if (node.typeParameters && node.typeParameters.params[0]) {
  17990. return inferRuntimeType(
  17991. ctx,
  17992. node.typeParameters.params[0],
  17993. scope
  17994. ).filter((t) => t !== "null");
  17995. }
  17996. break;
  17997. case "Extract":
  17998. if (node.typeParameters && node.typeParameters.params[1]) {
  17999. return inferRuntimeType(
  18000. ctx,
  18001. node.typeParameters.params[1],
  18002. scope
  18003. );
  18004. }
  18005. break;
  18006. case "Exclude":
  18007. case "OmitThisParameter":
  18008. if (node.typeParameters && node.typeParameters.params[0]) {
  18009. return inferRuntimeType(
  18010. ctx,
  18011. node.typeParameters.params[0],
  18012. scope
  18013. );
  18014. }
  18015. break;
  18016. }
  18017. }
  18018. }
  18019. break;
  18020. }
  18021. case "TSParenthesizedType":
  18022. return inferRuntimeType(ctx, node.typeAnnotation, scope);
  18023. case "TSUnionType":
  18024. return flattenTypes(ctx, node.types, scope, isKeyOf);
  18025. case "TSIntersectionType": {
  18026. return flattenTypes(ctx, node.types, scope, isKeyOf).filter(
  18027. (t) => t !== UNKNOWN_TYPE
  18028. );
  18029. }
  18030. case "TSEnumDeclaration":
  18031. return inferEnumType(node);
  18032. case "TSSymbolKeyword":
  18033. return ["Symbol"];
  18034. case "TSIndexedAccessType": {
  18035. const types = resolveIndexType(ctx, node, scope);
  18036. return flattenTypes(ctx, types, scope, isKeyOf);
  18037. }
  18038. case "ClassDeclaration":
  18039. return ["Object"];
  18040. case "TSImportType": {
  18041. const sourceScope = importSourceToScope(
  18042. ctx,
  18043. node.argument,
  18044. scope,
  18045. node.argument.value
  18046. );
  18047. const resolved = resolveTypeReference(ctx, node, sourceScope);
  18048. if (resolved) {
  18049. return inferRuntimeType(ctx, resolved, resolved._ownerScope);
  18050. }
  18051. break;
  18052. }
  18053. case "TSTypeQuery": {
  18054. const id = node.exprName;
  18055. if (id.type === "Identifier") {
  18056. const matched = scope.declares[id.name];
  18057. if (matched) {
  18058. return inferRuntimeType(ctx, matched, matched._ownerScope, isKeyOf);
  18059. }
  18060. }
  18061. break;
  18062. }
  18063. // e.g. readonly
  18064. case "TSTypeOperator": {
  18065. return inferRuntimeType(
  18066. ctx,
  18067. node.typeAnnotation,
  18068. scope,
  18069. node.operator === "keyof"
  18070. );
  18071. }
  18072. case "TSAnyKeyword": {
  18073. if (isKeyOf) {
  18074. return ["String", "Number", "Symbol"];
  18075. }
  18076. break;
  18077. }
  18078. }
  18079. } catch (e) {
  18080. }
  18081. return [UNKNOWN_TYPE];
  18082. }
  18083. function flattenTypes(ctx, types, scope, isKeyOf = false) {
  18084. if (types.length === 1) {
  18085. return inferRuntimeType(ctx, types[0], scope, isKeyOf);
  18086. }
  18087. return [
  18088. ...new Set(
  18089. [].concat(
  18090. ...types.map((t) => inferRuntimeType(ctx, t, scope, isKeyOf))
  18091. )
  18092. )
  18093. ];
  18094. }
  18095. function inferEnumType(node) {
  18096. const types = /* @__PURE__ */ new Set();
  18097. for (const m of node.members) {
  18098. if (m.initializer) {
  18099. switch (m.initializer.type) {
  18100. case "StringLiteral":
  18101. types.add("String");
  18102. break;
  18103. case "NumericLiteral":
  18104. types.add("Number");
  18105. break;
  18106. }
  18107. }
  18108. }
  18109. return types.size ? [...types] : ["Number"];
  18110. }
  18111. function resolveExtractPropTypes({ props }, scope) {
  18112. const res = { props: {} };
  18113. for (const key in props) {
  18114. const raw = props[key];
  18115. res.props[key] = reverseInferType(
  18116. raw.key,
  18117. raw.typeAnnotation.typeAnnotation,
  18118. scope
  18119. );
  18120. }
  18121. return res;
  18122. }
  18123. function reverseInferType(key, node, scope, optional = true, checkObjectSyntax = true) {
  18124. if (checkObjectSyntax && node.type === "TSTypeLiteral") {
  18125. const typeType = findStaticPropertyType(node, "type");
  18126. if (typeType) {
  18127. const requiredType = findStaticPropertyType(node, "required");
  18128. const optional2 = requiredType && requiredType.type === "TSLiteralType" && requiredType.literal.type === "BooleanLiteral" ? !requiredType.literal.value : true;
  18129. return reverseInferType(key, typeType, scope, optional2, false);
  18130. }
  18131. } else if (node.type === "TSTypeReference" && node.typeName.type === "Identifier") {
  18132. if (node.typeName.name.endsWith("Constructor")) {
  18133. return createProperty(
  18134. key,
  18135. ctorToType(node.typeName.name),
  18136. scope,
  18137. optional
  18138. );
  18139. } else if (node.typeName.name === "PropType" && node.typeParameters) {
  18140. return createProperty(key, node.typeParameters.params[0], scope, optional);
  18141. }
  18142. }
  18143. if ((node.type === "TSTypeReference" || node.type === "TSImportType") && node.typeParameters) {
  18144. for (const t of node.typeParameters.params) {
  18145. const inferred = reverseInferType(key, t, scope, optional);
  18146. if (inferred) return inferred;
  18147. }
  18148. }
  18149. return createProperty(key, { type: `TSNullKeyword` }, scope, optional);
  18150. }
  18151. function ctorToType(ctorType) {
  18152. const ctor = ctorType.slice(0, -11);
  18153. switch (ctor) {
  18154. case "String":
  18155. case "Number":
  18156. case "Boolean":
  18157. return { type: `TS${ctor}Keyword` };
  18158. case "Array":
  18159. case "Function":
  18160. case "Object":
  18161. case "Set":
  18162. case "Map":
  18163. case "WeakSet":
  18164. case "WeakMap":
  18165. case "Date":
  18166. case "Promise":
  18167. return {
  18168. type: "TSTypeReference",
  18169. typeName: { type: "Identifier", name: ctor }
  18170. };
  18171. }
  18172. return { type: `TSNullKeyword` };
  18173. }
  18174. function findStaticPropertyType(node, key) {
  18175. const prop = node.members.find(
  18176. (m) => m.type === "TSPropertySignature" && !m.computed && getId(m.key) === key && m.typeAnnotation
  18177. );
  18178. return prop && prop.typeAnnotation.typeAnnotation;
  18179. }
  18180. function resolveReturnType(ctx, arg, scope) {
  18181. var _a;
  18182. let resolved = arg;
  18183. if (arg.type === "TSTypeReference" || arg.type === "TSTypeQuery" || arg.type === "TSImportType") {
  18184. resolved = resolveTypeReference(ctx, arg, scope);
  18185. }
  18186. if (!resolved) return;
  18187. if (resolved.type === "TSFunctionType") {
  18188. return (_a = resolved.typeAnnotation) == null ? void 0 : _a.typeAnnotation;
  18189. }
  18190. if (resolved.type === "TSDeclareFunction") {
  18191. return resolved.returnType;
  18192. }
  18193. }
  18194. function resolveUnionType(ctx, node, scope) {
  18195. if (node.type === "TSTypeReference") {
  18196. const resolved = resolveTypeReference(ctx, node, scope);
  18197. if (resolved) node = resolved;
  18198. }
  18199. let types;
  18200. if (node.type === "TSUnionType") {
  18201. types = node.types.flatMap((node2) => resolveUnionType(ctx, node2, scope));
  18202. } else {
  18203. types = [node];
  18204. }
  18205. return types;
  18206. }
  18207. const DEFINE_MODEL = "defineModel";
  18208. function processDefineModel(ctx, node, declId) {
  18209. if (!isCallOf(node, DEFINE_MODEL)) {
  18210. return false;
  18211. }
  18212. ctx.hasDefineModelCall = true;
  18213. const type = node.typeParameters && node.typeParameters.params[0] || void 0;
  18214. let modelName;
  18215. let options;
  18216. const arg0 = node.arguments[0] && CompilerDOM.unwrapTSNode(node.arguments[0]);
  18217. const hasName = arg0 && arg0.type === "StringLiteral";
  18218. if (hasName) {
  18219. modelName = arg0.value;
  18220. options = node.arguments[1];
  18221. } else {
  18222. modelName = "modelValue";
  18223. options = arg0;
  18224. }
  18225. if (ctx.modelDecls[modelName]) {
  18226. ctx.error(`duplicate model name ${JSON.stringify(modelName)}`, node);
  18227. }
  18228. let optionsString = options && ctx.getString(options);
  18229. let optionsRemoved = !options;
  18230. const runtimeOptionNodes = [];
  18231. if (options && options.type === "ObjectExpression" && !options.properties.some((p) => p.type === "SpreadElement" || p.computed)) {
  18232. let removed = 0;
  18233. for (let i = options.properties.length - 1; i >= 0; i--) {
  18234. const p = options.properties[i];
  18235. const next = options.properties[i + 1];
  18236. const start = p.start;
  18237. const end = next ? next.start : options.end - 1;
  18238. 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"))) {
  18239. optionsString = optionsString.slice(0, start - options.start) + optionsString.slice(end - options.start);
  18240. } else {
  18241. removed++;
  18242. ctx.s.remove(ctx.startOffset + start, ctx.startOffset + end);
  18243. runtimeOptionNodes.push(p);
  18244. }
  18245. }
  18246. if (removed === options.properties.length) {
  18247. optionsRemoved = true;
  18248. ctx.s.remove(
  18249. ctx.startOffset + (hasName ? arg0.end : options.start),
  18250. ctx.startOffset + options.end
  18251. );
  18252. }
  18253. }
  18254. ctx.modelDecls[modelName] = {
  18255. type,
  18256. options: optionsString,
  18257. runtimeOptionNodes,
  18258. identifier: declId && declId.type === "Identifier" ? declId.name : void 0
  18259. };
  18260. ctx.bindingMetadata[modelName] = "props";
  18261. ctx.s.overwrite(
  18262. ctx.startOffset + node.callee.start,
  18263. ctx.startOffset + node.callee.end,
  18264. ctx.helper("useModel")
  18265. );
  18266. ctx.s.appendLeft(
  18267. ctx.startOffset + (node.arguments.length ? node.arguments[0].start : node.end - 1),
  18268. `__props, ` + (hasName ? `` : `${JSON.stringify(modelName)}${optionsRemoved ? `` : `, `}`)
  18269. );
  18270. return true;
  18271. }
  18272. function genModelProps(ctx) {
  18273. if (!ctx.hasDefineModelCall) return;
  18274. const isProd = !!ctx.options.isProd;
  18275. let modelPropsDecl = "";
  18276. for (const [name, { type, options: runtimeOptions }] of Object.entries(
  18277. ctx.modelDecls
  18278. )) {
  18279. let skipCheck = false;
  18280. let codegenOptions = ``;
  18281. let runtimeTypes = type && inferRuntimeType(ctx, type);
  18282. if (runtimeTypes) {
  18283. const hasBoolean = runtimeTypes.includes("Boolean");
  18284. const hasFunction = runtimeTypes.includes("Function");
  18285. const hasUnknownType = runtimeTypes.includes(UNKNOWN_TYPE);
  18286. if (hasUnknownType) {
  18287. if (hasBoolean || hasFunction) {
  18288. runtimeTypes = runtimeTypes.filter((t) => t !== UNKNOWN_TYPE);
  18289. skipCheck = true;
  18290. } else {
  18291. runtimeTypes = ["null"];
  18292. }
  18293. }
  18294. if (!isProd) {
  18295. codegenOptions = `type: ${toRuntimeTypeString(runtimeTypes)}` + (skipCheck ? ", skipCheck: true" : "");
  18296. } else if (hasBoolean || runtimeOptions && hasFunction) {
  18297. codegenOptions = `type: ${toRuntimeTypeString(runtimeTypes)}`;
  18298. } else ;
  18299. }
  18300. let decl;
  18301. if (codegenOptions && runtimeOptions) {
  18302. decl = ctx.isTS ? `{ ${codegenOptions}, ...${runtimeOptions} }` : `Object.assign({ ${codegenOptions} }, ${runtimeOptions})`;
  18303. } else if (codegenOptions) {
  18304. decl = `{ ${codegenOptions} }`;
  18305. } else if (runtimeOptions) {
  18306. decl = runtimeOptions;
  18307. } else {
  18308. decl = `{}`;
  18309. }
  18310. modelPropsDecl += `
  18311. ${JSON.stringify(name)}: ${decl},`;
  18312. const modifierPropName = JSON.stringify(
  18313. name === "modelValue" ? `modelModifiers` : `${name}Modifiers`
  18314. );
  18315. modelPropsDecl += `
  18316. ${modifierPropName}: {},`;
  18317. }
  18318. return `{${modelPropsDecl}
  18319. }`;
  18320. }
  18321. const DEFINE_PROPS = "defineProps";
  18322. const WITH_DEFAULTS = "withDefaults";
  18323. function processDefineProps(ctx, node, declId, isWithDefaults = false) {
  18324. if (!isCallOf(node, DEFINE_PROPS)) {
  18325. return processWithDefaults(ctx, node, declId);
  18326. }
  18327. if (ctx.hasDefinePropsCall) {
  18328. ctx.error(`duplicate ${DEFINE_PROPS}() call`, node);
  18329. }
  18330. ctx.hasDefinePropsCall = true;
  18331. ctx.propsRuntimeDecl = node.arguments[0];
  18332. if (ctx.propsRuntimeDecl) {
  18333. for (const key of getObjectOrArrayExpressionKeys(ctx.propsRuntimeDecl)) {
  18334. if (!(key in ctx.bindingMetadata)) {
  18335. ctx.bindingMetadata[key] = "props";
  18336. }
  18337. }
  18338. }
  18339. if (node.typeParameters) {
  18340. if (ctx.propsRuntimeDecl) {
  18341. ctx.error(
  18342. `${DEFINE_PROPS}() cannot accept both type and non-type arguments at the same time. Use one or the other.`,
  18343. node
  18344. );
  18345. }
  18346. ctx.propsTypeDecl = node.typeParameters.params[0];
  18347. }
  18348. if (!isWithDefaults && declId && declId.type === "ObjectPattern") {
  18349. processPropsDestructure(ctx, declId);
  18350. }
  18351. ctx.propsCall = node;
  18352. ctx.propsDecl = declId;
  18353. return true;
  18354. }
  18355. function processWithDefaults(ctx, node, declId) {
  18356. if (!isCallOf(node, WITH_DEFAULTS)) {
  18357. return false;
  18358. }
  18359. if (!processDefineProps(
  18360. ctx,
  18361. node.arguments[0],
  18362. declId,
  18363. true
  18364. )) {
  18365. ctx.error(
  18366. `${WITH_DEFAULTS}' first argument must be a ${DEFINE_PROPS} call.`,
  18367. node.arguments[0] || node
  18368. );
  18369. }
  18370. if (ctx.propsRuntimeDecl) {
  18371. ctx.error(
  18372. `${WITH_DEFAULTS} can only be used with type-based ${DEFINE_PROPS} declaration.`,
  18373. node
  18374. );
  18375. }
  18376. if (declId && declId.type === "ObjectPattern") {
  18377. ctx.warn(
  18378. `${WITH_DEFAULTS}() is unnecessary when using destructure with ${DEFINE_PROPS}().
  18379. Reactive destructure will be disabled when using withDefaults().
  18380. Prefer using destructure default values, e.g. const { foo = 1 } = defineProps(...). `,
  18381. node.callee
  18382. );
  18383. }
  18384. ctx.propsRuntimeDefaults = node.arguments[1];
  18385. if (!ctx.propsRuntimeDefaults) {
  18386. ctx.error(`The 2nd argument of ${WITH_DEFAULTS} is required.`, node);
  18387. }
  18388. ctx.propsCall = node;
  18389. return true;
  18390. }
  18391. function genRuntimeProps(ctx) {
  18392. let propsDecls;
  18393. if (ctx.propsRuntimeDecl) {
  18394. propsDecls = ctx.getString(ctx.propsRuntimeDecl).trim();
  18395. if (ctx.propsDestructureDecl) {
  18396. const defaults = [];
  18397. for (const key in ctx.propsDestructuredBindings) {
  18398. const d = genDestructuredDefaultValue(ctx, key);
  18399. const finalKey = getEscapedPropName(key);
  18400. if (d)
  18401. defaults.push(
  18402. `${finalKey}: ${d.valueString}${d.needSkipFactory ? `, __skip_${finalKey}: true` : ``}`
  18403. );
  18404. }
  18405. if (defaults.length) {
  18406. propsDecls = `/*@__PURE__*/${ctx.helper(
  18407. `mergeDefaults`
  18408. )}(${propsDecls}, {
  18409. ${defaults.join(",\n ")}
  18410. })`;
  18411. }
  18412. }
  18413. } else if (ctx.propsTypeDecl) {
  18414. propsDecls = extractRuntimeProps(ctx);
  18415. }
  18416. const modelsDecls = genModelProps(ctx);
  18417. if (propsDecls && modelsDecls) {
  18418. return `/*@__PURE__*/${ctx.helper(
  18419. "mergeModels"
  18420. )}(${propsDecls}, ${modelsDecls})`;
  18421. } else {
  18422. return modelsDecls || propsDecls;
  18423. }
  18424. }
  18425. function extractRuntimeProps(ctx) {
  18426. const props = resolveRuntimePropsFromType(ctx, ctx.propsTypeDecl);
  18427. if (!props.length) {
  18428. return;
  18429. }
  18430. const propStrings = [];
  18431. const hasStaticDefaults = hasStaticWithDefaults(ctx);
  18432. for (const prop of props) {
  18433. propStrings.push(genRuntimePropFromType(ctx, prop, hasStaticDefaults));
  18434. if ("bindingMetadata" in ctx && !(prop.key in ctx.bindingMetadata)) {
  18435. ctx.bindingMetadata[prop.key] = "props";
  18436. }
  18437. }
  18438. let propsDecls = `{
  18439. ${propStrings.join(",\n ")}
  18440. }`;
  18441. if (ctx.propsRuntimeDefaults && !hasStaticDefaults) {
  18442. propsDecls = `/*@__PURE__*/${ctx.helper(
  18443. "mergeDefaults"
  18444. )}(${propsDecls}, ${ctx.getString(ctx.propsRuntimeDefaults)})`;
  18445. }
  18446. return propsDecls;
  18447. }
  18448. function resolveRuntimePropsFromType(ctx, node) {
  18449. const props = [];
  18450. const elements = resolveTypeElements(ctx, node);
  18451. for (const key in elements.props) {
  18452. const e = elements.props[key];
  18453. let type = inferRuntimeType(ctx, e);
  18454. let skipCheck = false;
  18455. if (type.includes(UNKNOWN_TYPE)) {
  18456. if (type.includes("Boolean") || type.includes("Function")) {
  18457. type = type.filter((t) => t !== UNKNOWN_TYPE);
  18458. skipCheck = true;
  18459. } else {
  18460. type = ["null"];
  18461. }
  18462. }
  18463. props.push({
  18464. key,
  18465. required: !e.optional,
  18466. type: type || [`null`],
  18467. skipCheck
  18468. });
  18469. }
  18470. return props;
  18471. }
  18472. function genRuntimePropFromType(ctx, { key, required, type, skipCheck }, hasStaticDefaults) {
  18473. let defaultString;
  18474. const destructured = genDestructuredDefaultValue(ctx, key, type);
  18475. if (destructured) {
  18476. defaultString = `default: ${destructured.valueString}${destructured.needSkipFactory ? `, skipFactory: true` : ``}`;
  18477. } else if (hasStaticDefaults) {
  18478. const prop = ctx.propsRuntimeDefaults.properties.find(
  18479. (node) => {
  18480. if (node.type === "SpreadElement") return false;
  18481. return resolveObjectKey(node.key, node.computed) === key;
  18482. }
  18483. );
  18484. if (prop) {
  18485. if (prop.type === "ObjectProperty") {
  18486. defaultString = `default: ${ctx.getString(prop.value)}`;
  18487. } else {
  18488. defaultString = `${prop.async ? "async " : ""}${prop.kind !== "method" ? `${prop.kind} ` : ""}default() ${ctx.getString(prop.body)}`;
  18489. }
  18490. }
  18491. }
  18492. const finalKey = getEscapedPropName(key);
  18493. if (!ctx.options.isProd) {
  18494. return `${finalKey}: { ${concatStrings([
  18495. `type: ${toRuntimeTypeString(type)}`,
  18496. `required: ${required}`,
  18497. skipCheck && "skipCheck: true",
  18498. defaultString
  18499. ])} }`;
  18500. } else if (type.some(
  18501. (el) => el === "Boolean" || (!hasStaticDefaults || defaultString) && el === "Function"
  18502. )) {
  18503. return `${finalKey}: { ${concatStrings([
  18504. `type: ${toRuntimeTypeString(type)}`,
  18505. defaultString
  18506. ])} }`;
  18507. } else {
  18508. if (ctx.isCE) {
  18509. if (defaultString) {
  18510. return `${finalKey}: ${`{ ${defaultString}, type: ${toRuntimeTypeString(
  18511. type
  18512. )} }`}`;
  18513. } else {
  18514. return `${finalKey}: {type: ${toRuntimeTypeString(type)}}`;
  18515. }
  18516. }
  18517. return `${finalKey}: ${defaultString ? `{ ${defaultString} }` : `{}`}`;
  18518. }
  18519. }
  18520. function hasStaticWithDefaults(ctx) {
  18521. return !!(ctx.propsRuntimeDefaults && ctx.propsRuntimeDefaults.type === "ObjectExpression" && ctx.propsRuntimeDefaults.properties.every(
  18522. (node) => node.type !== "SpreadElement" && (!node.computed || node.key.type.endsWith("Literal"))
  18523. ));
  18524. }
  18525. function genDestructuredDefaultValue(ctx, key, inferredType) {
  18526. const destructured = ctx.propsDestructuredBindings[key];
  18527. const defaultVal = destructured && destructured.default;
  18528. if (defaultVal) {
  18529. const value = ctx.getString(defaultVal);
  18530. const unwrapped = CompilerDOM.unwrapTSNode(defaultVal);
  18531. if (inferredType && inferredType.length && !inferredType.includes("null")) {
  18532. const valueType = inferValueType(unwrapped);
  18533. if (valueType && !inferredType.includes(valueType)) {
  18534. ctx.error(
  18535. `Default value of prop "${key}" does not match declared type.`,
  18536. unwrapped
  18537. );
  18538. }
  18539. }
  18540. const needSkipFactory = !inferredType && (CompilerDOM.isFunctionType(unwrapped) || unwrapped.type === "Identifier");
  18541. const needFactoryWrap = !needSkipFactory && !isLiteralNode(unwrapped) && !(inferredType == null ? void 0 : inferredType.includes("Function"));
  18542. return {
  18543. valueString: needFactoryWrap ? `() => (${value})` : value,
  18544. needSkipFactory
  18545. };
  18546. }
  18547. }
  18548. function inferValueType(node) {
  18549. switch (node.type) {
  18550. case "StringLiteral":
  18551. return "String";
  18552. case "NumericLiteral":
  18553. return "Number";
  18554. case "BooleanLiteral":
  18555. return "Boolean";
  18556. case "ObjectExpression":
  18557. return "Object";
  18558. case "ArrayExpression":
  18559. return "Array";
  18560. case "FunctionExpression":
  18561. case "ArrowFunctionExpression":
  18562. return "Function";
  18563. }
  18564. }
  18565. function processPropsDestructure(ctx, declId) {
  18566. if (ctx.options.propsDestructure === "error") {
  18567. ctx.error(`Props destructure is explicitly prohibited via config.`, declId);
  18568. } else if (ctx.options.propsDestructure === false) {
  18569. return;
  18570. }
  18571. ctx.propsDestructureDecl = declId;
  18572. const registerBinding = (key, local, defaultValue) => {
  18573. ctx.propsDestructuredBindings[key] = { local, default: defaultValue };
  18574. if (local !== key) {
  18575. ctx.bindingMetadata[local] = "props-aliased";
  18576. (ctx.bindingMetadata.__propsAliases || (ctx.bindingMetadata.__propsAliases = {}))[local] = key;
  18577. }
  18578. };
  18579. for (const prop of declId.properties) {
  18580. if (prop.type === "ObjectProperty") {
  18581. const propKey = resolveObjectKey(prop.key, prop.computed);
  18582. if (!propKey) {
  18583. ctx.error(
  18584. `${DEFINE_PROPS}() destructure cannot use computed key.`,
  18585. prop.key
  18586. );
  18587. }
  18588. if (prop.value.type === "AssignmentPattern") {
  18589. const { left, right } = prop.value;
  18590. if (left.type !== "Identifier") {
  18591. ctx.error(
  18592. `${DEFINE_PROPS}() destructure does not support nested patterns.`,
  18593. left
  18594. );
  18595. }
  18596. registerBinding(propKey, left.name, right);
  18597. } else if (prop.value.type === "Identifier") {
  18598. registerBinding(propKey, prop.value.name);
  18599. } else {
  18600. ctx.error(
  18601. `${DEFINE_PROPS}() destructure does not support nested patterns.`,
  18602. prop.value
  18603. );
  18604. }
  18605. } else {
  18606. ctx.propsDestructureRestId = prop.argument.name;
  18607. ctx.bindingMetadata[ctx.propsDestructureRestId] = "setup-reactive-const";
  18608. }
  18609. }
  18610. }
  18611. function transformDestructuredProps(ctx, vueImportAliases) {
  18612. if (ctx.options.propsDestructure === false) {
  18613. return;
  18614. }
  18615. const rootScope = /* @__PURE__ */ Object.create(null);
  18616. const scopeStack = [rootScope];
  18617. let currentScope = rootScope;
  18618. const excludedIds = /* @__PURE__ */ new WeakSet();
  18619. const parentStack = [];
  18620. const propsLocalToPublicMap = /* @__PURE__ */ Object.create(null);
  18621. for (const key in ctx.propsDestructuredBindings) {
  18622. const { local } = ctx.propsDestructuredBindings[key];
  18623. rootScope[local] = true;
  18624. propsLocalToPublicMap[local] = key;
  18625. }
  18626. function pushScope() {
  18627. scopeStack.push(currentScope = Object.create(currentScope));
  18628. }
  18629. function popScope() {
  18630. scopeStack.pop();
  18631. currentScope = scopeStack[scopeStack.length - 1] || null;
  18632. }
  18633. function registerLocalBinding(id) {
  18634. excludedIds.add(id);
  18635. if (currentScope) {
  18636. currentScope[id.name] = false;
  18637. } else {
  18638. ctx.error(
  18639. "registerBinding called without active scope, something is wrong.",
  18640. id
  18641. );
  18642. }
  18643. }
  18644. function walkScope(node, isRoot = false) {
  18645. for (const stmt of node.body) {
  18646. if (stmt.type === "VariableDeclaration") {
  18647. walkVariableDeclaration(stmt, isRoot);
  18648. } else if (stmt.type === "FunctionDeclaration" || stmt.type === "ClassDeclaration") {
  18649. if (stmt.declare || !stmt.id) continue;
  18650. registerLocalBinding(stmt.id);
  18651. } else if ((stmt.type === "ForOfStatement" || stmt.type === "ForInStatement") && stmt.left.type === "VariableDeclaration") {
  18652. walkVariableDeclaration(stmt.left);
  18653. } else if (stmt.type === "ExportNamedDeclaration" && stmt.declaration && stmt.declaration.type === "VariableDeclaration") {
  18654. walkVariableDeclaration(stmt.declaration, isRoot);
  18655. } else if (stmt.type === "LabeledStatement" && stmt.body.type === "VariableDeclaration") {
  18656. walkVariableDeclaration(stmt.body, isRoot);
  18657. }
  18658. }
  18659. }
  18660. function walkVariableDeclaration(stmt, isRoot = false) {
  18661. if (stmt.declare) {
  18662. return;
  18663. }
  18664. for (const decl of stmt.declarations) {
  18665. const isDefineProps = isRoot && decl.init && isCallOf(CompilerDOM.unwrapTSNode(decl.init), "defineProps");
  18666. for (const id of CompilerDOM.extractIdentifiers(decl.id)) {
  18667. if (isDefineProps) {
  18668. excludedIds.add(id);
  18669. } else {
  18670. registerLocalBinding(id);
  18671. }
  18672. }
  18673. }
  18674. }
  18675. function rewriteId(id, parent, parentStack2) {
  18676. if (parent.type === "AssignmentExpression" && id === parent.left || parent.type === "UpdateExpression") {
  18677. ctx.error(`Cannot assign to destructured props as they are readonly.`, id);
  18678. }
  18679. if (CompilerDOM.isStaticProperty(parent) && parent.shorthand) {
  18680. if (!parent.inPattern || CompilerDOM.isInDestructureAssignment(parent, parentStack2)) {
  18681. ctx.s.appendLeft(
  18682. id.end + ctx.startOffset,
  18683. `: ${shared.genPropsAccessExp(propsLocalToPublicMap[id.name])}`
  18684. );
  18685. }
  18686. } else {
  18687. ctx.s.overwrite(
  18688. id.start + ctx.startOffset,
  18689. id.end + ctx.startOffset,
  18690. shared.genPropsAccessExp(propsLocalToPublicMap[id.name])
  18691. );
  18692. }
  18693. }
  18694. function checkUsage(node, method, alias = method) {
  18695. if (isCallOf(node, alias)) {
  18696. const arg = CompilerDOM.unwrapTSNode(node.arguments[0]);
  18697. if (arg.type === "Identifier" && currentScope[arg.name]) {
  18698. ctx.error(
  18699. `"${arg.name}" is a destructured prop and should not be passed directly to ${method}(). Pass a getter () => ${arg.name} instead.`,
  18700. arg
  18701. );
  18702. }
  18703. }
  18704. }
  18705. const ast = ctx.scriptSetupAst;
  18706. walkScope(ast, true);
  18707. estreeWalker.walk(ast, {
  18708. enter(node, parent) {
  18709. parent && parentStack.push(parent);
  18710. if (parent && parent.type.startsWith("TS") && !CompilerDOM.TS_NODE_TYPES.includes(parent.type)) {
  18711. return this.skip();
  18712. }
  18713. checkUsage(node, "watch", vueImportAliases.watch);
  18714. checkUsage(node, "toRef", vueImportAliases.toRef);
  18715. if (CompilerDOM.isFunctionType(node)) {
  18716. pushScope();
  18717. CompilerDOM.walkFunctionParams(node, registerLocalBinding);
  18718. if (node.body.type === "BlockStatement") {
  18719. walkScope(node.body);
  18720. }
  18721. return;
  18722. }
  18723. if (node.type === "CatchClause") {
  18724. pushScope();
  18725. if (node.param && node.param.type === "Identifier") {
  18726. registerLocalBinding(node.param);
  18727. }
  18728. walkScope(node.body);
  18729. return;
  18730. }
  18731. if (node.type === "BlockStatement" && !CompilerDOM.isFunctionType(parent)) {
  18732. pushScope();
  18733. walkScope(node);
  18734. return;
  18735. }
  18736. if (node.type === "Identifier") {
  18737. if (CompilerDOM.isReferencedIdentifier(node, parent, parentStack) && !excludedIds.has(node)) {
  18738. if (currentScope[node.name]) {
  18739. rewriteId(node, parent, parentStack);
  18740. }
  18741. }
  18742. }
  18743. },
  18744. leave(node, parent) {
  18745. parent && parentStack.pop();
  18746. if (node.type === "BlockStatement" && !CompilerDOM.isFunctionType(parent) || CompilerDOM.isFunctionType(node)) {
  18747. popScope();
  18748. }
  18749. }
  18750. });
  18751. }
  18752. const DEFINE_EMITS = "defineEmits";
  18753. function processDefineEmits(ctx, node, declId) {
  18754. if (!isCallOf(node, DEFINE_EMITS)) {
  18755. return false;
  18756. }
  18757. if (ctx.hasDefineEmitCall) {
  18758. ctx.error(`duplicate ${DEFINE_EMITS}() call`, node);
  18759. }
  18760. ctx.hasDefineEmitCall = true;
  18761. ctx.emitsRuntimeDecl = node.arguments[0];
  18762. if (node.typeParameters) {
  18763. if (ctx.emitsRuntimeDecl) {
  18764. ctx.error(
  18765. `${DEFINE_EMITS}() cannot accept both type and non-type arguments at the same time. Use one or the other.`,
  18766. node
  18767. );
  18768. }
  18769. ctx.emitsTypeDecl = node.typeParameters.params[0];
  18770. }
  18771. ctx.emitDecl = declId;
  18772. return true;
  18773. }
  18774. function genRuntimeEmits(ctx) {
  18775. let emitsDecl = "";
  18776. if (ctx.emitsRuntimeDecl) {
  18777. emitsDecl = ctx.getString(ctx.emitsRuntimeDecl).trim();
  18778. } else if (ctx.emitsTypeDecl) {
  18779. const typeDeclaredEmits = extractRuntimeEmits(ctx);
  18780. emitsDecl = typeDeclaredEmits.size ? `[${Array.from(typeDeclaredEmits).map((k) => JSON.stringify(k)).join(", ")}]` : ``;
  18781. }
  18782. if (ctx.hasDefineModelCall) {
  18783. let modelEmitsDecl = `[${Object.keys(ctx.modelDecls).map((n) => JSON.stringify(`update:${n}`)).join(", ")}]`;
  18784. emitsDecl = emitsDecl ? `/*@__PURE__*/${ctx.helper(
  18785. "mergeModels"
  18786. )}(${emitsDecl}, ${modelEmitsDecl})` : modelEmitsDecl;
  18787. }
  18788. return emitsDecl;
  18789. }
  18790. function extractRuntimeEmits(ctx) {
  18791. const emits = /* @__PURE__ */ new Set();
  18792. const node = ctx.emitsTypeDecl;
  18793. if (node.type === "TSFunctionType") {
  18794. extractEventNames(ctx, node.parameters[0], emits);
  18795. return emits;
  18796. }
  18797. const { props, calls } = resolveTypeElements(ctx, node);
  18798. let hasProperty = false;
  18799. for (const key in props) {
  18800. emits.add(key);
  18801. hasProperty = true;
  18802. }
  18803. if (calls) {
  18804. if (hasProperty) {
  18805. ctx.error(
  18806. `defineEmits() type cannot mixed call signature and property syntax.`,
  18807. node
  18808. );
  18809. }
  18810. for (const call of calls) {
  18811. extractEventNames(ctx, call.parameters[0], emits);
  18812. }
  18813. }
  18814. return emits;
  18815. }
  18816. function extractEventNames(ctx, eventName, emits) {
  18817. if (eventName.type === "Identifier" && eventName.typeAnnotation && eventName.typeAnnotation.type === "TSTypeAnnotation") {
  18818. const types = resolveUnionType(ctx, eventName.typeAnnotation.typeAnnotation);
  18819. for (const type of types) {
  18820. if (type.type === "TSLiteralType") {
  18821. if (type.literal.type !== "UnaryExpression" && type.literal.type !== "TemplateLiteral") {
  18822. emits.add(String(type.literal.value));
  18823. }
  18824. }
  18825. }
  18826. }
  18827. }
  18828. const DEFINE_EXPOSE = "defineExpose";
  18829. function processDefineExpose(ctx, node) {
  18830. if (isCallOf(node, DEFINE_EXPOSE)) {
  18831. if (ctx.hasDefineExposeCall) {
  18832. ctx.error(`duplicate ${DEFINE_EXPOSE}() call`, node);
  18833. }
  18834. ctx.hasDefineExposeCall = true;
  18835. return true;
  18836. }
  18837. return false;
  18838. }
  18839. const DEFINE_SLOTS = "defineSlots";
  18840. function processDefineSlots(ctx, node, declId) {
  18841. if (!isCallOf(node, DEFINE_SLOTS)) {
  18842. return false;
  18843. }
  18844. if (ctx.hasDefineSlotsCall) {
  18845. ctx.error(`duplicate ${DEFINE_SLOTS}() call`, node);
  18846. }
  18847. ctx.hasDefineSlotsCall = true;
  18848. if (node.arguments.length > 0) {
  18849. ctx.error(`${DEFINE_SLOTS}() cannot accept arguments`, node);
  18850. }
  18851. if (declId) {
  18852. ctx.s.overwrite(
  18853. ctx.startOffset + node.start,
  18854. ctx.startOffset + node.end,
  18855. `${ctx.helper("useSlots")}()`
  18856. );
  18857. }
  18858. return true;
  18859. }
  18860. const DEFINE_OPTIONS = "defineOptions";
  18861. function processDefineOptions(ctx, node) {
  18862. if (!isCallOf(node, DEFINE_OPTIONS)) {
  18863. return false;
  18864. }
  18865. if (ctx.hasDefineOptionsCall) {
  18866. ctx.error(`duplicate ${DEFINE_OPTIONS}() call`, node);
  18867. }
  18868. if (node.typeParameters) {
  18869. ctx.error(`${DEFINE_OPTIONS}() cannot accept type arguments`, node);
  18870. }
  18871. if (!node.arguments[0]) return true;
  18872. ctx.hasDefineOptionsCall = true;
  18873. ctx.optionsRuntimeDecl = CompilerDOM.unwrapTSNode(node.arguments[0]);
  18874. let propsOption = void 0;
  18875. let emitsOption = void 0;
  18876. let exposeOption = void 0;
  18877. let slotsOption = void 0;
  18878. if (ctx.optionsRuntimeDecl.type === "ObjectExpression") {
  18879. for (const prop of ctx.optionsRuntimeDecl.properties) {
  18880. if ((prop.type === "ObjectProperty" || prop.type === "ObjectMethod") && prop.key.type === "Identifier") {
  18881. switch (prop.key.name) {
  18882. case "props":
  18883. propsOption = prop;
  18884. break;
  18885. case "emits":
  18886. emitsOption = prop;
  18887. break;
  18888. case "expose":
  18889. exposeOption = prop;
  18890. break;
  18891. case "slots":
  18892. slotsOption = prop;
  18893. break;
  18894. }
  18895. }
  18896. }
  18897. }
  18898. if (propsOption) {
  18899. ctx.error(
  18900. `${DEFINE_OPTIONS}() cannot be used to declare props. Use ${DEFINE_PROPS}() instead.`,
  18901. propsOption
  18902. );
  18903. }
  18904. if (emitsOption) {
  18905. ctx.error(
  18906. `${DEFINE_OPTIONS}() cannot be used to declare emits. Use ${DEFINE_EMITS}() instead.`,
  18907. emitsOption
  18908. );
  18909. }
  18910. if (exposeOption) {
  18911. ctx.error(
  18912. `${DEFINE_OPTIONS}() cannot be used to declare expose. Use ${DEFINE_EXPOSE}() instead.`,
  18913. exposeOption
  18914. );
  18915. }
  18916. if (slotsOption) {
  18917. ctx.error(
  18918. `${DEFINE_OPTIONS}() cannot be used to declare slots. Use ${DEFINE_SLOTS}() instead.`,
  18919. slotsOption
  18920. );
  18921. }
  18922. return true;
  18923. }
  18924. function processAwait(ctx, node, needSemi, isStatement) {
  18925. const argumentStart = node.argument.extra && node.argument.extra.parenthesized ? node.argument.extra.parenStart : node.argument.start;
  18926. const startOffset = ctx.startOffset;
  18927. const argumentStr = ctx.descriptor.source.slice(
  18928. argumentStart + startOffset,
  18929. node.argument.end + startOffset
  18930. );
  18931. const containsNestedAwait = /\bawait\b/.test(argumentStr);
  18932. ctx.s.overwrite(
  18933. node.start + startOffset,
  18934. argumentStart + startOffset,
  18935. `${needSemi ? `;` : ``}(
  18936. ([__temp,__restore] = ${ctx.helper(
  18937. `withAsyncContext`
  18938. )}(${containsNestedAwait ? `async ` : ``}() => `
  18939. );
  18940. ctx.s.appendLeft(
  18941. node.end + startOffset,
  18942. `)),
  18943. ${isStatement ? `` : `__temp = `}await __temp,
  18944. __restore()${isStatement ? `` : `,
  18945. __temp`}
  18946. )`
  18947. );
  18948. }
  18949. const MACROS = [
  18950. DEFINE_PROPS,
  18951. DEFINE_EMITS,
  18952. DEFINE_EXPOSE,
  18953. DEFINE_OPTIONS,
  18954. DEFINE_SLOTS,
  18955. DEFINE_MODEL,
  18956. WITH_DEFAULTS
  18957. ];
  18958. function compileScript(sfc, options) {
  18959. var _a, _b, _c;
  18960. if (!options.id) {
  18961. warnOnce(
  18962. `compileScript now requires passing the \`id\` option.
  18963. Upgrade your vite or vue-loader version for compatibility with the latest experimental proposals.`
  18964. );
  18965. }
  18966. const ctx = new ScriptCompileContext(sfc, options);
  18967. const { script, scriptSetup, source, filename } = sfc;
  18968. const hoistStatic = options.hoistStatic !== false && !script;
  18969. const scopeId = options.id ? options.id.replace(/^data-v-/, "") : "";
  18970. const scriptLang = script && script.lang;
  18971. const scriptSetupLang = scriptSetup && scriptSetup.lang;
  18972. if (!scriptSetup) {
  18973. if (!script) {
  18974. throw new Error(`[@vue/compiler-sfc] SFC contains no <script> tags.`);
  18975. }
  18976. return processNormalScript(ctx, scopeId);
  18977. }
  18978. if (script && scriptLang !== scriptSetupLang) {
  18979. throw new Error(
  18980. `[@vue/compiler-sfc] <script> and <script setup> must have the same language type.`
  18981. );
  18982. }
  18983. if (scriptSetupLang && !ctx.isJS && !ctx.isTS) {
  18984. return scriptSetup;
  18985. }
  18986. const scriptBindings = /* @__PURE__ */ Object.create(null);
  18987. const setupBindings = /* @__PURE__ */ Object.create(null);
  18988. let defaultExport;
  18989. let hasAwait = false;
  18990. let hasInlinedSsrRenderFn = false;
  18991. const startOffset = ctx.startOffset;
  18992. const endOffset = ctx.endOffset;
  18993. const scriptStartOffset = script && script.loc.start.offset;
  18994. const scriptEndOffset = script && script.loc.end.offset;
  18995. function hoistNode(node) {
  18996. const start = node.start + startOffset;
  18997. let end = node.end + startOffset;
  18998. if (node.trailingComments && node.trailingComments.length > 0) {
  18999. const lastCommentNode = node.trailingComments[node.trailingComments.length - 1];
  19000. end = lastCommentNode.end + startOffset;
  19001. }
  19002. while (end <= source.length) {
  19003. if (!/\s/.test(source.charAt(end))) {
  19004. break;
  19005. }
  19006. end++;
  19007. }
  19008. ctx.s.move(start, end, 0);
  19009. }
  19010. function registerUserImport(source2, local, imported, isType, isFromSetup, needTemplateUsageCheck) {
  19011. let isUsedInTemplate = needTemplateUsageCheck;
  19012. if (needTemplateUsageCheck && ctx.isTS && sfc.template && !sfc.template.src && !sfc.template.lang) {
  19013. isUsedInTemplate = isImportUsed(local, sfc);
  19014. }
  19015. ctx.userImports[local] = {
  19016. isType,
  19017. imported,
  19018. local,
  19019. source: source2,
  19020. isFromSetup,
  19021. isUsedInTemplate
  19022. };
  19023. }
  19024. function checkInvalidScopeReference(node, method) {
  19025. if (!node) return;
  19026. CompilerDOM.walkIdentifiers(node, (id) => {
  19027. const binding = setupBindings[id.name];
  19028. if (binding && binding !== "literal-const") {
  19029. ctx.error(
  19030. `\`${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.`,
  19031. id
  19032. );
  19033. }
  19034. });
  19035. }
  19036. const scriptAst = ctx.scriptAst;
  19037. const scriptSetupAst = ctx.scriptSetupAst;
  19038. if (scriptAst) {
  19039. for (const node of scriptAst.body) {
  19040. if (node.type === "ImportDeclaration") {
  19041. for (const specifier of node.specifiers) {
  19042. const imported = getImportedName(specifier);
  19043. registerUserImport(
  19044. node.source.value,
  19045. specifier.local.name,
  19046. imported,
  19047. node.importKind === "type" || specifier.type === "ImportSpecifier" && specifier.importKind === "type",
  19048. false,
  19049. !options.inlineTemplate
  19050. );
  19051. }
  19052. }
  19053. }
  19054. }
  19055. for (const node of scriptSetupAst.body) {
  19056. if (node.type === "ImportDeclaration") {
  19057. hoistNode(node);
  19058. let removed = 0;
  19059. const removeSpecifier = (i) => {
  19060. const removeLeft = i > removed;
  19061. removed++;
  19062. const current = node.specifiers[i];
  19063. const next = node.specifiers[i + 1];
  19064. ctx.s.remove(
  19065. removeLeft ? node.specifiers[i - 1].end + startOffset : current.start + startOffset,
  19066. next && !removeLeft ? next.start + startOffset : current.end + startOffset
  19067. );
  19068. };
  19069. for (let i = 0; i < node.specifiers.length; i++) {
  19070. const specifier = node.specifiers[i];
  19071. const local = specifier.local.name;
  19072. const imported = getImportedName(specifier);
  19073. const source2 = node.source.value;
  19074. const existing = ctx.userImports[local];
  19075. if (source2 === "vue" && MACROS.includes(imported)) {
  19076. if (local === imported) {
  19077. warnOnce(
  19078. `\`${imported}\` is a compiler macro and no longer needs to be imported.`
  19079. );
  19080. } else {
  19081. ctx.error(
  19082. `\`${imported}\` is a compiler macro and cannot be aliased to a different name.`,
  19083. specifier
  19084. );
  19085. }
  19086. removeSpecifier(i);
  19087. } else if (existing) {
  19088. if (existing.source === source2 && existing.imported === imported) {
  19089. removeSpecifier(i);
  19090. } else {
  19091. ctx.error(
  19092. `different imports aliased to same local name.`,
  19093. specifier
  19094. );
  19095. }
  19096. } else {
  19097. registerUserImport(
  19098. source2,
  19099. local,
  19100. imported,
  19101. node.importKind === "type" || specifier.type === "ImportSpecifier" && specifier.importKind === "type",
  19102. true,
  19103. !options.inlineTemplate
  19104. );
  19105. }
  19106. }
  19107. if (node.specifiers.length && removed === node.specifiers.length) {
  19108. ctx.s.remove(node.start + startOffset, node.end + startOffset);
  19109. }
  19110. }
  19111. }
  19112. const vueImportAliases = {};
  19113. for (const key in ctx.userImports) {
  19114. const { source: source2, imported, local } = ctx.userImports[key];
  19115. if (source2 === "vue") vueImportAliases[imported] = local;
  19116. }
  19117. if (script && scriptAst) {
  19118. for (const node of scriptAst.body) {
  19119. if (node.type === "ExportDefaultDeclaration") {
  19120. defaultExport = node;
  19121. let optionProperties;
  19122. if (defaultExport.declaration.type === "ObjectExpression") {
  19123. optionProperties = defaultExport.declaration.properties;
  19124. } else if (defaultExport.declaration.type === "CallExpression" && defaultExport.declaration.arguments[0] && defaultExport.declaration.arguments[0].type === "ObjectExpression") {
  19125. optionProperties = defaultExport.declaration.arguments[0].properties;
  19126. }
  19127. if (optionProperties) {
  19128. for (const p of optionProperties) {
  19129. if (p.type === "ObjectProperty" && p.key.type === "Identifier" && p.key.name === "name") {
  19130. ctx.hasDefaultExportName = true;
  19131. }
  19132. if ((p.type === "ObjectMethod" || p.type === "ObjectProperty") && p.key.type === "Identifier" && p.key.name === "render") {
  19133. ctx.hasDefaultExportRender = true;
  19134. }
  19135. }
  19136. }
  19137. const start = node.start + scriptStartOffset;
  19138. const end = node.declaration.start + scriptStartOffset;
  19139. ctx.s.overwrite(start, end, `const ${normalScriptDefaultVar} = `);
  19140. } else if (node.type === "ExportNamedDeclaration") {
  19141. const defaultSpecifier = node.specifiers.find(
  19142. (s) => s.exported.type === "Identifier" && s.exported.name === "default"
  19143. );
  19144. if (defaultSpecifier) {
  19145. defaultExport = node;
  19146. if (node.specifiers.length > 1) {
  19147. ctx.s.remove(
  19148. defaultSpecifier.start + scriptStartOffset,
  19149. defaultSpecifier.end + scriptStartOffset
  19150. );
  19151. } else {
  19152. ctx.s.remove(
  19153. node.start + scriptStartOffset,
  19154. node.end + scriptStartOffset
  19155. );
  19156. }
  19157. if (node.source) {
  19158. ctx.s.prepend(
  19159. `import { ${defaultSpecifier.local.name} as ${normalScriptDefaultVar} } from '${node.source.value}'
  19160. `
  19161. );
  19162. } else {
  19163. ctx.s.appendLeft(
  19164. scriptEndOffset,
  19165. `
  19166. const ${normalScriptDefaultVar} = ${defaultSpecifier.local.name}
  19167. `
  19168. );
  19169. }
  19170. }
  19171. if (node.declaration) {
  19172. walkDeclaration(
  19173. "script",
  19174. node.declaration,
  19175. scriptBindings,
  19176. vueImportAliases,
  19177. hoistStatic
  19178. );
  19179. }
  19180. } else if ((node.type === "VariableDeclaration" || node.type === "FunctionDeclaration" || node.type === "ClassDeclaration" || node.type === "TSEnumDeclaration") && !node.declare) {
  19181. walkDeclaration(
  19182. "script",
  19183. node,
  19184. scriptBindings,
  19185. vueImportAliases,
  19186. hoistStatic
  19187. );
  19188. }
  19189. }
  19190. if (scriptStartOffset > startOffset) {
  19191. if (!/\n$/.test(script.content.trim())) {
  19192. ctx.s.appendLeft(scriptEndOffset, `
  19193. `);
  19194. }
  19195. ctx.s.move(scriptStartOffset, scriptEndOffset, 0);
  19196. }
  19197. }
  19198. for (const node of scriptSetupAst.body) {
  19199. if (node.type === "ExpressionStatement") {
  19200. const expr = CompilerDOM.unwrapTSNode(node.expression);
  19201. if (processDefineProps(ctx, expr) || processDefineEmits(ctx, expr) || processDefineOptions(ctx, expr) || processDefineSlots(ctx, expr)) {
  19202. ctx.s.remove(node.start + startOffset, node.end + startOffset);
  19203. } else if (processDefineExpose(ctx, expr)) {
  19204. const callee = expr.callee;
  19205. ctx.s.overwrite(
  19206. callee.start + startOffset,
  19207. callee.end + startOffset,
  19208. "__expose"
  19209. );
  19210. } else {
  19211. processDefineModel(ctx, expr);
  19212. }
  19213. }
  19214. if (node.type === "VariableDeclaration" && !node.declare) {
  19215. const total = node.declarations.length;
  19216. let left = total;
  19217. let lastNonRemoved;
  19218. for (let i = 0; i < total; i++) {
  19219. const decl = node.declarations[i];
  19220. const init = decl.init && CompilerDOM.unwrapTSNode(decl.init);
  19221. if (init) {
  19222. if (processDefineOptions(ctx, init)) {
  19223. ctx.error(
  19224. `${DEFINE_OPTIONS}() has no returning value, it cannot be assigned.`,
  19225. node
  19226. );
  19227. }
  19228. const isDefineProps = processDefineProps(ctx, init, decl.id);
  19229. if (ctx.propsDestructureRestId) {
  19230. setupBindings[ctx.propsDestructureRestId] = "setup-reactive-const";
  19231. }
  19232. const isDefineEmits = !isDefineProps && processDefineEmits(ctx, init, decl.id);
  19233. !isDefineEmits && (processDefineSlots(ctx, init, decl.id) || processDefineModel(ctx, init, decl.id));
  19234. if (isDefineProps && !ctx.propsDestructureRestId && ctx.propsDestructureDecl) {
  19235. if (left === 1) {
  19236. ctx.s.remove(node.start + startOffset, node.end + startOffset);
  19237. } else {
  19238. let start = decl.start + startOffset;
  19239. let end = decl.end + startOffset;
  19240. if (i === total - 1) {
  19241. start = node.declarations[lastNonRemoved].end + startOffset;
  19242. } else {
  19243. end = node.declarations[i + 1].start + startOffset;
  19244. }
  19245. ctx.s.remove(start, end);
  19246. left--;
  19247. }
  19248. } else if (isDefineEmits) {
  19249. ctx.s.overwrite(
  19250. startOffset + init.start,
  19251. startOffset + init.end,
  19252. "__emit"
  19253. );
  19254. } else {
  19255. lastNonRemoved = i;
  19256. }
  19257. }
  19258. }
  19259. }
  19260. let isAllLiteral = false;
  19261. if ((node.type === "VariableDeclaration" || node.type === "FunctionDeclaration" || node.type === "ClassDeclaration" || node.type === "TSEnumDeclaration") && !node.declare) {
  19262. isAllLiteral = walkDeclaration(
  19263. "scriptSetup",
  19264. node,
  19265. setupBindings,
  19266. vueImportAliases,
  19267. hoistStatic,
  19268. !!ctx.propsDestructureDecl
  19269. );
  19270. }
  19271. if (hoistStatic && isAllLiteral) {
  19272. hoistNode(node);
  19273. }
  19274. if (node.type === "VariableDeclaration" && !node.declare || node.type.endsWith("Statement")) {
  19275. const scope = [scriptSetupAst.body];
  19276. estreeWalker.walk(node, {
  19277. enter(child, parent) {
  19278. if (CompilerDOM.isFunctionType(child)) {
  19279. this.skip();
  19280. }
  19281. if (child.type === "BlockStatement") {
  19282. scope.push(child.body);
  19283. }
  19284. if (child.type === "AwaitExpression") {
  19285. hasAwait = true;
  19286. const currentScope = scope[scope.length - 1];
  19287. const needsSemi = currentScope.some((n, i) => {
  19288. return (scope.length === 1 || i > 0) && n.type === "ExpressionStatement" && n.start === child.start;
  19289. });
  19290. processAwait(
  19291. ctx,
  19292. child,
  19293. needsSemi,
  19294. parent.type === "ExpressionStatement"
  19295. );
  19296. }
  19297. },
  19298. exit(node2) {
  19299. if (node2.type === "BlockStatement") scope.pop();
  19300. }
  19301. });
  19302. }
  19303. if (node.type === "ExportNamedDeclaration" && node.exportKind !== "type" || node.type === "ExportAllDeclaration" || node.type === "ExportDefaultDeclaration") {
  19304. ctx.error(
  19305. `<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.`,
  19306. node
  19307. );
  19308. }
  19309. if (ctx.isTS) {
  19310. if (node.type.startsWith("TS") || node.type === "ExportNamedDeclaration" && node.exportKind === "type" || node.type === "VariableDeclaration" && node.declare) {
  19311. if (node.type !== "TSEnumDeclaration") {
  19312. hoistNode(node);
  19313. }
  19314. }
  19315. }
  19316. }
  19317. if (ctx.propsDestructureDecl) {
  19318. transformDestructuredProps(ctx, vueImportAliases);
  19319. }
  19320. checkInvalidScopeReference(ctx.propsRuntimeDecl, DEFINE_PROPS);
  19321. checkInvalidScopeReference(ctx.propsRuntimeDefaults, DEFINE_PROPS);
  19322. checkInvalidScopeReference(ctx.propsDestructureDecl, DEFINE_PROPS);
  19323. checkInvalidScopeReference(ctx.emitsRuntimeDecl, DEFINE_EMITS);
  19324. checkInvalidScopeReference(ctx.optionsRuntimeDecl, DEFINE_OPTIONS);
  19325. for (const { runtimeOptionNodes } of Object.values(ctx.modelDecls)) {
  19326. for (const node of runtimeOptionNodes) {
  19327. checkInvalidScopeReference(node, DEFINE_MODEL);
  19328. }
  19329. }
  19330. if (script) {
  19331. if (startOffset < scriptStartOffset) {
  19332. ctx.s.remove(0, startOffset);
  19333. ctx.s.remove(endOffset, scriptStartOffset);
  19334. ctx.s.remove(scriptEndOffset, source.length);
  19335. } else {
  19336. ctx.s.remove(0, scriptStartOffset);
  19337. ctx.s.remove(scriptEndOffset, startOffset);
  19338. ctx.s.remove(endOffset, source.length);
  19339. }
  19340. } else {
  19341. ctx.s.remove(0, startOffset);
  19342. ctx.s.remove(endOffset, source.length);
  19343. }
  19344. if (scriptAst) {
  19345. Object.assign(ctx.bindingMetadata, analyzeScriptBindings(scriptAst.body));
  19346. }
  19347. for (const [key, { isType, imported, source: source2 }] of Object.entries(
  19348. ctx.userImports
  19349. )) {
  19350. if (isType) continue;
  19351. ctx.bindingMetadata[key] = imported === "*" || imported === "default" && source2.endsWith(".vue") || source2 === "vue" ? "setup-const" : "setup-maybe-ref";
  19352. }
  19353. for (const key in scriptBindings) {
  19354. ctx.bindingMetadata[key] = scriptBindings[key];
  19355. }
  19356. for (const key in setupBindings) {
  19357. ctx.bindingMetadata[key] = setupBindings[key];
  19358. }
  19359. if (sfc.cssVars.length && // no need to do this when targeting SSR
  19360. !((_a = options.templateOptions) == null ? void 0 : _a.ssr)) {
  19361. ctx.helperImports.add(CSS_VARS_HELPER);
  19362. ctx.helperImports.add("unref");
  19363. ctx.s.prependLeft(
  19364. startOffset,
  19365. `
  19366. ${genCssVarsCode(
  19367. sfc.cssVars,
  19368. ctx.bindingMetadata,
  19369. scopeId,
  19370. !!options.isProd
  19371. )}
  19372. `
  19373. );
  19374. }
  19375. let args = `__props`;
  19376. if (ctx.propsTypeDecl) {
  19377. args += `: any`;
  19378. }
  19379. if (ctx.propsDecl) {
  19380. if (ctx.propsDestructureRestId) {
  19381. ctx.s.overwrite(
  19382. startOffset + ctx.propsCall.start,
  19383. startOffset + ctx.propsCall.end,
  19384. `${ctx.helper(`createPropsRestProxy`)}(__props, ${JSON.stringify(
  19385. Object.keys(ctx.propsDestructuredBindings)
  19386. )})`
  19387. );
  19388. ctx.s.overwrite(
  19389. startOffset + ctx.propsDestructureDecl.start,
  19390. startOffset + ctx.propsDestructureDecl.end,
  19391. ctx.propsDestructureRestId
  19392. );
  19393. } else if (!ctx.propsDestructureDecl) {
  19394. ctx.s.overwrite(
  19395. startOffset + ctx.propsCall.start,
  19396. startOffset + ctx.propsCall.end,
  19397. "__props"
  19398. );
  19399. }
  19400. }
  19401. if (hasAwait) {
  19402. const any = ctx.isTS ? `: any` : ``;
  19403. ctx.s.prependLeft(startOffset, `
  19404. let __temp${any}, __restore${any}
  19405. `);
  19406. }
  19407. const destructureElements = ctx.hasDefineExposeCall || !options.inlineTemplate ? [`expose: __expose`] : [];
  19408. if (ctx.emitDecl) {
  19409. destructureElements.push(`emit: __emit`);
  19410. }
  19411. if (destructureElements.length) {
  19412. args += `, { ${destructureElements.join(", ")} }`;
  19413. }
  19414. let returned;
  19415. if (!options.inlineTemplate || !sfc.template && ctx.hasDefaultExportRender) {
  19416. const allBindings = {
  19417. ...scriptBindings,
  19418. ...setupBindings
  19419. };
  19420. for (const key in ctx.userImports) {
  19421. if (!ctx.userImports[key].isType && ctx.userImports[key].isUsedInTemplate) {
  19422. allBindings[key] = true;
  19423. }
  19424. }
  19425. returned = `{ `;
  19426. for (const key in allBindings) {
  19427. if (allBindings[key] === true && ctx.userImports[key].source !== "vue" && !ctx.userImports[key].source.endsWith(".vue")) {
  19428. returned += `get ${key}() { return ${key} }, `;
  19429. } else if (ctx.bindingMetadata[key] === "setup-let") {
  19430. const setArg = key === "v" ? `_v` : `v`;
  19431. returned += `get ${key}() { return ${key} }, set ${key}(${setArg}) { ${key} = ${setArg} }, `;
  19432. } else {
  19433. returned += `${key}, `;
  19434. }
  19435. }
  19436. returned = returned.replace(/, $/, "") + ` }`;
  19437. } else {
  19438. if (sfc.template && !sfc.template.src) {
  19439. if (options.templateOptions && options.templateOptions.ssr) {
  19440. hasInlinedSsrRenderFn = true;
  19441. }
  19442. const { code, ast, preamble, tips, errors } = compileTemplate({
  19443. filename,
  19444. ast: sfc.template.ast,
  19445. source: sfc.template.content,
  19446. inMap: sfc.template.map,
  19447. ...options.templateOptions,
  19448. id: scopeId,
  19449. scoped: sfc.styles.some((s) => s.scoped),
  19450. isProd: options.isProd,
  19451. ssrCssVars: sfc.cssVars,
  19452. compilerOptions: {
  19453. ...options.templateOptions && options.templateOptions.compilerOptions,
  19454. inline: true,
  19455. isTS: ctx.isTS,
  19456. bindingMetadata: ctx.bindingMetadata
  19457. }
  19458. });
  19459. if (tips.length) {
  19460. tips.forEach(warnOnce);
  19461. }
  19462. const err = errors[0];
  19463. if (typeof err === "string") {
  19464. throw new Error(err);
  19465. } else if (err) {
  19466. if (err.loc) {
  19467. err.message += `
  19468. ` + sfc.filename + "\n" + shared.generateCodeFrame(
  19469. source,
  19470. err.loc.start.offset,
  19471. err.loc.end.offset
  19472. ) + `
  19473. `;
  19474. }
  19475. throw err;
  19476. }
  19477. if (preamble) {
  19478. ctx.s.prepend(preamble);
  19479. }
  19480. if (ast && ast.helpers.has(CompilerDOM.UNREF)) {
  19481. ctx.helperImports.delete("unref");
  19482. }
  19483. returned = code;
  19484. } else {
  19485. returned = `() => {}`;
  19486. }
  19487. }
  19488. if (!options.inlineTemplate && true) {
  19489. ctx.s.appendRight(
  19490. endOffset,
  19491. `
  19492. const __returned__ = ${returned}
  19493. Object.defineProperty(__returned__, '__isScriptSetup', { enumerable: false, value: true })
  19494. return __returned__
  19495. }
  19496. `
  19497. );
  19498. } else {
  19499. ctx.s.appendRight(endOffset, `
  19500. return ${returned}
  19501. }
  19502. `);
  19503. }
  19504. const genDefaultAs = options.genDefaultAs ? `const ${options.genDefaultAs} =` : `export default`;
  19505. let runtimeOptions = ``;
  19506. if (!ctx.hasDefaultExportName && filename && filename !== DEFAULT_FILENAME) {
  19507. const match = filename.match(/([^/\\]+)\.\w+$/);
  19508. if (match) {
  19509. runtimeOptions += `
  19510. __name: '${match[1]}',`;
  19511. }
  19512. }
  19513. if (hasInlinedSsrRenderFn) {
  19514. runtimeOptions += `
  19515. __ssrInlineRender: true,`;
  19516. }
  19517. const propsDecl = genRuntimeProps(ctx);
  19518. if (propsDecl) runtimeOptions += `
  19519. props: ${propsDecl},`;
  19520. const emitsDecl = genRuntimeEmits(ctx);
  19521. if (emitsDecl) runtimeOptions += `
  19522. emits: ${emitsDecl},`;
  19523. let definedOptions = "";
  19524. if (ctx.optionsRuntimeDecl) {
  19525. definedOptions = scriptSetup.content.slice(ctx.optionsRuntimeDecl.start, ctx.optionsRuntimeDecl.end).trim();
  19526. }
  19527. const exposeCall = ctx.hasDefineExposeCall || options.inlineTemplate ? `` : ` __expose();
  19528. `;
  19529. if (ctx.isTS) {
  19530. const def = (defaultExport ? `
  19531. ...${normalScriptDefaultVar},` : ``) + (definedOptions ? `
  19532. ...${definedOptions},` : "");
  19533. ctx.s.prependLeft(
  19534. startOffset,
  19535. `
  19536. ${genDefaultAs} /*@__PURE__*/${ctx.helper(
  19537. `defineComponent`
  19538. )}({${def}${runtimeOptions}
  19539. ${hasAwait ? `async ` : ``}setup(${args}) {
  19540. ${exposeCall}`
  19541. );
  19542. ctx.s.appendRight(endOffset, `})`);
  19543. } else {
  19544. if (defaultExport || definedOptions) {
  19545. ctx.s.prependLeft(
  19546. startOffset,
  19547. `
  19548. ${genDefaultAs} /*@__PURE__*/Object.assign(${defaultExport ? `${normalScriptDefaultVar}, ` : ""}${definedOptions ? `${definedOptions}, ` : ""}{${runtimeOptions}
  19549. ${hasAwait ? `async ` : ``}setup(${args}) {
  19550. ${exposeCall}`
  19551. );
  19552. ctx.s.appendRight(endOffset, `})`);
  19553. } else {
  19554. ctx.s.prependLeft(
  19555. startOffset,
  19556. `
  19557. ${genDefaultAs} {${runtimeOptions}
  19558. ${hasAwait ? `async ` : ``}setup(${args}) {
  19559. ${exposeCall}`
  19560. );
  19561. ctx.s.appendRight(endOffset, `}`);
  19562. }
  19563. }
  19564. if (ctx.helperImports.size > 0) {
  19565. const runtimeModuleName = (_c = (_b = options.templateOptions) == null ? void 0 : _b.compilerOptions) == null ? void 0 : _c.runtimeModuleName;
  19566. const importSrc = runtimeModuleName ? JSON.stringify(runtimeModuleName) : `'vue'`;
  19567. ctx.s.prepend(
  19568. `import { ${[...ctx.helperImports].map((h) => `${h} as _${h}`).join(", ")} } from ${importSrc}
  19569. `
  19570. );
  19571. }
  19572. return {
  19573. ...scriptSetup,
  19574. bindings: ctx.bindingMetadata,
  19575. imports: ctx.userImports,
  19576. content: ctx.s.toString(),
  19577. map: options.sourceMap !== false ? ctx.s.generateMap({
  19578. source: filename,
  19579. hires: true,
  19580. includeContent: true
  19581. }) : void 0,
  19582. scriptAst: scriptAst == null ? void 0 : scriptAst.body,
  19583. scriptSetupAst: scriptSetupAst == null ? void 0 : scriptSetupAst.body,
  19584. deps: ctx.deps ? [...ctx.deps] : void 0
  19585. };
  19586. }
  19587. function registerBinding(bindings, node, type) {
  19588. bindings[node.name] = type;
  19589. }
  19590. function walkDeclaration(from, node, bindings, userImportAliases, hoistStatic, isPropsDestructureEnabled = false) {
  19591. let isAllLiteral = false;
  19592. if (node.type === "VariableDeclaration") {
  19593. const isConst = node.kind === "const";
  19594. isAllLiteral = isConst && node.declarations.every(
  19595. (decl) => decl.id.type === "Identifier" && isStaticNode(decl.init)
  19596. );
  19597. for (const { id, init: _init } of node.declarations) {
  19598. const init = _init && CompilerDOM.unwrapTSNode(_init);
  19599. const isConstMacroCall = isConst && isCallOf(
  19600. init,
  19601. (c) => c === DEFINE_PROPS || c === DEFINE_EMITS || c === WITH_DEFAULTS || c === DEFINE_SLOTS
  19602. );
  19603. if (id.type === "Identifier") {
  19604. let bindingType;
  19605. const userReactiveBinding = userImportAliases["reactive"];
  19606. if ((hoistStatic || from === "script") && (isAllLiteral || isConst && isStaticNode(init))) {
  19607. bindingType = "literal-const";
  19608. } else if (isCallOf(init, userReactiveBinding)) {
  19609. bindingType = isConst ? "setup-reactive-const" : "setup-let";
  19610. } else if (
  19611. // if a declaration is a const literal, we can mark it so that
  19612. // the generated render fn code doesn't need to unref() it
  19613. isConstMacroCall || isConst && canNeverBeRef(init, userReactiveBinding)
  19614. ) {
  19615. bindingType = isCallOf(init, DEFINE_PROPS) ? "setup-reactive-const" : "setup-const";
  19616. } else if (isConst) {
  19617. if (isCallOf(
  19618. init,
  19619. (m) => m === userImportAliases["ref"] || m === userImportAliases["computed"] || m === userImportAliases["shallowRef"] || m === userImportAliases["customRef"] || m === userImportAliases["toRef"] || m === DEFINE_MODEL
  19620. )) {
  19621. bindingType = "setup-ref";
  19622. } else {
  19623. bindingType = "setup-maybe-ref";
  19624. }
  19625. } else {
  19626. bindingType = "setup-let";
  19627. }
  19628. registerBinding(bindings, id, bindingType);
  19629. } else {
  19630. if (isCallOf(init, DEFINE_PROPS) && isPropsDestructureEnabled) {
  19631. continue;
  19632. }
  19633. if (id.type === "ObjectPattern") {
  19634. walkObjectPattern(id, bindings, isConst, isConstMacroCall);
  19635. } else if (id.type === "ArrayPattern") {
  19636. walkArrayPattern(id, bindings, isConst, isConstMacroCall);
  19637. }
  19638. }
  19639. }
  19640. } else if (node.type === "TSEnumDeclaration") {
  19641. isAllLiteral = node.members.every(
  19642. (member) => !member.initializer || isStaticNode(member.initializer)
  19643. );
  19644. bindings[node.id.name] = isAllLiteral ? "literal-const" : "setup-const";
  19645. } else if (node.type === "FunctionDeclaration" || node.type === "ClassDeclaration") {
  19646. bindings[node.id.name] = "setup-const";
  19647. }
  19648. return isAllLiteral;
  19649. }
  19650. function walkObjectPattern(node, bindings, isConst, isDefineCall = false) {
  19651. for (const p of node.properties) {
  19652. if (p.type === "ObjectProperty") {
  19653. if (p.key.type === "Identifier" && p.key === p.value) {
  19654. const type = isDefineCall ? "setup-const" : isConst ? "setup-maybe-ref" : "setup-let";
  19655. registerBinding(bindings, p.key, type);
  19656. } else {
  19657. walkPattern(p.value, bindings, isConst, isDefineCall);
  19658. }
  19659. } else {
  19660. const type = isConst ? "setup-const" : "setup-let";
  19661. registerBinding(bindings, p.argument, type);
  19662. }
  19663. }
  19664. }
  19665. function walkArrayPattern(node, bindings, isConst, isDefineCall = false) {
  19666. for (const e of node.elements) {
  19667. e && walkPattern(e, bindings, isConst, isDefineCall);
  19668. }
  19669. }
  19670. function walkPattern(node, bindings, isConst, isDefineCall = false) {
  19671. if (node.type === "Identifier") {
  19672. const type = isDefineCall ? "setup-const" : isConst ? "setup-maybe-ref" : "setup-let";
  19673. registerBinding(bindings, node, type);
  19674. } else if (node.type === "RestElement") {
  19675. const type = isConst ? "setup-const" : "setup-let";
  19676. registerBinding(bindings, node.argument, type);
  19677. } else if (node.type === "ObjectPattern") {
  19678. walkObjectPattern(node, bindings, isConst);
  19679. } else if (node.type === "ArrayPattern") {
  19680. walkArrayPattern(node, bindings, isConst);
  19681. } else if (node.type === "AssignmentPattern") {
  19682. if (node.left.type === "Identifier") {
  19683. const type = isDefineCall ? "setup-const" : isConst ? "setup-maybe-ref" : "setup-let";
  19684. registerBinding(bindings, node.left, type);
  19685. } else {
  19686. walkPattern(node.left, bindings, isConst);
  19687. }
  19688. }
  19689. }
  19690. function canNeverBeRef(node, userReactiveImport) {
  19691. if (isCallOf(node, userReactiveImport)) {
  19692. return true;
  19693. }
  19694. switch (node.type) {
  19695. case "UnaryExpression":
  19696. case "BinaryExpression":
  19697. case "ArrayExpression":
  19698. case "ObjectExpression":
  19699. case "FunctionExpression":
  19700. case "ArrowFunctionExpression":
  19701. case "UpdateExpression":
  19702. case "ClassExpression":
  19703. case "TaggedTemplateExpression":
  19704. return true;
  19705. case "SequenceExpression":
  19706. return canNeverBeRef(
  19707. node.expressions[node.expressions.length - 1],
  19708. userReactiveImport
  19709. );
  19710. default:
  19711. if (isLiteralNode(node)) {
  19712. return true;
  19713. }
  19714. return false;
  19715. }
  19716. }
  19717. function isStaticNode(node) {
  19718. node = CompilerDOM.unwrapTSNode(node);
  19719. switch (node.type) {
  19720. case "UnaryExpression":
  19721. return isStaticNode(node.argument);
  19722. case "LogicalExpression":
  19723. // 1 > 2
  19724. case "BinaryExpression":
  19725. return isStaticNode(node.left) && isStaticNode(node.right);
  19726. case "ConditionalExpression": {
  19727. return isStaticNode(node.test) && isStaticNode(node.consequent) && isStaticNode(node.alternate);
  19728. }
  19729. case "SequenceExpression":
  19730. // (1, 2)
  19731. case "TemplateLiteral":
  19732. return node.expressions.every((expr) => isStaticNode(expr));
  19733. case "ParenthesizedExpression":
  19734. return isStaticNode(node.expression);
  19735. case "StringLiteral":
  19736. case "NumericLiteral":
  19737. case "BooleanLiteral":
  19738. case "NullLiteral":
  19739. case "BigIntLiteral":
  19740. return true;
  19741. }
  19742. return false;
  19743. }
  19744. const version = "3.5.12";
  19745. const parseCache = parseCache$1;
  19746. const errorMessages = {
  19747. ...CompilerDOM.errorMessages,
  19748. ...CompilerDOM.DOMErrorMessages
  19749. };
  19750. const walk = estreeWalker.walk;
  19751. const shouldTransformRef = () => false;
  19752. exports.extractIdentifiers = compilerCore.extractIdentifiers;
  19753. exports.generateCodeFrame = compilerCore.generateCodeFrame;
  19754. exports.isInDestructureAssignment = compilerCore.isInDestructureAssignment;
  19755. exports.isStaticProperty = compilerCore.isStaticProperty;
  19756. exports.walkIdentifiers = compilerCore.walkIdentifiers;
  19757. exports.MagicString = MagicString;
  19758. exports.babelParse = parser$1.parse;
  19759. exports.compileScript = compileScript;
  19760. exports.compileStyle = compileStyle;
  19761. exports.compileStyleAsync = compileStyleAsync;
  19762. exports.compileTemplate = compileTemplate;
  19763. exports.errorMessages = errorMessages;
  19764. exports.extractRuntimeEmits = extractRuntimeEmits;
  19765. exports.extractRuntimeProps = extractRuntimeProps;
  19766. exports.inferRuntimeType = inferRuntimeType;
  19767. exports.invalidateTypeCache = invalidateTypeCache;
  19768. exports.parse = parse$1;
  19769. exports.parseCache = parseCache;
  19770. exports.registerTS = registerTS;
  19771. exports.resolveTypeElements = resolveTypeElements;
  19772. exports.rewriteDefault = rewriteDefault;
  19773. exports.rewriteDefaultAST = rewriteDefaultAST;
  19774. exports.shouldTransformRef = shouldTransformRef;
  19775. exports.version = version;
  19776. exports.walk = walk;