lessc 390 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320732173227323732473257326732773287329733073317332733373347335733673377338733973407341734273437344734573467347734873497350735173527353735473557356735773587359736073617362736373647365736673677368736973707371737273737374737573767377737873797380738173827383738473857386738773887389739073917392739373947395739673977398739974007401740274037404740574067407740874097410741174127413741474157416741774187419742074217422742374247425742674277428742974307431743274337434743574367437743874397440744174427443744474457446744774487449745074517452745374547455745674577458745974607461746274637464746574667467746874697470747174727473747474757476747774787479748074817482748374847485748674877488748974907491749274937494749574967497749874997500750175027503750475057506750775087509751075117512751375147515751675177518751975207521752275237524752575267527752875297530753175327533753475357536753775387539754075417542754375447545754675477548754975507551755275537554755575567557755875597560756175627563756475657566756775687569757075717572757375747575757675777578757975807581758275837584758575867587758875897590759175927593759475957596759775987599760076017602760376047605760676077608760976107611761276137614761576167617761876197620762176227623762476257626762776287629763076317632763376347635763676377638763976407641764276437644764576467647764876497650765176527653765476557656765776587659766076617662766376647665766676677668766976707671767276737674767576767677767876797680768176827683768476857686768776887689769076917692769376947695769676977698769977007701770277037704770577067707770877097710771177127713771477157716771777187719772077217722772377247725772677277728772977307731773277337734773577367737773877397740774177427743774477457746774777487749775077517752775377547755775677577758775977607761776277637764776577667767776877697770777177727773777477757776777777787779778077817782778377847785778677877788778977907791779277937794779577967797779877997800780178027803780478057806780778087809781078117812781378147815781678177818781978207821782278237824782578267827782878297830783178327833783478357836783778387839784078417842784378447845784678477848784978507851785278537854785578567857785878597860786178627863786478657866786778687869787078717872787378747875787678777878787978807881788278837884788578867887788878897890789178927893789478957896789778987899790079017902790379047905790679077908790979107911791279137914791579167917791879197920792179227923792479257926792779287929793079317932793379347935793679377938793979407941794279437944794579467947794879497950795179527953795479557956795779587959796079617962796379647965796679677968796979707971797279737974797579767977797879797980798179827983798479857986798779887989799079917992799379947995799679977998799980008001800280038004800580068007800880098010801180128013801480158016801780188019802080218022802380248025802680278028802980308031803280338034803580368037803880398040804180428043804480458046804780488049805080518052805380548055805680578058805980608061806280638064806580668067806880698070807180728073807480758076807780788079808080818082808380848085808680878088808980908091809280938094809580968097809880998100810181028103810481058106810781088109811081118112811381148115811681178118811981208121812281238124812581268127812881298130813181328133813481358136813781388139814081418142814381448145814681478148814981508151815281538154815581568157815881598160816181628163816481658166816781688169817081718172817381748175817681778178817981808181818281838184818581868187818881898190819181928193819481958196819781988199820082018202820382048205820682078208820982108211821282138214821582168217821882198220822182228223822482258226822782288229823082318232823382348235823682378238823982408241824282438244824582468247824882498250825182528253825482558256825782588259826082618262826382648265826682678268826982708271827282738274827582768277827882798280828182828283828482858286828782888289829082918292829382948295829682978298829983008301830283038304830583068307830883098310831183128313831483158316831783188319832083218322832383248325832683278328832983308331833283338334833583368337833883398340834183428343834483458346834783488349835083518352835383548355835683578358835983608361836283638364836583668367836883698370837183728373837483758376837783788379838083818382838383848385838683878388838983908391839283938394839583968397839883998400840184028403840484058406840784088409841084118412841384148415841684178418841984208421842284238424842584268427842884298430843184328433843484358436843784388439844084418442844384448445844684478448844984508451845284538454845584568457845884598460846184628463846484658466846784688469847084718472847384748475847684778478847984808481848284838484848584868487848884898490849184928493849484958496849784988499850085018502850385048505850685078508850985108511851285138514851585168517851885198520852185228523852485258526852785288529853085318532853385348535853685378538853985408541854285438544854585468547854885498550855185528553855485558556855785588559856085618562856385648565856685678568856985708571857285738574857585768577857885798580858185828583858485858586858785888589859085918592859385948595859685978598859986008601860286038604860586068607860886098610861186128613861486158616861786188619862086218622862386248625862686278628862986308631863286338634863586368637863886398640864186428643864486458646864786488649865086518652865386548655865686578658865986608661866286638664866586668667866886698670867186728673867486758676867786788679868086818682868386848685868686878688868986908691869286938694869586968697869886998700870187028703870487058706870787088709871087118712871387148715871687178718871987208721872287238724872587268727872887298730873187328733873487358736873787388739874087418742874387448745874687478748874987508751875287538754875587568757875887598760876187628763876487658766876787688769877087718772877387748775877687778778877987808781878287838784878587868787878887898790879187928793879487958796879787988799880088018802880388048805880688078808880988108811881288138814881588168817881888198820882188228823882488258826882788288829883088318832883388348835883688378838883988408841884288438844884588468847884888498850885188528853885488558856885788588859886088618862886388648865886688678868886988708871887288738874887588768877887888798880888188828883888488858886888788888889889088918892889388948895889688978898889989008901890289038904890589068907890889098910891189128913891489158916891789188919892089218922892389248925892689278928892989308931893289338934893589368937893889398940894189428943894489458946894789488949895089518952895389548955895689578958895989608961896289638964896589668967896889698970897189728973897489758976897789788979898089818982898389848985898689878988898989908991899289938994899589968997899889999000900190029003900490059006900790089009901090119012901390149015901690179018901990209021902290239024902590269027902890299030903190329033903490359036903790389039904090419042904390449045904690479048904990509051905290539054905590569057905890599060906190629063906490659066906790689069907090719072907390749075907690779078907990809081908290839084908590869087908890899090909190929093909490959096909790989099910091019102910391049105910691079108910991109111911291139114911591169117911891199120912191229123912491259126912791289129913091319132913391349135913691379138913991409141914291439144914591469147914891499150915191529153915491559156915791589159916091619162916391649165916691679168916991709171917291739174917591769177917891799180918191829183918491859186918791889189919091919192919391949195919691979198919992009201920292039204920592069207920892099210921192129213921492159216921792189219922092219222922392249225922692279228922992309231923292339234923592369237923892399240924192429243924492459246924792489249925092519252925392549255925692579258925992609261926292639264926592669267926892699270927192729273927492759276927792789279928092819282928392849285928692879288928992909291929292939294929592969297929892999300930193029303930493059306930793089309931093119312931393149315931693179318931993209321932293239324932593269327932893299330933193329333933493359336933793389339934093419342934393449345934693479348934993509351935293539354935593569357935893599360936193629363936493659366936793689369937093719372937393749375937693779378937993809381938293839384938593869387938893899390939193929393939493959396939793989399940094019402940394049405940694079408940994109411941294139414941594169417941894199420942194229423942494259426942794289429943094319432943394349435943694379438943994409441944294439444944594469447944894499450945194529453945494559456945794589459946094619462946394649465946694679468946994709471947294739474947594769477947894799480948194829483948494859486948794889489949094919492949394949495949694979498949995009501950295039504950595069507950895099510951195129513951495159516951795189519952095219522952395249525952695279528952995309531953295339534953595369537953895399540954195429543954495459546954795489549955095519552955395549555955695579558955995609561956295639564956595669567956895699570957195729573957495759576957795789579958095819582958395849585958695879588958995909591959295939594959595969597959895999600960196029603960496059606960796089609961096119612961396149615961696179618961996209621962296239624962596269627962896299630963196329633963496359636963796389639964096419642964396449645964696479648964996509651965296539654965596569657965896599660966196629663966496659666966796689669967096719672967396749675967696779678967996809681968296839684968596869687968896899690969196929693969496959696969796989699970097019702970397049705970697079708970997109711971297139714971597169717971897199720972197229723972497259726972797289729973097319732973397349735973697379738973997409741974297439744974597469747974897499750975197529753975497559756975797589759976097619762976397649765976697679768976997709771977297739774977597769777977897799780978197829783978497859786978797889789979097919792979397949795979697979798979998009801980298039804980598069807980898099810981198129813981498159816981798189819982098219822982398249825982698279828982998309831983298339834983598369837983898399840984198429843984498459846984798489849985098519852985398549855985698579858985998609861986298639864986598669867986898699870987198729873987498759876987798789879988098819882988398849885988698879888988998909891989298939894989598969897989898999900990199029903990499059906990799089909991099119912991399149915991699179918991999209921992299239924992599269927992899299930993199329933993499359936993799389939994099419942994399449945994699479948994999509951995299539954995599569957995899599960996199629963996499659966996799689969997099719972997399749975997699779978997999809981998299839984998599869987998899899990999199929993999499959996999799989999100001000110002100031000410005100061000710008100091001010011100121001310014100151001610017100181001910020100211002210023100241002510026100271002810029100301003110032100331003410035100361003710038100391004010041100421004310044100451004610047100481004910050100511005210053100541005510056100571005810059100601006110062100631006410065100661006710068100691007010071100721007310074100751007610077100781007910080100811008210083100841008510086100871008810089100901009110092100931009410095100961009710098100991010010101101021010310104101051010610107101081010910110101111011210113101141011510116101171011810119101201012110122101231012410125101261012710128101291013010131101321013310134101351013610137101381013910140101411014210143101441014510146101471014810149101501015110152101531015410155101561015710158101591016010161101621016310164101651016610167101681016910170101711017210173101741017510176101771017810179101801018110182101831018410185101861018710188101891019010191101921019310194101951019610197101981019910200102011020210203102041020510206102071020810209102101021110212102131021410215102161021710218102191022010221102221022310224102251022610227102281022910230102311023210233102341023510236102371023810239102401024110242102431024410245102461024710248102491025010251102521025310254102551025610257102581025910260102611026210263102641026510266102671026810269102701027110272102731027410275102761027710278102791028010281102821028310284102851028610287102881028910290102911029210293102941029510296102971029810299103001030110302103031030410305103061030710308103091031010311103121031310314103151031610317103181031910320103211032210323103241032510326103271032810329103301033110332103331033410335103361033710338103391034010341103421034310344103451034610347103481034910350103511035210353103541035510356103571035810359103601036110362103631036410365103661036710368103691037010371103721037310374103751037610377103781037910380103811038210383103841038510386103871038810389103901039110392103931039410395103961039710398103991040010401104021040310404104051040610407104081040910410104111041210413104141041510416104171041810419104201042110422104231042410425104261042710428104291043010431104321043310434104351043610437104381043910440104411044210443104441044510446104471044810449104501045110452104531045410455104561045710458104591046010461104621046310464104651046610467104681046910470104711047210473104741047510476104771047810479104801048110482104831048410485104861048710488104891049010491104921049310494104951049610497104981049910500105011050210503105041050510506105071050810509105101051110512105131051410515105161051710518105191052010521105221052310524105251052610527105281052910530105311053210533105341053510536105371053810539105401054110542105431054410545105461054710548105491055010551105521055310554105551055610557105581055910560105611056210563105641056510566105671056810569105701057110572105731057410575105761057710578105791058010581105821058310584105851058610587105881058910590105911059210593105941059510596105971059810599106001060110602106031060410605106061060710608106091061010611106121061310614106151061610617106181061910620106211062210623106241062510626106271062810629106301063110632106331063410635106361063710638106391064010641106421064310644106451064610647106481064910650106511065210653106541065510656106571065810659106601066110662106631066410665106661066710668106691067010671106721067310674106751067610677106781067910680106811068210683106841068510686106871068810689106901069110692106931069410695106961069710698106991070010701107021070310704107051070610707107081070910710107111071210713107141071510716107171071810719107201072110722107231072410725107261072710728107291073010731107321073310734107351073610737107381073910740107411074210743107441074510746107471074810749107501075110752107531075410755107561075710758107591076010761107621076310764107651076610767107681076910770107711077210773107741077510776107771077810779107801078110782107831078410785107861078710788107891079010791107921079310794107951079610797107981079910800108011080210803108041080510806108071080810809108101081110812108131081410815108161081710818108191082010821108221082310824108251082610827108281082910830108311083210833108341083510836108371083810839108401084110842108431084410845108461084710848108491085010851108521085310854108551085610857108581085910860108611086210863108641086510866108671086810869108701087110872108731087410875108761087710878108791088010881108821088310884108851088610887108881088910890108911089210893108941089510896108971089810899109001090110902109031090410905109061090710908109091091010911109121091310914109151091610917109181091910920109211092210923109241092510926109271092810929109301093110932109331093410935109361093710938109391094010941109421094310944109451094610947109481094910950109511095210953109541095510956109571095810959109601096110962109631096410965109661096710968109691097010971109721097310974109751097610977109781097910980109811098210983109841098510986109871098810989109901099110992109931099410995109961099710998109991100011001110021100311004110051100611007110081100911010110111101211013110141101511016110171101811019110201102111022110231102411025110261102711028110291103011031110321103311034110351103611037110381103911040110411104211043110441104511046110471104811049110501105111052110531105411055110561105711058110591106011061110621106311064110651106611067110681106911070110711107211073110741107511076110771107811079110801108111082110831108411085110861108711088110891109011091110921109311094110951109611097110981109911100111011110211103111041110511106111071110811109111101111111112111131111411115111161111711118111191112011121111221112311124111251112611127111281112911130111311113211133111341113511136111371113811139111401114111142111431114411145111461114711148111491115011151111521115311154111551115611157111581115911160111611116211163111641116511166111671116811169111701117111172111731117411175111761117711178111791118011181111821118311184111851118611187111881118911190111911119211193111941119511196111971119811199112001120111202112031120411205112061120711208112091121011211112121121311214112151121611217112181121911220112211122211223112241122511226112271122811229112301123111232112331123411235112361123711238112391124011241112421124311244112451124611247112481124911250112511125211253112541125511256112571125811259112601126111262112631126411265112661126711268112691127011271112721127311274112751127611277112781127911280112811128211283112841128511286112871128811289112901129111292112931129411295112961129711298112991130011301113021130311304113051130611307113081130911310113111131211313113141131511316113171131811319113201132111322113231132411325113261132711328113291133011331113321133311334113351133611337113381133911340113411134211343113441134511346113471134811349113501135111352113531135411355113561135711358113591136011361113621136311364113651136611367113681136911370113711137211373113741137511376113771137811379113801138111382113831138411385113861138711388113891139011391113921139311394113951139611397113981139911400114011140211403114041140511406114071140811409114101141111412114131141411415114161141711418114191142011421114221142311424114251142611427114281142911430114311143211433114341143511436114371143811439114401144111442114431144411445114461144711448114491145011451114521145311454114551145611457114581145911460114611146211463114641146511466114671146811469114701147111472114731147411475114761147711478114791148011481114821148311484114851148611487114881148911490114911149211493114941149511496114971149811499115001150111502115031150411505115061150711508115091151011511115121151311514115151151611517115181151911520115211152211523115241152511526115271152811529115301153111532115331153411535115361153711538115391154011541115421154311544115451154611547115481154911550115511155211553115541155511556115571155811559115601156111562115631156411565115661156711568115691157011571115721157311574115751157611577115781157911580115811158211583115841158511586115871158811589115901159111592115931159411595115961159711598115991160011601116021160311604116051160611607116081160911610116111161211613116141161511616116171161811619116201162111622116231162411625116261162711628116291163011631116321163311634116351163611637116381163911640116411164211643116441164511646116471164811649116501165111652116531165411655116561165711658116591166011661116621166311664116651166611667116681166911670116711167211673116741167511676116771167811679116801168111682116831168411685116861168711688116891169011691116921169311694116951169611697116981169911700117011170211703117041170511706117071170811709117101171111712117131171411715117161171711718117191172011721117221172311724117251172611727117281172911730117311173211733117341173511736117371173811739117401174111742117431174411745117461174711748117491175011751117521175311754117551175611757117581175911760117611176211763117641176511766117671176811769117701177111772117731177411775117761177711778117791178011781117821178311784117851178611787117881178911790117911179211793117941179511796117971179811799118001180111802118031180411805118061180711808118091181011811118121181311814118151181611817118181181911820118211182211823118241182511826118271182811829118301183111832118331183411835118361183711838118391184011841118421184311844118451184611847118481184911850118511185211853118541185511856118571185811859118601186111862118631186411865118661186711868118691187011871118721187311874118751187611877118781187911880118811188211883118841188511886118871188811889118901189111892118931189411895118961189711898118991190011901119021190311904119051190611907119081190911910119111191211913119141191511916119171191811919119201192111922119231192411925119261192711928119291193011931119321193311934119351193611937119381193911940119411194211943119441194511946119471194811949119501195111952119531195411955119561195711958119591196011961119621196311964119651196611967119681196911970119711197211973119741197511976119771197811979119801198111982119831198411985119861198711988119891199011991119921199311994119951199611997119981199912000120011200212003120041200512006120071200812009120101201112012120131201412015120161201712018120191202012021120221202312024120251202612027120281202912030120311203212033120341203512036120371203812039120401204112042120431204412045120461204712048120491205012051120521205312054120551205612057120581205912060120611206212063120641206512066120671206812069120701207112072120731207412075120761207712078120791208012081120821208312084120851208612087120881208912090120911209212093120941209512096120971209812099121001210112102121031210412105121061210712108121091211012111121121211312114121151211612117121181211912120121211212212123121241212512126121271212812129121301213112132121331213412135121361213712138121391214012141121421214312144121451214612147121481214912150121511215212153121541215512156121571215812159121601216112162121631216412165121661216712168121691217012171121721217312174121751217612177121781217912180121811218212183121841218512186121871218812189121901219112192121931219412195121961219712198121991220012201122021220312204122051220612207122081220912210122111221212213122141221512216122171221812219122201222112222122231222412225122261222712228122291223012231122321223312234122351223612237122381223912240122411224212243122441224512246122471224812249122501225112252122531225412255122561225712258122591226012261122621226312264122651226612267122681226912270122711227212273122741227512276122771227812279122801228112282122831228412285122861228712288122891229012291122921229312294122951229612297122981229912300123011230212303123041230512306123071230812309123101231112312123131231412315123161231712318123191232012321123221232312324123251232612327123281232912330123311233212333123341233512336123371233812339123401234112342123431234412345123461234712348123491235012351123521235312354123551235612357123581235912360123611236212363123641236512366123671236812369123701237112372123731237412375123761237712378123791238012381123821238312384123851238612387123881238912390123911239212393123941239512396123971239812399124001240112402124031240412405124061240712408124091241012411124121241312414124151241612417124181241912420124211242212423124241242512426124271242812429124301243112432124331243412435124361243712438124391244012441124421244312444124451244612447124481244912450124511245212453124541245512456124571245812459124601246112462124631246412465124661246712468124691247012471124721247312474124751247612477124781247912480124811248212483124841248512486124871248812489124901249112492124931249412495124961249712498124991250012501125021250312504125051250612507125081250912510125111251212513125141251512516125171251812519125201252112522125231252412525125261252712528125291253012531125321253312534125351253612537125381253912540125411254212543125441254512546125471254812549125501255112552125531255412555125561255712558125591256012561125621256312564125651256612567125681256912570125711257212573125741257512576125771257812579125801258112582125831258412585125861258712588125891259012591125921259312594125951259612597125981259912600126011260212603126041260512606126071260812609126101261112612126131261412615126161261712618126191262012621126221262312624126251262612627126281262912630126311263212633126341263512636126371263812639126401264112642126431264412645126461264712648126491265012651126521265312654126551265612657126581265912660126611266212663126641266512666126671266812669126701267112672126731267412675126761267712678126791268012681126821268312684126851268612687126881268912690126911269212693126941269512696126971269812699127001270112702127031270412705127061270712708127091271012711127121271312714127151271612717127181271912720127211272212723127241272512726127271272812729127301273112732127331273412735127361273712738127391274012741127421274312744127451274612747127481274912750127511275212753127541275512756127571275812759127601276112762127631276412765127661276712768127691277012771127721277312774127751277612777127781277912780127811278212783127841278512786127871278812789127901279112792127931279412795127961279712798127991280012801128021280312804128051280612807128081280912810128111281212813128141281512816128171281812819128201282112822128231282412825128261282712828128291283012831128321283312834128351283612837128381283912840128411284212843128441284512846128471284812849128501285112852128531285412855128561285712858128591286012861128621286312864128651286612867128681286912870128711287212873128741287512876128771287812879128801288112882128831288412885128861288712888128891289012891128921289312894128951289612897128981289912900129011290212903129041290512906129071290812909129101291112912129131291412915129161291712918129191292012921129221292312924129251292612927129281292912930129311293212933129341293512936129371293812939129401294112942129431294412945129461294712948129491295012951129521295312954129551295612957129581295912960129611296212963129641296512966129671296812969129701297112972129731297412975129761297712978129791298012981129821298312984129851298612987129881298912990129911299212993129941299512996129971299812999130001300113002130031300413005130061300713008130091301013011130121301313014130151301613017130181301913020130211302213023130241302513026130271302813029130301303113032130331303413035130361303713038130391304013041130421304313044130451304613047130481304913050130511305213053130541305513056130571305813059130601306113062130631306413065130661306713068130691307013071130721307313074130751307613077130781307913080130811308213083130841308513086130871308813089130901309113092130931309413095130961309713098130991310013101131021310313104131051310613107131081310913110131111311213113131141311513116131171311813119131201312113122131231312413125131261312713128131291313013131131321313313134131351313613137131381313913140131411314213143131441314513146131471314813149131501315113152131531315413155131561315713158131591316013161131621316313164131651316613167131681316913170131711317213173131741317513176131771317813179131801318113182131831318413185131861318713188131891319013191131921319313194131951319613197131981319913200132011320213203132041320513206132071320813209132101321113212132131321413215132161321713218132191322013221132221322313224132251322613227132281322913230132311323213233132341323513236132371323813239132401324113242132431324413245132461324713248132491325013251132521325313254132551325613257132581325913260132611326213263132641326513266132671326813269132701327113272132731327413275132761327713278132791328013281132821328313284132851328613287132881328913290132911329213293132941329513296132971329813299133001330113302133031330413305133061330713308133091331013311133121331313314133151331613317133181331913320133211332213323133241332513326133271332813329133301333113332133331333413335133361333713338133391334013341133421334313344133451334613347133481334913350133511335213353133541335513356133571335813359133601336113362133631336413365133661336713368133691337013371133721337313374133751337613377133781337913380133811338213383133841338513386133871338813389133901339113392133931339413395133961339713398133991340013401134021340313404134051340613407134081340913410134111341213413134141341513416134171341813419134201342113422134231342413425134261342713428134291343013431134321343313434134351343613437134381343913440134411344213443134441344513446134471344813449134501345113452134531345413455134561345713458134591346013461134621346313464134651346613467134681346913470134711347213473134741347513476134771347813479134801348113482134831348413485134861348713488134891349013491134921349313494134951349613497134981349913500135011350213503135041350513506135071350813509135101351113512135131351413515135161351713518135191352013521135221352313524135251352613527135281352913530135311353213533135341353513536135371353813539135401354113542135431354413545135461354713548135491355013551135521355313554135551355613557135581355913560135611356213563135641356513566135671356813569135701357113572135731357413575135761357713578135791358013581135821358313584135851358613587135881358913590135911359213593135941359513596135971359813599136001360113602136031360413605136061360713608136091361013611136121361313614136151361613617136181361913620136211362213623136241362513626136271362813629136301363113632136331363413635136361363713638136391364013641136421364313644136451364613647136481364913650136511365213653136541365513656136571365813659136601366113662136631366413665136661366713668136691367013671136721367313674136751367613677136781367913680136811368213683136841368513686136871368813689136901369113692136931369413695136961369713698136991370013701137021370313704137051370613707137081370913710137111371213713137141371513716137171371813719137201372113722137231372413725137261372713728137291373013731137321373313734137351373613737137381373913740137411374213743137441374513746137471374813749137501375113752137531375413755137561375713758137591376013761137621376313764137651376613767137681376913770137711377213773137741377513776137771377813779137801378113782137831378413785137861378713788137891379013791137921379313794137951379613797137981379913800138011380213803138041380513806138071380813809138101381113812138131381413815138161381713818138191382013821138221382313824138251382613827138281382913830138311383213833138341383513836138371383813839138401384113842138431384413845138461384713848138491385013851138521385313854138551385613857138581385913860138611386213863138641386513866138671386813869138701387113872138731387413875138761387713878138791388013881138821388313884138851388613887138881388913890138911389213893138941389513896138971389813899139001390113902139031390413905139061390713908139091391013911139121391313914139151391613917139181391913920139211392213923139241392513926139271392813929139301393113932139331393413935139361393713938139391394013941139421394313944139451394613947139481394913950139511395213953139541395513956139571395813959139601396113962139631396413965139661396713968139691397013971139721397313974139751397613977139781397913980139811398213983139841398513986139871398813989139901399113992139931399413995139961399713998139991400014001140021400314004140051400614007140081400914010140111401214013140141401514016140171401814019140201402114022140231402414025140261402714028140291403014031140321403314034140351403614037140381403914040140411404214043140441404514046140471404814049140501405114052140531405414055140561405714058140591406014061140621406314064140651406614067140681406914070140711407214073140741407514076140771407814079140801408114082140831408414085140861408714088140891409014091140921409314094140951409614097140981409914100141011410214103141041410514106141071410814109141101411114112141131411414115141161411714118141191412014121141221412314124141251412614127141281412914130141311413214133141341413514136141371413814139141401414114142141431414414145141461414714148141491415014151141521415314154141551415614157141581415914160141611416214163141641416514166141671416814169141701417114172141731417414175141761417714178141791418014181141821418314184141851418614187141881418914190141911419214193141941419514196141971419814199142001420114202142031420414205142061420714208142091421014211142121421314214142151421614217142181421914220142211422214223142241422514226142271422814229142301423114232142331423414235142361423714238142391424014241142421424314244142451424614247142481424914250142511425214253142541425514256142571425814259142601426114262142631426414265142661426714268142691427014271142721427314274142751427614277142781427914280142811428214283142841428514286142871428814289142901429114292142931429414295142961429714298142991430014301143021430314304143051430614307143081430914310143111431214313143141431514316143171431814319143201432114322143231432414325143261432714328143291433014331143321433314334143351433614337143381433914340
  1. #!/usr/bin/env node
  2. // AUTO-GENERATED BY ROLLUP
  3. 'use strict';
  4. var path = require('path');
  5. var os = require('os');
  6. var CloneHelper = require('clone');
  7. var url = require('url');
  8. var fs;
  9. try {
  10. fs = require('graceful-fs');
  11. } catch (e) {
  12. fs = require('fs');
  13. }
  14. var fs$1 = fs;
  15. var Math$1 = {
  16. ALWAYS: 0,
  17. PARENS_DIVISION: 1,
  18. PARENS: 2,
  19. STRICT_LEGACY: 3
  20. };
  21. var RewriteUrls = {
  22. OFF: 0,
  23. LOCAL: 1,
  24. ALL: 2
  25. };
  26. /* jshint proto: true */
  27. function getLocation(index, inputStream) {
  28. var n = index + 1;
  29. var line = null;
  30. var column = -1;
  31. while (--n >= 0 && inputStream.charAt(n) !== '\n') {
  32. column++;
  33. }
  34. if (typeof index === 'number') {
  35. line = (inputStream.slice(0, index).match(/\n/g) || '').length;
  36. }
  37. return {
  38. line,
  39. column
  40. };
  41. }
  42. function copyArray(arr) {
  43. var i;
  44. var length = arr.length;
  45. var copy = new Array(length);
  46. for (i = 0; i < length; i++) {
  47. copy[i] = arr[i];
  48. }
  49. return copy;
  50. }
  51. function clone(obj) {
  52. var cloned = {};
  53. for (var prop in obj) {
  54. if (obj.hasOwnProperty(prop)) {
  55. cloned[prop] = obj[prop];
  56. }
  57. }
  58. return cloned;
  59. }
  60. function defaults(obj1, obj2) {
  61. var newObj = obj2 || {};
  62. if (!obj2._defaults) {
  63. newObj = {};
  64. var _defaults = CloneHelper(obj1);
  65. newObj._defaults = _defaults;
  66. var cloned = obj2 ? CloneHelper(obj2) : {};
  67. Object.assign(newObj, _defaults, cloned);
  68. }
  69. return newObj;
  70. }
  71. function copyOptions(obj1, obj2) {
  72. if (obj2 && obj2._defaults) {
  73. return obj2;
  74. }
  75. var opts = defaults(obj1, obj2);
  76. if (opts.strictMath) {
  77. opts.math = Math$1.STRICT_LEGACY;
  78. } // Back compat with changed relativeUrls option
  79. if (opts.relativeUrls) {
  80. opts.rewriteUrls = RewriteUrls.ALL;
  81. }
  82. if (typeof opts.math === 'string') {
  83. switch (opts.math.toLowerCase()) {
  84. case 'always':
  85. opts.math = Math$1.ALWAYS;
  86. break;
  87. case 'parens-division':
  88. opts.math = Math$1.PARENS_DIVISION;
  89. break;
  90. case 'strict':
  91. case 'parens':
  92. opts.math = Math$1.PARENS;
  93. break;
  94. case 'strict-legacy':
  95. opts.math = Math$1.STRICT_LEGACY;
  96. }
  97. }
  98. if (typeof opts.rewriteUrls === 'string') {
  99. switch (opts.rewriteUrls.toLowerCase()) {
  100. case 'off':
  101. opts.rewriteUrls = RewriteUrls.OFF;
  102. break;
  103. case 'local':
  104. opts.rewriteUrls = RewriteUrls.LOCAL;
  105. break;
  106. case 'all':
  107. opts.rewriteUrls = RewriteUrls.ALL;
  108. break;
  109. }
  110. }
  111. return opts;
  112. }
  113. function merge(obj1, obj2) {
  114. for (var prop in obj2) {
  115. if (obj2.hasOwnProperty(prop)) {
  116. obj1[prop] = obj2[prop];
  117. }
  118. }
  119. return obj1;
  120. }
  121. function flattenArray(arr) {
  122. var result = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : [];
  123. for (var i = 0, length = arr.length; i < length; i++) {
  124. var value = arr[i];
  125. if (Array.isArray(value)) {
  126. flattenArray(value, result);
  127. } else {
  128. if (value !== undefined) {
  129. result.push(value);
  130. }
  131. }
  132. }
  133. return result;
  134. }
  135. var utils = /*#__PURE__*/Object.freeze({
  136. getLocation: getLocation,
  137. copyArray: copyArray,
  138. clone: clone,
  139. defaults: defaults,
  140. copyOptions: copyOptions,
  141. merge: merge,
  142. flattenArray: flattenArray
  143. });
  144. var environment = {
  145. encodeBase64: function encodeBase64(str) {
  146. // Avoid Buffer constructor on newer versions of Node.js.
  147. var buffer = Buffer.from ? Buffer.from(str) : new Buffer(str);
  148. return buffer.toString('base64');
  149. },
  150. mimeLookup: function mimeLookup(filename) {
  151. return require('mime').lookup(filename);
  152. },
  153. charsetLookup: function charsetLookup(mime) {
  154. return require('mime').charsets.lookup(mime);
  155. },
  156. getSourceMapGenerator: function getSourceMapGenerator() {
  157. return require('source-map').SourceMapGenerator;
  158. }
  159. };
  160. function _classCallCheck(instance, Constructor) {
  161. if (!(instance instanceof Constructor)) {
  162. throw new TypeError("Cannot call a class as a function");
  163. }
  164. }
  165. function _defineProperties(target, props) {
  166. for (var i = 0; i < props.length; i++) {
  167. var descriptor = props[i];
  168. descriptor.enumerable = descriptor.enumerable || false;
  169. descriptor.configurable = true;
  170. if ("value" in descriptor) descriptor.writable = true;
  171. Object.defineProperty(target, descriptor.key, descriptor);
  172. }
  173. }
  174. function _createClass(Constructor, protoProps, staticProps) {
  175. if (protoProps) _defineProperties(Constructor.prototype, protoProps);
  176. if (staticProps) _defineProperties(Constructor, staticProps);
  177. return Constructor;
  178. }
  179. function _inherits(subClass, superClass) {
  180. if (typeof superClass !== "function" && superClass !== null) {
  181. throw new TypeError("Super expression must either be null or a function");
  182. }
  183. subClass.prototype = Object.create(superClass && superClass.prototype, {
  184. constructor: {
  185. value: subClass,
  186. writable: true,
  187. configurable: true
  188. }
  189. });
  190. if (superClass) _setPrototypeOf(subClass, superClass);
  191. }
  192. function _getPrototypeOf(o) {
  193. _getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf : function _getPrototypeOf(o) {
  194. return o.__proto__ || Object.getPrototypeOf(o);
  195. };
  196. return _getPrototypeOf(o);
  197. }
  198. function _setPrototypeOf(o, p) {
  199. _setPrototypeOf = Object.setPrototypeOf || function _setPrototypeOf(o, p) {
  200. o.__proto__ = p;
  201. return o;
  202. };
  203. return _setPrototypeOf(o, p);
  204. }
  205. function isNativeReflectConstruct() {
  206. if (typeof Reflect === "undefined" || !Reflect.construct) return false;
  207. if (Reflect.construct.sham) return false;
  208. if (typeof Proxy === "function") return true;
  209. try {
  210. Date.prototype.toString.call(Reflect.construct(Date, [], function () {}));
  211. return true;
  212. } catch (e) {
  213. return false;
  214. }
  215. }
  216. function _construct(Parent, args, Class) {
  217. if (isNativeReflectConstruct()) {
  218. _construct = Reflect.construct;
  219. } else {
  220. _construct = function _construct(Parent, args, Class) {
  221. var a = [null];
  222. a.push.apply(a, args);
  223. var Constructor = Function.bind.apply(Parent, a);
  224. var instance = new Constructor();
  225. if (Class) _setPrototypeOf(instance, Class.prototype);
  226. return instance;
  227. };
  228. }
  229. return _construct.apply(null, arguments);
  230. }
  231. function _assertThisInitialized(self) {
  232. if (self === void 0) {
  233. throw new ReferenceError("this hasn't been initialised - super() hasn't been called");
  234. }
  235. return self;
  236. }
  237. function _possibleConstructorReturn(self, call) {
  238. if (call && (typeof call === "object" || typeof call === "function")) {
  239. return call;
  240. }
  241. return _assertThisInitialized(self);
  242. }
  243. function _toConsumableArray(arr) {
  244. return _arrayWithoutHoles(arr) || _iterableToArray(arr) || _nonIterableSpread();
  245. }
  246. function _arrayWithoutHoles(arr) {
  247. if (Array.isArray(arr)) {
  248. for (var i = 0, arr2 = new Array(arr.length); i < arr.length; i++) arr2[i] = arr[i];
  249. return arr2;
  250. }
  251. }
  252. function _iterableToArray(iter) {
  253. if (Symbol.iterator in Object(iter) || Object.prototype.toString.call(iter) === "[object Arguments]") return Array.from(iter);
  254. }
  255. function _nonIterableSpread() {
  256. throw new TypeError("Invalid attempt to spread non-iterable instance");
  257. }
  258. var AbstractFileManager =
  259. /*#__PURE__*/
  260. function () {
  261. function AbstractFileManager() {
  262. _classCallCheck(this, AbstractFileManager);
  263. }
  264. _createClass(AbstractFileManager, [{
  265. key: "getPath",
  266. value: function getPath(filename) {
  267. var j = filename.lastIndexOf('?');
  268. if (j > 0) {
  269. filename = filename.slice(0, j);
  270. }
  271. j = filename.lastIndexOf('/');
  272. if (j < 0) {
  273. j = filename.lastIndexOf('\\');
  274. }
  275. if (j < 0) {
  276. return '';
  277. }
  278. return filename.slice(0, j + 1);
  279. }
  280. }, {
  281. key: "tryAppendExtension",
  282. value: function tryAppendExtension(path, ext) {
  283. return /(\.[a-z]*$)|([\?;].*)$/.test(path) ? path : path + ext;
  284. }
  285. }, {
  286. key: "tryAppendLessExtension",
  287. value: function tryAppendLessExtension(path) {
  288. return this.tryAppendExtension(path, '.less');
  289. }
  290. }, {
  291. key: "supportsSync",
  292. value: function supportsSync() {
  293. return false;
  294. }
  295. }, {
  296. key: "alwaysMakePathsAbsolute",
  297. value: function alwaysMakePathsAbsolute() {
  298. return false;
  299. }
  300. }, {
  301. key: "isPathAbsolute",
  302. value: function isPathAbsolute(filename) {
  303. return /^(?:[a-z-]+:|\/|\\|#)/i.test(filename);
  304. } // TODO: pull out / replace?
  305. }, {
  306. key: "join",
  307. value: function join(basePath, laterPath) {
  308. if (!basePath) {
  309. return laterPath;
  310. }
  311. return basePath + laterPath;
  312. }
  313. }, {
  314. key: "pathDiff",
  315. value: function pathDiff(url, baseUrl) {
  316. // diff between two paths to create a relative path
  317. var urlParts = this.extractUrlParts(url);
  318. var baseUrlParts = this.extractUrlParts(baseUrl);
  319. var i;
  320. var max;
  321. var urlDirectories;
  322. var baseUrlDirectories;
  323. var diff = '';
  324. if (urlParts.hostPart !== baseUrlParts.hostPart) {
  325. return '';
  326. }
  327. max = Math.max(baseUrlParts.directories.length, urlParts.directories.length);
  328. for (i = 0; i < max; i++) {
  329. if (baseUrlParts.directories[i] !== urlParts.directories[i]) {
  330. break;
  331. }
  332. }
  333. baseUrlDirectories = baseUrlParts.directories.slice(i);
  334. urlDirectories = urlParts.directories.slice(i);
  335. for (i = 0; i < baseUrlDirectories.length - 1; i++) {
  336. diff += '../';
  337. }
  338. for (i = 0; i < urlDirectories.length - 1; i++) {
  339. diff += `${urlDirectories[i]}/`;
  340. }
  341. return diff;
  342. }
  343. }, {
  344. key: "extractUrlParts",
  345. // helper function, not part of API
  346. value: function extractUrlParts(url, baseUrl) {
  347. // urlParts[1] = protocol://hostname/ OR /
  348. // urlParts[2] = / if path relative to host base
  349. // urlParts[3] = directories
  350. // urlParts[4] = filename
  351. // urlParts[5] = parameters
  352. var urlPartsRegex = /^((?:[a-z-]+:)?\/{2}(?:[^\/\?#]*\/)|([\/\\]))?((?:[^\/\\\?#]*[\/\\])*)([^\/\\\?#]*)([#\?].*)?$/i;
  353. var urlParts = url.match(urlPartsRegex);
  354. var returner = {};
  355. var rawDirectories = [];
  356. var directories = [];
  357. var i;
  358. var baseUrlParts;
  359. if (!urlParts) {
  360. throw new Error(`Could not parse sheet href - '${url}'`);
  361. } // Stylesheets in IE don't always return the full path
  362. if (baseUrl && (!urlParts[1] || urlParts[2])) {
  363. baseUrlParts = baseUrl.match(urlPartsRegex);
  364. if (!baseUrlParts) {
  365. throw new Error(`Could not parse page url - '${baseUrl}'`);
  366. }
  367. urlParts[1] = urlParts[1] || baseUrlParts[1] || '';
  368. if (!urlParts[2]) {
  369. urlParts[3] = baseUrlParts[3] + urlParts[3];
  370. }
  371. }
  372. if (urlParts[3]) {
  373. rawDirectories = urlParts[3].replace(/\\/g, '/').split('/'); // collapse '..' and skip '.'
  374. for (i = 0; i < rawDirectories.length; i++) {
  375. if (rawDirectories[i] === '..') {
  376. directories.pop();
  377. } else if (rawDirectories[i] !== '.') {
  378. directories.push(rawDirectories[i]);
  379. }
  380. }
  381. }
  382. returner.hostPart = urlParts[1];
  383. returner.directories = directories;
  384. returner.rawPath = (urlParts[1] || '') + rawDirectories.join('/');
  385. returner.path = (urlParts[1] || '') + directories.join('/');
  386. returner.filename = urlParts[4];
  387. returner.fileUrl = returner.path + (urlParts[4] || '');
  388. returner.url = returner.fileUrl + (urlParts[5] || '');
  389. return returner;
  390. }
  391. }]);
  392. return AbstractFileManager;
  393. }();
  394. var FileManager =
  395. /*#__PURE__*/
  396. function (_AbstractFileManager) {
  397. _inherits(FileManager, _AbstractFileManager);
  398. function FileManager() {
  399. var _this;
  400. _classCallCheck(this, FileManager);
  401. _this = _possibleConstructorReturn(this, _getPrototypeOf(FileManager).call(this));
  402. _this.contents = {};
  403. return _this;
  404. }
  405. _createClass(FileManager, [{
  406. key: "supports",
  407. value: function supports(filename, currentDirectory, options, environment) {
  408. return true;
  409. }
  410. }, {
  411. key: "supportsSync",
  412. value: function supportsSync(filename, currentDirectory, options, environment) {
  413. return true;
  414. }
  415. }, {
  416. key: "loadFile",
  417. value: function loadFile(filename, currentDirectory, options, environment, callback) {
  418. var fullFilename;
  419. var isAbsoluteFilename = this.isPathAbsolute(filename);
  420. var filenamesTried = [];
  421. var self = this;
  422. var prefix = filename.slice(0, 1);
  423. var explicit = prefix === '.' || prefix === '/';
  424. var result = null;
  425. var isNodeModule = false;
  426. var npmPrefix = 'npm://';
  427. options = options || {};
  428. var paths = isAbsoluteFilename ? [''] : [currentDirectory];
  429. if (options.paths) {
  430. paths.push.apply(paths, _toConsumableArray(options.paths));
  431. }
  432. if (!isAbsoluteFilename && paths.indexOf('.') === -1) {
  433. paths.push('.');
  434. }
  435. var prefixes = options.prefixes || [''];
  436. var fileParts = this.extractUrlParts(filename);
  437. if (options.syncImport) {
  438. getFileData(returnData, returnData);
  439. if (callback) {
  440. callback(result.error, result);
  441. } else {
  442. return result;
  443. }
  444. } else {
  445. // promise is guaranteed to be asyncronous
  446. // which helps as it allows the file handle
  447. // to be closed before it continues with the next file
  448. return new Promise(getFileData);
  449. }
  450. function returnData(data) {
  451. if (!data.filename) {
  452. result = {
  453. error: data
  454. };
  455. } else {
  456. result = data;
  457. }
  458. }
  459. function getFileData(fulfill, reject) {
  460. (function tryPathIndex(i) {
  461. if (i < paths.length) {
  462. (function tryPrefix(j) {
  463. if (j < prefixes.length) {
  464. isNodeModule = false;
  465. fullFilename = fileParts.rawPath + prefixes[j] + fileParts.filename;
  466. if (paths[i]) {
  467. fullFilename = path.join(paths[i], fullFilename);
  468. }
  469. if (!explicit && paths[i] === '.') {
  470. try {
  471. fullFilename = require.resolve(fullFilename);
  472. isNodeModule = true;
  473. } catch (e) {
  474. filenamesTried.push(npmPrefix + fullFilename);
  475. tryWithExtension();
  476. }
  477. } else {
  478. tryWithExtension();
  479. }
  480. function tryWithExtension() {
  481. var extFilename = options.ext ? self.tryAppendExtension(fullFilename, options.ext) : fullFilename;
  482. if (extFilename !== fullFilename && !explicit && paths[i] === '.') {
  483. try {
  484. fullFilename = require.resolve(extFilename);
  485. isNodeModule = true;
  486. } catch (e) {
  487. filenamesTried.push(npmPrefix + extFilename);
  488. fullFilename = extFilename;
  489. }
  490. } else {
  491. fullFilename = extFilename;
  492. }
  493. }
  494. var modified = false;
  495. if (self.contents[fullFilename]) {
  496. try {
  497. var stat = fs$1.statSync.apply(this, [fullFilename]);
  498. if (stat.mtime.getTime() === self.contents[fullFilename].mtime.getTime()) {
  499. fulfill({
  500. contents: self.contents[fullFilename].data,
  501. filename: fullFilename
  502. });
  503. } else {
  504. modified = true;
  505. }
  506. } catch (e) {
  507. modified = true;
  508. }
  509. }
  510. if (modified || !self.contents[fullFilename]) {
  511. var readFileArgs = [fullFilename];
  512. if (!options.rawBuffer) {
  513. readFileArgs.push('utf-8');
  514. }
  515. if (options.syncImport) {
  516. try {
  517. var data = fs$1.readFileSync.apply(this, readFileArgs);
  518. var stat = fs$1.statSync.apply(this, [fullFilename]);
  519. self.contents[fullFilename] = {
  520. data,
  521. mtime: stat.mtime
  522. };
  523. fulfill({
  524. contents: data,
  525. filename: fullFilename
  526. });
  527. } catch (e) {
  528. filenamesTried.push(isNodeModule ? npmPrefix + fullFilename : fullFilename);
  529. return tryPrefix(j + 1);
  530. }
  531. } else {
  532. readFileArgs.push(function (e, data) {
  533. if (e) {
  534. filenamesTried.push(isNodeModule ? npmPrefix + fullFilename : fullFilename);
  535. return tryPrefix(j + 1);
  536. }
  537. var stat = fs$1.statSync.apply(this, [fullFilename]);
  538. self.contents[fullFilename] = {
  539. data,
  540. mtime: stat.mtime
  541. };
  542. fulfill({
  543. contents: data,
  544. filename: fullFilename
  545. });
  546. });
  547. fs$1.readFile.apply(this, readFileArgs);
  548. }
  549. }
  550. } else {
  551. tryPathIndex(i + 1);
  552. }
  553. })(0);
  554. } else {
  555. reject({
  556. type: 'File',
  557. message: `'${filename}' wasn't found. Tried - ${filenamesTried.join(',')}`
  558. });
  559. }
  560. })(0);
  561. }
  562. }
  563. }, {
  564. key: "loadFileSync",
  565. value: function loadFileSync(filename, currentDirectory, options, environment) {
  566. options.syncImport = true;
  567. return this.loadFile(filename, currentDirectory, options, environment);
  568. }
  569. }]);
  570. return FileManager;
  571. }(AbstractFileManager);
  572. var logger = {
  573. error: function error(msg) {
  574. this._fireEvent('error', msg);
  575. },
  576. warn: function warn(msg) {
  577. this._fireEvent('warn', msg);
  578. },
  579. info: function info(msg) {
  580. this._fireEvent('info', msg);
  581. },
  582. debug: function debug(msg) {
  583. this._fireEvent('debug', msg);
  584. },
  585. addListener: function addListener(listener) {
  586. this._listeners.push(listener);
  587. },
  588. removeListener: function removeListener(listener) {
  589. for (var i = 0; i < this._listeners.length; i++) {
  590. if (this._listeners[i] === listener) {
  591. this._listeners.splice(i, 1);
  592. return;
  593. }
  594. }
  595. },
  596. _fireEvent: function _fireEvent(type, msg) {
  597. for (var i = 0; i < this._listeners.length; i++) {
  598. var logFunction = this._listeners[i][type];
  599. if (logFunction) {
  600. logFunction(msg);
  601. }
  602. }
  603. },
  604. _listeners: []
  605. };
  606. var isUrlRe = /^(?:https?:)?\/\//i;
  607. var request;
  608. var UrlFileManager =
  609. /*#__PURE__*/
  610. function (_AbstractFileManager) {
  611. _inherits(UrlFileManager, _AbstractFileManager);
  612. function UrlFileManager() {
  613. _classCallCheck(this, UrlFileManager);
  614. return _possibleConstructorReturn(this, _getPrototypeOf(UrlFileManager).apply(this, arguments));
  615. }
  616. _createClass(UrlFileManager, [{
  617. key: "supports",
  618. value: function supports(filename, currentDirectory, options, environment) {
  619. return isUrlRe.test(filename) || isUrlRe.test(currentDirectory);
  620. }
  621. }, {
  622. key: "loadFile",
  623. value: function loadFile(filename, currentDirectory, options, environment) {
  624. return new Promise(function (fulfill, reject) {
  625. if (request === undefined) {
  626. try {
  627. request = require('request');
  628. } catch (e) {
  629. request = null;
  630. }
  631. }
  632. if (!request) {
  633. reject({
  634. type: 'File',
  635. message: 'optional dependency \'request\' required to import over http(s)\n'
  636. });
  637. return;
  638. }
  639. var urlStr = isUrlRe.test(filename) ? filename : url.resolve(currentDirectory, filename);
  640. var urlObj = url.parse(urlStr);
  641. if (!urlObj.protocol) {
  642. urlObj.protocol = 'http';
  643. urlStr = urlObj.format();
  644. }
  645. request.get({
  646. uri: urlStr,
  647. strictSSL: !options.insecure
  648. }, function (error, res, body) {
  649. if (error) {
  650. reject({
  651. type: 'File',
  652. message: `resource '${urlStr}' gave this Error:\n ${error}\n`
  653. });
  654. return;
  655. }
  656. if (res && res.statusCode === 404) {
  657. reject({
  658. type: 'File',
  659. message: `resource '${urlStr}' was not found\n`
  660. });
  661. return;
  662. }
  663. if (!body) {
  664. logger.warn(`Warning: Empty body (HTTP ${res.statusCode}) returned by "${urlStr}"`);
  665. }
  666. fulfill({
  667. contents: body,
  668. filename: urlStr
  669. });
  670. });
  671. });
  672. }
  673. }]);
  674. return UrlFileManager;
  675. }(AbstractFileManager);
  676. var colors = {
  677. 'aliceblue': '#f0f8ff',
  678. 'antiquewhite': '#faebd7',
  679. 'aqua': '#00ffff',
  680. 'aquamarine': '#7fffd4',
  681. 'azure': '#f0ffff',
  682. 'beige': '#f5f5dc',
  683. 'bisque': '#ffe4c4',
  684. 'black': '#000000',
  685. 'blanchedalmond': '#ffebcd',
  686. 'blue': '#0000ff',
  687. 'blueviolet': '#8a2be2',
  688. 'brown': '#a52a2a',
  689. 'burlywood': '#deb887',
  690. 'cadetblue': '#5f9ea0',
  691. 'chartreuse': '#7fff00',
  692. 'chocolate': '#d2691e',
  693. 'coral': '#ff7f50',
  694. 'cornflowerblue': '#6495ed',
  695. 'cornsilk': '#fff8dc',
  696. 'crimson': '#dc143c',
  697. 'cyan': '#00ffff',
  698. 'darkblue': '#00008b',
  699. 'darkcyan': '#008b8b',
  700. 'darkgoldenrod': '#b8860b',
  701. 'darkgray': '#a9a9a9',
  702. 'darkgrey': '#a9a9a9',
  703. 'darkgreen': '#006400',
  704. 'darkkhaki': '#bdb76b',
  705. 'darkmagenta': '#8b008b',
  706. 'darkolivegreen': '#556b2f',
  707. 'darkorange': '#ff8c00',
  708. 'darkorchid': '#9932cc',
  709. 'darkred': '#8b0000',
  710. 'darksalmon': '#e9967a',
  711. 'darkseagreen': '#8fbc8f',
  712. 'darkslateblue': '#483d8b',
  713. 'darkslategray': '#2f4f4f',
  714. 'darkslategrey': '#2f4f4f',
  715. 'darkturquoise': '#00ced1',
  716. 'darkviolet': '#9400d3',
  717. 'deeppink': '#ff1493',
  718. 'deepskyblue': '#00bfff',
  719. 'dimgray': '#696969',
  720. 'dimgrey': '#696969',
  721. 'dodgerblue': '#1e90ff',
  722. 'firebrick': '#b22222',
  723. 'floralwhite': '#fffaf0',
  724. 'forestgreen': '#228b22',
  725. 'fuchsia': '#ff00ff',
  726. 'gainsboro': '#dcdcdc',
  727. 'ghostwhite': '#f8f8ff',
  728. 'gold': '#ffd700',
  729. 'goldenrod': '#daa520',
  730. 'gray': '#808080',
  731. 'grey': '#808080',
  732. 'green': '#008000',
  733. 'greenyellow': '#adff2f',
  734. 'honeydew': '#f0fff0',
  735. 'hotpink': '#ff69b4',
  736. 'indianred': '#cd5c5c',
  737. 'indigo': '#4b0082',
  738. 'ivory': '#fffff0',
  739. 'khaki': '#f0e68c',
  740. 'lavender': '#e6e6fa',
  741. 'lavenderblush': '#fff0f5',
  742. 'lawngreen': '#7cfc00',
  743. 'lemonchiffon': '#fffacd',
  744. 'lightblue': '#add8e6',
  745. 'lightcoral': '#f08080',
  746. 'lightcyan': '#e0ffff',
  747. 'lightgoldenrodyellow': '#fafad2',
  748. 'lightgray': '#d3d3d3',
  749. 'lightgrey': '#d3d3d3',
  750. 'lightgreen': '#90ee90',
  751. 'lightpink': '#ffb6c1',
  752. 'lightsalmon': '#ffa07a',
  753. 'lightseagreen': '#20b2aa',
  754. 'lightskyblue': '#87cefa',
  755. 'lightslategray': '#778899',
  756. 'lightslategrey': '#778899',
  757. 'lightsteelblue': '#b0c4de',
  758. 'lightyellow': '#ffffe0',
  759. 'lime': '#00ff00',
  760. 'limegreen': '#32cd32',
  761. 'linen': '#faf0e6',
  762. 'magenta': '#ff00ff',
  763. 'maroon': '#800000',
  764. 'mediumaquamarine': '#66cdaa',
  765. 'mediumblue': '#0000cd',
  766. 'mediumorchid': '#ba55d3',
  767. 'mediumpurple': '#9370d8',
  768. 'mediumseagreen': '#3cb371',
  769. 'mediumslateblue': '#7b68ee',
  770. 'mediumspringgreen': '#00fa9a',
  771. 'mediumturquoise': '#48d1cc',
  772. 'mediumvioletred': '#c71585',
  773. 'midnightblue': '#191970',
  774. 'mintcream': '#f5fffa',
  775. 'mistyrose': '#ffe4e1',
  776. 'moccasin': '#ffe4b5',
  777. 'navajowhite': '#ffdead',
  778. 'navy': '#000080',
  779. 'oldlace': '#fdf5e6',
  780. 'olive': '#808000',
  781. 'olivedrab': '#6b8e23',
  782. 'orange': '#ffa500',
  783. 'orangered': '#ff4500',
  784. 'orchid': '#da70d6',
  785. 'palegoldenrod': '#eee8aa',
  786. 'palegreen': '#98fb98',
  787. 'paleturquoise': '#afeeee',
  788. 'palevioletred': '#d87093',
  789. 'papayawhip': '#ffefd5',
  790. 'peachpuff': '#ffdab9',
  791. 'peru': '#cd853f',
  792. 'pink': '#ffc0cb',
  793. 'plum': '#dda0dd',
  794. 'powderblue': '#b0e0e6',
  795. 'purple': '#800080',
  796. 'rebeccapurple': '#663399',
  797. 'red': '#ff0000',
  798. 'rosybrown': '#bc8f8f',
  799. 'royalblue': '#4169e1',
  800. 'saddlebrown': '#8b4513',
  801. 'salmon': '#fa8072',
  802. 'sandybrown': '#f4a460',
  803. 'seagreen': '#2e8b57',
  804. 'seashell': '#fff5ee',
  805. 'sienna': '#a0522d',
  806. 'silver': '#c0c0c0',
  807. 'skyblue': '#87ceeb',
  808. 'slateblue': '#6a5acd',
  809. 'slategray': '#708090',
  810. 'slategrey': '#708090',
  811. 'snow': '#fffafa',
  812. 'springgreen': '#00ff7f',
  813. 'steelblue': '#4682b4',
  814. 'tan': '#d2b48c',
  815. 'teal': '#008080',
  816. 'thistle': '#d8bfd8',
  817. 'tomato': '#ff6347',
  818. 'turquoise': '#40e0d0',
  819. 'violet': '#ee82ee',
  820. 'wheat': '#f5deb3',
  821. 'white': '#ffffff',
  822. 'whitesmoke': '#f5f5f5',
  823. 'yellow': '#ffff00',
  824. 'yellowgreen': '#9acd32'
  825. };
  826. var unitConversions = {
  827. length: {
  828. 'm': 1,
  829. 'cm': 0.01,
  830. 'mm': 0.001,
  831. 'in': 0.0254,
  832. 'px': 0.0254 / 96,
  833. 'pt': 0.0254 / 72,
  834. 'pc': 0.0254 / 72 * 12
  835. },
  836. duration: {
  837. 's': 1,
  838. 'ms': 0.001
  839. },
  840. angle: {
  841. 'rad': 1 / (2 * Math.PI),
  842. 'deg': 1 / 360,
  843. 'grad': 1 / 400,
  844. 'turn': 1
  845. }
  846. };
  847. var data = {
  848. colors,
  849. unitConversions
  850. };
  851. var Node =
  852. /*#__PURE__*/
  853. function () {
  854. function Node() {
  855. _classCallCheck(this, Node);
  856. this.parent = null;
  857. this.visibilityBlocks = undefined;
  858. this.nodeVisible = undefined;
  859. this.rootNode = null;
  860. this.parsed = null;
  861. var self = this;
  862. Object.defineProperty(this, 'currentFileInfo', {
  863. get: function get() {
  864. return self.fileInfo();
  865. }
  866. });
  867. Object.defineProperty(this, 'index', {
  868. get: function get() {
  869. return self.getIndex();
  870. }
  871. });
  872. }
  873. _createClass(Node, [{
  874. key: "setParent",
  875. value: function setParent(nodes, parent) {
  876. function set(node) {
  877. if (node && node instanceof Node) {
  878. node.parent = parent;
  879. }
  880. }
  881. if (Array.isArray(nodes)) {
  882. nodes.forEach(set);
  883. } else {
  884. set(nodes);
  885. }
  886. }
  887. }, {
  888. key: "getIndex",
  889. value: function getIndex() {
  890. return this._index || this.parent && this.parent.getIndex() || 0;
  891. }
  892. }, {
  893. key: "fileInfo",
  894. value: function fileInfo() {
  895. return this._fileInfo || this.parent && this.parent.fileInfo() || {};
  896. }
  897. }, {
  898. key: "isRulesetLike",
  899. value: function isRulesetLike() {
  900. return false;
  901. }
  902. }, {
  903. key: "toCSS",
  904. value: function toCSS(context) {
  905. var strs = [];
  906. this.genCSS(context, {
  907. add: function add(chunk, fileInfo, index) {
  908. strs.push(chunk);
  909. },
  910. isEmpty: function isEmpty() {
  911. return strs.length === 0;
  912. }
  913. });
  914. return strs.join('');
  915. }
  916. }, {
  917. key: "genCSS",
  918. value: function genCSS(context, output) {
  919. output.add(this.value);
  920. }
  921. }, {
  922. key: "accept",
  923. value: function accept(visitor) {
  924. this.value = visitor.visit(this.value);
  925. }
  926. }, {
  927. key: "eval",
  928. value: function _eval() {
  929. return this;
  930. }
  931. }, {
  932. key: "_operate",
  933. value: function _operate(context, op, a, b) {
  934. switch (op) {
  935. case '+':
  936. return a + b;
  937. case '-':
  938. return a - b;
  939. case '*':
  940. return a * b;
  941. case '/':
  942. return a / b;
  943. }
  944. }
  945. }, {
  946. key: "fround",
  947. value: function fround(context, value) {
  948. var precision = context && context.numPrecision; // add "epsilon" to ensure numbers like 1.000000005 (represented as 1.000000004999...) are properly rounded:
  949. return precision ? Number((value + 2e-16).toFixed(precision)) : value;
  950. } // Returns true if this node represents root of ast imported by reference
  951. }, {
  952. key: "blocksVisibility",
  953. value: function blocksVisibility() {
  954. if (this.visibilityBlocks == null) {
  955. this.visibilityBlocks = 0;
  956. }
  957. return this.visibilityBlocks !== 0;
  958. }
  959. }, {
  960. key: "addVisibilityBlock",
  961. value: function addVisibilityBlock() {
  962. if (this.visibilityBlocks == null) {
  963. this.visibilityBlocks = 0;
  964. }
  965. this.visibilityBlocks = this.visibilityBlocks + 1;
  966. }
  967. }, {
  968. key: "removeVisibilityBlock",
  969. value: function removeVisibilityBlock() {
  970. if (this.visibilityBlocks == null) {
  971. this.visibilityBlocks = 0;
  972. }
  973. this.visibilityBlocks = this.visibilityBlocks - 1;
  974. } // Turns on node visibility - if called node will be shown in output regardless
  975. // of whether it comes from import by reference or not
  976. }, {
  977. key: "ensureVisibility",
  978. value: function ensureVisibility() {
  979. this.nodeVisible = true;
  980. } // Turns off node visibility - if called node will NOT be shown in output regardless
  981. // of whether it comes from import by reference or not
  982. }, {
  983. key: "ensureInvisibility",
  984. value: function ensureInvisibility() {
  985. this.nodeVisible = false;
  986. } // return values:
  987. // false - the node must not be visible
  988. // true - the node must be visible
  989. // undefined or null - the node has the same visibility as its parent
  990. }, {
  991. key: "isVisible",
  992. value: function isVisible() {
  993. return this.nodeVisible;
  994. }
  995. }, {
  996. key: "visibilityInfo",
  997. value: function visibilityInfo() {
  998. return {
  999. visibilityBlocks: this.visibilityBlocks,
  1000. nodeVisible: this.nodeVisible
  1001. };
  1002. }
  1003. }, {
  1004. key: "copyVisibilityInfo",
  1005. value: function copyVisibilityInfo(info) {
  1006. if (!info) {
  1007. return;
  1008. }
  1009. this.visibilityBlocks = info.visibilityBlocks;
  1010. this.nodeVisible = info.nodeVisible;
  1011. }
  1012. }]);
  1013. return Node;
  1014. }();
  1015. Node.compare = function (a, b) {
  1016. /* returns:
  1017. -1: a < b
  1018. 0: a = b
  1019. 1: a > b
  1020. and *any* other value for a != b (e.g. undefined, NaN, -2 etc.) */
  1021. if (a.compare && // for "symmetric results" force toCSS-based comparison
  1022. // of Quoted or Anonymous if either value is one of those
  1023. !(b.type === 'Quoted' || b.type === 'Anonymous')) {
  1024. return a.compare(b);
  1025. } else if (b.compare) {
  1026. return -b.compare(a);
  1027. } else if (a.type !== b.type) {
  1028. return undefined;
  1029. }
  1030. a = a.value;
  1031. b = b.value;
  1032. if (!Array.isArray(a)) {
  1033. return a === b ? 0 : undefined;
  1034. }
  1035. if (a.length !== b.length) {
  1036. return undefined;
  1037. }
  1038. for (var i = 0; i < a.length; i++) {
  1039. if (Node.compare(a[i], b[i]) !== 0) {
  1040. return undefined;
  1041. }
  1042. }
  1043. return 0;
  1044. };
  1045. Node.numericCompare = function (a, b) {
  1046. return a < b ? -1 : a === b ? 0 : a > b ? 1 : undefined;
  1047. };
  1048. // RGB Colors - #ff0014, #eee
  1049. //
  1050. var Color =
  1051. /*#__PURE__*/
  1052. function (_Node) {
  1053. _inherits(Color, _Node);
  1054. function Color(rgb, a, originalForm) {
  1055. var _this;
  1056. _classCallCheck(this, Color);
  1057. _this = _possibleConstructorReturn(this, _getPrototypeOf(Color).call(this));
  1058. var self = _assertThisInitialized(_this); //
  1059. // The end goal here, is to parse the arguments
  1060. // into an integer triplet, such as `128, 255, 0`
  1061. //
  1062. // This facilitates operations and conversions.
  1063. //
  1064. if (Array.isArray(rgb)) {
  1065. _this.rgb = rgb;
  1066. } else if (rgb.length >= 6) {
  1067. _this.rgb = [];
  1068. rgb.match(/.{2}/g).map(function (c, i) {
  1069. if (i < 3) {
  1070. self.rgb.push(parseInt(c, 16));
  1071. } else {
  1072. self.alpha = parseInt(c, 16) / 255;
  1073. }
  1074. });
  1075. } else {
  1076. _this.rgb = [];
  1077. rgb.split('').map(function (c, i) {
  1078. if (i < 3) {
  1079. self.rgb.push(parseInt(c + c, 16));
  1080. } else {
  1081. self.alpha = parseInt(c + c, 16) / 255;
  1082. }
  1083. });
  1084. }
  1085. _this.alpha = _this.alpha || (typeof a === 'number' ? a : 1);
  1086. if (typeof originalForm !== 'undefined') {
  1087. _this.value = originalForm;
  1088. }
  1089. return _this;
  1090. }
  1091. _createClass(Color, [{
  1092. key: "luma",
  1093. value: function luma() {
  1094. var r = this.rgb[0] / 255;
  1095. var g = this.rgb[1] / 255;
  1096. var b = this.rgb[2] / 255;
  1097. r = r <= 0.03928 ? r / 12.92 : Math.pow((r + 0.055) / 1.055, 2.4);
  1098. g = g <= 0.03928 ? g / 12.92 : Math.pow((g + 0.055) / 1.055, 2.4);
  1099. b = b <= 0.03928 ? b / 12.92 : Math.pow((b + 0.055) / 1.055, 2.4);
  1100. return 0.2126 * r + 0.7152 * g + 0.0722 * b;
  1101. }
  1102. }, {
  1103. key: "genCSS",
  1104. value: function genCSS(context, output) {
  1105. output.add(this.toCSS(context));
  1106. }
  1107. }, {
  1108. key: "toCSS",
  1109. value: function toCSS(context, doNotCompress) {
  1110. var compress = context && context.compress && !doNotCompress;
  1111. var color;
  1112. var alpha;
  1113. var colorFunction;
  1114. var args = []; // `value` is set if this color was originally
  1115. // converted from a named color string so we need
  1116. // to respect this and try to output named color too.
  1117. alpha = this.fround(context, this.alpha);
  1118. if (this.value) {
  1119. if (this.value.indexOf('rgb') === 0) {
  1120. if (alpha < 1) {
  1121. colorFunction = 'rgba';
  1122. }
  1123. } else if (this.value.indexOf('hsl') === 0) {
  1124. if (alpha < 1) {
  1125. colorFunction = 'hsla';
  1126. } else {
  1127. colorFunction = 'hsl';
  1128. }
  1129. } else {
  1130. return this.value;
  1131. }
  1132. } else {
  1133. if (alpha < 1) {
  1134. colorFunction = 'rgba';
  1135. }
  1136. }
  1137. switch (colorFunction) {
  1138. case 'rgba':
  1139. args = this.rgb.map(function (c) {
  1140. return clamp(Math.round(c), 255);
  1141. }).concat(clamp(alpha, 1));
  1142. break;
  1143. case 'hsla':
  1144. args.push(clamp(alpha, 1));
  1145. case 'hsl':
  1146. color = this.toHSL();
  1147. args = [this.fround(context, color.h), `${this.fround(context, color.s * 100)}%`, `${this.fround(context, color.l * 100)}%`].concat(args);
  1148. }
  1149. if (colorFunction) {
  1150. // Values are capped between `0` and `255`, rounded and zero-padded.
  1151. return `${colorFunction}(${args.join(`,${compress ? '' : ' '}`)})`;
  1152. }
  1153. color = this.toRGB();
  1154. if (compress) {
  1155. var splitcolor = color.split(''); // Convert color to short format
  1156. if (splitcolor[1] === splitcolor[2] && splitcolor[3] === splitcolor[4] && splitcolor[5] === splitcolor[6]) {
  1157. color = `#${splitcolor[1]}${splitcolor[3]}${splitcolor[5]}`;
  1158. }
  1159. }
  1160. return color;
  1161. } //
  1162. // Operations have to be done per-channel, if not,
  1163. // channels will spill onto each other. Once we have
  1164. // our result, in the form of an integer triplet,
  1165. // we create a new Color node to hold the result.
  1166. //
  1167. }, {
  1168. key: "operate",
  1169. value: function operate(context, op, other) {
  1170. var rgb = new Array(3);
  1171. var alpha = this.alpha * (1 - other.alpha) + other.alpha;
  1172. for (var c = 0; c < 3; c++) {
  1173. rgb[c] = this._operate(context, op, this.rgb[c], other.rgb[c]);
  1174. }
  1175. return new Color(rgb, alpha);
  1176. }
  1177. }, {
  1178. key: "toRGB",
  1179. value: function toRGB() {
  1180. return toHex(this.rgb);
  1181. }
  1182. }, {
  1183. key: "toHSL",
  1184. value: function toHSL() {
  1185. var r = this.rgb[0] / 255;
  1186. var g = this.rgb[1] / 255;
  1187. var b = this.rgb[2] / 255;
  1188. var a = this.alpha;
  1189. var max = Math.max(r, g, b);
  1190. var min = Math.min(r, g, b);
  1191. var h;
  1192. var s;
  1193. var l = (max + min) / 2;
  1194. var d = max - min;
  1195. if (max === min) {
  1196. h = s = 0;
  1197. } else {
  1198. s = l > 0.5 ? d / (2 - max - min) : d / (max + min);
  1199. switch (max) {
  1200. case r:
  1201. h = (g - b) / d + (g < b ? 6 : 0);
  1202. break;
  1203. case g:
  1204. h = (b - r) / d + 2;
  1205. break;
  1206. case b:
  1207. h = (r - g) / d + 4;
  1208. break;
  1209. }
  1210. h /= 6;
  1211. }
  1212. return {
  1213. h: h * 360,
  1214. s,
  1215. l,
  1216. a
  1217. };
  1218. } // Adapted from http://mjijackson.com/2008/02/rgb-to-hsl-and-rgb-to-hsv-color-model-conversion-algorithms-in-javascript
  1219. }, {
  1220. key: "toHSV",
  1221. value: function toHSV() {
  1222. var r = this.rgb[0] / 255;
  1223. var g = this.rgb[1] / 255;
  1224. var b = this.rgb[2] / 255;
  1225. var a = this.alpha;
  1226. var max = Math.max(r, g, b);
  1227. var min = Math.min(r, g, b);
  1228. var h;
  1229. var s;
  1230. var v = max;
  1231. var d = max - min;
  1232. if (max === 0) {
  1233. s = 0;
  1234. } else {
  1235. s = d / max;
  1236. }
  1237. if (max === min) {
  1238. h = 0;
  1239. } else {
  1240. switch (max) {
  1241. case r:
  1242. h = (g - b) / d + (g < b ? 6 : 0);
  1243. break;
  1244. case g:
  1245. h = (b - r) / d + 2;
  1246. break;
  1247. case b:
  1248. h = (r - g) / d + 4;
  1249. break;
  1250. }
  1251. h /= 6;
  1252. }
  1253. return {
  1254. h: h * 360,
  1255. s,
  1256. v,
  1257. a
  1258. };
  1259. }
  1260. }, {
  1261. key: "toARGB",
  1262. value: function toARGB() {
  1263. return toHex([this.alpha * 255].concat(this.rgb));
  1264. }
  1265. }, {
  1266. key: "compare",
  1267. value: function compare(x) {
  1268. return x.rgb && x.rgb[0] === this.rgb[0] && x.rgb[1] === this.rgb[1] && x.rgb[2] === this.rgb[2] && x.alpha === this.alpha ? 0 : undefined;
  1269. }
  1270. }]);
  1271. return Color;
  1272. }(Node);
  1273. Color.prototype.type = 'Color';
  1274. function clamp(v, max) {
  1275. return Math.min(Math.max(v, 0), max);
  1276. }
  1277. function toHex(v) {
  1278. return `#${v.map(function (c) {
  1279. c = clamp(Math.round(c), 255);
  1280. return (c < 16 ? '0' : '') + c.toString(16);
  1281. }).join('')}`;
  1282. }
  1283. Color.fromKeyword = function (keyword) {
  1284. var c;
  1285. var key = keyword.toLowerCase();
  1286. if (colors.hasOwnProperty(key)) {
  1287. c = new Color(colors[key].slice(1));
  1288. } else if (key === 'transparent') {
  1289. c = new Color([0, 0, 0], 0);
  1290. }
  1291. if (c) {
  1292. c.value = keyword;
  1293. return c;
  1294. }
  1295. };
  1296. var Paren =
  1297. /*#__PURE__*/
  1298. function (_Node) {
  1299. _inherits(Paren, _Node);
  1300. function Paren(node) {
  1301. var _this;
  1302. _classCallCheck(this, Paren);
  1303. _this = _possibleConstructorReturn(this, _getPrototypeOf(Paren).call(this));
  1304. _this.value = node;
  1305. return _this;
  1306. }
  1307. _createClass(Paren, [{
  1308. key: "genCSS",
  1309. value: function genCSS(context, output) {
  1310. output.add('(');
  1311. this.value.genCSS(context, output);
  1312. output.add(')');
  1313. }
  1314. }, {
  1315. key: "eval",
  1316. value: function _eval(context) {
  1317. return new Paren(this.value.eval(context));
  1318. }
  1319. }]);
  1320. return Paren;
  1321. }(Node);
  1322. Paren.prototype.type = 'Paren';
  1323. var _noSpaceCombinators = {
  1324. '': true,
  1325. ' ': true,
  1326. '|': true
  1327. };
  1328. var Combinator =
  1329. /*#__PURE__*/
  1330. function (_Node) {
  1331. _inherits(Combinator, _Node);
  1332. function Combinator(value) {
  1333. var _this;
  1334. _classCallCheck(this, Combinator);
  1335. _this = _possibleConstructorReturn(this, _getPrototypeOf(Combinator).call(this));
  1336. if (value === ' ') {
  1337. _this.value = ' ';
  1338. _this.emptyOrWhitespace = true;
  1339. } else {
  1340. _this.value = value ? value.trim() : '';
  1341. _this.emptyOrWhitespace = _this.value === '';
  1342. }
  1343. return _this;
  1344. }
  1345. _createClass(Combinator, [{
  1346. key: "genCSS",
  1347. value: function genCSS(context, output) {
  1348. var spaceOrEmpty = context.compress || _noSpaceCombinators[this.value] ? '' : ' ';
  1349. output.add(spaceOrEmpty + this.value + spaceOrEmpty);
  1350. }
  1351. }]);
  1352. return Combinator;
  1353. }(Node);
  1354. Combinator.prototype.type = 'Combinator';
  1355. var Element =
  1356. /*#__PURE__*/
  1357. function (_Node) {
  1358. _inherits(Element, _Node);
  1359. function Element(combinator, value, isVariable, index, currentFileInfo, visibilityInfo) {
  1360. var _this;
  1361. _classCallCheck(this, Element);
  1362. _this = _possibleConstructorReturn(this, _getPrototypeOf(Element).call(this));
  1363. _this.combinator = combinator instanceof Combinator ? combinator : new Combinator(combinator);
  1364. if (typeof value === 'string') {
  1365. _this.value = value.trim();
  1366. } else if (value) {
  1367. _this.value = value;
  1368. } else {
  1369. _this.value = '';
  1370. }
  1371. _this.isVariable = isVariable;
  1372. _this._index = index;
  1373. _this._fileInfo = currentFileInfo;
  1374. _this.copyVisibilityInfo(visibilityInfo);
  1375. _this.setParent(_this.combinator, _assertThisInitialized(_this));
  1376. return _this;
  1377. }
  1378. _createClass(Element, [{
  1379. key: "accept",
  1380. value: function accept(visitor) {
  1381. var value = this.value;
  1382. this.combinator = visitor.visit(this.combinator);
  1383. if (typeof value === 'object') {
  1384. this.value = visitor.visit(value);
  1385. }
  1386. }
  1387. }, {
  1388. key: "eval",
  1389. value: function _eval(context) {
  1390. return new Element(this.combinator, this.value.eval ? this.value.eval(context) : this.value, this.isVariable, this.getIndex(), this.fileInfo(), this.visibilityInfo());
  1391. }
  1392. }, {
  1393. key: "clone",
  1394. value: function clone() {
  1395. return new Element(this.combinator, this.value, this.isVariable, this.getIndex(), this.fileInfo(), this.visibilityInfo());
  1396. }
  1397. }, {
  1398. key: "genCSS",
  1399. value: function genCSS(context, output) {
  1400. output.add(this.toCSS(context), this.fileInfo(), this.getIndex());
  1401. }
  1402. }, {
  1403. key: "toCSS",
  1404. value: function toCSS() {
  1405. var context = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};
  1406. var value = this.value;
  1407. var firstSelector = context.firstSelector;
  1408. if (value instanceof Paren) {
  1409. // selector in parens should not be affected by outer selector
  1410. // flags (breaks only interpolated selectors - see #1973)
  1411. context.firstSelector = true;
  1412. }
  1413. value = value.toCSS ? value.toCSS(context) : value;
  1414. context.firstSelector = firstSelector;
  1415. if (value === '' && this.combinator.value.charAt(0) === '&') {
  1416. return '';
  1417. } else {
  1418. return this.combinator.toCSS(context) + value;
  1419. }
  1420. }
  1421. }]);
  1422. return Element;
  1423. }(Node);
  1424. Element.prototype.type = 'Element';
  1425. /**
  1426. * This is a centralized class of any error that could be thrown internally (mostly by the parser).
  1427. * Besides standard .message it keeps some additional data like a path to the file where the error
  1428. * occurred along with line and column numbers.
  1429. *
  1430. * @class
  1431. * @extends Error
  1432. * @type {module.LessError}
  1433. *
  1434. * @prop {string} type
  1435. * @prop {string} filename
  1436. * @prop {number} index
  1437. * @prop {number} line
  1438. * @prop {number} column
  1439. * @prop {number} callLine
  1440. * @prop {number} callExtract
  1441. * @prop {string[]} extract
  1442. *
  1443. * @param {Object} e - An error object to wrap around or just a descriptive object
  1444. * @param {Object} fileContentMap - An object with file contents in 'contents' property (like importManager) @todo - move to fileManager?
  1445. * @param {string} [currentFilename]
  1446. */
  1447. var LessError = function LessError(e, fileContentMap, currentFilename) {
  1448. Error.call(this);
  1449. var filename = e.filename || currentFilename;
  1450. this.message = e.message;
  1451. this.stack = e.stack;
  1452. if (fileContentMap && filename) {
  1453. var input = fileContentMap.contents[filename];
  1454. var loc = getLocation(e.index, input);
  1455. var line = loc.line;
  1456. var col = loc.column;
  1457. var callLine = e.call && getLocation(e.call, input).line;
  1458. var lines = input ? input.split('\n') : '';
  1459. this.type = e.type || 'Syntax';
  1460. this.filename = filename;
  1461. this.index = e.index;
  1462. this.line = typeof line === 'number' ? line + 1 : null;
  1463. this.column = col;
  1464. if (!this.line && this.stack) {
  1465. var found = this.stack.match(/(<anonymous>|Function):(\d+):(\d+)/);
  1466. if (found) {
  1467. if (found[2]) {
  1468. this.line = parseInt(found[2]) - 2;
  1469. }
  1470. if (found[3]) {
  1471. this.column = parseInt(found[3]);
  1472. }
  1473. }
  1474. }
  1475. this.callLine = callLine + 1;
  1476. this.callExtract = lines[callLine];
  1477. this.extract = [lines[this.line - 2], lines[this.line - 1], lines[this.line]];
  1478. }
  1479. };
  1480. if (typeof Object.create === 'undefined') {
  1481. var F = function F() {};
  1482. F.prototype = Error.prototype;
  1483. LessError.prototype = new F();
  1484. } else {
  1485. LessError.prototype = Object.create(Error.prototype);
  1486. }
  1487. LessError.prototype.constructor = LessError;
  1488. /**
  1489. * An overridden version of the default Object.prototype.toString
  1490. * which uses additional information to create a helpful message.
  1491. *
  1492. * @param {Object} options
  1493. * @returns {string}
  1494. */
  1495. LessError.prototype.toString = function () {
  1496. var options = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};
  1497. var message = '';
  1498. var extract = this.extract || [];
  1499. var error = [];
  1500. var stylize = function stylize(str) {
  1501. return str;
  1502. };
  1503. if (options.stylize) {
  1504. var type = typeof options.stylize;
  1505. if (type !== 'function') {
  1506. throw Error(`options.stylize should be a function, got a ${type}!`);
  1507. }
  1508. stylize = options.stylize;
  1509. }
  1510. if (this.line !== null) {
  1511. if (typeof extract[0] === 'string') {
  1512. error.push(stylize(`${this.line - 1} ${extract[0]}`, 'grey'));
  1513. }
  1514. if (typeof extract[1] === 'string') {
  1515. var errorTxt = `${this.line} `;
  1516. if (extract[1]) {
  1517. errorTxt += extract[1].slice(0, this.column) + stylize(stylize(stylize(extract[1].substr(this.column, 1), 'bold') + extract[1].slice(this.column + 1), 'red'), 'inverse');
  1518. }
  1519. error.push(errorTxt);
  1520. }
  1521. if (typeof extract[2] === 'string') {
  1522. error.push(stylize(`${this.line + 1} ${extract[2]}`, 'grey'));
  1523. }
  1524. error = `${error.join('\n') + stylize('', 'reset')}\n`;
  1525. }
  1526. message += stylize(`${this.type}Error: ${this.message}`, 'red');
  1527. if (this.filename) {
  1528. message += stylize(' in ', 'red') + this.filename;
  1529. }
  1530. if (this.line) {
  1531. message += stylize(` on line ${this.line}, column ${this.column + 1}:`, 'grey');
  1532. }
  1533. message += `\n${error}`;
  1534. if (this.callLine) {
  1535. message += `${stylize('from ', 'red') + (this.filename || '')}/n`;
  1536. message += `${stylize(this.callLine, 'grey')} ${this.callExtract}/n`;
  1537. }
  1538. return message;
  1539. };
  1540. var Selector =
  1541. /*#__PURE__*/
  1542. function (_Node) {
  1543. _inherits(Selector, _Node);
  1544. function Selector(elements, extendList, condition, index, currentFileInfo, visibilityInfo) {
  1545. var _this;
  1546. _classCallCheck(this, Selector);
  1547. _this = _possibleConstructorReturn(this, _getPrototypeOf(Selector).call(this));
  1548. _this.extendList = extendList;
  1549. _this.condition = condition;
  1550. _this.evaldCondition = !condition;
  1551. _this._index = index;
  1552. _this._fileInfo = currentFileInfo;
  1553. _this.elements = _this.getElements(elements);
  1554. _this.mixinElements_ = undefined;
  1555. _this.copyVisibilityInfo(visibilityInfo);
  1556. _this.setParent(_this.elements, _assertThisInitialized(_this));
  1557. return _this;
  1558. }
  1559. _createClass(Selector, [{
  1560. key: "accept",
  1561. value: function accept(visitor) {
  1562. if (this.elements) {
  1563. this.elements = visitor.visitArray(this.elements);
  1564. }
  1565. if (this.extendList) {
  1566. this.extendList = visitor.visitArray(this.extendList);
  1567. }
  1568. if (this.condition) {
  1569. this.condition = visitor.visit(this.condition);
  1570. }
  1571. }
  1572. }, {
  1573. key: "createDerived",
  1574. value: function createDerived(elements, extendList, evaldCondition) {
  1575. elements = this.getElements(elements);
  1576. var newSelector = new Selector(elements, extendList || this.extendList, null, this.getIndex(), this.fileInfo(), this.visibilityInfo());
  1577. newSelector.evaldCondition = evaldCondition != null ? evaldCondition : this.evaldCondition;
  1578. newSelector.mediaEmpty = this.mediaEmpty;
  1579. return newSelector;
  1580. }
  1581. }, {
  1582. key: "getElements",
  1583. value: function getElements(els) {
  1584. if (!els) {
  1585. return [new Element('', '&', false, this._index, this._fileInfo)];
  1586. }
  1587. if (typeof els === 'string') {
  1588. this.parse.parseNode(els, ['selector'], this._index, this._fileInfo, function (err, result) {
  1589. if (err) {
  1590. throw new LessError({
  1591. index: err.index,
  1592. message: err.message
  1593. }, this.parse.imports, this._fileInfo.filename);
  1594. }
  1595. els = result[0].elements;
  1596. });
  1597. }
  1598. return els;
  1599. }
  1600. }, {
  1601. key: "createEmptySelectors",
  1602. value: function createEmptySelectors() {
  1603. var el = new Element('', '&', false, this._index, this._fileInfo);
  1604. var sels = [new Selector([el], null, null, this._index, this._fileInfo)];
  1605. sels[0].mediaEmpty = true;
  1606. return sels;
  1607. }
  1608. }, {
  1609. key: "match",
  1610. value: function match(other) {
  1611. var elements = this.elements;
  1612. var len = elements.length;
  1613. var olen;
  1614. var i;
  1615. other = other.mixinElements();
  1616. olen = other.length;
  1617. if (olen === 0 || len < olen) {
  1618. return 0;
  1619. } else {
  1620. for (i = 0; i < olen; i++) {
  1621. if (elements[i].value !== other[i]) {
  1622. return 0;
  1623. }
  1624. }
  1625. }
  1626. return olen; // return number of matched elements
  1627. }
  1628. }, {
  1629. key: "mixinElements",
  1630. value: function mixinElements() {
  1631. if (this.mixinElements_) {
  1632. return this.mixinElements_;
  1633. }
  1634. var elements = this.elements.map(function (v) {
  1635. return v.combinator.value + (v.value.value || v.value);
  1636. }).join('').match(/[,&#\*\.\w-]([\w-]|(\\.))*/g);
  1637. if (elements) {
  1638. if (elements[0] === '&') {
  1639. elements.shift();
  1640. }
  1641. } else {
  1642. elements = [];
  1643. }
  1644. return this.mixinElements_ = elements;
  1645. }
  1646. }, {
  1647. key: "isJustParentSelector",
  1648. value: function isJustParentSelector() {
  1649. return !this.mediaEmpty && this.elements.length === 1 && this.elements[0].value === '&' && (this.elements[0].combinator.value === ' ' || this.elements[0].combinator.value === '');
  1650. }
  1651. }, {
  1652. key: "eval",
  1653. value: function _eval(context) {
  1654. var evaldCondition = this.condition && this.condition.eval(context);
  1655. var elements = this.elements;
  1656. var extendList = this.extendList;
  1657. elements = elements && elements.map(function (e) {
  1658. return e.eval(context);
  1659. });
  1660. extendList = extendList && extendList.map(function (extend) {
  1661. return extend.eval(context);
  1662. });
  1663. return this.createDerived(elements, extendList, evaldCondition);
  1664. }
  1665. }, {
  1666. key: "genCSS",
  1667. value: function genCSS(context, output) {
  1668. var i;
  1669. var element;
  1670. if ((!context || !context.firstSelector) && this.elements[0].combinator.value === '') {
  1671. output.add(' ', this.fileInfo(), this.getIndex());
  1672. }
  1673. for (i = 0; i < this.elements.length; i++) {
  1674. element = this.elements[i];
  1675. element.genCSS(context, output);
  1676. }
  1677. }
  1678. }, {
  1679. key: "getIsOutput",
  1680. value: function getIsOutput() {
  1681. return this.evaldCondition;
  1682. }
  1683. }]);
  1684. return Selector;
  1685. }(Node);
  1686. Selector.prototype.type = 'Selector';
  1687. var Value =
  1688. /*#__PURE__*/
  1689. function (_Node) {
  1690. _inherits(Value, _Node);
  1691. function Value(value) {
  1692. var _this;
  1693. _classCallCheck(this, Value);
  1694. _this = _possibleConstructorReturn(this, _getPrototypeOf(Value).call(this));
  1695. if (!value) {
  1696. throw new Error('Value requires an array argument');
  1697. }
  1698. if (!Array.isArray(value)) {
  1699. _this.value = [value];
  1700. } else {
  1701. _this.value = value;
  1702. }
  1703. return _this;
  1704. }
  1705. _createClass(Value, [{
  1706. key: "accept",
  1707. value: function accept(visitor) {
  1708. if (this.value) {
  1709. this.value = visitor.visitArray(this.value);
  1710. }
  1711. }
  1712. }, {
  1713. key: "eval",
  1714. value: function _eval(context) {
  1715. if (this.value.length === 1) {
  1716. return this.value[0].eval(context);
  1717. } else {
  1718. return new Value(this.value.map(function (v) {
  1719. return v.eval(context);
  1720. }));
  1721. }
  1722. }
  1723. }, {
  1724. key: "genCSS",
  1725. value: function genCSS(context, output) {
  1726. var i;
  1727. for (i = 0; i < this.value.length; i++) {
  1728. this.value[i].genCSS(context, output);
  1729. if (i + 1 < this.value.length) {
  1730. output.add(context && context.compress ? ',' : ', ');
  1731. }
  1732. }
  1733. }
  1734. }]);
  1735. return Value;
  1736. }(Node);
  1737. Value.prototype.type = 'Value';
  1738. var Keyword =
  1739. /*#__PURE__*/
  1740. function (_Node) {
  1741. _inherits(Keyword, _Node);
  1742. function Keyword(value) {
  1743. var _this;
  1744. _classCallCheck(this, Keyword);
  1745. _this = _possibleConstructorReturn(this, _getPrototypeOf(Keyword).call(this));
  1746. _this.value = value;
  1747. return _this;
  1748. }
  1749. _createClass(Keyword, [{
  1750. key: "genCSS",
  1751. value: function genCSS(context, output) {
  1752. if (this.value === '%') {
  1753. throw {
  1754. type: 'Syntax',
  1755. message: 'Invalid % without number'
  1756. };
  1757. }
  1758. output.add(this.value);
  1759. }
  1760. }]);
  1761. return Keyword;
  1762. }(Node);
  1763. Keyword.prototype.type = 'Keyword';
  1764. Keyword.True = new Keyword('true');
  1765. Keyword.False = new Keyword('false');
  1766. var Anonymous =
  1767. /*#__PURE__*/
  1768. function (_Node) {
  1769. _inherits(Anonymous, _Node);
  1770. function Anonymous(value, index, currentFileInfo, mapLines, rulesetLike, visibilityInfo) {
  1771. var _this;
  1772. _classCallCheck(this, Anonymous);
  1773. _this = _possibleConstructorReturn(this, _getPrototypeOf(Anonymous).call(this));
  1774. _this.value = value;
  1775. _this._index = index;
  1776. _this._fileInfo = currentFileInfo;
  1777. _this.mapLines = mapLines;
  1778. _this.rulesetLike = typeof rulesetLike === 'undefined' ? false : rulesetLike;
  1779. _this.allowRoot = true;
  1780. _this.copyVisibilityInfo(visibilityInfo);
  1781. return _this;
  1782. }
  1783. _createClass(Anonymous, [{
  1784. key: "eval",
  1785. value: function _eval() {
  1786. return new Anonymous(this.value, this._index, this._fileInfo, this.mapLines, this.rulesetLike, this.visibilityInfo());
  1787. }
  1788. }, {
  1789. key: "compare",
  1790. value: function compare(other) {
  1791. return other.toCSS && this.toCSS() === other.toCSS() ? 0 : undefined;
  1792. }
  1793. }, {
  1794. key: "isRulesetLike",
  1795. value: function isRulesetLike() {
  1796. return this.rulesetLike;
  1797. }
  1798. }, {
  1799. key: "genCSS",
  1800. value: function genCSS(context, output) {
  1801. this.nodeVisible = Boolean(this.value);
  1802. if (this.nodeVisible) {
  1803. output.add(this.value, this._fileInfo, this._index, this.mapLines);
  1804. }
  1805. }
  1806. }]);
  1807. return Anonymous;
  1808. }(Node);
  1809. Anonymous.prototype.type = 'Anonymous';
  1810. var MATH = Math$1;
  1811. var Declaration =
  1812. /*#__PURE__*/
  1813. function (_Node) {
  1814. _inherits(Declaration, _Node);
  1815. function Declaration(name, value, important, merge, index, currentFileInfo, inline, variable) {
  1816. var _this;
  1817. _classCallCheck(this, Declaration);
  1818. _this = _possibleConstructorReturn(this, _getPrototypeOf(Declaration).call(this));
  1819. _this.name = name;
  1820. _this.value = value instanceof Node ? value : new Value([value ? new Anonymous(value) : null]);
  1821. _this.important = important ? ` ${important.trim()}` : '';
  1822. _this.merge = merge;
  1823. _this._index = index;
  1824. _this._fileInfo = currentFileInfo;
  1825. _this.inline = inline || false;
  1826. _this.variable = variable !== undefined ? variable : name.charAt && name.charAt(0) === '@';
  1827. _this.allowRoot = true;
  1828. _this.setParent(_this.value, _assertThisInitialized(_this));
  1829. return _this;
  1830. }
  1831. _createClass(Declaration, [{
  1832. key: "genCSS",
  1833. value: function genCSS(context, output) {
  1834. output.add(this.name + (context.compress ? ':' : ': '), this.fileInfo(), this.getIndex());
  1835. try {
  1836. this.value.genCSS(context, output);
  1837. } catch (e) {
  1838. e.index = this._index;
  1839. e.filename = this._fileInfo.filename;
  1840. throw e;
  1841. }
  1842. output.add(this.important + (this.inline || context.lastRule && context.compress ? '' : ';'), this._fileInfo, this._index);
  1843. }
  1844. }, {
  1845. key: "eval",
  1846. value: function _eval(context) {
  1847. var mathBypass = false;
  1848. var prevMath;
  1849. var name = this.name;
  1850. var evaldValue;
  1851. var variable = this.variable;
  1852. if (typeof name !== 'string') {
  1853. // expand 'primitive' name directly to get
  1854. // things faster (~10% for benchmark.less):
  1855. name = name.length === 1 && name[0] instanceof Keyword ? name[0].value : evalName(context, name);
  1856. variable = false; // never treat expanded interpolation as new variable name
  1857. } // @todo remove when parens-division is default
  1858. if (name === 'font' && context.math === MATH.ALWAYS) {
  1859. mathBypass = true;
  1860. prevMath = context.math;
  1861. context.math = MATH.PARENS_DIVISION;
  1862. }
  1863. try {
  1864. context.importantScope.push({});
  1865. evaldValue = this.value.eval(context);
  1866. if (!this.variable && evaldValue.type === 'DetachedRuleset') {
  1867. throw {
  1868. message: 'Rulesets cannot be evaluated on a property.',
  1869. index: this.getIndex(),
  1870. filename: this.fileInfo().filename
  1871. };
  1872. }
  1873. var important = this.important;
  1874. var importantResult = context.importantScope.pop();
  1875. if (!important && importantResult.important) {
  1876. important = importantResult.important;
  1877. }
  1878. return new Declaration(name, evaldValue, important, this.merge, this.getIndex(), this.fileInfo(), this.inline, variable);
  1879. } catch (e) {
  1880. if (typeof e.index !== 'number') {
  1881. e.index = this.getIndex();
  1882. e.filename = this.fileInfo().filename;
  1883. }
  1884. throw e;
  1885. } finally {
  1886. if (mathBypass) {
  1887. context.math = prevMath;
  1888. }
  1889. }
  1890. }
  1891. }, {
  1892. key: "makeImportant",
  1893. value: function makeImportant() {
  1894. return new Declaration(this.name, this.value, '!important', this.merge, this.getIndex(), this.fileInfo(), this.inline);
  1895. }
  1896. }]);
  1897. return Declaration;
  1898. }(Node);
  1899. function evalName(context, name) {
  1900. var value = '';
  1901. var i;
  1902. var n = name.length;
  1903. var output = {
  1904. add: function add(s) {
  1905. value += s;
  1906. }
  1907. };
  1908. for (i = 0; i < n; i++) {
  1909. name[i].eval(context).genCSS(context, output);
  1910. }
  1911. return value;
  1912. }
  1913. Declaration.prototype.type = 'Declaration';
  1914. var debugInfo = function debugInfo(context, ctx, lineSeparator) {
  1915. var result = '';
  1916. if (context.dumpLineNumbers && !context.compress) {
  1917. switch (context.dumpLineNumbers) {
  1918. case 'comments':
  1919. result = debugInfo.asComment(ctx);
  1920. break;
  1921. case 'mediaquery':
  1922. result = debugInfo.asMediaQuery(ctx);
  1923. break;
  1924. case 'all':
  1925. result = debugInfo.asComment(ctx) + (lineSeparator || '') + debugInfo.asMediaQuery(ctx);
  1926. break;
  1927. }
  1928. }
  1929. return result;
  1930. };
  1931. debugInfo.asComment = function (ctx) {
  1932. return `/* line ${ctx.debugInfo.lineNumber}, ${ctx.debugInfo.fileName} */\n`;
  1933. };
  1934. debugInfo.asMediaQuery = function (ctx) {
  1935. var filenameWithProtocol = ctx.debugInfo.fileName;
  1936. if (!/^[a-z]+:\/\//i.test(filenameWithProtocol)) {
  1937. filenameWithProtocol = `file://${filenameWithProtocol}`;
  1938. }
  1939. return `@media -sass-debug-info{filename{font-family:${filenameWithProtocol.replace(/([.:\/\\])/g, function (a) {
  1940. if (a == '\\') {
  1941. a = '\/';
  1942. }
  1943. return `\\${a}`;
  1944. })}}line{font-family:\\00003${ctx.debugInfo.lineNumber}}}\n`;
  1945. };
  1946. var Comment =
  1947. /*#__PURE__*/
  1948. function (_Node) {
  1949. _inherits(Comment, _Node);
  1950. function Comment(value, isLineComment, index, currentFileInfo) {
  1951. var _this;
  1952. _classCallCheck(this, Comment);
  1953. _this = _possibleConstructorReturn(this, _getPrototypeOf(Comment).call(this));
  1954. _this.value = value;
  1955. _this.isLineComment = isLineComment;
  1956. _this._index = index;
  1957. _this._fileInfo = currentFileInfo;
  1958. _this.allowRoot = true;
  1959. return _this;
  1960. }
  1961. _createClass(Comment, [{
  1962. key: "genCSS",
  1963. value: function genCSS(context, output) {
  1964. if (this.debugInfo) {
  1965. output.add(debugInfo(context, this), this.fileInfo(), this.getIndex());
  1966. }
  1967. output.add(this.value);
  1968. }
  1969. }, {
  1970. key: "isSilent",
  1971. value: function isSilent(context) {
  1972. var isCompressed = context.compress && this.value[2] !== '!';
  1973. return this.isLineComment || isCompressed;
  1974. }
  1975. }]);
  1976. return Comment;
  1977. }(Node);
  1978. Comment.prototype.type = 'Comment';
  1979. var contexts = {};
  1980. var copyFromOriginal = function copyFromOriginal(original, destination, propertiesToCopy) {
  1981. if (!original) {
  1982. return;
  1983. }
  1984. for (var i = 0; i < propertiesToCopy.length; i++) {
  1985. if (original.hasOwnProperty(propertiesToCopy[i])) {
  1986. destination[propertiesToCopy[i]] = original[propertiesToCopy[i]];
  1987. }
  1988. }
  1989. };
  1990. /*
  1991. parse is used whilst parsing
  1992. */
  1993. var parseCopyProperties = [// options
  1994. 'paths', // option - unmodified - paths to search for imports on
  1995. 'rewriteUrls', // option - whether to adjust URL's to be relative
  1996. 'rootpath', // option - rootpath to append to URL's
  1997. 'strictImports', // option -
  1998. 'insecure', // option - whether to allow imports from insecure ssl hosts
  1999. 'dumpLineNumbers', // option - whether to dump line numbers
  2000. 'compress', // option - whether to compress
  2001. 'syncImport', // option - whether to import synchronously
  2002. 'chunkInput', // option - whether to chunk input. more performant but causes parse issues.
  2003. 'mime', // browser only - mime type for sheet import
  2004. 'useFileCache', // browser only - whether to use the per file session cache
  2005. // context
  2006. 'processImports', // option & context - whether to process imports. if false then imports will not be imported.
  2007. // Used by the import manager to stop multiple import visitors being created.
  2008. 'pluginManager' // Used as the plugin manager for the session
  2009. ];
  2010. contexts.Parse = function (options) {
  2011. copyFromOriginal(options, this, parseCopyProperties);
  2012. if (typeof this.paths === 'string') {
  2013. this.paths = [this.paths];
  2014. }
  2015. };
  2016. var evalCopyProperties = ['paths', // additional include paths
  2017. 'compress', // whether to compress
  2018. 'math', // whether math has to be within parenthesis
  2019. 'strictUnits', // whether units need to evaluate correctly
  2020. 'sourceMap', // whether to output a source map
  2021. 'importMultiple', // whether we are currently importing multiple copies
  2022. 'urlArgs', // whether to add args into url tokens
  2023. 'javascriptEnabled', // option - whether Inline JavaScript is enabled. if undefined, defaults to false
  2024. 'pluginManager', // Used as the plugin manager for the session
  2025. 'importantScope', // used to bubble up !important statements
  2026. 'rewriteUrls' // option - whether to adjust URL's to be relative
  2027. ];
  2028. function isPathRelative(path) {
  2029. return !/^(?:[a-z-]+:|\/|#)/i.test(path);
  2030. }
  2031. function isPathLocalRelative(path) {
  2032. return path.charAt(0) === '.';
  2033. }
  2034. contexts.Eval =
  2035. /*#__PURE__*/
  2036. function () {
  2037. function _class(options, frames) {
  2038. _classCallCheck(this, _class);
  2039. copyFromOriginal(options, this, evalCopyProperties);
  2040. if (typeof this.paths === 'string') {
  2041. this.paths = [this.paths];
  2042. }
  2043. this.frames = frames || [];
  2044. this.importantScope = this.importantScope || [];
  2045. this.inCalc = false;
  2046. this.mathOn = true;
  2047. }
  2048. _createClass(_class, [{
  2049. key: "enterCalc",
  2050. value: function enterCalc() {
  2051. if (!this.calcStack) {
  2052. this.calcStack = [];
  2053. }
  2054. this.calcStack.push(true);
  2055. this.inCalc = true;
  2056. }
  2057. }, {
  2058. key: "exitCalc",
  2059. value: function exitCalc() {
  2060. this.calcStack.pop();
  2061. if (!this.calcStack) {
  2062. this.inCalc = false;
  2063. }
  2064. }
  2065. }, {
  2066. key: "inParenthesis",
  2067. value: function inParenthesis() {
  2068. if (!this.parensStack) {
  2069. this.parensStack = [];
  2070. }
  2071. this.parensStack.push(true);
  2072. }
  2073. }, {
  2074. key: "outOfParenthesis",
  2075. value: function outOfParenthesis() {
  2076. this.parensStack.pop();
  2077. }
  2078. }, {
  2079. key: "isMathOn",
  2080. value: function isMathOn(op) {
  2081. if (!this.mathOn) {
  2082. return false;
  2083. }
  2084. if (op === '/' && this.math !== Math$1.ALWAYS && (!this.parensStack || !this.parensStack.length)) {
  2085. return false;
  2086. }
  2087. if (this.math > Math$1.PARENS_DIVISION) {
  2088. return this.parensStack && this.parensStack.length;
  2089. }
  2090. return true;
  2091. }
  2092. }, {
  2093. key: "pathRequiresRewrite",
  2094. value: function pathRequiresRewrite(path) {
  2095. var isRelative = this.rewriteUrls === RewriteUrls.LOCAL ? isPathLocalRelative : isPathRelative;
  2096. return isRelative(path);
  2097. }
  2098. }, {
  2099. key: "rewritePath",
  2100. value: function rewritePath(path, rootpath) {
  2101. var newPath;
  2102. rootpath = rootpath || '';
  2103. newPath = this.normalizePath(rootpath + path); // If a path was explicit relative and the rootpath was not an absolute path
  2104. // we must ensure that the new path is also explicit relative.
  2105. if (isPathLocalRelative(path) && isPathRelative(rootpath) && isPathLocalRelative(newPath) === false) {
  2106. newPath = `./${newPath}`;
  2107. }
  2108. return newPath;
  2109. }
  2110. }, {
  2111. key: "normalizePath",
  2112. value: function normalizePath(path) {
  2113. var segments = path.split('/').reverse();
  2114. var segment;
  2115. path = [];
  2116. while (segments.length !== 0) {
  2117. segment = segments.pop();
  2118. switch (segment) {
  2119. case '.':
  2120. break;
  2121. case '..':
  2122. if (path.length === 0 || path[path.length - 1] === '..') {
  2123. path.push(segment);
  2124. } else {
  2125. path.pop();
  2126. }
  2127. break;
  2128. default:
  2129. path.push(segment);
  2130. break;
  2131. }
  2132. }
  2133. return path.join('/');
  2134. }
  2135. }]);
  2136. return _class;
  2137. }();
  2138. function makeRegistry(base) {
  2139. return {
  2140. _data: {},
  2141. add: function add(name, func) {
  2142. // precautionary case conversion, as later querying of
  2143. // the registry by function-caller uses lower case as well.
  2144. name = name.toLowerCase();
  2145. if (this._data.hasOwnProperty(name)) ;
  2146. this._data[name] = func;
  2147. },
  2148. addMultiple: function addMultiple(functions) {
  2149. var _this = this;
  2150. Object.keys(functions).forEach(function (name) {
  2151. _this.add(name, functions[name]);
  2152. });
  2153. },
  2154. get: function get(name) {
  2155. return this._data[name] || base && base.get(name);
  2156. },
  2157. getLocalFunctions: function getLocalFunctions() {
  2158. return this._data;
  2159. },
  2160. inherit: function inherit() {
  2161. return makeRegistry(this);
  2162. },
  2163. create: function create(base) {
  2164. return makeRegistry(base);
  2165. }
  2166. };
  2167. }
  2168. var functionRegistry = makeRegistry(null);
  2169. var defaultFunc = {
  2170. eval: function _eval() {
  2171. var v = this.value_;
  2172. var e = this.error_;
  2173. if (e) {
  2174. throw e;
  2175. }
  2176. if (v != null) {
  2177. return v ? Keyword.True : Keyword.False;
  2178. }
  2179. },
  2180. value: function value(v) {
  2181. this.value_ = v;
  2182. },
  2183. error: function error(e) {
  2184. this.error_ = e;
  2185. },
  2186. reset: function reset() {
  2187. this.value_ = this.error_ = null;
  2188. }
  2189. };
  2190. var Ruleset =
  2191. /*#__PURE__*/
  2192. function (_Node) {
  2193. _inherits(Ruleset, _Node);
  2194. function Ruleset(selectors, rules, strictImports, visibilityInfo) {
  2195. var _this;
  2196. _classCallCheck(this, Ruleset);
  2197. _this = _possibleConstructorReturn(this, _getPrototypeOf(Ruleset).call(this));
  2198. _this.selectors = selectors;
  2199. _this.rules = rules;
  2200. _this._lookups = {};
  2201. _this._variables = null;
  2202. _this._properties = null;
  2203. _this.strictImports = strictImports;
  2204. _this.copyVisibilityInfo(visibilityInfo);
  2205. _this.allowRoot = true;
  2206. _this.setParent(_this.selectors, _assertThisInitialized(_this));
  2207. _this.setParent(_this.rules, _assertThisInitialized(_this));
  2208. return _this;
  2209. }
  2210. _createClass(Ruleset, [{
  2211. key: "isRulesetLike",
  2212. value: function isRulesetLike() {
  2213. return true;
  2214. }
  2215. }, {
  2216. key: "accept",
  2217. value: function accept(visitor) {
  2218. if (this.paths) {
  2219. this.paths = visitor.visitArray(this.paths, true);
  2220. } else if (this.selectors) {
  2221. this.selectors = visitor.visitArray(this.selectors);
  2222. }
  2223. if (this.rules && this.rules.length) {
  2224. this.rules = visitor.visitArray(this.rules);
  2225. }
  2226. }
  2227. }, {
  2228. key: "eval",
  2229. value: function _eval(context) {
  2230. var selectors;
  2231. var selCnt;
  2232. var selector;
  2233. var i;
  2234. var hasVariable;
  2235. var hasOnePassingSelector = false;
  2236. if (this.selectors && (selCnt = this.selectors.length)) {
  2237. selectors = new Array(selCnt);
  2238. defaultFunc.error({
  2239. type: 'Syntax',
  2240. message: 'it is currently only allowed in parametric mixin guards,'
  2241. });
  2242. for (i = 0; i < selCnt; i++) {
  2243. selector = this.selectors[i].eval(context);
  2244. for (var j = 0; j < selector.elements.length; j++) {
  2245. if (selector.elements[j].isVariable) {
  2246. hasVariable = true;
  2247. break;
  2248. }
  2249. }
  2250. selectors[i] = selector;
  2251. if (selector.evaldCondition) {
  2252. hasOnePassingSelector = true;
  2253. }
  2254. }
  2255. if (hasVariable) {
  2256. var toParseSelectors = new Array(selCnt);
  2257. for (i = 0; i < selCnt; i++) {
  2258. selector = selectors[i];
  2259. toParseSelectors[i] = selector.toCSS(context);
  2260. }
  2261. this.parse.parseNode(toParseSelectors.join(','), ["selectors"], selectors[0].getIndex(), selectors[0].fileInfo(), function (err, result) {
  2262. if (result) {
  2263. selectors = flattenArray(result);
  2264. }
  2265. });
  2266. }
  2267. defaultFunc.reset();
  2268. } else {
  2269. hasOnePassingSelector = true;
  2270. }
  2271. var rules = this.rules ? copyArray(this.rules) : null;
  2272. var ruleset = new Ruleset(selectors, rules, this.strictImports, this.visibilityInfo());
  2273. var rule;
  2274. var subRule;
  2275. ruleset.originalRuleset = this;
  2276. ruleset.root = this.root;
  2277. ruleset.firstRoot = this.firstRoot;
  2278. ruleset.allowImports = this.allowImports;
  2279. if (this.debugInfo) {
  2280. ruleset.debugInfo = this.debugInfo;
  2281. }
  2282. if (!hasOnePassingSelector) {
  2283. rules.length = 0;
  2284. } // inherit a function registry from the frames stack when possible;
  2285. // otherwise from the global registry
  2286. ruleset.functionRegistry = function (frames) {
  2287. var i = 0;
  2288. var n = frames.length;
  2289. var found;
  2290. for (; i !== n; ++i) {
  2291. found = frames[i].functionRegistry;
  2292. if (found) {
  2293. return found;
  2294. }
  2295. }
  2296. return functionRegistry;
  2297. }(context.frames).inherit(); // push the current ruleset to the frames stack
  2298. var ctxFrames = context.frames;
  2299. ctxFrames.unshift(ruleset); // currrent selectors
  2300. var ctxSelectors = context.selectors;
  2301. if (!ctxSelectors) {
  2302. context.selectors = ctxSelectors = [];
  2303. }
  2304. ctxSelectors.unshift(this.selectors); // Evaluate imports
  2305. if (ruleset.root || ruleset.allowImports || !ruleset.strictImports) {
  2306. ruleset.evalImports(context);
  2307. } // Store the frames around mixin definitions,
  2308. // so they can be evaluated like closures when the time comes.
  2309. var rsRules = ruleset.rules;
  2310. for (i = 0; rule = rsRules[i]; i++) {
  2311. if (rule.evalFirst) {
  2312. rsRules[i] = rule.eval(context);
  2313. }
  2314. }
  2315. var mediaBlockCount = context.mediaBlocks && context.mediaBlocks.length || 0; // Evaluate mixin calls.
  2316. for (i = 0; rule = rsRules[i]; i++) {
  2317. if (rule.type === 'MixinCall') {
  2318. /* jshint loopfunc:true */
  2319. rules = rule.eval(context).filter(function (r) {
  2320. if (r instanceof Declaration && r.variable) {
  2321. // do not pollute the scope if the variable is
  2322. // already there. consider returning false here
  2323. // but we need a way to "return" variable from mixins
  2324. return !ruleset.variable(r.name);
  2325. }
  2326. return true;
  2327. });
  2328. rsRules.splice.apply(rsRules, _toConsumableArray([i, 1].concat(rules)));
  2329. i += rules.length - 1;
  2330. ruleset.resetCache();
  2331. } else if (rule.type === 'VariableCall') {
  2332. /* jshint loopfunc:true */
  2333. rules = rule.eval(context).rules.filter(function (r) {
  2334. if (r instanceof Declaration && r.variable) {
  2335. // do not pollute the scope at all
  2336. return false;
  2337. }
  2338. return true;
  2339. });
  2340. rsRules.splice.apply(rsRules, _toConsumableArray([i, 1].concat(rules)));
  2341. i += rules.length - 1;
  2342. ruleset.resetCache();
  2343. }
  2344. } // Evaluate everything else
  2345. for (i = 0; rule = rsRules[i]; i++) {
  2346. if (!rule.evalFirst) {
  2347. rsRules[i] = rule = rule.eval ? rule.eval(context) : rule;
  2348. }
  2349. } // Evaluate everything else
  2350. for (i = 0; rule = rsRules[i]; i++) {
  2351. // for rulesets, check if it is a css guard and can be removed
  2352. if (rule instanceof Ruleset && rule.selectors && rule.selectors.length === 1) {
  2353. // check if it can be folded in (e.g. & where)
  2354. if (rule.selectors[0] && rule.selectors[0].isJustParentSelector()) {
  2355. rsRules.splice(i--, 1);
  2356. for (var j = 0; subRule = rule.rules[j]; j++) {
  2357. if (subRule instanceof Node) {
  2358. subRule.copyVisibilityInfo(rule.visibilityInfo());
  2359. if (!(subRule instanceof Declaration) || !subRule.variable) {
  2360. rsRules.splice(++i, 0, subRule);
  2361. }
  2362. }
  2363. }
  2364. }
  2365. }
  2366. } // Pop the stack
  2367. ctxFrames.shift();
  2368. ctxSelectors.shift();
  2369. if (context.mediaBlocks) {
  2370. for (i = mediaBlockCount; i < context.mediaBlocks.length; i++) {
  2371. context.mediaBlocks[i].bubbleSelectors(selectors);
  2372. }
  2373. }
  2374. return ruleset;
  2375. }
  2376. }, {
  2377. key: "evalImports",
  2378. value: function evalImports(context) {
  2379. var rules = this.rules;
  2380. var i;
  2381. var importRules;
  2382. if (!rules) {
  2383. return;
  2384. }
  2385. for (i = 0; i < rules.length; i++) {
  2386. if (rules[i].type === 'Import') {
  2387. importRules = rules[i].eval(context);
  2388. if (importRules && (importRules.length || importRules.length === 0)) {
  2389. rules.splice.apply(rules, _toConsumableArray([i, 1].concat(importRules)));
  2390. i += importRules.length - 1;
  2391. } else {
  2392. rules.splice(i, 1, importRules);
  2393. }
  2394. this.resetCache();
  2395. }
  2396. }
  2397. }
  2398. }, {
  2399. key: "makeImportant",
  2400. value: function makeImportant() {
  2401. var result = new Ruleset(this.selectors, this.rules.map(function (r) {
  2402. if (r.makeImportant) {
  2403. return r.makeImportant();
  2404. } else {
  2405. return r;
  2406. }
  2407. }), this.strictImports, this.visibilityInfo());
  2408. return result;
  2409. }
  2410. }, {
  2411. key: "matchArgs",
  2412. value: function matchArgs(args) {
  2413. return !args || args.length === 0;
  2414. } // lets you call a css selector with a guard
  2415. }, {
  2416. key: "matchCondition",
  2417. value: function matchCondition(args, context) {
  2418. var lastSelector = this.selectors[this.selectors.length - 1];
  2419. if (!lastSelector.evaldCondition) {
  2420. return false;
  2421. }
  2422. if (lastSelector.condition && !lastSelector.condition.eval(new contexts.Eval(context, context.frames))) {
  2423. return false;
  2424. }
  2425. return true;
  2426. }
  2427. }, {
  2428. key: "resetCache",
  2429. value: function resetCache() {
  2430. this._rulesets = null;
  2431. this._variables = null;
  2432. this._properties = null;
  2433. this._lookups = {};
  2434. }
  2435. }, {
  2436. key: "variables",
  2437. value: function variables() {
  2438. if (!this._variables) {
  2439. this._variables = !this.rules ? {} : this.rules.reduce(function (hash, r) {
  2440. if (r instanceof Declaration && r.variable === true) {
  2441. hash[r.name] = r;
  2442. } // when evaluating variables in an import statement, imports have not been eval'd
  2443. // so we need to go inside import statements.
  2444. // guard against root being a string (in the case of inlined less)
  2445. if (r.type === 'Import' && r.root && r.root.variables) {
  2446. var vars = r.root.variables();
  2447. for (var name in vars) {
  2448. if (vars.hasOwnProperty(name)) {
  2449. hash[name] = r.root.variable(name);
  2450. }
  2451. }
  2452. }
  2453. return hash;
  2454. }, {});
  2455. }
  2456. return this._variables;
  2457. }
  2458. }, {
  2459. key: "properties",
  2460. value: function properties() {
  2461. if (!this._properties) {
  2462. this._properties = !this.rules ? {} : this.rules.reduce(function (hash, r) {
  2463. if (r instanceof Declaration && r.variable !== true) {
  2464. var name = r.name.length === 1 && r.name[0] instanceof Keyword ? r.name[0].value : r.name; // Properties don't overwrite as they can merge
  2465. if (!hash[`$${name}`]) {
  2466. hash[`$${name}`] = [r];
  2467. } else {
  2468. hash[`$${name}`].push(r);
  2469. }
  2470. }
  2471. return hash;
  2472. }, {});
  2473. }
  2474. return this._properties;
  2475. }
  2476. }, {
  2477. key: "variable",
  2478. value: function variable(name) {
  2479. var decl = this.variables()[name];
  2480. if (decl) {
  2481. return this.parseValue(decl);
  2482. }
  2483. }
  2484. }, {
  2485. key: "property",
  2486. value: function property(name) {
  2487. var decl = this.properties()[name];
  2488. if (decl) {
  2489. return this.parseValue(decl);
  2490. }
  2491. }
  2492. }, {
  2493. key: "lastDeclaration",
  2494. value: function lastDeclaration() {
  2495. for (var i = this.rules.length; i > 0; i--) {
  2496. var decl = this.rules[i - 1];
  2497. if (decl instanceof Declaration) {
  2498. return this.parseValue(decl);
  2499. }
  2500. }
  2501. }
  2502. }, {
  2503. key: "parseValue",
  2504. value: function parseValue(toParse) {
  2505. var self = this;
  2506. function transformDeclaration(decl) {
  2507. if (decl.value instanceof Anonymous && !decl.parsed) {
  2508. if (typeof decl.value.value === 'string') {
  2509. this.parse.parseNode(decl.value.value, ['value', 'important'], decl.value.getIndex(), decl.fileInfo(), function (err, result) {
  2510. if (err) {
  2511. decl.parsed = true;
  2512. }
  2513. if (result) {
  2514. decl.value = result[0];
  2515. decl.important = result[1] || '';
  2516. decl.parsed = true;
  2517. }
  2518. });
  2519. } else {
  2520. decl.parsed = true;
  2521. }
  2522. return decl;
  2523. } else {
  2524. return decl;
  2525. }
  2526. }
  2527. if (!Array.isArray(toParse)) {
  2528. return transformDeclaration.call(self, toParse);
  2529. } else {
  2530. var nodes = [];
  2531. toParse.forEach(function (n) {
  2532. nodes.push(transformDeclaration.call(self, n));
  2533. });
  2534. return nodes;
  2535. }
  2536. }
  2537. }, {
  2538. key: "rulesets",
  2539. value: function rulesets() {
  2540. if (!this.rules) {
  2541. return [];
  2542. }
  2543. var filtRules = [];
  2544. var rules = this.rules;
  2545. var i;
  2546. var rule;
  2547. for (i = 0; rule = rules[i]; i++) {
  2548. if (rule.isRuleset) {
  2549. filtRules.push(rule);
  2550. }
  2551. }
  2552. return filtRules;
  2553. }
  2554. }, {
  2555. key: "prependRule",
  2556. value: function prependRule(rule) {
  2557. var rules = this.rules;
  2558. if (rules) {
  2559. rules.unshift(rule);
  2560. } else {
  2561. this.rules = [rule];
  2562. }
  2563. this.setParent(rule, this);
  2564. }
  2565. }, {
  2566. key: "find",
  2567. value: function find(selector) {
  2568. var self = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : this;
  2569. var filter = arguments.length > 2 ? arguments[2] : undefined;
  2570. var rules = [];
  2571. var match;
  2572. var foundMixins;
  2573. var key = selector.toCSS();
  2574. if (key in this._lookups) {
  2575. return this._lookups[key];
  2576. }
  2577. this.rulesets().forEach(function (rule) {
  2578. if (rule !== self) {
  2579. for (var j = 0; j < rule.selectors.length; j++) {
  2580. match = selector.match(rule.selectors[j]);
  2581. if (match) {
  2582. if (selector.elements.length > match) {
  2583. if (!filter || filter(rule)) {
  2584. foundMixins = rule.find(new Selector(selector.elements.slice(match)), self, filter);
  2585. for (var i = 0; i < foundMixins.length; ++i) {
  2586. foundMixins[i].path.push(rule);
  2587. }
  2588. Array.prototype.push.apply(rules, foundMixins);
  2589. }
  2590. } else {
  2591. rules.push({
  2592. rule,
  2593. path: []
  2594. });
  2595. }
  2596. break;
  2597. }
  2598. }
  2599. }
  2600. });
  2601. this._lookups[key] = rules;
  2602. return rules;
  2603. }
  2604. }, {
  2605. key: "genCSS",
  2606. value: function genCSS(context, output) {
  2607. var i;
  2608. var j;
  2609. var charsetRuleNodes = [];
  2610. var ruleNodes = [];
  2611. var // Line number debugging
  2612. debugInfo$1;
  2613. var rule;
  2614. var path;
  2615. context.tabLevel = context.tabLevel || 0;
  2616. if (!this.root) {
  2617. context.tabLevel++;
  2618. }
  2619. var tabRuleStr = context.compress ? '' : Array(context.tabLevel + 1).join(' ');
  2620. var tabSetStr = context.compress ? '' : Array(context.tabLevel).join(' ');
  2621. var sep;
  2622. var charsetNodeIndex = 0;
  2623. var importNodeIndex = 0;
  2624. for (i = 0; rule = this.rules[i]; i++) {
  2625. if (rule instanceof Comment) {
  2626. if (importNodeIndex === i) {
  2627. importNodeIndex++;
  2628. }
  2629. ruleNodes.push(rule);
  2630. } else if (rule.isCharset && rule.isCharset()) {
  2631. ruleNodes.splice(charsetNodeIndex, 0, rule);
  2632. charsetNodeIndex++;
  2633. importNodeIndex++;
  2634. } else if (rule.type === 'Import') {
  2635. ruleNodes.splice(importNodeIndex, 0, rule);
  2636. importNodeIndex++;
  2637. } else {
  2638. ruleNodes.push(rule);
  2639. }
  2640. }
  2641. ruleNodes = charsetRuleNodes.concat(ruleNodes); // If this is the root node, we don't render
  2642. // a selector, or {}.
  2643. if (!this.root) {
  2644. debugInfo$1 = debugInfo(context, this, tabSetStr);
  2645. if (debugInfo$1) {
  2646. output.add(debugInfo$1);
  2647. output.add(tabSetStr);
  2648. }
  2649. var paths = this.paths;
  2650. var pathCnt = paths.length;
  2651. var pathSubCnt;
  2652. sep = context.compress ? ',' : `,\n${tabSetStr}`;
  2653. for (i = 0; i < pathCnt; i++) {
  2654. path = paths[i];
  2655. if (!(pathSubCnt = path.length)) {
  2656. continue;
  2657. }
  2658. if (i > 0) {
  2659. output.add(sep);
  2660. }
  2661. context.firstSelector = true;
  2662. path[0].genCSS(context, output);
  2663. context.firstSelector = false;
  2664. for (j = 1; j < pathSubCnt; j++) {
  2665. path[j].genCSS(context, output);
  2666. }
  2667. }
  2668. output.add((context.compress ? '{' : ' {\n') + tabRuleStr);
  2669. } // Compile rules and rulesets
  2670. for (i = 0; rule = ruleNodes[i]; i++) {
  2671. if (i + 1 === ruleNodes.length) {
  2672. context.lastRule = true;
  2673. }
  2674. var currentLastRule = context.lastRule;
  2675. if (rule.isRulesetLike(rule)) {
  2676. context.lastRule = false;
  2677. }
  2678. if (rule.genCSS) {
  2679. rule.genCSS(context, output);
  2680. } else if (rule.value) {
  2681. output.add(rule.value.toString());
  2682. }
  2683. context.lastRule = currentLastRule;
  2684. if (!context.lastRule && rule.isVisible()) {
  2685. output.add(context.compress ? '' : `\n${tabRuleStr}`);
  2686. } else {
  2687. context.lastRule = false;
  2688. }
  2689. }
  2690. if (!this.root) {
  2691. output.add(context.compress ? '}' : `\n${tabSetStr}}`);
  2692. context.tabLevel--;
  2693. }
  2694. if (!output.isEmpty() && !context.compress && this.firstRoot) {
  2695. output.add('\n');
  2696. }
  2697. }
  2698. }, {
  2699. key: "joinSelectors",
  2700. value: function joinSelectors(paths, context, selectors) {
  2701. for (var s = 0; s < selectors.length; s++) {
  2702. this.joinSelector(paths, context, selectors[s]);
  2703. }
  2704. }
  2705. }, {
  2706. key: "joinSelector",
  2707. value: function joinSelector(paths, context, selector) {
  2708. function createParenthesis(elementsToPak, originalElement) {
  2709. var replacementParen;
  2710. var j;
  2711. if (elementsToPak.length === 0) {
  2712. replacementParen = new Paren(elementsToPak[0]);
  2713. } else {
  2714. var insideParent = new Array(elementsToPak.length);
  2715. for (j = 0; j < elementsToPak.length; j++) {
  2716. insideParent[j] = new Element(null, elementsToPak[j], originalElement.isVariable, originalElement._index, originalElement._fileInfo);
  2717. }
  2718. replacementParen = new Paren(new Selector(insideParent));
  2719. }
  2720. return replacementParen;
  2721. }
  2722. function createSelector(containedElement, originalElement) {
  2723. var element;
  2724. var selector;
  2725. element = new Element(null, containedElement, originalElement.isVariable, originalElement._index, originalElement._fileInfo);
  2726. selector = new Selector([element]);
  2727. return selector;
  2728. } // joins selector path from `beginningPath` with selector path in `addPath`
  2729. // `replacedElement` contains element that is being replaced by `addPath`
  2730. // returns concatenated path
  2731. function addReplacementIntoPath(beginningPath, addPath, replacedElement, originalSelector) {
  2732. var newSelectorPath;
  2733. var lastSelector;
  2734. var newJoinedSelector; // our new selector path
  2735. newSelectorPath = []; // construct the joined selector - if & is the first thing this will be empty,
  2736. // if not newJoinedSelector will be the last set of elements in the selector
  2737. if (beginningPath.length > 0) {
  2738. newSelectorPath = copyArray(beginningPath);
  2739. lastSelector = newSelectorPath.pop();
  2740. newJoinedSelector = originalSelector.createDerived(copyArray(lastSelector.elements));
  2741. } else {
  2742. newJoinedSelector = originalSelector.createDerived([]);
  2743. }
  2744. if (addPath.length > 0) {
  2745. // /deep/ is a CSS4 selector - (removed, so should deprecate)
  2746. // that is valid without anything in front of it
  2747. // so if the & does not have a combinator that is "" or " " then
  2748. // and there is a combinator on the parent, then grab that.
  2749. // this also allows + a { & .b { .a & { ... though not sure why you would want to do that
  2750. var combinator = replacedElement.combinator;
  2751. var parentEl = addPath[0].elements[0];
  2752. if (combinator.emptyOrWhitespace && !parentEl.combinator.emptyOrWhitespace) {
  2753. combinator = parentEl.combinator;
  2754. } // join the elements so far with the first part of the parent
  2755. newJoinedSelector.elements.push(new Element(combinator, parentEl.value, replacedElement.isVariable, replacedElement._index, replacedElement._fileInfo));
  2756. newJoinedSelector.elements = newJoinedSelector.elements.concat(addPath[0].elements.slice(1));
  2757. } // now add the joined selector - but only if it is not empty
  2758. if (newJoinedSelector.elements.length !== 0) {
  2759. newSelectorPath.push(newJoinedSelector);
  2760. } // put together the parent selectors after the join (e.g. the rest of the parent)
  2761. if (addPath.length > 1) {
  2762. var restOfPath = addPath.slice(1);
  2763. restOfPath = restOfPath.map(function (selector) {
  2764. return selector.createDerived(selector.elements, []);
  2765. });
  2766. newSelectorPath = newSelectorPath.concat(restOfPath);
  2767. }
  2768. return newSelectorPath;
  2769. } // joins selector path from `beginningPath` with every selector path in `addPaths` array
  2770. // `replacedElement` contains element that is being replaced by `addPath`
  2771. // returns array with all concatenated paths
  2772. function addAllReplacementsIntoPath(beginningPath, addPaths, replacedElement, originalSelector, result) {
  2773. var j;
  2774. for (j = 0; j < beginningPath.length; j++) {
  2775. var newSelectorPath = addReplacementIntoPath(beginningPath[j], addPaths, replacedElement, originalSelector);
  2776. result.push(newSelectorPath);
  2777. }
  2778. return result;
  2779. }
  2780. function mergeElementsOnToSelectors(elements, selectors) {
  2781. var i;
  2782. var sel;
  2783. if (elements.length === 0) {
  2784. return;
  2785. }
  2786. if (selectors.length === 0) {
  2787. selectors.push([new Selector(elements)]);
  2788. return;
  2789. }
  2790. for (i = 0; sel = selectors[i]; i++) {
  2791. // if the previous thing in sel is a parent this needs to join on to it
  2792. if (sel.length > 0) {
  2793. sel[sel.length - 1] = sel[sel.length - 1].createDerived(sel[sel.length - 1].elements.concat(elements));
  2794. } else {
  2795. sel.push(new Selector(elements));
  2796. }
  2797. }
  2798. } // replace all parent selectors inside `inSelector` by content of `context` array
  2799. // resulting selectors are returned inside `paths` array
  2800. // returns true if `inSelector` contained at least one parent selector
  2801. function replaceParentSelector(paths, context, inSelector) {
  2802. // The paths are [[Selector]]
  2803. // The first list is a list of comma separated selectors
  2804. // The inner list is a list of inheritance separated selectors
  2805. // e.g.
  2806. // .a, .b {
  2807. // .c {
  2808. // }
  2809. // }
  2810. // == [[.a] [.c]] [[.b] [.c]]
  2811. //
  2812. var i;
  2813. var j;
  2814. var k;
  2815. var currentElements;
  2816. var newSelectors;
  2817. var selectorsMultiplied;
  2818. var sel;
  2819. var el;
  2820. var hadParentSelector = false;
  2821. var length;
  2822. var lastSelector;
  2823. function findNestedSelector(element) {
  2824. var maybeSelector;
  2825. if (!(element.value instanceof Paren)) {
  2826. return null;
  2827. }
  2828. maybeSelector = element.value.value;
  2829. if (!(maybeSelector instanceof Selector)) {
  2830. return null;
  2831. }
  2832. return maybeSelector;
  2833. } // the elements from the current selector so far
  2834. currentElements = []; // the current list of new selectors to add to the path.
  2835. // We will build it up. We initiate it with one empty selector as we "multiply" the new selectors
  2836. // by the parents
  2837. newSelectors = [[]];
  2838. for (i = 0; el = inSelector.elements[i]; i++) {
  2839. // non parent reference elements just get added
  2840. if (el.value !== '&') {
  2841. var nestedSelector = findNestedSelector(el);
  2842. if (nestedSelector != null) {
  2843. // merge the current list of non parent selector elements
  2844. // on to the current list of selectors to add
  2845. mergeElementsOnToSelectors(currentElements, newSelectors);
  2846. var nestedPaths = [];
  2847. var replaced = void 0;
  2848. var replacedNewSelectors = [];
  2849. replaced = replaceParentSelector(nestedPaths, context, nestedSelector);
  2850. hadParentSelector = hadParentSelector || replaced; // the nestedPaths array should have only one member - replaceParentSelector does not multiply selectors
  2851. for (k = 0; k < nestedPaths.length; k++) {
  2852. var replacementSelector = createSelector(createParenthesis(nestedPaths[k], el), el);
  2853. addAllReplacementsIntoPath(newSelectors, [replacementSelector], el, inSelector, replacedNewSelectors);
  2854. }
  2855. newSelectors = replacedNewSelectors;
  2856. currentElements = [];
  2857. } else {
  2858. currentElements.push(el);
  2859. }
  2860. } else {
  2861. hadParentSelector = true; // the new list of selectors to add
  2862. selectorsMultiplied = []; // merge the current list of non parent selector elements
  2863. // on to the current list of selectors to add
  2864. mergeElementsOnToSelectors(currentElements, newSelectors); // loop through our current selectors
  2865. for (j = 0; j < newSelectors.length; j++) {
  2866. sel = newSelectors[j]; // if we don't have any parent paths, the & might be in a mixin so that it can be used
  2867. // whether there are parents or not
  2868. if (context.length === 0) {
  2869. // the combinator used on el should now be applied to the next element instead so that
  2870. // it is not lost
  2871. if (sel.length > 0) {
  2872. sel[0].elements.push(new Element(el.combinator, '', el.isVariable, el._index, el._fileInfo));
  2873. }
  2874. selectorsMultiplied.push(sel);
  2875. } else {
  2876. // and the parent selectors
  2877. for (k = 0; k < context.length; k++) {
  2878. // We need to put the current selectors
  2879. // then join the last selector's elements on to the parents selectors
  2880. var newSelectorPath = addReplacementIntoPath(sel, context[k], el, inSelector); // add that to our new set of selectors
  2881. selectorsMultiplied.push(newSelectorPath);
  2882. }
  2883. }
  2884. } // our new selectors has been multiplied, so reset the state
  2885. newSelectors = selectorsMultiplied;
  2886. currentElements = [];
  2887. }
  2888. } // if we have any elements left over (e.g. .a& .b == .b)
  2889. // add them on to all the current selectors
  2890. mergeElementsOnToSelectors(currentElements, newSelectors);
  2891. for (i = 0; i < newSelectors.length; i++) {
  2892. length = newSelectors[i].length;
  2893. if (length > 0) {
  2894. paths.push(newSelectors[i]);
  2895. lastSelector = newSelectors[i][length - 1];
  2896. newSelectors[i][length - 1] = lastSelector.createDerived(lastSelector.elements, inSelector.extendList);
  2897. }
  2898. }
  2899. return hadParentSelector;
  2900. }
  2901. function deriveSelector(visibilityInfo, deriveFrom) {
  2902. var newSelector = deriveFrom.createDerived(deriveFrom.elements, deriveFrom.extendList, deriveFrom.evaldCondition);
  2903. newSelector.copyVisibilityInfo(visibilityInfo);
  2904. return newSelector;
  2905. } // joinSelector code follows
  2906. var i;
  2907. var newPaths;
  2908. var hadParentSelector;
  2909. newPaths = [];
  2910. hadParentSelector = replaceParentSelector(newPaths, context, selector);
  2911. if (!hadParentSelector) {
  2912. if (context.length > 0) {
  2913. newPaths = [];
  2914. for (i = 0; i < context.length; i++) {
  2915. var concatenated = context[i].map(deriveSelector.bind(this, selector.visibilityInfo()));
  2916. concatenated.push(selector);
  2917. newPaths.push(concatenated);
  2918. }
  2919. } else {
  2920. newPaths = [[selector]];
  2921. }
  2922. }
  2923. for (i = 0; i < newPaths.length; i++) {
  2924. paths.push(newPaths[i]);
  2925. }
  2926. }
  2927. }]);
  2928. return Ruleset;
  2929. }(Node);
  2930. Ruleset.prototype.type = 'Ruleset';
  2931. Ruleset.prototype.isRuleset = true;
  2932. var AtRule =
  2933. /*#__PURE__*/
  2934. function (_Node) {
  2935. _inherits(AtRule, _Node);
  2936. function AtRule(name, value, rules, index, currentFileInfo, debugInfo, isRooted, visibilityInfo) {
  2937. var _this;
  2938. _classCallCheck(this, AtRule);
  2939. _this = _possibleConstructorReturn(this, _getPrototypeOf(AtRule).call(this));
  2940. var i;
  2941. _this.name = name;
  2942. _this.value = value instanceof Node ? value : value ? new Anonymous(value) : value;
  2943. if (rules) {
  2944. if (Array.isArray(rules)) {
  2945. _this.rules = rules;
  2946. } else {
  2947. _this.rules = [rules];
  2948. _this.rules[0].selectors = new Selector([], null, null, index, currentFileInfo).createEmptySelectors();
  2949. }
  2950. for (i = 0; i < _this.rules.length; i++) {
  2951. _this.rules[i].allowImports = true;
  2952. }
  2953. _this.setParent(_this.rules, _assertThisInitialized(_this));
  2954. }
  2955. _this._index = index;
  2956. _this._fileInfo = currentFileInfo;
  2957. _this.debugInfo = debugInfo;
  2958. _this.isRooted = isRooted || false;
  2959. _this.copyVisibilityInfo(visibilityInfo);
  2960. _this.allowRoot = true;
  2961. return _this;
  2962. }
  2963. _createClass(AtRule, [{
  2964. key: "accept",
  2965. value: function accept(visitor) {
  2966. var value = this.value;
  2967. var rules = this.rules;
  2968. if (rules) {
  2969. this.rules = visitor.visitArray(rules);
  2970. }
  2971. if (value) {
  2972. this.value = visitor.visit(value);
  2973. }
  2974. }
  2975. }, {
  2976. key: "isRulesetLike",
  2977. value: function isRulesetLike() {
  2978. return this.rules || !this.isCharset();
  2979. }
  2980. }, {
  2981. key: "isCharset",
  2982. value: function isCharset() {
  2983. return '@charset' === this.name;
  2984. }
  2985. }, {
  2986. key: "genCSS",
  2987. value: function genCSS(context, output) {
  2988. var value = this.value;
  2989. var rules = this.rules;
  2990. output.add(this.name, this.fileInfo(), this.getIndex());
  2991. if (value) {
  2992. output.add(' ');
  2993. value.genCSS(context, output);
  2994. }
  2995. if (rules) {
  2996. this.outputRuleset(context, output, rules);
  2997. } else {
  2998. output.add(';');
  2999. }
  3000. }
  3001. }, {
  3002. key: "eval",
  3003. value: function _eval(context) {
  3004. var mediaPathBackup;
  3005. var mediaBlocksBackup;
  3006. var value = this.value;
  3007. var rules = this.rules; // media stored inside other atrule should not bubble over it
  3008. // backpup media bubbling information
  3009. mediaPathBackup = context.mediaPath;
  3010. mediaBlocksBackup = context.mediaBlocks; // deleted media bubbling information
  3011. context.mediaPath = [];
  3012. context.mediaBlocks = [];
  3013. if (value) {
  3014. value = value.eval(context);
  3015. }
  3016. if (rules) {
  3017. // assuming that there is only one rule at this point - that is how parser constructs the rule
  3018. rules = [rules[0].eval(context)];
  3019. rules[0].root = true;
  3020. } // restore media bubbling information
  3021. context.mediaPath = mediaPathBackup;
  3022. context.mediaBlocks = mediaBlocksBackup;
  3023. return new AtRule(this.name, value, rules, this.getIndex(), this.fileInfo(), this.debugInfo, this.isRooted, this.visibilityInfo());
  3024. }
  3025. }, {
  3026. key: "variable",
  3027. value: function variable(name) {
  3028. if (this.rules) {
  3029. // assuming that there is only one rule at this point - that is how parser constructs the rule
  3030. return Ruleset.prototype.variable.call(this.rules[0], name);
  3031. }
  3032. }
  3033. }, {
  3034. key: "find",
  3035. value: function find() {
  3036. if (this.rules) {
  3037. for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
  3038. args[_key] = arguments[_key];
  3039. }
  3040. // assuming that there is only one rule at this point - that is how parser constructs the rule
  3041. return Ruleset.prototype.find.apply(this.rules[0], args);
  3042. }
  3043. }
  3044. }, {
  3045. key: "rulesets",
  3046. value: function rulesets() {
  3047. if (this.rules) {
  3048. // assuming that there is only one rule at this point - that is how parser constructs the rule
  3049. return Ruleset.prototype.rulesets.apply(this.rules[0]);
  3050. }
  3051. }
  3052. }, {
  3053. key: "outputRuleset",
  3054. value: function outputRuleset(context, output, rules) {
  3055. var ruleCnt = rules.length;
  3056. var i;
  3057. context.tabLevel = (context.tabLevel | 0) + 1; // Compressed
  3058. if (context.compress) {
  3059. output.add('{');
  3060. for (i = 0; i < ruleCnt; i++) {
  3061. rules[i].genCSS(context, output);
  3062. }
  3063. output.add('}');
  3064. context.tabLevel--;
  3065. return;
  3066. } // Non-compressed
  3067. var tabSetStr = `\n${Array(context.tabLevel).join(' ')}`;
  3068. var tabRuleStr = `${tabSetStr} `;
  3069. if (!ruleCnt) {
  3070. output.add(` {${tabSetStr}}`);
  3071. } else {
  3072. output.add(` {${tabRuleStr}`);
  3073. rules[0].genCSS(context, output);
  3074. for (i = 1; i < ruleCnt; i++) {
  3075. output.add(tabRuleStr);
  3076. rules[i].genCSS(context, output);
  3077. }
  3078. output.add(`${tabSetStr}}`);
  3079. }
  3080. context.tabLevel--;
  3081. }
  3082. }]);
  3083. return AtRule;
  3084. }(Node);
  3085. AtRule.prototype.type = 'AtRule';
  3086. var DetachedRuleset =
  3087. /*#__PURE__*/
  3088. function (_Node) {
  3089. _inherits(DetachedRuleset, _Node);
  3090. function DetachedRuleset(ruleset, frames) {
  3091. var _this;
  3092. _classCallCheck(this, DetachedRuleset);
  3093. _this = _possibleConstructorReturn(this, _getPrototypeOf(DetachedRuleset).call(this));
  3094. _this.ruleset = ruleset;
  3095. _this.frames = frames;
  3096. _this.setParent(_this.ruleset, _assertThisInitialized(_this));
  3097. return _this;
  3098. }
  3099. _createClass(DetachedRuleset, [{
  3100. key: "accept",
  3101. value: function accept(visitor) {
  3102. this.ruleset = visitor.visit(this.ruleset);
  3103. }
  3104. }, {
  3105. key: "eval",
  3106. value: function _eval(context) {
  3107. var frames = this.frames || copyArray(context.frames);
  3108. return new DetachedRuleset(this.ruleset, frames);
  3109. }
  3110. }, {
  3111. key: "callEval",
  3112. value: function callEval(context) {
  3113. return this.ruleset.eval(this.frames ? new contexts.Eval(context, this.frames.concat(context.frames)) : context);
  3114. }
  3115. }]);
  3116. return DetachedRuleset;
  3117. }(Node);
  3118. DetachedRuleset.prototype.type = 'DetachedRuleset';
  3119. DetachedRuleset.prototype.evalFirst = true;
  3120. var Unit =
  3121. /*#__PURE__*/
  3122. function (_Node) {
  3123. _inherits(Unit, _Node);
  3124. function Unit(numerator, denominator, backupUnit) {
  3125. var _this;
  3126. _classCallCheck(this, Unit);
  3127. _this = _possibleConstructorReturn(this, _getPrototypeOf(Unit).call(this));
  3128. _this.numerator = numerator ? copyArray(numerator).sort() : [];
  3129. _this.denominator = denominator ? copyArray(denominator).sort() : [];
  3130. if (backupUnit) {
  3131. _this.backupUnit = backupUnit;
  3132. } else if (numerator && numerator.length) {
  3133. _this.backupUnit = numerator[0];
  3134. }
  3135. return _this;
  3136. }
  3137. _createClass(Unit, [{
  3138. key: "clone",
  3139. value: function clone() {
  3140. return new Unit(copyArray(this.numerator), copyArray(this.denominator), this.backupUnit);
  3141. }
  3142. }, {
  3143. key: "genCSS",
  3144. value: function genCSS(context, output) {
  3145. // Dimension checks the unit is singular and throws an error if in strict math mode.
  3146. var strictUnits = context && context.strictUnits;
  3147. if (this.numerator.length === 1) {
  3148. output.add(this.numerator[0]); // the ideal situation
  3149. } else if (!strictUnits && this.backupUnit) {
  3150. output.add(this.backupUnit);
  3151. } else if (!strictUnits && this.denominator.length) {
  3152. output.add(this.denominator[0]);
  3153. }
  3154. }
  3155. }, {
  3156. key: "toString",
  3157. value: function toString() {
  3158. var i;
  3159. var returnStr = this.numerator.join('*');
  3160. for (i = 0; i < this.denominator.length; i++) {
  3161. returnStr += `/${this.denominator[i]}`;
  3162. }
  3163. return returnStr;
  3164. }
  3165. }, {
  3166. key: "compare",
  3167. value: function compare(other) {
  3168. return this.is(other.toString()) ? 0 : undefined;
  3169. }
  3170. }, {
  3171. key: "is",
  3172. value: function is(unitString) {
  3173. return this.toString().toUpperCase() === unitString.toUpperCase();
  3174. }
  3175. }, {
  3176. key: "isLength",
  3177. value: function isLength() {
  3178. return RegExp('^(px|em|ex|ch|rem|in|cm|mm|pc|pt|ex|vw|vh|vmin|vmax)$', 'gi').test(this.toCSS());
  3179. }
  3180. }, {
  3181. key: "isEmpty",
  3182. value: function isEmpty() {
  3183. return this.numerator.length === 0 && this.denominator.length === 0;
  3184. }
  3185. }, {
  3186. key: "isSingular",
  3187. value: function isSingular() {
  3188. return this.numerator.length <= 1 && this.denominator.length === 0;
  3189. }
  3190. }, {
  3191. key: "map",
  3192. value: function map(callback) {
  3193. var i;
  3194. for (i = 0; i < this.numerator.length; i++) {
  3195. this.numerator[i] = callback(this.numerator[i], false);
  3196. }
  3197. for (i = 0; i < this.denominator.length; i++) {
  3198. this.denominator[i] = callback(this.denominator[i], true);
  3199. }
  3200. }
  3201. }, {
  3202. key: "usedUnits",
  3203. value: function usedUnits() {
  3204. var group;
  3205. var result = {};
  3206. var mapUnit;
  3207. var groupName;
  3208. mapUnit = function mapUnit(atomicUnit) {
  3209. /* jshint loopfunc:true */
  3210. if (group.hasOwnProperty(atomicUnit) && !result[groupName]) {
  3211. result[groupName] = atomicUnit;
  3212. }
  3213. return atomicUnit;
  3214. };
  3215. for (groupName in unitConversions) {
  3216. if (unitConversions.hasOwnProperty(groupName)) {
  3217. group = unitConversions[groupName];
  3218. this.map(mapUnit);
  3219. }
  3220. }
  3221. return result;
  3222. }
  3223. }, {
  3224. key: "cancel",
  3225. value: function cancel() {
  3226. var counter = {};
  3227. var atomicUnit;
  3228. var i;
  3229. for (i = 0; i < this.numerator.length; i++) {
  3230. atomicUnit = this.numerator[i];
  3231. counter[atomicUnit] = (counter[atomicUnit] || 0) + 1;
  3232. }
  3233. for (i = 0; i < this.denominator.length; i++) {
  3234. atomicUnit = this.denominator[i];
  3235. counter[atomicUnit] = (counter[atomicUnit] || 0) - 1;
  3236. }
  3237. this.numerator = [];
  3238. this.denominator = [];
  3239. for (atomicUnit in counter) {
  3240. if (counter.hasOwnProperty(atomicUnit)) {
  3241. var count = counter[atomicUnit];
  3242. if (count > 0) {
  3243. for (i = 0; i < count; i++) {
  3244. this.numerator.push(atomicUnit);
  3245. }
  3246. } else if (count < 0) {
  3247. for (i = 0; i < -count; i++) {
  3248. this.denominator.push(atomicUnit);
  3249. }
  3250. }
  3251. }
  3252. }
  3253. this.numerator.sort();
  3254. this.denominator.sort();
  3255. }
  3256. }]);
  3257. return Unit;
  3258. }(Node);
  3259. Unit.prototype.type = 'Unit';
  3260. // A number with a unit
  3261. //
  3262. var Dimension =
  3263. /*#__PURE__*/
  3264. function (_Node) {
  3265. _inherits(Dimension, _Node);
  3266. function Dimension(value, unit) {
  3267. var _this;
  3268. _classCallCheck(this, Dimension);
  3269. _this = _possibleConstructorReturn(this, _getPrototypeOf(Dimension).call(this));
  3270. _this.value = parseFloat(value);
  3271. if (isNaN(_this.value)) {
  3272. throw new Error('Dimension is not a number.');
  3273. }
  3274. _this.unit = unit && unit instanceof Unit ? unit : new Unit(unit ? [unit] : undefined);
  3275. _this.setParent(_this.unit, _assertThisInitialized(_this));
  3276. return _this;
  3277. }
  3278. _createClass(Dimension, [{
  3279. key: "accept",
  3280. value: function accept(visitor) {
  3281. this.unit = visitor.visit(this.unit);
  3282. }
  3283. }, {
  3284. key: "eval",
  3285. value: function _eval(context) {
  3286. return this;
  3287. }
  3288. }, {
  3289. key: "toColor",
  3290. value: function toColor() {
  3291. return new Color([this.value, this.value, this.value]);
  3292. }
  3293. }, {
  3294. key: "genCSS",
  3295. value: function genCSS(context, output) {
  3296. if (context && context.strictUnits && !this.unit.isSingular()) {
  3297. throw new Error(`Multiple units in dimension. Correct the units or use the unit function. Bad unit: ${this.unit.toString()}`);
  3298. }
  3299. var value = this.fround(context, this.value);
  3300. var strValue = String(value);
  3301. if (value !== 0 && value < 0.000001 && value > -0.000001) {
  3302. // would be output 1e-6 etc.
  3303. strValue = value.toFixed(20).replace(/0+$/, '');
  3304. }
  3305. if (context && context.compress) {
  3306. // Zero values doesn't need a unit
  3307. if (value === 0 && this.unit.isLength()) {
  3308. output.add(strValue);
  3309. return;
  3310. } // Float values doesn't need a leading zero
  3311. if (value > 0 && value < 1) {
  3312. strValue = strValue.substr(1);
  3313. }
  3314. }
  3315. output.add(strValue);
  3316. this.unit.genCSS(context, output);
  3317. } // In an operation between two Dimensions,
  3318. // we default to the first Dimension's unit,
  3319. // so `1px + 2` will yield `3px`.
  3320. }, {
  3321. key: "operate",
  3322. value: function operate(context, op, other) {
  3323. /* jshint noempty:false */
  3324. var value = this._operate(context, op, this.value, other.value);
  3325. var unit = this.unit.clone();
  3326. if (op === '+' || op === '-') {
  3327. if (unit.numerator.length === 0 && unit.denominator.length === 0) {
  3328. unit = other.unit.clone();
  3329. if (this.unit.backupUnit) {
  3330. unit.backupUnit = this.unit.backupUnit;
  3331. }
  3332. } else if (other.unit.numerator.length === 0 && unit.denominator.length === 0) ; else {
  3333. other = other.convertTo(this.unit.usedUnits());
  3334. if (context.strictUnits && other.unit.toString() !== unit.toString()) {
  3335. throw new Error(`Incompatible units. Change the units or use the unit function. ` + `Bad units: '${unit.toString()}' and '${other.unit.toString()}'.`);
  3336. }
  3337. value = this._operate(context, op, this.value, other.value);
  3338. }
  3339. } else if (op === '*') {
  3340. unit.numerator = unit.numerator.concat(other.unit.numerator).sort();
  3341. unit.denominator = unit.denominator.concat(other.unit.denominator).sort();
  3342. unit.cancel();
  3343. } else if (op === '/') {
  3344. unit.numerator = unit.numerator.concat(other.unit.denominator).sort();
  3345. unit.denominator = unit.denominator.concat(other.unit.numerator).sort();
  3346. unit.cancel();
  3347. }
  3348. return new Dimension(value, unit);
  3349. }
  3350. }, {
  3351. key: "compare",
  3352. value: function compare(other) {
  3353. var a;
  3354. var b;
  3355. if (!(other instanceof Dimension)) {
  3356. return undefined;
  3357. }
  3358. if (this.unit.isEmpty() || other.unit.isEmpty()) {
  3359. a = this;
  3360. b = other;
  3361. } else {
  3362. a = this.unify();
  3363. b = other.unify();
  3364. if (a.unit.compare(b.unit) !== 0) {
  3365. return undefined;
  3366. }
  3367. }
  3368. return Node.numericCompare(a.value, b.value);
  3369. }
  3370. }, {
  3371. key: "unify",
  3372. value: function unify() {
  3373. return this.convertTo({
  3374. length: 'px',
  3375. duration: 's',
  3376. angle: 'rad'
  3377. });
  3378. }
  3379. }, {
  3380. key: "convertTo",
  3381. value: function convertTo(conversions) {
  3382. var value = this.value;
  3383. var unit = this.unit.clone();
  3384. var i;
  3385. var groupName;
  3386. var group;
  3387. var targetUnit;
  3388. var derivedConversions = {};
  3389. var applyUnit;
  3390. if (typeof conversions === 'string') {
  3391. for (i in unitConversions) {
  3392. if (unitConversions[i].hasOwnProperty(conversions)) {
  3393. derivedConversions = {};
  3394. derivedConversions[i] = conversions;
  3395. }
  3396. }
  3397. conversions = derivedConversions;
  3398. }
  3399. applyUnit = function applyUnit(atomicUnit, denominator) {
  3400. /* jshint loopfunc:true */
  3401. if (group.hasOwnProperty(atomicUnit)) {
  3402. if (denominator) {
  3403. value = value / (group[atomicUnit] / group[targetUnit]);
  3404. } else {
  3405. value = value * (group[atomicUnit] / group[targetUnit]);
  3406. }
  3407. return targetUnit;
  3408. }
  3409. return atomicUnit;
  3410. };
  3411. for (groupName in conversions) {
  3412. if (conversions.hasOwnProperty(groupName)) {
  3413. targetUnit = conversions[groupName];
  3414. group = unitConversions[groupName];
  3415. unit.map(applyUnit);
  3416. }
  3417. }
  3418. unit.cancel();
  3419. return new Dimension(value, unit);
  3420. }
  3421. }]);
  3422. return Dimension;
  3423. }(Node);
  3424. Dimension.prototype.type = 'Dimension';
  3425. var MATH$1 = Math$1;
  3426. var Operation =
  3427. /*#__PURE__*/
  3428. function (_Node) {
  3429. _inherits(Operation, _Node);
  3430. function Operation(op, operands, isSpaced) {
  3431. var _this;
  3432. _classCallCheck(this, Operation);
  3433. _this = _possibleConstructorReturn(this, _getPrototypeOf(Operation).call(this));
  3434. _this.op = op.trim();
  3435. _this.operands = operands;
  3436. _this.isSpaced = isSpaced;
  3437. return _this;
  3438. }
  3439. _createClass(Operation, [{
  3440. key: "accept",
  3441. value: function accept(visitor) {
  3442. this.operands = visitor.visitArray(this.operands);
  3443. }
  3444. }, {
  3445. key: "eval",
  3446. value: function _eval(context) {
  3447. var a = this.operands[0].eval(context);
  3448. var b = this.operands[1].eval(context);
  3449. var op;
  3450. if (context.isMathOn(this.op)) {
  3451. op = this.op === './' ? '/' : this.op;
  3452. if (a instanceof Dimension && b instanceof Color) {
  3453. a = a.toColor();
  3454. }
  3455. if (b instanceof Dimension && a instanceof Color) {
  3456. b = b.toColor();
  3457. }
  3458. if (!a.operate) {
  3459. if (a instanceof Operation && a.op === '/' && context.math === MATH$1.PARENS_DIVISION) {
  3460. return new Operation(this.op, [a, b], this.isSpaced);
  3461. }
  3462. throw {
  3463. type: 'Operation',
  3464. message: 'Operation on an invalid type'
  3465. };
  3466. }
  3467. return a.operate(context, op, b);
  3468. } else {
  3469. return new Operation(this.op, [a, b], this.isSpaced);
  3470. }
  3471. }
  3472. }, {
  3473. key: "genCSS",
  3474. value: function genCSS(context, output) {
  3475. this.operands[0].genCSS(context, output);
  3476. if (this.isSpaced) {
  3477. output.add(' ');
  3478. }
  3479. output.add(this.op);
  3480. if (this.isSpaced) {
  3481. output.add(' ');
  3482. }
  3483. this.operands[1].genCSS(context, output);
  3484. }
  3485. }]);
  3486. return Operation;
  3487. }(Node);
  3488. Operation.prototype.type = 'Operation';
  3489. var MATH$2 = Math$1;
  3490. var Expression =
  3491. /*#__PURE__*/
  3492. function (_Node) {
  3493. _inherits(Expression, _Node);
  3494. function Expression(value, noSpacing) {
  3495. var _this;
  3496. _classCallCheck(this, Expression);
  3497. _this = _possibleConstructorReturn(this, _getPrototypeOf(Expression).call(this));
  3498. _this.value = value;
  3499. _this.noSpacing = noSpacing;
  3500. if (!value) {
  3501. throw new Error('Expression requires an array parameter');
  3502. }
  3503. return _this;
  3504. }
  3505. _createClass(Expression, [{
  3506. key: "accept",
  3507. value: function accept(visitor) {
  3508. this.value = visitor.visitArray(this.value);
  3509. }
  3510. }, {
  3511. key: "eval",
  3512. value: function _eval(context) {
  3513. var returnValue;
  3514. var mathOn = context.isMathOn();
  3515. var inParenthesis = this.parens && (context.math !== MATH$2.STRICT_LEGACY || !this.parensInOp);
  3516. var doubleParen = false;
  3517. if (inParenthesis) {
  3518. context.inParenthesis();
  3519. }
  3520. if (this.value.length > 1) {
  3521. returnValue = new Expression(this.value.map(function (e) {
  3522. if (!e.eval) {
  3523. return e;
  3524. }
  3525. return e.eval(context);
  3526. }), this.noSpacing);
  3527. } else if (this.value.length === 1) {
  3528. if (this.value[0].parens && !this.value[0].parensInOp && !context.inCalc) {
  3529. doubleParen = true;
  3530. }
  3531. returnValue = this.value[0].eval(context);
  3532. } else {
  3533. returnValue = this;
  3534. }
  3535. if (inParenthesis) {
  3536. context.outOfParenthesis();
  3537. }
  3538. if (this.parens && this.parensInOp && !mathOn && !doubleParen && !(returnValue instanceof Dimension)) {
  3539. returnValue = new Paren(returnValue);
  3540. }
  3541. return returnValue;
  3542. }
  3543. }, {
  3544. key: "genCSS",
  3545. value: function genCSS(context, output) {
  3546. for (var i = 0; i < this.value.length; i++) {
  3547. this.value[i].genCSS(context, output);
  3548. if (!this.noSpacing && i + 1 < this.value.length) {
  3549. output.add(' ');
  3550. }
  3551. }
  3552. }
  3553. }, {
  3554. key: "throwAwayComments",
  3555. value: function throwAwayComments() {
  3556. this.value = this.value.filter(function (v) {
  3557. return !(v instanceof Comment);
  3558. });
  3559. }
  3560. }]);
  3561. return Expression;
  3562. }(Node);
  3563. Expression.prototype.type = 'Expression';
  3564. var functionCaller =
  3565. /*#__PURE__*/
  3566. function () {
  3567. function functionCaller(name, context, index, currentFileInfo) {
  3568. _classCallCheck(this, functionCaller);
  3569. this.name = name.toLowerCase();
  3570. this.index = index;
  3571. this.context = context;
  3572. this.currentFileInfo = currentFileInfo;
  3573. this.func = context.frames[0].functionRegistry.get(this.name);
  3574. }
  3575. _createClass(functionCaller, [{
  3576. key: "isValid",
  3577. value: function isValid() {
  3578. return Boolean(this.func);
  3579. }
  3580. }, {
  3581. key: "call",
  3582. value: function call(args) {
  3583. // This code is terrible and should be replaced as per this issue...
  3584. // https://github.com/less/less.js/issues/2477
  3585. if (Array.isArray(args)) {
  3586. args = args.filter(function (item) {
  3587. if (item.type === 'Comment') {
  3588. return false;
  3589. }
  3590. return true;
  3591. }).map(function (item) {
  3592. if (item.type === 'Expression') {
  3593. var subNodes = item.value.filter(function (item) {
  3594. if (item.type === 'Comment') {
  3595. return false;
  3596. }
  3597. return true;
  3598. });
  3599. if (subNodes.length === 1) {
  3600. return subNodes[0];
  3601. } else {
  3602. return new Expression(subNodes);
  3603. }
  3604. }
  3605. return item;
  3606. });
  3607. }
  3608. return this.func.apply(this, _toConsumableArray(args));
  3609. }
  3610. }]);
  3611. return functionCaller;
  3612. }();
  3613. // A function call node.
  3614. //
  3615. var Call =
  3616. /*#__PURE__*/
  3617. function (_Node) {
  3618. _inherits(Call, _Node);
  3619. function Call(name, args, index, currentFileInfo) {
  3620. var _this;
  3621. _classCallCheck(this, Call);
  3622. _this = _possibleConstructorReturn(this, _getPrototypeOf(Call).call(this));
  3623. _this.name = name;
  3624. _this.args = args;
  3625. _this.calc = name === 'calc';
  3626. _this._index = index;
  3627. _this._fileInfo = currentFileInfo;
  3628. return _this;
  3629. }
  3630. _createClass(Call, [{
  3631. key: "accept",
  3632. value: function accept(visitor) {
  3633. if (this.args) {
  3634. this.args = visitor.visitArray(this.args);
  3635. }
  3636. } //
  3637. // When evaluating a function call,
  3638. // we either find the function in the functionRegistry,
  3639. // in which case we call it, passing the evaluated arguments,
  3640. // if this returns null or we cannot find the function, we
  3641. // simply print it out as it appeared originally [2].
  3642. //
  3643. // The reason why we evaluate the arguments, is in the case where
  3644. // we try to pass a variable to a function, like: `saturate(@color)`.
  3645. // The function should receive the value, not the variable.
  3646. //
  3647. }, {
  3648. key: "eval",
  3649. value: function _eval(context) {
  3650. /**
  3651. * Turn off math for calc(), and switch back on for evaluating nested functions
  3652. */
  3653. var currentMathContext = context.mathOn;
  3654. context.mathOn = !this.calc;
  3655. if (this.calc || context.inCalc) {
  3656. context.enterCalc();
  3657. }
  3658. var args = this.args.map(function (a) {
  3659. return a.eval(context);
  3660. });
  3661. if (this.calc || context.inCalc) {
  3662. context.exitCalc();
  3663. }
  3664. context.mathOn = currentMathContext;
  3665. var result;
  3666. var funcCaller = new functionCaller(this.name, context, this.getIndex(), this.fileInfo());
  3667. if (funcCaller.isValid()) {
  3668. try {
  3669. result = funcCaller.call(args);
  3670. } catch (e) {
  3671. throw {
  3672. type: e.type || 'Runtime',
  3673. message: `error evaluating function \`${this.name}\`${e.message ? `: ${e.message}` : ''}`,
  3674. index: this.getIndex(),
  3675. filename: this.fileInfo().filename,
  3676. line: e.lineNumber,
  3677. column: e.columnNumber
  3678. };
  3679. }
  3680. if (result !== null && result !== undefined) {
  3681. // Results that that are not nodes are cast as Anonymous nodes
  3682. // Falsy values or booleans are returned as empty nodes
  3683. if (!(result instanceof Node)) {
  3684. if (!result || result === true) {
  3685. result = new Anonymous(null);
  3686. } else {
  3687. result = new Anonymous(result.toString());
  3688. }
  3689. }
  3690. result._index = this._index;
  3691. result._fileInfo = this._fileInfo;
  3692. return result;
  3693. }
  3694. }
  3695. return new Call(this.name, args, this.getIndex(), this.fileInfo());
  3696. }
  3697. }, {
  3698. key: "genCSS",
  3699. value: function genCSS(context, output) {
  3700. output.add(`${this.name}(`, this.fileInfo(), this.getIndex());
  3701. for (var i = 0; i < this.args.length; i++) {
  3702. this.args[i].genCSS(context, output);
  3703. if (i + 1 < this.args.length) {
  3704. output.add(', ');
  3705. }
  3706. }
  3707. output.add(')');
  3708. }
  3709. }]);
  3710. return Call;
  3711. }(Node);
  3712. Call.prototype.type = 'Call';
  3713. var Variable =
  3714. /*#__PURE__*/
  3715. function (_Node) {
  3716. _inherits(Variable, _Node);
  3717. function Variable(name, index, currentFileInfo) {
  3718. var _this;
  3719. _classCallCheck(this, Variable);
  3720. _this = _possibleConstructorReturn(this, _getPrototypeOf(Variable).call(this));
  3721. _this.name = name;
  3722. _this._index = index;
  3723. _this._fileInfo = currentFileInfo;
  3724. return _this;
  3725. }
  3726. _createClass(Variable, [{
  3727. key: "eval",
  3728. value: function _eval(context) {
  3729. var variable;
  3730. var name = this.name;
  3731. if (name.indexOf('@@') === 0) {
  3732. name = `@${new Variable(name.slice(1), this.getIndex(), this.fileInfo()).eval(context).value}`;
  3733. }
  3734. if (this.evaluating) {
  3735. throw {
  3736. type: 'Name',
  3737. message: `Recursive variable definition for ${name}`,
  3738. filename: this.fileInfo().filename,
  3739. index: this.getIndex()
  3740. };
  3741. }
  3742. this.evaluating = true;
  3743. variable = this.find(context.frames, function (frame) {
  3744. var v = frame.variable(name);
  3745. if (v) {
  3746. if (v.important) {
  3747. var importantScope = context.importantScope[context.importantScope.length - 1];
  3748. importantScope.important = v.important;
  3749. } // If in calc, wrap vars in a function call to cascade evaluate args first
  3750. if (context.inCalc) {
  3751. return new Call('_SELF', [v.value]).eval(context);
  3752. } else {
  3753. return v.value.eval(context);
  3754. }
  3755. }
  3756. });
  3757. if (variable) {
  3758. this.evaluating = false;
  3759. return variable;
  3760. } else {
  3761. throw {
  3762. type: 'Name',
  3763. message: `variable ${name} is undefined`,
  3764. filename: this.fileInfo().filename,
  3765. index: this.getIndex()
  3766. };
  3767. }
  3768. }
  3769. }, {
  3770. key: "find",
  3771. value: function find(obj, fun) {
  3772. for (var i = 0, r; i < obj.length; i++) {
  3773. r = fun.call(obj, obj[i]);
  3774. if (r) {
  3775. return r;
  3776. }
  3777. }
  3778. return null;
  3779. }
  3780. }]);
  3781. return Variable;
  3782. }(Node);
  3783. Variable.prototype.type = 'Variable';
  3784. var Property =
  3785. /*#__PURE__*/
  3786. function (_Node) {
  3787. _inherits(Property, _Node);
  3788. function Property(name, index, currentFileInfo) {
  3789. var _this;
  3790. _classCallCheck(this, Property);
  3791. _this = _possibleConstructorReturn(this, _getPrototypeOf(Property).call(this));
  3792. _this.name = name;
  3793. _this._index = index;
  3794. _this._fileInfo = currentFileInfo;
  3795. return _this;
  3796. }
  3797. _createClass(Property, [{
  3798. key: "eval",
  3799. value: function _eval(context) {
  3800. var property;
  3801. var name = this.name; // TODO: shorten this reference
  3802. var mergeRules = context.pluginManager.less.visitors.ToCSSVisitor.prototype._mergeRules;
  3803. if (this.evaluating) {
  3804. throw {
  3805. type: 'Name',
  3806. message: `Recursive property reference for ${name}`,
  3807. filename: this.fileInfo().filename,
  3808. index: this.getIndex()
  3809. };
  3810. }
  3811. this.evaluating = true;
  3812. property = this.find(context.frames, function (frame) {
  3813. var v;
  3814. var vArr = frame.property(name);
  3815. if (vArr) {
  3816. for (var i = 0; i < vArr.length; i++) {
  3817. v = vArr[i];
  3818. vArr[i] = new Declaration(v.name, v.value, v.important, v.merge, v.index, v.currentFileInfo, v.inline, v.variable);
  3819. }
  3820. mergeRules(vArr);
  3821. v = vArr[vArr.length - 1];
  3822. if (v.important) {
  3823. var importantScope = context.importantScope[context.importantScope.length - 1];
  3824. importantScope.important = v.important;
  3825. }
  3826. v = v.value.eval(context);
  3827. return v;
  3828. }
  3829. });
  3830. if (property) {
  3831. this.evaluating = false;
  3832. return property;
  3833. } else {
  3834. throw {
  3835. type: 'Name',
  3836. message: `Property '${name}' is undefined`,
  3837. filename: this.currentFileInfo.filename,
  3838. index: this.index
  3839. };
  3840. }
  3841. }
  3842. }, {
  3843. key: "find",
  3844. value: function find(obj, fun) {
  3845. for (var i = 0, r; i < obj.length; i++) {
  3846. r = fun.call(obj, obj[i]);
  3847. if (r) {
  3848. return r;
  3849. }
  3850. }
  3851. return null;
  3852. }
  3853. }]);
  3854. return Property;
  3855. }(Node);
  3856. Property.prototype.type = 'Property';
  3857. var Attribute =
  3858. /*#__PURE__*/
  3859. function (_Node) {
  3860. _inherits(Attribute, _Node);
  3861. function Attribute(key, op, value) {
  3862. var _this;
  3863. _classCallCheck(this, Attribute);
  3864. _this = _possibleConstructorReturn(this, _getPrototypeOf(Attribute).call(this));
  3865. _this.key = key;
  3866. _this.op = op;
  3867. _this.value = value;
  3868. return _this;
  3869. }
  3870. _createClass(Attribute, [{
  3871. key: "eval",
  3872. value: function _eval(context) {
  3873. return new Attribute(this.key.eval ? this.key.eval(context) : this.key, this.op, this.value && this.value.eval ? this.value.eval(context) : this.value);
  3874. }
  3875. }, {
  3876. key: "genCSS",
  3877. value: function genCSS(context, output) {
  3878. output.add(this.toCSS(context));
  3879. }
  3880. }, {
  3881. key: "toCSS",
  3882. value: function toCSS(context) {
  3883. var value = this.key.toCSS ? this.key.toCSS(context) : this.key;
  3884. if (this.op) {
  3885. value += this.op;
  3886. value += this.value.toCSS ? this.value.toCSS(context) : this.value;
  3887. }
  3888. return `[${value}]`;
  3889. }
  3890. }]);
  3891. return Attribute;
  3892. }(Node);
  3893. Attribute.prototype.type = 'Attribute';
  3894. var Quoted =
  3895. /*#__PURE__*/
  3896. function (_Node) {
  3897. _inherits(Quoted, _Node);
  3898. function Quoted(str, content, escaped, index, currentFileInfo) {
  3899. var _this;
  3900. _classCallCheck(this, Quoted);
  3901. _this = _possibleConstructorReturn(this, _getPrototypeOf(Quoted).call(this));
  3902. _this.escaped = escaped == null ? true : escaped;
  3903. _this.value = content || '';
  3904. _this.quote = str.charAt(0);
  3905. _this._index = index;
  3906. _this._fileInfo = currentFileInfo;
  3907. _this.variableRegex = /@\{([\w-]+)\}/g;
  3908. _this.propRegex = /\$\{([\w-]+)\}/g;
  3909. _this.allowRoot = escaped;
  3910. return _this;
  3911. }
  3912. _createClass(Quoted, [{
  3913. key: "genCSS",
  3914. value: function genCSS(context, output) {
  3915. if (!this.escaped) {
  3916. output.add(this.quote, this.fileInfo(), this.getIndex());
  3917. }
  3918. output.add(this.value);
  3919. if (!this.escaped) {
  3920. output.add(this.quote);
  3921. }
  3922. }
  3923. }, {
  3924. key: "containsVariables",
  3925. value: function containsVariables() {
  3926. return this.value.match(this.variableRegex);
  3927. }
  3928. }, {
  3929. key: "eval",
  3930. value: function _eval(context) {
  3931. var that = this;
  3932. var value = this.value;
  3933. var variableReplacement = function variableReplacement(_, name) {
  3934. var v = new Variable(`@${name}`, that.getIndex(), that.fileInfo()).eval(context, true);
  3935. return v instanceof Quoted ? v.value : v.toCSS();
  3936. };
  3937. var propertyReplacement = function propertyReplacement(_, name) {
  3938. var v = new Property(`$${name}`, that.getIndex(), that.fileInfo()).eval(context, true);
  3939. return v instanceof Quoted ? v.value : v.toCSS();
  3940. };
  3941. function iterativeReplace(value, regexp, replacementFnc) {
  3942. var evaluatedValue = value;
  3943. do {
  3944. value = evaluatedValue.toString();
  3945. evaluatedValue = value.replace(regexp, replacementFnc);
  3946. } while (value !== evaluatedValue);
  3947. return evaluatedValue;
  3948. }
  3949. value = iterativeReplace(value, this.variableRegex, variableReplacement);
  3950. value = iterativeReplace(value, this.propRegex, propertyReplacement);
  3951. return new Quoted(this.quote + value + this.quote, value, this.escaped, this.getIndex(), this.fileInfo());
  3952. }
  3953. }, {
  3954. key: "compare",
  3955. value: function compare(other) {
  3956. // when comparing quoted strings allow the quote to differ
  3957. if (other.type === 'Quoted' && !this.escaped && !other.escaped) {
  3958. return Node.numericCompare(this.value, other.value);
  3959. } else {
  3960. return other.toCSS && this.toCSS() === other.toCSS() ? 0 : undefined;
  3961. }
  3962. }
  3963. }]);
  3964. return Quoted;
  3965. }(Node);
  3966. Quoted.prototype.type = 'Quoted';
  3967. var URL =
  3968. /*#__PURE__*/
  3969. function (_Node) {
  3970. _inherits(URL, _Node);
  3971. function URL(val, index, currentFileInfo, isEvald) {
  3972. var _this;
  3973. _classCallCheck(this, URL);
  3974. _this = _possibleConstructorReturn(this, _getPrototypeOf(URL).call(this));
  3975. _this.value = val;
  3976. _this._index = index;
  3977. _this._fileInfo = currentFileInfo;
  3978. _this.isEvald = isEvald;
  3979. return _this;
  3980. }
  3981. _createClass(URL, [{
  3982. key: "accept",
  3983. value: function accept(visitor) {
  3984. this.value = visitor.visit(this.value);
  3985. }
  3986. }, {
  3987. key: "genCSS",
  3988. value: function genCSS(context, output) {
  3989. output.add('url(');
  3990. this.value.genCSS(context, output);
  3991. output.add(')');
  3992. }
  3993. }, {
  3994. key: "eval",
  3995. value: function _eval(context) {
  3996. var val = this.value.eval(context);
  3997. var rootpath;
  3998. if (!this.isEvald) {
  3999. // Add the rootpath if the URL requires a rewrite
  4000. rootpath = this.fileInfo() && this.fileInfo().rootpath;
  4001. if (typeof rootpath === 'string' && typeof val.value === 'string' && context.pathRequiresRewrite(val.value)) {
  4002. if (!val.quote) {
  4003. rootpath = escapePath(rootpath);
  4004. }
  4005. val.value = context.rewritePath(val.value, rootpath);
  4006. } else {
  4007. val.value = context.normalizePath(val.value);
  4008. } // Add url args if enabled
  4009. if (context.urlArgs) {
  4010. if (!val.value.match(/^\s*data:/)) {
  4011. var delimiter = val.value.indexOf('?') === -1 ? '?' : '&';
  4012. var urlArgs = delimiter + context.urlArgs;
  4013. if (val.value.indexOf('#') !== -1) {
  4014. val.value = val.value.replace('#', `${urlArgs}#`);
  4015. } else {
  4016. val.value += urlArgs;
  4017. }
  4018. }
  4019. }
  4020. }
  4021. return new URL(val, this.getIndex(), this.fileInfo(), true);
  4022. }
  4023. }]);
  4024. return URL;
  4025. }(Node);
  4026. URL.prototype.type = 'Url';
  4027. function escapePath(path) {
  4028. return path.replace(/[\(\)'"\s]/g, function (match) {
  4029. return `\\${match}`;
  4030. });
  4031. }
  4032. var Media =
  4033. /*#__PURE__*/
  4034. function (_AtRule) {
  4035. _inherits(Media, _AtRule);
  4036. function Media(value, features, index, currentFileInfo, visibilityInfo) {
  4037. var _this;
  4038. _classCallCheck(this, Media);
  4039. _this = _possibleConstructorReturn(this, _getPrototypeOf(Media).call(this));
  4040. _this._index = index;
  4041. _this._fileInfo = currentFileInfo;
  4042. var selectors = new Selector([], null, null, _this._index, _this._fileInfo).createEmptySelectors();
  4043. _this.features = new Value(features);
  4044. _this.rules = [new Ruleset(selectors, value)];
  4045. _this.rules[0].allowImports = true;
  4046. _this.copyVisibilityInfo(visibilityInfo);
  4047. _this.allowRoot = true;
  4048. _this.setParent(selectors, _assertThisInitialized(_this));
  4049. _this.setParent(_this.features, _assertThisInitialized(_this));
  4050. _this.setParent(_this.rules, _assertThisInitialized(_this));
  4051. return _this;
  4052. }
  4053. _createClass(Media, [{
  4054. key: "isRulesetLike",
  4055. value: function isRulesetLike() {
  4056. return true;
  4057. }
  4058. }, {
  4059. key: "accept",
  4060. value: function accept(visitor) {
  4061. if (this.features) {
  4062. this.features = visitor.visit(this.features);
  4063. }
  4064. if (this.rules) {
  4065. this.rules = visitor.visitArray(this.rules);
  4066. }
  4067. }
  4068. }, {
  4069. key: "genCSS",
  4070. value: function genCSS(context, output) {
  4071. output.add('@media ', this._fileInfo, this._index);
  4072. this.features.genCSS(context, output);
  4073. this.outputRuleset(context, output, this.rules);
  4074. }
  4075. }, {
  4076. key: "eval",
  4077. value: function _eval(context) {
  4078. if (!context.mediaBlocks) {
  4079. context.mediaBlocks = [];
  4080. context.mediaPath = [];
  4081. }
  4082. var media = new Media(null, [], this._index, this._fileInfo, this.visibilityInfo());
  4083. if (this.debugInfo) {
  4084. this.rules[0].debugInfo = this.debugInfo;
  4085. media.debugInfo = this.debugInfo;
  4086. }
  4087. media.features = this.features.eval(context);
  4088. context.mediaPath.push(media);
  4089. context.mediaBlocks.push(media);
  4090. this.rules[0].functionRegistry = context.frames[0].functionRegistry.inherit();
  4091. context.frames.unshift(this.rules[0]);
  4092. media.rules = [this.rules[0].eval(context)];
  4093. context.frames.shift();
  4094. context.mediaPath.pop();
  4095. return context.mediaPath.length === 0 ? media.evalTop(context) : media.evalNested(context);
  4096. }
  4097. }, {
  4098. key: "evalTop",
  4099. value: function evalTop(context) {
  4100. var result = this; // Render all dependent Media blocks.
  4101. if (context.mediaBlocks.length > 1) {
  4102. var selectors = new Selector([], null, null, this.getIndex(), this.fileInfo()).createEmptySelectors();
  4103. result = new Ruleset(selectors, context.mediaBlocks);
  4104. result.multiMedia = true;
  4105. result.copyVisibilityInfo(this.visibilityInfo());
  4106. this.setParent(result, this);
  4107. }
  4108. delete context.mediaBlocks;
  4109. delete context.mediaPath;
  4110. return result;
  4111. }
  4112. }, {
  4113. key: "evalNested",
  4114. value: function evalNested(context) {
  4115. var i;
  4116. var value;
  4117. var path = context.mediaPath.concat([this]); // Extract the media-query conditions separated with `,` (OR).
  4118. for (i = 0; i < path.length; i++) {
  4119. value = path[i].features instanceof Value ? path[i].features.value : path[i].features;
  4120. path[i] = Array.isArray(value) ? value : [value];
  4121. } // Trace all permutations to generate the resulting media-query.
  4122. //
  4123. // (a, b and c) with nested (d, e) ->
  4124. // a and d
  4125. // a and e
  4126. // b and c and d
  4127. // b and c and e
  4128. this.features = new Value(this.permute(path).map(function (path) {
  4129. path = path.map(function (fragment) {
  4130. return fragment.toCSS ? fragment : new Anonymous(fragment);
  4131. });
  4132. for (i = path.length - 1; i > 0; i--) {
  4133. path.splice(i, 0, new Anonymous('and'));
  4134. }
  4135. return new Expression(path);
  4136. }));
  4137. this.setParent(this.features, this); // Fake a tree-node that doesn't output anything.
  4138. return new Ruleset([], []);
  4139. }
  4140. }, {
  4141. key: "permute",
  4142. value: function permute(arr) {
  4143. if (arr.length === 0) {
  4144. return [];
  4145. } else if (arr.length === 1) {
  4146. return arr[0];
  4147. } else {
  4148. var result = [];
  4149. var rest = this.permute(arr.slice(1));
  4150. for (var i = 0; i < rest.length; i++) {
  4151. for (var j = 0; j < arr[0].length; j++) {
  4152. result.push([arr[0][j]].concat(rest[i]));
  4153. }
  4154. }
  4155. return result;
  4156. }
  4157. }
  4158. }, {
  4159. key: "bubbleSelectors",
  4160. value: function bubbleSelectors(selectors) {
  4161. if (!selectors) {
  4162. return;
  4163. }
  4164. this.rules = [new Ruleset(copyArray(selectors), [this.rules[0]])];
  4165. this.setParent(this.rules, this);
  4166. }
  4167. }]);
  4168. return Media;
  4169. }(AtRule);
  4170. Media.prototype.type = 'Media';
  4171. // CSS @import node
  4172. //
  4173. // The general strategy here is that we don't want to wait
  4174. // for the parsing to be completed, before we start importing
  4175. // the file. That's because in the context of a browser,
  4176. // most of the time will be spent waiting for the server to respond.
  4177. //
  4178. // On creation, we push the import path to our import queue, though
  4179. // `import,push`, we also pass it a callback, which it'll call once
  4180. // the file has been fetched, and parsed.
  4181. //
  4182. var Import =
  4183. /*#__PURE__*/
  4184. function (_Node) {
  4185. _inherits(Import, _Node);
  4186. function Import(path, features, options, index, currentFileInfo, visibilityInfo) {
  4187. var _this;
  4188. _classCallCheck(this, Import);
  4189. _this = _possibleConstructorReturn(this, _getPrototypeOf(Import).call(this));
  4190. _this.options = options;
  4191. _this._index = index;
  4192. _this._fileInfo = currentFileInfo;
  4193. _this.path = path;
  4194. _this.features = features;
  4195. _this.allowRoot = true;
  4196. if (_this.options.less !== undefined || _this.options.inline) {
  4197. _this.css = !_this.options.less || _this.options.inline;
  4198. } else {
  4199. var pathValue = _this.getPath();
  4200. if (pathValue && /[#\.\&\?]css([\?;].*)?$/.test(pathValue)) {
  4201. _this.css = true;
  4202. }
  4203. }
  4204. _this.copyVisibilityInfo(visibilityInfo);
  4205. _this.setParent(_this.features, _assertThisInitialized(_this));
  4206. _this.setParent(_this.path, _assertThisInitialized(_this));
  4207. return _this;
  4208. }
  4209. _createClass(Import, [{
  4210. key: "accept",
  4211. value: function accept(visitor) {
  4212. if (this.features) {
  4213. this.features = visitor.visit(this.features);
  4214. }
  4215. this.path = visitor.visit(this.path);
  4216. if (!this.options.isPlugin && !this.options.inline && this.root) {
  4217. this.root = visitor.visit(this.root);
  4218. }
  4219. }
  4220. }, {
  4221. key: "genCSS",
  4222. value: function genCSS(context, output) {
  4223. if (this.css && this.path._fileInfo.reference === undefined) {
  4224. output.add('@import ', this._fileInfo, this._index);
  4225. this.path.genCSS(context, output);
  4226. if (this.features) {
  4227. output.add(' ');
  4228. this.features.genCSS(context, output);
  4229. }
  4230. output.add(';');
  4231. }
  4232. }
  4233. }, {
  4234. key: "getPath",
  4235. value: function getPath() {
  4236. return this.path instanceof URL ? this.path.value.value : this.path.value;
  4237. }
  4238. }, {
  4239. key: "isVariableImport",
  4240. value: function isVariableImport() {
  4241. var path = this.path;
  4242. if (path instanceof URL) {
  4243. path = path.value;
  4244. }
  4245. if (path instanceof Quoted) {
  4246. return path.containsVariables();
  4247. }
  4248. return true;
  4249. }
  4250. }, {
  4251. key: "evalForImport",
  4252. value: function evalForImport(context) {
  4253. var path = this.path;
  4254. if (path instanceof URL) {
  4255. path = path.value;
  4256. }
  4257. return new Import(path.eval(context), this.features, this.options, this._index, this._fileInfo, this.visibilityInfo());
  4258. }
  4259. }, {
  4260. key: "evalPath",
  4261. value: function evalPath(context) {
  4262. var path = this.path.eval(context);
  4263. var fileInfo = this._fileInfo;
  4264. if (!(path instanceof URL)) {
  4265. // Add the rootpath if the URL requires a rewrite
  4266. var pathValue = path.value;
  4267. if (fileInfo && pathValue && context.pathRequiresRewrite(pathValue)) {
  4268. path.value = context.rewritePath(pathValue, fileInfo.rootpath);
  4269. } else {
  4270. path.value = context.normalizePath(path.value);
  4271. }
  4272. }
  4273. return path;
  4274. }
  4275. }, {
  4276. key: "eval",
  4277. value: function _eval(context) {
  4278. var result = this.doEval(context);
  4279. if (this.options.reference || this.blocksVisibility()) {
  4280. if (result.length || result.length === 0) {
  4281. result.forEach(function (node) {
  4282. node.addVisibilityBlock();
  4283. });
  4284. } else {
  4285. result.addVisibilityBlock();
  4286. }
  4287. }
  4288. return result;
  4289. }
  4290. }, {
  4291. key: "doEval",
  4292. value: function doEval(context) {
  4293. var ruleset;
  4294. var registry;
  4295. var features = this.features && this.features.eval(context);
  4296. if (this.options.isPlugin) {
  4297. if (this.root && this.root.eval) {
  4298. try {
  4299. this.root.eval(context);
  4300. } catch (e) {
  4301. e.message = 'Plugin error during evaluation';
  4302. throw new LessError(e, this.root.imports, this.root.filename);
  4303. }
  4304. }
  4305. registry = context.frames[0] && context.frames[0].functionRegistry;
  4306. if (registry && this.root && this.root.functions) {
  4307. registry.addMultiple(this.root.functions);
  4308. }
  4309. return [];
  4310. }
  4311. if (this.skip) {
  4312. if (typeof this.skip === 'function') {
  4313. this.skip = this.skip();
  4314. }
  4315. if (this.skip) {
  4316. return [];
  4317. }
  4318. }
  4319. if (this.options.inline) {
  4320. var contents = new Anonymous(this.root, 0, {
  4321. filename: this.importedFilename,
  4322. reference: this.path._fileInfo && this.path._fileInfo.reference
  4323. }, true, true);
  4324. return this.features ? new Media([contents], this.features.value) : [contents];
  4325. } else if (this.css) {
  4326. var newImport = new Import(this.evalPath(context), features, this.options, this._index);
  4327. if (!newImport.css && this.error) {
  4328. throw this.error;
  4329. }
  4330. return newImport;
  4331. } else {
  4332. ruleset = new Ruleset(null, copyArray(this.root.rules));
  4333. ruleset.evalImports(context);
  4334. return this.features ? new Media(ruleset.rules, this.features.value) : ruleset.rules;
  4335. }
  4336. }
  4337. }]);
  4338. return Import;
  4339. }(Node);
  4340. Import.prototype.type = 'Import';
  4341. var JsEvalNode =
  4342. /*#__PURE__*/
  4343. function (_Node) {
  4344. _inherits(JsEvalNode, _Node);
  4345. function JsEvalNode() {
  4346. _classCallCheck(this, JsEvalNode);
  4347. return _possibleConstructorReturn(this, _getPrototypeOf(JsEvalNode).apply(this, arguments));
  4348. }
  4349. _createClass(JsEvalNode, [{
  4350. key: "evaluateJavaScript",
  4351. value: function evaluateJavaScript(expression, context) {
  4352. var result;
  4353. var that = this;
  4354. var evalContext = {};
  4355. if (!context.javascriptEnabled) {
  4356. throw {
  4357. message: 'Inline JavaScript is not enabled. Is it set in your options?',
  4358. filename: this.fileInfo().filename,
  4359. index: this.getIndex()
  4360. };
  4361. }
  4362. expression = expression.replace(/@\{([\w-]+)\}/g, function (_, name) {
  4363. return that.jsify(new Variable(`@${name}`, that.getIndex(), that.fileInfo()).eval(context));
  4364. });
  4365. try {
  4366. expression = new Function(`return (${expression})`);
  4367. } catch (e) {
  4368. throw {
  4369. message: `JavaScript evaluation error: ${e.message} from \`${expression}\``,
  4370. filename: this.fileInfo().filename,
  4371. index: this.getIndex()
  4372. };
  4373. }
  4374. var variables = context.frames[0].variables();
  4375. for (var k in variables) {
  4376. if (variables.hasOwnProperty(k)) {
  4377. /* jshint loopfunc:true */
  4378. evalContext[k.slice(1)] = {
  4379. value: variables[k].value,
  4380. toJS: function toJS() {
  4381. return this.value.eval(context).toCSS();
  4382. }
  4383. };
  4384. }
  4385. }
  4386. try {
  4387. result = expression.call(evalContext);
  4388. } catch (e) {
  4389. throw {
  4390. message: `JavaScript evaluation error: '${e.name}: ${e.message.replace(/["]/g, '\'')}'`,
  4391. filename: this.fileInfo().filename,
  4392. index: this.getIndex()
  4393. };
  4394. }
  4395. return result;
  4396. }
  4397. }, {
  4398. key: "jsify",
  4399. value: function jsify(obj) {
  4400. if (Array.isArray(obj.value) && obj.value.length > 1) {
  4401. return `[${obj.value.map(function (v) {
  4402. return v.toCSS();
  4403. }).join(', ')}]`;
  4404. } else {
  4405. return obj.toCSS();
  4406. }
  4407. }
  4408. }]);
  4409. return JsEvalNode;
  4410. }(Node);
  4411. var JavaScript =
  4412. /*#__PURE__*/
  4413. function (_JsEvalNode) {
  4414. _inherits(JavaScript, _JsEvalNode);
  4415. function JavaScript(string, escaped, index, currentFileInfo) {
  4416. var _this;
  4417. _classCallCheck(this, JavaScript);
  4418. _this = _possibleConstructorReturn(this, _getPrototypeOf(JavaScript).call(this));
  4419. _this.escaped = escaped;
  4420. _this.expression = string;
  4421. _this._index = index;
  4422. _this._fileInfo = currentFileInfo;
  4423. return _this;
  4424. }
  4425. _createClass(JavaScript, [{
  4426. key: "eval",
  4427. value: function _eval(context) {
  4428. var result = this.evaluateJavaScript(this.expression, context);
  4429. var type = typeof result;
  4430. if (type === 'number' && !isNaN(result)) {
  4431. return new Dimension(result);
  4432. } else if (type === 'string') {
  4433. return new Quoted(`"${result}"`, result, this.escaped, this._index);
  4434. } else if (Array.isArray(result)) {
  4435. return new Anonymous(result.join(', '));
  4436. } else {
  4437. return new Anonymous(result);
  4438. }
  4439. }
  4440. }]);
  4441. return JavaScript;
  4442. }(JsEvalNode);
  4443. JavaScript.prototype.type = 'JavaScript';
  4444. var Assignment =
  4445. /*#__PURE__*/
  4446. function (_Node) {
  4447. _inherits(Assignment, _Node);
  4448. function Assignment(key, val) {
  4449. var _this;
  4450. _classCallCheck(this, Assignment);
  4451. _this = _possibleConstructorReturn(this, _getPrototypeOf(Assignment).call(this));
  4452. _this.key = key;
  4453. _this.value = val;
  4454. return _this;
  4455. }
  4456. _createClass(Assignment, [{
  4457. key: "accept",
  4458. value: function accept(visitor) {
  4459. this.value = visitor.visit(this.value);
  4460. }
  4461. }, {
  4462. key: "eval",
  4463. value: function _eval(context) {
  4464. if (this.value.eval) {
  4465. return new Assignment(this.key, this.value.eval(context));
  4466. }
  4467. return this;
  4468. }
  4469. }, {
  4470. key: "genCSS",
  4471. value: function genCSS(context, output) {
  4472. output.add(`${this.key}=`);
  4473. if (this.value.genCSS) {
  4474. this.value.genCSS(context, output);
  4475. } else {
  4476. output.add(this.value);
  4477. }
  4478. }
  4479. }]);
  4480. return Assignment;
  4481. }(Node);
  4482. Assignment.prototype.type = 'Assignment';
  4483. var Condition =
  4484. /*#__PURE__*/
  4485. function (_Node) {
  4486. _inherits(Condition, _Node);
  4487. function Condition(op, l, r, i, negate) {
  4488. var _this;
  4489. _classCallCheck(this, Condition);
  4490. _this = _possibleConstructorReturn(this, _getPrototypeOf(Condition).call(this));
  4491. _this.op = op.trim();
  4492. _this.lvalue = l;
  4493. _this.rvalue = r;
  4494. _this._index = i;
  4495. _this.negate = negate;
  4496. return _this;
  4497. }
  4498. _createClass(Condition, [{
  4499. key: "accept",
  4500. value: function accept(visitor) {
  4501. this.lvalue = visitor.visit(this.lvalue);
  4502. this.rvalue = visitor.visit(this.rvalue);
  4503. }
  4504. }, {
  4505. key: "eval",
  4506. value: function _eval(context) {
  4507. var result = function (op, a, b) {
  4508. switch (op) {
  4509. case 'and':
  4510. return a && b;
  4511. case 'or':
  4512. return a || b;
  4513. default:
  4514. switch (Node.compare(a, b)) {
  4515. case -1:
  4516. return op === '<' || op === '=<' || op === '<=';
  4517. case 0:
  4518. return op === '=' || op === '>=' || op === '=<' || op === '<=';
  4519. case 1:
  4520. return op === '>' || op === '>=';
  4521. default:
  4522. return false;
  4523. }
  4524. }
  4525. }(this.op, this.lvalue.eval(context), this.rvalue.eval(context));
  4526. return this.negate ? !result : result;
  4527. }
  4528. }]);
  4529. return Condition;
  4530. }(Node);
  4531. Condition.prototype.type = 'Condition';
  4532. var UnicodeDescriptor =
  4533. /*#__PURE__*/
  4534. function (_Node) {
  4535. _inherits(UnicodeDescriptor, _Node);
  4536. function UnicodeDescriptor(value) {
  4537. var _this;
  4538. _classCallCheck(this, UnicodeDescriptor);
  4539. _this = _possibleConstructorReturn(this, _getPrototypeOf(UnicodeDescriptor).call(this));
  4540. _this.value = value;
  4541. return _this;
  4542. }
  4543. return UnicodeDescriptor;
  4544. }(Node);
  4545. UnicodeDescriptor.prototype.type = 'UnicodeDescriptor';
  4546. var Negative =
  4547. /*#__PURE__*/
  4548. function (_Node) {
  4549. _inherits(Negative, _Node);
  4550. function Negative(node) {
  4551. var _this;
  4552. _classCallCheck(this, Negative);
  4553. _this = _possibleConstructorReturn(this, _getPrototypeOf(Negative).call(this));
  4554. _this.value = node;
  4555. return _this;
  4556. }
  4557. _createClass(Negative, [{
  4558. key: "genCSS",
  4559. value: function genCSS(context, output) {
  4560. output.add('-');
  4561. this.value.genCSS(context, output);
  4562. }
  4563. }, {
  4564. key: "eval",
  4565. value: function _eval(context) {
  4566. if (context.isMathOn()) {
  4567. return new Operation('*', [new Dimension(-1), this.value]).eval(context);
  4568. }
  4569. return new Negative(this.value.eval(context));
  4570. }
  4571. }]);
  4572. return Negative;
  4573. }(Node);
  4574. Negative.prototype.type = 'Negative';
  4575. var Extend =
  4576. /*#__PURE__*/
  4577. function (_Node) {
  4578. _inherits(Extend, _Node);
  4579. function Extend(selector, option, index, currentFileInfo, visibilityInfo) {
  4580. var _this;
  4581. _classCallCheck(this, Extend);
  4582. _this = _possibleConstructorReturn(this, _getPrototypeOf(Extend).call(this));
  4583. _this.selector = selector;
  4584. _this.option = option;
  4585. _this.object_id = Extend.next_id++;
  4586. _this.parent_ids = [_this.object_id];
  4587. _this._index = index;
  4588. _this._fileInfo = currentFileInfo;
  4589. _this.copyVisibilityInfo(visibilityInfo);
  4590. _this.allowRoot = true;
  4591. switch (option) {
  4592. case 'all':
  4593. _this.allowBefore = true;
  4594. _this.allowAfter = true;
  4595. break;
  4596. default:
  4597. _this.allowBefore = false;
  4598. _this.allowAfter = false;
  4599. break;
  4600. }
  4601. _this.setParent(_this.selector, _assertThisInitialized(_this));
  4602. return _this;
  4603. }
  4604. _createClass(Extend, [{
  4605. key: "accept",
  4606. value: function accept(visitor) {
  4607. this.selector = visitor.visit(this.selector);
  4608. }
  4609. }, {
  4610. key: "eval",
  4611. value: function _eval(context) {
  4612. return new Extend(this.selector.eval(context), this.option, this.getIndex(), this.fileInfo(), this.visibilityInfo());
  4613. }
  4614. }, {
  4615. key: "clone",
  4616. value: function clone(context) {
  4617. return new Extend(this.selector, this.option, this.getIndex(), this.fileInfo(), this.visibilityInfo());
  4618. } // it concatenates (joins) all selectors in selector array
  4619. }, {
  4620. key: "findSelfSelectors",
  4621. value: function findSelfSelectors(selectors) {
  4622. var selfElements = [];
  4623. var i;
  4624. var selectorElements;
  4625. for (i = 0; i < selectors.length; i++) {
  4626. selectorElements = selectors[i].elements; // duplicate the logic in genCSS function inside the selector node.
  4627. // future TODO - move both logics into the selector joiner visitor
  4628. if (i > 0 && selectorElements.length && selectorElements[0].combinator.value === '') {
  4629. selectorElements[0].combinator.value = ' ';
  4630. }
  4631. selfElements = selfElements.concat(selectors[i].elements);
  4632. }
  4633. this.selfSelectors = [new Selector(selfElements)];
  4634. this.selfSelectors[0].copyVisibilityInfo(this.visibilityInfo());
  4635. }
  4636. }]);
  4637. return Extend;
  4638. }(Node);
  4639. Extend.next_id = 0;
  4640. Extend.prototype.type = 'Extend';
  4641. var VariableCall =
  4642. /*#__PURE__*/
  4643. function (_Node) {
  4644. _inherits(VariableCall, _Node);
  4645. function VariableCall(variable, index, currentFileInfo) {
  4646. var _this;
  4647. _classCallCheck(this, VariableCall);
  4648. _this = _possibleConstructorReturn(this, _getPrototypeOf(VariableCall).call(this));
  4649. _this.variable = variable;
  4650. _this._index = index;
  4651. _this._fileInfo = currentFileInfo;
  4652. _this.allowRoot = true;
  4653. return _this;
  4654. }
  4655. _createClass(VariableCall, [{
  4656. key: "eval",
  4657. value: function _eval(context) {
  4658. var rules;
  4659. var detachedRuleset = new Variable(this.variable, this.getIndex(), this.fileInfo()).eval(context);
  4660. var error = new LessError({
  4661. message: `Could not evaluate variable call ${this.variable}`
  4662. });
  4663. if (!detachedRuleset.ruleset) {
  4664. if (detachedRuleset.rules) {
  4665. rules = detachedRuleset;
  4666. } else if (Array.isArray(detachedRuleset)) {
  4667. rules = new Ruleset('', detachedRuleset);
  4668. } else if (Array.isArray(detachedRuleset.value)) {
  4669. rules = new Ruleset('', detachedRuleset.value);
  4670. } else {
  4671. throw error;
  4672. }
  4673. detachedRuleset = new DetachedRuleset(rules);
  4674. }
  4675. if (detachedRuleset.ruleset) {
  4676. return detachedRuleset.callEval(context);
  4677. }
  4678. throw error;
  4679. }
  4680. }]);
  4681. return VariableCall;
  4682. }(Node);
  4683. VariableCall.prototype.type = 'VariableCall';
  4684. var NamespaceValue =
  4685. /*#__PURE__*/
  4686. function (_Node) {
  4687. _inherits(NamespaceValue, _Node);
  4688. function NamespaceValue(ruleCall, lookups, important, index, fileInfo) {
  4689. var _this;
  4690. _classCallCheck(this, NamespaceValue);
  4691. _this = _possibleConstructorReturn(this, _getPrototypeOf(NamespaceValue).call(this));
  4692. _this.value = ruleCall;
  4693. _this.lookups = lookups;
  4694. _this.important = important;
  4695. _this._index = index;
  4696. _this._fileInfo = fileInfo;
  4697. return _this;
  4698. }
  4699. _createClass(NamespaceValue, [{
  4700. key: "eval",
  4701. value: function _eval(context) {
  4702. var i;
  4703. var name;
  4704. var rules = this.value.eval(context);
  4705. for (i = 0; i < this.lookups.length; i++) {
  4706. name = this.lookups[i];
  4707. /**
  4708. * Eval'd DRs return rulesets.
  4709. * Eval'd mixins return rules, so let's make a ruleset if we need it.
  4710. * We need to do this because of late parsing of values
  4711. */
  4712. if (Array.isArray(rules)) {
  4713. rules = new Ruleset([new Selector()], rules);
  4714. }
  4715. if (name === '') {
  4716. rules = rules.lastDeclaration();
  4717. } else if (name.charAt(0) === '@') {
  4718. if (name.charAt(1) === '@') {
  4719. name = `@${new Variable(name.substr(1)).eval(context).value}`;
  4720. }
  4721. if (rules.variables) {
  4722. rules = rules.variable(name);
  4723. }
  4724. if (!rules) {
  4725. throw {
  4726. type: 'Name',
  4727. message: `variable ${name} not found`,
  4728. filename: this.fileInfo().filename,
  4729. index: this.getIndex()
  4730. };
  4731. }
  4732. } else {
  4733. if (name.substring(0, 2) === '$@') {
  4734. name = `$${new Variable(name.substr(1)).eval(context).value}`;
  4735. } else {
  4736. name = name.charAt(0) === '$' ? name : `$${name}`;
  4737. }
  4738. if (rules.properties) {
  4739. rules = rules.property(name);
  4740. }
  4741. if (!rules) {
  4742. throw {
  4743. type: 'Name',
  4744. message: `property "${name.substr(1)}" not found`,
  4745. filename: this.fileInfo().filename,
  4746. index: this.getIndex()
  4747. };
  4748. } // Properties are an array of values, since a ruleset can have multiple props.
  4749. // We pick the last one (the "cascaded" value)
  4750. rules = rules[rules.length - 1];
  4751. }
  4752. if (rules.value) {
  4753. rules = rules.eval(context).value;
  4754. }
  4755. if (rules.ruleset) {
  4756. rules = rules.ruleset.eval(context);
  4757. }
  4758. }
  4759. return rules;
  4760. }
  4761. }]);
  4762. return NamespaceValue;
  4763. }(Node);
  4764. NamespaceValue.prototype.type = 'NamespaceValue';
  4765. var Definition =
  4766. /*#__PURE__*/
  4767. function (_Ruleset) {
  4768. _inherits(Definition, _Ruleset);
  4769. function Definition(name, params, rules, condition, variadic, frames, visibilityInfo) {
  4770. var _this;
  4771. _classCallCheck(this, Definition);
  4772. _this = _possibleConstructorReturn(this, _getPrototypeOf(Definition).call(this));
  4773. _this.name = name || 'anonymous mixin';
  4774. _this.selectors = [new Selector([new Element(null, name, false, _this._index, _this._fileInfo)])];
  4775. _this.params = params;
  4776. _this.condition = condition;
  4777. _this.variadic = variadic;
  4778. _this.arity = params.length;
  4779. _this.rules = rules;
  4780. _this._lookups = {};
  4781. var optionalParameters = [];
  4782. _this.required = params.reduce(function (count, p) {
  4783. if (!p.name || p.name && !p.value) {
  4784. return count + 1;
  4785. } else {
  4786. optionalParameters.push(p.name);
  4787. return count;
  4788. }
  4789. }, 0);
  4790. _this.optionalParameters = optionalParameters;
  4791. _this.frames = frames;
  4792. _this.copyVisibilityInfo(visibilityInfo);
  4793. _this.allowRoot = true;
  4794. return _this;
  4795. }
  4796. _createClass(Definition, [{
  4797. key: "accept",
  4798. value: function accept(visitor) {
  4799. if (this.params && this.params.length) {
  4800. this.params = visitor.visitArray(this.params);
  4801. }
  4802. this.rules = visitor.visitArray(this.rules);
  4803. if (this.condition) {
  4804. this.condition = visitor.visit(this.condition);
  4805. }
  4806. }
  4807. }, {
  4808. key: "evalParams",
  4809. value: function evalParams(context, mixinEnv, args, evaldArguments) {
  4810. /* jshint boss:true */
  4811. var frame = new Ruleset(null, null);
  4812. var varargs;
  4813. var arg;
  4814. var params = copyArray(this.params);
  4815. var i;
  4816. var j;
  4817. var val;
  4818. var name;
  4819. var isNamedFound;
  4820. var argIndex;
  4821. var argsLength = 0;
  4822. if (mixinEnv.frames && mixinEnv.frames[0] && mixinEnv.frames[0].functionRegistry) {
  4823. frame.functionRegistry = mixinEnv.frames[0].functionRegistry.inherit();
  4824. }
  4825. mixinEnv = new contexts.Eval(mixinEnv, [frame].concat(mixinEnv.frames));
  4826. if (args) {
  4827. args = copyArray(args);
  4828. argsLength = args.length;
  4829. for (i = 0; i < argsLength; i++) {
  4830. arg = args[i];
  4831. if (name = arg && arg.name) {
  4832. isNamedFound = false;
  4833. for (j = 0; j < params.length; j++) {
  4834. if (!evaldArguments[j] && name === params[j].name) {
  4835. evaldArguments[j] = arg.value.eval(context);
  4836. frame.prependRule(new Declaration(name, arg.value.eval(context)));
  4837. isNamedFound = true;
  4838. break;
  4839. }
  4840. }
  4841. if (isNamedFound) {
  4842. args.splice(i, 1);
  4843. i--;
  4844. continue;
  4845. } else {
  4846. throw {
  4847. type: 'Runtime',
  4848. message: `Named argument for ${this.name} ${args[i].name} not found`
  4849. };
  4850. }
  4851. }
  4852. }
  4853. }
  4854. argIndex = 0;
  4855. for (i = 0; i < params.length; i++) {
  4856. if (evaldArguments[i]) {
  4857. continue;
  4858. }
  4859. arg = args && args[argIndex];
  4860. if (name = params[i].name) {
  4861. if (params[i].variadic) {
  4862. varargs = [];
  4863. for (j = argIndex; j < argsLength; j++) {
  4864. varargs.push(args[j].value.eval(context));
  4865. }
  4866. frame.prependRule(new Declaration(name, new Expression(varargs).eval(context)));
  4867. } else {
  4868. val = arg && arg.value;
  4869. if (val) {
  4870. // This was a mixin call, pass in a detached ruleset of it's eval'd rules
  4871. if (Array.isArray(val)) {
  4872. val = new DetachedRuleset(new Ruleset('', val));
  4873. } else {
  4874. val = val.eval(context);
  4875. }
  4876. } else if (params[i].value) {
  4877. val = params[i].value.eval(mixinEnv);
  4878. frame.resetCache();
  4879. } else {
  4880. throw {
  4881. type: 'Runtime',
  4882. message: `wrong number of arguments for ${this.name} (${argsLength} for ${this.arity})`
  4883. };
  4884. }
  4885. frame.prependRule(new Declaration(name, val));
  4886. evaldArguments[i] = val;
  4887. }
  4888. }
  4889. if (params[i].variadic && args) {
  4890. for (j = argIndex; j < argsLength; j++) {
  4891. evaldArguments[j] = args[j].value.eval(context);
  4892. }
  4893. }
  4894. argIndex++;
  4895. }
  4896. return frame;
  4897. }
  4898. }, {
  4899. key: "makeImportant",
  4900. value: function makeImportant() {
  4901. var rules = !this.rules ? this.rules : this.rules.map(function (r) {
  4902. if (r.makeImportant) {
  4903. return r.makeImportant(true);
  4904. } else {
  4905. return r;
  4906. }
  4907. });
  4908. var result = new Definition(this.name, this.params, rules, this.condition, this.variadic, this.frames);
  4909. return result;
  4910. }
  4911. }, {
  4912. key: "eval",
  4913. value: function _eval(context) {
  4914. return new Definition(this.name, this.params, this.rules, this.condition, this.variadic, this.frames || copyArray(context.frames));
  4915. }
  4916. }, {
  4917. key: "evalCall",
  4918. value: function evalCall(context, args, important) {
  4919. var _arguments = [];
  4920. var mixinFrames = this.frames ? this.frames.concat(context.frames) : context.frames;
  4921. var frame = this.evalParams(context, new contexts.Eval(context, mixinFrames), args, _arguments);
  4922. var rules;
  4923. var ruleset;
  4924. frame.prependRule(new Declaration('@arguments', new Expression(_arguments).eval(context)));
  4925. rules = copyArray(this.rules);
  4926. ruleset = new Ruleset(null, rules);
  4927. ruleset.originalRuleset = this;
  4928. ruleset = ruleset.eval(new contexts.Eval(context, [this, frame].concat(mixinFrames)));
  4929. if (important) {
  4930. ruleset = ruleset.makeImportant();
  4931. }
  4932. return ruleset;
  4933. }
  4934. }, {
  4935. key: "matchCondition",
  4936. value: function matchCondition(args, context) {
  4937. if (this.condition && !this.condition.eval(new contexts.Eval(context, [this.evalParams(context,
  4938. /* the parameter variables */
  4939. new contexts.Eval(context, this.frames ? this.frames.concat(context.frames) : context.frames), args, [])].concat(this.frames || []) // the parent namespace/mixin frames
  4940. .concat(context.frames)))) {
  4941. // the current environment frames
  4942. return false;
  4943. }
  4944. return true;
  4945. }
  4946. }, {
  4947. key: "matchArgs",
  4948. value: function matchArgs(args, context) {
  4949. var allArgsCnt = args && args.length || 0;
  4950. var len;
  4951. var optionalParameters = this.optionalParameters;
  4952. var requiredArgsCnt = !args ? 0 : args.reduce(function (count, p) {
  4953. if (optionalParameters.indexOf(p.name) < 0) {
  4954. return count + 1;
  4955. } else {
  4956. return count;
  4957. }
  4958. }, 0);
  4959. if (!this.variadic) {
  4960. if (requiredArgsCnt < this.required) {
  4961. return false;
  4962. }
  4963. if (allArgsCnt > this.params.length) {
  4964. return false;
  4965. }
  4966. } else {
  4967. if (requiredArgsCnt < this.required - 1) {
  4968. return false;
  4969. }
  4970. } // check patterns
  4971. len = Math.min(requiredArgsCnt, this.arity);
  4972. for (var i = 0; i < len; i++) {
  4973. if (!this.params[i].name && !this.params[i].variadic) {
  4974. if (args[i].value.eval(context).toCSS() != this.params[i].value.eval(context).toCSS()) {
  4975. return false;
  4976. }
  4977. }
  4978. }
  4979. return true;
  4980. }
  4981. }]);
  4982. return Definition;
  4983. }(Ruleset);
  4984. Definition.prototype.type = 'MixinDefinition';
  4985. Definition.prototype.evalFirst = true;
  4986. var MixinCall =
  4987. /*#__PURE__*/
  4988. function (_Node) {
  4989. _inherits(MixinCall, _Node);
  4990. function MixinCall(elements, args, index, currentFileInfo, important) {
  4991. var _this;
  4992. _classCallCheck(this, MixinCall);
  4993. _this = _possibleConstructorReturn(this, _getPrototypeOf(MixinCall).call(this));
  4994. _this.selector = new Selector(elements);
  4995. _this.arguments = args || [];
  4996. _this._index = index;
  4997. _this._fileInfo = currentFileInfo;
  4998. _this.important = important;
  4999. _this.allowRoot = true;
  5000. _this.setParent(_this.selector, _assertThisInitialized(_this));
  5001. return _this;
  5002. }
  5003. _createClass(MixinCall, [{
  5004. key: "accept",
  5005. value: function accept(visitor) {
  5006. if (this.selector) {
  5007. this.selector = visitor.visit(this.selector);
  5008. }
  5009. if (this.arguments.length) {
  5010. this.arguments = visitor.visitArray(this.arguments);
  5011. }
  5012. }
  5013. }, {
  5014. key: "eval",
  5015. value: function _eval(context) {
  5016. var mixins;
  5017. var mixin;
  5018. var mixinPath;
  5019. var args = [];
  5020. var arg;
  5021. var argValue;
  5022. var rules = [];
  5023. var match = false;
  5024. var i;
  5025. var m;
  5026. var f;
  5027. var isRecursive;
  5028. var isOneFound;
  5029. var candidates = [];
  5030. var candidate;
  5031. var conditionResult = [];
  5032. var defaultResult;
  5033. var defFalseEitherCase = -1;
  5034. var defNone = 0;
  5035. var defTrue = 1;
  5036. var defFalse = 2;
  5037. var count;
  5038. var originalRuleset;
  5039. var noArgumentsFilter;
  5040. this.selector = this.selector.eval(context);
  5041. function calcDefGroup(mixin, mixinPath) {
  5042. var f;
  5043. var p;
  5044. var namespace;
  5045. for (f = 0; f < 2; f++) {
  5046. conditionResult[f] = true;
  5047. defaultFunc.value(f);
  5048. for (p = 0; p < mixinPath.length && conditionResult[f]; p++) {
  5049. namespace = mixinPath[p];
  5050. if (namespace.matchCondition) {
  5051. conditionResult[f] = conditionResult[f] && namespace.matchCondition(null, context);
  5052. }
  5053. }
  5054. if (mixin.matchCondition) {
  5055. conditionResult[f] = conditionResult[f] && mixin.matchCondition(args, context);
  5056. }
  5057. }
  5058. if (conditionResult[0] || conditionResult[1]) {
  5059. if (conditionResult[0] != conditionResult[1]) {
  5060. return conditionResult[1] ? defTrue : defFalse;
  5061. }
  5062. return defNone;
  5063. }
  5064. return defFalseEitherCase;
  5065. }
  5066. for (i = 0; i < this.arguments.length; i++) {
  5067. arg = this.arguments[i];
  5068. argValue = arg.value.eval(context);
  5069. if (arg.expand && Array.isArray(argValue.value)) {
  5070. argValue = argValue.value;
  5071. for (m = 0; m < argValue.length; m++) {
  5072. args.push({
  5073. value: argValue[m]
  5074. });
  5075. }
  5076. } else {
  5077. args.push({
  5078. name: arg.name,
  5079. value: argValue
  5080. });
  5081. }
  5082. }
  5083. noArgumentsFilter = function noArgumentsFilter(rule) {
  5084. return rule.matchArgs(null, context);
  5085. };
  5086. for (i = 0; i < context.frames.length; i++) {
  5087. if ((mixins = context.frames[i].find(this.selector, null, noArgumentsFilter)).length > 0) {
  5088. isOneFound = true; // To make `default()` function independent of definition order we have two "subpasses" here.
  5089. // At first we evaluate each guard *twice* (with `default() == true` and `default() == false`),
  5090. // and build candidate list with corresponding flags. Then, when we know all possible matches,
  5091. // we make a final decision.
  5092. for (m = 0; m < mixins.length; m++) {
  5093. mixin = mixins[m].rule;
  5094. mixinPath = mixins[m].path;
  5095. isRecursive = false;
  5096. for (f = 0; f < context.frames.length; f++) {
  5097. if (!(mixin instanceof Definition) && mixin === (context.frames[f].originalRuleset || context.frames[f])) {
  5098. isRecursive = true;
  5099. break;
  5100. }
  5101. }
  5102. if (isRecursive) {
  5103. continue;
  5104. }
  5105. if (mixin.matchArgs(args, context)) {
  5106. candidate = {
  5107. mixin,
  5108. group: calcDefGroup(mixin, mixinPath)
  5109. };
  5110. if (candidate.group !== defFalseEitherCase) {
  5111. candidates.push(candidate);
  5112. }
  5113. match = true;
  5114. }
  5115. }
  5116. defaultFunc.reset();
  5117. count = [0, 0, 0];
  5118. for (m = 0; m < candidates.length; m++) {
  5119. count[candidates[m].group]++;
  5120. }
  5121. if (count[defNone] > 0) {
  5122. defaultResult = defFalse;
  5123. } else {
  5124. defaultResult = defTrue;
  5125. if (count[defTrue] + count[defFalse] > 1) {
  5126. throw {
  5127. type: 'Runtime',
  5128. message: `Ambiguous use of \`default()\` found when matching for \`${this.format(args)}\``,
  5129. index: this.getIndex(),
  5130. filename: this.fileInfo().filename
  5131. };
  5132. }
  5133. }
  5134. for (m = 0; m < candidates.length; m++) {
  5135. candidate = candidates[m].group;
  5136. if (candidate === defNone || candidate === defaultResult) {
  5137. try {
  5138. mixin = candidates[m].mixin;
  5139. if (!(mixin instanceof Definition)) {
  5140. originalRuleset = mixin.originalRuleset || mixin;
  5141. mixin = new Definition('', [], mixin.rules, null, false, null, originalRuleset.visibilityInfo());
  5142. mixin.originalRuleset = originalRuleset;
  5143. }
  5144. var newRules = mixin.evalCall(context, args, this.important).rules;
  5145. this._setVisibilityToReplacement(newRules);
  5146. Array.prototype.push.apply(rules, newRules);
  5147. } catch (e) {
  5148. throw {
  5149. message: e.message,
  5150. index: this.getIndex(),
  5151. filename: this.fileInfo().filename,
  5152. stack: e.stack
  5153. };
  5154. }
  5155. }
  5156. }
  5157. if (match) {
  5158. return rules;
  5159. }
  5160. }
  5161. }
  5162. if (isOneFound) {
  5163. throw {
  5164. type: 'Runtime',
  5165. message: `No matching definition was found for \`${this.format(args)}\``,
  5166. index: this.getIndex(),
  5167. filename: this.fileInfo().filename
  5168. };
  5169. } else {
  5170. throw {
  5171. type: 'Name',
  5172. message: `${this.selector.toCSS().trim()} is undefined`,
  5173. index: this.getIndex(),
  5174. filename: this.fileInfo().filename
  5175. };
  5176. }
  5177. }
  5178. }, {
  5179. key: "_setVisibilityToReplacement",
  5180. value: function _setVisibilityToReplacement(replacement) {
  5181. var i;
  5182. var rule;
  5183. if (this.blocksVisibility()) {
  5184. for (i = 0; i < replacement.length; i++) {
  5185. rule = replacement[i];
  5186. rule.addVisibilityBlock();
  5187. }
  5188. }
  5189. }
  5190. }, {
  5191. key: "format",
  5192. value: function format(args) {
  5193. return `${this.selector.toCSS().trim()}(${args ? args.map(function (a) {
  5194. var argValue = '';
  5195. if (a.name) {
  5196. argValue += `${a.name}:`;
  5197. }
  5198. if (a.value.toCSS) {
  5199. argValue += a.value.toCSS();
  5200. } else {
  5201. argValue += '???';
  5202. }
  5203. return argValue;
  5204. }).join(', ') : ''})`;
  5205. }
  5206. }]);
  5207. return MixinCall;
  5208. }(Node);
  5209. MixinCall.prototype.type = 'MixinCall';
  5210. var tree = {
  5211. Node,
  5212. Color,
  5213. AtRule,
  5214. DetachedRuleset,
  5215. Operation,
  5216. Dimension,
  5217. Unit,
  5218. Keyword,
  5219. Variable,
  5220. Property,
  5221. Ruleset,
  5222. Element,
  5223. Attribute,
  5224. Combinator,
  5225. Selector,
  5226. Quoted,
  5227. Expression,
  5228. Declaration,
  5229. Call,
  5230. URL,
  5231. Import,
  5232. Comment,
  5233. Anonymous,
  5234. Value,
  5235. JavaScript,
  5236. Assignment,
  5237. Condition,
  5238. Paren,
  5239. Media,
  5240. UnicodeDescriptor,
  5241. Negative,
  5242. Extend,
  5243. VariableCall,
  5244. NamespaceValue,
  5245. mixin: {
  5246. Call: MixinCall,
  5247. Definition: Definition
  5248. }
  5249. };
  5250. var environment$1 =
  5251. /*#__PURE__*/
  5252. function () {
  5253. function environment(externalEnvironment, fileManagers) {
  5254. _classCallCheck(this, environment);
  5255. this.fileManagers = fileManagers || [];
  5256. externalEnvironment = externalEnvironment || {};
  5257. var optionalFunctions = ['encodeBase64', 'mimeLookup', 'charsetLookup', 'getSourceMapGenerator'];
  5258. var requiredFunctions = [];
  5259. var functions = requiredFunctions.concat(optionalFunctions);
  5260. for (var i = 0; i < functions.length; i++) {
  5261. var propName = functions[i];
  5262. var environmentFunc = externalEnvironment[propName];
  5263. if (environmentFunc) {
  5264. this[propName] = environmentFunc.bind(externalEnvironment);
  5265. } else if (i < requiredFunctions.length) {
  5266. this.warn(`missing required function in environment - ${propName}`);
  5267. }
  5268. }
  5269. }
  5270. _createClass(environment, [{
  5271. key: "getFileManager",
  5272. value: function getFileManager(filename, currentDirectory, options, environment, isSync) {
  5273. if (!filename) {
  5274. logger.warn('getFileManager called with no filename.. Please report this issue. continuing.');
  5275. }
  5276. if (currentDirectory == null) {
  5277. logger.warn('getFileManager called with null directory.. Please report this issue. continuing.');
  5278. }
  5279. var fileManagers = this.fileManagers;
  5280. if (options.pluginManager) {
  5281. fileManagers = [].concat(fileManagers).concat(options.pluginManager.getFileManagers());
  5282. }
  5283. for (var i = fileManagers.length - 1; i >= 0; i--) {
  5284. var fileManager = fileManagers[i];
  5285. if (fileManager[isSync ? 'supportsSync' : 'supports'](filename, currentDirectory, options, environment)) {
  5286. return fileManager;
  5287. }
  5288. }
  5289. return null;
  5290. }
  5291. }, {
  5292. key: "addFileManager",
  5293. value: function addFileManager(fileManager) {
  5294. this.fileManagers.push(fileManager);
  5295. }
  5296. }, {
  5297. key: "clearFileManagers",
  5298. value: function clearFileManagers() {
  5299. this.fileManagers = [];
  5300. }
  5301. }]);
  5302. return environment;
  5303. }();
  5304. var AbstractPluginLoader =
  5305. /*#__PURE__*/
  5306. function () {
  5307. function AbstractPluginLoader() {
  5308. _classCallCheck(this, AbstractPluginLoader);
  5309. // Implemented by Node.js plugin loader
  5310. this.require = function () {
  5311. return null;
  5312. };
  5313. }
  5314. _createClass(AbstractPluginLoader, [{
  5315. key: "evalPlugin",
  5316. value: function evalPlugin(contents, context, imports, pluginOptions, fileInfo) {
  5317. var loader;
  5318. var registry;
  5319. var pluginObj;
  5320. var localModule;
  5321. var pluginManager;
  5322. var filename;
  5323. var result;
  5324. pluginManager = context.pluginManager;
  5325. if (fileInfo) {
  5326. if (typeof fileInfo === 'string') {
  5327. filename = fileInfo;
  5328. } else {
  5329. filename = fileInfo.filename;
  5330. }
  5331. }
  5332. var shortname = new this.less.FileManager().extractUrlParts(filename).filename;
  5333. if (filename) {
  5334. pluginObj = pluginManager.get(filename);
  5335. if (pluginObj) {
  5336. result = this.trySetOptions(pluginObj, filename, shortname, pluginOptions);
  5337. if (result) {
  5338. return result;
  5339. }
  5340. try {
  5341. if (pluginObj.use) {
  5342. pluginObj.use.call(this.context, pluginObj);
  5343. }
  5344. } catch (e) {
  5345. e.message = e.message || 'Error during @plugin call';
  5346. return new LessError(e, imports, filename);
  5347. }
  5348. return pluginObj;
  5349. }
  5350. }
  5351. localModule = {
  5352. exports: {},
  5353. pluginManager,
  5354. fileInfo
  5355. };
  5356. registry = functionRegistry.create();
  5357. var registerPlugin = function registerPlugin(obj) {
  5358. pluginObj = obj;
  5359. };
  5360. try {
  5361. loader = new Function('module', 'require', 'registerPlugin', 'functions', 'tree', 'less', 'fileInfo', contents);
  5362. loader(localModule, this.require(filename), registerPlugin, registry, this.less.tree, this.less, fileInfo);
  5363. } catch (e) {
  5364. return new LessError(e, imports, filename);
  5365. }
  5366. if (!pluginObj) {
  5367. pluginObj = localModule.exports;
  5368. }
  5369. pluginObj = this.validatePlugin(pluginObj, filename, shortname);
  5370. if (pluginObj instanceof LessError) {
  5371. return pluginObj;
  5372. }
  5373. if (pluginObj) {
  5374. pluginObj.imports = imports;
  5375. pluginObj.filename = filename; // For < 3.x (or unspecified minVersion) - setOptions() before install()
  5376. if (!pluginObj.minVersion || this.compareVersion('3.0.0', pluginObj.minVersion) < 0) {
  5377. result = this.trySetOptions(pluginObj, filename, shortname, pluginOptions);
  5378. if (result) {
  5379. return result;
  5380. }
  5381. } // Run on first load
  5382. pluginManager.addPlugin(pluginObj, fileInfo.filename, registry);
  5383. pluginObj.functions = registry.getLocalFunctions(); // Need to call setOptions again because the pluginObj might have functions
  5384. result = this.trySetOptions(pluginObj, filename, shortname, pluginOptions);
  5385. if (result) {
  5386. return result;
  5387. } // Run every @plugin call
  5388. try {
  5389. if (pluginObj.use) {
  5390. pluginObj.use.call(this.context, pluginObj);
  5391. }
  5392. } catch (e) {
  5393. e.message = e.message || 'Error during @plugin call';
  5394. return new LessError(e, imports, filename);
  5395. }
  5396. } else {
  5397. return new LessError({
  5398. message: 'Not a valid plugin'
  5399. }, imports, filename);
  5400. }
  5401. return pluginObj;
  5402. }
  5403. }, {
  5404. key: "trySetOptions",
  5405. value: function trySetOptions(plugin, filename, name, options) {
  5406. if (options && !plugin.setOptions) {
  5407. return new LessError({
  5408. message: `Options have been provided but the plugin ${name} does not support any options.`
  5409. });
  5410. }
  5411. try {
  5412. plugin.setOptions && plugin.setOptions(options);
  5413. } catch (e) {
  5414. return new LessError(e);
  5415. }
  5416. }
  5417. }, {
  5418. key: "validatePlugin",
  5419. value: function validatePlugin(plugin, filename, name) {
  5420. if (plugin) {
  5421. // support plugins being a function
  5422. // so that the plugin can be more usable programmatically
  5423. if (typeof plugin === 'function') {
  5424. plugin = new plugin();
  5425. }
  5426. if (plugin.minVersion) {
  5427. if (this.compareVersion(plugin.minVersion, this.less.version) < 0) {
  5428. return new LessError({
  5429. message: `Plugin ${name} requires version ${this.versionToString(plugin.minVersion)}`
  5430. });
  5431. }
  5432. }
  5433. return plugin;
  5434. }
  5435. return null;
  5436. }
  5437. }, {
  5438. key: "compareVersion",
  5439. value: function compareVersion(aVersion, bVersion) {
  5440. if (typeof aVersion === 'string') {
  5441. aVersion = aVersion.match(/^(\d+)\.?(\d+)?\.?(\d+)?/);
  5442. aVersion.shift();
  5443. }
  5444. for (var i = 0; i < aVersion.length; i++) {
  5445. if (aVersion[i] !== bVersion[i]) {
  5446. return parseInt(aVersion[i]) > parseInt(bVersion[i]) ? -1 : 1;
  5447. }
  5448. }
  5449. return 0;
  5450. }
  5451. }, {
  5452. key: "versionToString",
  5453. value: function versionToString(version) {
  5454. var versionString = '';
  5455. for (var i = 0; i < version.length; i++) {
  5456. versionString += (versionString ? '.' : '') + version[i];
  5457. }
  5458. return versionString;
  5459. }
  5460. }, {
  5461. key: "printUsage",
  5462. value: function printUsage(plugins) {
  5463. for (var i = 0; i < plugins.length; i++) {
  5464. var plugin = plugins[i];
  5465. if (plugin.printUsage) {
  5466. plugin.printUsage();
  5467. }
  5468. }
  5469. }
  5470. }]);
  5471. return AbstractPluginLoader;
  5472. }();
  5473. var _visitArgs = {
  5474. visitDeeper: true
  5475. };
  5476. var _hasIndexed = false;
  5477. function _noop(node) {
  5478. return node;
  5479. }
  5480. function indexNodeTypes(parent, ticker) {
  5481. // add .typeIndex to tree node types for lookup table
  5482. var key;
  5483. var child;
  5484. for (key in parent) {
  5485. /* eslint guard-for-in: 0 */
  5486. child = parent[key];
  5487. switch (typeof child) {
  5488. case 'function':
  5489. // ignore bound functions directly on tree which do not have a prototype
  5490. // or aren't nodes
  5491. if (child.prototype && child.prototype.type) {
  5492. child.prototype.typeIndex = ticker++;
  5493. }
  5494. break;
  5495. case 'object':
  5496. ticker = indexNodeTypes(child, ticker);
  5497. break;
  5498. }
  5499. }
  5500. return ticker;
  5501. }
  5502. var Visitor =
  5503. /*#__PURE__*/
  5504. function () {
  5505. function Visitor(implementation) {
  5506. _classCallCheck(this, Visitor);
  5507. this._implementation = implementation;
  5508. this._visitInCache = {};
  5509. this._visitOutCache = {};
  5510. if (!_hasIndexed) {
  5511. indexNodeTypes(tree, 1);
  5512. _hasIndexed = true;
  5513. }
  5514. }
  5515. _createClass(Visitor, [{
  5516. key: "visit",
  5517. value: function visit(node) {
  5518. if (!node) {
  5519. return node;
  5520. }
  5521. var nodeTypeIndex = node.typeIndex;
  5522. if (!nodeTypeIndex) {
  5523. // MixinCall args aren't a node type?
  5524. if (node.value && node.value.typeIndex) {
  5525. this.visit(node.value);
  5526. }
  5527. return node;
  5528. }
  5529. var impl = this._implementation;
  5530. var func = this._visitInCache[nodeTypeIndex];
  5531. var funcOut = this._visitOutCache[nodeTypeIndex];
  5532. var visitArgs = _visitArgs;
  5533. var fnName;
  5534. visitArgs.visitDeeper = true;
  5535. if (!func) {
  5536. fnName = `visit${node.type}`;
  5537. func = impl[fnName] || _noop;
  5538. funcOut = impl[`${fnName}Out`] || _noop;
  5539. this._visitInCache[nodeTypeIndex] = func;
  5540. this._visitOutCache[nodeTypeIndex] = funcOut;
  5541. }
  5542. if (func !== _noop) {
  5543. var newNode = func.call(impl, node, visitArgs);
  5544. if (node && impl.isReplacing) {
  5545. node = newNode;
  5546. }
  5547. }
  5548. if (visitArgs.visitDeeper && node && node.accept) {
  5549. node.accept(this);
  5550. }
  5551. if (funcOut != _noop) {
  5552. funcOut.call(impl, node);
  5553. }
  5554. return node;
  5555. }
  5556. }, {
  5557. key: "visitArray",
  5558. value: function visitArray(nodes, nonReplacing) {
  5559. if (!nodes) {
  5560. return nodes;
  5561. }
  5562. var cnt = nodes.length;
  5563. var i; // Non-replacing
  5564. if (nonReplacing || !this._implementation.isReplacing) {
  5565. for (i = 0; i < cnt; i++) {
  5566. this.visit(nodes[i]);
  5567. }
  5568. return nodes;
  5569. } // Replacing
  5570. var out = [];
  5571. for (i = 0; i < cnt; i++) {
  5572. var evald = this.visit(nodes[i]);
  5573. if (evald === undefined) {
  5574. continue;
  5575. }
  5576. if (!evald.splice) {
  5577. out.push(evald);
  5578. } else if (evald.length) {
  5579. this.flatten(evald, out);
  5580. }
  5581. }
  5582. return out;
  5583. }
  5584. }, {
  5585. key: "flatten",
  5586. value: function flatten(arr, out) {
  5587. if (!out) {
  5588. out = [];
  5589. }
  5590. var cnt;
  5591. var i;
  5592. var item;
  5593. var nestedCnt;
  5594. var j;
  5595. var nestedItem;
  5596. for (i = 0, cnt = arr.length; i < cnt; i++) {
  5597. item = arr[i];
  5598. if (item === undefined) {
  5599. continue;
  5600. }
  5601. if (!item.splice) {
  5602. out.push(item);
  5603. continue;
  5604. }
  5605. for (j = 0, nestedCnt = item.length; j < nestedCnt; j++) {
  5606. nestedItem = item[j];
  5607. if (nestedItem === undefined) {
  5608. continue;
  5609. }
  5610. if (!nestedItem.splice) {
  5611. out.push(nestedItem);
  5612. } else if (nestedItem.length) {
  5613. this.flatten(nestedItem, out);
  5614. }
  5615. }
  5616. }
  5617. return out;
  5618. }
  5619. }]);
  5620. return Visitor;
  5621. }();
  5622. var ImportSequencer =
  5623. /*#__PURE__*/
  5624. function () {
  5625. function ImportSequencer(onSequencerEmpty) {
  5626. _classCallCheck(this, ImportSequencer);
  5627. this.imports = [];
  5628. this.variableImports = [];
  5629. this._onSequencerEmpty = onSequencerEmpty;
  5630. this._currentDepth = 0;
  5631. }
  5632. _createClass(ImportSequencer, [{
  5633. key: "addImport",
  5634. value: function addImport(callback) {
  5635. var importSequencer = this;
  5636. var importItem = {
  5637. callback,
  5638. args: null,
  5639. isReady: false
  5640. };
  5641. this.imports.push(importItem);
  5642. return function () {
  5643. for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
  5644. args[_key] = arguments[_key];
  5645. }
  5646. importItem.args = Array.prototype.slice.call(args, 0);
  5647. importItem.isReady = true;
  5648. importSequencer.tryRun();
  5649. };
  5650. }
  5651. }, {
  5652. key: "addVariableImport",
  5653. value: function addVariableImport(callback) {
  5654. this.variableImports.push(callback);
  5655. }
  5656. }, {
  5657. key: "tryRun",
  5658. value: function tryRun() {
  5659. this._currentDepth++;
  5660. try {
  5661. while (true) {
  5662. while (this.imports.length > 0) {
  5663. var importItem = this.imports[0];
  5664. if (!importItem.isReady) {
  5665. return;
  5666. }
  5667. this.imports = this.imports.slice(1);
  5668. importItem.callback.apply(null, importItem.args);
  5669. }
  5670. if (this.variableImports.length === 0) {
  5671. break;
  5672. }
  5673. var variableImport = this.variableImports[0];
  5674. this.variableImports = this.variableImports.slice(1);
  5675. variableImport();
  5676. }
  5677. } finally {
  5678. this._currentDepth--;
  5679. }
  5680. if (this._currentDepth === 0 && this._onSequencerEmpty) {
  5681. this._onSequencerEmpty();
  5682. }
  5683. }
  5684. }]);
  5685. return ImportSequencer;
  5686. }();
  5687. var ImportVisitor = function ImportVisitor(importer, finish) {
  5688. this._visitor = new Visitor(this);
  5689. this._importer = importer;
  5690. this._finish = finish;
  5691. this.context = new contexts.Eval();
  5692. this.importCount = 0;
  5693. this.onceFileDetectionMap = {};
  5694. this.recursionDetector = {};
  5695. this._sequencer = new ImportSequencer(this._onSequencerEmpty.bind(this));
  5696. };
  5697. ImportVisitor.prototype = {
  5698. isReplacing: false,
  5699. run: function run(root) {
  5700. try {
  5701. // process the contents
  5702. this._visitor.visit(root);
  5703. } catch (e) {
  5704. this.error = e;
  5705. }
  5706. this.isFinished = true;
  5707. this._sequencer.tryRun();
  5708. },
  5709. _onSequencerEmpty: function _onSequencerEmpty() {
  5710. if (!this.isFinished) {
  5711. return;
  5712. }
  5713. this._finish(this.error);
  5714. },
  5715. visitImport: function visitImport(importNode, visitArgs) {
  5716. var inlineCSS = importNode.options.inline;
  5717. if (!importNode.css || inlineCSS) {
  5718. var context = new contexts.Eval(this.context, copyArray(this.context.frames));
  5719. var importParent = context.frames[0];
  5720. this.importCount++;
  5721. if (importNode.isVariableImport()) {
  5722. this._sequencer.addVariableImport(this.processImportNode.bind(this, importNode, context, importParent));
  5723. } else {
  5724. this.processImportNode(importNode, context, importParent);
  5725. }
  5726. }
  5727. visitArgs.visitDeeper = false;
  5728. },
  5729. processImportNode: function processImportNode(importNode, context, importParent) {
  5730. var evaldImportNode;
  5731. var inlineCSS = importNode.options.inline;
  5732. try {
  5733. evaldImportNode = importNode.evalForImport(context);
  5734. } catch (e) {
  5735. if (!e.filename) {
  5736. e.index = importNode.getIndex();
  5737. e.filename = importNode.fileInfo().filename;
  5738. } // attempt to eval properly and treat as css
  5739. importNode.css = true; // if that fails, this error will be thrown
  5740. importNode.error = e;
  5741. }
  5742. if (evaldImportNode && (!evaldImportNode.css || inlineCSS)) {
  5743. if (evaldImportNode.options.multiple) {
  5744. context.importMultiple = true;
  5745. } // try appending if we haven't determined if it is css or not
  5746. var tryAppendLessExtension = evaldImportNode.css === undefined;
  5747. for (var i = 0; i < importParent.rules.length; i++) {
  5748. if (importParent.rules[i] === importNode) {
  5749. importParent.rules[i] = evaldImportNode;
  5750. break;
  5751. }
  5752. }
  5753. var onImported = this.onImported.bind(this, evaldImportNode, context);
  5754. var sequencedOnImported = this._sequencer.addImport(onImported);
  5755. this._importer.push(evaldImportNode.getPath(), tryAppendLessExtension, evaldImportNode.fileInfo(), evaldImportNode.options, sequencedOnImported);
  5756. } else {
  5757. this.importCount--;
  5758. if (this.isFinished) {
  5759. this._sequencer.tryRun();
  5760. }
  5761. }
  5762. },
  5763. onImported: function onImported(importNode, context, e, root, importedAtRoot, fullPath) {
  5764. if (e) {
  5765. if (!e.filename) {
  5766. e.index = importNode.getIndex();
  5767. e.filename = importNode.fileInfo().filename;
  5768. }
  5769. this.error = e;
  5770. }
  5771. var importVisitor = this;
  5772. var inlineCSS = importNode.options.inline;
  5773. var isPlugin = importNode.options.isPlugin;
  5774. var isOptional = importNode.options.optional;
  5775. var duplicateImport = importedAtRoot || fullPath in importVisitor.recursionDetector;
  5776. if (!context.importMultiple) {
  5777. if (duplicateImport) {
  5778. importNode.skip = true;
  5779. } else {
  5780. importNode.skip = function () {
  5781. if (fullPath in importVisitor.onceFileDetectionMap) {
  5782. return true;
  5783. }
  5784. importVisitor.onceFileDetectionMap[fullPath] = true;
  5785. return false;
  5786. };
  5787. }
  5788. }
  5789. if (!fullPath && isOptional) {
  5790. importNode.skip = true;
  5791. }
  5792. if (root) {
  5793. importNode.root = root;
  5794. importNode.importedFilename = fullPath;
  5795. if (!inlineCSS && !isPlugin && (context.importMultiple || !duplicateImport)) {
  5796. importVisitor.recursionDetector[fullPath] = true;
  5797. var oldContext = this.context;
  5798. this.context = context;
  5799. try {
  5800. this._visitor.visit(root);
  5801. } catch (e) {
  5802. this.error = e;
  5803. }
  5804. this.context = oldContext;
  5805. }
  5806. }
  5807. importVisitor.importCount--;
  5808. if (importVisitor.isFinished) {
  5809. importVisitor._sequencer.tryRun();
  5810. }
  5811. },
  5812. visitDeclaration: function visitDeclaration(declNode, visitArgs) {
  5813. if (declNode.value.type === 'DetachedRuleset') {
  5814. this.context.frames.unshift(declNode);
  5815. } else {
  5816. visitArgs.visitDeeper = false;
  5817. }
  5818. },
  5819. visitDeclarationOut: function visitDeclarationOut(declNode) {
  5820. if (declNode.value.type === 'DetachedRuleset') {
  5821. this.context.frames.shift();
  5822. }
  5823. },
  5824. visitAtRule: function visitAtRule(atRuleNode, visitArgs) {
  5825. this.context.frames.unshift(atRuleNode);
  5826. },
  5827. visitAtRuleOut: function visitAtRuleOut(atRuleNode) {
  5828. this.context.frames.shift();
  5829. },
  5830. visitMixinDefinition: function visitMixinDefinition(mixinDefinitionNode, visitArgs) {
  5831. this.context.frames.unshift(mixinDefinitionNode);
  5832. },
  5833. visitMixinDefinitionOut: function visitMixinDefinitionOut(mixinDefinitionNode) {
  5834. this.context.frames.shift();
  5835. },
  5836. visitRuleset: function visitRuleset(rulesetNode, visitArgs) {
  5837. this.context.frames.unshift(rulesetNode);
  5838. },
  5839. visitRulesetOut: function visitRulesetOut(rulesetNode) {
  5840. this.context.frames.shift();
  5841. },
  5842. visitMedia: function visitMedia(mediaNode, visitArgs) {
  5843. this.context.frames.unshift(mediaNode.rules[0]);
  5844. },
  5845. visitMediaOut: function visitMediaOut(mediaNode) {
  5846. this.context.frames.shift();
  5847. }
  5848. };
  5849. var SetTreeVisibilityVisitor =
  5850. /*#__PURE__*/
  5851. function () {
  5852. function SetTreeVisibilityVisitor(visible) {
  5853. _classCallCheck(this, SetTreeVisibilityVisitor);
  5854. this.visible = visible;
  5855. }
  5856. _createClass(SetTreeVisibilityVisitor, [{
  5857. key: "run",
  5858. value: function run(root) {
  5859. this.visit(root);
  5860. }
  5861. }, {
  5862. key: "visitArray",
  5863. value: function visitArray(nodes) {
  5864. if (!nodes) {
  5865. return nodes;
  5866. }
  5867. var cnt = nodes.length;
  5868. var i;
  5869. for (i = 0; i < cnt; i++) {
  5870. this.visit(nodes[i]);
  5871. }
  5872. return nodes;
  5873. }
  5874. }, {
  5875. key: "visit",
  5876. value: function visit(node) {
  5877. if (!node) {
  5878. return node;
  5879. }
  5880. if (node.constructor === Array) {
  5881. return this.visitArray(node);
  5882. }
  5883. if (!node.blocksVisibility || node.blocksVisibility()) {
  5884. return node;
  5885. }
  5886. if (this.visible) {
  5887. node.ensureVisibility();
  5888. } else {
  5889. node.ensureInvisibility();
  5890. }
  5891. node.accept(this);
  5892. return node;
  5893. }
  5894. }]);
  5895. return SetTreeVisibilityVisitor;
  5896. }();
  5897. /* jshint loopfunc:true */
  5898. var ExtendFinderVisitor =
  5899. /*#__PURE__*/
  5900. function () {
  5901. function ExtendFinderVisitor() {
  5902. _classCallCheck(this, ExtendFinderVisitor);
  5903. this._visitor = new Visitor(this);
  5904. this.contexts = [];
  5905. this.allExtendsStack = [[]];
  5906. }
  5907. _createClass(ExtendFinderVisitor, [{
  5908. key: "run",
  5909. value: function run(root) {
  5910. root = this._visitor.visit(root);
  5911. root.allExtends = this.allExtendsStack[0];
  5912. return root;
  5913. }
  5914. }, {
  5915. key: "visitDeclaration",
  5916. value: function visitDeclaration(declNode, visitArgs) {
  5917. visitArgs.visitDeeper = false;
  5918. }
  5919. }, {
  5920. key: "visitMixinDefinition",
  5921. value: function visitMixinDefinition(mixinDefinitionNode, visitArgs) {
  5922. visitArgs.visitDeeper = false;
  5923. }
  5924. }, {
  5925. key: "visitRuleset",
  5926. value: function visitRuleset(rulesetNode, visitArgs) {
  5927. if (rulesetNode.root) {
  5928. return;
  5929. }
  5930. var i;
  5931. var j;
  5932. var extend;
  5933. var allSelectorsExtendList = [];
  5934. var extendList; // get &:extend(.a); rules which apply to all selectors in this ruleset
  5935. var rules = rulesetNode.rules;
  5936. var ruleCnt = rules ? rules.length : 0;
  5937. for (i = 0; i < ruleCnt; i++) {
  5938. if (rulesetNode.rules[i] instanceof tree.Extend) {
  5939. allSelectorsExtendList.push(rules[i]);
  5940. rulesetNode.extendOnEveryPath = true;
  5941. }
  5942. } // now find every selector and apply the extends that apply to all extends
  5943. // and the ones which apply to an individual extend
  5944. var paths = rulesetNode.paths;
  5945. for (i = 0; i < paths.length; i++) {
  5946. var selectorPath = paths[i];
  5947. var selector = selectorPath[selectorPath.length - 1];
  5948. var selExtendList = selector.extendList;
  5949. extendList = selExtendList ? copyArray(selExtendList).concat(allSelectorsExtendList) : allSelectorsExtendList;
  5950. if (extendList) {
  5951. extendList = extendList.map(function (allSelectorsExtend) {
  5952. return allSelectorsExtend.clone();
  5953. });
  5954. }
  5955. for (j = 0; j < extendList.length; j++) {
  5956. this.foundExtends = true;
  5957. extend = extendList[j];
  5958. extend.findSelfSelectors(selectorPath);
  5959. extend.ruleset = rulesetNode;
  5960. if (j === 0) {
  5961. extend.firstExtendOnThisSelectorPath = true;
  5962. }
  5963. this.allExtendsStack[this.allExtendsStack.length - 1].push(extend);
  5964. }
  5965. }
  5966. this.contexts.push(rulesetNode.selectors);
  5967. }
  5968. }, {
  5969. key: "visitRulesetOut",
  5970. value: function visitRulesetOut(rulesetNode) {
  5971. if (!rulesetNode.root) {
  5972. this.contexts.length = this.contexts.length - 1;
  5973. }
  5974. }
  5975. }, {
  5976. key: "visitMedia",
  5977. value: function visitMedia(mediaNode, visitArgs) {
  5978. mediaNode.allExtends = [];
  5979. this.allExtendsStack.push(mediaNode.allExtends);
  5980. }
  5981. }, {
  5982. key: "visitMediaOut",
  5983. value: function visitMediaOut(mediaNode) {
  5984. this.allExtendsStack.length = this.allExtendsStack.length - 1;
  5985. }
  5986. }, {
  5987. key: "visitAtRule",
  5988. value: function visitAtRule(atRuleNode, visitArgs) {
  5989. atRuleNode.allExtends = [];
  5990. this.allExtendsStack.push(atRuleNode.allExtends);
  5991. }
  5992. }, {
  5993. key: "visitAtRuleOut",
  5994. value: function visitAtRuleOut(atRuleNode) {
  5995. this.allExtendsStack.length = this.allExtendsStack.length - 1;
  5996. }
  5997. }]);
  5998. return ExtendFinderVisitor;
  5999. }();
  6000. var ProcessExtendsVisitor =
  6001. /*#__PURE__*/
  6002. function () {
  6003. function ProcessExtendsVisitor() {
  6004. _classCallCheck(this, ProcessExtendsVisitor);
  6005. this._visitor = new Visitor(this);
  6006. }
  6007. _createClass(ProcessExtendsVisitor, [{
  6008. key: "run",
  6009. value: function run(root) {
  6010. var extendFinder = new ExtendFinderVisitor();
  6011. this.extendIndices = {};
  6012. extendFinder.run(root);
  6013. if (!extendFinder.foundExtends) {
  6014. return root;
  6015. }
  6016. root.allExtends = root.allExtends.concat(this.doExtendChaining(root.allExtends, root.allExtends));
  6017. this.allExtendsStack = [root.allExtends];
  6018. var newRoot = this._visitor.visit(root);
  6019. this.checkExtendsForNonMatched(root.allExtends);
  6020. return newRoot;
  6021. }
  6022. }, {
  6023. key: "checkExtendsForNonMatched",
  6024. value: function checkExtendsForNonMatched(extendList) {
  6025. var indices = this.extendIndices;
  6026. extendList.filter(function (extend) {
  6027. return !extend.hasFoundMatches && extend.parent_ids.length == 1;
  6028. }).forEach(function (extend) {
  6029. var selector = '_unknown_';
  6030. try {
  6031. selector = extend.selector.toCSS({});
  6032. } catch (_) {}
  6033. if (!indices[`${extend.index} ${selector}`]) {
  6034. indices[`${extend.index} ${selector}`] = true;
  6035. logger.warn(`extend '${selector}' has no matches`);
  6036. }
  6037. });
  6038. }
  6039. }, {
  6040. key: "doExtendChaining",
  6041. value: function doExtendChaining(extendsList, extendsListTarget, iterationCount) {
  6042. //
  6043. // chaining is different from normal extension.. if we extend an extend then we are not just copying, altering
  6044. // and pasting the selector we would do normally, but we are also adding an extend with the same target selector
  6045. // this means this new extend can then go and alter other extends
  6046. //
  6047. // this method deals with all the chaining work - without it, extend is flat and doesn't work on other extend selectors
  6048. // this is also the most expensive.. and a match on one selector can cause an extension of a selector we had already
  6049. // processed if we look at each selector at a time, as is done in visitRuleset
  6050. var extendIndex;
  6051. var targetExtendIndex;
  6052. var matches;
  6053. var extendsToAdd = [];
  6054. var newSelector;
  6055. var extendVisitor = this;
  6056. var selectorPath;
  6057. var extend;
  6058. var targetExtend;
  6059. var newExtend;
  6060. iterationCount = iterationCount || 0; // loop through comparing every extend with every target extend.
  6061. // a target extend is the one on the ruleset we are looking at copy/edit/pasting in place
  6062. // e.g. .a:extend(.b) {} and .b:extend(.c) {} then the first extend extends the second one
  6063. // and the second is the target.
  6064. // the separation into two lists allows us to process a subset of chains with a bigger set, as is the
  6065. // case when processing media queries
  6066. for (extendIndex = 0; extendIndex < extendsList.length; extendIndex++) {
  6067. for (targetExtendIndex = 0; targetExtendIndex < extendsListTarget.length; targetExtendIndex++) {
  6068. extend = extendsList[extendIndex];
  6069. targetExtend = extendsListTarget[targetExtendIndex]; // look for circular references
  6070. if (extend.parent_ids.indexOf(targetExtend.object_id) >= 0) {
  6071. continue;
  6072. } // find a match in the target extends self selector (the bit before :extend)
  6073. selectorPath = [targetExtend.selfSelectors[0]];
  6074. matches = extendVisitor.findMatch(extend, selectorPath);
  6075. if (matches.length) {
  6076. extend.hasFoundMatches = true; // we found a match, so for each self selector..
  6077. extend.selfSelectors.forEach(function (selfSelector) {
  6078. var info = targetExtend.visibilityInfo(); // process the extend as usual
  6079. newSelector = extendVisitor.extendSelector(matches, selectorPath, selfSelector, extend.isVisible()); // but now we create a new extend from it
  6080. newExtend = new tree.Extend(targetExtend.selector, targetExtend.option, 0, targetExtend.fileInfo(), info);
  6081. newExtend.selfSelectors = newSelector; // add the extend onto the list of extends for that selector
  6082. newSelector[newSelector.length - 1].extendList = [newExtend]; // record that we need to add it.
  6083. extendsToAdd.push(newExtend);
  6084. newExtend.ruleset = targetExtend.ruleset; // remember its parents for circular references
  6085. newExtend.parent_ids = newExtend.parent_ids.concat(targetExtend.parent_ids, extend.parent_ids); // only process the selector once.. if we have :extend(.a,.b) then multiple
  6086. // extends will look at the same selector path, so when extending
  6087. // we know that any others will be duplicates in terms of what is added to the css
  6088. if (targetExtend.firstExtendOnThisSelectorPath) {
  6089. newExtend.firstExtendOnThisSelectorPath = true;
  6090. targetExtend.ruleset.paths.push(newSelector);
  6091. }
  6092. });
  6093. }
  6094. }
  6095. }
  6096. if (extendsToAdd.length) {
  6097. // try to detect circular references to stop a stack overflow.
  6098. // may no longer be needed.
  6099. this.extendChainCount++;
  6100. if (iterationCount > 100) {
  6101. var selectorOne = '{unable to calculate}';
  6102. var selectorTwo = '{unable to calculate}';
  6103. try {
  6104. selectorOne = extendsToAdd[0].selfSelectors[0].toCSS();
  6105. selectorTwo = extendsToAdd[0].selector.toCSS();
  6106. } catch (e) {}
  6107. throw {
  6108. message: `extend circular reference detected. One of the circular extends is currently:${selectorOne}:extend(${selectorTwo})`
  6109. };
  6110. } // now process the new extends on the existing rules so that we can handle a extending b extending c extending
  6111. // d extending e...
  6112. return extendsToAdd.concat(extendVisitor.doExtendChaining(extendsToAdd, extendsListTarget, iterationCount + 1));
  6113. } else {
  6114. return extendsToAdd;
  6115. }
  6116. }
  6117. }, {
  6118. key: "visitDeclaration",
  6119. value: function visitDeclaration(ruleNode, visitArgs) {
  6120. visitArgs.visitDeeper = false;
  6121. }
  6122. }, {
  6123. key: "visitMixinDefinition",
  6124. value: function visitMixinDefinition(mixinDefinitionNode, visitArgs) {
  6125. visitArgs.visitDeeper = false;
  6126. }
  6127. }, {
  6128. key: "visitSelector",
  6129. value: function visitSelector(selectorNode, visitArgs) {
  6130. visitArgs.visitDeeper = false;
  6131. }
  6132. }, {
  6133. key: "visitRuleset",
  6134. value: function visitRuleset(rulesetNode, visitArgs) {
  6135. if (rulesetNode.root) {
  6136. return;
  6137. }
  6138. var matches;
  6139. var pathIndex;
  6140. var extendIndex;
  6141. var allExtends = this.allExtendsStack[this.allExtendsStack.length - 1];
  6142. var selectorsToAdd = [];
  6143. var extendVisitor = this;
  6144. var selectorPath; // look at each selector path in the ruleset, find any extend matches and then copy, find and replace
  6145. for (extendIndex = 0; extendIndex < allExtends.length; extendIndex++) {
  6146. for (pathIndex = 0; pathIndex < rulesetNode.paths.length; pathIndex++) {
  6147. selectorPath = rulesetNode.paths[pathIndex]; // extending extends happens initially, before the main pass
  6148. if (rulesetNode.extendOnEveryPath) {
  6149. continue;
  6150. }
  6151. var extendList = selectorPath[selectorPath.length - 1].extendList;
  6152. if (extendList && extendList.length) {
  6153. continue;
  6154. }
  6155. matches = this.findMatch(allExtends[extendIndex], selectorPath);
  6156. if (matches.length) {
  6157. allExtends[extendIndex].hasFoundMatches = true;
  6158. allExtends[extendIndex].selfSelectors.forEach(function (selfSelector) {
  6159. var extendedSelectors;
  6160. extendedSelectors = extendVisitor.extendSelector(matches, selectorPath, selfSelector, allExtends[extendIndex].isVisible());
  6161. selectorsToAdd.push(extendedSelectors);
  6162. });
  6163. }
  6164. }
  6165. }
  6166. rulesetNode.paths = rulesetNode.paths.concat(selectorsToAdd);
  6167. }
  6168. }, {
  6169. key: "findMatch",
  6170. value: function findMatch(extend, haystackSelectorPath) {
  6171. //
  6172. // look through the haystack selector path to try and find the needle - extend.selector
  6173. // returns an array of selector matches that can then be replaced
  6174. //
  6175. var haystackSelectorIndex;
  6176. var hackstackSelector;
  6177. var hackstackElementIndex;
  6178. var haystackElement;
  6179. var targetCombinator;
  6180. var i;
  6181. var extendVisitor = this;
  6182. var needleElements = extend.selector.elements;
  6183. var potentialMatches = [];
  6184. var potentialMatch;
  6185. var matches = []; // loop through the haystack elements
  6186. for (haystackSelectorIndex = 0; haystackSelectorIndex < haystackSelectorPath.length; haystackSelectorIndex++) {
  6187. hackstackSelector = haystackSelectorPath[haystackSelectorIndex];
  6188. for (hackstackElementIndex = 0; hackstackElementIndex < hackstackSelector.elements.length; hackstackElementIndex++) {
  6189. haystackElement = hackstackSelector.elements[hackstackElementIndex]; // if we allow elements before our match we can add a potential match every time. otherwise only at the first element.
  6190. if (extend.allowBefore || haystackSelectorIndex === 0 && hackstackElementIndex === 0) {
  6191. potentialMatches.push({
  6192. pathIndex: haystackSelectorIndex,
  6193. index: hackstackElementIndex,
  6194. matched: 0,
  6195. initialCombinator: haystackElement.combinator
  6196. });
  6197. }
  6198. for (i = 0; i < potentialMatches.length; i++) {
  6199. potentialMatch = potentialMatches[i]; // selectors add " " onto the first element. When we use & it joins the selectors together, but if we don't
  6200. // then each selector in haystackSelectorPath has a space before it added in the toCSS phase. so we need to
  6201. // work out what the resulting combinator will be
  6202. targetCombinator = haystackElement.combinator.value;
  6203. if (targetCombinator === '' && hackstackElementIndex === 0) {
  6204. targetCombinator = ' ';
  6205. } // if we don't match, null our match to indicate failure
  6206. if (!extendVisitor.isElementValuesEqual(needleElements[potentialMatch.matched].value, haystackElement.value) || potentialMatch.matched > 0 && needleElements[potentialMatch.matched].combinator.value !== targetCombinator) {
  6207. potentialMatch = null;
  6208. } else {
  6209. potentialMatch.matched++;
  6210. } // if we are still valid and have finished, test whether we have elements after and whether these are allowed
  6211. if (potentialMatch) {
  6212. potentialMatch.finished = potentialMatch.matched === needleElements.length;
  6213. if (potentialMatch.finished && !extend.allowAfter && (hackstackElementIndex + 1 < hackstackSelector.elements.length || haystackSelectorIndex + 1 < haystackSelectorPath.length)) {
  6214. potentialMatch = null;
  6215. }
  6216. } // if null we remove, if not, we are still valid, so either push as a valid match or continue
  6217. if (potentialMatch) {
  6218. if (potentialMatch.finished) {
  6219. potentialMatch.length = needleElements.length;
  6220. potentialMatch.endPathIndex = haystackSelectorIndex;
  6221. potentialMatch.endPathElementIndex = hackstackElementIndex + 1; // index after end of match
  6222. potentialMatches.length = 0; // we don't allow matches to overlap, so start matching again
  6223. matches.push(potentialMatch);
  6224. }
  6225. } else {
  6226. potentialMatches.splice(i, 1);
  6227. i--;
  6228. }
  6229. }
  6230. }
  6231. }
  6232. return matches;
  6233. }
  6234. }, {
  6235. key: "isElementValuesEqual",
  6236. value: function isElementValuesEqual(elementValue1, elementValue2) {
  6237. if (typeof elementValue1 === 'string' || typeof elementValue2 === 'string') {
  6238. return elementValue1 === elementValue2;
  6239. }
  6240. if (elementValue1 instanceof tree.Attribute) {
  6241. if (elementValue1.op !== elementValue2.op || elementValue1.key !== elementValue2.key) {
  6242. return false;
  6243. }
  6244. if (!elementValue1.value || !elementValue2.value) {
  6245. if (elementValue1.value || elementValue2.value) {
  6246. return false;
  6247. }
  6248. return true;
  6249. }
  6250. elementValue1 = elementValue1.value.value || elementValue1.value;
  6251. elementValue2 = elementValue2.value.value || elementValue2.value;
  6252. return elementValue1 === elementValue2;
  6253. }
  6254. elementValue1 = elementValue1.value;
  6255. elementValue2 = elementValue2.value;
  6256. if (elementValue1 instanceof tree.Selector) {
  6257. if (!(elementValue2 instanceof tree.Selector) || elementValue1.elements.length !== elementValue2.elements.length) {
  6258. return false;
  6259. }
  6260. for (var i = 0; i < elementValue1.elements.length; i++) {
  6261. if (elementValue1.elements[i].combinator.value !== elementValue2.elements[i].combinator.value) {
  6262. if (i !== 0 || (elementValue1.elements[i].combinator.value || ' ') !== (elementValue2.elements[i].combinator.value || ' ')) {
  6263. return false;
  6264. }
  6265. }
  6266. if (!this.isElementValuesEqual(elementValue1.elements[i].value, elementValue2.elements[i].value)) {
  6267. return false;
  6268. }
  6269. }
  6270. return true;
  6271. }
  6272. return false;
  6273. }
  6274. }, {
  6275. key: "extendSelector",
  6276. value: function extendSelector(matches, selectorPath, replacementSelector, isVisible) {
  6277. // for a set of matches, replace each match with the replacement selector
  6278. var currentSelectorPathIndex = 0;
  6279. var currentSelectorPathElementIndex = 0;
  6280. var path = [];
  6281. var matchIndex;
  6282. var selector;
  6283. var firstElement;
  6284. var match;
  6285. var newElements;
  6286. for (matchIndex = 0; matchIndex < matches.length; matchIndex++) {
  6287. match = matches[matchIndex];
  6288. selector = selectorPath[match.pathIndex];
  6289. firstElement = new tree.Element(match.initialCombinator, replacementSelector.elements[0].value, replacementSelector.elements[0].isVariable, replacementSelector.elements[0].getIndex(), replacementSelector.elements[0].fileInfo());
  6290. if (match.pathIndex > currentSelectorPathIndex && currentSelectorPathElementIndex > 0) {
  6291. path[path.length - 1].elements = path[path.length - 1].elements.concat(selectorPath[currentSelectorPathIndex].elements.slice(currentSelectorPathElementIndex));
  6292. currentSelectorPathElementIndex = 0;
  6293. currentSelectorPathIndex++;
  6294. }
  6295. newElements = selector.elements.slice(currentSelectorPathElementIndex, match.index).concat([firstElement]).concat(replacementSelector.elements.slice(1));
  6296. if (currentSelectorPathIndex === match.pathIndex && matchIndex > 0) {
  6297. path[path.length - 1].elements = path[path.length - 1].elements.concat(newElements);
  6298. } else {
  6299. path = path.concat(selectorPath.slice(currentSelectorPathIndex, match.pathIndex));
  6300. path.push(new tree.Selector(newElements));
  6301. }
  6302. currentSelectorPathIndex = match.endPathIndex;
  6303. currentSelectorPathElementIndex = match.endPathElementIndex;
  6304. if (currentSelectorPathElementIndex >= selectorPath[currentSelectorPathIndex].elements.length) {
  6305. currentSelectorPathElementIndex = 0;
  6306. currentSelectorPathIndex++;
  6307. }
  6308. }
  6309. if (currentSelectorPathIndex < selectorPath.length && currentSelectorPathElementIndex > 0) {
  6310. path[path.length - 1].elements = path[path.length - 1].elements.concat(selectorPath[currentSelectorPathIndex].elements.slice(currentSelectorPathElementIndex));
  6311. currentSelectorPathIndex++;
  6312. }
  6313. path = path.concat(selectorPath.slice(currentSelectorPathIndex, selectorPath.length));
  6314. path = path.map(function (currentValue) {
  6315. // we can re-use elements here, because the visibility property matters only for selectors
  6316. var derived = currentValue.createDerived(currentValue.elements);
  6317. if (isVisible) {
  6318. derived.ensureVisibility();
  6319. } else {
  6320. derived.ensureInvisibility();
  6321. }
  6322. return derived;
  6323. });
  6324. return path;
  6325. }
  6326. }, {
  6327. key: "visitMedia",
  6328. value: function visitMedia(mediaNode, visitArgs) {
  6329. var newAllExtends = mediaNode.allExtends.concat(this.allExtendsStack[this.allExtendsStack.length - 1]);
  6330. newAllExtends = newAllExtends.concat(this.doExtendChaining(newAllExtends, mediaNode.allExtends));
  6331. this.allExtendsStack.push(newAllExtends);
  6332. }
  6333. }, {
  6334. key: "visitMediaOut",
  6335. value: function visitMediaOut(mediaNode) {
  6336. var lastIndex = this.allExtendsStack.length - 1;
  6337. this.allExtendsStack.length = lastIndex;
  6338. }
  6339. }, {
  6340. key: "visitAtRule",
  6341. value: function visitAtRule(atRuleNode, visitArgs) {
  6342. var newAllExtends = atRuleNode.allExtends.concat(this.allExtendsStack[this.allExtendsStack.length - 1]);
  6343. newAllExtends = newAllExtends.concat(this.doExtendChaining(newAllExtends, atRuleNode.allExtends));
  6344. this.allExtendsStack.push(newAllExtends);
  6345. }
  6346. }, {
  6347. key: "visitAtRuleOut",
  6348. value: function visitAtRuleOut(atRuleNode) {
  6349. var lastIndex = this.allExtendsStack.length - 1;
  6350. this.allExtendsStack.length = lastIndex;
  6351. }
  6352. }]);
  6353. return ProcessExtendsVisitor;
  6354. }();
  6355. var JoinSelectorVisitor =
  6356. /*#__PURE__*/
  6357. function () {
  6358. function JoinSelectorVisitor() {
  6359. _classCallCheck(this, JoinSelectorVisitor);
  6360. this.contexts = [[]];
  6361. this._visitor = new Visitor(this);
  6362. }
  6363. _createClass(JoinSelectorVisitor, [{
  6364. key: "run",
  6365. value: function run(root) {
  6366. return this._visitor.visit(root);
  6367. }
  6368. }, {
  6369. key: "visitDeclaration",
  6370. value: function visitDeclaration(declNode, visitArgs) {
  6371. visitArgs.visitDeeper = false;
  6372. }
  6373. }, {
  6374. key: "visitMixinDefinition",
  6375. value: function visitMixinDefinition(mixinDefinitionNode, visitArgs) {
  6376. visitArgs.visitDeeper = false;
  6377. }
  6378. }, {
  6379. key: "visitRuleset",
  6380. value: function visitRuleset(rulesetNode, visitArgs) {
  6381. var context = this.contexts[this.contexts.length - 1];
  6382. var paths = [];
  6383. var selectors;
  6384. this.contexts.push(paths);
  6385. if (!rulesetNode.root) {
  6386. selectors = rulesetNode.selectors;
  6387. if (selectors) {
  6388. selectors = selectors.filter(function (selector) {
  6389. return selector.getIsOutput();
  6390. });
  6391. rulesetNode.selectors = selectors.length ? selectors : selectors = null;
  6392. if (selectors) {
  6393. rulesetNode.joinSelectors(paths, context, selectors);
  6394. }
  6395. }
  6396. if (!selectors) {
  6397. rulesetNode.rules = null;
  6398. }
  6399. rulesetNode.paths = paths;
  6400. }
  6401. }
  6402. }, {
  6403. key: "visitRulesetOut",
  6404. value: function visitRulesetOut(rulesetNode) {
  6405. this.contexts.length = this.contexts.length - 1;
  6406. }
  6407. }, {
  6408. key: "visitMedia",
  6409. value: function visitMedia(mediaNode, visitArgs) {
  6410. var context = this.contexts[this.contexts.length - 1];
  6411. mediaNode.rules[0].root = context.length === 0 || context[0].multiMedia;
  6412. }
  6413. }, {
  6414. key: "visitAtRule",
  6415. value: function visitAtRule(atRuleNode, visitArgs) {
  6416. var context = this.contexts[this.contexts.length - 1];
  6417. if (atRuleNode.rules && atRuleNode.rules.length) {
  6418. atRuleNode.rules[0].root = atRuleNode.isRooted || context.length === 0 || null;
  6419. }
  6420. }
  6421. }]);
  6422. return JoinSelectorVisitor;
  6423. }();
  6424. var CSSVisitorUtils =
  6425. /*#__PURE__*/
  6426. function () {
  6427. function CSSVisitorUtils(context) {
  6428. _classCallCheck(this, CSSVisitorUtils);
  6429. this._visitor = new Visitor(this);
  6430. this._context = context;
  6431. }
  6432. _createClass(CSSVisitorUtils, [{
  6433. key: "containsSilentNonBlockedChild",
  6434. value: function containsSilentNonBlockedChild(bodyRules) {
  6435. var rule;
  6436. if (!bodyRules) {
  6437. return false;
  6438. }
  6439. for (var r = 0; r < bodyRules.length; r++) {
  6440. rule = bodyRules[r];
  6441. if (rule.isSilent && rule.isSilent(this._context) && !rule.blocksVisibility()) {
  6442. // the atrule contains something that was referenced (likely by extend)
  6443. // therefore it needs to be shown in output too
  6444. return true;
  6445. }
  6446. }
  6447. return false;
  6448. }
  6449. }, {
  6450. key: "keepOnlyVisibleChilds",
  6451. value: function keepOnlyVisibleChilds(owner) {
  6452. if (owner && owner.rules) {
  6453. owner.rules = owner.rules.filter(function (thing) {
  6454. return thing.isVisible();
  6455. });
  6456. }
  6457. }
  6458. }, {
  6459. key: "isEmpty",
  6460. value: function isEmpty(owner) {
  6461. return owner && owner.rules ? owner.rules.length === 0 : true;
  6462. }
  6463. }, {
  6464. key: "hasVisibleSelector",
  6465. value: function hasVisibleSelector(rulesetNode) {
  6466. return rulesetNode && rulesetNode.paths ? rulesetNode.paths.length > 0 : false;
  6467. }
  6468. }, {
  6469. key: "resolveVisibility",
  6470. value: function resolveVisibility(node, originalRules) {
  6471. if (!node.blocksVisibility()) {
  6472. if (this.isEmpty(node) && !this.containsSilentNonBlockedChild(originalRules)) {
  6473. return;
  6474. }
  6475. return node;
  6476. }
  6477. var compiledRulesBody = node.rules[0];
  6478. this.keepOnlyVisibleChilds(compiledRulesBody);
  6479. if (this.isEmpty(compiledRulesBody)) {
  6480. return;
  6481. }
  6482. node.ensureVisibility();
  6483. node.removeVisibilityBlock();
  6484. return node;
  6485. }
  6486. }, {
  6487. key: "isVisibleRuleset",
  6488. value: function isVisibleRuleset(rulesetNode) {
  6489. if (rulesetNode.firstRoot) {
  6490. return true;
  6491. }
  6492. if (this.isEmpty(rulesetNode)) {
  6493. return false;
  6494. }
  6495. if (!rulesetNode.root && !this.hasVisibleSelector(rulesetNode)) {
  6496. return false;
  6497. }
  6498. return true;
  6499. }
  6500. }]);
  6501. return CSSVisitorUtils;
  6502. }();
  6503. var ToCSSVisitor = function ToCSSVisitor(context) {
  6504. this._visitor = new Visitor(this);
  6505. this._context = context;
  6506. this.utils = new CSSVisitorUtils(context);
  6507. };
  6508. ToCSSVisitor.prototype = {
  6509. isReplacing: true,
  6510. run: function run(root) {
  6511. return this._visitor.visit(root);
  6512. },
  6513. visitDeclaration: function visitDeclaration(declNode, visitArgs) {
  6514. if (declNode.blocksVisibility() || declNode.variable) {
  6515. return;
  6516. }
  6517. return declNode;
  6518. },
  6519. visitMixinDefinition: function visitMixinDefinition(mixinNode, visitArgs) {
  6520. // mixin definitions do not get eval'd - this means they keep state
  6521. // so we have to clear that state here so it isn't used if toCSS is called twice
  6522. mixinNode.frames = [];
  6523. },
  6524. visitExtend: function visitExtend(extendNode, visitArgs) {},
  6525. visitComment: function visitComment(commentNode, visitArgs) {
  6526. if (commentNode.blocksVisibility() || commentNode.isSilent(this._context)) {
  6527. return;
  6528. }
  6529. return commentNode;
  6530. },
  6531. visitMedia: function visitMedia(mediaNode, visitArgs) {
  6532. var originalRules = mediaNode.rules[0].rules;
  6533. mediaNode.accept(this._visitor);
  6534. visitArgs.visitDeeper = false;
  6535. return this.utils.resolveVisibility(mediaNode, originalRules);
  6536. },
  6537. visitImport: function visitImport(importNode, visitArgs) {
  6538. if (importNode.blocksVisibility()) {
  6539. return;
  6540. }
  6541. return importNode;
  6542. },
  6543. visitAtRule: function visitAtRule(atRuleNode, visitArgs) {
  6544. if (atRuleNode.rules && atRuleNode.rules.length) {
  6545. return this.visitAtRuleWithBody(atRuleNode, visitArgs);
  6546. } else {
  6547. return this.visitAtRuleWithoutBody(atRuleNode, visitArgs);
  6548. }
  6549. },
  6550. visitAnonymous: function visitAnonymous(anonymousNode, visitArgs) {
  6551. if (!anonymousNode.blocksVisibility()) {
  6552. anonymousNode.accept(this._visitor);
  6553. return anonymousNode;
  6554. }
  6555. },
  6556. visitAtRuleWithBody: function visitAtRuleWithBody(atRuleNode, visitArgs) {
  6557. // if there is only one nested ruleset and that one has no path, then it is
  6558. // just fake ruleset
  6559. function hasFakeRuleset(atRuleNode) {
  6560. var bodyRules = atRuleNode.rules;
  6561. return bodyRules.length === 1 && (!bodyRules[0].paths || bodyRules[0].paths.length === 0);
  6562. }
  6563. function getBodyRules(atRuleNode) {
  6564. var nodeRules = atRuleNode.rules;
  6565. if (hasFakeRuleset(atRuleNode)) {
  6566. return nodeRules[0].rules;
  6567. }
  6568. return nodeRules;
  6569. } // it is still true that it is only one ruleset in array
  6570. // this is last such moment
  6571. // process childs
  6572. var originalRules = getBodyRules(atRuleNode);
  6573. atRuleNode.accept(this._visitor);
  6574. visitArgs.visitDeeper = false;
  6575. if (!this.utils.isEmpty(atRuleNode)) {
  6576. this._mergeRules(atRuleNode.rules[0].rules);
  6577. }
  6578. return this.utils.resolveVisibility(atRuleNode, originalRules);
  6579. },
  6580. visitAtRuleWithoutBody: function visitAtRuleWithoutBody(atRuleNode, visitArgs) {
  6581. if (atRuleNode.blocksVisibility()) {
  6582. return;
  6583. }
  6584. if (atRuleNode.name === '@charset') {
  6585. // Only output the debug info together with subsequent @charset definitions
  6586. // a comment (or @media statement) before the actual @charset atrule would
  6587. // be considered illegal css as it has to be on the first line
  6588. if (this.charset) {
  6589. if (atRuleNode.debugInfo) {
  6590. var comment = new tree.Comment(`/* ${atRuleNode.toCSS(this._context).replace(/\n/g, '')} */\n`);
  6591. comment.debugInfo = atRuleNode.debugInfo;
  6592. return this._visitor.visit(comment);
  6593. }
  6594. return;
  6595. }
  6596. this.charset = true;
  6597. }
  6598. return atRuleNode;
  6599. },
  6600. checkValidNodes: function checkValidNodes(rules, isRoot) {
  6601. if (!rules) {
  6602. return;
  6603. }
  6604. for (var i = 0; i < rules.length; i++) {
  6605. var ruleNode = rules[i];
  6606. if (isRoot && ruleNode instanceof tree.Declaration && !ruleNode.variable) {
  6607. throw {
  6608. message: 'Properties must be inside selector blocks. They cannot be in the root',
  6609. index: ruleNode.getIndex(),
  6610. filename: ruleNode.fileInfo() && ruleNode.fileInfo().filename
  6611. };
  6612. }
  6613. if (ruleNode instanceof tree.Call) {
  6614. throw {
  6615. message: `Function '${ruleNode.name}' is undefined`,
  6616. index: ruleNode.getIndex(),
  6617. filename: ruleNode.fileInfo() && ruleNode.fileInfo().filename
  6618. };
  6619. }
  6620. if (ruleNode.type && !ruleNode.allowRoot) {
  6621. throw {
  6622. message: `${ruleNode.type} node returned by a function is not valid here`,
  6623. index: ruleNode.getIndex(),
  6624. filename: ruleNode.fileInfo() && ruleNode.fileInfo().filename
  6625. };
  6626. }
  6627. }
  6628. },
  6629. visitRuleset: function visitRuleset(rulesetNode, visitArgs) {
  6630. // at this point rulesets are nested into each other
  6631. var rule;
  6632. var rulesets = [];
  6633. this.checkValidNodes(rulesetNode.rules, rulesetNode.firstRoot);
  6634. if (!rulesetNode.root) {
  6635. // remove invisible paths
  6636. this._compileRulesetPaths(rulesetNode); // remove rulesets from this ruleset body and compile them separately
  6637. var nodeRules = rulesetNode.rules;
  6638. var nodeRuleCnt = nodeRules ? nodeRules.length : 0;
  6639. for (var i = 0; i < nodeRuleCnt;) {
  6640. rule = nodeRules[i];
  6641. if (rule && rule.rules) {
  6642. // visit because we are moving them out from being a child
  6643. rulesets.push(this._visitor.visit(rule));
  6644. nodeRules.splice(i, 1);
  6645. nodeRuleCnt--;
  6646. continue;
  6647. }
  6648. i++;
  6649. } // accept the visitor to remove rules and refactor itself
  6650. // then we can decide nogw whether we want it or not
  6651. // compile body
  6652. if (nodeRuleCnt > 0) {
  6653. rulesetNode.accept(this._visitor);
  6654. } else {
  6655. rulesetNode.rules = null;
  6656. }
  6657. visitArgs.visitDeeper = false;
  6658. } else {
  6659. // if (! rulesetNode.root) {
  6660. rulesetNode.accept(this._visitor);
  6661. visitArgs.visitDeeper = false;
  6662. }
  6663. if (rulesetNode.rules) {
  6664. this._mergeRules(rulesetNode.rules);
  6665. this._removeDuplicateRules(rulesetNode.rules);
  6666. } // now decide whether we keep the ruleset
  6667. if (this.utils.isVisibleRuleset(rulesetNode)) {
  6668. rulesetNode.ensureVisibility();
  6669. rulesets.splice(0, 0, rulesetNode);
  6670. }
  6671. if (rulesets.length === 1) {
  6672. return rulesets[0];
  6673. }
  6674. return rulesets;
  6675. },
  6676. _compileRulesetPaths: function _compileRulesetPaths(rulesetNode) {
  6677. if (rulesetNode.paths) {
  6678. rulesetNode.paths = rulesetNode.paths.filter(function (p) {
  6679. var i;
  6680. if (p[0].elements[0].combinator.value === ' ') {
  6681. p[0].elements[0].combinator = new tree.Combinator('');
  6682. }
  6683. for (i = 0; i < p.length; i++) {
  6684. if (p[i].isVisible() && p[i].getIsOutput()) {
  6685. return true;
  6686. }
  6687. }
  6688. return false;
  6689. });
  6690. }
  6691. },
  6692. _removeDuplicateRules: function _removeDuplicateRules(rules) {
  6693. if (!rules) {
  6694. return;
  6695. } // remove duplicates
  6696. var ruleCache = {};
  6697. var ruleList;
  6698. var rule;
  6699. var i;
  6700. for (i = rules.length - 1; i >= 0; i--) {
  6701. rule = rules[i];
  6702. if (rule instanceof tree.Declaration) {
  6703. if (!ruleCache[rule.name]) {
  6704. ruleCache[rule.name] = rule;
  6705. } else {
  6706. ruleList = ruleCache[rule.name];
  6707. if (ruleList instanceof tree.Declaration) {
  6708. ruleList = ruleCache[rule.name] = [ruleCache[rule.name].toCSS(this._context)];
  6709. }
  6710. var ruleCSS = rule.toCSS(this._context);
  6711. if (ruleList.indexOf(ruleCSS) !== -1) {
  6712. rules.splice(i, 1);
  6713. } else {
  6714. ruleList.push(ruleCSS);
  6715. }
  6716. }
  6717. }
  6718. }
  6719. },
  6720. _mergeRules: function _mergeRules(rules) {
  6721. if (!rules) {
  6722. return;
  6723. }
  6724. var groups = {};
  6725. var groupsArr = [];
  6726. for (var i = 0; i < rules.length; i++) {
  6727. var rule = rules[i];
  6728. if (rule.merge) {
  6729. var key = rule.name;
  6730. groups[key] ? rules.splice(i--, 1) : groupsArr.push(groups[key] = []);
  6731. groups[key].push(rule);
  6732. }
  6733. }
  6734. groupsArr.forEach(function (group) {
  6735. if (group.length > 0) {
  6736. var result = group[0];
  6737. var space = [];
  6738. var comma = [new tree.Expression(space)];
  6739. group.forEach(function (rule) {
  6740. if (rule.merge === '+' && space.length > 0) {
  6741. comma.push(new tree.Expression(space = []));
  6742. }
  6743. space.push(rule.value);
  6744. result.important = result.important || rule.important;
  6745. });
  6746. result.value = new tree.Value(comma);
  6747. }
  6748. });
  6749. }
  6750. };
  6751. var visitors = {
  6752. Visitor,
  6753. ImportVisitor,
  6754. MarkVisibleSelectorsVisitor: SetTreeVisibilityVisitor,
  6755. ExtendVisitor: ProcessExtendsVisitor,
  6756. JoinSelectorVisitor,
  6757. ToCSSVisitor
  6758. };
  6759. // Split the input into chunks.
  6760. var chunker = (function (input, fail) {
  6761. var len = input.length;
  6762. var level = 0;
  6763. var parenLevel = 0;
  6764. var lastOpening;
  6765. var lastOpeningParen;
  6766. var lastMultiComment;
  6767. var lastMultiCommentEndBrace;
  6768. var chunks = [];
  6769. var emitFrom = 0;
  6770. var chunkerCurrentIndex;
  6771. var currentChunkStartIndex;
  6772. var cc;
  6773. var cc2;
  6774. var matched;
  6775. function emitChunk(force) {
  6776. var len = chunkerCurrentIndex - emitFrom;
  6777. if (len < 512 && !force || !len) {
  6778. return;
  6779. }
  6780. chunks.push(input.slice(emitFrom, chunkerCurrentIndex + 1));
  6781. emitFrom = chunkerCurrentIndex + 1;
  6782. }
  6783. for (chunkerCurrentIndex = 0; chunkerCurrentIndex < len; chunkerCurrentIndex++) {
  6784. cc = input.charCodeAt(chunkerCurrentIndex);
  6785. if (cc >= 97 && cc <= 122 || cc < 34) {
  6786. // a-z or whitespace
  6787. continue;
  6788. }
  6789. switch (cc) {
  6790. case 40:
  6791. // (
  6792. parenLevel++;
  6793. lastOpeningParen = chunkerCurrentIndex;
  6794. continue;
  6795. case 41:
  6796. // )
  6797. if (--parenLevel < 0) {
  6798. return fail('missing opening `(`', chunkerCurrentIndex);
  6799. }
  6800. continue;
  6801. case 59:
  6802. // ;
  6803. if (!parenLevel) {
  6804. emitChunk();
  6805. }
  6806. continue;
  6807. case 123:
  6808. // {
  6809. level++;
  6810. lastOpening = chunkerCurrentIndex;
  6811. continue;
  6812. case 125:
  6813. // }
  6814. if (--level < 0) {
  6815. return fail('missing opening `{`', chunkerCurrentIndex);
  6816. }
  6817. if (!level && !parenLevel) {
  6818. emitChunk();
  6819. }
  6820. continue;
  6821. case 92:
  6822. // \
  6823. if (chunkerCurrentIndex < len - 1) {
  6824. chunkerCurrentIndex++;
  6825. continue;
  6826. }
  6827. return fail('unescaped `\\`', chunkerCurrentIndex);
  6828. case 34:
  6829. case 39:
  6830. case 96:
  6831. // ", ' and `
  6832. matched = 0;
  6833. currentChunkStartIndex = chunkerCurrentIndex;
  6834. for (chunkerCurrentIndex = chunkerCurrentIndex + 1; chunkerCurrentIndex < len; chunkerCurrentIndex++) {
  6835. cc2 = input.charCodeAt(chunkerCurrentIndex);
  6836. if (cc2 > 96) {
  6837. continue;
  6838. }
  6839. if (cc2 == cc) {
  6840. matched = 1;
  6841. break;
  6842. }
  6843. if (cc2 == 92) {
  6844. // \
  6845. if (chunkerCurrentIndex == len - 1) {
  6846. return fail('unescaped `\\`', chunkerCurrentIndex);
  6847. }
  6848. chunkerCurrentIndex++;
  6849. }
  6850. }
  6851. if (matched) {
  6852. continue;
  6853. }
  6854. return fail(`unmatched \`${String.fromCharCode(cc)}\``, currentChunkStartIndex);
  6855. case 47:
  6856. // /, check for comment
  6857. if (parenLevel || chunkerCurrentIndex == len - 1) {
  6858. continue;
  6859. }
  6860. cc2 = input.charCodeAt(chunkerCurrentIndex + 1);
  6861. if (cc2 == 47) {
  6862. // //, find lnfeed
  6863. for (chunkerCurrentIndex = chunkerCurrentIndex + 2; chunkerCurrentIndex < len; chunkerCurrentIndex++) {
  6864. cc2 = input.charCodeAt(chunkerCurrentIndex);
  6865. if (cc2 <= 13 && (cc2 == 10 || cc2 == 13)) {
  6866. break;
  6867. }
  6868. }
  6869. } else if (cc2 == 42) {
  6870. // /*, find */
  6871. lastMultiComment = currentChunkStartIndex = chunkerCurrentIndex;
  6872. for (chunkerCurrentIndex = chunkerCurrentIndex + 2; chunkerCurrentIndex < len - 1; chunkerCurrentIndex++) {
  6873. cc2 = input.charCodeAt(chunkerCurrentIndex);
  6874. if (cc2 == 125) {
  6875. lastMultiCommentEndBrace = chunkerCurrentIndex;
  6876. }
  6877. if (cc2 != 42) {
  6878. continue;
  6879. }
  6880. if (input.charCodeAt(chunkerCurrentIndex + 1) == 47) {
  6881. break;
  6882. }
  6883. }
  6884. if (chunkerCurrentIndex == len - 1) {
  6885. return fail('missing closing `*/`', currentChunkStartIndex);
  6886. }
  6887. chunkerCurrentIndex++;
  6888. }
  6889. continue;
  6890. case 42:
  6891. // *, check for unmatched */
  6892. if (chunkerCurrentIndex < len - 1 && input.charCodeAt(chunkerCurrentIndex + 1) == 47) {
  6893. return fail('unmatched `/*`', chunkerCurrentIndex);
  6894. }
  6895. continue;
  6896. }
  6897. }
  6898. if (level !== 0) {
  6899. if (lastMultiComment > lastOpening && lastMultiCommentEndBrace > lastMultiComment) {
  6900. return fail('missing closing `}` or `*/`', lastOpening);
  6901. } else {
  6902. return fail('missing closing `}`', lastOpening);
  6903. }
  6904. } else if (parenLevel !== 0) {
  6905. return fail('missing closing `)`', lastOpeningParen);
  6906. }
  6907. emitChunk(true);
  6908. return chunks;
  6909. });
  6910. var getParserInput = (function () {
  6911. var // Less input string
  6912. input;
  6913. var // current chunk
  6914. j;
  6915. var // holds state for backtracking
  6916. saveStack = [];
  6917. var // furthest index the parser has gone to
  6918. furthest;
  6919. var // if this is furthest we got to, this is the probably cause
  6920. furthestPossibleErrorMessage;
  6921. var // chunkified input
  6922. chunks;
  6923. var // current chunk
  6924. current;
  6925. var // index of current chunk, in `input`
  6926. currentPos;
  6927. var parserInput = {};
  6928. var CHARCODE_SPACE = 32;
  6929. var CHARCODE_TAB = 9;
  6930. var CHARCODE_LF = 10;
  6931. var CHARCODE_CR = 13;
  6932. var CHARCODE_PLUS = 43;
  6933. var CHARCODE_COMMA = 44;
  6934. var CHARCODE_FORWARD_SLASH = 47;
  6935. var CHARCODE_9 = 57;
  6936. function skipWhitespace(length) {
  6937. var oldi = parserInput.i;
  6938. var oldj = j;
  6939. var curr = parserInput.i - currentPos;
  6940. var endIndex = parserInput.i + current.length - curr;
  6941. var mem = parserInput.i += length;
  6942. var inp = input;
  6943. var c;
  6944. var nextChar;
  6945. var comment;
  6946. for (; parserInput.i < endIndex; parserInput.i++) {
  6947. c = inp.charCodeAt(parserInput.i);
  6948. if (parserInput.autoCommentAbsorb && c === CHARCODE_FORWARD_SLASH) {
  6949. nextChar = inp.charAt(parserInput.i + 1);
  6950. if (nextChar === '/') {
  6951. comment = {
  6952. index: parserInput.i,
  6953. isLineComment: true
  6954. };
  6955. var nextNewLine = inp.indexOf('\n', parserInput.i + 2);
  6956. if (nextNewLine < 0) {
  6957. nextNewLine = endIndex;
  6958. }
  6959. parserInput.i = nextNewLine;
  6960. comment.text = inp.substr(comment.index, parserInput.i - comment.index);
  6961. parserInput.commentStore.push(comment);
  6962. continue;
  6963. } else if (nextChar === '*') {
  6964. var nextStarSlash = inp.indexOf('*/', parserInput.i + 2);
  6965. if (nextStarSlash >= 0) {
  6966. comment = {
  6967. index: parserInput.i,
  6968. text: inp.substr(parserInput.i, nextStarSlash + 2 - parserInput.i),
  6969. isLineComment: false
  6970. };
  6971. parserInput.i += comment.text.length - 1;
  6972. parserInput.commentStore.push(comment);
  6973. continue;
  6974. }
  6975. }
  6976. break;
  6977. }
  6978. if (c !== CHARCODE_SPACE && c !== CHARCODE_LF && c !== CHARCODE_TAB && c !== CHARCODE_CR) {
  6979. break;
  6980. }
  6981. }
  6982. current = current.slice(length + parserInput.i - mem + curr);
  6983. currentPos = parserInput.i;
  6984. if (!current.length) {
  6985. if (j < chunks.length - 1) {
  6986. current = chunks[++j];
  6987. skipWhitespace(0); // skip space at the beginning of a chunk
  6988. return true; // things changed
  6989. }
  6990. parserInput.finished = true;
  6991. }
  6992. return oldi !== parserInput.i || oldj !== j;
  6993. }
  6994. parserInput.save = function () {
  6995. currentPos = parserInput.i;
  6996. saveStack.push({
  6997. current,
  6998. i: parserInput.i,
  6999. j
  7000. });
  7001. };
  7002. parserInput.restore = function (possibleErrorMessage) {
  7003. if (parserInput.i > furthest || parserInput.i === furthest && possibleErrorMessage && !furthestPossibleErrorMessage) {
  7004. furthest = parserInput.i;
  7005. furthestPossibleErrorMessage = possibleErrorMessage;
  7006. }
  7007. var state = saveStack.pop();
  7008. current = state.current;
  7009. currentPos = parserInput.i = state.i;
  7010. j = state.j;
  7011. };
  7012. parserInput.forget = function () {
  7013. saveStack.pop();
  7014. };
  7015. parserInput.isWhitespace = function (offset) {
  7016. var pos = parserInput.i + (offset || 0);
  7017. var code = input.charCodeAt(pos);
  7018. return code === CHARCODE_SPACE || code === CHARCODE_CR || code === CHARCODE_TAB || code === CHARCODE_LF;
  7019. }; // Specialization of $(tok)
  7020. parserInput.$re = function (tok) {
  7021. if (parserInput.i > currentPos) {
  7022. current = current.slice(parserInput.i - currentPos);
  7023. currentPos = parserInput.i;
  7024. }
  7025. var m = tok.exec(current);
  7026. if (!m) {
  7027. return null;
  7028. }
  7029. skipWhitespace(m[0].length);
  7030. if (typeof m === 'string') {
  7031. return m;
  7032. }
  7033. return m.length === 1 ? m[0] : m;
  7034. };
  7035. parserInput.$char = function (tok) {
  7036. if (input.charAt(parserInput.i) !== tok) {
  7037. return null;
  7038. }
  7039. skipWhitespace(1);
  7040. return tok;
  7041. };
  7042. parserInput.$str = function (tok) {
  7043. var tokLength = tok.length; // https://jsperf.com/string-startswith/21
  7044. for (var i = 0; i < tokLength; i++) {
  7045. if (input.charAt(parserInput.i + i) !== tok.charAt(i)) {
  7046. return null;
  7047. }
  7048. }
  7049. skipWhitespace(tokLength);
  7050. return tok;
  7051. };
  7052. parserInput.$quoted = function (loc) {
  7053. var pos = loc || parserInput.i;
  7054. var startChar = input.charAt(pos);
  7055. if (startChar !== '\'' && startChar !== '"') {
  7056. return;
  7057. }
  7058. var length = input.length;
  7059. var currentPosition = pos;
  7060. for (var i = 1; i + currentPosition < length; i++) {
  7061. var nextChar = input.charAt(i + currentPosition);
  7062. switch (nextChar) {
  7063. case '\\':
  7064. i++;
  7065. continue;
  7066. case '\r':
  7067. case '\n':
  7068. break;
  7069. case startChar:
  7070. var str = input.substr(currentPosition, i + 1);
  7071. if (!loc && loc !== 0) {
  7072. skipWhitespace(i + 1);
  7073. return str;
  7074. }
  7075. return [startChar, str];
  7076. default:
  7077. }
  7078. }
  7079. return null;
  7080. };
  7081. /**
  7082. * Permissive parsing. Ignores everything except matching {} [] () and quotes
  7083. * until matching token (outside of blocks)
  7084. */
  7085. parserInput.$parseUntil = function (tok) {
  7086. var quote = '';
  7087. var returnVal = null;
  7088. var inComment = false;
  7089. var blockDepth = 0;
  7090. var blockStack = [];
  7091. var parseGroups = [];
  7092. var length = input.length;
  7093. var startPos = parserInput.i;
  7094. var lastPos = parserInput.i;
  7095. var i = parserInput.i;
  7096. var loop = true;
  7097. var testChar;
  7098. if (typeof tok === 'string') {
  7099. testChar = function testChar(char) {
  7100. return char === tok;
  7101. };
  7102. } else {
  7103. testChar = function testChar(char) {
  7104. return tok.test(char);
  7105. };
  7106. }
  7107. do {
  7108. var nextChar = input.charAt(i);
  7109. if (blockDepth === 0 && testChar(nextChar)) {
  7110. returnVal = input.substr(lastPos, i - lastPos);
  7111. if (returnVal) {
  7112. parseGroups.push(returnVal);
  7113. } else {
  7114. parseGroups.push(' ');
  7115. }
  7116. returnVal = parseGroups;
  7117. skipWhitespace(i - startPos);
  7118. loop = false;
  7119. } else {
  7120. if (inComment) {
  7121. if (nextChar === '*' && input.charAt(i + 1) === '/') {
  7122. i++;
  7123. blockDepth--;
  7124. inComment = false;
  7125. }
  7126. i++;
  7127. continue;
  7128. }
  7129. switch (nextChar) {
  7130. case '\\':
  7131. i++;
  7132. nextChar = input.charAt(i);
  7133. parseGroups.push(input.substr(lastPos, i - lastPos + 1));
  7134. lastPos = i + 1;
  7135. break;
  7136. case '/':
  7137. if (input.charAt(i + 1) === '*') {
  7138. i++;
  7139. inComment = true;
  7140. blockDepth++;
  7141. }
  7142. break;
  7143. case '\'':
  7144. case '"':
  7145. quote = parserInput.$quoted(i);
  7146. if (quote) {
  7147. parseGroups.push(input.substr(lastPos, i - lastPos), quote);
  7148. i += quote[1].length - 1;
  7149. lastPos = i + 1;
  7150. } else {
  7151. skipWhitespace(i - startPos);
  7152. returnVal = nextChar;
  7153. loop = false;
  7154. }
  7155. break;
  7156. case '{':
  7157. blockStack.push('}');
  7158. blockDepth++;
  7159. break;
  7160. case '(':
  7161. blockStack.push(')');
  7162. blockDepth++;
  7163. break;
  7164. case '[':
  7165. blockStack.push(']');
  7166. blockDepth++;
  7167. break;
  7168. case '}':
  7169. case ')':
  7170. case ']':
  7171. var expected = blockStack.pop();
  7172. if (nextChar === expected) {
  7173. blockDepth--;
  7174. } else {
  7175. // move the parser to the error and return expected
  7176. skipWhitespace(i - startPos);
  7177. returnVal = expected;
  7178. loop = false;
  7179. }
  7180. }
  7181. i++;
  7182. if (i > length) {
  7183. loop = false;
  7184. }
  7185. }
  7186. } while (loop);
  7187. return returnVal ? returnVal : null;
  7188. };
  7189. parserInput.autoCommentAbsorb = true;
  7190. parserInput.commentStore = [];
  7191. parserInput.finished = false; // Same as $(), but don't change the state of the parser,
  7192. // just return the match.
  7193. parserInput.peek = function (tok) {
  7194. if (typeof tok === 'string') {
  7195. // https://jsperf.com/string-startswith/21
  7196. for (var i = 0; i < tok.length; i++) {
  7197. if (input.charAt(parserInput.i + i) !== tok.charAt(i)) {
  7198. return false;
  7199. }
  7200. }
  7201. return true;
  7202. } else {
  7203. return tok.test(current);
  7204. }
  7205. }; // Specialization of peek()
  7206. // TODO remove or change some currentChar calls to peekChar
  7207. parserInput.peekChar = function (tok) {
  7208. return input.charAt(parserInput.i) === tok;
  7209. };
  7210. parserInput.currentChar = function () {
  7211. return input.charAt(parserInput.i);
  7212. };
  7213. parserInput.prevChar = function () {
  7214. return input.charAt(parserInput.i - 1);
  7215. };
  7216. parserInput.getInput = function () {
  7217. return input;
  7218. };
  7219. parserInput.peekNotNumeric = function () {
  7220. var c = input.charCodeAt(parserInput.i); // Is the first char of the dimension 0-9, '.', '+' or '-'
  7221. return c > CHARCODE_9 || c < CHARCODE_PLUS || c === CHARCODE_FORWARD_SLASH || c === CHARCODE_COMMA;
  7222. };
  7223. parserInput.start = function (str, chunkInput, failFunction) {
  7224. input = str;
  7225. parserInput.i = j = currentPos = furthest = 0; // chunking apparently makes things quicker (but my tests indicate
  7226. // it might actually make things slower in node at least)
  7227. // and it is a non-perfect parse - it can't recognise
  7228. // unquoted urls, meaning it can't distinguish comments
  7229. // meaning comments with quotes or {}() in them get 'counted'
  7230. // and then lead to parse errors.
  7231. // In addition if the chunking chunks in the wrong place we might
  7232. // not be able to parse a parser statement in one go
  7233. // this is officially deprecated but can be switched on via an option
  7234. // in the case it causes too much performance issues.
  7235. if (chunkInput) {
  7236. chunks = chunker(str, failFunction);
  7237. } else {
  7238. chunks = [str];
  7239. }
  7240. current = chunks[0];
  7241. skipWhitespace(0);
  7242. };
  7243. parserInput.end = function () {
  7244. var message;
  7245. var isFinished = parserInput.i >= input.length;
  7246. if (parserInput.i < furthest) {
  7247. message = furthestPossibleErrorMessage;
  7248. parserInput.i = furthest;
  7249. }
  7250. return {
  7251. isFinished,
  7252. furthest: parserInput.i,
  7253. furthestPossibleErrorMessage: message,
  7254. furthestReachedEnd: parserInput.i >= input.length - 1,
  7255. furthestChar: input[parserInput.i]
  7256. };
  7257. };
  7258. return parserInput;
  7259. });
  7260. // less.js - parser
  7261. //
  7262. // A relatively straight-forward predictive parser.
  7263. // There is no tokenization/lexing stage, the input is parsed
  7264. // in one sweep.
  7265. //
  7266. // To make the parser fast enough to run in the browser, several
  7267. // optimization had to be made:
  7268. //
  7269. // - Matching and slicing on a huge input is often cause of slowdowns.
  7270. // The solution is to chunkify the input into smaller strings.
  7271. // The chunks are stored in the `chunks` var,
  7272. // `j` holds the current chunk index, and `currentPos` holds
  7273. // the index of the current chunk in relation to `input`.
  7274. // This gives us an almost 4x speed-up.
  7275. //
  7276. // - In many cases, we don't need to match individual tokens;
  7277. // for example, if a value doesn't hold any variables, operations
  7278. // or dynamic references, the parser can effectively 'skip' it,
  7279. // treating it as a literal.
  7280. // An example would be '1px solid #000' - which evaluates to itself,
  7281. // we don't need to know what the individual components are.
  7282. // The drawback, of course is that you don't get the benefits of
  7283. // syntax-checking on the CSS. This gives us a 50% speed-up in the parser,
  7284. // and a smaller speed-up in the code-gen.
  7285. //
  7286. //
  7287. // Token matching is done with the `$` function, which either takes
  7288. // a terminal string or regexp, or a non-terminal function to call.
  7289. // It also takes care of moving all the indices forwards.
  7290. //
  7291. var Parser = function Parser(context, imports, fileInfo) {
  7292. var parsers;
  7293. var parserInput = getParserInput();
  7294. function error(msg, type) {
  7295. throw new LessError({
  7296. index: parserInput.i,
  7297. filename: fileInfo.filename,
  7298. type: type || 'Syntax',
  7299. message: msg
  7300. }, imports);
  7301. }
  7302. function expect(arg, msg) {
  7303. // some older browsers return typeof 'function' for RegExp
  7304. var result = arg instanceof Function ? arg.call(parsers) : parserInput.$re(arg);
  7305. if (result) {
  7306. return result;
  7307. }
  7308. error(msg || (typeof arg === 'string' ? `expected '${arg}' got '${parserInput.currentChar()}'` : 'unexpected token'));
  7309. } // Specialization of expect()
  7310. function expectChar(arg, msg) {
  7311. if (parserInput.$char(arg)) {
  7312. return arg;
  7313. }
  7314. error(msg || `expected '${arg}' got '${parserInput.currentChar()}'`);
  7315. }
  7316. function getDebugInfo(index) {
  7317. var filename = fileInfo.filename;
  7318. return {
  7319. lineNumber: getLocation(index, parserInput.getInput()).line + 1,
  7320. fileName: filename
  7321. };
  7322. }
  7323. /**
  7324. * Used after initial parsing to create nodes on the fly
  7325. *
  7326. * @param {String} str - string to parse
  7327. * @param {Array} parseList - array of parsers to run input through e.g. ["value", "important"]
  7328. * @param {Number} currentIndex - start number to begin indexing
  7329. * @param {Object} fileInfo - fileInfo to attach to created nodes
  7330. */
  7331. function parseNode(str, parseList, currentIndex, fileInfo, callback) {
  7332. var result;
  7333. var returnNodes = [];
  7334. var parser = parserInput;
  7335. try {
  7336. parser.start(str, false, function fail(msg, index) {
  7337. callback({
  7338. message: msg,
  7339. index: index + currentIndex
  7340. });
  7341. });
  7342. for (var x = 0, p, i; p = parseList[x]; x++) {
  7343. i = parser.i;
  7344. result = parsers[p]();
  7345. if (result) {
  7346. try {
  7347. result._index = i + currentIndex;
  7348. result._fileInfo = fileInfo;
  7349. } catch (e) {}
  7350. returnNodes.push(result);
  7351. } else {
  7352. returnNodes.push(null);
  7353. }
  7354. }
  7355. var endInfo = parser.end();
  7356. if (endInfo.isFinished) {
  7357. callback(null, returnNodes);
  7358. } else {
  7359. callback(true, null);
  7360. }
  7361. } catch (e) {
  7362. throw new LessError({
  7363. index: e.index + currentIndex,
  7364. message: e.message
  7365. }, imports, fileInfo.filename);
  7366. }
  7367. } //
  7368. // The Parser
  7369. //
  7370. return {
  7371. parserInput,
  7372. imports,
  7373. fileInfo,
  7374. parseNode,
  7375. //
  7376. // Parse an input string into an abstract syntax tree,
  7377. // @param str A string containing 'less' markup
  7378. // @param callback call `callback` when done.
  7379. // @param [additionalData] An optional map which can contains vars - a map (key, value) of variables to apply
  7380. //
  7381. parse: function parse(str, callback, additionalData) {
  7382. var root;
  7383. var error = null;
  7384. var globalVars;
  7385. var modifyVars;
  7386. var ignored;
  7387. var preText = '';
  7388. globalVars = additionalData && additionalData.globalVars ? `${Parser.serializeVars(additionalData.globalVars)}\n` : '';
  7389. modifyVars = additionalData && additionalData.modifyVars ? `\n${Parser.serializeVars(additionalData.modifyVars)}` : '';
  7390. if (context.pluginManager) {
  7391. var preProcessors = context.pluginManager.getPreProcessors();
  7392. for (var i = 0; i < preProcessors.length; i++) {
  7393. str = preProcessors[i].process(str, {
  7394. context,
  7395. imports,
  7396. fileInfo
  7397. });
  7398. }
  7399. }
  7400. if (globalVars || additionalData && additionalData.banner) {
  7401. preText = (additionalData && additionalData.banner ? additionalData.banner : '') + globalVars;
  7402. ignored = imports.contentsIgnoredChars;
  7403. ignored[fileInfo.filename] = ignored[fileInfo.filename] || 0;
  7404. ignored[fileInfo.filename] += preText.length;
  7405. }
  7406. str = str.replace(/\r\n?/g, '\n'); // Remove potential UTF Byte Order Mark
  7407. str = preText + str.replace(/^\uFEFF/, '') + modifyVars;
  7408. imports.contents[fileInfo.filename] = str; // Start with the primary rule.
  7409. // The whole syntax tree is held under a Ruleset node,
  7410. // with the `root` property set to true, so no `{}` are
  7411. // output. The callback is called when the input is parsed.
  7412. try {
  7413. parserInput.start(str, context.chunkInput, function fail(msg, index) {
  7414. throw new LessError({
  7415. index,
  7416. type: 'Parse',
  7417. message: msg,
  7418. filename: fileInfo.filename
  7419. }, imports);
  7420. });
  7421. tree.Node.prototype.parse = this;
  7422. root = new tree.Ruleset(null, this.parsers.primary());
  7423. tree.Node.prototype.rootNode = root;
  7424. root.root = true;
  7425. root.firstRoot = true;
  7426. root.functionRegistry = functionRegistry.inherit();
  7427. } catch (e) {
  7428. return callback(new LessError(e, imports, fileInfo.filename));
  7429. } // If `i` is smaller than the `input.length - 1`,
  7430. // it means the parser wasn't able to parse the whole
  7431. // string, so we've got a parsing error.
  7432. //
  7433. // We try to extract a \n delimited string,
  7434. // showing the line where the parse error occurred.
  7435. // We split it up into two parts (the part which parsed,
  7436. // and the part which didn't), so we can color them differently.
  7437. var endInfo = parserInput.end();
  7438. if (!endInfo.isFinished) {
  7439. var message = endInfo.furthestPossibleErrorMessage;
  7440. if (!message) {
  7441. message = 'Unrecognised input';
  7442. if (endInfo.furthestChar === '}') {
  7443. message += '. Possibly missing opening \'{\'';
  7444. } else if (endInfo.furthestChar === ')') {
  7445. message += '. Possibly missing opening \'(\'';
  7446. } else if (endInfo.furthestReachedEnd) {
  7447. message += '. Possibly missing something';
  7448. }
  7449. }
  7450. error = new LessError({
  7451. type: 'Parse',
  7452. message,
  7453. index: endInfo.furthest,
  7454. filename: fileInfo.filename
  7455. }, imports);
  7456. }
  7457. var finish = function finish(e) {
  7458. e = error || e || imports.error;
  7459. if (e) {
  7460. if (!(e instanceof LessError)) {
  7461. e = new LessError(e, imports, fileInfo.filename);
  7462. }
  7463. return callback(e);
  7464. } else {
  7465. return callback(null, root);
  7466. }
  7467. };
  7468. if (context.processImports !== false) {
  7469. new visitors.ImportVisitor(imports, finish).run(root);
  7470. } else {
  7471. return finish();
  7472. }
  7473. },
  7474. //
  7475. // Here in, the parsing rules/functions
  7476. //
  7477. // The basic structure of the syntax tree generated is as follows:
  7478. //
  7479. // Ruleset -> Declaration -> Value -> Expression -> Entity
  7480. //
  7481. // Here's some Less code:
  7482. //
  7483. // .class {
  7484. // color: #fff;
  7485. // border: 1px solid #000;
  7486. // width: @w + 4px;
  7487. // > .child {...}
  7488. // }
  7489. //
  7490. // And here's what the parse tree might look like:
  7491. //
  7492. // Ruleset (Selector '.class', [
  7493. // Declaration ("color", Value ([Expression [Color #fff]]))
  7494. // Declaration ("border", Value ([Expression [Dimension 1px][Keyword "solid"][Color #000]]))
  7495. // Declaration ("width", Value ([Expression [Operation " + " [Variable "@w"][Dimension 4px]]]))
  7496. // Ruleset (Selector [Element '>', '.child'], [...])
  7497. // ])
  7498. //
  7499. // In general, most rules will try to parse a token with the `$re()` function, and if the return
  7500. // value is truly, will return a new node, of the relevant type. Sometimes, we need to check
  7501. // first, before parsing, that's when we use `peek()`.
  7502. //
  7503. parsers: parsers = {
  7504. //
  7505. // The `primary` rule is the *entry* and *exit* point of the parser.
  7506. // The rules here can appear at any level of the parse tree.
  7507. //
  7508. // The recursive nature of the grammar is an interplay between the `block`
  7509. // rule, which represents `{ ... }`, the `ruleset` rule, and this `primary` rule,
  7510. // as represented by this simplified grammar:
  7511. //
  7512. // primary → (ruleset | declaration)+
  7513. // ruleset → selector+ block
  7514. // block → '{' primary '}'
  7515. //
  7516. // Only at one point is the primary rule not called from the
  7517. // block rule: at the root level.
  7518. //
  7519. primary: function primary() {
  7520. var mixin = this.mixin;
  7521. var root = [];
  7522. var node;
  7523. while (true) {
  7524. while (true) {
  7525. node = this.comment();
  7526. if (!node) {
  7527. break;
  7528. }
  7529. root.push(node);
  7530. } // always process comments before deciding if finished
  7531. if (parserInput.finished) {
  7532. break;
  7533. }
  7534. if (parserInput.peek('}')) {
  7535. break;
  7536. }
  7537. node = this.extendRule();
  7538. if (node) {
  7539. root = root.concat(node);
  7540. continue;
  7541. }
  7542. node = mixin.definition() || this.declaration() || this.ruleset() || mixin.call(false, false) || this.variableCall() || this.entities.call() || this.atrule();
  7543. if (node) {
  7544. root.push(node);
  7545. } else {
  7546. var foundSemiColon = false;
  7547. while (parserInput.$char(';')) {
  7548. foundSemiColon = true;
  7549. }
  7550. if (!foundSemiColon) {
  7551. break;
  7552. }
  7553. }
  7554. }
  7555. return root;
  7556. },
  7557. // comments are collected by the main parsing mechanism and then assigned to nodes
  7558. // where the current structure allows it
  7559. comment: function comment() {
  7560. if (parserInput.commentStore.length) {
  7561. var comment = parserInput.commentStore.shift();
  7562. return new tree.Comment(comment.text, comment.isLineComment, comment.index, fileInfo);
  7563. }
  7564. },
  7565. //
  7566. // Entities are tokens which can be found inside an Expression
  7567. //
  7568. entities: {
  7569. mixinLookup: function mixinLookup() {
  7570. return parsers.mixin.call(true, true);
  7571. },
  7572. //
  7573. // A string, which supports escaping " and '
  7574. //
  7575. // "milky way" 'he\'s the one!'
  7576. //
  7577. quoted: function quoted(forceEscaped) {
  7578. var str;
  7579. var index = parserInput.i;
  7580. var isEscaped = false;
  7581. parserInput.save();
  7582. if (parserInput.$char('~')) {
  7583. isEscaped = true;
  7584. } else if (forceEscaped) {
  7585. parserInput.restore();
  7586. return;
  7587. }
  7588. str = parserInput.$quoted();
  7589. if (!str) {
  7590. parserInput.restore();
  7591. return;
  7592. }
  7593. parserInput.forget();
  7594. return new tree.Quoted(str.charAt(0), str.substr(1, str.length - 2), isEscaped, index, fileInfo);
  7595. },
  7596. //
  7597. // A catch-all word, such as:
  7598. //
  7599. // black border-collapse
  7600. //
  7601. keyword: function keyword() {
  7602. var k = parserInput.$char('%') || parserInput.$re(/^\[?(?:[\w-]|\\(?:[A-Fa-f0-9]{1,6} ?|[^A-Fa-f0-9]))+\]?/);
  7603. if (k) {
  7604. return tree.Color.fromKeyword(k) || new tree.Keyword(k);
  7605. }
  7606. },
  7607. //
  7608. // A function call
  7609. //
  7610. // rgb(255, 0, 255)
  7611. //
  7612. // The arguments are parsed with the `entities.arguments` parser.
  7613. //
  7614. call: function call() {
  7615. var name;
  7616. var args;
  7617. var func;
  7618. var index = parserInput.i; // http://jsperf.com/case-insensitive-regex-vs-strtolower-then-regex/18
  7619. if (parserInput.peek(/^url\(/i)) {
  7620. return;
  7621. }
  7622. parserInput.save();
  7623. name = parserInput.$re(/^([\w-]+|%|progid:[\w\.]+)\(/);
  7624. if (!name) {
  7625. parserInput.forget();
  7626. return;
  7627. }
  7628. name = name[1];
  7629. func = this.customFuncCall(name);
  7630. if (func) {
  7631. args = func.parse();
  7632. if (args && func.stop) {
  7633. parserInput.forget();
  7634. return args;
  7635. }
  7636. }
  7637. args = this.arguments(args);
  7638. if (!parserInput.$char(')')) {
  7639. parserInput.restore('Could not parse call arguments or missing \')\'');
  7640. return;
  7641. }
  7642. parserInput.forget();
  7643. return new tree.Call(name, args, index, fileInfo);
  7644. },
  7645. //
  7646. // Parsing rules for functions with non-standard args, e.g.:
  7647. //
  7648. // boolean(not(2 > 1))
  7649. //
  7650. // This is a quick prototype, to be modified/improved when
  7651. // more custom-parsed funcs come (e.g. `selector(...)`)
  7652. //
  7653. customFuncCall: function customFuncCall(name) {
  7654. /* Ideally the table is to be moved out of here for faster perf.,
  7655. but it's quite tricky since it relies on all these `parsers`
  7656. and `expect` available only here */
  7657. return {
  7658. alpha: f(parsers.ieAlpha, true),
  7659. boolean: f(condition),
  7660. 'if': f(condition)
  7661. }[name.toLowerCase()];
  7662. function f(parse, stop) {
  7663. return {
  7664. parse,
  7665. // parsing function
  7666. stop // when true - stop after parse() and return its result,
  7667. // otherwise continue for plain args
  7668. };
  7669. }
  7670. function condition() {
  7671. return [expect(parsers.condition, 'expected condition')];
  7672. }
  7673. },
  7674. arguments: function _arguments(prevArgs) {
  7675. var argsComma = prevArgs || [];
  7676. var argsSemiColon = [];
  7677. var isSemiColonSeparated;
  7678. var value;
  7679. parserInput.save();
  7680. while (true) {
  7681. if (prevArgs) {
  7682. prevArgs = false;
  7683. } else {
  7684. value = parsers.detachedRuleset() || this.assignment() || parsers.expression();
  7685. if (!value) {
  7686. break;
  7687. }
  7688. if (value.value && value.value.length == 1) {
  7689. value = value.value[0];
  7690. }
  7691. argsComma.push(value);
  7692. }
  7693. if (parserInput.$char(',')) {
  7694. continue;
  7695. }
  7696. if (parserInput.$char(';') || isSemiColonSeparated) {
  7697. isSemiColonSeparated = true;
  7698. value = argsComma.length < 1 ? argsComma[0] : new tree.Value(argsComma);
  7699. argsSemiColon.push(value);
  7700. argsComma = [];
  7701. }
  7702. }
  7703. parserInput.forget();
  7704. return isSemiColonSeparated ? argsSemiColon : argsComma;
  7705. },
  7706. literal: function literal() {
  7707. return this.dimension() || this.color() || this.quoted() || this.unicodeDescriptor();
  7708. },
  7709. // Assignments are argument entities for calls.
  7710. // They are present in ie filter properties as shown below.
  7711. //
  7712. // filter: progid:DXImageTransform.Microsoft.Alpha( *opacity=50* )
  7713. //
  7714. assignment: function assignment() {
  7715. var key;
  7716. var value;
  7717. parserInput.save();
  7718. key = parserInput.$re(/^\w+(?=\s?=)/i);
  7719. if (!key) {
  7720. parserInput.restore();
  7721. return;
  7722. }
  7723. if (!parserInput.$char('=')) {
  7724. parserInput.restore();
  7725. return;
  7726. }
  7727. value = parsers.entity();
  7728. if (value) {
  7729. parserInput.forget();
  7730. return new tree.Assignment(key, value);
  7731. } else {
  7732. parserInput.restore();
  7733. }
  7734. },
  7735. //
  7736. // Parse url() tokens
  7737. //
  7738. // We use a specific rule for urls, because they don't really behave like
  7739. // standard function calls. The difference is that the argument doesn't have
  7740. // to be enclosed within a string, so it can't be parsed as an Expression.
  7741. //
  7742. url: function url() {
  7743. var value;
  7744. var index = parserInput.i;
  7745. parserInput.autoCommentAbsorb = false;
  7746. if (!parserInput.$str('url(')) {
  7747. parserInput.autoCommentAbsorb = true;
  7748. return;
  7749. }
  7750. value = this.quoted() || this.variable() || this.property() || parserInput.$re(/^(?:(?:\\[\(\)'"])|[^\(\)'"])+/) || '';
  7751. parserInput.autoCommentAbsorb = true;
  7752. expectChar(')');
  7753. return new tree.URL(value.value != null || value instanceof tree.Variable || value instanceof tree.Property ? value : new tree.Anonymous(value, index), index, fileInfo);
  7754. },
  7755. //
  7756. // A Variable entity, such as `@fink`, in
  7757. //
  7758. // width: @fink + 2px
  7759. //
  7760. // We use a different parser for variable definitions,
  7761. // see `parsers.variable`.
  7762. //
  7763. variable: function variable() {
  7764. var ch;
  7765. var name;
  7766. var index = parserInput.i;
  7767. parserInput.save();
  7768. if (parserInput.currentChar() === '@' && (name = parserInput.$re(/^@@?[\w-]+/))) {
  7769. ch = parserInput.currentChar();
  7770. if (ch === '(' || ch === '[' && !parserInput.prevChar().match(/^\s/)) {
  7771. // this may be a VariableCall lookup
  7772. var result = parsers.variableCall(name);
  7773. if (result) {
  7774. parserInput.forget();
  7775. return result;
  7776. }
  7777. }
  7778. parserInput.forget();
  7779. return new tree.Variable(name, index, fileInfo);
  7780. }
  7781. parserInput.restore();
  7782. },
  7783. // A variable entity using the protective {} e.g. @{var}
  7784. variableCurly: function variableCurly() {
  7785. var curly;
  7786. var index = parserInput.i;
  7787. if (parserInput.currentChar() === '@' && (curly = parserInput.$re(/^@\{([\w-]+)\}/))) {
  7788. return new tree.Variable(`@${curly[1]}`, index, fileInfo);
  7789. }
  7790. },
  7791. //
  7792. // A Property accessor, such as `$color`, in
  7793. //
  7794. // background-color: $color
  7795. //
  7796. property: function property() {
  7797. var name;
  7798. var index = parserInput.i;
  7799. if (parserInput.currentChar() === '$' && (name = parserInput.$re(/^\$[\w-]+/))) {
  7800. return new tree.Property(name, index, fileInfo);
  7801. }
  7802. },
  7803. // A property entity useing the protective {} e.g. ${prop}
  7804. propertyCurly: function propertyCurly() {
  7805. var curly;
  7806. var index = parserInput.i;
  7807. if (parserInput.currentChar() === '$' && (curly = parserInput.$re(/^\$\{([\w-]+)\}/))) {
  7808. return new tree.Property(`$${curly[1]}`, index, fileInfo);
  7809. }
  7810. },
  7811. //
  7812. // A Hexadecimal color
  7813. //
  7814. // #4F3C2F
  7815. //
  7816. // `rgb` and `hsl` colors are parsed through the `entities.call` parser.
  7817. //
  7818. color: function color() {
  7819. var rgb;
  7820. parserInput.save();
  7821. if (parserInput.currentChar() === '#' && (rgb = parserInput.$re(/^#([A-Fa-f0-9]{8}|[A-Fa-f0-9]{6}|[A-Fa-f0-9]{3,4})([\w.#\[])?/))) {
  7822. if (!rgb[2]) {
  7823. parserInput.forget();
  7824. return new tree.Color(rgb[1], undefined, rgb[0]);
  7825. }
  7826. }
  7827. parserInput.restore();
  7828. },
  7829. colorKeyword: function colorKeyword() {
  7830. parserInput.save();
  7831. var autoCommentAbsorb = parserInput.autoCommentAbsorb;
  7832. parserInput.autoCommentAbsorb = false;
  7833. var k = parserInput.$re(/^[_A-Za-z-][_A-Za-z0-9-]+/);
  7834. parserInput.autoCommentAbsorb = autoCommentAbsorb;
  7835. if (!k) {
  7836. parserInput.forget();
  7837. return;
  7838. }
  7839. parserInput.restore();
  7840. var color = tree.Color.fromKeyword(k);
  7841. if (color) {
  7842. parserInput.$str(k);
  7843. return color;
  7844. }
  7845. },
  7846. //
  7847. // A Dimension, that is, a number and a unit
  7848. //
  7849. // 0.5em 95%
  7850. //
  7851. dimension: function dimension() {
  7852. if (parserInput.peekNotNumeric()) {
  7853. return;
  7854. }
  7855. var value = parserInput.$re(/^([+-]?\d*\.?\d+)(%|[a-z_]+)?/i);
  7856. if (value) {
  7857. return new tree.Dimension(value[1], value[2]);
  7858. }
  7859. },
  7860. //
  7861. // A unicode descriptor, as is used in unicode-range
  7862. //
  7863. // U+0?? or U+00A1-00A9
  7864. //
  7865. unicodeDescriptor: function unicodeDescriptor() {
  7866. var ud;
  7867. ud = parserInput.$re(/^U\+[0-9a-fA-F?]+(\-[0-9a-fA-F?]+)?/);
  7868. if (ud) {
  7869. return new tree.UnicodeDescriptor(ud[0]);
  7870. }
  7871. },
  7872. //
  7873. // JavaScript code to be evaluated
  7874. //
  7875. // `window.location.href`
  7876. //
  7877. javascript: function javascript() {
  7878. var js;
  7879. var index = parserInput.i;
  7880. parserInput.save();
  7881. var escape = parserInput.$char('~');
  7882. var jsQuote = parserInput.$char('`');
  7883. if (!jsQuote) {
  7884. parserInput.restore();
  7885. return;
  7886. }
  7887. js = parserInput.$re(/^[^`]*`/);
  7888. if (js) {
  7889. parserInput.forget();
  7890. return new tree.JavaScript(js.substr(0, js.length - 1), Boolean(escape), index, fileInfo);
  7891. }
  7892. parserInput.restore('invalid javascript definition');
  7893. }
  7894. },
  7895. //
  7896. // The variable part of a variable definition. Used in the `rule` parser
  7897. //
  7898. // @fink:
  7899. //
  7900. variable: function variable() {
  7901. var name;
  7902. if (parserInput.currentChar() === '@' && (name = parserInput.$re(/^(@[\w-]+)\s*:/))) {
  7903. return name[1];
  7904. }
  7905. },
  7906. //
  7907. // Call a variable value to retrieve a detached ruleset
  7908. // or a value from a detached ruleset's rules.
  7909. //
  7910. // @fink();
  7911. // @fink;
  7912. // color: @fink[@color];
  7913. //
  7914. variableCall: function variableCall(parsedName) {
  7915. var lookups;
  7916. var important;
  7917. var i = parserInput.i;
  7918. var inValue = !!parsedName;
  7919. var name = parsedName;
  7920. parserInput.save();
  7921. if (name || parserInput.currentChar() === '@' && (name = parserInput.$re(/^(@[\w-]+)(\(\s*\))?/))) {
  7922. lookups = this.mixin.ruleLookups();
  7923. if (!lookups && (inValue && parserInput.$str('()') !== '()' || name[2] !== '()')) {
  7924. parserInput.restore('Missing \'[...]\' lookup in variable call');
  7925. return;
  7926. }
  7927. if (!inValue) {
  7928. name = name[1];
  7929. }
  7930. if (lookups && parsers.important()) {
  7931. important = true;
  7932. }
  7933. var call = new tree.VariableCall(name, i, fileInfo);
  7934. if (!inValue && parsers.end()) {
  7935. parserInput.forget();
  7936. return call;
  7937. } else {
  7938. parserInput.forget();
  7939. return new tree.NamespaceValue(call, lookups, important, i, fileInfo);
  7940. }
  7941. }
  7942. parserInput.restore();
  7943. },
  7944. //
  7945. // extend syntax - used to extend selectors
  7946. //
  7947. extend: function extend(isRule) {
  7948. var elements;
  7949. var e;
  7950. var index = parserInput.i;
  7951. var option;
  7952. var extendList;
  7953. var extend;
  7954. if (!parserInput.$str(isRule ? '&:extend(' : ':extend(')) {
  7955. return;
  7956. }
  7957. do {
  7958. option = null;
  7959. elements = null;
  7960. while (!(option = parserInput.$re(/^(all)(?=\s*(\)|,))/))) {
  7961. e = this.element();
  7962. if (!e) {
  7963. break;
  7964. }
  7965. if (elements) {
  7966. elements.push(e);
  7967. } else {
  7968. elements = [e];
  7969. }
  7970. }
  7971. option = option && option[1];
  7972. if (!elements) {
  7973. error('Missing target selector for :extend().');
  7974. }
  7975. extend = new tree.Extend(new tree.Selector(elements), option, index, fileInfo);
  7976. if (extendList) {
  7977. extendList.push(extend);
  7978. } else {
  7979. extendList = [extend];
  7980. }
  7981. } while (parserInput.$char(','));
  7982. expect(/^\)/);
  7983. if (isRule) {
  7984. expect(/^;/);
  7985. }
  7986. return extendList;
  7987. },
  7988. //
  7989. // extendRule - used in a rule to extend all the parent selectors
  7990. //
  7991. extendRule: function extendRule() {
  7992. return this.extend(true);
  7993. },
  7994. //
  7995. // Mixins
  7996. //
  7997. mixin: {
  7998. //
  7999. // A Mixin call, with an optional argument list
  8000. //
  8001. // #mixins > .square(#fff);
  8002. // #mixins.square(#fff);
  8003. // .rounded(4px, black);
  8004. // .button;
  8005. //
  8006. // We can lookup / return a value using the lookup syntax:
  8007. //
  8008. // color: #mixin.square(#fff)[@color];
  8009. //
  8010. // The `while` loop is there because mixins can be
  8011. // namespaced, but we only support the child and descendant
  8012. // selector for now.
  8013. //
  8014. call: function call(inValue, getLookup) {
  8015. var s = parserInput.currentChar();
  8016. var important = false;
  8017. var lookups;
  8018. var index = parserInput.i;
  8019. var elements;
  8020. var args;
  8021. var hasParens;
  8022. if (s !== '.' && s !== '#') {
  8023. return;
  8024. }
  8025. parserInput.save(); // stop us absorbing part of an invalid selector
  8026. elements = this.elements();
  8027. if (elements) {
  8028. if (parserInput.$char('(')) {
  8029. args = this.args(true).args;
  8030. expectChar(')');
  8031. hasParens = true;
  8032. }
  8033. if (getLookup !== false) {
  8034. lookups = this.ruleLookups();
  8035. }
  8036. if (getLookup === true && !lookups) {
  8037. parserInput.restore();
  8038. return;
  8039. }
  8040. if (inValue && !lookups && !hasParens) {
  8041. // This isn't a valid in-value mixin call
  8042. parserInput.restore();
  8043. return;
  8044. }
  8045. if (!inValue && parsers.important()) {
  8046. important = true;
  8047. }
  8048. if (inValue || parsers.end()) {
  8049. parserInput.forget();
  8050. var mixin = new tree.mixin.Call(elements, args, index, fileInfo, !lookups && important);
  8051. if (lookups) {
  8052. return new tree.NamespaceValue(mixin, lookups, important);
  8053. } else {
  8054. return mixin;
  8055. }
  8056. }
  8057. }
  8058. parserInput.restore();
  8059. },
  8060. /**
  8061. * Matching elements for mixins
  8062. * (Start with . or # and can have > )
  8063. */
  8064. elements: function elements() {
  8065. var elements;
  8066. var e;
  8067. var c;
  8068. var elem;
  8069. var elemIndex;
  8070. var re = /^[#.](?:[\w-]|\\(?:[A-Fa-f0-9]{1,6} ?|[^A-Fa-f0-9]))+/;
  8071. while (true) {
  8072. elemIndex = parserInput.i;
  8073. e = parserInput.$re(re);
  8074. if (!e) {
  8075. break;
  8076. }
  8077. elem = new tree.Element(c, e, false, elemIndex, fileInfo);
  8078. if (elements) {
  8079. elements.push(elem);
  8080. } else {
  8081. elements = [elem];
  8082. }
  8083. c = parserInput.$char('>');
  8084. }
  8085. return elements;
  8086. },
  8087. args: function args(isCall) {
  8088. var entities = parsers.entities;
  8089. var returner = {
  8090. args: null,
  8091. variadic: false
  8092. };
  8093. var expressions = [];
  8094. var argsSemiColon = [];
  8095. var argsComma = [];
  8096. var isSemiColonSeparated;
  8097. var expressionContainsNamed;
  8098. var name;
  8099. var nameLoop;
  8100. var value;
  8101. var arg;
  8102. var expand;
  8103. var hasSep = true;
  8104. parserInput.save();
  8105. while (true) {
  8106. if (isCall) {
  8107. arg = parsers.detachedRuleset() || parsers.expression();
  8108. } else {
  8109. parserInput.commentStore.length = 0;
  8110. if (parserInput.$str('...')) {
  8111. returner.variadic = true;
  8112. if (parserInput.$char(';') && !isSemiColonSeparated) {
  8113. isSemiColonSeparated = true;
  8114. }
  8115. (isSemiColonSeparated ? argsSemiColon : argsComma).push({
  8116. variadic: true
  8117. });
  8118. break;
  8119. }
  8120. arg = entities.variable() || entities.property() || entities.literal() || entities.keyword() || this.call(true);
  8121. }
  8122. if (!arg || !hasSep) {
  8123. break;
  8124. }
  8125. nameLoop = null;
  8126. if (arg.throwAwayComments) {
  8127. arg.throwAwayComments();
  8128. }
  8129. value = arg;
  8130. var val = null;
  8131. if (isCall) {
  8132. // Variable
  8133. if (arg.value && arg.value.length == 1) {
  8134. val = arg.value[0];
  8135. }
  8136. } else {
  8137. val = arg;
  8138. }
  8139. if (val && (val instanceof tree.Variable || val instanceof tree.Property)) {
  8140. if (parserInput.$char(':')) {
  8141. if (expressions.length > 0) {
  8142. if (isSemiColonSeparated) {
  8143. error('Cannot mix ; and , as delimiter types');
  8144. }
  8145. expressionContainsNamed = true;
  8146. }
  8147. value = parsers.detachedRuleset() || parsers.expression();
  8148. if (!value) {
  8149. if (isCall) {
  8150. error('could not understand value for named argument');
  8151. } else {
  8152. parserInput.restore();
  8153. returner.args = [];
  8154. return returner;
  8155. }
  8156. }
  8157. nameLoop = name = val.name;
  8158. } else if (parserInput.$str('...')) {
  8159. if (!isCall) {
  8160. returner.variadic = true;
  8161. if (parserInput.$char(';') && !isSemiColonSeparated) {
  8162. isSemiColonSeparated = true;
  8163. }
  8164. (isSemiColonSeparated ? argsSemiColon : argsComma).push({
  8165. name: arg.name,
  8166. variadic: true
  8167. });
  8168. break;
  8169. } else {
  8170. expand = true;
  8171. }
  8172. } else if (!isCall) {
  8173. name = nameLoop = val.name;
  8174. value = null;
  8175. }
  8176. }
  8177. if (value) {
  8178. expressions.push(value);
  8179. }
  8180. argsComma.push({
  8181. name: nameLoop,
  8182. value,
  8183. expand
  8184. });
  8185. if (parserInput.$char(',')) {
  8186. hasSep = true;
  8187. continue;
  8188. }
  8189. hasSep = parserInput.$char(';') === ';';
  8190. if (hasSep || isSemiColonSeparated) {
  8191. if (expressionContainsNamed) {
  8192. error('Cannot mix ; and , as delimiter types');
  8193. }
  8194. isSemiColonSeparated = true;
  8195. if (expressions.length > 1) {
  8196. value = new tree.Value(expressions);
  8197. }
  8198. argsSemiColon.push({
  8199. name,
  8200. value,
  8201. expand
  8202. });
  8203. name = null;
  8204. expressions = [];
  8205. expressionContainsNamed = false;
  8206. }
  8207. }
  8208. parserInput.forget();
  8209. returner.args = isSemiColonSeparated ? argsSemiColon : argsComma;
  8210. return returner;
  8211. },
  8212. //
  8213. // A Mixin definition, with a list of parameters
  8214. //
  8215. // .rounded (@radius: 2px, @color) {
  8216. // ...
  8217. // }
  8218. //
  8219. // Until we have a finer grained state-machine, we have to
  8220. // do a look-ahead, to make sure we don't have a mixin call.
  8221. // See the `rule` function for more information.
  8222. //
  8223. // We start by matching `.rounded (`, and then proceed on to
  8224. // the argument list, which has optional default values.
  8225. // We store the parameters in `params`, with a `value` key,
  8226. // if there is a value, such as in the case of `@radius`.
  8227. //
  8228. // Once we've got our params list, and a closing `)`, we parse
  8229. // the `{...}` block.
  8230. //
  8231. definition: function definition() {
  8232. var name;
  8233. var params = [];
  8234. var match;
  8235. var ruleset;
  8236. var cond;
  8237. var variadic = false;
  8238. if (parserInput.currentChar() !== '.' && parserInput.currentChar() !== '#' || parserInput.peek(/^[^{]*\}/)) {
  8239. return;
  8240. }
  8241. parserInput.save();
  8242. match = parserInput.$re(/^([#.](?:[\w-]|\\(?:[A-Fa-f0-9]{1,6} ?|[^A-Fa-f0-9]))+)\s*\(/);
  8243. if (match) {
  8244. name = match[1];
  8245. var argInfo = this.args(false);
  8246. params = argInfo.args;
  8247. variadic = argInfo.variadic; // .mixincall("@{a}");
  8248. // looks a bit like a mixin definition..
  8249. // also
  8250. // .mixincall(@a: {rule: set;});
  8251. // so we have to be nice and restore
  8252. if (!parserInput.$char(')')) {
  8253. parserInput.restore('Missing closing \')\'');
  8254. return;
  8255. }
  8256. parserInput.commentStore.length = 0;
  8257. if (parserInput.$str('when')) {
  8258. // Guard
  8259. cond = expect(parsers.conditions, 'expected condition');
  8260. }
  8261. ruleset = parsers.block();
  8262. if (ruleset) {
  8263. parserInput.forget();
  8264. return new tree.mixin.Definition(name, params, ruleset, cond, variadic);
  8265. } else {
  8266. parserInput.restore();
  8267. }
  8268. } else {
  8269. parserInput.forget();
  8270. }
  8271. },
  8272. ruleLookups: function ruleLookups() {
  8273. var rule;
  8274. var lookups = [];
  8275. if (parserInput.currentChar() !== '[') {
  8276. return;
  8277. }
  8278. while (true) {
  8279. parserInput.save();
  8280. rule = this.lookupValue();
  8281. if (!rule && rule !== '') {
  8282. parserInput.restore();
  8283. break;
  8284. }
  8285. lookups.push(rule);
  8286. parserInput.forget();
  8287. }
  8288. if (lookups.length > 0) {
  8289. return lookups;
  8290. }
  8291. },
  8292. lookupValue: function lookupValue() {
  8293. parserInput.save();
  8294. if (!parserInput.$char('[')) {
  8295. parserInput.restore();
  8296. return;
  8297. }
  8298. var name = parserInput.$re(/^(?:[@$]{0,2})[_a-zA-Z0-9-]*/);
  8299. if (!parserInput.$char(']')) {
  8300. parserInput.restore();
  8301. return;
  8302. }
  8303. if (name || name === '') {
  8304. parserInput.forget();
  8305. return name;
  8306. }
  8307. parserInput.restore();
  8308. }
  8309. },
  8310. //
  8311. // Entities are the smallest recognized token,
  8312. // and can be found inside a rule's value.
  8313. //
  8314. entity: function entity() {
  8315. var entities = this.entities;
  8316. return this.comment() || entities.literal() || entities.variable() || entities.url() || entities.property() || entities.call() || entities.keyword() || this.mixin.call(true) || entities.javascript();
  8317. },
  8318. //
  8319. // A Declaration terminator. Note that we use `peek()` to check for '}',
  8320. // because the `block` rule will be expecting it, but we still need to make sure
  8321. // it's there, if ';' was omitted.
  8322. //
  8323. end: function end() {
  8324. return parserInput.$char(';') || parserInput.peek('}');
  8325. },
  8326. //
  8327. // IE's alpha function
  8328. //
  8329. // alpha(opacity=88)
  8330. //
  8331. ieAlpha: function ieAlpha() {
  8332. var value; // http://jsperf.com/case-insensitive-regex-vs-strtolower-then-regex/18
  8333. if (!parserInput.$re(/^opacity=/i)) {
  8334. return;
  8335. }
  8336. value = parserInput.$re(/^\d+/);
  8337. if (!value) {
  8338. value = expect(parsers.entities.variable, 'Could not parse alpha');
  8339. value = `@{${value.name.slice(1)}}`;
  8340. }
  8341. expectChar(')');
  8342. return new tree.Quoted('', `alpha(opacity=${value})`);
  8343. },
  8344. //
  8345. // A Selector Element
  8346. //
  8347. // div
  8348. // + h1
  8349. // #socks
  8350. // input[type="text"]
  8351. //
  8352. // Elements are the building blocks for Selectors,
  8353. // they are made out of a `Combinator` (see combinator rule),
  8354. // and an element name, such as a tag a class, or `*`.
  8355. //
  8356. element: function element() {
  8357. var e;
  8358. var c;
  8359. var v;
  8360. var index = parserInput.i;
  8361. c = this.combinator();
  8362. e = parserInput.$re(/^(?:\d+\.\d+|\d+)%/) || parserInput.$re(/^(?:[.#]?|:*)(?:[\w-]|[^\x00-\x9f]|\\(?:[A-Fa-f0-9]{1,6} ?|[^A-Fa-f0-9]))+/) || parserInput.$char('*') || parserInput.$char('&') || this.attribute() || parserInput.$re(/^\([^&()@]+\)/) || parserInput.$re(/^[\.#:](?=@)/) || this.entities.variableCurly();
  8363. if (!e) {
  8364. parserInput.save();
  8365. if (parserInput.$char('(')) {
  8366. if ((v = this.selector(false)) && parserInput.$char(')')) {
  8367. e = new tree.Paren(v);
  8368. parserInput.forget();
  8369. } else {
  8370. parserInput.restore('Missing closing \')\'');
  8371. }
  8372. } else {
  8373. parserInput.forget();
  8374. }
  8375. }
  8376. if (e) {
  8377. return new tree.Element(c, e, e instanceof tree.Variable, index, fileInfo);
  8378. }
  8379. },
  8380. //
  8381. // Combinators combine elements together, in a Selector.
  8382. //
  8383. // Because our parser isn't white-space sensitive, special care
  8384. // has to be taken, when parsing the descendant combinator, ` `,
  8385. // as it's an empty space. We have to check the previous character
  8386. // in the input, to see if it's a ` ` character. More info on how
  8387. // we deal with this in *combinator.js*.
  8388. //
  8389. combinator: function combinator() {
  8390. var c = parserInput.currentChar();
  8391. if (c === '/') {
  8392. parserInput.save();
  8393. var slashedCombinator = parserInput.$re(/^\/[a-z]+\//i);
  8394. if (slashedCombinator) {
  8395. parserInput.forget();
  8396. return new tree.Combinator(slashedCombinator);
  8397. }
  8398. parserInput.restore();
  8399. }
  8400. if (c === '>' || c === '+' || c === '~' || c === '|' || c === '^') {
  8401. parserInput.i++;
  8402. if (c === '^' && parserInput.currentChar() === '^') {
  8403. c = '^^';
  8404. parserInput.i++;
  8405. }
  8406. while (parserInput.isWhitespace()) {
  8407. parserInput.i++;
  8408. }
  8409. return new tree.Combinator(c);
  8410. } else if (parserInput.isWhitespace(-1)) {
  8411. return new tree.Combinator(' ');
  8412. } else {
  8413. return new tree.Combinator(null);
  8414. }
  8415. },
  8416. //
  8417. // A CSS Selector
  8418. // with less extensions e.g. the ability to extend and guard
  8419. //
  8420. // .class > div + h1
  8421. // li a:hover
  8422. //
  8423. // Selectors are made out of one or more Elements, see above.
  8424. //
  8425. selector: function selector(isLess) {
  8426. var index = parserInput.i;
  8427. var elements;
  8428. var extendList;
  8429. var c;
  8430. var e;
  8431. var allExtends;
  8432. var when;
  8433. var condition;
  8434. isLess = isLess !== false;
  8435. while (isLess && (extendList = this.extend()) || isLess && (when = parserInput.$str('when')) || (e = this.element())) {
  8436. if (when) {
  8437. condition = expect(this.conditions, 'expected condition');
  8438. } else if (condition) {
  8439. error('CSS guard can only be used at the end of selector');
  8440. } else if (extendList) {
  8441. if (allExtends) {
  8442. allExtends = allExtends.concat(extendList);
  8443. } else {
  8444. allExtends = extendList;
  8445. }
  8446. } else {
  8447. if (allExtends) {
  8448. error('Extend can only be used at the end of selector');
  8449. }
  8450. c = parserInput.currentChar();
  8451. if (elements) {
  8452. elements.push(e);
  8453. } else {
  8454. elements = [e];
  8455. }
  8456. e = null;
  8457. }
  8458. if (c === '{' || c === '}' || c === ';' || c === ',' || c === ')') {
  8459. break;
  8460. }
  8461. }
  8462. if (elements) {
  8463. return new tree.Selector(elements, allExtends, condition, index, fileInfo);
  8464. }
  8465. if (allExtends) {
  8466. error('Extend must be used to extend a selector, it cannot be used on its own');
  8467. }
  8468. },
  8469. selectors: function selectors() {
  8470. var s;
  8471. var selectors;
  8472. while (true) {
  8473. s = this.selector();
  8474. if (!s) {
  8475. break;
  8476. }
  8477. if (selectors) {
  8478. selectors.push(s);
  8479. } else {
  8480. selectors = [s];
  8481. }
  8482. parserInput.commentStore.length = 0;
  8483. if (s.condition && selectors.length > 1) {
  8484. error("Guards are only currently allowed on a single selector.");
  8485. }
  8486. if (!parserInput.$char(',')) {
  8487. break;
  8488. }
  8489. if (s.condition) {
  8490. error("Guards are only currently allowed on a single selector.");
  8491. }
  8492. parserInput.commentStore.length = 0;
  8493. }
  8494. return selectors;
  8495. },
  8496. attribute: function attribute() {
  8497. if (!parserInput.$char('[')) {
  8498. return;
  8499. }
  8500. var entities = this.entities;
  8501. var key;
  8502. var val;
  8503. var op;
  8504. if (!(key = entities.variableCurly())) {
  8505. key = expect(/^(?:[_A-Za-z0-9-\*]*\|)?(?:[_A-Za-z0-9-]|\\.)+/);
  8506. }
  8507. op = parserInput.$re(/^[|~*$^]?=/);
  8508. if (op) {
  8509. val = entities.quoted() || parserInput.$re(/^[0-9]+%/) || parserInput.$re(/^[\w-]+/) || entities.variableCurly();
  8510. }
  8511. expectChar(']');
  8512. return new tree.Attribute(key, op, val);
  8513. },
  8514. //
  8515. // The `block` rule is used by `ruleset` and `mixin.definition`.
  8516. // It's a wrapper around the `primary` rule, with added `{}`.
  8517. //
  8518. block: function block() {
  8519. var content;
  8520. if (parserInput.$char('{') && (content = this.primary()) && parserInput.$char('}')) {
  8521. return content;
  8522. }
  8523. },
  8524. blockRuleset: function blockRuleset() {
  8525. var block = this.block();
  8526. if (block) {
  8527. block = new tree.Ruleset(null, block);
  8528. }
  8529. return block;
  8530. },
  8531. detachedRuleset: function detachedRuleset() {
  8532. var argInfo;
  8533. var params;
  8534. var variadic;
  8535. parserInput.save();
  8536. if (parserInput.$re(/^[.#]\(/)) {
  8537. /**
  8538. * DR args currently only implemented for each() function, and not
  8539. * yet settable as `@dr: #(@arg) {}`
  8540. * This should be done when DRs are merged with mixins.
  8541. * See: https://github.com/less/less-meta/issues/16
  8542. */
  8543. argInfo = this.mixin.args(false);
  8544. params = argInfo.args;
  8545. variadic = argInfo.variadic;
  8546. if (!parserInput.$char(')')) {
  8547. parserInput.restore();
  8548. return;
  8549. }
  8550. }
  8551. var blockRuleset = this.blockRuleset();
  8552. if (blockRuleset) {
  8553. parserInput.forget();
  8554. if (params) {
  8555. return new tree.mixin.Definition(null, params, blockRuleset, null, variadic);
  8556. }
  8557. return new tree.DetachedRuleset(blockRuleset);
  8558. }
  8559. parserInput.restore();
  8560. },
  8561. //
  8562. // div, .class, body > p {...}
  8563. //
  8564. ruleset: function ruleset() {
  8565. var selectors;
  8566. var rules;
  8567. var debugInfo;
  8568. parserInput.save();
  8569. if (context.dumpLineNumbers) {
  8570. debugInfo = getDebugInfo(parserInput.i);
  8571. }
  8572. selectors = this.selectors();
  8573. if (selectors && (rules = this.block())) {
  8574. parserInput.forget();
  8575. var ruleset = new tree.Ruleset(selectors, rules, context.strictImports);
  8576. if (context.dumpLineNumbers) {
  8577. ruleset.debugInfo = debugInfo;
  8578. }
  8579. return ruleset;
  8580. } else {
  8581. parserInput.restore();
  8582. }
  8583. },
  8584. declaration: function declaration() {
  8585. var name;
  8586. var value;
  8587. var index = parserInput.i;
  8588. var hasDR;
  8589. var c = parserInput.currentChar();
  8590. var important;
  8591. var merge;
  8592. var isVariable;
  8593. if (c === '.' || c === '#' || c === '&' || c === ':') {
  8594. return;
  8595. }
  8596. parserInput.save();
  8597. name = this.variable() || this.ruleProperty();
  8598. if (name) {
  8599. isVariable = typeof name === 'string';
  8600. if (isVariable) {
  8601. value = this.detachedRuleset();
  8602. if (value) {
  8603. hasDR = true;
  8604. }
  8605. }
  8606. parserInput.commentStore.length = 0;
  8607. if (!value) {
  8608. // a name returned by this.ruleProperty() is always an array of the form:
  8609. // [string-1, ..., string-n, ""] or [string-1, ..., string-n, "+"]
  8610. // where each item is a tree.Keyword or tree.Variable
  8611. merge = !isVariable && name.length > 1 && name.pop().value; // Custom property values get permissive parsing
  8612. if (name[0].value && name[0].value.slice(0, 2) === '--') {
  8613. value = this.permissiveValue();
  8614. } // Try to store values as anonymous
  8615. // If we need the value later we'll re-parse it in ruleset.parseValue
  8616. else {
  8617. value = this.anonymousValue();
  8618. }
  8619. if (value) {
  8620. parserInput.forget(); // anonymous values absorb the end ';' which is required for them to work
  8621. return new tree.Declaration(name, value, false, merge, index, fileInfo);
  8622. }
  8623. if (!value) {
  8624. value = this.value();
  8625. }
  8626. if (value) {
  8627. important = this.important();
  8628. } else if (isVariable) {
  8629. // As a last resort, try permissiveValue
  8630. value = this.permissiveValue();
  8631. }
  8632. }
  8633. if (value && (this.end() || hasDR)) {
  8634. parserInput.forget();
  8635. return new tree.Declaration(name, value, important, merge, index, fileInfo);
  8636. } else {
  8637. parserInput.restore();
  8638. }
  8639. } else {
  8640. parserInput.restore();
  8641. }
  8642. },
  8643. anonymousValue: function anonymousValue() {
  8644. var index = parserInput.i;
  8645. var match = parserInput.$re(/^([^.#@\$+\/'"*`(;{}-]*);/);
  8646. if (match) {
  8647. return new tree.Anonymous(match[1], index);
  8648. }
  8649. },
  8650. /**
  8651. * Used for custom properties, at-rules, and variables (as fallback)
  8652. * Parses almost anything inside of {} [] () "" blocks
  8653. * until it reaches outer-most tokens.
  8654. *
  8655. * First, it will try to parse comments and entities to reach
  8656. * the end. This is mostly like the Expression parser except no
  8657. * math is allowed.
  8658. */
  8659. permissiveValue: function permissiveValue(untilTokens) {
  8660. var i;
  8661. var e;
  8662. var done;
  8663. var value;
  8664. var tok = untilTokens || ';';
  8665. var index = parserInput.i;
  8666. var result = [];
  8667. function testCurrentChar() {
  8668. var char = parserInput.currentChar();
  8669. if (typeof tok === 'string') {
  8670. return char === tok;
  8671. } else {
  8672. return tok.test(char);
  8673. }
  8674. }
  8675. if (testCurrentChar()) {
  8676. return;
  8677. }
  8678. value = [];
  8679. do {
  8680. e = this.comment();
  8681. if (e) {
  8682. value.push(e);
  8683. continue;
  8684. }
  8685. e = this.entity();
  8686. if (e) {
  8687. value.push(e);
  8688. }
  8689. } while (e);
  8690. done = testCurrentChar();
  8691. if (value.length > 0) {
  8692. value = new tree.Expression(value);
  8693. if (done) {
  8694. return value;
  8695. } else {
  8696. result.push(value);
  8697. } // Preserve space before $parseUntil as it will not
  8698. if (parserInput.prevChar() === ' ') {
  8699. result.push(new tree.Anonymous(' ', index));
  8700. }
  8701. }
  8702. parserInput.save();
  8703. value = parserInput.$parseUntil(tok);
  8704. if (value) {
  8705. if (typeof value === 'string') {
  8706. error(`Expected '${value}'`, 'Parse');
  8707. }
  8708. if (value.length === 1 && value[0] === ' ') {
  8709. parserInput.forget();
  8710. return new tree.Anonymous('', index);
  8711. }
  8712. var item;
  8713. for (i = 0; i < value.length; i++) {
  8714. item = value[i];
  8715. if (Array.isArray(item)) {
  8716. // Treat actual quotes as normal quoted values
  8717. result.push(new tree.Quoted(item[0], item[1], true, index, fileInfo));
  8718. } else {
  8719. if (i === value.length - 1) {
  8720. item = item.trim();
  8721. } // Treat like quoted values, but replace vars like unquoted expressions
  8722. var quote = new tree.Quoted('\'', item, true, index, fileInfo);
  8723. quote.variableRegex = /@([\w-]+)/g;
  8724. quote.propRegex = /\$([\w-]+)/g;
  8725. result.push(quote);
  8726. }
  8727. }
  8728. parserInput.forget();
  8729. return new tree.Expression(result, true);
  8730. }
  8731. parserInput.restore();
  8732. },
  8733. //
  8734. // An @import atrule
  8735. //
  8736. // @import "lib";
  8737. //
  8738. // Depending on our environment, importing is done differently:
  8739. // In the browser, it's an XHR request, in Node, it would be a
  8740. // file-system operation. The function used for importing is
  8741. // stored in `import`, which we pass to the Import constructor.
  8742. //
  8743. 'import': function _import() {
  8744. var path;
  8745. var features;
  8746. var index = parserInput.i;
  8747. var dir = parserInput.$re(/^@import?\s+/);
  8748. if (dir) {
  8749. var options = (dir ? this.importOptions() : null) || {};
  8750. if (path = this.entities.quoted() || this.entities.url()) {
  8751. features = this.mediaFeatures();
  8752. if (!parserInput.$char(';')) {
  8753. parserInput.i = index;
  8754. error('missing semi-colon or unrecognised media features on import');
  8755. }
  8756. features = features && new tree.Value(features);
  8757. return new tree.Import(path, features, options, index, fileInfo);
  8758. } else {
  8759. parserInput.i = index;
  8760. error('malformed import statement');
  8761. }
  8762. }
  8763. },
  8764. importOptions: function importOptions() {
  8765. var o;
  8766. var options = {};
  8767. var optionName;
  8768. var value; // list of options, surrounded by parens
  8769. if (!parserInput.$char('(')) {
  8770. return null;
  8771. }
  8772. do {
  8773. o = this.importOption();
  8774. if (o) {
  8775. optionName = o;
  8776. value = true;
  8777. switch (optionName) {
  8778. case 'css':
  8779. optionName = 'less';
  8780. value = false;
  8781. break;
  8782. case 'once':
  8783. optionName = 'multiple';
  8784. value = false;
  8785. break;
  8786. }
  8787. options[optionName] = value;
  8788. if (!parserInput.$char(',')) {
  8789. break;
  8790. }
  8791. }
  8792. } while (o);
  8793. expectChar(')');
  8794. return options;
  8795. },
  8796. importOption: function importOption() {
  8797. var opt = parserInput.$re(/^(less|css|multiple|once|inline|reference|optional)/);
  8798. if (opt) {
  8799. return opt[1];
  8800. }
  8801. },
  8802. mediaFeature: function mediaFeature() {
  8803. var entities = this.entities;
  8804. var nodes = [];
  8805. var e;
  8806. var p;
  8807. parserInput.save();
  8808. do {
  8809. e = entities.keyword() || entities.variable() || entities.mixinLookup();
  8810. if (e) {
  8811. nodes.push(e);
  8812. } else if (parserInput.$char('(')) {
  8813. p = this.property();
  8814. e = this.value();
  8815. if (parserInput.$char(')')) {
  8816. if (p && e) {
  8817. nodes.push(new tree.Paren(new tree.Declaration(p, e, null, null, parserInput.i, fileInfo, true)));
  8818. } else if (e) {
  8819. nodes.push(new tree.Paren(e));
  8820. } else {
  8821. error('badly formed media feature definition');
  8822. }
  8823. } else {
  8824. error('Missing closing \')\'', 'Parse');
  8825. }
  8826. }
  8827. } while (e);
  8828. parserInput.forget();
  8829. if (nodes.length > 0) {
  8830. return new tree.Expression(nodes);
  8831. }
  8832. },
  8833. mediaFeatures: function mediaFeatures() {
  8834. var entities = this.entities;
  8835. var features = [];
  8836. var e;
  8837. do {
  8838. e = this.mediaFeature();
  8839. if (e) {
  8840. features.push(e);
  8841. if (!parserInput.$char(',')) {
  8842. break;
  8843. }
  8844. } else {
  8845. e = entities.variable() || entities.mixinLookup();
  8846. if (e) {
  8847. features.push(e);
  8848. if (!parserInput.$char(',')) {
  8849. break;
  8850. }
  8851. }
  8852. }
  8853. } while (e);
  8854. return features.length > 0 ? features : null;
  8855. },
  8856. media: function media() {
  8857. var features;
  8858. var rules;
  8859. var media;
  8860. var debugInfo;
  8861. var index = parserInput.i;
  8862. if (context.dumpLineNumbers) {
  8863. debugInfo = getDebugInfo(index);
  8864. }
  8865. parserInput.save();
  8866. if (parserInput.$str('@media')) {
  8867. features = this.mediaFeatures();
  8868. rules = this.block();
  8869. if (!rules) {
  8870. error('media definitions require block statements after any features');
  8871. }
  8872. parserInput.forget();
  8873. media = new tree.Media(rules, features, index, fileInfo);
  8874. if (context.dumpLineNumbers) {
  8875. media.debugInfo = debugInfo;
  8876. }
  8877. return media;
  8878. }
  8879. parserInput.restore();
  8880. },
  8881. //
  8882. // A @plugin directive, used to import plugins dynamically.
  8883. //
  8884. // @plugin (args) "lib";
  8885. //
  8886. plugin: function plugin() {
  8887. var path;
  8888. var args;
  8889. var options;
  8890. var index = parserInput.i;
  8891. var dir = parserInput.$re(/^@plugin?\s+/);
  8892. if (dir) {
  8893. args = this.pluginArgs();
  8894. if (args) {
  8895. options = {
  8896. pluginArgs: args,
  8897. isPlugin: true
  8898. };
  8899. } else {
  8900. options = {
  8901. isPlugin: true
  8902. };
  8903. }
  8904. if (path = this.entities.quoted() || this.entities.url()) {
  8905. if (!parserInput.$char(';')) {
  8906. parserInput.i = index;
  8907. error('missing semi-colon on @plugin');
  8908. }
  8909. return new tree.Import(path, null, options, index, fileInfo);
  8910. } else {
  8911. parserInput.i = index;
  8912. error('malformed @plugin statement');
  8913. }
  8914. }
  8915. },
  8916. pluginArgs: function pluginArgs() {
  8917. // list of options, surrounded by parens
  8918. parserInput.save();
  8919. if (!parserInput.$char('(')) {
  8920. parserInput.restore();
  8921. return null;
  8922. }
  8923. var args = parserInput.$re(/^\s*([^\);]+)\)\s*/);
  8924. if (args[1]) {
  8925. parserInput.forget();
  8926. return args[1].trim();
  8927. } else {
  8928. parserInput.restore();
  8929. return null;
  8930. }
  8931. },
  8932. //
  8933. // A CSS AtRule
  8934. //
  8935. // @charset "utf-8";
  8936. //
  8937. atrule: function atrule() {
  8938. var index = parserInput.i;
  8939. var name;
  8940. var value;
  8941. var rules;
  8942. var nonVendorSpecificName;
  8943. var hasIdentifier;
  8944. var hasExpression;
  8945. var hasUnknown;
  8946. var hasBlock = true;
  8947. var isRooted = true;
  8948. if (parserInput.currentChar() !== '@') {
  8949. return;
  8950. }
  8951. value = this['import']() || this.plugin() || this.media();
  8952. if (value) {
  8953. return value;
  8954. }
  8955. parserInput.save();
  8956. name = parserInput.$re(/^@[a-z-]+/);
  8957. if (!name) {
  8958. return;
  8959. }
  8960. nonVendorSpecificName = name;
  8961. if (name.charAt(1) == '-' && name.indexOf('-', 2) > 0) {
  8962. nonVendorSpecificName = `@${name.slice(name.indexOf('-', 2) + 1)}`;
  8963. }
  8964. switch (nonVendorSpecificName) {
  8965. case '@charset':
  8966. hasIdentifier = true;
  8967. hasBlock = false;
  8968. break;
  8969. case '@namespace':
  8970. hasExpression = true;
  8971. hasBlock = false;
  8972. break;
  8973. case '@keyframes':
  8974. case '@counter-style':
  8975. hasIdentifier = true;
  8976. break;
  8977. case '@document':
  8978. case '@supports':
  8979. hasUnknown = true;
  8980. isRooted = false;
  8981. break;
  8982. default:
  8983. hasUnknown = true;
  8984. break;
  8985. }
  8986. parserInput.commentStore.length = 0;
  8987. if (hasIdentifier) {
  8988. value = this.entity();
  8989. if (!value) {
  8990. error(`expected ${name} identifier`);
  8991. }
  8992. } else if (hasExpression) {
  8993. value = this.expression();
  8994. if (!value) {
  8995. error(`expected ${name} expression`);
  8996. }
  8997. } else if (hasUnknown) {
  8998. value = this.permissiveValue(/^[{;]/);
  8999. hasBlock = parserInput.currentChar() === '{';
  9000. if (!value) {
  9001. if (!hasBlock && parserInput.currentChar() !== ';') {
  9002. error(`${name} rule is missing block or ending semi-colon`);
  9003. }
  9004. } else if (!value.value) {
  9005. value = null;
  9006. }
  9007. }
  9008. if (hasBlock) {
  9009. rules = this.blockRuleset();
  9010. }
  9011. if (rules || !hasBlock && value && parserInput.$char(';')) {
  9012. parserInput.forget();
  9013. return new tree.AtRule(name, value, rules, index, fileInfo, context.dumpLineNumbers ? getDebugInfo(index) : null, isRooted);
  9014. }
  9015. parserInput.restore('at-rule options not recognised');
  9016. },
  9017. //
  9018. // A Value is a comma-delimited list of Expressions
  9019. //
  9020. // font-family: Baskerville, Georgia, serif;
  9021. //
  9022. // In a Rule, a Value represents everything after the `:`,
  9023. // and before the `;`.
  9024. //
  9025. value: function value() {
  9026. var e;
  9027. var expressions = [];
  9028. var index = parserInput.i;
  9029. do {
  9030. e = this.expression();
  9031. if (e) {
  9032. expressions.push(e);
  9033. if (!parserInput.$char(',')) {
  9034. break;
  9035. }
  9036. }
  9037. } while (e);
  9038. if (expressions.length > 0) {
  9039. return new tree.Value(expressions, index);
  9040. }
  9041. },
  9042. important: function important() {
  9043. if (parserInput.currentChar() === '!') {
  9044. return parserInput.$re(/^! *important/);
  9045. }
  9046. },
  9047. sub: function sub() {
  9048. var a;
  9049. var e;
  9050. parserInput.save();
  9051. if (parserInput.$char('(')) {
  9052. a = this.addition();
  9053. if (a && parserInput.$char(')')) {
  9054. parserInput.forget();
  9055. e = new tree.Expression([a]);
  9056. e.parens = true;
  9057. return e;
  9058. }
  9059. parserInput.restore('Expected \')\'');
  9060. return;
  9061. }
  9062. parserInput.restore();
  9063. },
  9064. multiplication: function multiplication() {
  9065. var m;
  9066. var a;
  9067. var op;
  9068. var operation;
  9069. var isSpaced;
  9070. m = this.operand();
  9071. if (m) {
  9072. isSpaced = parserInput.isWhitespace(-1);
  9073. while (true) {
  9074. if (parserInput.peek(/^\/[*\/]/)) {
  9075. break;
  9076. }
  9077. parserInput.save();
  9078. op = parserInput.$char('/') || parserInput.$char('*') || parserInput.$str('./');
  9079. if (!op) {
  9080. parserInput.forget();
  9081. break;
  9082. }
  9083. a = this.operand();
  9084. if (!a) {
  9085. parserInput.restore();
  9086. break;
  9087. }
  9088. parserInput.forget();
  9089. m.parensInOp = true;
  9090. a.parensInOp = true;
  9091. operation = new tree.Operation(op, [operation || m, a], isSpaced);
  9092. isSpaced = parserInput.isWhitespace(-1);
  9093. }
  9094. return operation || m;
  9095. }
  9096. },
  9097. addition: function addition() {
  9098. var m;
  9099. var a;
  9100. var op;
  9101. var operation;
  9102. var isSpaced;
  9103. m = this.multiplication();
  9104. if (m) {
  9105. isSpaced = parserInput.isWhitespace(-1);
  9106. while (true) {
  9107. op = parserInput.$re(/^[-+]\s+/) || !isSpaced && (parserInput.$char('+') || parserInput.$char('-'));
  9108. if (!op) {
  9109. break;
  9110. }
  9111. a = this.multiplication();
  9112. if (!a) {
  9113. break;
  9114. }
  9115. m.parensInOp = true;
  9116. a.parensInOp = true;
  9117. operation = new tree.Operation(op, [operation || m, a], isSpaced);
  9118. isSpaced = parserInput.isWhitespace(-1);
  9119. }
  9120. return operation || m;
  9121. }
  9122. },
  9123. conditions: function conditions() {
  9124. var a;
  9125. var b;
  9126. var index = parserInput.i;
  9127. var condition;
  9128. a = this.condition(true);
  9129. if (a) {
  9130. while (true) {
  9131. if (!parserInput.peek(/^,\s*(not\s*)?\(/) || !parserInput.$char(',')) {
  9132. break;
  9133. }
  9134. b = this.condition(true);
  9135. if (!b) {
  9136. break;
  9137. }
  9138. condition = new tree.Condition('or', condition || a, b, index);
  9139. }
  9140. return condition || a;
  9141. }
  9142. },
  9143. condition: function condition(needsParens) {
  9144. var result;
  9145. var logical;
  9146. var next;
  9147. function or() {
  9148. return parserInput.$str('or');
  9149. }
  9150. result = this.conditionAnd(needsParens);
  9151. if (!result) {
  9152. return;
  9153. }
  9154. logical = or();
  9155. if (logical) {
  9156. next = this.condition(needsParens);
  9157. if (next) {
  9158. result = new tree.Condition(logical, result, next);
  9159. } else {
  9160. return;
  9161. }
  9162. }
  9163. return result;
  9164. },
  9165. conditionAnd: function conditionAnd(needsParens) {
  9166. var result;
  9167. var logical;
  9168. var next;
  9169. var self = this;
  9170. function insideCondition() {
  9171. var cond = self.negatedCondition(needsParens) || self.parenthesisCondition(needsParens);
  9172. if (!cond && !needsParens) {
  9173. return self.atomicCondition(needsParens);
  9174. }
  9175. return cond;
  9176. }
  9177. function and() {
  9178. return parserInput.$str('and');
  9179. }
  9180. result = insideCondition();
  9181. if (!result) {
  9182. return;
  9183. }
  9184. logical = and();
  9185. if (logical) {
  9186. next = this.conditionAnd(needsParens);
  9187. if (next) {
  9188. result = new tree.Condition(logical, result, next);
  9189. } else {
  9190. return;
  9191. }
  9192. }
  9193. return result;
  9194. },
  9195. negatedCondition: function negatedCondition(needsParens) {
  9196. if (parserInput.$str('not')) {
  9197. var result = this.parenthesisCondition(needsParens);
  9198. if (result) {
  9199. result.negate = !result.negate;
  9200. }
  9201. return result;
  9202. }
  9203. },
  9204. parenthesisCondition: function parenthesisCondition(needsParens) {
  9205. function tryConditionFollowedByParenthesis(me) {
  9206. var body;
  9207. parserInput.save();
  9208. body = me.condition(needsParens);
  9209. if (!body) {
  9210. parserInput.restore();
  9211. return;
  9212. }
  9213. if (!parserInput.$char(')')) {
  9214. parserInput.restore();
  9215. return;
  9216. }
  9217. parserInput.forget();
  9218. return body;
  9219. }
  9220. var body;
  9221. parserInput.save();
  9222. if (!parserInput.$str('(')) {
  9223. parserInput.restore();
  9224. return;
  9225. }
  9226. body = tryConditionFollowedByParenthesis(this);
  9227. if (body) {
  9228. parserInput.forget();
  9229. return body;
  9230. }
  9231. body = this.atomicCondition(needsParens);
  9232. if (!body) {
  9233. parserInput.restore();
  9234. return;
  9235. }
  9236. if (!parserInput.$char(')')) {
  9237. parserInput.restore(`expected ')' got '${parserInput.currentChar()}'`);
  9238. return;
  9239. }
  9240. parserInput.forget();
  9241. return body;
  9242. },
  9243. atomicCondition: function atomicCondition(needsParens) {
  9244. var entities = this.entities;
  9245. var index = parserInput.i;
  9246. var a;
  9247. var b;
  9248. var c;
  9249. var op;
  9250. function cond() {
  9251. return this.addition() || entities.keyword() || entities.quoted() || entities.mixinLookup();
  9252. }
  9253. cond = cond.bind(this);
  9254. a = cond();
  9255. if (a) {
  9256. if (parserInput.$char('>')) {
  9257. if (parserInput.$char('=')) {
  9258. op = '>=';
  9259. } else {
  9260. op = '>';
  9261. }
  9262. } else if (parserInput.$char('<')) {
  9263. if (parserInput.$char('=')) {
  9264. op = '<=';
  9265. } else {
  9266. op = '<';
  9267. }
  9268. } else if (parserInput.$char('=')) {
  9269. if (parserInput.$char('>')) {
  9270. op = '=>';
  9271. } else if (parserInput.$char('<')) {
  9272. op = '=<';
  9273. } else {
  9274. op = '=';
  9275. }
  9276. }
  9277. if (op) {
  9278. b = cond();
  9279. if (b) {
  9280. c = new tree.Condition(op, a, b, index, false);
  9281. } else {
  9282. error('expected expression');
  9283. }
  9284. } else {
  9285. c = new tree.Condition('=', a, new tree.Keyword('true'), index, false);
  9286. }
  9287. return c;
  9288. }
  9289. },
  9290. //
  9291. // An operand is anything that can be part of an operation,
  9292. // such as a Color, or a Variable
  9293. //
  9294. operand: function operand() {
  9295. var entities = this.entities;
  9296. var negate;
  9297. if (parserInput.peek(/^-[@\$\(]/)) {
  9298. negate = parserInput.$char('-');
  9299. }
  9300. var o = this.sub() || entities.dimension() || entities.color() || entities.variable() || entities.property() || entities.call() || entities.quoted(true) || entities.colorKeyword() || entities.mixinLookup();
  9301. if (negate) {
  9302. o.parensInOp = true;
  9303. o = new tree.Negative(o);
  9304. }
  9305. return o;
  9306. },
  9307. //
  9308. // Expressions either represent mathematical operations,
  9309. // or white-space delimited Entities.
  9310. //
  9311. // 1px solid black
  9312. // @var * 2
  9313. //
  9314. expression: function expression() {
  9315. var entities = [];
  9316. var e;
  9317. var delim;
  9318. var index = parserInput.i;
  9319. do {
  9320. e = this.comment();
  9321. if (e) {
  9322. entities.push(e);
  9323. continue;
  9324. }
  9325. e = this.addition() || this.entity();
  9326. if (e) {
  9327. entities.push(e); // operations do not allow keyword "/" dimension (e.g. small/20px) so we support that here
  9328. if (!parserInput.peek(/^\/[\/*]/)) {
  9329. delim = parserInput.$char('/');
  9330. if (delim) {
  9331. entities.push(new tree.Anonymous(delim, index));
  9332. }
  9333. }
  9334. }
  9335. } while (e);
  9336. if (entities.length > 0) {
  9337. return new tree.Expression(entities);
  9338. }
  9339. },
  9340. property: function property() {
  9341. var name = parserInput.$re(/^(\*?-?[_a-zA-Z0-9-]+)\s*:/);
  9342. if (name) {
  9343. return name[1];
  9344. }
  9345. },
  9346. ruleProperty: function ruleProperty() {
  9347. var name = [];
  9348. var index = [];
  9349. var s;
  9350. var k;
  9351. parserInput.save();
  9352. var simpleProperty = parserInput.$re(/^([_a-zA-Z0-9-]+)\s*:/);
  9353. if (simpleProperty) {
  9354. name = [new tree.Keyword(simpleProperty[1])];
  9355. parserInput.forget();
  9356. return name;
  9357. }
  9358. function match(re) {
  9359. var i = parserInput.i;
  9360. var chunk = parserInput.$re(re);
  9361. if (chunk) {
  9362. index.push(i);
  9363. return name.push(chunk[1]);
  9364. }
  9365. }
  9366. match(/^(\*?)/);
  9367. while (true) {
  9368. if (!match(/^((?:[\w-]+)|(?:[@\$]\{[\w-]+\}))/)) {
  9369. break;
  9370. }
  9371. }
  9372. if (name.length > 1 && match(/^((?:\+_|\+)?)\s*:/)) {
  9373. parserInput.forget(); // at last, we have the complete match now. move forward,
  9374. // convert name particles to tree objects and return:
  9375. if (name[0] === '') {
  9376. name.shift();
  9377. index.shift();
  9378. }
  9379. for (k = 0; k < name.length; k++) {
  9380. s = name[k];
  9381. name[k] = s.charAt(0) !== '@' && s.charAt(0) !== '$' ? new tree.Keyword(s) : s.charAt(0) === '@' ? new tree.Variable(`@${s.slice(2, -1)}`, index[k], fileInfo) : new tree.Property(`$${s.slice(2, -1)}`, index[k], fileInfo);
  9382. }
  9383. return name;
  9384. }
  9385. parserInput.restore();
  9386. }
  9387. }
  9388. };
  9389. };
  9390. Parser.serializeVars = function (vars) {
  9391. var s = '';
  9392. for (var name in vars) {
  9393. if (Object.hasOwnProperty.call(vars, name)) {
  9394. var value = vars[name];
  9395. s += `${(name[0] === '@' ? '' : '@') + name}: ${value}${String(value).slice(-1) === ';' ? '' : ';'}`;
  9396. }
  9397. }
  9398. return s;
  9399. };
  9400. function boolean(condition) {
  9401. return condition ? Keyword.True : Keyword.False;
  9402. }
  9403. function If(condition, trueValue, falseValue) {
  9404. return condition ? trueValue : falseValue || new Anonymous();
  9405. }
  9406. var boolean$1 = {
  9407. boolean,
  9408. 'if': If
  9409. };
  9410. var colorFunctions;
  9411. function clamp$1(val) {
  9412. return Math.min(1, Math.max(0, val));
  9413. }
  9414. function hsla(origColor, hsl) {
  9415. var color = colorFunctions.hsla(hsl.h, hsl.s, hsl.l, hsl.a);
  9416. if (color) {
  9417. if (origColor.value && /^(rgb|hsl)/.test(origColor.value)) {
  9418. color.value = origColor.value;
  9419. } else {
  9420. color.value = 'rgb';
  9421. }
  9422. return color;
  9423. }
  9424. }
  9425. function toHSL(color) {
  9426. if (color.toHSL) {
  9427. return color.toHSL();
  9428. } else {
  9429. throw new Error('Argument cannot be evaluated to a color');
  9430. }
  9431. }
  9432. function toHSV(color) {
  9433. if (color.toHSV) {
  9434. return color.toHSV();
  9435. } else {
  9436. throw new Error('Argument cannot be evaluated to a color');
  9437. }
  9438. }
  9439. function number(n) {
  9440. if (n instanceof Dimension) {
  9441. return parseFloat(n.unit.is('%') ? n.value / 100 : n.value);
  9442. } else if (typeof n === 'number') {
  9443. return n;
  9444. } else {
  9445. throw {
  9446. type: 'Argument',
  9447. message: 'color functions take numbers as parameters'
  9448. };
  9449. }
  9450. }
  9451. function scaled(n, size) {
  9452. if (n instanceof Dimension && n.unit.is('%')) {
  9453. return parseFloat(n.value * size / 100);
  9454. } else {
  9455. return number(n);
  9456. }
  9457. }
  9458. colorFunctions = {
  9459. rgb: function rgb(r, g, b) {
  9460. var color = colorFunctions.rgba(r, g, b, 1.0);
  9461. if (color) {
  9462. color.value = 'rgb';
  9463. return color;
  9464. }
  9465. },
  9466. rgba: function rgba(r, g, b, a) {
  9467. try {
  9468. if (r instanceof Color) {
  9469. if (g) {
  9470. a = number(g);
  9471. } else {
  9472. a = r.alpha;
  9473. }
  9474. return new Color(r.rgb, a, 'rgba');
  9475. }
  9476. var rgb = [r, g, b].map(function (c) {
  9477. return scaled(c, 255);
  9478. });
  9479. a = number(a);
  9480. return new Color(rgb, a, 'rgba');
  9481. } catch (e) {}
  9482. },
  9483. hsl: function hsl(h, s, l) {
  9484. var color = colorFunctions.hsla(h, s, l, 1.0);
  9485. if (color) {
  9486. color.value = 'hsl';
  9487. return color;
  9488. }
  9489. },
  9490. hsla: function hsla(h, s, l, a) {
  9491. try {
  9492. if (h instanceof Color) {
  9493. if (s) {
  9494. a = number(s);
  9495. } else {
  9496. a = h.alpha;
  9497. }
  9498. return new Color(h.rgb, a, 'hsla');
  9499. }
  9500. var m1;
  9501. var m2;
  9502. function hue(h) {
  9503. h = h < 0 ? h + 1 : h > 1 ? h - 1 : h;
  9504. if (h * 6 < 1) {
  9505. return m1 + (m2 - m1) * h * 6;
  9506. } else if (h * 2 < 1) {
  9507. return m2;
  9508. } else if (h * 3 < 2) {
  9509. return m1 + (m2 - m1) * (2 / 3 - h) * 6;
  9510. } else {
  9511. return m1;
  9512. }
  9513. }
  9514. h = number(h) % 360 / 360;
  9515. s = clamp$1(number(s));
  9516. l = clamp$1(number(l));
  9517. a = clamp$1(number(a));
  9518. m2 = l <= 0.5 ? l * (s + 1) : l + s - l * s;
  9519. m1 = l * 2 - m2;
  9520. var rgb = [hue(h + 1 / 3) * 255, hue(h) * 255, hue(h - 1 / 3) * 255];
  9521. a = number(a);
  9522. return new Color(rgb, a, 'hsla');
  9523. } catch (e) {}
  9524. },
  9525. hsv: function hsv(h, s, v) {
  9526. return colorFunctions.hsva(h, s, v, 1.0);
  9527. },
  9528. hsva: function hsva(h, s, v, a) {
  9529. h = number(h) % 360 / 360 * 360;
  9530. s = number(s);
  9531. v = number(v);
  9532. a = number(a);
  9533. var i;
  9534. var f;
  9535. i = Math.floor(h / 60 % 6);
  9536. f = h / 60 - i;
  9537. var vs = [v, v * (1 - s), v * (1 - f * s), v * (1 - (1 - f) * s)];
  9538. var perm = [[0, 3, 1], [2, 0, 1], [1, 0, 3], [1, 2, 0], [3, 1, 0], [0, 1, 2]];
  9539. return colorFunctions.rgba(vs[perm[i][0]] * 255, vs[perm[i][1]] * 255, vs[perm[i][2]] * 255, a);
  9540. },
  9541. hue: function hue(color) {
  9542. return new Dimension(toHSL(color).h);
  9543. },
  9544. saturation: function saturation(color) {
  9545. return new Dimension(toHSL(color).s * 100, '%');
  9546. },
  9547. lightness: function lightness(color) {
  9548. return new Dimension(toHSL(color).l * 100, '%');
  9549. },
  9550. hsvhue: function hsvhue(color) {
  9551. return new Dimension(toHSV(color).h);
  9552. },
  9553. hsvsaturation: function hsvsaturation(color) {
  9554. return new Dimension(toHSV(color).s * 100, '%');
  9555. },
  9556. hsvvalue: function hsvvalue(color) {
  9557. return new Dimension(toHSV(color).v * 100, '%');
  9558. },
  9559. red: function red(color) {
  9560. return new Dimension(color.rgb[0]);
  9561. },
  9562. green: function green(color) {
  9563. return new Dimension(color.rgb[1]);
  9564. },
  9565. blue: function blue(color) {
  9566. return new Dimension(color.rgb[2]);
  9567. },
  9568. alpha: function alpha(color) {
  9569. return new Dimension(toHSL(color).a);
  9570. },
  9571. luma: function luma(color) {
  9572. return new Dimension(color.luma() * color.alpha * 100, '%');
  9573. },
  9574. luminance: function luminance(color) {
  9575. var luminance = 0.2126 * color.rgb[0] / 255 + 0.7152 * color.rgb[1] / 255 + 0.0722 * color.rgb[2] / 255;
  9576. return new Dimension(luminance * color.alpha * 100, '%');
  9577. },
  9578. saturate: function saturate(color, amount, method) {
  9579. // filter: saturate(3.2);
  9580. // should be kept as is, so check for color
  9581. if (!color.rgb) {
  9582. return null;
  9583. }
  9584. var hsl = toHSL(color);
  9585. if (typeof method !== 'undefined' && method.value === 'relative') {
  9586. hsl.s += hsl.s * amount.value / 100;
  9587. } else {
  9588. hsl.s += amount.value / 100;
  9589. }
  9590. hsl.s = clamp$1(hsl.s);
  9591. return hsla(color, hsl);
  9592. },
  9593. desaturate: function desaturate(color, amount, method) {
  9594. var hsl = toHSL(color);
  9595. if (typeof method !== 'undefined' && method.value === 'relative') {
  9596. hsl.s -= hsl.s * amount.value / 100;
  9597. } else {
  9598. hsl.s -= amount.value / 100;
  9599. }
  9600. hsl.s = clamp$1(hsl.s);
  9601. return hsla(color, hsl);
  9602. },
  9603. lighten: function lighten(color, amount, method) {
  9604. var hsl = toHSL(color);
  9605. if (typeof method !== 'undefined' && method.value === 'relative') {
  9606. hsl.l += hsl.l * amount.value / 100;
  9607. } else {
  9608. hsl.l += amount.value / 100;
  9609. }
  9610. hsl.l = clamp$1(hsl.l);
  9611. return hsla(color, hsl);
  9612. },
  9613. darken: function darken(color, amount, method) {
  9614. var hsl = toHSL(color);
  9615. if (typeof method !== 'undefined' && method.value === 'relative') {
  9616. hsl.l -= hsl.l * amount.value / 100;
  9617. } else {
  9618. hsl.l -= amount.value / 100;
  9619. }
  9620. hsl.l = clamp$1(hsl.l);
  9621. return hsla(color, hsl);
  9622. },
  9623. fadein: function fadein(color, amount, method) {
  9624. var hsl = toHSL(color);
  9625. if (typeof method !== 'undefined' && method.value === 'relative') {
  9626. hsl.a += hsl.a * amount.value / 100;
  9627. } else {
  9628. hsl.a += amount.value / 100;
  9629. }
  9630. hsl.a = clamp$1(hsl.a);
  9631. return hsla(color, hsl);
  9632. },
  9633. fadeout: function fadeout(color, amount, method) {
  9634. var hsl = toHSL(color);
  9635. if (typeof method !== 'undefined' && method.value === 'relative') {
  9636. hsl.a -= hsl.a * amount.value / 100;
  9637. } else {
  9638. hsl.a -= amount.value / 100;
  9639. }
  9640. hsl.a = clamp$1(hsl.a);
  9641. return hsla(color, hsl);
  9642. },
  9643. fade: function fade(color, amount) {
  9644. var hsl = toHSL(color);
  9645. hsl.a = amount.value / 100;
  9646. hsl.a = clamp$1(hsl.a);
  9647. return hsla(color, hsl);
  9648. },
  9649. spin: function spin(color, amount) {
  9650. var hsl = toHSL(color);
  9651. var hue = (hsl.h + amount.value) % 360;
  9652. hsl.h = hue < 0 ? 360 + hue : hue;
  9653. return hsla(color, hsl);
  9654. },
  9655. //
  9656. // Copyright (c) 2006-2009 Hampton Catlin, Natalie Weizenbaum, and Chris Eppstein
  9657. // http://sass-lang.com
  9658. //
  9659. mix: function mix(color1, color2, weight) {
  9660. if (!weight) {
  9661. weight = new Dimension(50);
  9662. }
  9663. var p = weight.value / 100.0;
  9664. var w = p * 2 - 1;
  9665. var a = toHSL(color1).a - toHSL(color2).a;
  9666. var w1 = ((w * a == -1 ? w : (w + a) / (1 + w * a)) + 1) / 2.0;
  9667. var w2 = 1 - w1;
  9668. var rgb = [color1.rgb[0] * w1 + color2.rgb[0] * w2, color1.rgb[1] * w1 + color2.rgb[1] * w2, color1.rgb[2] * w1 + color2.rgb[2] * w2];
  9669. var alpha = color1.alpha * p + color2.alpha * (1 - p);
  9670. return new Color(rgb, alpha);
  9671. },
  9672. greyscale: function greyscale(color) {
  9673. return colorFunctions.desaturate(color, new Dimension(100));
  9674. },
  9675. contrast: function contrast(color, dark, light, threshold) {
  9676. // filter: contrast(3.2);
  9677. // should be kept as is, so check for color
  9678. if (!color.rgb) {
  9679. return null;
  9680. }
  9681. if (typeof light === 'undefined') {
  9682. light = colorFunctions.rgba(255, 255, 255, 1.0);
  9683. }
  9684. if (typeof dark === 'undefined') {
  9685. dark = colorFunctions.rgba(0, 0, 0, 1.0);
  9686. } // Figure out which is actually light and dark:
  9687. if (dark.luma() > light.luma()) {
  9688. var t = light;
  9689. light = dark;
  9690. dark = t;
  9691. }
  9692. if (typeof threshold === 'undefined') {
  9693. threshold = 0.43;
  9694. } else {
  9695. threshold = number(threshold);
  9696. }
  9697. if (color.luma() < threshold) {
  9698. return light;
  9699. } else {
  9700. return dark;
  9701. }
  9702. },
  9703. // Changes made in 2.7.0 - Reverted in 3.0.0
  9704. // contrast: function (color, color1, color2, threshold) {
  9705. // // Return which of `color1` and `color2` has the greatest contrast with `color`
  9706. // // according to the standard WCAG contrast ratio calculation.
  9707. // // http://www.w3.org/TR/WCAG20/#contrast-ratiodef
  9708. // // The threshold param is no longer used, in line with SASS.
  9709. // // filter: contrast(3.2);
  9710. // // should be kept as is, so check for color
  9711. // if (!color.rgb) {
  9712. // return null;
  9713. // }
  9714. // if (typeof color1 === 'undefined') {
  9715. // color1 = colorFunctions.rgba(0, 0, 0, 1.0);
  9716. // }
  9717. // if (typeof color2 === 'undefined') {
  9718. // color2 = colorFunctions.rgba(255, 255, 255, 1.0);
  9719. // }
  9720. // var contrast1, contrast2;
  9721. // var luma = color.luma();
  9722. // var luma1 = color1.luma();
  9723. // var luma2 = color2.luma();
  9724. // // Calculate contrast ratios for each color
  9725. // if (luma > luma1) {
  9726. // contrast1 = (luma + 0.05) / (luma1 + 0.05);
  9727. // } else {
  9728. // contrast1 = (luma1 + 0.05) / (luma + 0.05);
  9729. // }
  9730. // if (luma > luma2) {
  9731. // contrast2 = (luma + 0.05) / (luma2 + 0.05);
  9732. // } else {
  9733. // contrast2 = (luma2 + 0.05) / (luma + 0.05);
  9734. // }
  9735. // if (contrast1 > contrast2) {
  9736. // return color1;
  9737. // } else {
  9738. // return color2;
  9739. // }
  9740. // },
  9741. argb: function argb(color) {
  9742. return new Anonymous(color.toARGB());
  9743. },
  9744. color: function color(c) {
  9745. if (c instanceof Quoted && /^#([A-Fa-f0-9]{8}|[A-Fa-f0-9]{6}|[A-Fa-f0-9]{3,4})$/i.test(c.value)) {
  9746. var val = c.value.slice(1);
  9747. return new Color(val, undefined, `#${val}`);
  9748. }
  9749. if (c instanceof Color || (c = Color.fromKeyword(c.value))) {
  9750. c.value = undefined;
  9751. return c;
  9752. }
  9753. throw {
  9754. type: 'Argument',
  9755. message: 'argument must be a color keyword or 3|4|6|8 digit hex e.g. #FFF'
  9756. };
  9757. },
  9758. tint: function tint(color, amount) {
  9759. return colorFunctions.mix(colorFunctions.rgb(255, 255, 255), color, amount);
  9760. },
  9761. shade: function shade(color, amount) {
  9762. return colorFunctions.mix(colorFunctions.rgb(0, 0, 0), color, amount);
  9763. }
  9764. };
  9765. var color = colorFunctions;
  9766. // ref: http://www.w3.org/TR/compositing-1
  9767. function colorBlend(mode, color1, color2) {
  9768. var ab = color1.alpha; // result
  9769. var // backdrop
  9770. cb;
  9771. var as = color2.alpha;
  9772. var // source
  9773. cs;
  9774. var ar;
  9775. var cr;
  9776. var r = [];
  9777. ar = as + ab * (1 - as);
  9778. for (var i = 0; i < 3; i++) {
  9779. cb = color1.rgb[i] / 255;
  9780. cs = color2.rgb[i] / 255;
  9781. cr = mode(cb, cs);
  9782. if (ar) {
  9783. cr = (as * cs + ab * (cb - as * (cb + cs - cr))) / ar;
  9784. }
  9785. r[i] = cr * 255;
  9786. }
  9787. return new Color(r, ar);
  9788. }
  9789. var colorBlendModeFunctions = {
  9790. multiply: function multiply(cb, cs) {
  9791. return cb * cs;
  9792. },
  9793. screen: function screen(cb, cs) {
  9794. return cb + cs - cb * cs;
  9795. },
  9796. overlay: function overlay(cb, cs) {
  9797. cb *= 2;
  9798. return cb <= 1 ? colorBlendModeFunctions.multiply(cb, cs) : colorBlendModeFunctions.screen(cb - 1, cs);
  9799. },
  9800. softlight: function softlight(cb, cs) {
  9801. var d = 1;
  9802. var e = cb;
  9803. if (cs > 0.5) {
  9804. e = 1;
  9805. d = cb > 0.25 ? Math.sqrt(cb) : ((16 * cb - 12) * cb + 4) * cb;
  9806. }
  9807. return cb - (1 - 2 * cs) * e * (d - cb);
  9808. },
  9809. hardlight: function hardlight(cb, cs) {
  9810. return colorBlendModeFunctions.overlay(cs, cb);
  9811. },
  9812. difference: function difference(cb, cs) {
  9813. return Math.abs(cb - cs);
  9814. },
  9815. exclusion: function exclusion(cb, cs) {
  9816. return cb + cs - 2 * cb * cs;
  9817. },
  9818. // non-w3c functions:
  9819. average: function average(cb, cs) {
  9820. return (cb + cs) / 2;
  9821. },
  9822. negation: function negation(cb, cs) {
  9823. return 1 - Math.abs(cb + cs - 1);
  9824. }
  9825. };
  9826. for (var f in colorBlendModeFunctions) {
  9827. if (colorBlendModeFunctions.hasOwnProperty(f)) {
  9828. colorBlend[f] = colorBlend.bind(null, colorBlendModeFunctions[f]);
  9829. }
  9830. }
  9831. var dataUri = (function (environment) {
  9832. var fallback = function fallback(functionThis, node) {
  9833. return new URL(node, functionThis.index, functionThis.currentFileInfo).eval(functionThis.context);
  9834. };
  9835. return {
  9836. 'data-uri': function dataUri(mimetypeNode, filePathNode) {
  9837. if (!filePathNode) {
  9838. filePathNode = mimetypeNode;
  9839. mimetypeNode = null;
  9840. }
  9841. var mimetype = mimetypeNode && mimetypeNode.value;
  9842. var filePath = filePathNode.value;
  9843. var currentFileInfo = this.currentFileInfo;
  9844. var currentDirectory = currentFileInfo.rewriteUrls ? currentFileInfo.currentDirectory : currentFileInfo.entryPath;
  9845. var fragmentStart = filePath.indexOf('#');
  9846. var fragment = '';
  9847. if (fragmentStart !== -1) {
  9848. fragment = filePath.slice(fragmentStart);
  9849. filePath = filePath.slice(0, fragmentStart);
  9850. }
  9851. var context = clone(this.context);
  9852. context.rawBuffer = true;
  9853. var fileManager = environment.getFileManager(filePath, currentDirectory, context, environment, true);
  9854. if (!fileManager) {
  9855. return fallback(this, filePathNode);
  9856. }
  9857. var useBase64 = false; // detect the mimetype if not given
  9858. if (!mimetypeNode) {
  9859. mimetype = environment.mimeLookup(filePath);
  9860. if (mimetype === 'image/svg+xml') {
  9861. useBase64 = false;
  9862. } else {
  9863. // use base 64 unless it's an ASCII or UTF-8 format
  9864. var charset = environment.charsetLookup(mimetype);
  9865. useBase64 = ['US-ASCII', 'UTF-8'].indexOf(charset) < 0;
  9866. }
  9867. if (useBase64) {
  9868. mimetype += ';base64';
  9869. }
  9870. } else {
  9871. useBase64 = /;base64$/.test(mimetype);
  9872. }
  9873. var fileSync = fileManager.loadFileSync(filePath, currentDirectory, context, environment);
  9874. if (!fileSync.contents) {
  9875. logger.warn(`Skipped data-uri embedding of ${filePath} because file not found`);
  9876. return fallback(this, filePathNode || mimetypeNode);
  9877. }
  9878. var buf = fileSync.contents;
  9879. if (useBase64 && !environment.encodeBase64) {
  9880. return fallback(this, filePathNode);
  9881. }
  9882. buf = useBase64 ? environment.encodeBase64(buf) : encodeURIComponent(buf);
  9883. var uri = `data:${mimetype},${buf}${fragment}`;
  9884. return new URL(new Quoted(`"${uri}"`, uri, false, this.index, this.currentFileInfo), this.index, this.currentFileInfo);
  9885. }
  9886. };
  9887. });
  9888. var getItemsFromNode = function getItemsFromNode(node) {
  9889. // handle non-array values as an array of length 1
  9890. // return 'undefined' if index is invalid
  9891. var items = Array.isArray(node.value) ? node.value : Array(node);
  9892. return items;
  9893. };
  9894. var list = {
  9895. _SELF: function _SELF(n) {
  9896. return n;
  9897. },
  9898. extract: function extract(values, index) {
  9899. // (1-based index)
  9900. index = index.value - 1;
  9901. return getItemsFromNode(values)[index];
  9902. },
  9903. length: function length(values) {
  9904. return new Dimension(getItemsFromNode(values).length);
  9905. },
  9906. /**
  9907. * Creates a Less list of incremental values.
  9908. * Modeled after Lodash's range function, also exists natively in PHP
  9909. *
  9910. * @param {Dimension} [start=1]
  9911. * @param {Dimension} end - e.g. 10 or 10px - unit is added to output
  9912. * @param {Dimension} [step=1]
  9913. */
  9914. range: function range(start, end, step) {
  9915. var from;
  9916. var to;
  9917. var stepValue = 1;
  9918. var list = [];
  9919. if (end) {
  9920. to = end;
  9921. from = start.value;
  9922. if (step) {
  9923. stepValue = step.value;
  9924. }
  9925. } else {
  9926. from = 1;
  9927. to = start;
  9928. }
  9929. for (var i = from; i <= to.value; i += stepValue) {
  9930. list.push(new Dimension(i, to.unit));
  9931. }
  9932. return new Expression(list);
  9933. },
  9934. each: function each(list, rs) {
  9935. var rules = [];
  9936. var newRules;
  9937. var iterator;
  9938. if (list.value && !(list instanceof Quoted)) {
  9939. if (Array.isArray(list.value)) {
  9940. iterator = list.value;
  9941. } else {
  9942. iterator = [list.value];
  9943. }
  9944. } else if (list.ruleset) {
  9945. iterator = list.ruleset.rules;
  9946. } else if (list.rules) {
  9947. iterator = list.rules;
  9948. } else if (Array.isArray(list)) {
  9949. iterator = list;
  9950. } else {
  9951. iterator = [list];
  9952. }
  9953. var valueName = '@value';
  9954. var keyName = '@key';
  9955. var indexName = '@index';
  9956. if (rs.params) {
  9957. valueName = rs.params[0] && rs.params[0].name;
  9958. keyName = rs.params[1] && rs.params[1].name;
  9959. indexName = rs.params[2] && rs.params[2].name;
  9960. rs = rs.rules;
  9961. } else {
  9962. rs = rs.ruleset;
  9963. }
  9964. for (var i = 0; i < iterator.length; i++) {
  9965. var key = void 0;
  9966. var value = void 0;
  9967. var item = iterator[i];
  9968. if (item instanceof Declaration) {
  9969. key = typeof item.name === 'string' ? item.name : item.name[0].value;
  9970. value = item.value;
  9971. } else {
  9972. key = new Dimension(i + 1);
  9973. value = item;
  9974. }
  9975. if (item instanceof Comment) {
  9976. continue;
  9977. }
  9978. newRules = rs.rules.slice(0);
  9979. if (valueName) {
  9980. newRules.push(new Declaration(valueName, value, false, false, this.index, this.currentFileInfo));
  9981. }
  9982. if (indexName) {
  9983. newRules.push(new Declaration(indexName, new Dimension(i + 1), false, false, this.index, this.currentFileInfo));
  9984. }
  9985. if (keyName) {
  9986. newRules.push(new Declaration(keyName, key, false, false, this.index, this.currentFileInfo));
  9987. }
  9988. rules.push(new Ruleset([new Selector([new Element("", '&')])], newRules, rs.strictImports, rs.visibilityInfo()));
  9989. }
  9990. return new Ruleset([new Selector([new Element("", '&')])], rules, rs.strictImports, rs.visibilityInfo()).eval(this.context);
  9991. }
  9992. };
  9993. var MathHelper = function MathHelper(fn, unit, n) {
  9994. if (!(n instanceof Dimension)) {
  9995. throw {
  9996. type: 'Argument',
  9997. message: 'argument must be a number'
  9998. };
  9999. }
  10000. if (unit == null) {
  10001. unit = n.unit;
  10002. } else {
  10003. n = n.unify();
  10004. }
  10005. return new Dimension(fn(parseFloat(n.value)), unit);
  10006. };
  10007. var mathFunctions = {
  10008. // name, unit
  10009. ceil: null,
  10010. floor: null,
  10011. sqrt: null,
  10012. abs: null,
  10013. tan: '',
  10014. sin: '',
  10015. cos: '',
  10016. atan: 'rad',
  10017. asin: 'rad',
  10018. acos: 'rad'
  10019. };
  10020. for (var f$1 in mathFunctions) {
  10021. if (mathFunctions.hasOwnProperty(f$1)) {
  10022. mathFunctions[f$1] = MathHelper.bind(null, Math[f$1], mathFunctions[f$1]);
  10023. }
  10024. }
  10025. mathFunctions.round = function (n, f) {
  10026. var fraction = typeof f === 'undefined' ? 0 : f.value;
  10027. return MathHelper(function (num) {
  10028. return num.toFixed(fraction);
  10029. }, null, n);
  10030. };
  10031. var minMax = function minMax(isMin, args) {
  10032. args = Array.prototype.slice.call(args);
  10033. switch (args.length) {
  10034. case 0:
  10035. throw {
  10036. type: 'Argument',
  10037. message: 'one or more arguments required'
  10038. };
  10039. }
  10040. var i; // key is the unit.toString() for unified Dimension values,
  10041. var j;
  10042. var current;
  10043. var currentUnified;
  10044. var referenceUnified;
  10045. var unit;
  10046. var unitStatic;
  10047. var unitClone;
  10048. var // elems only contains original argument values.
  10049. order = [];
  10050. var values = {}; // value is the index into the order array.
  10051. for (i = 0; i < args.length; i++) {
  10052. current = args[i];
  10053. if (!(current instanceof Dimension)) {
  10054. if (Array.isArray(args[i].value)) {
  10055. Array.prototype.push.apply(args, Array.prototype.slice.call(args[i].value));
  10056. }
  10057. continue;
  10058. }
  10059. currentUnified = current.unit.toString() === '' && unitClone !== undefined ? new Dimension(current.value, unitClone).unify() : current.unify();
  10060. unit = currentUnified.unit.toString() === '' && unitStatic !== undefined ? unitStatic : currentUnified.unit.toString();
  10061. unitStatic = unit !== '' && unitStatic === undefined || unit !== '' && order[0].unify().unit.toString() === '' ? unit : unitStatic;
  10062. unitClone = unit !== '' && unitClone === undefined ? current.unit.toString() : unitClone;
  10063. j = values[''] !== undefined && unit !== '' && unit === unitStatic ? values[''] : values[unit];
  10064. if (j === undefined) {
  10065. if (unitStatic !== undefined && unit !== unitStatic) {
  10066. throw {
  10067. type: 'Argument',
  10068. message: 'incompatible types'
  10069. };
  10070. }
  10071. values[unit] = order.length;
  10072. order.push(current);
  10073. continue;
  10074. }
  10075. referenceUnified = order[j].unit.toString() === '' && unitClone !== undefined ? new Dimension(order[j].value, unitClone).unify() : order[j].unify();
  10076. if (isMin && currentUnified.value < referenceUnified.value || !isMin && currentUnified.value > referenceUnified.value) {
  10077. order[j] = current;
  10078. }
  10079. }
  10080. if (order.length == 1) {
  10081. return order[0];
  10082. }
  10083. args = order.map(function (a) {
  10084. return a.toCSS(this.context);
  10085. }).join(this.context.compress ? ',' : ', ');
  10086. return new Anonymous(`${isMin ? 'min' : 'max'}(${args})`);
  10087. };
  10088. var number$1 = {
  10089. min: function min() {
  10090. for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
  10091. args[_key] = arguments[_key];
  10092. }
  10093. return minMax(true, args);
  10094. },
  10095. max: function max() {
  10096. for (var _len2 = arguments.length, args = new Array(_len2), _key2 = 0; _key2 < _len2; _key2++) {
  10097. args[_key2] = arguments[_key2];
  10098. }
  10099. return minMax(false, args);
  10100. },
  10101. convert: function convert(val, unit) {
  10102. return val.convertTo(unit.value);
  10103. },
  10104. pi: function pi() {
  10105. return new Dimension(Math.PI);
  10106. },
  10107. mod: function mod(a, b) {
  10108. return new Dimension(a.value % b.value, a.unit);
  10109. },
  10110. pow: function pow(x, y) {
  10111. if (typeof x === 'number' && typeof y === 'number') {
  10112. x = new Dimension(x);
  10113. y = new Dimension(y);
  10114. } else if (!(x instanceof Dimension) || !(y instanceof Dimension)) {
  10115. throw {
  10116. type: 'Argument',
  10117. message: 'arguments must be numbers'
  10118. };
  10119. }
  10120. return new Dimension(Math.pow(x.value, y.value), x.unit);
  10121. },
  10122. percentage: function percentage(n) {
  10123. var result = MathHelper(function (num) {
  10124. return num * 100;
  10125. }, '%', n);
  10126. return result;
  10127. }
  10128. };
  10129. var string = {
  10130. e: function e(str) {
  10131. return new Quoted('"', str instanceof JavaScript ? str.evaluated : str.value, true);
  10132. },
  10133. escape: function escape(str) {
  10134. return new Anonymous(encodeURI(str.value).replace(/=/g, '%3D').replace(/:/g, '%3A').replace(/#/g, '%23').replace(/;/g, '%3B').replace(/\(/g, '%28').replace(/\)/g, '%29'));
  10135. },
  10136. replace: function replace(string, pattern, replacement, flags) {
  10137. var result = string.value;
  10138. replacement = replacement.type === 'Quoted' ? replacement.value : replacement.toCSS();
  10139. result = result.replace(new RegExp(pattern.value, flags ? flags.value : ''), replacement);
  10140. return new Quoted(string.quote || '', result, string.escaped);
  10141. },
  10142. '%': function _(string
  10143. /* arg, arg, ... */
  10144. ) {
  10145. var args = Array.prototype.slice.call(arguments, 1);
  10146. var result = string.value;
  10147. var _loop = function _loop(i) {
  10148. /* jshint loopfunc:true */
  10149. result = result.replace(/%[sda]/i, function (token) {
  10150. var value = args[i].type === 'Quoted' && token.match(/s/i) ? args[i].value : args[i].toCSS();
  10151. return token.match(/[A-Z]$/) ? encodeURIComponent(value) : value;
  10152. });
  10153. };
  10154. for (var i = 0; i < args.length; i++) {
  10155. _loop(i);
  10156. }
  10157. result = result.replace(/%%/g, '%');
  10158. return new Quoted(string.quote || '', result, string.escaped);
  10159. }
  10160. };
  10161. var svg = (function (environment) {
  10162. return {
  10163. 'svg-gradient': function svgGradient(direction) {
  10164. var stops;
  10165. var gradientDirectionSvg;
  10166. var gradientType = 'linear';
  10167. var rectangleDimension = 'x="0" y="0" width="1" height="1"';
  10168. var renderEnv = {
  10169. compress: false
  10170. };
  10171. var returner;
  10172. var directionValue = direction.toCSS(renderEnv);
  10173. var i;
  10174. var color;
  10175. var position;
  10176. var positionValue;
  10177. var alpha;
  10178. function throwArgumentDescriptor() {
  10179. throw {
  10180. type: 'Argument',
  10181. message: 'svg-gradient expects direction, start_color [start_position], [color position,]...,' + ' end_color [end_position] or direction, color list'
  10182. };
  10183. }
  10184. if (arguments.length == 2) {
  10185. if (arguments[1].value.length < 2) {
  10186. throwArgumentDescriptor();
  10187. }
  10188. stops = arguments[1].value;
  10189. } else if (arguments.length < 3) {
  10190. throwArgumentDescriptor();
  10191. } else {
  10192. stops = Array.prototype.slice.call(arguments, 1);
  10193. }
  10194. switch (directionValue) {
  10195. case 'to bottom':
  10196. gradientDirectionSvg = 'x1="0%" y1="0%" x2="0%" y2="100%"';
  10197. break;
  10198. case 'to right':
  10199. gradientDirectionSvg = 'x1="0%" y1="0%" x2="100%" y2="0%"';
  10200. break;
  10201. case 'to bottom right':
  10202. gradientDirectionSvg = 'x1="0%" y1="0%" x2="100%" y2="100%"';
  10203. break;
  10204. case 'to top right':
  10205. gradientDirectionSvg = 'x1="0%" y1="100%" x2="100%" y2="0%"';
  10206. break;
  10207. case 'ellipse':
  10208. case 'ellipse at center':
  10209. gradientType = 'radial';
  10210. gradientDirectionSvg = 'cx="50%" cy="50%" r="75%"';
  10211. rectangleDimension = 'x="-50" y="-50" width="101" height="101"';
  10212. break;
  10213. default:
  10214. throw {
  10215. type: 'Argument',
  10216. message: 'svg-gradient direction must be \'to bottom\', \'to right\',' + ' \'to bottom right\', \'to top right\' or \'ellipse at center\''
  10217. };
  10218. }
  10219. returner = `<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 1 1"><${gradientType}Gradient id="g" ${gradientDirectionSvg}>`;
  10220. for (i = 0; i < stops.length; i += 1) {
  10221. if (stops[i] instanceof Expression) {
  10222. color = stops[i].value[0];
  10223. position = stops[i].value[1];
  10224. } else {
  10225. color = stops[i];
  10226. position = undefined;
  10227. }
  10228. if (!(color instanceof Color) || !((i === 0 || i + 1 === stops.length) && position === undefined) && !(position instanceof Dimension)) {
  10229. throwArgumentDescriptor();
  10230. }
  10231. positionValue = position ? position.toCSS(renderEnv) : i === 0 ? '0%' : '100%';
  10232. alpha = color.alpha;
  10233. returner += `<stop offset="${positionValue}" stop-color="${color.toRGB()}"${alpha < 1 ? ` stop-opacity="${alpha}"` : ''}/>`;
  10234. }
  10235. returner += `</${gradientType}Gradient><rect ${rectangleDimension} fill="url(#g)" /></svg>`;
  10236. returner = encodeURIComponent(returner);
  10237. returner = `data:image/svg+xml,${returner}`;
  10238. return new URL(new Quoted(`'${returner}'`, returner, false, this.index, this.currentFileInfo), this.index, this.currentFileInfo);
  10239. }
  10240. };
  10241. });
  10242. var isa = function isa(n, Type) {
  10243. return n instanceof Type ? Keyword.True : Keyword.False;
  10244. };
  10245. var isunit = function isunit(n, unit) {
  10246. if (unit === undefined) {
  10247. throw {
  10248. type: 'Argument',
  10249. message: 'missing the required second argument to isunit.'
  10250. };
  10251. }
  10252. unit = typeof unit.value === 'string' ? unit.value : unit;
  10253. if (typeof unit !== 'string') {
  10254. throw {
  10255. type: 'Argument',
  10256. message: 'Second argument to isunit should be a unit or a string.'
  10257. };
  10258. }
  10259. return n instanceof Dimension && n.unit.is(unit) ? Keyword.True : Keyword.False;
  10260. };
  10261. var types = {
  10262. isruleset: function isruleset(n) {
  10263. return isa(n, DetachedRuleset);
  10264. },
  10265. iscolor: function iscolor(n) {
  10266. return isa(n, Color);
  10267. },
  10268. isnumber: function isnumber(n) {
  10269. return isa(n, Dimension);
  10270. },
  10271. isstring: function isstring(n) {
  10272. return isa(n, Quoted);
  10273. },
  10274. iskeyword: function iskeyword(n) {
  10275. return isa(n, Keyword);
  10276. },
  10277. isurl: function isurl(n) {
  10278. return isa(n, URL);
  10279. },
  10280. ispixel: function ispixel(n) {
  10281. return isunit(n, 'px');
  10282. },
  10283. ispercentage: function ispercentage(n) {
  10284. return isunit(n, '%');
  10285. },
  10286. isem: function isem(n) {
  10287. return isunit(n, 'em');
  10288. },
  10289. isunit,
  10290. unit: function unit(val, _unit) {
  10291. if (!(val instanceof Dimension)) {
  10292. throw {
  10293. type: 'Argument',
  10294. message: `the first argument to unit must be a number${val instanceof Operation ? '. Have you forgotten parenthesis?' : ''}`
  10295. };
  10296. }
  10297. if (_unit) {
  10298. if (_unit instanceof Keyword) {
  10299. _unit = _unit.value;
  10300. } else {
  10301. _unit = _unit.toCSS();
  10302. }
  10303. } else {
  10304. _unit = '';
  10305. }
  10306. return new Dimension(val.value, _unit);
  10307. },
  10308. 'get-unit': function getUnit(n) {
  10309. return new Anonymous(n.unit);
  10310. }
  10311. };
  10312. var Functions = (function (environment) {
  10313. var functions = {
  10314. functionRegistry,
  10315. functionCaller
  10316. }; // register functions
  10317. functionRegistry.addMultiple(boolean$1);
  10318. functionRegistry.add('default', defaultFunc.eval.bind(defaultFunc));
  10319. functionRegistry.addMultiple(color);
  10320. functionRegistry.addMultiple(colorBlend);
  10321. functionRegistry.addMultiple(dataUri(environment));
  10322. functionRegistry.addMultiple(list);
  10323. functionRegistry.addMultiple(mathFunctions);
  10324. functionRegistry.addMultiple(number$1);
  10325. functionRegistry.addMultiple(string);
  10326. functionRegistry.addMultiple(svg());
  10327. functionRegistry.addMultiple(types);
  10328. return functions;
  10329. });
  10330. var sourceMapOutput = (function (environment) {
  10331. var SourceMapOutput =
  10332. /*#__PURE__*/
  10333. function () {
  10334. function SourceMapOutput(options) {
  10335. _classCallCheck(this, SourceMapOutput);
  10336. this._css = [];
  10337. this._rootNode = options.rootNode;
  10338. this._contentsMap = options.contentsMap;
  10339. this._contentsIgnoredCharsMap = options.contentsIgnoredCharsMap;
  10340. if (options.sourceMapFilename) {
  10341. this._sourceMapFilename = options.sourceMapFilename.replace(/\\/g, '/');
  10342. }
  10343. this._outputFilename = options.outputFilename;
  10344. this.sourceMapURL = options.sourceMapURL;
  10345. if (options.sourceMapBasepath) {
  10346. this._sourceMapBasepath = options.sourceMapBasepath.replace(/\\/g, '/');
  10347. }
  10348. if (options.sourceMapRootpath) {
  10349. this._sourceMapRootpath = options.sourceMapRootpath.replace(/\\/g, '/');
  10350. if (this._sourceMapRootpath.charAt(this._sourceMapRootpath.length - 1) !== '/') {
  10351. this._sourceMapRootpath += '/';
  10352. }
  10353. } else {
  10354. this._sourceMapRootpath = '';
  10355. }
  10356. this._outputSourceFiles = options.outputSourceFiles;
  10357. this._sourceMapGeneratorConstructor = environment.getSourceMapGenerator();
  10358. this._lineNumber = 0;
  10359. this._column = 0;
  10360. }
  10361. _createClass(SourceMapOutput, [{
  10362. key: "removeBasepath",
  10363. value: function removeBasepath(path) {
  10364. if (this._sourceMapBasepath && path.indexOf(this._sourceMapBasepath) === 0) {
  10365. path = path.substring(this._sourceMapBasepath.length);
  10366. if (path.charAt(0) === '\\' || path.charAt(0) === '/') {
  10367. path = path.substring(1);
  10368. }
  10369. }
  10370. return path;
  10371. }
  10372. }, {
  10373. key: "normalizeFilename",
  10374. value: function normalizeFilename(filename) {
  10375. filename = filename.replace(/\\/g, '/');
  10376. filename = this.removeBasepath(filename);
  10377. return (this._sourceMapRootpath || '') + filename;
  10378. }
  10379. }, {
  10380. key: "add",
  10381. value: function add(chunk, fileInfo, index, mapLines) {
  10382. // ignore adding empty strings
  10383. if (!chunk) {
  10384. return;
  10385. }
  10386. var lines;
  10387. var sourceLines;
  10388. var columns;
  10389. var sourceColumns;
  10390. var i;
  10391. if (fileInfo && fileInfo.filename) {
  10392. var inputSource = this._contentsMap[fileInfo.filename]; // remove vars/banner added to the top of the file
  10393. if (this._contentsIgnoredCharsMap[fileInfo.filename]) {
  10394. // adjust the index
  10395. index -= this._contentsIgnoredCharsMap[fileInfo.filename];
  10396. if (index < 0) {
  10397. index = 0;
  10398. } // adjust the source
  10399. inputSource = inputSource.slice(this._contentsIgnoredCharsMap[fileInfo.filename]);
  10400. } // ignore empty content
  10401. if (inputSource === undefined) {
  10402. return;
  10403. }
  10404. inputSource = inputSource.substring(0, index);
  10405. sourceLines = inputSource.split('\n');
  10406. sourceColumns = sourceLines[sourceLines.length - 1];
  10407. }
  10408. lines = chunk.split('\n');
  10409. columns = lines[lines.length - 1];
  10410. if (fileInfo && fileInfo.filename) {
  10411. if (!mapLines) {
  10412. this._sourceMapGenerator.addMapping({
  10413. generated: {
  10414. line: this._lineNumber + 1,
  10415. column: this._column
  10416. },
  10417. original: {
  10418. line: sourceLines.length,
  10419. column: sourceColumns.length
  10420. },
  10421. source: this.normalizeFilename(fileInfo.filename)
  10422. });
  10423. } else {
  10424. for (i = 0; i < lines.length; i++) {
  10425. this._sourceMapGenerator.addMapping({
  10426. generated: {
  10427. line: this._lineNumber + i + 1,
  10428. column: i === 0 ? this._column : 0
  10429. },
  10430. original: {
  10431. line: sourceLines.length + i,
  10432. column: i === 0 ? sourceColumns.length : 0
  10433. },
  10434. source: this.normalizeFilename(fileInfo.filename)
  10435. });
  10436. }
  10437. }
  10438. }
  10439. if (lines.length === 1) {
  10440. this._column += columns.length;
  10441. } else {
  10442. this._lineNumber += lines.length - 1;
  10443. this._column = columns.length;
  10444. }
  10445. this._css.push(chunk);
  10446. }
  10447. }, {
  10448. key: "isEmpty",
  10449. value: function isEmpty() {
  10450. return this._css.length === 0;
  10451. }
  10452. }, {
  10453. key: "toCSS",
  10454. value: function toCSS(context) {
  10455. this._sourceMapGenerator = new this._sourceMapGeneratorConstructor({
  10456. file: this._outputFilename,
  10457. sourceRoot: null
  10458. });
  10459. if (this._outputSourceFiles) {
  10460. for (var filename in this._contentsMap) {
  10461. if (this._contentsMap.hasOwnProperty(filename)) {
  10462. var source = this._contentsMap[filename];
  10463. if (this._contentsIgnoredCharsMap[filename]) {
  10464. source = source.slice(this._contentsIgnoredCharsMap[filename]);
  10465. }
  10466. this._sourceMapGenerator.setSourceContent(this.normalizeFilename(filename), source);
  10467. }
  10468. }
  10469. }
  10470. this._rootNode.genCSS(context, this);
  10471. if (this._css.length > 0) {
  10472. var sourceMapURL;
  10473. var sourceMapContent = JSON.stringify(this._sourceMapGenerator.toJSON());
  10474. if (this.sourceMapURL) {
  10475. sourceMapURL = this.sourceMapURL;
  10476. } else if (this._sourceMapFilename) {
  10477. sourceMapURL = this._sourceMapFilename;
  10478. }
  10479. this.sourceMapURL = sourceMapURL;
  10480. this.sourceMap = sourceMapContent;
  10481. }
  10482. return this._css.join('');
  10483. }
  10484. }]);
  10485. return SourceMapOutput;
  10486. }();
  10487. return SourceMapOutput;
  10488. });
  10489. var sourceMapBuilder = (function (SourceMapOutput, environment) {
  10490. var SourceMapBuilder =
  10491. /*#__PURE__*/
  10492. function () {
  10493. function SourceMapBuilder(options) {
  10494. _classCallCheck(this, SourceMapBuilder);
  10495. this.options = options;
  10496. }
  10497. _createClass(SourceMapBuilder, [{
  10498. key: "toCSS",
  10499. value: function toCSS(rootNode, options, imports) {
  10500. var sourceMapOutput = new SourceMapOutput({
  10501. contentsIgnoredCharsMap: imports.contentsIgnoredChars,
  10502. rootNode,
  10503. contentsMap: imports.contents,
  10504. sourceMapFilename: this.options.sourceMapFilename,
  10505. sourceMapURL: this.options.sourceMapURL,
  10506. outputFilename: this.options.sourceMapOutputFilename,
  10507. sourceMapBasepath: this.options.sourceMapBasepath,
  10508. sourceMapRootpath: this.options.sourceMapRootpath,
  10509. outputSourceFiles: this.options.outputSourceFiles,
  10510. sourceMapGenerator: this.options.sourceMapGenerator,
  10511. sourceMapFileInline: this.options.sourceMapFileInline
  10512. });
  10513. var css = sourceMapOutput.toCSS(options);
  10514. this.sourceMap = sourceMapOutput.sourceMap;
  10515. this.sourceMapURL = sourceMapOutput.sourceMapURL;
  10516. if (this.options.sourceMapInputFilename) {
  10517. this.sourceMapInputFilename = sourceMapOutput.normalizeFilename(this.options.sourceMapInputFilename);
  10518. }
  10519. if (this.options.sourceMapBasepath !== undefined && this.sourceMapURL !== undefined) {
  10520. this.sourceMapURL = sourceMapOutput.removeBasepath(this.sourceMapURL);
  10521. }
  10522. return css + this.getCSSAppendage();
  10523. }
  10524. }, {
  10525. key: "getCSSAppendage",
  10526. value: function getCSSAppendage() {
  10527. var sourceMapURL = this.sourceMapURL;
  10528. if (this.options.sourceMapFileInline) {
  10529. if (this.sourceMap === undefined) {
  10530. return '';
  10531. }
  10532. sourceMapURL = `data:application/json;base64,${environment.encodeBase64(this.sourceMap)}`;
  10533. }
  10534. if (sourceMapURL) {
  10535. return `/*# sourceMappingURL=${sourceMapURL} */`;
  10536. }
  10537. return '';
  10538. }
  10539. }, {
  10540. key: "getExternalSourceMap",
  10541. value: function getExternalSourceMap() {
  10542. return this.sourceMap;
  10543. }
  10544. }, {
  10545. key: "setExternalSourceMap",
  10546. value: function setExternalSourceMap(sourceMap) {
  10547. this.sourceMap = sourceMap;
  10548. }
  10549. }, {
  10550. key: "isInline",
  10551. value: function isInline() {
  10552. return this.options.sourceMapFileInline;
  10553. }
  10554. }, {
  10555. key: "getSourceMapURL",
  10556. value: function getSourceMapURL() {
  10557. return this.sourceMapURL;
  10558. }
  10559. }, {
  10560. key: "getOutputFilename",
  10561. value: function getOutputFilename() {
  10562. return this.options.sourceMapOutputFilename;
  10563. }
  10564. }, {
  10565. key: "getInputFilename",
  10566. value: function getInputFilename() {
  10567. return this.sourceMapInputFilename;
  10568. }
  10569. }]);
  10570. return SourceMapBuilder;
  10571. }();
  10572. return SourceMapBuilder;
  10573. });
  10574. var transformTree = (function (root) {
  10575. var options = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};
  10576. var evaldRoot;
  10577. var variables = options.variables;
  10578. var evalEnv = new contexts.Eval(options); //
  10579. // Allows setting variables with a hash, so:
  10580. //
  10581. // `{ color: new tree.Color('#f01') }` will become:
  10582. //
  10583. // new tree.Declaration('@color',
  10584. // new tree.Value([
  10585. // new tree.Expression([
  10586. // new tree.Color('#f01')
  10587. // ])
  10588. // ])
  10589. // )
  10590. //
  10591. if (typeof variables === 'object' && !Array.isArray(variables)) {
  10592. variables = Object.keys(variables).map(function (k) {
  10593. var value = variables[k];
  10594. if (!(value instanceof tree.Value)) {
  10595. if (!(value instanceof tree.Expression)) {
  10596. value = new tree.Expression([value]);
  10597. }
  10598. value = new tree.Value([value]);
  10599. }
  10600. return new tree.Declaration(`@${k}`, value, false, null, 0);
  10601. });
  10602. evalEnv.frames = [new tree.Ruleset(null, variables)];
  10603. }
  10604. var visitors$1 = [new visitors.JoinSelectorVisitor(), new visitors.MarkVisibleSelectorsVisitor(true), new visitors.ExtendVisitor(), new visitors.ToCSSVisitor({
  10605. compress: Boolean(options.compress)
  10606. })];
  10607. var preEvalVisitors = [];
  10608. var v;
  10609. var visitorIterator;
  10610. /**
  10611. * first() / get() allows visitors to be added while visiting
  10612. *
  10613. * @todo Add scoping for visitors just like functions for @plugin; right now they're global
  10614. */
  10615. if (options.pluginManager) {
  10616. visitorIterator = options.pluginManager.visitor();
  10617. for (var i = 0; i < 2; i++) {
  10618. visitorIterator.first();
  10619. while (v = visitorIterator.get()) {
  10620. if (v.isPreEvalVisitor) {
  10621. if (i === 0 || preEvalVisitors.indexOf(v) === -1) {
  10622. preEvalVisitors.push(v);
  10623. v.run(root);
  10624. }
  10625. } else {
  10626. if (i === 0 || visitors$1.indexOf(v) === -1) {
  10627. if (v.isPreVisitor) {
  10628. visitors$1.unshift(v);
  10629. } else {
  10630. visitors$1.push(v);
  10631. }
  10632. }
  10633. }
  10634. }
  10635. }
  10636. }
  10637. evaldRoot = root.eval(evalEnv);
  10638. for (var i = 0; i < visitors$1.length; i++) {
  10639. visitors$1[i].run(evaldRoot);
  10640. } // Run any remaining visitors added after eval pass
  10641. if (options.pluginManager) {
  10642. visitorIterator.first();
  10643. while (v = visitorIterator.get()) {
  10644. if (visitors$1.indexOf(v) === -1 && preEvalVisitors.indexOf(v) === -1) {
  10645. v.run(evaldRoot);
  10646. }
  10647. }
  10648. }
  10649. return evaldRoot;
  10650. });
  10651. var parseTree = (function (SourceMapBuilder) {
  10652. var ParseTree =
  10653. /*#__PURE__*/
  10654. function () {
  10655. function ParseTree(root, imports) {
  10656. _classCallCheck(this, ParseTree);
  10657. this.root = root;
  10658. this.imports = imports;
  10659. }
  10660. _createClass(ParseTree, [{
  10661. key: "toCSS",
  10662. value: function toCSS(options) {
  10663. var evaldRoot;
  10664. var result = {};
  10665. var sourceMapBuilder;
  10666. try {
  10667. evaldRoot = transformTree(this.root, options);
  10668. } catch (e) {
  10669. throw new LessError(e, this.imports);
  10670. }
  10671. try {
  10672. var compress = Boolean(options.compress);
  10673. if (compress) {
  10674. logger.warn('The compress option has been deprecated. ' + 'We recommend you use a dedicated css minifier, for instance see less-plugin-clean-css.');
  10675. }
  10676. var toCSSOptions = {
  10677. compress,
  10678. dumpLineNumbers: options.dumpLineNumbers,
  10679. strictUnits: Boolean(options.strictUnits),
  10680. numPrecision: 8
  10681. };
  10682. if (options.sourceMap) {
  10683. sourceMapBuilder = new SourceMapBuilder(options.sourceMap);
  10684. result.css = sourceMapBuilder.toCSS(evaldRoot, toCSSOptions, this.imports);
  10685. } else {
  10686. result.css = evaldRoot.toCSS(toCSSOptions);
  10687. }
  10688. } catch (e) {
  10689. throw new LessError(e, this.imports);
  10690. }
  10691. if (options.pluginManager) {
  10692. var postProcessors = options.pluginManager.getPostProcessors();
  10693. for (var i = 0; i < postProcessors.length; i++) {
  10694. result.css = postProcessors[i].process(result.css, {
  10695. sourceMap: sourceMapBuilder,
  10696. options,
  10697. imports: this.imports
  10698. });
  10699. }
  10700. }
  10701. if (options.sourceMap) {
  10702. result.map = sourceMapBuilder.getExternalSourceMap();
  10703. }
  10704. result.imports = [];
  10705. for (var file in this.imports.files) {
  10706. if (this.imports.files.hasOwnProperty(file) && file !== this.imports.rootFilename) {
  10707. result.imports.push(file);
  10708. }
  10709. }
  10710. return result;
  10711. }
  10712. }]);
  10713. return ParseTree;
  10714. }();
  10715. return ParseTree;
  10716. });
  10717. var importManager = (function (environment) {
  10718. // FileInfo = {
  10719. // 'rewriteUrls' - option - whether to adjust URL's to be relative
  10720. // 'filename' - full resolved filename of current file
  10721. // 'rootpath' - path to append to normal URLs for this node
  10722. // 'currentDirectory' - path to the current file, absolute
  10723. // 'rootFilename' - filename of the base file
  10724. // 'entryPath' - absolute path to the entry file
  10725. // 'reference' - whether the file should not be output and only output parts that are referenced
  10726. var ImportManager =
  10727. /*#__PURE__*/
  10728. function () {
  10729. function ImportManager(less, context, rootFileInfo) {
  10730. _classCallCheck(this, ImportManager);
  10731. this.less = less;
  10732. this.rootFilename = rootFileInfo.filename;
  10733. this.paths = context.paths || []; // Search paths, when importing
  10734. this.contents = {}; // map - filename to contents of all the files
  10735. this.contentsIgnoredChars = {}; // map - filename to lines at the beginning of each file to ignore
  10736. this.mime = context.mime;
  10737. this.error = null;
  10738. this.context = context; // Deprecated? Unused outside of here, could be useful.
  10739. this.queue = []; // Files which haven't been imported yet
  10740. this.files = {}; // Holds the imported parse trees.
  10741. }
  10742. /**
  10743. * Add an import to be imported
  10744. * @param path - the raw path
  10745. * @param tryAppendExtension - whether to try appending a file extension (.less or .js if the path has no extension)
  10746. * @param currentFileInfo - the current file info (used for instance to work out relative paths)
  10747. * @param importOptions - import options
  10748. * @param callback - callback for when it is imported
  10749. */
  10750. _createClass(ImportManager, [{
  10751. key: "push",
  10752. value: function push(path, tryAppendExtension, currentFileInfo, importOptions, callback) {
  10753. var importManager = this;
  10754. var pluginLoader = this.context.pluginManager.Loader;
  10755. this.queue.push(path);
  10756. var fileParsedFunc = function fileParsedFunc(e, root, fullPath) {
  10757. importManager.queue.splice(importManager.queue.indexOf(path), 1); // Remove the path from the queue
  10758. var importedEqualsRoot = fullPath === importManager.rootFilename;
  10759. if (importOptions.optional && e) {
  10760. callback(null, {
  10761. rules: []
  10762. }, false, null);
  10763. logger.info(`The file ${fullPath} was skipped because it was not found and the import was marked optional.`);
  10764. } else {
  10765. // Inline imports aren't cached here.
  10766. // If we start to cache them, please make sure they won't conflict with non-inline imports of the
  10767. // same name as they used to do before this comment and the condition below have been added.
  10768. if (!importManager.files[fullPath] && !importOptions.inline) {
  10769. importManager.files[fullPath] = {
  10770. root,
  10771. options: importOptions
  10772. };
  10773. }
  10774. if (e && !importManager.error) {
  10775. importManager.error = e;
  10776. }
  10777. callback(e, root, importedEqualsRoot, fullPath);
  10778. }
  10779. };
  10780. var newFileInfo = {
  10781. rewriteUrls: this.context.rewriteUrls,
  10782. entryPath: currentFileInfo.entryPath,
  10783. rootpath: currentFileInfo.rootpath,
  10784. rootFilename: currentFileInfo.rootFilename
  10785. };
  10786. var fileManager = environment.getFileManager(path, currentFileInfo.currentDirectory, this.context, environment);
  10787. if (!fileManager) {
  10788. fileParsedFunc({
  10789. message: `Could not find a file-manager for ${path}`
  10790. });
  10791. return;
  10792. }
  10793. var loadFileCallback = function loadFileCallback(loadedFile) {
  10794. var plugin;
  10795. var resolvedFilename = loadedFile.filename;
  10796. var contents = loadedFile.contents.replace(/^\uFEFF/, ''); // Pass on an updated rootpath if path of imported file is relative and file
  10797. // is in a (sub|sup) directory
  10798. //
  10799. // Examples:
  10800. // - If path of imported file is 'module/nav/nav.less' and rootpath is 'less/',
  10801. // then rootpath should become 'less/module/nav/'
  10802. // - If path of imported file is '../mixins.less' and rootpath is 'less/',
  10803. // then rootpath should become 'less/../'
  10804. newFileInfo.currentDirectory = fileManager.getPath(resolvedFilename);
  10805. if (newFileInfo.rewriteUrls) {
  10806. newFileInfo.rootpath = fileManager.join(importManager.context.rootpath || '', fileManager.pathDiff(newFileInfo.currentDirectory, newFileInfo.entryPath));
  10807. if (!fileManager.isPathAbsolute(newFileInfo.rootpath) && fileManager.alwaysMakePathsAbsolute()) {
  10808. newFileInfo.rootpath = fileManager.join(newFileInfo.entryPath, newFileInfo.rootpath);
  10809. }
  10810. }
  10811. newFileInfo.filename = resolvedFilename;
  10812. var newEnv = new contexts.Parse(importManager.context);
  10813. newEnv.processImports = false;
  10814. importManager.contents[resolvedFilename] = contents;
  10815. if (currentFileInfo.reference || importOptions.reference) {
  10816. newFileInfo.reference = true;
  10817. }
  10818. if (importOptions.isPlugin) {
  10819. plugin = pluginLoader.evalPlugin(contents, newEnv, importManager, importOptions.pluginArgs, newFileInfo);
  10820. if (plugin instanceof LessError) {
  10821. fileParsedFunc(plugin, null, resolvedFilename);
  10822. } else {
  10823. fileParsedFunc(null, plugin, resolvedFilename);
  10824. }
  10825. } else if (importOptions.inline) {
  10826. fileParsedFunc(null, contents, resolvedFilename);
  10827. } else {
  10828. // import (multiple) parse trees apparently get altered and can't be cached.
  10829. // TODO: investigate why this is
  10830. if (importManager.files[resolvedFilename] && !importManager.files[resolvedFilename].options.multiple && !importOptions.multiple) {
  10831. fileParsedFunc(null, importManager.files[resolvedFilename].root, resolvedFilename);
  10832. } else {
  10833. new Parser(newEnv, importManager, newFileInfo).parse(contents, function (e, root) {
  10834. fileParsedFunc(e, root, resolvedFilename);
  10835. });
  10836. }
  10837. }
  10838. };
  10839. var promise;
  10840. var context = clone(this.context);
  10841. if (tryAppendExtension) {
  10842. context.ext = importOptions.isPlugin ? '.js' : '.less';
  10843. }
  10844. if (importOptions.isPlugin) {
  10845. context.mime = 'application/javascript';
  10846. promise = pluginLoader.loadPlugin(path, currentFileInfo.currentDirectory, context, environment, fileManager);
  10847. } else {
  10848. promise = fileManager.loadFile(path, currentFileInfo.currentDirectory, context, environment, function (err, loadedFile) {
  10849. if (err) {
  10850. fileParsedFunc(err);
  10851. } else {
  10852. loadFileCallback(loadedFile);
  10853. }
  10854. });
  10855. }
  10856. if (promise) {
  10857. promise.then(loadFileCallback, fileParsedFunc);
  10858. }
  10859. }
  10860. }]);
  10861. return ImportManager;
  10862. }();
  10863. return ImportManager;
  10864. });
  10865. var Render = (function (environment, ParseTree, ImportManager) {
  10866. var render = function render(input, options, callback) {
  10867. if (typeof options === 'function') {
  10868. callback = options;
  10869. options = copyOptions(this.options, {});
  10870. } else {
  10871. options = copyOptions(this.options, options || {});
  10872. }
  10873. if (!callback) {
  10874. var self = this;
  10875. return new Promise(function (resolve, reject) {
  10876. render.call(self, input, options, function (err, output) {
  10877. if (err) {
  10878. reject(err);
  10879. } else {
  10880. resolve(output);
  10881. }
  10882. });
  10883. });
  10884. } else {
  10885. this.parse(input, options, function (err, root, imports, options) {
  10886. if (err) {
  10887. return callback(err);
  10888. }
  10889. var result;
  10890. try {
  10891. var parseTree = new ParseTree(root, imports);
  10892. result = parseTree.toCSS(options);
  10893. } catch (err) {
  10894. return callback(err);
  10895. }
  10896. callback(null, result);
  10897. });
  10898. }
  10899. };
  10900. return render;
  10901. });
  10902. /**
  10903. * Plugin Manager
  10904. */
  10905. var PluginManager =
  10906. /*#__PURE__*/
  10907. function () {
  10908. function PluginManager(less) {
  10909. _classCallCheck(this, PluginManager);
  10910. this.less = less;
  10911. this.visitors = [];
  10912. this.preProcessors = [];
  10913. this.postProcessors = [];
  10914. this.installedPlugins = [];
  10915. this.fileManagers = [];
  10916. this.iterator = -1;
  10917. this.pluginCache = {};
  10918. this.Loader = new less.PluginLoader(less);
  10919. }
  10920. /**
  10921. * Adds all the plugins in the array
  10922. * @param {Array} plugins
  10923. */
  10924. _createClass(PluginManager, [{
  10925. key: "addPlugins",
  10926. value: function addPlugins(plugins) {
  10927. if (plugins) {
  10928. for (var i = 0; i < plugins.length; i++) {
  10929. this.addPlugin(plugins[i]);
  10930. }
  10931. }
  10932. }
  10933. /**
  10934. *
  10935. * @param plugin
  10936. * @param {String} filename
  10937. */
  10938. }, {
  10939. key: "addPlugin",
  10940. value: function addPlugin(plugin, filename, functionRegistry) {
  10941. this.installedPlugins.push(plugin);
  10942. if (filename) {
  10943. this.pluginCache[filename] = plugin;
  10944. }
  10945. if (plugin.install) {
  10946. plugin.install(this.less, this, functionRegistry || this.less.functions.functionRegistry);
  10947. }
  10948. }
  10949. /**
  10950. *
  10951. * @param filename
  10952. */
  10953. }, {
  10954. key: "get",
  10955. value: function get(filename) {
  10956. return this.pluginCache[filename];
  10957. }
  10958. /**
  10959. * Adds a visitor. The visitor object has options on itself to determine
  10960. * when it should run.
  10961. * @param visitor
  10962. */
  10963. }, {
  10964. key: "addVisitor",
  10965. value: function addVisitor(visitor) {
  10966. this.visitors.push(visitor);
  10967. }
  10968. /**
  10969. * Adds a pre processor object
  10970. * @param {object} preProcessor
  10971. * @param {number} priority - guidelines 1 = before import, 1000 = import, 2000 = after import
  10972. */
  10973. }, {
  10974. key: "addPreProcessor",
  10975. value: function addPreProcessor(preProcessor, priority) {
  10976. var indexToInsertAt;
  10977. for (indexToInsertAt = 0; indexToInsertAt < this.preProcessors.length; indexToInsertAt++) {
  10978. if (this.preProcessors[indexToInsertAt].priority >= priority) {
  10979. break;
  10980. }
  10981. }
  10982. this.preProcessors.splice(indexToInsertAt, 0, {
  10983. preProcessor,
  10984. priority
  10985. });
  10986. }
  10987. /**
  10988. * Adds a post processor object
  10989. * @param {object} postProcessor
  10990. * @param {number} priority - guidelines 1 = before compression, 1000 = compression, 2000 = after compression
  10991. */
  10992. }, {
  10993. key: "addPostProcessor",
  10994. value: function addPostProcessor(postProcessor, priority) {
  10995. var indexToInsertAt;
  10996. for (indexToInsertAt = 0; indexToInsertAt < this.postProcessors.length; indexToInsertAt++) {
  10997. if (this.postProcessors[indexToInsertAt].priority >= priority) {
  10998. break;
  10999. }
  11000. }
  11001. this.postProcessors.splice(indexToInsertAt, 0, {
  11002. postProcessor,
  11003. priority
  11004. });
  11005. }
  11006. /**
  11007. *
  11008. * @param manager
  11009. */
  11010. }, {
  11011. key: "addFileManager",
  11012. value: function addFileManager(manager) {
  11013. this.fileManagers.push(manager);
  11014. }
  11015. /**
  11016. *
  11017. * @returns {Array}
  11018. * @private
  11019. */
  11020. }, {
  11021. key: "getPreProcessors",
  11022. value: function getPreProcessors() {
  11023. var preProcessors = [];
  11024. for (var i = 0; i < this.preProcessors.length; i++) {
  11025. preProcessors.push(this.preProcessors[i].preProcessor);
  11026. }
  11027. return preProcessors;
  11028. }
  11029. /**
  11030. *
  11031. * @returns {Array}
  11032. * @private
  11033. */
  11034. }, {
  11035. key: "getPostProcessors",
  11036. value: function getPostProcessors() {
  11037. var postProcessors = [];
  11038. for (var i = 0; i < this.postProcessors.length; i++) {
  11039. postProcessors.push(this.postProcessors[i].postProcessor);
  11040. }
  11041. return postProcessors;
  11042. }
  11043. /**
  11044. *
  11045. * @returns {Array}
  11046. * @private
  11047. */
  11048. }, {
  11049. key: "getVisitors",
  11050. value: function getVisitors() {
  11051. return this.visitors;
  11052. }
  11053. }, {
  11054. key: "visitor",
  11055. value: function visitor() {
  11056. var self = this;
  11057. return {
  11058. first: function first() {
  11059. self.iterator = -1;
  11060. return self.visitors[self.iterator];
  11061. },
  11062. get: function get() {
  11063. self.iterator += 1;
  11064. return self.visitors[self.iterator];
  11065. }
  11066. };
  11067. }
  11068. /**
  11069. *
  11070. * @returns {Array}
  11071. * @private
  11072. */
  11073. }, {
  11074. key: "getFileManagers",
  11075. value: function getFileManagers() {
  11076. return this.fileManagers;
  11077. }
  11078. }]);
  11079. return PluginManager;
  11080. }();
  11081. var pm;
  11082. function PluginManagerFactory(less, newFactory) {
  11083. if (newFactory || !pm) {
  11084. pm = new PluginManager(less);
  11085. }
  11086. return pm;
  11087. }
  11088. var Parse = (function (environment, ParseTree, ImportManager) {
  11089. var parse = function parse(input, options, callback) {
  11090. if (typeof options === 'function') {
  11091. callback = options;
  11092. options = copyOptions(this.options, {});
  11093. } else {
  11094. options = copyOptions(this.options, options || {});
  11095. }
  11096. if (!callback) {
  11097. var self = this;
  11098. return new Promise(function (resolve, reject) {
  11099. parse.call(self, input, options, function (err, output) {
  11100. if (err) {
  11101. reject(err);
  11102. } else {
  11103. resolve(output);
  11104. }
  11105. });
  11106. });
  11107. } else {
  11108. var context;
  11109. var rootFileInfo;
  11110. var pluginManager = new PluginManagerFactory(this, !options.reUsePluginManager);
  11111. options.pluginManager = pluginManager;
  11112. context = new contexts.Parse(options);
  11113. if (options.rootFileInfo) {
  11114. rootFileInfo = options.rootFileInfo;
  11115. } else {
  11116. var filename = options.filename || 'input';
  11117. var entryPath = filename.replace(/[^\/\\]*$/, '');
  11118. rootFileInfo = {
  11119. filename,
  11120. rewriteUrls: context.rewriteUrls,
  11121. rootpath: context.rootpath || '',
  11122. currentDirectory: entryPath,
  11123. entryPath,
  11124. rootFilename: filename
  11125. }; // add in a missing trailing slash
  11126. if (rootFileInfo.rootpath && rootFileInfo.rootpath.slice(-1) !== '/') {
  11127. rootFileInfo.rootpath += '/';
  11128. }
  11129. }
  11130. var imports = new ImportManager(this, context, rootFileInfo);
  11131. this.importManager = imports; // TODO: allow the plugins to be just a list of paths or names
  11132. // Do an async plugin queue like lessc
  11133. if (options.plugins) {
  11134. options.plugins.forEach(function (plugin) {
  11135. var evalResult;
  11136. var contents;
  11137. if (plugin.fileContent) {
  11138. contents = plugin.fileContent.replace(/^\uFEFF/, '');
  11139. evalResult = pluginManager.Loader.evalPlugin(contents, context, imports, plugin.options, plugin.filename);
  11140. if (evalResult instanceof LessError) {
  11141. return callback(evalResult);
  11142. }
  11143. } else {
  11144. pluginManager.addPlugin(plugin);
  11145. }
  11146. });
  11147. }
  11148. new Parser(context, imports, rootFileInfo).parse(input, function (e, root) {
  11149. if (e) {
  11150. return callback(e);
  11151. }
  11152. callback(null, root, imports, options);
  11153. }, options);
  11154. }
  11155. };
  11156. return parse;
  11157. });
  11158. var createFromEnvironment = (function (environment, fileManagers) {
  11159. /**
  11160. * @todo
  11161. * This original code could be improved quite a bit.
  11162. * Many classes / modules currently add side-effects / mutations to passed in objects,
  11163. * which makes it hard to refactor and reason about.
  11164. */
  11165. environment = new environment$1(environment, fileManagers);
  11166. var SourceMapOutput = sourceMapOutput(environment);
  11167. var SourceMapBuilder = sourceMapBuilder(SourceMapOutput, environment);
  11168. var ParseTree = parseTree(SourceMapBuilder);
  11169. var ImportManager = importManager(environment);
  11170. var render = Render(environment, ParseTree);
  11171. var parse = Parse(environment, ParseTree, ImportManager);
  11172. var functions = Functions(environment);
  11173. /**
  11174. * @todo
  11175. * This root properties / methods need to be organized.
  11176. * It's not clear what should / must be public and why.
  11177. */
  11178. var initial = {
  11179. version: [3, 10, 3],
  11180. data,
  11181. tree,
  11182. Environment: environment$1,
  11183. AbstractFileManager,
  11184. AbstractPluginLoader,
  11185. environment,
  11186. visitors,
  11187. Parser,
  11188. functions,
  11189. contexts,
  11190. SourceMapOutput,
  11191. SourceMapBuilder,
  11192. ParseTree,
  11193. ImportManager,
  11194. render,
  11195. parse,
  11196. LessError,
  11197. transformTree,
  11198. utils,
  11199. PluginManager: PluginManagerFactory,
  11200. logger
  11201. }; // Create a public API
  11202. var ctor = function ctor(t) {
  11203. return function () {
  11204. for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
  11205. args[_key] = arguments[_key];
  11206. }
  11207. return _construct(t, args);
  11208. };
  11209. };
  11210. var t;
  11211. var api = Object.create(initial);
  11212. for (var n in initial.tree) {
  11213. /* eslint guard-for-in: 0 */
  11214. t = initial.tree[n];
  11215. if (typeof t === 'function') {
  11216. api[n.toLowerCase()] = ctor(t);
  11217. } else {
  11218. api[n] = Object.create(null);
  11219. for (var o in t) {
  11220. /* eslint guard-for-in: 0 */
  11221. api[n][o.toLowerCase()] = ctor(t[o]);
  11222. }
  11223. }
  11224. }
  11225. return api;
  11226. });
  11227. function createCommonjsModule(fn, module) {
  11228. return module = { exports: {} }, fn(module, module.exports), module.exports;
  11229. }
  11230. var lesscHelper = createCommonjsModule(function (module, exports) {
  11231. // lessc_helper.js
  11232. //
  11233. // helper functions for lessc
  11234. var lessc_helper = {
  11235. // Stylize a string
  11236. stylize: function stylize(str, style) {
  11237. var styles = {
  11238. 'reset': [0, 0],
  11239. 'bold': [1, 22],
  11240. 'inverse': [7, 27],
  11241. 'underline': [4, 24],
  11242. 'yellow': [33, 39],
  11243. 'green': [32, 39],
  11244. 'red': [31, 39],
  11245. 'grey': [90, 39]
  11246. };
  11247. return `\x1b[${styles[style][0]}m${str}\x1b[${styles[style][1]}m`;
  11248. },
  11249. // Print command line options
  11250. printUsage: function printUsage() {
  11251. console.log('usage: lessc [option option=parameter ...] <source> [destination]');
  11252. console.log('');
  11253. console.log('If source is set to `-\' (dash or hyphen-minus), input is read from stdin.');
  11254. console.log('');
  11255. console.log('options:');
  11256. console.log(' -h, --help Prints help (this message) and exit.');
  11257. console.log(' --include-path=PATHS Sets include paths. Separated by `:\'. `;\' also supported on windows.');
  11258. console.log(' -M, --depends Outputs a makefile import dependency list to stdout.');
  11259. console.log(' --no-color Disables colorized output.');
  11260. console.log(' --ie-compat Enables IE8 compatibility checks.');
  11261. console.log(' --js Enables inline JavaScript in less files');
  11262. console.log(' -l, --lint Syntax check only (lint).');
  11263. console.log(' -s, --silent Suppresses output of error messages.');
  11264. console.log(' --strict-imports Forces evaluation of imports.');
  11265. console.log(' --insecure Allows imports from insecure https hosts.');
  11266. console.log(' -v, --version Prints version number and exit.');
  11267. console.log(' --verbose Be verbose.');
  11268. console.log(' --source-map[=FILENAME] Outputs a v3 sourcemap to the filename (or output filename.map).');
  11269. console.log(' --source-map-rootpath=X Adds this path onto the sourcemap filename and less file paths.');
  11270. console.log(' --source-map-basepath=X Sets sourcemap base path, defaults to current working directory.');
  11271. console.log(' --source-map-include-source Puts the less files into the map instead of referencing them.');
  11272. console.log(' --source-map-inline Puts the map (and any less files) as a base64 data uri into the output css file.');
  11273. console.log(' --source-map-url=URL Sets a custom URL to map file, for sourceMappingURL comment');
  11274. console.log(' in generated CSS file.');
  11275. console.log(' -rp, --rootpath=URL Sets rootpath for url rewriting in relative imports and urls');
  11276. console.log(' Works with or without the relative-urls option.');
  11277. console.log(' -ru=, --rewrite-urls= Rewrites URLs to make them relative to the base less file.');
  11278. console.log(' all|local|off \'all\' rewrites all URLs, \'local\' just those starting with a \'.\'');
  11279. console.log('');
  11280. console.log(' -m=, --math=');
  11281. console.log(' always Less will eagerly perform math operations always.');
  11282. console.log(' parens-division Math performed except for division (/) operator');
  11283. console.log(' parens | strict Math only performed inside parentheses');
  11284. console.log(' strict-legacy Parens required in very strict terms (legacy --strict-math)');
  11285. console.log('');
  11286. console.log(' -su=on|off Allows mixed units, e.g. 1px+1em or 1px*1px which have units');
  11287. console.log(' --strict-units=on|off that cannot be represented.');
  11288. console.log(' --global-var=\'VAR=VALUE\' Defines a variable that can be referenced by the file.');
  11289. console.log(' --modify-var=\'VAR=VALUE\' Modifies a variable already declared in the file.');
  11290. console.log(' --url-args=\'QUERYSTRING\' Adds params into url tokens (e.g. 42, cb=42 or \'a=1&b=2\')');
  11291. console.log(' --plugin=PLUGIN=OPTIONS Loads a plugin. You can also omit the --plugin= if the plugin begins');
  11292. console.log(' less-plugin. E.g. the clean css plugin is called less-plugin-clean-css');
  11293. console.log(' once installed (npm install less-plugin-clean-css), use either with');
  11294. console.log(' --plugin=less-plugin-clean-css or just --clean-css');
  11295. console.log(' specify options afterwards e.g. --plugin=less-plugin-clean-css="advanced"');
  11296. console.log(' or --clean-css="advanced"');
  11297. console.log('');
  11298. console.log('-------------------------- Deprecated ----------------');
  11299. console.log(' -sm=on|off Legacy parens-only math. Use --math');
  11300. console.log(' --strict-math=on|off ');
  11301. console.log('');
  11302. console.log(' --line-numbers=TYPE Outputs filename and line numbers.');
  11303. console.log(' TYPE can be either \'comments\', which will output');
  11304. console.log(' the debug info within comments, \'mediaquery\'');
  11305. console.log(' that will output the information within a fake');
  11306. console.log(' media query which is compatible with the SASS');
  11307. console.log(' format, and \'all\' which will do both.');
  11308. console.log(' -x, --compress Compresses output by removing some whitespaces.');
  11309. console.log(' We recommend you use a dedicated minifer like less-plugin-clean-css');
  11310. console.log('');
  11311. console.log('Report bugs to: http://github.com/less/less.js/issues');
  11312. console.log('Home page: <http://lesscss.org/>');
  11313. }
  11314. }; // Exports helper functions
  11315. for (var h in lessc_helper) {
  11316. if (lessc_helper.hasOwnProperty(h)) {
  11317. exports[h] = lessc_helper[h];
  11318. }
  11319. }
  11320. });
  11321. /**
  11322. * Node Plugin Loader
  11323. */
  11324. var PluginLoader =
  11325. /*#__PURE__*/
  11326. function (_AbstractPluginLoader) {
  11327. _inherits(PluginLoader, _AbstractPluginLoader);
  11328. function PluginLoader(less) {
  11329. var _this;
  11330. _classCallCheck(this, PluginLoader);
  11331. _this = _possibleConstructorReturn(this, _getPrototypeOf(PluginLoader).call(this));
  11332. _this.less = less;
  11333. _this.require = function (prefix) {
  11334. prefix = path.dirname(prefix);
  11335. return function (id) {
  11336. var str = id.substr(0, 2);
  11337. if (str === '..' || str === './') {
  11338. return require(path.join(prefix, id));
  11339. } else {
  11340. return require(id);
  11341. }
  11342. };
  11343. };
  11344. return _this;
  11345. }
  11346. _createClass(PluginLoader, [{
  11347. key: "loadPlugin",
  11348. value: function loadPlugin(filename, basePath, context, environment, fileManager) {
  11349. var prefix = filename.slice(0, 1);
  11350. var explicit = prefix === '.' || prefix === '/' || filename.slice(-3).toLowerCase() === '.js';
  11351. if (!explicit) {
  11352. context.prefixes = ['less-plugin-', ''];
  11353. }
  11354. return new Promise(function (fulfill, reject) {
  11355. fileManager.loadFile(filename, basePath, context, environment).then(function (data) {
  11356. try {
  11357. fulfill(data);
  11358. } catch (e) {
  11359. console.log(e);
  11360. reject(e);
  11361. }
  11362. }).catch(function (err) {
  11363. reject(err);
  11364. });
  11365. });
  11366. }
  11367. }]);
  11368. return PluginLoader;
  11369. }(AbstractPluginLoader);
  11370. // Export a new default each time
  11371. var defaultOptions = (function () {
  11372. return {
  11373. /* Inline Javascript - @plugin still allowed */
  11374. javascriptEnabled: false,
  11375. /* Outputs a makefile import dependency list to stdout. */
  11376. depends: false,
  11377. /* (DEPRECATED) Compress using less built-in compression.
  11378. * This does an okay job but does not utilise all the tricks of
  11379. * dedicated css compression. */
  11380. compress: false,
  11381. /* Runs the less parser and just reports errors without any output. */
  11382. lint: false,
  11383. /* Sets available include paths.
  11384. * If the file in an @import rule does not exist at that exact location,
  11385. * less will look for it at the location(s) passed to this option.
  11386. * You might use this for instance to specify a path to a library which
  11387. * you want to be referenced simply and relatively in the less files. */
  11388. paths: [],
  11389. /* color output in the terminal */
  11390. color: true,
  11391. /* The strictImports controls whether the compiler will allow an @import inside of either
  11392. * @media blocks or (a later addition) other selector blocks.
  11393. * See: https://github.com/less/less.js/issues/656 */
  11394. strictImports: false,
  11395. /* Allow Imports from Insecure HTTPS Hosts */
  11396. insecure: false,
  11397. /* Allows you to add a path to every generated import and url in your css.
  11398. * This does not affect less import statements that are processed, just ones
  11399. * that are left in the output css. */
  11400. rootpath: '',
  11401. /* By default URLs are kept as-is, so if you import a file in a sub-directory
  11402. * that references an image, exactly the same URL will be output in the css.
  11403. * This option allows you to re-write URL's in imported files so that the
  11404. * URL is always relative to the base imported file */
  11405. rewriteUrls: false,
  11406. /* How to process math
  11407. * 0 always - eagerly try to solve all operations
  11408. * 1 parens-division - require parens for division "/"
  11409. * 2 parens | strict - require parens for all operations
  11410. * 3 strict-legacy - legacy strict behavior (super-strict)
  11411. */
  11412. math: 0,
  11413. /* Without this option, less attempts to guess at the output unit when it does maths. */
  11414. strictUnits: false,
  11415. /* Effectively the declaration is put at the top of your base Less file,
  11416. * meaning it can be used but it also can be overridden if this variable
  11417. * is defined in the file. */
  11418. globalVars: null,
  11419. /* As opposed to the global variable option, this puts the declaration at the
  11420. * end of your base file, meaning it will override anything defined in your Less file. */
  11421. modifyVars: null,
  11422. /* This option allows you to specify a argument to go on to every URL. */
  11423. urlArgs: ''
  11424. };
  11425. });
  11426. var imageSize = (function (environment) {
  11427. function _imageSize(functionContext, filePathNode) {
  11428. var filePath = filePathNode.value;
  11429. var currentFileInfo = functionContext.currentFileInfo;
  11430. var currentDirectory = currentFileInfo.rewriteUrls ? currentFileInfo.currentDirectory : currentFileInfo.entryPath;
  11431. var fragmentStart = filePath.indexOf('#');
  11432. var fragment = '';
  11433. if (fragmentStart !== -1) {
  11434. fragment = filePath.slice(fragmentStart);
  11435. filePath = filePath.slice(0, fragmentStart);
  11436. }
  11437. var fileManager = environment.getFileManager(filePath, currentDirectory, functionContext.context, environment, true);
  11438. if (!fileManager) {
  11439. throw {
  11440. type: 'File',
  11441. message: `Can not set up FileManager for ${filePathNode}`
  11442. };
  11443. }
  11444. var fileSync = fileManager.loadFileSync(filePath, currentDirectory, functionContext.context, environment);
  11445. if (fileSync.error) {
  11446. throw fileSync.error;
  11447. }
  11448. var sizeOf = require('image-size');
  11449. return sizeOf(fileSync.filename);
  11450. }
  11451. var imageFunctions = {
  11452. 'image-size': function imageSize(filePathNode) {
  11453. var size = _imageSize(this, filePathNode);
  11454. return new Expression([new Dimension(size.width, 'px'), new Dimension(size.height, 'px')]);
  11455. },
  11456. 'image-width': function imageWidth(filePathNode) {
  11457. var size = _imageSize(this, filePathNode);
  11458. return new Dimension(size.width, 'px');
  11459. },
  11460. 'image-height': function imageHeight(filePathNode) {
  11461. var size = _imageSize(this, filePathNode);
  11462. return new Dimension(size.height, 'px');
  11463. }
  11464. };
  11465. functionRegistry.addMultiple(imageFunctions);
  11466. });
  11467. var less = createFromEnvironment(environment, [new FileManager(), new UrlFileManager()]); // allow people to create less with their own environment
  11468. less.createFromEnvironment = createFromEnvironment;
  11469. less.lesscHelper = lesscHelper;
  11470. less.PluginLoader = PluginLoader;
  11471. less.fs = fs$1;
  11472. less.FileManager = FileManager;
  11473. less.UrlFileManager = UrlFileManager; // Set up options
  11474. less.options = defaultOptions(); // provide image-size functionality
  11475. imageSize(less.environment);
  11476. var errno;
  11477. var mkdirp;
  11478. try {
  11479. errno = require('errno');
  11480. } catch (err) {
  11481. errno = null;
  11482. }
  11483. var pluginManager = new less.PluginManager(less);
  11484. var fileManager = new less.FileManager();
  11485. var plugins = [];
  11486. var queuePlugins = [];
  11487. var args = process.argv.slice(1);
  11488. var silent = false;
  11489. var verbose = false;
  11490. var options = less.options;
  11491. options.plugins = plugins;
  11492. options.reUsePluginManager = true;
  11493. var sourceMapOptions = {};
  11494. var continueProcessing = true; // Calling process.exit does not flush stdout always. Instead of exiting the process, we set the process' exitCode,
  11495. // close all handles and wait for the event loop to exit the process.
  11496. // @see https://github.com/nodejs/node/issues/6409
  11497. // Unfortunately, node 0.10.x does not support setting process.exitCode, so we need to call reallyExit() explicitly.
  11498. // @see https://nodejs.org/api/process.html#process_process_exitcode
  11499. // Additionally we also need to make sure that uncaughtExceptions are never swallowed.
  11500. // @see https://github.com/less/less.js/issues/2881
  11501. // This code can safely be removed if node 0.10.x is not supported anymore.
  11502. process.on('exit', function () {
  11503. process.reallyExit(process.exitCode);
  11504. });
  11505. process.on('uncaughtException', function (err) {
  11506. console.error(err);
  11507. process.exitCode = 1;
  11508. }); // This code will still be required because otherwise rejected promises would not be reported to the user
  11509. process.on('unhandledRejection', function (err) {
  11510. console.error(err);
  11511. process.exitCode = 1;
  11512. });
  11513. var checkArgFunc = function checkArgFunc(arg, option) {
  11514. if (!option) {
  11515. console.error(`${arg} option requires a parameter`);
  11516. continueProcessing = false;
  11517. process.exitCode = 1;
  11518. return false;
  11519. }
  11520. return true;
  11521. };
  11522. var checkBooleanArg = function checkBooleanArg(arg) {
  11523. var onOff = /^((on|t|true|y|yes)|(off|f|false|n|no))$/i.exec(arg);
  11524. if (!onOff) {
  11525. console.error(` unable to parse ${arg} as a boolean. use one of on/t/true/y/yes/off/f/false/n/no`);
  11526. continueProcessing = false;
  11527. process.exitCode = 1;
  11528. return false;
  11529. }
  11530. return Boolean(onOff[2]);
  11531. };
  11532. var parseVariableOption = function parseVariableOption(option, variables) {
  11533. var parts = option.split('=', 2);
  11534. variables[parts[0]] = parts[1];
  11535. };
  11536. var sourceMapFileInline = false;
  11537. function printUsage() {
  11538. less.lesscHelper.printUsage();
  11539. pluginManager.Loader.printUsage(plugins);
  11540. continueProcessing = false;
  11541. }
  11542. function render() {
  11543. if (!continueProcessing) {
  11544. return;
  11545. }
  11546. var input = args[1];
  11547. if (input && input != '-') {
  11548. input = path.resolve(process.cwd(), input);
  11549. }
  11550. var output = args[2];
  11551. var outputbase = args[2];
  11552. if (output) {
  11553. output = path.resolve(process.cwd(), output);
  11554. }
  11555. if (options.sourceMap) {
  11556. sourceMapOptions.sourceMapInputFilename = input;
  11557. if (!sourceMapOptions.sourceMapFullFilename) {
  11558. if (!output && !sourceMapFileInline) {
  11559. console.error('the sourcemap option only has an optional filename if the css filename is given');
  11560. console.error('consider adding --source-map-map-inline which embeds the sourcemap into the css');
  11561. process.exitCode = 1;
  11562. return;
  11563. } // its in the same directory, so always just the basename
  11564. if (output) {
  11565. sourceMapOptions.sourceMapOutputFilename = path.basename(output);
  11566. sourceMapOptions.sourceMapFullFilename = `${output}.map`;
  11567. } // its in the same directory, so always just the basename
  11568. if ('sourceMapFullFilename' in sourceMapOptions) {
  11569. sourceMapOptions.sourceMapFilename = path.basename(sourceMapOptions.sourceMapFullFilename);
  11570. }
  11571. } else if (options.sourceMap && !sourceMapFileInline) {
  11572. var mapFilename = path.resolve(process.cwd(), sourceMapOptions.sourceMapFullFilename);
  11573. var mapDir = path.dirname(mapFilename);
  11574. var outputDir = path.dirname(output); // find the path from the map to the output file
  11575. sourceMapOptions.sourceMapOutputFilename = path.join(path.relative(mapDir, outputDir), path.basename(output)); // make the sourcemap filename point to the sourcemap relative to the css file output directory
  11576. sourceMapOptions.sourceMapFilename = path.join(path.relative(outputDir, mapDir), path.basename(sourceMapOptions.sourceMapFullFilename));
  11577. }
  11578. }
  11579. if (sourceMapOptions.sourceMapBasepath === undefined) {
  11580. sourceMapOptions.sourceMapBasepath = input ? path.dirname(input) : process.cwd();
  11581. }
  11582. if (sourceMapOptions.sourceMapRootpath === undefined) {
  11583. var pathToMap = path.dirname((sourceMapFileInline ? output : sourceMapOptions.sourceMapFullFilename) || '.');
  11584. var pathToInput = path.dirname(sourceMapOptions.sourceMapInputFilename || '.');
  11585. sourceMapOptions.sourceMapRootpath = path.relative(pathToMap, pathToInput);
  11586. }
  11587. if (!input) {
  11588. console.error('lessc: no input files');
  11589. console.error('');
  11590. printUsage();
  11591. process.exitCode = 1;
  11592. return;
  11593. }
  11594. var ensureDirectory = function ensureDirectory(filepath) {
  11595. var dir = path.dirname(filepath);
  11596. var cmd;
  11597. var existsSync = fs$1.existsSync || path.existsSync;
  11598. if (!existsSync(dir)) {
  11599. if (mkdirp === undefined) {
  11600. try {
  11601. mkdirp = require('mkdirp');
  11602. } catch (e) {
  11603. mkdirp = null;
  11604. }
  11605. }
  11606. cmd = mkdirp && mkdirp.sync || fs$1.mkdirSync;
  11607. cmd(dir);
  11608. }
  11609. };
  11610. if (options.depends) {
  11611. if (!outputbase) {
  11612. console.error('option --depends requires an output path to be specified');
  11613. process.exitCode = 1;
  11614. return;
  11615. }
  11616. process.stdout.write(`${outputbase}: `);
  11617. }
  11618. if (!sourceMapFileInline) {
  11619. var writeSourceMap = function writeSourceMap() {
  11620. var output = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : '';
  11621. var onDone = arguments.length > 1 ? arguments[1] : undefined;
  11622. var filename = sourceMapOptions.sourceMapFullFilename;
  11623. ensureDirectory(filename);
  11624. fs$1.writeFile(filename, output, 'utf8', function (err) {
  11625. if (err) {
  11626. var description = 'Error: ';
  11627. if (errno && errno.errno[err.errno]) {
  11628. description += errno.errno[err.errno].description;
  11629. } else {
  11630. description += `${err.code} ${err.message}`;
  11631. }
  11632. console.error(`lessc: failed to create file ${filename}`);
  11633. console.error(description);
  11634. process.exitCode = 1;
  11635. } else {
  11636. less.logger.info(`lessc: wrote ${filename}`);
  11637. }
  11638. onDone();
  11639. });
  11640. };
  11641. }
  11642. var writeSourceMapIfNeeded = function writeSourceMapIfNeeded(output, onDone) {
  11643. if (options.sourceMap && !sourceMapFileInline) {
  11644. writeSourceMap(output, onDone);
  11645. } else {
  11646. onDone();
  11647. }
  11648. };
  11649. var writeOutput = function writeOutput(output, result, onSuccess) {
  11650. if (options.depends) {
  11651. onSuccess();
  11652. } else if (output) {
  11653. ensureDirectory(output);
  11654. fs$1.writeFile(output, result.css, {
  11655. encoding: 'utf8'
  11656. }, function (err) {
  11657. if (err) {
  11658. var description = 'Error: ';
  11659. if (errno && errno.errno[err.errno]) {
  11660. description += errno.errno[err.errno].description;
  11661. } else {
  11662. description += `${err.code} ${err.message}`;
  11663. }
  11664. console.error(`lessc: failed to create file ${output}`);
  11665. console.error(description);
  11666. process.exitCode = 1;
  11667. } else {
  11668. less.logger.info(`lessc: wrote ${output}`);
  11669. onSuccess();
  11670. }
  11671. });
  11672. } else if (!options.depends) {
  11673. process.stdout.write(result.css);
  11674. onSuccess();
  11675. }
  11676. };
  11677. var logDependencies = function logDependencies(options, result) {
  11678. if (options.depends) {
  11679. var depends = '';
  11680. for (var i = 0; i < result.imports.length; i++) {
  11681. depends += `${result.imports[i]} `;
  11682. }
  11683. console.log(depends);
  11684. }
  11685. };
  11686. var parseLessFile = function parseLessFile(e, data) {
  11687. if (e) {
  11688. console.error(`lessc: ${e.message}`);
  11689. process.exitCode = 1;
  11690. return;
  11691. }
  11692. data = data.replace(/^\uFEFF/, '');
  11693. options.paths = [path.dirname(input)].concat(options.paths);
  11694. options.filename = input;
  11695. if (options.lint) {
  11696. options.sourceMap = false;
  11697. }
  11698. sourceMapOptions.sourceMapFileInline = sourceMapFileInline;
  11699. if (options.sourceMap) {
  11700. options.sourceMap = sourceMapOptions;
  11701. }
  11702. less.logger.addListener({
  11703. info: function info(msg) {
  11704. if (verbose) {
  11705. console.log(msg);
  11706. }
  11707. },
  11708. warn: function warn(msg) {
  11709. // do not show warning if the silent option is used
  11710. if (!silent) {
  11711. console.warn(msg);
  11712. }
  11713. },
  11714. error: function error(msg) {
  11715. console.error(msg);
  11716. }
  11717. });
  11718. less.render(data, options).then(function (result) {
  11719. if (!options.lint) {
  11720. writeOutput(output, result, function () {
  11721. writeSourceMapIfNeeded(result.map, function () {
  11722. logDependencies(options, result);
  11723. });
  11724. });
  11725. }
  11726. }, function (err) {
  11727. if (!options.silent) {
  11728. console.error(err.toString({
  11729. stylize: options.color && less.lesscHelper.stylize
  11730. }));
  11731. }
  11732. process.exitCode = 1;
  11733. });
  11734. };
  11735. if (input != '-') {
  11736. fs$1.readFile(input, 'utf8', parseLessFile);
  11737. } else {
  11738. process.stdin.resume();
  11739. process.stdin.setEncoding('utf8');
  11740. var buffer = '';
  11741. process.stdin.on('data', function (data) {
  11742. buffer += data;
  11743. });
  11744. process.stdin.on('end', function () {
  11745. parseLessFile(false, buffer);
  11746. });
  11747. }
  11748. }
  11749. function processPluginQueue() {
  11750. var x = 0;
  11751. function pluginError(name) {
  11752. console.error(`Unable to load plugin ${name} please make sure that it is installed under or at the same level as less`);
  11753. process.exitCode = 1;
  11754. }
  11755. function pluginFinished(plugin) {
  11756. x++;
  11757. plugins.push(plugin);
  11758. if (x === queuePlugins.length) {
  11759. render();
  11760. }
  11761. }
  11762. queuePlugins.forEach(function (queue) {
  11763. var context = clone(options);
  11764. pluginManager.Loader.loadPlugin(queue.name, process.cwd(), context, less.environment, fileManager).then(function (data) {
  11765. pluginFinished({
  11766. fileContent: data.contents,
  11767. filename: data.filename,
  11768. options: queue.options
  11769. });
  11770. }).catch(function () {
  11771. pluginError(queue.name);
  11772. });
  11773. });
  11774. } // self executing function so we can return
  11775. (function () {
  11776. args = args.filter(function (arg) {
  11777. var match;
  11778. match = arg.match(/^-I(.+)$/);
  11779. if (match) {
  11780. options.paths.push(match[1]);
  11781. return false;
  11782. }
  11783. match = arg.match(/^--?([a-z][0-9a-z-]*)(?:=(.*))?$/i);
  11784. if (match) {
  11785. arg = match[1];
  11786. } else {
  11787. return arg;
  11788. }
  11789. switch (arg) {
  11790. case 'v':
  11791. case 'version':
  11792. console.log(`lessc ${less.version.join('.')} (Less Compiler) [JavaScript]`);
  11793. continueProcessing = false;
  11794. break;
  11795. case 'verbose':
  11796. verbose = true;
  11797. break;
  11798. case 's':
  11799. case 'silent':
  11800. silent = true;
  11801. break;
  11802. case 'l':
  11803. case 'lint':
  11804. options.lint = true;
  11805. break;
  11806. case 'strict-imports':
  11807. options.strictImports = true;
  11808. break;
  11809. case 'h':
  11810. case 'help':
  11811. printUsage();
  11812. break;
  11813. case 'x':
  11814. case 'compress':
  11815. options.compress = true;
  11816. break;
  11817. case 'insecure':
  11818. options.insecure = true;
  11819. break;
  11820. case 'M':
  11821. case 'depends':
  11822. options.depends = true;
  11823. break;
  11824. case 'max-line-len':
  11825. if (checkArgFunc(arg, match[2])) {
  11826. options.maxLineLen = parseInt(match[2], 10);
  11827. if (options.maxLineLen <= 0) {
  11828. options.maxLineLen = -1;
  11829. }
  11830. }
  11831. break;
  11832. case 'no-color':
  11833. options.color = false;
  11834. break;
  11835. case 'js':
  11836. options.javascriptEnabled = true;
  11837. break;
  11838. case 'no-js':
  11839. console.error('The "--no-js" argument is deprecated, as inline JavaScript ' + 'is disabled by default. Use "--js" to enable inline JavaScript (not recommended).');
  11840. break;
  11841. case 'include-path':
  11842. if (checkArgFunc(arg, match[2])) {
  11843. // ; supported on windows.
  11844. // : supported on windows and linux, excluding a drive letter like C:\ so C:\file:D:\file parses to 2
  11845. options.paths = match[2].split(os.type().match(/Windows/) ? /:(?!\\)|;/ : ':').map(function (p) {
  11846. if (p) {
  11847. return path.resolve(process.cwd(), p);
  11848. }
  11849. });
  11850. }
  11851. break;
  11852. case 'line-numbers':
  11853. if (checkArgFunc(arg, match[2])) {
  11854. options.dumpLineNumbers = match[2];
  11855. }
  11856. break;
  11857. case 'source-map':
  11858. options.sourceMap = true;
  11859. if (match[2]) {
  11860. sourceMapOptions.sourceMapFullFilename = match[2];
  11861. }
  11862. break;
  11863. case 'source-map-rootpath':
  11864. if (checkArgFunc(arg, match[2])) {
  11865. sourceMapOptions.sourceMapRootpath = match[2];
  11866. }
  11867. break;
  11868. case 'source-map-basepath':
  11869. if (checkArgFunc(arg, match[2])) {
  11870. sourceMapOptions.sourceMapBasepath = match[2];
  11871. }
  11872. break;
  11873. case 'source-map-inline':
  11874. case 'source-map-map-inline':
  11875. sourceMapFileInline = true;
  11876. options.sourceMap = true;
  11877. break;
  11878. case 'source-map-include-source':
  11879. case 'source-map-less-inline':
  11880. sourceMapOptions.outputSourceFiles = true;
  11881. break;
  11882. case 'source-map-url':
  11883. if (checkArgFunc(arg, match[2])) {
  11884. sourceMapOptions.sourceMapURL = match[2];
  11885. }
  11886. break;
  11887. case 'rp':
  11888. case 'rootpath':
  11889. if (checkArgFunc(arg, match[2])) {
  11890. options.rootpath = match[2].replace(/\\/g, '/');
  11891. }
  11892. break;
  11893. case 'relative-urls':
  11894. console.warn('The --relative-urls option has been deprecated. Use --rewrite-urls=all.');
  11895. options.rewriteUrls = RewriteUrls.ALL;
  11896. break;
  11897. case 'ru':
  11898. case 'rewrite-urls':
  11899. var m = match[2];
  11900. if (m) {
  11901. if (m === 'local') {
  11902. options.rewriteUrls = RewriteUrls.LOCAL;
  11903. } else if (m === 'off') {
  11904. options.rewriteUrls = RewriteUrls.OFF;
  11905. } else if (m === 'all') {
  11906. options.rewriteUrls = RewriteUrls.ALL;
  11907. } else {
  11908. console.error(`Unknown rewrite-urls argument ${m}`);
  11909. continueProcessing = false;
  11910. process.exitCode = 1;
  11911. }
  11912. } else {
  11913. options.rewriteUrls = RewriteUrls.ALL;
  11914. }
  11915. break;
  11916. case 'sm':
  11917. case 'strict-math':
  11918. console.warn('The --strict-math option has been deprecated. Use --math=strict.');
  11919. if (checkArgFunc(arg, match[2])) {
  11920. if (checkBooleanArg(match[2])) {
  11921. options.math = Math$1.STRICT_LEGACY;
  11922. }
  11923. }
  11924. break;
  11925. case 'm':
  11926. case 'math':
  11927. if (checkArgFunc(arg, match[2])) {
  11928. options.math = match[2];
  11929. }
  11930. break;
  11931. case 'su':
  11932. case 'strict-units':
  11933. if (checkArgFunc(arg, match[2])) {
  11934. options.strictUnits = checkBooleanArg(match[2]);
  11935. }
  11936. break;
  11937. case 'global-var':
  11938. if (checkArgFunc(arg, match[2])) {
  11939. if (!options.globalVars) {
  11940. options.globalVars = {};
  11941. }
  11942. parseVariableOption(match[2], options.globalVars);
  11943. }
  11944. break;
  11945. case 'modify-var':
  11946. if (checkArgFunc(arg, match[2])) {
  11947. if (!options.modifyVars) {
  11948. options.modifyVars = {};
  11949. }
  11950. parseVariableOption(match[2], options.modifyVars);
  11951. }
  11952. break;
  11953. case 'url-args':
  11954. if (checkArgFunc(arg, match[2])) {
  11955. options.urlArgs = match[2];
  11956. }
  11957. break;
  11958. case 'plugin':
  11959. var splitupArg = match[2].match(/^([^=]+)(=(.*))?/);
  11960. var name = splitupArg[1];
  11961. var pluginOptions = splitupArg[3];
  11962. queuePlugins.push({
  11963. name,
  11964. options: pluginOptions
  11965. });
  11966. break;
  11967. default:
  11968. queuePlugins.push({
  11969. name: arg,
  11970. options: match[2],
  11971. default: true
  11972. });
  11973. break;
  11974. }
  11975. });
  11976. if (queuePlugins.length > 0) {
  11977. processPluginQueue();
  11978. } else {
  11979. render();
  11980. }
  11981. })();