compiler-sfc.cjs.js 649 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320732173227323732473257326732773287329733073317332733373347335733673377338733973407341734273437344734573467347734873497350735173527353735473557356735773587359736073617362736373647365736673677368736973707371737273737374737573767377737873797380738173827383738473857386738773887389739073917392739373947395739673977398739974007401740274037404740574067407740874097410741174127413741474157416741774187419742074217422742374247425742674277428742974307431743274337434743574367437743874397440744174427443744474457446744774487449745074517452745374547455745674577458745974607461746274637464746574667467746874697470747174727473747474757476747774787479748074817482748374847485748674877488748974907491749274937494749574967497749874997500750175027503750475057506750775087509751075117512751375147515751675177518751975207521752275237524752575267527752875297530753175327533753475357536753775387539754075417542754375447545754675477548754975507551755275537554755575567557755875597560756175627563756475657566756775687569757075717572757375747575757675777578757975807581758275837584758575867587758875897590759175927593759475957596759775987599760076017602760376047605760676077608760976107611761276137614761576167617761876197620762176227623762476257626762776287629763076317632763376347635763676377638763976407641764276437644764576467647764876497650765176527653765476557656765776587659766076617662766376647665766676677668766976707671767276737674767576767677767876797680768176827683768476857686768776887689769076917692769376947695769676977698769977007701770277037704770577067707770877097710771177127713771477157716771777187719772077217722772377247725772677277728772977307731773277337734773577367737773877397740774177427743774477457746774777487749775077517752775377547755775677577758775977607761776277637764776577667767776877697770777177727773777477757776777777787779778077817782778377847785778677877788778977907791779277937794779577967797779877997800780178027803780478057806780778087809781078117812781378147815781678177818781978207821782278237824782578267827782878297830783178327833783478357836783778387839784078417842784378447845784678477848784978507851785278537854785578567857785878597860786178627863786478657866786778687869787078717872787378747875787678777878787978807881788278837884788578867887788878897890789178927893789478957896789778987899790079017902790379047905790679077908790979107911791279137914791579167917791879197920792179227923792479257926792779287929793079317932793379347935793679377938793979407941794279437944794579467947794879497950795179527953795479557956795779587959796079617962796379647965796679677968796979707971797279737974797579767977797879797980798179827983798479857986798779887989799079917992799379947995799679977998799980008001800280038004800580068007800880098010801180128013801480158016801780188019802080218022802380248025802680278028802980308031803280338034803580368037803880398040804180428043804480458046804780488049805080518052805380548055805680578058805980608061806280638064806580668067806880698070807180728073807480758076807780788079808080818082808380848085808680878088808980908091809280938094809580968097809880998100810181028103810481058106810781088109811081118112811381148115811681178118811981208121812281238124812581268127812881298130813181328133813481358136813781388139814081418142814381448145814681478148814981508151815281538154815581568157815881598160816181628163816481658166816781688169817081718172817381748175817681778178817981808181818281838184818581868187818881898190819181928193819481958196819781988199820082018202820382048205820682078208820982108211821282138214821582168217821882198220822182228223822482258226822782288229823082318232823382348235823682378238823982408241824282438244824582468247824882498250825182528253825482558256825782588259826082618262826382648265826682678268826982708271827282738274827582768277827882798280828182828283828482858286828782888289829082918292829382948295829682978298829983008301830283038304830583068307830883098310831183128313831483158316831783188319832083218322832383248325832683278328832983308331833283338334833583368337833883398340834183428343834483458346834783488349835083518352835383548355835683578358835983608361836283638364836583668367836883698370837183728373837483758376837783788379838083818382838383848385838683878388838983908391839283938394839583968397839883998400840184028403840484058406840784088409841084118412841384148415841684178418841984208421842284238424842584268427842884298430843184328433843484358436843784388439844084418442844384448445844684478448844984508451845284538454845584568457845884598460846184628463846484658466846784688469847084718472847384748475847684778478847984808481848284838484848584868487848884898490849184928493849484958496849784988499850085018502850385048505850685078508850985108511851285138514851585168517851885198520852185228523852485258526852785288529853085318532853385348535853685378538853985408541854285438544854585468547854885498550855185528553855485558556855785588559856085618562856385648565856685678568856985708571857285738574857585768577857885798580858185828583858485858586858785888589859085918592859385948595859685978598859986008601860286038604860586068607860886098610861186128613861486158616861786188619862086218622862386248625862686278628862986308631863286338634863586368637863886398640864186428643864486458646864786488649865086518652865386548655865686578658865986608661866286638664866586668667866886698670867186728673867486758676867786788679868086818682868386848685868686878688868986908691869286938694869586968697869886998700870187028703870487058706870787088709871087118712871387148715871687178718871987208721872287238724872587268727872887298730873187328733873487358736873787388739874087418742874387448745874687478748874987508751875287538754875587568757875887598760876187628763876487658766876787688769877087718772877387748775877687778778877987808781878287838784878587868787878887898790879187928793879487958796879787988799880088018802880388048805880688078808880988108811881288138814881588168817881888198820882188228823882488258826882788288829883088318832883388348835883688378838883988408841884288438844884588468847884888498850885188528853885488558856885788588859886088618862886388648865886688678868886988708871887288738874887588768877887888798880888188828883888488858886888788888889889088918892889388948895889688978898889989008901890289038904890589068907890889098910891189128913891489158916891789188919892089218922892389248925892689278928892989308931893289338934893589368937893889398940894189428943894489458946894789488949895089518952895389548955895689578958895989608961896289638964896589668967896889698970897189728973897489758976897789788979898089818982898389848985898689878988898989908991899289938994899589968997899889999000900190029003900490059006900790089009901090119012901390149015901690179018901990209021902290239024902590269027902890299030903190329033903490359036903790389039904090419042904390449045904690479048904990509051905290539054905590569057905890599060906190629063906490659066906790689069907090719072907390749075907690779078907990809081908290839084908590869087908890899090909190929093909490959096909790989099910091019102910391049105910691079108910991109111911291139114911591169117911891199120912191229123912491259126912791289129913091319132913391349135913691379138913991409141914291439144914591469147914891499150915191529153915491559156915791589159916091619162916391649165916691679168916991709171917291739174917591769177917891799180918191829183918491859186918791889189919091919192919391949195919691979198919992009201920292039204920592069207920892099210921192129213921492159216921792189219922092219222922392249225922692279228922992309231923292339234923592369237923892399240924192429243924492459246924792489249925092519252925392549255925692579258925992609261926292639264926592669267926892699270927192729273927492759276927792789279928092819282928392849285928692879288928992909291929292939294929592969297929892999300930193029303930493059306930793089309931093119312931393149315931693179318931993209321932293239324932593269327932893299330933193329333933493359336933793389339934093419342934393449345934693479348934993509351935293539354935593569357935893599360936193629363936493659366936793689369937093719372937393749375937693779378937993809381938293839384938593869387938893899390939193929393939493959396939793989399940094019402940394049405940694079408940994109411941294139414941594169417941894199420942194229423942494259426942794289429943094319432943394349435943694379438943994409441944294439444944594469447944894499450945194529453945494559456945794589459946094619462946394649465946694679468946994709471947294739474947594769477947894799480948194829483948494859486948794889489949094919492949394949495949694979498949995009501950295039504950595069507950895099510951195129513951495159516951795189519952095219522952395249525952695279528952995309531953295339534953595369537953895399540954195429543954495459546954795489549955095519552955395549555955695579558955995609561956295639564956595669567956895699570957195729573957495759576957795789579958095819582958395849585958695879588958995909591959295939594959595969597959895999600960196029603960496059606960796089609961096119612961396149615961696179618961996209621962296239624962596269627962896299630963196329633963496359636963796389639964096419642964396449645964696479648964996509651965296539654965596569657965896599660966196629663966496659666966796689669967096719672967396749675967696779678967996809681968296839684968596869687968896899690969196929693969496959696969796989699970097019702970397049705970697079708970997109711971297139714971597169717971897199720972197229723972497259726972797289729973097319732973397349735973697379738973997409741974297439744974597469747974897499750975197529753975497559756975797589759976097619762976397649765976697679768976997709771977297739774977597769777977897799780978197829783978497859786978797889789979097919792979397949795979697979798979998009801980298039804980598069807980898099810981198129813981498159816981798189819982098219822982398249825982698279828982998309831983298339834983598369837983898399840984198429843984498459846984798489849985098519852985398549855985698579858985998609861986298639864986598669867986898699870987198729873987498759876987798789879988098819882988398849885988698879888988998909891989298939894989598969897989898999900990199029903990499059906990799089909991099119912991399149915991699179918991999209921992299239924992599269927992899299930993199329933993499359936993799389939994099419942994399449945994699479948994999509951995299539954995599569957995899599960996199629963996499659966996799689969997099719972997399749975997699779978997999809981998299839984998599869987998899899990999199929993999499959996999799989999100001000110002100031000410005100061000710008100091001010011100121001310014100151001610017100181001910020100211002210023100241002510026100271002810029100301003110032100331003410035100361003710038100391004010041100421004310044100451004610047100481004910050100511005210053100541005510056100571005810059100601006110062100631006410065100661006710068100691007010071100721007310074100751007610077100781007910080100811008210083100841008510086100871008810089100901009110092100931009410095100961009710098100991010010101101021010310104101051010610107101081010910110101111011210113101141011510116101171011810119101201012110122101231012410125101261012710128101291013010131101321013310134101351013610137101381013910140101411014210143101441014510146101471014810149101501015110152101531015410155101561015710158101591016010161101621016310164101651016610167101681016910170101711017210173101741017510176101771017810179101801018110182101831018410185101861018710188101891019010191101921019310194101951019610197101981019910200102011020210203102041020510206102071020810209102101021110212102131021410215102161021710218102191022010221102221022310224102251022610227102281022910230102311023210233102341023510236102371023810239102401024110242102431024410245102461024710248102491025010251102521025310254102551025610257102581025910260102611026210263102641026510266102671026810269102701027110272102731027410275102761027710278102791028010281102821028310284102851028610287102881028910290102911029210293102941029510296102971029810299103001030110302103031030410305103061030710308103091031010311103121031310314103151031610317103181031910320103211032210323103241032510326103271032810329103301033110332103331033410335103361033710338103391034010341103421034310344103451034610347103481034910350103511035210353103541035510356103571035810359103601036110362103631036410365103661036710368103691037010371103721037310374103751037610377103781037910380103811038210383103841038510386103871038810389103901039110392103931039410395103961039710398103991040010401104021040310404104051040610407104081040910410104111041210413104141041510416104171041810419104201042110422104231042410425104261042710428104291043010431104321043310434104351043610437104381043910440104411044210443104441044510446104471044810449104501045110452104531045410455104561045710458104591046010461104621046310464104651046610467104681046910470104711047210473104741047510476104771047810479104801048110482104831048410485104861048710488104891049010491104921049310494104951049610497104981049910500105011050210503105041050510506105071050810509105101051110512105131051410515105161051710518105191052010521105221052310524105251052610527105281052910530105311053210533105341053510536105371053810539105401054110542105431054410545105461054710548105491055010551105521055310554105551055610557105581055910560105611056210563105641056510566105671056810569105701057110572105731057410575105761057710578105791058010581105821058310584105851058610587105881058910590105911059210593105941059510596105971059810599106001060110602106031060410605106061060710608106091061010611106121061310614106151061610617106181061910620106211062210623106241062510626106271062810629106301063110632106331063410635106361063710638106391064010641106421064310644106451064610647106481064910650106511065210653106541065510656106571065810659106601066110662106631066410665106661066710668106691067010671106721067310674106751067610677106781067910680106811068210683106841068510686106871068810689106901069110692106931069410695106961069710698106991070010701107021070310704107051070610707107081070910710107111071210713107141071510716107171071810719107201072110722107231072410725107261072710728107291073010731107321073310734107351073610737107381073910740107411074210743107441074510746107471074810749107501075110752107531075410755107561075710758107591076010761107621076310764107651076610767107681076910770107711077210773107741077510776107771077810779107801078110782107831078410785107861078710788107891079010791107921079310794107951079610797107981079910800108011080210803108041080510806108071080810809108101081110812108131081410815108161081710818108191082010821108221082310824108251082610827108281082910830108311083210833108341083510836108371083810839108401084110842108431084410845108461084710848108491085010851108521085310854108551085610857108581085910860108611086210863108641086510866108671086810869108701087110872108731087410875108761087710878108791088010881108821088310884108851088610887108881088910890108911089210893108941089510896108971089810899109001090110902109031090410905109061090710908109091091010911109121091310914109151091610917109181091910920109211092210923109241092510926109271092810929109301093110932109331093410935109361093710938109391094010941109421094310944109451094610947109481094910950109511095210953109541095510956109571095810959109601096110962109631096410965109661096710968109691097010971109721097310974109751097610977109781097910980109811098210983109841098510986109871098810989109901099110992109931099410995109961099710998109991100011001110021100311004110051100611007110081100911010110111101211013110141101511016110171101811019110201102111022110231102411025110261102711028110291103011031110321103311034110351103611037110381103911040110411104211043110441104511046110471104811049110501105111052110531105411055110561105711058110591106011061110621106311064110651106611067110681106911070110711107211073110741107511076110771107811079110801108111082110831108411085110861108711088110891109011091110921109311094110951109611097110981109911100111011110211103111041110511106111071110811109111101111111112111131111411115111161111711118111191112011121111221112311124111251112611127111281112911130111311113211133111341113511136111371113811139111401114111142111431114411145111461114711148111491115011151111521115311154111551115611157111581115911160111611116211163111641116511166111671116811169111701117111172111731117411175111761117711178111791118011181111821118311184111851118611187111881118911190111911119211193111941119511196111971119811199112001120111202112031120411205112061120711208112091121011211112121121311214112151121611217112181121911220112211122211223112241122511226112271122811229112301123111232112331123411235112361123711238112391124011241112421124311244112451124611247112481124911250112511125211253112541125511256112571125811259112601126111262112631126411265112661126711268112691127011271112721127311274112751127611277112781127911280112811128211283112841128511286112871128811289112901129111292112931129411295112961129711298112991130011301113021130311304113051130611307113081130911310113111131211313113141131511316113171131811319113201132111322113231132411325113261132711328113291133011331113321133311334113351133611337113381133911340113411134211343113441134511346113471134811349113501135111352113531135411355113561135711358113591136011361113621136311364113651136611367113681136911370113711137211373113741137511376113771137811379113801138111382113831138411385113861138711388113891139011391113921139311394113951139611397113981139911400114011140211403114041140511406114071140811409114101141111412114131141411415114161141711418114191142011421114221142311424114251142611427114281142911430114311143211433114341143511436114371143811439114401144111442114431144411445114461144711448114491145011451114521145311454114551145611457114581145911460114611146211463114641146511466114671146811469114701147111472114731147411475114761147711478114791148011481114821148311484114851148611487114881148911490114911149211493114941149511496114971149811499115001150111502115031150411505115061150711508115091151011511115121151311514115151151611517115181151911520115211152211523115241152511526115271152811529115301153111532115331153411535115361153711538115391154011541115421154311544115451154611547115481154911550115511155211553115541155511556115571155811559115601156111562115631156411565115661156711568115691157011571115721157311574115751157611577115781157911580115811158211583115841158511586115871158811589115901159111592115931159411595115961159711598115991160011601116021160311604116051160611607116081160911610116111161211613116141161511616116171161811619116201162111622116231162411625116261162711628116291163011631116321163311634116351163611637116381163911640116411164211643116441164511646116471164811649116501165111652116531165411655116561165711658116591166011661116621166311664116651166611667116681166911670116711167211673116741167511676116771167811679116801168111682116831168411685116861168711688116891169011691116921169311694116951169611697116981169911700117011170211703117041170511706117071170811709117101171111712117131171411715117161171711718117191172011721117221172311724117251172611727117281172911730117311173211733117341173511736117371173811739117401174111742117431174411745117461174711748117491175011751117521175311754117551175611757117581175911760117611176211763117641176511766117671176811769117701177111772117731177411775117761177711778117791178011781117821178311784117851178611787117881178911790117911179211793117941179511796117971179811799118001180111802118031180411805118061180711808118091181011811118121181311814118151181611817118181181911820118211182211823118241182511826118271182811829118301183111832118331183411835118361183711838118391184011841118421184311844118451184611847118481184911850118511185211853118541185511856118571185811859118601186111862118631186411865118661186711868118691187011871118721187311874118751187611877118781187911880118811188211883118841188511886118871188811889118901189111892118931189411895118961189711898118991190011901119021190311904119051190611907119081190911910119111191211913119141191511916119171191811919119201192111922119231192411925119261192711928119291193011931119321193311934119351193611937119381193911940119411194211943119441194511946119471194811949119501195111952119531195411955119561195711958119591196011961119621196311964119651196611967119681196911970119711197211973119741197511976119771197811979119801198111982119831198411985119861198711988119891199011991119921199311994119951199611997119981199912000120011200212003120041200512006120071200812009120101201112012120131201412015120161201712018120191202012021120221202312024120251202612027120281202912030120311203212033120341203512036120371203812039120401204112042120431204412045120461204712048120491205012051120521205312054120551205612057120581205912060120611206212063120641206512066120671206812069120701207112072120731207412075120761207712078120791208012081120821208312084120851208612087120881208912090120911209212093120941209512096120971209812099121001210112102121031210412105121061210712108121091211012111121121211312114121151211612117121181211912120121211212212123121241212512126121271212812129121301213112132121331213412135121361213712138121391214012141121421214312144121451214612147121481214912150121511215212153121541215512156121571215812159121601216112162121631216412165121661216712168121691217012171121721217312174121751217612177121781217912180121811218212183121841218512186121871218812189121901219112192121931219412195121961219712198121991220012201122021220312204122051220612207122081220912210122111221212213122141221512216122171221812219122201222112222122231222412225122261222712228122291223012231122321223312234122351223612237122381223912240122411224212243122441224512246122471224812249122501225112252122531225412255122561225712258122591226012261122621226312264122651226612267122681226912270122711227212273122741227512276122771227812279122801228112282122831228412285122861228712288122891229012291122921229312294122951229612297122981229912300123011230212303123041230512306123071230812309123101231112312123131231412315123161231712318123191232012321123221232312324123251232612327123281232912330123311233212333123341233512336123371233812339123401234112342123431234412345123461234712348123491235012351123521235312354123551235612357123581235912360123611236212363123641236512366123671236812369123701237112372123731237412375123761237712378123791238012381123821238312384123851238612387123881238912390123911239212393123941239512396123971239812399124001240112402124031240412405124061240712408124091241012411124121241312414124151241612417124181241912420124211242212423124241242512426124271242812429124301243112432124331243412435124361243712438124391244012441124421244312444124451244612447124481244912450124511245212453124541245512456124571245812459124601246112462124631246412465124661246712468124691247012471124721247312474124751247612477124781247912480124811248212483124841248512486124871248812489124901249112492124931249412495124961249712498124991250012501125021250312504125051250612507125081250912510125111251212513125141251512516125171251812519125201252112522125231252412525125261252712528125291253012531125321253312534125351253612537125381253912540125411254212543125441254512546125471254812549125501255112552125531255412555125561255712558125591256012561125621256312564125651256612567125681256912570125711257212573125741257512576125771257812579125801258112582125831258412585125861258712588125891259012591125921259312594125951259612597125981259912600126011260212603126041260512606126071260812609126101261112612126131261412615126161261712618126191262012621126221262312624126251262612627126281262912630126311263212633126341263512636126371263812639126401264112642126431264412645126461264712648126491265012651126521265312654126551265612657126581265912660126611266212663126641266512666126671266812669126701267112672126731267412675126761267712678126791268012681126821268312684126851268612687126881268912690126911269212693126941269512696126971269812699127001270112702127031270412705127061270712708127091271012711127121271312714127151271612717127181271912720127211272212723127241272512726127271272812729127301273112732127331273412735127361273712738127391274012741127421274312744127451274612747127481274912750127511275212753127541275512756127571275812759127601276112762127631276412765127661276712768127691277012771127721277312774127751277612777127781277912780127811278212783127841278512786127871278812789127901279112792127931279412795127961279712798127991280012801128021280312804128051280612807128081280912810128111281212813128141281512816128171281812819128201282112822128231282412825128261282712828128291283012831128321283312834128351283612837128381283912840128411284212843128441284512846128471284812849128501285112852128531285412855128561285712858128591286012861128621286312864128651286612867128681286912870128711287212873128741287512876128771287812879128801288112882128831288412885128861288712888128891289012891128921289312894128951289612897128981289912900129011290212903129041290512906129071290812909129101291112912129131291412915129161291712918129191292012921129221292312924129251292612927129281292912930129311293212933129341293512936129371293812939129401294112942129431294412945129461294712948129491295012951129521295312954129551295612957129581295912960129611296212963129641296512966129671296812969129701297112972129731297412975129761297712978129791298012981129821298312984129851298612987129881298912990129911299212993129941299512996129971299812999130001300113002130031300413005130061300713008130091301013011130121301313014130151301613017130181301913020130211302213023130241302513026130271302813029130301303113032130331303413035130361303713038130391304013041130421304313044130451304613047130481304913050130511305213053130541305513056130571305813059130601306113062130631306413065130661306713068130691307013071130721307313074130751307613077130781307913080130811308213083130841308513086130871308813089130901309113092130931309413095130961309713098130991310013101131021310313104131051310613107131081310913110131111311213113131141311513116131171311813119131201312113122131231312413125131261312713128131291313013131131321313313134131351313613137131381313913140131411314213143131441314513146131471314813149131501315113152131531315413155131561315713158131591316013161131621316313164131651316613167131681316913170131711317213173131741317513176131771317813179131801318113182131831318413185131861318713188131891319013191131921319313194131951319613197131981319913200132011320213203132041320513206132071320813209132101321113212132131321413215132161321713218132191322013221132221322313224132251322613227132281322913230132311323213233132341323513236132371323813239132401324113242132431324413245132461324713248132491325013251132521325313254132551325613257132581325913260132611326213263132641326513266132671326813269132701327113272132731327413275132761327713278132791328013281132821328313284132851328613287132881328913290132911329213293132941329513296132971329813299133001330113302133031330413305133061330713308133091331013311133121331313314133151331613317133181331913320133211332213323133241332513326133271332813329133301333113332133331333413335133361333713338133391334013341133421334313344133451334613347133481334913350133511335213353133541335513356133571335813359133601336113362133631336413365133661336713368133691337013371133721337313374133751337613377133781337913380133811338213383133841338513386133871338813389133901339113392133931339413395133961339713398133991340013401134021340313404134051340613407134081340913410134111341213413134141341513416134171341813419134201342113422134231342413425134261342713428134291343013431134321343313434134351343613437134381343913440134411344213443134441344513446134471344813449134501345113452134531345413455134561345713458134591346013461134621346313464134651346613467134681346913470134711347213473134741347513476134771347813479134801348113482134831348413485134861348713488134891349013491134921349313494134951349613497134981349913500135011350213503135041350513506135071350813509135101351113512135131351413515135161351713518135191352013521135221352313524135251352613527135281352913530135311353213533135341353513536135371353813539135401354113542135431354413545135461354713548135491355013551135521355313554135551355613557135581355913560135611356213563135641356513566135671356813569135701357113572135731357413575135761357713578135791358013581135821358313584135851358613587135881358913590135911359213593135941359513596135971359813599136001360113602136031360413605136061360713608136091361013611136121361313614136151361613617136181361913620136211362213623136241362513626136271362813629136301363113632136331363413635136361363713638136391364013641136421364313644136451364613647136481364913650136511365213653136541365513656136571365813659136601366113662136631366413665136661366713668136691367013671136721367313674136751367613677136781367913680136811368213683136841368513686136871368813689136901369113692136931369413695136961369713698136991370013701137021370313704137051370613707137081370913710137111371213713137141371513716137171371813719137201372113722137231372413725137261372713728137291373013731137321373313734137351373613737137381373913740137411374213743137441374513746137471374813749137501375113752137531375413755137561375713758137591376013761137621376313764137651376613767137681376913770137711377213773137741377513776137771377813779137801378113782137831378413785137861378713788137891379013791137921379313794137951379613797137981379913800138011380213803138041380513806138071380813809138101381113812138131381413815138161381713818138191382013821138221382313824138251382613827138281382913830138311383213833138341383513836138371383813839138401384113842138431384413845138461384713848138491385013851138521385313854138551385613857138581385913860138611386213863138641386513866138671386813869138701387113872138731387413875138761387713878138791388013881138821388313884138851388613887138881388913890138911389213893138941389513896138971389813899139001390113902139031390413905139061390713908139091391013911139121391313914139151391613917139181391913920139211392213923139241392513926139271392813929139301393113932139331393413935139361393713938139391394013941139421394313944139451394613947139481394913950139511395213953139541395513956139571395813959139601396113962139631396413965139661396713968139691397013971139721397313974139751397613977139781397913980139811398213983139841398513986139871398813989139901399113992139931399413995139961399713998139991400014001140021400314004140051400614007140081400914010140111401214013140141401514016140171401814019140201402114022140231402414025140261402714028140291403014031140321403314034140351403614037140381403914040140411404214043140441404514046140471404814049140501405114052140531405414055140561405714058140591406014061140621406314064140651406614067140681406914070140711407214073140741407514076140771407814079140801408114082140831408414085140861408714088140891409014091140921409314094140951409614097140981409914100141011410214103141041410514106141071410814109141101411114112141131411414115141161411714118141191412014121141221412314124141251412614127141281412914130141311413214133141341413514136141371413814139141401414114142141431414414145141461414714148141491415014151141521415314154141551415614157141581415914160141611416214163141641416514166141671416814169141701417114172141731417414175141761417714178141791418014181141821418314184141851418614187141881418914190141911419214193141941419514196141971419814199142001420114202142031420414205142061420714208142091421014211142121421314214142151421614217142181421914220142211422214223142241422514226142271422814229142301423114232142331423414235142361423714238142391424014241142421424314244142451424614247142481424914250142511425214253142541425514256142571425814259142601426114262142631426414265142661426714268142691427014271142721427314274142751427614277142781427914280142811428214283142841428514286142871428814289142901429114292142931429414295142961429714298142991430014301143021430314304143051430614307143081430914310143111431214313143141431514316143171431814319143201432114322143231432414325143261432714328143291433014331143321433314334143351433614337143381433914340143411434214343143441434514346143471434814349143501435114352143531435414355143561435714358143591436014361143621436314364143651436614367143681436914370143711437214373143741437514376143771437814379143801438114382143831438414385143861438714388143891439014391143921439314394143951439614397143981439914400144011440214403144041440514406144071440814409144101441114412144131441414415144161441714418144191442014421144221442314424144251442614427144281442914430144311443214433144341443514436144371443814439144401444114442144431444414445144461444714448144491445014451144521445314454144551445614457144581445914460144611446214463144641446514466144671446814469144701447114472144731447414475144761447714478144791448014481144821448314484144851448614487144881448914490144911449214493144941449514496144971449814499145001450114502145031450414505145061450714508145091451014511145121451314514145151451614517145181451914520145211452214523145241452514526145271452814529145301453114532145331453414535145361453714538145391454014541145421454314544145451454614547145481454914550145511455214553145541455514556145571455814559145601456114562145631456414565145661456714568145691457014571145721457314574145751457614577145781457914580145811458214583145841458514586145871458814589145901459114592145931459414595145961459714598145991460014601146021460314604146051460614607146081460914610146111461214613146141461514616146171461814619146201462114622146231462414625146261462714628146291463014631146321463314634146351463614637146381463914640146411464214643146441464514646146471464814649146501465114652146531465414655146561465714658146591466014661146621466314664146651466614667146681466914670146711467214673146741467514676146771467814679146801468114682146831468414685146861468714688146891469014691146921469314694146951469614697146981469914700147011470214703147041470514706147071470814709147101471114712147131471414715147161471714718147191472014721147221472314724147251472614727147281472914730147311473214733147341473514736147371473814739147401474114742147431474414745147461474714748147491475014751147521475314754147551475614757147581475914760147611476214763147641476514766147671476814769147701477114772147731477414775147761477714778147791478014781147821478314784147851478614787147881478914790147911479214793147941479514796147971479814799148001480114802148031480414805148061480714808148091481014811148121481314814148151481614817148181481914820148211482214823148241482514826148271482814829148301483114832148331483414835148361483714838148391484014841148421484314844148451484614847148481484914850148511485214853148541485514856148571485814859148601486114862148631486414865148661486714868148691487014871148721487314874148751487614877148781487914880148811488214883148841488514886148871488814889148901489114892148931489414895148961489714898148991490014901149021490314904149051490614907149081490914910149111491214913149141491514916149171491814919149201492114922149231492414925149261492714928149291493014931149321493314934149351493614937149381493914940149411494214943149441494514946149471494814949149501495114952149531495414955149561495714958149591496014961149621496314964149651496614967149681496914970149711497214973149741497514976149771497814979149801498114982149831498414985149861498714988149891499014991149921499314994149951499614997149981499915000150011500215003150041500515006150071500815009150101501115012150131501415015150161501715018150191502015021150221502315024150251502615027150281502915030150311503215033150341503515036150371503815039150401504115042150431504415045150461504715048150491505015051150521505315054150551505615057150581505915060150611506215063150641506515066150671506815069150701507115072150731507415075150761507715078150791508015081150821508315084150851508615087150881508915090150911509215093150941509515096150971509815099151001510115102151031510415105151061510715108151091511015111151121511315114151151511615117151181511915120151211512215123151241512515126151271512815129151301513115132151331513415135151361513715138151391514015141151421514315144151451514615147151481514915150151511515215153151541515515156151571515815159151601516115162151631516415165151661516715168151691517015171151721517315174151751517615177151781517915180151811518215183151841518515186151871518815189151901519115192151931519415195151961519715198151991520015201152021520315204152051520615207152081520915210152111521215213152141521515216152171521815219152201522115222152231522415225152261522715228152291523015231152321523315234152351523615237152381523915240152411524215243152441524515246152471524815249152501525115252152531525415255152561525715258152591526015261152621526315264152651526615267152681526915270152711527215273152741527515276152771527815279152801528115282152831528415285152861528715288152891529015291152921529315294152951529615297152981529915300153011530215303153041530515306153071530815309153101531115312153131531415315153161531715318153191532015321153221532315324153251532615327153281532915330153311533215333153341533515336153371533815339153401534115342153431534415345153461534715348153491535015351153521535315354153551535615357153581535915360153611536215363153641536515366153671536815369153701537115372153731537415375153761537715378153791538015381153821538315384153851538615387153881538915390153911539215393153941539515396153971539815399154001540115402154031540415405154061540715408154091541015411154121541315414154151541615417154181541915420154211542215423154241542515426154271542815429154301543115432154331543415435154361543715438154391544015441154421544315444154451544615447154481544915450154511545215453154541545515456154571545815459154601546115462154631546415465154661546715468154691547015471154721547315474154751547615477154781547915480154811548215483154841548515486154871548815489154901549115492154931549415495154961549715498154991550015501155021550315504155051550615507155081550915510155111551215513155141551515516155171551815519155201552115522155231552415525155261552715528155291553015531155321553315534155351553615537155381553915540155411554215543155441554515546155471554815549155501555115552155531555415555155561555715558155591556015561155621556315564155651556615567155681556915570155711557215573155741557515576155771557815579155801558115582155831558415585155861558715588155891559015591155921559315594155951559615597155981559915600156011560215603156041560515606156071560815609156101561115612156131561415615156161561715618156191562015621156221562315624156251562615627156281562915630156311563215633156341563515636156371563815639156401564115642156431564415645156461564715648156491565015651156521565315654156551565615657156581565915660156611566215663156641566515666156671566815669156701567115672156731567415675156761567715678156791568015681156821568315684156851568615687156881568915690156911569215693156941569515696156971569815699157001570115702157031570415705157061570715708157091571015711157121571315714157151571615717157181571915720157211572215723157241572515726157271572815729157301573115732157331573415735157361573715738157391574015741157421574315744157451574615747157481574915750157511575215753157541575515756157571575815759157601576115762157631576415765157661576715768157691577015771157721577315774157751577615777157781577915780157811578215783157841578515786157871578815789157901579115792157931579415795157961579715798157991580015801158021580315804158051580615807158081580915810158111581215813158141581515816158171581815819158201582115822158231582415825158261582715828158291583015831158321583315834158351583615837158381583915840158411584215843158441584515846158471584815849158501585115852158531585415855158561585715858158591586015861158621586315864158651586615867158681586915870158711587215873158741587515876158771587815879158801588115882158831588415885158861588715888158891589015891158921589315894158951589615897158981589915900159011590215903159041590515906159071590815909159101591115912159131591415915159161591715918159191592015921159221592315924159251592615927159281592915930159311593215933159341593515936159371593815939159401594115942159431594415945159461594715948159491595015951159521595315954159551595615957159581595915960159611596215963159641596515966159671596815969159701597115972159731597415975159761597715978159791598015981159821598315984159851598615987159881598915990159911599215993159941599515996159971599815999160001600116002160031600416005160061600716008160091601016011160121601316014160151601616017160181601916020160211602216023160241602516026160271602816029160301603116032160331603416035160361603716038160391604016041160421604316044160451604616047160481604916050160511605216053160541605516056160571605816059160601606116062160631606416065160661606716068160691607016071160721607316074160751607616077160781607916080160811608216083160841608516086160871608816089160901609116092160931609416095160961609716098160991610016101161021610316104161051610616107161081610916110161111611216113161141611516116161171611816119161201612116122161231612416125161261612716128161291613016131161321613316134161351613616137161381613916140161411614216143161441614516146161471614816149161501615116152161531615416155161561615716158161591616016161161621616316164161651616616167161681616916170161711617216173161741617516176161771617816179161801618116182161831618416185161861618716188161891619016191161921619316194161951619616197161981619916200162011620216203162041620516206162071620816209162101621116212162131621416215162161621716218162191622016221162221622316224162251622616227162281622916230162311623216233162341623516236162371623816239162401624116242162431624416245162461624716248162491625016251162521625316254162551625616257162581625916260162611626216263162641626516266162671626816269162701627116272162731627416275162761627716278162791628016281162821628316284162851628616287162881628916290162911629216293162941629516296162971629816299163001630116302163031630416305163061630716308163091631016311163121631316314163151631616317163181631916320163211632216323163241632516326163271632816329163301633116332163331633416335163361633716338163391634016341163421634316344163451634616347163481634916350163511635216353163541635516356163571635816359163601636116362163631636416365163661636716368163691637016371163721637316374163751637616377163781637916380163811638216383163841638516386163871638816389163901639116392163931639416395163961639716398163991640016401164021640316404164051640616407164081640916410164111641216413164141641516416164171641816419164201642116422164231642416425164261642716428164291643016431164321643316434164351643616437164381643916440164411644216443164441644516446164471644816449164501645116452164531645416455164561645716458164591646016461164621646316464164651646616467164681646916470164711647216473164741647516476164771647816479164801648116482164831648416485164861648716488164891649016491164921649316494164951649616497164981649916500165011650216503165041650516506165071650816509165101651116512165131651416515165161651716518165191652016521165221652316524165251652616527165281652916530165311653216533165341653516536165371653816539165401654116542165431654416545165461654716548165491655016551165521655316554165551655616557165581655916560165611656216563165641656516566165671656816569165701657116572165731657416575165761657716578165791658016581165821658316584165851658616587165881658916590165911659216593165941659516596165971659816599166001660116602166031660416605166061660716608166091661016611166121661316614166151661616617166181661916620166211662216623166241662516626166271662816629166301663116632166331663416635166361663716638166391664016641166421664316644166451664616647166481664916650166511665216653166541665516656166571665816659166601666116662166631666416665166661666716668166691667016671166721667316674166751667616677166781667916680166811668216683166841668516686166871668816689166901669116692166931669416695166961669716698166991670016701167021670316704167051670616707167081670916710167111671216713167141671516716167171671816719167201672116722167231672416725167261672716728167291673016731167321673316734167351673616737167381673916740167411674216743167441674516746167471674816749167501675116752167531675416755167561675716758167591676016761167621676316764167651676616767167681676916770167711677216773167741677516776167771677816779167801678116782167831678416785167861678716788167891679016791167921679316794167951679616797167981679916800168011680216803168041680516806168071680816809168101681116812168131681416815168161681716818168191682016821168221682316824168251682616827168281682916830168311683216833168341683516836168371683816839168401684116842168431684416845168461684716848168491685016851168521685316854168551685616857168581685916860168611686216863168641686516866168671686816869168701687116872168731687416875168761687716878168791688016881168821688316884168851688616887168881688916890168911689216893168941689516896168971689816899169001690116902169031690416905169061690716908169091691016911169121691316914169151691616917169181691916920169211692216923169241692516926169271692816929169301693116932169331693416935169361693716938169391694016941169421694316944169451694616947169481694916950169511695216953169541695516956169571695816959169601696116962169631696416965169661696716968169691697016971169721697316974169751697616977169781697916980169811698216983169841698516986169871698816989169901699116992169931699416995169961699716998169991700017001170021700317004170051700617007170081700917010170111701217013170141701517016170171701817019170201702117022170231702417025170261702717028170291703017031170321703317034170351703617037170381703917040170411704217043170441704517046170471704817049170501705117052170531705417055170561705717058170591706017061170621706317064170651706617067170681706917070170711707217073170741707517076170771707817079170801708117082170831708417085170861708717088170891709017091170921709317094170951709617097170981709917100171011710217103171041710517106171071710817109171101711117112171131711417115171161711717118171191712017121171221712317124171251712617127171281712917130171311713217133171341713517136171371713817139171401714117142171431714417145171461714717148171491715017151171521715317154171551715617157171581715917160171611716217163171641716517166171671716817169171701717117172171731717417175171761717717178171791718017181171821718317184171851718617187171881718917190171911719217193171941719517196171971719817199172001720117202172031720417205172061720717208172091721017211172121721317214172151721617217172181721917220172211722217223172241722517226172271722817229172301723117232172331723417235172361723717238172391724017241172421724317244172451724617247172481724917250172511725217253172541725517256172571725817259172601726117262172631726417265172661726717268172691727017271172721727317274172751727617277172781727917280172811728217283172841728517286172871728817289172901729117292172931729417295172961729717298172991730017301173021730317304173051730617307173081730917310173111731217313173141731517316173171731817319173201732117322173231732417325173261732717328173291733017331173321733317334173351733617337173381733917340173411734217343173441734517346173471734817349173501735117352173531735417355173561735717358173591736017361173621736317364173651736617367173681736917370173711737217373173741737517376173771737817379173801738117382173831738417385173861738717388173891739017391173921739317394173951739617397173981739917400174011740217403174041740517406174071740817409174101741117412174131741417415174161741717418174191742017421174221742317424174251742617427174281742917430174311743217433174341743517436174371743817439174401744117442174431744417445174461744717448174491745017451174521745317454174551745617457174581745917460174611746217463174641746517466174671746817469174701747117472174731747417475174761747717478174791748017481174821748317484174851748617487174881748917490174911749217493174941749517496174971749817499175001750117502175031750417505175061750717508175091751017511175121751317514175151751617517175181751917520175211752217523175241752517526175271752817529175301753117532175331753417535175361753717538175391754017541175421754317544175451754617547175481754917550175511755217553175541755517556175571755817559175601756117562175631756417565175661756717568175691757017571175721757317574175751757617577175781757917580175811758217583175841758517586175871758817589175901759117592175931759417595175961759717598175991760017601176021760317604176051760617607176081760917610176111761217613176141761517616176171761817619176201762117622176231762417625176261762717628176291763017631176321763317634176351763617637176381763917640176411764217643176441764517646176471764817649176501765117652176531765417655176561765717658176591766017661176621766317664176651766617667176681766917670176711767217673176741767517676176771767817679176801768117682176831768417685176861768717688176891769017691176921769317694176951769617697176981769917700177011770217703177041770517706177071770817709177101771117712177131771417715177161771717718177191772017721177221772317724177251772617727177281772917730177311773217733177341773517736177371773817739177401774117742177431774417745177461774717748177491775017751177521775317754177551775617757177581775917760177611776217763177641776517766177671776817769177701777117772177731777417775177761777717778177791778017781177821778317784177851778617787177881778917790177911779217793177941779517796177971779817799178001780117802178031780417805178061780717808178091781017811178121781317814178151781617817178181781917820178211782217823178241782517826178271782817829178301783117832178331783417835178361783717838178391784017841178421784317844178451784617847178481784917850178511785217853178541785517856178571785817859178601786117862178631786417865178661786717868178691787017871178721787317874178751787617877178781787917880178811788217883178841788517886178871788817889178901789117892178931789417895178961789717898178991790017901179021790317904179051790617907179081790917910179111791217913179141791517916179171791817919179201792117922179231792417925179261792717928179291793017931179321793317934179351793617937179381793917940179411794217943179441794517946179471794817949179501795117952179531795417955179561795717958179591796017961179621796317964179651796617967179681796917970179711797217973179741797517976179771797817979179801798117982179831798417985179861798717988179891799017991179921799317994179951799617997179981799918000180011800218003180041800518006180071800818009180101801118012180131801418015180161801718018180191802018021180221802318024180251802618027180281802918030180311803218033180341803518036180371803818039180401804118042180431804418045180461804718048180491805018051180521805318054180551805618057180581805918060180611806218063180641806518066180671806818069180701807118072180731807418075180761807718078180791808018081180821808318084180851808618087180881808918090180911809218093180941809518096180971809818099181001810118102181031810418105181061810718108181091811018111181121811318114181151811618117181181811918120181211812218123181241812518126181271812818129181301813118132181331813418135181361813718138181391814018141181421814318144181451814618147181481814918150181511815218153181541815518156181571815818159181601816118162181631816418165181661816718168181691817018171181721817318174181751817618177181781817918180181811818218183181841818518186181871818818189181901819118192181931819418195181961819718198181991820018201182021820318204182051820618207182081820918210182111821218213182141821518216182171821818219182201822118222182231822418225182261822718228182291823018231182321823318234182351823618237182381823918240182411824218243182441824518246182471824818249182501825118252182531825418255182561825718258182591826018261182621826318264182651826618267182681826918270182711827218273182741827518276182771827818279182801828118282182831828418285182861828718288182891829018291182921829318294182951829618297182981829918300183011830218303183041830518306183071830818309183101831118312183131831418315183161831718318183191832018321183221832318324183251832618327183281832918330183311833218333183341833518336183371833818339183401834118342183431834418345183461834718348183491835018351183521835318354183551835618357183581835918360183611836218363183641836518366183671836818369183701837118372183731837418375183761837718378183791838018381183821838318384183851838618387183881838918390183911839218393183941839518396183971839818399184001840118402184031840418405184061840718408184091841018411184121841318414184151841618417184181841918420184211842218423184241842518426184271842818429184301843118432184331843418435184361843718438184391844018441184421844318444184451844618447184481844918450184511845218453184541845518456184571845818459184601846118462184631846418465184661846718468184691847018471184721847318474184751847618477184781847918480184811848218483184841848518486184871848818489184901849118492184931849418495184961849718498184991850018501185021850318504185051850618507185081850918510185111851218513185141851518516185171851818519185201852118522185231852418525185261852718528185291853018531185321853318534185351853618537185381853918540185411854218543185441854518546185471854818549185501855118552185531855418555185561855718558185591856018561185621856318564185651856618567185681856918570185711857218573185741857518576185771857818579185801858118582185831858418585185861858718588185891859018591185921859318594185951859618597185981859918600186011860218603186041860518606186071860818609186101861118612186131861418615186161861718618186191862018621186221862318624186251862618627186281862918630186311863218633186341863518636186371863818639186401864118642186431864418645186461864718648186491865018651186521865318654186551865618657186581865918660186611866218663186641866518666186671866818669186701867118672186731867418675186761867718678186791868018681186821868318684186851868618687186881868918690186911869218693186941869518696186971869818699187001870118702187031870418705187061870718708187091871018711187121871318714187151871618717187181871918720187211872218723187241872518726187271872818729187301873118732187331873418735187361873718738187391874018741187421874318744187451874618747187481874918750187511875218753187541875518756187571875818759187601876118762187631876418765187661876718768187691877018771187721877318774187751877618777187781877918780187811878218783187841878518786187871878818789187901879118792187931879418795187961879718798187991880018801188021880318804188051880618807188081880918810188111881218813188141881518816188171881818819188201882118822188231882418825188261882718828188291883018831188321883318834188351883618837188381883918840188411884218843188441884518846188471884818849188501885118852188531885418855188561885718858188591886018861188621886318864188651886618867188681886918870188711887218873188741887518876188771887818879188801888118882188831888418885188861888718888188891889018891188921889318894188951889618897188981889918900189011890218903189041890518906189071890818909189101891118912189131891418915189161891718918189191892018921189221892318924189251892618927189281892918930189311893218933189341893518936189371893818939189401894118942189431894418945189461894718948189491895018951189521895318954189551895618957189581895918960189611896218963189641896518966189671896818969189701897118972189731897418975189761897718978189791898018981189821898318984189851898618987189881898918990189911899218993189941899518996189971899818999190001900119002190031900419005190061900719008190091901019011190121901319014190151901619017190181901919020190211902219023190241902519026190271902819029190301903119032190331903419035190361903719038190391904019041190421904319044190451904619047190481904919050190511905219053190541905519056190571905819059190601906119062190631906419065190661906719068190691907019071190721907319074190751907619077190781907919080190811908219083190841908519086190871908819089190901909119092190931909419095190961909719098190991910019101191021910319104191051910619107191081910919110191111911219113191141911519116191171911819119191201912119122191231912419125191261912719128191291913019131191321913319134191351913619137191381913919140191411914219143191441914519146191471914819149191501915119152191531915419155191561915719158191591916019161191621916319164191651916619167191681916919170191711917219173191741917519176191771917819179191801918119182191831918419185191861918719188191891919019191191921919319194191951919619197191981919919200192011920219203192041920519206192071920819209192101921119212192131921419215192161921719218192191922019221192221922319224192251922619227192281922919230192311923219233192341923519236192371923819239192401924119242192431924419245192461924719248192491925019251192521925319254192551925619257192581925919260192611926219263192641926519266192671926819269192701927119272192731927419275192761927719278192791928019281192821928319284192851928619287192881928919290192911929219293192941929519296192971929819299193001930119302193031930419305193061930719308193091931019311193121931319314193151931619317193181931919320193211932219323193241932519326193271932819329193301933119332193331933419335193361933719338193391934019341193421934319344193451934619347193481934919350193511935219353193541935519356193571935819359193601936119362193631936419365193661936719368193691937019371193721937319374193751937619377193781937919380193811938219383193841938519386193871938819389193901939119392193931939419395193961939719398193991940019401194021940319404194051940619407194081940919410194111941219413194141941519416194171941819419194201942119422194231942419425194261942719428194291943019431194321943319434194351943619437194381943919440194411944219443194441944519446194471944819449194501945119452194531945419455194561945719458194591946019461194621946319464194651946619467194681946919470194711947219473194741947519476194771947819479194801948119482194831948419485194861948719488194891949019491194921949319494194951949619497194981949919500195011950219503195041950519506195071950819509195101951119512195131951419515195161951719518195191952019521195221952319524195251952619527195281952919530195311953219533195341953519536195371953819539195401954119542195431954419545195461954719548195491955019551195521955319554195551955619557195581955919560195611956219563195641956519566195671956819569195701957119572195731957419575195761957719578195791958019581195821958319584195851958619587195881958919590195911959219593195941959519596195971959819599196001960119602196031960419605196061960719608196091961019611196121961319614196151961619617196181961919620196211962219623196241962519626196271962819629196301963119632196331963419635196361963719638196391964019641196421964319644196451964619647196481964919650196511965219653196541965519656196571965819659196601966119662196631966419665196661966719668196691967019671196721967319674196751967619677196781967919680196811968219683196841968519686196871968819689196901969119692196931969419695196961969719698196991970019701197021970319704197051970619707197081970919710197111971219713197141971519716197171971819719197201972119722197231972419725197261972719728197291973019731197321973319734197351973619737197381973919740197411974219743197441974519746197471974819749197501975119752197531975419755197561975719758197591976019761197621976319764197651976619767197681976919770197711977219773197741977519776197771977819779197801978119782197831978419785197861978719788197891979019791197921979319794197951979619797197981979919800198011980219803198041980519806198071980819809198101981119812198131981419815198161981719818198191982019821198221982319824198251982619827198281982919830198311983219833198341983519836198371983819839198401984119842198431984419845198461984719848198491985019851198521985319854198551985619857198581985919860198611986219863198641986519866198671986819869198701987119872198731987419875198761987719878198791988019881198821988319884198851988619887198881988919890198911989219893198941989519896198971989819899199001990119902199031990419905199061990719908199091991019911199121991319914199151991619917199181991919920199211992219923199241992519926199271992819929199301993119932199331993419935199361993719938199391994019941199421994319944199451994619947199481994919950199511995219953199541995519956199571995819959199601996119962199631996419965199661996719968199691997019971199721997319974199751997619977199781997919980199811998219983199841998519986199871998819989199901999119992199931999419995199961999719998199992000020001200022000320004200052000620007200082000920010200112001220013200142001520016200172001820019200202002120022200232002420025200262002720028200292003020031200322003320034200352003620037200382003920040200412004220043200442004520046200472004820049200502005120052200532005420055200562005720058200592006020061200622006320064200652006620067200682006920070200712007220073200742007520076200772007820079200802008120082200832008420085200862008720088200892009020091200922009320094200952009620097200982009920100201012010220103201042010520106201072010820109201102011120112201132011420115201162011720118201192012020121201222012320124201252012620127201282012920130201312013220133201342013520136201372013820139201402014120142201432014420145201462014720148201492015020151201522015320154201552015620157201582015920160201612016220163201642016520166201672016820169201702017120172201732017420175201762017720178201792018020181201822018320184201852018620187201882018920190201912019220193201942019520196201972019820199202002020120202202032020420205202062020720208202092021020211202122021320214202152021620217202182021920220202212022220223202242022520226202272022820229202302023120232202332023420235202362023720238202392024020241202422024320244202452024620247202482024920250202512025220253202542025520256202572025820259202602026120262202632026420265202662026720268202692027020271202722027320274202752027620277202782027920280202812028220283202842028520286202872028820289202902029120292202932029420295202962029720298202992030020301203022030320304203052030620307203082030920310203112031220313203142031520316203172031820319203202032120322203232032420325203262032720328203292033020331203322033320334203352033620337203382033920340203412034220343203442034520346203472034820349203502035120352203532035420355203562035720358203592036020361203622036320364203652036620367203682036920370203712037220373203742037520376203772037820379203802038120382203832038420385203862038720388203892039020391203922039320394203952039620397203982039920400204012040220403204042040520406204072040820409204102041120412204132041420415204162041720418204192042020421204222042320424204252042620427204282042920430204312043220433204342043520436204372043820439204402044120442204432044420445204462044720448204492045020451204522045320454204552045620457204582045920460204612046220463204642046520466204672046820469204702047120472204732047420475204762047720478204792048020481204822048320484204852048620487204882048920490204912049220493204942049520496204972049820499205002050120502205032050420505205062050720508205092051020511205122051320514205152051620517205182051920520205212052220523205242052520526205272052820529205302053120532205332053420535205362053720538205392054020541205422054320544205452054620547205482054920550205512055220553205542055520556205572055820559205602056120562205632056420565205662056720568205692057020571205722057320574205752057620577205782057920580205812058220583205842058520586205872058820589205902059120592205932059420595205962059720598205992060020601206022060320604206052060620607206082060920610206112061220613206142061520616206172061820619206202062120622206232062420625206262062720628206292063020631206322063320634206352063620637206382063920640206412064220643
  1. /**
  2. * @vue/compiler-sfc v3.4.21
  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 path$3 = require('path');
  12. var shared = require('@vue/shared');
  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. const UNKNOWN_TYPE = "Unknown";
  36. function resolveObjectKey(node, computed) {
  37. switch (node.type) {
  38. case "StringLiteral":
  39. case "NumericLiteral":
  40. return String(node.value);
  41. case "Identifier":
  42. if (!computed)
  43. return node.name;
  44. }
  45. return void 0;
  46. }
  47. function concatStrings(strs) {
  48. return strs.filter((s) => !!s).join(", ");
  49. }
  50. function isLiteralNode(node) {
  51. return node.type.endsWith("Literal");
  52. }
  53. function isCallOf(node, test) {
  54. return !!(node && test && node.type === "CallExpression" && node.callee.type === "Identifier" && (typeof test === "string" ? node.callee.name === test : test(node.callee.name)));
  55. }
  56. function toRuntimeTypeString(types) {
  57. return types.length > 1 ? `[${types.join(", ")}]` : types[0];
  58. }
  59. function getImportedName(specifier) {
  60. if (specifier.type === "ImportSpecifier")
  61. return specifier.imported.type === "Identifier" ? specifier.imported.name : specifier.imported.value;
  62. else if (specifier.type === "ImportNamespaceSpecifier")
  63. return "*";
  64. return "default";
  65. }
  66. function getId(node) {
  67. return node.type === "Identifier" ? node.name : node.type === "StringLiteral" ? node.value : null;
  68. }
  69. const identity = (str) => str;
  70. const fileNameLowerCaseRegExp = /[^\u0130\u0131\u00DFa-z0-9\\/:\-_\. ]+/g;
  71. const toLowerCase = (str) => str.toLowerCase();
  72. function toFileNameLowerCase(x) {
  73. return fileNameLowerCaseRegExp.test(x) ? x.replace(fileNameLowerCaseRegExp, toLowerCase) : x;
  74. }
  75. function createGetCanonicalFileName(useCaseSensitiveFileNames) {
  76. return useCaseSensitiveFileNames ? identity : toFileNameLowerCase;
  77. }
  78. const normalize = (path$3.posix || path$3).normalize;
  79. const windowsSlashRE = /\\/g;
  80. function normalizePath(p) {
  81. return normalize(p.replace(windowsSlashRE, "/"));
  82. }
  83. const joinPaths = (path$3.posix || path$3).join;
  84. const propNameEscapeSymbolsRE = /[ !"#$%&'()*+,./:;<=>?@[\\\]^`{|}~\-]/;
  85. function getEscapedPropName(key) {
  86. return propNameEscapeSymbolsRE.test(key) ? JSON.stringify(key) : key;
  87. }
  88. const cssVarNameEscapeSymbolsRE = /[ !"#$%&'()*+,./:;<=>?@[\\\]^`{|}~]/g;
  89. function getEscapedCssVarName(key, doubleEscape) {
  90. return key.replace(
  91. cssVarNameEscapeSymbolsRE,
  92. (s) => doubleEscape ? `\\\\${s}` : `\\${s}`
  93. );
  94. }
  95. var commonjsGlobal = typeof globalThis !== 'undefined' ? globalThis : typeof window !== 'undefined' ? window : typeof global !== 'undefined' ? global : typeof self !== 'undefined' ? self : {};
  96. function getDefaultExportFromCjs (x) {
  97. return x && x.__esModule && Object.prototype.hasOwnProperty.call(x, 'default') ? x['default'] : x;
  98. }
  99. function pad (hash, len) {
  100. while (hash.length < len) {
  101. hash = '0' + hash;
  102. }
  103. return hash;
  104. }
  105. function fold (hash, text) {
  106. var i;
  107. var chr;
  108. var len;
  109. if (text.length === 0) {
  110. return hash;
  111. }
  112. for (i = 0, len = text.length; i < len; i++) {
  113. chr = text.charCodeAt(i);
  114. hash = ((hash << 5) - hash) + chr;
  115. hash |= 0;
  116. }
  117. return hash < 0 ? hash * -2 : hash;
  118. }
  119. function foldObject (hash, o, seen) {
  120. return Object.keys(o).sort().reduce(foldKey, hash);
  121. function foldKey (hash, key) {
  122. return foldValue(hash, o[key], key, seen);
  123. }
  124. }
  125. function foldValue (input, value, key, seen) {
  126. var hash = fold(fold(fold(input, key), toString$1(value)), typeof value);
  127. if (value === null) {
  128. return fold(hash, 'null');
  129. }
  130. if (value === undefined) {
  131. return fold(hash, 'undefined');
  132. }
  133. if (typeof value === 'object' || typeof value === 'function') {
  134. if (seen.indexOf(value) !== -1) {
  135. return fold(hash, '[Circular]' + key);
  136. }
  137. seen.push(value);
  138. var objHash = foldObject(hash, value, seen);
  139. if (!('valueOf' in value) || typeof value.valueOf !== 'function') {
  140. return objHash;
  141. }
  142. try {
  143. return fold(objHash, String(value.valueOf()))
  144. } catch (err) {
  145. return fold(objHash, '[valueOf exception]' + (err.stack || err.message))
  146. }
  147. }
  148. return fold(hash, value.toString());
  149. }
  150. function toString$1 (o) {
  151. return Object.prototype.toString.call(o);
  152. }
  153. function sum (o) {
  154. return pad(foldValue(0, o, '', []).toString(16), 8);
  155. }
  156. var hashSum = sum;
  157. var hash$1 = /*@__PURE__*/getDefaultExportFromCjs(hashSum);
  158. const CSS_VARS_HELPER = `useCssVars`;
  159. function genCssVarsFromList(vars, id, isProd, isSSR = false) {
  160. return `{
  161. ${vars.map(
  162. (key) => `"${isSSR ? `--` : ``}${genVarName(id, key, isProd, isSSR)}": (${key})`
  163. ).join(",\n ")}
  164. }`;
  165. }
  166. function genVarName(id, raw, isProd, isSSR = false) {
  167. if (isProd) {
  168. return hash$1(id + raw);
  169. } else {
  170. return `${id}-${getEscapedCssVarName(raw, isSSR)}`;
  171. }
  172. }
  173. function normalizeExpression(exp) {
  174. exp = exp.trim();
  175. if (exp[0] === `'` && exp[exp.length - 1] === `'` || exp[0] === `"` && exp[exp.length - 1] === `"`) {
  176. return exp.slice(1, -1);
  177. }
  178. return exp;
  179. }
  180. const vBindRE = /v-bind\s*\(/g;
  181. function parseCssVars(sfc) {
  182. const vars = [];
  183. sfc.styles.forEach((style) => {
  184. let match;
  185. const content = style.content.replace(/\/\*([\s\S]*?)\*\/|\/\/.*/g, "");
  186. while (match = vBindRE.exec(content)) {
  187. const start = match.index + match[0].length;
  188. const end = lexBinding(content, start);
  189. if (end !== null) {
  190. const variable = normalizeExpression(content.slice(start, end));
  191. if (!vars.includes(variable)) {
  192. vars.push(variable);
  193. }
  194. }
  195. }
  196. });
  197. return vars;
  198. }
  199. function lexBinding(content, start) {
  200. let state = 0 /* inParens */;
  201. let parenDepth = 0;
  202. for (let i = start; i < content.length; i++) {
  203. const char = content.charAt(i);
  204. switch (state) {
  205. case 0 /* inParens */:
  206. if (char === `'`) {
  207. state = 1 /* inSingleQuoteString */;
  208. } else if (char === `"`) {
  209. state = 2 /* inDoubleQuoteString */;
  210. } else if (char === `(`) {
  211. parenDepth++;
  212. } else if (char === `)`) {
  213. if (parenDepth > 0) {
  214. parenDepth--;
  215. } else {
  216. return i;
  217. }
  218. }
  219. break;
  220. case 1 /* inSingleQuoteString */:
  221. if (char === `'`) {
  222. state = 0 /* inParens */;
  223. }
  224. break;
  225. case 2 /* inDoubleQuoteString */:
  226. if (char === `"`) {
  227. state = 0 /* inParens */;
  228. }
  229. break;
  230. }
  231. }
  232. return null;
  233. }
  234. const cssVarsPlugin = (opts) => {
  235. const { id, isProd } = opts;
  236. return {
  237. postcssPlugin: "vue-sfc-vars",
  238. Declaration(decl) {
  239. const value = decl.value;
  240. if (vBindRE.test(value)) {
  241. vBindRE.lastIndex = 0;
  242. let transformed = "";
  243. let lastIndex = 0;
  244. let match;
  245. while (match = vBindRE.exec(value)) {
  246. const start = match.index + match[0].length;
  247. const end = lexBinding(value, start);
  248. if (end !== null) {
  249. const variable = normalizeExpression(value.slice(start, end));
  250. transformed += value.slice(lastIndex, match.index) + `var(--${genVarName(id, variable, isProd)})`;
  251. lastIndex = end + 1;
  252. }
  253. }
  254. decl.value = transformed + value.slice(lastIndex);
  255. }
  256. }
  257. };
  258. };
  259. cssVarsPlugin.postcss = true;
  260. function genCssVarsCode(vars, bindings, id, isProd) {
  261. const varsExp = genCssVarsFromList(vars, id, isProd);
  262. const exp = CompilerDOM.createSimpleExpression(varsExp, false);
  263. const context = CompilerDOM.createTransformContext(CompilerDOM.createRoot([]), {
  264. prefixIdentifiers: true,
  265. inline: true,
  266. bindingMetadata: bindings.__isScriptSetup === false ? void 0 : bindings
  267. });
  268. const transformed = CompilerDOM.processExpression(exp, context);
  269. const transformedString = transformed.type === 4 ? transformed.content : transformed.children.map((c) => {
  270. return typeof c === "string" ? c : c.content;
  271. }).join("");
  272. return `_${CSS_VARS_HELPER}(_ctx => (${transformedString}))`;
  273. }
  274. function genNormalScriptCssVarsCode(cssVars, bindings, id, isProd, defaultVar) {
  275. return `
  276. import { ${CSS_VARS_HELPER} as _${CSS_VARS_HELPER} } from 'vue'
  277. const __injectCSSVars__ = () => {
  278. ${genCssVarsCode(
  279. cssVars,
  280. bindings,
  281. id,
  282. isProd
  283. )}}
  284. const __setup__ = ${defaultVar}.setup
  285. ${defaultVar}.setup = __setup__
  286. ? (props, ctx) => { __injectCSSVars__();return __setup__(props, ctx) }
  287. : __injectCSSVars__
  288. `;
  289. }
  290. /**
  291. * @module LRUCache
  292. */
  293. const perf = typeof performance === 'object' &&
  294. performance &&
  295. typeof performance.now === 'function'
  296. ? performance
  297. : Date;
  298. const warned = new Set();
  299. /* c8 ignore start */
  300. const PROCESS = (typeof process === 'object' && !!process ? process : {});
  301. /* c8 ignore start */
  302. const emitWarning = (msg, type, code, fn) => {
  303. typeof PROCESS.emitWarning === 'function'
  304. ? PROCESS.emitWarning(msg, type, code, fn)
  305. : console.error(`[${code}] ${type}: ${msg}`);
  306. };
  307. let AC = globalThis.AbortController;
  308. let AS = globalThis.AbortSignal;
  309. /* c8 ignore start */
  310. if (typeof AC === 'undefined') {
  311. //@ts-ignore
  312. AS = class AbortSignal {
  313. onabort;
  314. _onabort = [];
  315. reason;
  316. aborted = false;
  317. addEventListener(_, fn) {
  318. this._onabort.push(fn);
  319. }
  320. };
  321. //@ts-ignore
  322. AC = class AbortController {
  323. constructor() {
  324. warnACPolyfill();
  325. }
  326. signal = new AS();
  327. abort(reason) {
  328. if (this.signal.aborted)
  329. return;
  330. //@ts-ignore
  331. this.signal.reason = reason;
  332. //@ts-ignore
  333. this.signal.aborted = true;
  334. //@ts-ignore
  335. for (const fn of this.signal._onabort) {
  336. fn(reason);
  337. }
  338. this.signal.onabort?.(reason);
  339. }
  340. };
  341. let printACPolyfillWarning = PROCESS.env?.LRU_CACHE_IGNORE_AC_WARNING !== '1';
  342. const warnACPolyfill = () => {
  343. if (!printACPolyfillWarning)
  344. return;
  345. printACPolyfillWarning = false;
  346. emitWarning('AbortController is not defined. If using lru-cache in ' +
  347. 'node 14, load an AbortController polyfill from the ' +
  348. '`node-abort-controller` package. A minimal polyfill is ' +
  349. 'provided for use by LRUCache.fetch(), but it should not be ' +
  350. 'relied upon in other contexts (eg, passing it to other APIs that ' +
  351. 'use AbortController/AbortSignal might have undesirable effects). ' +
  352. 'You may disable this with LRU_CACHE_IGNORE_AC_WARNING=1 in the env.', 'NO_ABORT_CONTROLLER', 'ENOTSUP', warnACPolyfill);
  353. };
  354. }
  355. /* c8 ignore stop */
  356. const shouldWarn = (code) => !warned.has(code);
  357. const isPosInt = (n) => n && n === Math.floor(n) && n > 0 && isFinite(n);
  358. /* c8 ignore start */
  359. // This is a little bit ridiculous, tbh.
  360. // The maximum array length is 2^32-1 or thereabouts on most JS impls.
  361. // And well before that point, you're caching the entire world, I mean,
  362. // that's ~32GB of just integers for the next/prev links, plus whatever
  363. // else to hold that many keys and values. Just filling the memory with
  364. // zeroes at init time is brutal when you get that big.
  365. // But why not be complete?
  366. // Maybe in the future, these limits will have expanded.
  367. const getUintArray = (max) => !isPosInt(max)
  368. ? null
  369. : max <= Math.pow(2, 8)
  370. ? Uint8Array
  371. : max <= Math.pow(2, 16)
  372. ? Uint16Array
  373. : max <= Math.pow(2, 32)
  374. ? Uint32Array
  375. : max <= Number.MAX_SAFE_INTEGER
  376. ? ZeroArray
  377. : null;
  378. /* c8 ignore stop */
  379. class ZeroArray extends Array {
  380. constructor(size) {
  381. super(size);
  382. this.fill(0);
  383. }
  384. }
  385. class Stack {
  386. heap;
  387. length;
  388. // private constructor
  389. static #constructing = false;
  390. static create(max) {
  391. const HeapCls = getUintArray(max);
  392. if (!HeapCls)
  393. return [];
  394. Stack.#constructing = true;
  395. const s = new Stack(max, HeapCls);
  396. Stack.#constructing = false;
  397. return s;
  398. }
  399. constructor(max, HeapCls) {
  400. /* c8 ignore start */
  401. if (!Stack.#constructing) {
  402. throw new TypeError('instantiate Stack using Stack.create(n)');
  403. }
  404. /* c8 ignore stop */
  405. this.heap = new HeapCls(max);
  406. this.length = 0;
  407. }
  408. push(n) {
  409. this.heap[this.length++] = n;
  410. }
  411. pop() {
  412. return this.heap[--this.length];
  413. }
  414. }
  415. /**
  416. * Default export, the thing you're using this module to get.
  417. *
  418. * All properties from the options object (with the exception of
  419. * {@link OptionsBase.max} and {@link OptionsBase.maxSize}) are added as
  420. * normal public members. (`max` and `maxBase` are read-only getters.)
  421. * Changing any of these will alter the defaults for subsequent method calls,
  422. * but is otherwise safe.
  423. */
  424. class LRUCache {
  425. // properties coming in from the options of these, only max and maxSize
  426. // really *need* to be protected. The rest can be modified, as they just
  427. // set defaults for various methods.
  428. #max;
  429. #maxSize;
  430. #dispose;
  431. #disposeAfter;
  432. #fetchMethod;
  433. /**
  434. * {@link LRUCache.OptionsBase.ttl}
  435. */
  436. ttl;
  437. /**
  438. * {@link LRUCache.OptionsBase.ttlResolution}
  439. */
  440. ttlResolution;
  441. /**
  442. * {@link LRUCache.OptionsBase.ttlAutopurge}
  443. */
  444. ttlAutopurge;
  445. /**
  446. * {@link LRUCache.OptionsBase.updateAgeOnGet}
  447. */
  448. updateAgeOnGet;
  449. /**
  450. * {@link LRUCache.OptionsBase.updateAgeOnHas}
  451. */
  452. updateAgeOnHas;
  453. /**
  454. * {@link LRUCache.OptionsBase.allowStale}
  455. */
  456. allowStale;
  457. /**
  458. * {@link LRUCache.OptionsBase.noDisposeOnSet}
  459. */
  460. noDisposeOnSet;
  461. /**
  462. * {@link LRUCache.OptionsBase.noUpdateTTL}
  463. */
  464. noUpdateTTL;
  465. /**
  466. * {@link LRUCache.OptionsBase.maxEntrySize}
  467. */
  468. maxEntrySize;
  469. /**
  470. * {@link LRUCache.OptionsBase.sizeCalculation}
  471. */
  472. sizeCalculation;
  473. /**
  474. * {@link LRUCache.OptionsBase.noDeleteOnFetchRejection}
  475. */
  476. noDeleteOnFetchRejection;
  477. /**
  478. * {@link LRUCache.OptionsBase.noDeleteOnStaleGet}
  479. */
  480. noDeleteOnStaleGet;
  481. /**
  482. * {@link LRUCache.OptionsBase.allowStaleOnFetchAbort}
  483. */
  484. allowStaleOnFetchAbort;
  485. /**
  486. * {@link LRUCache.OptionsBase.allowStaleOnFetchRejection}
  487. */
  488. allowStaleOnFetchRejection;
  489. /**
  490. * {@link LRUCache.OptionsBase.ignoreFetchAbort}
  491. */
  492. ignoreFetchAbort;
  493. // computed properties
  494. #size;
  495. #calculatedSize;
  496. #keyMap;
  497. #keyList;
  498. #valList;
  499. #next;
  500. #prev;
  501. #head;
  502. #tail;
  503. #free;
  504. #disposed;
  505. #sizes;
  506. #starts;
  507. #ttls;
  508. #hasDispose;
  509. #hasFetchMethod;
  510. #hasDisposeAfter;
  511. /**
  512. * Do not call this method unless you need to inspect the
  513. * inner workings of the cache. If anything returned by this
  514. * object is modified in any way, strange breakage may occur.
  515. *
  516. * These fields are private for a reason!
  517. *
  518. * @internal
  519. */
  520. static unsafeExposeInternals(c) {
  521. return {
  522. // properties
  523. starts: c.#starts,
  524. ttls: c.#ttls,
  525. sizes: c.#sizes,
  526. keyMap: c.#keyMap,
  527. keyList: c.#keyList,
  528. valList: c.#valList,
  529. next: c.#next,
  530. prev: c.#prev,
  531. get head() {
  532. return c.#head;
  533. },
  534. get tail() {
  535. return c.#tail;
  536. },
  537. free: c.#free,
  538. // methods
  539. isBackgroundFetch: (p) => c.#isBackgroundFetch(p),
  540. backgroundFetch: (k, index, options, context) => c.#backgroundFetch(k, index, options, context),
  541. moveToTail: (index) => c.#moveToTail(index),
  542. indexes: (options) => c.#indexes(options),
  543. rindexes: (options) => c.#rindexes(options),
  544. isStale: (index) => c.#isStale(index),
  545. };
  546. }
  547. // Protected read-only members
  548. /**
  549. * {@link LRUCache.OptionsBase.max} (read-only)
  550. */
  551. get max() {
  552. return this.#max;
  553. }
  554. /**
  555. * {@link LRUCache.OptionsBase.maxSize} (read-only)
  556. */
  557. get maxSize() {
  558. return this.#maxSize;
  559. }
  560. /**
  561. * The total computed size of items in the cache (read-only)
  562. */
  563. get calculatedSize() {
  564. return this.#calculatedSize;
  565. }
  566. /**
  567. * The number of items stored in the cache (read-only)
  568. */
  569. get size() {
  570. return this.#size;
  571. }
  572. /**
  573. * {@link LRUCache.OptionsBase.fetchMethod} (read-only)
  574. */
  575. get fetchMethod() {
  576. return this.#fetchMethod;
  577. }
  578. /**
  579. * {@link LRUCache.OptionsBase.dispose} (read-only)
  580. */
  581. get dispose() {
  582. return this.#dispose;
  583. }
  584. /**
  585. * {@link LRUCache.OptionsBase.disposeAfter} (read-only)
  586. */
  587. get disposeAfter() {
  588. return this.#disposeAfter;
  589. }
  590. constructor(options) {
  591. 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;
  592. if (max !== 0 && !isPosInt(max)) {
  593. throw new TypeError('max option must be a nonnegative integer');
  594. }
  595. const UintArray = max ? getUintArray(max) : Array;
  596. if (!UintArray) {
  597. throw new Error('invalid max value: ' + max);
  598. }
  599. this.#max = max;
  600. this.#maxSize = maxSize;
  601. this.maxEntrySize = maxEntrySize || this.#maxSize;
  602. this.sizeCalculation = sizeCalculation;
  603. if (this.sizeCalculation) {
  604. if (!this.#maxSize && !this.maxEntrySize) {
  605. throw new TypeError('cannot set sizeCalculation without setting maxSize or maxEntrySize');
  606. }
  607. if (typeof this.sizeCalculation !== 'function') {
  608. throw new TypeError('sizeCalculation set to non-function');
  609. }
  610. }
  611. if (fetchMethod !== undefined &&
  612. typeof fetchMethod !== 'function') {
  613. throw new TypeError('fetchMethod must be a function if specified');
  614. }
  615. this.#fetchMethod = fetchMethod;
  616. this.#hasFetchMethod = !!fetchMethod;
  617. this.#keyMap = new Map();
  618. this.#keyList = new Array(max).fill(undefined);
  619. this.#valList = new Array(max).fill(undefined);
  620. this.#next = new UintArray(max);
  621. this.#prev = new UintArray(max);
  622. this.#head = 0;
  623. this.#tail = 0;
  624. this.#free = Stack.create(max);
  625. this.#size = 0;
  626. this.#calculatedSize = 0;
  627. if (typeof dispose === 'function') {
  628. this.#dispose = dispose;
  629. }
  630. if (typeof disposeAfter === 'function') {
  631. this.#disposeAfter = disposeAfter;
  632. this.#disposed = [];
  633. }
  634. else {
  635. this.#disposeAfter = undefined;
  636. this.#disposed = undefined;
  637. }
  638. this.#hasDispose = !!this.#dispose;
  639. this.#hasDisposeAfter = !!this.#disposeAfter;
  640. this.noDisposeOnSet = !!noDisposeOnSet;
  641. this.noUpdateTTL = !!noUpdateTTL;
  642. this.noDeleteOnFetchRejection = !!noDeleteOnFetchRejection;
  643. this.allowStaleOnFetchRejection = !!allowStaleOnFetchRejection;
  644. this.allowStaleOnFetchAbort = !!allowStaleOnFetchAbort;
  645. this.ignoreFetchAbort = !!ignoreFetchAbort;
  646. // NB: maxEntrySize is set to maxSize if it's set
  647. if (this.maxEntrySize !== 0) {
  648. if (this.#maxSize !== 0) {
  649. if (!isPosInt(this.#maxSize)) {
  650. throw new TypeError('maxSize must be a positive integer if specified');
  651. }
  652. }
  653. if (!isPosInt(this.maxEntrySize)) {
  654. throw new TypeError('maxEntrySize must be a positive integer if specified');
  655. }
  656. this.#initializeSizeTracking();
  657. }
  658. this.allowStale = !!allowStale;
  659. this.noDeleteOnStaleGet = !!noDeleteOnStaleGet;
  660. this.updateAgeOnGet = !!updateAgeOnGet;
  661. this.updateAgeOnHas = !!updateAgeOnHas;
  662. this.ttlResolution =
  663. isPosInt(ttlResolution) || ttlResolution === 0
  664. ? ttlResolution
  665. : 1;
  666. this.ttlAutopurge = !!ttlAutopurge;
  667. this.ttl = ttl || 0;
  668. if (this.ttl) {
  669. if (!isPosInt(this.ttl)) {
  670. throw new TypeError('ttl must be a positive integer if specified');
  671. }
  672. this.#initializeTTLTracking();
  673. }
  674. // do not allow completely unbounded caches
  675. if (this.#max === 0 && this.ttl === 0 && this.#maxSize === 0) {
  676. throw new TypeError('At least one of max, maxSize, or ttl is required');
  677. }
  678. if (!this.ttlAutopurge && !this.#max && !this.#maxSize) {
  679. const code = 'LRU_CACHE_UNBOUNDED';
  680. if (shouldWarn(code)) {
  681. warned.add(code);
  682. const msg = 'TTL caching without ttlAutopurge, max, or maxSize can ' +
  683. 'result in unbounded memory consumption.';
  684. emitWarning(msg, 'UnboundedCacheWarning', code, LRUCache);
  685. }
  686. }
  687. }
  688. /**
  689. * Return the remaining TTL time for a given entry key
  690. */
  691. getRemainingTTL(key) {
  692. return this.#keyMap.has(key) ? Infinity : 0;
  693. }
  694. #initializeTTLTracking() {
  695. const ttls = new ZeroArray(this.#max);
  696. const starts = new ZeroArray(this.#max);
  697. this.#ttls = ttls;
  698. this.#starts = starts;
  699. this.#setItemTTL = (index, ttl, start = perf.now()) => {
  700. starts[index] = ttl !== 0 ? start : 0;
  701. ttls[index] = ttl;
  702. if (ttl !== 0 && this.ttlAutopurge) {
  703. const t = setTimeout(() => {
  704. if (this.#isStale(index)) {
  705. this.delete(this.#keyList[index]);
  706. }
  707. }, ttl + 1);
  708. // unref() not supported on all platforms
  709. /* c8 ignore start */
  710. if (t.unref) {
  711. t.unref();
  712. }
  713. /* c8 ignore stop */
  714. }
  715. };
  716. this.#updateItemAge = index => {
  717. starts[index] = ttls[index] !== 0 ? perf.now() : 0;
  718. };
  719. this.#statusTTL = (status, index) => {
  720. if (ttls[index]) {
  721. const ttl = ttls[index];
  722. const start = starts[index];
  723. /* c8 ignore next */
  724. if (!ttl || !start)
  725. return;
  726. status.ttl = ttl;
  727. status.start = start;
  728. status.now = cachedNow || getNow();
  729. const age = status.now - start;
  730. status.remainingTTL = ttl - age;
  731. }
  732. };
  733. // debounce calls to perf.now() to 1s so we're not hitting
  734. // that costly call repeatedly.
  735. let cachedNow = 0;
  736. const getNow = () => {
  737. const n = perf.now();
  738. if (this.ttlResolution > 0) {
  739. cachedNow = n;
  740. const t = setTimeout(() => (cachedNow = 0), this.ttlResolution);
  741. // not available on all platforms
  742. /* c8 ignore start */
  743. if (t.unref) {
  744. t.unref();
  745. }
  746. /* c8 ignore stop */
  747. }
  748. return n;
  749. };
  750. this.getRemainingTTL = key => {
  751. const index = this.#keyMap.get(key);
  752. if (index === undefined) {
  753. return 0;
  754. }
  755. const ttl = ttls[index];
  756. const start = starts[index];
  757. if (!ttl || !start) {
  758. return Infinity;
  759. }
  760. const age = (cachedNow || getNow()) - start;
  761. return ttl - age;
  762. };
  763. this.#isStale = index => {
  764. const s = starts[index];
  765. const t = ttls[index];
  766. return !!t && !!s && (cachedNow || getNow()) - s > t;
  767. };
  768. }
  769. // conditionally set private methods related to TTL
  770. #updateItemAge = () => { };
  771. #statusTTL = () => { };
  772. #setItemTTL = () => { };
  773. /* c8 ignore stop */
  774. #isStale = () => false;
  775. #initializeSizeTracking() {
  776. const sizes = new ZeroArray(this.#max);
  777. this.#calculatedSize = 0;
  778. this.#sizes = sizes;
  779. this.#removeItemSize = index => {
  780. this.#calculatedSize -= sizes[index];
  781. sizes[index] = 0;
  782. };
  783. this.#requireSize = (k, v, size, sizeCalculation) => {
  784. // provisionally accept background fetches.
  785. // actual value size will be checked when they return.
  786. if (this.#isBackgroundFetch(v)) {
  787. return 0;
  788. }
  789. if (!isPosInt(size)) {
  790. if (sizeCalculation) {
  791. if (typeof sizeCalculation !== 'function') {
  792. throw new TypeError('sizeCalculation must be a function');
  793. }
  794. size = sizeCalculation(v, k);
  795. if (!isPosInt(size)) {
  796. throw new TypeError('sizeCalculation return invalid (expect positive integer)');
  797. }
  798. }
  799. else {
  800. throw new TypeError('invalid size value (must be positive integer). ' +
  801. 'When maxSize or maxEntrySize is used, sizeCalculation ' +
  802. 'or size must be set.');
  803. }
  804. }
  805. return size;
  806. };
  807. this.#addItemSize = (index, size, status) => {
  808. sizes[index] = size;
  809. if (this.#maxSize) {
  810. const maxSize = this.#maxSize - sizes[index];
  811. while (this.#calculatedSize > maxSize) {
  812. this.#evict(true);
  813. }
  814. }
  815. this.#calculatedSize += sizes[index];
  816. if (status) {
  817. status.entrySize = size;
  818. status.totalCalculatedSize = this.#calculatedSize;
  819. }
  820. };
  821. }
  822. #removeItemSize = _i => { };
  823. #addItemSize = (_i, _s, _st) => { };
  824. #requireSize = (_k, _v, size, sizeCalculation) => {
  825. if (size || sizeCalculation) {
  826. throw new TypeError('cannot set size without setting maxSize or maxEntrySize on cache');
  827. }
  828. return 0;
  829. };
  830. *#indexes({ allowStale = this.allowStale } = {}) {
  831. if (this.#size) {
  832. for (let i = this.#tail; true;) {
  833. if (!this.#isValidIndex(i)) {
  834. break;
  835. }
  836. if (allowStale || !this.#isStale(i)) {
  837. yield i;
  838. }
  839. if (i === this.#head) {
  840. break;
  841. }
  842. else {
  843. i = this.#prev[i];
  844. }
  845. }
  846. }
  847. }
  848. *#rindexes({ allowStale = this.allowStale } = {}) {
  849. if (this.#size) {
  850. for (let i = this.#head; true;) {
  851. if (!this.#isValidIndex(i)) {
  852. break;
  853. }
  854. if (allowStale || !this.#isStale(i)) {
  855. yield i;
  856. }
  857. if (i === this.#tail) {
  858. break;
  859. }
  860. else {
  861. i = this.#next[i];
  862. }
  863. }
  864. }
  865. }
  866. #isValidIndex(index) {
  867. return (index !== undefined &&
  868. this.#keyMap.get(this.#keyList[index]) === index);
  869. }
  870. /**
  871. * Return a generator yielding `[key, value]` pairs,
  872. * in order from most recently used to least recently used.
  873. */
  874. *entries() {
  875. for (const i of this.#indexes()) {
  876. if (this.#valList[i] !== undefined &&
  877. this.#keyList[i] !== undefined &&
  878. !this.#isBackgroundFetch(this.#valList[i])) {
  879. yield [this.#keyList[i], this.#valList[i]];
  880. }
  881. }
  882. }
  883. /**
  884. * Inverse order version of {@link LRUCache.entries}
  885. *
  886. * Return a generator yielding `[key, value]` pairs,
  887. * in order from least recently used to most recently used.
  888. */
  889. *rentries() {
  890. for (const i of this.#rindexes()) {
  891. if (this.#valList[i] !== undefined &&
  892. this.#keyList[i] !== undefined &&
  893. !this.#isBackgroundFetch(this.#valList[i])) {
  894. yield [this.#keyList[i], this.#valList[i]];
  895. }
  896. }
  897. }
  898. /**
  899. * Return a generator yielding the keys in the cache,
  900. * in order from most recently used to least recently used.
  901. */
  902. *keys() {
  903. for (const i of this.#indexes()) {
  904. const k = this.#keyList[i];
  905. if (k !== undefined &&
  906. !this.#isBackgroundFetch(this.#valList[i])) {
  907. yield k;
  908. }
  909. }
  910. }
  911. /**
  912. * Inverse order version of {@link LRUCache.keys}
  913. *
  914. * Return a generator yielding the keys in the cache,
  915. * in order from least recently used to most recently used.
  916. */
  917. *rkeys() {
  918. for (const i of this.#rindexes()) {
  919. const k = this.#keyList[i];
  920. if (k !== undefined &&
  921. !this.#isBackgroundFetch(this.#valList[i])) {
  922. yield k;
  923. }
  924. }
  925. }
  926. /**
  927. * Return a generator yielding the values in the cache,
  928. * in order from most recently used to least recently used.
  929. */
  930. *values() {
  931. for (const i of this.#indexes()) {
  932. const v = this.#valList[i];
  933. if (v !== undefined &&
  934. !this.#isBackgroundFetch(this.#valList[i])) {
  935. yield this.#valList[i];
  936. }
  937. }
  938. }
  939. /**
  940. * Inverse order version of {@link LRUCache.values}
  941. *
  942. * Return a generator yielding the values in the cache,
  943. * in order from least recently used to most recently used.
  944. */
  945. *rvalues() {
  946. for (const i of this.#rindexes()) {
  947. const v = this.#valList[i];
  948. if (v !== undefined &&
  949. !this.#isBackgroundFetch(this.#valList[i])) {
  950. yield this.#valList[i];
  951. }
  952. }
  953. }
  954. /**
  955. * Iterating over the cache itself yields the same results as
  956. * {@link LRUCache.entries}
  957. */
  958. [Symbol.iterator]() {
  959. return this.entries();
  960. }
  961. /**
  962. * Find a value for which the supplied fn method returns a truthy value,
  963. * similar to Array.find(). fn is called as fn(value, key, cache).
  964. */
  965. find(fn, getOptions = {}) {
  966. for (const i of this.#indexes()) {
  967. const v = this.#valList[i];
  968. const value = this.#isBackgroundFetch(v)
  969. ? v.__staleWhileFetching
  970. : v;
  971. if (value === undefined)
  972. continue;
  973. if (fn(value, this.#keyList[i], this)) {
  974. return this.get(this.#keyList[i], getOptions);
  975. }
  976. }
  977. }
  978. /**
  979. * Call the supplied function on each item in the cache, in order from
  980. * most recently used to least recently used. fn is called as
  981. * fn(value, key, cache). Does not update age or recenty of use.
  982. * Does not iterate over stale values.
  983. */
  984. forEach(fn, thisp = this) {
  985. for (const i of this.#indexes()) {
  986. const v = this.#valList[i];
  987. const value = this.#isBackgroundFetch(v)
  988. ? v.__staleWhileFetching
  989. : v;
  990. if (value === undefined)
  991. continue;
  992. fn.call(thisp, value, this.#keyList[i], this);
  993. }
  994. }
  995. /**
  996. * The same as {@link LRUCache.forEach} but items are iterated over in
  997. * reverse order. (ie, less recently used items are iterated over first.)
  998. */
  999. rforEach(fn, thisp = this) {
  1000. for (const i of this.#rindexes()) {
  1001. const v = this.#valList[i];
  1002. const value = this.#isBackgroundFetch(v)
  1003. ? v.__staleWhileFetching
  1004. : v;
  1005. if (value === undefined)
  1006. continue;
  1007. fn.call(thisp, value, this.#keyList[i], this);
  1008. }
  1009. }
  1010. /**
  1011. * Delete any stale entries. Returns true if anything was removed,
  1012. * false otherwise.
  1013. */
  1014. purgeStale() {
  1015. let deleted = false;
  1016. for (const i of this.#rindexes({ allowStale: true })) {
  1017. if (this.#isStale(i)) {
  1018. this.delete(this.#keyList[i]);
  1019. deleted = true;
  1020. }
  1021. }
  1022. return deleted;
  1023. }
  1024. /**
  1025. * Get the extended info about a given entry, to get its value, size, and
  1026. * TTL info simultaneously. Like {@link LRUCache#dump}, but just for a
  1027. * single key. Always returns stale values, if their info is found in the
  1028. * cache, so be sure to check for expired TTLs if relevant.
  1029. */
  1030. info(key) {
  1031. const i = this.#keyMap.get(key);
  1032. if (i === undefined)
  1033. return undefined;
  1034. const v = this.#valList[i];
  1035. const value = this.#isBackgroundFetch(v)
  1036. ? v.__staleWhileFetching
  1037. : v;
  1038. if (value === undefined)
  1039. return undefined;
  1040. const entry = { value };
  1041. if (this.#ttls && this.#starts) {
  1042. const ttl = this.#ttls[i];
  1043. const start = this.#starts[i];
  1044. if (ttl && start) {
  1045. const remain = ttl - (perf.now() - start);
  1046. entry.ttl = remain;
  1047. entry.start = Date.now();
  1048. }
  1049. }
  1050. if (this.#sizes) {
  1051. entry.size = this.#sizes[i];
  1052. }
  1053. return entry;
  1054. }
  1055. /**
  1056. * Return an array of [key, {@link LRUCache.Entry}] tuples which can be
  1057. * passed to cache.load()
  1058. */
  1059. dump() {
  1060. const arr = [];
  1061. for (const i of this.#indexes({ allowStale: true })) {
  1062. const key = this.#keyList[i];
  1063. const v = this.#valList[i];
  1064. const value = this.#isBackgroundFetch(v)
  1065. ? v.__staleWhileFetching
  1066. : v;
  1067. if (value === undefined || key === undefined)
  1068. continue;
  1069. const entry = { value };
  1070. if (this.#ttls && this.#starts) {
  1071. entry.ttl = this.#ttls[i];
  1072. // always dump the start relative to a portable timestamp
  1073. // it's ok for this to be a bit slow, it's a rare operation.
  1074. const age = perf.now() - this.#starts[i];
  1075. entry.start = Math.floor(Date.now() - age);
  1076. }
  1077. if (this.#sizes) {
  1078. entry.size = this.#sizes[i];
  1079. }
  1080. arr.unshift([key, entry]);
  1081. }
  1082. return arr;
  1083. }
  1084. /**
  1085. * Reset the cache and load in the items in entries in the order listed.
  1086. * Note that the shape of the resulting cache may be different if the
  1087. * same options are not used in both caches.
  1088. */
  1089. load(arr) {
  1090. this.clear();
  1091. for (const [key, entry] of arr) {
  1092. if (entry.start) {
  1093. // entry.start is a portable timestamp, but we may be using
  1094. // node's performance.now(), so calculate the offset, so that
  1095. // we get the intended remaining TTL, no matter how long it's
  1096. // been on ice.
  1097. //
  1098. // it's ok for this to be a bit slow, it's a rare operation.
  1099. const age = Date.now() - entry.start;
  1100. entry.start = perf.now() - age;
  1101. }
  1102. this.set(key, entry.value, entry);
  1103. }
  1104. }
  1105. /**
  1106. * Add a value to the cache.
  1107. *
  1108. * Note: if `undefined` is specified as a value, this is an alias for
  1109. * {@link LRUCache#delete}
  1110. */
  1111. set(k, v, setOptions = {}) {
  1112. if (v === undefined) {
  1113. this.delete(k);
  1114. return this;
  1115. }
  1116. const { ttl = this.ttl, start, noDisposeOnSet = this.noDisposeOnSet, sizeCalculation = this.sizeCalculation, status, } = setOptions;
  1117. let { noUpdateTTL = this.noUpdateTTL } = setOptions;
  1118. const size = this.#requireSize(k, v, setOptions.size || 0, sizeCalculation);
  1119. // if the item doesn't fit, don't do anything
  1120. // NB: maxEntrySize set to maxSize by default
  1121. if (this.maxEntrySize && size > this.maxEntrySize) {
  1122. if (status) {
  1123. status.set = 'miss';
  1124. status.maxEntrySizeExceeded = true;
  1125. }
  1126. // have to delete, in case something is there already.
  1127. this.delete(k);
  1128. return this;
  1129. }
  1130. let index = this.#size === 0 ? undefined : this.#keyMap.get(k);
  1131. if (index === undefined) {
  1132. // addition
  1133. index = (this.#size === 0
  1134. ? this.#tail
  1135. : this.#free.length !== 0
  1136. ? this.#free.pop()
  1137. : this.#size === this.#max
  1138. ? this.#evict(false)
  1139. : this.#size);
  1140. this.#keyList[index] = k;
  1141. this.#valList[index] = v;
  1142. this.#keyMap.set(k, index);
  1143. this.#next[this.#tail] = index;
  1144. this.#prev[index] = this.#tail;
  1145. this.#tail = index;
  1146. this.#size++;
  1147. this.#addItemSize(index, size, status);
  1148. if (status)
  1149. status.set = 'add';
  1150. noUpdateTTL = false;
  1151. }
  1152. else {
  1153. // update
  1154. this.#moveToTail(index);
  1155. const oldVal = this.#valList[index];
  1156. if (v !== oldVal) {
  1157. if (this.#hasFetchMethod && this.#isBackgroundFetch(oldVal)) {
  1158. oldVal.__abortController.abort(new Error('replaced'));
  1159. const { __staleWhileFetching: s } = oldVal;
  1160. if (s !== undefined && !noDisposeOnSet) {
  1161. if (this.#hasDispose) {
  1162. this.#dispose?.(s, k, 'set');
  1163. }
  1164. if (this.#hasDisposeAfter) {
  1165. this.#disposed?.push([s, k, 'set']);
  1166. }
  1167. }
  1168. }
  1169. else if (!noDisposeOnSet) {
  1170. if (this.#hasDispose) {
  1171. this.#dispose?.(oldVal, k, 'set');
  1172. }
  1173. if (this.#hasDisposeAfter) {
  1174. this.#disposed?.push([oldVal, k, 'set']);
  1175. }
  1176. }
  1177. this.#removeItemSize(index);
  1178. this.#addItemSize(index, size, status);
  1179. this.#valList[index] = v;
  1180. if (status) {
  1181. status.set = 'replace';
  1182. const oldValue = oldVal && this.#isBackgroundFetch(oldVal)
  1183. ? oldVal.__staleWhileFetching
  1184. : oldVal;
  1185. if (oldValue !== undefined)
  1186. status.oldValue = oldValue;
  1187. }
  1188. }
  1189. else if (status) {
  1190. status.set = 'update';
  1191. }
  1192. }
  1193. if (ttl !== 0 && !this.#ttls) {
  1194. this.#initializeTTLTracking();
  1195. }
  1196. if (this.#ttls) {
  1197. if (!noUpdateTTL) {
  1198. this.#setItemTTL(index, ttl, start);
  1199. }
  1200. if (status)
  1201. this.#statusTTL(status, index);
  1202. }
  1203. if (!noDisposeOnSet && this.#hasDisposeAfter && this.#disposed) {
  1204. const dt = this.#disposed;
  1205. let task;
  1206. while ((task = dt?.shift())) {
  1207. this.#disposeAfter?.(...task);
  1208. }
  1209. }
  1210. return this;
  1211. }
  1212. /**
  1213. * Evict the least recently used item, returning its value or
  1214. * `undefined` if cache is empty.
  1215. */
  1216. pop() {
  1217. try {
  1218. while (this.#size) {
  1219. const val = this.#valList[this.#head];
  1220. this.#evict(true);
  1221. if (this.#isBackgroundFetch(val)) {
  1222. if (val.__staleWhileFetching) {
  1223. return val.__staleWhileFetching;
  1224. }
  1225. }
  1226. else if (val !== undefined) {
  1227. return val;
  1228. }
  1229. }
  1230. }
  1231. finally {
  1232. if (this.#hasDisposeAfter && this.#disposed) {
  1233. const dt = this.#disposed;
  1234. let task;
  1235. while ((task = dt?.shift())) {
  1236. this.#disposeAfter?.(...task);
  1237. }
  1238. }
  1239. }
  1240. }
  1241. #evict(free) {
  1242. const head = this.#head;
  1243. const k = this.#keyList[head];
  1244. const v = this.#valList[head];
  1245. if (this.#hasFetchMethod && this.#isBackgroundFetch(v)) {
  1246. v.__abortController.abort(new Error('evicted'));
  1247. }
  1248. else if (this.#hasDispose || this.#hasDisposeAfter) {
  1249. if (this.#hasDispose) {
  1250. this.#dispose?.(v, k, 'evict');
  1251. }
  1252. if (this.#hasDisposeAfter) {
  1253. this.#disposed?.push([v, k, 'evict']);
  1254. }
  1255. }
  1256. this.#removeItemSize(head);
  1257. // if we aren't about to use the index, then null these out
  1258. if (free) {
  1259. this.#keyList[head] = undefined;
  1260. this.#valList[head] = undefined;
  1261. this.#free.push(head);
  1262. }
  1263. if (this.#size === 1) {
  1264. this.#head = this.#tail = 0;
  1265. this.#free.length = 0;
  1266. }
  1267. else {
  1268. this.#head = this.#next[head];
  1269. }
  1270. this.#keyMap.delete(k);
  1271. this.#size--;
  1272. return head;
  1273. }
  1274. /**
  1275. * Check if a key is in the cache, without updating the recency of use.
  1276. * Will return false if the item is stale, even though it is technically
  1277. * in the cache.
  1278. *
  1279. * Will not update item age unless
  1280. * {@link LRUCache.OptionsBase.updateAgeOnHas} is set.
  1281. */
  1282. has(k, hasOptions = {}) {
  1283. const { updateAgeOnHas = this.updateAgeOnHas, status } = hasOptions;
  1284. const index = this.#keyMap.get(k);
  1285. if (index !== undefined) {
  1286. const v = this.#valList[index];
  1287. if (this.#isBackgroundFetch(v) &&
  1288. v.__staleWhileFetching === undefined) {
  1289. return false;
  1290. }
  1291. if (!this.#isStale(index)) {
  1292. if (updateAgeOnHas) {
  1293. this.#updateItemAge(index);
  1294. }
  1295. if (status) {
  1296. status.has = 'hit';
  1297. this.#statusTTL(status, index);
  1298. }
  1299. return true;
  1300. }
  1301. else if (status) {
  1302. status.has = 'stale';
  1303. this.#statusTTL(status, index);
  1304. }
  1305. }
  1306. else if (status) {
  1307. status.has = 'miss';
  1308. }
  1309. return false;
  1310. }
  1311. /**
  1312. * Like {@link LRUCache#get} but doesn't update recency or delete stale
  1313. * items.
  1314. *
  1315. * Returns `undefined` if the item is stale, unless
  1316. * {@link LRUCache.OptionsBase.allowStale} is set.
  1317. */
  1318. peek(k, peekOptions = {}) {
  1319. const { allowStale = this.allowStale } = peekOptions;
  1320. const index = this.#keyMap.get(k);
  1321. if (index === undefined ||
  1322. (!allowStale && this.#isStale(index))) {
  1323. return;
  1324. }
  1325. const v = this.#valList[index];
  1326. // either stale and allowed, or forcing a refresh of non-stale value
  1327. return this.#isBackgroundFetch(v) ? v.__staleWhileFetching : v;
  1328. }
  1329. #backgroundFetch(k, index, options, context) {
  1330. const v = index === undefined ? undefined : this.#valList[index];
  1331. if (this.#isBackgroundFetch(v)) {
  1332. return v;
  1333. }
  1334. const ac = new AC();
  1335. const { signal } = options;
  1336. // when/if our AC signals, then stop listening to theirs.
  1337. signal?.addEventListener('abort', () => ac.abort(signal.reason), {
  1338. signal: ac.signal,
  1339. });
  1340. const fetchOpts = {
  1341. signal: ac.signal,
  1342. options,
  1343. context,
  1344. };
  1345. const cb = (v, updateCache = false) => {
  1346. const { aborted } = ac.signal;
  1347. const ignoreAbort = options.ignoreFetchAbort && v !== undefined;
  1348. if (options.status) {
  1349. if (aborted && !updateCache) {
  1350. options.status.fetchAborted = true;
  1351. options.status.fetchError = ac.signal.reason;
  1352. if (ignoreAbort)
  1353. options.status.fetchAbortIgnored = true;
  1354. }
  1355. else {
  1356. options.status.fetchResolved = true;
  1357. }
  1358. }
  1359. if (aborted && !ignoreAbort && !updateCache) {
  1360. return fetchFail(ac.signal.reason);
  1361. }
  1362. // either we didn't abort, and are still here, or we did, and ignored
  1363. const bf = p;
  1364. if (this.#valList[index] === p) {
  1365. if (v === undefined) {
  1366. if (bf.__staleWhileFetching) {
  1367. this.#valList[index] = bf.__staleWhileFetching;
  1368. }
  1369. else {
  1370. this.delete(k);
  1371. }
  1372. }
  1373. else {
  1374. if (options.status)
  1375. options.status.fetchUpdated = true;
  1376. this.set(k, v, fetchOpts.options);
  1377. }
  1378. }
  1379. return v;
  1380. };
  1381. const eb = (er) => {
  1382. if (options.status) {
  1383. options.status.fetchRejected = true;
  1384. options.status.fetchError = er;
  1385. }
  1386. return fetchFail(er);
  1387. };
  1388. const fetchFail = (er) => {
  1389. const { aborted } = ac.signal;
  1390. const allowStaleAborted = aborted && options.allowStaleOnFetchAbort;
  1391. const allowStale = allowStaleAborted || options.allowStaleOnFetchRejection;
  1392. const noDelete = allowStale || options.noDeleteOnFetchRejection;
  1393. const bf = p;
  1394. if (this.#valList[index] === p) {
  1395. // if we allow stale on fetch rejections, then we need to ensure that
  1396. // the stale value is not removed from the cache when the fetch fails.
  1397. const del = !noDelete || bf.__staleWhileFetching === undefined;
  1398. if (del) {
  1399. this.delete(k);
  1400. }
  1401. else if (!allowStaleAborted) {
  1402. // still replace the *promise* with the stale value,
  1403. // since we are done with the promise at this point.
  1404. // leave it untouched if we're still waiting for an
  1405. // aborted background fetch that hasn't yet returned.
  1406. this.#valList[index] = bf.__staleWhileFetching;
  1407. }
  1408. }
  1409. if (allowStale) {
  1410. if (options.status && bf.__staleWhileFetching !== undefined) {
  1411. options.status.returnedStale = true;
  1412. }
  1413. return bf.__staleWhileFetching;
  1414. }
  1415. else if (bf.__returned === bf) {
  1416. throw er;
  1417. }
  1418. };
  1419. const pcall = (res, rej) => {
  1420. const fmp = this.#fetchMethod?.(k, v, fetchOpts);
  1421. if (fmp && fmp instanceof Promise) {
  1422. fmp.then(v => res(v === undefined ? undefined : v), rej);
  1423. }
  1424. // ignored, we go until we finish, regardless.
  1425. // defer check until we are actually aborting,
  1426. // so fetchMethod can override.
  1427. ac.signal.addEventListener('abort', () => {
  1428. if (!options.ignoreFetchAbort ||
  1429. options.allowStaleOnFetchAbort) {
  1430. res(undefined);
  1431. // when it eventually resolves, update the cache.
  1432. if (options.allowStaleOnFetchAbort) {
  1433. res = v => cb(v, true);
  1434. }
  1435. }
  1436. });
  1437. };
  1438. if (options.status)
  1439. options.status.fetchDispatched = true;
  1440. const p = new Promise(pcall).then(cb, eb);
  1441. const bf = Object.assign(p, {
  1442. __abortController: ac,
  1443. __staleWhileFetching: v,
  1444. __returned: undefined,
  1445. });
  1446. if (index === undefined) {
  1447. // internal, don't expose status.
  1448. this.set(k, bf, { ...fetchOpts.options, status: undefined });
  1449. index = this.#keyMap.get(k);
  1450. }
  1451. else {
  1452. this.#valList[index] = bf;
  1453. }
  1454. return bf;
  1455. }
  1456. #isBackgroundFetch(p) {
  1457. if (!this.#hasFetchMethod)
  1458. return false;
  1459. const b = p;
  1460. return (!!b &&
  1461. b instanceof Promise &&
  1462. b.hasOwnProperty('__staleWhileFetching') &&
  1463. b.__abortController instanceof AC);
  1464. }
  1465. async fetch(k, fetchOptions = {}) {
  1466. const {
  1467. // get options
  1468. allowStale = this.allowStale, updateAgeOnGet = this.updateAgeOnGet, noDeleteOnStaleGet = this.noDeleteOnStaleGet,
  1469. // set options
  1470. ttl = this.ttl, noDisposeOnSet = this.noDisposeOnSet, size = 0, sizeCalculation = this.sizeCalculation, noUpdateTTL = this.noUpdateTTL,
  1471. // fetch exclusive options
  1472. noDeleteOnFetchRejection = this.noDeleteOnFetchRejection, allowStaleOnFetchRejection = this.allowStaleOnFetchRejection, ignoreFetchAbort = this.ignoreFetchAbort, allowStaleOnFetchAbort = this.allowStaleOnFetchAbort, context, forceRefresh = false, status, signal, } = fetchOptions;
  1473. if (!this.#hasFetchMethod) {
  1474. if (status)
  1475. status.fetch = 'get';
  1476. return this.get(k, {
  1477. allowStale,
  1478. updateAgeOnGet,
  1479. noDeleteOnStaleGet,
  1480. status,
  1481. });
  1482. }
  1483. const options = {
  1484. allowStale,
  1485. updateAgeOnGet,
  1486. noDeleteOnStaleGet,
  1487. ttl,
  1488. noDisposeOnSet,
  1489. size,
  1490. sizeCalculation,
  1491. noUpdateTTL,
  1492. noDeleteOnFetchRejection,
  1493. allowStaleOnFetchRejection,
  1494. allowStaleOnFetchAbort,
  1495. ignoreFetchAbort,
  1496. status,
  1497. signal,
  1498. };
  1499. let index = this.#keyMap.get(k);
  1500. if (index === undefined) {
  1501. if (status)
  1502. status.fetch = 'miss';
  1503. const p = this.#backgroundFetch(k, index, options, context);
  1504. return (p.__returned = p);
  1505. }
  1506. else {
  1507. // in cache, maybe already fetching
  1508. const v = this.#valList[index];
  1509. if (this.#isBackgroundFetch(v)) {
  1510. const stale = allowStale && v.__staleWhileFetching !== undefined;
  1511. if (status) {
  1512. status.fetch = 'inflight';
  1513. if (stale)
  1514. status.returnedStale = true;
  1515. }
  1516. return stale ? v.__staleWhileFetching : (v.__returned = v);
  1517. }
  1518. // if we force a refresh, that means do NOT serve the cached value,
  1519. // unless we are already in the process of refreshing the cache.
  1520. const isStale = this.#isStale(index);
  1521. if (!forceRefresh && !isStale) {
  1522. if (status)
  1523. status.fetch = 'hit';
  1524. this.#moveToTail(index);
  1525. if (updateAgeOnGet) {
  1526. this.#updateItemAge(index);
  1527. }
  1528. if (status)
  1529. this.#statusTTL(status, index);
  1530. return v;
  1531. }
  1532. // ok, it is stale or a forced refresh, and not already fetching.
  1533. // refresh the cache.
  1534. const p = this.#backgroundFetch(k, index, options, context);
  1535. const hasStale = p.__staleWhileFetching !== undefined;
  1536. const staleVal = hasStale && allowStale;
  1537. if (status) {
  1538. status.fetch = isStale ? 'stale' : 'refresh';
  1539. if (staleVal && isStale)
  1540. status.returnedStale = true;
  1541. }
  1542. return staleVal ? p.__staleWhileFetching : (p.__returned = p);
  1543. }
  1544. }
  1545. /**
  1546. * Return a value from the cache. Will update the recency of the cache
  1547. * entry found.
  1548. *
  1549. * If the key is not found, get() will return `undefined`.
  1550. */
  1551. get(k, getOptions = {}) {
  1552. const { allowStale = this.allowStale, updateAgeOnGet = this.updateAgeOnGet, noDeleteOnStaleGet = this.noDeleteOnStaleGet, status, } = getOptions;
  1553. const index = this.#keyMap.get(k);
  1554. if (index !== undefined) {
  1555. const value = this.#valList[index];
  1556. const fetching = this.#isBackgroundFetch(value);
  1557. if (status)
  1558. this.#statusTTL(status, index);
  1559. if (this.#isStale(index)) {
  1560. if (status)
  1561. status.get = 'stale';
  1562. // delete only if not an in-flight background fetch
  1563. if (!fetching) {
  1564. if (!noDeleteOnStaleGet) {
  1565. this.delete(k);
  1566. }
  1567. if (status && allowStale)
  1568. status.returnedStale = true;
  1569. return allowStale ? value : undefined;
  1570. }
  1571. else {
  1572. if (status &&
  1573. allowStale &&
  1574. value.__staleWhileFetching !== undefined) {
  1575. status.returnedStale = true;
  1576. }
  1577. return allowStale ? value.__staleWhileFetching : undefined;
  1578. }
  1579. }
  1580. else {
  1581. if (status)
  1582. status.get = 'hit';
  1583. // if we're currently fetching it, we don't actually have it yet
  1584. // it's not stale, which means this isn't a staleWhileRefetching.
  1585. // If it's not stale, and fetching, AND has a __staleWhileFetching
  1586. // value, then that means the user fetched with {forceRefresh:true},
  1587. // so it's safe to return that value.
  1588. if (fetching) {
  1589. return value.__staleWhileFetching;
  1590. }
  1591. this.#moveToTail(index);
  1592. if (updateAgeOnGet) {
  1593. this.#updateItemAge(index);
  1594. }
  1595. return value;
  1596. }
  1597. }
  1598. else if (status) {
  1599. status.get = 'miss';
  1600. }
  1601. }
  1602. #connect(p, n) {
  1603. this.#prev[n] = p;
  1604. this.#next[p] = n;
  1605. }
  1606. #moveToTail(index) {
  1607. // if tail already, nothing to do
  1608. // if head, move head to next[index]
  1609. // else
  1610. // move next[prev[index]] to next[index] (head has no prev)
  1611. // move prev[next[index]] to prev[index]
  1612. // prev[index] = tail
  1613. // next[tail] = index
  1614. // tail = index
  1615. if (index !== this.#tail) {
  1616. if (index === this.#head) {
  1617. this.#head = this.#next[index];
  1618. }
  1619. else {
  1620. this.#connect(this.#prev[index], this.#next[index]);
  1621. }
  1622. this.#connect(this.#tail, index);
  1623. this.#tail = index;
  1624. }
  1625. }
  1626. /**
  1627. * Deletes a key out of the cache.
  1628. * Returns true if the key was deleted, false otherwise.
  1629. */
  1630. delete(k) {
  1631. let deleted = false;
  1632. if (this.#size !== 0) {
  1633. const index = this.#keyMap.get(k);
  1634. if (index !== undefined) {
  1635. deleted = true;
  1636. if (this.#size === 1) {
  1637. this.clear();
  1638. }
  1639. else {
  1640. this.#removeItemSize(index);
  1641. const v = this.#valList[index];
  1642. if (this.#isBackgroundFetch(v)) {
  1643. v.__abortController.abort(new Error('deleted'));
  1644. }
  1645. else if (this.#hasDispose || this.#hasDisposeAfter) {
  1646. if (this.#hasDispose) {
  1647. this.#dispose?.(v, k, 'delete');
  1648. }
  1649. if (this.#hasDisposeAfter) {
  1650. this.#disposed?.push([v, k, 'delete']);
  1651. }
  1652. }
  1653. this.#keyMap.delete(k);
  1654. this.#keyList[index] = undefined;
  1655. this.#valList[index] = undefined;
  1656. if (index === this.#tail) {
  1657. this.#tail = this.#prev[index];
  1658. }
  1659. else if (index === this.#head) {
  1660. this.#head = this.#next[index];
  1661. }
  1662. else {
  1663. const pi = this.#prev[index];
  1664. this.#next[pi] = this.#next[index];
  1665. const ni = this.#next[index];
  1666. this.#prev[ni] = this.#prev[index];
  1667. }
  1668. this.#size--;
  1669. this.#free.push(index);
  1670. }
  1671. }
  1672. }
  1673. if (this.#hasDisposeAfter && this.#disposed?.length) {
  1674. const dt = this.#disposed;
  1675. let task;
  1676. while ((task = dt?.shift())) {
  1677. this.#disposeAfter?.(...task);
  1678. }
  1679. }
  1680. return deleted;
  1681. }
  1682. /**
  1683. * Clear the cache entirely, throwing away all values.
  1684. */
  1685. clear() {
  1686. for (const index of this.#rindexes({ allowStale: true })) {
  1687. const v = this.#valList[index];
  1688. if (this.#isBackgroundFetch(v)) {
  1689. v.__abortController.abort(new Error('deleted'));
  1690. }
  1691. else {
  1692. const k = this.#keyList[index];
  1693. if (this.#hasDispose) {
  1694. this.#dispose?.(v, k, 'delete');
  1695. }
  1696. if (this.#hasDisposeAfter) {
  1697. this.#disposed?.push([v, k, 'delete']);
  1698. }
  1699. }
  1700. }
  1701. this.#keyMap.clear();
  1702. this.#valList.fill(undefined);
  1703. this.#keyList.fill(undefined);
  1704. if (this.#ttls && this.#starts) {
  1705. this.#ttls.fill(0);
  1706. this.#starts.fill(0);
  1707. }
  1708. if (this.#sizes) {
  1709. this.#sizes.fill(0);
  1710. }
  1711. this.#head = 0;
  1712. this.#tail = 0;
  1713. this.#free.length = 0;
  1714. this.#calculatedSize = 0;
  1715. this.#size = 0;
  1716. if (this.#hasDisposeAfter && this.#disposed) {
  1717. const dt = this.#disposed;
  1718. let task;
  1719. while ((task = dt?.shift())) {
  1720. this.#disposeAfter?.(...task);
  1721. }
  1722. }
  1723. }
  1724. }
  1725. function createCache(max = 500) {
  1726. return new LRUCache({ max });
  1727. }
  1728. function isImportUsed(local, sfc) {
  1729. return resolveTemplateUsedIdentifiers(sfc).has(local);
  1730. }
  1731. const templateUsageCheckCache = createCache();
  1732. function resolveTemplateUsedIdentifiers(sfc) {
  1733. const { content, ast } = sfc.template;
  1734. const cached = templateUsageCheckCache.get(content);
  1735. if (cached) {
  1736. return cached;
  1737. }
  1738. const ids = /* @__PURE__ */ new Set();
  1739. ast.children.forEach(walk);
  1740. function walk(node) {
  1741. var _a;
  1742. switch (node.type) {
  1743. case 1:
  1744. let tag = node.tag;
  1745. if (tag.includes("."))
  1746. tag = tag.split(".")[0].trim();
  1747. if (!CompilerDOM.parserOptions.isNativeTag(tag) && !CompilerDOM.parserOptions.isBuiltInComponent(tag)) {
  1748. ids.add(shared.camelize(tag));
  1749. ids.add(shared.capitalize(shared.camelize(tag)));
  1750. }
  1751. for (let i = 0; i < node.props.length; i++) {
  1752. const prop = node.props[i];
  1753. if (prop.type === 7) {
  1754. if (!shared.isBuiltInDirective(prop.name)) {
  1755. ids.add(`v${shared.capitalize(shared.camelize(prop.name))}`);
  1756. }
  1757. if (prop.arg && !prop.arg.isStatic) {
  1758. extractIdentifiers(ids, prop.arg);
  1759. }
  1760. if (prop.name === "for") {
  1761. extractIdentifiers(ids, prop.forParseResult.source);
  1762. } else if (prop.exp) {
  1763. extractIdentifiers(ids, prop.exp);
  1764. }
  1765. }
  1766. if (prop.type === 6 && prop.name === "ref" && ((_a = prop.value) == null ? void 0 : _a.content)) {
  1767. ids.add(prop.value.content);
  1768. }
  1769. }
  1770. node.children.forEach(walk);
  1771. break;
  1772. case 5:
  1773. extractIdentifiers(ids, node.content);
  1774. break;
  1775. }
  1776. }
  1777. templateUsageCheckCache.set(content, ids);
  1778. return ids;
  1779. }
  1780. function extractIdentifiers(ids, node) {
  1781. if (node.ast) {
  1782. CompilerDOM.walkIdentifiers(node.ast, (n) => ids.add(n.name));
  1783. } else if (node.ast === null) {
  1784. ids.add(node.content);
  1785. }
  1786. }
  1787. const DEFAULT_FILENAME = "anonymous.vue";
  1788. const parseCache$1 = createCache();
  1789. function genCacheKey(source, options) {
  1790. var _a;
  1791. return source + JSON.stringify(
  1792. {
  1793. ...options,
  1794. compiler: { parse: (_a = options.compiler) == null ? void 0 : _a.parse }
  1795. },
  1796. (_, val) => typeof val === "function" ? val.toString() : val
  1797. );
  1798. }
  1799. function parse$2(source, options = {}) {
  1800. const sourceKey = genCacheKey(source, options);
  1801. const cache = parseCache$1.get(sourceKey);
  1802. if (cache) {
  1803. return cache;
  1804. }
  1805. const {
  1806. sourceMap = true,
  1807. filename = DEFAULT_FILENAME,
  1808. sourceRoot = "",
  1809. pad = false,
  1810. ignoreEmpty = true,
  1811. compiler = CompilerDOM__namespace,
  1812. templateParseOptions = {},
  1813. parseExpressions = true
  1814. } = options;
  1815. const descriptor = {
  1816. filename,
  1817. source,
  1818. template: null,
  1819. script: null,
  1820. scriptSetup: null,
  1821. styles: [],
  1822. customBlocks: [],
  1823. cssVars: [],
  1824. slotted: false,
  1825. shouldForceReload: (prevImports) => hmrShouldReload(prevImports, descriptor)
  1826. };
  1827. const errors = [];
  1828. const ast = compiler.parse(source, {
  1829. parseMode: "sfc",
  1830. prefixIdentifiers: parseExpressions,
  1831. ...templateParseOptions,
  1832. onError: (e) => {
  1833. errors.push(e);
  1834. }
  1835. });
  1836. ast.children.forEach((node) => {
  1837. if (node.type !== 1) {
  1838. return;
  1839. }
  1840. if (ignoreEmpty && node.tag !== "template" && isEmpty(node) && !hasSrc(node)) {
  1841. return;
  1842. }
  1843. switch (node.tag) {
  1844. case "template":
  1845. if (!descriptor.template) {
  1846. const templateBlock = descriptor.template = createBlock(
  1847. node,
  1848. source,
  1849. false
  1850. );
  1851. if (!templateBlock.attrs.src) {
  1852. templateBlock.ast = compilerCore.createRoot(node.children, source);
  1853. }
  1854. if (templateBlock.attrs.functional) {
  1855. const err = new SyntaxError(
  1856. `<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.`
  1857. );
  1858. err.loc = node.props.find(
  1859. (p) => p.type === 6 && p.name === "functional"
  1860. ).loc;
  1861. errors.push(err);
  1862. }
  1863. } else {
  1864. errors.push(createDuplicateBlockError(node));
  1865. }
  1866. break;
  1867. case "script":
  1868. const scriptBlock = createBlock(node, source, pad);
  1869. const isSetup = !!scriptBlock.attrs.setup;
  1870. if (isSetup && !descriptor.scriptSetup) {
  1871. descriptor.scriptSetup = scriptBlock;
  1872. break;
  1873. }
  1874. if (!isSetup && !descriptor.script) {
  1875. descriptor.script = scriptBlock;
  1876. break;
  1877. }
  1878. errors.push(createDuplicateBlockError(node, isSetup));
  1879. break;
  1880. case "style":
  1881. const styleBlock = createBlock(node, source, pad);
  1882. if (styleBlock.attrs.vars) {
  1883. errors.push(
  1884. new SyntaxError(
  1885. `<style vars> has been replaced by a new proposal: https://github.com/vuejs/rfcs/pull/231`
  1886. )
  1887. );
  1888. }
  1889. descriptor.styles.push(styleBlock);
  1890. break;
  1891. default:
  1892. descriptor.customBlocks.push(createBlock(node, source, pad));
  1893. break;
  1894. }
  1895. });
  1896. if (!descriptor.template && !descriptor.script && !descriptor.scriptSetup) {
  1897. errors.push(
  1898. new SyntaxError(
  1899. `At least one <template> or <script> is required in a single file component.`
  1900. )
  1901. );
  1902. }
  1903. if (descriptor.scriptSetup) {
  1904. if (descriptor.scriptSetup.src) {
  1905. errors.push(
  1906. new SyntaxError(
  1907. `<script setup> cannot use the "src" attribute because its syntax will be ambiguous outside of the component.`
  1908. )
  1909. );
  1910. descriptor.scriptSetup = null;
  1911. }
  1912. if (descriptor.script && descriptor.script.src) {
  1913. errors.push(
  1914. new SyntaxError(
  1915. `<script> cannot use the "src" attribute when <script setup> is also present because they must be processed together.`
  1916. )
  1917. );
  1918. descriptor.script = null;
  1919. }
  1920. }
  1921. let templateColumnOffset = 0;
  1922. if (descriptor.template && (descriptor.template.lang === "pug" || descriptor.template.lang === "jade")) {
  1923. [descriptor.template.content, templateColumnOffset] = dedent(
  1924. descriptor.template.content
  1925. );
  1926. }
  1927. if (sourceMap) {
  1928. const genMap = (block, columnOffset = 0) => {
  1929. if (block && !block.src) {
  1930. block.map = generateSourceMap(
  1931. filename,
  1932. source,
  1933. block.content,
  1934. sourceRoot,
  1935. !pad || block.type === "template" ? block.loc.start.line - 1 : 0,
  1936. columnOffset
  1937. );
  1938. }
  1939. };
  1940. genMap(descriptor.template, templateColumnOffset);
  1941. genMap(descriptor.script);
  1942. descriptor.styles.forEach((s) => genMap(s));
  1943. descriptor.customBlocks.forEach((s) => genMap(s));
  1944. }
  1945. descriptor.cssVars = parseCssVars(descriptor);
  1946. const slottedRE = /(?:::v-|:)slotted\(/;
  1947. descriptor.slotted = descriptor.styles.some(
  1948. (s) => s.scoped && slottedRE.test(s.content)
  1949. );
  1950. const result = {
  1951. descriptor,
  1952. errors
  1953. };
  1954. parseCache$1.set(sourceKey, result);
  1955. return result;
  1956. }
  1957. function createDuplicateBlockError(node, isScriptSetup = false) {
  1958. const err = new SyntaxError(
  1959. `Single file component can contain only one <${node.tag}${isScriptSetup ? ` setup` : ``}> element`
  1960. );
  1961. err.loc = node.loc;
  1962. return err;
  1963. }
  1964. function createBlock(node, source, pad) {
  1965. const type = node.tag;
  1966. const loc = node.innerLoc;
  1967. const attrs = {};
  1968. const block = {
  1969. type,
  1970. content: source.slice(loc.start.offset, loc.end.offset),
  1971. loc,
  1972. attrs
  1973. };
  1974. if (pad) {
  1975. block.content = padContent(source, block, pad) + block.content;
  1976. }
  1977. node.props.forEach((p) => {
  1978. if (p.type === 6) {
  1979. const name = p.name;
  1980. attrs[name] = p.value ? p.value.content || true : true;
  1981. if (name === "lang") {
  1982. block.lang = p.value && p.value.content;
  1983. } else if (name === "src") {
  1984. block.src = p.value && p.value.content;
  1985. } else if (type === "style") {
  1986. if (name === "scoped") {
  1987. block.scoped = true;
  1988. } else if (name === "module") {
  1989. block.module = attrs[name];
  1990. }
  1991. } else if (type === "script" && name === "setup") {
  1992. block.setup = attrs.setup;
  1993. }
  1994. }
  1995. });
  1996. return block;
  1997. }
  1998. const splitRE = /\r?\n/g;
  1999. const emptyRE = /^(?:\/\/)?\s*$/;
  2000. const replaceRE = /./g;
  2001. function generateSourceMap(filename, source, generated, sourceRoot, lineOffset, columnOffset) {
  2002. const map = new sourceMapJs.SourceMapGenerator({
  2003. file: filename.replace(/\\/g, "/"),
  2004. sourceRoot: sourceRoot.replace(/\\/g, "/")
  2005. });
  2006. map.setSourceContent(filename, source);
  2007. map._sources.add(filename);
  2008. generated.split(splitRE).forEach((line, index) => {
  2009. if (!emptyRE.test(line)) {
  2010. const originalLine = index + 1 + lineOffset;
  2011. const generatedLine = index + 1;
  2012. for (let i = 0; i < line.length; i++) {
  2013. if (!/\s/.test(line[i])) {
  2014. map._mappings.add({
  2015. originalLine,
  2016. originalColumn: i + columnOffset,
  2017. generatedLine,
  2018. generatedColumn: i,
  2019. source: filename,
  2020. // @ts-expect-error
  2021. name: null
  2022. });
  2023. }
  2024. }
  2025. }
  2026. });
  2027. return map.toJSON();
  2028. }
  2029. function padContent(content, block, pad) {
  2030. content = content.slice(0, block.loc.start.offset);
  2031. if (pad === "space") {
  2032. return content.replace(replaceRE, " ");
  2033. } else {
  2034. const offset = content.split(splitRE).length;
  2035. const padChar = block.type === "script" && !block.lang ? "//\n" : "\n";
  2036. return Array(offset).join(padChar);
  2037. }
  2038. }
  2039. function hasSrc(node) {
  2040. return node.props.some((p) => {
  2041. if (p.type !== 6) {
  2042. return false;
  2043. }
  2044. return p.name === "src";
  2045. });
  2046. }
  2047. function isEmpty(node) {
  2048. for (let i = 0; i < node.children.length; i++) {
  2049. const child = node.children[i];
  2050. if (child.type !== 2 || child.content.trim() !== "") {
  2051. return false;
  2052. }
  2053. }
  2054. return true;
  2055. }
  2056. function hmrShouldReload(prevImports, next) {
  2057. if (!next.scriptSetup || next.scriptSetup.lang !== "ts" && next.scriptSetup.lang !== "tsx") {
  2058. return false;
  2059. }
  2060. for (const key in prevImports) {
  2061. if (!prevImports[key].isUsedInTemplate && isImportUsed(key, next)) {
  2062. return true;
  2063. }
  2064. }
  2065. return false;
  2066. }
  2067. function dedent(s) {
  2068. const lines = s.split("\n");
  2069. const minIndent = lines.reduce(function(minIndent2, line) {
  2070. var _a, _b;
  2071. if (line.trim() === "") {
  2072. return minIndent2;
  2073. }
  2074. const indent = ((_b = (_a = line.match(/^\s*/)) == null ? void 0 : _a[0]) == null ? void 0 : _b.length) || 0;
  2075. return Math.min(indent, minIndent2);
  2076. }, Infinity);
  2077. if (minIndent === 0) {
  2078. return [s, minIndent];
  2079. }
  2080. return [
  2081. lines.map(function(line) {
  2082. return line.slice(minIndent);
  2083. }).join("\n"),
  2084. minIndent
  2085. ];
  2086. }
  2087. function isRelativeUrl(url) {
  2088. const firstChar = url.charAt(0);
  2089. return firstChar === "." || firstChar === "~" || firstChar === "@";
  2090. }
  2091. const externalRE = /^(https?:)?\/\//;
  2092. function isExternalUrl(url) {
  2093. return externalRE.test(url);
  2094. }
  2095. const dataUrlRE = /^\s*data:/i;
  2096. function isDataUrl(url) {
  2097. return dataUrlRE.test(url);
  2098. }
  2099. function parseUrl(url) {
  2100. const firstChar = url.charAt(0);
  2101. if (firstChar === "~") {
  2102. const secondChar = url.charAt(1);
  2103. url = url.slice(secondChar === "/" ? 2 : 1);
  2104. }
  2105. return parseUriParts(url);
  2106. }
  2107. function parseUriParts(urlString) {
  2108. return url.parse(shared.isString(urlString) ? urlString : "", false, true);
  2109. }
  2110. const defaultAssetUrlOptions = {
  2111. base: null,
  2112. includeAbsolute: false,
  2113. tags: {
  2114. video: ["src", "poster"],
  2115. source: ["src"],
  2116. img: ["src"],
  2117. image: ["xlink:href", "href"],
  2118. use: ["xlink:href", "href"]
  2119. }
  2120. };
  2121. const normalizeOptions = (options) => {
  2122. if (Object.keys(options).some((key) => shared.isArray(options[key]))) {
  2123. return {
  2124. ...defaultAssetUrlOptions,
  2125. tags: options
  2126. };
  2127. }
  2128. return {
  2129. ...defaultAssetUrlOptions,
  2130. ...options
  2131. };
  2132. };
  2133. const createAssetUrlTransformWithOptions = (options) => {
  2134. return (node, context) => transformAssetUrl(node, context, options);
  2135. };
  2136. const transformAssetUrl = (node, context, options = defaultAssetUrlOptions) => {
  2137. if (node.type === 1) {
  2138. if (!node.props.length) {
  2139. return;
  2140. }
  2141. const tags = options.tags || defaultAssetUrlOptions.tags;
  2142. const attrs = tags[node.tag];
  2143. const wildCardAttrs = tags["*"];
  2144. if (!attrs && !wildCardAttrs) {
  2145. return;
  2146. }
  2147. const assetAttrs = (attrs || []).concat(wildCardAttrs || []);
  2148. node.props.forEach((attr, index) => {
  2149. 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)) {
  2150. return;
  2151. }
  2152. const url = parseUrl(attr.value.content);
  2153. if (options.base && attr.value.content[0] === ".") {
  2154. const base = parseUrl(options.base);
  2155. const protocol = base.protocol || "";
  2156. const host = base.host ? protocol + "//" + base.host : "";
  2157. const basePath = base.path || "/";
  2158. attr.value.content = host + (path$3.posix || path$3).join(basePath, url.path + (url.hash || ""));
  2159. return;
  2160. }
  2161. const exp = getImportsExpressionExp(url.path, url.hash, attr.loc, context);
  2162. node.props[index] = {
  2163. type: 7,
  2164. name: "bind",
  2165. arg: compilerCore.createSimpleExpression(attr.name, true, attr.loc),
  2166. exp,
  2167. modifiers: [],
  2168. loc: attr.loc
  2169. };
  2170. });
  2171. }
  2172. };
  2173. function getImportsExpressionExp(path2, hash, loc, context) {
  2174. if (path2) {
  2175. let name;
  2176. let exp;
  2177. const existingIndex = context.imports.findIndex((i) => i.path === path2);
  2178. if (existingIndex > -1) {
  2179. name = `_imports_${existingIndex}`;
  2180. exp = context.imports[existingIndex].exp;
  2181. } else {
  2182. name = `_imports_${context.imports.length}`;
  2183. exp = compilerCore.createSimpleExpression(
  2184. name,
  2185. false,
  2186. loc,
  2187. 3
  2188. );
  2189. context.imports.push({
  2190. exp,
  2191. path: decodeURIComponent(path2)
  2192. });
  2193. }
  2194. if (!hash) {
  2195. return exp;
  2196. }
  2197. const hashExp = `${name} + '${hash}'`;
  2198. const finalExp = compilerCore.createSimpleExpression(
  2199. hashExp,
  2200. false,
  2201. loc,
  2202. 3
  2203. );
  2204. if (!context.hoistStatic) {
  2205. return finalExp;
  2206. }
  2207. const existingHoistIndex = context.hoists.findIndex((h) => {
  2208. return h && h.type === 4 && !h.isStatic && h.content === hashExp;
  2209. });
  2210. if (existingHoistIndex > -1) {
  2211. return compilerCore.createSimpleExpression(
  2212. `_hoisted_${existingHoistIndex + 1}`,
  2213. false,
  2214. loc,
  2215. 3
  2216. );
  2217. }
  2218. return context.hoist(finalExp);
  2219. } else {
  2220. return compilerCore.createSimpleExpression(`''`, false, loc, 3);
  2221. }
  2222. }
  2223. const srcsetTags = ["img", "source"];
  2224. const escapedSpaceCharacters = /( |\\t|\\n|\\f|\\r)+/g;
  2225. const createSrcsetTransformWithOptions = (options) => {
  2226. return (node, context) => transformSrcset(node, context, options);
  2227. };
  2228. const transformSrcset = (node, context, options = defaultAssetUrlOptions) => {
  2229. if (node.type === 1) {
  2230. if (srcsetTags.includes(node.tag) && node.props.length) {
  2231. node.props.forEach((attr, index) => {
  2232. if (attr.name === "srcset" && attr.type === 6) {
  2233. if (!attr.value)
  2234. return;
  2235. const value = attr.value.content;
  2236. if (!value)
  2237. return;
  2238. const imageCandidates = value.split(",").map((s) => {
  2239. const [url, descriptor] = s.replace(escapedSpaceCharacters, " ").trim().split(" ", 2);
  2240. return { url, descriptor };
  2241. });
  2242. for (let i = 0; i < imageCandidates.length; i++) {
  2243. const { url } = imageCandidates[i];
  2244. if (isDataUrl(url)) {
  2245. imageCandidates[i + 1].url = url + "," + imageCandidates[i + 1].url;
  2246. imageCandidates.splice(i, 1);
  2247. }
  2248. }
  2249. const shouldProcessUrl = (url) => {
  2250. return !isExternalUrl(url) && !isDataUrl(url) && (options.includeAbsolute || isRelativeUrl(url));
  2251. };
  2252. if (!imageCandidates.some(({ url }) => shouldProcessUrl(url))) {
  2253. return;
  2254. }
  2255. if (options.base) {
  2256. const base = options.base;
  2257. const set = [];
  2258. let needImportTransform = false;
  2259. imageCandidates.forEach((candidate) => {
  2260. let { url, descriptor } = candidate;
  2261. descriptor = descriptor ? ` ${descriptor}` : ``;
  2262. if (url[0] === ".") {
  2263. candidate.url = (path$3.posix || path$3).join(base, url);
  2264. set.push(candidate.url + descriptor);
  2265. } else if (shouldProcessUrl(url)) {
  2266. needImportTransform = true;
  2267. } else {
  2268. set.push(url + descriptor);
  2269. }
  2270. });
  2271. if (!needImportTransform) {
  2272. attr.value.content = set.join(", ");
  2273. return;
  2274. }
  2275. }
  2276. const compoundExpression = compilerCore.createCompoundExpression([], attr.loc);
  2277. imageCandidates.forEach(({ url, descriptor }, index2) => {
  2278. if (shouldProcessUrl(url)) {
  2279. const { path: path2 } = parseUrl(url);
  2280. let exp2;
  2281. if (path2) {
  2282. const existingImportsIndex = context.imports.findIndex(
  2283. (i) => i.path === path2
  2284. );
  2285. if (existingImportsIndex > -1) {
  2286. exp2 = compilerCore.createSimpleExpression(
  2287. `_imports_${existingImportsIndex}`,
  2288. false,
  2289. attr.loc,
  2290. 3
  2291. );
  2292. } else {
  2293. exp2 = compilerCore.createSimpleExpression(
  2294. `_imports_${context.imports.length}`,
  2295. false,
  2296. attr.loc,
  2297. 3
  2298. );
  2299. context.imports.push({ exp: exp2, path: path2 });
  2300. }
  2301. compoundExpression.children.push(exp2);
  2302. }
  2303. } else {
  2304. const exp2 = compilerCore.createSimpleExpression(
  2305. `"${url}"`,
  2306. false,
  2307. attr.loc,
  2308. 3
  2309. );
  2310. compoundExpression.children.push(exp2);
  2311. }
  2312. const isNotLast = imageCandidates.length - 1 > index2;
  2313. if (descriptor && isNotLast) {
  2314. compoundExpression.children.push(` + ' ${descriptor}, ' + `);
  2315. } else if (descriptor) {
  2316. compoundExpression.children.push(` + ' ${descriptor}'`);
  2317. } else if (isNotLast) {
  2318. compoundExpression.children.push(` + ', ' + `);
  2319. }
  2320. });
  2321. let exp = compoundExpression;
  2322. if (context.hoistStatic) {
  2323. exp = context.hoist(compoundExpression);
  2324. exp.constType = 3;
  2325. }
  2326. node.props[index] = {
  2327. type: 7,
  2328. name: "bind",
  2329. arg: compilerCore.createSimpleExpression("srcset", true, attr.loc),
  2330. exp,
  2331. modifiers: [],
  2332. loc: attr.loc
  2333. };
  2334. }
  2335. });
  2336. }
  2337. }
  2338. };
  2339. function commonjsRequire(path) {
  2340. 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.');
  2341. }
  2342. var consolidate$2 = {exports: {}};
  2343. (function (module, exports) {
  2344. /*
  2345. * Engines which do not support caching of their file contents
  2346. * should use the `read()` function defined in consolidate.js
  2347. * On top of this, when an engine compiles to a `Function`,
  2348. * these functions should either be cached within consolidate.js
  2349. * or the engine itself via `options.cache`. This will allow
  2350. * users and frameworks to pass `options.cache = true` for
  2351. * `NODE_ENV=production`, however edit the file(s) without
  2352. * re-loading the application in development.
  2353. */
  2354. /**
  2355. * Module dependencies.
  2356. */
  2357. var fs = require$$0;
  2358. var path = path$3;
  2359. var util = require$$2;
  2360. var join = path.join;
  2361. var resolve = path.resolve;
  2362. var extname = path.extname;
  2363. var dirname = path.dirname;
  2364. var isAbsolute = path.isAbsolute;
  2365. var readCache = {};
  2366. /**
  2367. * Require cache.
  2368. */
  2369. var cacheStore = {};
  2370. /**
  2371. * Require cache.
  2372. */
  2373. var requires = {};
  2374. /**
  2375. * Clear the cache.
  2376. *
  2377. * @api public
  2378. */
  2379. exports.clearCache = function() {
  2380. readCache = {};
  2381. cacheStore = {};
  2382. };
  2383. /**
  2384. * Conditionally cache `compiled` template based
  2385. * on the `options` filename and `.cache` boolean.
  2386. *
  2387. * @param {Object} options
  2388. * @param {Function} compiled
  2389. * @return {Function}
  2390. * @api private
  2391. */
  2392. function cache(options, compiled) {
  2393. // cachable
  2394. if (compiled && options.filename && options.cache) {
  2395. delete readCache[options.filename];
  2396. cacheStore[options.filename] = compiled;
  2397. return compiled;
  2398. }
  2399. // check cache
  2400. if (options.filename && options.cache) {
  2401. return cacheStore[options.filename];
  2402. }
  2403. return compiled;
  2404. }
  2405. /**
  2406. * Read `path` with `options` with
  2407. * callback `(err, str)`. When `options.cache`
  2408. * is true the template string will be cached.
  2409. *
  2410. * @param {String} options
  2411. * @param {Function} cb
  2412. * @api private
  2413. */
  2414. function read(path, options, cb) {
  2415. var str = readCache[path];
  2416. var cached = options.cache && str && typeof str === 'string';
  2417. // cached (only if cached is a string and not a compiled template function)
  2418. if (cached) return cb(null, str);
  2419. // read
  2420. fs.readFile(path, 'utf8', function(err, str) {
  2421. if (err) return cb(err);
  2422. // remove extraneous utf8 BOM marker
  2423. str = str.replace(/^\uFEFF/, '');
  2424. if (options.cache) readCache[path] = str;
  2425. cb(null, str);
  2426. });
  2427. }
  2428. /**
  2429. * Read `path` with `options` with
  2430. * callback `(err, str)`. When `options.cache`
  2431. * is true the partial string will be cached.
  2432. *
  2433. * @param {String} options
  2434. * @param {Function} fn
  2435. * @api private
  2436. */
  2437. function readPartials(path, options, cb) {
  2438. if (!options.partials) return cb();
  2439. var keys = Object.keys(options.partials);
  2440. var partials = {};
  2441. function next(index) {
  2442. if (index === keys.length) return cb(null, partials);
  2443. var key = keys[index];
  2444. var partialPath = options.partials[key];
  2445. if (partialPath === undefined || partialPath === null || partialPath === false) {
  2446. return next(++index);
  2447. }
  2448. var file;
  2449. if (isAbsolute(partialPath)) {
  2450. if (extname(partialPath) !== '') {
  2451. file = partialPath;
  2452. } else {
  2453. file = join(partialPath + extname(path));
  2454. }
  2455. } else {
  2456. file = join(dirname(path), partialPath + extname(path));
  2457. }
  2458. read(file, options, function(err, str) {
  2459. if (err) return cb(err);
  2460. partials[key] = str;
  2461. next(++index);
  2462. });
  2463. }
  2464. next(0);
  2465. }
  2466. /**
  2467. * promisify
  2468. */
  2469. function promisify(cb, fn) {
  2470. return new Promise(function(resolve, reject) {
  2471. cb = cb || function(err, html) {
  2472. if (err) {
  2473. return reject(err);
  2474. }
  2475. resolve(html);
  2476. };
  2477. fn(cb);
  2478. });
  2479. }
  2480. /**
  2481. * fromStringRenderer
  2482. */
  2483. function fromStringRenderer(name) {
  2484. return function(path, options, cb) {
  2485. options.filename = path;
  2486. return promisify(cb, function(cb) {
  2487. readPartials(path, options, function(err, partials) {
  2488. var extend = (requires.extend || (requires.extend = require$$2._extend));
  2489. var opts = extend({}, options);
  2490. opts.partials = partials;
  2491. if (err) return cb(err);
  2492. if (cache(opts)) {
  2493. exports[name].render('', opts, cb);
  2494. } else {
  2495. read(path, opts, function(err, str) {
  2496. if (err) return cb(err);
  2497. exports[name].render(str, opts, cb);
  2498. });
  2499. }
  2500. });
  2501. });
  2502. };
  2503. }
  2504. /**
  2505. * velocity support.
  2506. */
  2507. exports.velocityjs = fromStringRenderer('velocityjs');
  2508. /**
  2509. * velocity string support.
  2510. */
  2511. exports.velocityjs.render = function(str, options, cb) {
  2512. return promisify(cb, function(cb) {
  2513. var engine = requires.velocityjs || (requires.velocityjs = require('velocityjs'));
  2514. try {
  2515. options.locals = options;
  2516. cb(null, engine.render(str, options).trimLeft());
  2517. } catch (err) {
  2518. cb(err);
  2519. }
  2520. });
  2521. };
  2522. /**
  2523. * Liquid support.
  2524. */
  2525. exports.liquid = fromStringRenderer('liquid');
  2526. /**
  2527. * Liquid string support.
  2528. */
  2529. /**
  2530. * Note that in order to get filters and custom tags we've had to push
  2531. * all user-defined locals down into @locals. However, just to make things
  2532. * backwards-compatible, any property of `options` that is left after
  2533. * processing and removing `locals`, `meta`, `filters`, `customTags` and
  2534. * `includeDir` will also become a local.
  2535. */
  2536. function _renderTinyliquid(engine, str, options, cb) {
  2537. var context = engine.newContext();
  2538. var k;
  2539. /**
  2540. * Note that there's a bug in the library that doesn't allow us to pass
  2541. * the locals to newContext(), hence looping through the keys:
  2542. */
  2543. if (options.locals) {
  2544. for (k in options.locals) {
  2545. context.setLocals(k, options.locals[k]);
  2546. }
  2547. delete options.locals;
  2548. }
  2549. if (options.meta) {
  2550. context.setLocals('page', options.meta);
  2551. delete options.meta;
  2552. }
  2553. /**
  2554. * Add any defined filters:
  2555. */
  2556. if (options.filters) {
  2557. for (k in options.filters) {
  2558. context.setFilter(k, options.filters[k]);
  2559. }
  2560. delete options.filters;
  2561. }
  2562. /**
  2563. * Set up a callback for the include directory:
  2564. */
  2565. var includeDir = options.includeDir || process.cwd();
  2566. context.onInclude(function(name, callback) {
  2567. var extname = path.extname(name) ? '' : '.liquid';
  2568. var filename = path.resolve(includeDir, name + extname);
  2569. fs.readFile(filename, {encoding: 'utf8'}, function(err, data) {
  2570. if (err) return callback(err);
  2571. callback(null, engine.parse(data));
  2572. });
  2573. });
  2574. delete options.includeDir;
  2575. /**
  2576. * The custom tag functions need to have their results pushed back
  2577. * through the parser, so set up a shim before calling the provided
  2578. * callback:
  2579. */
  2580. var compileOptions = {
  2581. customTags: {}
  2582. };
  2583. if (options.customTags) {
  2584. var tagFunctions = options.customTags;
  2585. for (k in options.customTags) {
  2586. /*Tell jshint there's no problem with having this function in the loop */
  2587. /*jshint -W083 */
  2588. compileOptions.customTags[k] = function(context, name, body) {
  2589. var tpl = tagFunctions[name](body.trim());
  2590. context.astStack.push(engine.parse(tpl));
  2591. };
  2592. /*jshint +W083 */
  2593. }
  2594. delete options.customTags;
  2595. }
  2596. /**
  2597. * Now anything left in `options` becomes a local:
  2598. */
  2599. for (k in options) {
  2600. context.setLocals(k, options[k]);
  2601. }
  2602. /**
  2603. * Finally, execute the template:
  2604. */
  2605. var tmpl = cache(context) || cache(context, engine.compile(str, compileOptions));
  2606. tmpl(context, cb);
  2607. }
  2608. exports.liquid.render = function(str, options, cb) {
  2609. return promisify(cb, function(cb) {
  2610. var engine = requires.liquid;
  2611. var Liquid;
  2612. try {
  2613. // set up tinyliquid engine
  2614. engine = requires.liquid = require('tinyliquid');
  2615. // use tinyliquid engine
  2616. _renderTinyliquid(engine, str, options, cb);
  2617. return;
  2618. } catch (err) {
  2619. // set up liquid-node engine
  2620. try {
  2621. Liquid = requires.liquid = require('liquid-node');
  2622. engine = new Liquid.Engine();
  2623. } catch (err) {
  2624. throw err;
  2625. }
  2626. }
  2627. // use liquid-node engine
  2628. try {
  2629. var locals = options.locals || {};
  2630. if (options.meta) {
  2631. locals.pages = options.meta;
  2632. delete options.meta;
  2633. }
  2634. /**
  2635. * Add any defined filters:
  2636. */
  2637. if (options.filters) {
  2638. engine.registerFilters(options.filters);
  2639. delete options.filters;
  2640. }
  2641. /**
  2642. * Set up a callback for the include directory:
  2643. */
  2644. var includeDir = options.includeDir || process.cwd();
  2645. engine.fileSystem = new Liquid.LocalFileSystem(includeDir, 'liquid');
  2646. delete options.includeDir;
  2647. /**
  2648. * The custom tag functions need to have their results pushed back
  2649. * through the parser, so set up a shim before calling the provided
  2650. * callback:
  2651. */
  2652. if (options.customTags) {
  2653. var tagFunctions = options.customTags;
  2654. for (k in options.customTags) {
  2655. engine.registerTag(k, tagFunctions[k]);
  2656. }
  2657. delete options.customTags;
  2658. }
  2659. /**
  2660. * Now anything left in `options` becomes a local:
  2661. */
  2662. for (var k in options) {
  2663. locals[k] = options[k];
  2664. }
  2665. /**
  2666. * Finally, execute the template:
  2667. */
  2668. return engine
  2669. .parseAndRender(str, locals)
  2670. .nodeify(function(err, result) {
  2671. if (err) {
  2672. throw new Error(err);
  2673. } else {
  2674. return cb(null, result);
  2675. }
  2676. });
  2677. } catch (err) {
  2678. cb(err);
  2679. }
  2680. });
  2681. };
  2682. /**
  2683. * Jade support.
  2684. */
  2685. exports.jade = function(path, options, cb) {
  2686. return promisify(cb, function(cb) {
  2687. var engine = requires.jade;
  2688. if (!engine) {
  2689. try {
  2690. engine = requires.jade = require('jade');
  2691. } catch (err) {
  2692. try {
  2693. engine = requires.jade = require('then-jade');
  2694. } catch (otherError) {
  2695. throw err;
  2696. }
  2697. }
  2698. }
  2699. try {
  2700. var tmpl = cache(options) || cache(options, engine.compileFile(path, options));
  2701. cb(null, tmpl(options));
  2702. } catch (err) {
  2703. cb(err);
  2704. }
  2705. });
  2706. };
  2707. /**
  2708. * Jade string support.
  2709. */
  2710. exports.jade.render = function(str, options, cb) {
  2711. return promisify(cb, function(cb) {
  2712. var engine = requires.jade;
  2713. if (!engine) {
  2714. try {
  2715. engine = requires.jade = require('jade');
  2716. } catch (err) {
  2717. try {
  2718. engine = requires.jade = require('then-jade');
  2719. } catch (otherError) {
  2720. throw err;
  2721. }
  2722. }
  2723. }
  2724. try {
  2725. var tmpl = cache(options) || cache(options, engine.compile(str, options));
  2726. cb(null, tmpl(options));
  2727. } catch (err) {
  2728. cb(err);
  2729. }
  2730. });
  2731. };
  2732. /**
  2733. * Dust support.
  2734. */
  2735. exports.dust = fromStringRenderer('dust');
  2736. /**
  2737. * Dust string support.
  2738. */
  2739. exports.dust.render = function(str, options, cb) {
  2740. return promisify(cb, function(cb) {
  2741. var engine = requires.dust;
  2742. if (!engine) {
  2743. try {
  2744. engine = requires.dust = require('dust');
  2745. } catch (err) {
  2746. try {
  2747. engine = requires.dust = require('dustjs-helpers');
  2748. } catch (err) {
  2749. engine = requires.dust = require('dustjs-linkedin');
  2750. }
  2751. }
  2752. }
  2753. var ext = 'dust';
  2754. var views = '.';
  2755. if (options) {
  2756. if (options.ext) ext = options.ext;
  2757. if (options.views) views = options.views;
  2758. if (options.settings && options.settings.views) views = options.settings.views;
  2759. }
  2760. if (!options || (options && !options.cache)) engine.cache = {};
  2761. engine.onLoad = function(path, callback) {
  2762. if (extname(path) === '') path += '.' + ext;
  2763. if (path[0] !== '/') path = views + '/' + path;
  2764. read(path, options, callback);
  2765. };
  2766. try {
  2767. var templateName;
  2768. if (options.filename) {
  2769. templateName = options.filename.replace(new RegExp('^' + views + '/'), '').replace(new RegExp('\\.' + ext), '');
  2770. }
  2771. var tmpl = cache(options) || cache(options, engine.compileFn(str, templateName));
  2772. tmpl(options, cb);
  2773. } catch (err) {
  2774. cb(err);
  2775. }
  2776. });
  2777. };
  2778. /**
  2779. * Swig support.
  2780. */
  2781. exports.swig = fromStringRenderer('swig');
  2782. /**
  2783. * Swig string support.
  2784. */
  2785. exports.swig.render = function(str, options, cb) {
  2786. return promisify(cb, function(cb) {
  2787. var engine = requires.swig;
  2788. if (!engine) {
  2789. try {
  2790. engine = requires.swig = require('swig');
  2791. } catch (err) {
  2792. try {
  2793. engine = requires.swig = require('swig-templates');
  2794. } catch (otherError) {
  2795. throw err;
  2796. }
  2797. }
  2798. }
  2799. try {
  2800. if (options.cache === true) options.cache = 'memory';
  2801. engine.setDefaults({ cache: options.cache });
  2802. var tmpl = cache(options) || cache(options, engine.compile(str, options));
  2803. cb(null, tmpl(options));
  2804. } catch (err) {
  2805. cb(err);
  2806. }
  2807. });
  2808. };
  2809. /**
  2810. * Razor support.
  2811. */
  2812. exports.razor = function(path, options, cb) {
  2813. return promisify(cb, function(cb) {
  2814. var engine = requires.razor;
  2815. if (!engine) {
  2816. try {
  2817. engine = requires.razor = require('razor-tmpl');
  2818. } catch (err) {
  2819. throw err;
  2820. }
  2821. }
  2822. try {
  2823. var tmpl = cache(options) || cache(options, (locals) => {
  2824. console.log('Rendering razor file', path);
  2825. return engine.renderFileSync(path, locals);
  2826. });
  2827. cb(null, tmpl(options));
  2828. } catch (err) {
  2829. cb(err);
  2830. }
  2831. });
  2832. };
  2833. /**
  2834. * razor string support.
  2835. */
  2836. exports.razor.render = function(str, options, cb) {
  2837. return promisify(cb, function(cb) {
  2838. try {
  2839. var engine = requires.razor = require('razor-tmpl');
  2840. } catch (err) {
  2841. throw err;
  2842. }
  2843. try {
  2844. var tf = engine.compile(str);
  2845. var tmpl = cache(options) || cache(options, tf);
  2846. cb(null, tmpl(options));
  2847. } catch (err) {
  2848. cb(err);
  2849. }
  2850. });
  2851. };
  2852. /**
  2853. * Atpl support.
  2854. */
  2855. exports.atpl = fromStringRenderer('atpl');
  2856. /**
  2857. * Atpl string support.
  2858. */
  2859. exports.atpl.render = function(str, options, cb) {
  2860. return promisify(cb, function(cb) {
  2861. var engine = requires.atpl || (requires.atpl = require('atpl'));
  2862. try {
  2863. var tmpl = cache(options) || cache(options, engine.compile(str, options));
  2864. cb(null, tmpl(options));
  2865. } catch (err) {
  2866. cb(err);
  2867. }
  2868. });
  2869. };
  2870. /**
  2871. * Liquor support,
  2872. */
  2873. exports.liquor = fromStringRenderer('liquor');
  2874. /**
  2875. * Liquor string support.
  2876. */
  2877. exports.liquor.render = function(str, options, cb) {
  2878. return promisify(cb, function(cb) {
  2879. var engine = requires.liquor || (requires.liquor = require('liquor'));
  2880. try {
  2881. var tmpl = cache(options) || cache(options, engine.compile(str, options));
  2882. cb(null, tmpl(options));
  2883. } catch (err) {
  2884. cb(err);
  2885. }
  2886. });
  2887. };
  2888. /**
  2889. * Twig support.
  2890. */
  2891. exports.twig = fromStringRenderer('twig');
  2892. /**
  2893. * Twig string support.
  2894. */
  2895. exports.twig.render = function(str, options, cb) {
  2896. return promisify(cb, function(cb) {
  2897. var engine = requires.twig || (requires.twig = require('twig').twig);
  2898. var templateData = {
  2899. data: str,
  2900. allowInlineIncludes: options.allowInlineIncludes,
  2901. namespaces: options.namespaces,
  2902. path: options.path
  2903. };
  2904. try {
  2905. var tmpl = cache(templateData) || cache(templateData, engine(templateData));
  2906. cb(null, tmpl.render(options));
  2907. } catch (err) {
  2908. cb(err);
  2909. }
  2910. });
  2911. };
  2912. /**
  2913. * EJS support.
  2914. */
  2915. exports.ejs = fromStringRenderer('ejs');
  2916. /**
  2917. * EJS string support.
  2918. */
  2919. exports.ejs.render = function(str, options, cb) {
  2920. return promisify(cb, function(cb) {
  2921. var engine = requires.ejs || (requires.ejs = require('ejs'));
  2922. try {
  2923. var tmpl = cache(options) || cache(options, engine.compile(str, options));
  2924. cb(null, tmpl(options));
  2925. } catch (err) {
  2926. cb(err);
  2927. }
  2928. });
  2929. };
  2930. /**
  2931. * Eco support.
  2932. */
  2933. exports.eco = fromStringRenderer('eco');
  2934. /**
  2935. * Eco string support.
  2936. */
  2937. exports.eco.render = function(str, options, cb) {
  2938. return promisify(cb, function(cb) {
  2939. var engine = requires.eco || (requires.eco = require('eco'));
  2940. try {
  2941. cb(null, engine.render(str, options));
  2942. } catch (err) {
  2943. cb(err);
  2944. }
  2945. });
  2946. };
  2947. /**
  2948. * Jazz support.
  2949. */
  2950. exports.jazz = fromStringRenderer('jazz');
  2951. /**
  2952. * Jazz string support.
  2953. */
  2954. exports.jazz.render = function(str, options, cb) {
  2955. return promisify(cb, function(cb) {
  2956. var engine = requires.jazz || (requires.jazz = require('jazz'));
  2957. try {
  2958. var tmpl = cache(options) || cache(options, engine.compile(str, options));
  2959. tmpl.eval(options, function(str) {
  2960. cb(null, str);
  2961. });
  2962. } catch (err) {
  2963. cb(err);
  2964. }
  2965. });
  2966. };
  2967. /**
  2968. * JQTPL support.
  2969. */
  2970. exports.jqtpl = fromStringRenderer('jqtpl');
  2971. /**
  2972. * JQTPL string support.
  2973. */
  2974. exports.jqtpl.render = function(str, options, cb) {
  2975. return promisify(cb, function(cb) {
  2976. var engine = requires.jqtpl || (requires.jqtpl = require('jqtpl'));
  2977. try {
  2978. engine.template(str, str);
  2979. cb(null, engine.tmpl(str, options));
  2980. } catch (err) {
  2981. cb(err);
  2982. }
  2983. });
  2984. };
  2985. /**
  2986. * Haml support.
  2987. */
  2988. exports.haml = fromStringRenderer('haml');
  2989. /**
  2990. * Haml string support.
  2991. */
  2992. exports.haml.render = function(str, options, cb) {
  2993. return promisify(cb, function(cb) {
  2994. var engine = requires.haml || (requires.haml = require('hamljs'));
  2995. try {
  2996. options.locals = options;
  2997. cb(null, engine.render(str, options).trimLeft());
  2998. } catch (err) {
  2999. cb(err);
  3000. }
  3001. });
  3002. };
  3003. /**
  3004. * Hamlet support.
  3005. */
  3006. exports.hamlet = fromStringRenderer('hamlet');
  3007. /**
  3008. * Hamlet string support.
  3009. */
  3010. exports.hamlet.render = function(str, options, cb) {
  3011. return promisify(cb, function(cb) {
  3012. var engine = requires.hamlet || (requires.hamlet = require('hamlet'));
  3013. try {
  3014. options.locals = options;
  3015. cb(null, engine.render(str, options).trimLeft());
  3016. } catch (err) {
  3017. cb(err);
  3018. }
  3019. });
  3020. };
  3021. /**
  3022. * Whiskers support.
  3023. */
  3024. exports.whiskers = function(path, options, cb) {
  3025. return promisify(cb, function(cb) {
  3026. var engine = requires.whiskers || (requires.whiskers = require('whiskers'));
  3027. engine.__express(path, options, cb);
  3028. });
  3029. };
  3030. /**
  3031. * Whiskers string support.
  3032. */
  3033. exports.whiskers.render = function(str, options, cb) {
  3034. return promisify(cb, function(cb) {
  3035. var engine = requires.whiskers || (requires.whiskers = require('whiskers'));
  3036. try {
  3037. cb(null, engine.render(str, options));
  3038. } catch (err) {
  3039. cb(err);
  3040. }
  3041. });
  3042. };
  3043. /**
  3044. * Coffee-HAML support.
  3045. */
  3046. exports['haml-coffee'] = fromStringRenderer('haml-coffee');
  3047. /**
  3048. * Coffee-HAML string support.
  3049. */
  3050. exports['haml-coffee'].render = function(str, options, cb) {
  3051. return promisify(cb, function(cb) {
  3052. var engine = requires['haml-coffee'] || (requires['haml-coffee'] = require('haml-coffee'));
  3053. try {
  3054. var tmpl = cache(options) || cache(options, engine.compile(str, options));
  3055. cb(null, tmpl(options));
  3056. } catch (err) {
  3057. cb(err);
  3058. }
  3059. });
  3060. };
  3061. /**
  3062. * Hogan support.
  3063. */
  3064. exports.hogan = fromStringRenderer('hogan');
  3065. /**
  3066. * Hogan string support.
  3067. */
  3068. exports.hogan.render = function(str, options, cb) {
  3069. return promisify(cb, function(cb) {
  3070. var engine = requires.hogan || (requires.hogan = require('hogan.js'));
  3071. try {
  3072. var tmpl = cache(options) || cache(options, engine.compile(str, options));
  3073. cb(null, tmpl.render(options, options.partials));
  3074. } catch (err) {
  3075. cb(err);
  3076. }
  3077. });
  3078. };
  3079. /**
  3080. * templayed.js support.
  3081. */
  3082. exports.templayed = fromStringRenderer('templayed');
  3083. /**
  3084. * templayed.js string support.
  3085. */
  3086. exports.templayed.render = function(str, options, cb) {
  3087. return promisify(cb, function(cb) {
  3088. var engine = requires.templayed || (requires.templayed = require('templayed'));
  3089. try {
  3090. var tmpl = cache(options) || cache(options, engine(str));
  3091. cb(null, tmpl(options));
  3092. } catch (err) {
  3093. cb(err);
  3094. }
  3095. });
  3096. };
  3097. /**
  3098. * Handlebars support.
  3099. */
  3100. exports.handlebars = fromStringRenderer('handlebars');
  3101. /**
  3102. * Handlebars string support.
  3103. */
  3104. exports.handlebars.render = function(str, options, cb) {
  3105. return promisify(cb, function(cb) {
  3106. var engine = requires.handlebars || (requires.handlebars = require('handlebars'));
  3107. try {
  3108. for (var partial in options.partials) {
  3109. engine.registerPartial(partial, options.partials[partial]);
  3110. }
  3111. for (var helper in options.helpers) {
  3112. engine.registerHelper(helper, options.helpers[helper]);
  3113. }
  3114. var tmpl = cache(options) || cache(options, engine.compile(str, options));
  3115. cb(null, tmpl(options));
  3116. } catch (err) {
  3117. cb(err);
  3118. }
  3119. });
  3120. };
  3121. /**
  3122. * Underscore support.
  3123. */
  3124. exports.underscore = fromStringRenderer('underscore');
  3125. /**
  3126. * Underscore string support.
  3127. */
  3128. exports.underscore.render = function(str, options, cb) {
  3129. return promisify(cb, function(cb) {
  3130. var engine = requires.underscore || (requires.underscore = require('underscore'));
  3131. try {
  3132. const partials = {};
  3133. for (var partial in options.partials) {
  3134. partials[partial] = engine.template(options.partials[partial]);
  3135. }
  3136. options.partials = partials;
  3137. var tmpl = cache(options) || cache(options, engine.template(str, null, options));
  3138. cb(null, tmpl(options).replace(/\n$/, ''));
  3139. } catch (err) {
  3140. cb(err);
  3141. }
  3142. });
  3143. };
  3144. /**
  3145. * Lodash support.
  3146. */
  3147. exports.lodash = fromStringRenderer('lodash');
  3148. /**
  3149. * Lodash string support.
  3150. */
  3151. exports.lodash.render = function(str, options, cb) {
  3152. return promisify(cb, function(cb) {
  3153. var engine = requires.lodash || (requires.lodash = require('lodash'));
  3154. try {
  3155. var tmpl = cache(options) || cache(options, engine.template(str, options));
  3156. cb(null, tmpl(options).replace(/\n$/, ''));
  3157. } catch (err) {
  3158. cb(err);
  3159. }
  3160. });
  3161. };
  3162. /**
  3163. * Pug support. (formerly Jade)
  3164. */
  3165. exports.pug = function(path, options, cb) {
  3166. return promisify(cb, function(cb) {
  3167. var engine = requires.pug;
  3168. if (!engine) {
  3169. try {
  3170. engine = requires.pug = require('pug');
  3171. } catch (err) {
  3172. try {
  3173. engine = requires.pug = require('then-pug');
  3174. } catch (otherError) {
  3175. throw err;
  3176. }
  3177. }
  3178. }
  3179. try {
  3180. var tmpl = cache(options) || cache(options, engine.compileFile(path, options));
  3181. cb(null, tmpl(options));
  3182. } catch (err) {
  3183. cb(err);
  3184. }
  3185. });
  3186. };
  3187. /**
  3188. * Pug string support.
  3189. */
  3190. exports.pug.render = function(str, options, cb) {
  3191. return promisify(cb, function(cb) {
  3192. var engine = requires.pug;
  3193. if (!engine) {
  3194. try {
  3195. engine = requires.pug = require('pug');
  3196. } catch (err) {
  3197. try {
  3198. engine = requires.pug = require('then-pug');
  3199. } catch (otherError) {
  3200. throw err;
  3201. }
  3202. }
  3203. }
  3204. try {
  3205. var tmpl = cache(options) || cache(options, engine.compile(str, options));
  3206. cb(null, tmpl(options));
  3207. } catch (err) {
  3208. cb(err);
  3209. }
  3210. });
  3211. };
  3212. /**
  3213. * QEJS support.
  3214. */
  3215. exports.qejs = fromStringRenderer('qejs');
  3216. /**
  3217. * QEJS string support.
  3218. */
  3219. exports.qejs.render = function(str, options, cb) {
  3220. return promisify(cb, function(cb) {
  3221. try {
  3222. var engine = requires.qejs || (requires.qejs = require('qejs'));
  3223. engine.render(str, options).then(function(result) {
  3224. cb(null, result);
  3225. }, function(err) {
  3226. cb(err);
  3227. }).done();
  3228. } catch (err) {
  3229. cb(err);
  3230. }
  3231. });
  3232. };
  3233. /**
  3234. * Walrus support.
  3235. */
  3236. exports.walrus = fromStringRenderer('walrus');
  3237. /**
  3238. * Walrus string support.
  3239. */
  3240. exports.walrus.render = function(str, options, cb) {
  3241. return promisify(cb, function(cb) {
  3242. var engine = requires.walrus || (requires.walrus = require('walrus'));
  3243. try {
  3244. var tmpl = cache(options) || cache(options, engine.parse(str));
  3245. cb(null, tmpl.compile(options));
  3246. } catch (err) {
  3247. cb(err);
  3248. }
  3249. });
  3250. };
  3251. /**
  3252. * Mustache support.
  3253. */
  3254. exports.mustache = fromStringRenderer('mustache');
  3255. /**
  3256. * Mustache string support.
  3257. */
  3258. exports.mustache.render = function(str, options, cb) {
  3259. return promisify(cb, function(cb) {
  3260. var engine = requires.mustache || (requires.mustache = require('mustache'));
  3261. try {
  3262. cb(null, engine.render(str, options, options.partials));
  3263. } catch (err) {
  3264. cb(err);
  3265. }
  3266. });
  3267. };
  3268. /**
  3269. * Just support.
  3270. */
  3271. exports.just = function(path, options, cb) {
  3272. return promisify(cb, function(cb) {
  3273. var engine = requires.just;
  3274. if (!engine) {
  3275. var JUST = require('just');
  3276. engine = requires.just = new JUST();
  3277. }
  3278. engine.configure({ useCache: options.cache });
  3279. engine.render(path, options, cb);
  3280. });
  3281. };
  3282. /**
  3283. * Just string support.
  3284. */
  3285. exports.just.render = function(str, options, cb) {
  3286. return promisify(cb, function(cb) {
  3287. var JUST = require('just');
  3288. var engine = new JUST({ root: { page: str }});
  3289. engine.render('page', options, cb);
  3290. });
  3291. };
  3292. /**
  3293. * ECT support.
  3294. */
  3295. exports.ect = function(path, options, cb) {
  3296. return promisify(cb, function(cb) {
  3297. var engine = requires.ect;
  3298. if (!engine) {
  3299. var ECT = require('ect');
  3300. engine = requires.ect = new ECT(options);
  3301. }
  3302. engine.configure({ cache: options.cache });
  3303. engine.render(path, options, cb);
  3304. });
  3305. };
  3306. /**
  3307. * ECT string support.
  3308. */
  3309. exports.ect.render = function(str, options, cb) {
  3310. return promisify(cb, function(cb) {
  3311. var ECT = require('ect');
  3312. var engine = new ECT({ root: { page: str }});
  3313. engine.render('page', options, cb);
  3314. });
  3315. };
  3316. /**
  3317. * mote support.
  3318. */
  3319. exports.mote = fromStringRenderer('mote');
  3320. /**
  3321. * mote string support.
  3322. */
  3323. exports.mote.render = function(str, options, cb) {
  3324. return promisify(cb, function(cb) {
  3325. var engine = requires.mote || (requires.mote = require('mote'));
  3326. try {
  3327. var tmpl = cache(options) || cache(options, engine.compile(str));
  3328. cb(null, tmpl(options));
  3329. } catch (err) {
  3330. cb(err);
  3331. }
  3332. });
  3333. };
  3334. /**
  3335. * Toffee support.
  3336. */
  3337. exports.toffee = function(path, options, cb) {
  3338. return promisify(cb, function(cb) {
  3339. var toffee = requires.toffee || (requires.toffee = require('toffee'));
  3340. toffee.__consolidate_engine_render(path, options, cb);
  3341. });
  3342. };
  3343. /**
  3344. * Toffee string support.
  3345. */
  3346. exports.toffee.render = function(str, options, cb) {
  3347. return promisify(cb, function(cb) {
  3348. var engine = requires.toffee || (requires.toffee = require('toffee'));
  3349. try {
  3350. engine.str_render(str, options, cb);
  3351. } catch (err) {
  3352. cb(err);
  3353. }
  3354. });
  3355. };
  3356. /**
  3357. * doT support.
  3358. */
  3359. exports.dot = fromStringRenderer('dot');
  3360. /**
  3361. * doT string support.
  3362. */
  3363. exports.dot.render = function(str, options, cb) {
  3364. return promisify(cb, function(cb) {
  3365. var engine = requires.dot || (requires.dot = require('dot'));
  3366. var extend = (requires.extend || (requires.extend = require$$2._extend));
  3367. try {
  3368. var settings = {};
  3369. settings = extend(settings, engine.templateSettings);
  3370. settings = extend(settings, options ? options.dot : {});
  3371. var tmpl = cache(options) || cache(options, engine.template(str, settings, options));
  3372. cb(null, tmpl(options));
  3373. } catch (err) {
  3374. cb(err);
  3375. }
  3376. });
  3377. };
  3378. /**
  3379. * bracket support.
  3380. */
  3381. exports.bracket = fromStringRenderer('bracket');
  3382. /**
  3383. * bracket string support.
  3384. */
  3385. exports.bracket.render = function(str, options, cb) {
  3386. return promisify(cb, function(cb) {
  3387. var engine = requires.bracket || (requires.bracket = require('bracket-template'));
  3388. try {
  3389. var tmpl = cache(options) || cache(options, engine.default.compile(str, options));
  3390. cb(null, tmpl(options));
  3391. } catch (err) {
  3392. cb(err);
  3393. }
  3394. });
  3395. };
  3396. /**
  3397. * Ractive support.
  3398. */
  3399. exports.ractive = fromStringRenderer('ractive');
  3400. /**
  3401. * Ractive string support.
  3402. */
  3403. exports.ractive.render = function(str, options, cb) {
  3404. return promisify(cb, function(cb) {
  3405. var Engine = requires.ractive || (requires.ractive = require('ractive'));
  3406. var template = cache(options) || cache(options, Engine.parse(str));
  3407. options.template = template;
  3408. if (options.data === null || options.data === undefined) {
  3409. var extend = (requires.extend || (requires.extend = require$$2._extend));
  3410. // Shallow clone the options object
  3411. options.data = extend({}, options);
  3412. // Remove consolidate-specific properties from the clone
  3413. var i;
  3414. var length;
  3415. var properties = ['template', 'filename', 'cache', 'partials'];
  3416. for (i = 0, length = properties.length; i < length; i++) {
  3417. var property = properties[i];
  3418. delete options.data[property];
  3419. }
  3420. }
  3421. try {
  3422. cb(null, new Engine(options).toHTML());
  3423. } catch (err) {
  3424. cb(err);
  3425. }
  3426. });
  3427. };
  3428. /**
  3429. * Nunjucks support.
  3430. */
  3431. exports.nunjucks = fromStringRenderer('nunjucks');
  3432. /**
  3433. * Nunjucks string support.
  3434. */
  3435. exports.nunjucks.render = function(str, options, cb) {
  3436. return promisify(cb, function(cb) {
  3437. try {
  3438. var engine = options.nunjucksEnv || requires.nunjucks || (requires.nunjucks = require('nunjucks'));
  3439. var env = engine;
  3440. // deprecated fallback support for express
  3441. // <https://github.com/tj/consolidate.js/pull/152>
  3442. // <https://github.com/tj/consolidate.js/pull/224>
  3443. if (options.settings && options.settings.views) {
  3444. env = engine.configure(options.settings.views);
  3445. } else if (options.nunjucks && options.nunjucks.configure) {
  3446. env = engine.configure.apply(engine, options.nunjucks.configure);
  3447. }
  3448. //
  3449. // because `renderString` does not initiate loaders
  3450. // we must manually create a loader for it based off
  3451. // either `options.settings.views` or `options.nunjucks` or `options.nunjucks.root`
  3452. //
  3453. // <https://github.com/mozilla/nunjucks/issues/730>
  3454. // <https://github.com/crocodilejs/node-email-templates/issues/182>
  3455. //
  3456. // so instead we simply check if we passed a custom loader
  3457. // otherwise we create a simple file based loader
  3458. if (options.loader) {
  3459. env = new engine.Environment(options.loader);
  3460. } else if (options.settings && options.settings.views) {
  3461. env = new engine.Environment(
  3462. new engine.FileSystemLoader(options.settings.views)
  3463. );
  3464. } else if (options.nunjucks && options.nunjucks.loader) {
  3465. if (typeof options.nunjucks.loader === 'string') {
  3466. env = new engine.Environment(new engine.FileSystemLoader(options.nunjucks.loader));
  3467. } else {
  3468. env = new engine.Environment(
  3469. new engine.FileSystemLoader(
  3470. options.nunjucks.loader[0],
  3471. options.nunjucks.loader[1]
  3472. )
  3473. );
  3474. }
  3475. }
  3476. env.renderString(str, options, cb);
  3477. } catch (err) {
  3478. throw cb(err);
  3479. }
  3480. });
  3481. };
  3482. /**
  3483. * HTMLing support.
  3484. */
  3485. exports.htmling = fromStringRenderer('htmling');
  3486. /**
  3487. * HTMLing string support.
  3488. */
  3489. exports.htmling.render = function(str, options, cb) {
  3490. return promisify(cb, function(cb) {
  3491. var engine = requires.htmling || (requires.htmling = require('htmling'));
  3492. try {
  3493. var tmpl = cache(options) || cache(options, engine.string(str));
  3494. cb(null, tmpl.render(options));
  3495. } catch (err) {
  3496. cb(err);
  3497. }
  3498. });
  3499. };
  3500. /**
  3501. * Rendering function
  3502. */
  3503. function requireReact(module, filename) {
  3504. var babel = requires.babel || (requires.babel = require('babel-core'));
  3505. var compiled = babel.transformFileSync(filename, { presets: [ 'react' ] }).code;
  3506. return module._compile(compiled, filename);
  3507. }
  3508. exports.requireReact = requireReact;
  3509. /**
  3510. * Converting a string into a node module.
  3511. */
  3512. function requireReactString(src, filename) {
  3513. var babel = requires.babel || (requires.babel = require('babel-core'));
  3514. if (!filename) filename = '';
  3515. var m = new module.constructor();
  3516. filename = filename || '';
  3517. // Compile Using React
  3518. var compiled = babel.transform(src, { presets: [ 'react' ] }).code;
  3519. // Compile as a module
  3520. m.paths = module.paths;
  3521. m._compile(compiled, filename);
  3522. return m.exports;
  3523. }
  3524. /**
  3525. * A naive helper to replace {{tags}} with options.tags content
  3526. */
  3527. function reactBaseTmpl(data, options) {
  3528. var exp;
  3529. var regex;
  3530. // Iterates through the keys in file object
  3531. // and interpolate / replace {{key}} with it's value
  3532. for (var k in options) {
  3533. if (options.hasOwnProperty(k)) {
  3534. exp = '{{' + k + '}}';
  3535. regex = new RegExp(exp, 'g');
  3536. if (data.match(regex)) {
  3537. data = data.replace(regex, options[k]);
  3538. }
  3539. }
  3540. }
  3541. return data;
  3542. }
  3543. /**
  3544. * Plates Support.
  3545. */
  3546. exports.plates = fromStringRenderer('plates');
  3547. /**
  3548. * Plates string support.
  3549. */
  3550. exports.plates.render = function(str, options, cb) {
  3551. return promisify(cb, function(cb) {
  3552. var engine = requires.plates || (requires.plates = require('plates'));
  3553. var map = options.map || undefined;
  3554. try {
  3555. var tmpl = engine.bind(str, options, map);
  3556. cb(null, tmpl);
  3557. } catch (err) {
  3558. cb(err);
  3559. }
  3560. });
  3561. };
  3562. /**
  3563. * The main render parser for React bsaed templates
  3564. */
  3565. function reactRenderer(type) {
  3566. if (commonjsRequire.extensions) {
  3567. // Ensure JSX is transformed on require
  3568. if (!commonjsRequire.extensions['.jsx']) {
  3569. commonjsRequire.extensions['.jsx'] = requireReact;
  3570. }
  3571. // Supporting .react extension as well as test cases
  3572. // Using .react extension is not recommended.
  3573. if (!commonjsRequire.extensions['.react']) {
  3574. commonjsRequire.extensions['.react'] = requireReact;
  3575. }
  3576. }
  3577. // Return rendering fx
  3578. return function(str, options, cb) {
  3579. return promisify(cb, function(cb) {
  3580. // React Import
  3581. var ReactDOM = requires.ReactDOM || (requires.ReactDOM = require('react-dom/server'));
  3582. var react = requires.react || (requires.react = require('react'));
  3583. // Assign HTML Base
  3584. var base = options.base;
  3585. delete options.base;
  3586. var enableCache = options.cache;
  3587. delete options.cache;
  3588. var isNonStatic = options.isNonStatic;
  3589. delete options.isNonStatic;
  3590. // Start Conversion
  3591. try {
  3592. var Code;
  3593. var Factory;
  3594. var baseStr;
  3595. var content;
  3596. var parsed;
  3597. if (!cache(options)) {
  3598. // Parsing
  3599. if (type === 'path') {
  3600. var path = resolve(str);
  3601. delete require.cache[path];
  3602. Code = commonjsRequire(path);
  3603. } else {
  3604. Code = requireReactString(str);
  3605. }
  3606. Factory = cache(options, react.createFactory(Code));
  3607. } else {
  3608. Factory = cache(options);
  3609. }
  3610. parsed = new Factory(options);
  3611. content = (isNonStatic) ? ReactDOM.renderToString(parsed) : ReactDOM.renderToStaticMarkup(parsed);
  3612. if (base) {
  3613. baseStr = readCache[str] || fs.readFileSync(resolve(base), 'utf8');
  3614. if (enableCache) {
  3615. readCache[str] = baseStr;
  3616. }
  3617. options.content = content;
  3618. content = reactBaseTmpl(baseStr, options);
  3619. }
  3620. cb(null, content);
  3621. } catch (err) {
  3622. cb(err);
  3623. }
  3624. });
  3625. };
  3626. }
  3627. /**
  3628. * React JS Support
  3629. */
  3630. exports.react = reactRenderer('path');
  3631. /**
  3632. * React JS string support.
  3633. */
  3634. exports.react.render = reactRenderer('string');
  3635. /**
  3636. * ARC-templates support.
  3637. */
  3638. exports['arc-templates'] = fromStringRenderer('arc-templates');
  3639. /**
  3640. * ARC-templates string support.
  3641. */
  3642. exports['arc-templates'].render = function(str, options, cb) {
  3643. var readFileWithOptions = util.promisify(read);
  3644. var consolidateFileSystem = {};
  3645. consolidateFileSystem.readFile = function(path) {
  3646. return readFileWithOptions(path, options);
  3647. };
  3648. return promisify(cb, function(cb) {
  3649. try {
  3650. var engine = requires['arc-templates'];
  3651. if (!engine) {
  3652. var Engine = require('arc-templates/dist/es5');
  3653. engine = requires['arc-templates'] = new Engine({ filesystem: consolidateFileSystem });
  3654. }
  3655. var compiler = cache(options) || cache(options, engine.compileString(str, options.filename));
  3656. compiler.then(function(func) { return func(options); })
  3657. .then(function(result) { cb(null, result.content); })
  3658. .catch(cb);
  3659. } catch (err) {
  3660. cb(err);
  3661. }
  3662. });
  3663. };
  3664. /**
  3665. * Vash support
  3666. */
  3667. exports.vash = fromStringRenderer('vash');
  3668. /**
  3669. * Vash string support
  3670. */
  3671. exports.vash.render = function(str, options, cb) {
  3672. return promisify(cb, function(cb) {
  3673. var engine = requires.vash || (requires.vash = require('vash'));
  3674. try {
  3675. // helper system : https://github.com/kirbysayshi/vash#helper-system
  3676. if (options.helpers) {
  3677. for (var key in options.helpers) {
  3678. if (!options.helpers.hasOwnProperty(key) || typeof options.helpers[key] !== 'function') {
  3679. continue;
  3680. }
  3681. engine.helpers[key] = options.helpers[key];
  3682. }
  3683. }
  3684. var tmpl = cache(options) || cache(options, engine.compile(str, options));
  3685. tmpl(options, function sealLayout(err, ctx) {
  3686. if (err) cb(err);
  3687. ctx.finishLayout();
  3688. cb(null, ctx.toString().replace(/\n$/, ''));
  3689. });
  3690. } catch (err) {
  3691. cb(err);
  3692. }
  3693. });
  3694. };
  3695. /**
  3696. * Slm support.
  3697. */
  3698. exports.slm = fromStringRenderer('slm');
  3699. /**
  3700. * Slm string support.
  3701. */
  3702. exports.slm.render = function(str, options, cb) {
  3703. return promisify(cb, function(cb) {
  3704. var engine = requires.slm || (requires.slm = require('slm'));
  3705. try {
  3706. var tmpl = cache(options) || cache(options, engine.compile(str, options));
  3707. cb(null, tmpl(options));
  3708. } catch (err) {
  3709. cb(err);
  3710. }
  3711. });
  3712. };
  3713. /**
  3714. * Marko support.
  3715. */
  3716. exports.marko = function(path, options, cb) {
  3717. return promisify(cb, function(cb) {
  3718. var engine = requires.marko || (requires.marko = require('marko'));
  3719. options.writeToDisk = !!options.cache;
  3720. try {
  3721. var tmpl = cache(options) || cache(options, engine.load(path, options));
  3722. tmpl.renderToString(options, cb);
  3723. } catch (err) {
  3724. cb(err);
  3725. }
  3726. });
  3727. };
  3728. /**
  3729. * Marko string support.
  3730. */
  3731. exports.marko.render = function(str, options, cb) {
  3732. return promisify(cb, function(cb) {
  3733. var engine = requires.marko || (requires.marko = require('marko'));
  3734. options.writeToDisk = !!options.cache;
  3735. options.filename = options.filename || 'string.marko';
  3736. try {
  3737. var tmpl = cache(options) || cache(options, engine.load(options.filename, str, options));
  3738. tmpl.renderToString(options, cb);
  3739. } catch (err) {
  3740. cb(err);
  3741. }
  3742. });
  3743. };
  3744. /**
  3745. * Teacup support.
  3746. */
  3747. exports.teacup = function(path, options, cb) {
  3748. return promisify(cb, function(cb) {
  3749. var engine = requires.teacup || (requires.teacup = require('teacup/lib/express'));
  3750. commonjsRequire.extensions['.teacup'] = commonjsRequire.extensions['.coffee'];
  3751. if (path[0] !== '/') {
  3752. path = join(process.cwd(), path);
  3753. }
  3754. if (!options.cache) {
  3755. var callback = cb;
  3756. cb = function() {
  3757. delete require.cache[path];
  3758. callback.apply(this, arguments);
  3759. };
  3760. }
  3761. engine.renderFile(path, options, cb);
  3762. });
  3763. };
  3764. /**
  3765. * Teacup string support.
  3766. */
  3767. exports.teacup.render = function(str, options, cb) {
  3768. var coffee = require('coffee-script');
  3769. var vm = require('vm');
  3770. var sandbox = {
  3771. module: {exports: {}},
  3772. require: commonjsRequire
  3773. };
  3774. return promisify(cb, function(cb) {
  3775. vm.runInNewContext(coffee.compile(str), sandbox);
  3776. var tmpl = sandbox.module.exports;
  3777. cb(null, tmpl(options));
  3778. });
  3779. };
  3780. /**
  3781. * Squirrelly support.
  3782. */
  3783. exports.squirrelly = fromStringRenderer('squirrelly');
  3784. /**
  3785. * Squirrelly string support.
  3786. */
  3787. exports.squirrelly.render = function(str, options, cb) {
  3788. return promisify(cb, function(cb) {
  3789. var engine = requires.squirrelly || (requires.squirrelly = require('squirrelly'));
  3790. try {
  3791. for (var partial in options.partials) {
  3792. engine.definePartial(partial, options.partials[partial]);
  3793. }
  3794. for (var helper in options.helpers) {
  3795. engine.defineHelper(helper, options.helpers[helper]);
  3796. }
  3797. var tmpl = cache(options) || cache(options, engine.Compile(str, options));
  3798. cb(null, tmpl(options, engine));
  3799. } catch (err) {
  3800. cb(err);
  3801. }
  3802. });
  3803. };
  3804. /**
  3805. * Twing support.
  3806. */
  3807. exports.twing = fromStringRenderer('twing');
  3808. /**
  3809. * Twing string support.
  3810. */
  3811. exports.twing.render = function(str, options, cb) {
  3812. return promisify(cb, function(cb) {
  3813. var engine = requires.twing || (requires.twing = require('twing'));
  3814. try {
  3815. new engine.TwingEnvironment(new engine.TwingLoaderNull()).createTemplate(str).then((twingTemplate) => {
  3816. twingTemplate.render(options).then((rendTmpl) => {
  3817. var tmpl = cache(options) || cache(options, rendTmpl);
  3818. cb(null, tmpl);
  3819. });
  3820. });
  3821. } catch (err) {
  3822. cb(err);
  3823. }
  3824. });
  3825. };
  3826. /**
  3827. * expose the instance of the engine
  3828. */
  3829. exports.requires = requires;
  3830. } (consolidate$2, consolidate$2.exports));
  3831. var consolidateExports = consolidate$2.exports;
  3832. var consolidate = consolidateExports;
  3833. var consolidate$1 = /*@__PURE__*/getDefaultExportFromCjs(consolidate);
  3834. const hasWarned = {};
  3835. function warnOnce(msg) {
  3836. const isNodeProd = typeof process !== "undefined" && process.env.NODE_ENV === "production";
  3837. if (!isNodeProd && true && !hasWarned[msg]) {
  3838. hasWarned[msg] = true;
  3839. warn(msg);
  3840. }
  3841. }
  3842. function warn(msg) {
  3843. console.warn(
  3844. `\x1B[1m\x1B[33m[@vue/compiler-sfc]\x1B[0m\x1B[33m ${msg}\x1B[0m
  3845. `
  3846. );
  3847. }
  3848. function preprocess$1({ source, filename, preprocessOptions }, preprocessor) {
  3849. let res = "";
  3850. let err = null;
  3851. preprocessor.render(
  3852. source,
  3853. { filename, ...preprocessOptions },
  3854. (_err, _res) => {
  3855. if (_err)
  3856. err = _err;
  3857. res = _res;
  3858. }
  3859. );
  3860. if (err)
  3861. throw err;
  3862. return res;
  3863. }
  3864. function compileTemplate(options) {
  3865. const { preprocessLang, preprocessCustomRequire } = options;
  3866. const preprocessor = preprocessLang ? preprocessCustomRequire ? preprocessCustomRequire(preprocessLang) : consolidate$1[preprocessLang] : false;
  3867. if (preprocessor) {
  3868. try {
  3869. return doCompileTemplate({
  3870. ...options,
  3871. source: preprocess$1(options, preprocessor),
  3872. ast: void 0
  3873. // invalidate AST if template goes through preprocessor
  3874. });
  3875. } catch (e) {
  3876. return {
  3877. code: `export default function render() {}`,
  3878. source: options.source,
  3879. tips: [],
  3880. errors: [e]
  3881. };
  3882. }
  3883. } else if (preprocessLang) {
  3884. return {
  3885. code: `export default function render() {}`,
  3886. source: options.source,
  3887. tips: [
  3888. `Component ${options.filename} uses lang ${preprocessLang} for template. Please install the language preprocessor.`
  3889. ],
  3890. errors: [
  3891. `Component ${options.filename} uses lang ${preprocessLang} for template, however it is not installed.`
  3892. ]
  3893. };
  3894. } else {
  3895. return doCompileTemplate(options);
  3896. }
  3897. }
  3898. function doCompileTemplate({
  3899. filename,
  3900. id,
  3901. scoped,
  3902. slotted,
  3903. inMap,
  3904. source,
  3905. ast: inAST,
  3906. ssr = false,
  3907. ssrCssVars,
  3908. isProd = false,
  3909. compiler,
  3910. compilerOptions = {},
  3911. transformAssetUrls
  3912. }) {
  3913. const errors = [];
  3914. const warnings = [];
  3915. let nodeTransforms = [];
  3916. if (shared.isObject(transformAssetUrls)) {
  3917. const assetOptions = normalizeOptions(transformAssetUrls);
  3918. nodeTransforms = [
  3919. createAssetUrlTransformWithOptions(assetOptions),
  3920. createSrcsetTransformWithOptions(assetOptions)
  3921. ];
  3922. } else if (transformAssetUrls !== false) {
  3923. nodeTransforms = [transformAssetUrl, transformSrcset];
  3924. }
  3925. if (ssr && !ssrCssVars) {
  3926. warnOnce(
  3927. `compileTemplate is called with \`ssr: true\` but no corresponding \`cssVars\` option.\`.`
  3928. );
  3929. }
  3930. if (!id) {
  3931. warnOnce(`compileTemplate now requires the \`id\` option.\`.`);
  3932. id = "";
  3933. }
  3934. const shortId = id.replace(/^data-v-/, "");
  3935. const longId = `data-v-${shortId}`;
  3936. const defaultCompiler = ssr ? CompilerSSR__namespace : CompilerDOM__namespace;
  3937. compiler = compiler || defaultCompiler;
  3938. if (compiler !== defaultCompiler) {
  3939. inAST = void 0;
  3940. }
  3941. if (inAST == null ? void 0 : inAST.transformed) {
  3942. const newAST = (ssr ? CompilerDOM__namespace : compiler).parse(inAST.source, {
  3943. prefixIdentifiers: true,
  3944. ...compilerOptions,
  3945. parseMode: "sfc",
  3946. onError: (e) => errors.push(e)
  3947. });
  3948. const template = newAST.children.find(
  3949. (node) => node.type === 1 && node.tag === "template"
  3950. );
  3951. inAST = compilerCore.createRoot(template.children, inAST.source);
  3952. }
  3953. let { code, ast, preamble, map } = compiler.compile(inAST || source, {
  3954. mode: "module",
  3955. prefixIdentifiers: true,
  3956. hoistStatic: true,
  3957. cacheHandlers: true,
  3958. ssrCssVars: ssr && ssrCssVars && ssrCssVars.length ? genCssVarsFromList(ssrCssVars, shortId, isProd, true) : "",
  3959. scopeId: scoped ? longId : void 0,
  3960. slotted,
  3961. sourceMap: true,
  3962. ...compilerOptions,
  3963. hmr: !isProd,
  3964. nodeTransforms: nodeTransforms.concat(compilerOptions.nodeTransforms || []),
  3965. filename,
  3966. onError: (e) => errors.push(e),
  3967. onWarn: (w) => warnings.push(w)
  3968. });
  3969. if (inMap && !inAST) {
  3970. if (map) {
  3971. map = mapLines(inMap, map);
  3972. }
  3973. if (errors.length) {
  3974. patchErrors(errors, source, inMap);
  3975. }
  3976. }
  3977. const tips = warnings.map((w) => {
  3978. let msg = w.message;
  3979. if (w.loc) {
  3980. msg += `
  3981. ${shared.generateCodeFrame(
  3982. (inAST == null ? void 0 : inAST.source) || source,
  3983. w.loc.start.offset,
  3984. w.loc.end.offset
  3985. )}`;
  3986. }
  3987. return msg;
  3988. });
  3989. return { code, ast, preamble, source, errors, tips, map };
  3990. }
  3991. function mapLines(oldMap, newMap) {
  3992. if (!oldMap)
  3993. return newMap;
  3994. if (!newMap)
  3995. return oldMap;
  3996. const oldMapConsumer = new sourceMapJs.SourceMapConsumer(oldMap);
  3997. const newMapConsumer = new sourceMapJs.SourceMapConsumer(newMap);
  3998. const mergedMapGenerator = new sourceMapJs.SourceMapGenerator();
  3999. newMapConsumer.eachMapping((m) => {
  4000. if (m.originalLine == null) {
  4001. return;
  4002. }
  4003. const origPosInOldMap = oldMapConsumer.originalPositionFor({
  4004. line: m.originalLine,
  4005. column: m.originalColumn
  4006. });
  4007. if (origPosInOldMap.source == null) {
  4008. return;
  4009. }
  4010. mergedMapGenerator.addMapping({
  4011. generated: {
  4012. line: m.generatedLine,
  4013. column: m.generatedColumn
  4014. },
  4015. original: {
  4016. line: origPosInOldMap.line,
  4017. // map line
  4018. // use current column, since the oldMap produced by @vue/compiler-sfc
  4019. // does not
  4020. column: m.originalColumn
  4021. },
  4022. source: origPosInOldMap.source,
  4023. name: origPosInOldMap.name
  4024. });
  4025. });
  4026. const generator = mergedMapGenerator;
  4027. oldMapConsumer.sources.forEach((sourceFile) => {
  4028. generator._sources.add(sourceFile);
  4029. const sourceContent = oldMapConsumer.sourceContentFor(sourceFile);
  4030. if (sourceContent != null) {
  4031. mergedMapGenerator.setSourceContent(sourceFile, sourceContent);
  4032. }
  4033. });
  4034. generator._sourceRoot = oldMap.sourceRoot;
  4035. generator._file = oldMap.file;
  4036. return generator.toJSON();
  4037. }
  4038. function patchErrors(errors, source, inMap) {
  4039. const originalSource = inMap.sourcesContent[0];
  4040. const offset = originalSource.indexOf(source);
  4041. const lineOffset = originalSource.slice(0, offset).split(/\r?\n/).length - 1;
  4042. errors.forEach((err) => {
  4043. if (err.loc) {
  4044. err.loc.start.line += lineOffset;
  4045. err.loc.start.offset += offset;
  4046. if (err.loc.end !== err.loc.start) {
  4047. err.loc.end.line += lineOffset;
  4048. err.loc.end.offset += offset;
  4049. }
  4050. }
  4051. });
  4052. }
  4053. const trimPlugin = () => {
  4054. return {
  4055. postcssPlugin: "vue-sfc-trim",
  4056. Once(root) {
  4057. root.walk(({ type, raws }) => {
  4058. if (type === "rule" || type === "atrule") {
  4059. if (raws.before)
  4060. raws.before = "\n";
  4061. if ("after" in raws && raws.after)
  4062. raws.after = "\n";
  4063. }
  4064. });
  4065. }
  4066. };
  4067. };
  4068. trimPlugin.postcss = true;
  4069. var dist = {exports: {}};
  4070. var processor = {exports: {}};
  4071. var parser = {exports: {}};
  4072. var root$2 = {exports: {}};
  4073. var container = {exports: {}};
  4074. var node$1 = {exports: {}};
  4075. var util$6 = {};
  4076. var unesc = {exports: {}};
  4077. (function (module, exports) {
  4078. exports.__esModule = true;
  4079. exports["default"] = unesc;
  4080. // Many thanks for this post which made this migration much easier.
  4081. // https://mathiasbynens.be/notes/css-escapes
  4082. /**
  4083. *
  4084. * @param {string} str
  4085. * @returns {[string, number]|undefined}
  4086. */
  4087. function gobbleHex(str) {
  4088. var lower = str.toLowerCase();
  4089. var hex = '';
  4090. var spaceTerminated = false;
  4091. for (var i = 0; i < 6 && lower[i] !== undefined; i++) {
  4092. var code = lower.charCodeAt(i);
  4093. // check to see if we are dealing with a valid hex char [a-f|0-9]
  4094. var valid = code >= 97 && code <= 102 || code >= 48 && code <= 57;
  4095. // https://drafts.csswg.org/css-syntax/#consume-escaped-code-point
  4096. spaceTerminated = code === 32;
  4097. if (!valid) {
  4098. break;
  4099. }
  4100. hex += lower[i];
  4101. }
  4102. if (hex.length === 0) {
  4103. return undefined;
  4104. }
  4105. var codePoint = parseInt(hex, 16);
  4106. var isSurrogate = codePoint >= 0xD800 && codePoint <= 0xDFFF;
  4107. // Add special case for
  4108. // "If this number is zero, or is for a surrogate, or is greater than the maximum allowed code point"
  4109. // https://drafts.csswg.org/css-syntax/#maximum-allowed-code-point
  4110. if (isSurrogate || codePoint === 0x0000 || codePoint > 0x10FFFF) {
  4111. return ["\uFFFD", hex.length + (spaceTerminated ? 1 : 0)];
  4112. }
  4113. return [String.fromCodePoint(codePoint), hex.length + (spaceTerminated ? 1 : 0)];
  4114. }
  4115. var CONTAINS_ESCAPE = /\\/;
  4116. function unesc(str) {
  4117. var needToProcess = CONTAINS_ESCAPE.test(str);
  4118. if (!needToProcess) {
  4119. return str;
  4120. }
  4121. var ret = "";
  4122. for (var i = 0; i < str.length; i++) {
  4123. if (str[i] === "\\") {
  4124. var gobbled = gobbleHex(str.slice(i + 1, i + 7));
  4125. if (gobbled !== undefined) {
  4126. ret += gobbled[0];
  4127. i += gobbled[1];
  4128. continue;
  4129. }
  4130. // Retain a pair of \\ if double escaped `\\\\`
  4131. // https://github.com/postcss/postcss-selector-parser/commit/268c9a7656fb53f543dc620aa5b73a30ec3ff20e
  4132. if (str[i + 1] === "\\") {
  4133. ret += "\\";
  4134. i++;
  4135. continue;
  4136. }
  4137. // if \\ is at the end of the string retain it
  4138. // https://github.com/postcss/postcss-selector-parser/commit/01a6b346e3612ce1ab20219acc26abdc259ccefb
  4139. if (str.length === i + 1) {
  4140. ret += str[i];
  4141. }
  4142. continue;
  4143. }
  4144. ret += str[i];
  4145. }
  4146. return ret;
  4147. }
  4148. module.exports = exports.default;
  4149. } (unesc, unesc.exports));
  4150. var unescExports = unesc.exports;
  4151. var getProp = {exports: {}};
  4152. (function (module, exports) {
  4153. exports.__esModule = true;
  4154. exports["default"] = getProp;
  4155. function getProp(obj) {
  4156. for (var _len = arguments.length, props = new Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++) {
  4157. props[_key - 1] = arguments[_key];
  4158. }
  4159. while (props.length > 0) {
  4160. var prop = props.shift();
  4161. if (!obj[prop]) {
  4162. return undefined;
  4163. }
  4164. obj = obj[prop];
  4165. }
  4166. return obj;
  4167. }
  4168. module.exports = exports.default;
  4169. } (getProp, getProp.exports));
  4170. var getPropExports = getProp.exports;
  4171. var ensureObject = {exports: {}};
  4172. (function (module, exports) {
  4173. exports.__esModule = true;
  4174. exports["default"] = ensureObject;
  4175. function ensureObject(obj) {
  4176. for (var _len = arguments.length, props = new Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++) {
  4177. props[_key - 1] = arguments[_key];
  4178. }
  4179. while (props.length > 0) {
  4180. var prop = props.shift();
  4181. if (!obj[prop]) {
  4182. obj[prop] = {};
  4183. }
  4184. obj = obj[prop];
  4185. }
  4186. }
  4187. module.exports = exports.default;
  4188. } (ensureObject, ensureObject.exports));
  4189. var ensureObjectExports = ensureObject.exports;
  4190. var stripComments = {exports: {}};
  4191. (function (module, exports) {
  4192. exports.__esModule = true;
  4193. exports["default"] = stripComments;
  4194. function stripComments(str) {
  4195. var s = "";
  4196. var commentStart = str.indexOf("/*");
  4197. var lastEnd = 0;
  4198. while (commentStart >= 0) {
  4199. s = s + str.slice(lastEnd, commentStart);
  4200. var commentEnd = str.indexOf("*/", commentStart + 2);
  4201. if (commentEnd < 0) {
  4202. return s;
  4203. }
  4204. lastEnd = commentEnd + 2;
  4205. commentStart = str.indexOf("/*", lastEnd);
  4206. }
  4207. s = s + str.slice(lastEnd);
  4208. return s;
  4209. }
  4210. module.exports = exports.default;
  4211. } (stripComments, stripComments.exports));
  4212. var stripCommentsExports = stripComments.exports;
  4213. util$6.__esModule = true;
  4214. util$6.unesc = util$6.stripComments = util$6.getProp = util$6.ensureObject = void 0;
  4215. var _unesc = _interopRequireDefault$5(unescExports);
  4216. util$6.unesc = _unesc["default"];
  4217. var _getProp = _interopRequireDefault$5(getPropExports);
  4218. util$6.getProp = _getProp["default"];
  4219. var _ensureObject = _interopRequireDefault$5(ensureObjectExports);
  4220. util$6.ensureObject = _ensureObject["default"];
  4221. var _stripComments = _interopRequireDefault$5(stripCommentsExports);
  4222. util$6.stripComments = _stripComments["default"];
  4223. function _interopRequireDefault$5(obj) { return obj && obj.__esModule ? obj : { "default": obj }; }
  4224. (function (module, exports) {
  4225. exports.__esModule = true;
  4226. exports["default"] = void 0;
  4227. var _util = util$6;
  4228. 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); } }
  4229. function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); Object.defineProperty(Constructor, "prototype", { writable: false }); return Constructor; }
  4230. var cloneNode = function cloneNode(obj, parent) {
  4231. if (typeof obj !== 'object' || obj === null) {
  4232. return obj;
  4233. }
  4234. var cloned = new obj.constructor();
  4235. for (var i in obj) {
  4236. if (!obj.hasOwnProperty(i)) {
  4237. continue;
  4238. }
  4239. var value = obj[i];
  4240. var type = typeof value;
  4241. if (i === 'parent' && type === 'object') {
  4242. if (parent) {
  4243. cloned[i] = parent;
  4244. }
  4245. } else if (value instanceof Array) {
  4246. cloned[i] = value.map(function (j) {
  4247. return cloneNode(j, cloned);
  4248. });
  4249. } else {
  4250. cloned[i] = cloneNode(value, cloned);
  4251. }
  4252. }
  4253. return cloned;
  4254. };
  4255. var Node = /*#__PURE__*/function () {
  4256. function Node(opts) {
  4257. if (opts === void 0) {
  4258. opts = {};
  4259. }
  4260. Object.assign(this, opts);
  4261. this.spaces = this.spaces || {};
  4262. this.spaces.before = this.spaces.before || '';
  4263. this.spaces.after = this.spaces.after || '';
  4264. }
  4265. var _proto = Node.prototype;
  4266. _proto.remove = function remove() {
  4267. if (this.parent) {
  4268. this.parent.removeChild(this);
  4269. }
  4270. this.parent = undefined;
  4271. return this;
  4272. };
  4273. _proto.replaceWith = function replaceWith() {
  4274. if (this.parent) {
  4275. for (var index in arguments) {
  4276. this.parent.insertBefore(this, arguments[index]);
  4277. }
  4278. this.remove();
  4279. }
  4280. return this;
  4281. };
  4282. _proto.next = function next() {
  4283. return this.parent.at(this.parent.index(this) + 1);
  4284. };
  4285. _proto.prev = function prev() {
  4286. return this.parent.at(this.parent.index(this) - 1);
  4287. };
  4288. _proto.clone = function clone(overrides) {
  4289. if (overrides === void 0) {
  4290. overrides = {};
  4291. }
  4292. var cloned = cloneNode(this);
  4293. for (var name in overrides) {
  4294. cloned[name] = overrides[name];
  4295. }
  4296. return cloned;
  4297. }
  4298. /**
  4299. * Some non-standard syntax doesn't follow normal escaping rules for css.
  4300. * This allows non standard syntax to be appended to an existing property
  4301. * by specifying the escaped value. By specifying the escaped value,
  4302. * illegal characters are allowed to be directly inserted into css output.
  4303. * @param {string} name the property to set
  4304. * @param {any} value the unescaped value of the property
  4305. * @param {string} valueEscaped optional. the escaped value of the property.
  4306. */;
  4307. _proto.appendToPropertyAndEscape = function appendToPropertyAndEscape(name, value, valueEscaped) {
  4308. if (!this.raws) {
  4309. this.raws = {};
  4310. }
  4311. var originalValue = this[name];
  4312. var originalEscaped = this.raws[name];
  4313. this[name] = originalValue + value; // this may trigger a setter that updates raws, so it has to be set first.
  4314. if (originalEscaped || valueEscaped !== value) {
  4315. this.raws[name] = (originalEscaped || originalValue) + valueEscaped;
  4316. } else {
  4317. delete this.raws[name]; // delete any escaped value that was created by the setter.
  4318. }
  4319. }
  4320. /**
  4321. * Some non-standard syntax doesn't follow normal escaping rules for css.
  4322. * This allows the escaped value to be specified directly, allowing illegal
  4323. * characters to be directly inserted into css output.
  4324. * @param {string} name the property to set
  4325. * @param {any} value the unescaped value of the property
  4326. * @param {string} valueEscaped the escaped value of the property.
  4327. */;
  4328. _proto.setPropertyAndEscape = function setPropertyAndEscape(name, value, valueEscaped) {
  4329. if (!this.raws) {
  4330. this.raws = {};
  4331. }
  4332. this[name] = value; // this may trigger a setter that updates raws, so it has to be set first.
  4333. this.raws[name] = valueEscaped;
  4334. }
  4335. /**
  4336. * When you want a value to passed through to CSS directly. This method
  4337. * deletes the corresponding raw value causing the stringifier to fallback
  4338. * to the unescaped value.
  4339. * @param {string} name the property to set.
  4340. * @param {any} value The value that is both escaped and unescaped.
  4341. */;
  4342. _proto.setPropertyWithoutEscape = function setPropertyWithoutEscape(name, value) {
  4343. this[name] = value; // this may trigger a setter that updates raws, so it has to be set first.
  4344. if (this.raws) {
  4345. delete this.raws[name];
  4346. }
  4347. }
  4348. /**
  4349. *
  4350. * @param {number} line The number (starting with 1)
  4351. * @param {number} column The column number (starting with 1)
  4352. */;
  4353. _proto.isAtPosition = function isAtPosition(line, column) {
  4354. if (this.source && this.source.start && this.source.end) {
  4355. if (this.source.start.line > line) {
  4356. return false;
  4357. }
  4358. if (this.source.end.line < line) {
  4359. return false;
  4360. }
  4361. if (this.source.start.line === line && this.source.start.column > column) {
  4362. return false;
  4363. }
  4364. if (this.source.end.line === line && this.source.end.column < column) {
  4365. return false;
  4366. }
  4367. return true;
  4368. }
  4369. return undefined;
  4370. };
  4371. _proto.stringifyProperty = function stringifyProperty(name) {
  4372. return this.raws && this.raws[name] || this[name];
  4373. };
  4374. _proto.valueToString = function valueToString() {
  4375. return String(this.stringifyProperty("value"));
  4376. };
  4377. _proto.toString = function toString() {
  4378. return [this.rawSpaceBefore, this.valueToString(), this.rawSpaceAfter].join('');
  4379. };
  4380. _createClass(Node, [{
  4381. key: "rawSpaceBefore",
  4382. get: function get() {
  4383. var rawSpace = this.raws && this.raws.spaces && this.raws.spaces.before;
  4384. if (rawSpace === undefined) {
  4385. rawSpace = this.spaces && this.spaces.before;
  4386. }
  4387. return rawSpace || "";
  4388. },
  4389. set: function set(raw) {
  4390. (0, _util.ensureObject)(this, "raws", "spaces");
  4391. this.raws.spaces.before = raw;
  4392. }
  4393. }, {
  4394. key: "rawSpaceAfter",
  4395. get: function get() {
  4396. var rawSpace = this.raws && this.raws.spaces && this.raws.spaces.after;
  4397. if (rawSpace === undefined) {
  4398. rawSpace = this.spaces.after;
  4399. }
  4400. return rawSpace || "";
  4401. },
  4402. set: function set(raw) {
  4403. (0, _util.ensureObject)(this, "raws", "spaces");
  4404. this.raws.spaces.after = raw;
  4405. }
  4406. }]);
  4407. return Node;
  4408. }();
  4409. exports["default"] = Node;
  4410. module.exports = exports.default;
  4411. } (node$1, node$1.exports));
  4412. var nodeExports = node$1.exports;
  4413. var types$1 = {};
  4414. types$1.__esModule = true;
  4415. 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;
  4416. var TAG = 'tag';
  4417. types$1.TAG = TAG;
  4418. var STRING = 'string';
  4419. types$1.STRING = STRING;
  4420. var SELECTOR = 'selector';
  4421. types$1.SELECTOR = SELECTOR;
  4422. var ROOT = 'root';
  4423. types$1.ROOT = ROOT;
  4424. var PSEUDO = 'pseudo';
  4425. types$1.PSEUDO = PSEUDO;
  4426. var NESTING = 'nesting';
  4427. types$1.NESTING = NESTING;
  4428. var ID = 'id';
  4429. types$1.ID = ID;
  4430. var COMMENT = 'comment';
  4431. types$1.COMMENT = COMMENT;
  4432. var COMBINATOR = 'combinator';
  4433. types$1.COMBINATOR = COMBINATOR;
  4434. var CLASS = 'class';
  4435. types$1.CLASS = CLASS;
  4436. var ATTRIBUTE = 'attribute';
  4437. types$1.ATTRIBUTE = ATTRIBUTE;
  4438. var UNIVERSAL = 'universal';
  4439. types$1.UNIVERSAL = UNIVERSAL;
  4440. (function (module, exports) {
  4441. exports.__esModule = true;
  4442. exports["default"] = void 0;
  4443. var _node = _interopRequireDefault(nodeExports);
  4444. var types = _interopRequireWildcard(types$1);
  4445. 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); }
  4446. function _interopRequireWildcard(obj, nodeInterop) { if (!nodeInterop && 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; }
  4447. function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; }
  4448. 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 && o && typeof o.length === "number") { 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."); }
  4449. 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); }
  4450. 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; }
  4451. 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); } }
  4452. function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); Object.defineProperty(Constructor, "prototype", { writable: false }); return Constructor; }
  4453. function _inheritsLoose(subClass, superClass) { subClass.prototype = Object.create(superClass.prototype); subClass.prototype.constructor = subClass; _setPrototypeOf(subClass, superClass); }
  4454. function _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf ? Object.setPrototypeOf.bind() : function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); }
  4455. var Container = /*#__PURE__*/function (_Node) {
  4456. _inheritsLoose(Container, _Node);
  4457. function Container(opts) {
  4458. var _this;
  4459. _this = _Node.call(this, opts) || this;
  4460. if (!_this.nodes) {
  4461. _this.nodes = [];
  4462. }
  4463. return _this;
  4464. }
  4465. var _proto = Container.prototype;
  4466. _proto.append = function append(selector) {
  4467. selector.parent = this;
  4468. this.nodes.push(selector);
  4469. return this;
  4470. };
  4471. _proto.prepend = function prepend(selector) {
  4472. selector.parent = this;
  4473. this.nodes.unshift(selector);
  4474. return this;
  4475. };
  4476. _proto.at = function at(index) {
  4477. return this.nodes[index];
  4478. };
  4479. _proto.index = function index(child) {
  4480. if (typeof child === 'number') {
  4481. return child;
  4482. }
  4483. return this.nodes.indexOf(child);
  4484. };
  4485. _proto.removeChild = function removeChild(child) {
  4486. child = this.index(child);
  4487. this.at(child).parent = undefined;
  4488. this.nodes.splice(child, 1);
  4489. var index;
  4490. for (var id in this.indexes) {
  4491. index = this.indexes[id];
  4492. if (index >= child) {
  4493. this.indexes[id] = index - 1;
  4494. }
  4495. }
  4496. return this;
  4497. };
  4498. _proto.removeAll = function removeAll() {
  4499. for (var _iterator = _createForOfIteratorHelperLoose(this.nodes), _step; !(_step = _iterator()).done;) {
  4500. var node = _step.value;
  4501. node.parent = undefined;
  4502. }
  4503. this.nodes = [];
  4504. return this;
  4505. };
  4506. _proto.empty = function empty() {
  4507. return this.removeAll();
  4508. };
  4509. _proto.insertAfter = function insertAfter(oldNode, newNode) {
  4510. newNode.parent = this;
  4511. var oldIndex = this.index(oldNode);
  4512. this.nodes.splice(oldIndex + 1, 0, newNode);
  4513. newNode.parent = this;
  4514. var index;
  4515. for (var id in this.indexes) {
  4516. index = this.indexes[id];
  4517. if (oldIndex <= index) {
  4518. this.indexes[id] = index + 1;
  4519. }
  4520. }
  4521. return this;
  4522. };
  4523. _proto.insertBefore = function insertBefore(oldNode, newNode) {
  4524. newNode.parent = this;
  4525. var oldIndex = this.index(oldNode);
  4526. this.nodes.splice(oldIndex, 0, newNode);
  4527. newNode.parent = this;
  4528. var index;
  4529. for (var id in this.indexes) {
  4530. index = this.indexes[id];
  4531. if (index <= oldIndex) {
  4532. this.indexes[id] = index + 1;
  4533. }
  4534. }
  4535. return this;
  4536. };
  4537. _proto._findChildAtPosition = function _findChildAtPosition(line, col) {
  4538. var found = undefined;
  4539. this.each(function (node) {
  4540. if (node.atPosition) {
  4541. var foundChild = node.atPosition(line, col);
  4542. if (foundChild) {
  4543. found = foundChild;
  4544. return false;
  4545. }
  4546. } else if (node.isAtPosition(line, col)) {
  4547. found = node;
  4548. return false;
  4549. }
  4550. });
  4551. return found;
  4552. }
  4553. /**
  4554. * Return the most specific node at the line and column number given.
  4555. * The source location is based on the original parsed location, locations aren't
  4556. * updated as selector nodes are mutated.
  4557. *
  4558. * Note that this location is relative to the location of the first character
  4559. * of the selector, and not the location of the selector in the overall document
  4560. * when used in conjunction with postcss.
  4561. *
  4562. * If not found, returns undefined.
  4563. * @param {number} line The line number of the node to find. (1-based index)
  4564. * @param {number} col The column number of the node to find. (1-based index)
  4565. */;
  4566. _proto.atPosition = function atPosition(line, col) {
  4567. if (this.isAtPosition(line, col)) {
  4568. return this._findChildAtPosition(line, col) || this;
  4569. } else {
  4570. return undefined;
  4571. }
  4572. };
  4573. _proto._inferEndPosition = function _inferEndPosition() {
  4574. if (this.last && this.last.source && this.last.source.end) {
  4575. this.source = this.source || {};
  4576. this.source.end = this.source.end || {};
  4577. Object.assign(this.source.end, this.last.source.end);
  4578. }
  4579. };
  4580. _proto.each = function each(callback) {
  4581. if (!this.lastEach) {
  4582. this.lastEach = 0;
  4583. }
  4584. if (!this.indexes) {
  4585. this.indexes = {};
  4586. }
  4587. this.lastEach++;
  4588. var id = this.lastEach;
  4589. this.indexes[id] = 0;
  4590. if (!this.length) {
  4591. return undefined;
  4592. }
  4593. var index, result;
  4594. while (this.indexes[id] < this.length) {
  4595. index = this.indexes[id];
  4596. result = callback(this.at(index), index);
  4597. if (result === false) {
  4598. break;
  4599. }
  4600. this.indexes[id] += 1;
  4601. }
  4602. delete this.indexes[id];
  4603. if (result === false) {
  4604. return false;
  4605. }
  4606. };
  4607. _proto.walk = function walk(callback) {
  4608. return this.each(function (node, i) {
  4609. var result = callback(node, i);
  4610. if (result !== false && node.length) {
  4611. result = node.walk(callback);
  4612. }
  4613. if (result === false) {
  4614. return false;
  4615. }
  4616. });
  4617. };
  4618. _proto.walkAttributes = function walkAttributes(callback) {
  4619. var _this2 = this;
  4620. return this.walk(function (selector) {
  4621. if (selector.type === types.ATTRIBUTE) {
  4622. return callback.call(_this2, selector);
  4623. }
  4624. });
  4625. };
  4626. _proto.walkClasses = function walkClasses(callback) {
  4627. var _this3 = this;
  4628. return this.walk(function (selector) {
  4629. if (selector.type === types.CLASS) {
  4630. return callback.call(_this3, selector);
  4631. }
  4632. });
  4633. };
  4634. _proto.walkCombinators = function walkCombinators(callback) {
  4635. var _this4 = this;
  4636. return this.walk(function (selector) {
  4637. if (selector.type === types.COMBINATOR) {
  4638. return callback.call(_this4, selector);
  4639. }
  4640. });
  4641. };
  4642. _proto.walkComments = function walkComments(callback) {
  4643. var _this5 = this;
  4644. return this.walk(function (selector) {
  4645. if (selector.type === types.COMMENT) {
  4646. return callback.call(_this5, selector);
  4647. }
  4648. });
  4649. };
  4650. _proto.walkIds = function walkIds(callback) {
  4651. var _this6 = this;
  4652. return this.walk(function (selector) {
  4653. if (selector.type === types.ID) {
  4654. return callback.call(_this6, selector);
  4655. }
  4656. });
  4657. };
  4658. _proto.walkNesting = function walkNesting(callback) {
  4659. var _this7 = this;
  4660. return this.walk(function (selector) {
  4661. if (selector.type === types.NESTING) {
  4662. return callback.call(_this7, selector);
  4663. }
  4664. });
  4665. };
  4666. _proto.walkPseudos = function walkPseudos(callback) {
  4667. var _this8 = this;
  4668. return this.walk(function (selector) {
  4669. if (selector.type === types.PSEUDO) {
  4670. return callback.call(_this8, selector);
  4671. }
  4672. });
  4673. };
  4674. _proto.walkTags = function walkTags(callback) {
  4675. var _this9 = this;
  4676. return this.walk(function (selector) {
  4677. if (selector.type === types.TAG) {
  4678. return callback.call(_this9, selector);
  4679. }
  4680. });
  4681. };
  4682. _proto.walkUniversals = function walkUniversals(callback) {
  4683. var _this10 = this;
  4684. return this.walk(function (selector) {
  4685. if (selector.type === types.UNIVERSAL) {
  4686. return callback.call(_this10, selector);
  4687. }
  4688. });
  4689. };
  4690. _proto.split = function split(callback) {
  4691. var _this11 = this;
  4692. var current = [];
  4693. return this.reduce(function (memo, node, index) {
  4694. var split = callback.call(_this11, node);
  4695. current.push(node);
  4696. if (split) {
  4697. memo.push(current);
  4698. current = [];
  4699. } else if (index === _this11.length - 1) {
  4700. memo.push(current);
  4701. }
  4702. return memo;
  4703. }, []);
  4704. };
  4705. _proto.map = function map(callback) {
  4706. return this.nodes.map(callback);
  4707. };
  4708. _proto.reduce = function reduce(callback, memo) {
  4709. return this.nodes.reduce(callback, memo);
  4710. };
  4711. _proto.every = function every(callback) {
  4712. return this.nodes.every(callback);
  4713. };
  4714. _proto.some = function some(callback) {
  4715. return this.nodes.some(callback);
  4716. };
  4717. _proto.filter = function filter(callback) {
  4718. return this.nodes.filter(callback);
  4719. };
  4720. _proto.sort = function sort(callback) {
  4721. return this.nodes.sort(callback);
  4722. };
  4723. _proto.toString = function toString() {
  4724. return this.map(String).join('');
  4725. };
  4726. _createClass(Container, [{
  4727. key: "first",
  4728. get: function get() {
  4729. return this.at(0);
  4730. }
  4731. }, {
  4732. key: "last",
  4733. get: function get() {
  4734. return this.at(this.length - 1);
  4735. }
  4736. }, {
  4737. key: "length",
  4738. get: function get() {
  4739. return this.nodes.length;
  4740. }
  4741. }]);
  4742. return Container;
  4743. }(_node["default"]);
  4744. exports["default"] = Container;
  4745. module.exports = exports.default;
  4746. } (container, container.exports));
  4747. var containerExports = container.exports;
  4748. (function (module, exports) {
  4749. exports.__esModule = true;
  4750. exports["default"] = void 0;
  4751. var _container = _interopRequireDefault(containerExports);
  4752. var _types = types$1;
  4753. function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; }
  4754. 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); } }
  4755. function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); Object.defineProperty(Constructor, "prototype", { writable: false }); return Constructor; }
  4756. function _inheritsLoose(subClass, superClass) { subClass.prototype = Object.create(superClass.prototype); subClass.prototype.constructor = subClass; _setPrototypeOf(subClass, superClass); }
  4757. function _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf ? Object.setPrototypeOf.bind() : function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); }
  4758. var Root = /*#__PURE__*/function (_Container) {
  4759. _inheritsLoose(Root, _Container);
  4760. function Root(opts) {
  4761. var _this;
  4762. _this = _Container.call(this, opts) || this;
  4763. _this.type = _types.ROOT;
  4764. return _this;
  4765. }
  4766. var _proto = Root.prototype;
  4767. _proto.toString = function toString() {
  4768. var str = this.reduce(function (memo, selector) {
  4769. memo.push(String(selector));
  4770. return memo;
  4771. }, []).join(',');
  4772. return this.trailingComma ? str + ',' : str;
  4773. };
  4774. _proto.error = function error(message, options) {
  4775. if (this._error) {
  4776. return this._error(message, options);
  4777. } else {
  4778. return new Error(message);
  4779. }
  4780. };
  4781. _createClass(Root, [{
  4782. key: "errorGenerator",
  4783. set: function set(handler) {
  4784. this._error = handler;
  4785. }
  4786. }]);
  4787. return Root;
  4788. }(_container["default"]);
  4789. exports["default"] = Root;
  4790. module.exports = exports.default;
  4791. } (root$2, root$2.exports));
  4792. var rootExports = root$2.exports;
  4793. var selector$1 = {exports: {}};
  4794. (function (module, exports) {
  4795. exports.__esModule = true;
  4796. exports["default"] = void 0;
  4797. var _container = _interopRequireDefault(containerExports);
  4798. var _types = types$1;
  4799. function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; }
  4800. function _inheritsLoose(subClass, superClass) { subClass.prototype = Object.create(superClass.prototype); subClass.prototype.constructor = subClass; _setPrototypeOf(subClass, superClass); }
  4801. function _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf ? Object.setPrototypeOf.bind() : function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); }
  4802. var Selector = /*#__PURE__*/function (_Container) {
  4803. _inheritsLoose(Selector, _Container);
  4804. function Selector(opts) {
  4805. var _this;
  4806. _this = _Container.call(this, opts) || this;
  4807. _this.type = _types.SELECTOR;
  4808. return _this;
  4809. }
  4810. return Selector;
  4811. }(_container["default"]);
  4812. exports["default"] = Selector;
  4813. module.exports = exports.default;
  4814. } (selector$1, selector$1.exports));
  4815. var selectorExports = selector$1.exports;
  4816. var className$1 = {exports: {}};
  4817. /*! https://mths.be/cssesc v3.0.0 by @mathias */
  4818. var object = {};
  4819. var hasOwnProperty$1 = object.hasOwnProperty;
  4820. var merge$2 = function merge(options, defaults) {
  4821. if (!options) {
  4822. return defaults;
  4823. }
  4824. var result = {};
  4825. for (var key in defaults) {
  4826. // `if (defaults.hasOwnProperty(key) { … }` is not needed here, since
  4827. // only recognized option names are used.
  4828. result[key] = hasOwnProperty$1.call(options, key) ? options[key] : defaults[key];
  4829. }
  4830. return result;
  4831. };
  4832. var regexAnySingleEscape = /[ -,\.\/:-@\[-\^`\{-~]/;
  4833. var regexSingleEscape = /[ -,\.\/:-@\[\]\^`\{-~]/;
  4834. var regexExcessiveSpaces = /(^|\\+)?(\\[A-F0-9]{1,6})\x20(?![a-fA-F0-9\x20])/g;
  4835. // https://mathiasbynens.be/notes/css-escapes#css
  4836. var cssesc = function cssesc(string, options) {
  4837. options = merge$2(options, cssesc.options);
  4838. if (options.quotes != 'single' && options.quotes != 'double') {
  4839. options.quotes = 'single';
  4840. }
  4841. var quote = options.quotes == 'double' ? '"' : '\'';
  4842. var isIdentifier = options.isIdentifier;
  4843. var firstChar = string.charAt(0);
  4844. var output = '';
  4845. var counter = 0;
  4846. var length = string.length;
  4847. while (counter < length) {
  4848. var character = string.charAt(counter++);
  4849. var codePoint = character.charCodeAt();
  4850. var value = void 0;
  4851. // If it’s not a printable ASCII character…
  4852. if (codePoint < 0x20 || codePoint > 0x7E) {
  4853. if (codePoint >= 0xD800 && codePoint <= 0xDBFF && counter < length) {
  4854. // It’s a high surrogate, and there is a next character.
  4855. var extra = string.charCodeAt(counter++);
  4856. if ((extra & 0xFC00) == 0xDC00) {
  4857. // next character is low surrogate
  4858. codePoint = ((codePoint & 0x3FF) << 10) + (extra & 0x3FF) + 0x10000;
  4859. } else {
  4860. // It’s an unmatched surrogate; only append this code unit, in case
  4861. // the next code unit is the high surrogate of a surrogate pair.
  4862. counter--;
  4863. }
  4864. }
  4865. value = '\\' + codePoint.toString(16).toUpperCase() + ' ';
  4866. } else {
  4867. if (options.escapeEverything) {
  4868. if (regexAnySingleEscape.test(character)) {
  4869. value = '\\' + character;
  4870. } else {
  4871. value = '\\' + codePoint.toString(16).toUpperCase() + ' ';
  4872. }
  4873. } else if (/[\t\n\f\r\x0B]/.test(character)) {
  4874. value = '\\' + codePoint.toString(16).toUpperCase() + ' ';
  4875. } else if (character == '\\' || !isIdentifier && (character == '"' && quote == character || character == '\'' && quote == character) || isIdentifier && regexSingleEscape.test(character)) {
  4876. value = '\\' + character;
  4877. } else {
  4878. value = character;
  4879. }
  4880. }
  4881. output += value;
  4882. }
  4883. if (isIdentifier) {
  4884. if (/^-[-\d]/.test(output)) {
  4885. output = '\\-' + output.slice(1);
  4886. } else if (/\d/.test(firstChar)) {
  4887. output = '\\3' + firstChar + ' ' + output.slice(1);
  4888. }
  4889. }
  4890. // Remove spaces after `\HEX` escapes that are not followed by a hex digit,
  4891. // since they’re redundant. Note that this is only possible if the escape
  4892. // sequence isn’t preceded by an odd number of backslashes.
  4893. output = output.replace(regexExcessiveSpaces, function ($0, $1, $2) {
  4894. if ($1 && $1.length % 2) {
  4895. // It’s not safe to remove the space, so don’t.
  4896. return $0;
  4897. }
  4898. // Strip the space.
  4899. return ($1 || '') + $2;
  4900. });
  4901. if (!isIdentifier && options.wrap) {
  4902. return quote + output + quote;
  4903. }
  4904. return output;
  4905. };
  4906. // Expose default options (so they can be overridden globally).
  4907. cssesc.options = {
  4908. 'escapeEverything': false,
  4909. 'isIdentifier': false,
  4910. 'quotes': 'single',
  4911. 'wrap': false
  4912. };
  4913. cssesc.version = '3.0.0';
  4914. var cssesc_1 = cssesc;
  4915. (function (module, exports) {
  4916. exports.__esModule = true;
  4917. exports["default"] = void 0;
  4918. var _cssesc = _interopRequireDefault(cssesc_1);
  4919. var _util = util$6;
  4920. var _node = _interopRequireDefault(nodeExports);
  4921. var _types = types$1;
  4922. function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; }
  4923. 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); } }
  4924. function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); Object.defineProperty(Constructor, "prototype", { writable: false }); return Constructor; }
  4925. function _inheritsLoose(subClass, superClass) { subClass.prototype = Object.create(superClass.prototype); subClass.prototype.constructor = subClass; _setPrototypeOf(subClass, superClass); }
  4926. function _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf ? Object.setPrototypeOf.bind() : function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); }
  4927. var ClassName = /*#__PURE__*/function (_Node) {
  4928. _inheritsLoose(ClassName, _Node);
  4929. function ClassName(opts) {
  4930. var _this;
  4931. _this = _Node.call(this, opts) || this;
  4932. _this.type = _types.CLASS;
  4933. _this._constructed = true;
  4934. return _this;
  4935. }
  4936. var _proto = ClassName.prototype;
  4937. _proto.valueToString = function valueToString() {
  4938. return '.' + _Node.prototype.valueToString.call(this);
  4939. };
  4940. _createClass(ClassName, [{
  4941. key: "value",
  4942. get: function get() {
  4943. return this._value;
  4944. },
  4945. set: function set(v) {
  4946. if (this._constructed) {
  4947. var escaped = (0, _cssesc["default"])(v, {
  4948. isIdentifier: true
  4949. });
  4950. if (escaped !== v) {
  4951. (0, _util.ensureObject)(this, "raws");
  4952. this.raws.value = escaped;
  4953. } else if (this.raws) {
  4954. delete this.raws.value;
  4955. }
  4956. }
  4957. this._value = v;
  4958. }
  4959. }]);
  4960. return ClassName;
  4961. }(_node["default"]);
  4962. exports["default"] = ClassName;
  4963. module.exports = exports.default;
  4964. } (className$1, className$1.exports));
  4965. var classNameExports = className$1.exports;
  4966. var comment$2 = {exports: {}};
  4967. (function (module, exports) {
  4968. exports.__esModule = true;
  4969. exports["default"] = void 0;
  4970. var _node = _interopRequireDefault(nodeExports);
  4971. var _types = types$1;
  4972. function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; }
  4973. function _inheritsLoose(subClass, superClass) { subClass.prototype = Object.create(superClass.prototype); subClass.prototype.constructor = subClass; _setPrototypeOf(subClass, superClass); }
  4974. function _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf ? Object.setPrototypeOf.bind() : function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); }
  4975. var Comment = /*#__PURE__*/function (_Node) {
  4976. _inheritsLoose(Comment, _Node);
  4977. function Comment(opts) {
  4978. var _this;
  4979. _this = _Node.call(this, opts) || this;
  4980. _this.type = _types.COMMENT;
  4981. return _this;
  4982. }
  4983. return Comment;
  4984. }(_node["default"]);
  4985. exports["default"] = Comment;
  4986. module.exports = exports.default;
  4987. } (comment$2, comment$2.exports));
  4988. var commentExports = comment$2.exports;
  4989. var id$1 = {exports: {}};
  4990. (function (module, exports) {
  4991. exports.__esModule = true;
  4992. exports["default"] = void 0;
  4993. var _node = _interopRequireDefault(nodeExports);
  4994. var _types = types$1;
  4995. function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; }
  4996. function _inheritsLoose(subClass, superClass) { subClass.prototype = Object.create(superClass.prototype); subClass.prototype.constructor = subClass; _setPrototypeOf(subClass, superClass); }
  4997. function _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf ? Object.setPrototypeOf.bind() : function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); }
  4998. var ID = /*#__PURE__*/function (_Node) {
  4999. _inheritsLoose(ID, _Node);
  5000. function ID(opts) {
  5001. var _this;
  5002. _this = _Node.call(this, opts) || this;
  5003. _this.type = _types.ID;
  5004. return _this;
  5005. }
  5006. var _proto = ID.prototype;
  5007. _proto.valueToString = function valueToString() {
  5008. return '#' + _Node.prototype.valueToString.call(this);
  5009. };
  5010. return ID;
  5011. }(_node["default"]);
  5012. exports["default"] = ID;
  5013. module.exports = exports.default;
  5014. } (id$1, id$1.exports));
  5015. var idExports = id$1.exports;
  5016. var tag$1 = {exports: {}};
  5017. var namespace = {exports: {}};
  5018. (function (module, exports) {
  5019. exports.__esModule = true;
  5020. exports["default"] = void 0;
  5021. var _cssesc = _interopRequireDefault(cssesc_1);
  5022. var _util = util$6;
  5023. var _node = _interopRequireDefault(nodeExports);
  5024. function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; }
  5025. 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); } }
  5026. function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); Object.defineProperty(Constructor, "prototype", { writable: false }); return Constructor; }
  5027. function _inheritsLoose(subClass, superClass) { subClass.prototype = Object.create(superClass.prototype); subClass.prototype.constructor = subClass; _setPrototypeOf(subClass, superClass); }
  5028. function _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf ? Object.setPrototypeOf.bind() : function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); }
  5029. var Namespace = /*#__PURE__*/function (_Node) {
  5030. _inheritsLoose(Namespace, _Node);
  5031. function Namespace() {
  5032. return _Node.apply(this, arguments) || this;
  5033. }
  5034. var _proto = Namespace.prototype;
  5035. _proto.qualifiedName = function qualifiedName(value) {
  5036. if (this.namespace) {
  5037. return this.namespaceString + "|" + value;
  5038. } else {
  5039. return value;
  5040. }
  5041. };
  5042. _proto.valueToString = function valueToString() {
  5043. return this.qualifiedName(_Node.prototype.valueToString.call(this));
  5044. };
  5045. _createClass(Namespace, [{
  5046. key: "namespace",
  5047. get: function get() {
  5048. return this._namespace;
  5049. },
  5050. set: function set(namespace) {
  5051. if (namespace === true || namespace === "*" || namespace === "&") {
  5052. this._namespace = namespace;
  5053. if (this.raws) {
  5054. delete this.raws.namespace;
  5055. }
  5056. return;
  5057. }
  5058. var escaped = (0, _cssesc["default"])(namespace, {
  5059. isIdentifier: true
  5060. });
  5061. this._namespace = namespace;
  5062. if (escaped !== namespace) {
  5063. (0, _util.ensureObject)(this, "raws");
  5064. this.raws.namespace = escaped;
  5065. } else if (this.raws) {
  5066. delete this.raws.namespace;
  5067. }
  5068. }
  5069. }, {
  5070. key: "ns",
  5071. get: function get() {
  5072. return this._namespace;
  5073. },
  5074. set: function set(namespace) {
  5075. this.namespace = namespace;
  5076. }
  5077. }, {
  5078. key: "namespaceString",
  5079. get: function get() {
  5080. if (this.namespace) {
  5081. var ns = this.stringifyProperty("namespace");
  5082. if (ns === true) {
  5083. return '';
  5084. } else {
  5085. return ns;
  5086. }
  5087. } else {
  5088. return '';
  5089. }
  5090. }
  5091. }]);
  5092. return Namespace;
  5093. }(_node["default"]);
  5094. exports["default"] = Namespace;
  5095. module.exports = exports.default;
  5096. } (namespace, namespace.exports));
  5097. var namespaceExports = namespace.exports;
  5098. (function (module, exports) {
  5099. exports.__esModule = true;
  5100. exports["default"] = void 0;
  5101. var _namespace = _interopRequireDefault(namespaceExports);
  5102. var _types = types$1;
  5103. function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; }
  5104. function _inheritsLoose(subClass, superClass) { subClass.prototype = Object.create(superClass.prototype); subClass.prototype.constructor = subClass; _setPrototypeOf(subClass, superClass); }
  5105. function _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf ? Object.setPrototypeOf.bind() : function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); }
  5106. var Tag = /*#__PURE__*/function (_Namespace) {
  5107. _inheritsLoose(Tag, _Namespace);
  5108. function Tag(opts) {
  5109. var _this;
  5110. _this = _Namespace.call(this, opts) || this;
  5111. _this.type = _types.TAG;
  5112. return _this;
  5113. }
  5114. return Tag;
  5115. }(_namespace["default"]);
  5116. exports["default"] = Tag;
  5117. module.exports = exports.default;
  5118. } (tag$1, tag$1.exports));
  5119. var tagExports = tag$1.exports;
  5120. var string$1 = {exports: {}};
  5121. (function (module, exports) {
  5122. exports.__esModule = true;
  5123. exports["default"] = void 0;
  5124. var _node = _interopRequireDefault(nodeExports);
  5125. var _types = types$1;
  5126. function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; }
  5127. function _inheritsLoose(subClass, superClass) { subClass.prototype = Object.create(superClass.prototype); subClass.prototype.constructor = subClass; _setPrototypeOf(subClass, superClass); }
  5128. function _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf ? Object.setPrototypeOf.bind() : function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); }
  5129. var String = /*#__PURE__*/function (_Node) {
  5130. _inheritsLoose(String, _Node);
  5131. function String(opts) {
  5132. var _this;
  5133. _this = _Node.call(this, opts) || this;
  5134. _this.type = _types.STRING;
  5135. return _this;
  5136. }
  5137. return String;
  5138. }(_node["default"]);
  5139. exports["default"] = String;
  5140. module.exports = exports.default;
  5141. } (string$1, string$1.exports));
  5142. var stringExports = string$1.exports;
  5143. var pseudo$1 = {exports: {}};
  5144. (function (module, exports) {
  5145. exports.__esModule = true;
  5146. exports["default"] = void 0;
  5147. var _container = _interopRequireDefault(containerExports);
  5148. var _types = types$1;
  5149. function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; }
  5150. function _inheritsLoose(subClass, superClass) { subClass.prototype = Object.create(superClass.prototype); subClass.prototype.constructor = subClass; _setPrototypeOf(subClass, superClass); }
  5151. function _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf ? Object.setPrototypeOf.bind() : function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); }
  5152. var Pseudo = /*#__PURE__*/function (_Container) {
  5153. _inheritsLoose(Pseudo, _Container);
  5154. function Pseudo(opts) {
  5155. var _this;
  5156. _this = _Container.call(this, opts) || this;
  5157. _this.type = _types.PSEUDO;
  5158. return _this;
  5159. }
  5160. var _proto = Pseudo.prototype;
  5161. _proto.toString = function toString() {
  5162. var params = this.length ? '(' + this.map(String).join(',') + ')' : '';
  5163. return [this.rawSpaceBefore, this.stringifyProperty("value"), params, this.rawSpaceAfter].join('');
  5164. };
  5165. return Pseudo;
  5166. }(_container["default"]);
  5167. exports["default"] = Pseudo;
  5168. module.exports = exports.default;
  5169. } (pseudo$1, pseudo$1.exports));
  5170. var pseudoExports = pseudo$1.exports;
  5171. var attribute$1 = {};
  5172. /**
  5173. * For Node.js, simply re-export the core `util.deprecate` function.
  5174. */
  5175. var node = require$$2.deprecate;
  5176. (function (exports) {
  5177. exports.__esModule = true;
  5178. exports["default"] = void 0;
  5179. exports.unescapeValue = unescapeValue;
  5180. var _cssesc = _interopRequireDefault(cssesc_1);
  5181. var _unesc = _interopRequireDefault(unescExports);
  5182. var _namespace = _interopRequireDefault(namespaceExports);
  5183. var _types = types$1;
  5184. var _CSSESC_QUOTE_OPTIONS;
  5185. function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; }
  5186. 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); } }
  5187. function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); Object.defineProperty(Constructor, "prototype", { writable: false }); return Constructor; }
  5188. function _inheritsLoose(subClass, superClass) { subClass.prototype = Object.create(superClass.prototype); subClass.prototype.constructor = subClass; _setPrototypeOf(subClass, superClass); }
  5189. function _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf ? Object.setPrototypeOf.bind() : function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); }
  5190. var deprecate = node;
  5191. var WRAPPED_IN_QUOTES = /^('|")([^]*)\1$/;
  5192. var warnOfDeprecatedValueAssignment = deprecate(function () {}, "Assigning an attribute a value containing characters that might need to be escaped is deprecated. " + "Call attribute.setValue() instead.");
  5193. var warnOfDeprecatedQuotedAssignment = deprecate(function () {}, "Assigning attr.quoted is deprecated and has no effect. Assign to attr.quoteMark instead.");
  5194. var warnOfDeprecatedConstructor = deprecate(function () {}, "Constructing an Attribute selector with a value without specifying quoteMark is deprecated. Note: The value should be unescaped now.");
  5195. function unescapeValue(value) {
  5196. var deprecatedUsage = false;
  5197. var quoteMark = null;
  5198. var unescaped = value;
  5199. var m = unescaped.match(WRAPPED_IN_QUOTES);
  5200. if (m) {
  5201. quoteMark = m[1];
  5202. unescaped = m[2];
  5203. }
  5204. unescaped = (0, _unesc["default"])(unescaped);
  5205. if (unescaped !== value) {
  5206. deprecatedUsage = true;
  5207. }
  5208. return {
  5209. deprecatedUsage: deprecatedUsage,
  5210. unescaped: unescaped,
  5211. quoteMark: quoteMark
  5212. };
  5213. }
  5214. function handleDeprecatedContructorOpts(opts) {
  5215. if (opts.quoteMark !== undefined) {
  5216. return opts;
  5217. }
  5218. if (opts.value === undefined) {
  5219. return opts;
  5220. }
  5221. warnOfDeprecatedConstructor();
  5222. var _unescapeValue = unescapeValue(opts.value),
  5223. quoteMark = _unescapeValue.quoteMark,
  5224. unescaped = _unescapeValue.unescaped;
  5225. if (!opts.raws) {
  5226. opts.raws = {};
  5227. }
  5228. if (opts.raws.value === undefined) {
  5229. opts.raws.value = opts.value;
  5230. }
  5231. opts.value = unescaped;
  5232. opts.quoteMark = quoteMark;
  5233. return opts;
  5234. }
  5235. var Attribute = /*#__PURE__*/function (_Namespace) {
  5236. _inheritsLoose(Attribute, _Namespace);
  5237. function Attribute(opts) {
  5238. var _this;
  5239. if (opts === void 0) {
  5240. opts = {};
  5241. }
  5242. _this = _Namespace.call(this, handleDeprecatedContructorOpts(opts)) || this;
  5243. _this.type = _types.ATTRIBUTE;
  5244. _this.raws = _this.raws || {};
  5245. Object.defineProperty(_this.raws, 'unquoted', {
  5246. get: deprecate(function () {
  5247. return _this.value;
  5248. }, "attr.raws.unquoted is deprecated. Call attr.value instead."),
  5249. set: deprecate(function () {
  5250. return _this.value;
  5251. }, "Setting attr.raws.unquoted is deprecated and has no effect. attr.value is unescaped by default now.")
  5252. });
  5253. _this._constructed = true;
  5254. return _this;
  5255. }
  5256. /**
  5257. * Returns the Attribute's value quoted such that it would be legal to use
  5258. * in the value of a css file. The original value's quotation setting
  5259. * used for stringification is left unchanged. See `setValue(value, options)`
  5260. * if you want to control the quote settings of a new value for the attribute.
  5261. *
  5262. * You can also change the quotation used for the current value by setting quoteMark.
  5263. *
  5264. * Options:
  5265. * * quoteMark {'"' | "'" | null} - Use this value to quote the value. If this
  5266. * option is not set, the original value for quoteMark will be used. If
  5267. * indeterminate, a double quote is used. The legal values are:
  5268. * * `null` - the value will be unquoted and characters will be escaped as necessary.
  5269. * * `'` - the value will be quoted with a single quote and single quotes are escaped.
  5270. * * `"` - the value will be quoted with a double quote and double quotes are escaped.
  5271. * * preferCurrentQuoteMark {boolean} - if true, prefer the source quote mark
  5272. * over the quoteMark option value.
  5273. * * smart {boolean} - if true, will select a quote mark based on the value
  5274. * and the other options specified here. See the `smartQuoteMark()`
  5275. * method.
  5276. **/
  5277. var _proto = Attribute.prototype;
  5278. _proto.getQuotedValue = function getQuotedValue(options) {
  5279. if (options === void 0) {
  5280. options = {};
  5281. }
  5282. var quoteMark = this._determineQuoteMark(options);
  5283. var cssescopts = CSSESC_QUOTE_OPTIONS[quoteMark];
  5284. var escaped = (0, _cssesc["default"])(this._value, cssescopts);
  5285. return escaped;
  5286. };
  5287. _proto._determineQuoteMark = function _determineQuoteMark(options) {
  5288. return options.smart ? this.smartQuoteMark(options) : this.preferredQuoteMark(options);
  5289. }
  5290. /**
  5291. * Set the unescaped value with the specified quotation options. The value
  5292. * provided must not include any wrapping quote marks -- those quotes will
  5293. * be interpreted as part of the value and escaped accordingly.
  5294. */;
  5295. _proto.setValue = function setValue(value, options) {
  5296. if (options === void 0) {
  5297. options = {};
  5298. }
  5299. this._value = value;
  5300. this._quoteMark = this._determineQuoteMark(options);
  5301. this._syncRawValue();
  5302. }
  5303. /**
  5304. * Intelligently select a quoteMark value based on the value's contents. If
  5305. * the value is a legal CSS ident, it will not be quoted. Otherwise a quote
  5306. * mark will be picked that minimizes the number of escapes.
  5307. *
  5308. * If there's no clear winner, the quote mark from these options is used,
  5309. * then the source quote mark (this is inverted if `preferCurrentQuoteMark` is
  5310. * true). If the quoteMark is unspecified, a double quote is used.
  5311. *
  5312. * @param options This takes the quoteMark and preferCurrentQuoteMark options
  5313. * from the quoteValue method.
  5314. */;
  5315. _proto.smartQuoteMark = function smartQuoteMark(options) {
  5316. var v = this.value;
  5317. var numSingleQuotes = v.replace(/[^']/g, '').length;
  5318. var numDoubleQuotes = v.replace(/[^"]/g, '').length;
  5319. if (numSingleQuotes + numDoubleQuotes === 0) {
  5320. var escaped = (0, _cssesc["default"])(v, {
  5321. isIdentifier: true
  5322. });
  5323. if (escaped === v) {
  5324. return Attribute.NO_QUOTE;
  5325. } else {
  5326. var pref = this.preferredQuoteMark(options);
  5327. if (pref === Attribute.NO_QUOTE) {
  5328. // pick a quote mark that isn't none and see if it's smaller
  5329. var quote = this.quoteMark || options.quoteMark || Attribute.DOUBLE_QUOTE;
  5330. var opts = CSSESC_QUOTE_OPTIONS[quote];
  5331. var quoteValue = (0, _cssesc["default"])(v, opts);
  5332. if (quoteValue.length < escaped.length) {
  5333. return quote;
  5334. }
  5335. }
  5336. return pref;
  5337. }
  5338. } else if (numDoubleQuotes === numSingleQuotes) {
  5339. return this.preferredQuoteMark(options);
  5340. } else if (numDoubleQuotes < numSingleQuotes) {
  5341. return Attribute.DOUBLE_QUOTE;
  5342. } else {
  5343. return Attribute.SINGLE_QUOTE;
  5344. }
  5345. }
  5346. /**
  5347. * Selects the preferred quote mark based on the options and the current quote mark value.
  5348. * If you want the quote mark to depend on the attribute value, call `smartQuoteMark(opts)`
  5349. * instead.
  5350. */;
  5351. _proto.preferredQuoteMark = function preferredQuoteMark(options) {
  5352. var quoteMark = options.preferCurrentQuoteMark ? this.quoteMark : options.quoteMark;
  5353. if (quoteMark === undefined) {
  5354. quoteMark = options.preferCurrentQuoteMark ? options.quoteMark : this.quoteMark;
  5355. }
  5356. if (quoteMark === undefined) {
  5357. quoteMark = Attribute.DOUBLE_QUOTE;
  5358. }
  5359. return quoteMark;
  5360. };
  5361. _proto._syncRawValue = function _syncRawValue() {
  5362. var rawValue = (0, _cssesc["default"])(this._value, CSSESC_QUOTE_OPTIONS[this.quoteMark]);
  5363. if (rawValue === this._value) {
  5364. if (this.raws) {
  5365. delete this.raws.value;
  5366. }
  5367. } else {
  5368. this.raws.value = rawValue;
  5369. }
  5370. };
  5371. _proto._handleEscapes = function _handleEscapes(prop, value) {
  5372. if (this._constructed) {
  5373. var escaped = (0, _cssesc["default"])(value, {
  5374. isIdentifier: true
  5375. });
  5376. if (escaped !== value) {
  5377. this.raws[prop] = escaped;
  5378. } else {
  5379. delete this.raws[prop];
  5380. }
  5381. }
  5382. };
  5383. _proto._spacesFor = function _spacesFor(name) {
  5384. var attrSpaces = {
  5385. before: '',
  5386. after: ''
  5387. };
  5388. var spaces = this.spaces[name] || {};
  5389. var rawSpaces = this.raws.spaces && this.raws.spaces[name] || {};
  5390. return Object.assign(attrSpaces, spaces, rawSpaces);
  5391. };
  5392. _proto._stringFor = function _stringFor(name, spaceName, concat) {
  5393. if (spaceName === void 0) {
  5394. spaceName = name;
  5395. }
  5396. if (concat === void 0) {
  5397. concat = defaultAttrConcat;
  5398. }
  5399. var attrSpaces = this._spacesFor(spaceName);
  5400. return concat(this.stringifyProperty(name), attrSpaces);
  5401. }
  5402. /**
  5403. * returns the offset of the attribute part specified relative to the
  5404. * start of the node of the output string.
  5405. *
  5406. * * "ns" - alias for "namespace"
  5407. * * "namespace" - the namespace if it exists.
  5408. * * "attribute" - the attribute name
  5409. * * "attributeNS" - the start of the attribute or its namespace
  5410. * * "operator" - the match operator of the attribute
  5411. * * "value" - The value (string or identifier)
  5412. * * "insensitive" - the case insensitivity flag;
  5413. * @param part One of the possible values inside an attribute.
  5414. * @returns -1 if the name is invalid or the value doesn't exist in this attribute.
  5415. */;
  5416. _proto.offsetOf = function offsetOf(name) {
  5417. var count = 1;
  5418. var attributeSpaces = this._spacesFor("attribute");
  5419. count += attributeSpaces.before.length;
  5420. if (name === "namespace" || name === "ns") {
  5421. return this.namespace ? count : -1;
  5422. }
  5423. if (name === "attributeNS") {
  5424. return count;
  5425. }
  5426. count += this.namespaceString.length;
  5427. if (this.namespace) {
  5428. count += 1;
  5429. }
  5430. if (name === "attribute") {
  5431. return count;
  5432. }
  5433. count += this.stringifyProperty("attribute").length;
  5434. count += attributeSpaces.after.length;
  5435. var operatorSpaces = this._spacesFor("operator");
  5436. count += operatorSpaces.before.length;
  5437. var operator = this.stringifyProperty("operator");
  5438. if (name === "operator") {
  5439. return operator ? count : -1;
  5440. }
  5441. count += operator.length;
  5442. count += operatorSpaces.after.length;
  5443. var valueSpaces = this._spacesFor("value");
  5444. count += valueSpaces.before.length;
  5445. var value = this.stringifyProperty("value");
  5446. if (name === "value") {
  5447. return value ? count : -1;
  5448. }
  5449. count += value.length;
  5450. count += valueSpaces.after.length;
  5451. var insensitiveSpaces = this._spacesFor("insensitive");
  5452. count += insensitiveSpaces.before.length;
  5453. if (name === "insensitive") {
  5454. return this.insensitive ? count : -1;
  5455. }
  5456. return -1;
  5457. };
  5458. _proto.toString = function toString() {
  5459. var _this2 = this;
  5460. var selector = [this.rawSpaceBefore, '['];
  5461. selector.push(this._stringFor('qualifiedAttribute', 'attribute'));
  5462. if (this.operator && (this.value || this.value === '')) {
  5463. selector.push(this._stringFor('operator'));
  5464. selector.push(this._stringFor('value'));
  5465. selector.push(this._stringFor('insensitiveFlag', 'insensitive', function (attrValue, attrSpaces) {
  5466. if (attrValue.length > 0 && !_this2.quoted && attrSpaces.before.length === 0 && !(_this2.spaces.value && _this2.spaces.value.after)) {
  5467. attrSpaces.before = " ";
  5468. }
  5469. return defaultAttrConcat(attrValue, attrSpaces);
  5470. }));
  5471. }
  5472. selector.push(']');
  5473. selector.push(this.rawSpaceAfter);
  5474. return selector.join('');
  5475. };
  5476. _createClass(Attribute, [{
  5477. key: "quoted",
  5478. get: function get() {
  5479. var qm = this.quoteMark;
  5480. return qm === "'" || qm === '"';
  5481. },
  5482. set: function set(value) {
  5483. warnOfDeprecatedQuotedAssignment();
  5484. }
  5485. /**
  5486. * returns a single (`'`) or double (`"`) quote character if the value is quoted.
  5487. * returns `null` if the value is not quoted.
  5488. * returns `undefined` if the quotation state is unknown (this can happen when
  5489. * the attribute is constructed without specifying a quote mark.)
  5490. */
  5491. }, {
  5492. key: "quoteMark",
  5493. get: function get() {
  5494. return this._quoteMark;
  5495. }
  5496. /**
  5497. * Set the quote mark to be used by this attribute's value.
  5498. * If the quote mark changes, the raw (escaped) value at `attr.raws.value` of the attribute
  5499. * value is updated accordingly.
  5500. *
  5501. * @param {"'" | '"' | null} quoteMark The quote mark or `null` if the value should be unquoted.
  5502. */,
  5503. set: function set(quoteMark) {
  5504. if (!this._constructed) {
  5505. this._quoteMark = quoteMark;
  5506. return;
  5507. }
  5508. if (this._quoteMark !== quoteMark) {
  5509. this._quoteMark = quoteMark;
  5510. this._syncRawValue();
  5511. }
  5512. }
  5513. }, {
  5514. key: "qualifiedAttribute",
  5515. get: function get() {
  5516. return this.qualifiedName(this.raws.attribute || this.attribute);
  5517. }
  5518. }, {
  5519. key: "insensitiveFlag",
  5520. get: function get() {
  5521. return this.insensitive ? 'i' : '';
  5522. }
  5523. }, {
  5524. key: "value",
  5525. get: function get() {
  5526. return this._value;
  5527. },
  5528. set:
  5529. /**
  5530. * Before 3.0, the value had to be set to an escaped value including any wrapped
  5531. * quote marks. In 3.0, the semantics of `Attribute.value` changed so that the value
  5532. * is unescaped during parsing and any quote marks are removed.
  5533. *
  5534. * Because the ambiguity of this semantic change, if you set `attr.value = newValue`,
  5535. * a deprecation warning is raised when the new value contains any characters that would
  5536. * require escaping (including if it contains wrapped quotes).
  5537. *
  5538. * Instead, you should call `attr.setValue(newValue, opts)` and pass options that describe
  5539. * how the new value is quoted.
  5540. */
  5541. function set(v) {
  5542. if (this._constructed) {
  5543. var _unescapeValue2 = unescapeValue(v),
  5544. deprecatedUsage = _unescapeValue2.deprecatedUsage,
  5545. unescaped = _unescapeValue2.unescaped,
  5546. quoteMark = _unescapeValue2.quoteMark;
  5547. if (deprecatedUsage) {
  5548. warnOfDeprecatedValueAssignment();
  5549. }
  5550. if (unescaped === this._value && quoteMark === this._quoteMark) {
  5551. return;
  5552. }
  5553. this._value = unescaped;
  5554. this._quoteMark = quoteMark;
  5555. this._syncRawValue();
  5556. } else {
  5557. this._value = v;
  5558. }
  5559. }
  5560. }, {
  5561. key: "insensitive",
  5562. get: function get() {
  5563. return this._insensitive;
  5564. }
  5565. /**
  5566. * Set the case insensitive flag.
  5567. * If the case insensitive flag changes, the raw (escaped) value at `attr.raws.insensitiveFlag`
  5568. * of the attribute is updated accordingly.
  5569. *
  5570. * @param {true | false} insensitive true if the attribute should match case-insensitively.
  5571. */,
  5572. set: function set(insensitive) {
  5573. if (!insensitive) {
  5574. this._insensitive = false;
  5575. // "i" and "I" can be used in "this.raws.insensitiveFlag" to store the original notation.
  5576. // When setting `attr.insensitive = false` both should be erased to ensure correct serialization.
  5577. if (this.raws && (this.raws.insensitiveFlag === 'I' || this.raws.insensitiveFlag === 'i')) {
  5578. this.raws.insensitiveFlag = undefined;
  5579. }
  5580. }
  5581. this._insensitive = insensitive;
  5582. }
  5583. }, {
  5584. key: "attribute",
  5585. get: function get() {
  5586. return this._attribute;
  5587. },
  5588. set: function set(name) {
  5589. this._handleEscapes("attribute", name);
  5590. this._attribute = name;
  5591. }
  5592. }]);
  5593. return Attribute;
  5594. }(_namespace["default"]);
  5595. exports["default"] = Attribute;
  5596. Attribute.NO_QUOTE = null;
  5597. Attribute.SINGLE_QUOTE = "'";
  5598. Attribute.DOUBLE_QUOTE = '"';
  5599. var CSSESC_QUOTE_OPTIONS = (_CSSESC_QUOTE_OPTIONS = {
  5600. "'": {
  5601. quotes: 'single',
  5602. wrap: true
  5603. },
  5604. '"': {
  5605. quotes: 'double',
  5606. wrap: true
  5607. }
  5608. }, _CSSESC_QUOTE_OPTIONS[null] = {
  5609. isIdentifier: true
  5610. }, _CSSESC_QUOTE_OPTIONS);
  5611. function defaultAttrConcat(attrValue, attrSpaces) {
  5612. return "" + attrSpaces.before + attrValue + attrSpaces.after;
  5613. }
  5614. } (attribute$1));
  5615. var universal$1 = {exports: {}};
  5616. (function (module, exports) {
  5617. exports.__esModule = true;
  5618. exports["default"] = void 0;
  5619. var _namespace = _interopRequireDefault(namespaceExports);
  5620. var _types = types$1;
  5621. function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; }
  5622. function _inheritsLoose(subClass, superClass) { subClass.prototype = Object.create(superClass.prototype); subClass.prototype.constructor = subClass; _setPrototypeOf(subClass, superClass); }
  5623. function _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf ? Object.setPrototypeOf.bind() : function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); }
  5624. var Universal = /*#__PURE__*/function (_Namespace) {
  5625. _inheritsLoose(Universal, _Namespace);
  5626. function Universal(opts) {
  5627. var _this;
  5628. _this = _Namespace.call(this, opts) || this;
  5629. _this.type = _types.UNIVERSAL;
  5630. _this.value = '*';
  5631. return _this;
  5632. }
  5633. return Universal;
  5634. }(_namespace["default"]);
  5635. exports["default"] = Universal;
  5636. module.exports = exports.default;
  5637. } (universal$1, universal$1.exports));
  5638. var universalExports = universal$1.exports;
  5639. var combinator$2 = {exports: {}};
  5640. (function (module, exports) {
  5641. exports.__esModule = true;
  5642. exports["default"] = void 0;
  5643. var _node = _interopRequireDefault(nodeExports);
  5644. var _types = types$1;
  5645. function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; }
  5646. function _inheritsLoose(subClass, superClass) { subClass.prototype = Object.create(superClass.prototype); subClass.prototype.constructor = subClass; _setPrototypeOf(subClass, superClass); }
  5647. function _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf ? Object.setPrototypeOf.bind() : function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); }
  5648. var Combinator = /*#__PURE__*/function (_Node) {
  5649. _inheritsLoose(Combinator, _Node);
  5650. function Combinator(opts) {
  5651. var _this;
  5652. _this = _Node.call(this, opts) || this;
  5653. _this.type = _types.COMBINATOR;
  5654. return _this;
  5655. }
  5656. return Combinator;
  5657. }(_node["default"]);
  5658. exports["default"] = Combinator;
  5659. module.exports = exports.default;
  5660. } (combinator$2, combinator$2.exports));
  5661. var combinatorExports = combinator$2.exports;
  5662. var nesting$1 = {exports: {}};
  5663. (function (module, exports) {
  5664. exports.__esModule = true;
  5665. exports["default"] = void 0;
  5666. var _node = _interopRequireDefault(nodeExports);
  5667. var _types = types$1;
  5668. function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; }
  5669. function _inheritsLoose(subClass, superClass) { subClass.prototype = Object.create(superClass.prototype); subClass.prototype.constructor = subClass; _setPrototypeOf(subClass, superClass); }
  5670. function _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf ? Object.setPrototypeOf.bind() : function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); }
  5671. var Nesting = /*#__PURE__*/function (_Node) {
  5672. _inheritsLoose(Nesting, _Node);
  5673. function Nesting(opts) {
  5674. var _this;
  5675. _this = _Node.call(this, opts) || this;
  5676. _this.type = _types.NESTING;
  5677. _this.value = '&';
  5678. return _this;
  5679. }
  5680. return Nesting;
  5681. }(_node["default"]);
  5682. exports["default"] = Nesting;
  5683. module.exports = exports.default;
  5684. } (nesting$1, nesting$1.exports));
  5685. var nestingExports = nesting$1.exports;
  5686. var sortAscending = {exports: {}};
  5687. (function (module, exports) {
  5688. exports.__esModule = true;
  5689. exports["default"] = sortAscending;
  5690. function sortAscending(list) {
  5691. return list.sort(function (a, b) {
  5692. return a - b;
  5693. });
  5694. }
  5695. module.exports = exports.default;
  5696. } (sortAscending, sortAscending.exports));
  5697. var sortAscendingExports = sortAscending.exports;
  5698. var tokenize = {};
  5699. var tokenTypes = {};
  5700. tokenTypes.__esModule = true;
  5701. 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;
  5702. var ampersand = 38; // `&`.charCodeAt(0);
  5703. tokenTypes.ampersand = ampersand;
  5704. var asterisk = 42; // `*`.charCodeAt(0);
  5705. tokenTypes.asterisk = asterisk;
  5706. var at = 64; // `@`.charCodeAt(0);
  5707. tokenTypes.at = at;
  5708. var comma$1 = 44; // `,`.charCodeAt(0);
  5709. tokenTypes.comma = comma$1;
  5710. var colon$1 = 58; // `:`.charCodeAt(0);
  5711. tokenTypes.colon = colon$1;
  5712. var semicolon = 59; // `;`.charCodeAt(0);
  5713. tokenTypes.semicolon = semicolon;
  5714. var openParenthesis = 40; // `(`.charCodeAt(0);
  5715. tokenTypes.openParenthesis = openParenthesis;
  5716. var closeParenthesis = 41; // `)`.charCodeAt(0);
  5717. tokenTypes.closeParenthesis = closeParenthesis;
  5718. var openSquare = 91; // `[`.charCodeAt(0);
  5719. tokenTypes.openSquare = openSquare;
  5720. var closeSquare = 93; // `]`.charCodeAt(0);
  5721. tokenTypes.closeSquare = closeSquare;
  5722. var dollar = 36; // `$`.charCodeAt(0);
  5723. tokenTypes.dollar = dollar;
  5724. var tilde = 126; // `~`.charCodeAt(0);
  5725. tokenTypes.tilde = tilde;
  5726. var caret = 94; // `^`.charCodeAt(0);
  5727. tokenTypes.caret = caret;
  5728. var plus$1 = 43; // `+`.charCodeAt(0);
  5729. tokenTypes.plus = plus$1;
  5730. var equals = 61; // `=`.charCodeAt(0);
  5731. tokenTypes.equals = equals;
  5732. var pipe = 124; // `|`.charCodeAt(0);
  5733. tokenTypes.pipe = pipe;
  5734. var greaterThan = 62; // `>`.charCodeAt(0);
  5735. tokenTypes.greaterThan = greaterThan;
  5736. var space = 32; // ` `.charCodeAt(0);
  5737. tokenTypes.space = space;
  5738. var singleQuote$1 = 39; // `'`.charCodeAt(0);
  5739. tokenTypes.singleQuote = singleQuote$1;
  5740. var doubleQuote$1 = 34; // `"`.charCodeAt(0);
  5741. tokenTypes.doubleQuote = doubleQuote$1;
  5742. var slash$1 = 47; // `/`.charCodeAt(0);
  5743. tokenTypes.slash = slash$1;
  5744. var bang = 33; // `!`.charCodeAt(0);
  5745. tokenTypes.bang = bang;
  5746. var backslash$1 = 92; // '\\'.charCodeAt(0);
  5747. tokenTypes.backslash = backslash$1;
  5748. var cr = 13; // '\r'.charCodeAt(0);
  5749. tokenTypes.cr = cr;
  5750. var feed = 12; // '\f'.charCodeAt(0);
  5751. tokenTypes.feed = feed;
  5752. var newline = 10; // '\n'.charCodeAt(0);
  5753. tokenTypes.newline = newline;
  5754. var tab = 9; // '\t'.charCodeAt(0);
  5755. // Expose aliases primarily for readability.
  5756. tokenTypes.tab = tab;
  5757. var str = singleQuote$1;
  5758. // No good single character representation!
  5759. tokenTypes.str = str;
  5760. var comment$1 = -1;
  5761. tokenTypes.comment = comment$1;
  5762. var word = -2;
  5763. tokenTypes.word = word;
  5764. var combinator$1 = -3;
  5765. tokenTypes.combinator = combinator$1;
  5766. (function (exports) {
  5767. exports.__esModule = true;
  5768. exports.FIELDS = void 0;
  5769. exports["default"] = tokenize;
  5770. var t = _interopRequireWildcard(tokenTypes);
  5771. var _unescapable, _wordDelimiters;
  5772. 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); }
  5773. function _interopRequireWildcard(obj, nodeInterop) { if (!nodeInterop && 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; }
  5774. var unescapable = (_unescapable = {}, _unescapable[t.tab] = true, _unescapable[t.newline] = true, _unescapable[t.cr] = true, _unescapable[t.feed] = true, _unescapable);
  5775. 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);
  5776. var hex = {};
  5777. var hexChars = "0123456789abcdefABCDEF";
  5778. for (var i = 0; i < hexChars.length; i++) {
  5779. hex[hexChars.charCodeAt(i)] = true;
  5780. }
  5781. /**
  5782. * Returns the last index of the bar css word
  5783. * @param {string} css The string in which the word begins
  5784. * @param {number} start The index into the string where word's first letter occurs
  5785. */
  5786. function consumeWord(css, start) {
  5787. var next = start;
  5788. var code;
  5789. do {
  5790. code = css.charCodeAt(next);
  5791. if (wordDelimiters[code]) {
  5792. return next - 1;
  5793. } else if (code === t.backslash) {
  5794. next = consumeEscape(css, next) + 1;
  5795. } else {
  5796. // All other characters are part of the word
  5797. next++;
  5798. }
  5799. } while (next < css.length);
  5800. return next - 1;
  5801. }
  5802. /**
  5803. * Returns the last index of the escape sequence
  5804. * @param {string} css The string in which the sequence begins
  5805. * @param {number} start The index into the string where escape character (`\`) occurs.
  5806. */
  5807. function consumeEscape(css, start) {
  5808. var next = start;
  5809. var code = css.charCodeAt(next + 1);
  5810. if (unescapable[code]) ; else if (hex[code]) {
  5811. var hexDigits = 0;
  5812. // consume up to 6 hex chars
  5813. do {
  5814. next++;
  5815. hexDigits++;
  5816. code = css.charCodeAt(next + 1);
  5817. } while (hex[code] && hexDigits < 6);
  5818. // if fewer than 6 hex chars, a trailing space ends the escape
  5819. if (hexDigits < 6 && code === t.space) {
  5820. next++;
  5821. }
  5822. } else {
  5823. // the next char is part of the current word
  5824. next++;
  5825. }
  5826. return next;
  5827. }
  5828. var FIELDS = {
  5829. TYPE: 0,
  5830. START_LINE: 1,
  5831. START_COL: 2,
  5832. END_LINE: 3,
  5833. END_COL: 4,
  5834. START_POS: 5,
  5835. END_POS: 6
  5836. };
  5837. exports.FIELDS = FIELDS;
  5838. function tokenize(input) {
  5839. var tokens = [];
  5840. var css = input.css.valueOf();
  5841. var _css = css,
  5842. length = _css.length;
  5843. var offset = -1;
  5844. var line = 1;
  5845. var start = 0;
  5846. var end = 0;
  5847. var code, content, endColumn, endLine, escaped, escapePos, last, lines, next, nextLine, nextOffset, quote, tokenType;
  5848. function unclosed(what, fix) {
  5849. if (input.safe) {
  5850. // fyi: this is never set to true.
  5851. css += fix;
  5852. next = css.length - 1;
  5853. } else {
  5854. throw input.error('Unclosed ' + what, line, start - offset, start);
  5855. }
  5856. }
  5857. while (start < length) {
  5858. code = css.charCodeAt(start);
  5859. if (code === t.newline) {
  5860. offset = start;
  5861. line += 1;
  5862. }
  5863. switch (code) {
  5864. case t.space:
  5865. case t.tab:
  5866. case t.newline:
  5867. case t.cr:
  5868. case t.feed:
  5869. next = start;
  5870. do {
  5871. next += 1;
  5872. code = css.charCodeAt(next);
  5873. if (code === t.newline) {
  5874. offset = next;
  5875. line += 1;
  5876. }
  5877. } while (code === t.space || code === t.newline || code === t.tab || code === t.cr || code === t.feed);
  5878. tokenType = t.space;
  5879. endLine = line;
  5880. endColumn = next - offset - 1;
  5881. end = next;
  5882. break;
  5883. case t.plus:
  5884. case t.greaterThan:
  5885. case t.tilde:
  5886. case t.pipe:
  5887. next = start;
  5888. do {
  5889. next += 1;
  5890. code = css.charCodeAt(next);
  5891. } while (code === t.plus || code === t.greaterThan || code === t.tilde || code === t.pipe);
  5892. tokenType = t.combinator;
  5893. endLine = line;
  5894. endColumn = start - offset;
  5895. end = next;
  5896. break;
  5897. // Consume these characters as single tokens.
  5898. case t.asterisk:
  5899. case t.ampersand:
  5900. case t.bang:
  5901. case t.comma:
  5902. case t.equals:
  5903. case t.dollar:
  5904. case t.caret:
  5905. case t.openSquare:
  5906. case t.closeSquare:
  5907. case t.colon:
  5908. case t.semicolon:
  5909. case t.openParenthesis:
  5910. case t.closeParenthesis:
  5911. next = start;
  5912. tokenType = code;
  5913. endLine = line;
  5914. endColumn = start - offset;
  5915. end = next + 1;
  5916. break;
  5917. case t.singleQuote:
  5918. case t.doubleQuote:
  5919. quote = code === t.singleQuote ? "'" : '"';
  5920. next = start;
  5921. do {
  5922. escaped = false;
  5923. next = css.indexOf(quote, next + 1);
  5924. if (next === -1) {
  5925. unclosed('quote', quote);
  5926. }
  5927. escapePos = next;
  5928. while (css.charCodeAt(escapePos - 1) === t.backslash) {
  5929. escapePos -= 1;
  5930. escaped = !escaped;
  5931. }
  5932. } while (escaped);
  5933. tokenType = t.str;
  5934. endLine = line;
  5935. endColumn = start - offset;
  5936. end = next + 1;
  5937. break;
  5938. default:
  5939. if (code === t.slash && css.charCodeAt(start + 1) === t.asterisk) {
  5940. next = css.indexOf('*/', start + 2) + 1;
  5941. if (next === 0) {
  5942. unclosed('comment', '*/');
  5943. }
  5944. content = css.slice(start, next + 1);
  5945. lines = content.split('\n');
  5946. last = lines.length - 1;
  5947. if (last > 0) {
  5948. nextLine = line + last;
  5949. nextOffset = next - lines[last].length;
  5950. } else {
  5951. nextLine = line;
  5952. nextOffset = offset;
  5953. }
  5954. tokenType = t.comment;
  5955. line = nextLine;
  5956. endLine = nextLine;
  5957. endColumn = next - nextOffset;
  5958. } else if (code === t.slash) {
  5959. next = start;
  5960. tokenType = code;
  5961. endLine = line;
  5962. endColumn = start - offset;
  5963. end = next + 1;
  5964. } else {
  5965. next = consumeWord(css, start);
  5966. tokenType = t.word;
  5967. endLine = line;
  5968. endColumn = next - offset;
  5969. }
  5970. end = next + 1;
  5971. break;
  5972. }
  5973. // Ensure that the token structure remains consistent
  5974. tokens.push([tokenType,
  5975. // [0] Token type
  5976. line,
  5977. // [1] Starting line
  5978. start - offset,
  5979. // [2] Starting column
  5980. endLine,
  5981. // [3] Ending line
  5982. endColumn,
  5983. // [4] Ending column
  5984. start,
  5985. // [5] Start position / Source index
  5986. end // [6] End position
  5987. ]);
  5988. // Reset offset for the next token
  5989. if (nextOffset) {
  5990. offset = nextOffset;
  5991. nextOffset = null;
  5992. }
  5993. start = end;
  5994. }
  5995. return tokens;
  5996. }
  5997. } (tokenize));
  5998. (function (module, exports) {
  5999. exports.__esModule = true;
  6000. exports["default"] = void 0;
  6001. var _root = _interopRequireDefault(rootExports);
  6002. var _selector = _interopRequireDefault(selectorExports);
  6003. var _className = _interopRequireDefault(classNameExports);
  6004. var _comment = _interopRequireDefault(commentExports);
  6005. var _id = _interopRequireDefault(idExports);
  6006. var _tag = _interopRequireDefault(tagExports);
  6007. var _string = _interopRequireDefault(stringExports);
  6008. var _pseudo = _interopRequireDefault(pseudoExports);
  6009. var _attribute = _interopRequireWildcard(attribute$1);
  6010. var _universal = _interopRequireDefault(universalExports);
  6011. var _combinator = _interopRequireDefault(combinatorExports);
  6012. var _nesting = _interopRequireDefault(nestingExports);
  6013. var _sortAscending = _interopRequireDefault(sortAscendingExports);
  6014. var _tokenize = _interopRequireWildcard(tokenize);
  6015. var tokens = _interopRequireWildcard(tokenTypes);
  6016. var types = _interopRequireWildcard(types$1);
  6017. var _util = util$6;
  6018. var _WHITESPACE_TOKENS, _Object$assign;
  6019. 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); }
  6020. function _interopRequireWildcard(obj, nodeInterop) { if (!nodeInterop && 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; }
  6021. function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; }
  6022. 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); } }
  6023. function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); Object.defineProperty(Constructor, "prototype", { writable: false }); return Constructor; }
  6024. 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);
  6025. var WHITESPACE_EQUIV_TOKENS = Object.assign({}, WHITESPACE_TOKENS, (_Object$assign = {}, _Object$assign[tokens.comment] = true, _Object$assign));
  6026. function tokenStart(token) {
  6027. return {
  6028. line: token[_tokenize.FIELDS.START_LINE],
  6029. column: token[_tokenize.FIELDS.START_COL]
  6030. };
  6031. }
  6032. function tokenEnd(token) {
  6033. return {
  6034. line: token[_tokenize.FIELDS.END_LINE],
  6035. column: token[_tokenize.FIELDS.END_COL]
  6036. };
  6037. }
  6038. function getSource(startLine, startColumn, endLine, endColumn) {
  6039. return {
  6040. start: {
  6041. line: startLine,
  6042. column: startColumn
  6043. },
  6044. end: {
  6045. line: endLine,
  6046. column: endColumn
  6047. }
  6048. };
  6049. }
  6050. function getTokenSource(token) {
  6051. return getSource(token[_tokenize.FIELDS.START_LINE], token[_tokenize.FIELDS.START_COL], token[_tokenize.FIELDS.END_LINE], token[_tokenize.FIELDS.END_COL]);
  6052. }
  6053. function getTokenSourceSpan(startToken, endToken) {
  6054. if (!startToken) {
  6055. return undefined;
  6056. }
  6057. return getSource(startToken[_tokenize.FIELDS.START_LINE], startToken[_tokenize.FIELDS.START_COL], endToken[_tokenize.FIELDS.END_LINE], endToken[_tokenize.FIELDS.END_COL]);
  6058. }
  6059. function unescapeProp(node, prop) {
  6060. var value = node[prop];
  6061. if (typeof value !== "string") {
  6062. return;
  6063. }
  6064. if (value.indexOf("\\") !== -1) {
  6065. (0, _util.ensureObject)(node, 'raws');
  6066. node[prop] = (0, _util.unesc)(value);
  6067. if (node.raws[prop] === undefined) {
  6068. node.raws[prop] = value;
  6069. }
  6070. }
  6071. return node;
  6072. }
  6073. function indexesOf(array, item) {
  6074. var i = -1;
  6075. var indexes = [];
  6076. while ((i = array.indexOf(item, i + 1)) !== -1) {
  6077. indexes.push(i);
  6078. }
  6079. return indexes;
  6080. }
  6081. function uniqs() {
  6082. var list = Array.prototype.concat.apply([], arguments);
  6083. return list.filter(function (item, i) {
  6084. return i === list.indexOf(item);
  6085. });
  6086. }
  6087. var Parser = /*#__PURE__*/function () {
  6088. function Parser(rule, options) {
  6089. if (options === void 0) {
  6090. options = {};
  6091. }
  6092. this.rule = rule;
  6093. this.options = Object.assign({
  6094. lossy: false,
  6095. safe: false
  6096. }, options);
  6097. this.position = 0;
  6098. this.css = typeof this.rule === 'string' ? this.rule : this.rule.selector;
  6099. this.tokens = (0, _tokenize["default"])({
  6100. css: this.css,
  6101. error: this._errorGenerator(),
  6102. safe: this.options.safe
  6103. });
  6104. var rootSource = getTokenSourceSpan(this.tokens[0], this.tokens[this.tokens.length - 1]);
  6105. this.root = new _root["default"]({
  6106. source: rootSource
  6107. });
  6108. this.root.errorGenerator = this._errorGenerator();
  6109. var selector = new _selector["default"]({
  6110. source: {
  6111. start: {
  6112. line: 1,
  6113. column: 1
  6114. }
  6115. }
  6116. });
  6117. this.root.append(selector);
  6118. this.current = selector;
  6119. this.loop();
  6120. }
  6121. var _proto = Parser.prototype;
  6122. _proto._errorGenerator = function _errorGenerator() {
  6123. var _this = this;
  6124. return function (message, errorOptions) {
  6125. if (typeof _this.rule === 'string') {
  6126. return new Error(message);
  6127. }
  6128. return _this.rule.error(message, errorOptions);
  6129. };
  6130. };
  6131. _proto.attribute = function attribute() {
  6132. var attr = [];
  6133. var startingToken = this.currToken;
  6134. this.position++;
  6135. while (this.position < this.tokens.length && this.currToken[_tokenize.FIELDS.TYPE] !== tokens.closeSquare) {
  6136. attr.push(this.currToken);
  6137. this.position++;
  6138. }
  6139. if (this.currToken[_tokenize.FIELDS.TYPE] !== tokens.closeSquare) {
  6140. return this.expected('closing square bracket', this.currToken[_tokenize.FIELDS.START_POS]);
  6141. }
  6142. var len = attr.length;
  6143. var node = {
  6144. source: getSource(startingToken[1], startingToken[2], this.currToken[3], this.currToken[4]),
  6145. sourceIndex: startingToken[_tokenize.FIELDS.START_POS]
  6146. };
  6147. if (len === 1 && !~[tokens.word].indexOf(attr[0][_tokenize.FIELDS.TYPE])) {
  6148. return this.expected('attribute', attr[0][_tokenize.FIELDS.START_POS]);
  6149. }
  6150. var pos = 0;
  6151. var spaceBefore = '';
  6152. var commentBefore = '';
  6153. var lastAdded = null;
  6154. var spaceAfterMeaningfulToken = false;
  6155. while (pos < len) {
  6156. var token = attr[pos];
  6157. var content = this.content(token);
  6158. var next = attr[pos + 1];
  6159. switch (token[_tokenize.FIELDS.TYPE]) {
  6160. case tokens.space:
  6161. // if (
  6162. // len === 1 ||
  6163. // pos === 0 && this.content(next) === '|'
  6164. // ) {
  6165. // return this.expected('attribute', token[TOKEN.START_POS], content);
  6166. // }
  6167. spaceAfterMeaningfulToken = true;
  6168. if (this.options.lossy) {
  6169. break;
  6170. }
  6171. if (lastAdded) {
  6172. (0, _util.ensureObject)(node, 'spaces', lastAdded);
  6173. var prevContent = node.spaces[lastAdded].after || '';
  6174. node.spaces[lastAdded].after = prevContent + content;
  6175. var existingComment = (0, _util.getProp)(node, 'raws', 'spaces', lastAdded, 'after') || null;
  6176. if (existingComment) {
  6177. node.raws.spaces[lastAdded].after = existingComment + content;
  6178. }
  6179. } else {
  6180. spaceBefore = spaceBefore + content;
  6181. commentBefore = commentBefore + content;
  6182. }
  6183. break;
  6184. case tokens.asterisk:
  6185. if (next[_tokenize.FIELDS.TYPE] === tokens.equals) {
  6186. node.operator = content;
  6187. lastAdded = 'operator';
  6188. } else if ((!node.namespace || lastAdded === "namespace" && !spaceAfterMeaningfulToken) && next) {
  6189. if (spaceBefore) {
  6190. (0, _util.ensureObject)(node, 'spaces', 'attribute');
  6191. node.spaces.attribute.before = spaceBefore;
  6192. spaceBefore = '';
  6193. }
  6194. if (commentBefore) {
  6195. (0, _util.ensureObject)(node, 'raws', 'spaces', 'attribute');
  6196. node.raws.spaces.attribute.before = spaceBefore;
  6197. commentBefore = '';
  6198. }
  6199. node.namespace = (node.namespace || "") + content;
  6200. var rawValue = (0, _util.getProp)(node, 'raws', 'namespace') || null;
  6201. if (rawValue) {
  6202. node.raws.namespace += content;
  6203. }
  6204. lastAdded = 'namespace';
  6205. }
  6206. spaceAfterMeaningfulToken = false;
  6207. break;
  6208. case tokens.dollar:
  6209. if (lastAdded === "value") {
  6210. var oldRawValue = (0, _util.getProp)(node, 'raws', 'value');
  6211. node.value += "$";
  6212. if (oldRawValue) {
  6213. node.raws.value = oldRawValue + "$";
  6214. }
  6215. break;
  6216. }
  6217. // Falls through
  6218. case tokens.caret:
  6219. if (next[_tokenize.FIELDS.TYPE] === tokens.equals) {
  6220. node.operator = content;
  6221. lastAdded = 'operator';
  6222. }
  6223. spaceAfterMeaningfulToken = false;
  6224. break;
  6225. case tokens.combinator:
  6226. if (content === '~' && next[_tokenize.FIELDS.TYPE] === tokens.equals) {
  6227. node.operator = content;
  6228. lastAdded = 'operator';
  6229. }
  6230. if (content !== '|') {
  6231. spaceAfterMeaningfulToken = false;
  6232. break;
  6233. }
  6234. if (next[_tokenize.FIELDS.TYPE] === tokens.equals) {
  6235. node.operator = content;
  6236. lastAdded = 'operator';
  6237. } else if (!node.namespace && !node.attribute) {
  6238. node.namespace = true;
  6239. }
  6240. spaceAfterMeaningfulToken = false;
  6241. break;
  6242. case tokens.word:
  6243. if (next && this.content(next) === '|' && attr[pos + 2] && attr[pos + 2][_tokenize.FIELDS.TYPE] !== tokens.equals &&
  6244. // this look-ahead probably fails with comment nodes involved.
  6245. !node.operator && !node.namespace) {
  6246. node.namespace = content;
  6247. lastAdded = 'namespace';
  6248. } else if (!node.attribute || lastAdded === "attribute" && !spaceAfterMeaningfulToken) {
  6249. if (spaceBefore) {
  6250. (0, _util.ensureObject)(node, 'spaces', 'attribute');
  6251. node.spaces.attribute.before = spaceBefore;
  6252. spaceBefore = '';
  6253. }
  6254. if (commentBefore) {
  6255. (0, _util.ensureObject)(node, 'raws', 'spaces', 'attribute');
  6256. node.raws.spaces.attribute.before = commentBefore;
  6257. commentBefore = '';
  6258. }
  6259. node.attribute = (node.attribute || "") + content;
  6260. var _rawValue = (0, _util.getProp)(node, 'raws', 'attribute') || null;
  6261. if (_rawValue) {
  6262. node.raws.attribute += content;
  6263. }
  6264. lastAdded = 'attribute';
  6265. } else if (!node.value && node.value !== "" || lastAdded === "value" && !(spaceAfterMeaningfulToken || node.quoteMark)) {
  6266. var _unescaped = (0, _util.unesc)(content);
  6267. var _oldRawValue = (0, _util.getProp)(node, 'raws', 'value') || '';
  6268. var oldValue = node.value || '';
  6269. node.value = oldValue + _unescaped;
  6270. node.quoteMark = null;
  6271. if (_unescaped !== content || _oldRawValue) {
  6272. (0, _util.ensureObject)(node, 'raws');
  6273. node.raws.value = (_oldRawValue || oldValue) + content;
  6274. }
  6275. lastAdded = 'value';
  6276. } else {
  6277. var insensitive = content === 'i' || content === "I";
  6278. if ((node.value || node.value === '') && (node.quoteMark || spaceAfterMeaningfulToken)) {
  6279. node.insensitive = insensitive;
  6280. if (!insensitive || content === "I") {
  6281. (0, _util.ensureObject)(node, 'raws');
  6282. node.raws.insensitiveFlag = content;
  6283. }
  6284. lastAdded = 'insensitive';
  6285. if (spaceBefore) {
  6286. (0, _util.ensureObject)(node, 'spaces', 'insensitive');
  6287. node.spaces.insensitive.before = spaceBefore;
  6288. spaceBefore = '';
  6289. }
  6290. if (commentBefore) {
  6291. (0, _util.ensureObject)(node, 'raws', 'spaces', 'insensitive');
  6292. node.raws.spaces.insensitive.before = commentBefore;
  6293. commentBefore = '';
  6294. }
  6295. } else if (node.value || node.value === '') {
  6296. lastAdded = 'value';
  6297. node.value += content;
  6298. if (node.raws.value) {
  6299. node.raws.value += content;
  6300. }
  6301. }
  6302. }
  6303. spaceAfterMeaningfulToken = false;
  6304. break;
  6305. case tokens.str:
  6306. if (!node.attribute || !node.operator) {
  6307. return this.error("Expected an attribute followed by an operator preceding the string.", {
  6308. index: token[_tokenize.FIELDS.START_POS]
  6309. });
  6310. }
  6311. var _unescapeValue = (0, _attribute.unescapeValue)(content),
  6312. unescaped = _unescapeValue.unescaped,
  6313. quoteMark = _unescapeValue.quoteMark;
  6314. node.value = unescaped;
  6315. node.quoteMark = quoteMark;
  6316. lastAdded = 'value';
  6317. (0, _util.ensureObject)(node, 'raws');
  6318. node.raws.value = content;
  6319. spaceAfterMeaningfulToken = false;
  6320. break;
  6321. case tokens.equals:
  6322. if (!node.attribute) {
  6323. return this.expected('attribute', token[_tokenize.FIELDS.START_POS], content);
  6324. }
  6325. if (node.value) {
  6326. return this.error('Unexpected "=" found; an operator was already defined.', {
  6327. index: token[_tokenize.FIELDS.START_POS]
  6328. });
  6329. }
  6330. node.operator = node.operator ? node.operator + content : content;
  6331. lastAdded = 'operator';
  6332. spaceAfterMeaningfulToken = false;
  6333. break;
  6334. case tokens.comment:
  6335. if (lastAdded) {
  6336. if (spaceAfterMeaningfulToken || next && next[_tokenize.FIELDS.TYPE] === tokens.space || lastAdded === 'insensitive') {
  6337. var lastComment = (0, _util.getProp)(node, 'spaces', lastAdded, 'after') || '';
  6338. var rawLastComment = (0, _util.getProp)(node, 'raws', 'spaces', lastAdded, 'after') || lastComment;
  6339. (0, _util.ensureObject)(node, 'raws', 'spaces', lastAdded);
  6340. node.raws.spaces[lastAdded].after = rawLastComment + content;
  6341. } else {
  6342. var lastValue = node[lastAdded] || '';
  6343. var rawLastValue = (0, _util.getProp)(node, 'raws', lastAdded) || lastValue;
  6344. (0, _util.ensureObject)(node, 'raws');
  6345. node.raws[lastAdded] = rawLastValue + content;
  6346. }
  6347. } else {
  6348. commentBefore = commentBefore + content;
  6349. }
  6350. break;
  6351. default:
  6352. return this.error("Unexpected \"" + content + "\" found.", {
  6353. index: token[_tokenize.FIELDS.START_POS]
  6354. });
  6355. }
  6356. pos++;
  6357. }
  6358. unescapeProp(node, "attribute");
  6359. unescapeProp(node, "namespace");
  6360. this.newNode(new _attribute["default"](node));
  6361. this.position++;
  6362. }
  6363. /**
  6364. * return a node containing meaningless garbage up to (but not including) the specified token position.
  6365. * if the token position is negative, all remaining tokens are consumed.
  6366. *
  6367. * This returns an array containing a single string node if all whitespace,
  6368. * otherwise an array of comment nodes with space before and after.
  6369. *
  6370. * These tokens are not added to the current selector, the caller can add them or use them to amend
  6371. * a previous node's space metadata.
  6372. *
  6373. * In lossy mode, this returns only comments.
  6374. */;
  6375. _proto.parseWhitespaceEquivalentTokens = function parseWhitespaceEquivalentTokens(stopPosition) {
  6376. if (stopPosition < 0) {
  6377. stopPosition = this.tokens.length;
  6378. }
  6379. var startPosition = this.position;
  6380. var nodes = [];
  6381. var space = "";
  6382. var lastComment = undefined;
  6383. do {
  6384. if (WHITESPACE_TOKENS[this.currToken[_tokenize.FIELDS.TYPE]]) {
  6385. if (!this.options.lossy) {
  6386. space += this.content();
  6387. }
  6388. } else if (this.currToken[_tokenize.FIELDS.TYPE] === tokens.comment) {
  6389. var spaces = {};
  6390. if (space) {
  6391. spaces.before = space;
  6392. space = "";
  6393. }
  6394. lastComment = new _comment["default"]({
  6395. value: this.content(),
  6396. source: getTokenSource(this.currToken),
  6397. sourceIndex: this.currToken[_tokenize.FIELDS.START_POS],
  6398. spaces: spaces
  6399. });
  6400. nodes.push(lastComment);
  6401. }
  6402. } while (++this.position < stopPosition);
  6403. if (space) {
  6404. if (lastComment) {
  6405. lastComment.spaces.after = space;
  6406. } else if (!this.options.lossy) {
  6407. var firstToken = this.tokens[startPosition];
  6408. var lastToken = this.tokens[this.position - 1];
  6409. nodes.push(new _string["default"]({
  6410. value: '',
  6411. source: getSource(firstToken[_tokenize.FIELDS.START_LINE], firstToken[_tokenize.FIELDS.START_COL], lastToken[_tokenize.FIELDS.END_LINE], lastToken[_tokenize.FIELDS.END_COL]),
  6412. sourceIndex: firstToken[_tokenize.FIELDS.START_POS],
  6413. spaces: {
  6414. before: space,
  6415. after: ''
  6416. }
  6417. }));
  6418. }
  6419. }
  6420. return nodes;
  6421. }
  6422. /**
  6423. *
  6424. * @param {*} nodes
  6425. */;
  6426. _proto.convertWhitespaceNodesToSpace = function convertWhitespaceNodesToSpace(nodes, requiredSpace) {
  6427. var _this2 = this;
  6428. if (requiredSpace === void 0) {
  6429. requiredSpace = false;
  6430. }
  6431. var space = "";
  6432. var rawSpace = "";
  6433. nodes.forEach(function (n) {
  6434. var spaceBefore = _this2.lossySpace(n.spaces.before, requiredSpace);
  6435. var rawSpaceBefore = _this2.lossySpace(n.rawSpaceBefore, requiredSpace);
  6436. space += spaceBefore + _this2.lossySpace(n.spaces.after, requiredSpace && spaceBefore.length === 0);
  6437. rawSpace += spaceBefore + n.value + _this2.lossySpace(n.rawSpaceAfter, requiredSpace && rawSpaceBefore.length === 0);
  6438. });
  6439. if (rawSpace === space) {
  6440. rawSpace = undefined;
  6441. }
  6442. var result = {
  6443. space: space,
  6444. rawSpace: rawSpace
  6445. };
  6446. return result;
  6447. };
  6448. _proto.isNamedCombinator = function isNamedCombinator(position) {
  6449. if (position === void 0) {
  6450. position = this.position;
  6451. }
  6452. 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;
  6453. };
  6454. _proto.namedCombinator = function namedCombinator() {
  6455. if (this.isNamedCombinator()) {
  6456. var nameRaw = this.content(this.tokens[this.position + 1]);
  6457. var name = (0, _util.unesc)(nameRaw).toLowerCase();
  6458. var raws = {};
  6459. if (name !== nameRaw) {
  6460. raws.value = "/" + nameRaw + "/";
  6461. }
  6462. var node = new _combinator["default"]({
  6463. value: "/" + name + "/",
  6464. 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]),
  6465. sourceIndex: this.currToken[_tokenize.FIELDS.START_POS],
  6466. raws: raws
  6467. });
  6468. this.position = this.position + 3;
  6469. return node;
  6470. } else {
  6471. this.unexpected();
  6472. }
  6473. };
  6474. _proto.combinator = function combinator() {
  6475. var _this3 = this;
  6476. if (this.content() === '|') {
  6477. return this.namespace();
  6478. }
  6479. // We need to decide between a space that's a descendant combinator and meaningless whitespace at the end of a selector.
  6480. var nextSigTokenPos = this.locateNextMeaningfulToken(this.position);
  6481. if (nextSigTokenPos < 0 || this.tokens[nextSigTokenPos][_tokenize.FIELDS.TYPE] === tokens.comma) {
  6482. var nodes = this.parseWhitespaceEquivalentTokens(nextSigTokenPos);
  6483. if (nodes.length > 0) {
  6484. var last = this.current.last;
  6485. if (last) {
  6486. var _this$convertWhitespa = this.convertWhitespaceNodesToSpace(nodes),
  6487. space = _this$convertWhitespa.space,
  6488. rawSpace = _this$convertWhitespa.rawSpace;
  6489. if (rawSpace !== undefined) {
  6490. last.rawSpaceAfter += rawSpace;
  6491. }
  6492. last.spaces.after += space;
  6493. } else {
  6494. nodes.forEach(function (n) {
  6495. return _this3.newNode(n);
  6496. });
  6497. }
  6498. }
  6499. return;
  6500. }
  6501. var firstToken = this.currToken;
  6502. var spaceOrDescendantSelectorNodes = undefined;
  6503. if (nextSigTokenPos > this.position) {
  6504. spaceOrDescendantSelectorNodes = this.parseWhitespaceEquivalentTokens(nextSigTokenPos);
  6505. }
  6506. var node;
  6507. if (this.isNamedCombinator()) {
  6508. node = this.namedCombinator();
  6509. } else if (this.currToken[_tokenize.FIELDS.TYPE] === tokens.combinator) {
  6510. node = new _combinator["default"]({
  6511. value: this.content(),
  6512. source: getTokenSource(this.currToken),
  6513. sourceIndex: this.currToken[_tokenize.FIELDS.START_POS]
  6514. });
  6515. this.position++;
  6516. } else if (WHITESPACE_TOKENS[this.currToken[_tokenize.FIELDS.TYPE]]) ; else if (!spaceOrDescendantSelectorNodes) {
  6517. this.unexpected();
  6518. }
  6519. if (node) {
  6520. if (spaceOrDescendantSelectorNodes) {
  6521. var _this$convertWhitespa2 = this.convertWhitespaceNodesToSpace(spaceOrDescendantSelectorNodes),
  6522. _space = _this$convertWhitespa2.space,
  6523. _rawSpace = _this$convertWhitespa2.rawSpace;
  6524. node.spaces.before = _space;
  6525. node.rawSpaceBefore = _rawSpace;
  6526. }
  6527. } else {
  6528. // descendant combinator
  6529. var _this$convertWhitespa3 = this.convertWhitespaceNodesToSpace(spaceOrDescendantSelectorNodes, true),
  6530. _space2 = _this$convertWhitespa3.space,
  6531. _rawSpace2 = _this$convertWhitespa3.rawSpace;
  6532. if (!_rawSpace2) {
  6533. _rawSpace2 = _space2;
  6534. }
  6535. var spaces = {};
  6536. var raws = {
  6537. spaces: {}
  6538. };
  6539. if (_space2.endsWith(' ') && _rawSpace2.endsWith(' ')) {
  6540. spaces.before = _space2.slice(0, _space2.length - 1);
  6541. raws.spaces.before = _rawSpace2.slice(0, _rawSpace2.length - 1);
  6542. } else if (_space2.startsWith(' ') && _rawSpace2.startsWith(' ')) {
  6543. spaces.after = _space2.slice(1);
  6544. raws.spaces.after = _rawSpace2.slice(1);
  6545. } else {
  6546. raws.value = _rawSpace2;
  6547. }
  6548. node = new _combinator["default"]({
  6549. value: ' ',
  6550. source: getTokenSourceSpan(firstToken, this.tokens[this.position - 1]),
  6551. sourceIndex: firstToken[_tokenize.FIELDS.START_POS],
  6552. spaces: spaces,
  6553. raws: raws
  6554. });
  6555. }
  6556. if (this.currToken && this.currToken[_tokenize.FIELDS.TYPE] === tokens.space) {
  6557. node.spaces.after = this.optionalSpace(this.content());
  6558. this.position++;
  6559. }
  6560. return this.newNode(node);
  6561. };
  6562. _proto.comma = function comma() {
  6563. if (this.position === this.tokens.length - 1) {
  6564. this.root.trailingComma = true;
  6565. this.position++;
  6566. return;
  6567. }
  6568. this.current._inferEndPosition();
  6569. var selector = new _selector["default"]({
  6570. source: {
  6571. start: tokenStart(this.tokens[this.position + 1])
  6572. }
  6573. });
  6574. this.current.parent.append(selector);
  6575. this.current = selector;
  6576. this.position++;
  6577. };
  6578. _proto.comment = function comment() {
  6579. var current = this.currToken;
  6580. this.newNode(new _comment["default"]({
  6581. value: this.content(),
  6582. source: getTokenSource(current),
  6583. sourceIndex: current[_tokenize.FIELDS.START_POS]
  6584. }));
  6585. this.position++;
  6586. };
  6587. _proto.error = function error(message, opts) {
  6588. throw this.root.error(message, opts);
  6589. };
  6590. _proto.missingBackslash = function missingBackslash() {
  6591. return this.error('Expected a backslash preceding the semicolon.', {
  6592. index: this.currToken[_tokenize.FIELDS.START_POS]
  6593. });
  6594. };
  6595. _proto.missingParenthesis = function missingParenthesis() {
  6596. return this.expected('opening parenthesis', this.currToken[_tokenize.FIELDS.START_POS]);
  6597. };
  6598. _proto.missingSquareBracket = function missingSquareBracket() {
  6599. return this.expected('opening square bracket', this.currToken[_tokenize.FIELDS.START_POS]);
  6600. };
  6601. _proto.unexpected = function unexpected() {
  6602. return this.error("Unexpected '" + this.content() + "'. Escaping special characters with \\ may help.", this.currToken[_tokenize.FIELDS.START_POS]);
  6603. };
  6604. _proto.unexpectedPipe = function unexpectedPipe() {
  6605. return this.error("Unexpected '|'.", this.currToken[_tokenize.FIELDS.START_POS]);
  6606. };
  6607. _proto.namespace = function namespace() {
  6608. var before = this.prevToken && this.content(this.prevToken) || true;
  6609. if (this.nextToken[_tokenize.FIELDS.TYPE] === tokens.word) {
  6610. this.position++;
  6611. return this.word(before);
  6612. } else if (this.nextToken[_tokenize.FIELDS.TYPE] === tokens.asterisk) {
  6613. this.position++;
  6614. return this.universal(before);
  6615. }
  6616. this.unexpectedPipe();
  6617. };
  6618. _proto.nesting = function nesting() {
  6619. if (this.nextToken) {
  6620. var nextContent = this.content(this.nextToken);
  6621. if (nextContent === "|") {
  6622. this.position++;
  6623. return;
  6624. }
  6625. }
  6626. var current = this.currToken;
  6627. this.newNode(new _nesting["default"]({
  6628. value: this.content(),
  6629. source: getTokenSource(current),
  6630. sourceIndex: current[_tokenize.FIELDS.START_POS]
  6631. }));
  6632. this.position++;
  6633. };
  6634. _proto.parentheses = function parentheses() {
  6635. var last = this.current.last;
  6636. var unbalanced = 1;
  6637. this.position++;
  6638. if (last && last.type === types.PSEUDO) {
  6639. var selector = new _selector["default"]({
  6640. source: {
  6641. start: tokenStart(this.tokens[this.position - 1])
  6642. }
  6643. });
  6644. var cache = this.current;
  6645. last.append(selector);
  6646. this.current = selector;
  6647. while (this.position < this.tokens.length && unbalanced) {
  6648. if (this.currToken[_tokenize.FIELDS.TYPE] === tokens.openParenthesis) {
  6649. unbalanced++;
  6650. }
  6651. if (this.currToken[_tokenize.FIELDS.TYPE] === tokens.closeParenthesis) {
  6652. unbalanced--;
  6653. }
  6654. if (unbalanced) {
  6655. this.parse();
  6656. } else {
  6657. this.current.source.end = tokenEnd(this.currToken);
  6658. this.current.parent.source.end = tokenEnd(this.currToken);
  6659. this.position++;
  6660. }
  6661. }
  6662. this.current = cache;
  6663. } else {
  6664. // I think this case should be an error. It's used to implement a basic parse of media queries
  6665. // but I don't think it's a good idea.
  6666. var parenStart = this.currToken;
  6667. var parenValue = "(";
  6668. var parenEnd;
  6669. while (this.position < this.tokens.length && unbalanced) {
  6670. if (this.currToken[_tokenize.FIELDS.TYPE] === tokens.openParenthesis) {
  6671. unbalanced++;
  6672. }
  6673. if (this.currToken[_tokenize.FIELDS.TYPE] === tokens.closeParenthesis) {
  6674. unbalanced--;
  6675. }
  6676. parenEnd = this.currToken;
  6677. parenValue += this.parseParenthesisToken(this.currToken);
  6678. this.position++;
  6679. }
  6680. if (last) {
  6681. last.appendToPropertyAndEscape("value", parenValue, parenValue);
  6682. } else {
  6683. this.newNode(new _string["default"]({
  6684. value: parenValue,
  6685. source: getSource(parenStart[_tokenize.FIELDS.START_LINE], parenStart[_tokenize.FIELDS.START_COL], parenEnd[_tokenize.FIELDS.END_LINE], parenEnd[_tokenize.FIELDS.END_COL]),
  6686. sourceIndex: parenStart[_tokenize.FIELDS.START_POS]
  6687. }));
  6688. }
  6689. }
  6690. if (unbalanced) {
  6691. return this.expected('closing parenthesis', this.currToken[_tokenize.FIELDS.START_POS]);
  6692. }
  6693. };
  6694. _proto.pseudo = function pseudo() {
  6695. var _this4 = this;
  6696. var pseudoStr = '';
  6697. var startingToken = this.currToken;
  6698. while (this.currToken && this.currToken[_tokenize.FIELDS.TYPE] === tokens.colon) {
  6699. pseudoStr += this.content();
  6700. this.position++;
  6701. }
  6702. if (!this.currToken) {
  6703. return this.expected(['pseudo-class', 'pseudo-element'], this.position - 1);
  6704. }
  6705. if (this.currToken[_tokenize.FIELDS.TYPE] === tokens.word) {
  6706. this.splitWord(false, function (first, length) {
  6707. pseudoStr += first;
  6708. _this4.newNode(new _pseudo["default"]({
  6709. value: pseudoStr,
  6710. source: getTokenSourceSpan(startingToken, _this4.currToken),
  6711. sourceIndex: startingToken[_tokenize.FIELDS.START_POS]
  6712. }));
  6713. if (length > 1 && _this4.nextToken && _this4.nextToken[_tokenize.FIELDS.TYPE] === tokens.openParenthesis) {
  6714. _this4.error('Misplaced parenthesis.', {
  6715. index: _this4.nextToken[_tokenize.FIELDS.START_POS]
  6716. });
  6717. }
  6718. });
  6719. } else {
  6720. return this.expected(['pseudo-class', 'pseudo-element'], this.currToken[_tokenize.FIELDS.START_POS]);
  6721. }
  6722. };
  6723. _proto.space = function space() {
  6724. var content = this.content();
  6725. // Handle space before and after the selector
  6726. if (this.position === 0 || this.prevToken[_tokenize.FIELDS.TYPE] === tokens.comma || this.prevToken[_tokenize.FIELDS.TYPE] === tokens.openParenthesis || this.current.nodes.every(function (node) {
  6727. return node.type === 'comment';
  6728. })) {
  6729. this.spaces = this.optionalSpace(content);
  6730. this.position++;
  6731. } else if (this.position === this.tokens.length - 1 || this.nextToken[_tokenize.FIELDS.TYPE] === tokens.comma || this.nextToken[_tokenize.FIELDS.TYPE] === tokens.closeParenthesis) {
  6732. this.current.last.spaces.after = this.optionalSpace(content);
  6733. this.position++;
  6734. } else {
  6735. this.combinator();
  6736. }
  6737. };
  6738. _proto.string = function string() {
  6739. var current = this.currToken;
  6740. this.newNode(new _string["default"]({
  6741. value: this.content(),
  6742. source: getTokenSource(current),
  6743. sourceIndex: current[_tokenize.FIELDS.START_POS]
  6744. }));
  6745. this.position++;
  6746. };
  6747. _proto.universal = function universal(namespace) {
  6748. var nextToken = this.nextToken;
  6749. if (nextToken && this.content(nextToken) === '|') {
  6750. this.position++;
  6751. return this.namespace();
  6752. }
  6753. var current = this.currToken;
  6754. this.newNode(new _universal["default"]({
  6755. value: this.content(),
  6756. source: getTokenSource(current),
  6757. sourceIndex: current[_tokenize.FIELDS.START_POS]
  6758. }), namespace);
  6759. this.position++;
  6760. };
  6761. _proto.splitWord = function splitWord(namespace, firstCallback) {
  6762. var _this5 = this;
  6763. var nextToken = this.nextToken;
  6764. var word = this.content();
  6765. while (nextToken && ~[tokens.dollar, tokens.caret, tokens.equals, tokens.word].indexOf(nextToken[_tokenize.FIELDS.TYPE])) {
  6766. this.position++;
  6767. var current = this.content();
  6768. word += current;
  6769. if (current.lastIndexOf('\\') === current.length - 1) {
  6770. var next = this.nextToken;
  6771. if (next && next[_tokenize.FIELDS.TYPE] === tokens.space) {
  6772. word += this.requiredSpace(this.content(next));
  6773. this.position++;
  6774. }
  6775. }
  6776. nextToken = this.nextToken;
  6777. }
  6778. var hasClass = indexesOf(word, '.').filter(function (i) {
  6779. // Allow escaped dot within class name
  6780. var escapedDot = word[i - 1] === '\\';
  6781. // Allow decimal numbers percent in @keyframes
  6782. var isKeyframesPercent = /^\d+\.\d+%$/.test(word);
  6783. return !escapedDot && !isKeyframesPercent;
  6784. });
  6785. var hasId = indexesOf(word, '#').filter(function (i) {
  6786. return word[i - 1] !== '\\';
  6787. });
  6788. // Eliminate Sass interpolations from the list of id indexes
  6789. var interpolations = indexesOf(word, '#{');
  6790. if (interpolations.length) {
  6791. hasId = hasId.filter(function (hashIndex) {
  6792. return !~interpolations.indexOf(hashIndex);
  6793. });
  6794. }
  6795. var indices = (0, _sortAscending["default"])(uniqs([0].concat(hasClass, hasId)));
  6796. indices.forEach(function (ind, i) {
  6797. var index = indices[i + 1] || word.length;
  6798. var value = word.slice(ind, index);
  6799. if (i === 0 && firstCallback) {
  6800. return firstCallback.call(_this5, value, indices.length);
  6801. }
  6802. var node;
  6803. var current = _this5.currToken;
  6804. var sourceIndex = current[_tokenize.FIELDS.START_POS] + indices[i];
  6805. var source = getSource(current[1], current[2] + ind, current[3], current[2] + (index - 1));
  6806. if (~hasClass.indexOf(ind)) {
  6807. var classNameOpts = {
  6808. value: value.slice(1),
  6809. source: source,
  6810. sourceIndex: sourceIndex
  6811. };
  6812. node = new _className["default"](unescapeProp(classNameOpts, "value"));
  6813. } else if (~hasId.indexOf(ind)) {
  6814. var idOpts = {
  6815. value: value.slice(1),
  6816. source: source,
  6817. sourceIndex: sourceIndex
  6818. };
  6819. node = new _id["default"](unescapeProp(idOpts, "value"));
  6820. } else {
  6821. var tagOpts = {
  6822. value: value,
  6823. source: source,
  6824. sourceIndex: sourceIndex
  6825. };
  6826. unescapeProp(tagOpts, "value");
  6827. node = new _tag["default"](tagOpts);
  6828. }
  6829. _this5.newNode(node, namespace);
  6830. // Ensure that the namespace is used only once
  6831. namespace = null;
  6832. });
  6833. this.position++;
  6834. };
  6835. _proto.word = function word(namespace) {
  6836. var nextToken = this.nextToken;
  6837. if (nextToken && this.content(nextToken) === '|') {
  6838. this.position++;
  6839. return this.namespace();
  6840. }
  6841. return this.splitWord(namespace);
  6842. };
  6843. _proto.loop = function loop() {
  6844. while (this.position < this.tokens.length) {
  6845. this.parse(true);
  6846. }
  6847. this.current._inferEndPosition();
  6848. return this.root;
  6849. };
  6850. _proto.parse = function parse(throwOnParenthesis) {
  6851. switch (this.currToken[_tokenize.FIELDS.TYPE]) {
  6852. case tokens.space:
  6853. this.space();
  6854. break;
  6855. case tokens.comment:
  6856. this.comment();
  6857. break;
  6858. case tokens.openParenthesis:
  6859. this.parentheses();
  6860. break;
  6861. case tokens.closeParenthesis:
  6862. if (throwOnParenthesis) {
  6863. this.missingParenthesis();
  6864. }
  6865. break;
  6866. case tokens.openSquare:
  6867. this.attribute();
  6868. break;
  6869. case tokens.dollar:
  6870. case tokens.caret:
  6871. case tokens.equals:
  6872. case tokens.word:
  6873. this.word();
  6874. break;
  6875. case tokens.colon:
  6876. this.pseudo();
  6877. break;
  6878. case tokens.comma:
  6879. this.comma();
  6880. break;
  6881. case tokens.asterisk:
  6882. this.universal();
  6883. break;
  6884. case tokens.ampersand:
  6885. this.nesting();
  6886. break;
  6887. case tokens.slash:
  6888. case tokens.combinator:
  6889. this.combinator();
  6890. break;
  6891. case tokens.str:
  6892. this.string();
  6893. break;
  6894. // These cases throw; no break needed.
  6895. case tokens.closeSquare:
  6896. this.missingSquareBracket();
  6897. case tokens.semicolon:
  6898. this.missingBackslash();
  6899. default:
  6900. this.unexpected();
  6901. }
  6902. }
  6903. /**
  6904. * Helpers
  6905. */;
  6906. _proto.expected = function expected(description, index, found) {
  6907. if (Array.isArray(description)) {
  6908. var last = description.pop();
  6909. description = description.join(', ') + " or " + last;
  6910. }
  6911. var an = /^[aeiou]/.test(description[0]) ? 'an' : 'a';
  6912. if (!found) {
  6913. return this.error("Expected " + an + " " + description + ".", {
  6914. index: index
  6915. });
  6916. }
  6917. return this.error("Expected " + an + " " + description + ", found \"" + found + "\" instead.", {
  6918. index: index
  6919. });
  6920. };
  6921. _proto.requiredSpace = function requiredSpace(space) {
  6922. return this.options.lossy ? ' ' : space;
  6923. };
  6924. _proto.optionalSpace = function optionalSpace(space) {
  6925. return this.options.lossy ? '' : space;
  6926. };
  6927. _proto.lossySpace = function lossySpace(space, required) {
  6928. if (this.options.lossy) {
  6929. return required ? ' ' : '';
  6930. } else {
  6931. return space;
  6932. }
  6933. };
  6934. _proto.parseParenthesisToken = function parseParenthesisToken(token) {
  6935. var content = this.content(token);
  6936. if (token[_tokenize.FIELDS.TYPE] === tokens.space) {
  6937. return this.requiredSpace(content);
  6938. } else {
  6939. return content;
  6940. }
  6941. };
  6942. _proto.newNode = function newNode(node, namespace) {
  6943. if (namespace) {
  6944. if (/^ +$/.test(namespace)) {
  6945. if (!this.options.lossy) {
  6946. this.spaces = (this.spaces || '') + namespace;
  6947. }
  6948. namespace = true;
  6949. }
  6950. node.namespace = namespace;
  6951. unescapeProp(node, "namespace");
  6952. }
  6953. if (this.spaces) {
  6954. node.spaces.before = this.spaces;
  6955. this.spaces = '';
  6956. }
  6957. return this.current.append(node);
  6958. };
  6959. _proto.content = function content(token) {
  6960. if (token === void 0) {
  6961. token = this.currToken;
  6962. }
  6963. return this.css.slice(token[_tokenize.FIELDS.START_POS], token[_tokenize.FIELDS.END_POS]);
  6964. };
  6965. /**
  6966. * returns the index of the next non-whitespace, non-comment token.
  6967. * returns -1 if no meaningful token is found.
  6968. */
  6969. _proto.locateNextMeaningfulToken = function locateNextMeaningfulToken(startPosition) {
  6970. if (startPosition === void 0) {
  6971. startPosition = this.position + 1;
  6972. }
  6973. var searchPosition = startPosition;
  6974. while (searchPosition < this.tokens.length) {
  6975. if (WHITESPACE_EQUIV_TOKENS[this.tokens[searchPosition][_tokenize.FIELDS.TYPE]]) {
  6976. searchPosition++;
  6977. continue;
  6978. } else {
  6979. return searchPosition;
  6980. }
  6981. }
  6982. return -1;
  6983. };
  6984. _createClass(Parser, [{
  6985. key: "currToken",
  6986. get: function get() {
  6987. return this.tokens[this.position];
  6988. }
  6989. }, {
  6990. key: "nextToken",
  6991. get: function get() {
  6992. return this.tokens[this.position + 1];
  6993. }
  6994. }, {
  6995. key: "prevToken",
  6996. get: function get() {
  6997. return this.tokens[this.position - 1];
  6998. }
  6999. }]);
  7000. return Parser;
  7001. }();
  7002. exports["default"] = Parser;
  7003. module.exports = exports.default;
  7004. } (parser, parser.exports));
  7005. var parserExports = parser.exports;
  7006. (function (module, exports) {
  7007. exports.__esModule = true;
  7008. exports["default"] = void 0;
  7009. var _parser = _interopRequireDefault(parserExports);
  7010. function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; }
  7011. var Processor = /*#__PURE__*/function () {
  7012. function Processor(func, options) {
  7013. this.func = func || function noop() {};
  7014. this.funcRes = null;
  7015. this.options = options;
  7016. }
  7017. var _proto = Processor.prototype;
  7018. _proto._shouldUpdateSelector = function _shouldUpdateSelector(rule, options) {
  7019. if (options === void 0) {
  7020. options = {};
  7021. }
  7022. var merged = Object.assign({}, this.options, options);
  7023. if (merged.updateSelector === false) {
  7024. return false;
  7025. } else {
  7026. return typeof rule !== "string";
  7027. }
  7028. };
  7029. _proto._isLossy = function _isLossy(options) {
  7030. if (options === void 0) {
  7031. options = {};
  7032. }
  7033. var merged = Object.assign({}, this.options, options);
  7034. if (merged.lossless === false) {
  7035. return true;
  7036. } else {
  7037. return false;
  7038. }
  7039. };
  7040. _proto._root = function _root(rule, options) {
  7041. if (options === void 0) {
  7042. options = {};
  7043. }
  7044. var parser = new _parser["default"](rule, this._parseOptions(options));
  7045. return parser.root;
  7046. };
  7047. _proto._parseOptions = function _parseOptions(options) {
  7048. return {
  7049. lossy: this._isLossy(options)
  7050. };
  7051. };
  7052. _proto._run = function _run(rule, options) {
  7053. var _this = this;
  7054. if (options === void 0) {
  7055. options = {};
  7056. }
  7057. return new Promise(function (resolve, reject) {
  7058. try {
  7059. var root = _this._root(rule, options);
  7060. Promise.resolve(_this.func(root)).then(function (transform) {
  7061. var string = undefined;
  7062. if (_this._shouldUpdateSelector(rule, options)) {
  7063. string = root.toString();
  7064. rule.selector = string;
  7065. }
  7066. return {
  7067. transform: transform,
  7068. root: root,
  7069. string: string
  7070. };
  7071. }).then(resolve, reject);
  7072. } catch (e) {
  7073. reject(e);
  7074. return;
  7075. }
  7076. });
  7077. };
  7078. _proto._runSync = function _runSync(rule, options) {
  7079. if (options === void 0) {
  7080. options = {};
  7081. }
  7082. var root = this._root(rule, options);
  7083. var transform = this.func(root);
  7084. if (transform && typeof transform.then === "function") {
  7085. throw new Error("Selector processor returned a promise to a synchronous call.");
  7086. }
  7087. var string = undefined;
  7088. if (options.updateSelector && typeof rule !== "string") {
  7089. string = root.toString();
  7090. rule.selector = string;
  7091. }
  7092. return {
  7093. transform: transform,
  7094. root: root,
  7095. string: string
  7096. };
  7097. }
  7098. /**
  7099. * Process rule into a selector AST.
  7100. *
  7101. * @param rule {postcss.Rule | string} The css selector to be processed
  7102. * @param options The options for processing
  7103. * @returns {Promise<parser.Root>} The AST of the selector after processing it.
  7104. */;
  7105. _proto.ast = function ast(rule, options) {
  7106. return this._run(rule, options).then(function (result) {
  7107. return result.root;
  7108. });
  7109. }
  7110. /**
  7111. * Process rule into a selector AST synchronously.
  7112. *
  7113. * @param rule {postcss.Rule | string} The css selector to be processed
  7114. * @param options The options for processing
  7115. * @returns {parser.Root} The AST of the selector after processing it.
  7116. */;
  7117. _proto.astSync = function astSync(rule, options) {
  7118. return this._runSync(rule, options).root;
  7119. }
  7120. /**
  7121. * Process a selector into a transformed value asynchronously
  7122. *
  7123. * @param rule {postcss.Rule | string} The css selector to be processed
  7124. * @param options The options for processing
  7125. * @returns {Promise<any>} The value returned by the processor.
  7126. */;
  7127. _proto.transform = function transform(rule, options) {
  7128. return this._run(rule, options).then(function (result) {
  7129. return result.transform;
  7130. });
  7131. }
  7132. /**
  7133. * Process a selector into a transformed value synchronously.
  7134. *
  7135. * @param rule {postcss.Rule | string} The css selector to be processed
  7136. * @param options The options for processing
  7137. * @returns {any} The value returned by the processor.
  7138. */;
  7139. _proto.transformSync = function transformSync(rule, options) {
  7140. return this._runSync(rule, options).transform;
  7141. }
  7142. /**
  7143. * Process a selector into a new selector string asynchronously.
  7144. *
  7145. * @param rule {postcss.Rule | string} The css selector to be processed
  7146. * @param options The options for processing
  7147. * @returns {string} the selector after processing.
  7148. */;
  7149. _proto.process = function process(rule, options) {
  7150. return this._run(rule, options).then(function (result) {
  7151. return result.string || result.root.toString();
  7152. });
  7153. }
  7154. /**
  7155. * Process a selector into a new selector string synchronously.
  7156. *
  7157. * @param rule {postcss.Rule | string} The css selector to be processed
  7158. * @param options The options for processing
  7159. * @returns {string} the selector after processing.
  7160. */;
  7161. _proto.processSync = function processSync(rule, options) {
  7162. var result = this._runSync(rule, options);
  7163. return result.string || result.root.toString();
  7164. };
  7165. return Processor;
  7166. }();
  7167. exports["default"] = Processor;
  7168. module.exports = exports.default;
  7169. } (processor, processor.exports));
  7170. var processorExports = processor.exports;
  7171. var selectors = {};
  7172. var constructors = {};
  7173. constructors.__esModule = true;
  7174. 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;
  7175. var _attribute = _interopRequireDefault$4(attribute$1);
  7176. var _className = _interopRequireDefault$4(classNameExports);
  7177. var _combinator = _interopRequireDefault$4(combinatorExports);
  7178. var _comment = _interopRequireDefault$4(commentExports);
  7179. var _id = _interopRequireDefault$4(idExports);
  7180. var _nesting = _interopRequireDefault$4(nestingExports);
  7181. var _pseudo = _interopRequireDefault$4(pseudoExports);
  7182. var _root = _interopRequireDefault$4(rootExports);
  7183. var _selector = _interopRequireDefault$4(selectorExports);
  7184. var _string = _interopRequireDefault$4(stringExports);
  7185. var _tag = _interopRequireDefault$4(tagExports);
  7186. var _universal = _interopRequireDefault$4(universalExports);
  7187. function _interopRequireDefault$4(obj) { return obj && obj.__esModule ? obj : { "default": obj }; }
  7188. var attribute = function attribute(opts) {
  7189. return new _attribute["default"](opts);
  7190. };
  7191. constructors.attribute = attribute;
  7192. var className = function className(opts) {
  7193. return new _className["default"](opts);
  7194. };
  7195. constructors.className = className;
  7196. var combinator = function combinator(opts) {
  7197. return new _combinator["default"](opts);
  7198. };
  7199. constructors.combinator = combinator;
  7200. var comment = function comment(opts) {
  7201. return new _comment["default"](opts);
  7202. };
  7203. constructors.comment = comment;
  7204. var id = function id(opts) {
  7205. return new _id["default"](opts);
  7206. };
  7207. constructors.id = id;
  7208. var nesting = function nesting(opts) {
  7209. return new _nesting["default"](opts);
  7210. };
  7211. constructors.nesting = nesting;
  7212. var pseudo = function pseudo(opts) {
  7213. return new _pseudo["default"](opts);
  7214. };
  7215. constructors.pseudo = pseudo;
  7216. var root$1 = function root(opts) {
  7217. return new _root["default"](opts);
  7218. };
  7219. constructors.root = root$1;
  7220. var selector = function selector(opts) {
  7221. return new _selector["default"](opts);
  7222. };
  7223. constructors.selector = selector;
  7224. var string = function string(opts) {
  7225. return new _string["default"](opts);
  7226. };
  7227. constructors.string = string;
  7228. var tag = function tag(opts) {
  7229. return new _tag["default"](opts);
  7230. };
  7231. constructors.tag = tag;
  7232. var universal = function universal(opts) {
  7233. return new _universal["default"](opts);
  7234. };
  7235. constructors.universal = universal;
  7236. var guards = {};
  7237. guards.__esModule = true;
  7238. guards.isComment = guards.isCombinator = guards.isClassName = guards.isAttribute = void 0;
  7239. guards.isContainer = isContainer;
  7240. guards.isIdentifier = void 0;
  7241. guards.isNamespace = isNamespace;
  7242. guards.isNesting = void 0;
  7243. guards.isNode = isNode;
  7244. guards.isPseudo = void 0;
  7245. guards.isPseudoClass = isPseudoClass;
  7246. guards.isPseudoElement = isPseudoElement;
  7247. guards.isUniversal = guards.isTag = guards.isString = guards.isSelector = guards.isRoot = void 0;
  7248. var _types = types$1;
  7249. var _IS_TYPE;
  7250. 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);
  7251. function isNode(node) {
  7252. return typeof node === "object" && IS_TYPE[node.type];
  7253. }
  7254. function isNodeType(type, node) {
  7255. return isNode(node) && node.type === type;
  7256. }
  7257. var isAttribute = isNodeType.bind(null, _types.ATTRIBUTE);
  7258. guards.isAttribute = isAttribute;
  7259. var isClassName = isNodeType.bind(null, _types.CLASS);
  7260. guards.isClassName = isClassName;
  7261. var isCombinator = isNodeType.bind(null, _types.COMBINATOR);
  7262. guards.isCombinator = isCombinator;
  7263. var isComment = isNodeType.bind(null, _types.COMMENT);
  7264. guards.isComment = isComment;
  7265. var isIdentifier = isNodeType.bind(null, _types.ID);
  7266. guards.isIdentifier = isIdentifier;
  7267. var isNesting = isNodeType.bind(null, _types.NESTING);
  7268. guards.isNesting = isNesting;
  7269. var isPseudo = isNodeType.bind(null, _types.PSEUDO);
  7270. guards.isPseudo = isPseudo;
  7271. var isRoot = isNodeType.bind(null, _types.ROOT);
  7272. guards.isRoot = isRoot;
  7273. var isSelector = isNodeType.bind(null, _types.SELECTOR);
  7274. guards.isSelector = isSelector;
  7275. var isString = isNodeType.bind(null, _types.STRING);
  7276. guards.isString = isString;
  7277. var isTag = isNodeType.bind(null, _types.TAG);
  7278. guards.isTag = isTag;
  7279. var isUniversal = isNodeType.bind(null, _types.UNIVERSAL);
  7280. guards.isUniversal = isUniversal;
  7281. function isPseudoElement(node) {
  7282. 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");
  7283. }
  7284. function isPseudoClass(node) {
  7285. return isPseudo(node) && !isPseudoElement(node);
  7286. }
  7287. function isContainer(node) {
  7288. return !!(isNode(node) && node.walk);
  7289. }
  7290. function isNamespace(node) {
  7291. return isAttribute(node) || isTag(node);
  7292. }
  7293. (function (exports) {
  7294. exports.__esModule = true;
  7295. var _types = types$1;
  7296. Object.keys(_types).forEach(function (key) {
  7297. if (key === "default" || key === "__esModule") return;
  7298. if (key in exports && exports[key] === _types[key]) return;
  7299. exports[key] = _types[key];
  7300. });
  7301. var _constructors = constructors;
  7302. Object.keys(_constructors).forEach(function (key) {
  7303. if (key === "default" || key === "__esModule") return;
  7304. if (key in exports && exports[key] === _constructors[key]) return;
  7305. exports[key] = _constructors[key];
  7306. });
  7307. var _guards = guards;
  7308. Object.keys(_guards).forEach(function (key) {
  7309. if (key === "default" || key === "__esModule") return;
  7310. if (key in exports && exports[key] === _guards[key]) return;
  7311. exports[key] = _guards[key];
  7312. });
  7313. } (selectors));
  7314. (function (module, exports) {
  7315. exports.__esModule = true;
  7316. exports["default"] = void 0;
  7317. var _processor = _interopRequireDefault(processorExports);
  7318. var selectors$1 = _interopRequireWildcard(selectors);
  7319. 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); }
  7320. function _interopRequireWildcard(obj, nodeInterop) { if (!nodeInterop && 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; }
  7321. function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; }
  7322. var parser = function parser(processor) {
  7323. return new _processor["default"](processor);
  7324. };
  7325. Object.assign(parser, selectors$1);
  7326. delete parser.__esModule;
  7327. var _default = parser;
  7328. exports["default"] = _default;
  7329. module.exports = exports.default;
  7330. } (dist, dist.exports));
  7331. var distExports = dist.exports;
  7332. var selectorParser$2 = /*@__PURE__*/getDefaultExportFromCjs(distExports);
  7333. const animationNameRE = /^(-\w+-)?animation-name$/;
  7334. const animationRE = /^(-\w+-)?animation$/;
  7335. const scopedPlugin = (id = "") => {
  7336. const keyframes = /* @__PURE__ */ Object.create(null);
  7337. const shortId = id.replace(/^data-v-/, "");
  7338. return {
  7339. postcssPlugin: "vue-sfc-scoped",
  7340. Rule(rule) {
  7341. processRule(id, rule);
  7342. },
  7343. AtRule(node) {
  7344. if (/-?keyframes$/.test(node.name) && !node.params.endsWith(`-${shortId}`)) {
  7345. keyframes[node.params] = node.params = node.params + "-" + shortId;
  7346. }
  7347. },
  7348. OnceExit(root) {
  7349. if (Object.keys(keyframes).length) {
  7350. root.walkDecls((decl) => {
  7351. if (animationNameRE.test(decl.prop)) {
  7352. decl.value = decl.value.split(",").map((v) => keyframes[v.trim()] || v.trim()).join(",");
  7353. }
  7354. if (animationRE.test(decl.prop)) {
  7355. decl.value = decl.value.split(",").map((v) => {
  7356. const vals = v.trim().split(/\s+/);
  7357. const i = vals.findIndex((val) => keyframes[val]);
  7358. if (i !== -1) {
  7359. vals.splice(i, 1, keyframes[vals[i]]);
  7360. return vals.join(" ");
  7361. } else {
  7362. return v;
  7363. }
  7364. }).join(",");
  7365. }
  7366. });
  7367. }
  7368. }
  7369. };
  7370. };
  7371. const processedRules = /* @__PURE__ */ new WeakSet();
  7372. function processRule(id, rule) {
  7373. if (processedRules.has(rule) || rule.parent && rule.parent.type === "atrule" && /-?keyframes$/.test(rule.parent.name)) {
  7374. return;
  7375. }
  7376. processedRules.add(rule);
  7377. rule.selector = selectorParser$2((selectorRoot) => {
  7378. selectorRoot.each((selector) => {
  7379. rewriteSelector(id, selector, selectorRoot);
  7380. });
  7381. }).processSync(rule.selector);
  7382. }
  7383. function rewriteSelector(id, selector, selectorRoot, slotted = false) {
  7384. let node = null;
  7385. let shouldInject = true;
  7386. selector.each((n) => {
  7387. if (n.type === "combinator" && (n.value === ">>>" || n.value === "/deep/")) {
  7388. n.value = " ";
  7389. n.spaces.before = n.spaces.after = "";
  7390. warn(
  7391. `the >>> and /deep/ combinators have been deprecated. Use :deep() instead.`
  7392. );
  7393. return false;
  7394. }
  7395. if (n.type === "pseudo") {
  7396. const { value } = n;
  7397. if (value === ":deep" || value === "::v-deep") {
  7398. if (n.nodes.length) {
  7399. let last = n;
  7400. n.nodes[0].each((ss) => {
  7401. selector.insertAfter(last, ss);
  7402. last = ss;
  7403. });
  7404. const prev = selector.at(selector.index(n) - 1);
  7405. if (!prev || !isSpaceCombinator(prev)) {
  7406. selector.insertAfter(
  7407. n,
  7408. selectorParser$2.combinator({
  7409. value: " "
  7410. })
  7411. );
  7412. }
  7413. selector.removeChild(n);
  7414. } else {
  7415. warn(
  7416. `${value} usage as a combinator has been deprecated. Use :deep(<inner-selector>) instead of ${value} <inner-selector>.`
  7417. );
  7418. const prev = selector.at(selector.index(n) - 1);
  7419. if (prev && isSpaceCombinator(prev)) {
  7420. selector.removeChild(prev);
  7421. }
  7422. selector.removeChild(n);
  7423. }
  7424. return false;
  7425. }
  7426. if (value === ":slotted" || value === "::v-slotted") {
  7427. rewriteSelector(
  7428. id,
  7429. n.nodes[0],
  7430. selectorRoot,
  7431. true
  7432. /* slotted */
  7433. );
  7434. let last = n;
  7435. n.nodes[0].each((ss) => {
  7436. selector.insertAfter(last, ss);
  7437. last = ss;
  7438. });
  7439. selector.removeChild(n);
  7440. shouldInject = false;
  7441. return false;
  7442. }
  7443. if (value === ":global" || value === "::v-global") {
  7444. selectorRoot.insertAfter(selector, n.nodes[0]);
  7445. selectorRoot.removeChild(selector);
  7446. return false;
  7447. }
  7448. }
  7449. if (n.type !== "pseudo" && n.type !== "combinator" || n.type === "pseudo" && (n.value === ":is" || n.value === ":where")) {
  7450. node = n;
  7451. }
  7452. });
  7453. if (node) {
  7454. const { type, value } = node;
  7455. if (type === "pseudo" && (value === ":is" || value === ":where")) {
  7456. node.nodes.forEach(
  7457. (value2) => rewriteSelector(id, value2, selectorRoot, slotted)
  7458. );
  7459. shouldInject = false;
  7460. }
  7461. }
  7462. if (node) {
  7463. node.spaces.after = "";
  7464. } else {
  7465. selector.first.spaces.before = "";
  7466. }
  7467. if (shouldInject) {
  7468. const idToAdd = slotted ? id + "-s" : id;
  7469. selector.insertAfter(
  7470. // If node is null it means we need to inject [id] at the start
  7471. // insertAfter can handle `null` here
  7472. node,
  7473. selectorParser$2.attribute({
  7474. attribute: idToAdd,
  7475. value: idToAdd,
  7476. raws: {},
  7477. quoteMark: `"`
  7478. })
  7479. );
  7480. }
  7481. }
  7482. function isSpaceCombinator(node) {
  7483. return node.type === "combinator" && /^\s+$/.test(node.value);
  7484. }
  7485. scopedPlugin.postcss = true;
  7486. var sourceMap$1 = {};
  7487. var sourceMapGenerator = {};
  7488. var base64Vlq = {};
  7489. var base64$1 = {};
  7490. /* -*- Mode: js; js-indent-level: 2; -*- */
  7491. /*
  7492. * Copyright 2011 Mozilla Foundation and contributors
  7493. * Licensed under the New BSD license. See LICENSE or:
  7494. * http://opensource.org/licenses/BSD-3-Clause
  7495. */
  7496. var intToCharMap = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/'.split('');
  7497. /**
  7498. * Encode an integer in the range of 0 to 63 to a single base 64 digit.
  7499. */
  7500. base64$1.encode = function (number) {
  7501. if (0 <= number && number < intToCharMap.length) {
  7502. return intToCharMap[number];
  7503. }
  7504. throw new TypeError("Must be between 0 and 63: " + number);
  7505. };
  7506. /**
  7507. * Decode a single base 64 character code digit to an integer. Returns -1 on
  7508. * failure.
  7509. */
  7510. base64$1.decode = function (charCode) {
  7511. var bigA = 65; // 'A'
  7512. var bigZ = 90; // 'Z'
  7513. var littleA = 97; // 'a'
  7514. var littleZ = 122; // 'z'
  7515. var zero = 48; // '0'
  7516. var nine = 57; // '9'
  7517. var plus = 43; // '+'
  7518. var slash = 47; // '/'
  7519. var littleOffset = 26;
  7520. var numberOffset = 52;
  7521. // 0 - 25: ABCDEFGHIJKLMNOPQRSTUVWXYZ
  7522. if (bigA <= charCode && charCode <= bigZ) {
  7523. return (charCode - bigA);
  7524. }
  7525. // 26 - 51: abcdefghijklmnopqrstuvwxyz
  7526. if (littleA <= charCode && charCode <= littleZ) {
  7527. return (charCode - littleA + littleOffset);
  7528. }
  7529. // 52 - 61: 0123456789
  7530. if (zero <= charCode && charCode <= nine) {
  7531. return (charCode - zero + numberOffset);
  7532. }
  7533. // 62: +
  7534. if (charCode == plus) {
  7535. return 62;
  7536. }
  7537. // 63: /
  7538. if (charCode == slash) {
  7539. return 63;
  7540. }
  7541. // Invalid base64 digit.
  7542. return -1;
  7543. };
  7544. /* -*- Mode: js; js-indent-level: 2; -*- */
  7545. /*
  7546. * Copyright 2011 Mozilla Foundation and contributors
  7547. * Licensed under the New BSD license. See LICENSE or:
  7548. * http://opensource.org/licenses/BSD-3-Clause
  7549. *
  7550. * Based on the Base 64 VLQ implementation in Closure Compiler:
  7551. * https://code.google.com/p/closure-compiler/source/browse/trunk/src/com/google/debugging/sourcemap/Base64VLQ.java
  7552. *
  7553. * Copyright 2011 The Closure Compiler Authors. All rights reserved.
  7554. * Redistribution and use in source and binary forms, with or without
  7555. * modification, are permitted provided that the following conditions are
  7556. * met:
  7557. *
  7558. * * Redistributions of source code must retain the above copyright
  7559. * notice, this list of conditions and the following disclaimer.
  7560. * * Redistributions in binary form must reproduce the above
  7561. * copyright notice, this list of conditions and the following
  7562. * disclaimer in the documentation and/or other materials provided
  7563. * with the distribution.
  7564. * * Neither the name of Google Inc. nor the names of its
  7565. * contributors may be used to endorse or promote products derived
  7566. * from this software without specific prior written permission.
  7567. *
  7568. * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
  7569. * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
  7570. * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
  7571. * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
  7572. * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
  7573. * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
  7574. * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
  7575. * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
  7576. * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
  7577. * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
  7578. * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  7579. */
  7580. var base64 = base64$1;
  7581. // A single base 64 digit can contain 6 bits of data. For the base 64 variable
  7582. // length quantities we use in the source map spec, the first bit is the sign,
  7583. // the next four bits are the actual value, and the 6th bit is the
  7584. // continuation bit. The continuation bit tells us whether there are more
  7585. // digits in this value following this digit.
  7586. //
  7587. // Continuation
  7588. // | Sign
  7589. // | |
  7590. // V V
  7591. // 101011
  7592. var VLQ_BASE_SHIFT = 5;
  7593. // binary: 100000
  7594. var VLQ_BASE = 1 << VLQ_BASE_SHIFT;
  7595. // binary: 011111
  7596. var VLQ_BASE_MASK = VLQ_BASE - 1;
  7597. // binary: 100000
  7598. var VLQ_CONTINUATION_BIT = VLQ_BASE;
  7599. /**
  7600. * Converts from a two-complement value to a value where the sign bit is
  7601. * placed in the least significant bit. For example, as decimals:
  7602. * 1 becomes 2 (10 binary), -1 becomes 3 (11 binary)
  7603. * 2 becomes 4 (100 binary), -2 becomes 5 (101 binary)
  7604. */
  7605. function toVLQSigned(aValue) {
  7606. return aValue < 0
  7607. ? ((-aValue) << 1) + 1
  7608. : (aValue << 1) + 0;
  7609. }
  7610. /**
  7611. * Converts to a two-complement value from a value where the sign bit is
  7612. * placed in the least significant bit. For example, as decimals:
  7613. * 2 (10 binary) becomes 1, 3 (11 binary) becomes -1
  7614. * 4 (100 binary) becomes 2, 5 (101 binary) becomes -2
  7615. */
  7616. function fromVLQSigned(aValue) {
  7617. var isNegative = (aValue & 1) === 1;
  7618. var shifted = aValue >> 1;
  7619. return isNegative
  7620. ? -shifted
  7621. : shifted;
  7622. }
  7623. /**
  7624. * Returns the base 64 VLQ encoded value.
  7625. */
  7626. base64Vlq.encode = function base64VLQ_encode(aValue) {
  7627. var encoded = "";
  7628. var digit;
  7629. var vlq = toVLQSigned(aValue);
  7630. do {
  7631. digit = vlq & VLQ_BASE_MASK;
  7632. vlq >>>= VLQ_BASE_SHIFT;
  7633. if (vlq > 0) {
  7634. // There are still more digits in this value, so we must make sure the
  7635. // continuation bit is marked.
  7636. digit |= VLQ_CONTINUATION_BIT;
  7637. }
  7638. encoded += base64.encode(digit);
  7639. } while (vlq > 0);
  7640. return encoded;
  7641. };
  7642. /**
  7643. * Decodes the next base 64 VLQ value from the given string and returns the
  7644. * value and the rest of the string via the out parameter.
  7645. */
  7646. base64Vlq.decode = function base64VLQ_decode(aStr, aIndex, aOutParam) {
  7647. var strLen = aStr.length;
  7648. var result = 0;
  7649. var shift = 0;
  7650. var continuation, digit;
  7651. do {
  7652. if (aIndex >= strLen) {
  7653. throw new Error("Expected more digits in base 64 VLQ value.");
  7654. }
  7655. digit = base64.decode(aStr.charCodeAt(aIndex++));
  7656. if (digit === -1) {
  7657. throw new Error("Invalid base64 digit: " + aStr.charAt(aIndex - 1));
  7658. }
  7659. continuation = !!(digit & VLQ_CONTINUATION_BIT);
  7660. digit &= VLQ_BASE_MASK;
  7661. result = result + (digit << shift);
  7662. shift += VLQ_BASE_SHIFT;
  7663. } while (continuation);
  7664. aOutParam.value = fromVLQSigned(result);
  7665. aOutParam.rest = aIndex;
  7666. };
  7667. var util$5 = {};
  7668. /* -*- Mode: js; js-indent-level: 2; -*- */
  7669. (function (exports) {
  7670. /*
  7671. * Copyright 2011 Mozilla Foundation and contributors
  7672. * Licensed under the New BSD license. See LICENSE or:
  7673. * http://opensource.org/licenses/BSD-3-Clause
  7674. */
  7675. /**
  7676. * This is a helper function for getting values from parameter/options
  7677. * objects.
  7678. *
  7679. * @param args The object we are extracting values from
  7680. * @param name The name of the property we are getting.
  7681. * @param defaultValue An optional value to return if the property is missing
  7682. * from the object. If this is not specified and the property is missing, an
  7683. * error will be thrown.
  7684. */
  7685. function getArg(aArgs, aName, aDefaultValue) {
  7686. if (aName in aArgs) {
  7687. return aArgs[aName];
  7688. } else if (arguments.length === 3) {
  7689. return aDefaultValue;
  7690. } else {
  7691. throw new Error('"' + aName + '" is a required argument.');
  7692. }
  7693. }
  7694. exports.getArg = getArg;
  7695. var urlRegexp = /^(?:([\w+\-.]+):)?\/\/(?:(\w+:\w+)@)?([\w.-]*)(?::(\d+))?(.*)$/;
  7696. var dataUrlRegexp = /^data:.+\,.+$/;
  7697. function urlParse(aUrl) {
  7698. var match = aUrl.match(urlRegexp);
  7699. if (!match) {
  7700. return null;
  7701. }
  7702. return {
  7703. scheme: match[1],
  7704. auth: match[2],
  7705. host: match[3],
  7706. port: match[4],
  7707. path: match[5]
  7708. };
  7709. }
  7710. exports.urlParse = urlParse;
  7711. function urlGenerate(aParsedUrl) {
  7712. var url = '';
  7713. if (aParsedUrl.scheme) {
  7714. url += aParsedUrl.scheme + ':';
  7715. }
  7716. url += '//';
  7717. if (aParsedUrl.auth) {
  7718. url += aParsedUrl.auth + '@';
  7719. }
  7720. if (aParsedUrl.host) {
  7721. url += aParsedUrl.host;
  7722. }
  7723. if (aParsedUrl.port) {
  7724. url += ":" + aParsedUrl.port;
  7725. }
  7726. if (aParsedUrl.path) {
  7727. url += aParsedUrl.path;
  7728. }
  7729. return url;
  7730. }
  7731. exports.urlGenerate = urlGenerate;
  7732. /**
  7733. * Normalizes a path, or the path portion of a URL:
  7734. *
  7735. * - Replaces consecutive slashes with one slash.
  7736. * - Removes unnecessary '.' parts.
  7737. * - Removes unnecessary '<dir>/..' parts.
  7738. *
  7739. * Based on code in the Node.js 'path' core module.
  7740. *
  7741. * @param aPath The path or url to normalize.
  7742. */
  7743. function normalize(aPath) {
  7744. var path = aPath;
  7745. var url = urlParse(aPath);
  7746. if (url) {
  7747. if (!url.path) {
  7748. return aPath;
  7749. }
  7750. path = url.path;
  7751. }
  7752. var isAbsolute = exports.isAbsolute(path);
  7753. var parts = path.split(/\/+/);
  7754. for (var part, up = 0, i = parts.length - 1; i >= 0; i--) {
  7755. part = parts[i];
  7756. if (part === '.') {
  7757. parts.splice(i, 1);
  7758. } else if (part === '..') {
  7759. up++;
  7760. } else if (up > 0) {
  7761. if (part === '') {
  7762. // The first part is blank if the path is absolute. Trying to go
  7763. // above the root is a no-op. Therefore we can remove all '..' parts
  7764. // directly after the root.
  7765. parts.splice(i + 1, up);
  7766. up = 0;
  7767. } else {
  7768. parts.splice(i, 2);
  7769. up--;
  7770. }
  7771. }
  7772. }
  7773. path = parts.join('/');
  7774. if (path === '') {
  7775. path = isAbsolute ? '/' : '.';
  7776. }
  7777. if (url) {
  7778. url.path = path;
  7779. return urlGenerate(url);
  7780. }
  7781. return path;
  7782. }
  7783. exports.normalize = normalize;
  7784. /**
  7785. * Joins two paths/URLs.
  7786. *
  7787. * @param aRoot The root path or URL.
  7788. * @param aPath The path or URL to be joined with the root.
  7789. *
  7790. * - If aPath is a URL or a data URI, aPath is returned, unless aPath is a
  7791. * scheme-relative URL: Then the scheme of aRoot, if any, is prepended
  7792. * first.
  7793. * - Otherwise aPath is a path. If aRoot is a URL, then its path portion
  7794. * is updated with the result and aRoot is returned. Otherwise the result
  7795. * is returned.
  7796. * - If aPath is absolute, the result is aPath.
  7797. * - Otherwise the two paths are joined with a slash.
  7798. * - Joining for example 'http://' and 'www.example.com' is also supported.
  7799. */
  7800. function join(aRoot, aPath) {
  7801. if (aRoot === "") {
  7802. aRoot = ".";
  7803. }
  7804. if (aPath === "") {
  7805. aPath = ".";
  7806. }
  7807. var aPathUrl = urlParse(aPath);
  7808. var aRootUrl = urlParse(aRoot);
  7809. if (aRootUrl) {
  7810. aRoot = aRootUrl.path || '/';
  7811. }
  7812. // `join(foo, '//www.example.org')`
  7813. if (aPathUrl && !aPathUrl.scheme) {
  7814. if (aRootUrl) {
  7815. aPathUrl.scheme = aRootUrl.scheme;
  7816. }
  7817. return urlGenerate(aPathUrl);
  7818. }
  7819. if (aPathUrl || aPath.match(dataUrlRegexp)) {
  7820. return aPath;
  7821. }
  7822. // `join('http://', 'www.example.com')`
  7823. if (aRootUrl && !aRootUrl.host && !aRootUrl.path) {
  7824. aRootUrl.host = aPath;
  7825. return urlGenerate(aRootUrl);
  7826. }
  7827. var joined = aPath.charAt(0) === '/'
  7828. ? aPath
  7829. : normalize(aRoot.replace(/\/+$/, '') + '/' + aPath);
  7830. if (aRootUrl) {
  7831. aRootUrl.path = joined;
  7832. return urlGenerate(aRootUrl);
  7833. }
  7834. return joined;
  7835. }
  7836. exports.join = join;
  7837. exports.isAbsolute = function (aPath) {
  7838. return aPath.charAt(0) === '/' || urlRegexp.test(aPath);
  7839. };
  7840. /**
  7841. * Make a path relative to a URL or another path.
  7842. *
  7843. * @param aRoot The root path or URL.
  7844. * @param aPath The path or URL to be made relative to aRoot.
  7845. */
  7846. function relative(aRoot, aPath) {
  7847. if (aRoot === "") {
  7848. aRoot = ".";
  7849. }
  7850. aRoot = aRoot.replace(/\/$/, '');
  7851. // It is possible for the path to be above the root. In this case, simply
  7852. // checking whether the root is a prefix of the path won't work. Instead, we
  7853. // need to remove components from the root one by one, until either we find
  7854. // a prefix that fits, or we run out of components to remove.
  7855. var level = 0;
  7856. while (aPath.indexOf(aRoot + '/') !== 0) {
  7857. var index = aRoot.lastIndexOf("/");
  7858. if (index < 0) {
  7859. return aPath;
  7860. }
  7861. // If the only part of the root that is left is the scheme (i.e. http://,
  7862. // file:///, etc.), one or more slashes (/), or simply nothing at all, we
  7863. // have exhausted all components, so the path is not relative to the root.
  7864. aRoot = aRoot.slice(0, index);
  7865. if (aRoot.match(/^([^\/]+:\/)?\/*$/)) {
  7866. return aPath;
  7867. }
  7868. ++level;
  7869. }
  7870. // Make sure we add a "../" for each component we removed from the root.
  7871. return Array(level + 1).join("../") + aPath.substr(aRoot.length + 1);
  7872. }
  7873. exports.relative = relative;
  7874. var supportsNullProto = (function () {
  7875. var obj = Object.create(null);
  7876. return !('__proto__' in obj);
  7877. }());
  7878. function identity (s) {
  7879. return s;
  7880. }
  7881. /**
  7882. * Because behavior goes wacky when you set `__proto__` on objects, we
  7883. * have to prefix all the strings in our set with an arbitrary character.
  7884. *
  7885. * See https://github.com/mozilla/source-map/pull/31 and
  7886. * https://github.com/mozilla/source-map/issues/30
  7887. *
  7888. * @param String aStr
  7889. */
  7890. function toSetString(aStr) {
  7891. if (isProtoString(aStr)) {
  7892. return '$' + aStr;
  7893. }
  7894. return aStr;
  7895. }
  7896. exports.toSetString = supportsNullProto ? identity : toSetString;
  7897. function fromSetString(aStr) {
  7898. if (isProtoString(aStr)) {
  7899. return aStr.slice(1);
  7900. }
  7901. return aStr;
  7902. }
  7903. exports.fromSetString = supportsNullProto ? identity : fromSetString;
  7904. function isProtoString(s) {
  7905. if (!s) {
  7906. return false;
  7907. }
  7908. var length = s.length;
  7909. if (length < 9 /* "__proto__".length */) {
  7910. return false;
  7911. }
  7912. if (s.charCodeAt(length - 1) !== 95 /* '_' */ ||
  7913. s.charCodeAt(length - 2) !== 95 /* '_' */ ||
  7914. s.charCodeAt(length - 3) !== 111 /* 'o' */ ||
  7915. s.charCodeAt(length - 4) !== 116 /* 't' */ ||
  7916. s.charCodeAt(length - 5) !== 111 /* 'o' */ ||
  7917. s.charCodeAt(length - 6) !== 114 /* 'r' */ ||
  7918. s.charCodeAt(length - 7) !== 112 /* 'p' */ ||
  7919. s.charCodeAt(length - 8) !== 95 /* '_' */ ||
  7920. s.charCodeAt(length - 9) !== 95 /* '_' */) {
  7921. return false;
  7922. }
  7923. for (var i = length - 10; i >= 0; i--) {
  7924. if (s.charCodeAt(i) !== 36 /* '$' */) {
  7925. return false;
  7926. }
  7927. }
  7928. return true;
  7929. }
  7930. /**
  7931. * Comparator between two mappings where the original positions are compared.
  7932. *
  7933. * Optionally pass in `true` as `onlyCompareGenerated` to consider two
  7934. * mappings with the same original source/line/column, but different generated
  7935. * line and column the same. Useful when searching for a mapping with a
  7936. * stubbed out mapping.
  7937. */
  7938. function compareByOriginalPositions(mappingA, mappingB, onlyCompareOriginal) {
  7939. var cmp = strcmp(mappingA.source, mappingB.source);
  7940. if (cmp !== 0) {
  7941. return cmp;
  7942. }
  7943. cmp = mappingA.originalLine - mappingB.originalLine;
  7944. if (cmp !== 0) {
  7945. return cmp;
  7946. }
  7947. cmp = mappingA.originalColumn - mappingB.originalColumn;
  7948. if (cmp !== 0 || onlyCompareOriginal) {
  7949. return cmp;
  7950. }
  7951. cmp = mappingA.generatedColumn - mappingB.generatedColumn;
  7952. if (cmp !== 0) {
  7953. return cmp;
  7954. }
  7955. cmp = mappingA.generatedLine - mappingB.generatedLine;
  7956. if (cmp !== 0) {
  7957. return cmp;
  7958. }
  7959. return strcmp(mappingA.name, mappingB.name);
  7960. }
  7961. exports.compareByOriginalPositions = compareByOriginalPositions;
  7962. /**
  7963. * Comparator between two mappings with deflated source and name indices where
  7964. * the generated positions are compared.
  7965. *
  7966. * Optionally pass in `true` as `onlyCompareGenerated` to consider two
  7967. * mappings with the same generated line and column, but different
  7968. * source/name/original line and column the same. Useful when searching for a
  7969. * mapping with a stubbed out mapping.
  7970. */
  7971. function compareByGeneratedPositionsDeflated(mappingA, mappingB, onlyCompareGenerated) {
  7972. var cmp = mappingA.generatedLine - mappingB.generatedLine;
  7973. if (cmp !== 0) {
  7974. return cmp;
  7975. }
  7976. cmp = mappingA.generatedColumn - mappingB.generatedColumn;
  7977. if (cmp !== 0 || onlyCompareGenerated) {
  7978. return cmp;
  7979. }
  7980. cmp = strcmp(mappingA.source, mappingB.source);
  7981. if (cmp !== 0) {
  7982. return cmp;
  7983. }
  7984. cmp = mappingA.originalLine - mappingB.originalLine;
  7985. if (cmp !== 0) {
  7986. return cmp;
  7987. }
  7988. cmp = mappingA.originalColumn - mappingB.originalColumn;
  7989. if (cmp !== 0) {
  7990. return cmp;
  7991. }
  7992. return strcmp(mappingA.name, mappingB.name);
  7993. }
  7994. exports.compareByGeneratedPositionsDeflated = compareByGeneratedPositionsDeflated;
  7995. function strcmp(aStr1, aStr2) {
  7996. if (aStr1 === aStr2) {
  7997. return 0;
  7998. }
  7999. if (aStr1 === null) {
  8000. return 1; // aStr2 !== null
  8001. }
  8002. if (aStr2 === null) {
  8003. return -1; // aStr1 !== null
  8004. }
  8005. if (aStr1 > aStr2) {
  8006. return 1;
  8007. }
  8008. return -1;
  8009. }
  8010. /**
  8011. * Comparator between two mappings with inflated source and name strings where
  8012. * the generated positions are compared.
  8013. */
  8014. function compareByGeneratedPositionsInflated(mappingA, mappingB) {
  8015. var cmp = mappingA.generatedLine - mappingB.generatedLine;
  8016. if (cmp !== 0) {
  8017. return cmp;
  8018. }
  8019. cmp = mappingA.generatedColumn - mappingB.generatedColumn;
  8020. if (cmp !== 0) {
  8021. return cmp;
  8022. }
  8023. cmp = strcmp(mappingA.source, mappingB.source);
  8024. if (cmp !== 0) {
  8025. return cmp;
  8026. }
  8027. cmp = mappingA.originalLine - mappingB.originalLine;
  8028. if (cmp !== 0) {
  8029. return cmp;
  8030. }
  8031. cmp = mappingA.originalColumn - mappingB.originalColumn;
  8032. if (cmp !== 0) {
  8033. return cmp;
  8034. }
  8035. return strcmp(mappingA.name, mappingB.name);
  8036. }
  8037. exports.compareByGeneratedPositionsInflated = compareByGeneratedPositionsInflated;
  8038. /**
  8039. * Strip any JSON XSSI avoidance prefix from the string (as documented
  8040. * in the source maps specification), and then parse the string as
  8041. * JSON.
  8042. */
  8043. function parseSourceMapInput(str) {
  8044. return JSON.parse(str.replace(/^\)]}'[^\n]*\n/, ''));
  8045. }
  8046. exports.parseSourceMapInput = parseSourceMapInput;
  8047. /**
  8048. * Compute the URL of a source given the the source root, the source's
  8049. * URL, and the source map's URL.
  8050. */
  8051. function computeSourceURL(sourceRoot, sourceURL, sourceMapURL) {
  8052. sourceURL = sourceURL || '';
  8053. if (sourceRoot) {
  8054. // This follows what Chrome does.
  8055. if (sourceRoot[sourceRoot.length - 1] !== '/' && sourceURL[0] !== '/') {
  8056. sourceRoot += '/';
  8057. }
  8058. // The spec says:
  8059. // Line 4: An optional source root, useful for relocating source
  8060. // files on a server or removing repeated values in the
  8061. // “sources” entry. This value is prepended to the individual
  8062. // entries in the “source” field.
  8063. sourceURL = sourceRoot + sourceURL;
  8064. }
  8065. // Historically, SourceMapConsumer did not take the sourceMapURL as
  8066. // a parameter. This mode is still somewhat supported, which is why
  8067. // this code block is conditional. However, it's preferable to pass
  8068. // the source map URL to SourceMapConsumer, so that this function
  8069. // can implement the source URL resolution algorithm as outlined in
  8070. // the spec. This block is basically the equivalent of:
  8071. // new URL(sourceURL, sourceMapURL).toString()
  8072. // ... except it avoids using URL, which wasn't available in the
  8073. // older releases of node still supported by this library.
  8074. //
  8075. // The spec says:
  8076. // If the sources are not absolute URLs after prepending of the
  8077. // “sourceRoot”, the sources are resolved relative to the
  8078. // SourceMap (like resolving script src in a html document).
  8079. if (sourceMapURL) {
  8080. var parsed = urlParse(sourceMapURL);
  8081. if (!parsed) {
  8082. throw new Error("sourceMapURL could not be parsed");
  8083. }
  8084. if (parsed.path) {
  8085. // Strip the last path component, but keep the "/".
  8086. var index = parsed.path.lastIndexOf('/');
  8087. if (index >= 0) {
  8088. parsed.path = parsed.path.substring(0, index + 1);
  8089. }
  8090. }
  8091. sourceURL = join(urlGenerate(parsed), sourceURL);
  8092. }
  8093. return normalize(sourceURL);
  8094. }
  8095. exports.computeSourceURL = computeSourceURL;
  8096. } (util$5));
  8097. var arraySet = {};
  8098. /* -*- Mode: js; js-indent-level: 2; -*- */
  8099. /*
  8100. * Copyright 2011 Mozilla Foundation and contributors
  8101. * Licensed under the New BSD license. See LICENSE or:
  8102. * http://opensource.org/licenses/BSD-3-Clause
  8103. */
  8104. var util$4 = util$5;
  8105. var has = Object.prototype.hasOwnProperty;
  8106. var hasNativeMap = typeof Map !== "undefined";
  8107. /**
  8108. * A data structure which is a combination of an array and a set. Adding a new
  8109. * member is O(1), testing for membership is O(1), and finding the index of an
  8110. * element is O(1). Removing elements from the set is not supported. Only
  8111. * strings are supported for membership.
  8112. */
  8113. function ArraySet$2() {
  8114. this._array = [];
  8115. this._set = hasNativeMap ? new Map() : Object.create(null);
  8116. }
  8117. /**
  8118. * Static method for creating ArraySet instances from an existing array.
  8119. */
  8120. ArraySet$2.fromArray = function ArraySet_fromArray(aArray, aAllowDuplicates) {
  8121. var set = new ArraySet$2();
  8122. for (var i = 0, len = aArray.length; i < len; i++) {
  8123. set.add(aArray[i], aAllowDuplicates);
  8124. }
  8125. return set;
  8126. };
  8127. /**
  8128. * Return how many unique items are in this ArraySet. If duplicates have been
  8129. * added, than those do not count towards the size.
  8130. *
  8131. * @returns Number
  8132. */
  8133. ArraySet$2.prototype.size = function ArraySet_size() {
  8134. return hasNativeMap ? this._set.size : Object.getOwnPropertyNames(this._set).length;
  8135. };
  8136. /**
  8137. * Add the given string to this set.
  8138. *
  8139. * @param String aStr
  8140. */
  8141. ArraySet$2.prototype.add = function ArraySet_add(aStr, aAllowDuplicates) {
  8142. var sStr = hasNativeMap ? aStr : util$4.toSetString(aStr);
  8143. var isDuplicate = hasNativeMap ? this.has(aStr) : has.call(this._set, sStr);
  8144. var idx = this._array.length;
  8145. if (!isDuplicate || aAllowDuplicates) {
  8146. this._array.push(aStr);
  8147. }
  8148. if (!isDuplicate) {
  8149. if (hasNativeMap) {
  8150. this._set.set(aStr, idx);
  8151. } else {
  8152. this._set[sStr] = idx;
  8153. }
  8154. }
  8155. };
  8156. /**
  8157. * Is the given string a member of this set?
  8158. *
  8159. * @param String aStr
  8160. */
  8161. ArraySet$2.prototype.has = function ArraySet_has(aStr) {
  8162. if (hasNativeMap) {
  8163. return this._set.has(aStr);
  8164. } else {
  8165. var sStr = util$4.toSetString(aStr);
  8166. return has.call(this._set, sStr);
  8167. }
  8168. };
  8169. /**
  8170. * What is the index of the given string in the array?
  8171. *
  8172. * @param String aStr
  8173. */
  8174. ArraySet$2.prototype.indexOf = function ArraySet_indexOf(aStr) {
  8175. if (hasNativeMap) {
  8176. var idx = this._set.get(aStr);
  8177. if (idx >= 0) {
  8178. return idx;
  8179. }
  8180. } else {
  8181. var sStr = util$4.toSetString(aStr);
  8182. if (has.call(this._set, sStr)) {
  8183. return this._set[sStr];
  8184. }
  8185. }
  8186. throw new Error('"' + aStr + '" is not in the set.');
  8187. };
  8188. /**
  8189. * What is the element at the given index?
  8190. *
  8191. * @param Number aIdx
  8192. */
  8193. ArraySet$2.prototype.at = function ArraySet_at(aIdx) {
  8194. if (aIdx >= 0 && aIdx < this._array.length) {
  8195. return this._array[aIdx];
  8196. }
  8197. throw new Error('No element indexed by ' + aIdx);
  8198. };
  8199. /**
  8200. * Returns the array representation of this set (which has the proper indices
  8201. * indicated by indexOf). Note that this is a copy of the internal array used
  8202. * for storing the members so that no one can mess with internal state.
  8203. */
  8204. ArraySet$2.prototype.toArray = function ArraySet_toArray() {
  8205. return this._array.slice();
  8206. };
  8207. arraySet.ArraySet = ArraySet$2;
  8208. var mappingList = {};
  8209. /* -*- Mode: js; js-indent-level: 2; -*- */
  8210. /*
  8211. * Copyright 2014 Mozilla Foundation and contributors
  8212. * Licensed under the New BSD license. See LICENSE or:
  8213. * http://opensource.org/licenses/BSD-3-Clause
  8214. */
  8215. var util$3 = util$5;
  8216. /**
  8217. * Determine whether mappingB is after mappingA with respect to generated
  8218. * position.
  8219. */
  8220. function generatedPositionAfter(mappingA, mappingB) {
  8221. // Optimized for most common case
  8222. var lineA = mappingA.generatedLine;
  8223. var lineB = mappingB.generatedLine;
  8224. var columnA = mappingA.generatedColumn;
  8225. var columnB = mappingB.generatedColumn;
  8226. return lineB > lineA || lineB == lineA && columnB >= columnA ||
  8227. util$3.compareByGeneratedPositionsInflated(mappingA, mappingB) <= 0;
  8228. }
  8229. /**
  8230. * A data structure to provide a sorted view of accumulated mappings in a
  8231. * performance conscious manner. It trades a neglibable overhead in general
  8232. * case for a large speedup in case of mappings being added in order.
  8233. */
  8234. function MappingList$1() {
  8235. this._array = [];
  8236. this._sorted = true;
  8237. // Serves as infimum
  8238. this._last = {generatedLine: -1, generatedColumn: 0};
  8239. }
  8240. /**
  8241. * Iterate through internal items. This method takes the same arguments that
  8242. * `Array.prototype.forEach` takes.
  8243. *
  8244. * NOTE: The order of the mappings is NOT guaranteed.
  8245. */
  8246. MappingList$1.prototype.unsortedForEach =
  8247. function MappingList_forEach(aCallback, aThisArg) {
  8248. this._array.forEach(aCallback, aThisArg);
  8249. };
  8250. /**
  8251. * Add the given source mapping.
  8252. *
  8253. * @param Object aMapping
  8254. */
  8255. MappingList$1.prototype.add = function MappingList_add(aMapping) {
  8256. if (generatedPositionAfter(this._last, aMapping)) {
  8257. this._last = aMapping;
  8258. this._array.push(aMapping);
  8259. } else {
  8260. this._sorted = false;
  8261. this._array.push(aMapping);
  8262. }
  8263. };
  8264. /**
  8265. * Returns the flat, sorted array of mappings. The mappings are sorted by
  8266. * generated position.
  8267. *
  8268. * WARNING: This method returns internal data without copying, for
  8269. * performance. The return value must NOT be mutated, and should be treated as
  8270. * an immutable borrow. If you want to take ownership, you must make your own
  8271. * copy.
  8272. */
  8273. MappingList$1.prototype.toArray = function MappingList_toArray() {
  8274. if (!this._sorted) {
  8275. this._array.sort(util$3.compareByGeneratedPositionsInflated);
  8276. this._sorted = true;
  8277. }
  8278. return this._array;
  8279. };
  8280. mappingList.MappingList = MappingList$1;
  8281. /* -*- Mode: js; js-indent-level: 2; -*- */
  8282. /*
  8283. * Copyright 2011 Mozilla Foundation and contributors
  8284. * Licensed under the New BSD license. See LICENSE or:
  8285. * http://opensource.org/licenses/BSD-3-Clause
  8286. */
  8287. var base64VLQ$1 = base64Vlq;
  8288. var util$2 = util$5;
  8289. var ArraySet$1 = arraySet.ArraySet;
  8290. var MappingList = mappingList.MappingList;
  8291. /**
  8292. * An instance of the SourceMapGenerator represents a source map which is
  8293. * being built incrementally. You may pass an object with the following
  8294. * properties:
  8295. *
  8296. * - file: The filename of the generated source.
  8297. * - sourceRoot: A root for all relative URLs in this source map.
  8298. */
  8299. function SourceMapGenerator$2(aArgs) {
  8300. if (!aArgs) {
  8301. aArgs = {};
  8302. }
  8303. this._file = util$2.getArg(aArgs, 'file', null);
  8304. this._sourceRoot = util$2.getArg(aArgs, 'sourceRoot', null);
  8305. this._skipValidation = util$2.getArg(aArgs, 'skipValidation', false);
  8306. this._sources = new ArraySet$1();
  8307. this._names = new ArraySet$1();
  8308. this._mappings = new MappingList();
  8309. this._sourcesContents = null;
  8310. }
  8311. SourceMapGenerator$2.prototype._version = 3;
  8312. /**
  8313. * Creates a new SourceMapGenerator based on a SourceMapConsumer
  8314. *
  8315. * @param aSourceMapConsumer The SourceMap.
  8316. */
  8317. SourceMapGenerator$2.fromSourceMap =
  8318. function SourceMapGenerator_fromSourceMap(aSourceMapConsumer) {
  8319. var sourceRoot = aSourceMapConsumer.sourceRoot;
  8320. var generator = new SourceMapGenerator$2({
  8321. file: aSourceMapConsumer.file,
  8322. sourceRoot: sourceRoot
  8323. });
  8324. aSourceMapConsumer.eachMapping(function (mapping) {
  8325. var newMapping = {
  8326. generated: {
  8327. line: mapping.generatedLine,
  8328. column: mapping.generatedColumn
  8329. }
  8330. };
  8331. if (mapping.source != null) {
  8332. newMapping.source = mapping.source;
  8333. if (sourceRoot != null) {
  8334. newMapping.source = util$2.relative(sourceRoot, newMapping.source);
  8335. }
  8336. newMapping.original = {
  8337. line: mapping.originalLine,
  8338. column: mapping.originalColumn
  8339. };
  8340. if (mapping.name != null) {
  8341. newMapping.name = mapping.name;
  8342. }
  8343. }
  8344. generator.addMapping(newMapping);
  8345. });
  8346. aSourceMapConsumer.sources.forEach(function (sourceFile) {
  8347. var sourceRelative = sourceFile;
  8348. if (sourceRoot !== null) {
  8349. sourceRelative = util$2.relative(sourceRoot, sourceFile);
  8350. }
  8351. if (!generator._sources.has(sourceRelative)) {
  8352. generator._sources.add(sourceRelative);
  8353. }
  8354. var content = aSourceMapConsumer.sourceContentFor(sourceFile);
  8355. if (content != null) {
  8356. generator.setSourceContent(sourceFile, content);
  8357. }
  8358. });
  8359. return generator;
  8360. };
  8361. /**
  8362. * Add a single mapping from original source line and column to the generated
  8363. * source's line and column for this source map being created. The mapping
  8364. * object should have the following properties:
  8365. *
  8366. * - generated: An object with the generated line and column positions.
  8367. * - original: An object with the original line and column positions.
  8368. * - source: The original source file (relative to the sourceRoot).
  8369. * - name: An optional original token name for this mapping.
  8370. */
  8371. SourceMapGenerator$2.prototype.addMapping =
  8372. function SourceMapGenerator_addMapping(aArgs) {
  8373. var generated = util$2.getArg(aArgs, 'generated');
  8374. var original = util$2.getArg(aArgs, 'original', null);
  8375. var source = util$2.getArg(aArgs, 'source', null);
  8376. var name = util$2.getArg(aArgs, 'name', null);
  8377. if (!this._skipValidation) {
  8378. this._validateMapping(generated, original, source, name);
  8379. }
  8380. if (source != null) {
  8381. source = String(source);
  8382. if (!this._sources.has(source)) {
  8383. this._sources.add(source);
  8384. }
  8385. }
  8386. if (name != null) {
  8387. name = String(name);
  8388. if (!this._names.has(name)) {
  8389. this._names.add(name);
  8390. }
  8391. }
  8392. this._mappings.add({
  8393. generatedLine: generated.line,
  8394. generatedColumn: generated.column,
  8395. originalLine: original != null && original.line,
  8396. originalColumn: original != null && original.column,
  8397. source: source,
  8398. name: name
  8399. });
  8400. };
  8401. /**
  8402. * Set the source content for a source file.
  8403. */
  8404. SourceMapGenerator$2.prototype.setSourceContent =
  8405. function SourceMapGenerator_setSourceContent(aSourceFile, aSourceContent) {
  8406. var source = aSourceFile;
  8407. if (this._sourceRoot != null) {
  8408. source = util$2.relative(this._sourceRoot, source);
  8409. }
  8410. if (aSourceContent != null) {
  8411. // Add the source content to the _sourcesContents map.
  8412. // Create a new _sourcesContents map if the property is null.
  8413. if (!this._sourcesContents) {
  8414. this._sourcesContents = Object.create(null);
  8415. }
  8416. this._sourcesContents[util$2.toSetString(source)] = aSourceContent;
  8417. } else if (this._sourcesContents) {
  8418. // Remove the source file from the _sourcesContents map.
  8419. // If the _sourcesContents map is empty, set the property to null.
  8420. delete this._sourcesContents[util$2.toSetString(source)];
  8421. if (Object.keys(this._sourcesContents).length === 0) {
  8422. this._sourcesContents = null;
  8423. }
  8424. }
  8425. };
  8426. /**
  8427. * Applies the mappings of a sub-source-map for a specific source file to the
  8428. * source map being generated. Each mapping to the supplied source file is
  8429. * rewritten using the supplied source map. Note: The resolution for the
  8430. * resulting mappings is the minimium of this map and the supplied map.
  8431. *
  8432. * @param aSourceMapConsumer The source map to be applied.
  8433. * @param aSourceFile Optional. The filename of the source file.
  8434. * If omitted, SourceMapConsumer's file property will be used.
  8435. * @param aSourceMapPath Optional. The dirname of the path to the source map
  8436. * to be applied. If relative, it is relative to the SourceMapConsumer.
  8437. * This parameter is needed when the two source maps aren't in the same
  8438. * directory, and the source map to be applied contains relative source
  8439. * paths. If so, those relative source paths need to be rewritten
  8440. * relative to the SourceMapGenerator.
  8441. */
  8442. SourceMapGenerator$2.prototype.applySourceMap =
  8443. function SourceMapGenerator_applySourceMap(aSourceMapConsumer, aSourceFile, aSourceMapPath) {
  8444. var sourceFile = aSourceFile;
  8445. // If aSourceFile is omitted, we will use the file property of the SourceMap
  8446. if (aSourceFile == null) {
  8447. if (aSourceMapConsumer.file == null) {
  8448. throw new Error(
  8449. 'SourceMapGenerator.prototype.applySourceMap requires either an explicit source file, ' +
  8450. 'or the source map\'s "file" property. Both were omitted.'
  8451. );
  8452. }
  8453. sourceFile = aSourceMapConsumer.file;
  8454. }
  8455. var sourceRoot = this._sourceRoot;
  8456. // Make "sourceFile" relative if an absolute Url is passed.
  8457. if (sourceRoot != null) {
  8458. sourceFile = util$2.relative(sourceRoot, sourceFile);
  8459. }
  8460. // Applying the SourceMap can add and remove items from the sources and
  8461. // the names array.
  8462. var newSources = new ArraySet$1();
  8463. var newNames = new ArraySet$1();
  8464. // Find mappings for the "sourceFile"
  8465. this._mappings.unsortedForEach(function (mapping) {
  8466. if (mapping.source === sourceFile && mapping.originalLine != null) {
  8467. // Check if it can be mapped by the source map, then update the mapping.
  8468. var original = aSourceMapConsumer.originalPositionFor({
  8469. line: mapping.originalLine,
  8470. column: mapping.originalColumn
  8471. });
  8472. if (original.source != null) {
  8473. // Copy mapping
  8474. mapping.source = original.source;
  8475. if (aSourceMapPath != null) {
  8476. mapping.source = util$2.join(aSourceMapPath, mapping.source);
  8477. }
  8478. if (sourceRoot != null) {
  8479. mapping.source = util$2.relative(sourceRoot, mapping.source);
  8480. }
  8481. mapping.originalLine = original.line;
  8482. mapping.originalColumn = original.column;
  8483. if (original.name != null) {
  8484. mapping.name = original.name;
  8485. }
  8486. }
  8487. }
  8488. var source = mapping.source;
  8489. if (source != null && !newSources.has(source)) {
  8490. newSources.add(source);
  8491. }
  8492. var name = mapping.name;
  8493. if (name != null && !newNames.has(name)) {
  8494. newNames.add(name);
  8495. }
  8496. }, this);
  8497. this._sources = newSources;
  8498. this._names = newNames;
  8499. // Copy sourcesContents of applied map.
  8500. aSourceMapConsumer.sources.forEach(function (sourceFile) {
  8501. var content = aSourceMapConsumer.sourceContentFor(sourceFile);
  8502. if (content != null) {
  8503. if (aSourceMapPath != null) {
  8504. sourceFile = util$2.join(aSourceMapPath, sourceFile);
  8505. }
  8506. if (sourceRoot != null) {
  8507. sourceFile = util$2.relative(sourceRoot, sourceFile);
  8508. }
  8509. this.setSourceContent(sourceFile, content);
  8510. }
  8511. }, this);
  8512. };
  8513. /**
  8514. * A mapping can have one of the three levels of data:
  8515. *
  8516. * 1. Just the generated position.
  8517. * 2. The Generated position, original position, and original source.
  8518. * 3. Generated and original position, original source, as well as a name
  8519. * token.
  8520. *
  8521. * To maintain consistency, we validate that any new mapping being added falls
  8522. * in to one of these categories.
  8523. */
  8524. SourceMapGenerator$2.prototype._validateMapping =
  8525. function SourceMapGenerator_validateMapping(aGenerated, aOriginal, aSource,
  8526. aName) {
  8527. // When aOriginal is truthy but has empty values for .line and .column,
  8528. // it is most likely a programmer error. In this case we throw a very
  8529. // specific error message to try to guide them the right way.
  8530. // For example: https://github.com/Polymer/polymer-bundler/pull/519
  8531. if (aOriginal && typeof aOriginal.line !== 'number' && typeof aOriginal.column !== 'number') {
  8532. throw new Error(
  8533. 'original.line and original.column are not numbers -- you probably meant to omit ' +
  8534. 'the original mapping entirely and only map the generated position. If so, pass ' +
  8535. 'null for the original mapping instead of an object with empty or null values.'
  8536. );
  8537. }
  8538. if (aGenerated && 'line' in aGenerated && 'column' in aGenerated
  8539. && aGenerated.line > 0 && aGenerated.column >= 0
  8540. && !aOriginal && !aSource && !aName) {
  8541. // Case 1.
  8542. return;
  8543. }
  8544. else if (aGenerated && 'line' in aGenerated && 'column' in aGenerated
  8545. && aOriginal && 'line' in aOriginal && 'column' in aOriginal
  8546. && aGenerated.line > 0 && aGenerated.column >= 0
  8547. && aOriginal.line > 0 && aOriginal.column >= 0
  8548. && aSource) {
  8549. // Cases 2 and 3.
  8550. return;
  8551. }
  8552. else {
  8553. throw new Error('Invalid mapping: ' + JSON.stringify({
  8554. generated: aGenerated,
  8555. source: aSource,
  8556. original: aOriginal,
  8557. name: aName
  8558. }));
  8559. }
  8560. };
  8561. /**
  8562. * Serialize the accumulated mappings in to the stream of base 64 VLQs
  8563. * specified by the source map format.
  8564. */
  8565. SourceMapGenerator$2.prototype._serializeMappings =
  8566. function SourceMapGenerator_serializeMappings() {
  8567. var previousGeneratedColumn = 0;
  8568. var previousGeneratedLine = 1;
  8569. var previousOriginalColumn = 0;
  8570. var previousOriginalLine = 0;
  8571. var previousName = 0;
  8572. var previousSource = 0;
  8573. var result = '';
  8574. var next;
  8575. var mapping;
  8576. var nameIdx;
  8577. var sourceIdx;
  8578. var mappings = this._mappings.toArray();
  8579. for (var i = 0, len = mappings.length; i < len; i++) {
  8580. mapping = mappings[i];
  8581. next = '';
  8582. if (mapping.generatedLine !== previousGeneratedLine) {
  8583. previousGeneratedColumn = 0;
  8584. while (mapping.generatedLine !== previousGeneratedLine) {
  8585. next += ';';
  8586. previousGeneratedLine++;
  8587. }
  8588. }
  8589. else {
  8590. if (i > 0) {
  8591. if (!util$2.compareByGeneratedPositionsInflated(mapping, mappings[i - 1])) {
  8592. continue;
  8593. }
  8594. next += ',';
  8595. }
  8596. }
  8597. next += base64VLQ$1.encode(mapping.generatedColumn
  8598. - previousGeneratedColumn);
  8599. previousGeneratedColumn = mapping.generatedColumn;
  8600. if (mapping.source != null) {
  8601. sourceIdx = this._sources.indexOf(mapping.source);
  8602. next += base64VLQ$1.encode(sourceIdx - previousSource);
  8603. previousSource = sourceIdx;
  8604. // lines are stored 0-based in SourceMap spec version 3
  8605. next += base64VLQ$1.encode(mapping.originalLine - 1
  8606. - previousOriginalLine);
  8607. previousOriginalLine = mapping.originalLine - 1;
  8608. next += base64VLQ$1.encode(mapping.originalColumn
  8609. - previousOriginalColumn);
  8610. previousOriginalColumn = mapping.originalColumn;
  8611. if (mapping.name != null) {
  8612. nameIdx = this._names.indexOf(mapping.name);
  8613. next += base64VLQ$1.encode(nameIdx - previousName);
  8614. previousName = nameIdx;
  8615. }
  8616. }
  8617. result += next;
  8618. }
  8619. return result;
  8620. };
  8621. SourceMapGenerator$2.prototype._generateSourcesContent =
  8622. function SourceMapGenerator_generateSourcesContent(aSources, aSourceRoot) {
  8623. return aSources.map(function (source) {
  8624. if (!this._sourcesContents) {
  8625. return null;
  8626. }
  8627. if (aSourceRoot != null) {
  8628. source = util$2.relative(aSourceRoot, source);
  8629. }
  8630. var key = util$2.toSetString(source);
  8631. return Object.prototype.hasOwnProperty.call(this._sourcesContents, key)
  8632. ? this._sourcesContents[key]
  8633. : null;
  8634. }, this);
  8635. };
  8636. /**
  8637. * Externalize the source map.
  8638. */
  8639. SourceMapGenerator$2.prototype.toJSON =
  8640. function SourceMapGenerator_toJSON() {
  8641. var map = {
  8642. version: this._version,
  8643. sources: this._sources.toArray(),
  8644. names: this._names.toArray(),
  8645. mappings: this._serializeMappings()
  8646. };
  8647. if (this._file != null) {
  8648. map.file = this._file;
  8649. }
  8650. if (this._sourceRoot != null) {
  8651. map.sourceRoot = this._sourceRoot;
  8652. }
  8653. if (this._sourcesContents) {
  8654. map.sourcesContent = this._generateSourcesContent(map.sources, map.sourceRoot);
  8655. }
  8656. return map;
  8657. };
  8658. /**
  8659. * Render the source map being generated to a string.
  8660. */
  8661. SourceMapGenerator$2.prototype.toString =
  8662. function SourceMapGenerator_toString() {
  8663. return JSON.stringify(this.toJSON());
  8664. };
  8665. sourceMapGenerator.SourceMapGenerator = SourceMapGenerator$2;
  8666. var sourceMapConsumer = {};
  8667. var binarySearch$1 = {};
  8668. /* -*- Mode: js; js-indent-level: 2; -*- */
  8669. (function (exports) {
  8670. /*
  8671. * Copyright 2011 Mozilla Foundation and contributors
  8672. * Licensed under the New BSD license. See LICENSE or:
  8673. * http://opensource.org/licenses/BSD-3-Clause
  8674. */
  8675. exports.GREATEST_LOWER_BOUND = 1;
  8676. exports.LEAST_UPPER_BOUND = 2;
  8677. /**
  8678. * Recursive implementation of binary search.
  8679. *
  8680. * @param aLow Indices here and lower do not contain the needle.
  8681. * @param aHigh Indices here and higher do not contain the needle.
  8682. * @param aNeedle The element being searched for.
  8683. * @param aHaystack The non-empty array being searched.
  8684. * @param aCompare Function which takes two elements and returns -1, 0, or 1.
  8685. * @param aBias Either 'binarySearch.GREATEST_LOWER_BOUND' or
  8686. * 'binarySearch.LEAST_UPPER_BOUND'. Specifies whether to return the
  8687. * closest element that is smaller than or greater than the one we are
  8688. * searching for, respectively, if the exact element cannot be found.
  8689. */
  8690. function recursiveSearch(aLow, aHigh, aNeedle, aHaystack, aCompare, aBias) {
  8691. // This function terminates when one of the following is true:
  8692. //
  8693. // 1. We find the exact element we are looking for.
  8694. //
  8695. // 2. We did not find the exact element, but we can return the index of
  8696. // the next-closest element.
  8697. //
  8698. // 3. We did not find the exact element, and there is no next-closest
  8699. // element than the one we are searching for, so we return -1.
  8700. var mid = Math.floor((aHigh - aLow) / 2) + aLow;
  8701. var cmp = aCompare(aNeedle, aHaystack[mid], true);
  8702. if (cmp === 0) {
  8703. // Found the element we are looking for.
  8704. return mid;
  8705. }
  8706. else if (cmp > 0) {
  8707. // Our needle is greater than aHaystack[mid].
  8708. if (aHigh - mid > 1) {
  8709. // The element is in the upper half.
  8710. return recursiveSearch(mid, aHigh, aNeedle, aHaystack, aCompare, aBias);
  8711. }
  8712. // The exact needle element was not found in this haystack. Determine if
  8713. // we are in termination case (3) or (2) and return the appropriate thing.
  8714. if (aBias == exports.LEAST_UPPER_BOUND) {
  8715. return aHigh < aHaystack.length ? aHigh : -1;
  8716. } else {
  8717. return mid;
  8718. }
  8719. }
  8720. else {
  8721. // Our needle is less than aHaystack[mid].
  8722. if (mid - aLow > 1) {
  8723. // The element is in the lower half.
  8724. return recursiveSearch(aLow, mid, aNeedle, aHaystack, aCompare, aBias);
  8725. }
  8726. // we are in termination case (3) or (2) and return the appropriate thing.
  8727. if (aBias == exports.LEAST_UPPER_BOUND) {
  8728. return mid;
  8729. } else {
  8730. return aLow < 0 ? -1 : aLow;
  8731. }
  8732. }
  8733. }
  8734. /**
  8735. * This is an implementation of binary search which will always try and return
  8736. * the index of the closest element if there is no exact hit. This is because
  8737. * mappings between original and generated line/col pairs are single points,
  8738. * and there is an implicit region between each of them, so a miss just means
  8739. * that you aren't on the very start of a region.
  8740. *
  8741. * @param aNeedle The element you are looking for.
  8742. * @param aHaystack The array that is being searched.
  8743. * @param aCompare A function which takes the needle and an element in the
  8744. * array and returns -1, 0, or 1 depending on whether the needle is less
  8745. * than, equal to, or greater than the element, respectively.
  8746. * @param aBias Either 'binarySearch.GREATEST_LOWER_BOUND' or
  8747. * 'binarySearch.LEAST_UPPER_BOUND'. Specifies whether to return the
  8748. * closest element that is smaller than or greater than the one we are
  8749. * searching for, respectively, if the exact element cannot be found.
  8750. * Defaults to 'binarySearch.GREATEST_LOWER_BOUND'.
  8751. */
  8752. exports.search = function search(aNeedle, aHaystack, aCompare, aBias) {
  8753. if (aHaystack.length === 0) {
  8754. return -1;
  8755. }
  8756. var index = recursiveSearch(-1, aHaystack.length, aNeedle, aHaystack,
  8757. aCompare, aBias || exports.GREATEST_LOWER_BOUND);
  8758. if (index < 0) {
  8759. return -1;
  8760. }
  8761. // We have found either the exact element, or the next-closest element than
  8762. // the one we are searching for. However, there may be more than one such
  8763. // element. Make sure we always return the smallest of these.
  8764. while (index - 1 >= 0) {
  8765. if (aCompare(aHaystack[index], aHaystack[index - 1], true) !== 0) {
  8766. break;
  8767. }
  8768. --index;
  8769. }
  8770. return index;
  8771. };
  8772. } (binarySearch$1));
  8773. var quickSort$1 = {};
  8774. /* -*- Mode: js; js-indent-level: 2; -*- */
  8775. /*
  8776. * Copyright 2011 Mozilla Foundation and contributors
  8777. * Licensed under the New BSD license. See LICENSE or:
  8778. * http://opensource.org/licenses/BSD-3-Clause
  8779. */
  8780. // It turns out that some (most?) JavaScript engines don't self-host
  8781. // `Array.prototype.sort`. This makes sense because C++ will likely remain
  8782. // faster than JS when doing raw CPU-intensive sorting. However, when using a
  8783. // custom comparator function, calling back and forth between the VM's C++ and
  8784. // JIT'd JS is rather slow *and* loses JIT type information, resulting in
  8785. // worse generated code for the comparator function than would be optimal. In
  8786. // fact, when sorting with a comparator, these costs outweigh the benefits of
  8787. // sorting in C++. By using our own JS-implemented Quick Sort (below), we get
  8788. // a ~3500ms mean speed-up in `bench/bench.html`.
  8789. /**
  8790. * Swap the elements indexed by `x` and `y` in the array `ary`.
  8791. *
  8792. * @param {Array} ary
  8793. * The array.
  8794. * @param {Number} x
  8795. * The index of the first item.
  8796. * @param {Number} y
  8797. * The index of the second item.
  8798. */
  8799. function swap(ary, x, y) {
  8800. var temp = ary[x];
  8801. ary[x] = ary[y];
  8802. ary[y] = temp;
  8803. }
  8804. /**
  8805. * Returns a random integer within the range `low .. high` inclusive.
  8806. *
  8807. * @param {Number} low
  8808. * The lower bound on the range.
  8809. * @param {Number} high
  8810. * The upper bound on the range.
  8811. */
  8812. function randomIntInRange(low, high) {
  8813. return Math.round(low + (Math.random() * (high - low)));
  8814. }
  8815. /**
  8816. * The Quick Sort algorithm.
  8817. *
  8818. * @param {Array} ary
  8819. * An array to sort.
  8820. * @param {function} comparator
  8821. * Function to use to compare two items.
  8822. * @param {Number} p
  8823. * Start index of the array
  8824. * @param {Number} r
  8825. * End index of the array
  8826. */
  8827. function doQuickSort(ary, comparator, p, r) {
  8828. // If our lower bound is less than our upper bound, we (1) partition the
  8829. // array into two pieces and (2) recurse on each half. If it is not, this is
  8830. // the empty array and our base case.
  8831. if (p < r) {
  8832. // (1) Partitioning.
  8833. //
  8834. // The partitioning chooses a pivot between `p` and `r` and moves all
  8835. // elements that are less than or equal to the pivot to the before it, and
  8836. // all the elements that are greater than it after it. The effect is that
  8837. // once partition is done, the pivot is in the exact place it will be when
  8838. // the array is put in sorted order, and it will not need to be moved
  8839. // again. This runs in O(n) time.
  8840. // Always choose a random pivot so that an input array which is reverse
  8841. // sorted does not cause O(n^2) running time.
  8842. var pivotIndex = randomIntInRange(p, r);
  8843. var i = p - 1;
  8844. swap(ary, pivotIndex, r);
  8845. var pivot = ary[r];
  8846. // Immediately after `j` is incremented in this loop, the following hold
  8847. // true:
  8848. //
  8849. // * Every element in `ary[p .. i]` is less than or equal to the pivot.
  8850. //
  8851. // * Every element in `ary[i+1 .. j-1]` is greater than the pivot.
  8852. for (var j = p; j < r; j++) {
  8853. if (comparator(ary[j], pivot) <= 0) {
  8854. i += 1;
  8855. swap(ary, i, j);
  8856. }
  8857. }
  8858. swap(ary, i + 1, j);
  8859. var q = i + 1;
  8860. // (2) Recurse on each half.
  8861. doQuickSort(ary, comparator, p, q - 1);
  8862. doQuickSort(ary, comparator, q + 1, r);
  8863. }
  8864. }
  8865. /**
  8866. * Sort the given array in-place with the given comparator function.
  8867. *
  8868. * @param {Array} ary
  8869. * An array to sort.
  8870. * @param {function} comparator
  8871. * Function to use to compare two items.
  8872. */
  8873. quickSort$1.quickSort = function (ary, comparator) {
  8874. doQuickSort(ary, comparator, 0, ary.length - 1);
  8875. };
  8876. /* -*- Mode: js; js-indent-level: 2; -*- */
  8877. /*
  8878. * Copyright 2011 Mozilla Foundation and contributors
  8879. * Licensed under the New BSD license. See LICENSE or:
  8880. * http://opensource.org/licenses/BSD-3-Clause
  8881. */
  8882. var util$1 = util$5;
  8883. var binarySearch = binarySearch$1;
  8884. var ArraySet = arraySet.ArraySet;
  8885. var base64VLQ = base64Vlq;
  8886. var quickSort = quickSort$1.quickSort;
  8887. function SourceMapConsumer$1(aSourceMap, aSourceMapURL) {
  8888. var sourceMap = aSourceMap;
  8889. if (typeof aSourceMap === 'string') {
  8890. sourceMap = util$1.parseSourceMapInput(aSourceMap);
  8891. }
  8892. return sourceMap.sections != null
  8893. ? new IndexedSourceMapConsumer(sourceMap, aSourceMapURL)
  8894. : new BasicSourceMapConsumer(sourceMap, aSourceMapURL);
  8895. }
  8896. SourceMapConsumer$1.fromSourceMap = function(aSourceMap, aSourceMapURL) {
  8897. return BasicSourceMapConsumer.fromSourceMap(aSourceMap, aSourceMapURL);
  8898. };
  8899. /**
  8900. * The version of the source mapping spec that we are consuming.
  8901. */
  8902. SourceMapConsumer$1.prototype._version = 3;
  8903. // `__generatedMappings` and `__originalMappings` are arrays that hold the
  8904. // parsed mapping coordinates from the source map's "mappings" attribute. They
  8905. // are lazily instantiated, accessed via the `_generatedMappings` and
  8906. // `_originalMappings` getters respectively, and we only parse the mappings
  8907. // and create these arrays once queried for a source location. We jump through
  8908. // these hoops because there can be many thousands of mappings, and parsing
  8909. // them is expensive, so we only want to do it if we must.
  8910. //
  8911. // Each object in the arrays is of the form:
  8912. //
  8913. // {
  8914. // generatedLine: The line number in the generated code,
  8915. // generatedColumn: The column number in the generated code,
  8916. // source: The path to the original source file that generated this
  8917. // chunk of code,
  8918. // originalLine: The line number in the original source that
  8919. // corresponds to this chunk of generated code,
  8920. // originalColumn: The column number in the original source that
  8921. // corresponds to this chunk of generated code,
  8922. // name: The name of the original symbol which generated this chunk of
  8923. // code.
  8924. // }
  8925. //
  8926. // All properties except for `generatedLine` and `generatedColumn` can be
  8927. // `null`.
  8928. //
  8929. // `_generatedMappings` is ordered by the generated positions.
  8930. //
  8931. // `_originalMappings` is ordered by the original positions.
  8932. SourceMapConsumer$1.prototype.__generatedMappings = null;
  8933. Object.defineProperty(SourceMapConsumer$1.prototype, '_generatedMappings', {
  8934. configurable: true,
  8935. enumerable: true,
  8936. get: function () {
  8937. if (!this.__generatedMappings) {
  8938. this._parseMappings(this._mappings, this.sourceRoot);
  8939. }
  8940. return this.__generatedMappings;
  8941. }
  8942. });
  8943. SourceMapConsumer$1.prototype.__originalMappings = null;
  8944. Object.defineProperty(SourceMapConsumer$1.prototype, '_originalMappings', {
  8945. configurable: true,
  8946. enumerable: true,
  8947. get: function () {
  8948. if (!this.__originalMappings) {
  8949. this._parseMappings(this._mappings, this.sourceRoot);
  8950. }
  8951. return this.__originalMappings;
  8952. }
  8953. });
  8954. SourceMapConsumer$1.prototype._charIsMappingSeparator =
  8955. function SourceMapConsumer_charIsMappingSeparator(aStr, index) {
  8956. var c = aStr.charAt(index);
  8957. return c === ";" || c === ",";
  8958. };
  8959. /**
  8960. * Parse the mappings in a string in to a data structure which we can easily
  8961. * query (the ordered arrays in the `this.__generatedMappings` and
  8962. * `this.__originalMappings` properties).
  8963. */
  8964. SourceMapConsumer$1.prototype._parseMappings =
  8965. function SourceMapConsumer_parseMappings(aStr, aSourceRoot) {
  8966. throw new Error("Subclasses must implement _parseMappings");
  8967. };
  8968. SourceMapConsumer$1.GENERATED_ORDER = 1;
  8969. SourceMapConsumer$1.ORIGINAL_ORDER = 2;
  8970. SourceMapConsumer$1.GREATEST_LOWER_BOUND = 1;
  8971. SourceMapConsumer$1.LEAST_UPPER_BOUND = 2;
  8972. /**
  8973. * Iterate over each mapping between an original source/line/column and a
  8974. * generated line/column in this source map.
  8975. *
  8976. * @param Function aCallback
  8977. * The function that is called with each mapping.
  8978. * @param Object aContext
  8979. * Optional. If specified, this object will be the value of `this` every
  8980. * time that `aCallback` is called.
  8981. * @param aOrder
  8982. * Either `SourceMapConsumer.GENERATED_ORDER` or
  8983. * `SourceMapConsumer.ORIGINAL_ORDER`. Specifies whether you want to
  8984. * iterate over the mappings sorted by the generated file's line/column
  8985. * order or the original's source/line/column order, respectively. Defaults to
  8986. * `SourceMapConsumer.GENERATED_ORDER`.
  8987. */
  8988. SourceMapConsumer$1.prototype.eachMapping =
  8989. function SourceMapConsumer_eachMapping(aCallback, aContext, aOrder) {
  8990. var context = aContext || null;
  8991. var order = aOrder || SourceMapConsumer$1.GENERATED_ORDER;
  8992. var mappings;
  8993. switch (order) {
  8994. case SourceMapConsumer$1.GENERATED_ORDER:
  8995. mappings = this._generatedMappings;
  8996. break;
  8997. case SourceMapConsumer$1.ORIGINAL_ORDER:
  8998. mappings = this._originalMappings;
  8999. break;
  9000. default:
  9001. throw new Error("Unknown order of iteration.");
  9002. }
  9003. var sourceRoot = this.sourceRoot;
  9004. mappings.map(function (mapping) {
  9005. var source = mapping.source === null ? null : this._sources.at(mapping.source);
  9006. source = util$1.computeSourceURL(sourceRoot, source, this._sourceMapURL);
  9007. return {
  9008. source: source,
  9009. generatedLine: mapping.generatedLine,
  9010. generatedColumn: mapping.generatedColumn,
  9011. originalLine: mapping.originalLine,
  9012. originalColumn: mapping.originalColumn,
  9013. name: mapping.name === null ? null : this._names.at(mapping.name)
  9014. };
  9015. }, this).forEach(aCallback, context);
  9016. };
  9017. /**
  9018. * Returns all generated line and column information for the original source,
  9019. * line, and column provided. If no column is provided, returns all mappings
  9020. * corresponding to a either the line we are searching for or the next
  9021. * closest line that has any mappings. Otherwise, returns all mappings
  9022. * corresponding to the given line and either the column we are searching for
  9023. * or the next closest column that has any offsets.
  9024. *
  9025. * The only argument is an object with the following properties:
  9026. *
  9027. * - source: The filename of the original source.
  9028. * - line: The line number in the original source. The line number is 1-based.
  9029. * - column: Optional. the column number in the original source.
  9030. * The column number is 0-based.
  9031. *
  9032. * and an array of objects is returned, each with the following properties:
  9033. *
  9034. * - line: The line number in the generated source, or null. The
  9035. * line number is 1-based.
  9036. * - column: The column number in the generated source, or null.
  9037. * The column number is 0-based.
  9038. */
  9039. SourceMapConsumer$1.prototype.allGeneratedPositionsFor =
  9040. function SourceMapConsumer_allGeneratedPositionsFor(aArgs) {
  9041. var line = util$1.getArg(aArgs, 'line');
  9042. // When there is no exact match, BasicSourceMapConsumer.prototype._findMapping
  9043. // returns the index of the closest mapping less than the needle. By
  9044. // setting needle.originalColumn to 0, we thus find the last mapping for
  9045. // the given line, provided such a mapping exists.
  9046. var needle = {
  9047. source: util$1.getArg(aArgs, 'source'),
  9048. originalLine: line,
  9049. originalColumn: util$1.getArg(aArgs, 'column', 0)
  9050. };
  9051. needle.source = this._findSourceIndex(needle.source);
  9052. if (needle.source < 0) {
  9053. return [];
  9054. }
  9055. var mappings = [];
  9056. var index = this._findMapping(needle,
  9057. this._originalMappings,
  9058. "originalLine",
  9059. "originalColumn",
  9060. util$1.compareByOriginalPositions,
  9061. binarySearch.LEAST_UPPER_BOUND);
  9062. if (index >= 0) {
  9063. var mapping = this._originalMappings[index];
  9064. if (aArgs.column === undefined) {
  9065. var originalLine = mapping.originalLine;
  9066. // Iterate until either we run out of mappings, or we run into
  9067. // a mapping for a different line than the one we found. Since
  9068. // mappings are sorted, this is guaranteed to find all mappings for
  9069. // the line we found.
  9070. while (mapping && mapping.originalLine === originalLine) {
  9071. mappings.push({
  9072. line: util$1.getArg(mapping, 'generatedLine', null),
  9073. column: util$1.getArg(mapping, 'generatedColumn', null),
  9074. lastColumn: util$1.getArg(mapping, 'lastGeneratedColumn', null)
  9075. });
  9076. mapping = this._originalMappings[++index];
  9077. }
  9078. } else {
  9079. var originalColumn = mapping.originalColumn;
  9080. // Iterate until either we run out of mappings, or we run into
  9081. // a mapping for a different line than the one we were searching for.
  9082. // Since mappings are sorted, this is guaranteed to find all mappings for
  9083. // the line we are searching for.
  9084. while (mapping &&
  9085. mapping.originalLine === line &&
  9086. mapping.originalColumn == originalColumn) {
  9087. mappings.push({
  9088. line: util$1.getArg(mapping, 'generatedLine', null),
  9089. column: util$1.getArg(mapping, 'generatedColumn', null),
  9090. lastColumn: util$1.getArg(mapping, 'lastGeneratedColumn', null)
  9091. });
  9092. mapping = this._originalMappings[++index];
  9093. }
  9094. }
  9095. }
  9096. return mappings;
  9097. };
  9098. sourceMapConsumer.SourceMapConsumer = SourceMapConsumer$1;
  9099. /**
  9100. * A BasicSourceMapConsumer instance represents a parsed source map which we can
  9101. * query for information about the original file positions by giving it a file
  9102. * position in the generated source.
  9103. *
  9104. * The first parameter is the raw source map (either as a JSON string, or
  9105. * already parsed to an object). According to the spec, source maps have the
  9106. * following attributes:
  9107. *
  9108. * - version: Which version of the source map spec this map is following.
  9109. * - sources: An array of URLs to the original source files.
  9110. * - names: An array of identifiers which can be referrenced by individual mappings.
  9111. * - sourceRoot: Optional. The URL root from which all sources are relative.
  9112. * - sourcesContent: Optional. An array of contents of the original source files.
  9113. * - mappings: A string of base64 VLQs which contain the actual mappings.
  9114. * - file: Optional. The generated file this source map is associated with.
  9115. *
  9116. * Here is an example source map, taken from the source map spec[0]:
  9117. *
  9118. * {
  9119. * version : 3,
  9120. * file: "out.js",
  9121. * sourceRoot : "",
  9122. * sources: ["foo.js", "bar.js"],
  9123. * names: ["src", "maps", "are", "fun"],
  9124. * mappings: "AA,AB;;ABCDE;"
  9125. * }
  9126. *
  9127. * The second parameter, if given, is a string whose value is the URL
  9128. * at which the source map was found. This URL is used to compute the
  9129. * sources array.
  9130. *
  9131. * [0]: https://docs.google.com/document/d/1U1RGAehQwRypUTovF1KRlpiOFze0b-_2gc6fAH0KY0k/edit?pli=1#
  9132. */
  9133. function BasicSourceMapConsumer(aSourceMap, aSourceMapURL) {
  9134. var sourceMap = aSourceMap;
  9135. if (typeof aSourceMap === 'string') {
  9136. sourceMap = util$1.parseSourceMapInput(aSourceMap);
  9137. }
  9138. var version = util$1.getArg(sourceMap, 'version');
  9139. var sources = util$1.getArg(sourceMap, 'sources');
  9140. // Sass 3.3 leaves out the 'names' array, so we deviate from the spec (which
  9141. // requires the array) to play nice here.
  9142. var names = util$1.getArg(sourceMap, 'names', []);
  9143. var sourceRoot = util$1.getArg(sourceMap, 'sourceRoot', null);
  9144. var sourcesContent = util$1.getArg(sourceMap, 'sourcesContent', null);
  9145. var mappings = util$1.getArg(sourceMap, 'mappings');
  9146. var file = util$1.getArg(sourceMap, 'file', null);
  9147. // Once again, Sass deviates from the spec and supplies the version as a
  9148. // string rather than a number, so we use loose equality checking here.
  9149. if (version != this._version) {
  9150. throw new Error('Unsupported version: ' + version);
  9151. }
  9152. if (sourceRoot) {
  9153. sourceRoot = util$1.normalize(sourceRoot);
  9154. }
  9155. sources = sources
  9156. .map(String)
  9157. // Some source maps produce relative source paths like "./foo.js" instead of
  9158. // "foo.js". Normalize these first so that future comparisons will succeed.
  9159. // See bugzil.la/1090768.
  9160. .map(util$1.normalize)
  9161. // Always ensure that absolute sources are internally stored relative to
  9162. // the source root, if the source root is absolute. Not doing this would
  9163. // be particularly problematic when the source root is a prefix of the
  9164. // source (valid, but why??). See github issue #199 and bugzil.la/1188982.
  9165. .map(function (source) {
  9166. return sourceRoot && util$1.isAbsolute(sourceRoot) && util$1.isAbsolute(source)
  9167. ? util$1.relative(sourceRoot, source)
  9168. : source;
  9169. });
  9170. // Pass `true` below to allow duplicate names and sources. While source maps
  9171. // are intended to be compressed and deduplicated, the TypeScript compiler
  9172. // sometimes generates source maps with duplicates in them. See Github issue
  9173. // #72 and bugzil.la/889492.
  9174. this._names = ArraySet.fromArray(names.map(String), true);
  9175. this._sources = ArraySet.fromArray(sources, true);
  9176. this._absoluteSources = this._sources.toArray().map(function (s) {
  9177. return util$1.computeSourceURL(sourceRoot, s, aSourceMapURL);
  9178. });
  9179. this.sourceRoot = sourceRoot;
  9180. this.sourcesContent = sourcesContent;
  9181. this._mappings = mappings;
  9182. this._sourceMapURL = aSourceMapURL;
  9183. this.file = file;
  9184. }
  9185. BasicSourceMapConsumer.prototype = Object.create(SourceMapConsumer$1.prototype);
  9186. BasicSourceMapConsumer.prototype.consumer = SourceMapConsumer$1;
  9187. /**
  9188. * Utility function to find the index of a source. Returns -1 if not
  9189. * found.
  9190. */
  9191. BasicSourceMapConsumer.prototype._findSourceIndex = function(aSource) {
  9192. var relativeSource = aSource;
  9193. if (this.sourceRoot != null) {
  9194. relativeSource = util$1.relative(this.sourceRoot, relativeSource);
  9195. }
  9196. if (this._sources.has(relativeSource)) {
  9197. return this._sources.indexOf(relativeSource);
  9198. }
  9199. // Maybe aSource is an absolute URL as returned by |sources|. In
  9200. // this case we can't simply undo the transform.
  9201. var i;
  9202. for (i = 0; i < this._absoluteSources.length; ++i) {
  9203. if (this._absoluteSources[i] == aSource) {
  9204. return i;
  9205. }
  9206. }
  9207. return -1;
  9208. };
  9209. /**
  9210. * Create a BasicSourceMapConsumer from a SourceMapGenerator.
  9211. *
  9212. * @param SourceMapGenerator aSourceMap
  9213. * The source map that will be consumed.
  9214. * @param String aSourceMapURL
  9215. * The URL at which the source map can be found (optional)
  9216. * @returns BasicSourceMapConsumer
  9217. */
  9218. BasicSourceMapConsumer.fromSourceMap =
  9219. function SourceMapConsumer_fromSourceMap(aSourceMap, aSourceMapURL) {
  9220. var smc = Object.create(BasicSourceMapConsumer.prototype);
  9221. var names = smc._names = ArraySet.fromArray(aSourceMap._names.toArray(), true);
  9222. var sources = smc._sources = ArraySet.fromArray(aSourceMap._sources.toArray(), true);
  9223. smc.sourceRoot = aSourceMap._sourceRoot;
  9224. smc.sourcesContent = aSourceMap._generateSourcesContent(smc._sources.toArray(),
  9225. smc.sourceRoot);
  9226. smc.file = aSourceMap._file;
  9227. smc._sourceMapURL = aSourceMapURL;
  9228. smc._absoluteSources = smc._sources.toArray().map(function (s) {
  9229. return util$1.computeSourceURL(smc.sourceRoot, s, aSourceMapURL);
  9230. });
  9231. // Because we are modifying the entries (by converting string sources and
  9232. // names to indices into the sources and names ArraySets), we have to make
  9233. // a copy of the entry or else bad things happen. Shared mutable state
  9234. // strikes again! See github issue #191.
  9235. var generatedMappings = aSourceMap._mappings.toArray().slice();
  9236. var destGeneratedMappings = smc.__generatedMappings = [];
  9237. var destOriginalMappings = smc.__originalMappings = [];
  9238. for (var i = 0, length = generatedMappings.length; i < length; i++) {
  9239. var srcMapping = generatedMappings[i];
  9240. var destMapping = new Mapping;
  9241. destMapping.generatedLine = srcMapping.generatedLine;
  9242. destMapping.generatedColumn = srcMapping.generatedColumn;
  9243. if (srcMapping.source) {
  9244. destMapping.source = sources.indexOf(srcMapping.source);
  9245. destMapping.originalLine = srcMapping.originalLine;
  9246. destMapping.originalColumn = srcMapping.originalColumn;
  9247. if (srcMapping.name) {
  9248. destMapping.name = names.indexOf(srcMapping.name);
  9249. }
  9250. destOriginalMappings.push(destMapping);
  9251. }
  9252. destGeneratedMappings.push(destMapping);
  9253. }
  9254. quickSort(smc.__originalMappings, util$1.compareByOriginalPositions);
  9255. return smc;
  9256. };
  9257. /**
  9258. * The version of the source mapping spec that we are consuming.
  9259. */
  9260. BasicSourceMapConsumer.prototype._version = 3;
  9261. /**
  9262. * The list of original sources.
  9263. */
  9264. Object.defineProperty(BasicSourceMapConsumer.prototype, 'sources', {
  9265. get: function () {
  9266. return this._absoluteSources.slice();
  9267. }
  9268. });
  9269. /**
  9270. * Provide the JIT with a nice shape / hidden class.
  9271. */
  9272. function Mapping() {
  9273. this.generatedLine = 0;
  9274. this.generatedColumn = 0;
  9275. this.source = null;
  9276. this.originalLine = null;
  9277. this.originalColumn = null;
  9278. this.name = null;
  9279. }
  9280. /**
  9281. * Parse the mappings in a string in to a data structure which we can easily
  9282. * query (the ordered arrays in the `this.__generatedMappings` and
  9283. * `this.__originalMappings` properties).
  9284. */
  9285. BasicSourceMapConsumer.prototype._parseMappings =
  9286. function SourceMapConsumer_parseMappings(aStr, aSourceRoot) {
  9287. var generatedLine = 1;
  9288. var previousGeneratedColumn = 0;
  9289. var previousOriginalLine = 0;
  9290. var previousOriginalColumn = 0;
  9291. var previousSource = 0;
  9292. var previousName = 0;
  9293. var length = aStr.length;
  9294. var index = 0;
  9295. var cachedSegments = {};
  9296. var temp = {};
  9297. var originalMappings = [];
  9298. var generatedMappings = [];
  9299. var mapping, str, segment, end, value;
  9300. while (index < length) {
  9301. if (aStr.charAt(index) === ';') {
  9302. generatedLine++;
  9303. index++;
  9304. previousGeneratedColumn = 0;
  9305. }
  9306. else if (aStr.charAt(index) === ',') {
  9307. index++;
  9308. }
  9309. else {
  9310. mapping = new Mapping();
  9311. mapping.generatedLine = generatedLine;
  9312. // Because each offset is encoded relative to the previous one,
  9313. // many segments often have the same encoding. We can exploit this
  9314. // fact by caching the parsed variable length fields of each segment,
  9315. // allowing us to avoid a second parse if we encounter the same
  9316. // segment again.
  9317. for (end = index; end < length; end++) {
  9318. if (this._charIsMappingSeparator(aStr, end)) {
  9319. break;
  9320. }
  9321. }
  9322. str = aStr.slice(index, end);
  9323. segment = cachedSegments[str];
  9324. if (segment) {
  9325. index += str.length;
  9326. } else {
  9327. segment = [];
  9328. while (index < end) {
  9329. base64VLQ.decode(aStr, index, temp);
  9330. value = temp.value;
  9331. index = temp.rest;
  9332. segment.push(value);
  9333. }
  9334. if (segment.length === 2) {
  9335. throw new Error('Found a source, but no line and column');
  9336. }
  9337. if (segment.length === 3) {
  9338. throw new Error('Found a source and line, but no column');
  9339. }
  9340. cachedSegments[str] = segment;
  9341. }
  9342. // Generated column.
  9343. mapping.generatedColumn = previousGeneratedColumn + segment[0];
  9344. previousGeneratedColumn = mapping.generatedColumn;
  9345. if (segment.length > 1) {
  9346. // Original source.
  9347. mapping.source = previousSource + segment[1];
  9348. previousSource += segment[1];
  9349. // Original line.
  9350. mapping.originalLine = previousOriginalLine + segment[2];
  9351. previousOriginalLine = mapping.originalLine;
  9352. // Lines are stored 0-based
  9353. mapping.originalLine += 1;
  9354. // Original column.
  9355. mapping.originalColumn = previousOriginalColumn + segment[3];
  9356. previousOriginalColumn = mapping.originalColumn;
  9357. if (segment.length > 4) {
  9358. // Original name.
  9359. mapping.name = previousName + segment[4];
  9360. previousName += segment[4];
  9361. }
  9362. }
  9363. generatedMappings.push(mapping);
  9364. if (typeof mapping.originalLine === 'number') {
  9365. originalMappings.push(mapping);
  9366. }
  9367. }
  9368. }
  9369. quickSort(generatedMappings, util$1.compareByGeneratedPositionsDeflated);
  9370. this.__generatedMappings = generatedMappings;
  9371. quickSort(originalMappings, util$1.compareByOriginalPositions);
  9372. this.__originalMappings = originalMappings;
  9373. };
  9374. /**
  9375. * Find the mapping that best matches the hypothetical "needle" mapping that
  9376. * we are searching for in the given "haystack" of mappings.
  9377. */
  9378. BasicSourceMapConsumer.prototype._findMapping =
  9379. function SourceMapConsumer_findMapping(aNeedle, aMappings, aLineName,
  9380. aColumnName, aComparator, aBias) {
  9381. // To return the position we are searching for, we must first find the
  9382. // mapping for the given position and then return the opposite position it
  9383. // points to. Because the mappings are sorted, we can use binary search to
  9384. // find the best mapping.
  9385. if (aNeedle[aLineName] <= 0) {
  9386. throw new TypeError('Line must be greater than or equal to 1, got '
  9387. + aNeedle[aLineName]);
  9388. }
  9389. if (aNeedle[aColumnName] < 0) {
  9390. throw new TypeError('Column must be greater than or equal to 0, got '
  9391. + aNeedle[aColumnName]);
  9392. }
  9393. return binarySearch.search(aNeedle, aMappings, aComparator, aBias);
  9394. };
  9395. /**
  9396. * Compute the last column for each generated mapping. The last column is
  9397. * inclusive.
  9398. */
  9399. BasicSourceMapConsumer.prototype.computeColumnSpans =
  9400. function SourceMapConsumer_computeColumnSpans() {
  9401. for (var index = 0; index < this._generatedMappings.length; ++index) {
  9402. var mapping = this._generatedMappings[index];
  9403. // Mappings do not contain a field for the last generated columnt. We
  9404. // can come up with an optimistic estimate, however, by assuming that
  9405. // mappings are contiguous (i.e. given two consecutive mappings, the
  9406. // first mapping ends where the second one starts).
  9407. if (index + 1 < this._generatedMappings.length) {
  9408. var nextMapping = this._generatedMappings[index + 1];
  9409. if (mapping.generatedLine === nextMapping.generatedLine) {
  9410. mapping.lastGeneratedColumn = nextMapping.generatedColumn - 1;
  9411. continue;
  9412. }
  9413. }
  9414. // The last mapping for each line spans the entire line.
  9415. mapping.lastGeneratedColumn = Infinity;
  9416. }
  9417. };
  9418. /**
  9419. * Returns the original source, line, and column information for the generated
  9420. * source's line and column positions provided. The only argument is an object
  9421. * with the following properties:
  9422. *
  9423. * - line: The line number in the generated source. The line number
  9424. * is 1-based.
  9425. * - column: The column number in the generated source. The column
  9426. * number is 0-based.
  9427. * - bias: Either 'SourceMapConsumer.GREATEST_LOWER_BOUND' or
  9428. * 'SourceMapConsumer.LEAST_UPPER_BOUND'. Specifies whether to return the
  9429. * closest element that is smaller than or greater than the one we are
  9430. * searching for, respectively, if the exact element cannot be found.
  9431. * Defaults to 'SourceMapConsumer.GREATEST_LOWER_BOUND'.
  9432. *
  9433. * and an object is returned with the following properties:
  9434. *
  9435. * - source: The original source file, or null.
  9436. * - line: The line number in the original source, or null. The
  9437. * line number is 1-based.
  9438. * - column: The column number in the original source, or null. The
  9439. * column number is 0-based.
  9440. * - name: The original identifier, or null.
  9441. */
  9442. BasicSourceMapConsumer.prototype.originalPositionFor =
  9443. function SourceMapConsumer_originalPositionFor(aArgs) {
  9444. var needle = {
  9445. generatedLine: util$1.getArg(aArgs, 'line'),
  9446. generatedColumn: util$1.getArg(aArgs, 'column')
  9447. };
  9448. var index = this._findMapping(
  9449. needle,
  9450. this._generatedMappings,
  9451. "generatedLine",
  9452. "generatedColumn",
  9453. util$1.compareByGeneratedPositionsDeflated,
  9454. util$1.getArg(aArgs, 'bias', SourceMapConsumer$1.GREATEST_LOWER_BOUND)
  9455. );
  9456. if (index >= 0) {
  9457. var mapping = this._generatedMappings[index];
  9458. if (mapping.generatedLine === needle.generatedLine) {
  9459. var source = util$1.getArg(mapping, 'source', null);
  9460. if (source !== null) {
  9461. source = this._sources.at(source);
  9462. source = util$1.computeSourceURL(this.sourceRoot, source, this._sourceMapURL);
  9463. }
  9464. var name = util$1.getArg(mapping, 'name', null);
  9465. if (name !== null) {
  9466. name = this._names.at(name);
  9467. }
  9468. return {
  9469. source: source,
  9470. line: util$1.getArg(mapping, 'originalLine', null),
  9471. column: util$1.getArg(mapping, 'originalColumn', null),
  9472. name: name
  9473. };
  9474. }
  9475. }
  9476. return {
  9477. source: null,
  9478. line: null,
  9479. column: null,
  9480. name: null
  9481. };
  9482. };
  9483. /**
  9484. * Return true if we have the source content for every source in the source
  9485. * map, false otherwise.
  9486. */
  9487. BasicSourceMapConsumer.prototype.hasContentsOfAllSources =
  9488. function BasicSourceMapConsumer_hasContentsOfAllSources() {
  9489. if (!this.sourcesContent) {
  9490. return false;
  9491. }
  9492. return this.sourcesContent.length >= this._sources.size() &&
  9493. !this.sourcesContent.some(function (sc) { return sc == null; });
  9494. };
  9495. /**
  9496. * Returns the original source content. The only argument is the url of the
  9497. * original source file. Returns null if no original source content is
  9498. * available.
  9499. */
  9500. BasicSourceMapConsumer.prototype.sourceContentFor =
  9501. function SourceMapConsumer_sourceContentFor(aSource, nullOnMissing) {
  9502. if (!this.sourcesContent) {
  9503. return null;
  9504. }
  9505. var index = this._findSourceIndex(aSource);
  9506. if (index >= 0) {
  9507. return this.sourcesContent[index];
  9508. }
  9509. var relativeSource = aSource;
  9510. if (this.sourceRoot != null) {
  9511. relativeSource = util$1.relative(this.sourceRoot, relativeSource);
  9512. }
  9513. var url;
  9514. if (this.sourceRoot != null
  9515. && (url = util$1.urlParse(this.sourceRoot))) {
  9516. // XXX: file:// URIs and absolute paths lead to unexpected behavior for
  9517. // many users. We can help them out when they expect file:// URIs to
  9518. // behave like it would if they were running a local HTTP server. See
  9519. // https://bugzilla.mozilla.org/show_bug.cgi?id=885597.
  9520. var fileUriAbsPath = relativeSource.replace(/^file:\/\//, "");
  9521. if (url.scheme == "file"
  9522. && this._sources.has(fileUriAbsPath)) {
  9523. return this.sourcesContent[this._sources.indexOf(fileUriAbsPath)]
  9524. }
  9525. if ((!url.path || url.path == "/")
  9526. && this._sources.has("/" + relativeSource)) {
  9527. return this.sourcesContent[this._sources.indexOf("/" + relativeSource)];
  9528. }
  9529. }
  9530. // This function is used recursively from
  9531. // IndexedSourceMapConsumer.prototype.sourceContentFor. In that case, we
  9532. // don't want to throw if we can't find the source - we just want to
  9533. // return null, so we provide a flag to exit gracefully.
  9534. if (nullOnMissing) {
  9535. return null;
  9536. }
  9537. else {
  9538. throw new Error('"' + relativeSource + '" is not in the SourceMap.');
  9539. }
  9540. };
  9541. /**
  9542. * Returns the generated line and column information for the original source,
  9543. * line, and column positions provided. The only argument is an object with
  9544. * the following properties:
  9545. *
  9546. * - source: The filename of the original source.
  9547. * - line: The line number in the original source. The line number
  9548. * is 1-based.
  9549. * - column: The column number in the original source. The column
  9550. * number is 0-based.
  9551. * - bias: Either 'SourceMapConsumer.GREATEST_LOWER_BOUND' or
  9552. * 'SourceMapConsumer.LEAST_UPPER_BOUND'. Specifies whether to return the
  9553. * closest element that is smaller than or greater than the one we are
  9554. * searching for, respectively, if the exact element cannot be found.
  9555. * Defaults to 'SourceMapConsumer.GREATEST_LOWER_BOUND'.
  9556. *
  9557. * and an object is returned with the following properties:
  9558. *
  9559. * - line: The line number in the generated source, or null. The
  9560. * line number is 1-based.
  9561. * - column: The column number in the generated source, or null.
  9562. * The column number is 0-based.
  9563. */
  9564. BasicSourceMapConsumer.prototype.generatedPositionFor =
  9565. function SourceMapConsumer_generatedPositionFor(aArgs) {
  9566. var source = util$1.getArg(aArgs, 'source');
  9567. source = this._findSourceIndex(source);
  9568. if (source < 0) {
  9569. return {
  9570. line: null,
  9571. column: null,
  9572. lastColumn: null
  9573. };
  9574. }
  9575. var needle = {
  9576. source: source,
  9577. originalLine: util$1.getArg(aArgs, 'line'),
  9578. originalColumn: util$1.getArg(aArgs, 'column')
  9579. };
  9580. var index = this._findMapping(
  9581. needle,
  9582. this._originalMappings,
  9583. "originalLine",
  9584. "originalColumn",
  9585. util$1.compareByOriginalPositions,
  9586. util$1.getArg(aArgs, 'bias', SourceMapConsumer$1.GREATEST_LOWER_BOUND)
  9587. );
  9588. if (index >= 0) {
  9589. var mapping = this._originalMappings[index];
  9590. if (mapping.source === needle.source) {
  9591. return {
  9592. line: util$1.getArg(mapping, 'generatedLine', null),
  9593. column: util$1.getArg(mapping, 'generatedColumn', null),
  9594. lastColumn: util$1.getArg(mapping, 'lastGeneratedColumn', null)
  9595. };
  9596. }
  9597. }
  9598. return {
  9599. line: null,
  9600. column: null,
  9601. lastColumn: null
  9602. };
  9603. };
  9604. sourceMapConsumer.BasicSourceMapConsumer = BasicSourceMapConsumer;
  9605. /**
  9606. * An IndexedSourceMapConsumer instance represents a parsed source map which
  9607. * we can query for information. It differs from BasicSourceMapConsumer in
  9608. * that it takes "indexed" source maps (i.e. ones with a "sections" field) as
  9609. * input.
  9610. *
  9611. * The first parameter is a raw source map (either as a JSON string, or already
  9612. * parsed to an object). According to the spec for indexed source maps, they
  9613. * have the following attributes:
  9614. *
  9615. * - version: Which version of the source map spec this map is following.
  9616. * - file: Optional. The generated file this source map is associated with.
  9617. * - sections: A list of section definitions.
  9618. *
  9619. * Each value under the "sections" field has two fields:
  9620. * - offset: The offset into the original specified at which this section
  9621. * begins to apply, defined as an object with a "line" and "column"
  9622. * field.
  9623. * - map: A source map definition. This source map could also be indexed,
  9624. * but doesn't have to be.
  9625. *
  9626. * Instead of the "map" field, it's also possible to have a "url" field
  9627. * specifying a URL to retrieve a source map from, but that's currently
  9628. * unsupported.
  9629. *
  9630. * Here's an example source map, taken from the source map spec[0], but
  9631. * modified to omit a section which uses the "url" field.
  9632. *
  9633. * {
  9634. * version : 3,
  9635. * file: "app.js",
  9636. * sections: [{
  9637. * offset: {line:100, column:10},
  9638. * map: {
  9639. * version : 3,
  9640. * file: "section.js",
  9641. * sources: ["foo.js", "bar.js"],
  9642. * names: ["src", "maps", "are", "fun"],
  9643. * mappings: "AAAA,E;;ABCDE;"
  9644. * }
  9645. * }],
  9646. * }
  9647. *
  9648. * The second parameter, if given, is a string whose value is the URL
  9649. * at which the source map was found. This URL is used to compute the
  9650. * sources array.
  9651. *
  9652. * [0]: https://docs.google.com/document/d/1U1RGAehQwRypUTovF1KRlpiOFze0b-_2gc6fAH0KY0k/edit#heading=h.535es3xeprgt
  9653. */
  9654. function IndexedSourceMapConsumer(aSourceMap, aSourceMapURL) {
  9655. var sourceMap = aSourceMap;
  9656. if (typeof aSourceMap === 'string') {
  9657. sourceMap = util$1.parseSourceMapInput(aSourceMap);
  9658. }
  9659. var version = util$1.getArg(sourceMap, 'version');
  9660. var sections = util$1.getArg(sourceMap, 'sections');
  9661. if (version != this._version) {
  9662. throw new Error('Unsupported version: ' + version);
  9663. }
  9664. this._sources = new ArraySet();
  9665. this._names = new ArraySet();
  9666. var lastOffset = {
  9667. line: -1,
  9668. column: 0
  9669. };
  9670. this._sections = sections.map(function (s) {
  9671. if (s.url) {
  9672. // The url field will require support for asynchronicity.
  9673. // See https://github.com/mozilla/source-map/issues/16
  9674. throw new Error('Support for url field in sections not implemented.');
  9675. }
  9676. var offset = util$1.getArg(s, 'offset');
  9677. var offsetLine = util$1.getArg(offset, 'line');
  9678. var offsetColumn = util$1.getArg(offset, 'column');
  9679. if (offsetLine < lastOffset.line ||
  9680. (offsetLine === lastOffset.line && offsetColumn < lastOffset.column)) {
  9681. throw new Error('Section offsets must be ordered and non-overlapping.');
  9682. }
  9683. lastOffset = offset;
  9684. return {
  9685. generatedOffset: {
  9686. // The offset fields are 0-based, but we use 1-based indices when
  9687. // encoding/decoding from VLQ.
  9688. generatedLine: offsetLine + 1,
  9689. generatedColumn: offsetColumn + 1
  9690. },
  9691. consumer: new SourceMapConsumer$1(util$1.getArg(s, 'map'), aSourceMapURL)
  9692. }
  9693. });
  9694. }
  9695. IndexedSourceMapConsumer.prototype = Object.create(SourceMapConsumer$1.prototype);
  9696. IndexedSourceMapConsumer.prototype.constructor = SourceMapConsumer$1;
  9697. /**
  9698. * The version of the source mapping spec that we are consuming.
  9699. */
  9700. IndexedSourceMapConsumer.prototype._version = 3;
  9701. /**
  9702. * The list of original sources.
  9703. */
  9704. Object.defineProperty(IndexedSourceMapConsumer.prototype, 'sources', {
  9705. get: function () {
  9706. var sources = [];
  9707. for (var i = 0; i < this._sections.length; i++) {
  9708. for (var j = 0; j < this._sections[i].consumer.sources.length; j++) {
  9709. sources.push(this._sections[i].consumer.sources[j]);
  9710. }
  9711. }
  9712. return sources;
  9713. }
  9714. });
  9715. /**
  9716. * Returns the original source, line, and column information for the generated
  9717. * source's line and column positions provided. The only argument is an object
  9718. * with the following properties:
  9719. *
  9720. * - line: The line number in the generated source. The line number
  9721. * is 1-based.
  9722. * - column: The column number in the generated source. The column
  9723. * number is 0-based.
  9724. *
  9725. * and an object is returned with the following properties:
  9726. *
  9727. * - source: The original source file, or null.
  9728. * - line: The line number in the original source, or null. The
  9729. * line number is 1-based.
  9730. * - column: The column number in the original source, or null. The
  9731. * column number is 0-based.
  9732. * - name: The original identifier, or null.
  9733. */
  9734. IndexedSourceMapConsumer.prototype.originalPositionFor =
  9735. function IndexedSourceMapConsumer_originalPositionFor(aArgs) {
  9736. var needle = {
  9737. generatedLine: util$1.getArg(aArgs, 'line'),
  9738. generatedColumn: util$1.getArg(aArgs, 'column')
  9739. };
  9740. // Find the section containing the generated position we're trying to map
  9741. // to an original position.
  9742. var sectionIndex = binarySearch.search(needle, this._sections,
  9743. function(needle, section) {
  9744. var cmp = needle.generatedLine - section.generatedOffset.generatedLine;
  9745. if (cmp) {
  9746. return cmp;
  9747. }
  9748. return (needle.generatedColumn -
  9749. section.generatedOffset.generatedColumn);
  9750. });
  9751. var section = this._sections[sectionIndex];
  9752. if (!section) {
  9753. return {
  9754. source: null,
  9755. line: null,
  9756. column: null,
  9757. name: null
  9758. };
  9759. }
  9760. return section.consumer.originalPositionFor({
  9761. line: needle.generatedLine -
  9762. (section.generatedOffset.generatedLine - 1),
  9763. column: needle.generatedColumn -
  9764. (section.generatedOffset.generatedLine === needle.generatedLine
  9765. ? section.generatedOffset.generatedColumn - 1
  9766. : 0),
  9767. bias: aArgs.bias
  9768. });
  9769. };
  9770. /**
  9771. * Return true if we have the source content for every source in the source
  9772. * map, false otherwise.
  9773. */
  9774. IndexedSourceMapConsumer.prototype.hasContentsOfAllSources =
  9775. function IndexedSourceMapConsumer_hasContentsOfAllSources() {
  9776. return this._sections.every(function (s) {
  9777. return s.consumer.hasContentsOfAllSources();
  9778. });
  9779. };
  9780. /**
  9781. * Returns the original source content. The only argument is the url of the
  9782. * original source file. Returns null if no original source content is
  9783. * available.
  9784. */
  9785. IndexedSourceMapConsumer.prototype.sourceContentFor =
  9786. function IndexedSourceMapConsumer_sourceContentFor(aSource, nullOnMissing) {
  9787. for (var i = 0; i < this._sections.length; i++) {
  9788. var section = this._sections[i];
  9789. var content = section.consumer.sourceContentFor(aSource, true);
  9790. if (content) {
  9791. return content;
  9792. }
  9793. }
  9794. if (nullOnMissing) {
  9795. return null;
  9796. }
  9797. else {
  9798. throw new Error('"' + aSource + '" is not in the SourceMap.');
  9799. }
  9800. };
  9801. /**
  9802. * Returns the generated line and column information for the original source,
  9803. * line, and column positions provided. The only argument is an object with
  9804. * the following properties:
  9805. *
  9806. * - source: The filename of the original source.
  9807. * - line: The line number in the original source. The line number
  9808. * is 1-based.
  9809. * - column: The column number in the original source. The column
  9810. * number is 0-based.
  9811. *
  9812. * and an object is returned with the following properties:
  9813. *
  9814. * - line: The line number in the generated source, or null. The
  9815. * line number is 1-based.
  9816. * - column: The column number in the generated source, or null.
  9817. * The column number is 0-based.
  9818. */
  9819. IndexedSourceMapConsumer.prototype.generatedPositionFor =
  9820. function IndexedSourceMapConsumer_generatedPositionFor(aArgs) {
  9821. for (var i = 0; i < this._sections.length; i++) {
  9822. var section = this._sections[i];
  9823. // Only consider this section if the requested source is in the list of
  9824. // sources of the consumer.
  9825. if (section.consumer._findSourceIndex(util$1.getArg(aArgs, 'source')) === -1) {
  9826. continue;
  9827. }
  9828. var generatedPosition = section.consumer.generatedPositionFor(aArgs);
  9829. if (generatedPosition) {
  9830. var ret = {
  9831. line: generatedPosition.line +
  9832. (section.generatedOffset.generatedLine - 1),
  9833. column: generatedPosition.column +
  9834. (section.generatedOffset.generatedLine === generatedPosition.line
  9835. ? section.generatedOffset.generatedColumn - 1
  9836. : 0)
  9837. };
  9838. return ret;
  9839. }
  9840. }
  9841. return {
  9842. line: null,
  9843. column: null
  9844. };
  9845. };
  9846. /**
  9847. * Parse the mappings in a string in to a data structure which we can easily
  9848. * query (the ordered arrays in the `this.__generatedMappings` and
  9849. * `this.__originalMappings` properties).
  9850. */
  9851. IndexedSourceMapConsumer.prototype._parseMappings =
  9852. function IndexedSourceMapConsumer_parseMappings(aStr, aSourceRoot) {
  9853. this.__generatedMappings = [];
  9854. this.__originalMappings = [];
  9855. for (var i = 0; i < this._sections.length; i++) {
  9856. var section = this._sections[i];
  9857. var sectionMappings = section.consumer._generatedMappings;
  9858. for (var j = 0; j < sectionMappings.length; j++) {
  9859. var mapping = sectionMappings[j];
  9860. var source = section.consumer._sources.at(mapping.source);
  9861. source = util$1.computeSourceURL(section.consumer.sourceRoot, source, this._sourceMapURL);
  9862. this._sources.add(source);
  9863. source = this._sources.indexOf(source);
  9864. var name = null;
  9865. if (mapping.name) {
  9866. name = section.consumer._names.at(mapping.name);
  9867. this._names.add(name);
  9868. name = this._names.indexOf(name);
  9869. }
  9870. // The mappings coming from the consumer for the section have
  9871. // generated positions relative to the start of the section, so we
  9872. // need to offset them to be relative to the start of the concatenated
  9873. // generated file.
  9874. var adjustedMapping = {
  9875. source: source,
  9876. generatedLine: mapping.generatedLine +
  9877. (section.generatedOffset.generatedLine - 1),
  9878. generatedColumn: mapping.generatedColumn +
  9879. (section.generatedOffset.generatedLine === mapping.generatedLine
  9880. ? section.generatedOffset.generatedColumn - 1
  9881. : 0),
  9882. originalLine: mapping.originalLine,
  9883. originalColumn: mapping.originalColumn,
  9884. name: name
  9885. };
  9886. this.__generatedMappings.push(adjustedMapping);
  9887. if (typeof adjustedMapping.originalLine === 'number') {
  9888. this.__originalMappings.push(adjustedMapping);
  9889. }
  9890. }
  9891. }
  9892. quickSort(this.__generatedMappings, util$1.compareByGeneratedPositionsDeflated);
  9893. quickSort(this.__originalMappings, util$1.compareByOriginalPositions);
  9894. };
  9895. sourceMapConsumer.IndexedSourceMapConsumer = IndexedSourceMapConsumer;
  9896. var sourceNode = {};
  9897. /* -*- Mode: js; js-indent-level: 2; -*- */
  9898. /*
  9899. * Copyright 2011 Mozilla Foundation and contributors
  9900. * Licensed under the New BSD license. See LICENSE or:
  9901. * http://opensource.org/licenses/BSD-3-Clause
  9902. */
  9903. var SourceMapGenerator$1 = sourceMapGenerator.SourceMapGenerator;
  9904. var util = util$5;
  9905. // Matches a Windows-style `\r\n` newline or a `\n` newline used by all other
  9906. // operating systems these days (capturing the result).
  9907. var REGEX_NEWLINE = /(\r?\n)/;
  9908. // Newline character code for charCodeAt() comparisons
  9909. var NEWLINE_CODE = 10;
  9910. // Private symbol for identifying `SourceNode`s when multiple versions of
  9911. // the source-map library are loaded. This MUST NOT CHANGE across
  9912. // versions!
  9913. var isSourceNode = "$$$isSourceNode$$$";
  9914. /**
  9915. * SourceNodes provide a way to abstract over interpolating/concatenating
  9916. * snippets of generated JavaScript source code while maintaining the line and
  9917. * column information associated with the original source code.
  9918. *
  9919. * @param aLine The original line number.
  9920. * @param aColumn The original column number.
  9921. * @param aSource The original source's filename.
  9922. * @param aChunks Optional. An array of strings which are snippets of
  9923. * generated JS, or other SourceNodes.
  9924. * @param aName The original identifier.
  9925. */
  9926. function SourceNode(aLine, aColumn, aSource, aChunks, aName) {
  9927. this.children = [];
  9928. this.sourceContents = {};
  9929. this.line = aLine == null ? null : aLine;
  9930. this.column = aColumn == null ? null : aColumn;
  9931. this.source = aSource == null ? null : aSource;
  9932. this.name = aName == null ? null : aName;
  9933. this[isSourceNode] = true;
  9934. if (aChunks != null) this.add(aChunks);
  9935. }
  9936. /**
  9937. * Creates a SourceNode from generated code and a SourceMapConsumer.
  9938. *
  9939. * @param aGeneratedCode The generated code
  9940. * @param aSourceMapConsumer The SourceMap for the generated code
  9941. * @param aRelativePath Optional. The path that relative sources in the
  9942. * SourceMapConsumer should be relative to.
  9943. */
  9944. SourceNode.fromStringWithSourceMap =
  9945. function SourceNode_fromStringWithSourceMap(aGeneratedCode, aSourceMapConsumer, aRelativePath) {
  9946. // The SourceNode we want to fill with the generated code
  9947. // and the SourceMap
  9948. var node = new SourceNode();
  9949. // All even indices of this array are one line of the generated code,
  9950. // while all odd indices are the newlines between two adjacent lines
  9951. // (since `REGEX_NEWLINE` captures its match).
  9952. // Processed fragments are accessed by calling `shiftNextLine`.
  9953. var remainingLines = aGeneratedCode.split(REGEX_NEWLINE);
  9954. var remainingLinesIndex = 0;
  9955. var shiftNextLine = function() {
  9956. var lineContents = getNextLine();
  9957. // The last line of a file might not have a newline.
  9958. var newLine = getNextLine() || "";
  9959. return lineContents + newLine;
  9960. function getNextLine() {
  9961. return remainingLinesIndex < remainingLines.length ?
  9962. remainingLines[remainingLinesIndex++] : undefined;
  9963. }
  9964. };
  9965. // We need to remember the position of "remainingLines"
  9966. var lastGeneratedLine = 1, lastGeneratedColumn = 0;
  9967. // The generate SourceNodes we need a code range.
  9968. // To extract it current and last mapping is used.
  9969. // Here we store the last mapping.
  9970. var lastMapping = null;
  9971. aSourceMapConsumer.eachMapping(function (mapping) {
  9972. if (lastMapping !== null) {
  9973. // We add the code from "lastMapping" to "mapping":
  9974. // First check if there is a new line in between.
  9975. if (lastGeneratedLine < mapping.generatedLine) {
  9976. // Associate first line with "lastMapping"
  9977. addMappingWithCode(lastMapping, shiftNextLine());
  9978. lastGeneratedLine++;
  9979. lastGeneratedColumn = 0;
  9980. // The remaining code is added without mapping
  9981. } else {
  9982. // There is no new line in between.
  9983. // Associate the code between "lastGeneratedColumn" and
  9984. // "mapping.generatedColumn" with "lastMapping"
  9985. var nextLine = remainingLines[remainingLinesIndex] || '';
  9986. var code = nextLine.substr(0, mapping.generatedColumn -
  9987. lastGeneratedColumn);
  9988. remainingLines[remainingLinesIndex] = nextLine.substr(mapping.generatedColumn -
  9989. lastGeneratedColumn);
  9990. lastGeneratedColumn = mapping.generatedColumn;
  9991. addMappingWithCode(lastMapping, code);
  9992. // No more remaining code, continue
  9993. lastMapping = mapping;
  9994. return;
  9995. }
  9996. }
  9997. // We add the generated code until the first mapping
  9998. // to the SourceNode without any mapping.
  9999. // Each line is added as separate string.
  10000. while (lastGeneratedLine < mapping.generatedLine) {
  10001. node.add(shiftNextLine());
  10002. lastGeneratedLine++;
  10003. }
  10004. if (lastGeneratedColumn < mapping.generatedColumn) {
  10005. var nextLine = remainingLines[remainingLinesIndex] || '';
  10006. node.add(nextLine.substr(0, mapping.generatedColumn));
  10007. remainingLines[remainingLinesIndex] = nextLine.substr(mapping.generatedColumn);
  10008. lastGeneratedColumn = mapping.generatedColumn;
  10009. }
  10010. lastMapping = mapping;
  10011. }, this);
  10012. // We have processed all mappings.
  10013. if (remainingLinesIndex < remainingLines.length) {
  10014. if (lastMapping) {
  10015. // Associate the remaining code in the current line with "lastMapping"
  10016. addMappingWithCode(lastMapping, shiftNextLine());
  10017. }
  10018. // and add the remaining lines without any mapping
  10019. node.add(remainingLines.splice(remainingLinesIndex).join(""));
  10020. }
  10021. // Copy sourcesContent into SourceNode
  10022. aSourceMapConsumer.sources.forEach(function (sourceFile) {
  10023. var content = aSourceMapConsumer.sourceContentFor(sourceFile);
  10024. if (content != null) {
  10025. if (aRelativePath != null) {
  10026. sourceFile = util.join(aRelativePath, sourceFile);
  10027. }
  10028. node.setSourceContent(sourceFile, content);
  10029. }
  10030. });
  10031. return node;
  10032. function addMappingWithCode(mapping, code) {
  10033. if (mapping === null || mapping.source === undefined) {
  10034. node.add(code);
  10035. } else {
  10036. var source = aRelativePath
  10037. ? util.join(aRelativePath, mapping.source)
  10038. : mapping.source;
  10039. node.add(new SourceNode(mapping.originalLine,
  10040. mapping.originalColumn,
  10041. source,
  10042. code,
  10043. mapping.name));
  10044. }
  10045. }
  10046. };
  10047. /**
  10048. * Add a chunk of generated JS to this source node.
  10049. *
  10050. * @param aChunk A string snippet of generated JS code, another instance of
  10051. * SourceNode, or an array where each member is one of those things.
  10052. */
  10053. SourceNode.prototype.add = function SourceNode_add(aChunk) {
  10054. if (Array.isArray(aChunk)) {
  10055. aChunk.forEach(function (chunk) {
  10056. this.add(chunk);
  10057. }, this);
  10058. }
  10059. else if (aChunk[isSourceNode] || typeof aChunk === "string") {
  10060. if (aChunk) {
  10061. this.children.push(aChunk);
  10062. }
  10063. }
  10064. else {
  10065. throw new TypeError(
  10066. "Expected a SourceNode, string, or an array of SourceNodes and strings. Got " + aChunk
  10067. );
  10068. }
  10069. return this;
  10070. };
  10071. /**
  10072. * Add a chunk of generated JS to the beginning of this source node.
  10073. *
  10074. * @param aChunk A string snippet of generated JS code, another instance of
  10075. * SourceNode, or an array where each member is one of those things.
  10076. */
  10077. SourceNode.prototype.prepend = function SourceNode_prepend(aChunk) {
  10078. if (Array.isArray(aChunk)) {
  10079. for (var i = aChunk.length-1; i >= 0; i--) {
  10080. this.prepend(aChunk[i]);
  10081. }
  10082. }
  10083. else if (aChunk[isSourceNode] || typeof aChunk === "string") {
  10084. this.children.unshift(aChunk);
  10085. }
  10086. else {
  10087. throw new TypeError(
  10088. "Expected a SourceNode, string, or an array of SourceNodes and strings. Got " + aChunk
  10089. );
  10090. }
  10091. return this;
  10092. };
  10093. /**
  10094. * Walk over the tree of JS snippets in this node and its children. The
  10095. * walking function is called once for each snippet of JS and is passed that
  10096. * snippet and the its original associated source's line/column location.
  10097. *
  10098. * @param aFn The traversal function.
  10099. */
  10100. SourceNode.prototype.walk = function SourceNode_walk(aFn) {
  10101. var chunk;
  10102. for (var i = 0, len = this.children.length; i < len; i++) {
  10103. chunk = this.children[i];
  10104. if (chunk[isSourceNode]) {
  10105. chunk.walk(aFn);
  10106. }
  10107. else {
  10108. if (chunk !== '') {
  10109. aFn(chunk, { source: this.source,
  10110. line: this.line,
  10111. column: this.column,
  10112. name: this.name });
  10113. }
  10114. }
  10115. }
  10116. };
  10117. /**
  10118. * Like `String.prototype.join` except for SourceNodes. Inserts `aStr` between
  10119. * each of `this.children`.
  10120. *
  10121. * @param aSep The separator.
  10122. */
  10123. SourceNode.prototype.join = function SourceNode_join(aSep) {
  10124. var newChildren;
  10125. var i;
  10126. var len = this.children.length;
  10127. if (len > 0) {
  10128. newChildren = [];
  10129. for (i = 0; i < len-1; i++) {
  10130. newChildren.push(this.children[i]);
  10131. newChildren.push(aSep);
  10132. }
  10133. newChildren.push(this.children[i]);
  10134. this.children = newChildren;
  10135. }
  10136. return this;
  10137. };
  10138. /**
  10139. * Call String.prototype.replace on the very right-most source snippet. Useful
  10140. * for trimming whitespace from the end of a source node, etc.
  10141. *
  10142. * @param aPattern The pattern to replace.
  10143. * @param aReplacement The thing to replace the pattern with.
  10144. */
  10145. SourceNode.prototype.replaceRight = function SourceNode_replaceRight(aPattern, aReplacement) {
  10146. var lastChild = this.children[this.children.length - 1];
  10147. if (lastChild[isSourceNode]) {
  10148. lastChild.replaceRight(aPattern, aReplacement);
  10149. }
  10150. else if (typeof lastChild === 'string') {
  10151. this.children[this.children.length - 1] = lastChild.replace(aPattern, aReplacement);
  10152. }
  10153. else {
  10154. this.children.push(''.replace(aPattern, aReplacement));
  10155. }
  10156. return this;
  10157. };
  10158. /**
  10159. * Set the source content for a source file. This will be added to the SourceMapGenerator
  10160. * in the sourcesContent field.
  10161. *
  10162. * @param aSourceFile The filename of the source file
  10163. * @param aSourceContent The content of the source file
  10164. */
  10165. SourceNode.prototype.setSourceContent =
  10166. function SourceNode_setSourceContent(aSourceFile, aSourceContent) {
  10167. this.sourceContents[util.toSetString(aSourceFile)] = aSourceContent;
  10168. };
  10169. /**
  10170. * Walk over the tree of SourceNodes. The walking function is called for each
  10171. * source file content and is passed the filename and source content.
  10172. *
  10173. * @param aFn The traversal function.
  10174. */
  10175. SourceNode.prototype.walkSourceContents =
  10176. function SourceNode_walkSourceContents(aFn) {
  10177. for (var i = 0, len = this.children.length; i < len; i++) {
  10178. if (this.children[i][isSourceNode]) {
  10179. this.children[i].walkSourceContents(aFn);
  10180. }
  10181. }
  10182. var sources = Object.keys(this.sourceContents);
  10183. for (var i = 0, len = sources.length; i < len; i++) {
  10184. aFn(util.fromSetString(sources[i]), this.sourceContents[sources[i]]);
  10185. }
  10186. };
  10187. /**
  10188. * Return the string representation of this source node. Walks over the tree
  10189. * and concatenates all the various snippets together to one string.
  10190. */
  10191. SourceNode.prototype.toString = function SourceNode_toString() {
  10192. var str = "";
  10193. this.walk(function (chunk) {
  10194. str += chunk;
  10195. });
  10196. return str;
  10197. };
  10198. /**
  10199. * Returns the string representation of this source node along with a source
  10200. * map.
  10201. */
  10202. SourceNode.prototype.toStringWithSourceMap = function SourceNode_toStringWithSourceMap(aArgs) {
  10203. var generated = {
  10204. code: "",
  10205. line: 1,
  10206. column: 0
  10207. };
  10208. var map = new SourceMapGenerator$1(aArgs);
  10209. var sourceMappingActive = false;
  10210. var lastOriginalSource = null;
  10211. var lastOriginalLine = null;
  10212. var lastOriginalColumn = null;
  10213. var lastOriginalName = null;
  10214. this.walk(function (chunk, original) {
  10215. generated.code += chunk;
  10216. if (original.source !== null
  10217. && original.line !== null
  10218. && original.column !== null) {
  10219. if(lastOriginalSource !== original.source
  10220. || lastOriginalLine !== original.line
  10221. || lastOriginalColumn !== original.column
  10222. || lastOriginalName !== original.name) {
  10223. map.addMapping({
  10224. source: original.source,
  10225. original: {
  10226. line: original.line,
  10227. column: original.column
  10228. },
  10229. generated: {
  10230. line: generated.line,
  10231. column: generated.column
  10232. },
  10233. name: original.name
  10234. });
  10235. }
  10236. lastOriginalSource = original.source;
  10237. lastOriginalLine = original.line;
  10238. lastOriginalColumn = original.column;
  10239. lastOriginalName = original.name;
  10240. sourceMappingActive = true;
  10241. } else if (sourceMappingActive) {
  10242. map.addMapping({
  10243. generated: {
  10244. line: generated.line,
  10245. column: generated.column
  10246. }
  10247. });
  10248. lastOriginalSource = null;
  10249. sourceMappingActive = false;
  10250. }
  10251. for (var idx = 0, length = chunk.length; idx < length; idx++) {
  10252. if (chunk.charCodeAt(idx) === NEWLINE_CODE) {
  10253. generated.line++;
  10254. generated.column = 0;
  10255. // Mappings end at eol
  10256. if (idx + 1 === length) {
  10257. lastOriginalSource = null;
  10258. sourceMappingActive = false;
  10259. } else if (sourceMappingActive) {
  10260. map.addMapping({
  10261. source: original.source,
  10262. original: {
  10263. line: original.line,
  10264. column: original.column
  10265. },
  10266. generated: {
  10267. line: generated.line,
  10268. column: generated.column
  10269. },
  10270. name: original.name
  10271. });
  10272. }
  10273. } else {
  10274. generated.column++;
  10275. }
  10276. }
  10277. });
  10278. this.walkSourceContents(function (sourceFile, sourceContent) {
  10279. map.setSourceContent(sourceFile, sourceContent);
  10280. });
  10281. return { code: generated.code, map: map };
  10282. };
  10283. sourceNode.SourceNode = SourceNode;
  10284. /*
  10285. * Copyright 2009-2011 Mozilla Foundation and contributors
  10286. * Licensed under the New BSD license. See LICENSE.txt or:
  10287. * http://opensource.org/licenses/BSD-3-Clause
  10288. */
  10289. sourceMap$1.SourceMapGenerator = sourceMapGenerator.SourceMapGenerator;
  10290. sourceMap$1.SourceMapConsumer = sourceMapConsumer.SourceMapConsumer;
  10291. sourceMap$1.SourceNode = sourceNode.SourceNode;
  10292. var sourceMap = sourceMap$1;
  10293. var SourceMapConsumer = sourceMap.SourceMapConsumer;
  10294. var SourceMapGenerator = sourceMap.SourceMapGenerator;
  10295. var mergeSourceMap = merge;
  10296. /**
  10297. * Merge old source map and new source map and return merged.
  10298. * If old or new source map value is falsy, return another one as it is.
  10299. *
  10300. * @param {object|string} [oldMap] old source map object
  10301. * @param {object|string} [newmap] new source map object
  10302. * @return {object|undefined} merged source map object, or undefined when both old and new source map are undefined
  10303. */
  10304. function merge(oldMap, newMap) {
  10305. if (!oldMap) return newMap
  10306. if (!newMap) return oldMap
  10307. var oldMapConsumer = new SourceMapConsumer(oldMap);
  10308. var newMapConsumer = new SourceMapConsumer(newMap);
  10309. var mergedMapGenerator = new SourceMapGenerator();
  10310. // iterate on new map and overwrite original position of new map with one of old map
  10311. newMapConsumer.eachMapping(function(m) {
  10312. // pass when `originalLine` is null.
  10313. // It occurs in case that the node does not have origin in original code.
  10314. if (m.originalLine == null) return
  10315. var origPosInOldMap = oldMapConsumer.originalPositionFor({
  10316. line: m.originalLine,
  10317. column: m.originalColumn
  10318. });
  10319. if (origPosInOldMap.source == null) return
  10320. mergedMapGenerator.addMapping({
  10321. original: {
  10322. line: origPosInOldMap.line,
  10323. column: origPosInOldMap.column
  10324. },
  10325. generated: {
  10326. line: m.generatedLine,
  10327. column: m.generatedColumn
  10328. },
  10329. source: origPosInOldMap.source,
  10330. name: origPosInOldMap.name
  10331. });
  10332. });
  10333. var consumers = [oldMapConsumer, newMapConsumer];
  10334. consumers.forEach(function(consumer) {
  10335. consumer.sources.forEach(function(sourceFile) {
  10336. mergedMapGenerator._sources.add(sourceFile);
  10337. var sourceContent = consumer.sourceContentFor(sourceFile);
  10338. if (sourceContent != null) {
  10339. mergedMapGenerator.setSourceContent(sourceFile, sourceContent);
  10340. }
  10341. });
  10342. });
  10343. mergedMapGenerator._sourceRoot = oldMap.sourceRoot;
  10344. mergedMapGenerator._file = oldMap.file;
  10345. return JSON.parse(mergedMapGenerator.toString())
  10346. }
  10347. var merge$1 = /*@__PURE__*/getDefaultExportFromCjs(mergeSourceMap);
  10348. const scss = (source, map, options, load = require) => {
  10349. const nodeSass = load("sass");
  10350. const finalOptions = {
  10351. ...options,
  10352. data: getSource(source, options.filename, options.additionalData),
  10353. file: options.filename,
  10354. outFile: options.filename,
  10355. sourceMap: !!map
  10356. };
  10357. try {
  10358. const result = nodeSass.renderSync(finalOptions);
  10359. const dependencies = result.stats.includedFiles;
  10360. if (map) {
  10361. return {
  10362. code: result.css.toString(),
  10363. map: merge$1(map, JSON.parse(result.map.toString())),
  10364. errors: [],
  10365. dependencies
  10366. };
  10367. }
  10368. return { code: result.css.toString(), errors: [], dependencies };
  10369. } catch (e) {
  10370. return { code: "", errors: [e], dependencies: [] };
  10371. }
  10372. };
  10373. const sass = (source, map, options, load) => scss(
  10374. source,
  10375. map,
  10376. {
  10377. ...options,
  10378. indentedSyntax: true
  10379. },
  10380. load
  10381. );
  10382. const less = (source, map, options, load = require) => {
  10383. const nodeLess = load("less");
  10384. let result;
  10385. let error = null;
  10386. nodeLess.render(
  10387. getSource(source, options.filename, options.additionalData),
  10388. { ...options, syncImport: true },
  10389. (err, output) => {
  10390. error = err;
  10391. result = output;
  10392. }
  10393. );
  10394. if (error)
  10395. return { code: "", errors: [error], dependencies: [] };
  10396. const dependencies = result.imports;
  10397. if (map) {
  10398. return {
  10399. code: result.css.toString(),
  10400. map: merge$1(map, result.map),
  10401. errors: [],
  10402. dependencies
  10403. };
  10404. }
  10405. return {
  10406. code: result.css.toString(),
  10407. errors: [],
  10408. dependencies
  10409. };
  10410. };
  10411. const styl = (source, map, options, load = require) => {
  10412. const nodeStylus = load("stylus");
  10413. try {
  10414. const ref = nodeStylus(source, options);
  10415. if (map)
  10416. ref.set("sourcemap", { inline: false, comment: false });
  10417. const result = ref.render();
  10418. const dependencies = ref.deps();
  10419. if (map) {
  10420. return {
  10421. code: result,
  10422. map: merge$1(map, ref.sourcemap),
  10423. errors: [],
  10424. dependencies
  10425. };
  10426. }
  10427. return { code: result, errors: [], dependencies };
  10428. } catch (e) {
  10429. return { code: "", errors: [e], dependencies: [] };
  10430. }
  10431. };
  10432. function getSource(source, filename, additionalData) {
  10433. if (!additionalData)
  10434. return source;
  10435. if (shared.isFunction(additionalData)) {
  10436. return additionalData(source, filename);
  10437. }
  10438. return additionalData + source;
  10439. }
  10440. const processors = {
  10441. less,
  10442. sass,
  10443. scss,
  10444. styl,
  10445. stylus: styl
  10446. };
  10447. var build = {exports: {}};
  10448. var fs = {};
  10449. Object.defineProperty(fs, "__esModule", {
  10450. value: true
  10451. });
  10452. fs.getFileSystem = getFileSystem;
  10453. fs.setFileSystem = setFileSystem;
  10454. let fileSystem = {
  10455. readFile: () => {
  10456. throw Error("readFile not implemented");
  10457. },
  10458. writeFile: () => {
  10459. throw Error("writeFile not implemented");
  10460. }
  10461. };
  10462. function setFileSystem(fs) {
  10463. fileSystem.readFile = fs.readFile;
  10464. fileSystem.writeFile = fs.writeFile;
  10465. }
  10466. function getFileSystem() {
  10467. return fileSystem;
  10468. }
  10469. var pluginFactory = {};
  10470. var unquote$1 = {};
  10471. Object.defineProperty(unquote$1, "__esModule", {
  10472. value: true
  10473. });
  10474. unquote$1.default = unquote;
  10475. // copied from https://github.com/lakenen/node-unquote
  10476. const reg = /['"]/;
  10477. function unquote(str) {
  10478. if (!str) {
  10479. return "";
  10480. }
  10481. if (reg.test(str.charAt(0))) {
  10482. str = str.substr(1);
  10483. }
  10484. if (reg.test(str.charAt(str.length - 1))) {
  10485. str = str.substr(0, str.length - 1);
  10486. }
  10487. return str;
  10488. }
  10489. var Parser$1 = {};
  10490. const matchValueName = /[$]?[\w-]+/g;
  10491. const replaceValueSymbols$2 = (value, replacements) => {
  10492. let matches;
  10493. while ((matches = matchValueName.exec(value))) {
  10494. const replacement = replacements[matches[0]];
  10495. if (replacement) {
  10496. value =
  10497. value.slice(0, matches.index) +
  10498. replacement +
  10499. value.slice(matchValueName.lastIndex);
  10500. matchValueName.lastIndex -= matches[0].length - replacement.length;
  10501. }
  10502. }
  10503. return value;
  10504. };
  10505. var replaceValueSymbols_1 = replaceValueSymbols$2;
  10506. const replaceValueSymbols$1 = replaceValueSymbols_1;
  10507. const replaceSymbols$1 = (css, replacements) => {
  10508. css.walk((node) => {
  10509. if (node.type === "decl" && node.value) {
  10510. node.value = replaceValueSymbols$1(node.value.toString(), replacements);
  10511. } else if (node.type === "rule" && node.selector) {
  10512. node.selector = replaceValueSymbols$1(
  10513. node.selector.toString(),
  10514. replacements
  10515. );
  10516. } else if (node.type === "atrule" && node.params) {
  10517. node.params = replaceValueSymbols$1(node.params.toString(), replacements);
  10518. }
  10519. });
  10520. };
  10521. var replaceSymbols_1 = replaceSymbols$1;
  10522. const importPattern = /^:import\(("[^"]*"|'[^']*'|[^"']+)\)$/;
  10523. const balancedQuotes = /^("[^"]*"|'[^']*'|[^"']+)$/;
  10524. const getDeclsObject = (rule) => {
  10525. const object = {};
  10526. rule.walkDecls((decl) => {
  10527. const before = decl.raws.before ? decl.raws.before.trim() : "";
  10528. object[before + decl.prop] = decl.value;
  10529. });
  10530. return object;
  10531. };
  10532. /**
  10533. *
  10534. * @param {string} css
  10535. * @param {boolean} removeRules
  10536. * @param {'auto' | 'rule' | 'at-rule'} mode
  10537. */
  10538. const extractICSS$2 = (css, removeRules = true, mode = "auto") => {
  10539. const icssImports = {};
  10540. const icssExports = {};
  10541. function addImports(node, path) {
  10542. const unquoted = path.replace(/'|"/g, "");
  10543. icssImports[unquoted] = Object.assign(
  10544. icssImports[unquoted] || {},
  10545. getDeclsObject(node)
  10546. );
  10547. if (removeRules) {
  10548. node.remove();
  10549. }
  10550. }
  10551. function addExports(node) {
  10552. Object.assign(icssExports, getDeclsObject(node));
  10553. if (removeRules) {
  10554. node.remove();
  10555. }
  10556. }
  10557. css.each((node) => {
  10558. if (node.type === "rule" && mode !== "at-rule") {
  10559. if (node.selector.slice(0, 7) === ":import") {
  10560. const matches = importPattern.exec(node.selector);
  10561. if (matches) {
  10562. addImports(node, matches[1]);
  10563. }
  10564. }
  10565. if (node.selector === ":export") {
  10566. addExports(node);
  10567. }
  10568. }
  10569. if (node.type === "atrule" && mode !== "rule") {
  10570. if (node.name === "icss-import") {
  10571. const matches = balancedQuotes.exec(node.params);
  10572. if (matches) {
  10573. addImports(node, matches[1]);
  10574. }
  10575. }
  10576. if (node.name === "icss-export") {
  10577. addExports(node);
  10578. }
  10579. }
  10580. });
  10581. return { icssImports, icssExports };
  10582. };
  10583. var extractICSS_1 = extractICSS$2;
  10584. const createImports = (imports, postcss, mode = "rule") => {
  10585. return Object.keys(imports).map((path) => {
  10586. const aliases = imports[path];
  10587. const declarations = Object.keys(aliases).map((key) =>
  10588. postcss.decl({
  10589. prop: key,
  10590. value: aliases[key],
  10591. raws: { before: "\n " },
  10592. })
  10593. );
  10594. const hasDeclarations = declarations.length > 0;
  10595. const rule =
  10596. mode === "rule"
  10597. ? postcss.rule({
  10598. selector: `:import('${path}')`,
  10599. raws: { after: hasDeclarations ? "\n" : "" },
  10600. })
  10601. : postcss.atRule({
  10602. name: "icss-import",
  10603. params: `'${path}'`,
  10604. raws: { after: hasDeclarations ? "\n" : "" },
  10605. });
  10606. if (hasDeclarations) {
  10607. rule.append(declarations);
  10608. }
  10609. return rule;
  10610. });
  10611. };
  10612. const createExports = (exports, postcss, mode = "rule") => {
  10613. const declarations = Object.keys(exports).map((key) =>
  10614. postcss.decl({
  10615. prop: key,
  10616. value: exports[key],
  10617. raws: { before: "\n " },
  10618. })
  10619. );
  10620. if (declarations.length === 0) {
  10621. return [];
  10622. }
  10623. const rule =
  10624. mode === "rule"
  10625. ? postcss.rule({
  10626. selector: `:export`,
  10627. raws: { after: "\n" },
  10628. })
  10629. : postcss.atRule({
  10630. name: "icss-export",
  10631. raws: { after: "\n" },
  10632. });
  10633. rule.append(declarations);
  10634. return [rule];
  10635. };
  10636. const createICSSRules$1 = (imports, exports, postcss, mode) => [
  10637. ...createImports(imports, postcss, mode),
  10638. ...createExports(exports, postcss, mode),
  10639. ];
  10640. var createICSSRules_1 = createICSSRules$1;
  10641. const replaceValueSymbols = replaceValueSymbols_1;
  10642. const replaceSymbols = replaceSymbols_1;
  10643. const extractICSS$1 = extractICSS_1;
  10644. const createICSSRules = createICSSRules_1;
  10645. var src$4 = {
  10646. replaceValueSymbols,
  10647. replaceSymbols,
  10648. extractICSS: extractICSS$1,
  10649. createICSSRules,
  10650. };
  10651. Object.defineProperty(Parser$1, "__esModule", {
  10652. value: true
  10653. });
  10654. Parser$1.default = void 0;
  10655. var _icssUtils = src$4;
  10656. // Initially copied from https://github.com/css-modules/css-modules-loader-core
  10657. const importRegexp = /^:import\((.+)\)$/;
  10658. class Parser {
  10659. constructor(pathFetcher, trace) {
  10660. this.pathFetcher = pathFetcher;
  10661. this.plugin = this.plugin.bind(this);
  10662. this.exportTokens = {};
  10663. this.translations = {};
  10664. this.trace = trace;
  10665. }
  10666. plugin() {
  10667. const parser = this;
  10668. return {
  10669. postcssPlugin: "css-modules-parser",
  10670. async OnceExit(css) {
  10671. await Promise.all(parser.fetchAllImports(css));
  10672. parser.linkImportedSymbols(css);
  10673. return parser.extractExports(css);
  10674. }
  10675. };
  10676. }
  10677. fetchAllImports(css) {
  10678. let imports = [];
  10679. css.each(node => {
  10680. if (node.type == "rule" && node.selector.match(importRegexp)) {
  10681. imports.push(this.fetchImport(node, css.source.input.from, imports.length));
  10682. }
  10683. });
  10684. return imports;
  10685. }
  10686. linkImportedSymbols(css) {
  10687. (0, _icssUtils.replaceSymbols)(css, this.translations);
  10688. }
  10689. extractExports(css) {
  10690. css.each(node => {
  10691. if (node.type == "rule" && node.selector == ":export") this.handleExport(node);
  10692. });
  10693. }
  10694. handleExport(exportNode) {
  10695. exportNode.each(decl => {
  10696. if (decl.type == "decl") {
  10697. Object.keys(this.translations).forEach(translation => {
  10698. decl.value = decl.value.replace(translation, this.translations[translation]);
  10699. });
  10700. this.exportTokens[decl.prop] = decl.value;
  10701. }
  10702. });
  10703. exportNode.remove();
  10704. }
  10705. async fetchImport(importNode, relativeTo, depNr) {
  10706. const file = importNode.selector.match(importRegexp)[1];
  10707. const depTrace = this.trace + String.fromCharCode(depNr);
  10708. const exports = await this.pathFetcher(file, relativeTo, depTrace);
  10709. try {
  10710. importNode.each(decl => {
  10711. if (decl.type == "decl") {
  10712. this.translations[decl.prop] = exports[decl.value];
  10713. }
  10714. });
  10715. importNode.remove();
  10716. } catch (err) {
  10717. console.log(err);
  10718. }
  10719. }
  10720. }
  10721. Parser$1.default = Parser;
  10722. var saveJSON$1 = {};
  10723. Object.defineProperty(saveJSON$1, "__esModule", {
  10724. value: true
  10725. });
  10726. saveJSON$1.default = saveJSON;
  10727. var _fs$2 = fs;
  10728. function saveJSON(cssFile, json) {
  10729. return new Promise((resolve, reject) => {
  10730. const {
  10731. writeFile
  10732. } = (0, _fs$2.getFileSystem)();
  10733. writeFile(`${cssFile}.json`, JSON.stringify(json), e => e ? reject(e) : resolve(json));
  10734. });
  10735. }
  10736. var localsConvention = {};
  10737. /**
  10738. * lodash (Custom Build) <https://lodash.com/>
  10739. * Build: `lodash modularize exports="npm" -o ./`
  10740. * Copyright jQuery Foundation and other contributors <https://jquery.org/>
  10741. * Released under MIT license <https://lodash.com/license>
  10742. * Based on Underscore.js 1.8.3 <http://underscorejs.org/LICENSE>
  10743. * Copyright Jeremy Ashkenas, DocumentCloud and Investigative Reporters & Editors
  10744. */
  10745. /** Used as references for various `Number` constants. */
  10746. var INFINITY = 1 / 0;
  10747. /** `Object#toString` result references. */
  10748. var symbolTag = '[object Symbol]';
  10749. /** Used to match words composed of alphanumeric characters. */
  10750. var reAsciiWord = /[^\x00-\x2f\x3a-\x40\x5b-\x60\x7b-\x7f]+/g;
  10751. /** Used to match Latin Unicode letters (excluding mathematical operators). */
  10752. var reLatin = /[\xc0-\xd6\xd8-\xf6\xf8-\xff\u0100-\u017f]/g;
  10753. /** Used to compose unicode character classes. */
  10754. var rsAstralRange = '\\ud800-\\udfff',
  10755. rsComboMarksRange = '\\u0300-\\u036f\\ufe20-\\ufe23',
  10756. rsComboSymbolsRange = '\\u20d0-\\u20f0',
  10757. rsDingbatRange = '\\u2700-\\u27bf',
  10758. rsLowerRange = 'a-z\\xdf-\\xf6\\xf8-\\xff',
  10759. rsMathOpRange = '\\xac\\xb1\\xd7\\xf7',
  10760. rsNonCharRange = '\\x00-\\x2f\\x3a-\\x40\\x5b-\\x60\\x7b-\\xbf',
  10761. rsPunctuationRange = '\\u2000-\\u206f',
  10762. 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',
  10763. rsUpperRange = 'A-Z\\xc0-\\xd6\\xd8-\\xde',
  10764. rsVarRange = '\\ufe0e\\ufe0f',
  10765. rsBreakRange = rsMathOpRange + rsNonCharRange + rsPunctuationRange + rsSpaceRange;
  10766. /** Used to compose unicode capture groups. */
  10767. var rsApos = "['\u2019]",
  10768. rsAstral = '[' + rsAstralRange + ']',
  10769. rsBreak = '[' + rsBreakRange + ']',
  10770. rsCombo = '[' + rsComboMarksRange + rsComboSymbolsRange + ']',
  10771. rsDigits = '\\d+',
  10772. rsDingbat = '[' + rsDingbatRange + ']',
  10773. rsLower = '[' + rsLowerRange + ']',
  10774. rsMisc = '[^' + rsAstralRange + rsBreakRange + rsDigits + rsDingbatRange + rsLowerRange + rsUpperRange + ']',
  10775. rsFitz = '\\ud83c[\\udffb-\\udfff]',
  10776. rsModifier = '(?:' + rsCombo + '|' + rsFitz + ')',
  10777. rsNonAstral = '[^' + rsAstralRange + ']',
  10778. rsRegional = '(?:\\ud83c[\\udde6-\\uddff]){2}',
  10779. rsSurrPair = '[\\ud800-\\udbff][\\udc00-\\udfff]',
  10780. rsUpper = '[' + rsUpperRange + ']',
  10781. rsZWJ = '\\u200d';
  10782. /** Used to compose unicode regexes. */
  10783. var rsLowerMisc = '(?:' + rsLower + '|' + rsMisc + ')',
  10784. rsUpperMisc = '(?:' + rsUpper + '|' + rsMisc + ')',
  10785. rsOptLowerContr = '(?:' + rsApos + '(?:d|ll|m|re|s|t|ve))?',
  10786. rsOptUpperContr = '(?:' + rsApos + '(?:D|LL|M|RE|S|T|VE))?',
  10787. reOptMod = rsModifier + '?',
  10788. rsOptVar = '[' + rsVarRange + ']?',
  10789. rsOptJoin = '(?:' + rsZWJ + '(?:' + [rsNonAstral, rsRegional, rsSurrPair].join('|') + ')' + rsOptVar + reOptMod + ')*',
  10790. rsSeq = rsOptVar + reOptMod + rsOptJoin,
  10791. rsEmoji = '(?:' + [rsDingbat, rsRegional, rsSurrPair].join('|') + ')' + rsSeq,
  10792. rsSymbol = '(?:' + [rsNonAstral + rsCombo + '?', rsCombo, rsRegional, rsSurrPair, rsAstral].join('|') + ')';
  10793. /** Used to match apostrophes. */
  10794. var reApos = RegExp(rsApos, 'g');
  10795. /**
  10796. * Used to match [combining diacritical marks](https://en.wikipedia.org/wiki/Combining_Diacritical_Marks) and
  10797. * [combining diacritical marks for symbols](https://en.wikipedia.org/wiki/Combining_Diacritical_Marks_for_Symbols).
  10798. */
  10799. var reComboMark = RegExp(rsCombo, 'g');
  10800. /** Used to match [string symbols](https://mathiasbynens.be/notes/javascript-unicode). */
  10801. var reUnicode = RegExp(rsFitz + '(?=' + rsFitz + ')|' + rsSymbol + rsSeq, 'g');
  10802. /** Used to match complex or compound words. */
  10803. var reUnicodeWord = RegExp([
  10804. rsUpper + '?' + rsLower + '+' + rsOptLowerContr + '(?=' + [rsBreak, rsUpper, '$'].join('|') + ')',
  10805. rsUpperMisc + '+' + rsOptUpperContr + '(?=' + [rsBreak, rsUpper + rsLowerMisc, '$'].join('|') + ')',
  10806. rsUpper + '?' + rsLowerMisc + '+' + rsOptLowerContr,
  10807. rsUpper + '+' + rsOptUpperContr,
  10808. rsDigits,
  10809. rsEmoji
  10810. ].join('|'), 'g');
  10811. /** 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/). */
  10812. var reHasUnicode = RegExp('[' + rsZWJ + rsAstralRange + rsComboMarksRange + rsComboSymbolsRange + rsVarRange + ']');
  10813. /** Used to detect strings that need a more robust regexp to match words. */
  10814. 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 ]/;
  10815. /** Used to map Latin Unicode letters to basic Latin letters. */
  10816. var deburredLetters = {
  10817. // Latin-1 Supplement block.
  10818. '\xc0': 'A', '\xc1': 'A', '\xc2': 'A', '\xc3': 'A', '\xc4': 'A', '\xc5': 'A',
  10819. '\xe0': 'a', '\xe1': 'a', '\xe2': 'a', '\xe3': 'a', '\xe4': 'a', '\xe5': 'a',
  10820. '\xc7': 'C', '\xe7': 'c',
  10821. '\xd0': 'D', '\xf0': 'd',
  10822. '\xc8': 'E', '\xc9': 'E', '\xca': 'E', '\xcb': 'E',
  10823. '\xe8': 'e', '\xe9': 'e', '\xea': 'e', '\xeb': 'e',
  10824. '\xcc': 'I', '\xcd': 'I', '\xce': 'I', '\xcf': 'I',
  10825. '\xec': 'i', '\xed': 'i', '\xee': 'i', '\xef': 'i',
  10826. '\xd1': 'N', '\xf1': 'n',
  10827. '\xd2': 'O', '\xd3': 'O', '\xd4': 'O', '\xd5': 'O', '\xd6': 'O', '\xd8': 'O',
  10828. '\xf2': 'o', '\xf3': 'o', '\xf4': 'o', '\xf5': 'o', '\xf6': 'o', '\xf8': 'o',
  10829. '\xd9': 'U', '\xda': 'U', '\xdb': 'U', '\xdc': 'U',
  10830. '\xf9': 'u', '\xfa': 'u', '\xfb': 'u', '\xfc': 'u',
  10831. '\xdd': 'Y', '\xfd': 'y', '\xff': 'y',
  10832. '\xc6': 'Ae', '\xe6': 'ae',
  10833. '\xde': 'Th', '\xfe': 'th',
  10834. '\xdf': 'ss',
  10835. // Latin Extended-A block.
  10836. '\u0100': 'A', '\u0102': 'A', '\u0104': 'A',
  10837. '\u0101': 'a', '\u0103': 'a', '\u0105': 'a',
  10838. '\u0106': 'C', '\u0108': 'C', '\u010a': 'C', '\u010c': 'C',
  10839. '\u0107': 'c', '\u0109': 'c', '\u010b': 'c', '\u010d': 'c',
  10840. '\u010e': 'D', '\u0110': 'D', '\u010f': 'd', '\u0111': 'd',
  10841. '\u0112': 'E', '\u0114': 'E', '\u0116': 'E', '\u0118': 'E', '\u011a': 'E',
  10842. '\u0113': 'e', '\u0115': 'e', '\u0117': 'e', '\u0119': 'e', '\u011b': 'e',
  10843. '\u011c': 'G', '\u011e': 'G', '\u0120': 'G', '\u0122': 'G',
  10844. '\u011d': 'g', '\u011f': 'g', '\u0121': 'g', '\u0123': 'g',
  10845. '\u0124': 'H', '\u0126': 'H', '\u0125': 'h', '\u0127': 'h',
  10846. '\u0128': 'I', '\u012a': 'I', '\u012c': 'I', '\u012e': 'I', '\u0130': 'I',
  10847. '\u0129': 'i', '\u012b': 'i', '\u012d': 'i', '\u012f': 'i', '\u0131': 'i',
  10848. '\u0134': 'J', '\u0135': 'j',
  10849. '\u0136': 'K', '\u0137': 'k', '\u0138': 'k',
  10850. '\u0139': 'L', '\u013b': 'L', '\u013d': 'L', '\u013f': 'L', '\u0141': 'L',
  10851. '\u013a': 'l', '\u013c': 'l', '\u013e': 'l', '\u0140': 'l', '\u0142': 'l',
  10852. '\u0143': 'N', '\u0145': 'N', '\u0147': 'N', '\u014a': 'N',
  10853. '\u0144': 'n', '\u0146': 'n', '\u0148': 'n', '\u014b': 'n',
  10854. '\u014c': 'O', '\u014e': 'O', '\u0150': 'O',
  10855. '\u014d': 'o', '\u014f': 'o', '\u0151': 'o',
  10856. '\u0154': 'R', '\u0156': 'R', '\u0158': 'R',
  10857. '\u0155': 'r', '\u0157': 'r', '\u0159': 'r',
  10858. '\u015a': 'S', '\u015c': 'S', '\u015e': 'S', '\u0160': 'S',
  10859. '\u015b': 's', '\u015d': 's', '\u015f': 's', '\u0161': 's',
  10860. '\u0162': 'T', '\u0164': 'T', '\u0166': 'T',
  10861. '\u0163': 't', '\u0165': 't', '\u0167': 't',
  10862. '\u0168': 'U', '\u016a': 'U', '\u016c': 'U', '\u016e': 'U', '\u0170': 'U', '\u0172': 'U',
  10863. '\u0169': 'u', '\u016b': 'u', '\u016d': 'u', '\u016f': 'u', '\u0171': 'u', '\u0173': 'u',
  10864. '\u0174': 'W', '\u0175': 'w',
  10865. '\u0176': 'Y', '\u0177': 'y', '\u0178': 'Y',
  10866. '\u0179': 'Z', '\u017b': 'Z', '\u017d': 'Z',
  10867. '\u017a': 'z', '\u017c': 'z', '\u017e': 'z',
  10868. '\u0132': 'IJ', '\u0133': 'ij',
  10869. '\u0152': 'Oe', '\u0153': 'oe',
  10870. '\u0149': "'n", '\u017f': 'ss'
  10871. };
  10872. /** Detect free variable `global` from Node.js. */
  10873. var freeGlobal = typeof commonjsGlobal == 'object' && commonjsGlobal && commonjsGlobal.Object === Object && commonjsGlobal;
  10874. /** Detect free variable `self`. */
  10875. var freeSelf = typeof self == 'object' && self && self.Object === Object && self;
  10876. /** Used as a reference to the global object. */
  10877. var root = freeGlobal || freeSelf || Function('return this')();
  10878. /**
  10879. * A specialized version of `_.reduce` for arrays without support for
  10880. * iteratee shorthands.
  10881. *
  10882. * @private
  10883. * @param {Array} [array] The array to iterate over.
  10884. * @param {Function} iteratee The function invoked per iteration.
  10885. * @param {*} [accumulator] The initial value.
  10886. * @param {boolean} [initAccum] Specify using the first element of `array` as
  10887. * the initial value.
  10888. * @returns {*} Returns the accumulated value.
  10889. */
  10890. function arrayReduce(array, iteratee, accumulator, initAccum) {
  10891. var index = -1,
  10892. length = array ? array.length : 0;
  10893. if (initAccum && length) {
  10894. accumulator = array[++index];
  10895. }
  10896. while (++index < length) {
  10897. accumulator = iteratee(accumulator, array[index], index, array);
  10898. }
  10899. return accumulator;
  10900. }
  10901. /**
  10902. * Converts an ASCII `string` to an array.
  10903. *
  10904. * @private
  10905. * @param {string} string The string to convert.
  10906. * @returns {Array} Returns the converted array.
  10907. */
  10908. function asciiToArray(string) {
  10909. return string.split('');
  10910. }
  10911. /**
  10912. * Splits an ASCII `string` into an array of its words.
  10913. *
  10914. * @private
  10915. * @param {string} The string to inspect.
  10916. * @returns {Array} Returns the words of `string`.
  10917. */
  10918. function asciiWords(string) {
  10919. return string.match(reAsciiWord) || [];
  10920. }
  10921. /**
  10922. * The base implementation of `_.propertyOf` without support for deep paths.
  10923. *
  10924. * @private
  10925. * @param {Object} object The object to query.
  10926. * @returns {Function} Returns the new accessor function.
  10927. */
  10928. function basePropertyOf(object) {
  10929. return function(key) {
  10930. return object == null ? undefined : object[key];
  10931. };
  10932. }
  10933. /**
  10934. * Used by `_.deburr` to convert Latin-1 Supplement and Latin Extended-A
  10935. * letters to basic Latin letters.
  10936. *
  10937. * @private
  10938. * @param {string} letter The matched letter to deburr.
  10939. * @returns {string} Returns the deburred letter.
  10940. */
  10941. var deburrLetter = basePropertyOf(deburredLetters);
  10942. /**
  10943. * Checks if `string` contains Unicode symbols.
  10944. *
  10945. * @private
  10946. * @param {string} string The string to inspect.
  10947. * @returns {boolean} Returns `true` if a symbol is found, else `false`.
  10948. */
  10949. function hasUnicode(string) {
  10950. return reHasUnicode.test(string);
  10951. }
  10952. /**
  10953. * Checks if `string` contains a word composed of Unicode symbols.
  10954. *
  10955. * @private
  10956. * @param {string} string The string to inspect.
  10957. * @returns {boolean} Returns `true` if a word is found, else `false`.
  10958. */
  10959. function hasUnicodeWord(string) {
  10960. return reHasUnicodeWord.test(string);
  10961. }
  10962. /**
  10963. * Converts `string` to an array.
  10964. *
  10965. * @private
  10966. * @param {string} string The string to convert.
  10967. * @returns {Array} Returns the converted array.
  10968. */
  10969. function stringToArray(string) {
  10970. return hasUnicode(string)
  10971. ? unicodeToArray(string)
  10972. : asciiToArray(string);
  10973. }
  10974. /**
  10975. * Converts a Unicode `string` to an array.
  10976. *
  10977. * @private
  10978. * @param {string} string The string to convert.
  10979. * @returns {Array} Returns the converted array.
  10980. */
  10981. function unicodeToArray(string) {
  10982. return string.match(reUnicode) || [];
  10983. }
  10984. /**
  10985. * Splits a Unicode `string` into an array of its words.
  10986. *
  10987. * @private
  10988. * @param {string} The string to inspect.
  10989. * @returns {Array} Returns the words of `string`.
  10990. */
  10991. function unicodeWords(string) {
  10992. return string.match(reUnicodeWord) || [];
  10993. }
  10994. /** Used for built-in method references. */
  10995. var objectProto = Object.prototype;
  10996. /**
  10997. * Used to resolve the
  10998. * [`toStringTag`](http://ecma-international.org/ecma-262/7.0/#sec-object.prototype.tostring)
  10999. * of values.
  11000. */
  11001. var objectToString = objectProto.toString;
  11002. /** Built-in value references. */
  11003. var Symbol$1 = root.Symbol;
  11004. /** Used to convert symbols to primitives and strings. */
  11005. var symbolProto = Symbol$1 ? Symbol$1.prototype : undefined,
  11006. symbolToString = symbolProto ? symbolProto.toString : undefined;
  11007. /**
  11008. * The base implementation of `_.slice` without an iteratee call guard.
  11009. *
  11010. * @private
  11011. * @param {Array} array The array to slice.
  11012. * @param {number} [start=0] The start position.
  11013. * @param {number} [end=array.length] The end position.
  11014. * @returns {Array} Returns the slice of `array`.
  11015. */
  11016. function baseSlice(array, start, end) {
  11017. var index = -1,
  11018. length = array.length;
  11019. if (start < 0) {
  11020. start = -start > length ? 0 : (length + start);
  11021. }
  11022. end = end > length ? length : end;
  11023. if (end < 0) {
  11024. end += length;
  11025. }
  11026. length = start > end ? 0 : ((end - start) >>> 0);
  11027. start >>>= 0;
  11028. var result = Array(length);
  11029. while (++index < length) {
  11030. result[index] = array[index + start];
  11031. }
  11032. return result;
  11033. }
  11034. /**
  11035. * The base implementation of `_.toString` which doesn't convert nullish
  11036. * values to empty strings.
  11037. *
  11038. * @private
  11039. * @param {*} value The value to process.
  11040. * @returns {string} Returns the string.
  11041. */
  11042. function baseToString(value) {
  11043. // Exit early for strings to avoid a performance hit in some environments.
  11044. if (typeof value == 'string') {
  11045. return value;
  11046. }
  11047. if (isSymbol(value)) {
  11048. return symbolToString ? symbolToString.call(value) : '';
  11049. }
  11050. var result = (value + '');
  11051. return (result == '0' && (1 / value) == -INFINITY) ? '-0' : result;
  11052. }
  11053. /**
  11054. * Casts `array` to a slice if it's needed.
  11055. *
  11056. * @private
  11057. * @param {Array} array The array to inspect.
  11058. * @param {number} start The start position.
  11059. * @param {number} [end=array.length] The end position.
  11060. * @returns {Array} Returns the cast slice.
  11061. */
  11062. function castSlice(array, start, end) {
  11063. var length = array.length;
  11064. end = end === undefined ? length : end;
  11065. return (!start && end >= length) ? array : baseSlice(array, start, end);
  11066. }
  11067. /**
  11068. * Creates a function like `_.lowerFirst`.
  11069. *
  11070. * @private
  11071. * @param {string} methodName The name of the `String` case method to use.
  11072. * @returns {Function} Returns the new case function.
  11073. */
  11074. function createCaseFirst(methodName) {
  11075. return function(string) {
  11076. string = toString(string);
  11077. var strSymbols = hasUnicode(string)
  11078. ? stringToArray(string)
  11079. : undefined;
  11080. var chr = strSymbols
  11081. ? strSymbols[0]
  11082. : string.charAt(0);
  11083. var trailing = strSymbols
  11084. ? castSlice(strSymbols, 1).join('')
  11085. : string.slice(1);
  11086. return chr[methodName]() + trailing;
  11087. };
  11088. }
  11089. /**
  11090. * Creates a function like `_.camelCase`.
  11091. *
  11092. * @private
  11093. * @param {Function} callback The function to combine each word.
  11094. * @returns {Function} Returns the new compounder function.
  11095. */
  11096. function createCompounder(callback) {
  11097. return function(string) {
  11098. return arrayReduce(words(deburr(string).replace(reApos, '')), callback, '');
  11099. };
  11100. }
  11101. /**
  11102. * Checks if `value` is object-like. A value is object-like if it's not `null`
  11103. * and has a `typeof` result of "object".
  11104. *
  11105. * @static
  11106. * @memberOf _
  11107. * @since 4.0.0
  11108. * @category Lang
  11109. * @param {*} value The value to check.
  11110. * @returns {boolean} Returns `true` if `value` is object-like, else `false`.
  11111. * @example
  11112. *
  11113. * _.isObjectLike({});
  11114. * // => true
  11115. *
  11116. * _.isObjectLike([1, 2, 3]);
  11117. * // => true
  11118. *
  11119. * _.isObjectLike(_.noop);
  11120. * // => false
  11121. *
  11122. * _.isObjectLike(null);
  11123. * // => false
  11124. */
  11125. function isObjectLike(value) {
  11126. return !!value && typeof value == 'object';
  11127. }
  11128. /**
  11129. * Checks if `value` is classified as a `Symbol` primitive or object.
  11130. *
  11131. * @static
  11132. * @memberOf _
  11133. * @since 4.0.0
  11134. * @category Lang
  11135. * @param {*} value The value to check.
  11136. * @returns {boolean} Returns `true` if `value` is a symbol, else `false`.
  11137. * @example
  11138. *
  11139. * _.isSymbol(Symbol.iterator);
  11140. * // => true
  11141. *
  11142. * _.isSymbol('abc');
  11143. * // => false
  11144. */
  11145. function isSymbol(value) {
  11146. return typeof value == 'symbol' ||
  11147. (isObjectLike(value) && objectToString.call(value) == symbolTag);
  11148. }
  11149. /**
  11150. * Converts `value` to a string. An empty string is returned for `null`
  11151. * and `undefined` values. The sign of `-0` is preserved.
  11152. *
  11153. * @static
  11154. * @memberOf _
  11155. * @since 4.0.0
  11156. * @category Lang
  11157. * @param {*} value The value to process.
  11158. * @returns {string} Returns the string.
  11159. * @example
  11160. *
  11161. * _.toString(null);
  11162. * // => ''
  11163. *
  11164. * _.toString(-0);
  11165. * // => '-0'
  11166. *
  11167. * _.toString([1, 2, 3]);
  11168. * // => '1,2,3'
  11169. */
  11170. function toString(value) {
  11171. return value == null ? '' : baseToString(value);
  11172. }
  11173. /**
  11174. * Converts `string` to [camel case](https://en.wikipedia.org/wiki/CamelCase).
  11175. *
  11176. * @static
  11177. * @memberOf _
  11178. * @since 3.0.0
  11179. * @category String
  11180. * @param {string} [string=''] The string to convert.
  11181. * @returns {string} Returns the camel cased string.
  11182. * @example
  11183. *
  11184. * _.camelCase('Foo Bar');
  11185. * // => 'fooBar'
  11186. *
  11187. * _.camelCase('--foo-bar--');
  11188. * // => 'fooBar'
  11189. *
  11190. * _.camelCase('__FOO_BAR__');
  11191. * // => 'fooBar'
  11192. */
  11193. var camelCase = createCompounder(function(result, word, index) {
  11194. word = word.toLowerCase();
  11195. return result + (index ? capitalize(word) : word);
  11196. });
  11197. /**
  11198. * Converts the first character of `string` to upper case and the remaining
  11199. * to lower case.
  11200. *
  11201. * @static
  11202. * @memberOf _
  11203. * @since 3.0.0
  11204. * @category String
  11205. * @param {string} [string=''] The string to capitalize.
  11206. * @returns {string} Returns the capitalized string.
  11207. * @example
  11208. *
  11209. * _.capitalize('FRED');
  11210. * // => 'Fred'
  11211. */
  11212. function capitalize(string) {
  11213. return upperFirst(toString(string).toLowerCase());
  11214. }
  11215. /**
  11216. * Deburrs `string` by converting
  11217. * [Latin-1 Supplement](https://en.wikipedia.org/wiki/Latin-1_Supplement_(Unicode_block)#Character_table)
  11218. * and [Latin Extended-A](https://en.wikipedia.org/wiki/Latin_Extended-A)
  11219. * letters to basic Latin letters and removing
  11220. * [combining diacritical marks](https://en.wikipedia.org/wiki/Combining_Diacritical_Marks).
  11221. *
  11222. * @static
  11223. * @memberOf _
  11224. * @since 3.0.0
  11225. * @category String
  11226. * @param {string} [string=''] The string to deburr.
  11227. * @returns {string} Returns the deburred string.
  11228. * @example
  11229. *
  11230. * _.deburr('déjà vu');
  11231. * // => 'deja vu'
  11232. */
  11233. function deburr(string) {
  11234. string = toString(string);
  11235. return string && string.replace(reLatin, deburrLetter).replace(reComboMark, '');
  11236. }
  11237. /**
  11238. * Converts the first character of `string` to upper case.
  11239. *
  11240. * @static
  11241. * @memberOf _
  11242. * @since 4.0.0
  11243. * @category String
  11244. * @param {string} [string=''] The string to convert.
  11245. * @returns {string} Returns the converted string.
  11246. * @example
  11247. *
  11248. * _.upperFirst('fred');
  11249. * // => 'Fred'
  11250. *
  11251. * _.upperFirst('FRED');
  11252. * // => 'FRED'
  11253. */
  11254. var upperFirst = createCaseFirst('toUpperCase');
  11255. /**
  11256. * Splits `string` into an array of its words.
  11257. *
  11258. * @static
  11259. * @memberOf _
  11260. * @since 3.0.0
  11261. * @category String
  11262. * @param {string} [string=''] The string to inspect.
  11263. * @param {RegExp|string} [pattern] The pattern to match words.
  11264. * @param- {Object} [guard] Enables use as an iteratee for methods like `_.map`.
  11265. * @returns {Array} Returns the words of `string`.
  11266. * @example
  11267. *
  11268. * _.words('fred, barney, & pebbles');
  11269. * // => ['fred', 'barney', 'pebbles']
  11270. *
  11271. * _.words('fred, barney, & pebbles', /[^, ]+/g);
  11272. * // => ['fred', 'barney', '&', 'pebbles']
  11273. */
  11274. function words(string, pattern, guard) {
  11275. string = toString(string);
  11276. pattern = guard ? undefined : pattern;
  11277. if (pattern === undefined) {
  11278. return hasUnicodeWord(string) ? unicodeWords(string) : asciiWords(string);
  11279. }
  11280. return string.match(pattern) || [];
  11281. }
  11282. var lodash_camelcase = camelCase;
  11283. Object.defineProperty(localsConvention, "__esModule", {
  11284. value: true
  11285. });
  11286. localsConvention.makeLocalsConventionReducer = makeLocalsConventionReducer;
  11287. var _lodash = _interopRequireDefault$3(lodash_camelcase);
  11288. function _interopRequireDefault$3(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
  11289. function dashesCamelCase(string) {
  11290. return string.replace(/-+(\w)/g, (_, firstLetter) => firstLetter.toUpperCase());
  11291. }
  11292. function makeLocalsConventionReducer(localsConvention, inputFile) {
  11293. const isFunc = typeof localsConvention === "function";
  11294. return (tokens, [className, value]) => {
  11295. if (isFunc) {
  11296. const convention = localsConvention(className, value, inputFile);
  11297. tokens[convention] = value;
  11298. return tokens;
  11299. }
  11300. switch (localsConvention) {
  11301. case "camelCase":
  11302. tokens[className] = value;
  11303. tokens[(0, _lodash.default)(className)] = value;
  11304. break;
  11305. case "camelCaseOnly":
  11306. tokens[(0, _lodash.default)(className)] = value;
  11307. break;
  11308. case "dashes":
  11309. tokens[className] = value;
  11310. tokens[dashesCamelCase(className)] = value;
  11311. break;
  11312. case "dashesOnly":
  11313. tokens[dashesCamelCase(className)] = value;
  11314. break;
  11315. }
  11316. return tokens;
  11317. };
  11318. }
  11319. var FileSystemLoader$1 = {};
  11320. Object.defineProperty(FileSystemLoader$1, "__esModule", {
  11321. value: true
  11322. });
  11323. FileSystemLoader$1.default = void 0;
  11324. var _postcss$1 = _interopRequireDefault$2(require$$0$1);
  11325. var _path = _interopRequireDefault$2(path$3);
  11326. var _Parser$1 = _interopRequireDefault$2(Parser$1);
  11327. var _fs$1 = fs;
  11328. function _interopRequireDefault$2(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
  11329. // Initially copied from https://github.com/css-modules/css-modules-loader-core
  11330. class Core {
  11331. constructor(plugins) {
  11332. this.plugins = plugins || Core.defaultPlugins;
  11333. }
  11334. async load(sourceString, sourcePath, trace, pathFetcher) {
  11335. const parser = new _Parser$1.default(pathFetcher, trace);
  11336. const plugins = this.plugins.concat([parser.plugin()]);
  11337. const result = await (0, _postcss$1.default)(plugins).process(sourceString, {
  11338. from: sourcePath
  11339. });
  11340. return {
  11341. injectableSource: result.css,
  11342. exportTokens: parser.exportTokens
  11343. };
  11344. }
  11345. } // Sorts dependencies in the following way:
  11346. // AAA comes before AA and A
  11347. // AB comes after AA and before A
  11348. // All Bs come after all As
  11349. // This ensures that the files are always returned in the following order:
  11350. // - In the order they were required, except
  11351. // - After all their dependencies
  11352. const traceKeySorter = (a, b) => {
  11353. if (a.length < b.length) {
  11354. return a < b.substring(0, a.length) ? -1 : 1;
  11355. }
  11356. if (a.length > b.length) {
  11357. return a.substring(0, b.length) <= b ? -1 : 1;
  11358. }
  11359. return a < b ? -1 : 1;
  11360. };
  11361. class FileSystemLoader {
  11362. constructor(root, plugins, fileResolve) {
  11363. if (root === "/" && process.platform === "win32") {
  11364. const cwdDrive = process.cwd().slice(0, 3);
  11365. if (!/^[A-Za-z]:\\$/.test(cwdDrive)) {
  11366. throw new Error(`Failed to obtain root from "${process.cwd()}".`);
  11367. }
  11368. root = cwdDrive;
  11369. }
  11370. this.root = root;
  11371. this.fileResolve = fileResolve;
  11372. this.sources = {};
  11373. this.traces = {};
  11374. this.importNr = 0;
  11375. this.core = new Core(plugins);
  11376. this.tokensByFile = {};
  11377. this.fs = (0, _fs$1.getFileSystem)();
  11378. }
  11379. async fetch(_newPath, relativeTo, _trace) {
  11380. const newPath = _newPath.replace(/^["']|["']$/g, "");
  11381. const trace = _trace || String.fromCharCode(this.importNr++);
  11382. const useFileResolve = typeof this.fileResolve === "function";
  11383. const fileResolvedPath = useFileResolve ? await this.fileResolve(newPath, relativeTo) : await Promise.resolve();
  11384. if (fileResolvedPath && !_path.default.isAbsolute(fileResolvedPath)) {
  11385. throw new Error('The returned path from the "fileResolve" option must be absolute.');
  11386. }
  11387. const relativeDir = _path.default.dirname(relativeTo);
  11388. const rootRelativePath = fileResolvedPath || _path.default.resolve(relativeDir, newPath);
  11389. 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
  11390. if (!useFileResolve && newPath[0] !== "." && !_path.default.isAbsolute(newPath)) {
  11391. try {
  11392. fileRelativePath = require.resolve(newPath);
  11393. } catch (e) {// noop
  11394. }
  11395. }
  11396. const tokens = this.tokensByFile[fileRelativePath];
  11397. if (tokens) return tokens;
  11398. return new Promise((resolve, reject) => {
  11399. this.fs.readFile(fileRelativePath, "utf-8", async (err, source) => {
  11400. if (err) reject(err);
  11401. const {
  11402. injectableSource,
  11403. exportTokens
  11404. } = await this.core.load(source, rootRelativePath, trace, this.fetch.bind(this));
  11405. this.sources[fileRelativePath] = injectableSource;
  11406. this.traces[trace] = fileRelativePath;
  11407. this.tokensByFile[fileRelativePath] = exportTokens;
  11408. resolve(exportTokens);
  11409. });
  11410. });
  11411. }
  11412. get finalSource() {
  11413. const traces = this.traces;
  11414. const sources = this.sources;
  11415. let written = new Set();
  11416. return Object.keys(traces).sort(traceKeySorter).map(key => {
  11417. const filename = traces[key];
  11418. if (written.has(filename)) {
  11419. return null;
  11420. }
  11421. written.add(filename);
  11422. return sources[filename];
  11423. }).join("");
  11424. }
  11425. }
  11426. FileSystemLoader$1.default = FileSystemLoader;
  11427. var scoping = {};
  11428. var src$3 = {exports: {}};
  11429. const PERMANENT_MARKER = 2;
  11430. const TEMPORARY_MARKER = 1;
  11431. function createError(node, graph) {
  11432. const er = new Error("Nondeterministic import's order");
  11433. const related = graph[node];
  11434. const relatedNode = related.find(
  11435. (relatedNode) => graph[relatedNode].indexOf(node) > -1
  11436. );
  11437. er.nodes = [node, relatedNode];
  11438. return er;
  11439. }
  11440. function walkGraph(node, graph, state, result, strict) {
  11441. if (state[node] === PERMANENT_MARKER) {
  11442. return;
  11443. }
  11444. if (state[node] === TEMPORARY_MARKER) {
  11445. if (strict) {
  11446. return createError(node, graph);
  11447. }
  11448. return;
  11449. }
  11450. state[node] = TEMPORARY_MARKER;
  11451. const children = graph[node];
  11452. const length = children.length;
  11453. for (let i = 0; i < length; ++i) {
  11454. const error = walkGraph(children[i], graph, state, result, strict);
  11455. if (error instanceof Error) {
  11456. return error;
  11457. }
  11458. }
  11459. state[node] = PERMANENT_MARKER;
  11460. result.push(node);
  11461. }
  11462. function topologicalSort$1(graph, strict) {
  11463. const result = [];
  11464. const state = {};
  11465. const nodes = Object.keys(graph);
  11466. const length = nodes.length;
  11467. for (let i = 0; i < length; ++i) {
  11468. const er = walkGraph(nodes[i], graph, state, result, strict);
  11469. if (er instanceof Error) {
  11470. return er;
  11471. }
  11472. }
  11473. return result;
  11474. }
  11475. var topologicalSort_1 = topologicalSort$1;
  11476. const topologicalSort = topologicalSort_1;
  11477. const matchImports$1 = /^(.+?)\s+from\s+(?:"([^"]+)"|'([^']+)'|(global))$/;
  11478. const icssImport = /^:import\((?:"([^"]+)"|'([^']+)')\)/;
  11479. const VISITED_MARKER = 1;
  11480. /**
  11481. * :import('G') {}
  11482. *
  11483. * Rule
  11484. * composes: ... from 'A'
  11485. * composes: ... from 'B'
  11486. * Rule
  11487. * composes: ... from 'A'
  11488. * composes: ... from 'A'
  11489. * composes: ... from 'C'
  11490. *
  11491. * Results in:
  11492. *
  11493. * graph: {
  11494. * G: [],
  11495. * A: [],
  11496. * B: ['A'],
  11497. * C: ['A'],
  11498. * }
  11499. */
  11500. function addImportToGraph(importId, parentId, graph, visited) {
  11501. const siblingsId = parentId + "_" + "siblings";
  11502. const visitedId = parentId + "_" + importId;
  11503. if (visited[visitedId] !== VISITED_MARKER) {
  11504. if (!Array.isArray(visited[siblingsId])) {
  11505. visited[siblingsId] = [];
  11506. }
  11507. const siblings = visited[siblingsId];
  11508. if (Array.isArray(graph[importId])) {
  11509. graph[importId] = graph[importId].concat(siblings);
  11510. } else {
  11511. graph[importId] = siblings.slice();
  11512. }
  11513. visited[visitedId] = VISITED_MARKER;
  11514. siblings.push(importId);
  11515. }
  11516. }
  11517. src$3.exports = (options = {}) => {
  11518. let importIndex = 0;
  11519. const createImportedName =
  11520. typeof options.createImportedName !== "function"
  11521. ? (importName /*, path*/) =>
  11522. `i__imported_${importName.replace(/\W/g, "_")}_${importIndex++}`
  11523. : options.createImportedName;
  11524. const failOnWrongOrder = options.failOnWrongOrder;
  11525. return {
  11526. postcssPlugin: "postcss-modules-extract-imports",
  11527. prepare() {
  11528. const graph = {};
  11529. const visited = {};
  11530. const existingImports = {};
  11531. const importDecls = {};
  11532. const imports = {};
  11533. return {
  11534. Once(root, postcss) {
  11535. // Check the existing imports order and save refs
  11536. root.walkRules((rule) => {
  11537. const matches = icssImport.exec(rule.selector);
  11538. if (matches) {
  11539. const [, /*match*/ doubleQuotePath, singleQuotePath] = matches;
  11540. const importPath = doubleQuotePath || singleQuotePath;
  11541. addImportToGraph(importPath, "root", graph, visited);
  11542. existingImports[importPath] = rule;
  11543. }
  11544. });
  11545. root.walkDecls(/^composes$/, (declaration) => {
  11546. const matches = declaration.value.match(matchImports$1);
  11547. if (!matches) {
  11548. return;
  11549. }
  11550. let tmpSymbols;
  11551. let [
  11552. ,
  11553. /*match*/ symbols,
  11554. doubleQuotePath,
  11555. singleQuotePath,
  11556. global,
  11557. ] = matches;
  11558. if (global) {
  11559. // Composing globals simply means changing these classes to wrap them in global(name)
  11560. tmpSymbols = symbols.split(/\s+/).map((s) => `global(${s})`);
  11561. } else {
  11562. const importPath = doubleQuotePath || singleQuotePath;
  11563. let parent = declaration.parent;
  11564. let parentIndexes = "";
  11565. while (parent.type !== "root") {
  11566. parentIndexes =
  11567. parent.parent.index(parent) + "_" + parentIndexes;
  11568. parent = parent.parent;
  11569. }
  11570. const { selector } = declaration.parent;
  11571. const parentRule = `_${parentIndexes}${selector}`;
  11572. addImportToGraph(importPath, parentRule, graph, visited);
  11573. importDecls[importPath] = declaration;
  11574. imports[importPath] = imports[importPath] || {};
  11575. tmpSymbols = symbols.split(/\s+/).map((s) => {
  11576. if (!imports[importPath][s]) {
  11577. imports[importPath][s] = createImportedName(s, importPath);
  11578. }
  11579. return imports[importPath][s];
  11580. });
  11581. }
  11582. declaration.value = tmpSymbols.join(" ");
  11583. });
  11584. const importsOrder = topologicalSort(graph, failOnWrongOrder);
  11585. if (importsOrder instanceof Error) {
  11586. const importPath = importsOrder.nodes.find((importPath) =>
  11587. // eslint-disable-next-line no-prototype-builtins
  11588. importDecls.hasOwnProperty(importPath)
  11589. );
  11590. const decl = importDecls[importPath];
  11591. throw decl.error(
  11592. "Failed to resolve order of composed modules " +
  11593. importsOrder.nodes
  11594. .map((importPath) => "`" + importPath + "`")
  11595. .join(", ") +
  11596. ".",
  11597. {
  11598. plugin: "postcss-modules-extract-imports",
  11599. word: "composes",
  11600. }
  11601. );
  11602. }
  11603. let lastImportRule;
  11604. importsOrder.forEach((path) => {
  11605. const importedSymbols = imports[path];
  11606. let rule = existingImports[path];
  11607. if (!rule && importedSymbols) {
  11608. rule = postcss.rule({
  11609. selector: `:import("${path}")`,
  11610. raws: { after: "\n" },
  11611. });
  11612. if (lastImportRule) {
  11613. root.insertAfter(lastImportRule, rule);
  11614. } else {
  11615. root.prepend(rule);
  11616. }
  11617. }
  11618. lastImportRule = rule;
  11619. if (!importedSymbols) {
  11620. return;
  11621. }
  11622. Object.keys(importedSymbols).forEach((importedSymbol) => {
  11623. rule.append(
  11624. postcss.decl({
  11625. value: importedSymbol,
  11626. prop: importedSymbols[importedSymbol],
  11627. raws: { before: "\n " },
  11628. })
  11629. );
  11630. });
  11631. });
  11632. },
  11633. };
  11634. },
  11635. };
  11636. };
  11637. src$3.exports.postcss = true;
  11638. var srcExports$2 = src$3.exports;
  11639. var wasmHash = {exports: {}};
  11640. /*
  11641. MIT License http://www.opensource.org/licenses/mit-license.php
  11642. Author Tobias Koppers @sokra
  11643. */
  11644. var hasRequiredWasmHash;
  11645. function requireWasmHash () {
  11646. if (hasRequiredWasmHash) return wasmHash.exports;
  11647. hasRequiredWasmHash = 1;
  11648. // 65536 is the size of a wasm memory page
  11649. // 64 is the maximum chunk size for every possible wasm hash implementation
  11650. // 4 is the maximum number of bytes per char for string encoding (max is utf-8)
  11651. // ~3 makes sure that it's always a block of 4 chars, so avoid partially encoded bytes for base64
  11652. const MAX_SHORT_STRING = Math.floor((65536 - 64) / 4) & ~3;
  11653. class WasmHash {
  11654. /**
  11655. * @param {WebAssembly.Instance} instance wasm instance
  11656. * @param {WebAssembly.Instance[]} instancesPool pool of instances
  11657. * @param {number} chunkSize size of data chunks passed to wasm
  11658. * @param {number} digestSize size of digest returned by wasm
  11659. */
  11660. constructor(instance, instancesPool, chunkSize, digestSize) {
  11661. const exports = /** @type {any} */ (instance.exports);
  11662. exports.init();
  11663. this.exports = exports;
  11664. this.mem = Buffer.from(exports.memory.buffer, 0, 65536);
  11665. this.buffered = 0;
  11666. this.instancesPool = instancesPool;
  11667. this.chunkSize = chunkSize;
  11668. this.digestSize = digestSize;
  11669. }
  11670. reset() {
  11671. this.buffered = 0;
  11672. this.exports.init();
  11673. }
  11674. /**
  11675. * @param {Buffer | string} data data
  11676. * @param {BufferEncoding=} encoding encoding
  11677. * @returns {this} itself
  11678. */
  11679. update(data, encoding) {
  11680. if (typeof data === "string") {
  11681. while (data.length > MAX_SHORT_STRING) {
  11682. this._updateWithShortString(data.slice(0, MAX_SHORT_STRING), encoding);
  11683. data = data.slice(MAX_SHORT_STRING);
  11684. }
  11685. this._updateWithShortString(data, encoding);
  11686. return this;
  11687. }
  11688. this._updateWithBuffer(data);
  11689. return this;
  11690. }
  11691. /**
  11692. * @param {string} data data
  11693. * @param {BufferEncoding=} encoding encoding
  11694. * @returns {void}
  11695. */
  11696. _updateWithShortString(data, encoding) {
  11697. const { exports, buffered, mem, chunkSize } = this;
  11698. let endPos;
  11699. if (data.length < 70) {
  11700. if (!encoding || encoding === "utf-8" || encoding === "utf8") {
  11701. endPos = buffered;
  11702. for (let i = 0; i < data.length; i++) {
  11703. const cc = data.charCodeAt(i);
  11704. if (cc < 0x80) {
  11705. mem[endPos++] = cc;
  11706. } else if (cc < 0x800) {
  11707. mem[endPos] = (cc >> 6) | 0xc0;
  11708. mem[endPos + 1] = (cc & 0x3f) | 0x80;
  11709. endPos += 2;
  11710. } else {
  11711. // bail-out for weird chars
  11712. endPos += mem.write(data.slice(i), endPos, encoding);
  11713. break;
  11714. }
  11715. }
  11716. } else if (encoding === "latin1") {
  11717. endPos = buffered;
  11718. for (let i = 0; i < data.length; i++) {
  11719. const cc = data.charCodeAt(i);
  11720. mem[endPos++] = cc;
  11721. }
  11722. } else {
  11723. endPos = buffered + mem.write(data, buffered, encoding);
  11724. }
  11725. } else {
  11726. endPos = buffered + mem.write(data, buffered, encoding);
  11727. }
  11728. if (endPos < chunkSize) {
  11729. this.buffered = endPos;
  11730. } else {
  11731. const l = endPos & ~(this.chunkSize - 1);
  11732. exports.update(l);
  11733. const newBuffered = endPos - l;
  11734. this.buffered = newBuffered;
  11735. if (newBuffered > 0) {
  11736. mem.copyWithin(0, l, endPos);
  11737. }
  11738. }
  11739. }
  11740. /**
  11741. * @param {Buffer} data data
  11742. * @returns {void}
  11743. */
  11744. _updateWithBuffer(data) {
  11745. const { exports, buffered, mem } = this;
  11746. const length = data.length;
  11747. if (buffered + length < this.chunkSize) {
  11748. data.copy(mem, buffered, 0, length);
  11749. this.buffered += length;
  11750. } else {
  11751. const l = (buffered + length) & ~(this.chunkSize - 1);
  11752. if (l > 65536) {
  11753. let i = 65536 - buffered;
  11754. data.copy(mem, buffered, 0, i);
  11755. exports.update(65536);
  11756. const stop = l - buffered - 65536;
  11757. while (i < stop) {
  11758. data.copy(mem, 0, i, i + 65536);
  11759. exports.update(65536);
  11760. i += 65536;
  11761. }
  11762. data.copy(mem, 0, i, l - buffered);
  11763. exports.update(l - buffered - i);
  11764. } else {
  11765. data.copy(mem, buffered, 0, l - buffered);
  11766. exports.update(l);
  11767. }
  11768. const newBuffered = length + buffered - l;
  11769. this.buffered = newBuffered;
  11770. if (newBuffered > 0) {
  11771. data.copy(mem, 0, length - newBuffered, length);
  11772. }
  11773. }
  11774. }
  11775. digest(type) {
  11776. const { exports, buffered, mem, digestSize } = this;
  11777. exports.final(buffered);
  11778. this.instancesPool.push(this);
  11779. const hex = mem.toString("latin1", 0, digestSize);
  11780. if (type === "hex") {
  11781. return hex;
  11782. }
  11783. if (type === "binary" || !type) {
  11784. return Buffer.from(hex, "hex");
  11785. }
  11786. return Buffer.from(hex, "hex").toString(type);
  11787. }
  11788. }
  11789. const create = (wasmModule, instancesPool, chunkSize, digestSize) => {
  11790. if (instancesPool.length > 0) {
  11791. const old = instancesPool.pop();
  11792. old.reset();
  11793. return old;
  11794. } else {
  11795. return new WasmHash(
  11796. new WebAssembly.Instance(wasmModule),
  11797. instancesPool,
  11798. chunkSize,
  11799. digestSize
  11800. );
  11801. }
  11802. };
  11803. wasmHash.exports = create;
  11804. wasmHash.exports.MAX_SHORT_STRING = MAX_SHORT_STRING;
  11805. return wasmHash.exports;
  11806. }
  11807. /*
  11808. MIT License http://www.opensource.org/licenses/mit-license.php
  11809. Author Tobias Koppers @sokra
  11810. */
  11811. var xxhash64_1;
  11812. var hasRequiredXxhash64;
  11813. function requireXxhash64 () {
  11814. if (hasRequiredXxhash64) return xxhash64_1;
  11815. hasRequiredXxhash64 = 1;
  11816. const create = requireWasmHash();
  11817. //#region wasm code: xxhash64 (../../../assembly/hash/xxhash64.asm.ts) --initialMemory 1
  11818. const xxhash64 = new WebAssembly.Module(
  11819. Buffer.from(
  11820. // 1173 bytes
  11821. "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",
  11822. "base64"
  11823. )
  11824. );
  11825. //#endregion
  11826. xxhash64_1 = create.bind(null, xxhash64, [], 32, 16);
  11827. return xxhash64_1;
  11828. }
  11829. var BatchedHash_1;
  11830. var hasRequiredBatchedHash;
  11831. function requireBatchedHash () {
  11832. if (hasRequiredBatchedHash) return BatchedHash_1;
  11833. hasRequiredBatchedHash = 1;
  11834. const MAX_SHORT_STRING = requireWasmHash().MAX_SHORT_STRING;
  11835. class BatchedHash {
  11836. constructor(hash) {
  11837. this.string = undefined;
  11838. this.encoding = undefined;
  11839. this.hash = hash;
  11840. }
  11841. /**
  11842. * Update hash {@link https://nodejs.org/api/crypto.html#crypto_hash_update_data_inputencoding}
  11843. * @param {string|Buffer} data data
  11844. * @param {string=} inputEncoding data encoding
  11845. * @returns {this} updated hash
  11846. */
  11847. update(data, inputEncoding) {
  11848. if (this.string !== undefined) {
  11849. if (
  11850. typeof data === "string" &&
  11851. inputEncoding === this.encoding &&
  11852. this.string.length + data.length < MAX_SHORT_STRING
  11853. ) {
  11854. this.string += data;
  11855. return this;
  11856. }
  11857. this.hash.update(this.string, this.encoding);
  11858. this.string = undefined;
  11859. }
  11860. if (typeof data === "string") {
  11861. if (
  11862. data.length < MAX_SHORT_STRING &&
  11863. // base64 encoding is not valid since it may contain padding chars
  11864. (!inputEncoding || !inputEncoding.startsWith("ba"))
  11865. ) {
  11866. this.string = data;
  11867. this.encoding = inputEncoding;
  11868. } else {
  11869. this.hash.update(data, inputEncoding);
  11870. }
  11871. } else {
  11872. this.hash.update(data);
  11873. }
  11874. return this;
  11875. }
  11876. /**
  11877. * Calculates the digest {@link https://nodejs.org/api/crypto.html#crypto_hash_digest_encoding}
  11878. * @param {string=} encoding encoding of the return value
  11879. * @returns {string|Buffer} digest
  11880. */
  11881. digest(encoding) {
  11882. if (this.string !== undefined) {
  11883. this.hash.update(this.string, this.encoding);
  11884. }
  11885. return this.hash.digest(encoding);
  11886. }
  11887. }
  11888. BatchedHash_1 = BatchedHash;
  11889. return BatchedHash_1;
  11890. }
  11891. /*
  11892. MIT License http://www.opensource.org/licenses/mit-license.php
  11893. Author Tobias Koppers @sokra
  11894. */
  11895. var md4_1;
  11896. var hasRequiredMd4;
  11897. function requireMd4 () {
  11898. if (hasRequiredMd4) return md4_1;
  11899. hasRequiredMd4 = 1;
  11900. const create = requireWasmHash();
  11901. //#region wasm code: md4 (../../../assembly/hash/md4.asm.ts) --initialMemory 1
  11902. const md4 = new WebAssembly.Module(
  11903. Buffer.from(
  11904. // 2150 bytes
  11905. "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=",
  11906. "base64"
  11907. )
  11908. );
  11909. //#endregion
  11910. md4_1 = create.bind(null, md4, [], 64, 32);
  11911. return md4_1;
  11912. }
  11913. var BulkUpdateDecorator_1;
  11914. var hasRequiredBulkUpdateDecorator;
  11915. function requireBulkUpdateDecorator () {
  11916. if (hasRequiredBulkUpdateDecorator) return BulkUpdateDecorator_1;
  11917. hasRequiredBulkUpdateDecorator = 1;
  11918. const BULK_SIZE = 2000;
  11919. // We are using an object instead of a Map as this will stay static during the runtime
  11920. // so access to it can be optimized by v8
  11921. const digestCaches = {};
  11922. class BulkUpdateDecorator {
  11923. /**
  11924. * @param {Hash | function(): Hash} hashOrFactory function to create a hash
  11925. * @param {string=} hashKey key for caching
  11926. */
  11927. constructor(hashOrFactory, hashKey) {
  11928. this.hashKey = hashKey;
  11929. if (typeof hashOrFactory === "function") {
  11930. this.hashFactory = hashOrFactory;
  11931. this.hash = undefined;
  11932. } else {
  11933. this.hashFactory = undefined;
  11934. this.hash = hashOrFactory;
  11935. }
  11936. this.buffer = "";
  11937. }
  11938. /**
  11939. * Update hash {@link https://nodejs.org/api/crypto.html#crypto_hash_update_data_inputencoding}
  11940. * @param {string|Buffer} data data
  11941. * @param {string=} inputEncoding data encoding
  11942. * @returns {this} updated hash
  11943. */
  11944. update(data, inputEncoding) {
  11945. if (
  11946. inputEncoding !== undefined ||
  11947. typeof data !== "string" ||
  11948. data.length > BULK_SIZE
  11949. ) {
  11950. if (this.hash === undefined) {
  11951. this.hash = this.hashFactory();
  11952. }
  11953. if (this.buffer.length > 0) {
  11954. this.hash.update(this.buffer);
  11955. this.buffer = "";
  11956. }
  11957. this.hash.update(data, inputEncoding);
  11958. } else {
  11959. this.buffer += data;
  11960. if (this.buffer.length > BULK_SIZE) {
  11961. if (this.hash === undefined) {
  11962. this.hash = this.hashFactory();
  11963. }
  11964. this.hash.update(this.buffer);
  11965. this.buffer = "";
  11966. }
  11967. }
  11968. return this;
  11969. }
  11970. /**
  11971. * Calculates the digest {@link https://nodejs.org/api/crypto.html#crypto_hash_digest_encoding}
  11972. * @param {string=} encoding encoding of the return value
  11973. * @returns {string|Buffer} digest
  11974. */
  11975. digest(encoding) {
  11976. let digestCache;
  11977. const buffer = this.buffer;
  11978. if (this.hash === undefined) {
  11979. // short data for hash, we can use caching
  11980. const cacheKey = `${this.hashKey}-${encoding}`;
  11981. digestCache = digestCaches[cacheKey];
  11982. if (digestCache === undefined) {
  11983. digestCache = digestCaches[cacheKey] = new Map();
  11984. }
  11985. const cacheEntry = digestCache.get(buffer);
  11986. if (cacheEntry !== undefined) {
  11987. return cacheEntry;
  11988. }
  11989. this.hash = this.hashFactory();
  11990. }
  11991. if (buffer.length > 0) {
  11992. this.hash.update(buffer);
  11993. }
  11994. const digestResult = this.hash.digest(encoding);
  11995. if (digestCache !== undefined) {
  11996. digestCache.set(buffer, digestResult);
  11997. }
  11998. return digestResult;
  11999. }
  12000. }
  12001. BulkUpdateDecorator_1 = BulkUpdateDecorator;
  12002. return BulkUpdateDecorator_1;
  12003. }
  12004. const baseEncodeTables = {
  12005. 26: "abcdefghijklmnopqrstuvwxyz",
  12006. 32: "123456789abcdefghjkmnpqrstuvwxyz", // no 0lio
  12007. 36: "0123456789abcdefghijklmnopqrstuvwxyz",
  12008. 49: "abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ", // no lIO
  12009. 52: "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ",
  12010. 58: "123456789abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ", // no 0lIO
  12011. 62: "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ",
  12012. 64: "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ-_",
  12013. };
  12014. /**
  12015. * @param {Uint32Array} uint32Array Treated as a long base-0x100000000 number, little endian
  12016. * @param {number} divisor The divisor
  12017. * @return {number} Modulo (remainder) of the division
  12018. */
  12019. function divmod32(uint32Array, divisor) {
  12020. let carry = 0;
  12021. for (let i = uint32Array.length - 1; i >= 0; i--) {
  12022. const value = carry * 0x100000000 + uint32Array[i];
  12023. carry = value % divisor;
  12024. uint32Array[i] = Math.floor(value / divisor);
  12025. }
  12026. return carry;
  12027. }
  12028. function encodeBufferToBase(buffer, base, length) {
  12029. const encodeTable = baseEncodeTables[base];
  12030. if (!encodeTable) {
  12031. throw new Error("Unknown encoding base" + base);
  12032. }
  12033. // Input bits are only enough to generate this many characters
  12034. const limit = Math.ceil((buffer.length * 8) / Math.log2(base));
  12035. length = Math.min(length, limit);
  12036. // Most of the crypto digests (if not all) has length a multiple of 4 bytes.
  12037. // Fewer numbers in the array means faster math.
  12038. const uint32Array = new Uint32Array(Math.ceil(buffer.length / 4));
  12039. // Make sure the input buffer data is copied and is not mutated by reference.
  12040. // divmod32() would corrupt the BulkUpdateDecorator cache otherwise.
  12041. buffer.copy(Buffer.from(uint32Array.buffer));
  12042. let output = "";
  12043. for (let i = 0; i < length; i++) {
  12044. output = encodeTable[divmod32(uint32Array, base)] + output;
  12045. }
  12046. return output;
  12047. }
  12048. let crypto = undefined;
  12049. let createXXHash64 = undefined;
  12050. let createMd4 = undefined;
  12051. let BatchedHash = undefined;
  12052. let BulkUpdateDecorator = undefined;
  12053. function getHashDigest$1(buffer, algorithm, digestType, maxLength) {
  12054. algorithm = algorithm || "xxhash64";
  12055. maxLength = maxLength || 9999;
  12056. let hash;
  12057. if (algorithm === "xxhash64") {
  12058. if (createXXHash64 === undefined) {
  12059. createXXHash64 = requireXxhash64();
  12060. if (BatchedHash === undefined) {
  12061. BatchedHash = requireBatchedHash();
  12062. }
  12063. }
  12064. hash = new BatchedHash(createXXHash64());
  12065. } else if (algorithm === "md4") {
  12066. if (createMd4 === undefined) {
  12067. createMd4 = requireMd4();
  12068. if (BatchedHash === undefined) {
  12069. BatchedHash = requireBatchedHash();
  12070. }
  12071. }
  12072. hash = new BatchedHash(createMd4());
  12073. } else if (algorithm === "native-md4") {
  12074. if (typeof crypto === "undefined") {
  12075. crypto = require("crypto");
  12076. if (BulkUpdateDecorator === undefined) {
  12077. BulkUpdateDecorator = requireBulkUpdateDecorator();
  12078. }
  12079. }
  12080. hash = new BulkUpdateDecorator(() => crypto.createHash("md4"), "md4");
  12081. } else {
  12082. if (typeof crypto === "undefined") {
  12083. crypto = require("crypto");
  12084. if (BulkUpdateDecorator === undefined) {
  12085. BulkUpdateDecorator = requireBulkUpdateDecorator();
  12086. }
  12087. }
  12088. hash = new BulkUpdateDecorator(
  12089. () => crypto.createHash(algorithm),
  12090. algorithm
  12091. );
  12092. }
  12093. hash.update(buffer);
  12094. if (
  12095. digestType === "base26" ||
  12096. digestType === "base32" ||
  12097. digestType === "base36" ||
  12098. digestType === "base49" ||
  12099. digestType === "base52" ||
  12100. digestType === "base58" ||
  12101. digestType === "base62"
  12102. ) {
  12103. return encodeBufferToBase(hash.digest(), digestType.substr(4), maxLength);
  12104. } else {
  12105. return hash.digest(digestType || "hex").substr(0, maxLength);
  12106. }
  12107. }
  12108. var getHashDigest_1 = getHashDigest$1;
  12109. const path$2 = path$3;
  12110. const getHashDigest = getHashDigest_1;
  12111. function interpolateName$1(loaderContext, name, options = {}) {
  12112. let filename;
  12113. const hasQuery =
  12114. loaderContext.resourceQuery && loaderContext.resourceQuery.length > 1;
  12115. if (typeof name === "function") {
  12116. filename = name(
  12117. loaderContext.resourcePath,
  12118. hasQuery ? loaderContext.resourceQuery : undefined
  12119. );
  12120. } else {
  12121. filename = name || "[hash].[ext]";
  12122. }
  12123. const context = options.context;
  12124. const content = options.content;
  12125. const regExp = options.regExp;
  12126. let ext = "bin";
  12127. let basename = "file";
  12128. let directory = "";
  12129. let folder = "";
  12130. let query = "";
  12131. if (loaderContext.resourcePath) {
  12132. const parsed = path$2.parse(loaderContext.resourcePath);
  12133. let resourcePath = loaderContext.resourcePath;
  12134. if (parsed.ext) {
  12135. ext = parsed.ext.substr(1);
  12136. }
  12137. if (parsed.dir) {
  12138. basename = parsed.name;
  12139. resourcePath = parsed.dir + path$2.sep;
  12140. }
  12141. if (typeof context !== "undefined") {
  12142. directory = path$2
  12143. .relative(context, resourcePath + "_")
  12144. .replace(/\\/g, "/")
  12145. .replace(/\.\.(\/)?/g, "_$1");
  12146. directory = directory.substr(0, directory.length - 1);
  12147. } else {
  12148. directory = resourcePath.replace(/\\/g, "/").replace(/\.\.(\/)?/g, "_$1");
  12149. }
  12150. if (directory.length === 1) {
  12151. directory = "";
  12152. } else if (directory.length > 1) {
  12153. folder = path$2.basename(directory);
  12154. }
  12155. }
  12156. if (loaderContext.resourceQuery && loaderContext.resourceQuery.length > 1) {
  12157. query = loaderContext.resourceQuery;
  12158. const hashIdx = query.indexOf("#");
  12159. if (hashIdx >= 0) {
  12160. query = query.substr(0, hashIdx);
  12161. }
  12162. }
  12163. let url = filename;
  12164. if (content) {
  12165. // Match hash template
  12166. url = url
  12167. // `hash` and `contenthash` are same in `loader-utils` context
  12168. // let's keep `hash` for backward compatibility
  12169. .replace(
  12170. /\[(?:([^[:\]]+):)?(?:hash|contenthash)(?::([a-z]+\d*))?(?::(\d+))?\]/gi,
  12171. (all, hashType, digestType, maxLength) =>
  12172. getHashDigest(content, hashType, digestType, parseInt(maxLength, 10))
  12173. );
  12174. }
  12175. url = url
  12176. .replace(/\[ext\]/gi, () => ext)
  12177. .replace(/\[name\]/gi, () => basename)
  12178. .replace(/\[path\]/gi, () => directory)
  12179. .replace(/\[folder\]/gi, () => folder)
  12180. .replace(/\[query\]/gi, () => query);
  12181. if (regExp && loaderContext.resourcePath) {
  12182. const match = loaderContext.resourcePath.match(new RegExp(regExp));
  12183. match &&
  12184. match.forEach((matched, i) => {
  12185. url = url.replace(new RegExp("\\[" + i + "\\]", "ig"), matched);
  12186. });
  12187. }
  12188. if (
  12189. typeof loaderContext.options === "object" &&
  12190. typeof loaderContext.options.customInterpolateName === "function"
  12191. ) {
  12192. url = loaderContext.options.customInterpolateName.call(
  12193. loaderContext,
  12194. url,
  12195. name,
  12196. options
  12197. );
  12198. }
  12199. return url;
  12200. }
  12201. var interpolateName_1 = interpolateName$1;
  12202. var interpolateName = interpolateName_1;
  12203. var path$1 = path$3;
  12204. /**
  12205. * @param {string} pattern
  12206. * @param {object} options
  12207. * @param {string} options.context
  12208. * @param {string} options.hashPrefix
  12209. * @return {function}
  12210. */
  12211. var genericNames = function createGenerator(pattern, options) {
  12212. options = options || {};
  12213. var context =
  12214. options && typeof options.context === "string"
  12215. ? options.context
  12216. : process.cwd();
  12217. var hashPrefix =
  12218. options && typeof options.hashPrefix === "string" ? options.hashPrefix : "";
  12219. /**
  12220. * @param {string} localName Usually a class name
  12221. * @param {string} filepath Absolute path
  12222. * @return {string}
  12223. */
  12224. return function generate(localName, filepath) {
  12225. var name = pattern.replace(/\[local\]/gi, localName);
  12226. var loaderContext = {
  12227. resourcePath: filepath,
  12228. };
  12229. var loaderOptions = {
  12230. content:
  12231. hashPrefix +
  12232. path$1.relative(context, filepath).replace(/\\/g, "/") +
  12233. "\x00" +
  12234. localName,
  12235. context: context,
  12236. };
  12237. var genericName = interpolateName(loaderContext, name, loaderOptions);
  12238. return genericName
  12239. .replace(new RegExp("[^a-zA-Z0-9\\-_\u00A0-\uFFFF]", "g"), "-")
  12240. .replace(/^((-?[0-9])|--)/, "_$1");
  12241. };
  12242. };
  12243. var src$2 = {exports: {}};
  12244. var openParentheses = "(".charCodeAt(0);
  12245. var closeParentheses = ")".charCodeAt(0);
  12246. var singleQuote = "'".charCodeAt(0);
  12247. var doubleQuote = '"'.charCodeAt(0);
  12248. var backslash = "\\".charCodeAt(0);
  12249. var slash = "/".charCodeAt(0);
  12250. var comma = ",".charCodeAt(0);
  12251. var colon = ":".charCodeAt(0);
  12252. var star$2 = "*".charCodeAt(0);
  12253. var uLower = "u".charCodeAt(0);
  12254. var uUpper = "U".charCodeAt(0);
  12255. var plus = "+".charCodeAt(0);
  12256. var isUnicodeRange = /^[a-f0-9?-]+$/i;
  12257. var parse$1 = function(input) {
  12258. var tokens = [];
  12259. var value = input;
  12260. var next,
  12261. quote,
  12262. prev,
  12263. token,
  12264. escape,
  12265. escapePos,
  12266. whitespacePos,
  12267. parenthesesOpenPos;
  12268. var pos = 0;
  12269. var code = value.charCodeAt(pos);
  12270. var max = value.length;
  12271. var stack = [{ nodes: tokens }];
  12272. var balanced = 0;
  12273. var parent;
  12274. var name = "";
  12275. var before = "";
  12276. var after = "";
  12277. while (pos < max) {
  12278. // Whitespaces
  12279. if (code <= 32) {
  12280. next = pos;
  12281. do {
  12282. next += 1;
  12283. code = value.charCodeAt(next);
  12284. } while (code <= 32);
  12285. token = value.slice(pos, next);
  12286. prev = tokens[tokens.length - 1];
  12287. if (code === closeParentheses && balanced) {
  12288. after = token;
  12289. } else if (prev && prev.type === "div") {
  12290. prev.after = token;
  12291. prev.sourceEndIndex += token.length;
  12292. } else if (
  12293. code === comma ||
  12294. code === colon ||
  12295. (code === slash &&
  12296. value.charCodeAt(next + 1) !== star$2 &&
  12297. (!parent ||
  12298. (parent && parent.type === "function" && parent.value !== "calc")))
  12299. ) {
  12300. before = token;
  12301. } else {
  12302. tokens.push({
  12303. type: "space",
  12304. sourceIndex: pos,
  12305. sourceEndIndex: next,
  12306. value: token
  12307. });
  12308. }
  12309. pos = next;
  12310. // Quotes
  12311. } else if (code === singleQuote || code === doubleQuote) {
  12312. next = pos;
  12313. quote = code === singleQuote ? "'" : '"';
  12314. token = {
  12315. type: "string",
  12316. sourceIndex: pos,
  12317. quote: quote
  12318. };
  12319. do {
  12320. escape = false;
  12321. next = value.indexOf(quote, next + 1);
  12322. if (~next) {
  12323. escapePos = next;
  12324. while (value.charCodeAt(escapePos - 1) === backslash) {
  12325. escapePos -= 1;
  12326. escape = !escape;
  12327. }
  12328. } else {
  12329. value += quote;
  12330. next = value.length - 1;
  12331. token.unclosed = true;
  12332. }
  12333. } while (escape);
  12334. token.value = value.slice(pos + 1, next);
  12335. token.sourceEndIndex = token.unclosed ? next : next + 1;
  12336. tokens.push(token);
  12337. pos = next + 1;
  12338. code = value.charCodeAt(pos);
  12339. // Comments
  12340. } else if (code === slash && value.charCodeAt(pos + 1) === star$2) {
  12341. next = value.indexOf("*/", pos);
  12342. token = {
  12343. type: "comment",
  12344. sourceIndex: pos,
  12345. sourceEndIndex: next + 2
  12346. };
  12347. if (next === -1) {
  12348. token.unclosed = true;
  12349. next = value.length;
  12350. token.sourceEndIndex = next;
  12351. }
  12352. token.value = value.slice(pos + 2, next);
  12353. tokens.push(token);
  12354. pos = next + 2;
  12355. code = value.charCodeAt(pos);
  12356. // Operation within calc
  12357. } else if (
  12358. (code === slash || code === star$2) &&
  12359. parent &&
  12360. parent.type === "function" &&
  12361. parent.value === "calc"
  12362. ) {
  12363. token = value[pos];
  12364. tokens.push({
  12365. type: "word",
  12366. sourceIndex: pos - before.length,
  12367. sourceEndIndex: pos + token.length,
  12368. value: token
  12369. });
  12370. pos += 1;
  12371. code = value.charCodeAt(pos);
  12372. // Dividers
  12373. } else if (code === slash || code === comma || code === colon) {
  12374. token = value[pos];
  12375. tokens.push({
  12376. type: "div",
  12377. sourceIndex: pos - before.length,
  12378. sourceEndIndex: pos + token.length,
  12379. value: token,
  12380. before: before,
  12381. after: ""
  12382. });
  12383. before = "";
  12384. pos += 1;
  12385. code = value.charCodeAt(pos);
  12386. // Open parentheses
  12387. } else if (openParentheses === code) {
  12388. // Whitespaces after open parentheses
  12389. next = pos;
  12390. do {
  12391. next += 1;
  12392. code = value.charCodeAt(next);
  12393. } while (code <= 32);
  12394. parenthesesOpenPos = pos;
  12395. token = {
  12396. type: "function",
  12397. sourceIndex: pos - name.length,
  12398. value: name,
  12399. before: value.slice(parenthesesOpenPos + 1, next)
  12400. };
  12401. pos = next;
  12402. if (name === "url" && code !== singleQuote && code !== doubleQuote) {
  12403. next -= 1;
  12404. do {
  12405. escape = false;
  12406. next = value.indexOf(")", next + 1);
  12407. if (~next) {
  12408. escapePos = next;
  12409. while (value.charCodeAt(escapePos - 1) === backslash) {
  12410. escapePos -= 1;
  12411. escape = !escape;
  12412. }
  12413. } else {
  12414. value += ")";
  12415. next = value.length - 1;
  12416. token.unclosed = true;
  12417. }
  12418. } while (escape);
  12419. // Whitespaces before closed
  12420. whitespacePos = next;
  12421. do {
  12422. whitespacePos -= 1;
  12423. code = value.charCodeAt(whitespacePos);
  12424. } while (code <= 32);
  12425. if (parenthesesOpenPos < whitespacePos) {
  12426. if (pos !== whitespacePos + 1) {
  12427. token.nodes = [
  12428. {
  12429. type: "word",
  12430. sourceIndex: pos,
  12431. sourceEndIndex: whitespacePos + 1,
  12432. value: value.slice(pos, whitespacePos + 1)
  12433. }
  12434. ];
  12435. } else {
  12436. token.nodes = [];
  12437. }
  12438. if (token.unclosed && whitespacePos + 1 !== next) {
  12439. token.after = "";
  12440. token.nodes.push({
  12441. type: "space",
  12442. sourceIndex: whitespacePos + 1,
  12443. sourceEndIndex: next,
  12444. value: value.slice(whitespacePos + 1, next)
  12445. });
  12446. } else {
  12447. token.after = value.slice(whitespacePos + 1, next);
  12448. token.sourceEndIndex = next;
  12449. }
  12450. } else {
  12451. token.after = "";
  12452. token.nodes = [];
  12453. }
  12454. pos = next + 1;
  12455. token.sourceEndIndex = token.unclosed ? next : pos;
  12456. code = value.charCodeAt(pos);
  12457. tokens.push(token);
  12458. } else {
  12459. balanced += 1;
  12460. token.after = "";
  12461. token.sourceEndIndex = pos + 1;
  12462. tokens.push(token);
  12463. stack.push(token);
  12464. tokens = token.nodes = [];
  12465. parent = token;
  12466. }
  12467. name = "";
  12468. // Close parentheses
  12469. } else if (closeParentheses === code && balanced) {
  12470. pos += 1;
  12471. code = value.charCodeAt(pos);
  12472. parent.after = after;
  12473. parent.sourceEndIndex += after.length;
  12474. after = "";
  12475. balanced -= 1;
  12476. stack[stack.length - 1].sourceEndIndex = pos;
  12477. stack.pop();
  12478. parent = stack[balanced];
  12479. tokens = parent.nodes;
  12480. // Words
  12481. } else {
  12482. next = pos;
  12483. do {
  12484. if (code === backslash) {
  12485. next += 1;
  12486. }
  12487. next += 1;
  12488. code = value.charCodeAt(next);
  12489. } while (
  12490. next < max &&
  12491. !(
  12492. code <= 32 ||
  12493. code === singleQuote ||
  12494. code === doubleQuote ||
  12495. code === comma ||
  12496. code === colon ||
  12497. code === slash ||
  12498. code === openParentheses ||
  12499. (code === star$2 &&
  12500. parent &&
  12501. parent.type === "function" &&
  12502. parent.value === "calc") ||
  12503. (code === slash &&
  12504. parent.type === "function" &&
  12505. parent.value === "calc") ||
  12506. (code === closeParentheses && balanced)
  12507. )
  12508. );
  12509. token = value.slice(pos, next);
  12510. if (openParentheses === code) {
  12511. name = token;
  12512. } else if (
  12513. (uLower === token.charCodeAt(0) || uUpper === token.charCodeAt(0)) &&
  12514. plus === token.charCodeAt(1) &&
  12515. isUnicodeRange.test(token.slice(2))
  12516. ) {
  12517. tokens.push({
  12518. type: "unicode-range",
  12519. sourceIndex: pos,
  12520. sourceEndIndex: next,
  12521. value: token
  12522. });
  12523. } else {
  12524. tokens.push({
  12525. type: "word",
  12526. sourceIndex: pos,
  12527. sourceEndIndex: next,
  12528. value: token
  12529. });
  12530. }
  12531. pos = next;
  12532. }
  12533. }
  12534. for (pos = stack.length - 1; pos; pos -= 1) {
  12535. stack[pos].unclosed = true;
  12536. stack[pos].sourceEndIndex = value.length;
  12537. }
  12538. return stack[0].nodes;
  12539. };
  12540. var walk$2 = function walk(nodes, cb, bubble) {
  12541. var i, max, node, result;
  12542. for (i = 0, max = nodes.length; i < max; i += 1) {
  12543. node = nodes[i];
  12544. if (!bubble) {
  12545. result = cb(node, i, nodes);
  12546. }
  12547. if (
  12548. result !== false &&
  12549. node.type === "function" &&
  12550. Array.isArray(node.nodes)
  12551. ) {
  12552. walk(node.nodes, cb, bubble);
  12553. }
  12554. if (bubble) {
  12555. cb(node, i, nodes);
  12556. }
  12557. }
  12558. };
  12559. function stringifyNode(node, custom) {
  12560. var type = node.type;
  12561. var value = node.value;
  12562. var buf;
  12563. var customResult;
  12564. if (custom && (customResult = custom(node)) !== undefined) {
  12565. return customResult;
  12566. } else if (type === "word" || type === "space") {
  12567. return value;
  12568. } else if (type === "string") {
  12569. buf = node.quote || "";
  12570. return buf + value + (node.unclosed ? "" : buf);
  12571. } else if (type === "comment") {
  12572. return "/*" + value + (node.unclosed ? "" : "*/");
  12573. } else if (type === "div") {
  12574. return (node.before || "") + value + (node.after || "");
  12575. } else if (Array.isArray(node.nodes)) {
  12576. buf = stringify$1(node.nodes, custom);
  12577. if (type !== "function") {
  12578. return buf;
  12579. }
  12580. return (
  12581. value +
  12582. "(" +
  12583. (node.before || "") +
  12584. buf +
  12585. (node.after || "") +
  12586. (node.unclosed ? "" : ")")
  12587. );
  12588. }
  12589. return value;
  12590. }
  12591. function stringify$1(nodes, custom) {
  12592. var result, i;
  12593. if (Array.isArray(nodes)) {
  12594. result = "";
  12595. for (i = nodes.length - 1; ~i; i -= 1) {
  12596. result = stringifyNode(nodes[i], custom) + result;
  12597. }
  12598. return result;
  12599. }
  12600. return stringifyNode(nodes, custom);
  12601. }
  12602. var stringify_1 = stringify$1;
  12603. var unit;
  12604. var hasRequiredUnit;
  12605. function requireUnit () {
  12606. if (hasRequiredUnit) return unit;
  12607. hasRequiredUnit = 1;
  12608. var minus = "-".charCodeAt(0);
  12609. var plus = "+".charCodeAt(0);
  12610. var dot = ".".charCodeAt(0);
  12611. var exp = "e".charCodeAt(0);
  12612. var EXP = "E".charCodeAt(0);
  12613. // Check if three code points would start a number
  12614. // https://www.w3.org/TR/css-syntax-3/#starts-with-a-number
  12615. function likeNumber(value) {
  12616. var code = value.charCodeAt(0);
  12617. var nextCode;
  12618. if (code === plus || code === minus) {
  12619. nextCode = value.charCodeAt(1);
  12620. if (nextCode >= 48 && nextCode <= 57) {
  12621. return true;
  12622. }
  12623. var nextNextCode = value.charCodeAt(2);
  12624. if (nextCode === dot && nextNextCode >= 48 && nextNextCode <= 57) {
  12625. return true;
  12626. }
  12627. return false;
  12628. }
  12629. if (code === dot) {
  12630. nextCode = value.charCodeAt(1);
  12631. if (nextCode >= 48 && nextCode <= 57) {
  12632. return true;
  12633. }
  12634. return false;
  12635. }
  12636. if (code >= 48 && code <= 57) {
  12637. return true;
  12638. }
  12639. return false;
  12640. }
  12641. // Consume a number
  12642. // https://www.w3.org/TR/css-syntax-3/#consume-number
  12643. unit = function(value) {
  12644. var pos = 0;
  12645. var length = value.length;
  12646. var code;
  12647. var nextCode;
  12648. var nextNextCode;
  12649. if (length === 0 || !likeNumber(value)) {
  12650. return false;
  12651. }
  12652. code = value.charCodeAt(pos);
  12653. if (code === plus || code === minus) {
  12654. pos++;
  12655. }
  12656. while (pos < length) {
  12657. code = value.charCodeAt(pos);
  12658. if (code < 48 || code > 57) {
  12659. break;
  12660. }
  12661. pos += 1;
  12662. }
  12663. code = value.charCodeAt(pos);
  12664. nextCode = value.charCodeAt(pos + 1);
  12665. if (code === dot && nextCode >= 48 && nextCode <= 57) {
  12666. pos += 2;
  12667. while (pos < length) {
  12668. code = value.charCodeAt(pos);
  12669. if (code < 48 || code > 57) {
  12670. break;
  12671. }
  12672. pos += 1;
  12673. }
  12674. }
  12675. code = value.charCodeAt(pos);
  12676. nextCode = value.charCodeAt(pos + 1);
  12677. nextNextCode = value.charCodeAt(pos + 2);
  12678. if (
  12679. (code === exp || code === EXP) &&
  12680. ((nextCode >= 48 && nextCode <= 57) ||
  12681. ((nextCode === plus || nextCode === minus) &&
  12682. nextNextCode >= 48 &&
  12683. nextNextCode <= 57))
  12684. ) {
  12685. pos += nextCode === plus || nextCode === minus ? 3 : 2;
  12686. while (pos < length) {
  12687. code = value.charCodeAt(pos);
  12688. if (code < 48 || code > 57) {
  12689. break;
  12690. }
  12691. pos += 1;
  12692. }
  12693. }
  12694. return {
  12695. number: value.slice(0, pos),
  12696. unit: value.slice(pos)
  12697. };
  12698. };
  12699. return unit;
  12700. }
  12701. var parse = parse$1;
  12702. var walk$1 = walk$2;
  12703. var stringify = stringify_1;
  12704. function ValueParser(value) {
  12705. if (this instanceof ValueParser) {
  12706. this.nodes = parse(value);
  12707. return this;
  12708. }
  12709. return new ValueParser(value);
  12710. }
  12711. ValueParser.prototype.toString = function() {
  12712. return Array.isArray(this.nodes) ? stringify(this.nodes) : "";
  12713. };
  12714. ValueParser.prototype.walk = function(cb, bubble) {
  12715. walk$1(this.nodes, cb, bubble);
  12716. return this;
  12717. };
  12718. ValueParser.unit = requireUnit();
  12719. ValueParser.walk = walk$1;
  12720. ValueParser.stringify = stringify;
  12721. var lib = ValueParser;
  12722. const selectorParser$1 = distExports;
  12723. const valueParser = lib;
  12724. const { extractICSS } = src$4;
  12725. const isSpacing = (node) => node.type === "combinator" && node.value === " ";
  12726. function normalizeNodeArray(nodes) {
  12727. const array = [];
  12728. nodes.forEach((x) => {
  12729. if (Array.isArray(x)) {
  12730. normalizeNodeArray(x).forEach((item) => {
  12731. array.push(item);
  12732. });
  12733. } else if (x) {
  12734. array.push(x);
  12735. }
  12736. });
  12737. if (array.length > 0 && isSpacing(array[array.length - 1])) {
  12738. array.pop();
  12739. }
  12740. return array;
  12741. }
  12742. function localizeNode(rule, mode, localAliasMap) {
  12743. const transform = (node, context) => {
  12744. if (context.ignoreNextSpacing && !isSpacing(node)) {
  12745. throw new Error("Missing whitespace after " + context.ignoreNextSpacing);
  12746. }
  12747. if (context.enforceNoSpacing && isSpacing(node)) {
  12748. throw new Error("Missing whitespace before " + context.enforceNoSpacing);
  12749. }
  12750. let newNodes;
  12751. switch (node.type) {
  12752. case "root": {
  12753. let resultingGlobal;
  12754. context.hasPureGlobals = false;
  12755. newNodes = node.nodes.map((n) => {
  12756. const nContext = {
  12757. global: context.global,
  12758. lastWasSpacing: true,
  12759. hasLocals: false,
  12760. explicit: false,
  12761. };
  12762. n = transform(n, nContext);
  12763. if (typeof resultingGlobal === "undefined") {
  12764. resultingGlobal = nContext.global;
  12765. } else if (resultingGlobal !== nContext.global) {
  12766. throw new Error(
  12767. 'Inconsistent rule global/local result in rule "' +
  12768. node +
  12769. '" (multiple selectors must result in the same mode for the rule)'
  12770. );
  12771. }
  12772. if (!nContext.hasLocals) {
  12773. context.hasPureGlobals = true;
  12774. }
  12775. return n;
  12776. });
  12777. context.global = resultingGlobal;
  12778. node.nodes = normalizeNodeArray(newNodes);
  12779. break;
  12780. }
  12781. case "selector": {
  12782. newNodes = node.map((childNode) => transform(childNode, context));
  12783. node = node.clone();
  12784. node.nodes = normalizeNodeArray(newNodes);
  12785. break;
  12786. }
  12787. case "combinator": {
  12788. if (isSpacing(node)) {
  12789. if (context.ignoreNextSpacing) {
  12790. context.ignoreNextSpacing = false;
  12791. context.lastWasSpacing = false;
  12792. context.enforceNoSpacing = false;
  12793. return null;
  12794. }
  12795. context.lastWasSpacing = true;
  12796. return node;
  12797. }
  12798. break;
  12799. }
  12800. case "pseudo": {
  12801. let childContext;
  12802. const isNested = !!node.length;
  12803. const isScoped = node.value === ":local" || node.value === ":global";
  12804. const isImportExport =
  12805. node.value === ":import" || node.value === ":export";
  12806. if (isImportExport) {
  12807. context.hasLocals = true;
  12808. // :local(.foo)
  12809. } else if (isNested) {
  12810. if (isScoped) {
  12811. if (node.nodes.length === 0) {
  12812. throw new Error(`${node.value}() can't be empty`);
  12813. }
  12814. if (context.inside) {
  12815. throw new Error(
  12816. `A ${node.value} is not allowed inside of a ${context.inside}(...)`
  12817. );
  12818. }
  12819. childContext = {
  12820. global: node.value === ":global",
  12821. inside: node.value,
  12822. hasLocals: false,
  12823. explicit: true,
  12824. };
  12825. newNodes = node
  12826. .map((childNode) => transform(childNode, childContext))
  12827. .reduce((acc, next) => acc.concat(next.nodes), []);
  12828. if (newNodes.length) {
  12829. const { before, after } = node.spaces;
  12830. const first = newNodes[0];
  12831. const last = newNodes[newNodes.length - 1];
  12832. first.spaces = { before, after: first.spaces.after };
  12833. last.spaces = { before: last.spaces.before, after };
  12834. }
  12835. node = newNodes;
  12836. break;
  12837. } else {
  12838. childContext = {
  12839. global: context.global,
  12840. inside: context.inside,
  12841. lastWasSpacing: true,
  12842. hasLocals: false,
  12843. explicit: context.explicit,
  12844. };
  12845. newNodes = node.map((childNode) => {
  12846. const newContext = {
  12847. ...childContext,
  12848. enforceNoSpacing: false,
  12849. };
  12850. const result = transform(childNode, newContext);
  12851. childContext.global = newContext.global;
  12852. childContext.hasLocals = newContext.hasLocals;
  12853. return result;
  12854. });
  12855. node = node.clone();
  12856. node.nodes = normalizeNodeArray(newNodes);
  12857. if (childContext.hasLocals) {
  12858. context.hasLocals = true;
  12859. }
  12860. }
  12861. break;
  12862. //:local .foo .bar
  12863. } else if (isScoped) {
  12864. if (context.inside) {
  12865. throw new Error(
  12866. `A ${node.value} is not allowed inside of a ${context.inside}(...)`
  12867. );
  12868. }
  12869. const addBackSpacing = !!node.spaces.before;
  12870. context.ignoreNextSpacing = context.lastWasSpacing
  12871. ? node.value
  12872. : false;
  12873. context.enforceNoSpacing = context.lastWasSpacing
  12874. ? false
  12875. : node.value;
  12876. context.global = node.value === ":global";
  12877. context.explicit = true;
  12878. // because this node has spacing that is lost when we remove it
  12879. // we make up for it by adding an extra combinator in since adding
  12880. // spacing on the parent selector doesn't work
  12881. return addBackSpacing
  12882. ? selectorParser$1.combinator({ value: " " })
  12883. : null;
  12884. }
  12885. break;
  12886. }
  12887. case "id":
  12888. case "class": {
  12889. if (!node.value) {
  12890. throw new Error("Invalid class or id selector syntax");
  12891. }
  12892. if (context.global) {
  12893. break;
  12894. }
  12895. const isImportedValue = localAliasMap.has(node.value);
  12896. const isImportedWithExplicitScope = isImportedValue && context.explicit;
  12897. if (!isImportedValue || isImportedWithExplicitScope) {
  12898. const innerNode = node.clone();
  12899. innerNode.spaces = { before: "", after: "" };
  12900. node = selectorParser$1.pseudo({
  12901. value: ":local",
  12902. nodes: [innerNode],
  12903. spaces: node.spaces,
  12904. });
  12905. context.hasLocals = true;
  12906. }
  12907. break;
  12908. }
  12909. }
  12910. context.lastWasSpacing = false;
  12911. context.ignoreNextSpacing = false;
  12912. context.enforceNoSpacing = false;
  12913. return node;
  12914. };
  12915. const rootContext = {
  12916. global: mode === "global",
  12917. hasPureGlobals: false,
  12918. };
  12919. rootContext.selector = selectorParser$1((root) => {
  12920. transform(root, rootContext);
  12921. }).processSync(rule, { updateSelector: false, lossless: true });
  12922. return rootContext;
  12923. }
  12924. function localizeDeclNode(node, context) {
  12925. switch (node.type) {
  12926. case "word":
  12927. if (context.localizeNextItem) {
  12928. if (!context.localAliasMap.has(node.value)) {
  12929. node.value = ":local(" + node.value + ")";
  12930. context.localizeNextItem = false;
  12931. }
  12932. }
  12933. break;
  12934. case "function":
  12935. if (
  12936. context.options &&
  12937. context.options.rewriteUrl &&
  12938. node.value.toLowerCase() === "url"
  12939. ) {
  12940. node.nodes.map((nestedNode) => {
  12941. if (nestedNode.type !== "string" && nestedNode.type !== "word") {
  12942. return;
  12943. }
  12944. let newUrl = context.options.rewriteUrl(
  12945. context.global,
  12946. nestedNode.value
  12947. );
  12948. switch (nestedNode.type) {
  12949. case "string":
  12950. if (nestedNode.quote === "'") {
  12951. newUrl = newUrl.replace(/(\\)/g, "\\$1").replace(/'/g, "\\'");
  12952. }
  12953. if (nestedNode.quote === '"') {
  12954. newUrl = newUrl.replace(/(\\)/g, "\\$1").replace(/"/g, '\\"');
  12955. }
  12956. break;
  12957. case "word":
  12958. newUrl = newUrl.replace(/("|'|\)|\\)/g, "\\$1");
  12959. break;
  12960. }
  12961. nestedNode.value = newUrl;
  12962. });
  12963. }
  12964. break;
  12965. }
  12966. return node;
  12967. }
  12968. // `none` is special value, other is global values
  12969. const specialKeywords = [
  12970. "none",
  12971. "inherit",
  12972. "initial",
  12973. "revert",
  12974. "revert-layer",
  12975. "unset",
  12976. ];
  12977. function localizeDeclarationValues(localize, declaration, context) {
  12978. const valueNodes = valueParser(declaration.value);
  12979. valueNodes.walk((node, index, nodes) => {
  12980. if (
  12981. node.type === "function" &&
  12982. (node.value.toLowerCase() === "var" || node.value.toLowerCase() === "env")
  12983. ) {
  12984. return false;
  12985. }
  12986. if (
  12987. node.type === "word" &&
  12988. specialKeywords.includes(node.value.toLowerCase())
  12989. ) {
  12990. return;
  12991. }
  12992. const subContext = {
  12993. options: context.options,
  12994. global: context.global,
  12995. localizeNextItem: localize && !context.global,
  12996. localAliasMap: context.localAliasMap,
  12997. };
  12998. nodes[index] = localizeDeclNode(node, subContext);
  12999. });
  13000. declaration.value = valueNodes.toString();
  13001. }
  13002. function localizeDeclaration(declaration, context) {
  13003. const isAnimation = /animation$/i.test(declaration.prop);
  13004. if (isAnimation) {
  13005. // letter
  13006. // An uppercase letter or a lowercase letter.
  13007. //
  13008. // ident-start code point
  13009. // A letter, a non-ASCII code point, or U+005F LOW LINE (_).
  13010. //
  13011. // ident code point
  13012. // An ident-start code point, a digit, or U+002D HYPHEN-MINUS (-).
  13013. // We don't validate `hex digits`, because we don't need it, it is work of linters.
  13014. const validIdent =
  13015. /^-?([a-z\u0080-\uFFFF_]|(\\[^\r\n\f])|-)((\\[^\r\n\f])|[a-z\u0080-\uFFFF_0-9-])*$/i;
  13016. /*
  13017. The spec defines some keywords that you can use to describe properties such as the timing
  13018. function. These are still valid animation names, so as long as there is a property that accepts
  13019. a keyword, it is given priority. Only when all the properties that can take a keyword are
  13020. exhausted can the animation name be set to the keyword. I.e.
  13021. animation: infinite infinite;
  13022. The animation will repeat an infinite number of times from the first argument, and will have an
  13023. animation name of infinite from the second.
  13024. */
  13025. const animationKeywords = {
  13026. // animation-direction
  13027. $normal: 1,
  13028. $reverse: 1,
  13029. $alternate: 1,
  13030. "$alternate-reverse": 1,
  13031. // animation-fill-mode
  13032. $forwards: 1,
  13033. $backwards: 1,
  13034. $both: 1,
  13035. // animation-iteration-count
  13036. $infinite: 1,
  13037. // animation-play-state
  13038. $paused: 1,
  13039. $running: 1,
  13040. // animation-timing-function
  13041. $ease: 1,
  13042. "$ease-in": 1,
  13043. "$ease-out": 1,
  13044. "$ease-in-out": 1,
  13045. $linear: 1,
  13046. "$step-end": 1,
  13047. "$step-start": 1,
  13048. // Special
  13049. $none: Infinity, // No matter how many times you write none, it will never be an animation name
  13050. // Global values
  13051. $initial: Infinity,
  13052. $inherit: Infinity,
  13053. $unset: Infinity,
  13054. $revert: Infinity,
  13055. "$revert-layer": Infinity,
  13056. };
  13057. let parsedAnimationKeywords = {};
  13058. const valueNodes = valueParser(declaration.value).walk((node) => {
  13059. // If div-token appeared (represents as comma ','), a possibility of an animation-keywords should be reflesh.
  13060. if (node.type === "div") {
  13061. parsedAnimationKeywords = {};
  13062. return;
  13063. }
  13064. // Do not handle nested functions
  13065. else if (node.type === "function") {
  13066. return false;
  13067. }
  13068. // Ignore all except word
  13069. else if (node.type !== "word") {
  13070. return;
  13071. }
  13072. const value = node.type === "word" ? node.value.toLowerCase() : null;
  13073. let shouldParseAnimationName = false;
  13074. if (value && validIdent.test(value)) {
  13075. if ("$" + value in animationKeywords) {
  13076. parsedAnimationKeywords["$" + value] =
  13077. "$" + value in parsedAnimationKeywords
  13078. ? parsedAnimationKeywords["$" + value] + 1
  13079. : 0;
  13080. shouldParseAnimationName =
  13081. parsedAnimationKeywords["$" + value] >=
  13082. animationKeywords["$" + value];
  13083. } else {
  13084. shouldParseAnimationName = true;
  13085. }
  13086. }
  13087. const subContext = {
  13088. options: context.options,
  13089. global: context.global,
  13090. localizeNextItem: shouldParseAnimationName && !context.global,
  13091. localAliasMap: context.localAliasMap,
  13092. };
  13093. return localizeDeclNode(node, subContext);
  13094. });
  13095. declaration.value = valueNodes.toString();
  13096. return;
  13097. }
  13098. const isAnimationName = /animation(-name)?$/i.test(declaration.prop);
  13099. if (isAnimationName) {
  13100. return localizeDeclarationValues(true, declaration, context);
  13101. }
  13102. const hasUrl = /url\(/i.test(declaration.value);
  13103. if (hasUrl) {
  13104. return localizeDeclarationValues(false, declaration, context);
  13105. }
  13106. }
  13107. src$2.exports = (options = {}) => {
  13108. if (
  13109. options &&
  13110. options.mode &&
  13111. options.mode !== "global" &&
  13112. options.mode !== "local" &&
  13113. options.mode !== "pure"
  13114. ) {
  13115. throw new Error(
  13116. 'options.mode must be either "global", "local" or "pure" (default "local")'
  13117. );
  13118. }
  13119. const pureMode = options && options.mode === "pure";
  13120. const globalMode = options && options.mode === "global";
  13121. return {
  13122. postcssPlugin: "postcss-modules-local-by-default",
  13123. prepare() {
  13124. const localAliasMap = new Map();
  13125. return {
  13126. Once(root) {
  13127. const { icssImports } = extractICSS(root, false);
  13128. Object.keys(icssImports).forEach((key) => {
  13129. Object.keys(icssImports[key]).forEach((prop) => {
  13130. localAliasMap.set(prop, icssImports[key][prop]);
  13131. });
  13132. });
  13133. root.walkAtRules((atRule) => {
  13134. if (/keyframes$/i.test(atRule.name)) {
  13135. const globalMatch = /^\s*:global\s*\((.+)\)\s*$/.exec(
  13136. atRule.params
  13137. );
  13138. const localMatch = /^\s*:local\s*\((.+)\)\s*$/.exec(
  13139. atRule.params
  13140. );
  13141. let globalKeyframes = globalMode;
  13142. if (globalMatch) {
  13143. if (pureMode) {
  13144. throw atRule.error(
  13145. "@keyframes :global(...) is not allowed in pure mode"
  13146. );
  13147. }
  13148. atRule.params = globalMatch[1];
  13149. globalKeyframes = true;
  13150. } else if (localMatch) {
  13151. atRule.params = localMatch[0];
  13152. globalKeyframes = false;
  13153. } else if (!globalMode) {
  13154. if (atRule.params && !localAliasMap.has(atRule.params)) {
  13155. atRule.params = ":local(" + atRule.params + ")";
  13156. }
  13157. }
  13158. atRule.walkDecls((declaration) => {
  13159. localizeDeclaration(declaration, {
  13160. localAliasMap,
  13161. options: options,
  13162. global: globalKeyframes,
  13163. });
  13164. });
  13165. } else if (atRule.nodes) {
  13166. atRule.nodes.forEach((declaration) => {
  13167. if (declaration.type === "decl") {
  13168. localizeDeclaration(declaration, {
  13169. localAliasMap,
  13170. options: options,
  13171. global: globalMode,
  13172. });
  13173. }
  13174. });
  13175. }
  13176. });
  13177. root.walkRules((rule) => {
  13178. if (
  13179. rule.parent &&
  13180. rule.parent.type === "atrule" &&
  13181. /keyframes$/i.test(rule.parent.name)
  13182. ) {
  13183. // ignore keyframe rules
  13184. return;
  13185. }
  13186. const context = localizeNode(rule, options.mode, localAliasMap);
  13187. context.options = options;
  13188. context.localAliasMap = localAliasMap;
  13189. if (pureMode && context.hasPureGlobals) {
  13190. throw rule.error(
  13191. 'Selector "' +
  13192. rule.selector +
  13193. '" is not pure ' +
  13194. "(pure selectors must contain at least one local class or id)"
  13195. );
  13196. }
  13197. rule.selector = context.selector;
  13198. // Less-syntax mixins parse as rules with no nodes
  13199. if (rule.nodes) {
  13200. rule.nodes.forEach((declaration) =>
  13201. localizeDeclaration(declaration, context)
  13202. );
  13203. }
  13204. });
  13205. },
  13206. };
  13207. },
  13208. };
  13209. };
  13210. src$2.exports.postcss = true;
  13211. var srcExports$1 = src$2.exports;
  13212. const selectorParser = distExports;
  13213. const hasOwnProperty = Object.prototype.hasOwnProperty;
  13214. function getSingleLocalNamesForComposes(root) {
  13215. return root.nodes.map((node) => {
  13216. if (node.type !== "selector" || node.nodes.length !== 1) {
  13217. throw new Error(
  13218. `composition is only allowed when selector is single :local class name not in "${root}"`
  13219. );
  13220. }
  13221. node = node.nodes[0];
  13222. if (
  13223. node.type !== "pseudo" ||
  13224. node.value !== ":local" ||
  13225. node.nodes.length !== 1
  13226. ) {
  13227. throw new Error(
  13228. 'composition is only allowed when selector is single :local class name not in "' +
  13229. root +
  13230. '", "' +
  13231. node +
  13232. '" is weird'
  13233. );
  13234. }
  13235. node = node.first;
  13236. if (node.type !== "selector" || node.length !== 1) {
  13237. throw new Error(
  13238. 'composition is only allowed when selector is single :local class name not in "' +
  13239. root +
  13240. '", "' +
  13241. node +
  13242. '" is weird'
  13243. );
  13244. }
  13245. node = node.first;
  13246. if (node.type !== "class") {
  13247. // 'id' is not possible, because you can't compose ids
  13248. throw new Error(
  13249. 'composition is only allowed when selector is single :local class name not in "' +
  13250. root +
  13251. '", "' +
  13252. node +
  13253. '" is weird'
  13254. );
  13255. }
  13256. return node.value;
  13257. });
  13258. }
  13259. const whitespace = "[\\x20\\t\\r\\n\\f]";
  13260. const unescapeRegExp = new RegExp(
  13261. "\\\\([\\da-f]{1,6}" + whitespace + "?|(" + whitespace + ")|.)",
  13262. "ig"
  13263. );
  13264. function unescape$1(str) {
  13265. return str.replace(unescapeRegExp, (_, escaped, escapedWhitespace) => {
  13266. const high = "0x" + escaped - 0x10000;
  13267. // NaN means non-codepoint
  13268. // Workaround erroneous numeric interpretation of +"0x"
  13269. return high !== high || escapedWhitespace
  13270. ? escaped
  13271. : high < 0
  13272. ? // BMP codepoint
  13273. String.fromCharCode(high + 0x10000)
  13274. : // Supplemental Plane codepoint (surrogate pair)
  13275. String.fromCharCode((high >> 10) | 0xd800, (high & 0x3ff) | 0xdc00);
  13276. });
  13277. }
  13278. const plugin = (options = {}) => {
  13279. const generateScopedName =
  13280. (options && options.generateScopedName) || plugin.generateScopedName;
  13281. const generateExportEntry =
  13282. (options && options.generateExportEntry) || plugin.generateExportEntry;
  13283. const exportGlobals = options && options.exportGlobals;
  13284. return {
  13285. postcssPlugin: "postcss-modules-scope",
  13286. Once(root, { rule }) {
  13287. const exports = Object.create(null);
  13288. function exportScopedName(name, rawName) {
  13289. const scopedName = generateScopedName(
  13290. rawName ? rawName : name,
  13291. root.source.input.from,
  13292. root.source.input.css
  13293. );
  13294. const exportEntry = generateExportEntry(
  13295. rawName ? rawName : name,
  13296. scopedName,
  13297. root.source.input.from,
  13298. root.source.input.css
  13299. );
  13300. const { key, value } = exportEntry;
  13301. exports[key] = exports[key] || [];
  13302. if (exports[key].indexOf(value) < 0) {
  13303. exports[key].push(value);
  13304. }
  13305. return scopedName;
  13306. }
  13307. function localizeNode(node) {
  13308. switch (node.type) {
  13309. case "selector":
  13310. node.nodes = node.map(localizeNode);
  13311. return node;
  13312. case "class":
  13313. return selectorParser.className({
  13314. value: exportScopedName(
  13315. node.value,
  13316. node.raws && node.raws.value ? node.raws.value : null
  13317. ),
  13318. });
  13319. case "id": {
  13320. return selectorParser.id({
  13321. value: exportScopedName(
  13322. node.value,
  13323. node.raws && node.raws.value ? node.raws.value : null
  13324. ),
  13325. });
  13326. }
  13327. }
  13328. throw new Error(
  13329. `${node.type} ("${node}") is not allowed in a :local block`
  13330. );
  13331. }
  13332. function traverseNode(node) {
  13333. switch (node.type) {
  13334. case "pseudo":
  13335. if (node.value === ":local") {
  13336. if (node.nodes.length !== 1) {
  13337. throw new Error('Unexpected comma (",") in :local block');
  13338. }
  13339. const selector = localizeNode(node.first, node.spaces);
  13340. // move the spaces that were around the psuedo selector to the first
  13341. // non-container node
  13342. selector.first.spaces = node.spaces;
  13343. const nextNode = node.next();
  13344. if (
  13345. nextNode &&
  13346. nextNode.type === "combinator" &&
  13347. nextNode.value === " " &&
  13348. /\\[A-F0-9]{1,6}$/.test(selector.last.value)
  13349. ) {
  13350. selector.last.spaces.after = " ";
  13351. }
  13352. node.replaceWith(selector);
  13353. return;
  13354. }
  13355. /* falls through */
  13356. case "root":
  13357. case "selector": {
  13358. node.each(traverseNode);
  13359. break;
  13360. }
  13361. case "id":
  13362. case "class":
  13363. if (exportGlobals) {
  13364. exports[node.value] = [node.value];
  13365. }
  13366. break;
  13367. }
  13368. return node;
  13369. }
  13370. // Find any :import and remember imported names
  13371. const importedNames = {};
  13372. root.walkRules(/^:import\(.+\)$/, (rule) => {
  13373. rule.walkDecls((decl) => {
  13374. importedNames[decl.prop] = true;
  13375. });
  13376. });
  13377. // Find any :local selectors
  13378. root.walkRules((rule) => {
  13379. let parsedSelector = selectorParser().astSync(rule);
  13380. rule.selector = traverseNode(parsedSelector.clone()).toString();
  13381. rule.walkDecls(/composes|compose-with/i, (decl) => {
  13382. const localNames = getSingleLocalNamesForComposes(parsedSelector);
  13383. const classes = decl.value.split(/\s+/);
  13384. classes.forEach((className) => {
  13385. const global = /^global\(([^)]+)\)$/.exec(className);
  13386. if (global) {
  13387. localNames.forEach((exportedName) => {
  13388. exports[exportedName].push(global[1]);
  13389. });
  13390. } else if (hasOwnProperty.call(importedNames, className)) {
  13391. localNames.forEach((exportedName) => {
  13392. exports[exportedName].push(className);
  13393. });
  13394. } else if (hasOwnProperty.call(exports, className)) {
  13395. localNames.forEach((exportedName) => {
  13396. exports[className].forEach((item) => {
  13397. exports[exportedName].push(item);
  13398. });
  13399. });
  13400. } else {
  13401. throw decl.error(
  13402. `referenced class name "${className}" in ${decl.prop} not found`
  13403. );
  13404. }
  13405. });
  13406. decl.remove();
  13407. });
  13408. // Find any :local values
  13409. rule.walkDecls((decl) => {
  13410. if (!/:local\s*\((.+?)\)/.test(decl.value)) {
  13411. return;
  13412. }
  13413. let tokens = decl.value.split(/(,|'[^']*'|"[^"]*")/);
  13414. tokens = tokens.map((token, idx) => {
  13415. if (idx === 0 || tokens[idx - 1] === ",") {
  13416. let result = token;
  13417. const localMatch = /:local\s*\((.+?)\)/.exec(token);
  13418. if (localMatch) {
  13419. const input = localMatch.input;
  13420. const matchPattern = localMatch[0];
  13421. const matchVal = localMatch[1];
  13422. const newVal = exportScopedName(matchVal);
  13423. result = input.replace(matchPattern, newVal);
  13424. } else {
  13425. return token;
  13426. }
  13427. return result;
  13428. } else {
  13429. return token;
  13430. }
  13431. });
  13432. decl.value = tokens.join("");
  13433. });
  13434. });
  13435. // Find any :local keyframes
  13436. root.walkAtRules(/keyframes$/i, (atRule) => {
  13437. const localMatch = /^\s*:local\s*\((.+?)\)\s*$/.exec(atRule.params);
  13438. if (!localMatch) {
  13439. return;
  13440. }
  13441. atRule.params = exportScopedName(localMatch[1]);
  13442. });
  13443. // If we found any :locals, insert an :export rule
  13444. const exportedNames = Object.keys(exports);
  13445. if (exportedNames.length > 0) {
  13446. const exportRule = rule({ selector: ":export" });
  13447. exportedNames.forEach((exportedName) =>
  13448. exportRule.append({
  13449. prop: exportedName,
  13450. value: exports[exportedName].join(" "),
  13451. raws: { before: "\n " },
  13452. })
  13453. );
  13454. root.append(exportRule);
  13455. }
  13456. },
  13457. };
  13458. };
  13459. plugin.postcss = true;
  13460. plugin.generateScopedName = function (name, path) {
  13461. const sanitisedPath = path
  13462. .replace(/\.[^./\\]+$/, "")
  13463. .replace(/[\W_]+/g, "_")
  13464. .replace(/^_|_$/g, "");
  13465. return `_${sanitisedPath}__${name}`.trim();
  13466. };
  13467. plugin.generateExportEntry = function (name, scopedName) {
  13468. return {
  13469. key: unescape$1(name),
  13470. value: unescape$1(scopedName),
  13471. };
  13472. };
  13473. var src$1 = plugin;
  13474. function hash(str) {
  13475. var hash = 5381,
  13476. i = str.length;
  13477. while(i) {
  13478. hash = (hash * 33) ^ str.charCodeAt(--i);
  13479. }
  13480. /* JavaScript does bitwise operations (like XOR, above) on 32-bit signed
  13481. * integers. Since we want the results to be always positive, convert the
  13482. * signed int to an unsigned by doing an unsigned bitshift. */
  13483. return hash >>> 0;
  13484. }
  13485. var stringHash = hash;
  13486. var src = {exports: {}};
  13487. const ICSSUtils = src$4;
  13488. const matchImports = /^(.+?|\([\s\S]+?\))\s+from\s+("[^"]*"|'[^']*'|[\w-]+)$/;
  13489. const matchValueDefinition = /(?:\s+|^)([\w-]+):?(.*?)$/;
  13490. const matchImport = /^([\w-]+)(?:\s+as\s+([\w-]+))?/;
  13491. src.exports = (options) => {
  13492. let importIndex = 0;
  13493. const createImportedName =
  13494. (options && options.createImportedName) ||
  13495. ((importName /*, path*/) =>
  13496. `i__const_${importName.replace(/\W/g, "_")}_${importIndex++}`);
  13497. return {
  13498. postcssPlugin: "postcss-modules-values",
  13499. prepare(result) {
  13500. const importAliases = [];
  13501. const definitions = {};
  13502. return {
  13503. Once(root, postcss) {
  13504. root.walkAtRules(/value/i, (atRule) => {
  13505. const matches = atRule.params.match(matchImports);
  13506. if (matches) {
  13507. let [, /*match*/ aliases, path] = matches;
  13508. // We can use constants for path names
  13509. if (definitions[path]) {
  13510. path = definitions[path];
  13511. }
  13512. const imports = aliases
  13513. .replace(/^\(\s*([\s\S]+)\s*\)$/, "$1")
  13514. .split(/\s*,\s*/)
  13515. .map((alias) => {
  13516. const tokens = matchImport.exec(alias);
  13517. if (tokens) {
  13518. const [, /*match*/ theirName, myName = theirName] = tokens;
  13519. const importedName = createImportedName(myName);
  13520. definitions[myName] = importedName;
  13521. return { theirName, importedName };
  13522. } else {
  13523. throw new Error(`@import statement "${alias}" is invalid!`);
  13524. }
  13525. });
  13526. importAliases.push({ path, imports });
  13527. atRule.remove();
  13528. return;
  13529. }
  13530. if (atRule.params.indexOf("@value") !== -1) {
  13531. result.warn("Invalid value definition: " + atRule.params);
  13532. }
  13533. let [, key, value] = `${atRule.params}${atRule.raws.between}`.match(
  13534. matchValueDefinition
  13535. );
  13536. const normalizedValue = value.replace(/\/\*((?!\*\/).*?)\*\//g, "");
  13537. if (normalizedValue.length === 0) {
  13538. result.warn("Invalid value definition: " + atRule.params);
  13539. atRule.remove();
  13540. return;
  13541. }
  13542. let isOnlySpace = /^\s+$/.test(normalizedValue);
  13543. if (!isOnlySpace) {
  13544. value = value.trim();
  13545. }
  13546. // Add to the definitions, knowing that values can refer to each other
  13547. definitions[key] = ICSSUtils.replaceValueSymbols(
  13548. value,
  13549. definitions
  13550. );
  13551. atRule.remove();
  13552. });
  13553. /* If we have no definitions, don't continue */
  13554. if (!Object.keys(definitions).length) {
  13555. return;
  13556. }
  13557. /* Perform replacements */
  13558. ICSSUtils.replaceSymbols(root, definitions);
  13559. /* 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 */
  13560. const exportDeclarations = Object.keys(definitions).map((key) =>
  13561. postcss.decl({
  13562. value: definitions[key],
  13563. prop: key,
  13564. raws: { before: "\n " },
  13565. })
  13566. );
  13567. /* Add export rules if any */
  13568. if (exportDeclarations.length > 0) {
  13569. const exportRule = postcss.rule({
  13570. selector: ":export",
  13571. raws: { after: "\n" },
  13572. });
  13573. exportRule.append(exportDeclarations);
  13574. root.prepend(exportRule);
  13575. }
  13576. /* Add import rules */
  13577. importAliases.reverse().forEach(({ path, imports }) => {
  13578. const importRule = postcss.rule({
  13579. selector: `:import(${path})`,
  13580. raws: { after: "\n" },
  13581. });
  13582. imports.forEach(({ theirName, importedName }) => {
  13583. importRule.append({
  13584. value: theirName,
  13585. prop: importedName,
  13586. raws: { before: "\n " },
  13587. });
  13588. });
  13589. root.prepend(importRule);
  13590. });
  13591. },
  13592. };
  13593. },
  13594. };
  13595. };
  13596. src.exports.postcss = true;
  13597. var srcExports = src.exports;
  13598. Object.defineProperty(scoping, "__esModule", {
  13599. value: true
  13600. });
  13601. scoping.behaviours = void 0;
  13602. scoping.getDefaultPlugins = getDefaultPlugins;
  13603. scoping.getDefaultScopeBehaviour = getDefaultScopeBehaviour;
  13604. scoping.getScopedNameGenerator = getScopedNameGenerator;
  13605. var _postcssModulesExtractImports = _interopRequireDefault$1(srcExports$2);
  13606. var _genericNames = _interopRequireDefault$1(genericNames);
  13607. var _postcssModulesLocalByDefault = _interopRequireDefault$1(srcExports$1);
  13608. var _postcssModulesScope = _interopRequireDefault$1(src$1);
  13609. var _stringHash = _interopRequireDefault$1(stringHash);
  13610. var _postcssModulesValues = _interopRequireDefault$1(srcExports);
  13611. function _interopRequireDefault$1(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
  13612. const behaviours = {
  13613. LOCAL: "local",
  13614. GLOBAL: "global"
  13615. };
  13616. scoping.behaviours = behaviours;
  13617. function getDefaultPlugins({
  13618. behaviour,
  13619. generateScopedName,
  13620. exportGlobals
  13621. }) {
  13622. const scope = (0, _postcssModulesScope.default)({
  13623. generateScopedName,
  13624. exportGlobals
  13625. });
  13626. const plugins = {
  13627. [behaviours.LOCAL]: [_postcssModulesValues.default, (0, _postcssModulesLocalByDefault.default)({
  13628. mode: "local"
  13629. }), _postcssModulesExtractImports.default, scope],
  13630. [behaviours.GLOBAL]: [_postcssModulesValues.default, (0, _postcssModulesLocalByDefault.default)({
  13631. mode: "global"
  13632. }), _postcssModulesExtractImports.default, scope]
  13633. };
  13634. return plugins[behaviour];
  13635. }
  13636. function isValidBehaviour(behaviour) {
  13637. return Object.keys(behaviours).map(key => behaviours[key]).indexOf(behaviour) > -1;
  13638. }
  13639. function getDefaultScopeBehaviour(scopeBehaviour) {
  13640. return scopeBehaviour && isValidBehaviour(scopeBehaviour) ? scopeBehaviour : behaviours.LOCAL;
  13641. }
  13642. function generateScopedNameDefault(name, filename, css) {
  13643. const i = css.indexOf(`.${name}`);
  13644. const lineNumber = css.substr(0, i).split(/[\r\n]/).length;
  13645. const hash = (0, _stringHash.default)(css).toString(36).substr(0, 5);
  13646. return `_${name}_${hash}_${lineNumber}`;
  13647. }
  13648. function getScopedNameGenerator(generateScopedName, hashPrefix) {
  13649. const scopedNameGenerator = generateScopedName || generateScopedNameDefault;
  13650. if (typeof scopedNameGenerator === "function") {
  13651. return scopedNameGenerator;
  13652. }
  13653. return (0, _genericNames.default)(scopedNameGenerator, {
  13654. context: process.cwd(),
  13655. hashPrefix: hashPrefix
  13656. });
  13657. }
  13658. Object.defineProperty(pluginFactory, "__esModule", {
  13659. value: true
  13660. });
  13661. pluginFactory.makePlugin = makePlugin;
  13662. var _postcss = _interopRequireDefault(require$$0$1);
  13663. var _unquote = _interopRequireDefault(unquote$1);
  13664. var _Parser = _interopRequireDefault(Parser$1);
  13665. var _saveJSON = _interopRequireDefault(saveJSON$1);
  13666. var _localsConvention = localsConvention;
  13667. var _FileSystemLoader = _interopRequireDefault(FileSystemLoader$1);
  13668. var _scoping = scoping;
  13669. function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
  13670. const PLUGIN_NAME = "postcss-modules";
  13671. function isGlobalModule(globalModules, inputFile) {
  13672. return globalModules.some(regex => inputFile.match(regex));
  13673. }
  13674. function getDefaultPluginsList(opts, inputFile) {
  13675. const globalModulesList = opts.globalModulePaths || null;
  13676. const exportGlobals = opts.exportGlobals || false;
  13677. const defaultBehaviour = (0, _scoping.getDefaultScopeBehaviour)(opts.scopeBehaviour);
  13678. const generateScopedName = (0, _scoping.getScopedNameGenerator)(opts.generateScopedName, opts.hashPrefix);
  13679. if (globalModulesList && isGlobalModule(globalModulesList, inputFile)) {
  13680. return (0, _scoping.getDefaultPlugins)({
  13681. behaviour: _scoping.behaviours.GLOBAL,
  13682. generateScopedName,
  13683. exportGlobals
  13684. });
  13685. }
  13686. return (0, _scoping.getDefaultPlugins)({
  13687. behaviour: defaultBehaviour,
  13688. generateScopedName,
  13689. exportGlobals
  13690. });
  13691. }
  13692. function getLoader(opts, plugins) {
  13693. const root = typeof opts.root === "undefined" ? "/" : opts.root;
  13694. return typeof opts.Loader === "function" ? new opts.Loader(root, plugins, opts.resolve) : new _FileSystemLoader.default(root, plugins, opts.resolve);
  13695. }
  13696. function isOurPlugin(plugin) {
  13697. return plugin.postcssPlugin === PLUGIN_NAME;
  13698. }
  13699. function makePlugin(opts) {
  13700. return {
  13701. postcssPlugin: PLUGIN_NAME,
  13702. async OnceExit(css, {
  13703. result
  13704. }) {
  13705. const getJSON = opts.getJSON || _saveJSON.default;
  13706. const inputFile = css.source.input.file;
  13707. const pluginList = getDefaultPluginsList(opts, inputFile);
  13708. const resultPluginIndex = result.processor.plugins.findIndex(plugin => isOurPlugin(plugin));
  13709. if (resultPluginIndex === -1) {
  13710. throw new Error("Plugin missing from options.");
  13711. }
  13712. const earlierPlugins = result.processor.plugins.slice(0, resultPluginIndex);
  13713. const loaderPlugins = [...earlierPlugins, ...pluginList];
  13714. const loader = getLoader(opts, loaderPlugins);
  13715. const fetcher = async (file, relativeTo, depTrace) => {
  13716. const unquoteFile = (0, _unquote.default)(file);
  13717. return loader.fetch.call(loader, unquoteFile, relativeTo, depTrace);
  13718. };
  13719. const parser = new _Parser.default(fetcher);
  13720. await (0, _postcss.default)([...pluginList, parser.plugin()]).process(css, {
  13721. from: inputFile
  13722. });
  13723. const out = loader.finalSource;
  13724. if (out) css.prepend(out);
  13725. if (opts.localsConvention) {
  13726. const reducer = (0, _localsConvention.makeLocalsConventionReducer)(opts.localsConvention, inputFile);
  13727. parser.exportTokens = Object.entries(parser.exportTokens).reduce(reducer, {});
  13728. }
  13729. result.messages.push({
  13730. type: "export",
  13731. plugin: "postcss-modules",
  13732. exportTokens: parser.exportTokens
  13733. }); // getJSON may return a promise
  13734. return getJSON(css.source.input.file, parser.exportTokens, result.opts.to);
  13735. }
  13736. };
  13737. }
  13738. var _fs = require$$0;
  13739. var _fs2 = fs;
  13740. var _pluginFactory = pluginFactory;
  13741. (0, _fs2.setFileSystem)({
  13742. readFile: _fs.readFile,
  13743. writeFile: _fs.writeFile
  13744. });
  13745. build.exports = (opts = {}) => (0, _pluginFactory.makePlugin)(opts);
  13746. build.exports.postcss = true;
  13747. var buildExports = build.exports;
  13748. var postcssModules = /*@__PURE__*/getDefaultExportFromCjs(buildExports);
  13749. function compileStyle(options) {
  13750. return doCompileStyle({
  13751. ...options,
  13752. isAsync: false
  13753. });
  13754. }
  13755. function compileStyleAsync(options) {
  13756. return doCompileStyle({
  13757. ...options,
  13758. isAsync: true
  13759. });
  13760. }
  13761. function doCompileStyle(options) {
  13762. const {
  13763. filename,
  13764. id,
  13765. scoped = false,
  13766. trim = true,
  13767. isProd = false,
  13768. modules = false,
  13769. modulesOptions = {},
  13770. preprocessLang,
  13771. postcssOptions,
  13772. postcssPlugins
  13773. } = options;
  13774. const preprocessor = preprocessLang && processors[preprocessLang];
  13775. const preProcessedSource = preprocessor && preprocess(options, preprocessor);
  13776. const map = preProcessedSource ? preProcessedSource.map : options.inMap || options.map;
  13777. const source = preProcessedSource ? preProcessedSource.code : options.source;
  13778. const shortId = id.replace(/^data-v-/, "");
  13779. const longId = `data-v-${shortId}`;
  13780. const plugins = (postcssPlugins || []).slice();
  13781. plugins.unshift(cssVarsPlugin({ id: shortId, isProd }));
  13782. if (trim) {
  13783. plugins.push(trimPlugin());
  13784. }
  13785. if (scoped) {
  13786. plugins.push(scopedPlugin(longId));
  13787. }
  13788. let cssModules;
  13789. if (modules) {
  13790. if (!options.isAsync) {
  13791. throw new Error(
  13792. "[@vue/compiler-sfc] `modules` option can only be used with compileStyleAsync()."
  13793. );
  13794. }
  13795. plugins.push(
  13796. postcssModules({
  13797. ...modulesOptions,
  13798. getJSON: (_cssFileName, json) => {
  13799. cssModules = json;
  13800. }
  13801. })
  13802. );
  13803. }
  13804. const postCSSOptions = {
  13805. ...postcssOptions,
  13806. to: filename,
  13807. from: filename
  13808. };
  13809. if (map) {
  13810. postCSSOptions.map = {
  13811. inline: false,
  13812. annotation: false,
  13813. prev: map
  13814. };
  13815. }
  13816. let result;
  13817. let code;
  13818. let outMap;
  13819. const dependencies = new Set(
  13820. preProcessedSource ? preProcessedSource.dependencies : []
  13821. );
  13822. dependencies.delete(filename);
  13823. const errors = [];
  13824. if (preProcessedSource && preProcessedSource.errors.length) {
  13825. errors.push(...preProcessedSource.errors);
  13826. }
  13827. const recordPlainCssDependencies = (messages) => {
  13828. messages.forEach((msg) => {
  13829. if (msg.type === "dependency") {
  13830. dependencies.add(msg.file);
  13831. }
  13832. });
  13833. return dependencies;
  13834. };
  13835. try {
  13836. result = require$$0$1(plugins).process(source, postCSSOptions);
  13837. if (options.isAsync) {
  13838. return result.then((result2) => ({
  13839. code: result2.css || "",
  13840. map: result2.map && result2.map.toJSON(),
  13841. errors,
  13842. modules: cssModules,
  13843. rawResult: result2,
  13844. dependencies: recordPlainCssDependencies(result2.messages)
  13845. })).catch((error) => ({
  13846. code: "",
  13847. map: void 0,
  13848. errors: [...errors, error],
  13849. rawResult: void 0,
  13850. dependencies
  13851. }));
  13852. }
  13853. recordPlainCssDependencies(result.messages);
  13854. code = result.css;
  13855. outMap = result.map;
  13856. } catch (e) {
  13857. errors.push(e);
  13858. }
  13859. return {
  13860. code: code || ``,
  13861. map: outMap && outMap.toJSON(),
  13862. errors,
  13863. rawResult: result,
  13864. dependencies
  13865. };
  13866. }
  13867. function preprocess(options, preprocessor) {
  13868. return preprocessor(
  13869. options.source,
  13870. options.inMap || options.map,
  13871. {
  13872. filename: options.filename,
  13873. ...options.preprocessOptions
  13874. },
  13875. options.preprocessCustomRequire
  13876. );
  13877. }
  13878. function analyzeScriptBindings(ast) {
  13879. for (const node of ast) {
  13880. if (node.type === "ExportDefaultDeclaration" && node.declaration.type === "ObjectExpression") {
  13881. return analyzeBindingsFromOptions(node.declaration);
  13882. }
  13883. }
  13884. return {};
  13885. }
  13886. function analyzeBindingsFromOptions(node) {
  13887. const bindings = {};
  13888. Object.defineProperty(bindings, "__isScriptSetup", {
  13889. enumerable: false,
  13890. value: false
  13891. });
  13892. for (const property of node.properties) {
  13893. if (property.type === "ObjectProperty" && !property.computed && property.key.type === "Identifier") {
  13894. if (property.key.name === "props") {
  13895. for (const key of getObjectOrArrayExpressionKeys(property.value)) {
  13896. bindings[key] = "props";
  13897. }
  13898. } else if (property.key.name === "inject") {
  13899. for (const key of getObjectOrArrayExpressionKeys(property.value)) {
  13900. bindings[key] = "options";
  13901. }
  13902. } else if (property.value.type === "ObjectExpression" && (property.key.name === "computed" || property.key.name === "methods")) {
  13903. for (const key of getObjectExpressionKeys(property.value)) {
  13904. bindings[key] = "options";
  13905. }
  13906. }
  13907. } else if (property.type === "ObjectMethod" && property.key.type === "Identifier" && (property.key.name === "setup" || property.key.name === "data")) {
  13908. for (const bodyItem of property.body.body) {
  13909. if (bodyItem.type === "ReturnStatement" && bodyItem.argument && bodyItem.argument.type === "ObjectExpression") {
  13910. for (const key of getObjectExpressionKeys(bodyItem.argument)) {
  13911. bindings[key] = property.key.name === "setup" ? "setup-maybe-ref" : "data";
  13912. }
  13913. }
  13914. }
  13915. }
  13916. }
  13917. return bindings;
  13918. }
  13919. function getObjectExpressionKeys(node) {
  13920. const keys = [];
  13921. for (const prop of node.properties) {
  13922. if (prop.type === "SpreadElement")
  13923. continue;
  13924. const key = resolveObjectKey(prop.key, prop.computed);
  13925. if (key)
  13926. keys.push(String(key));
  13927. }
  13928. return keys;
  13929. }
  13930. function getArrayExpressionKeys(node) {
  13931. const keys = [];
  13932. for (const element of node.elements) {
  13933. if (element && element.type === "StringLiteral") {
  13934. keys.push(element.value);
  13935. }
  13936. }
  13937. return keys;
  13938. }
  13939. function getObjectOrArrayExpressionKeys(value) {
  13940. if (value.type === "ArrayExpression") {
  13941. return getArrayExpressionKeys(value);
  13942. }
  13943. if (value.type === "ObjectExpression") {
  13944. return getObjectExpressionKeys(value);
  13945. }
  13946. return [];
  13947. }
  13948. var _a, _b;
  13949. class ScriptCompileContext {
  13950. constructor(descriptor, options) {
  13951. this.descriptor = descriptor;
  13952. this.options = options;
  13953. this.isCE = false;
  13954. this.source = this.descriptor.source;
  13955. this.filename = this.descriptor.filename;
  13956. this.s = new MagicString(this.source);
  13957. this.startOffset = (_a = this.descriptor.scriptSetup) == null ? void 0 : _a.loc.start.offset;
  13958. this.endOffset = (_b = this.descriptor.scriptSetup) == null ? void 0 : _b.loc.end.offset;
  13959. this.userImports = /* @__PURE__ */ Object.create(null);
  13960. // macros presence check
  13961. this.hasDefinePropsCall = false;
  13962. this.hasDefineEmitCall = false;
  13963. this.hasDefineExposeCall = false;
  13964. this.hasDefaultExportName = false;
  13965. this.hasDefaultExportRender = false;
  13966. this.hasDefineOptionsCall = false;
  13967. this.hasDefineSlotsCall = false;
  13968. this.hasDefineModelCall = false;
  13969. this.propsDestructuredBindings = /* @__PURE__ */ Object.create(null);
  13970. // defineModel
  13971. this.modelDecls = /* @__PURE__ */ Object.create(null);
  13972. // codegen
  13973. this.bindingMetadata = {};
  13974. this.helperImports = /* @__PURE__ */ new Set();
  13975. const { script, scriptSetup } = descriptor;
  13976. const scriptLang = script && script.lang;
  13977. const scriptSetupLang = scriptSetup && scriptSetup.lang;
  13978. this.isJS = scriptLang === "js" || scriptLang === "jsx" || scriptSetupLang === "js" || scriptSetupLang === "jsx";
  13979. this.isTS = scriptLang === "ts" || scriptLang === "tsx" || scriptSetupLang === "ts" || scriptSetupLang === "tsx";
  13980. const customElement = options.customElement;
  13981. const filename = this.descriptor.filename;
  13982. if (customElement) {
  13983. this.isCE = typeof customElement === "boolean" ? customElement : customElement(filename);
  13984. }
  13985. const plugins = resolveParserPlugins(
  13986. scriptLang || scriptSetupLang,
  13987. options.babelParserPlugins
  13988. );
  13989. function parse(input, offset) {
  13990. try {
  13991. return parser$1.parse(input, {
  13992. plugins,
  13993. sourceType: "module"
  13994. }).program;
  13995. } catch (e) {
  13996. e.message = `[vue/compiler-sfc] ${e.message}
  13997. ${descriptor.filename}
  13998. ${shared.generateCodeFrame(
  13999. descriptor.source,
  14000. e.pos + offset,
  14001. e.pos + offset + 1
  14002. )}`;
  14003. throw e;
  14004. }
  14005. }
  14006. this.scriptAst = descriptor.script && parse(descriptor.script.content, descriptor.script.loc.start.offset);
  14007. this.scriptSetupAst = descriptor.scriptSetup && parse(descriptor.scriptSetup.content, this.startOffset);
  14008. }
  14009. helper(key) {
  14010. this.helperImports.add(key);
  14011. return `_${key}`;
  14012. }
  14013. getString(node, scriptSetup = true) {
  14014. const block = scriptSetup ? this.descriptor.scriptSetup : this.descriptor.script;
  14015. return block.content.slice(node.start, node.end);
  14016. }
  14017. error(msg, node, scope) {
  14018. const offset = scope ? scope.offset : this.startOffset;
  14019. throw new Error(
  14020. `[@vue/compiler-sfc] ${msg}
  14021. ${(scope || this.descriptor).filename}
  14022. ${shared.generateCodeFrame(
  14023. (scope || this.descriptor).source,
  14024. node.start + offset,
  14025. node.end + offset
  14026. )}`
  14027. );
  14028. }
  14029. }
  14030. function resolveParserPlugins(lang, userPlugins, dts = false) {
  14031. const plugins = [];
  14032. if (!userPlugins || !userPlugins.some(
  14033. (p) => p === "importAssertions" || p === "importAttributes" || shared.isArray(p) && p[0] === "importAttributes"
  14034. )) {
  14035. plugins.push("importAttributes");
  14036. }
  14037. if (lang === "jsx" || lang === "tsx") {
  14038. plugins.push("jsx");
  14039. } else if (userPlugins) {
  14040. userPlugins = userPlugins.filter((p) => p !== "jsx");
  14041. }
  14042. if (lang === "ts" || lang === "tsx") {
  14043. plugins.push(["typescript", { dts }], "explicitResourceManagement");
  14044. if (!userPlugins || !userPlugins.includes("decorators")) {
  14045. plugins.push("decorators-legacy");
  14046. }
  14047. }
  14048. if (userPlugins) {
  14049. plugins.push(...userPlugins);
  14050. }
  14051. return plugins;
  14052. }
  14053. function rewriteDefault(input, as, parserPlugins) {
  14054. const ast = parser$1.parse(input, {
  14055. sourceType: "module",
  14056. plugins: resolveParserPlugins("js", parserPlugins)
  14057. }).program.body;
  14058. const s = new MagicString(input);
  14059. rewriteDefaultAST(ast, s, as);
  14060. return s.toString();
  14061. }
  14062. function rewriteDefaultAST(ast, s, as) {
  14063. if (!hasDefaultExport(ast)) {
  14064. s.append(`
  14065. const ${as} = {}`);
  14066. return;
  14067. }
  14068. ast.forEach((node) => {
  14069. if (node.type === "ExportDefaultDeclaration") {
  14070. if (node.declaration.type === "ClassDeclaration" && node.declaration.id) {
  14071. let start = node.declaration.decorators && node.declaration.decorators.length > 0 ? node.declaration.decorators[node.declaration.decorators.length - 1].end : node.start;
  14072. s.overwrite(start, node.declaration.id.start, ` class `);
  14073. s.append(`
  14074. const ${as} = ${node.declaration.id.name}`);
  14075. } else {
  14076. s.overwrite(node.start, node.declaration.start, `const ${as} = `);
  14077. }
  14078. } else if (node.type === "ExportNamedDeclaration") {
  14079. for (const specifier of node.specifiers) {
  14080. if (specifier.type === "ExportSpecifier" && specifier.exported.type === "Identifier" && specifier.exported.name === "default") {
  14081. if (node.source) {
  14082. if (specifier.local.name === "default") {
  14083. s.prepend(
  14084. `import { default as __VUE_DEFAULT__ } from '${node.source.value}'
  14085. `
  14086. );
  14087. const end2 = specifierEnd(s, specifier.local.end, node.end);
  14088. s.remove(specifier.start, end2);
  14089. s.append(`
  14090. const ${as} = __VUE_DEFAULT__`);
  14091. continue;
  14092. } else {
  14093. s.prepend(
  14094. `import { ${s.slice(
  14095. specifier.local.start,
  14096. specifier.local.end
  14097. )} as __VUE_DEFAULT__ } from '${node.source.value}'
  14098. `
  14099. );
  14100. const end2 = specifierEnd(s, specifier.exported.end, node.end);
  14101. s.remove(specifier.start, end2);
  14102. s.append(`
  14103. const ${as} = __VUE_DEFAULT__`);
  14104. continue;
  14105. }
  14106. }
  14107. const end = specifierEnd(s, specifier.end, node.end);
  14108. s.remove(specifier.start, end);
  14109. s.append(`
  14110. const ${as} = ${specifier.local.name}`);
  14111. }
  14112. }
  14113. }
  14114. });
  14115. }
  14116. function hasDefaultExport(ast) {
  14117. for (const stmt of ast) {
  14118. if (stmt.type === "ExportDefaultDeclaration") {
  14119. return true;
  14120. } else if (stmt.type === "ExportNamedDeclaration" && stmt.specifiers.some(
  14121. (spec) => spec.exported.name === "default"
  14122. )) {
  14123. return true;
  14124. }
  14125. }
  14126. return false;
  14127. }
  14128. function specifierEnd(s, end, nodeEnd) {
  14129. let hasCommas = false;
  14130. let oldEnd = end;
  14131. while (end < nodeEnd) {
  14132. if (/\s/.test(s.slice(end, end + 1))) {
  14133. end++;
  14134. } else if (s.slice(end, end + 1) === ",") {
  14135. end++;
  14136. hasCommas = true;
  14137. break;
  14138. } else if (s.slice(end, end + 1) === "}") {
  14139. break;
  14140. }
  14141. }
  14142. return hasCommas ? end : oldEnd;
  14143. }
  14144. const normalScriptDefaultVar = `__default__`;
  14145. function processNormalScript(ctx, scopeId) {
  14146. var _a;
  14147. const script = ctx.descriptor.script;
  14148. if (script.lang && !ctx.isJS && !ctx.isTS) {
  14149. return script;
  14150. }
  14151. try {
  14152. let content = script.content;
  14153. let map = script.map;
  14154. const scriptAst = ctx.scriptAst;
  14155. const bindings = analyzeScriptBindings(scriptAst.body);
  14156. const { cssVars } = ctx.descriptor;
  14157. const { genDefaultAs, isProd } = ctx.options;
  14158. if (cssVars.length || genDefaultAs) {
  14159. const defaultVar = genDefaultAs || normalScriptDefaultVar;
  14160. const s = new MagicString(content);
  14161. rewriteDefaultAST(scriptAst.body, s, defaultVar);
  14162. content = s.toString();
  14163. if (cssVars.length && !((_a = ctx.options.templateOptions) == null ? void 0 : _a.ssr)) {
  14164. content += genNormalScriptCssVarsCode(
  14165. cssVars,
  14166. bindings,
  14167. scopeId,
  14168. !!isProd,
  14169. defaultVar
  14170. );
  14171. }
  14172. if (!genDefaultAs) {
  14173. content += `
  14174. export default ${defaultVar}`;
  14175. }
  14176. }
  14177. return {
  14178. ...script,
  14179. content,
  14180. map,
  14181. bindings,
  14182. scriptAst: scriptAst.body
  14183. };
  14184. } catch (e) {
  14185. return script;
  14186. }
  14187. }
  14188. var balancedMatch = balanced$1;
  14189. function balanced$1(a, b, str) {
  14190. if (a instanceof RegExp) a = maybeMatch(a, str);
  14191. if (b instanceof RegExp) b = maybeMatch(b, str);
  14192. var r = range(a, b, str);
  14193. return r && {
  14194. start: r[0],
  14195. end: r[1],
  14196. pre: str.slice(0, r[0]),
  14197. body: str.slice(r[0] + a.length, r[1]),
  14198. post: str.slice(r[1] + b.length)
  14199. };
  14200. }
  14201. function maybeMatch(reg, str) {
  14202. var m = str.match(reg);
  14203. return m ? m[0] : null;
  14204. }
  14205. balanced$1.range = range;
  14206. function range(a, b, str) {
  14207. var begs, beg, left, right, result;
  14208. var ai = str.indexOf(a);
  14209. var bi = str.indexOf(b, ai + 1);
  14210. var i = ai;
  14211. if (ai >= 0 && bi > 0) {
  14212. if(a===b) {
  14213. return [ai, bi];
  14214. }
  14215. begs = [];
  14216. left = str.length;
  14217. while (i >= 0 && !result) {
  14218. if (i == ai) {
  14219. begs.push(i);
  14220. ai = str.indexOf(a, i + 1);
  14221. } else if (begs.length == 1) {
  14222. result = [ begs.pop(), bi ];
  14223. } else {
  14224. beg = begs.pop();
  14225. if (beg < left) {
  14226. left = beg;
  14227. right = bi;
  14228. }
  14229. bi = str.indexOf(b, i + 1);
  14230. }
  14231. i = ai < bi && ai >= 0 ? ai : bi;
  14232. }
  14233. if (begs.length) {
  14234. result = [ left, right ];
  14235. }
  14236. }
  14237. return result;
  14238. }
  14239. var balanced = balancedMatch;
  14240. var braceExpansion = expandTop;
  14241. var escSlash = '\0SLASH'+Math.random()+'\0';
  14242. var escOpen = '\0OPEN'+Math.random()+'\0';
  14243. var escClose = '\0CLOSE'+Math.random()+'\0';
  14244. var escComma = '\0COMMA'+Math.random()+'\0';
  14245. var escPeriod = '\0PERIOD'+Math.random()+'\0';
  14246. function numeric(str) {
  14247. return parseInt(str, 10) == str
  14248. ? parseInt(str, 10)
  14249. : str.charCodeAt(0);
  14250. }
  14251. function escapeBraces(str) {
  14252. return str.split('\\\\').join(escSlash)
  14253. .split('\\{').join(escOpen)
  14254. .split('\\}').join(escClose)
  14255. .split('\\,').join(escComma)
  14256. .split('\\.').join(escPeriod);
  14257. }
  14258. function unescapeBraces(str) {
  14259. return str.split(escSlash).join('\\')
  14260. .split(escOpen).join('{')
  14261. .split(escClose).join('}')
  14262. .split(escComma).join(',')
  14263. .split(escPeriod).join('.');
  14264. }
  14265. // Basically just str.split(","), but handling cases
  14266. // where we have nested braced sections, which should be
  14267. // treated as individual members, like {a,{b,c},d}
  14268. function parseCommaParts(str) {
  14269. if (!str)
  14270. return [''];
  14271. var parts = [];
  14272. var m = balanced('{', '}', str);
  14273. if (!m)
  14274. return str.split(',');
  14275. var pre = m.pre;
  14276. var body = m.body;
  14277. var post = m.post;
  14278. var p = pre.split(',');
  14279. p[p.length-1] += '{' + body + '}';
  14280. var postParts = parseCommaParts(post);
  14281. if (post.length) {
  14282. p[p.length-1] += postParts.shift();
  14283. p.push.apply(p, postParts);
  14284. }
  14285. parts.push.apply(parts, p);
  14286. return parts;
  14287. }
  14288. function expandTop(str) {
  14289. if (!str)
  14290. return [];
  14291. // I don't know why Bash 4.3 does this, but it does.
  14292. // Anything starting with {} will have the first two bytes preserved
  14293. // but *only* at the top level, so {},a}b will not expand to anything,
  14294. // but a{},b}c will be expanded to [a}c,abc].
  14295. // One could argue that this is a bug in Bash, but since the goal of
  14296. // this module is to match Bash's rules, we escape a leading {}
  14297. if (str.substr(0, 2) === '{}') {
  14298. str = '\\{\\}' + str.substr(2);
  14299. }
  14300. return expand(escapeBraces(str), true).map(unescapeBraces);
  14301. }
  14302. function embrace(str) {
  14303. return '{' + str + '}';
  14304. }
  14305. function isPadded(el) {
  14306. return /^-?0\d/.test(el);
  14307. }
  14308. function lte(i, y) {
  14309. return i <= y;
  14310. }
  14311. function gte(i, y) {
  14312. return i >= y;
  14313. }
  14314. function expand(str, isTop) {
  14315. var expansions = [];
  14316. var m = balanced('{', '}', str);
  14317. if (!m) return [str];
  14318. // no need to expand pre, since it is guaranteed to be free of brace-sets
  14319. var pre = m.pre;
  14320. var post = m.post.length
  14321. ? expand(m.post, false)
  14322. : [''];
  14323. if (/\$$/.test(m.pre)) {
  14324. for (var k = 0; k < post.length; k++) {
  14325. var expansion = pre+ '{' + m.body + '}' + post[k];
  14326. expansions.push(expansion);
  14327. }
  14328. } else {
  14329. var isNumericSequence = /^-?\d+\.\.-?\d+(?:\.\.-?\d+)?$/.test(m.body);
  14330. var isAlphaSequence = /^[a-zA-Z]\.\.[a-zA-Z](?:\.\.-?\d+)?$/.test(m.body);
  14331. var isSequence = isNumericSequence || isAlphaSequence;
  14332. var isOptions = m.body.indexOf(',') >= 0;
  14333. if (!isSequence && !isOptions) {
  14334. // {a},b}
  14335. if (m.post.match(/,.*\}/)) {
  14336. str = m.pre + '{' + m.body + escClose + m.post;
  14337. return expand(str);
  14338. }
  14339. return [str];
  14340. }
  14341. var n;
  14342. if (isSequence) {
  14343. n = m.body.split(/\.\./);
  14344. } else {
  14345. n = parseCommaParts(m.body);
  14346. if (n.length === 1) {
  14347. // x{{a,b}}y ==> x{a}y x{b}y
  14348. n = expand(n[0], false).map(embrace);
  14349. if (n.length === 1) {
  14350. return post.map(function(p) {
  14351. return m.pre + n[0] + p;
  14352. });
  14353. }
  14354. }
  14355. }
  14356. // at this point, n is the parts, and we know it's not a comma set
  14357. // with a single entry.
  14358. var N;
  14359. if (isSequence) {
  14360. var x = numeric(n[0]);
  14361. var y = numeric(n[1]);
  14362. var width = Math.max(n[0].length, n[1].length);
  14363. var incr = n.length == 3
  14364. ? Math.abs(numeric(n[2]))
  14365. : 1;
  14366. var test = lte;
  14367. var reverse = y < x;
  14368. if (reverse) {
  14369. incr *= -1;
  14370. test = gte;
  14371. }
  14372. var pad = n.some(isPadded);
  14373. N = [];
  14374. for (var i = x; test(i, y); i += incr) {
  14375. var c;
  14376. if (isAlphaSequence) {
  14377. c = String.fromCharCode(i);
  14378. if (c === '\\')
  14379. c = '';
  14380. } else {
  14381. c = String(i);
  14382. if (pad) {
  14383. var need = width - c.length;
  14384. if (need > 0) {
  14385. var z = new Array(need + 1).join('0');
  14386. if (i < 0)
  14387. c = '-' + z + c.slice(1);
  14388. else
  14389. c = z + c;
  14390. }
  14391. }
  14392. }
  14393. N.push(c);
  14394. }
  14395. } else {
  14396. N = [];
  14397. for (var j = 0; j < n.length; j++) {
  14398. N.push.apply(N, expand(n[j], false));
  14399. }
  14400. }
  14401. for (var j = 0; j < N.length; j++) {
  14402. for (var k = 0; k < post.length; k++) {
  14403. var expansion = pre + N[j] + post[k];
  14404. if (!isTop || isSequence || expansion)
  14405. expansions.push(expansion);
  14406. }
  14407. }
  14408. }
  14409. return expansions;
  14410. }
  14411. var expand$1 = /*@__PURE__*/getDefaultExportFromCjs(braceExpansion);
  14412. const MAX_PATTERN_LENGTH = 1024 * 64;
  14413. const assertValidPattern = (pattern) => {
  14414. if (typeof pattern !== 'string') {
  14415. throw new TypeError('invalid pattern');
  14416. }
  14417. if (pattern.length > MAX_PATTERN_LENGTH) {
  14418. throw new TypeError('pattern is too long');
  14419. }
  14420. };
  14421. // translate the various posix character classes into unicode properties
  14422. // this works across all unicode locales
  14423. // { <posix class>: [<translation>, /u flag required, negated]
  14424. const posixClasses = {
  14425. '[:alnum:]': ['\\p{L}\\p{Nl}\\p{Nd}', true],
  14426. '[:alpha:]': ['\\p{L}\\p{Nl}', true],
  14427. '[:ascii:]': ['\\x' + '00-\\x' + '7f', false],
  14428. '[:blank:]': ['\\p{Zs}\\t', true],
  14429. '[:cntrl:]': ['\\p{Cc}', true],
  14430. '[:digit:]': ['\\p{Nd}', true],
  14431. '[:graph:]': ['\\p{Z}\\p{C}', true, true],
  14432. '[:lower:]': ['\\p{Ll}', true],
  14433. '[:print:]': ['\\p{C}', true],
  14434. '[:punct:]': ['\\p{P}', true],
  14435. '[:space:]': ['\\p{Z}\\t\\r\\n\\v\\f', true],
  14436. '[:upper:]': ['\\p{Lu}', true],
  14437. '[:word:]': ['\\p{L}\\p{Nl}\\p{Nd}\\p{Pc}', true],
  14438. '[:xdigit:]': ['A-Fa-f0-9', false],
  14439. };
  14440. // only need to escape a few things inside of brace expressions
  14441. // escapes: [ \ ] -
  14442. const braceEscape = (s) => s.replace(/[[\]\\-]/g, '\\$&');
  14443. // escape all regexp magic characters
  14444. const regexpEscape = (s) => s.replace(/[-[\]{}()*+?.,\\^$|#\s]/g, '\\$&');
  14445. // everything has already been escaped, we just have to join
  14446. const rangesToString = (ranges) => ranges.join('');
  14447. // takes a glob string at a posix brace expression, and returns
  14448. // an equivalent regular expression source, and boolean indicating
  14449. // whether the /u flag needs to be applied, and the number of chars
  14450. // consumed to parse the character class.
  14451. // This also removes out of order ranges, and returns ($.) if the
  14452. // entire class just no good.
  14453. const parseClass = (glob, position) => {
  14454. const pos = position;
  14455. /* c8 ignore start */
  14456. if (glob.charAt(pos) !== '[') {
  14457. throw new Error('not in a brace expression');
  14458. }
  14459. /* c8 ignore stop */
  14460. const ranges = [];
  14461. const negs = [];
  14462. let i = pos + 1;
  14463. let sawStart = false;
  14464. let uflag = false;
  14465. let escaping = false;
  14466. let negate = false;
  14467. let endPos = pos;
  14468. let rangeStart = '';
  14469. WHILE: while (i < glob.length) {
  14470. const c = glob.charAt(i);
  14471. if ((c === '!' || c === '^') && i === pos + 1) {
  14472. negate = true;
  14473. i++;
  14474. continue;
  14475. }
  14476. if (c === ']' && sawStart && !escaping) {
  14477. endPos = i + 1;
  14478. break;
  14479. }
  14480. sawStart = true;
  14481. if (c === '\\') {
  14482. if (!escaping) {
  14483. escaping = true;
  14484. i++;
  14485. continue;
  14486. }
  14487. // escaped \ char, fall through and treat like normal char
  14488. }
  14489. if (c === '[' && !escaping) {
  14490. // either a posix class, a collation equivalent, or just a [
  14491. for (const [cls, [unip, u, neg]] of Object.entries(posixClasses)) {
  14492. if (glob.startsWith(cls, i)) {
  14493. // invalid, [a-[] is fine, but not [a-[:alpha]]
  14494. if (rangeStart) {
  14495. return ['$.', false, glob.length - pos, true];
  14496. }
  14497. i += cls.length;
  14498. if (neg)
  14499. negs.push(unip);
  14500. else
  14501. ranges.push(unip);
  14502. uflag = uflag || u;
  14503. continue WHILE;
  14504. }
  14505. }
  14506. }
  14507. // now it's just a normal character, effectively
  14508. escaping = false;
  14509. if (rangeStart) {
  14510. // throw this range away if it's not valid, but others
  14511. // can still match.
  14512. if (c > rangeStart) {
  14513. ranges.push(braceEscape(rangeStart) + '-' + braceEscape(c));
  14514. }
  14515. else if (c === rangeStart) {
  14516. ranges.push(braceEscape(c));
  14517. }
  14518. rangeStart = '';
  14519. i++;
  14520. continue;
  14521. }
  14522. // now might be the start of a range.
  14523. // can be either c-d or c-] or c<more...>] or c] at this point
  14524. if (glob.startsWith('-]', i + 1)) {
  14525. ranges.push(braceEscape(c + '-'));
  14526. i += 2;
  14527. continue;
  14528. }
  14529. if (glob.startsWith('-', i + 1)) {
  14530. rangeStart = c;
  14531. i += 2;
  14532. continue;
  14533. }
  14534. // not the start of a range, just a single character
  14535. ranges.push(braceEscape(c));
  14536. i++;
  14537. }
  14538. if (endPos < i) {
  14539. // didn't see the end of the class, not a valid class,
  14540. // but might still be valid as a literal match.
  14541. return ['', false, 0, false];
  14542. }
  14543. // if we got no ranges and no negates, then we have a range that
  14544. // cannot possibly match anything, and that poisons the whole glob
  14545. if (!ranges.length && !negs.length) {
  14546. return ['$.', false, glob.length - pos, true];
  14547. }
  14548. // if we got one positive range, and it's a single character, then that's
  14549. // not actually a magic pattern, it's just that one literal character.
  14550. // we should not treat that as "magic", we should just return the literal
  14551. // character. [_] is a perfectly valid way to escape glob magic chars.
  14552. if (negs.length === 0 &&
  14553. ranges.length === 1 &&
  14554. /^\\?.$/.test(ranges[0]) &&
  14555. !negate) {
  14556. const r = ranges[0].length === 2 ? ranges[0].slice(-1) : ranges[0];
  14557. return [regexpEscape(r), false, endPos - pos, false];
  14558. }
  14559. const sranges = '[' + (negate ? '^' : '') + rangesToString(ranges) + ']';
  14560. const snegs = '[' + (negate ? '' : '^') + rangesToString(negs) + ']';
  14561. const comb = ranges.length && negs.length
  14562. ? '(' + sranges + '|' + snegs + ')'
  14563. : ranges.length
  14564. ? sranges
  14565. : snegs;
  14566. return [comb, uflag, endPos - pos, true];
  14567. };
  14568. /**
  14569. * Un-escape a string that has been escaped with {@link escape}.
  14570. *
  14571. * If the {@link windowsPathsNoEscape} option is used, then square-brace
  14572. * escapes are removed, but not backslash escapes. For example, it will turn
  14573. * the string `'[*]'` into `*`, but it will not turn `'\\*'` into `'*'`,
  14574. * becuase `\` is a path separator in `windowsPathsNoEscape` mode.
  14575. *
  14576. * When `windowsPathsNoEscape` is not set, then both brace escapes and
  14577. * backslash escapes are removed.
  14578. *
  14579. * Slashes (and backslashes in `windowsPathsNoEscape` mode) cannot be escaped
  14580. * or unescaped.
  14581. */
  14582. const unescape = (s, { windowsPathsNoEscape = false, } = {}) => {
  14583. return windowsPathsNoEscape
  14584. ? s.replace(/\[([^\/\\])\]/g, '$1')
  14585. : s.replace(/((?!\\).|^)\[([^\/\\])\]/g, '$1$2').replace(/\\([^\/])/g, '$1');
  14586. };
  14587. // parse a single path portion
  14588. const types = new Set(['!', '?', '+', '*', '@']);
  14589. const isExtglobType = (c) => types.has(c);
  14590. // Patterns that get prepended to bind to the start of either the
  14591. // entire string, or just a single path portion, to prevent dots
  14592. // and/or traversal patterns, when needed.
  14593. // Exts don't need the ^ or / bit, because the root binds that already.
  14594. const startNoTraversal = '(?!(?:^|/)\\.\\.?(?:$|/))';
  14595. const startNoDot = '(?!\\.)';
  14596. // characters that indicate a start of pattern needs the "no dots" bit,
  14597. // because a dot *might* be matched. ( is not in the list, because in
  14598. // the case of a child extglob, it will handle the prevention itself.
  14599. const addPatternStart = new Set(['[', '.']);
  14600. // cases where traversal is A-OK, no dot prevention needed
  14601. const justDots = new Set(['..', '.']);
  14602. const reSpecials = new Set('().*{}+?[]^$\\!');
  14603. const regExpEscape$1 = (s) => s.replace(/[-[\]{}()*+?.,\\^$|#\s]/g, '\\$&');
  14604. // any single thing other than /
  14605. const qmark$1 = '[^/]';
  14606. // * => any number of characters
  14607. const star$1 = qmark$1 + '*?';
  14608. // use + when we need to ensure that *something* matches, because the * is
  14609. // the only thing in the path portion.
  14610. const starNoEmpty = qmark$1 + '+?';
  14611. // remove the \ chars that we added if we end up doing a nonmagic compare
  14612. // const deslash = (s: string) => s.replace(/\\(.)/g, '$1')
  14613. class AST {
  14614. type;
  14615. #root;
  14616. #hasMagic;
  14617. #uflag = false;
  14618. #parts = [];
  14619. #parent;
  14620. #parentIndex;
  14621. #negs;
  14622. #filledNegs = false;
  14623. #options;
  14624. #toString;
  14625. // set to true if it's an extglob with no children
  14626. // (which really means one child of '')
  14627. #emptyExt = false;
  14628. constructor(type, parent, options = {}) {
  14629. this.type = type;
  14630. // extglobs are inherently magical
  14631. if (type)
  14632. this.#hasMagic = true;
  14633. this.#parent = parent;
  14634. this.#root = this.#parent ? this.#parent.#root : this;
  14635. this.#options = this.#root === this ? options : this.#root.#options;
  14636. this.#negs = this.#root === this ? [] : this.#root.#negs;
  14637. if (type === '!' && !this.#root.#filledNegs)
  14638. this.#negs.push(this);
  14639. this.#parentIndex = this.#parent ? this.#parent.#parts.length : 0;
  14640. }
  14641. get hasMagic() {
  14642. /* c8 ignore start */
  14643. if (this.#hasMagic !== undefined)
  14644. return this.#hasMagic;
  14645. /* c8 ignore stop */
  14646. for (const p of this.#parts) {
  14647. if (typeof p === 'string')
  14648. continue;
  14649. if (p.type || p.hasMagic)
  14650. return (this.#hasMagic = true);
  14651. }
  14652. // note: will be undefined until we generate the regexp src and find out
  14653. return this.#hasMagic;
  14654. }
  14655. // reconstructs the pattern
  14656. toString() {
  14657. if (this.#toString !== undefined)
  14658. return this.#toString;
  14659. if (!this.type) {
  14660. return (this.#toString = this.#parts.map(p => String(p)).join(''));
  14661. }
  14662. else {
  14663. return (this.#toString =
  14664. this.type + '(' + this.#parts.map(p => String(p)).join('|') + ')');
  14665. }
  14666. }
  14667. #fillNegs() {
  14668. /* c8 ignore start */
  14669. if (this !== this.#root)
  14670. throw new Error('should only call on root');
  14671. if (this.#filledNegs)
  14672. return this;
  14673. /* c8 ignore stop */
  14674. // call toString() once to fill this out
  14675. this.toString();
  14676. this.#filledNegs = true;
  14677. let n;
  14678. while ((n = this.#negs.pop())) {
  14679. if (n.type !== '!')
  14680. continue;
  14681. // walk up the tree, appending everthing that comes AFTER parentIndex
  14682. let p = n;
  14683. let pp = p.#parent;
  14684. while (pp) {
  14685. for (let i = p.#parentIndex + 1; !pp.type && i < pp.#parts.length; i++) {
  14686. for (const part of n.#parts) {
  14687. /* c8 ignore start */
  14688. if (typeof part === 'string') {
  14689. throw new Error('string part in extglob AST??');
  14690. }
  14691. /* c8 ignore stop */
  14692. part.copyIn(pp.#parts[i]);
  14693. }
  14694. }
  14695. p = pp;
  14696. pp = p.#parent;
  14697. }
  14698. }
  14699. return this;
  14700. }
  14701. push(...parts) {
  14702. for (const p of parts) {
  14703. if (p === '')
  14704. continue;
  14705. /* c8 ignore start */
  14706. if (typeof p !== 'string' && !(p instanceof AST && p.#parent === this)) {
  14707. throw new Error('invalid part: ' + p);
  14708. }
  14709. /* c8 ignore stop */
  14710. this.#parts.push(p);
  14711. }
  14712. }
  14713. toJSON() {
  14714. const ret = this.type === null
  14715. ? this.#parts.slice().map(p => (typeof p === 'string' ? p : p.toJSON()))
  14716. : [this.type, ...this.#parts.map(p => p.toJSON())];
  14717. if (this.isStart() && !this.type)
  14718. ret.unshift([]);
  14719. if (this.isEnd() &&
  14720. (this === this.#root ||
  14721. (this.#root.#filledNegs && this.#parent?.type === '!'))) {
  14722. ret.push({});
  14723. }
  14724. return ret;
  14725. }
  14726. isStart() {
  14727. if (this.#root === this)
  14728. return true;
  14729. // if (this.type) return !!this.#parent?.isStart()
  14730. if (!this.#parent?.isStart())
  14731. return false;
  14732. if (this.#parentIndex === 0)
  14733. return true;
  14734. // if everything AHEAD of this is a negation, then it's still the "start"
  14735. const p = this.#parent;
  14736. for (let i = 0; i < this.#parentIndex; i++) {
  14737. const pp = p.#parts[i];
  14738. if (!(pp instanceof AST && pp.type === '!')) {
  14739. return false;
  14740. }
  14741. }
  14742. return true;
  14743. }
  14744. isEnd() {
  14745. if (this.#root === this)
  14746. return true;
  14747. if (this.#parent?.type === '!')
  14748. return true;
  14749. if (!this.#parent?.isEnd())
  14750. return false;
  14751. if (!this.type)
  14752. return this.#parent?.isEnd();
  14753. // if not root, it'll always have a parent
  14754. /* c8 ignore start */
  14755. const pl = this.#parent ? this.#parent.#parts.length : 0;
  14756. /* c8 ignore stop */
  14757. return this.#parentIndex === pl - 1;
  14758. }
  14759. copyIn(part) {
  14760. if (typeof part === 'string')
  14761. this.push(part);
  14762. else
  14763. this.push(part.clone(this));
  14764. }
  14765. clone(parent) {
  14766. const c = new AST(this.type, parent);
  14767. for (const p of this.#parts) {
  14768. c.copyIn(p);
  14769. }
  14770. return c;
  14771. }
  14772. static #parseAST(str, ast, pos, opt) {
  14773. let escaping = false;
  14774. let inBrace = false;
  14775. let braceStart = -1;
  14776. let braceNeg = false;
  14777. if (ast.type === null) {
  14778. // outside of a extglob, append until we find a start
  14779. let i = pos;
  14780. let acc = '';
  14781. while (i < str.length) {
  14782. const c = str.charAt(i++);
  14783. // still accumulate escapes at this point, but we do ignore
  14784. // starts that are escaped
  14785. if (escaping || c === '\\') {
  14786. escaping = !escaping;
  14787. acc += c;
  14788. continue;
  14789. }
  14790. if (inBrace) {
  14791. if (i === braceStart + 1) {
  14792. if (c === '^' || c === '!') {
  14793. braceNeg = true;
  14794. }
  14795. }
  14796. else if (c === ']' && !(i === braceStart + 2 && braceNeg)) {
  14797. inBrace = false;
  14798. }
  14799. acc += c;
  14800. continue;
  14801. }
  14802. else if (c === '[') {
  14803. inBrace = true;
  14804. braceStart = i;
  14805. braceNeg = false;
  14806. acc += c;
  14807. continue;
  14808. }
  14809. if (!opt.noext && isExtglobType(c) && str.charAt(i) === '(') {
  14810. ast.push(acc);
  14811. acc = '';
  14812. const ext = new AST(c, ast);
  14813. i = AST.#parseAST(str, ext, i, opt);
  14814. ast.push(ext);
  14815. continue;
  14816. }
  14817. acc += c;
  14818. }
  14819. ast.push(acc);
  14820. return i;
  14821. }
  14822. // some kind of extglob, pos is at the (
  14823. // find the next | or )
  14824. let i = pos + 1;
  14825. let part = new AST(null, ast);
  14826. const parts = [];
  14827. let acc = '';
  14828. while (i < str.length) {
  14829. const c = str.charAt(i++);
  14830. // still accumulate escapes at this point, but we do ignore
  14831. // starts that are escaped
  14832. if (escaping || c === '\\') {
  14833. escaping = !escaping;
  14834. acc += c;
  14835. continue;
  14836. }
  14837. if (inBrace) {
  14838. if (i === braceStart + 1) {
  14839. if (c === '^' || c === '!') {
  14840. braceNeg = true;
  14841. }
  14842. }
  14843. else if (c === ']' && !(i === braceStart + 2 && braceNeg)) {
  14844. inBrace = false;
  14845. }
  14846. acc += c;
  14847. continue;
  14848. }
  14849. else if (c === '[') {
  14850. inBrace = true;
  14851. braceStart = i;
  14852. braceNeg = false;
  14853. acc += c;
  14854. continue;
  14855. }
  14856. if (isExtglobType(c) && str.charAt(i) === '(') {
  14857. part.push(acc);
  14858. acc = '';
  14859. const ext = new AST(c, part);
  14860. part.push(ext);
  14861. i = AST.#parseAST(str, ext, i, opt);
  14862. continue;
  14863. }
  14864. if (c === '|') {
  14865. part.push(acc);
  14866. acc = '';
  14867. parts.push(part);
  14868. part = new AST(null, ast);
  14869. continue;
  14870. }
  14871. if (c === ')') {
  14872. if (acc === '' && ast.#parts.length === 0) {
  14873. ast.#emptyExt = true;
  14874. }
  14875. part.push(acc);
  14876. acc = '';
  14877. ast.push(...parts, part);
  14878. return i;
  14879. }
  14880. acc += c;
  14881. }
  14882. // unfinished extglob
  14883. // if we got here, it was a malformed extglob! not an extglob, but
  14884. // maybe something else in there.
  14885. ast.type = null;
  14886. ast.#hasMagic = undefined;
  14887. ast.#parts = [str.substring(pos - 1)];
  14888. return i;
  14889. }
  14890. static fromGlob(pattern, options = {}) {
  14891. const ast = new AST(null, undefined, options);
  14892. AST.#parseAST(pattern, ast, 0, options);
  14893. return ast;
  14894. }
  14895. // returns the regular expression if there's magic, or the unescaped
  14896. // string if not.
  14897. toMMPattern() {
  14898. // should only be called on root
  14899. /* c8 ignore start */
  14900. if (this !== this.#root)
  14901. return this.#root.toMMPattern();
  14902. /* c8 ignore stop */
  14903. const glob = this.toString();
  14904. const [re, body, hasMagic, uflag] = this.toRegExpSource();
  14905. // if we're in nocase mode, and not nocaseMagicOnly, then we do
  14906. // still need a regular expression if we have to case-insensitively
  14907. // match capital/lowercase characters.
  14908. const anyMagic = hasMagic ||
  14909. this.#hasMagic ||
  14910. (this.#options.nocase &&
  14911. !this.#options.nocaseMagicOnly &&
  14912. glob.toUpperCase() !== glob.toLowerCase());
  14913. if (!anyMagic) {
  14914. return body;
  14915. }
  14916. const flags = (this.#options.nocase ? 'i' : '') + (uflag ? 'u' : '');
  14917. return Object.assign(new RegExp(`^${re}$`, flags), {
  14918. _src: re,
  14919. _glob: glob,
  14920. });
  14921. }
  14922. // returns the string match, the regexp source, whether there's magic
  14923. // in the regexp (so a regular expression is required) and whether or
  14924. // not the uflag is needed for the regular expression (for posix classes)
  14925. // TODO: instead of injecting the start/end at this point, just return
  14926. // the BODY of the regexp, along with the start/end portions suitable
  14927. // for binding the start/end in either a joined full-path makeRe context
  14928. // (where we bind to (^|/), or a standalone matchPart context (where
  14929. // we bind to ^, and not /). Otherwise slashes get duped!
  14930. //
  14931. // In part-matching mode, the start is:
  14932. // - if not isStart: nothing
  14933. // - if traversal possible, but not allowed: ^(?!\.\.?$)
  14934. // - if dots allowed or not possible: ^
  14935. // - if dots possible and not allowed: ^(?!\.)
  14936. // end is:
  14937. // - if not isEnd(): nothing
  14938. // - else: $
  14939. //
  14940. // In full-path matching mode, we put the slash at the START of the
  14941. // pattern, so start is:
  14942. // - if first pattern: same as part-matching mode
  14943. // - if not isStart(): nothing
  14944. // - if traversal possible, but not allowed: /(?!\.\.?(?:$|/))
  14945. // - if dots allowed or not possible: /
  14946. // - if dots possible and not allowed: /(?!\.)
  14947. // end is:
  14948. // - if last pattern, same as part-matching mode
  14949. // - else nothing
  14950. //
  14951. // Always put the (?:$|/) on negated tails, though, because that has to be
  14952. // there to bind the end of the negated pattern portion, and it's easier to
  14953. // just stick it in now rather than try to inject it later in the middle of
  14954. // the pattern.
  14955. //
  14956. // We can just always return the same end, and leave it up to the caller
  14957. // to know whether it's going to be used joined or in parts.
  14958. // And, if the start is adjusted slightly, can do the same there:
  14959. // - if not isStart: nothing
  14960. // - if traversal possible, but not allowed: (?:/|^)(?!\.\.?$)
  14961. // - if dots allowed or not possible: (?:/|^)
  14962. // - if dots possible and not allowed: (?:/|^)(?!\.)
  14963. //
  14964. // But it's better to have a simpler binding without a conditional, for
  14965. // performance, so probably better to return both start options.
  14966. //
  14967. // Then the caller just ignores the end if it's not the first pattern,
  14968. // and the start always gets applied.
  14969. //
  14970. // But that's always going to be $ if it's the ending pattern, or nothing,
  14971. // so the caller can just attach $ at the end of the pattern when building.
  14972. //
  14973. // So the todo is:
  14974. // - better detect what kind of start is needed
  14975. // - return both flavors of starting pattern
  14976. // - attach $ at the end of the pattern when creating the actual RegExp
  14977. //
  14978. // Ah, but wait, no, that all only applies to the root when the first pattern
  14979. // is not an extglob. If the first pattern IS an extglob, then we need all
  14980. // that dot prevention biz to live in the extglob portions, because eg
  14981. // +(*|.x*) can match .xy but not .yx.
  14982. //
  14983. // So, return the two flavors if it's #root and the first child is not an
  14984. // AST, otherwise leave it to the child AST to handle it, and there,
  14985. // use the (?:^|/) style of start binding.
  14986. //
  14987. // Even simplified further:
  14988. // - Since the start for a join is eg /(?!\.) and the start for a part
  14989. // is ^(?!\.), we can just prepend (?!\.) to the pattern (either root
  14990. // or start or whatever) and prepend ^ or / at the Regexp construction.
  14991. toRegExpSource(allowDot) {
  14992. const dot = allowDot ?? !!this.#options.dot;
  14993. if (this.#root === this)
  14994. this.#fillNegs();
  14995. if (!this.type) {
  14996. const noEmpty = this.isStart() && this.isEnd();
  14997. const src = this.#parts
  14998. .map(p => {
  14999. const [re, _, hasMagic, uflag] = typeof p === 'string'
  15000. ? AST.#parseGlob(p, this.#hasMagic, noEmpty)
  15001. : p.toRegExpSource(allowDot);
  15002. this.#hasMagic = this.#hasMagic || hasMagic;
  15003. this.#uflag = this.#uflag || uflag;
  15004. return re;
  15005. })
  15006. .join('');
  15007. let start = '';
  15008. if (this.isStart()) {
  15009. if (typeof this.#parts[0] === 'string') {
  15010. // this is the string that will match the start of the pattern,
  15011. // so we need to protect against dots and such.
  15012. // '.' and '..' cannot match unless the pattern is that exactly,
  15013. // even if it starts with . or dot:true is set.
  15014. const dotTravAllowed = this.#parts.length === 1 && justDots.has(this.#parts[0]);
  15015. if (!dotTravAllowed) {
  15016. const aps = addPatternStart;
  15017. // check if we have a possibility of matching . or ..,
  15018. // and prevent that.
  15019. const needNoTrav =
  15020. // dots are allowed, and the pattern starts with [ or .
  15021. (dot && aps.has(src.charAt(0))) ||
  15022. // the pattern starts with \., and then [ or .
  15023. (src.startsWith('\\.') && aps.has(src.charAt(2))) ||
  15024. // the pattern starts with \.\., and then [ or .
  15025. (src.startsWith('\\.\\.') && aps.has(src.charAt(4)));
  15026. // no need to prevent dots if it can't match a dot, or if a
  15027. // sub-pattern will be preventing it anyway.
  15028. const needNoDot = !dot && !allowDot && aps.has(src.charAt(0));
  15029. start = needNoTrav ? startNoTraversal : needNoDot ? startNoDot : '';
  15030. }
  15031. }
  15032. }
  15033. // append the "end of path portion" pattern to negation tails
  15034. let end = '';
  15035. if (this.isEnd() &&
  15036. this.#root.#filledNegs &&
  15037. this.#parent?.type === '!') {
  15038. end = '(?:$|\\/)';
  15039. }
  15040. const final = start + src + end;
  15041. return [
  15042. final,
  15043. unescape(src),
  15044. (this.#hasMagic = !!this.#hasMagic),
  15045. this.#uflag,
  15046. ];
  15047. }
  15048. // We need to calculate the body *twice* if it's a repeat pattern
  15049. // at the start, once in nodot mode, then again in dot mode, so a
  15050. // pattern like *(?) can match 'x.y'
  15051. const repeated = this.type === '*' || this.type === '+';
  15052. // some kind of extglob
  15053. const start = this.type === '!' ? '(?:(?!(?:' : '(?:';
  15054. let body = this.#partsToRegExp(dot);
  15055. if (this.isStart() && this.isEnd() && !body && this.type !== '!') {
  15056. // invalid extglob, has to at least be *something* present, if it's
  15057. // the entire path portion.
  15058. const s = this.toString();
  15059. this.#parts = [s];
  15060. this.type = null;
  15061. this.#hasMagic = undefined;
  15062. return [s, unescape(this.toString()), false, false];
  15063. }
  15064. // XXX abstract out this map method
  15065. let bodyDotAllowed = !repeated || allowDot || dot || !startNoDot
  15066. ? ''
  15067. : this.#partsToRegExp(true);
  15068. if (bodyDotAllowed === body) {
  15069. bodyDotAllowed = '';
  15070. }
  15071. if (bodyDotAllowed) {
  15072. body = `(?:${body})(?:${bodyDotAllowed})*?`;
  15073. }
  15074. // an empty !() is exactly equivalent to a starNoEmpty
  15075. let final = '';
  15076. if (this.type === '!' && this.#emptyExt) {
  15077. final = (this.isStart() && !dot ? startNoDot : '') + starNoEmpty;
  15078. }
  15079. else {
  15080. const close = this.type === '!'
  15081. ? // !() must match something,but !(x) can match ''
  15082. '))' +
  15083. (this.isStart() && !dot && !allowDot ? startNoDot : '') +
  15084. star$1 +
  15085. ')'
  15086. : this.type === '@'
  15087. ? ')'
  15088. : this.type === '?'
  15089. ? ')?'
  15090. : this.type === '+' && bodyDotAllowed
  15091. ? ')'
  15092. : this.type === '*' && bodyDotAllowed
  15093. ? `)?`
  15094. : `)${this.type}`;
  15095. final = start + body + close;
  15096. }
  15097. return [
  15098. final,
  15099. unescape(body),
  15100. (this.#hasMagic = !!this.#hasMagic),
  15101. this.#uflag,
  15102. ];
  15103. }
  15104. #partsToRegExp(dot) {
  15105. return this.#parts
  15106. .map(p => {
  15107. // extglob ASTs should only contain parent ASTs
  15108. /* c8 ignore start */
  15109. if (typeof p === 'string') {
  15110. throw new Error('string type in extglob ast??');
  15111. }
  15112. /* c8 ignore stop */
  15113. // can ignore hasMagic, because extglobs are already always magic
  15114. const [re, _, _hasMagic, uflag] = p.toRegExpSource(dot);
  15115. this.#uflag = this.#uflag || uflag;
  15116. return re;
  15117. })
  15118. .filter(p => !(this.isStart() && this.isEnd()) || !!p)
  15119. .join('|');
  15120. }
  15121. static #parseGlob(glob, hasMagic, noEmpty = false) {
  15122. let escaping = false;
  15123. let re = '';
  15124. let uflag = false;
  15125. for (let i = 0; i < glob.length; i++) {
  15126. const c = glob.charAt(i);
  15127. if (escaping) {
  15128. escaping = false;
  15129. re += (reSpecials.has(c) ? '\\' : '') + c;
  15130. continue;
  15131. }
  15132. if (c === '\\') {
  15133. if (i === glob.length - 1) {
  15134. re += '\\\\';
  15135. }
  15136. else {
  15137. escaping = true;
  15138. }
  15139. continue;
  15140. }
  15141. if (c === '[') {
  15142. const [src, needUflag, consumed, magic] = parseClass(glob, i);
  15143. if (consumed) {
  15144. re += src;
  15145. uflag = uflag || needUflag;
  15146. i += consumed - 1;
  15147. hasMagic = hasMagic || magic;
  15148. continue;
  15149. }
  15150. }
  15151. if (c === '*') {
  15152. if (noEmpty && glob === '*')
  15153. re += starNoEmpty;
  15154. else
  15155. re += star$1;
  15156. hasMagic = true;
  15157. continue;
  15158. }
  15159. if (c === '?') {
  15160. re += qmark$1;
  15161. hasMagic = true;
  15162. continue;
  15163. }
  15164. re += regExpEscape$1(c);
  15165. }
  15166. return [re, unescape(glob), !!hasMagic, uflag];
  15167. }
  15168. }
  15169. /**
  15170. * Escape all magic characters in a glob pattern.
  15171. *
  15172. * If the {@link windowsPathsNoEscape | GlobOptions.windowsPathsNoEscape}
  15173. * option is used, then characters are escaped by wrapping in `[]`, because
  15174. * a magic character wrapped in a character class can only be satisfied by
  15175. * that exact character. In this mode, `\` is _not_ escaped, because it is
  15176. * not interpreted as a magic character, but instead as a path separator.
  15177. */
  15178. const escape = (s, { windowsPathsNoEscape = false, } = {}) => {
  15179. // don't need to escape +@! because we escape the parens
  15180. // that make those magic, and escaping ! as [!] isn't valid,
  15181. // because [!]] is a valid glob class meaning not ']'.
  15182. return windowsPathsNoEscape
  15183. ? s.replace(/[?*()[\]]/g, '[$&]')
  15184. : s.replace(/[?*()[\]\\]/g, '\\$&');
  15185. };
  15186. const minimatch = (p, pattern, options = {}) => {
  15187. assertValidPattern(pattern);
  15188. // shortcut: comments match nothing.
  15189. if (!options.nocomment && pattern.charAt(0) === '#') {
  15190. return false;
  15191. }
  15192. return new Minimatch(pattern, options).match(p);
  15193. };
  15194. // Optimized checking for the most common glob patterns.
  15195. const starDotExtRE = /^\*+([^+@!?\*\[\(]*)$/;
  15196. const starDotExtTest = (ext) => (f) => !f.startsWith('.') && f.endsWith(ext);
  15197. const starDotExtTestDot = (ext) => (f) => f.endsWith(ext);
  15198. const starDotExtTestNocase = (ext) => {
  15199. ext = ext.toLowerCase();
  15200. return (f) => !f.startsWith('.') && f.toLowerCase().endsWith(ext);
  15201. };
  15202. const starDotExtTestNocaseDot = (ext) => {
  15203. ext = ext.toLowerCase();
  15204. return (f) => f.toLowerCase().endsWith(ext);
  15205. };
  15206. const starDotStarRE = /^\*+\.\*+$/;
  15207. const starDotStarTest = (f) => !f.startsWith('.') && f.includes('.');
  15208. const starDotStarTestDot = (f) => f !== '.' && f !== '..' && f.includes('.');
  15209. const dotStarRE = /^\.\*+$/;
  15210. const dotStarTest = (f) => f !== '.' && f !== '..' && f.startsWith('.');
  15211. const starRE = /^\*+$/;
  15212. const starTest = (f) => f.length !== 0 && !f.startsWith('.');
  15213. const starTestDot = (f) => f.length !== 0 && f !== '.' && f !== '..';
  15214. const qmarksRE = /^\?+([^+@!?\*\[\(]*)?$/;
  15215. const qmarksTestNocase = ([$0, ext = '']) => {
  15216. const noext = qmarksTestNoExt([$0]);
  15217. if (!ext)
  15218. return noext;
  15219. ext = ext.toLowerCase();
  15220. return (f) => noext(f) && f.toLowerCase().endsWith(ext);
  15221. };
  15222. const qmarksTestNocaseDot = ([$0, ext = '']) => {
  15223. const noext = qmarksTestNoExtDot([$0]);
  15224. if (!ext)
  15225. return noext;
  15226. ext = ext.toLowerCase();
  15227. return (f) => noext(f) && f.toLowerCase().endsWith(ext);
  15228. };
  15229. const qmarksTestDot = ([$0, ext = '']) => {
  15230. const noext = qmarksTestNoExtDot([$0]);
  15231. return !ext ? noext : (f) => noext(f) && f.endsWith(ext);
  15232. };
  15233. const qmarksTest = ([$0, ext = '']) => {
  15234. const noext = qmarksTestNoExt([$0]);
  15235. return !ext ? noext : (f) => noext(f) && f.endsWith(ext);
  15236. };
  15237. const qmarksTestNoExt = ([$0]) => {
  15238. const len = $0.length;
  15239. return (f) => f.length === len && !f.startsWith('.');
  15240. };
  15241. const qmarksTestNoExtDot = ([$0]) => {
  15242. const len = $0.length;
  15243. return (f) => f.length === len && f !== '.' && f !== '..';
  15244. };
  15245. /* c8 ignore start */
  15246. const defaultPlatform = (typeof process === 'object' && process
  15247. ? (typeof process.env === 'object' &&
  15248. process.env &&
  15249. process.env.__MINIMATCH_TESTING_PLATFORM__) ||
  15250. process.platform
  15251. : 'posix');
  15252. const path = {
  15253. win32: { sep: '\\' },
  15254. posix: { sep: '/' },
  15255. };
  15256. /* c8 ignore stop */
  15257. const sep = defaultPlatform === 'win32' ? path.win32.sep : path.posix.sep;
  15258. minimatch.sep = sep;
  15259. const GLOBSTAR = Symbol('globstar **');
  15260. minimatch.GLOBSTAR = GLOBSTAR;
  15261. // any single thing other than /
  15262. // don't need to escape / when using new RegExp()
  15263. const qmark = '[^/]';
  15264. // * => any number of characters
  15265. const star = qmark + '*?';
  15266. // ** when dots are allowed. Anything goes, except .. and .
  15267. // not (^ or / followed by one or two dots followed by $ or /),
  15268. // followed by anything, any number of times.
  15269. const twoStarDot = '(?:(?!(?:\\/|^)(?:\\.{1,2})($|\\/)).)*?';
  15270. // not a ^ or / followed by a dot,
  15271. // followed by anything, any number of times.
  15272. const twoStarNoDot = '(?:(?!(?:\\/|^)\\.).)*?';
  15273. const filter = (pattern, options = {}) => (p) => minimatch(p, pattern, options);
  15274. minimatch.filter = filter;
  15275. const ext = (a, b = {}) => Object.assign({}, a, b);
  15276. const defaults = (def) => {
  15277. if (!def || typeof def !== 'object' || !Object.keys(def).length) {
  15278. return minimatch;
  15279. }
  15280. const orig = minimatch;
  15281. const m = (p, pattern, options = {}) => orig(p, pattern, ext(def, options));
  15282. return Object.assign(m, {
  15283. Minimatch: class Minimatch extends orig.Minimatch {
  15284. constructor(pattern, options = {}) {
  15285. super(pattern, ext(def, options));
  15286. }
  15287. static defaults(options) {
  15288. return orig.defaults(ext(def, options)).Minimatch;
  15289. }
  15290. },
  15291. AST: class AST extends orig.AST {
  15292. /* c8 ignore start */
  15293. constructor(type, parent, options = {}) {
  15294. super(type, parent, ext(def, options));
  15295. }
  15296. /* c8 ignore stop */
  15297. static fromGlob(pattern, options = {}) {
  15298. return orig.AST.fromGlob(pattern, ext(def, options));
  15299. }
  15300. },
  15301. unescape: (s, options = {}) => orig.unescape(s, ext(def, options)),
  15302. escape: (s, options = {}) => orig.escape(s, ext(def, options)),
  15303. filter: (pattern, options = {}) => orig.filter(pattern, ext(def, options)),
  15304. defaults: (options) => orig.defaults(ext(def, options)),
  15305. makeRe: (pattern, options = {}) => orig.makeRe(pattern, ext(def, options)),
  15306. braceExpand: (pattern, options = {}) => orig.braceExpand(pattern, ext(def, options)),
  15307. match: (list, pattern, options = {}) => orig.match(list, pattern, ext(def, options)),
  15308. sep: orig.sep,
  15309. GLOBSTAR: GLOBSTAR,
  15310. });
  15311. };
  15312. minimatch.defaults = defaults;
  15313. // Brace expansion:
  15314. // a{b,c}d -> abd acd
  15315. // a{b,}c -> abc ac
  15316. // a{0..3}d -> a0d a1d a2d a3d
  15317. // a{b,c{d,e}f}g -> abg acdfg acefg
  15318. // a{b,c}d{e,f}g -> abdeg acdeg abdeg abdfg
  15319. //
  15320. // Invalid sets are not expanded.
  15321. // a{2..}b -> a{2..}b
  15322. // a{b}c -> a{b}c
  15323. const braceExpand = (pattern, options = {}) => {
  15324. assertValidPattern(pattern);
  15325. // Thanks to Yeting Li <https://github.com/yetingli> for
  15326. // improving this regexp to avoid a ReDOS vulnerability.
  15327. if (options.nobrace || !/\{(?:(?!\{).)*\}/.test(pattern)) {
  15328. // shortcut. no need to expand.
  15329. return [pattern];
  15330. }
  15331. return expand$1(pattern);
  15332. };
  15333. minimatch.braceExpand = braceExpand;
  15334. // parse a component of the expanded set.
  15335. // At this point, no pattern may contain "/" in it
  15336. // so we're going to return a 2d array, where each entry is the full
  15337. // pattern, split on '/', and then turned into a regular expression.
  15338. // A regexp is made at the end which joins each array with an
  15339. // escaped /, and another full one which joins each regexp with |.
  15340. //
  15341. // Following the lead of Bash 4.1, note that "**" only has special meaning
  15342. // when it is the *only* thing in a path portion. Otherwise, any series
  15343. // of * is equivalent to a single *. Globstar behavior is enabled by
  15344. // default, and can be disabled by setting options.noglobstar.
  15345. const makeRe = (pattern, options = {}) => new Minimatch(pattern, options).makeRe();
  15346. minimatch.makeRe = makeRe;
  15347. const match = (list, pattern, options = {}) => {
  15348. const mm = new Minimatch(pattern, options);
  15349. list = list.filter(f => mm.match(f));
  15350. if (mm.options.nonull && !list.length) {
  15351. list.push(pattern);
  15352. }
  15353. return list;
  15354. };
  15355. minimatch.match = match;
  15356. // replace stuff like \* with *
  15357. const globMagic = /[?*]|[+@!]\(.*?\)|\[|\]/;
  15358. const regExpEscape = (s) => s.replace(/[-[\]{}()*+?.,\\^$|#\s]/g, '\\$&');
  15359. class Minimatch {
  15360. options;
  15361. set;
  15362. pattern;
  15363. windowsPathsNoEscape;
  15364. nonegate;
  15365. negate;
  15366. comment;
  15367. empty;
  15368. preserveMultipleSlashes;
  15369. partial;
  15370. globSet;
  15371. globParts;
  15372. nocase;
  15373. isWindows;
  15374. platform;
  15375. windowsNoMagicRoot;
  15376. regexp;
  15377. constructor(pattern, options = {}) {
  15378. assertValidPattern(pattern);
  15379. options = options || {};
  15380. this.options = options;
  15381. this.pattern = pattern;
  15382. this.platform = options.platform || defaultPlatform;
  15383. this.isWindows = this.platform === 'win32';
  15384. this.windowsPathsNoEscape =
  15385. !!options.windowsPathsNoEscape || options.allowWindowsEscape === false;
  15386. if (this.windowsPathsNoEscape) {
  15387. this.pattern = this.pattern.replace(/\\/g, '/');
  15388. }
  15389. this.preserveMultipleSlashes = !!options.preserveMultipleSlashes;
  15390. this.regexp = null;
  15391. this.negate = false;
  15392. this.nonegate = !!options.nonegate;
  15393. this.comment = false;
  15394. this.empty = false;
  15395. this.partial = !!options.partial;
  15396. this.nocase = !!this.options.nocase;
  15397. this.windowsNoMagicRoot =
  15398. options.windowsNoMagicRoot !== undefined
  15399. ? options.windowsNoMagicRoot
  15400. : !!(this.isWindows && this.nocase);
  15401. this.globSet = [];
  15402. this.globParts = [];
  15403. this.set = [];
  15404. // make the set of regexps etc.
  15405. this.make();
  15406. }
  15407. hasMagic() {
  15408. if (this.options.magicalBraces && this.set.length > 1) {
  15409. return true;
  15410. }
  15411. for (const pattern of this.set) {
  15412. for (const part of pattern) {
  15413. if (typeof part !== 'string')
  15414. return true;
  15415. }
  15416. }
  15417. return false;
  15418. }
  15419. debug(..._) { }
  15420. make() {
  15421. const pattern = this.pattern;
  15422. const options = this.options;
  15423. // empty patterns and comments match nothing.
  15424. if (!options.nocomment && pattern.charAt(0) === '#') {
  15425. this.comment = true;
  15426. return;
  15427. }
  15428. if (!pattern) {
  15429. this.empty = true;
  15430. return;
  15431. }
  15432. // step 1: figure out negation, etc.
  15433. this.parseNegate();
  15434. // step 2: expand braces
  15435. this.globSet = [...new Set(this.braceExpand())];
  15436. if (options.debug) {
  15437. this.debug = (...args) => console.error(...args);
  15438. }
  15439. this.debug(this.pattern, this.globSet);
  15440. // step 3: now we have a set, so turn each one into a series of
  15441. // path-portion matching patterns.
  15442. // These will be regexps, except in the case of "**", which is
  15443. // set to the GLOBSTAR object for globstar behavior,
  15444. // and will not contain any / characters
  15445. //
  15446. // First, we preprocess to make the glob pattern sets a bit simpler
  15447. // and deduped. There are some perf-killing patterns that can cause
  15448. // problems with a glob walk, but we can simplify them down a bit.
  15449. const rawGlobParts = this.globSet.map(s => this.slashSplit(s));
  15450. this.globParts = this.preprocess(rawGlobParts);
  15451. this.debug(this.pattern, this.globParts);
  15452. // glob --> regexps
  15453. let set = this.globParts.map((s, _, __) => {
  15454. if (this.isWindows && this.windowsNoMagicRoot) {
  15455. // check if it's a drive or unc path.
  15456. const isUNC = s[0] === '' &&
  15457. s[1] === '' &&
  15458. (s[2] === '?' || !globMagic.test(s[2])) &&
  15459. !globMagic.test(s[3]);
  15460. const isDrive = /^[a-z]:/i.test(s[0]);
  15461. if (isUNC) {
  15462. return [...s.slice(0, 4), ...s.slice(4).map(ss => this.parse(ss))];
  15463. }
  15464. else if (isDrive) {
  15465. return [s[0], ...s.slice(1).map(ss => this.parse(ss))];
  15466. }
  15467. }
  15468. return s.map(ss => this.parse(ss));
  15469. });
  15470. this.debug(this.pattern, set);
  15471. // filter out everything that didn't compile properly.
  15472. this.set = set.filter(s => s.indexOf(false) === -1);
  15473. // do not treat the ? in UNC paths as magic
  15474. if (this.isWindows) {
  15475. for (let i = 0; i < this.set.length; i++) {
  15476. const p = this.set[i];
  15477. if (p[0] === '' &&
  15478. p[1] === '' &&
  15479. this.globParts[i][2] === '?' &&
  15480. typeof p[3] === 'string' &&
  15481. /^[a-z]:$/i.test(p[3])) {
  15482. p[2] = '?';
  15483. }
  15484. }
  15485. }
  15486. this.debug(this.pattern, this.set);
  15487. }
  15488. // various transforms to equivalent pattern sets that are
  15489. // faster to process in a filesystem walk. The goal is to
  15490. // eliminate what we can, and push all ** patterns as far
  15491. // to the right as possible, even if it increases the number
  15492. // of patterns that we have to process.
  15493. preprocess(globParts) {
  15494. // if we're not in globstar mode, then turn all ** into *
  15495. if (this.options.noglobstar) {
  15496. for (let i = 0; i < globParts.length; i++) {
  15497. for (let j = 0; j < globParts[i].length; j++) {
  15498. if (globParts[i][j] === '**') {
  15499. globParts[i][j] = '*';
  15500. }
  15501. }
  15502. }
  15503. }
  15504. const { optimizationLevel = 1 } = this.options;
  15505. if (optimizationLevel >= 2) {
  15506. // aggressive optimization for the purpose of fs walking
  15507. globParts = this.firstPhasePreProcess(globParts);
  15508. globParts = this.secondPhasePreProcess(globParts);
  15509. }
  15510. else if (optimizationLevel >= 1) {
  15511. // just basic optimizations to remove some .. parts
  15512. globParts = this.levelOneOptimize(globParts);
  15513. }
  15514. else {
  15515. globParts = this.adjascentGlobstarOptimize(globParts);
  15516. }
  15517. return globParts;
  15518. }
  15519. // just get rid of adjascent ** portions
  15520. adjascentGlobstarOptimize(globParts) {
  15521. return globParts.map(parts => {
  15522. let gs = -1;
  15523. while (-1 !== (gs = parts.indexOf('**', gs + 1))) {
  15524. let i = gs;
  15525. while (parts[i + 1] === '**') {
  15526. i++;
  15527. }
  15528. if (i !== gs) {
  15529. parts.splice(gs, i - gs);
  15530. }
  15531. }
  15532. return parts;
  15533. });
  15534. }
  15535. // get rid of adjascent ** and resolve .. portions
  15536. levelOneOptimize(globParts) {
  15537. return globParts.map(parts => {
  15538. parts = parts.reduce((set, part) => {
  15539. const prev = set[set.length - 1];
  15540. if (part === '**' && prev === '**') {
  15541. return set;
  15542. }
  15543. if (part === '..') {
  15544. if (prev && prev !== '..' && prev !== '.' && prev !== '**') {
  15545. set.pop();
  15546. return set;
  15547. }
  15548. }
  15549. set.push(part);
  15550. return set;
  15551. }, []);
  15552. return parts.length === 0 ? [''] : parts;
  15553. });
  15554. }
  15555. levelTwoFileOptimize(parts) {
  15556. if (!Array.isArray(parts)) {
  15557. parts = this.slashSplit(parts);
  15558. }
  15559. let didSomething = false;
  15560. do {
  15561. didSomething = false;
  15562. // <pre>/<e>/<rest> -> <pre>/<rest>
  15563. if (!this.preserveMultipleSlashes) {
  15564. for (let i = 1; i < parts.length - 1; i++) {
  15565. const p = parts[i];
  15566. // don't squeeze out UNC patterns
  15567. if (i === 1 && p === '' && parts[0] === '')
  15568. continue;
  15569. if (p === '.' || p === '') {
  15570. didSomething = true;
  15571. parts.splice(i, 1);
  15572. i--;
  15573. }
  15574. }
  15575. if (parts[0] === '.' &&
  15576. parts.length === 2 &&
  15577. (parts[1] === '.' || parts[1] === '')) {
  15578. didSomething = true;
  15579. parts.pop();
  15580. }
  15581. }
  15582. // <pre>/<p>/../<rest> -> <pre>/<rest>
  15583. let dd = 0;
  15584. while (-1 !== (dd = parts.indexOf('..', dd + 1))) {
  15585. const p = parts[dd - 1];
  15586. if (p && p !== '.' && p !== '..' && p !== '**') {
  15587. didSomething = true;
  15588. parts.splice(dd - 1, 2);
  15589. dd -= 2;
  15590. }
  15591. }
  15592. } while (didSomething);
  15593. return parts.length === 0 ? [''] : parts;
  15594. }
  15595. // First phase: single-pattern processing
  15596. // <pre> is 1 or more portions
  15597. // <rest> is 1 or more portions
  15598. // <p> is any portion other than ., .., '', or **
  15599. // <e> is . or ''
  15600. //
  15601. // **/.. is *brutal* for filesystem walking performance, because
  15602. // it effectively resets the recursive walk each time it occurs,
  15603. // and ** cannot be reduced out by a .. pattern part like a regexp
  15604. // or most strings (other than .., ., and '') can be.
  15605. //
  15606. // <pre>/**/../<p>/<p>/<rest> -> {<pre>/../<p>/<p>/<rest>,<pre>/**/<p>/<p>/<rest>}
  15607. // <pre>/<e>/<rest> -> <pre>/<rest>
  15608. // <pre>/<p>/../<rest> -> <pre>/<rest>
  15609. // **/**/<rest> -> **/<rest>
  15610. //
  15611. // **/*/<rest> -> */**/<rest> <== not valid because ** doesn't follow
  15612. // this WOULD be allowed if ** did follow symlinks, or * didn't
  15613. firstPhasePreProcess(globParts) {
  15614. let didSomething = false;
  15615. do {
  15616. didSomething = false;
  15617. // <pre>/**/../<p>/<p>/<rest> -> {<pre>/../<p>/<p>/<rest>,<pre>/**/<p>/<p>/<rest>}
  15618. for (let parts of globParts) {
  15619. let gs = -1;
  15620. while (-1 !== (gs = parts.indexOf('**', gs + 1))) {
  15621. let gss = gs;
  15622. while (parts[gss + 1] === '**') {
  15623. // <pre>/**/**/<rest> -> <pre>/**/<rest>
  15624. gss++;
  15625. }
  15626. // eg, if gs is 2 and gss is 4, that means we have 3 **
  15627. // parts, and can remove 2 of them.
  15628. if (gss > gs) {
  15629. parts.splice(gs + 1, gss - gs);
  15630. }
  15631. let next = parts[gs + 1];
  15632. const p = parts[gs + 2];
  15633. const p2 = parts[gs + 3];
  15634. if (next !== '..')
  15635. continue;
  15636. if (!p ||
  15637. p === '.' ||
  15638. p === '..' ||
  15639. !p2 ||
  15640. p2 === '.' ||
  15641. p2 === '..') {
  15642. continue;
  15643. }
  15644. didSomething = true;
  15645. // edit parts in place, and push the new one
  15646. parts.splice(gs, 1);
  15647. const other = parts.slice(0);
  15648. other[gs] = '**';
  15649. globParts.push(other);
  15650. gs--;
  15651. }
  15652. // <pre>/<e>/<rest> -> <pre>/<rest>
  15653. if (!this.preserveMultipleSlashes) {
  15654. for (let i = 1; i < parts.length - 1; i++) {
  15655. const p = parts[i];
  15656. // don't squeeze out UNC patterns
  15657. if (i === 1 && p === '' && parts[0] === '')
  15658. continue;
  15659. if (p === '.' || p === '') {
  15660. didSomething = true;
  15661. parts.splice(i, 1);
  15662. i--;
  15663. }
  15664. }
  15665. if (parts[0] === '.' &&
  15666. parts.length === 2 &&
  15667. (parts[1] === '.' || parts[1] === '')) {
  15668. didSomething = true;
  15669. parts.pop();
  15670. }
  15671. }
  15672. // <pre>/<p>/../<rest> -> <pre>/<rest>
  15673. let dd = 0;
  15674. while (-1 !== (dd = parts.indexOf('..', dd + 1))) {
  15675. const p = parts[dd - 1];
  15676. if (p && p !== '.' && p !== '..' && p !== '**') {
  15677. didSomething = true;
  15678. const needDot = dd === 1 && parts[dd + 1] === '**';
  15679. const splin = needDot ? ['.'] : [];
  15680. parts.splice(dd - 1, 2, ...splin);
  15681. if (parts.length === 0)
  15682. parts.push('');
  15683. dd -= 2;
  15684. }
  15685. }
  15686. }
  15687. } while (didSomething);
  15688. return globParts;
  15689. }
  15690. // second phase: multi-pattern dedupes
  15691. // {<pre>/*/<rest>,<pre>/<p>/<rest>} -> <pre>/*/<rest>
  15692. // {<pre>/<rest>,<pre>/<rest>} -> <pre>/<rest>
  15693. // {<pre>/**/<rest>,<pre>/<rest>} -> <pre>/**/<rest>
  15694. //
  15695. // {<pre>/**/<rest>,<pre>/**/<p>/<rest>} -> <pre>/**/<rest>
  15696. // ^-- not valid because ** doens't follow symlinks
  15697. secondPhasePreProcess(globParts) {
  15698. for (let i = 0; i < globParts.length - 1; i++) {
  15699. for (let j = i + 1; j < globParts.length; j++) {
  15700. const matched = this.partsMatch(globParts[i], globParts[j], !this.preserveMultipleSlashes);
  15701. if (!matched)
  15702. continue;
  15703. globParts[i] = matched;
  15704. globParts[j] = [];
  15705. }
  15706. }
  15707. return globParts.filter(gs => gs.length);
  15708. }
  15709. partsMatch(a, b, emptyGSMatch = false) {
  15710. let ai = 0;
  15711. let bi = 0;
  15712. let result = [];
  15713. let which = '';
  15714. while (ai < a.length && bi < b.length) {
  15715. if (a[ai] === b[bi]) {
  15716. result.push(which === 'b' ? b[bi] : a[ai]);
  15717. ai++;
  15718. bi++;
  15719. }
  15720. else if (emptyGSMatch && a[ai] === '**' && b[bi] === a[ai + 1]) {
  15721. result.push(a[ai]);
  15722. ai++;
  15723. }
  15724. else if (emptyGSMatch && b[bi] === '**' && a[ai] === b[bi + 1]) {
  15725. result.push(b[bi]);
  15726. bi++;
  15727. }
  15728. else if (a[ai] === '*' &&
  15729. b[bi] &&
  15730. (this.options.dot || !b[bi].startsWith('.')) &&
  15731. b[bi] !== '**') {
  15732. if (which === 'b')
  15733. return false;
  15734. which = 'a';
  15735. result.push(a[ai]);
  15736. ai++;
  15737. bi++;
  15738. }
  15739. else if (b[bi] === '*' &&
  15740. a[ai] &&
  15741. (this.options.dot || !a[ai].startsWith('.')) &&
  15742. a[ai] !== '**') {
  15743. if (which === 'a')
  15744. return false;
  15745. which = 'b';
  15746. result.push(b[bi]);
  15747. ai++;
  15748. bi++;
  15749. }
  15750. else {
  15751. return false;
  15752. }
  15753. }
  15754. // if we fall out of the loop, it means they two are identical
  15755. // as long as their lengths match
  15756. return a.length === b.length && result;
  15757. }
  15758. parseNegate() {
  15759. if (this.nonegate)
  15760. return;
  15761. const pattern = this.pattern;
  15762. let negate = false;
  15763. let negateOffset = 0;
  15764. for (let i = 0; i < pattern.length && pattern.charAt(i) === '!'; i++) {
  15765. negate = !negate;
  15766. negateOffset++;
  15767. }
  15768. if (negateOffset)
  15769. this.pattern = pattern.slice(negateOffset);
  15770. this.negate = negate;
  15771. }
  15772. // set partial to true to test if, for example,
  15773. // "/a/b" matches the start of "/*/b/*/d"
  15774. // Partial means, if you run out of file before you run
  15775. // out of pattern, then that's fine, as long as all
  15776. // the parts match.
  15777. matchOne(file, pattern, partial = false) {
  15778. const options = this.options;
  15779. // UNC paths like //?/X:/... can match X:/... and vice versa
  15780. // Drive letters in absolute drive or unc paths are always compared
  15781. // case-insensitively.
  15782. if (this.isWindows) {
  15783. const fileDrive = typeof file[0] === 'string' && /^[a-z]:$/i.test(file[0]);
  15784. const fileUNC = !fileDrive &&
  15785. file[0] === '' &&
  15786. file[1] === '' &&
  15787. file[2] === '?' &&
  15788. /^[a-z]:$/i.test(file[3]);
  15789. const patternDrive = typeof pattern[0] === 'string' && /^[a-z]:$/i.test(pattern[0]);
  15790. const patternUNC = !patternDrive &&
  15791. pattern[0] === '' &&
  15792. pattern[1] === '' &&
  15793. pattern[2] === '?' &&
  15794. typeof pattern[3] === 'string' &&
  15795. /^[a-z]:$/i.test(pattern[3]);
  15796. const fdi = fileUNC ? 3 : fileDrive ? 0 : undefined;
  15797. const pdi = patternUNC ? 3 : patternDrive ? 0 : undefined;
  15798. if (typeof fdi === 'number' && typeof pdi === 'number') {
  15799. const [fd, pd] = [file[fdi], pattern[pdi]];
  15800. if (fd.toLowerCase() === pd.toLowerCase()) {
  15801. pattern[pdi] = fd;
  15802. if (pdi > fdi) {
  15803. pattern = pattern.slice(pdi);
  15804. }
  15805. else if (fdi > pdi) {
  15806. file = file.slice(fdi);
  15807. }
  15808. }
  15809. }
  15810. }
  15811. // resolve and reduce . and .. portions in the file as well.
  15812. // dont' need to do the second phase, because it's only one string[]
  15813. const { optimizationLevel = 1 } = this.options;
  15814. if (optimizationLevel >= 2) {
  15815. file = this.levelTwoFileOptimize(file);
  15816. }
  15817. this.debug('matchOne', this, { file, pattern });
  15818. this.debug('matchOne', file.length, pattern.length);
  15819. for (var fi = 0, pi = 0, fl = file.length, pl = pattern.length; fi < fl && pi < pl; fi++, pi++) {
  15820. this.debug('matchOne loop');
  15821. var p = pattern[pi];
  15822. var f = file[fi];
  15823. this.debug(pattern, p, f);
  15824. // should be impossible.
  15825. // some invalid regexp stuff in the set.
  15826. /* c8 ignore start */
  15827. if (p === false) {
  15828. return false;
  15829. }
  15830. /* c8 ignore stop */
  15831. if (p === GLOBSTAR) {
  15832. this.debug('GLOBSTAR', [pattern, p, f]);
  15833. // "**"
  15834. // a/**/b/**/c would match the following:
  15835. // a/b/x/y/z/c
  15836. // a/x/y/z/b/c
  15837. // a/b/x/b/x/c
  15838. // a/b/c
  15839. // To do this, take the rest of the pattern after
  15840. // the **, and see if it would match the file remainder.
  15841. // If so, return success.
  15842. // If not, the ** "swallows" a segment, and try again.
  15843. // This is recursively awful.
  15844. //
  15845. // a/**/b/**/c matching a/b/x/y/z/c
  15846. // - a matches a
  15847. // - doublestar
  15848. // - matchOne(b/x/y/z/c, b/**/c)
  15849. // - b matches b
  15850. // - doublestar
  15851. // - matchOne(x/y/z/c, c) -> no
  15852. // - matchOne(y/z/c, c) -> no
  15853. // - matchOne(z/c, c) -> no
  15854. // - matchOne(c, c) yes, hit
  15855. var fr = fi;
  15856. var pr = pi + 1;
  15857. if (pr === pl) {
  15858. this.debug('** at the end');
  15859. // a ** at the end will just swallow the rest.
  15860. // We have found a match.
  15861. // however, it will not swallow /.x, unless
  15862. // options.dot is set.
  15863. // . and .. are *never* matched by **, for explosively
  15864. // exponential reasons.
  15865. for (; fi < fl; fi++) {
  15866. if (file[fi] === '.' ||
  15867. file[fi] === '..' ||
  15868. (!options.dot && file[fi].charAt(0) === '.'))
  15869. return false;
  15870. }
  15871. return true;
  15872. }
  15873. // ok, let's see if we can swallow whatever we can.
  15874. while (fr < fl) {
  15875. var swallowee = file[fr];
  15876. this.debug('\nglobstar while', file, fr, pattern, pr, swallowee);
  15877. // XXX remove this slice. Just pass the start index.
  15878. if (this.matchOne(file.slice(fr), pattern.slice(pr), partial)) {
  15879. this.debug('globstar found match!', fr, fl, swallowee);
  15880. // found a match.
  15881. return true;
  15882. }
  15883. else {
  15884. // can't swallow "." or ".." ever.
  15885. // can only swallow ".foo" when explicitly asked.
  15886. if (swallowee === '.' ||
  15887. swallowee === '..' ||
  15888. (!options.dot && swallowee.charAt(0) === '.')) {
  15889. this.debug('dot detected!', file, fr, pattern, pr);
  15890. break;
  15891. }
  15892. // ** swallows a segment, and continue.
  15893. this.debug('globstar swallow a segment, and continue');
  15894. fr++;
  15895. }
  15896. }
  15897. // no match was found.
  15898. // However, in partial mode, we can't say this is necessarily over.
  15899. /* c8 ignore start */
  15900. if (partial) {
  15901. // ran out of file
  15902. this.debug('\n>>> no match, partial?', file, fr, pattern, pr);
  15903. if (fr === fl) {
  15904. return true;
  15905. }
  15906. }
  15907. /* c8 ignore stop */
  15908. return false;
  15909. }
  15910. // something other than **
  15911. // non-magic patterns just have to match exactly
  15912. // patterns with magic have been turned into regexps.
  15913. let hit;
  15914. if (typeof p === 'string') {
  15915. hit = f === p;
  15916. this.debug('string match', p, f, hit);
  15917. }
  15918. else {
  15919. hit = p.test(f);
  15920. this.debug('pattern match', p, f, hit);
  15921. }
  15922. if (!hit)
  15923. return false;
  15924. }
  15925. // Note: ending in / means that we'll get a final ""
  15926. // at the end of the pattern. This can only match a
  15927. // corresponding "" at the end of the file.
  15928. // If the file ends in /, then it can only match a
  15929. // a pattern that ends in /, unless the pattern just
  15930. // doesn't have any more for it. But, a/b/ should *not*
  15931. // match "a/b/*", even though "" matches against the
  15932. // [^/]*? pattern, except in partial mode, where it might
  15933. // simply not be reached yet.
  15934. // However, a/b/ should still satisfy a/*
  15935. // now either we fell off the end of the pattern, or we're done.
  15936. if (fi === fl && pi === pl) {
  15937. // ran out of pattern and filename at the same time.
  15938. // an exact hit!
  15939. return true;
  15940. }
  15941. else if (fi === fl) {
  15942. // ran out of file, but still had pattern left.
  15943. // this is ok if we're doing the match as part of
  15944. // a glob fs traversal.
  15945. return partial;
  15946. }
  15947. else if (pi === pl) {
  15948. // ran out of pattern, still have file left.
  15949. // this is only acceptable if we're on the very last
  15950. // empty segment of a file with a trailing slash.
  15951. // a/* should match a/b/
  15952. return fi === fl - 1 && file[fi] === '';
  15953. /* c8 ignore start */
  15954. }
  15955. else {
  15956. // should be unreachable.
  15957. throw new Error('wtf?');
  15958. }
  15959. /* c8 ignore stop */
  15960. }
  15961. braceExpand() {
  15962. return braceExpand(this.pattern, this.options);
  15963. }
  15964. parse(pattern) {
  15965. assertValidPattern(pattern);
  15966. const options = this.options;
  15967. // shortcuts
  15968. if (pattern === '**')
  15969. return GLOBSTAR;
  15970. if (pattern === '')
  15971. return '';
  15972. // far and away, the most common glob pattern parts are
  15973. // *, *.*, and *.<ext> Add a fast check method for those.
  15974. let m;
  15975. let fastTest = null;
  15976. if ((m = pattern.match(starRE))) {
  15977. fastTest = options.dot ? starTestDot : starTest;
  15978. }
  15979. else if ((m = pattern.match(starDotExtRE))) {
  15980. fastTest = (options.nocase
  15981. ? options.dot
  15982. ? starDotExtTestNocaseDot
  15983. : starDotExtTestNocase
  15984. : options.dot
  15985. ? starDotExtTestDot
  15986. : starDotExtTest)(m[1]);
  15987. }
  15988. else if ((m = pattern.match(qmarksRE))) {
  15989. fastTest = (options.nocase
  15990. ? options.dot
  15991. ? qmarksTestNocaseDot
  15992. : qmarksTestNocase
  15993. : options.dot
  15994. ? qmarksTestDot
  15995. : qmarksTest)(m);
  15996. }
  15997. else if ((m = pattern.match(starDotStarRE))) {
  15998. fastTest = options.dot ? starDotStarTestDot : starDotStarTest;
  15999. }
  16000. else if ((m = pattern.match(dotStarRE))) {
  16001. fastTest = dotStarTest;
  16002. }
  16003. const re = AST.fromGlob(pattern, this.options).toMMPattern();
  16004. return fastTest ? Object.assign(re, { test: fastTest }) : re;
  16005. }
  16006. makeRe() {
  16007. if (this.regexp || this.regexp === false)
  16008. return this.regexp;
  16009. // at this point, this.set is a 2d array of partial
  16010. // pattern strings, or "**".
  16011. //
  16012. // It's better to use .match(). This function shouldn't
  16013. // be used, really, but it's pretty convenient sometimes,
  16014. // when you just want to work with a regex.
  16015. const set = this.set;
  16016. if (!set.length) {
  16017. this.regexp = false;
  16018. return this.regexp;
  16019. }
  16020. const options = this.options;
  16021. const twoStar = options.noglobstar
  16022. ? star
  16023. : options.dot
  16024. ? twoStarDot
  16025. : twoStarNoDot;
  16026. const flags = new Set(options.nocase ? ['i'] : []);
  16027. // regexpify non-globstar patterns
  16028. // if ** is only item, then we just do one twoStar
  16029. // if ** is first, and there are more, prepend (\/|twoStar\/)? to next
  16030. // if ** is last, append (\/twoStar|) to previous
  16031. // if ** is in the middle, append (\/|\/twoStar\/) to previous
  16032. // then filter out GLOBSTAR symbols
  16033. let re = set
  16034. .map(pattern => {
  16035. const pp = pattern.map(p => {
  16036. if (p instanceof RegExp) {
  16037. for (const f of p.flags.split(''))
  16038. flags.add(f);
  16039. }
  16040. return typeof p === 'string'
  16041. ? regExpEscape(p)
  16042. : p === GLOBSTAR
  16043. ? GLOBSTAR
  16044. : p._src;
  16045. });
  16046. pp.forEach((p, i) => {
  16047. const next = pp[i + 1];
  16048. const prev = pp[i - 1];
  16049. if (p !== GLOBSTAR || prev === GLOBSTAR) {
  16050. return;
  16051. }
  16052. if (prev === undefined) {
  16053. if (next !== undefined && next !== GLOBSTAR) {
  16054. pp[i + 1] = '(?:\\/|' + twoStar + '\\/)?' + next;
  16055. }
  16056. else {
  16057. pp[i] = twoStar;
  16058. }
  16059. }
  16060. else if (next === undefined) {
  16061. pp[i - 1] = prev + '(?:\\/|' + twoStar + ')?';
  16062. }
  16063. else if (next !== GLOBSTAR) {
  16064. pp[i - 1] = prev + '(?:\\/|\\/' + twoStar + '\\/)' + next;
  16065. pp[i + 1] = GLOBSTAR;
  16066. }
  16067. });
  16068. return pp.filter(p => p !== GLOBSTAR).join('/');
  16069. })
  16070. .join('|');
  16071. // need to wrap in parens if we had more than one thing with |,
  16072. // otherwise only the first will be anchored to ^ and the last to $
  16073. const [open, close] = set.length > 1 ? ['(?:', ')'] : ['', ''];
  16074. // must match entire pattern
  16075. // ending in a * or ** will make it less strict.
  16076. re = '^' + open + re + close + '$';
  16077. // can match anything, as long as it's not this.
  16078. if (this.negate)
  16079. re = '^(?!' + re + ').+$';
  16080. try {
  16081. this.regexp = new RegExp(re, [...flags].join(''));
  16082. /* c8 ignore start */
  16083. }
  16084. catch (ex) {
  16085. // should be impossible
  16086. this.regexp = false;
  16087. }
  16088. /* c8 ignore stop */
  16089. return this.regexp;
  16090. }
  16091. slashSplit(p) {
  16092. // if p starts with // on windows, we preserve that
  16093. // so that UNC paths aren't broken. Otherwise, any number of
  16094. // / characters are coalesced into one, unless
  16095. // preserveMultipleSlashes is set to true.
  16096. if (this.preserveMultipleSlashes) {
  16097. return p.split('/');
  16098. }
  16099. else if (this.isWindows && /^\/\/[^\/]+/.test(p)) {
  16100. // add an extra '' for the one we lose
  16101. return ['', ...p.split(/\/+/)];
  16102. }
  16103. else {
  16104. return p.split(/\/+/);
  16105. }
  16106. }
  16107. match(f, partial = this.partial) {
  16108. this.debug('match', f, this.pattern);
  16109. // short-circuit in the case of busted things.
  16110. // comments, etc.
  16111. if (this.comment) {
  16112. return false;
  16113. }
  16114. if (this.empty) {
  16115. return f === '';
  16116. }
  16117. if (f === '/' && partial) {
  16118. return true;
  16119. }
  16120. const options = this.options;
  16121. // windows: need to use /, not \
  16122. if (this.isWindows) {
  16123. f = f.split('\\').join('/');
  16124. }
  16125. // treat the test path as a set of pathparts.
  16126. const ff = this.slashSplit(f);
  16127. this.debug(this.pattern, 'split', ff);
  16128. // just ONE of the pattern sets in this.set needs to match
  16129. // in order for it to be valid. If negating, then just one
  16130. // match means that we have failed.
  16131. // Either way, return on the first hit.
  16132. const set = this.set;
  16133. this.debug(this.pattern, 'set', set);
  16134. // Find the basename of the path by looking for the last non-empty segment
  16135. let filename = ff[ff.length - 1];
  16136. if (!filename) {
  16137. for (let i = ff.length - 2; !filename && i >= 0; i--) {
  16138. filename = ff[i];
  16139. }
  16140. }
  16141. for (let i = 0; i < set.length; i++) {
  16142. const pattern = set[i];
  16143. let file = ff;
  16144. if (options.matchBase && pattern.length === 1) {
  16145. file = [filename];
  16146. }
  16147. const hit = this.matchOne(file, pattern, partial);
  16148. if (hit) {
  16149. if (options.flipNegate) {
  16150. return true;
  16151. }
  16152. return !this.negate;
  16153. }
  16154. }
  16155. // didn't get any hits. this is success if it's a negative
  16156. // pattern, failure otherwise.
  16157. if (options.flipNegate) {
  16158. return false;
  16159. }
  16160. return this.negate;
  16161. }
  16162. static defaults(def) {
  16163. return minimatch.defaults(def).Minimatch;
  16164. }
  16165. }
  16166. /* c8 ignore stop */
  16167. minimatch.AST = AST;
  16168. minimatch.Minimatch = Minimatch;
  16169. minimatch.escape = escape;
  16170. minimatch.unescape = unescape;
  16171. class TypeScope {
  16172. constructor(filename, source, offset = 0, imports = /* @__PURE__ */ Object.create(null), types = /* @__PURE__ */ Object.create(null), declares = /* @__PURE__ */ Object.create(null)) {
  16173. this.filename = filename;
  16174. this.source = source;
  16175. this.offset = offset;
  16176. this.imports = imports;
  16177. this.types = types;
  16178. this.declares = declares;
  16179. this.isGenericScope = false;
  16180. this.resolvedImportSources = /* @__PURE__ */ Object.create(null);
  16181. this.exportedTypes = /* @__PURE__ */ Object.create(null);
  16182. this.exportedDeclares = /* @__PURE__ */ Object.create(null);
  16183. }
  16184. }
  16185. function resolveTypeElements(ctx, node, scope, typeParameters) {
  16186. const canCache = !typeParameters;
  16187. if (canCache && node._resolvedElements) {
  16188. return node._resolvedElements;
  16189. }
  16190. const resolved = innerResolveTypeElements(
  16191. ctx,
  16192. node,
  16193. node._ownerScope || scope || ctxToScope(ctx),
  16194. typeParameters
  16195. );
  16196. return canCache ? node._resolvedElements = resolved : resolved;
  16197. }
  16198. function innerResolveTypeElements(ctx, node, scope, typeParameters) {
  16199. var _a, _b;
  16200. switch (node.type) {
  16201. case "TSTypeLiteral":
  16202. return typeElementsToMap(ctx, node.members, scope, typeParameters);
  16203. case "TSInterfaceDeclaration":
  16204. return resolveInterfaceMembers(ctx, node, scope, typeParameters);
  16205. case "TSTypeAliasDeclaration":
  16206. case "TSParenthesizedType":
  16207. return resolveTypeElements(
  16208. ctx,
  16209. node.typeAnnotation,
  16210. scope,
  16211. typeParameters
  16212. );
  16213. case "TSFunctionType": {
  16214. return { props: {}, calls: [node] };
  16215. }
  16216. case "TSUnionType":
  16217. case "TSIntersectionType":
  16218. return mergeElements(
  16219. node.types.map((t) => resolveTypeElements(ctx, t, scope, typeParameters)),
  16220. node.type
  16221. );
  16222. case "TSMappedType":
  16223. return resolveMappedType(ctx, node, scope);
  16224. case "TSIndexedAccessType": {
  16225. const types = resolveIndexType(ctx, node, scope);
  16226. return mergeElements(
  16227. types.map((t) => resolveTypeElements(ctx, t, t._ownerScope)),
  16228. "TSUnionType"
  16229. );
  16230. }
  16231. case "TSExpressionWithTypeArguments":
  16232. case "TSTypeReference": {
  16233. const typeName = getReferenceName(node);
  16234. if ((typeName === "ExtractPropTypes" || typeName === "ExtractPublicPropTypes") && node.typeParameters && ((_a = scope.imports[typeName]) == null ? void 0 : _a.source) === "vue") {
  16235. return resolveExtractPropTypes(
  16236. resolveTypeElements(
  16237. ctx,
  16238. node.typeParameters.params[0],
  16239. scope,
  16240. typeParameters
  16241. ),
  16242. scope
  16243. );
  16244. }
  16245. const resolved = resolveTypeReference(ctx, node, scope);
  16246. if (resolved) {
  16247. let typeParams;
  16248. if ((resolved.type === "TSTypeAliasDeclaration" || resolved.type === "TSInterfaceDeclaration") && resolved.typeParameters && node.typeParameters) {
  16249. typeParams = /* @__PURE__ */ Object.create(null);
  16250. resolved.typeParameters.params.forEach((p, i) => {
  16251. let param = typeParameters && typeParameters[p.name];
  16252. if (!param)
  16253. param = node.typeParameters.params[i];
  16254. typeParams[p.name] = param;
  16255. });
  16256. }
  16257. return resolveTypeElements(
  16258. ctx,
  16259. resolved,
  16260. resolved._ownerScope,
  16261. typeParams
  16262. );
  16263. } else {
  16264. if (typeof typeName === "string") {
  16265. if (typeParameters && typeParameters[typeName]) {
  16266. return resolveTypeElements(
  16267. ctx,
  16268. typeParameters[typeName],
  16269. scope,
  16270. typeParameters
  16271. );
  16272. }
  16273. if (
  16274. // @ts-expect-error
  16275. SupportedBuiltinsSet.has(typeName)
  16276. ) {
  16277. return resolveBuiltin(
  16278. ctx,
  16279. node,
  16280. typeName,
  16281. scope,
  16282. typeParameters
  16283. );
  16284. } else if (typeName === "ReturnType" && node.typeParameters) {
  16285. const ret = resolveReturnType(
  16286. ctx,
  16287. node.typeParameters.params[0],
  16288. scope
  16289. );
  16290. if (ret) {
  16291. return resolveTypeElements(ctx, ret, scope);
  16292. }
  16293. }
  16294. }
  16295. return ctx.error(
  16296. `Unresolvable type reference or unsupported built-in utility type`,
  16297. node,
  16298. scope
  16299. );
  16300. }
  16301. }
  16302. case "TSImportType": {
  16303. if (getId(node.argument) === "vue" && ((_b = node.qualifier) == null ? void 0 : _b.type) === "Identifier" && node.qualifier.name === "ExtractPropTypes" && node.typeParameters) {
  16304. return resolveExtractPropTypes(
  16305. resolveTypeElements(ctx, node.typeParameters.params[0], scope),
  16306. scope
  16307. );
  16308. }
  16309. const sourceScope = importSourceToScope(
  16310. ctx,
  16311. node.argument,
  16312. scope,
  16313. node.argument.value
  16314. );
  16315. const resolved = resolveTypeReference(ctx, node, sourceScope);
  16316. if (resolved) {
  16317. return resolveTypeElements(ctx, resolved, resolved._ownerScope);
  16318. }
  16319. break;
  16320. }
  16321. case "TSTypeQuery":
  16322. {
  16323. const resolved = resolveTypeReference(ctx, node, scope);
  16324. if (resolved) {
  16325. return resolveTypeElements(ctx, resolved, resolved._ownerScope);
  16326. }
  16327. }
  16328. break;
  16329. }
  16330. return ctx.error(`Unresolvable type: ${node.type}`, node, scope);
  16331. }
  16332. function typeElementsToMap(ctx, elements, scope = ctxToScope(ctx), typeParameters) {
  16333. const res = { props: {} };
  16334. for (const e of elements) {
  16335. if (e.type === "TSPropertySignature" || e.type === "TSMethodSignature") {
  16336. if (typeParameters) {
  16337. scope = createChildScope(scope);
  16338. scope.isGenericScope = true;
  16339. Object.assign(scope.types, typeParameters);
  16340. }
  16341. e._ownerScope = scope;
  16342. const name = getId(e.key);
  16343. if (name && !e.computed) {
  16344. res.props[name] = e;
  16345. } else if (e.key.type === "TemplateLiteral") {
  16346. for (const key of resolveTemplateKeys(ctx, e.key, scope)) {
  16347. res.props[key] = e;
  16348. }
  16349. } else {
  16350. ctx.error(
  16351. `Unsupported computed key in type referenced by a macro`,
  16352. e.key,
  16353. scope
  16354. );
  16355. }
  16356. } else if (e.type === "TSCallSignatureDeclaration") {
  16357. (res.calls || (res.calls = [])).push(e);
  16358. }
  16359. }
  16360. return res;
  16361. }
  16362. function mergeElements(maps, type) {
  16363. if (maps.length === 1)
  16364. return maps[0];
  16365. const res = { props: {} };
  16366. const { props: baseProps } = res;
  16367. for (const { props, calls } of maps) {
  16368. for (const key in props) {
  16369. if (!shared.hasOwn(baseProps, key)) {
  16370. baseProps[key] = props[key];
  16371. } else {
  16372. baseProps[key] = createProperty(
  16373. baseProps[key].key,
  16374. {
  16375. type,
  16376. // @ts-expect-error
  16377. types: [baseProps[key], props[key]]
  16378. },
  16379. baseProps[key]._ownerScope,
  16380. baseProps[key].optional || props[key].optional
  16381. );
  16382. }
  16383. }
  16384. if (calls) {
  16385. (res.calls || (res.calls = [])).push(...calls);
  16386. }
  16387. }
  16388. return res;
  16389. }
  16390. function createProperty(key, typeAnnotation, scope, optional) {
  16391. return {
  16392. type: "TSPropertySignature",
  16393. key,
  16394. kind: "get",
  16395. optional,
  16396. typeAnnotation: {
  16397. type: "TSTypeAnnotation",
  16398. typeAnnotation
  16399. },
  16400. _ownerScope: scope
  16401. };
  16402. }
  16403. function resolveInterfaceMembers(ctx, node, scope, typeParameters) {
  16404. const base = typeElementsToMap(
  16405. ctx,
  16406. node.body.body,
  16407. node._ownerScope,
  16408. typeParameters
  16409. );
  16410. if (node.extends) {
  16411. for (const ext of node.extends) {
  16412. if (ext.leadingComments && ext.leadingComments.some((c) => c.value.includes("@vue-ignore"))) {
  16413. continue;
  16414. }
  16415. try {
  16416. const { props, calls } = resolveTypeElements(ctx, ext, scope);
  16417. for (const key in props) {
  16418. if (!shared.hasOwn(base.props, key)) {
  16419. base.props[key] = props[key];
  16420. }
  16421. }
  16422. if (calls) {
  16423. ;
  16424. (base.calls || (base.calls = [])).push(...calls);
  16425. }
  16426. } catch (e) {
  16427. ctx.error(
  16428. `Failed to resolve extends base type.
  16429. If this previously worked in 3.2, you can instruct the compiler to ignore this extend by adding /* @vue-ignore */ before it, for example:
  16430. interface Props extends /* @vue-ignore */ Base {}
  16431. Note: both in 3.2 or with the ignore, the properties in the base type are treated as fallthrough attrs at runtime.`,
  16432. ext
  16433. );
  16434. }
  16435. }
  16436. }
  16437. return base;
  16438. }
  16439. function resolveMappedType(ctx, node, scope) {
  16440. const res = { props: {} };
  16441. const keys = resolveStringType(ctx, node.typeParameter.constraint, scope);
  16442. for (const key of keys) {
  16443. res.props[key] = createProperty(
  16444. {
  16445. type: "Identifier",
  16446. name: key
  16447. },
  16448. node.typeAnnotation,
  16449. scope,
  16450. !!node.optional
  16451. );
  16452. }
  16453. return res;
  16454. }
  16455. function resolveIndexType(ctx, node, scope) {
  16456. var _a, _b;
  16457. if (node.indexType.type === "TSNumberKeyword") {
  16458. return resolveArrayElementType(ctx, node.objectType, scope);
  16459. }
  16460. const { indexType, objectType } = node;
  16461. const types = [];
  16462. let keys;
  16463. let resolved;
  16464. if (indexType.type === "TSStringKeyword") {
  16465. resolved = resolveTypeElements(ctx, objectType, scope);
  16466. keys = Object.keys(resolved.props);
  16467. } else {
  16468. keys = resolveStringType(ctx, indexType, scope);
  16469. resolved = resolveTypeElements(ctx, objectType, scope);
  16470. }
  16471. for (const key of keys) {
  16472. const targetType = (_b = (_a = resolved.props[key]) == null ? void 0 : _a.typeAnnotation) == null ? void 0 : _b.typeAnnotation;
  16473. if (targetType) {
  16474. targetType._ownerScope = resolved.props[key]._ownerScope;
  16475. types.push(targetType);
  16476. }
  16477. }
  16478. return types;
  16479. }
  16480. function resolveArrayElementType(ctx, node, scope) {
  16481. if (node.type === "TSArrayType") {
  16482. return [node.elementType];
  16483. }
  16484. if (node.type === "TSTupleType") {
  16485. return node.elementTypes.map(
  16486. (t) => t.type === "TSNamedTupleMember" ? t.elementType : t
  16487. );
  16488. }
  16489. if (node.type === "TSTypeReference") {
  16490. if (getReferenceName(node) === "Array" && node.typeParameters) {
  16491. return node.typeParameters.params;
  16492. } else {
  16493. const resolved = resolveTypeReference(ctx, node, scope);
  16494. if (resolved) {
  16495. return resolveArrayElementType(ctx, resolved, scope);
  16496. }
  16497. }
  16498. }
  16499. return ctx.error(
  16500. "Failed to resolve element type from target type",
  16501. node,
  16502. scope
  16503. );
  16504. }
  16505. function resolveStringType(ctx, node, scope) {
  16506. switch (node.type) {
  16507. case "StringLiteral":
  16508. return [node.value];
  16509. case "TSLiteralType":
  16510. return resolveStringType(ctx, node.literal, scope);
  16511. case "TSUnionType":
  16512. return node.types.map((t) => resolveStringType(ctx, t, scope)).flat();
  16513. case "TemplateLiteral": {
  16514. return resolveTemplateKeys(ctx, node, scope);
  16515. }
  16516. case "TSTypeReference": {
  16517. const resolved = resolveTypeReference(ctx, node, scope);
  16518. if (resolved) {
  16519. return resolveStringType(ctx, resolved, scope);
  16520. }
  16521. if (node.typeName.type === "Identifier") {
  16522. const getParam = (index = 0) => resolveStringType(ctx, node.typeParameters.params[index], scope);
  16523. switch (node.typeName.name) {
  16524. case "Extract":
  16525. return getParam(1);
  16526. case "Exclude": {
  16527. const excluded = getParam(1);
  16528. return getParam().filter((s) => !excluded.includes(s));
  16529. }
  16530. case "Uppercase":
  16531. return getParam().map((s) => s.toUpperCase());
  16532. case "Lowercase":
  16533. return getParam().map((s) => s.toLowerCase());
  16534. case "Capitalize":
  16535. return getParam().map(shared.capitalize);
  16536. case "Uncapitalize":
  16537. return getParam().map((s) => s[0].toLowerCase() + s.slice(1));
  16538. default:
  16539. ctx.error(
  16540. "Unsupported type when resolving index type",
  16541. node.typeName,
  16542. scope
  16543. );
  16544. }
  16545. }
  16546. }
  16547. }
  16548. return ctx.error("Failed to resolve index type into finite keys", node, scope);
  16549. }
  16550. function resolveTemplateKeys(ctx, node, scope) {
  16551. if (!node.expressions.length) {
  16552. return [node.quasis[0].value.raw];
  16553. }
  16554. const res = [];
  16555. const e = node.expressions[0];
  16556. const q = node.quasis[0];
  16557. const leading = q ? q.value.raw : ``;
  16558. const resolved = resolveStringType(ctx, e, scope);
  16559. const restResolved = resolveTemplateKeys(
  16560. ctx,
  16561. {
  16562. ...node,
  16563. expressions: node.expressions.slice(1),
  16564. quasis: q ? node.quasis.slice(1) : node.quasis
  16565. },
  16566. scope
  16567. );
  16568. for (const r of resolved) {
  16569. for (const rr of restResolved) {
  16570. res.push(leading + r + rr);
  16571. }
  16572. }
  16573. return res;
  16574. }
  16575. const SupportedBuiltinsSet = /* @__PURE__ */ new Set([
  16576. "Partial",
  16577. "Required",
  16578. "Readonly",
  16579. "Pick",
  16580. "Omit"
  16581. ]);
  16582. function resolveBuiltin(ctx, node, name, scope, typeParameters) {
  16583. const t = resolveTypeElements(
  16584. ctx,
  16585. node.typeParameters.params[0],
  16586. scope,
  16587. typeParameters
  16588. );
  16589. switch (name) {
  16590. case "Partial": {
  16591. const res2 = { props: {}, calls: t.calls };
  16592. Object.keys(t.props).forEach((key) => {
  16593. res2.props[key] = { ...t.props[key], optional: true };
  16594. });
  16595. return res2;
  16596. }
  16597. case "Required": {
  16598. const res2 = { props: {}, calls: t.calls };
  16599. Object.keys(t.props).forEach((key) => {
  16600. res2.props[key] = { ...t.props[key], optional: false };
  16601. });
  16602. return res2;
  16603. }
  16604. case "Readonly":
  16605. return t;
  16606. case "Pick": {
  16607. const picked = resolveStringType(
  16608. ctx,
  16609. node.typeParameters.params[1],
  16610. scope
  16611. );
  16612. const res2 = { props: {}, calls: t.calls };
  16613. for (const key of picked) {
  16614. res2.props[key] = t.props[key];
  16615. }
  16616. return res2;
  16617. }
  16618. case "Omit":
  16619. const omitted = resolveStringType(
  16620. ctx,
  16621. node.typeParameters.params[1],
  16622. scope
  16623. );
  16624. const res = { props: {}, calls: t.calls };
  16625. for (const key in t.props) {
  16626. if (!omitted.includes(key)) {
  16627. res.props[key] = t.props[key];
  16628. }
  16629. }
  16630. return res;
  16631. }
  16632. }
  16633. function resolveTypeReference(ctx, node, scope, name, onlyExported = false) {
  16634. const canCache = !(scope == null ? void 0 : scope.isGenericScope);
  16635. if (canCache && node._resolvedReference) {
  16636. return node._resolvedReference;
  16637. }
  16638. const resolved = innerResolveTypeReference(
  16639. ctx,
  16640. scope || ctxToScope(ctx),
  16641. name || getReferenceName(node),
  16642. node,
  16643. onlyExported
  16644. );
  16645. return canCache ? node._resolvedReference = resolved : resolved;
  16646. }
  16647. function innerResolveTypeReference(ctx, scope, name, node, onlyExported) {
  16648. if (typeof name === "string") {
  16649. if (scope.imports[name]) {
  16650. return resolveTypeFromImport(ctx, node, name, scope);
  16651. } else {
  16652. const lookupSource = node.type === "TSTypeQuery" ? onlyExported ? scope.exportedDeclares : scope.declares : onlyExported ? scope.exportedTypes : scope.types;
  16653. if (lookupSource[name]) {
  16654. return lookupSource[name];
  16655. } else {
  16656. const globalScopes = resolveGlobalScope(ctx);
  16657. if (globalScopes) {
  16658. for (const s of globalScopes) {
  16659. const src = node.type === "TSTypeQuery" ? s.declares : s.types;
  16660. if (src[name]) {
  16661. (ctx.deps || (ctx.deps = /* @__PURE__ */ new Set())).add(s.filename);
  16662. return src[name];
  16663. }
  16664. }
  16665. }
  16666. }
  16667. }
  16668. } else {
  16669. let ns = innerResolveTypeReference(ctx, scope, name[0], node, onlyExported);
  16670. if (ns) {
  16671. if (ns.type !== "TSModuleDeclaration") {
  16672. ns = ns._ns;
  16673. }
  16674. if (ns) {
  16675. const childScope = moduleDeclToScope(ctx, ns, ns._ownerScope || scope);
  16676. return innerResolveTypeReference(
  16677. ctx,
  16678. childScope,
  16679. name.length > 2 ? name.slice(1) : name[name.length - 1],
  16680. node,
  16681. !ns.declare
  16682. );
  16683. }
  16684. }
  16685. }
  16686. }
  16687. function getReferenceName(node) {
  16688. const ref = node.type === "TSTypeReference" ? node.typeName : node.type === "TSExpressionWithTypeArguments" ? node.expression : node.type === "TSImportType" ? node.qualifier : node.exprName;
  16689. if ((ref == null ? void 0 : ref.type) === "Identifier") {
  16690. return ref.name;
  16691. } else if ((ref == null ? void 0 : ref.type) === "TSQualifiedName") {
  16692. return qualifiedNameToPath(ref);
  16693. } else {
  16694. return "default";
  16695. }
  16696. }
  16697. function qualifiedNameToPath(node) {
  16698. if (node.type === "Identifier") {
  16699. return [node.name];
  16700. } else {
  16701. return [...qualifiedNameToPath(node.left), node.right.name];
  16702. }
  16703. }
  16704. function resolveGlobalScope(ctx) {
  16705. if (ctx.options.globalTypeFiles) {
  16706. const fs = resolveFS(ctx);
  16707. if (!fs) {
  16708. throw new Error("[vue/compiler-sfc] globalTypeFiles requires fs access.");
  16709. }
  16710. return ctx.options.globalTypeFiles.map(
  16711. (file) => fileToScope(ctx, normalizePath(file), true)
  16712. );
  16713. }
  16714. }
  16715. let ts;
  16716. let loadTS;
  16717. function registerTS(_loadTS) {
  16718. loadTS = () => {
  16719. try {
  16720. return _loadTS();
  16721. } catch (err) {
  16722. if (typeof err.message === "string" && err.message.includes("Cannot find module")) {
  16723. throw new Error(
  16724. 'Failed to load TypeScript, which is required for resolving imported types. Please make sure "typescript" is installed as a project dependency.'
  16725. );
  16726. } else {
  16727. throw new Error(
  16728. "Failed to load TypeScript for resolving imported types."
  16729. );
  16730. }
  16731. }
  16732. };
  16733. }
  16734. function resolveFS(ctx) {
  16735. if (ctx.fs) {
  16736. return ctx.fs;
  16737. }
  16738. if (!ts && loadTS) {
  16739. ts = loadTS();
  16740. }
  16741. const fs = ctx.options.fs || (ts == null ? void 0 : ts.sys);
  16742. if (!fs) {
  16743. return;
  16744. }
  16745. return ctx.fs = {
  16746. fileExists(file) {
  16747. if (file.endsWith(".vue.ts")) {
  16748. file = file.replace(/\.ts$/, "");
  16749. }
  16750. return fs.fileExists(file);
  16751. },
  16752. readFile(file) {
  16753. if (file.endsWith(".vue.ts")) {
  16754. file = file.replace(/\.ts$/, "");
  16755. }
  16756. return fs.readFile(file);
  16757. },
  16758. realpath: fs.realpath
  16759. };
  16760. }
  16761. function resolveTypeFromImport(ctx, node, name, scope) {
  16762. const { source, imported } = scope.imports[name];
  16763. const sourceScope = importSourceToScope(ctx, node, scope, source);
  16764. return resolveTypeReference(ctx, node, sourceScope, imported, true);
  16765. }
  16766. function importSourceToScope(ctx, node, scope, source) {
  16767. let fs;
  16768. try {
  16769. fs = resolveFS(ctx);
  16770. } catch (err) {
  16771. return ctx.error(err.message, node, scope);
  16772. }
  16773. if (!fs) {
  16774. return ctx.error(
  16775. `No fs option provided to \`compileScript\` in non-Node environment. File system access is required for resolving imported types.`,
  16776. node,
  16777. scope
  16778. );
  16779. }
  16780. let resolved = scope.resolvedImportSources[source];
  16781. if (!resolved) {
  16782. if (source.startsWith("..")) {
  16783. const osSpecificJoinFn = process__namespace.platform === "win32" ? path$3.join : joinPaths;
  16784. const filename = osSpecificJoinFn(path$3.dirname(scope.filename), source);
  16785. resolved = resolveExt(filename, fs);
  16786. } else if (source.startsWith(".")) {
  16787. const filename = joinPaths(path$3.dirname(scope.filename), source);
  16788. resolved = resolveExt(filename, fs);
  16789. } else {
  16790. if (!ts) {
  16791. if (loadTS)
  16792. ts = loadTS();
  16793. if (!ts) {
  16794. return ctx.error(
  16795. `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.`,
  16796. node,
  16797. scope
  16798. );
  16799. }
  16800. }
  16801. resolved = resolveWithTS(scope.filename, source, ts, fs);
  16802. }
  16803. if (resolved) {
  16804. resolved = scope.resolvedImportSources[source] = normalizePath(resolved);
  16805. }
  16806. }
  16807. if (resolved) {
  16808. (ctx.deps || (ctx.deps = /* @__PURE__ */ new Set())).add(resolved);
  16809. return fileToScope(ctx, resolved);
  16810. } else {
  16811. return ctx.error(
  16812. `Failed to resolve import source ${JSON.stringify(source)}.`,
  16813. node,
  16814. scope
  16815. );
  16816. }
  16817. }
  16818. function resolveExt(filename, fs) {
  16819. filename = filename.replace(/\.js$/, "");
  16820. const tryResolve = (filename2) => {
  16821. if (fs.fileExists(filename2))
  16822. return filename2;
  16823. };
  16824. return tryResolve(filename) || tryResolve(filename + `.ts`) || tryResolve(filename + `.d.ts`) || tryResolve(joinPaths(filename, `index.ts`)) || tryResolve(joinPaths(filename, `index.d.ts`));
  16825. }
  16826. const tsConfigCache = createCache();
  16827. const tsConfigRefMap = /* @__PURE__ */ new Map();
  16828. function resolveWithTS(containingFile, source, ts2, fs) {
  16829. var _a, _b;
  16830. const configPath = ts2.findConfigFile(containingFile, fs.fileExists);
  16831. let tsCompilerOptions;
  16832. let tsResolveCache;
  16833. if (configPath) {
  16834. let configs;
  16835. const normalizedConfigPath = normalizePath(configPath);
  16836. const cached = tsConfigCache.get(normalizedConfigPath);
  16837. if (!cached) {
  16838. configs = loadTSConfig(configPath, ts2, fs).map((config) => ({ config }));
  16839. tsConfigCache.set(normalizedConfigPath, configs);
  16840. } else {
  16841. configs = cached;
  16842. }
  16843. let matchedConfig;
  16844. if (configs.length === 1) {
  16845. matchedConfig = configs[0];
  16846. } else {
  16847. for (const c of configs) {
  16848. const base = normalizePath(
  16849. c.config.options.pathsBasePath || path$3.dirname(c.config.options.configFilePath)
  16850. );
  16851. const included = (_a = c.config.raw) == null ? void 0 : _a.include;
  16852. const excluded = (_b = c.config.raw) == null ? void 0 : _b.exclude;
  16853. if (!included && (!base || containingFile.startsWith(base)) || included.some((p) => minimatch(containingFile, joinPaths(base, p)))) {
  16854. if (excluded && excluded.some((p) => minimatch(containingFile, joinPaths(base, p)))) {
  16855. continue;
  16856. }
  16857. matchedConfig = c;
  16858. break;
  16859. }
  16860. }
  16861. if (!matchedConfig) {
  16862. matchedConfig = configs[configs.length - 1];
  16863. }
  16864. }
  16865. tsCompilerOptions = matchedConfig.config.options;
  16866. tsResolveCache = matchedConfig.cache || (matchedConfig.cache = ts2.createModuleResolutionCache(
  16867. process__namespace.cwd(),
  16868. createGetCanonicalFileName(ts2.sys.useCaseSensitiveFileNames),
  16869. tsCompilerOptions
  16870. ));
  16871. } else {
  16872. tsCompilerOptions = {};
  16873. }
  16874. const res = ts2.resolveModuleName(
  16875. source,
  16876. containingFile,
  16877. tsCompilerOptions,
  16878. fs,
  16879. tsResolveCache
  16880. );
  16881. if (res.resolvedModule) {
  16882. let filename = res.resolvedModule.resolvedFileName;
  16883. if (filename.endsWith(".vue.ts")) {
  16884. filename = filename.replace(/\.ts$/, "");
  16885. }
  16886. return fs.realpath ? fs.realpath(filename) : filename;
  16887. }
  16888. }
  16889. function loadTSConfig(configPath, ts2, fs) {
  16890. const parseConfigHost = ts2.sys;
  16891. const config = ts2.parseJsonConfigFileContent(
  16892. ts2.readConfigFile(configPath, fs.readFile).config,
  16893. parseConfigHost,
  16894. path$3.dirname(configPath),
  16895. void 0,
  16896. configPath
  16897. );
  16898. const res = [config];
  16899. if (config.projectReferences) {
  16900. for (const ref of config.projectReferences) {
  16901. tsConfigRefMap.set(ref.path, configPath);
  16902. res.unshift(...loadTSConfig(ref.path, ts2, fs));
  16903. }
  16904. }
  16905. return res;
  16906. }
  16907. const fileToScopeCache = createCache();
  16908. function invalidateTypeCache(filename) {
  16909. filename = normalizePath(filename);
  16910. fileToScopeCache.delete(filename);
  16911. tsConfigCache.delete(filename);
  16912. const affectedConfig = tsConfigRefMap.get(filename);
  16913. if (affectedConfig)
  16914. tsConfigCache.delete(affectedConfig);
  16915. }
  16916. function fileToScope(ctx, filename, asGlobal = false) {
  16917. const cached = fileToScopeCache.get(filename);
  16918. if (cached) {
  16919. return cached;
  16920. }
  16921. const fs = resolveFS(ctx);
  16922. const source = fs.readFile(filename) || "";
  16923. const body = parseFile(filename, source, ctx.options.babelParserPlugins);
  16924. const scope = new TypeScope(filename, source, 0, recordImports(body));
  16925. recordTypes(ctx, body, scope, asGlobal);
  16926. fileToScopeCache.set(filename, scope);
  16927. return scope;
  16928. }
  16929. function parseFile(filename, content, parserPlugins) {
  16930. const ext = path$3.extname(filename);
  16931. if (ext === ".ts" || ext === ".tsx") {
  16932. return parser$1.parse(content, {
  16933. plugins: resolveParserPlugins(
  16934. ext.slice(1),
  16935. parserPlugins,
  16936. filename.endsWith(".d.ts")
  16937. ),
  16938. sourceType: "module"
  16939. }).program.body;
  16940. } else if (ext === ".vue") {
  16941. const {
  16942. descriptor: { script, scriptSetup }
  16943. } = parse$2(content);
  16944. if (!script && !scriptSetup) {
  16945. return [];
  16946. }
  16947. const scriptOffset = script ? script.loc.start.offset : Infinity;
  16948. const scriptSetupOffset = scriptSetup ? scriptSetup.loc.start.offset : Infinity;
  16949. const firstBlock = scriptOffset < scriptSetupOffset ? script : scriptSetup;
  16950. const secondBlock = scriptOffset < scriptSetupOffset ? scriptSetup : script;
  16951. let scriptContent = " ".repeat(Math.min(scriptOffset, scriptSetupOffset)) + firstBlock.content;
  16952. if (secondBlock) {
  16953. scriptContent += " ".repeat(secondBlock.loc.start.offset - script.loc.end.offset) + secondBlock.content;
  16954. }
  16955. const lang = (script == null ? void 0 : script.lang) || (scriptSetup == null ? void 0 : scriptSetup.lang);
  16956. return parser$1.parse(scriptContent, {
  16957. plugins: resolveParserPlugins(lang, parserPlugins),
  16958. sourceType: "module"
  16959. }).program.body;
  16960. }
  16961. return [];
  16962. }
  16963. function ctxToScope(ctx) {
  16964. if (ctx.scope) {
  16965. return ctx.scope;
  16966. }
  16967. const body = "ast" in ctx ? ctx.ast : ctx.scriptAst ? [...ctx.scriptAst.body, ...ctx.scriptSetupAst.body] : ctx.scriptSetupAst.body;
  16968. const scope = new TypeScope(
  16969. ctx.filename,
  16970. ctx.source,
  16971. "startOffset" in ctx ? ctx.startOffset : 0,
  16972. "userImports" in ctx ? Object.create(ctx.userImports) : recordImports(body)
  16973. );
  16974. recordTypes(ctx, body, scope);
  16975. return ctx.scope = scope;
  16976. }
  16977. function moduleDeclToScope(ctx, node, parentScope) {
  16978. if (node._resolvedChildScope) {
  16979. return node._resolvedChildScope;
  16980. }
  16981. const scope = createChildScope(parentScope);
  16982. if (node.body.type === "TSModuleDeclaration") {
  16983. const decl = node.body;
  16984. decl._ownerScope = scope;
  16985. const id = getId(decl.id);
  16986. scope.types[id] = scope.exportedTypes[id] = decl;
  16987. } else {
  16988. recordTypes(ctx, node.body.body, scope);
  16989. }
  16990. return node._resolvedChildScope = scope;
  16991. }
  16992. function createChildScope(parentScope) {
  16993. return new TypeScope(
  16994. parentScope.filename,
  16995. parentScope.source,
  16996. parentScope.offset,
  16997. Object.create(parentScope.imports),
  16998. Object.create(parentScope.types),
  16999. Object.create(parentScope.declares)
  17000. );
  17001. }
  17002. const importExportRE = /^Import|^Export/;
  17003. function recordTypes(ctx, body, scope, asGlobal = false) {
  17004. const { types, declares, exportedTypes, exportedDeclares, imports } = scope;
  17005. const isAmbient = asGlobal ? !body.some((s) => importExportRE.test(s.type)) : false;
  17006. for (const stmt of body) {
  17007. if (asGlobal) {
  17008. if (isAmbient) {
  17009. if (stmt.declare) {
  17010. recordType(stmt, types, declares);
  17011. }
  17012. } else if (stmt.type === "TSModuleDeclaration" && stmt.global) {
  17013. for (const s of stmt.body.body) {
  17014. recordType(s, types, declares);
  17015. }
  17016. }
  17017. } else {
  17018. recordType(stmt, types, declares);
  17019. }
  17020. }
  17021. if (!asGlobal) {
  17022. for (const stmt of body) {
  17023. if (stmt.type === "ExportNamedDeclaration") {
  17024. if (stmt.declaration) {
  17025. recordType(stmt.declaration, types, declares);
  17026. recordType(stmt.declaration, exportedTypes, exportedDeclares);
  17027. } else {
  17028. for (const spec of stmt.specifiers) {
  17029. if (spec.type === "ExportSpecifier") {
  17030. const local = spec.local.name;
  17031. const exported = getId(spec.exported);
  17032. if (stmt.source) {
  17033. imports[exported] = {
  17034. source: stmt.source.value,
  17035. imported: local
  17036. };
  17037. exportedTypes[exported] = {
  17038. type: "TSTypeReference",
  17039. typeName: {
  17040. type: "Identifier",
  17041. name: local
  17042. },
  17043. _ownerScope: scope
  17044. };
  17045. } else if (types[local]) {
  17046. exportedTypes[exported] = types[local];
  17047. }
  17048. }
  17049. }
  17050. }
  17051. } else if (stmt.type === "ExportAllDeclaration") {
  17052. const sourceScope = importSourceToScope(
  17053. ctx,
  17054. stmt.source,
  17055. scope,
  17056. stmt.source.value
  17057. );
  17058. Object.assign(scope.exportedTypes, sourceScope.exportedTypes);
  17059. } else if (stmt.type === "ExportDefaultDeclaration" && stmt.declaration) {
  17060. if (stmt.declaration.type !== "Identifier") {
  17061. recordType(stmt.declaration, types, declares, "default");
  17062. recordType(
  17063. stmt.declaration,
  17064. exportedTypes,
  17065. exportedDeclares,
  17066. "default"
  17067. );
  17068. } else if (types[stmt.declaration.name]) {
  17069. exportedTypes["default"] = types[stmt.declaration.name];
  17070. }
  17071. }
  17072. }
  17073. }
  17074. for (const key of Object.keys(types)) {
  17075. const node = types[key];
  17076. node._ownerScope = scope;
  17077. if (node._ns)
  17078. node._ns._ownerScope = scope;
  17079. }
  17080. for (const key of Object.keys(declares)) {
  17081. declares[key]._ownerScope = scope;
  17082. }
  17083. }
  17084. function recordType(node, types, declares, overwriteId) {
  17085. switch (node.type) {
  17086. case "TSInterfaceDeclaration":
  17087. case "TSEnumDeclaration":
  17088. case "TSModuleDeclaration": {
  17089. const id = overwriteId || getId(node.id);
  17090. let existing = types[id];
  17091. if (existing) {
  17092. if (node.type === "TSModuleDeclaration") {
  17093. if (existing.type === "TSModuleDeclaration") {
  17094. mergeNamespaces(existing, node);
  17095. } else {
  17096. attachNamespace(existing, node);
  17097. }
  17098. break;
  17099. }
  17100. if (existing.type === "TSModuleDeclaration") {
  17101. types[id] = node;
  17102. attachNamespace(node, existing);
  17103. break;
  17104. }
  17105. if (existing.type !== node.type) {
  17106. break;
  17107. }
  17108. if (node.type === "TSInterfaceDeclaration") {
  17109. existing.body.body.push(...node.body.body);
  17110. } else {
  17111. existing.members.push(...node.members);
  17112. }
  17113. } else {
  17114. types[id] = node;
  17115. }
  17116. break;
  17117. }
  17118. case "ClassDeclaration":
  17119. if (overwriteId || node.id)
  17120. types[overwriteId || getId(node.id)] = node;
  17121. break;
  17122. case "TSTypeAliasDeclaration":
  17123. types[node.id.name] = node.typeParameters ? node : node.typeAnnotation;
  17124. break;
  17125. case "TSDeclareFunction":
  17126. if (node.id)
  17127. declares[node.id.name] = node;
  17128. break;
  17129. case "VariableDeclaration": {
  17130. if (node.declare) {
  17131. for (const decl of node.declarations) {
  17132. if (decl.id.type === "Identifier" && decl.id.typeAnnotation) {
  17133. declares[decl.id.name] = decl.id.typeAnnotation.typeAnnotation;
  17134. }
  17135. }
  17136. }
  17137. break;
  17138. }
  17139. }
  17140. }
  17141. function mergeNamespaces(to, from) {
  17142. const toBody = to.body;
  17143. const fromBody = from.body;
  17144. if (toBody.type === "TSModuleDeclaration") {
  17145. if (fromBody.type === "TSModuleDeclaration") {
  17146. mergeNamespaces(toBody, fromBody);
  17147. } else {
  17148. fromBody.body.push({
  17149. type: "ExportNamedDeclaration",
  17150. declaration: toBody,
  17151. exportKind: "type",
  17152. specifiers: []
  17153. });
  17154. }
  17155. } else if (fromBody.type === "TSModuleDeclaration") {
  17156. toBody.body.push({
  17157. type: "ExportNamedDeclaration",
  17158. declaration: fromBody,
  17159. exportKind: "type",
  17160. specifiers: []
  17161. });
  17162. } else {
  17163. toBody.body.push(...fromBody.body);
  17164. }
  17165. }
  17166. function attachNamespace(to, ns) {
  17167. if (!to._ns) {
  17168. to._ns = ns;
  17169. } else {
  17170. mergeNamespaces(to._ns, ns);
  17171. }
  17172. }
  17173. function recordImports(body) {
  17174. const imports = /* @__PURE__ */ Object.create(null);
  17175. for (const s of body) {
  17176. recordImport(s, imports);
  17177. }
  17178. return imports;
  17179. }
  17180. function recordImport(node, imports) {
  17181. if (node.type !== "ImportDeclaration") {
  17182. return;
  17183. }
  17184. for (const s of node.specifiers) {
  17185. imports[s.local.name] = {
  17186. imported: getImportedName(s),
  17187. source: node.source.value
  17188. };
  17189. }
  17190. }
  17191. function inferRuntimeType(ctx, node, scope = node._ownerScope || ctxToScope(ctx)) {
  17192. try {
  17193. switch (node.type) {
  17194. case "TSStringKeyword":
  17195. return ["String"];
  17196. case "TSNumberKeyword":
  17197. return ["Number"];
  17198. case "TSBooleanKeyword":
  17199. return ["Boolean"];
  17200. case "TSObjectKeyword":
  17201. return ["Object"];
  17202. case "TSNullKeyword":
  17203. return ["null"];
  17204. case "TSTypeLiteral":
  17205. case "TSInterfaceDeclaration": {
  17206. const types = /* @__PURE__ */ new Set();
  17207. const members = node.type === "TSTypeLiteral" ? node.members : node.body.body;
  17208. for (const m of members) {
  17209. if (m.type === "TSCallSignatureDeclaration" || m.type === "TSConstructSignatureDeclaration") {
  17210. types.add("Function");
  17211. } else {
  17212. types.add("Object");
  17213. }
  17214. }
  17215. return types.size ? Array.from(types) : ["Object"];
  17216. }
  17217. case "TSPropertySignature":
  17218. if (node.typeAnnotation) {
  17219. return inferRuntimeType(
  17220. ctx,
  17221. node.typeAnnotation.typeAnnotation,
  17222. scope
  17223. );
  17224. }
  17225. break;
  17226. case "TSMethodSignature":
  17227. case "TSFunctionType":
  17228. return ["Function"];
  17229. case "TSArrayType":
  17230. case "TSTupleType":
  17231. return ["Array"];
  17232. case "TSLiteralType":
  17233. switch (node.literal.type) {
  17234. case "StringLiteral":
  17235. return ["String"];
  17236. case "BooleanLiteral":
  17237. return ["Boolean"];
  17238. case "NumericLiteral":
  17239. case "BigIntLiteral":
  17240. return ["Number"];
  17241. default:
  17242. return [UNKNOWN_TYPE];
  17243. }
  17244. case "TSTypeReference": {
  17245. const resolved = resolveTypeReference(ctx, node, scope);
  17246. if (resolved) {
  17247. return inferRuntimeType(ctx, resolved, resolved._ownerScope);
  17248. }
  17249. if (node.typeName.type === "Identifier") {
  17250. switch (node.typeName.name) {
  17251. case "Array":
  17252. case "Function":
  17253. case "Object":
  17254. case "Set":
  17255. case "Map":
  17256. case "WeakSet":
  17257. case "WeakMap":
  17258. case "Date":
  17259. case "Promise":
  17260. case "Error":
  17261. return [node.typeName.name];
  17262. case "Partial":
  17263. case "Required":
  17264. case "Readonly":
  17265. case "Record":
  17266. case "Pick":
  17267. case "Omit":
  17268. case "InstanceType":
  17269. return ["Object"];
  17270. case "Uppercase":
  17271. case "Lowercase":
  17272. case "Capitalize":
  17273. case "Uncapitalize":
  17274. return ["String"];
  17275. case "Parameters":
  17276. case "ConstructorParameters":
  17277. return ["Array"];
  17278. case "NonNullable":
  17279. if (node.typeParameters && node.typeParameters.params[0]) {
  17280. return inferRuntimeType(
  17281. ctx,
  17282. node.typeParameters.params[0],
  17283. scope
  17284. ).filter((t) => t !== "null");
  17285. }
  17286. break;
  17287. case "Extract":
  17288. if (node.typeParameters && node.typeParameters.params[1]) {
  17289. return inferRuntimeType(
  17290. ctx,
  17291. node.typeParameters.params[1],
  17292. scope
  17293. );
  17294. }
  17295. break;
  17296. case "Exclude":
  17297. case "OmitThisParameter":
  17298. if (node.typeParameters && node.typeParameters.params[0]) {
  17299. return inferRuntimeType(
  17300. ctx,
  17301. node.typeParameters.params[0],
  17302. scope
  17303. );
  17304. }
  17305. break;
  17306. }
  17307. }
  17308. break;
  17309. }
  17310. case "TSParenthesizedType":
  17311. return inferRuntimeType(ctx, node.typeAnnotation, scope);
  17312. case "TSUnionType":
  17313. return flattenTypes(ctx, node.types, scope);
  17314. case "TSIntersectionType": {
  17315. return flattenTypes(ctx, node.types, scope).filter(
  17316. (t) => t !== UNKNOWN_TYPE
  17317. );
  17318. }
  17319. case "TSEnumDeclaration":
  17320. return inferEnumType(node);
  17321. case "TSSymbolKeyword":
  17322. return ["Symbol"];
  17323. case "TSIndexedAccessType": {
  17324. const types = resolveIndexType(ctx, node, scope);
  17325. return flattenTypes(ctx, types, scope);
  17326. }
  17327. case "ClassDeclaration":
  17328. return ["Object"];
  17329. case "TSImportType": {
  17330. const sourceScope = importSourceToScope(
  17331. ctx,
  17332. node.argument,
  17333. scope,
  17334. node.argument.value
  17335. );
  17336. const resolved = resolveTypeReference(ctx, node, sourceScope);
  17337. if (resolved) {
  17338. return inferRuntimeType(ctx, resolved, resolved._ownerScope);
  17339. }
  17340. break;
  17341. }
  17342. case "TSTypeQuery": {
  17343. const id = node.exprName;
  17344. if (id.type === "Identifier") {
  17345. const matched = scope.declares[id.name];
  17346. if (matched) {
  17347. return inferRuntimeType(ctx, matched, matched._ownerScope);
  17348. }
  17349. }
  17350. break;
  17351. }
  17352. }
  17353. } catch (e) {
  17354. }
  17355. return [UNKNOWN_TYPE];
  17356. }
  17357. function flattenTypes(ctx, types, scope) {
  17358. if (types.length === 1) {
  17359. return inferRuntimeType(ctx, types[0], scope);
  17360. }
  17361. return [
  17362. ...new Set(
  17363. [].concat(
  17364. ...types.map((t) => inferRuntimeType(ctx, t, scope))
  17365. )
  17366. )
  17367. ];
  17368. }
  17369. function inferEnumType(node) {
  17370. const types = /* @__PURE__ */ new Set();
  17371. for (const m of node.members) {
  17372. if (m.initializer) {
  17373. switch (m.initializer.type) {
  17374. case "StringLiteral":
  17375. types.add("String");
  17376. break;
  17377. case "NumericLiteral":
  17378. types.add("Number");
  17379. break;
  17380. }
  17381. }
  17382. }
  17383. return types.size ? [...types] : ["Number"];
  17384. }
  17385. function resolveExtractPropTypes({ props }, scope) {
  17386. const res = { props: {} };
  17387. for (const key in props) {
  17388. const raw = props[key];
  17389. res.props[key] = reverseInferType(
  17390. raw.key,
  17391. raw.typeAnnotation.typeAnnotation,
  17392. scope
  17393. );
  17394. }
  17395. return res;
  17396. }
  17397. function reverseInferType(key, node, scope, optional = true, checkObjectSyntax = true) {
  17398. if (checkObjectSyntax && node.type === "TSTypeLiteral") {
  17399. const typeType = findStaticPropertyType(node, "type");
  17400. if (typeType) {
  17401. const requiredType = findStaticPropertyType(node, "required");
  17402. const optional2 = requiredType && requiredType.type === "TSLiteralType" && requiredType.literal.type === "BooleanLiteral" ? !requiredType.literal.value : true;
  17403. return reverseInferType(key, typeType, scope, optional2, false);
  17404. }
  17405. } else if (node.type === "TSTypeReference" && node.typeName.type === "Identifier") {
  17406. if (node.typeName.name.endsWith("Constructor")) {
  17407. return createProperty(
  17408. key,
  17409. ctorToType(node.typeName.name),
  17410. scope,
  17411. optional
  17412. );
  17413. } else if (node.typeName.name === "PropType" && node.typeParameters) {
  17414. return createProperty(key, node.typeParameters.params[0], scope, optional);
  17415. }
  17416. }
  17417. if ((node.type === "TSTypeReference" || node.type === "TSImportType") && node.typeParameters) {
  17418. for (const t of node.typeParameters.params) {
  17419. const inferred = reverseInferType(key, t, scope, optional);
  17420. if (inferred)
  17421. return inferred;
  17422. }
  17423. }
  17424. return createProperty(key, { type: `TSNullKeyword` }, scope, optional);
  17425. }
  17426. function ctorToType(ctorType) {
  17427. const ctor = ctorType.slice(0, -11);
  17428. switch (ctor) {
  17429. case "String":
  17430. case "Number":
  17431. case "Boolean":
  17432. return { type: `TS${ctor}Keyword` };
  17433. case "Array":
  17434. case "Function":
  17435. case "Object":
  17436. case "Set":
  17437. case "Map":
  17438. case "WeakSet":
  17439. case "WeakMap":
  17440. case "Date":
  17441. case "Promise":
  17442. return {
  17443. type: "TSTypeReference",
  17444. typeName: { type: "Identifier", name: ctor }
  17445. };
  17446. }
  17447. return { type: `TSNullKeyword` };
  17448. }
  17449. function findStaticPropertyType(node, key) {
  17450. const prop = node.members.find(
  17451. (m) => m.type === "TSPropertySignature" && !m.computed && getId(m.key) === key && m.typeAnnotation
  17452. );
  17453. return prop && prop.typeAnnotation.typeAnnotation;
  17454. }
  17455. function resolveReturnType(ctx, arg, scope) {
  17456. var _a;
  17457. let resolved = arg;
  17458. if (arg.type === "TSTypeReference" || arg.type === "TSTypeQuery" || arg.type === "TSImportType") {
  17459. resolved = resolveTypeReference(ctx, arg, scope);
  17460. }
  17461. if (!resolved)
  17462. return;
  17463. if (resolved.type === "TSFunctionType") {
  17464. return (_a = resolved.typeAnnotation) == null ? void 0 : _a.typeAnnotation;
  17465. }
  17466. if (resolved.type === "TSDeclareFunction") {
  17467. return resolved.returnType;
  17468. }
  17469. }
  17470. function resolveUnionType(ctx, node, scope) {
  17471. if (node.type === "TSTypeReference") {
  17472. const resolved = resolveTypeReference(ctx, node, scope);
  17473. if (resolved)
  17474. node = resolved;
  17475. }
  17476. let types;
  17477. if (node.type === "TSUnionType") {
  17478. types = node.types.flatMap((node2) => resolveUnionType(ctx, node2, scope));
  17479. } else {
  17480. types = [node];
  17481. }
  17482. return types;
  17483. }
  17484. const DEFINE_MODEL = "defineModel";
  17485. function processDefineModel(ctx, node, declId) {
  17486. if (!isCallOf(node, DEFINE_MODEL)) {
  17487. return false;
  17488. }
  17489. ctx.hasDefineModelCall = true;
  17490. const type = node.typeParameters && node.typeParameters.params[0] || void 0;
  17491. let modelName;
  17492. let options;
  17493. const arg0 = node.arguments[0] && CompilerDOM.unwrapTSNode(node.arguments[0]);
  17494. const hasName = arg0 && arg0.type === "StringLiteral";
  17495. if (hasName) {
  17496. modelName = arg0.value;
  17497. options = node.arguments[1];
  17498. } else {
  17499. modelName = "modelValue";
  17500. options = arg0;
  17501. }
  17502. if (ctx.modelDecls[modelName]) {
  17503. ctx.error(`duplicate model name ${JSON.stringify(modelName)}`, node);
  17504. }
  17505. let optionsString = options && ctx.getString(options);
  17506. let optionsRemoved = !options;
  17507. const runtimeOptionNodes = [];
  17508. if (options && options.type === "ObjectExpression" && !options.properties.some((p) => p.type === "SpreadElement" || p.computed)) {
  17509. let removed = 0;
  17510. for (let i = options.properties.length - 1; i >= 0; i--) {
  17511. const p = options.properties[i];
  17512. const next = options.properties[i + 1];
  17513. const start = p.start;
  17514. const end = next ? next.start : options.end - 1;
  17515. 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"))) {
  17516. optionsString = optionsString.slice(0, start - options.start) + optionsString.slice(end - options.start);
  17517. } else {
  17518. removed++;
  17519. ctx.s.remove(ctx.startOffset + start, ctx.startOffset + end);
  17520. runtimeOptionNodes.push(p);
  17521. }
  17522. }
  17523. if (removed === options.properties.length) {
  17524. optionsRemoved = true;
  17525. ctx.s.remove(
  17526. ctx.startOffset + (hasName ? arg0.end : options.start),
  17527. ctx.startOffset + options.end
  17528. );
  17529. }
  17530. }
  17531. ctx.modelDecls[modelName] = {
  17532. type,
  17533. options: optionsString,
  17534. runtimeOptionNodes,
  17535. identifier: declId && declId.type === "Identifier" ? declId.name : void 0
  17536. };
  17537. ctx.bindingMetadata[modelName] = "props";
  17538. ctx.s.overwrite(
  17539. ctx.startOffset + node.callee.start,
  17540. ctx.startOffset + node.callee.end,
  17541. ctx.helper("useModel")
  17542. );
  17543. ctx.s.appendLeft(
  17544. ctx.startOffset + (node.arguments.length ? node.arguments[0].start : node.end - 1),
  17545. `__props, ` + (hasName ? `` : `${JSON.stringify(modelName)}${optionsRemoved ? `` : `, `}`)
  17546. );
  17547. return true;
  17548. }
  17549. function genModelProps(ctx) {
  17550. if (!ctx.hasDefineModelCall)
  17551. return;
  17552. const isProd = !!ctx.options.isProd;
  17553. let modelPropsDecl = "";
  17554. for (const [name, { type, options }] of Object.entries(ctx.modelDecls)) {
  17555. let skipCheck = false;
  17556. let runtimeTypes = type && inferRuntimeType(ctx, type);
  17557. if (runtimeTypes) {
  17558. const hasUnknownType = runtimeTypes.includes(UNKNOWN_TYPE);
  17559. runtimeTypes = runtimeTypes.filter((el) => {
  17560. if (el === UNKNOWN_TYPE)
  17561. return false;
  17562. return isProd ? el === "Boolean" || el === "Function" && options : true;
  17563. });
  17564. skipCheck = !isProd && hasUnknownType && runtimeTypes.length > 0;
  17565. }
  17566. let runtimeType = runtimeTypes && runtimeTypes.length > 0 && toRuntimeTypeString(runtimeTypes) || void 0;
  17567. const codegenOptions = concatStrings([
  17568. runtimeType && `type: ${runtimeType}`,
  17569. skipCheck && "skipCheck: true"
  17570. ]);
  17571. let decl;
  17572. if (runtimeType && options) {
  17573. decl = ctx.isTS ? `{ ${codegenOptions}, ...${options} }` : `Object.assign({ ${codegenOptions} }, ${options})`;
  17574. } else {
  17575. decl = options || (runtimeType ? `{ ${codegenOptions} }` : "{}");
  17576. }
  17577. modelPropsDecl += `
  17578. ${JSON.stringify(name)}: ${decl},`;
  17579. const modifierPropName = JSON.stringify(
  17580. name === "modelValue" ? `modelModifiers` : `${name}Modifiers`
  17581. );
  17582. modelPropsDecl += `
  17583. ${modifierPropName}: {},`;
  17584. }
  17585. return `{${modelPropsDecl}
  17586. }`;
  17587. }
  17588. const DEFINE_PROPS = "defineProps";
  17589. const WITH_DEFAULTS = "withDefaults";
  17590. function processDefineProps(ctx, node, declId) {
  17591. if (!isCallOf(node, DEFINE_PROPS)) {
  17592. return processWithDefaults(ctx, node, declId);
  17593. }
  17594. if (ctx.hasDefinePropsCall) {
  17595. ctx.error(`duplicate ${DEFINE_PROPS}() call`, node);
  17596. }
  17597. ctx.hasDefinePropsCall = true;
  17598. ctx.propsRuntimeDecl = node.arguments[0];
  17599. if (ctx.propsRuntimeDecl) {
  17600. for (const key of getObjectOrArrayExpressionKeys(ctx.propsRuntimeDecl)) {
  17601. if (!(key in ctx.bindingMetadata)) {
  17602. ctx.bindingMetadata[key] = "props";
  17603. }
  17604. }
  17605. }
  17606. if (node.typeParameters) {
  17607. if (ctx.propsRuntimeDecl) {
  17608. ctx.error(
  17609. `${DEFINE_PROPS}() cannot accept both type and non-type arguments at the same time. Use one or the other.`,
  17610. node
  17611. );
  17612. }
  17613. ctx.propsTypeDecl = node.typeParameters.params[0];
  17614. }
  17615. if (declId && declId.type === "ObjectPattern") {
  17616. processPropsDestructure(ctx, declId);
  17617. }
  17618. ctx.propsCall = node;
  17619. ctx.propsDecl = declId;
  17620. return true;
  17621. }
  17622. function processWithDefaults(ctx, node, declId) {
  17623. if (!isCallOf(node, WITH_DEFAULTS)) {
  17624. return false;
  17625. }
  17626. if (!processDefineProps(ctx, node.arguments[0], declId)) {
  17627. ctx.error(
  17628. `${WITH_DEFAULTS}' first argument must be a ${DEFINE_PROPS} call.`,
  17629. node.arguments[0] || node
  17630. );
  17631. }
  17632. if (ctx.propsRuntimeDecl) {
  17633. ctx.error(
  17634. `${WITH_DEFAULTS} can only be used with type-based ${DEFINE_PROPS} declaration.`,
  17635. node
  17636. );
  17637. }
  17638. if (ctx.propsDestructureDecl) {
  17639. ctx.error(
  17640. `${WITH_DEFAULTS}() is unnecessary when using destructure with ${DEFINE_PROPS}().
  17641. Prefer using destructure default values, e.g. const { foo = 1 } = defineProps(...).`,
  17642. node.callee
  17643. );
  17644. }
  17645. ctx.propsRuntimeDefaults = node.arguments[1];
  17646. if (!ctx.propsRuntimeDefaults) {
  17647. ctx.error(`The 2nd argument of ${WITH_DEFAULTS} is required.`, node);
  17648. }
  17649. ctx.propsCall = node;
  17650. return true;
  17651. }
  17652. function genRuntimeProps(ctx) {
  17653. let propsDecls;
  17654. if (ctx.propsRuntimeDecl) {
  17655. propsDecls = ctx.getString(ctx.propsRuntimeDecl).trim();
  17656. if (ctx.propsDestructureDecl) {
  17657. const defaults = [];
  17658. for (const key in ctx.propsDestructuredBindings) {
  17659. const d = genDestructuredDefaultValue(ctx, key);
  17660. const finalKey = getEscapedPropName(key);
  17661. if (d)
  17662. defaults.push(
  17663. `${finalKey}: ${d.valueString}${d.needSkipFactory ? `, __skip_${finalKey}: true` : ``}`
  17664. );
  17665. }
  17666. if (defaults.length) {
  17667. propsDecls = `/*#__PURE__*/${ctx.helper(
  17668. `mergeDefaults`
  17669. )}(${propsDecls}, {
  17670. ${defaults.join(",\n ")}
  17671. })`;
  17672. }
  17673. }
  17674. } else if (ctx.propsTypeDecl) {
  17675. propsDecls = extractRuntimeProps(ctx);
  17676. }
  17677. const modelsDecls = genModelProps(ctx);
  17678. if (propsDecls && modelsDecls) {
  17679. return `/*#__PURE__*/${ctx.helper(
  17680. "mergeModels"
  17681. )}(${propsDecls}, ${modelsDecls})`;
  17682. } else {
  17683. return modelsDecls || propsDecls;
  17684. }
  17685. }
  17686. function extractRuntimeProps(ctx) {
  17687. const props = resolveRuntimePropsFromType(ctx, ctx.propsTypeDecl);
  17688. if (!props.length) {
  17689. return;
  17690. }
  17691. const propStrings = [];
  17692. const hasStaticDefaults = hasStaticWithDefaults(ctx);
  17693. for (const prop of props) {
  17694. propStrings.push(genRuntimePropFromType(ctx, prop, hasStaticDefaults));
  17695. if ("bindingMetadata" in ctx && !(prop.key in ctx.bindingMetadata)) {
  17696. ctx.bindingMetadata[prop.key] = "props";
  17697. }
  17698. }
  17699. let propsDecls = `{
  17700. ${propStrings.join(",\n ")}
  17701. }`;
  17702. if (ctx.propsRuntimeDefaults && !hasStaticDefaults) {
  17703. propsDecls = `/*#__PURE__*/${ctx.helper(
  17704. "mergeDefaults"
  17705. )}(${propsDecls}, ${ctx.getString(ctx.propsRuntimeDefaults)})`;
  17706. }
  17707. return propsDecls;
  17708. }
  17709. function resolveRuntimePropsFromType(ctx, node) {
  17710. const props = [];
  17711. const elements = resolveTypeElements(ctx, node);
  17712. for (const key in elements.props) {
  17713. const e = elements.props[key];
  17714. let type = inferRuntimeType(ctx, e);
  17715. let skipCheck = false;
  17716. if (type.includes(UNKNOWN_TYPE)) {
  17717. if (type.includes("Boolean") || type.includes("Function")) {
  17718. type = type.filter((t) => t !== UNKNOWN_TYPE);
  17719. skipCheck = true;
  17720. } else {
  17721. type = ["null"];
  17722. }
  17723. }
  17724. props.push({
  17725. key,
  17726. required: !e.optional,
  17727. type: type || [`null`],
  17728. skipCheck
  17729. });
  17730. }
  17731. return props;
  17732. }
  17733. function genRuntimePropFromType(ctx, { key, required, type, skipCheck }, hasStaticDefaults) {
  17734. let defaultString;
  17735. const destructured = genDestructuredDefaultValue(ctx, key, type);
  17736. if (destructured) {
  17737. defaultString = `default: ${destructured.valueString}${destructured.needSkipFactory ? `, skipFactory: true` : ``}`;
  17738. } else if (hasStaticDefaults) {
  17739. const prop = ctx.propsRuntimeDefaults.properties.find(
  17740. (node) => {
  17741. if (node.type === "SpreadElement")
  17742. return false;
  17743. return resolveObjectKey(node.key, node.computed) === key;
  17744. }
  17745. );
  17746. if (prop) {
  17747. if (prop.type === "ObjectProperty") {
  17748. defaultString = `default: ${ctx.getString(prop.value)}`;
  17749. } else {
  17750. defaultString = `${prop.async ? "async " : ""}${prop.kind !== "method" ? `${prop.kind} ` : ""}default() ${ctx.getString(prop.body)}`;
  17751. }
  17752. }
  17753. }
  17754. const finalKey = getEscapedPropName(key);
  17755. if (!ctx.options.isProd) {
  17756. return `${finalKey}: { ${concatStrings([
  17757. `type: ${toRuntimeTypeString(type)}`,
  17758. `required: ${required}`,
  17759. skipCheck && "skipCheck: true",
  17760. defaultString
  17761. ])} }`;
  17762. } else if (type.some(
  17763. (el) => el === "Boolean" || (!hasStaticDefaults || defaultString) && el === "Function"
  17764. )) {
  17765. return `${finalKey}: { ${concatStrings([
  17766. `type: ${toRuntimeTypeString(type)}`,
  17767. defaultString
  17768. ])} }`;
  17769. } else {
  17770. if (ctx.isCE) {
  17771. if (defaultString) {
  17772. return `${finalKey}: ${`{ ${defaultString}, type: ${toRuntimeTypeString(
  17773. type
  17774. )} }`}`;
  17775. } else {
  17776. return `${finalKey}: {type: ${toRuntimeTypeString(type)}}`;
  17777. }
  17778. }
  17779. return `${finalKey}: ${defaultString ? `{ ${defaultString} }` : `{}`}`;
  17780. }
  17781. }
  17782. function hasStaticWithDefaults(ctx) {
  17783. return !!(ctx.propsRuntimeDefaults && ctx.propsRuntimeDefaults.type === "ObjectExpression" && ctx.propsRuntimeDefaults.properties.every(
  17784. (node) => node.type !== "SpreadElement" && (!node.computed || node.key.type.endsWith("Literal"))
  17785. ));
  17786. }
  17787. function genDestructuredDefaultValue(ctx, key, inferredType) {
  17788. const destructured = ctx.propsDestructuredBindings[key];
  17789. const defaultVal = destructured && destructured.default;
  17790. if (defaultVal) {
  17791. const value = ctx.getString(defaultVal);
  17792. const unwrapped = CompilerDOM.unwrapTSNode(defaultVal);
  17793. if (inferredType && inferredType.length && !inferredType.includes("null")) {
  17794. const valueType = inferValueType(unwrapped);
  17795. if (valueType && !inferredType.includes(valueType)) {
  17796. ctx.error(
  17797. `Default value of prop "${key}" does not match declared type.`,
  17798. unwrapped
  17799. );
  17800. }
  17801. }
  17802. const needSkipFactory = !inferredType && (CompilerDOM.isFunctionType(unwrapped) || unwrapped.type === "Identifier");
  17803. const needFactoryWrap = !needSkipFactory && !isLiteralNode(unwrapped) && !(inferredType == null ? void 0 : inferredType.includes("Function"));
  17804. return {
  17805. valueString: needFactoryWrap ? `() => (${value})` : value,
  17806. needSkipFactory
  17807. };
  17808. }
  17809. }
  17810. function inferValueType(node) {
  17811. switch (node.type) {
  17812. case "StringLiteral":
  17813. return "String";
  17814. case "NumericLiteral":
  17815. return "Number";
  17816. case "BooleanLiteral":
  17817. return "Boolean";
  17818. case "ObjectExpression":
  17819. return "Object";
  17820. case "ArrayExpression":
  17821. return "Array";
  17822. case "FunctionExpression":
  17823. case "ArrowFunctionExpression":
  17824. return "Function";
  17825. }
  17826. }
  17827. function processPropsDestructure(ctx, declId) {
  17828. if (!ctx.options.propsDestructure) {
  17829. return;
  17830. }
  17831. warnOnce(
  17832. `This project is using reactive props destructure, which is an experimental feature. It may receive breaking changes or be removed in the future, so use at your own risk.
  17833. To stay updated, follow the RFC at https://github.com/vuejs/rfcs/discussions/502.`
  17834. );
  17835. ctx.propsDestructureDecl = declId;
  17836. const registerBinding = (key, local, defaultValue) => {
  17837. ctx.propsDestructuredBindings[key] = { local, default: defaultValue };
  17838. if (local !== key) {
  17839. ctx.bindingMetadata[local] = "props-aliased";
  17840. (ctx.bindingMetadata.__propsAliases || (ctx.bindingMetadata.__propsAliases = {}))[local] = key;
  17841. }
  17842. };
  17843. for (const prop of declId.properties) {
  17844. if (prop.type === "ObjectProperty") {
  17845. const propKey = resolveObjectKey(prop.key, prop.computed);
  17846. if (!propKey) {
  17847. ctx.error(
  17848. `${DEFINE_PROPS}() destructure cannot use computed key.`,
  17849. prop.key
  17850. );
  17851. }
  17852. if (prop.value.type === "AssignmentPattern") {
  17853. const { left, right } = prop.value;
  17854. if (left.type !== "Identifier") {
  17855. ctx.error(
  17856. `${DEFINE_PROPS}() destructure does not support nested patterns.`,
  17857. left
  17858. );
  17859. }
  17860. registerBinding(propKey, left.name, right);
  17861. } else if (prop.value.type === "Identifier") {
  17862. registerBinding(propKey, prop.value.name);
  17863. } else {
  17864. ctx.error(
  17865. `${DEFINE_PROPS}() destructure does not support nested patterns.`,
  17866. prop.value
  17867. );
  17868. }
  17869. } else {
  17870. ctx.propsDestructureRestId = prop.argument.name;
  17871. ctx.bindingMetadata[ctx.propsDestructureRestId] = "setup-reactive-const";
  17872. }
  17873. }
  17874. }
  17875. function transformDestructuredProps(ctx, vueImportAliases) {
  17876. if (!ctx.options.propsDestructure) {
  17877. return;
  17878. }
  17879. const rootScope = {};
  17880. const scopeStack = [rootScope];
  17881. let currentScope = rootScope;
  17882. const excludedIds = /* @__PURE__ */ new WeakSet();
  17883. const parentStack = [];
  17884. const propsLocalToPublicMap = /* @__PURE__ */ Object.create(null);
  17885. for (const key in ctx.propsDestructuredBindings) {
  17886. const { local } = ctx.propsDestructuredBindings[key];
  17887. rootScope[local] = true;
  17888. propsLocalToPublicMap[local] = key;
  17889. }
  17890. function pushScope() {
  17891. scopeStack.push(currentScope = Object.create(currentScope));
  17892. }
  17893. function popScope() {
  17894. scopeStack.pop();
  17895. currentScope = scopeStack[scopeStack.length - 1] || null;
  17896. }
  17897. function registerLocalBinding(id) {
  17898. excludedIds.add(id);
  17899. if (currentScope) {
  17900. currentScope[id.name] = false;
  17901. } else {
  17902. ctx.error(
  17903. "registerBinding called without active scope, something is wrong.",
  17904. id
  17905. );
  17906. }
  17907. }
  17908. function walkScope(node, isRoot = false) {
  17909. for (const stmt of node.body) {
  17910. if (stmt.type === "VariableDeclaration") {
  17911. walkVariableDeclaration(stmt, isRoot);
  17912. } else if (stmt.type === "FunctionDeclaration" || stmt.type === "ClassDeclaration") {
  17913. if (stmt.declare || !stmt.id)
  17914. continue;
  17915. registerLocalBinding(stmt.id);
  17916. } else if ((stmt.type === "ForOfStatement" || stmt.type === "ForInStatement") && stmt.left.type === "VariableDeclaration") {
  17917. walkVariableDeclaration(stmt.left);
  17918. } else if (stmt.type === "ExportNamedDeclaration" && stmt.declaration && stmt.declaration.type === "VariableDeclaration") {
  17919. walkVariableDeclaration(stmt.declaration, isRoot);
  17920. } else if (stmt.type === "LabeledStatement" && stmt.body.type === "VariableDeclaration") {
  17921. walkVariableDeclaration(stmt.body, isRoot);
  17922. }
  17923. }
  17924. }
  17925. function walkVariableDeclaration(stmt, isRoot = false) {
  17926. if (stmt.declare) {
  17927. return;
  17928. }
  17929. for (const decl of stmt.declarations) {
  17930. const isDefineProps = isRoot && decl.init && isCallOf(CompilerDOM.unwrapTSNode(decl.init), "defineProps");
  17931. for (const id of CompilerDOM.extractIdentifiers(decl.id)) {
  17932. if (isDefineProps) {
  17933. excludedIds.add(id);
  17934. } else {
  17935. registerLocalBinding(id);
  17936. }
  17937. }
  17938. }
  17939. }
  17940. function rewriteId(id, parent, parentStack2) {
  17941. if (parent.type === "AssignmentExpression" && id === parent.left || parent.type === "UpdateExpression") {
  17942. ctx.error(`Cannot assign to destructured props as they are readonly.`, id);
  17943. }
  17944. if (CompilerDOM.isStaticProperty(parent) && parent.shorthand) {
  17945. if (!parent.inPattern || CompilerDOM.isInDestructureAssignment(parent, parentStack2)) {
  17946. ctx.s.appendLeft(
  17947. id.end + ctx.startOffset,
  17948. `: ${shared.genPropsAccessExp(propsLocalToPublicMap[id.name])}`
  17949. );
  17950. }
  17951. } else {
  17952. ctx.s.overwrite(
  17953. id.start + ctx.startOffset,
  17954. id.end + ctx.startOffset,
  17955. shared.genPropsAccessExp(propsLocalToPublicMap[id.name])
  17956. );
  17957. }
  17958. }
  17959. function checkUsage(node, method, alias = method) {
  17960. if (isCallOf(node, alias)) {
  17961. const arg = CompilerDOM.unwrapTSNode(node.arguments[0]);
  17962. if (arg.type === "Identifier" && currentScope[arg.name]) {
  17963. ctx.error(
  17964. `"${arg.name}" is a destructured prop and should not be passed directly to ${method}(). Pass a getter () => ${arg.name} instead.`,
  17965. arg
  17966. );
  17967. }
  17968. }
  17969. }
  17970. const ast = ctx.scriptSetupAst;
  17971. walkScope(ast, true);
  17972. estreeWalker.walk(ast, {
  17973. enter(node, parent) {
  17974. parent && parentStack.push(parent);
  17975. if (parent && parent.type.startsWith("TS") && parent.type !== "TSAsExpression" && parent.type !== "TSNonNullExpression" && parent.type !== "TSTypeAssertion") {
  17976. return this.skip();
  17977. }
  17978. checkUsage(node, "watch", vueImportAliases.watch);
  17979. checkUsage(node, "toRef", vueImportAliases.toRef);
  17980. if (CompilerDOM.isFunctionType(node)) {
  17981. pushScope();
  17982. CompilerDOM.walkFunctionParams(node, registerLocalBinding);
  17983. if (node.body.type === "BlockStatement") {
  17984. walkScope(node.body);
  17985. }
  17986. return;
  17987. }
  17988. if (node.type === "CatchClause") {
  17989. pushScope();
  17990. if (node.param && node.param.type === "Identifier") {
  17991. registerLocalBinding(node.param);
  17992. }
  17993. walkScope(node.body);
  17994. return;
  17995. }
  17996. if (node.type === "BlockStatement" && !CompilerDOM.isFunctionType(parent)) {
  17997. pushScope();
  17998. walkScope(node);
  17999. return;
  18000. }
  18001. if (node.type === "Identifier") {
  18002. if (CompilerDOM.isReferencedIdentifier(node, parent, parentStack) && !excludedIds.has(node)) {
  18003. if (currentScope[node.name]) {
  18004. rewriteId(node, parent, parentStack);
  18005. }
  18006. }
  18007. }
  18008. },
  18009. leave(node, parent) {
  18010. parent && parentStack.pop();
  18011. if (node.type === "BlockStatement" && !CompilerDOM.isFunctionType(parent) || CompilerDOM.isFunctionType(node)) {
  18012. popScope();
  18013. }
  18014. }
  18015. });
  18016. }
  18017. const DEFINE_EMITS = "defineEmits";
  18018. function processDefineEmits(ctx, node, declId) {
  18019. if (!isCallOf(node, DEFINE_EMITS)) {
  18020. return false;
  18021. }
  18022. if (ctx.hasDefineEmitCall) {
  18023. ctx.error(`duplicate ${DEFINE_EMITS}() call`, node);
  18024. }
  18025. ctx.hasDefineEmitCall = true;
  18026. ctx.emitsRuntimeDecl = node.arguments[0];
  18027. if (node.typeParameters) {
  18028. if (ctx.emitsRuntimeDecl) {
  18029. ctx.error(
  18030. `${DEFINE_EMITS}() cannot accept both type and non-type arguments at the same time. Use one or the other.`,
  18031. node
  18032. );
  18033. }
  18034. ctx.emitsTypeDecl = node.typeParameters.params[0];
  18035. }
  18036. ctx.emitDecl = declId;
  18037. return true;
  18038. }
  18039. function genRuntimeEmits(ctx) {
  18040. let emitsDecl = "";
  18041. if (ctx.emitsRuntimeDecl) {
  18042. emitsDecl = ctx.getString(ctx.emitsRuntimeDecl).trim();
  18043. } else if (ctx.emitsTypeDecl) {
  18044. const typeDeclaredEmits = extractRuntimeEmits(ctx);
  18045. emitsDecl = typeDeclaredEmits.size ? `[${Array.from(typeDeclaredEmits).map((k) => JSON.stringify(k)).join(", ")}]` : ``;
  18046. }
  18047. if (ctx.hasDefineModelCall) {
  18048. let modelEmitsDecl = `[${Object.keys(ctx.modelDecls).map((n) => JSON.stringify(`update:${n}`)).join(", ")}]`;
  18049. emitsDecl = emitsDecl ? `/*#__PURE__*/${ctx.helper(
  18050. "mergeModels"
  18051. )}(${emitsDecl}, ${modelEmitsDecl})` : modelEmitsDecl;
  18052. }
  18053. return emitsDecl;
  18054. }
  18055. function extractRuntimeEmits(ctx) {
  18056. const emits = /* @__PURE__ */ new Set();
  18057. const node = ctx.emitsTypeDecl;
  18058. if (node.type === "TSFunctionType") {
  18059. extractEventNames(ctx, node.parameters[0], emits);
  18060. return emits;
  18061. }
  18062. const { props, calls } = resolveTypeElements(ctx, node);
  18063. let hasProperty = false;
  18064. for (const key in props) {
  18065. emits.add(key);
  18066. hasProperty = true;
  18067. }
  18068. if (calls) {
  18069. if (hasProperty) {
  18070. ctx.error(
  18071. `defineEmits() type cannot mixed call signature and property syntax.`,
  18072. node
  18073. );
  18074. }
  18075. for (const call of calls) {
  18076. extractEventNames(ctx, call.parameters[0], emits);
  18077. }
  18078. }
  18079. return emits;
  18080. }
  18081. function extractEventNames(ctx, eventName, emits) {
  18082. if (eventName.type === "Identifier" && eventName.typeAnnotation && eventName.typeAnnotation.type === "TSTypeAnnotation") {
  18083. const types = resolveUnionType(ctx, eventName.typeAnnotation.typeAnnotation);
  18084. for (const type of types) {
  18085. if (type.type === "TSLiteralType") {
  18086. if (type.literal.type !== "UnaryExpression" && type.literal.type !== "TemplateLiteral") {
  18087. emits.add(String(type.literal.value));
  18088. }
  18089. }
  18090. }
  18091. }
  18092. }
  18093. const DEFINE_EXPOSE = "defineExpose";
  18094. function processDefineExpose(ctx, node) {
  18095. if (isCallOf(node, DEFINE_EXPOSE)) {
  18096. if (ctx.hasDefineExposeCall) {
  18097. ctx.error(`duplicate ${DEFINE_EXPOSE}() call`, node);
  18098. }
  18099. ctx.hasDefineExposeCall = true;
  18100. return true;
  18101. }
  18102. return false;
  18103. }
  18104. const DEFINE_SLOTS = "defineSlots";
  18105. function processDefineSlots(ctx, node, declId) {
  18106. if (!isCallOf(node, DEFINE_SLOTS)) {
  18107. return false;
  18108. }
  18109. if (ctx.hasDefineSlotsCall) {
  18110. ctx.error(`duplicate ${DEFINE_SLOTS}() call`, node);
  18111. }
  18112. ctx.hasDefineSlotsCall = true;
  18113. if (node.arguments.length > 0) {
  18114. ctx.error(`${DEFINE_SLOTS}() cannot accept arguments`, node);
  18115. }
  18116. if (declId) {
  18117. ctx.s.overwrite(
  18118. ctx.startOffset + node.start,
  18119. ctx.startOffset + node.end,
  18120. `${ctx.helper("useSlots")}()`
  18121. );
  18122. }
  18123. return true;
  18124. }
  18125. const DEFINE_OPTIONS = "defineOptions";
  18126. function processDefineOptions(ctx, node) {
  18127. if (!isCallOf(node, DEFINE_OPTIONS)) {
  18128. return false;
  18129. }
  18130. if (ctx.hasDefineOptionsCall) {
  18131. ctx.error(`duplicate ${DEFINE_OPTIONS}() call`, node);
  18132. }
  18133. if (node.typeParameters) {
  18134. ctx.error(`${DEFINE_OPTIONS}() cannot accept type arguments`, node);
  18135. }
  18136. if (!node.arguments[0])
  18137. return true;
  18138. ctx.hasDefineOptionsCall = true;
  18139. ctx.optionsRuntimeDecl = CompilerDOM.unwrapTSNode(node.arguments[0]);
  18140. let propsOption = void 0;
  18141. let emitsOption = void 0;
  18142. let exposeOption = void 0;
  18143. let slotsOption = void 0;
  18144. if (ctx.optionsRuntimeDecl.type === "ObjectExpression") {
  18145. for (const prop of ctx.optionsRuntimeDecl.properties) {
  18146. if ((prop.type === "ObjectProperty" || prop.type === "ObjectMethod") && prop.key.type === "Identifier") {
  18147. if (prop.key.name === "props")
  18148. propsOption = prop;
  18149. if (prop.key.name === "emits")
  18150. emitsOption = prop;
  18151. if (prop.key.name === "expose")
  18152. exposeOption = prop;
  18153. if (prop.key.name === "slots")
  18154. slotsOption = prop;
  18155. }
  18156. }
  18157. }
  18158. if (propsOption) {
  18159. ctx.error(
  18160. `${DEFINE_OPTIONS}() cannot be used to declare props. Use ${DEFINE_PROPS}() instead.`,
  18161. propsOption
  18162. );
  18163. }
  18164. if (emitsOption) {
  18165. ctx.error(
  18166. `${DEFINE_OPTIONS}() cannot be used to declare emits. Use ${DEFINE_EMITS}() instead.`,
  18167. emitsOption
  18168. );
  18169. }
  18170. if (exposeOption) {
  18171. ctx.error(
  18172. `${DEFINE_OPTIONS}() cannot be used to declare expose. Use ${DEFINE_EXPOSE}() instead.`,
  18173. exposeOption
  18174. );
  18175. }
  18176. if (slotsOption) {
  18177. ctx.error(
  18178. `${DEFINE_OPTIONS}() cannot be used to declare slots. Use ${DEFINE_SLOTS}() instead.`,
  18179. slotsOption
  18180. );
  18181. }
  18182. return true;
  18183. }
  18184. function processAwait(ctx, node, needSemi, isStatement) {
  18185. const argumentStart = node.argument.extra && node.argument.extra.parenthesized ? node.argument.extra.parenStart : node.argument.start;
  18186. const startOffset = ctx.startOffset;
  18187. const argumentStr = ctx.descriptor.source.slice(
  18188. argumentStart + startOffset,
  18189. node.argument.end + startOffset
  18190. );
  18191. const containsNestedAwait = /\bawait\b/.test(argumentStr);
  18192. ctx.s.overwrite(
  18193. node.start + startOffset,
  18194. argumentStart + startOffset,
  18195. `${needSemi ? `;` : ``}(
  18196. ([__temp,__restore] = ${ctx.helper(
  18197. `withAsyncContext`
  18198. )}(${containsNestedAwait ? `async ` : ``}() => `
  18199. );
  18200. ctx.s.appendLeft(
  18201. node.end + startOffset,
  18202. `)),
  18203. ${isStatement ? `` : `__temp = `}await __temp,
  18204. __restore()${isStatement ? `` : `,
  18205. __temp`}
  18206. )`
  18207. );
  18208. }
  18209. function compileScript(sfc, options) {
  18210. var _a;
  18211. if (!options.id) {
  18212. warnOnce(
  18213. `compileScript now requires passing the \`id\` option.
  18214. Upgrade your vite or vue-loader version for compatibility with the latest experimental proposals.`
  18215. );
  18216. }
  18217. const ctx = new ScriptCompileContext(sfc, options);
  18218. const { script, scriptSetup, source, filename } = sfc;
  18219. const hoistStatic = options.hoistStatic !== false && !script;
  18220. const scopeId = options.id ? options.id.replace(/^data-v-/, "") : "";
  18221. const scriptLang = script && script.lang;
  18222. const scriptSetupLang = scriptSetup && scriptSetup.lang;
  18223. if (!scriptSetup) {
  18224. if (!script) {
  18225. throw new Error(`[@vue/compiler-sfc] SFC contains no <script> tags.`);
  18226. }
  18227. return processNormalScript(ctx, scopeId);
  18228. }
  18229. if (script && scriptLang !== scriptSetupLang) {
  18230. throw new Error(
  18231. `[@vue/compiler-sfc] <script> and <script setup> must have the same language type.`
  18232. );
  18233. }
  18234. if (scriptSetupLang && !ctx.isJS && !ctx.isTS) {
  18235. return scriptSetup;
  18236. }
  18237. const scriptBindings = /* @__PURE__ */ Object.create(null);
  18238. const setupBindings = /* @__PURE__ */ Object.create(null);
  18239. let defaultExport;
  18240. let hasAwait = false;
  18241. let hasInlinedSsrRenderFn = false;
  18242. const startOffset = ctx.startOffset;
  18243. const endOffset = ctx.endOffset;
  18244. const scriptStartOffset = script && script.loc.start.offset;
  18245. const scriptEndOffset = script && script.loc.end.offset;
  18246. function hoistNode(node) {
  18247. const start = node.start + startOffset;
  18248. let end = node.end + startOffset;
  18249. if (node.trailingComments && node.trailingComments.length > 0) {
  18250. const lastCommentNode = node.trailingComments[node.trailingComments.length - 1];
  18251. end = lastCommentNode.end + startOffset;
  18252. }
  18253. while (end <= source.length) {
  18254. if (!/\s/.test(source.charAt(end))) {
  18255. break;
  18256. }
  18257. end++;
  18258. }
  18259. ctx.s.move(start, end, 0);
  18260. }
  18261. function registerUserImport(source2, local, imported, isType, isFromSetup, needTemplateUsageCheck) {
  18262. let isUsedInTemplate = needTemplateUsageCheck;
  18263. if (needTemplateUsageCheck && ctx.isTS && sfc.template && !sfc.template.src && !sfc.template.lang) {
  18264. isUsedInTemplate = isImportUsed(local, sfc);
  18265. }
  18266. ctx.userImports[local] = {
  18267. isType,
  18268. imported,
  18269. local,
  18270. source: source2,
  18271. isFromSetup,
  18272. isUsedInTemplate
  18273. };
  18274. }
  18275. function checkInvalidScopeReference(node, method) {
  18276. if (!node)
  18277. return;
  18278. CompilerDOM.walkIdentifiers(node, (id) => {
  18279. const binding = setupBindings[id.name];
  18280. if (binding && binding !== "literal-const") {
  18281. ctx.error(
  18282. `\`${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.`,
  18283. id
  18284. );
  18285. }
  18286. });
  18287. }
  18288. const scriptAst = ctx.scriptAst;
  18289. const scriptSetupAst = ctx.scriptSetupAst;
  18290. if (scriptAst) {
  18291. for (const node of scriptAst.body) {
  18292. if (node.type === "ImportDeclaration") {
  18293. for (const specifier of node.specifiers) {
  18294. const imported = getImportedName(specifier);
  18295. registerUserImport(
  18296. node.source.value,
  18297. specifier.local.name,
  18298. imported,
  18299. node.importKind === "type" || specifier.type === "ImportSpecifier" && specifier.importKind === "type",
  18300. false,
  18301. !options.inlineTemplate
  18302. );
  18303. }
  18304. }
  18305. }
  18306. }
  18307. for (const node of scriptSetupAst.body) {
  18308. if (node.type === "ImportDeclaration") {
  18309. hoistNode(node);
  18310. let removed = 0;
  18311. const removeSpecifier = (i) => {
  18312. const removeLeft = i > removed;
  18313. removed++;
  18314. const current = node.specifiers[i];
  18315. const next = node.specifiers[i + 1];
  18316. ctx.s.remove(
  18317. removeLeft ? node.specifiers[i - 1].end + startOffset : current.start + startOffset,
  18318. next && !removeLeft ? next.start + startOffset : current.end + startOffset
  18319. );
  18320. };
  18321. for (let i = 0; i < node.specifiers.length; i++) {
  18322. const specifier = node.specifiers[i];
  18323. const local = specifier.local.name;
  18324. const imported = getImportedName(specifier);
  18325. const source2 = node.source.value;
  18326. const existing = ctx.userImports[local];
  18327. if (source2 === "vue" && (imported === DEFINE_PROPS || imported === DEFINE_EMITS || imported === DEFINE_EXPOSE)) {
  18328. warnOnce(
  18329. `\`${imported}\` is a compiler macro and no longer needs to be imported.`
  18330. );
  18331. removeSpecifier(i);
  18332. } else if (existing) {
  18333. if (existing.source === source2 && existing.imported === imported) {
  18334. removeSpecifier(i);
  18335. } else {
  18336. ctx.error(
  18337. `different imports aliased to same local name.`,
  18338. specifier
  18339. );
  18340. }
  18341. } else {
  18342. registerUserImport(
  18343. source2,
  18344. local,
  18345. imported,
  18346. node.importKind === "type" || specifier.type === "ImportSpecifier" && specifier.importKind === "type",
  18347. true,
  18348. !options.inlineTemplate
  18349. );
  18350. }
  18351. }
  18352. if (node.specifiers.length && removed === node.specifiers.length) {
  18353. ctx.s.remove(node.start + startOffset, node.end + startOffset);
  18354. }
  18355. }
  18356. }
  18357. const vueImportAliases = {};
  18358. for (const key in ctx.userImports) {
  18359. const { source: source2, imported, local } = ctx.userImports[key];
  18360. if (source2 === "vue")
  18361. vueImportAliases[imported] = local;
  18362. }
  18363. if (script && scriptAst) {
  18364. for (const node of scriptAst.body) {
  18365. if (node.type === "ExportDefaultDeclaration") {
  18366. defaultExport = node;
  18367. let optionProperties;
  18368. if (defaultExport.declaration.type === "ObjectExpression") {
  18369. optionProperties = defaultExport.declaration.properties;
  18370. } else if (defaultExport.declaration.type === "CallExpression" && defaultExport.declaration.arguments[0] && defaultExport.declaration.arguments[0].type === "ObjectExpression") {
  18371. optionProperties = defaultExport.declaration.arguments[0].properties;
  18372. }
  18373. if (optionProperties) {
  18374. for (const p of optionProperties) {
  18375. if (p.type === "ObjectProperty" && p.key.type === "Identifier" && p.key.name === "name") {
  18376. ctx.hasDefaultExportName = true;
  18377. }
  18378. if ((p.type === "ObjectMethod" || p.type === "ObjectProperty") && p.key.type === "Identifier" && p.key.name === "render") {
  18379. ctx.hasDefaultExportRender = true;
  18380. }
  18381. }
  18382. }
  18383. const start = node.start + scriptStartOffset;
  18384. const end = node.declaration.start + scriptStartOffset;
  18385. ctx.s.overwrite(start, end, `const ${normalScriptDefaultVar} = `);
  18386. } else if (node.type === "ExportNamedDeclaration") {
  18387. const defaultSpecifier = node.specifiers.find(
  18388. (s) => s.exported.type === "Identifier" && s.exported.name === "default"
  18389. );
  18390. if (defaultSpecifier) {
  18391. defaultExport = node;
  18392. if (node.specifiers.length > 1) {
  18393. ctx.s.remove(
  18394. defaultSpecifier.start + scriptStartOffset,
  18395. defaultSpecifier.end + scriptStartOffset
  18396. );
  18397. } else {
  18398. ctx.s.remove(
  18399. node.start + scriptStartOffset,
  18400. node.end + scriptStartOffset
  18401. );
  18402. }
  18403. if (node.source) {
  18404. ctx.s.prepend(
  18405. `import { ${defaultSpecifier.local.name} as ${normalScriptDefaultVar} } from '${node.source.value}'
  18406. `
  18407. );
  18408. } else {
  18409. ctx.s.appendLeft(
  18410. scriptEndOffset,
  18411. `
  18412. const ${normalScriptDefaultVar} = ${defaultSpecifier.local.name}
  18413. `
  18414. );
  18415. }
  18416. }
  18417. if (node.declaration) {
  18418. walkDeclaration(
  18419. "script",
  18420. node.declaration,
  18421. scriptBindings,
  18422. vueImportAliases,
  18423. hoistStatic
  18424. );
  18425. }
  18426. } else if ((node.type === "VariableDeclaration" || node.type === "FunctionDeclaration" || node.type === "ClassDeclaration" || node.type === "TSEnumDeclaration") && !node.declare) {
  18427. walkDeclaration(
  18428. "script",
  18429. node,
  18430. scriptBindings,
  18431. vueImportAliases,
  18432. hoistStatic
  18433. );
  18434. }
  18435. }
  18436. if (scriptStartOffset > startOffset) {
  18437. if (!/\n$/.test(script.content.trim())) {
  18438. ctx.s.appendLeft(scriptEndOffset, `
  18439. `);
  18440. }
  18441. ctx.s.move(scriptStartOffset, scriptEndOffset, 0);
  18442. }
  18443. }
  18444. for (const node of scriptSetupAst.body) {
  18445. if (node.type === "ExpressionStatement") {
  18446. const expr = CompilerDOM.unwrapTSNode(node.expression);
  18447. if (processDefineProps(ctx, expr) || processDefineEmits(ctx, expr) || processDefineOptions(ctx, expr) || processDefineSlots(ctx, expr)) {
  18448. ctx.s.remove(node.start + startOffset, node.end + startOffset);
  18449. } else if (processDefineExpose(ctx, expr)) {
  18450. const callee = expr.callee;
  18451. ctx.s.overwrite(
  18452. callee.start + startOffset,
  18453. callee.end + startOffset,
  18454. "__expose"
  18455. );
  18456. } else {
  18457. processDefineModel(ctx, expr);
  18458. }
  18459. }
  18460. if (node.type === "VariableDeclaration" && !node.declare) {
  18461. const total = node.declarations.length;
  18462. let left = total;
  18463. let lastNonRemoved;
  18464. for (let i = 0; i < total; i++) {
  18465. const decl = node.declarations[i];
  18466. const init = decl.init && CompilerDOM.unwrapTSNode(decl.init);
  18467. if (init) {
  18468. if (processDefineOptions(ctx, init)) {
  18469. ctx.error(
  18470. `${DEFINE_OPTIONS}() has no returning value, it cannot be assigned.`,
  18471. node
  18472. );
  18473. }
  18474. const isDefineProps = processDefineProps(ctx, init, decl.id);
  18475. const isDefineEmits = !isDefineProps && processDefineEmits(ctx, init, decl.id);
  18476. !isDefineEmits && (processDefineSlots(ctx, init, decl.id) || processDefineModel(ctx, init, decl.id));
  18477. if (isDefineProps && !ctx.propsDestructureRestId && ctx.propsDestructureDecl) {
  18478. if (left === 1) {
  18479. ctx.s.remove(node.start + startOffset, node.end + startOffset);
  18480. } else {
  18481. let start = decl.start + startOffset;
  18482. let end = decl.end + startOffset;
  18483. if (i === total - 1) {
  18484. start = node.declarations[lastNonRemoved].end + startOffset;
  18485. } else {
  18486. end = node.declarations[i + 1].start + startOffset;
  18487. }
  18488. ctx.s.remove(start, end);
  18489. left--;
  18490. }
  18491. } else if (isDefineEmits) {
  18492. ctx.s.overwrite(
  18493. startOffset + init.start,
  18494. startOffset + init.end,
  18495. "__emit"
  18496. );
  18497. } else {
  18498. lastNonRemoved = i;
  18499. }
  18500. }
  18501. }
  18502. }
  18503. let isAllLiteral = false;
  18504. if ((node.type === "VariableDeclaration" || node.type === "FunctionDeclaration" || node.type === "ClassDeclaration" || node.type === "TSEnumDeclaration") && !node.declare) {
  18505. isAllLiteral = walkDeclaration(
  18506. "scriptSetup",
  18507. node,
  18508. setupBindings,
  18509. vueImportAliases,
  18510. hoistStatic
  18511. );
  18512. }
  18513. if (hoistStatic && isAllLiteral) {
  18514. hoistNode(node);
  18515. }
  18516. if (node.type === "VariableDeclaration" && !node.declare || node.type.endsWith("Statement")) {
  18517. const scope = [scriptSetupAst.body];
  18518. estreeWalker.walk(node, {
  18519. enter(child, parent) {
  18520. if (CompilerDOM.isFunctionType(child)) {
  18521. this.skip();
  18522. }
  18523. if (child.type === "BlockStatement") {
  18524. scope.push(child.body);
  18525. }
  18526. if (child.type === "AwaitExpression") {
  18527. hasAwait = true;
  18528. const currentScope = scope[scope.length - 1];
  18529. const needsSemi = currentScope.some((n, i) => {
  18530. return (scope.length === 1 || i > 0) && n.type === "ExpressionStatement" && n.start === child.start;
  18531. });
  18532. processAwait(
  18533. ctx,
  18534. child,
  18535. needsSemi,
  18536. parent.type === "ExpressionStatement"
  18537. );
  18538. }
  18539. },
  18540. exit(node2) {
  18541. if (node2.type === "BlockStatement")
  18542. scope.pop();
  18543. }
  18544. });
  18545. }
  18546. if (node.type === "ExportNamedDeclaration" && node.exportKind !== "type" || node.type === "ExportAllDeclaration" || node.type === "ExportDefaultDeclaration") {
  18547. ctx.error(
  18548. `<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.`,
  18549. node
  18550. );
  18551. }
  18552. if (ctx.isTS) {
  18553. if (node.type.startsWith("TS") || node.type === "ExportNamedDeclaration" && node.exportKind === "type" || node.type === "VariableDeclaration" && node.declare) {
  18554. if (node.type !== "TSEnumDeclaration") {
  18555. hoistNode(node);
  18556. }
  18557. }
  18558. }
  18559. }
  18560. if (ctx.propsDestructureDecl) {
  18561. transformDestructuredProps(ctx, vueImportAliases);
  18562. }
  18563. checkInvalidScopeReference(ctx.propsRuntimeDecl, DEFINE_PROPS);
  18564. checkInvalidScopeReference(ctx.propsRuntimeDefaults, DEFINE_PROPS);
  18565. checkInvalidScopeReference(ctx.propsDestructureDecl, DEFINE_PROPS);
  18566. checkInvalidScopeReference(ctx.emitsRuntimeDecl, DEFINE_EMITS);
  18567. checkInvalidScopeReference(ctx.optionsRuntimeDecl, DEFINE_OPTIONS);
  18568. for (const { runtimeOptionNodes } of Object.values(ctx.modelDecls)) {
  18569. for (const node of runtimeOptionNodes) {
  18570. checkInvalidScopeReference(node, DEFINE_MODEL);
  18571. }
  18572. }
  18573. if (script) {
  18574. if (startOffset < scriptStartOffset) {
  18575. ctx.s.remove(0, startOffset);
  18576. ctx.s.remove(endOffset, scriptStartOffset);
  18577. ctx.s.remove(scriptEndOffset, source.length);
  18578. } else {
  18579. ctx.s.remove(0, scriptStartOffset);
  18580. ctx.s.remove(scriptEndOffset, startOffset);
  18581. ctx.s.remove(endOffset, source.length);
  18582. }
  18583. } else {
  18584. ctx.s.remove(0, startOffset);
  18585. ctx.s.remove(endOffset, source.length);
  18586. }
  18587. if (scriptAst) {
  18588. Object.assign(ctx.bindingMetadata, analyzeScriptBindings(scriptAst.body));
  18589. }
  18590. for (const [key, { isType, imported, source: source2 }] of Object.entries(
  18591. ctx.userImports
  18592. )) {
  18593. if (isType)
  18594. continue;
  18595. ctx.bindingMetadata[key] = imported === "*" || imported === "default" && source2.endsWith(".vue") || source2 === "vue" ? "setup-const" : "setup-maybe-ref";
  18596. }
  18597. for (const key in scriptBindings) {
  18598. ctx.bindingMetadata[key] = scriptBindings[key];
  18599. }
  18600. for (const key in setupBindings) {
  18601. ctx.bindingMetadata[key] = setupBindings[key];
  18602. }
  18603. if (sfc.cssVars.length && // no need to do this when targeting SSR
  18604. !((_a = options.templateOptions) == null ? void 0 : _a.ssr)) {
  18605. ctx.helperImports.add(CSS_VARS_HELPER);
  18606. ctx.helperImports.add("unref");
  18607. ctx.s.prependLeft(
  18608. startOffset,
  18609. `
  18610. ${genCssVarsCode(
  18611. sfc.cssVars,
  18612. ctx.bindingMetadata,
  18613. scopeId,
  18614. !!options.isProd
  18615. )}
  18616. `
  18617. );
  18618. }
  18619. let args = `__props`;
  18620. if (ctx.propsTypeDecl) {
  18621. args += `: any`;
  18622. }
  18623. if (ctx.propsDecl) {
  18624. if (ctx.propsDestructureRestId) {
  18625. ctx.s.overwrite(
  18626. startOffset + ctx.propsCall.start,
  18627. startOffset + ctx.propsCall.end,
  18628. `${ctx.helper(`createPropsRestProxy`)}(__props, ${JSON.stringify(
  18629. Object.keys(ctx.propsDestructuredBindings)
  18630. )})`
  18631. );
  18632. ctx.s.overwrite(
  18633. startOffset + ctx.propsDestructureDecl.start,
  18634. startOffset + ctx.propsDestructureDecl.end,
  18635. ctx.propsDestructureRestId
  18636. );
  18637. } else if (!ctx.propsDestructureDecl) {
  18638. ctx.s.overwrite(
  18639. startOffset + ctx.propsCall.start,
  18640. startOffset + ctx.propsCall.end,
  18641. "__props"
  18642. );
  18643. }
  18644. }
  18645. if (hasAwait) {
  18646. const any = ctx.isTS ? `: any` : ``;
  18647. ctx.s.prependLeft(startOffset, `
  18648. let __temp${any}, __restore${any}
  18649. `);
  18650. }
  18651. const destructureElements = ctx.hasDefineExposeCall || !options.inlineTemplate ? [`expose: __expose`] : [];
  18652. if (ctx.emitDecl) {
  18653. destructureElements.push(`emit: __emit`);
  18654. }
  18655. if (destructureElements.length) {
  18656. args += `, { ${destructureElements.join(", ")} }`;
  18657. }
  18658. let returned;
  18659. if (!options.inlineTemplate || !sfc.template && ctx.hasDefaultExportRender) {
  18660. const allBindings = {
  18661. ...scriptBindings,
  18662. ...setupBindings
  18663. };
  18664. for (const key in ctx.userImports) {
  18665. if (!ctx.userImports[key].isType && ctx.userImports[key].isUsedInTemplate) {
  18666. allBindings[key] = true;
  18667. }
  18668. }
  18669. returned = `{ `;
  18670. for (const key in allBindings) {
  18671. if (allBindings[key] === true && ctx.userImports[key].source !== "vue" && !ctx.userImports[key].source.endsWith(".vue")) {
  18672. returned += `get ${key}() { return ${key} }, `;
  18673. } else if (ctx.bindingMetadata[key] === "setup-let") {
  18674. const setArg = key === "v" ? `_v` : `v`;
  18675. returned += `get ${key}() { return ${key} }, set ${key}(${setArg}) { ${key} = ${setArg} }, `;
  18676. } else {
  18677. returned += `${key}, `;
  18678. }
  18679. }
  18680. returned = returned.replace(/, $/, "") + ` }`;
  18681. } else {
  18682. if (sfc.template && !sfc.template.src) {
  18683. if (options.templateOptions && options.templateOptions.ssr) {
  18684. hasInlinedSsrRenderFn = true;
  18685. }
  18686. const { code, ast, preamble, tips, errors } = compileTemplate({
  18687. filename,
  18688. ast: sfc.template.ast,
  18689. source: sfc.template.content,
  18690. inMap: sfc.template.map,
  18691. ...options.templateOptions,
  18692. id: scopeId,
  18693. scoped: sfc.styles.some((s) => s.scoped),
  18694. isProd: options.isProd,
  18695. ssrCssVars: sfc.cssVars,
  18696. compilerOptions: {
  18697. ...options.templateOptions && options.templateOptions.compilerOptions,
  18698. inline: true,
  18699. isTS: ctx.isTS,
  18700. bindingMetadata: ctx.bindingMetadata
  18701. }
  18702. });
  18703. if (tips.length) {
  18704. tips.forEach(warnOnce);
  18705. }
  18706. const err = errors[0];
  18707. if (typeof err === "string") {
  18708. throw new Error(err);
  18709. } else if (err) {
  18710. if (err.loc) {
  18711. err.message += `
  18712. ` + sfc.filename + "\n" + shared.generateCodeFrame(
  18713. source,
  18714. err.loc.start.offset,
  18715. err.loc.end.offset
  18716. ) + `
  18717. `;
  18718. }
  18719. throw err;
  18720. }
  18721. if (preamble) {
  18722. ctx.s.prepend(preamble);
  18723. }
  18724. if (ast && ast.helpers.has(CompilerDOM.UNREF)) {
  18725. ctx.helperImports.delete("unref");
  18726. }
  18727. returned = code;
  18728. } else {
  18729. returned = `() => {}`;
  18730. }
  18731. }
  18732. if (!options.inlineTemplate && true) {
  18733. ctx.s.appendRight(
  18734. endOffset,
  18735. `
  18736. const __returned__ = ${returned}
  18737. Object.defineProperty(__returned__, '__isScriptSetup', { enumerable: false, value: true })
  18738. return __returned__
  18739. }
  18740. `
  18741. );
  18742. } else {
  18743. ctx.s.appendRight(endOffset, `
  18744. return ${returned}
  18745. }
  18746. `);
  18747. }
  18748. const genDefaultAs = options.genDefaultAs ? `const ${options.genDefaultAs} =` : `export default`;
  18749. let runtimeOptions = ``;
  18750. if (!ctx.hasDefaultExportName && filename && filename !== DEFAULT_FILENAME) {
  18751. const match = filename.match(/([^/\\]+)\.\w+$/);
  18752. if (match) {
  18753. runtimeOptions += `
  18754. __name: '${match[1]}',`;
  18755. }
  18756. }
  18757. if (hasInlinedSsrRenderFn) {
  18758. runtimeOptions += `
  18759. __ssrInlineRender: true,`;
  18760. }
  18761. const propsDecl = genRuntimeProps(ctx);
  18762. if (propsDecl)
  18763. runtimeOptions += `
  18764. props: ${propsDecl},`;
  18765. const emitsDecl = genRuntimeEmits(ctx);
  18766. if (emitsDecl)
  18767. runtimeOptions += `
  18768. emits: ${emitsDecl},`;
  18769. let definedOptions = "";
  18770. if (ctx.optionsRuntimeDecl) {
  18771. definedOptions = scriptSetup.content.slice(ctx.optionsRuntimeDecl.start, ctx.optionsRuntimeDecl.end).trim();
  18772. }
  18773. const exposeCall = ctx.hasDefineExposeCall || options.inlineTemplate ? `` : ` __expose();
  18774. `;
  18775. if (ctx.isTS) {
  18776. const def = (defaultExport ? `
  18777. ...${normalScriptDefaultVar},` : ``) + (definedOptions ? `
  18778. ...${definedOptions},` : "");
  18779. ctx.s.prependLeft(
  18780. startOffset,
  18781. `
  18782. ${genDefaultAs} /*#__PURE__*/${ctx.helper(
  18783. `defineComponent`
  18784. )}({${def}${runtimeOptions}
  18785. ${hasAwait ? `async ` : ``}setup(${args}) {
  18786. ${exposeCall}`
  18787. );
  18788. ctx.s.appendRight(endOffset, `})`);
  18789. } else {
  18790. if (defaultExport || definedOptions) {
  18791. ctx.s.prependLeft(
  18792. startOffset,
  18793. `
  18794. ${genDefaultAs} /*#__PURE__*/Object.assign(${defaultExport ? `${normalScriptDefaultVar}, ` : ""}${definedOptions ? `${definedOptions}, ` : ""}{${runtimeOptions}
  18795. ${hasAwait ? `async ` : ``}setup(${args}) {
  18796. ${exposeCall}`
  18797. );
  18798. ctx.s.appendRight(endOffset, `})`);
  18799. } else {
  18800. ctx.s.prependLeft(
  18801. startOffset,
  18802. `
  18803. ${genDefaultAs} {${runtimeOptions}
  18804. ${hasAwait ? `async ` : ``}setup(${args}) {
  18805. ${exposeCall}`
  18806. );
  18807. ctx.s.appendRight(endOffset, `}`);
  18808. }
  18809. }
  18810. if (ctx.helperImports.size > 0) {
  18811. ctx.s.prepend(
  18812. `import { ${[...ctx.helperImports].map((h) => `${h} as _${h}`).join(", ")} } from 'vue'
  18813. `
  18814. );
  18815. }
  18816. return {
  18817. ...scriptSetup,
  18818. bindings: ctx.bindingMetadata,
  18819. imports: ctx.userImports,
  18820. content: ctx.s.toString(),
  18821. map: options.sourceMap !== false ? ctx.s.generateMap({
  18822. source: filename,
  18823. hires: true,
  18824. includeContent: true
  18825. }) : void 0,
  18826. scriptAst: scriptAst == null ? void 0 : scriptAst.body,
  18827. scriptSetupAst: scriptSetupAst == null ? void 0 : scriptSetupAst.body,
  18828. deps: ctx.deps ? [...ctx.deps] : void 0
  18829. };
  18830. }
  18831. function registerBinding(bindings, node, type) {
  18832. bindings[node.name] = type;
  18833. }
  18834. function walkDeclaration(from, node, bindings, userImportAliases, hoistStatic) {
  18835. let isAllLiteral = false;
  18836. if (node.type === "VariableDeclaration") {
  18837. const isConst = node.kind === "const";
  18838. isAllLiteral = isConst && node.declarations.every(
  18839. (decl) => decl.id.type === "Identifier" && isStaticNode(decl.init)
  18840. );
  18841. for (const { id, init: _init } of node.declarations) {
  18842. const init = _init && CompilerDOM.unwrapTSNode(_init);
  18843. const isDefineCall = !!(isConst && isCallOf(
  18844. init,
  18845. (c) => c === DEFINE_PROPS || c === DEFINE_EMITS || c === WITH_DEFAULTS
  18846. ));
  18847. if (id.type === "Identifier") {
  18848. let bindingType;
  18849. const userReactiveBinding = userImportAliases["reactive"];
  18850. if ((hoistStatic || from === "script") && (isAllLiteral || isConst && isStaticNode(init))) {
  18851. bindingType = "literal-const";
  18852. } else if (isCallOf(init, userReactiveBinding)) {
  18853. bindingType = isConst ? "setup-reactive-const" : "setup-let";
  18854. } else if (
  18855. // if a declaration is a const literal, we can mark it so that
  18856. // the generated render fn code doesn't need to unref() it
  18857. isDefineCall || isConst && canNeverBeRef(init, userReactiveBinding)
  18858. ) {
  18859. bindingType = isCallOf(init, DEFINE_PROPS) ? "setup-reactive-const" : "setup-const";
  18860. } else if (isConst) {
  18861. if (isCallOf(
  18862. init,
  18863. (m) => m === userImportAliases["ref"] || m === userImportAliases["computed"] || m === userImportAliases["shallowRef"] || m === userImportAliases["customRef"] || m === userImportAliases["toRef"] || m === DEFINE_MODEL
  18864. )) {
  18865. bindingType = "setup-ref";
  18866. } else {
  18867. bindingType = "setup-maybe-ref";
  18868. }
  18869. } else {
  18870. bindingType = "setup-let";
  18871. }
  18872. registerBinding(bindings, id, bindingType);
  18873. } else {
  18874. if (isCallOf(init, DEFINE_PROPS)) {
  18875. continue;
  18876. }
  18877. if (id.type === "ObjectPattern") {
  18878. walkObjectPattern(id, bindings, isConst, isDefineCall);
  18879. } else if (id.type === "ArrayPattern") {
  18880. walkArrayPattern(id, bindings, isConst, isDefineCall);
  18881. }
  18882. }
  18883. }
  18884. } else if (node.type === "TSEnumDeclaration") {
  18885. isAllLiteral = node.members.every(
  18886. (member) => !member.initializer || isStaticNode(member.initializer)
  18887. );
  18888. bindings[node.id.name] = isAllLiteral ? "literal-const" : "setup-const";
  18889. } else if (node.type === "FunctionDeclaration" || node.type === "ClassDeclaration") {
  18890. bindings[node.id.name] = "setup-const";
  18891. }
  18892. return isAllLiteral;
  18893. }
  18894. function walkObjectPattern(node, bindings, isConst, isDefineCall = false) {
  18895. for (const p of node.properties) {
  18896. if (p.type === "ObjectProperty") {
  18897. if (p.key.type === "Identifier" && p.key === p.value) {
  18898. const type = isDefineCall ? "setup-const" : isConst ? "setup-maybe-ref" : "setup-let";
  18899. registerBinding(bindings, p.key, type);
  18900. } else {
  18901. walkPattern(p.value, bindings, isConst, isDefineCall);
  18902. }
  18903. } else {
  18904. const type = isConst ? "setup-const" : "setup-let";
  18905. registerBinding(bindings, p.argument, type);
  18906. }
  18907. }
  18908. }
  18909. function walkArrayPattern(node, bindings, isConst, isDefineCall = false) {
  18910. for (const e of node.elements) {
  18911. e && walkPattern(e, bindings, isConst, isDefineCall);
  18912. }
  18913. }
  18914. function walkPattern(node, bindings, isConst, isDefineCall = false) {
  18915. if (node.type === "Identifier") {
  18916. const type = isDefineCall ? "setup-const" : isConst ? "setup-maybe-ref" : "setup-let";
  18917. registerBinding(bindings, node, type);
  18918. } else if (node.type === "RestElement") {
  18919. const type = isConst ? "setup-const" : "setup-let";
  18920. registerBinding(bindings, node.argument, type);
  18921. } else if (node.type === "ObjectPattern") {
  18922. walkObjectPattern(node, bindings, isConst);
  18923. } else if (node.type === "ArrayPattern") {
  18924. walkArrayPattern(node, bindings, isConst);
  18925. } else if (node.type === "AssignmentPattern") {
  18926. if (node.left.type === "Identifier") {
  18927. const type = isDefineCall ? "setup-const" : isConst ? "setup-maybe-ref" : "setup-let";
  18928. registerBinding(bindings, node.left, type);
  18929. } else {
  18930. walkPattern(node.left, bindings, isConst);
  18931. }
  18932. }
  18933. }
  18934. function canNeverBeRef(node, userReactiveImport) {
  18935. if (isCallOf(node, userReactiveImport)) {
  18936. return true;
  18937. }
  18938. switch (node.type) {
  18939. case "UnaryExpression":
  18940. case "BinaryExpression":
  18941. case "ArrayExpression":
  18942. case "ObjectExpression":
  18943. case "FunctionExpression":
  18944. case "ArrowFunctionExpression":
  18945. case "UpdateExpression":
  18946. case "ClassExpression":
  18947. case "TaggedTemplateExpression":
  18948. return true;
  18949. case "SequenceExpression":
  18950. return canNeverBeRef(
  18951. node.expressions[node.expressions.length - 1],
  18952. userReactiveImport
  18953. );
  18954. default:
  18955. if (isLiteralNode(node)) {
  18956. return true;
  18957. }
  18958. return false;
  18959. }
  18960. }
  18961. function isStaticNode(node) {
  18962. node = CompilerDOM.unwrapTSNode(node);
  18963. switch (node.type) {
  18964. case "UnaryExpression":
  18965. return isStaticNode(node.argument);
  18966. case "LogicalExpression":
  18967. case "BinaryExpression":
  18968. return isStaticNode(node.left) && isStaticNode(node.right);
  18969. case "ConditionalExpression": {
  18970. return isStaticNode(node.test) && isStaticNode(node.consequent) && isStaticNode(node.alternate);
  18971. }
  18972. case "SequenceExpression":
  18973. case "TemplateLiteral":
  18974. return node.expressions.every((expr) => isStaticNode(expr));
  18975. case "ParenthesizedExpression":
  18976. return isStaticNode(node.expression);
  18977. case "StringLiteral":
  18978. case "NumericLiteral":
  18979. case "BooleanLiteral":
  18980. case "NullLiteral":
  18981. case "BigIntLiteral":
  18982. return true;
  18983. }
  18984. return false;
  18985. }
  18986. const version = "3.4.21";
  18987. const parseCache = parseCache$1;
  18988. const errorMessages = {
  18989. ...CompilerDOM.errorMessages,
  18990. ...CompilerDOM.DOMErrorMessages
  18991. };
  18992. const walk = estreeWalker.walk;
  18993. const shouldTransformRef = () => false;
  18994. exports.extractIdentifiers = compilerCore.extractIdentifiers;
  18995. exports.generateCodeFrame = compilerCore.generateCodeFrame;
  18996. exports.isInDestructureAssignment = compilerCore.isInDestructureAssignment;
  18997. exports.isStaticProperty = compilerCore.isStaticProperty;
  18998. exports.walkIdentifiers = compilerCore.walkIdentifiers;
  18999. exports.MagicString = MagicString;
  19000. exports.babelParse = parser$1.parse;
  19001. exports.compileScript = compileScript;
  19002. exports.compileStyle = compileStyle;
  19003. exports.compileStyleAsync = compileStyleAsync;
  19004. exports.compileTemplate = compileTemplate;
  19005. exports.errorMessages = errorMessages;
  19006. exports.extractRuntimeEmits = extractRuntimeEmits;
  19007. exports.extractRuntimeProps = extractRuntimeProps;
  19008. exports.inferRuntimeType = inferRuntimeType;
  19009. exports.invalidateTypeCache = invalidateTypeCache;
  19010. exports.parse = parse$2;
  19011. exports.parseCache = parseCache;
  19012. exports.registerTS = registerTS;
  19013. exports.resolveTypeElements = resolveTypeElements;
  19014. exports.rewriteDefault = rewriteDefault;
  19015. exports.rewriteDefaultAST = rewriteDefaultAST;
  19016. exports.shouldTransformRef = shouldTransformRef;
  19017. exports.version = version;
  19018. exports.walk = walk;