less.js 474 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320732173227323732473257326732773287329733073317332733373347335733673377338733973407341734273437344734573467347734873497350735173527353735473557356735773587359736073617362736373647365736673677368736973707371737273737374737573767377737873797380738173827383738473857386738773887389739073917392739373947395739673977398739974007401740274037404740574067407740874097410741174127413741474157416741774187419742074217422742374247425742674277428742974307431743274337434743574367437743874397440744174427443744474457446744774487449745074517452745374547455745674577458745974607461746274637464746574667467746874697470747174727473747474757476747774787479748074817482748374847485748674877488748974907491749274937494749574967497749874997500750175027503750475057506750775087509751075117512751375147515751675177518751975207521752275237524752575267527752875297530753175327533753475357536753775387539754075417542754375447545754675477548754975507551755275537554755575567557755875597560756175627563756475657566756775687569757075717572757375747575757675777578757975807581758275837584758575867587758875897590759175927593759475957596759775987599760076017602760376047605760676077608760976107611761276137614761576167617761876197620762176227623762476257626762776287629763076317632763376347635763676377638763976407641764276437644764576467647764876497650765176527653765476557656765776587659766076617662766376647665766676677668766976707671767276737674767576767677767876797680768176827683768476857686768776887689769076917692769376947695769676977698769977007701770277037704770577067707770877097710771177127713771477157716771777187719772077217722772377247725772677277728772977307731773277337734773577367737773877397740774177427743774477457746774777487749775077517752775377547755775677577758775977607761776277637764776577667767776877697770777177727773777477757776777777787779778077817782778377847785778677877788778977907791779277937794779577967797779877997800780178027803780478057806780778087809781078117812781378147815781678177818781978207821782278237824782578267827782878297830783178327833783478357836783778387839784078417842784378447845784678477848784978507851785278537854785578567857785878597860786178627863786478657866786778687869787078717872787378747875787678777878787978807881788278837884788578867887788878897890789178927893789478957896789778987899790079017902790379047905790679077908790979107911791279137914791579167917791879197920792179227923792479257926792779287929793079317932793379347935793679377938793979407941794279437944794579467947794879497950795179527953795479557956795779587959796079617962796379647965796679677968796979707971797279737974797579767977797879797980798179827983798479857986798779887989799079917992799379947995799679977998799980008001800280038004800580068007800880098010801180128013801480158016801780188019802080218022802380248025802680278028802980308031803280338034803580368037803880398040804180428043804480458046804780488049805080518052805380548055805680578058805980608061806280638064806580668067806880698070807180728073807480758076807780788079808080818082808380848085808680878088808980908091809280938094809580968097809880998100810181028103810481058106810781088109811081118112811381148115811681178118811981208121812281238124812581268127812881298130813181328133813481358136813781388139814081418142814381448145814681478148814981508151815281538154815581568157815881598160816181628163816481658166816781688169817081718172817381748175817681778178817981808181818281838184818581868187818881898190819181928193819481958196819781988199820082018202820382048205820682078208820982108211821282138214821582168217821882198220822182228223822482258226822782288229823082318232823382348235823682378238823982408241824282438244824582468247824882498250825182528253825482558256825782588259826082618262826382648265826682678268826982708271827282738274827582768277827882798280828182828283828482858286828782888289829082918292829382948295829682978298829983008301830283038304830583068307830883098310831183128313831483158316831783188319832083218322832383248325832683278328832983308331833283338334833583368337833883398340834183428343834483458346834783488349835083518352835383548355835683578358835983608361836283638364836583668367836883698370837183728373837483758376837783788379838083818382838383848385838683878388838983908391839283938394839583968397839883998400840184028403840484058406840784088409841084118412841384148415841684178418841984208421842284238424842584268427842884298430843184328433843484358436843784388439844084418442844384448445844684478448844984508451845284538454845584568457845884598460846184628463846484658466846784688469847084718472847384748475847684778478847984808481848284838484848584868487848884898490849184928493849484958496849784988499850085018502850385048505850685078508850985108511851285138514851585168517851885198520852185228523852485258526852785288529853085318532853385348535853685378538853985408541854285438544854585468547854885498550855185528553855485558556855785588559856085618562856385648565856685678568856985708571857285738574857585768577857885798580858185828583858485858586858785888589859085918592859385948595859685978598859986008601860286038604860586068607860886098610861186128613861486158616861786188619862086218622862386248625862686278628862986308631863286338634863586368637863886398640864186428643864486458646864786488649865086518652865386548655865686578658865986608661866286638664866586668667866886698670867186728673867486758676867786788679868086818682868386848685868686878688868986908691869286938694869586968697869886998700870187028703870487058706870787088709871087118712871387148715871687178718871987208721872287238724872587268727872887298730873187328733873487358736873787388739874087418742874387448745874687478748874987508751875287538754875587568757875887598760876187628763876487658766876787688769877087718772877387748775877687778778877987808781878287838784878587868787878887898790879187928793879487958796879787988799880088018802880388048805880688078808880988108811881288138814881588168817881888198820882188228823882488258826882788288829883088318832883388348835883688378838883988408841884288438844884588468847884888498850885188528853885488558856885788588859886088618862886388648865886688678868886988708871887288738874887588768877887888798880888188828883888488858886888788888889889088918892889388948895889688978898889989008901890289038904890589068907890889098910891189128913891489158916891789188919892089218922892389248925892689278928892989308931893289338934893589368937893889398940894189428943894489458946894789488949895089518952895389548955895689578958895989608961896289638964896589668967896889698970897189728973897489758976897789788979898089818982898389848985898689878988898989908991899289938994899589968997899889999000900190029003900490059006900790089009901090119012901390149015901690179018901990209021902290239024902590269027902890299030903190329033903490359036903790389039904090419042904390449045904690479048904990509051905290539054905590569057905890599060906190629063906490659066906790689069907090719072907390749075907690779078907990809081908290839084908590869087908890899090909190929093909490959096909790989099910091019102910391049105910691079108910991109111911291139114911591169117911891199120912191229123912491259126912791289129913091319132913391349135913691379138913991409141914291439144914591469147914891499150915191529153915491559156915791589159916091619162916391649165916691679168916991709171917291739174917591769177917891799180918191829183918491859186918791889189919091919192919391949195919691979198919992009201920292039204920592069207920892099210921192129213921492159216921792189219922092219222922392249225922692279228922992309231923292339234923592369237923892399240924192429243924492459246924792489249925092519252925392549255925692579258925992609261926292639264926592669267926892699270927192729273927492759276927792789279928092819282928392849285928692879288928992909291929292939294929592969297929892999300930193029303930493059306930793089309931093119312931393149315931693179318931993209321932293239324932593269327932893299330933193329333933493359336933793389339934093419342934393449345934693479348934993509351935293539354935593569357935893599360936193629363936493659366936793689369937093719372937393749375937693779378937993809381938293839384938593869387938893899390939193929393939493959396939793989399940094019402940394049405940694079408940994109411941294139414941594169417941894199420942194229423942494259426942794289429943094319432943394349435943694379438943994409441944294439444944594469447944894499450945194529453945494559456945794589459946094619462946394649465946694679468946994709471947294739474947594769477947894799480948194829483948494859486948794889489949094919492949394949495949694979498949995009501950295039504950595069507950895099510951195129513951495159516951795189519952095219522952395249525952695279528952995309531953295339534953595369537953895399540954195429543954495459546954795489549955095519552955395549555955695579558955995609561956295639564956595669567956895699570957195729573957495759576957795789579958095819582958395849585958695879588958995909591959295939594959595969597959895999600960196029603960496059606960796089609961096119612961396149615961696179618961996209621962296239624962596269627962896299630963196329633963496359636963796389639964096419642964396449645964696479648964996509651965296539654965596569657965896599660966196629663966496659666966796689669967096719672967396749675967696779678967996809681968296839684968596869687968896899690969196929693969496959696969796989699970097019702970397049705970697079708970997109711971297139714971597169717971897199720972197229723972497259726972797289729973097319732973397349735973697379738973997409741974297439744974597469747974897499750975197529753975497559756975797589759976097619762976397649765976697679768976997709771977297739774977597769777977897799780978197829783978497859786978797889789979097919792979397949795979697979798979998009801980298039804980598069807980898099810981198129813981498159816981798189819982098219822982398249825982698279828982998309831983298339834983598369837983898399840984198429843984498459846984798489849985098519852985398549855985698579858985998609861986298639864986598669867986898699870987198729873987498759876987798789879988098819882988398849885988698879888988998909891989298939894989598969897989898999900990199029903990499059906990799089909991099119912991399149915991699179918991999209921992299239924992599269927992899299930993199329933993499359936993799389939994099419942994399449945994699479948994999509951995299539954995599569957995899599960996199629963996499659966996799689969997099719972997399749975997699779978997999809981998299839984998599869987998899899990999199929993999499959996999799989999100001000110002100031000410005100061000710008100091001010011100121001310014100151001610017100181001910020100211002210023100241002510026100271002810029100301003110032100331003410035100361003710038100391004010041100421004310044100451004610047100481004910050100511005210053100541005510056100571005810059100601006110062100631006410065100661006710068100691007010071100721007310074100751007610077100781007910080100811008210083100841008510086100871008810089100901009110092100931009410095100961009710098100991010010101101021010310104101051010610107101081010910110101111011210113101141011510116101171011810119101201012110122101231012410125101261012710128101291013010131101321013310134101351013610137101381013910140101411014210143101441014510146101471014810149101501015110152101531015410155101561015710158101591016010161101621016310164101651016610167101681016910170101711017210173101741017510176101771017810179101801018110182101831018410185101861018710188101891019010191101921019310194101951019610197101981019910200102011020210203102041020510206102071020810209102101021110212102131021410215102161021710218102191022010221102221022310224102251022610227102281022910230102311023210233102341023510236102371023810239102401024110242102431024410245102461024710248102491025010251102521025310254102551025610257102581025910260102611026210263102641026510266102671026810269102701027110272102731027410275102761027710278102791028010281102821028310284102851028610287102881028910290102911029210293102941029510296102971029810299103001030110302103031030410305103061030710308103091031010311103121031310314103151031610317103181031910320103211032210323103241032510326103271032810329103301033110332103331033410335103361033710338103391034010341103421034310344103451034610347103481034910350103511035210353103541035510356103571035810359103601036110362103631036410365103661036710368103691037010371103721037310374103751037610377103781037910380103811038210383103841038510386103871038810389103901039110392103931039410395103961039710398103991040010401104021040310404104051040610407104081040910410104111041210413104141041510416104171041810419104201042110422104231042410425104261042710428104291043010431104321043310434104351043610437104381043910440104411044210443104441044510446104471044810449104501045110452104531045410455104561045710458104591046010461104621046310464104651046610467104681046910470104711047210473104741047510476104771047810479104801048110482104831048410485104861048710488104891049010491104921049310494104951049610497104981049910500105011050210503105041050510506105071050810509105101051110512105131051410515105161051710518105191052010521105221052310524105251052610527105281052910530105311053210533105341053510536105371053810539105401054110542105431054410545105461054710548105491055010551105521055310554105551055610557105581055910560105611056210563105641056510566105671056810569105701057110572105731057410575105761057710578105791058010581105821058310584105851058610587105881058910590105911059210593105941059510596105971059810599106001060110602106031060410605106061060710608106091061010611106121061310614106151061610617106181061910620106211062210623106241062510626106271062810629106301063110632106331063410635106361063710638106391064010641106421064310644106451064610647106481064910650106511065210653106541065510656106571065810659106601066110662106631066410665106661066710668106691067010671106721067310674106751067610677106781067910680106811068210683106841068510686106871068810689106901069110692106931069410695106961069710698106991070010701107021070310704107051070610707107081070910710107111071210713107141071510716107171071810719107201072110722107231072410725107261072710728107291073010731107321073310734107351073610737107381073910740107411074210743107441074510746107471074810749107501075110752107531075410755107561075710758107591076010761107621076310764107651076610767107681076910770107711077210773107741077510776107771077810779107801078110782107831078410785107861078710788107891079010791107921079310794107951079610797107981079910800108011080210803108041080510806108071080810809108101081110812108131081410815108161081710818108191082010821108221082310824108251082610827108281082910830108311083210833108341083510836108371083810839108401084110842108431084410845108461084710848108491085010851108521085310854108551085610857108581085910860108611086210863108641086510866108671086810869108701087110872108731087410875108761087710878108791088010881108821088310884108851088610887108881088910890108911089210893108941089510896108971089810899109001090110902109031090410905109061090710908109091091010911109121091310914109151091610917109181091910920109211092210923109241092510926109271092810929109301093110932109331093410935109361093710938109391094010941109421094310944109451094610947109481094910950109511095210953109541095510956109571095810959109601096110962109631096410965109661096710968109691097010971109721097310974109751097610977109781097910980109811098210983109841098510986109871098810989109901099110992109931099410995109961099710998109991100011001110021100311004110051100611007110081100911010110111101211013110141101511016110171101811019110201102111022110231102411025110261102711028110291103011031110321103311034110351103611037110381103911040110411104211043110441104511046110471104811049110501105111052110531105411055110561105711058110591106011061110621106311064110651106611067110681106911070110711107211073110741107511076110771107811079110801108111082110831108411085110861108711088110891109011091110921109311094110951109611097110981109911100111011110211103111041110511106111071110811109111101111111112111131111411115111161111711118111191112011121111221112311124111251112611127111281112911130111311113211133111341113511136111371113811139111401114111142111431114411145111461114711148111491115011151111521115311154111551115611157111581115911160111611116211163111641116511166111671116811169111701117111172111731117411175111761117711178111791118011181111821118311184111851118611187111881118911190111911119211193111941119511196111971119811199112001120111202112031120411205112061120711208112091121011211112121121311214112151121611217112181121911220112211122211223112241122511226112271122811229112301123111232112331123411235112361123711238112391124011241112421124311244112451124611247112481124911250112511125211253112541125511256112571125811259112601126111262112631126411265112661126711268112691127011271112721127311274112751127611277112781127911280112811128211283112841128511286112871128811289112901129111292112931129411295112961129711298112991130011301113021130311304113051130611307113081130911310113111131211313113141131511316113171131811319113201132111322113231132411325113261132711328113291133011331113321133311334113351133611337113381133911340113411134211343113441134511346113471134811349113501135111352113531135411355113561135711358113591136011361113621136311364113651136611367113681136911370113711137211373113741137511376113771137811379113801138111382113831138411385113861138711388113891139011391113921139311394113951139611397113981139911400114011140211403114041140511406114071140811409114101141111412114131141411415114161141711418114191142011421114221142311424114251142611427114281142911430114311143211433114341143511436114371143811439114401144111442114431144411445114461144711448114491145011451114521145311454114551145611457114581145911460114611146211463114641146511466114671146811469114701147111472114731147411475114761147711478114791148011481114821148311484114851148611487114881148911490114911149211493114941149511496114971149811499115001150111502115031150411505115061150711508115091151011511115121151311514115151151611517
  1. /**
  2. * Less - Leaner CSS v4.2.0
  3. * http://lesscss.org
  4. *
  5. * Copyright (c) 2009-2023, Alexis Sellier <[email protected]>
  6. * Licensed under the Apache-2.0 License.
  7. *
  8. * @license Apache-2.0
  9. */
  10. (function (global, factory) {
  11. typeof exports === 'object' && typeof module !== 'undefined' ? module.exports = factory() :
  12. typeof define === 'function' && define.amd ? define(factory) :
  13. (global = typeof globalThis !== 'undefined' ? globalThis : global || self, global.less = factory());
  14. }(this, (function () { 'use strict';
  15. // Export a new default each time
  16. function defaultOptions () {
  17. return {
  18. /* Inline Javascript - @plugin still allowed */
  19. javascriptEnabled: false,
  20. /* Outputs a makefile import dependency list to stdout. */
  21. depends: false,
  22. /* (DEPRECATED) Compress using less built-in compression.
  23. * This does an okay job but does not utilise all the tricks of
  24. * dedicated css compression. */
  25. compress: false,
  26. /* Runs the less parser and just reports errors without any output. */
  27. lint: false,
  28. /* Sets available include paths.
  29. * If the file in an @import rule does not exist at that exact location,
  30. * less will look for it at the location(s) passed to this option.
  31. * You might use this for instance to specify a path to a library which
  32. * you want to be referenced simply and relatively in the less files. */
  33. paths: [],
  34. /* color output in the terminal */
  35. color: true,
  36. /* The strictImports controls whether the compiler will allow an @import inside of either
  37. * @media blocks or (a later addition) other selector blocks.
  38. * See: https://github.com/less/less.js/issues/656 */
  39. strictImports: false,
  40. /* Allow Imports from Insecure HTTPS Hosts */
  41. insecure: false,
  42. /* Allows you to add a path to every generated import and url in your css.
  43. * This does not affect less import statements that are processed, just ones
  44. * that are left in the output css. */
  45. rootpath: '',
  46. /* By default URLs are kept as-is, so if you import a file in a sub-directory
  47. * that references an image, exactly the same URL will be output in the css.
  48. * This option allows you to re-write URL's in imported files so that the
  49. * URL is always relative to the base imported file */
  50. rewriteUrls: false,
  51. /* How to process math
  52. * 0 always - eagerly try to solve all operations
  53. * 1 parens-division - require parens for division "/"
  54. * 2 parens | strict - require parens for all operations
  55. * 3 strict-legacy - legacy strict behavior (super-strict)
  56. */
  57. math: 1,
  58. /* Without this option, less attempts to guess at the output unit when it does maths. */
  59. strictUnits: false,
  60. /* Effectively the declaration is put at the top of your base Less file,
  61. * meaning it can be used but it also can be overridden if this variable
  62. * is defined in the file. */
  63. globalVars: null,
  64. /* As opposed to the global variable option, this puts the declaration at the
  65. * end of your base file, meaning it will override anything defined in your Less file. */
  66. modifyVars: null,
  67. /* This option allows you to specify a argument to go on to every URL. */
  68. urlArgs: ''
  69. };
  70. }
  71. function extractId(href) {
  72. return href.replace(/^[a-z-]+:\/+?[^/]+/, '') // Remove protocol & domain
  73. .replace(/[?&]livereload=\w+/, '') // Remove LiveReload cachebuster
  74. .replace(/^\//, '') // Remove root /
  75. .replace(/\.[a-zA-Z]+$/, '') // Remove simple extension
  76. .replace(/[^.\w-]+/g, '-') // Replace illegal characters
  77. .replace(/\./g, ':'); // Replace dots with colons(for valid id)
  78. }
  79. function addDataAttr(options, tag) {
  80. if (!tag) {
  81. return;
  82. } // in case of tag is null or undefined
  83. for (var opt in tag.dataset) {
  84. if (Object.prototype.hasOwnProperty.call(tag.dataset, opt)) {
  85. if (opt === 'env' || opt === 'dumpLineNumbers' || opt === 'rootpath' || opt === 'errorReporting') {
  86. options[opt] = tag.dataset[opt];
  87. }
  88. else {
  89. try {
  90. options[opt] = JSON.parse(tag.dataset[opt]);
  91. }
  92. catch (_) { }
  93. }
  94. }
  95. }
  96. }
  97. var browser = {
  98. createCSS: function (document, styles, sheet) {
  99. // Strip the query-string
  100. var href = sheet.href || '';
  101. // If there is no title set, use the filename, minus the extension
  102. var id = "less:" + (sheet.title || extractId(href));
  103. // If this has already been inserted into the DOM, we may need to replace it
  104. var oldStyleNode = document.getElementById(id);
  105. var keepOldStyleNode = false;
  106. // Create a new stylesheet node for insertion or (if necessary) replacement
  107. var styleNode = document.createElement('style');
  108. styleNode.setAttribute('type', 'text/css');
  109. if (sheet.media) {
  110. styleNode.setAttribute('media', sheet.media);
  111. }
  112. styleNode.id = id;
  113. if (!styleNode.styleSheet) {
  114. styleNode.appendChild(document.createTextNode(styles));
  115. // If new contents match contents of oldStyleNode, don't replace oldStyleNode
  116. keepOldStyleNode = (oldStyleNode !== null && oldStyleNode.childNodes.length > 0 && styleNode.childNodes.length > 0 &&
  117. oldStyleNode.firstChild.nodeValue === styleNode.firstChild.nodeValue);
  118. }
  119. var head = document.getElementsByTagName('head')[0];
  120. // If there is no oldStyleNode, just append; otherwise, only append if we need
  121. // to replace oldStyleNode with an updated stylesheet
  122. if (oldStyleNode === null || keepOldStyleNode === false) {
  123. var nextEl = sheet && sheet.nextSibling || null;
  124. if (nextEl) {
  125. nextEl.parentNode.insertBefore(styleNode, nextEl);
  126. }
  127. else {
  128. head.appendChild(styleNode);
  129. }
  130. }
  131. if (oldStyleNode && keepOldStyleNode === false) {
  132. oldStyleNode.parentNode.removeChild(oldStyleNode);
  133. }
  134. // For IE.
  135. // This needs to happen *after* the style element is added to the DOM, otherwise IE 7 and 8 may crash.
  136. // See http://social.msdn.microsoft.com/Forums/en-US/7e081b65-878a-4c22-8e68-c10d39c2ed32/internet-explorer-crashes-appending-style-element-to-head
  137. if (styleNode.styleSheet) {
  138. try {
  139. styleNode.styleSheet.cssText = styles;
  140. }
  141. catch (e) {
  142. throw new Error('Couldn\'t reassign styleSheet.cssText.');
  143. }
  144. }
  145. },
  146. currentScript: function (window) {
  147. var document = window.document;
  148. return document.currentScript || (function () {
  149. var scripts = document.getElementsByTagName('script');
  150. return scripts[scripts.length - 1];
  151. })();
  152. }
  153. };
  154. var addDefaultOptions = (function (window, options) {
  155. // use options from the current script tag data attribues
  156. addDataAttr(options, browser.currentScript(window));
  157. if (options.isFileProtocol === undefined) {
  158. options.isFileProtocol = /^(file|(chrome|safari)(-extension)?|resource|qrc|app):/.test(window.location.protocol);
  159. }
  160. // Load styles asynchronously (default: false)
  161. //
  162. // This is set to `false` by default, so that the body
  163. // doesn't start loading before the stylesheets are parsed.
  164. // Setting this to `true` can result in flickering.
  165. //
  166. options.async = options.async || false;
  167. options.fileAsync = options.fileAsync || false;
  168. // Interval between watch polls
  169. options.poll = options.poll || (options.isFileProtocol ? 1000 : 1500);
  170. options.env = options.env || (window.location.hostname == '127.0.0.1' ||
  171. window.location.hostname == '0.0.0.0' ||
  172. window.location.hostname == 'localhost' ||
  173. (window.location.port &&
  174. window.location.port.length > 0) ||
  175. options.isFileProtocol ? 'development'
  176. : 'production');
  177. var dumpLineNumbers = /!dumpLineNumbers:(comments|mediaquery|all)/.exec(window.location.hash);
  178. if (dumpLineNumbers) {
  179. options.dumpLineNumbers = dumpLineNumbers[1];
  180. }
  181. if (options.useFileCache === undefined) {
  182. options.useFileCache = true;
  183. }
  184. if (options.onReady === undefined) {
  185. options.onReady = true;
  186. }
  187. if (options.relativeUrls) {
  188. options.rewriteUrls = 'all';
  189. }
  190. });
  191. var logger$1 = {
  192. error: function (msg) {
  193. this._fireEvent('error', msg);
  194. },
  195. warn: function (msg) {
  196. this._fireEvent('warn', msg);
  197. },
  198. info: function (msg) {
  199. this._fireEvent('info', msg);
  200. },
  201. debug: function (msg) {
  202. this._fireEvent('debug', msg);
  203. },
  204. addListener: function (listener) {
  205. this._listeners.push(listener);
  206. },
  207. removeListener: function (listener) {
  208. for (var i_1 = 0; i_1 < this._listeners.length; i_1++) {
  209. if (this._listeners[i_1] === listener) {
  210. this._listeners.splice(i_1, 1);
  211. return;
  212. }
  213. }
  214. },
  215. _fireEvent: function (type, msg) {
  216. for (var i_2 = 0; i_2 < this._listeners.length; i_2++) {
  217. var logFunction = this._listeners[i_2][type];
  218. if (logFunction) {
  219. logFunction(msg);
  220. }
  221. }
  222. },
  223. _listeners: []
  224. };
  225. /**
  226. * @todo Document why this abstraction exists, and the relationship between
  227. * environment, file managers, and plugin manager
  228. */
  229. var Environment = /** @class */ (function () {
  230. function Environment(externalEnvironment, fileManagers) {
  231. this.fileManagers = fileManagers || [];
  232. externalEnvironment = externalEnvironment || {};
  233. var optionalFunctions = ['encodeBase64', 'mimeLookup', 'charsetLookup', 'getSourceMapGenerator'];
  234. var requiredFunctions = [];
  235. var functions = requiredFunctions.concat(optionalFunctions);
  236. for (var i_1 = 0; i_1 < functions.length; i_1++) {
  237. var propName = functions[i_1];
  238. var environmentFunc = externalEnvironment[propName];
  239. if (environmentFunc) {
  240. this[propName] = environmentFunc.bind(externalEnvironment);
  241. }
  242. else if (i_1 < requiredFunctions.length) {
  243. this.warn("missing required function in environment - " + propName);
  244. }
  245. }
  246. }
  247. Environment.prototype.getFileManager = function (filename, currentDirectory, options, environment, isSync) {
  248. if (!filename) {
  249. logger$1.warn('getFileManager called with no filename.. Please report this issue. continuing.');
  250. }
  251. if (currentDirectory === undefined) {
  252. logger$1.warn('getFileManager called with null directory.. Please report this issue. continuing.');
  253. }
  254. var fileManagers = this.fileManagers;
  255. if (options.pluginManager) {
  256. fileManagers = [].concat(fileManagers).concat(options.pluginManager.getFileManagers());
  257. }
  258. for (var i_2 = fileManagers.length - 1; i_2 >= 0; i_2--) {
  259. var fileManager = fileManagers[i_2];
  260. if (fileManager[isSync ? 'supportsSync' : 'supports'](filename, currentDirectory, options, environment)) {
  261. return fileManager;
  262. }
  263. }
  264. return null;
  265. };
  266. Environment.prototype.addFileManager = function (fileManager) {
  267. this.fileManagers.push(fileManager);
  268. };
  269. Environment.prototype.clearFileManagers = function () {
  270. this.fileManagers = [];
  271. };
  272. return Environment;
  273. }());
  274. var colors = {
  275. 'aliceblue': '#f0f8ff',
  276. 'antiquewhite': '#faebd7',
  277. 'aqua': '#00ffff',
  278. 'aquamarine': '#7fffd4',
  279. 'azure': '#f0ffff',
  280. 'beige': '#f5f5dc',
  281. 'bisque': '#ffe4c4',
  282. 'black': '#000000',
  283. 'blanchedalmond': '#ffebcd',
  284. 'blue': '#0000ff',
  285. 'blueviolet': '#8a2be2',
  286. 'brown': '#a52a2a',
  287. 'burlywood': '#deb887',
  288. 'cadetblue': '#5f9ea0',
  289. 'chartreuse': '#7fff00',
  290. 'chocolate': '#d2691e',
  291. 'coral': '#ff7f50',
  292. 'cornflowerblue': '#6495ed',
  293. 'cornsilk': '#fff8dc',
  294. 'crimson': '#dc143c',
  295. 'cyan': '#00ffff',
  296. 'darkblue': '#00008b',
  297. 'darkcyan': '#008b8b',
  298. 'darkgoldenrod': '#b8860b',
  299. 'darkgray': '#a9a9a9',
  300. 'darkgrey': '#a9a9a9',
  301. 'darkgreen': '#006400',
  302. 'darkkhaki': '#bdb76b',
  303. 'darkmagenta': '#8b008b',
  304. 'darkolivegreen': '#556b2f',
  305. 'darkorange': '#ff8c00',
  306. 'darkorchid': '#9932cc',
  307. 'darkred': '#8b0000',
  308. 'darksalmon': '#e9967a',
  309. 'darkseagreen': '#8fbc8f',
  310. 'darkslateblue': '#483d8b',
  311. 'darkslategray': '#2f4f4f',
  312. 'darkslategrey': '#2f4f4f',
  313. 'darkturquoise': '#00ced1',
  314. 'darkviolet': '#9400d3',
  315. 'deeppink': '#ff1493',
  316. 'deepskyblue': '#00bfff',
  317. 'dimgray': '#696969',
  318. 'dimgrey': '#696969',
  319. 'dodgerblue': '#1e90ff',
  320. 'firebrick': '#b22222',
  321. 'floralwhite': '#fffaf0',
  322. 'forestgreen': '#228b22',
  323. 'fuchsia': '#ff00ff',
  324. 'gainsboro': '#dcdcdc',
  325. 'ghostwhite': '#f8f8ff',
  326. 'gold': '#ffd700',
  327. 'goldenrod': '#daa520',
  328. 'gray': '#808080',
  329. 'grey': '#808080',
  330. 'green': '#008000',
  331. 'greenyellow': '#adff2f',
  332. 'honeydew': '#f0fff0',
  333. 'hotpink': '#ff69b4',
  334. 'indianred': '#cd5c5c',
  335. 'indigo': '#4b0082',
  336. 'ivory': '#fffff0',
  337. 'khaki': '#f0e68c',
  338. 'lavender': '#e6e6fa',
  339. 'lavenderblush': '#fff0f5',
  340. 'lawngreen': '#7cfc00',
  341. 'lemonchiffon': '#fffacd',
  342. 'lightblue': '#add8e6',
  343. 'lightcoral': '#f08080',
  344. 'lightcyan': '#e0ffff',
  345. 'lightgoldenrodyellow': '#fafad2',
  346. 'lightgray': '#d3d3d3',
  347. 'lightgrey': '#d3d3d3',
  348. 'lightgreen': '#90ee90',
  349. 'lightpink': '#ffb6c1',
  350. 'lightsalmon': '#ffa07a',
  351. 'lightseagreen': '#20b2aa',
  352. 'lightskyblue': '#87cefa',
  353. 'lightslategray': '#778899',
  354. 'lightslategrey': '#778899',
  355. 'lightsteelblue': '#b0c4de',
  356. 'lightyellow': '#ffffe0',
  357. 'lime': '#00ff00',
  358. 'limegreen': '#32cd32',
  359. 'linen': '#faf0e6',
  360. 'magenta': '#ff00ff',
  361. 'maroon': '#800000',
  362. 'mediumaquamarine': '#66cdaa',
  363. 'mediumblue': '#0000cd',
  364. 'mediumorchid': '#ba55d3',
  365. 'mediumpurple': '#9370d8',
  366. 'mediumseagreen': '#3cb371',
  367. 'mediumslateblue': '#7b68ee',
  368. 'mediumspringgreen': '#00fa9a',
  369. 'mediumturquoise': '#48d1cc',
  370. 'mediumvioletred': '#c71585',
  371. 'midnightblue': '#191970',
  372. 'mintcream': '#f5fffa',
  373. 'mistyrose': '#ffe4e1',
  374. 'moccasin': '#ffe4b5',
  375. 'navajowhite': '#ffdead',
  376. 'navy': '#000080',
  377. 'oldlace': '#fdf5e6',
  378. 'olive': '#808000',
  379. 'olivedrab': '#6b8e23',
  380. 'orange': '#ffa500',
  381. 'orangered': '#ff4500',
  382. 'orchid': '#da70d6',
  383. 'palegoldenrod': '#eee8aa',
  384. 'palegreen': '#98fb98',
  385. 'paleturquoise': '#afeeee',
  386. 'palevioletred': '#d87093',
  387. 'papayawhip': '#ffefd5',
  388. 'peachpuff': '#ffdab9',
  389. 'peru': '#cd853f',
  390. 'pink': '#ffc0cb',
  391. 'plum': '#dda0dd',
  392. 'powderblue': '#b0e0e6',
  393. 'purple': '#800080',
  394. 'rebeccapurple': '#663399',
  395. 'red': '#ff0000',
  396. 'rosybrown': '#bc8f8f',
  397. 'royalblue': '#4169e1',
  398. 'saddlebrown': '#8b4513',
  399. 'salmon': '#fa8072',
  400. 'sandybrown': '#f4a460',
  401. 'seagreen': '#2e8b57',
  402. 'seashell': '#fff5ee',
  403. 'sienna': '#a0522d',
  404. 'silver': '#c0c0c0',
  405. 'skyblue': '#87ceeb',
  406. 'slateblue': '#6a5acd',
  407. 'slategray': '#708090',
  408. 'slategrey': '#708090',
  409. 'snow': '#fffafa',
  410. 'springgreen': '#00ff7f',
  411. 'steelblue': '#4682b4',
  412. 'tan': '#d2b48c',
  413. 'teal': '#008080',
  414. 'thistle': '#d8bfd8',
  415. 'tomato': '#ff6347',
  416. 'turquoise': '#40e0d0',
  417. 'violet': '#ee82ee',
  418. 'wheat': '#f5deb3',
  419. 'white': '#ffffff',
  420. 'whitesmoke': '#f5f5f5',
  421. 'yellow': '#ffff00',
  422. 'yellowgreen': '#9acd32'
  423. };
  424. var unitConversions = {
  425. length: {
  426. 'm': 1,
  427. 'cm': 0.01,
  428. 'mm': 0.001,
  429. 'in': 0.0254,
  430. 'px': 0.0254 / 96,
  431. 'pt': 0.0254 / 72,
  432. 'pc': 0.0254 / 72 * 12
  433. },
  434. duration: {
  435. 's': 1,
  436. 'ms': 0.001
  437. },
  438. angle: {
  439. 'rad': 1 / (2 * Math.PI),
  440. 'deg': 1 / 360,
  441. 'grad': 1 / 400,
  442. 'turn': 1
  443. }
  444. };
  445. var data = { colors: colors, unitConversions: unitConversions };
  446. /**
  447. * The reason why Node is a class and other nodes simply do not extend
  448. * from Node (since we're transpiling) is due to this issue:
  449. *
  450. * @see https://github.com/less/less.js/issues/3434
  451. */
  452. var Node = /** @class */ (function () {
  453. function Node() {
  454. this.parent = null;
  455. this.visibilityBlocks = undefined;
  456. this.nodeVisible = undefined;
  457. this.rootNode = null;
  458. this.parsed = null;
  459. }
  460. Object.defineProperty(Node.prototype, "currentFileInfo", {
  461. get: function () {
  462. return this.fileInfo();
  463. },
  464. enumerable: false,
  465. configurable: true
  466. });
  467. Object.defineProperty(Node.prototype, "index", {
  468. get: function () {
  469. return this.getIndex();
  470. },
  471. enumerable: false,
  472. configurable: true
  473. });
  474. Node.prototype.setParent = function (nodes, parent) {
  475. function set(node) {
  476. if (node && node instanceof Node) {
  477. node.parent = parent;
  478. }
  479. }
  480. if (Array.isArray(nodes)) {
  481. nodes.forEach(set);
  482. }
  483. else {
  484. set(nodes);
  485. }
  486. };
  487. Node.prototype.getIndex = function () {
  488. return this._index || (this.parent && this.parent.getIndex()) || 0;
  489. };
  490. Node.prototype.fileInfo = function () {
  491. return this._fileInfo || (this.parent && this.parent.fileInfo()) || {};
  492. };
  493. Node.prototype.isRulesetLike = function () { return false; };
  494. Node.prototype.toCSS = function (context) {
  495. var strs = [];
  496. this.genCSS(context, {
  497. // remove when genCSS has JSDoc types
  498. // eslint-disable-next-line no-unused-vars
  499. add: function (chunk, fileInfo, index) {
  500. strs.push(chunk);
  501. },
  502. isEmpty: function () {
  503. return strs.length === 0;
  504. }
  505. });
  506. return strs.join('');
  507. };
  508. Node.prototype.genCSS = function (context, output) {
  509. output.add(this.value);
  510. };
  511. Node.prototype.accept = function (visitor) {
  512. this.value = visitor.visit(this.value);
  513. };
  514. Node.prototype.eval = function () { return this; };
  515. Node.prototype._operate = function (context, op, a, b) {
  516. switch (op) {
  517. case '+': return a + b;
  518. case '-': return a - b;
  519. case '*': return a * b;
  520. case '/': return a / b;
  521. }
  522. };
  523. Node.prototype.fround = function (context, value) {
  524. var precision = context && context.numPrecision;
  525. // add "epsilon" to ensure numbers like 1.000000005 (represented as 1.000000004999...) are properly rounded:
  526. return (precision) ? Number((value + 2e-16).toFixed(precision)) : value;
  527. };
  528. Node.compare = function (a, b) {
  529. /* returns:
  530. -1: a < b
  531. 0: a = b
  532. 1: a > b
  533. and *any* other value for a != b (e.g. undefined, NaN, -2 etc.) */
  534. if ((a.compare) &&
  535. // for "symmetric results" force toCSS-based comparison
  536. // of Quoted or Anonymous if either value is one of those
  537. !(b.type === 'Quoted' || b.type === 'Anonymous')) {
  538. return a.compare(b);
  539. }
  540. else if (b.compare) {
  541. return -b.compare(a);
  542. }
  543. else if (a.type !== b.type) {
  544. return undefined;
  545. }
  546. a = a.value;
  547. b = b.value;
  548. if (!Array.isArray(a)) {
  549. return a === b ? 0 : undefined;
  550. }
  551. if (a.length !== b.length) {
  552. return undefined;
  553. }
  554. for (var i_1 = 0; i_1 < a.length; i_1++) {
  555. if (Node.compare(a[i_1], b[i_1]) !== 0) {
  556. return undefined;
  557. }
  558. }
  559. return 0;
  560. };
  561. Node.numericCompare = function (a, b) {
  562. return a < b ? -1
  563. : a === b ? 0
  564. : a > b ? 1 : undefined;
  565. };
  566. // Returns true if this node represents root of ast imported by reference
  567. Node.prototype.blocksVisibility = function () {
  568. if (this.visibilityBlocks === undefined) {
  569. this.visibilityBlocks = 0;
  570. }
  571. return this.visibilityBlocks !== 0;
  572. };
  573. Node.prototype.addVisibilityBlock = function () {
  574. if (this.visibilityBlocks === undefined) {
  575. this.visibilityBlocks = 0;
  576. }
  577. this.visibilityBlocks = this.visibilityBlocks + 1;
  578. };
  579. Node.prototype.removeVisibilityBlock = function () {
  580. if (this.visibilityBlocks === undefined) {
  581. this.visibilityBlocks = 0;
  582. }
  583. this.visibilityBlocks = this.visibilityBlocks - 1;
  584. };
  585. // Turns on node visibility - if called node will be shown in output regardless
  586. // of whether it comes from import by reference or not
  587. Node.prototype.ensureVisibility = function () {
  588. this.nodeVisible = true;
  589. };
  590. // Turns off node visibility - if called node will NOT be shown in output regardless
  591. // of whether it comes from import by reference or not
  592. Node.prototype.ensureInvisibility = function () {
  593. this.nodeVisible = false;
  594. };
  595. // return values:
  596. // false - the node must not be visible
  597. // true - the node must be visible
  598. // undefined or null - the node has the same visibility as its parent
  599. Node.prototype.isVisible = function () {
  600. return this.nodeVisible;
  601. };
  602. Node.prototype.visibilityInfo = function () {
  603. return {
  604. visibilityBlocks: this.visibilityBlocks,
  605. nodeVisible: this.nodeVisible
  606. };
  607. };
  608. Node.prototype.copyVisibilityInfo = function (info) {
  609. if (!info) {
  610. return;
  611. }
  612. this.visibilityBlocks = info.visibilityBlocks;
  613. this.nodeVisible = info.nodeVisible;
  614. };
  615. return Node;
  616. }());
  617. //
  618. // RGB Colors - #ff0014, #eee
  619. //
  620. var Color = function (rgb, a, originalForm) {
  621. var self = this;
  622. //
  623. // The end goal here, is to parse the arguments
  624. // into an integer triplet, such as `128, 255, 0`
  625. //
  626. // This facilitates operations and conversions.
  627. //
  628. if (Array.isArray(rgb)) {
  629. this.rgb = rgb;
  630. }
  631. else if (rgb.length >= 6) {
  632. this.rgb = [];
  633. rgb.match(/.{2}/g).map(function (c, i) {
  634. if (i < 3) {
  635. self.rgb.push(parseInt(c, 16));
  636. }
  637. else {
  638. self.alpha = (parseInt(c, 16)) / 255;
  639. }
  640. });
  641. }
  642. else {
  643. this.rgb = [];
  644. rgb.split('').map(function (c, i) {
  645. if (i < 3) {
  646. self.rgb.push(parseInt(c + c, 16));
  647. }
  648. else {
  649. self.alpha = (parseInt(c + c, 16)) / 255;
  650. }
  651. });
  652. }
  653. this.alpha = this.alpha || (typeof a === 'number' ? a : 1);
  654. if (typeof originalForm !== 'undefined') {
  655. this.value = originalForm;
  656. }
  657. };
  658. Color.prototype = Object.assign(new Node(), {
  659. type: 'Color',
  660. luma: function () {
  661. var r = this.rgb[0] / 255, g = this.rgb[1] / 255, b = this.rgb[2] / 255;
  662. r = (r <= 0.03928) ? r / 12.92 : Math.pow(((r + 0.055) / 1.055), 2.4);
  663. g = (g <= 0.03928) ? g / 12.92 : Math.pow(((g + 0.055) / 1.055), 2.4);
  664. b = (b <= 0.03928) ? b / 12.92 : Math.pow(((b + 0.055) / 1.055), 2.4);
  665. return 0.2126 * r + 0.7152 * g + 0.0722 * b;
  666. },
  667. genCSS: function (context, output) {
  668. output.add(this.toCSS(context));
  669. },
  670. toCSS: function (context, doNotCompress) {
  671. var compress = context && context.compress && !doNotCompress;
  672. var color;
  673. var alpha;
  674. var colorFunction;
  675. var args = [];
  676. // `value` is set if this color was originally
  677. // converted from a named color string so we need
  678. // to respect this and try to output named color too.
  679. alpha = this.fround(context, this.alpha);
  680. if (this.value) {
  681. if (this.value.indexOf('rgb') === 0) {
  682. if (alpha < 1) {
  683. colorFunction = 'rgba';
  684. }
  685. }
  686. else if (this.value.indexOf('hsl') === 0) {
  687. if (alpha < 1) {
  688. colorFunction = 'hsla';
  689. }
  690. else {
  691. colorFunction = 'hsl';
  692. }
  693. }
  694. else {
  695. return this.value;
  696. }
  697. }
  698. else {
  699. if (alpha < 1) {
  700. colorFunction = 'rgba';
  701. }
  702. }
  703. switch (colorFunction) {
  704. case 'rgba':
  705. args = this.rgb.map(function (c) {
  706. return clamp$1(Math.round(c), 255);
  707. }).concat(clamp$1(alpha, 1));
  708. break;
  709. case 'hsla':
  710. args.push(clamp$1(alpha, 1));
  711. // eslint-disable-next-line no-fallthrough
  712. case 'hsl':
  713. color = this.toHSL();
  714. args = [
  715. this.fround(context, color.h),
  716. this.fround(context, color.s * 100) + "%",
  717. this.fround(context, color.l * 100) + "%"
  718. ].concat(args);
  719. }
  720. if (colorFunction) {
  721. // Values are capped between `0` and `255`, rounded and zero-padded.
  722. return colorFunction + "(" + args.join("," + (compress ? '' : ' ')) + ")";
  723. }
  724. color = this.toRGB();
  725. if (compress) {
  726. var splitcolor = color.split('');
  727. // Convert color to short format
  728. if (splitcolor[1] === splitcolor[2] && splitcolor[3] === splitcolor[4] && splitcolor[5] === splitcolor[6]) {
  729. color = "#" + splitcolor[1] + splitcolor[3] + splitcolor[5];
  730. }
  731. }
  732. return color;
  733. },
  734. //
  735. // Operations have to be done per-channel, if not,
  736. // channels will spill onto each other. Once we have
  737. // our result, in the form of an integer triplet,
  738. // we create a new Color node to hold the result.
  739. //
  740. operate: function (context, op, other) {
  741. var rgb = new Array(3);
  742. var alpha = this.alpha * (1 - other.alpha) + other.alpha;
  743. for (var c = 0; c < 3; c++) {
  744. rgb[c] = this._operate(context, op, this.rgb[c], other.rgb[c]);
  745. }
  746. return new Color(rgb, alpha);
  747. },
  748. toRGB: function () {
  749. return toHex(this.rgb);
  750. },
  751. toHSL: function () {
  752. var r = this.rgb[0] / 255, g = this.rgb[1] / 255, b = this.rgb[2] / 255, a = this.alpha;
  753. var max = Math.max(r, g, b), min = Math.min(r, g, b);
  754. var h;
  755. var s;
  756. var l = (max + min) / 2;
  757. var d = max - min;
  758. if (max === min) {
  759. h = s = 0;
  760. }
  761. else {
  762. s = l > 0.5 ? d / (2 - max - min) : d / (max + min);
  763. switch (max) {
  764. case r:
  765. h = (g - b) / d + (g < b ? 6 : 0);
  766. break;
  767. case g:
  768. h = (b - r) / d + 2;
  769. break;
  770. case b:
  771. h = (r - g) / d + 4;
  772. break;
  773. }
  774. h /= 6;
  775. }
  776. return { h: h * 360, s: s, l: l, a: a };
  777. },
  778. // Adapted from http://mjijackson.com/2008/02/rgb-to-hsl-and-rgb-to-hsv-color-model-conversion-algorithms-in-javascript
  779. toHSV: function () {
  780. var r = this.rgb[0] / 255, g = this.rgb[1] / 255, b = this.rgb[2] / 255, a = this.alpha;
  781. var max = Math.max(r, g, b), min = Math.min(r, g, b);
  782. var h;
  783. var s;
  784. var v = max;
  785. var d = max - min;
  786. if (max === 0) {
  787. s = 0;
  788. }
  789. else {
  790. s = d / max;
  791. }
  792. if (max === min) {
  793. h = 0;
  794. }
  795. else {
  796. switch (max) {
  797. case r:
  798. h = (g - b) / d + (g < b ? 6 : 0);
  799. break;
  800. case g:
  801. h = (b - r) / d + 2;
  802. break;
  803. case b:
  804. h = (r - g) / d + 4;
  805. break;
  806. }
  807. h /= 6;
  808. }
  809. return { h: h * 360, s: s, v: v, a: a };
  810. },
  811. toARGB: function () {
  812. return toHex([this.alpha * 255].concat(this.rgb));
  813. },
  814. compare: function (x) {
  815. return (x.rgb &&
  816. x.rgb[0] === this.rgb[0] &&
  817. x.rgb[1] === this.rgb[1] &&
  818. x.rgb[2] === this.rgb[2] &&
  819. x.alpha === this.alpha) ? 0 : undefined;
  820. }
  821. });
  822. Color.fromKeyword = function (keyword) {
  823. var c;
  824. var key = keyword.toLowerCase();
  825. // eslint-disable-next-line no-prototype-builtins
  826. if (colors.hasOwnProperty(key)) {
  827. c = new Color(colors[key].slice(1));
  828. }
  829. else if (key === 'transparent') {
  830. c = new Color([0, 0, 0], 0);
  831. }
  832. if (c) {
  833. c.value = keyword;
  834. return c;
  835. }
  836. };
  837. function clamp$1(v, max) {
  838. return Math.min(Math.max(v, 0), max);
  839. }
  840. function toHex(v) {
  841. return "#" + v.map(function (c) {
  842. c = clamp$1(Math.round(c), 255);
  843. return (c < 16 ? '0' : '') + c.toString(16);
  844. }).join('');
  845. }
  846. var Paren = function (node) {
  847. this.value = node;
  848. };
  849. Paren.prototype = Object.assign(new Node(), {
  850. type: 'Paren',
  851. genCSS: function (context, output) {
  852. output.add('(');
  853. this.value.genCSS(context, output);
  854. output.add(')');
  855. },
  856. eval: function (context) {
  857. return new Paren(this.value.eval(context));
  858. }
  859. });
  860. var _noSpaceCombinators = {
  861. '': true,
  862. ' ': true,
  863. '|': true
  864. };
  865. var Combinator = function (value) {
  866. if (value === ' ') {
  867. this.value = ' ';
  868. this.emptyOrWhitespace = true;
  869. }
  870. else {
  871. this.value = value ? value.trim() : '';
  872. this.emptyOrWhitespace = this.value === '';
  873. }
  874. };
  875. Combinator.prototype = Object.assign(new Node(), {
  876. type: 'Combinator',
  877. genCSS: function (context, output) {
  878. var spaceOrEmpty = (context.compress || _noSpaceCombinators[this.value]) ? '' : ' ';
  879. output.add(spaceOrEmpty + this.value + spaceOrEmpty);
  880. }
  881. });
  882. var Element = function (combinator, value, isVariable, index, currentFileInfo, visibilityInfo) {
  883. this.combinator = combinator instanceof Combinator ?
  884. combinator : new Combinator(combinator);
  885. if (typeof value === 'string') {
  886. this.value = value.trim();
  887. }
  888. else if (value) {
  889. this.value = value;
  890. }
  891. else {
  892. this.value = '';
  893. }
  894. this.isVariable = isVariable;
  895. this._index = index;
  896. this._fileInfo = currentFileInfo;
  897. this.copyVisibilityInfo(visibilityInfo);
  898. this.setParent(this.combinator, this);
  899. };
  900. Element.prototype = Object.assign(new Node(), {
  901. type: 'Element',
  902. accept: function (visitor) {
  903. var value = this.value;
  904. this.combinator = visitor.visit(this.combinator);
  905. if (typeof value === 'object') {
  906. this.value = visitor.visit(value);
  907. }
  908. },
  909. eval: function (context) {
  910. return new Element(this.combinator, this.value.eval ? this.value.eval(context) : this.value, this.isVariable, this.getIndex(), this.fileInfo(), this.visibilityInfo());
  911. },
  912. clone: function () {
  913. return new Element(this.combinator, this.value, this.isVariable, this.getIndex(), this.fileInfo(), this.visibilityInfo());
  914. },
  915. genCSS: function (context, output) {
  916. output.add(this.toCSS(context), this.fileInfo(), this.getIndex());
  917. },
  918. toCSS: function (context) {
  919. context = context || {};
  920. var value = this.value;
  921. var firstSelector = context.firstSelector;
  922. if (value instanceof Paren) {
  923. // selector in parens should not be affected by outer selector
  924. // flags (breaks only interpolated selectors - see #1973)
  925. context.firstSelector = true;
  926. }
  927. value = value.toCSS ? value.toCSS(context) : value;
  928. context.firstSelector = firstSelector;
  929. if (value === '' && this.combinator.value.charAt(0) === '&') {
  930. return '';
  931. }
  932. else {
  933. return this.combinator.toCSS(context) + value;
  934. }
  935. }
  936. });
  937. var Math$1 = {
  938. ALWAYS: 0,
  939. PARENS_DIVISION: 1,
  940. PARENS: 2
  941. // removed - STRICT_LEGACY: 3
  942. };
  943. var RewriteUrls = {
  944. OFF: 0,
  945. LOCAL: 1,
  946. ALL: 2
  947. };
  948. /**
  949. * Returns the object type of the given payload
  950. *
  951. * @param {*} payload
  952. * @returns {string}
  953. */
  954. function getType(payload) {
  955. return Object.prototype.toString.call(payload).slice(8, -1);
  956. }
  957. /**
  958. * Returns whether the payload is a plain JavaScript object (excluding special classes or objects with other prototypes)
  959. *
  960. * @param {*} payload
  961. * @returns {payload is Record<string, any>}
  962. */
  963. function isPlainObject(payload) {
  964. if (getType(payload) !== 'Object')
  965. return false;
  966. return payload.constructor === Object && Object.getPrototypeOf(payload) === Object.prototype;
  967. }
  968. /**
  969. * Returns whether the payload is an array
  970. *
  971. * @param {any} payload
  972. * @returns {payload is any[]}
  973. */
  974. function isArray(payload) {
  975. return getType(payload) === 'Array';
  976. }
  977. /*! *****************************************************************************
  978. Copyright (c) Microsoft Corporation. All rights reserved.
  979. Licensed under the Apache License, Version 2.0 (the "License"); you may not use
  980. this file except in compliance with the License. You may obtain a copy of the
  981. License at http://www.apache.org/licenses/LICENSE-2.0
  982. THIS CODE IS PROVIDED ON AN *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  983. KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY IMPLIED
  984. WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE,
  985. MERCHANTABLITY OR NON-INFRINGEMENT.
  986. See the Apache Version 2.0 License for specific language governing permissions
  987. and limitations under the License.
  988. ***************************************************************************** */
  989. function __spreadArrays() {
  990. for (var s = 0, i = 0, il = arguments.length; i < il; i++)
  991. s += arguments[i].length;
  992. for (var r = Array(s), k = 0, i = 0; i < il; i++)
  993. for (var a = arguments[i], j = 0, jl = a.length; j < jl; j++, k++)
  994. r[k] = a[j];
  995. return r;
  996. }
  997. function assignProp(carry, key, newVal, originalObject, includeNonenumerable) {
  998. var propType = {}.propertyIsEnumerable.call(originalObject, key)
  999. ? 'enumerable'
  1000. : 'nonenumerable';
  1001. if (propType === 'enumerable')
  1002. carry[key] = newVal;
  1003. if (includeNonenumerable && propType === 'nonenumerable') {
  1004. Object.defineProperty(carry, key, {
  1005. value: newVal,
  1006. enumerable: false,
  1007. writable: true,
  1008. configurable: true,
  1009. });
  1010. }
  1011. }
  1012. /**
  1013. * Copy (clone) an object and all its props recursively to get rid of any prop referenced of the original object. Arrays are also cloned, however objects inside arrays are still linked.
  1014. *
  1015. * @export
  1016. * @template T
  1017. * @param {T} target Target can be anything
  1018. * @param {Options} [options={}] Options can be `props` or `nonenumerable`
  1019. * @returns {T} the target with replaced values
  1020. * @export
  1021. */
  1022. function copy(target, options) {
  1023. if (options === void 0) {
  1024. options = {};
  1025. }
  1026. if (isArray(target))
  1027. return target.map(function (i) { return copy(i, options); });
  1028. if (!isPlainObject(target))
  1029. return target;
  1030. var props = Object.getOwnPropertyNames(target);
  1031. var symbols = Object.getOwnPropertySymbols(target);
  1032. return __spreadArrays(props, symbols).reduce(function (carry, key) {
  1033. if (isArray(options.props) && !options.props.includes(key)) {
  1034. return carry;
  1035. }
  1036. var val = target[key];
  1037. var newVal = copy(val, options);
  1038. assignProp(carry, key, newVal, target, options.nonenumerable);
  1039. return carry;
  1040. }, {});
  1041. }
  1042. /* jshint proto: true */
  1043. function getLocation(index, inputStream) {
  1044. var n = index + 1;
  1045. var line = null;
  1046. var column = -1;
  1047. while (--n >= 0 && inputStream.charAt(n) !== '\n') {
  1048. column++;
  1049. }
  1050. if (typeof index === 'number') {
  1051. line = (inputStream.slice(0, index).match(/\n/g) || '').length;
  1052. }
  1053. return {
  1054. line: line,
  1055. column: column
  1056. };
  1057. }
  1058. function copyArray(arr) {
  1059. var i;
  1060. var length = arr.length;
  1061. var copy = new Array(length);
  1062. for (i = 0; i < length; i++) {
  1063. copy[i] = arr[i];
  1064. }
  1065. return copy;
  1066. }
  1067. function clone(obj) {
  1068. var cloned = {};
  1069. for (var prop in obj) {
  1070. if (Object.prototype.hasOwnProperty.call(obj, prop)) {
  1071. cloned[prop] = obj[prop];
  1072. }
  1073. }
  1074. return cloned;
  1075. }
  1076. function defaults(obj1, obj2) {
  1077. var newObj = obj2 || {};
  1078. if (!obj2._defaults) {
  1079. newObj = {};
  1080. var defaults_1 = copy(obj1);
  1081. newObj._defaults = defaults_1;
  1082. var cloned = obj2 ? copy(obj2) : {};
  1083. Object.assign(newObj, defaults_1, cloned);
  1084. }
  1085. return newObj;
  1086. }
  1087. function copyOptions(obj1, obj2) {
  1088. if (obj2 && obj2._defaults) {
  1089. return obj2;
  1090. }
  1091. var opts = defaults(obj1, obj2);
  1092. if (opts.strictMath) {
  1093. opts.math = Math$1.PARENS;
  1094. }
  1095. // Back compat with changed relativeUrls option
  1096. if (opts.relativeUrls) {
  1097. opts.rewriteUrls = RewriteUrls.ALL;
  1098. }
  1099. if (typeof opts.math === 'string') {
  1100. switch (opts.math.toLowerCase()) {
  1101. case 'always':
  1102. opts.math = Math$1.ALWAYS;
  1103. break;
  1104. case 'parens-division':
  1105. opts.math = Math$1.PARENS_DIVISION;
  1106. break;
  1107. case 'strict':
  1108. case 'parens':
  1109. opts.math = Math$1.PARENS;
  1110. break;
  1111. default:
  1112. opts.math = Math$1.PARENS;
  1113. }
  1114. }
  1115. if (typeof opts.rewriteUrls === 'string') {
  1116. switch (opts.rewriteUrls.toLowerCase()) {
  1117. case 'off':
  1118. opts.rewriteUrls = RewriteUrls.OFF;
  1119. break;
  1120. case 'local':
  1121. opts.rewriteUrls = RewriteUrls.LOCAL;
  1122. break;
  1123. case 'all':
  1124. opts.rewriteUrls = RewriteUrls.ALL;
  1125. break;
  1126. }
  1127. }
  1128. return opts;
  1129. }
  1130. function merge(obj1, obj2) {
  1131. for (var prop in obj2) {
  1132. if (Object.prototype.hasOwnProperty.call(obj2, prop)) {
  1133. obj1[prop] = obj2[prop];
  1134. }
  1135. }
  1136. return obj1;
  1137. }
  1138. function flattenArray(arr, result) {
  1139. if (result === void 0) { result = []; }
  1140. for (var i_1 = 0, length_1 = arr.length; i_1 < length_1; i_1++) {
  1141. var value = arr[i_1];
  1142. if (Array.isArray(value)) {
  1143. flattenArray(value, result);
  1144. }
  1145. else {
  1146. if (value !== undefined) {
  1147. result.push(value);
  1148. }
  1149. }
  1150. }
  1151. return result;
  1152. }
  1153. function isNullOrUndefined(val) {
  1154. return val === null || val === undefined;
  1155. }
  1156. var utils = /*#__PURE__*/Object.freeze({
  1157. __proto__: null,
  1158. getLocation: getLocation,
  1159. copyArray: copyArray,
  1160. clone: clone,
  1161. defaults: defaults,
  1162. copyOptions: copyOptions,
  1163. merge: merge,
  1164. flattenArray: flattenArray,
  1165. isNullOrUndefined: isNullOrUndefined
  1166. });
  1167. var anonymousFunc = /(<anonymous>|Function):(\d+):(\d+)/;
  1168. /**
  1169. * This is a centralized class of any error that could be thrown internally (mostly by the parser).
  1170. * Besides standard .message it keeps some additional data like a path to the file where the error
  1171. * occurred along with line and column numbers.
  1172. *
  1173. * @class
  1174. * @extends Error
  1175. * @type {module.LessError}
  1176. *
  1177. * @prop {string} type
  1178. * @prop {string} filename
  1179. * @prop {number} index
  1180. * @prop {number} line
  1181. * @prop {number} column
  1182. * @prop {number} callLine
  1183. * @prop {number} callExtract
  1184. * @prop {string[]} extract
  1185. *
  1186. * @param {Object} e - An error object to wrap around or just a descriptive object
  1187. * @param {Object} fileContentMap - An object with file contents in 'contents' property (like importManager) @todo - move to fileManager?
  1188. * @param {string} [currentFilename]
  1189. */
  1190. var LessError = function (e, fileContentMap, currentFilename) {
  1191. Error.call(this);
  1192. var filename = e.filename || currentFilename;
  1193. this.message = e.message;
  1194. this.stack = e.stack;
  1195. if (fileContentMap && filename) {
  1196. var input = fileContentMap.contents[filename];
  1197. var loc = getLocation(e.index, input);
  1198. var line = loc.line;
  1199. var col = loc.column;
  1200. var callLine = e.call && getLocation(e.call, input).line;
  1201. var lines = input ? input.split('\n') : '';
  1202. this.type = e.type || 'Syntax';
  1203. this.filename = filename;
  1204. this.index = e.index;
  1205. this.line = typeof line === 'number' ? line + 1 : null;
  1206. this.column = col;
  1207. if (!this.line && this.stack) {
  1208. var found = this.stack.match(anonymousFunc);
  1209. /**
  1210. * We have to figure out how this environment stringifies anonymous functions
  1211. * so we can correctly map plugin errors.
  1212. *
  1213. * Note, in Node 8, the output of anonymous funcs varied based on parameters
  1214. * being present or not, so we inject dummy params.
  1215. */
  1216. var func = new Function('a', 'throw new Error()');
  1217. var lineAdjust = 0;
  1218. try {
  1219. func();
  1220. }
  1221. catch (e) {
  1222. var match = e.stack.match(anonymousFunc);
  1223. lineAdjust = 1 - parseInt(match[2]);
  1224. }
  1225. if (found) {
  1226. if (found[2]) {
  1227. this.line = parseInt(found[2]) + lineAdjust;
  1228. }
  1229. if (found[3]) {
  1230. this.column = parseInt(found[3]);
  1231. }
  1232. }
  1233. }
  1234. this.callLine = callLine + 1;
  1235. this.callExtract = lines[callLine];
  1236. this.extract = [
  1237. lines[this.line - 2],
  1238. lines[this.line - 1],
  1239. lines[this.line]
  1240. ];
  1241. }
  1242. };
  1243. if (typeof Object.create === 'undefined') {
  1244. var F = function () { };
  1245. F.prototype = Error.prototype;
  1246. LessError.prototype = new F();
  1247. }
  1248. else {
  1249. LessError.prototype = Object.create(Error.prototype);
  1250. }
  1251. LessError.prototype.constructor = LessError;
  1252. /**
  1253. * An overridden version of the default Object.prototype.toString
  1254. * which uses additional information to create a helpful message.
  1255. *
  1256. * @param {Object} options
  1257. * @returns {string}
  1258. */
  1259. LessError.prototype.toString = function (options) {
  1260. options = options || {};
  1261. var message = '';
  1262. var extract = this.extract || [];
  1263. var error = [];
  1264. var stylize = function (str) { return str; };
  1265. if (options.stylize) {
  1266. var type = typeof options.stylize;
  1267. if (type !== 'function') {
  1268. throw Error("options.stylize should be a function, got a " + type + "!");
  1269. }
  1270. stylize = options.stylize;
  1271. }
  1272. if (this.line !== null) {
  1273. if (typeof extract[0] === 'string') {
  1274. error.push(stylize(this.line - 1 + " " + extract[0], 'grey'));
  1275. }
  1276. if (typeof extract[1] === 'string') {
  1277. var errorTxt = this.line + " ";
  1278. if (extract[1]) {
  1279. errorTxt += extract[1].slice(0, this.column) +
  1280. stylize(stylize(stylize(extract[1].substr(this.column, 1), 'bold') +
  1281. extract[1].slice(this.column + 1), 'red'), 'inverse');
  1282. }
  1283. error.push(errorTxt);
  1284. }
  1285. if (typeof extract[2] === 'string') {
  1286. error.push(stylize(this.line + 1 + " " + extract[2], 'grey'));
  1287. }
  1288. error = error.join('\n') + stylize('', 'reset') + "\n";
  1289. }
  1290. message += stylize(this.type + "Error: " + this.message, 'red');
  1291. if (this.filename) {
  1292. message += stylize(' in ', 'red') + this.filename;
  1293. }
  1294. if (this.line) {
  1295. message += stylize(" on line " + this.line + ", column " + (this.column + 1) + ":", 'grey');
  1296. }
  1297. message += "\n" + error;
  1298. if (this.callLine) {
  1299. message += stylize('from ', 'red') + (this.filename || '') + "/n";
  1300. message += stylize(this.callLine, 'grey') + " " + this.callExtract + "/n";
  1301. }
  1302. return message;
  1303. };
  1304. var _visitArgs = { visitDeeper: true };
  1305. var _hasIndexed = false;
  1306. function _noop(node) {
  1307. return node;
  1308. }
  1309. function indexNodeTypes(parent, ticker) {
  1310. // add .typeIndex to tree node types for lookup table
  1311. var key, child;
  1312. for (key in parent) {
  1313. /* eslint guard-for-in: 0 */
  1314. child = parent[key];
  1315. switch (typeof child) {
  1316. case 'function':
  1317. // ignore bound functions directly on tree which do not have a prototype
  1318. // or aren't nodes
  1319. if (child.prototype && child.prototype.type) {
  1320. child.prototype.typeIndex = ticker++;
  1321. }
  1322. break;
  1323. case 'object':
  1324. ticker = indexNodeTypes(child, ticker);
  1325. break;
  1326. }
  1327. }
  1328. return ticker;
  1329. }
  1330. var Visitor = /** @class */ (function () {
  1331. function Visitor(implementation) {
  1332. this._implementation = implementation;
  1333. this._visitInCache = {};
  1334. this._visitOutCache = {};
  1335. if (!_hasIndexed) {
  1336. indexNodeTypes(tree, 1);
  1337. _hasIndexed = true;
  1338. }
  1339. }
  1340. Visitor.prototype.visit = function (node) {
  1341. if (!node) {
  1342. return node;
  1343. }
  1344. var nodeTypeIndex = node.typeIndex;
  1345. if (!nodeTypeIndex) {
  1346. // MixinCall args aren't a node type?
  1347. if (node.value && node.value.typeIndex) {
  1348. this.visit(node.value);
  1349. }
  1350. return node;
  1351. }
  1352. var impl = this._implementation;
  1353. var func = this._visitInCache[nodeTypeIndex];
  1354. var funcOut = this._visitOutCache[nodeTypeIndex];
  1355. var visitArgs = _visitArgs;
  1356. var fnName;
  1357. visitArgs.visitDeeper = true;
  1358. if (!func) {
  1359. fnName = "visit" + node.type;
  1360. func = impl[fnName] || _noop;
  1361. funcOut = impl[fnName + "Out"] || _noop;
  1362. this._visitInCache[nodeTypeIndex] = func;
  1363. this._visitOutCache[nodeTypeIndex] = funcOut;
  1364. }
  1365. if (func !== _noop) {
  1366. var newNode = func.call(impl, node, visitArgs);
  1367. if (node && impl.isReplacing) {
  1368. node = newNode;
  1369. }
  1370. }
  1371. if (visitArgs.visitDeeper && node) {
  1372. if (node.length) {
  1373. for (var i_1 = 0, cnt = node.length; i_1 < cnt; i_1++) {
  1374. if (node[i_1].accept) {
  1375. node[i_1].accept(this);
  1376. }
  1377. }
  1378. }
  1379. else if (node.accept) {
  1380. node.accept(this);
  1381. }
  1382. }
  1383. if (funcOut != _noop) {
  1384. funcOut.call(impl, node);
  1385. }
  1386. return node;
  1387. };
  1388. Visitor.prototype.visitArray = function (nodes, nonReplacing) {
  1389. if (!nodes) {
  1390. return nodes;
  1391. }
  1392. var cnt = nodes.length;
  1393. var i;
  1394. // Non-replacing
  1395. if (nonReplacing || !this._implementation.isReplacing) {
  1396. for (i = 0; i < cnt; i++) {
  1397. this.visit(nodes[i]);
  1398. }
  1399. return nodes;
  1400. }
  1401. // Replacing
  1402. var out = [];
  1403. for (i = 0; i < cnt; i++) {
  1404. var evald = this.visit(nodes[i]);
  1405. if (evald === undefined) {
  1406. continue;
  1407. }
  1408. if (!evald.splice) {
  1409. out.push(evald);
  1410. }
  1411. else if (evald.length) {
  1412. this.flatten(evald, out);
  1413. }
  1414. }
  1415. return out;
  1416. };
  1417. Visitor.prototype.flatten = function (arr, out) {
  1418. if (!out) {
  1419. out = [];
  1420. }
  1421. var cnt, i, item, nestedCnt, j, nestedItem;
  1422. for (i = 0, cnt = arr.length; i < cnt; i++) {
  1423. item = arr[i];
  1424. if (item === undefined) {
  1425. continue;
  1426. }
  1427. if (!item.splice) {
  1428. out.push(item);
  1429. continue;
  1430. }
  1431. for (j = 0, nestedCnt = item.length; j < nestedCnt; j++) {
  1432. nestedItem = item[j];
  1433. if (nestedItem === undefined) {
  1434. continue;
  1435. }
  1436. if (!nestedItem.splice) {
  1437. out.push(nestedItem);
  1438. }
  1439. else if (nestedItem.length) {
  1440. this.flatten(nestedItem, out);
  1441. }
  1442. }
  1443. }
  1444. return out;
  1445. };
  1446. return Visitor;
  1447. }());
  1448. var contexts = {};
  1449. var copyFromOriginal = function copyFromOriginal(original, destination, propertiesToCopy) {
  1450. if (!original) {
  1451. return;
  1452. }
  1453. for (var i_1 = 0; i_1 < propertiesToCopy.length; i_1++) {
  1454. if (Object.prototype.hasOwnProperty.call(original, propertiesToCopy[i_1])) {
  1455. destination[propertiesToCopy[i_1]] = original[propertiesToCopy[i_1]];
  1456. }
  1457. }
  1458. };
  1459. /*
  1460. parse is used whilst parsing
  1461. */
  1462. var parseCopyProperties = [
  1463. // options
  1464. 'paths',
  1465. 'rewriteUrls',
  1466. 'rootpath',
  1467. 'strictImports',
  1468. 'insecure',
  1469. 'dumpLineNumbers',
  1470. 'compress',
  1471. 'syncImport',
  1472. 'chunkInput',
  1473. 'mime',
  1474. 'useFileCache',
  1475. // context
  1476. 'processImports',
  1477. // Used by the import manager to stop multiple import visitors being created.
  1478. 'pluginManager' // Used as the plugin manager for the session
  1479. ];
  1480. contexts.Parse = function (options) {
  1481. copyFromOriginal(options, this, parseCopyProperties);
  1482. if (typeof this.paths === 'string') {
  1483. this.paths = [this.paths];
  1484. }
  1485. };
  1486. var evalCopyProperties = [
  1487. 'paths',
  1488. 'compress',
  1489. 'math',
  1490. 'strictUnits',
  1491. 'sourceMap',
  1492. 'importMultiple',
  1493. 'urlArgs',
  1494. 'javascriptEnabled',
  1495. 'pluginManager',
  1496. 'importantScope',
  1497. 'rewriteUrls' // option - whether to adjust URL's to be relative
  1498. ];
  1499. contexts.Eval = function (options, frames) {
  1500. copyFromOriginal(options, this, evalCopyProperties);
  1501. if (typeof this.paths === 'string') {
  1502. this.paths = [this.paths];
  1503. }
  1504. this.frames = frames || [];
  1505. this.importantScope = this.importantScope || [];
  1506. };
  1507. contexts.Eval.prototype.enterCalc = function () {
  1508. if (!this.calcStack) {
  1509. this.calcStack = [];
  1510. }
  1511. this.calcStack.push(true);
  1512. this.inCalc = true;
  1513. };
  1514. contexts.Eval.prototype.exitCalc = function () {
  1515. this.calcStack.pop();
  1516. if (!this.calcStack.length) {
  1517. this.inCalc = false;
  1518. }
  1519. };
  1520. contexts.Eval.prototype.inParenthesis = function () {
  1521. if (!this.parensStack) {
  1522. this.parensStack = [];
  1523. }
  1524. this.parensStack.push(true);
  1525. };
  1526. contexts.Eval.prototype.outOfParenthesis = function () {
  1527. this.parensStack.pop();
  1528. };
  1529. contexts.Eval.prototype.inCalc = false;
  1530. contexts.Eval.prototype.mathOn = true;
  1531. contexts.Eval.prototype.isMathOn = function (op) {
  1532. if (!this.mathOn) {
  1533. return false;
  1534. }
  1535. if (op === '/' && this.math !== Math$1.ALWAYS && (!this.parensStack || !this.parensStack.length)) {
  1536. return false;
  1537. }
  1538. if (this.math > Math$1.PARENS_DIVISION) {
  1539. return this.parensStack && this.parensStack.length;
  1540. }
  1541. return true;
  1542. };
  1543. contexts.Eval.prototype.pathRequiresRewrite = function (path) {
  1544. var isRelative = this.rewriteUrls === RewriteUrls.LOCAL ? isPathLocalRelative : isPathRelative;
  1545. return isRelative(path);
  1546. };
  1547. contexts.Eval.prototype.rewritePath = function (path, rootpath) {
  1548. var newPath;
  1549. rootpath = rootpath || '';
  1550. newPath = this.normalizePath(rootpath + path);
  1551. // If a path was explicit relative and the rootpath was not an absolute path
  1552. // we must ensure that the new path is also explicit relative.
  1553. if (isPathLocalRelative(path) &&
  1554. isPathRelative(rootpath) &&
  1555. isPathLocalRelative(newPath) === false) {
  1556. newPath = "./" + newPath;
  1557. }
  1558. return newPath;
  1559. };
  1560. contexts.Eval.prototype.normalizePath = function (path) {
  1561. var segments = path.split('/').reverse();
  1562. var segment;
  1563. path = [];
  1564. while (segments.length !== 0) {
  1565. segment = segments.pop();
  1566. switch (segment) {
  1567. case '.':
  1568. break;
  1569. case '..':
  1570. if ((path.length === 0) || (path[path.length - 1] === '..')) {
  1571. path.push(segment);
  1572. }
  1573. else {
  1574. path.pop();
  1575. }
  1576. break;
  1577. default:
  1578. path.push(segment);
  1579. break;
  1580. }
  1581. }
  1582. return path.join('/');
  1583. };
  1584. function isPathRelative(path) {
  1585. return !/^(?:[a-z-]+:|\/|#)/i.test(path);
  1586. }
  1587. function isPathLocalRelative(path) {
  1588. return path.charAt(0) === '.';
  1589. }
  1590. // todo - do the same for the toCSS ?
  1591. var ImportSequencer = /** @class */ (function () {
  1592. function ImportSequencer(onSequencerEmpty) {
  1593. this.imports = [];
  1594. this.variableImports = [];
  1595. this._onSequencerEmpty = onSequencerEmpty;
  1596. this._currentDepth = 0;
  1597. }
  1598. ImportSequencer.prototype.addImport = function (callback) {
  1599. var importSequencer = this, importItem = {
  1600. callback: callback,
  1601. args: null,
  1602. isReady: false
  1603. };
  1604. this.imports.push(importItem);
  1605. return function () {
  1606. importItem.args = Array.prototype.slice.call(arguments, 0);
  1607. importItem.isReady = true;
  1608. importSequencer.tryRun();
  1609. };
  1610. };
  1611. ImportSequencer.prototype.addVariableImport = function (callback) {
  1612. this.variableImports.push(callback);
  1613. };
  1614. ImportSequencer.prototype.tryRun = function () {
  1615. this._currentDepth++;
  1616. try {
  1617. while (true) {
  1618. while (this.imports.length > 0) {
  1619. var importItem = this.imports[0];
  1620. if (!importItem.isReady) {
  1621. return;
  1622. }
  1623. this.imports = this.imports.slice(1);
  1624. importItem.callback.apply(null, importItem.args);
  1625. }
  1626. if (this.variableImports.length === 0) {
  1627. break;
  1628. }
  1629. var variableImport = this.variableImports[0];
  1630. this.variableImports = this.variableImports.slice(1);
  1631. variableImport();
  1632. }
  1633. }
  1634. finally {
  1635. this._currentDepth--;
  1636. }
  1637. if (this._currentDepth === 0 && this._onSequencerEmpty) {
  1638. this._onSequencerEmpty();
  1639. }
  1640. };
  1641. return ImportSequencer;
  1642. }());
  1643. /* eslint-disable no-unused-vars */
  1644. var ImportVisitor = function (importer, finish) {
  1645. this._visitor = new Visitor(this);
  1646. this._importer = importer;
  1647. this._finish = finish;
  1648. this.context = new contexts.Eval();
  1649. this.importCount = 0;
  1650. this.onceFileDetectionMap = {};
  1651. this.recursionDetector = {};
  1652. this._sequencer = new ImportSequencer(this._onSequencerEmpty.bind(this));
  1653. };
  1654. ImportVisitor.prototype = {
  1655. isReplacing: false,
  1656. run: function (root) {
  1657. try {
  1658. // process the contents
  1659. this._visitor.visit(root);
  1660. }
  1661. catch (e) {
  1662. this.error = e;
  1663. }
  1664. this.isFinished = true;
  1665. this._sequencer.tryRun();
  1666. },
  1667. _onSequencerEmpty: function () {
  1668. if (!this.isFinished) {
  1669. return;
  1670. }
  1671. this._finish(this.error);
  1672. },
  1673. visitImport: function (importNode, visitArgs) {
  1674. var inlineCSS = importNode.options.inline;
  1675. if (!importNode.css || inlineCSS) {
  1676. var context = new contexts.Eval(this.context, copyArray(this.context.frames));
  1677. var importParent = context.frames[0];
  1678. this.importCount++;
  1679. if (importNode.isVariableImport()) {
  1680. this._sequencer.addVariableImport(this.processImportNode.bind(this, importNode, context, importParent));
  1681. }
  1682. else {
  1683. this.processImportNode(importNode, context, importParent);
  1684. }
  1685. }
  1686. visitArgs.visitDeeper = false;
  1687. },
  1688. processImportNode: function (importNode, context, importParent) {
  1689. var evaldImportNode;
  1690. var inlineCSS = importNode.options.inline;
  1691. try {
  1692. evaldImportNode = importNode.evalForImport(context);
  1693. }
  1694. catch (e) {
  1695. if (!e.filename) {
  1696. e.index = importNode.getIndex();
  1697. e.filename = importNode.fileInfo().filename;
  1698. }
  1699. // attempt to eval properly and treat as css
  1700. importNode.css = true;
  1701. // if that fails, this error will be thrown
  1702. importNode.error = e;
  1703. }
  1704. if (evaldImportNode && (!evaldImportNode.css || inlineCSS)) {
  1705. if (evaldImportNode.options.multiple) {
  1706. context.importMultiple = true;
  1707. }
  1708. // try appending if we haven't determined if it is css or not
  1709. var tryAppendLessExtension = evaldImportNode.css === undefined;
  1710. for (var i_1 = 0; i_1 < importParent.rules.length; i_1++) {
  1711. if (importParent.rules[i_1] === importNode) {
  1712. importParent.rules[i_1] = evaldImportNode;
  1713. break;
  1714. }
  1715. }
  1716. var onImported = this.onImported.bind(this, evaldImportNode, context), sequencedOnImported = this._sequencer.addImport(onImported);
  1717. this._importer.push(evaldImportNode.getPath(), tryAppendLessExtension, evaldImportNode.fileInfo(), evaldImportNode.options, sequencedOnImported);
  1718. }
  1719. else {
  1720. this.importCount--;
  1721. if (this.isFinished) {
  1722. this._sequencer.tryRun();
  1723. }
  1724. }
  1725. },
  1726. onImported: function (importNode, context, e, root, importedAtRoot, fullPath) {
  1727. if (e) {
  1728. if (!e.filename) {
  1729. e.index = importNode.getIndex();
  1730. e.filename = importNode.fileInfo().filename;
  1731. }
  1732. this.error = e;
  1733. }
  1734. var importVisitor = this, inlineCSS = importNode.options.inline, isPlugin = importNode.options.isPlugin, isOptional = importNode.options.optional, duplicateImport = importedAtRoot || fullPath in importVisitor.recursionDetector;
  1735. if (!context.importMultiple) {
  1736. if (duplicateImport) {
  1737. importNode.skip = true;
  1738. }
  1739. else {
  1740. importNode.skip = function () {
  1741. if (fullPath in importVisitor.onceFileDetectionMap) {
  1742. return true;
  1743. }
  1744. importVisitor.onceFileDetectionMap[fullPath] = true;
  1745. return false;
  1746. };
  1747. }
  1748. }
  1749. if (!fullPath && isOptional) {
  1750. importNode.skip = true;
  1751. }
  1752. if (root) {
  1753. importNode.root = root;
  1754. importNode.importedFilename = fullPath;
  1755. if (!inlineCSS && !isPlugin && (context.importMultiple || !duplicateImport)) {
  1756. importVisitor.recursionDetector[fullPath] = true;
  1757. var oldContext = this.context;
  1758. this.context = context;
  1759. try {
  1760. this._visitor.visit(root);
  1761. }
  1762. catch (e) {
  1763. this.error = e;
  1764. }
  1765. this.context = oldContext;
  1766. }
  1767. }
  1768. importVisitor.importCount--;
  1769. if (importVisitor.isFinished) {
  1770. importVisitor._sequencer.tryRun();
  1771. }
  1772. },
  1773. visitDeclaration: function (declNode, visitArgs) {
  1774. if (declNode.value.type === 'DetachedRuleset') {
  1775. this.context.frames.unshift(declNode);
  1776. }
  1777. else {
  1778. visitArgs.visitDeeper = false;
  1779. }
  1780. },
  1781. visitDeclarationOut: function (declNode) {
  1782. if (declNode.value.type === 'DetachedRuleset') {
  1783. this.context.frames.shift();
  1784. }
  1785. },
  1786. visitAtRule: function (atRuleNode, visitArgs) {
  1787. this.context.frames.unshift(atRuleNode);
  1788. },
  1789. visitAtRuleOut: function (atRuleNode) {
  1790. this.context.frames.shift();
  1791. },
  1792. visitMixinDefinition: function (mixinDefinitionNode, visitArgs) {
  1793. this.context.frames.unshift(mixinDefinitionNode);
  1794. },
  1795. visitMixinDefinitionOut: function (mixinDefinitionNode) {
  1796. this.context.frames.shift();
  1797. },
  1798. visitRuleset: function (rulesetNode, visitArgs) {
  1799. this.context.frames.unshift(rulesetNode);
  1800. },
  1801. visitRulesetOut: function (rulesetNode) {
  1802. this.context.frames.shift();
  1803. },
  1804. visitMedia: function (mediaNode, visitArgs) {
  1805. this.context.frames.unshift(mediaNode.rules[0]);
  1806. },
  1807. visitMediaOut: function (mediaNode) {
  1808. this.context.frames.shift();
  1809. }
  1810. };
  1811. var SetTreeVisibilityVisitor = /** @class */ (function () {
  1812. function SetTreeVisibilityVisitor(visible) {
  1813. this.visible = visible;
  1814. }
  1815. SetTreeVisibilityVisitor.prototype.run = function (root) {
  1816. this.visit(root);
  1817. };
  1818. SetTreeVisibilityVisitor.prototype.visitArray = function (nodes) {
  1819. if (!nodes) {
  1820. return nodes;
  1821. }
  1822. var cnt = nodes.length;
  1823. var i;
  1824. for (i = 0; i < cnt; i++) {
  1825. this.visit(nodes[i]);
  1826. }
  1827. return nodes;
  1828. };
  1829. SetTreeVisibilityVisitor.prototype.visit = function (node) {
  1830. if (!node) {
  1831. return node;
  1832. }
  1833. if (node.constructor === Array) {
  1834. return this.visitArray(node);
  1835. }
  1836. if (!node.blocksVisibility || node.blocksVisibility()) {
  1837. return node;
  1838. }
  1839. if (this.visible) {
  1840. node.ensureVisibility();
  1841. }
  1842. else {
  1843. node.ensureInvisibility();
  1844. }
  1845. node.accept(this);
  1846. return node;
  1847. };
  1848. return SetTreeVisibilityVisitor;
  1849. }());
  1850. /* eslint-disable no-unused-vars */
  1851. /* jshint loopfunc:true */
  1852. var ExtendFinderVisitor = /** @class */ (function () {
  1853. function ExtendFinderVisitor() {
  1854. this._visitor = new Visitor(this);
  1855. this.contexts = [];
  1856. this.allExtendsStack = [[]];
  1857. }
  1858. ExtendFinderVisitor.prototype.run = function (root) {
  1859. root = this._visitor.visit(root);
  1860. root.allExtends = this.allExtendsStack[0];
  1861. return root;
  1862. };
  1863. ExtendFinderVisitor.prototype.visitDeclaration = function (declNode, visitArgs) {
  1864. visitArgs.visitDeeper = false;
  1865. };
  1866. ExtendFinderVisitor.prototype.visitMixinDefinition = function (mixinDefinitionNode, visitArgs) {
  1867. visitArgs.visitDeeper = false;
  1868. };
  1869. ExtendFinderVisitor.prototype.visitRuleset = function (rulesetNode, visitArgs) {
  1870. if (rulesetNode.root) {
  1871. return;
  1872. }
  1873. var i;
  1874. var j;
  1875. var extend;
  1876. var allSelectorsExtendList = [];
  1877. var extendList;
  1878. // get &:extend(.a); rules which apply to all selectors in this ruleset
  1879. var rules = rulesetNode.rules, ruleCnt = rules ? rules.length : 0;
  1880. for (i = 0; i < ruleCnt; i++) {
  1881. if (rulesetNode.rules[i] instanceof tree.Extend) {
  1882. allSelectorsExtendList.push(rules[i]);
  1883. rulesetNode.extendOnEveryPath = true;
  1884. }
  1885. }
  1886. // now find every selector and apply the extends that apply to all extends
  1887. // and the ones which apply to an individual extend
  1888. var paths = rulesetNode.paths;
  1889. for (i = 0; i < paths.length; i++) {
  1890. var selectorPath = paths[i], selector = selectorPath[selectorPath.length - 1], selExtendList = selector.extendList;
  1891. extendList = selExtendList ? copyArray(selExtendList).concat(allSelectorsExtendList)
  1892. : allSelectorsExtendList;
  1893. if (extendList) {
  1894. extendList = extendList.map(function (allSelectorsExtend) {
  1895. return allSelectorsExtend.clone();
  1896. });
  1897. }
  1898. for (j = 0; j < extendList.length; j++) {
  1899. this.foundExtends = true;
  1900. extend = extendList[j];
  1901. extend.findSelfSelectors(selectorPath);
  1902. extend.ruleset = rulesetNode;
  1903. if (j === 0) {
  1904. extend.firstExtendOnThisSelectorPath = true;
  1905. }
  1906. this.allExtendsStack[this.allExtendsStack.length - 1].push(extend);
  1907. }
  1908. }
  1909. this.contexts.push(rulesetNode.selectors);
  1910. };
  1911. ExtendFinderVisitor.prototype.visitRulesetOut = function (rulesetNode) {
  1912. if (!rulesetNode.root) {
  1913. this.contexts.length = this.contexts.length - 1;
  1914. }
  1915. };
  1916. ExtendFinderVisitor.prototype.visitMedia = function (mediaNode, visitArgs) {
  1917. mediaNode.allExtends = [];
  1918. this.allExtendsStack.push(mediaNode.allExtends);
  1919. };
  1920. ExtendFinderVisitor.prototype.visitMediaOut = function (mediaNode) {
  1921. this.allExtendsStack.length = this.allExtendsStack.length - 1;
  1922. };
  1923. ExtendFinderVisitor.prototype.visitAtRule = function (atRuleNode, visitArgs) {
  1924. atRuleNode.allExtends = [];
  1925. this.allExtendsStack.push(atRuleNode.allExtends);
  1926. };
  1927. ExtendFinderVisitor.prototype.visitAtRuleOut = function (atRuleNode) {
  1928. this.allExtendsStack.length = this.allExtendsStack.length - 1;
  1929. };
  1930. return ExtendFinderVisitor;
  1931. }());
  1932. var ProcessExtendsVisitor = /** @class */ (function () {
  1933. function ProcessExtendsVisitor() {
  1934. this._visitor = new Visitor(this);
  1935. }
  1936. ProcessExtendsVisitor.prototype.run = function (root) {
  1937. var extendFinder = new ExtendFinderVisitor();
  1938. this.extendIndices = {};
  1939. extendFinder.run(root);
  1940. if (!extendFinder.foundExtends) {
  1941. return root;
  1942. }
  1943. root.allExtends = root.allExtends.concat(this.doExtendChaining(root.allExtends, root.allExtends));
  1944. this.allExtendsStack = [root.allExtends];
  1945. var newRoot = this._visitor.visit(root);
  1946. this.checkExtendsForNonMatched(root.allExtends);
  1947. return newRoot;
  1948. };
  1949. ProcessExtendsVisitor.prototype.checkExtendsForNonMatched = function (extendList) {
  1950. var indices = this.extendIndices;
  1951. extendList.filter(function (extend) {
  1952. return !extend.hasFoundMatches && extend.parent_ids.length == 1;
  1953. }).forEach(function (extend) {
  1954. var selector = '_unknown_';
  1955. try {
  1956. selector = extend.selector.toCSS({});
  1957. }
  1958. catch (_) { }
  1959. if (!indices[extend.index + " " + selector]) {
  1960. indices[extend.index + " " + selector] = true;
  1961. logger$1.warn("extend '" + selector + "' has no matches");
  1962. }
  1963. });
  1964. };
  1965. ProcessExtendsVisitor.prototype.doExtendChaining = function (extendsList, extendsListTarget, iterationCount) {
  1966. //
  1967. // chaining is different from normal extension.. if we extend an extend then we are not just copying, altering
  1968. // and pasting the selector we would do normally, but we are also adding an extend with the same target selector
  1969. // this means this new extend can then go and alter other extends
  1970. //
  1971. // this method deals with all the chaining work - without it, extend is flat and doesn't work on other extend selectors
  1972. // this is also the most expensive.. and a match on one selector can cause an extension of a selector we had already
  1973. // processed if we look at each selector at a time, as is done in visitRuleset
  1974. var extendIndex;
  1975. var targetExtendIndex;
  1976. var matches;
  1977. var extendsToAdd = [];
  1978. var newSelector;
  1979. var extendVisitor = this;
  1980. var selectorPath;
  1981. var extend;
  1982. var targetExtend;
  1983. var newExtend;
  1984. iterationCount = iterationCount || 0;
  1985. // loop through comparing every extend with every target extend.
  1986. // a target extend is the one on the ruleset we are looking at copy/edit/pasting in place
  1987. // e.g. .a:extend(.b) {} and .b:extend(.c) {} then the first extend extends the second one
  1988. // and the second is the target.
  1989. // the separation into two lists allows us to process a subset of chains with a bigger set, as is the
  1990. // case when processing media queries
  1991. for (extendIndex = 0; extendIndex < extendsList.length; extendIndex++) {
  1992. for (targetExtendIndex = 0; targetExtendIndex < extendsListTarget.length; targetExtendIndex++) {
  1993. extend = extendsList[extendIndex];
  1994. targetExtend = extendsListTarget[targetExtendIndex];
  1995. // look for circular references
  1996. if (extend.parent_ids.indexOf(targetExtend.object_id) >= 0) {
  1997. continue;
  1998. }
  1999. // find a match in the target extends self selector (the bit before :extend)
  2000. selectorPath = [targetExtend.selfSelectors[0]];
  2001. matches = extendVisitor.findMatch(extend, selectorPath);
  2002. if (matches.length) {
  2003. extend.hasFoundMatches = true;
  2004. // we found a match, so for each self selector..
  2005. extend.selfSelectors.forEach(function (selfSelector) {
  2006. var info = targetExtend.visibilityInfo();
  2007. // process the extend as usual
  2008. newSelector = extendVisitor.extendSelector(matches, selectorPath, selfSelector, extend.isVisible());
  2009. // but now we create a new extend from it
  2010. newExtend = new (tree.Extend)(targetExtend.selector, targetExtend.option, 0, targetExtend.fileInfo(), info);
  2011. newExtend.selfSelectors = newSelector;
  2012. // add the extend onto the list of extends for that selector
  2013. newSelector[newSelector.length - 1].extendList = [newExtend];
  2014. // record that we need to add it.
  2015. extendsToAdd.push(newExtend);
  2016. newExtend.ruleset = targetExtend.ruleset;
  2017. // remember its parents for circular references
  2018. newExtend.parent_ids = newExtend.parent_ids.concat(targetExtend.parent_ids, extend.parent_ids);
  2019. // only process the selector once.. if we have :extend(.a,.b) then multiple
  2020. // extends will look at the same selector path, so when extending
  2021. // we know that any others will be duplicates in terms of what is added to the css
  2022. if (targetExtend.firstExtendOnThisSelectorPath) {
  2023. newExtend.firstExtendOnThisSelectorPath = true;
  2024. targetExtend.ruleset.paths.push(newSelector);
  2025. }
  2026. });
  2027. }
  2028. }
  2029. }
  2030. if (extendsToAdd.length) {
  2031. // try to detect circular references to stop a stack overflow.
  2032. // may no longer be needed.
  2033. this.extendChainCount++;
  2034. if (iterationCount > 100) {
  2035. var selectorOne = '{unable to calculate}';
  2036. var selectorTwo = '{unable to calculate}';
  2037. try {
  2038. selectorOne = extendsToAdd[0].selfSelectors[0].toCSS();
  2039. selectorTwo = extendsToAdd[0].selector.toCSS();
  2040. }
  2041. catch (e) { }
  2042. throw { message: "extend circular reference detected. One of the circular extends is currently:" + selectorOne + ":extend(" + selectorTwo + ")" };
  2043. }
  2044. // now process the new extends on the existing rules so that we can handle a extending b extending c extending
  2045. // d extending e...
  2046. return extendsToAdd.concat(extendVisitor.doExtendChaining(extendsToAdd, extendsListTarget, iterationCount + 1));
  2047. }
  2048. else {
  2049. return extendsToAdd;
  2050. }
  2051. };
  2052. ProcessExtendsVisitor.prototype.visitDeclaration = function (ruleNode, visitArgs) {
  2053. visitArgs.visitDeeper = false;
  2054. };
  2055. ProcessExtendsVisitor.prototype.visitMixinDefinition = function (mixinDefinitionNode, visitArgs) {
  2056. visitArgs.visitDeeper = false;
  2057. };
  2058. ProcessExtendsVisitor.prototype.visitSelector = function (selectorNode, visitArgs) {
  2059. visitArgs.visitDeeper = false;
  2060. };
  2061. ProcessExtendsVisitor.prototype.visitRuleset = function (rulesetNode, visitArgs) {
  2062. if (rulesetNode.root) {
  2063. return;
  2064. }
  2065. var matches;
  2066. var pathIndex;
  2067. var extendIndex;
  2068. var allExtends = this.allExtendsStack[this.allExtendsStack.length - 1];
  2069. var selectorsToAdd = [];
  2070. var extendVisitor = this;
  2071. var selectorPath;
  2072. // look at each selector path in the ruleset, find any extend matches and then copy, find and replace
  2073. for (extendIndex = 0; extendIndex < allExtends.length; extendIndex++) {
  2074. for (pathIndex = 0; pathIndex < rulesetNode.paths.length; pathIndex++) {
  2075. selectorPath = rulesetNode.paths[pathIndex];
  2076. // extending extends happens initially, before the main pass
  2077. if (rulesetNode.extendOnEveryPath) {
  2078. continue;
  2079. }
  2080. var extendList = selectorPath[selectorPath.length - 1].extendList;
  2081. if (extendList && extendList.length) {
  2082. continue;
  2083. }
  2084. matches = this.findMatch(allExtends[extendIndex], selectorPath);
  2085. if (matches.length) {
  2086. allExtends[extendIndex].hasFoundMatches = true;
  2087. allExtends[extendIndex].selfSelectors.forEach(function (selfSelector) {
  2088. var extendedSelectors;
  2089. extendedSelectors = extendVisitor.extendSelector(matches, selectorPath, selfSelector, allExtends[extendIndex].isVisible());
  2090. selectorsToAdd.push(extendedSelectors);
  2091. });
  2092. }
  2093. }
  2094. }
  2095. rulesetNode.paths = rulesetNode.paths.concat(selectorsToAdd);
  2096. };
  2097. ProcessExtendsVisitor.prototype.findMatch = function (extend, haystackSelectorPath) {
  2098. //
  2099. // look through the haystack selector path to try and find the needle - extend.selector
  2100. // returns an array of selector matches that can then be replaced
  2101. //
  2102. var haystackSelectorIndex;
  2103. var hackstackSelector;
  2104. var hackstackElementIndex;
  2105. var haystackElement;
  2106. var targetCombinator;
  2107. var i;
  2108. var extendVisitor = this;
  2109. var needleElements = extend.selector.elements;
  2110. var potentialMatches = [];
  2111. var potentialMatch;
  2112. var matches = [];
  2113. // loop through the haystack elements
  2114. for (haystackSelectorIndex = 0; haystackSelectorIndex < haystackSelectorPath.length; haystackSelectorIndex++) {
  2115. hackstackSelector = haystackSelectorPath[haystackSelectorIndex];
  2116. for (hackstackElementIndex = 0; hackstackElementIndex < hackstackSelector.elements.length; hackstackElementIndex++) {
  2117. haystackElement = hackstackSelector.elements[hackstackElementIndex];
  2118. // if we allow elements before our match we can add a potential match every time. otherwise only at the first element.
  2119. if (extend.allowBefore || (haystackSelectorIndex === 0 && hackstackElementIndex === 0)) {
  2120. potentialMatches.push({ pathIndex: haystackSelectorIndex, index: hackstackElementIndex, matched: 0,
  2121. initialCombinator: haystackElement.combinator });
  2122. }
  2123. for (i = 0; i < potentialMatches.length; i++) {
  2124. potentialMatch = potentialMatches[i];
  2125. // selectors add " " onto the first element. When we use & it joins the selectors together, but if we don't
  2126. // then each selector in haystackSelectorPath has a space before it added in the toCSS phase. so we need to
  2127. // work out what the resulting combinator will be
  2128. targetCombinator = haystackElement.combinator.value;
  2129. if (targetCombinator === '' && hackstackElementIndex === 0) {
  2130. targetCombinator = ' ';
  2131. }
  2132. // if we don't match, null our match to indicate failure
  2133. if (!extendVisitor.isElementValuesEqual(needleElements[potentialMatch.matched].value, haystackElement.value) ||
  2134. (potentialMatch.matched > 0 && needleElements[potentialMatch.matched].combinator.value !== targetCombinator)) {
  2135. potentialMatch = null;
  2136. }
  2137. else {
  2138. potentialMatch.matched++;
  2139. }
  2140. // if we are still valid and have finished, test whether we have elements after and whether these are allowed
  2141. if (potentialMatch) {
  2142. potentialMatch.finished = potentialMatch.matched === needleElements.length;
  2143. if (potentialMatch.finished &&
  2144. (!extend.allowAfter &&
  2145. (hackstackElementIndex + 1 < hackstackSelector.elements.length || haystackSelectorIndex + 1 < haystackSelectorPath.length))) {
  2146. potentialMatch = null;
  2147. }
  2148. }
  2149. // if null we remove, if not, we are still valid, so either push as a valid match or continue
  2150. if (potentialMatch) {
  2151. if (potentialMatch.finished) {
  2152. potentialMatch.length = needleElements.length;
  2153. potentialMatch.endPathIndex = haystackSelectorIndex;
  2154. potentialMatch.endPathElementIndex = hackstackElementIndex + 1; // index after end of match
  2155. potentialMatches.length = 0; // we don't allow matches to overlap, so start matching again
  2156. matches.push(potentialMatch);
  2157. }
  2158. }
  2159. else {
  2160. potentialMatches.splice(i, 1);
  2161. i--;
  2162. }
  2163. }
  2164. }
  2165. }
  2166. return matches;
  2167. };
  2168. ProcessExtendsVisitor.prototype.isElementValuesEqual = function (elementValue1, elementValue2) {
  2169. if (typeof elementValue1 === 'string' || typeof elementValue2 === 'string') {
  2170. return elementValue1 === elementValue2;
  2171. }
  2172. if (elementValue1 instanceof tree.Attribute) {
  2173. if (elementValue1.op !== elementValue2.op || elementValue1.key !== elementValue2.key) {
  2174. return false;
  2175. }
  2176. if (!elementValue1.value || !elementValue2.value) {
  2177. if (elementValue1.value || elementValue2.value) {
  2178. return false;
  2179. }
  2180. return true;
  2181. }
  2182. elementValue1 = elementValue1.value.value || elementValue1.value;
  2183. elementValue2 = elementValue2.value.value || elementValue2.value;
  2184. return elementValue1 === elementValue2;
  2185. }
  2186. elementValue1 = elementValue1.value;
  2187. elementValue2 = elementValue2.value;
  2188. if (elementValue1 instanceof tree.Selector) {
  2189. if (!(elementValue2 instanceof tree.Selector) || elementValue1.elements.length !== elementValue2.elements.length) {
  2190. return false;
  2191. }
  2192. for (var i_1 = 0; i_1 < elementValue1.elements.length; i_1++) {
  2193. if (elementValue1.elements[i_1].combinator.value !== elementValue2.elements[i_1].combinator.value) {
  2194. if (i_1 !== 0 || (elementValue1.elements[i_1].combinator.value || ' ') !== (elementValue2.elements[i_1].combinator.value || ' ')) {
  2195. return false;
  2196. }
  2197. }
  2198. if (!this.isElementValuesEqual(elementValue1.elements[i_1].value, elementValue2.elements[i_1].value)) {
  2199. return false;
  2200. }
  2201. }
  2202. return true;
  2203. }
  2204. return false;
  2205. };
  2206. ProcessExtendsVisitor.prototype.extendSelector = function (matches, selectorPath, replacementSelector, isVisible) {
  2207. // for a set of matches, replace each match with the replacement selector
  2208. var currentSelectorPathIndex = 0, currentSelectorPathElementIndex = 0, path = [], matchIndex, selector, firstElement, match, newElements;
  2209. for (matchIndex = 0; matchIndex < matches.length; matchIndex++) {
  2210. match = matches[matchIndex];
  2211. selector = selectorPath[match.pathIndex];
  2212. firstElement = new tree.Element(match.initialCombinator, replacementSelector.elements[0].value, replacementSelector.elements[0].isVariable, replacementSelector.elements[0].getIndex(), replacementSelector.elements[0].fileInfo());
  2213. if (match.pathIndex > currentSelectorPathIndex && currentSelectorPathElementIndex > 0) {
  2214. path[path.length - 1].elements = path[path.length - 1]
  2215. .elements.concat(selectorPath[currentSelectorPathIndex].elements.slice(currentSelectorPathElementIndex));
  2216. currentSelectorPathElementIndex = 0;
  2217. currentSelectorPathIndex++;
  2218. }
  2219. newElements = selector.elements
  2220. .slice(currentSelectorPathElementIndex, match.index)
  2221. .concat([firstElement])
  2222. .concat(replacementSelector.elements.slice(1));
  2223. if (currentSelectorPathIndex === match.pathIndex && matchIndex > 0) {
  2224. path[path.length - 1].elements =
  2225. path[path.length - 1].elements.concat(newElements);
  2226. }
  2227. else {
  2228. path = path.concat(selectorPath.slice(currentSelectorPathIndex, match.pathIndex));
  2229. path.push(new tree.Selector(newElements));
  2230. }
  2231. currentSelectorPathIndex = match.endPathIndex;
  2232. currentSelectorPathElementIndex = match.endPathElementIndex;
  2233. if (currentSelectorPathElementIndex >= selectorPath[currentSelectorPathIndex].elements.length) {
  2234. currentSelectorPathElementIndex = 0;
  2235. currentSelectorPathIndex++;
  2236. }
  2237. }
  2238. if (currentSelectorPathIndex < selectorPath.length && currentSelectorPathElementIndex > 0) {
  2239. path[path.length - 1].elements = path[path.length - 1]
  2240. .elements.concat(selectorPath[currentSelectorPathIndex].elements.slice(currentSelectorPathElementIndex));
  2241. currentSelectorPathIndex++;
  2242. }
  2243. path = path.concat(selectorPath.slice(currentSelectorPathIndex, selectorPath.length));
  2244. path = path.map(function (currentValue) {
  2245. // we can re-use elements here, because the visibility property matters only for selectors
  2246. var derived = currentValue.createDerived(currentValue.elements);
  2247. if (isVisible) {
  2248. derived.ensureVisibility();
  2249. }
  2250. else {
  2251. derived.ensureInvisibility();
  2252. }
  2253. return derived;
  2254. });
  2255. return path;
  2256. };
  2257. ProcessExtendsVisitor.prototype.visitMedia = function (mediaNode, visitArgs) {
  2258. var newAllExtends = mediaNode.allExtends.concat(this.allExtendsStack[this.allExtendsStack.length - 1]);
  2259. newAllExtends = newAllExtends.concat(this.doExtendChaining(newAllExtends, mediaNode.allExtends));
  2260. this.allExtendsStack.push(newAllExtends);
  2261. };
  2262. ProcessExtendsVisitor.prototype.visitMediaOut = function (mediaNode) {
  2263. var lastIndex = this.allExtendsStack.length - 1;
  2264. this.allExtendsStack.length = lastIndex;
  2265. };
  2266. ProcessExtendsVisitor.prototype.visitAtRule = function (atRuleNode, visitArgs) {
  2267. var newAllExtends = atRuleNode.allExtends.concat(this.allExtendsStack[this.allExtendsStack.length - 1]);
  2268. newAllExtends = newAllExtends.concat(this.doExtendChaining(newAllExtends, atRuleNode.allExtends));
  2269. this.allExtendsStack.push(newAllExtends);
  2270. };
  2271. ProcessExtendsVisitor.prototype.visitAtRuleOut = function (atRuleNode) {
  2272. var lastIndex = this.allExtendsStack.length - 1;
  2273. this.allExtendsStack.length = lastIndex;
  2274. };
  2275. return ProcessExtendsVisitor;
  2276. }());
  2277. /* eslint-disable no-unused-vars */
  2278. var JoinSelectorVisitor = /** @class */ (function () {
  2279. function JoinSelectorVisitor() {
  2280. this.contexts = [[]];
  2281. this._visitor = new Visitor(this);
  2282. }
  2283. JoinSelectorVisitor.prototype.run = function (root) {
  2284. return this._visitor.visit(root);
  2285. };
  2286. JoinSelectorVisitor.prototype.visitDeclaration = function (declNode, visitArgs) {
  2287. visitArgs.visitDeeper = false;
  2288. };
  2289. JoinSelectorVisitor.prototype.visitMixinDefinition = function (mixinDefinitionNode, visitArgs) {
  2290. visitArgs.visitDeeper = false;
  2291. };
  2292. JoinSelectorVisitor.prototype.visitRuleset = function (rulesetNode, visitArgs) {
  2293. var context = this.contexts[this.contexts.length - 1];
  2294. var paths = [];
  2295. var selectors;
  2296. this.contexts.push(paths);
  2297. if (!rulesetNode.root) {
  2298. selectors = rulesetNode.selectors;
  2299. if (selectors) {
  2300. selectors = selectors.filter(function (selector) { return selector.getIsOutput(); });
  2301. rulesetNode.selectors = selectors.length ? selectors : (selectors = null);
  2302. if (selectors) {
  2303. rulesetNode.joinSelectors(paths, context, selectors);
  2304. }
  2305. }
  2306. if (!selectors) {
  2307. rulesetNode.rules = null;
  2308. }
  2309. rulesetNode.paths = paths;
  2310. }
  2311. };
  2312. JoinSelectorVisitor.prototype.visitRulesetOut = function (rulesetNode) {
  2313. this.contexts.length = this.contexts.length - 1;
  2314. };
  2315. JoinSelectorVisitor.prototype.visitMedia = function (mediaNode, visitArgs) {
  2316. var context = this.contexts[this.contexts.length - 1];
  2317. mediaNode.rules[0].root = (context.length === 0 || context[0].multiMedia);
  2318. };
  2319. JoinSelectorVisitor.prototype.visitAtRule = function (atRuleNode, visitArgs) {
  2320. var context = this.contexts[this.contexts.length - 1];
  2321. if (atRuleNode.rules && atRuleNode.rules.length) {
  2322. atRuleNode.rules[0].root = (atRuleNode.isRooted || context.length === 0 || null);
  2323. }
  2324. };
  2325. return JoinSelectorVisitor;
  2326. }());
  2327. /* eslint-disable no-unused-vars */
  2328. var CSSVisitorUtils = /** @class */ (function () {
  2329. function CSSVisitorUtils(context) {
  2330. this._visitor = new Visitor(this);
  2331. this._context = context;
  2332. }
  2333. CSSVisitorUtils.prototype.containsSilentNonBlockedChild = function (bodyRules) {
  2334. var rule;
  2335. if (!bodyRules) {
  2336. return false;
  2337. }
  2338. for (var r = 0; r < bodyRules.length; r++) {
  2339. rule = bodyRules[r];
  2340. if (rule.isSilent && rule.isSilent(this._context) && !rule.blocksVisibility()) {
  2341. // the atrule contains something that was referenced (likely by extend)
  2342. // therefore it needs to be shown in output too
  2343. return true;
  2344. }
  2345. }
  2346. return false;
  2347. };
  2348. CSSVisitorUtils.prototype.keepOnlyVisibleChilds = function (owner) {
  2349. if (owner && owner.rules) {
  2350. owner.rules = owner.rules.filter(function (thing) { return thing.isVisible(); });
  2351. }
  2352. };
  2353. CSSVisitorUtils.prototype.isEmpty = function (owner) {
  2354. return (owner && owner.rules)
  2355. ? (owner.rules.length === 0) : true;
  2356. };
  2357. CSSVisitorUtils.prototype.hasVisibleSelector = function (rulesetNode) {
  2358. return (rulesetNode && rulesetNode.paths)
  2359. ? (rulesetNode.paths.length > 0) : false;
  2360. };
  2361. CSSVisitorUtils.prototype.resolveVisibility = function (node) {
  2362. if (!node.blocksVisibility()) {
  2363. if (this.isEmpty(node)) {
  2364. return;
  2365. }
  2366. return node;
  2367. }
  2368. var compiledRulesBody = node.rules[0];
  2369. this.keepOnlyVisibleChilds(compiledRulesBody);
  2370. if (this.isEmpty(compiledRulesBody)) {
  2371. return;
  2372. }
  2373. node.ensureVisibility();
  2374. node.removeVisibilityBlock();
  2375. return node;
  2376. };
  2377. CSSVisitorUtils.prototype.isVisibleRuleset = function (rulesetNode) {
  2378. if (rulesetNode.firstRoot) {
  2379. return true;
  2380. }
  2381. if (this.isEmpty(rulesetNode)) {
  2382. return false;
  2383. }
  2384. if (!rulesetNode.root && !this.hasVisibleSelector(rulesetNode)) {
  2385. return false;
  2386. }
  2387. return true;
  2388. };
  2389. return CSSVisitorUtils;
  2390. }());
  2391. var ToCSSVisitor = function (context) {
  2392. this._visitor = new Visitor(this);
  2393. this._context = context;
  2394. this.utils = new CSSVisitorUtils(context);
  2395. };
  2396. ToCSSVisitor.prototype = {
  2397. isReplacing: true,
  2398. run: function (root) {
  2399. return this._visitor.visit(root);
  2400. },
  2401. visitDeclaration: function (declNode, visitArgs) {
  2402. if (declNode.blocksVisibility() || declNode.variable) {
  2403. return;
  2404. }
  2405. return declNode;
  2406. },
  2407. visitMixinDefinition: function (mixinNode, visitArgs) {
  2408. // mixin definitions do not get eval'd - this means they keep state
  2409. // so we have to clear that state here so it isn't used if toCSS is called twice
  2410. mixinNode.frames = [];
  2411. },
  2412. visitExtend: function (extendNode, visitArgs) {
  2413. },
  2414. visitComment: function (commentNode, visitArgs) {
  2415. if (commentNode.blocksVisibility() || commentNode.isSilent(this._context)) {
  2416. return;
  2417. }
  2418. return commentNode;
  2419. },
  2420. visitMedia: function (mediaNode, visitArgs) {
  2421. var originalRules = mediaNode.rules[0].rules;
  2422. mediaNode.accept(this._visitor);
  2423. visitArgs.visitDeeper = false;
  2424. return this.utils.resolveVisibility(mediaNode, originalRules);
  2425. },
  2426. visitImport: function (importNode, visitArgs) {
  2427. if (importNode.blocksVisibility()) {
  2428. return;
  2429. }
  2430. return importNode;
  2431. },
  2432. visitAtRule: function (atRuleNode, visitArgs) {
  2433. if (atRuleNode.rules && atRuleNode.rules.length) {
  2434. return this.visitAtRuleWithBody(atRuleNode, visitArgs);
  2435. }
  2436. else {
  2437. return this.visitAtRuleWithoutBody(atRuleNode, visitArgs);
  2438. }
  2439. },
  2440. visitAnonymous: function (anonymousNode, visitArgs) {
  2441. if (!anonymousNode.blocksVisibility()) {
  2442. anonymousNode.accept(this._visitor);
  2443. return anonymousNode;
  2444. }
  2445. },
  2446. visitAtRuleWithBody: function (atRuleNode, visitArgs) {
  2447. // if there is only one nested ruleset and that one has no path, then it is
  2448. // just fake ruleset
  2449. function hasFakeRuleset(atRuleNode) {
  2450. var bodyRules = atRuleNode.rules;
  2451. return bodyRules.length === 1 && (!bodyRules[0].paths || bodyRules[0].paths.length === 0);
  2452. }
  2453. function getBodyRules(atRuleNode) {
  2454. var nodeRules = atRuleNode.rules;
  2455. if (hasFakeRuleset(atRuleNode)) {
  2456. return nodeRules[0].rules;
  2457. }
  2458. return nodeRules;
  2459. }
  2460. // it is still true that it is only one ruleset in array
  2461. // this is last such moment
  2462. // process childs
  2463. var originalRules = getBodyRules(atRuleNode);
  2464. atRuleNode.accept(this._visitor);
  2465. visitArgs.visitDeeper = false;
  2466. if (!this.utils.isEmpty(atRuleNode)) {
  2467. this._mergeRules(atRuleNode.rules[0].rules);
  2468. }
  2469. return this.utils.resolveVisibility(atRuleNode, originalRules);
  2470. },
  2471. visitAtRuleWithoutBody: function (atRuleNode, visitArgs) {
  2472. if (atRuleNode.blocksVisibility()) {
  2473. return;
  2474. }
  2475. if (atRuleNode.name === '@charset') {
  2476. // Only output the debug info together with subsequent @charset definitions
  2477. // a comment (or @media statement) before the actual @charset atrule would
  2478. // be considered illegal css as it has to be on the first line
  2479. if (this.charset) {
  2480. if (atRuleNode.debugInfo) {
  2481. var comment = new tree.Comment("/* " + atRuleNode.toCSS(this._context).replace(/\n/g, '') + " */\n");
  2482. comment.debugInfo = atRuleNode.debugInfo;
  2483. return this._visitor.visit(comment);
  2484. }
  2485. return;
  2486. }
  2487. this.charset = true;
  2488. }
  2489. return atRuleNode;
  2490. },
  2491. checkValidNodes: function (rules, isRoot) {
  2492. if (!rules) {
  2493. return;
  2494. }
  2495. for (var i_1 = 0; i_1 < rules.length; i_1++) {
  2496. var ruleNode = rules[i_1];
  2497. if (isRoot && ruleNode instanceof tree.Declaration && !ruleNode.variable) {
  2498. throw { message: 'Properties must be inside selector blocks. They cannot be in the root',
  2499. index: ruleNode.getIndex(), filename: ruleNode.fileInfo() && ruleNode.fileInfo().filename };
  2500. }
  2501. if (ruleNode instanceof tree.Call) {
  2502. throw { message: "Function '" + ruleNode.name + "' did not return a root node",
  2503. index: ruleNode.getIndex(), filename: ruleNode.fileInfo() && ruleNode.fileInfo().filename };
  2504. }
  2505. if (ruleNode.type && !ruleNode.allowRoot) {
  2506. throw { message: ruleNode.type + " node returned by a function is not valid here",
  2507. index: ruleNode.getIndex(), filename: ruleNode.fileInfo() && ruleNode.fileInfo().filename };
  2508. }
  2509. }
  2510. },
  2511. visitRuleset: function (rulesetNode, visitArgs) {
  2512. // at this point rulesets are nested into each other
  2513. var rule;
  2514. var rulesets = [];
  2515. this.checkValidNodes(rulesetNode.rules, rulesetNode.firstRoot);
  2516. if (!rulesetNode.root) {
  2517. // remove invisible paths
  2518. this._compileRulesetPaths(rulesetNode);
  2519. // remove rulesets from this ruleset body and compile them separately
  2520. var nodeRules = rulesetNode.rules;
  2521. var nodeRuleCnt = nodeRules ? nodeRules.length : 0;
  2522. for (var i_2 = 0; i_2 < nodeRuleCnt;) {
  2523. rule = nodeRules[i_2];
  2524. if (rule && rule.rules) {
  2525. // visit because we are moving them out from being a child
  2526. rulesets.push(this._visitor.visit(rule));
  2527. nodeRules.splice(i_2, 1);
  2528. nodeRuleCnt--;
  2529. continue;
  2530. }
  2531. i_2++;
  2532. }
  2533. // accept the visitor to remove rules and refactor itself
  2534. // then we can decide nogw whether we want it or not
  2535. // compile body
  2536. if (nodeRuleCnt > 0) {
  2537. rulesetNode.accept(this._visitor);
  2538. }
  2539. else {
  2540. rulesetNode.rules = null;
  2541. }
  2542. visitArgs.visitDeeper = false;
  2543. }
  2544. else { // if (! rulesetNode.root) {
  2545. rulesetNode.accept(this._visitor);
  2546. visitArgs.visitDeeper = false;
  2547. }
  2548. if (rulesetNode.rules) {
  2549. this._mergeRules(rulesetNode.rules);
  2550. this._removeDuplicateRules(rulesetNode.rules);
  2551. }
  2552. // now decide whether we keep the ruleset
  2553. if (this.utils.isVisibleRuleset(rulesetNode)) {
  2554. rulesetNode.ensureVisibility();
  2555. rulesets.splice(0, 0, rulesetNode);
  2556. }
  2557. if (rulesets.length === 1) {
  2558. return rulesets[0];
  2559. }
  2560. return rulesets;
  2561. },
  2562. _compileRulesetPaths: function (rulesetNode) {
  2563. if (rulesetNode.paths) {
  2564. rulesetNode.paths = rulesetNode.paths
  2565. .filter(function (p) {
  2566. var i;
  2567. if (p[0].elements[0].combinator.value === ' ') {
  2568. p[0].elements[0].combinator = new (tree.Combinator)('');
  2569. }
  2570. for (i = 0; i < p.length; i++) {
  2571. if (p[i].isVisible() && p[i].getIsOutput()) {
  2572. return true;
  2573. }
  2574. }
  2575. return false;
  2576. });
  2577. }
  2578. },
  2579. _removeDuplicateRules: function (rules) {
  2580. if (!rules) {
  2581. return;
  2582. }
  2583. // remove duplicates
  2584. var ruleCache = {};
  2585. var ruleList;
  2586. var rule;
  2587. var i;
  2588. for (i = rules.length - 1; i >= 0; i--) {
  2589. rule = rules[i];
  2590. if (rule instanceof tree.Declaration) {
  2591. if (!ruleCache[rule.name]) {
  2592. ruleCache[rule.name] = rule;
  2593. }
  2594. else {
  2595. ruleList = ruleCache[rule.name];
  2596. if (ruleList instanceof tree.Declaration) {
  2597. ruleList = ruleCache[rule.name] = [ruleCache[rule.name].toCSS(this._context)];
  2598. }
  2599. var ruleCSS = rule.toCSS(this._context);
  2600. if (ruleList.indexOf(ruleCSS) !== -1) {
  2601. rules.splice(i, 1);
  2602. }
  2603. else {
  2604. ruleList.push(ruleCSS);
  2605. }
  2606. }
  2607. }
  2608. }
  2609. },
  2610. _mergeRules: function (rules) {
  2611. if (!rules) {
  2612. return;
  2613. }
  2614. var groups = {};
  2615. var groupsArr = [];
  2616. for (var i_3 = 0; i_3 < rules.length; i_3++) {
  2617. var rule = rules[i_3];
  2618. if (rule.merge) {
  2619. var key = rule.name;
  2620. groups[key] ? rules.splice(i_3--, 1) :
  2621. groupsArr.push(groups[key] = []);
  2622. groups[key].push(rule);
  2623. }
  2624. }
  2625. groupsArr.forEach(function (group) {
  2626. if (group.length > 0) {
  2627. var result_1 = group[0];
  2628. var space_1 = [];
  2629. var comma_1 = [new tree.Expression(space_1)];
  2630. group.forEach(function (rule) {
  2631. if ((rule.merge === '+') && (space_1.length > 0)) {
  2632. comma_1.push(new tree.Expression(space_1 = []));
  2633. }
  2634. space_1.push(rule.value);
  2635. result_1.important = result_1.important || rule.important;
  2636. });
  2637. result_1.value = new tree.Value(comma_1);
  2638. }
  2639. });
  2640. }
  2641. };
  2642. var visitors = {
  2643. Visitor: Visitor,
  2644. ImportVisitor: ImportVisitor,
  2645. MarkVisibleSelectorsVisitor: SetTreeVisibilityVisitor,
  2646. ExtendVisitor: ProcessExtendsVisitor,
  2647. JoinSelectorVisitor: JoinSelectorVisitor,
  2648. ToCSSVisitor: ToCSSVisitor
  2649. };
  2650. // Split the input into chunks.
  2651. function chunker (input, fail) {
  2652. var len = input.length;
  2653. var level = 0;
  2654. var parenLevel = 0;
  2655. var lastOpening;
  2656. var lastOpeningParen;
  2657. var lastMultiComment;
  2658. var lastMultiCommentEndBrace;
  2659. var chunks = [];
  2660. var emitFrom = 0;
  2661. var chunkerCurrentIndex;
  2662. var currentChunkStartIndex;
  2663. var cc;
  2664. var cc2;
  2665. var matched;
  2666. function emitChunk(force) {
  2667. var len = chunkerCurrentIndex - emitFrom;
  2668. if (((len < 512) && !force) || !len) {
  2669. return;
  2670. }
  2671. chunks.push(input.slice(emitFrom, chunkerCurrentIndex + 1));
  2672. emitFrom = chunkerCurrentIndex + 1;
  2673. }
  2674. for (chunkerCurrentIndex = 0; chunkerCurrentIndex < len; chunkerCurrentIndex++) {
  2675. cc = input.charCodeAt(chunkerCurrentIndex);
  2676. if (((cc >= 97) && (cc <= 122)) || (cc < 34)) {
  2677. // a-z or whitespace
  2678. continue;
  2679. }
  2680. switch (cc) {
  2681. case 40: // (
  2682. parenLevel++;
  2683. lastOpeningParen = chunkerCurrentIndex;
  2684. continue;
  2685. case 41: // )
  2686. if (--parenLevel < 0) {
  2687. return fail('missing opening `(`', chunkerCurrentIndex);
  2688. }
  2689. continue;
  2690. case 59: // ;
  2691. if (!parenLevel) {
  2692. emitChunk();
  2693. }
  2694. continue;
  2695. case 123: // {
  2696. level++;
  2697. lastOpening = chunkerCurrentIndex;
  2698. continue;
  2699. case 125: // }
  2700. if (--level < 0) {
  2701. return fail('missing opening `{`', chunkerCurrentIndex);
  2702. }
  2703. if (!level && !parenLevel) {
  2704. emitChunk();
  2705. }
  2706. continue;
  2707. case 92: // \
  2708. if (chunkerCurrentIndex < len - 1) {
  2709. chunkerCurrentIndex++;
  2710. continue;
  2711. }
  2712. return fail('unescaped `\\`', chunkerCurrentIndex);
  2713. case 34:
  2714. case 39:
  2715. case 96: // ", ' and `
  2716. matched = 0;
  2717. currentChunkStartIndex = chunkerCurrentIndex;
  2718. for (chunkerCurrentIndex = chunkerCurrentIndex + 1; chunkerCurrentIndex < len; chunkerCurrentIndex++) {
  2719. cc2 = input.charCodeAt(chunkerCurrentIndex);
  2720. if (cc2 > 96) {
  2721. continue;
  2722. }
  2723. if (cc2 == cc) {
  2724. matched = 1;
  2725. break;
  2726. }
  2727. if (cc2 == 92) { // \
  2728. if (chunkerCurrentIndex == len - 1) {
  2729. return fail('unescaped `\\`', chunkerCurrentIndex);
  2730. }
  2731. chunkerCurrentIndex++;
  2732. }
  2733. }
  2734. if (matched) {
  2735. continue;
  2736. }
  2737. return fail("unmatched `" + String.fromCharCode(cc) + "`", currentChunkStartIndex);
  2738. case 47: // /, check for comment
  2739. if (parenLevel || (chunkerCurrentIndex == len - 1)) {
  2740. continue;
  2741. }
  2742. cc2 = input.charCodeAt(chunkerCurrentIndex + 1);
  2743. if (cc2 == 47) {
  2744. // //, find lnfeed
  2745. for (chunkerCurrentIndex = chunkerCurrentIndex + 2; chunkerCurrentIndex < len; chunkerCurrentIndex++) {
  2746. cc2 = input.charCodeAt(chunkerCurrentIndex);
  2747. if ((cc2 <= 13) && ((cc2 == 10) || (cc2 == 13))) {
  2748. break;
  2749. }
  2750. }
  2751. }
  2752. else if (cc2 == 42) {
  2753. // /*, find */
  2754. lastMultiComment = currentChunkStartIndex = chunkerCurrentIndex;
  2755. for (chunkerCurrentIndex = chunkerCurrentIndex + 2; chunkerCurrentIndex < len - 1; chunkerCurrentIndex++) {
  2756. cc2 = input.charCodeAt(chunkerCurrentIndex);
  2757. if (cc2 == 125) {
  2758. lastMultiCommentEndBrace = chunkerCurrentIndex;
  2759. }
  2760. if (cc2 != 42) {
  2761. continue;
  2762. }
  2763. if (input.charCodeAt(chunkerCurrentIndex + 1) == 47) {
  2764. break;
  2765. }
  2766. }
  2767. if (chunkerCurrentIndex == len - 1) {
  2768. return fail('missing closing `*/`', currentChunkStartIndex);
  2769. }
  2770. chunkerCurrentIndex++;
  2771. }
  2772. continue;
  2773. case 42: // *, check for unmatched */
  2774. if ((chunkerCurrentIndex < len - 1) && (input.charCodeAt(chunkerCurrentIndex + 1) == 47)) {
  2775. return fail('unmatched `/*`', chunkerCurrentIndex);
  2776. }
  2777. continue;
  2778. }
  2779. }
  2780. if (level !== 0) {
  2781. if ((lastMultiComment > lastOpening) && (lastMultiCommentEndBrace > lastMultiComment)) {
  2782. return fail('missing closing `}` or `*/`', lastOpening);
  2783. }
  2784. else {
  2785. return fail('missing closing `}`', lastOpening);
  2786. }
  2787. }
  2788. else if (parenLevel !== 0) {
  2789. return fail('missing closing `)`', lastOpeningParen);
  2790. }
  2791. emitChunk(true);
  2792. return chunks;
  2793. }
  2794. var getParserInput = (function () {
  2795. var // Less input string
  2796. input;
  2797. var // current chunk
  2798. j;
  2799. var // holds state for backtracking
  2800. saveStack = [];
  2801. var // furthest index the parser has gone to
  2802. furthest;
  2803. var // if this is furthest we got to, this is the probably cause
  2804. furthestPossibleErrorMessage;
  2805. var // chunkified input
  2806. chunks;
  2807. var // current chunk
  2808. current;
  2809. var // index of current chunk, in `input`
  2810. currentPos;
  2811. var parserInput = {};
  2812. var CHARCODE_SPACE = 32;
  2813. var CHARCODE_TAB = 9;
  2814. var CHARCODE_LF = 10;
  2815. var CHARCODE_CR = 13;
  2816. var CHARCODE_PLUS = 43;
  2817. var CHARCODE_COMMA = 44;
  2818. var CHARCODE_FORWARD_SLASH = 47;
  2819. var CHARCODE_9 = 57;
  2820. function skipWhitespace(length) {
  2821. var oldi = parserInput.i;
  2822. var oldj = j;
  2823. var curr = parserInput.i - currentPos;
  2824. var endIndex = parserInput.i + current.length - curr;
  2825. var mem = (parserInput.i += length);
  2826. var inp = input;
  2827. var c;
  2828. var nextChar;
  2829. var comment;
  2830. for (; parserInput.i < endIndex; parserInput.i++) {
  2831. c = inp.charCodeAt(parserInput.i);
  2832. if (parserInput.autoCommentAbsorb && c === CHARCODE_FORWARD_SLASH) {
  2833. nextChar = inp.charAt(parserInput.i + 1);
  2834. if (nextChar === '/') {
  2835. comment = { index: parserInput.i, isLineComment: true };
  2836. var nextNewLine = inp.indexOf('\n', parserInput.i + 2);
  2837. if (nextNewLine < 0) {
  2838. nextNewLine = endIndex;
  2839. }
  2840. parserInput.i = nextNewLine;
  2841. comment.text = inp.substr(comment.index, parserInput.i - comment.index);
  2842. parserInput.commentStore.push(comment);
  2843. continue;
  2844. }
  2845. else if (nextChar === '*') {
  2846. var nextStarSlash = inp.indexOf('*/', parserInput.i + 2);
  2847. if (nextStarSlash >= 0) {
  2848. comment = {
  2849. index: parserInput.i,
  2850. text: inp.substr(parserInput.i, nextStarSlash + 2 - parserInput.i),
  2851. isLineComment: false
  2852. };
  2853. parserInput.i += comment.text.length - 1;
  2854. parserInput.commentStore.push(comment);
  2855. continue;
  2856. }
  2857. }
  2858. break;
  2859. }
  2860. if ((c !== CHARCODE_SPACE) && (c !== CHARCODE_LF) && (c !== CHARCODE_TAB) && (c !== CHARCODE_CR)) {
  2861. break;
  2862. }
  2863. }
  2864. current = current.slice(length + parserInput.i - mem + curr);
  2865. currentPos = parserInput.i;
  2866. if (!current.length) {
  2867. if (j < chunks.length - 1) {
  2868. current = chunks[++j];
  2869. skipWhitespace(0); // skip space at the beginning of a chunk
  2870. return true; // things changed
  2871. }
  2872. parserInput.finished = true;
  2873. }
  2874. return oldi !== parserInput.i || oldj !== j;
  2875. }
  2876. parserInput.save = function () {
  2877. currentPos = parserInput.i;
  2878. saveStack.push({ current: current, i: parserInput.i, j: j });
  2879. };
  2880. parserInput.restore = function (possibleErrorMessage) {
  2881. if (parserInput.i > furthest || (parserInput.i === furthest && possibleErrorMessage && !furthestPossibleErrorMessage)) {
  2882. furthest = parserInput.i;
  2883. furthestPossibleErrorMessage = possibleErrorMessage;
  2884. }
  2885. var state = saveStack.pop();
  2886. current = state.current;
  2887. currentPos = parserInput.i = state.i;
  2888. j = state.j;
  2889. };
  2890. parserInput.forget = function () {
  2891. saveStack.pop();
  2892. };
  2893. parserInput.isWhitespace = function (offset) {
  2894. var pos = parserInput.i + (offset || 0);
  2895. var code = input.charCodeAt(pos);
  2896. return (code === CHARCODE_SPACE || code === CHARCODE_CR || code === CHARCODE_TAB || code === CHARCODE_LF);
  2897. };
  2898. // Specialization of $(tok)
  2899. parserInput.$re = function (tok) {
  2900. if (parserInput.i > currentPos) {
  2901. current = current.slice(parserInput.i - currentPos);
  2902. currentPos = parserInput.i;
  2903. }
  2904. var m = tok.exec(current);
  2905. if (!m) {
  2906. return null;
  2907. }
  2908. skipWhitespace(m[0].length);
  2909. if (typeof m === 'string') {
  2910. return m;
  2911. }
  2912. return m.length === 1 ? m[0] : m;
  2913. };
  2914. parserInput.$char = function (tok) {
  2915. if (input.charAt(parserInput.i) !== tok) {
  2916. return null;
  2917. }
  2918. skipWhitespace(1);
  2919. return tok;
  2920. };
  2921. parserInput.$peekChar = function (tok) {
  2922. if (input.charAt(parserInput.i) !== tok) {
  2923. return null;
  2924. }
  2925. return tok;
  2926. };
  2927. parserInput.$str = function (tok) {
  2928. var tokLength = tok.length;
  2929. // https://jsperf.com/string-startswith/21
  2930. for (var i_1 = 0; i_1 < tokLength; i_1++) {
  2931. if (input.charAt(parserInput.i + i_1) !== tok.charAt(i_1)) {
  2932. return null;
  2933. }
  2934. }
  2935. skipWhitespace(tokLength);
  2936. return tok;
  2937. };
  2938. parserInput.$quoted = function (loc) {
  2939. var pos = loc || parserInput.i;
  2940. var startChar = input.charAt(pos);
  2941. if (startChar !== '\'' && startChar !== '"') {
  2942. return;
  2943. }
  2944. var length = input.length;
  2945. var currentPosition = pos;
  2946. for (var i_2 = 1; i_2 + currentPosition < length; i_2++) {
  2947. var nextChar = input.charAt(i_2 + currentPosition);
  2948. switch (nextChar) {
  2949. case '\\':
  2950. i_2++;
  2951. continue;
  2952. case '\r':
  2953. case '\n':
  2954. break;
  2955. case startChar: {
  2956. var str = input.substr(currentPosition, i_2 + 1);
  2957. if (!loc && loc !== 0) {
  2958. skipWhitespace(i_2 + 1);
  2959. return str;
  2960. }
  2961. return [startChar, str];
  2962. }
  2963. }
  2964. }
  2965. return null;
  2966. };
  2967. /**
  2968. * Permissive parsing. Ignores everything except matching {} [] () and quotes
  2969. * until matching token (outside of blocks)
  2970. */
  2971. parserInput.$parseUntil = function (tok) {
  2972. var quote = '';
  2973. var returnVal = null;
  2974. var inComment = false;
  2975. var blockDepth = 0;
  2976. var blockStack = [];
  2977. var parseGroups = [];
  2978. var length = input.length;
  2979. var startPos = parserInput.i;
  2980. var lastPos = parserInput.i;
  2981. var i = parserInput.i;
  2982. var loop = true;
  2983. var testChar;
  2984. if (typeof tok === 'string') {
  2985. testChar = function (char) { return char === tok; };
  2986. }
  2987. else {
  2988. testChar = function (char) { return tok.test(char); };
  2989. }
  2990. do {
  2991. var nextChar = input.charAt(i);
  2992. if (blockDepth === 0 && testChar(nextChar)) {
  2993. returnVal = input.substr(lastPos, i - lastPos);
  2994. if (returnVal) {
  2995. parseGroups.push(returnVal);
  2996. }
  2997. else {
  2998. parseGroups.push(' ');
  2999. }
  3000. returnVal = parseGroups;
  3001. skipWhitespace(i - startPos);
  3002. loop = false;
  3003. }
  3004. else {
  3005. if (inComment) {
  3006. if (nextChar === '*' &&
  3007. input.charAt(i + 1) === '/') {
  3008. i++;
  3009. blockDepth--;
  3010. inComment = false;
  3011. }
  3012. i++;
  3013. continue;
  3014. }
  3015. switch (nextChar) {
  3016. case '\\':
  3017. i++;
  3018. nextChar = input.charAt(i);
  3019. parseGroups.push(input.substr(lastPos, i - lastPos + 1));
  3020. lastPos = i + 1;
  3021. break;
  3022. case '/':
  3023. if (input.charAt(i + 1) === '*') {
  3024. i++;
  3025. inComment = true;
  3026. blockDepth++;
  3027. }
  3028. break;
  3029. case '\'':
  3030. case '"':
  3031. quote = parserInput.$quoted(i);
  3032. if (quote) {
  3033. parseGroups.push(input.substr(lastPos, i - lastPos), quote);
  3034. i += quote[1].length - 1;
  3035. lastPos = i + 1;
  3036. }
  3037. else {
  3038. skipWhitespace(i - startPos);
  3039. returnVal = nextChar;
  3040. loop = false;
  3041. }
  3042. break;
  3043. case '{':
  3044. blockStack.push('}');
  3045. blockDepth++;
  3046. break;
  3047. case '(':
  3048. blockStack.push(')');
  3049. blockDepth++;
  3050. break;
  3051. case '[':
  3052. blockStack.push(']');
  3053. blockDepth++;
  3054. break;
  3055. case '}':
  3056. case ')':
  3057. case ']': {
  3058. var expected = blockStack.pop();
  3059. if (nextChar === expected) {
  3060. blockDepth--;
  3061. }
  3062. else {
  3063. // move the parser to the error and return expected
  3064. skipWhitespace(i - startPos);
  3065. returnVal = expected;
  3066. loop = false;
  3067. }
  3068. }
  3069. }
  3070. i++;
  3071. if (i > length) {
  3072. loop = false;
  3073. }
  3074. }
  3075. } while (loop);
  3076. return returnVal ? returnVal : null;
  3077. };
  3078. parserInput.autoCommentAbsorb = true;
  3079. parserInput.commentStore = [];
  3080. parserInput.finished = false;
  3081. // Same as $(), but don't change the state of the parser,
  3082. // just return the match.
  3083. parserInput.peek = function (tok) {
  3084. if (typeof tok === 'string') {
  3085. // https://jsperf.com/string-startswith/21
  3086. for (var i_3 = 0; i_3 < tok.length; i_3++) {
  3087. if (input.charAt(parserInput.i + i_3) !== tok.charAt(i_3)) {
  3088. return false;
  3089. }
  3090. }
  3091. return true;
  3092. }
  3093. else {
  3094. return tok.test(current);
  3095. }
  3096. };
  3097. // Specialization of peek()
  3098. // TODO remove or change some currentChar calls to peekChar
  3099. parserInput.peekChar = function (tok) { return input.charAt(parserInput.i) === tok; };
  3100. parserInput.currentChar = function () { return input.charAt(parserInput.i); };
  3101. parserInput.prevChar = function () { return input.charAt(parserInput.i - 1); };
  3102. parserInput.getInput = function () { return input; };
  3103. parserInput.peekNotNumeric = function () {
  3104. var c = input.charCodeAt(parserInput.i);
  3105. // Is the first char of the dimension 0-9, '.', '+' or '-'
  3106. return (c > CHARCODE_9 || c < CHARCODE_PLUS) || c === CHARCODE_FORWARD_SLASH || c === CHARCODE_COMMA;
  3107. };
  3108. parserInput.start = function (str, chunkInput, failFunction) {
  3109. input = str;
  3110. parserInput.i = j = currentPos = furthest = 0;
  3111. // chunking apparently makes things quicker (but my tests indicate
  3112. // it might actually make things slower in node at least)
  3113. // and it is a non-perfect parse - it can't recognise
  3114. // unquoted urls, meaning it can't distinguish comments
  3115. // meaning comments with quotes or {}() in them get 'counted'
  3116. // and then lead to parse errors.
  3117. // In addition if the chunking chunks in the wrong place we might
  3118. // not be able to parse a parser statement in one go
  3119. // this is officially deprecated but can be switched on via an option
  3120. // in the case it causes too much performance issues.
  3121. if (chunkInput) {
  3122. chunks = chunker(str, failFunction);
  3123. }
  3124. else {
  3125. chunks = [str];
  3126. }
  3127. current = chunks[0];
  3128. skipWhitespace(0);
  3129. };
  3130. parserInput.end = function () {
  3131. var message;
  3132. var isFinished = parserInput.i >= input.length;
  3133. if (parserInput.i < furthest) {
  3134. message = furthestPossibleErrorMessage;
  3135. parserInput.i = furthest;
  3136. }
  3137. return {
  3138. isFinished: isFinished,
  3139. furthest: parserInput.i,
  3140. furthestPossibleErrorMessage: message,
  3141. furthestReachedEnd: parserInput.i >= input.length - 1,
  3142. furthestChar: input[parserInput.i]
  3143. };
  3144. };
  3145. return parserInput;
  3146. });
  3147. function makeRegistry(base) {
  3148. return {
  3149. _data: {},
  3150. add: function (name, func) {
  3151. // precautionary case conversion, as later querying of
  3152. // the registry by function-caller uses lower case as well.
  3153. name = name.toLowerCase();
  3154. // eslint-disable-next-line no-prototype-builtins
  3155. if (this._data.hasOwnProperty(name)) ;
  3156. this._data[name] = func;
  3157. },
  3158. addMultiple: function (functions) {
  3159. var _this = this;
  3160. Object.keys(functions).forEach(function (name) {
  3161. _this.add(name, functions[name]);
  3162. });
  3163. },
  3164. get: function (name) {
  3165. return this._data[name] || (base && base.get(name));
  3166. },
  3167. getLocalFunctions: function () {
  3168. return this._data;
  3169. },
  3170. inherit: function () {
  3171. return makeRegistry(this);
  3172. },
  3173. create: function (base) {
  3174. return makeRegistry(base);
  3175. }
  3176. };
  3177. }
  3178. var functionRegistry = makeRegistry(null);
  3179. var MediaSyntaxOptions = {
  3180. queryInParens: true
  3181. };
  3182. var ContainerSyntaxOptions = {
  3183. queryInParens: true
  3184. };
  3185. //
  3186. // less.js - parser
  3187. //
  3188. // A relatively straight-forward predictive parser.
  3189. // There is no tokenization/lexing stage, the input is parsed
  3190. // in one sweep.
  3191. //
  3192. // To make the parser fast enough to run in the browser, several
  3193. // optimization had to be made:
  3194. //
  3195. // - Matching and slicing on a huge input is often cause of slowdowns.
  3196. // The solution is to chunkify the input into smaller strings.
  3197. // The chunks are stored in the `chunks` var,
  3198. // `j` holds the current chunk index, and `currentPos` holds
  3199. // the index of the current chunk in relation to `input`.
  3200. // This gives us an almost 4x speed-up.
  3201. //
  3202. // - In many cases, we don't need to match individual tokens;
  3203. // for example, if a value doesn't hold any variables, operations
  3204. // or dynamic references, the parser can effectively 'skip' it,
  3205. // treating it as a literal.
  3206. // An example would be '1px solid #000' - which evaluates to itself,
  3207. // we don't need to know what the individual components are.
  3208. // The drawback, of course is that you don't get the benefits of
  3209. // syntax-checking on the CSS. This gives us a 50% speed-up in the parser,
  3210. // and a smaller speed-up in the code-gen.
  3211. //
  3212. //
  3213. // Token matching is done with the `$` function, which either takes
  3214. // a terminal string or regexp, or a non-terminal function to call.
  3215. // It also takes care of moving all the indices forwards.
  3216. //
  3217. var Parser = function Parser(context, imports, fileInfo, currentIndex) {
  3218. currentIndex = currentIndex || 0;
  3219. var parsers;
  3220. var parserInput = getParserInput();
  3221. function error(msg, type) {
  3222. throw new LessError({
  3223. index: parserInput.i,
  3224. filename: fileInfo.filename,
  3225. type: type || 'Syntax',
  3226. message: msg
  3227. }, imports);
  3228. }
  3229. function expect(arg, msg) {
  3230. // some older browsers return typeof 'function' for RegExp
  3231. var result = (arg instanceof Function) ? arg.call(parsers) : parserInput.$re(arg);
  3232. if (result) {
  3233. return result;
  3234. }
  3235. error(msg || (typeof arg === 'string'
  3236. ? "expected '" + arg + "' got '" + parserInput.currentChar() + "'"
  3237. : 'unexpected token'));
  3238. }
  3239. // Specialization of expect()
  3240. function expectChar(arg, msg) {
  3241. if (parserInput.$char(arg)) {
  3242. return arg;
  3243. }
  3244. error(msg || "expected '" + arg + "' got '" + parserInput.currentChar() + "'");
  3245. }
  3246. function getDebugInfo(index) {
  3247. var filename = fileInfo.filename;
  3248. return {
  3249. lineNumber: getLocation(index, parserInput.getInput()).line + 1,
  3250. fileName: filename
  3251. };
  3252. }
  3253. /**
  3254. * Used after initial parsing to create nodes on the fly
  3255. *
  3256. * @param {String} str - string to parse
  3257. * @param {Array} parseList - array of parsers to run input through e.g. ["value", "important"]
  3258. * @param {Number} currentIndex - start number to begin indexing
  3259. * @param {Object} fileInfo - fileInfo to attach to created nodes
  3260. */
  3261. function parseNode(str, parseList, callback) {
  3262. var result;
  3263. var returnNodes = [];
  3264. var parser = parserInput;
  3265. try {
  3266. parser.start(str, false, function fail(msg, index) {
  3267. callback({
  3268. message: msg,
  3269. index: index + currentIndex
  3270. });
  3271. });
  3272. for (var x = 0, p = void 0; (p = parseList[x]); x++) {
  3273. result = parsers[p]();
  3274. returnNodes.push(result || null);
  3275. }
  3276. var endInfo = parser.end();
  3277. if (endInfo.isFinished) {
  3278. callback(null, returnNodes);
  3279. }
  3280. else {
  3281. callback(true, null);
  3282. }
  3283. }
  3284. catch (e) {
  3285. throw new LessError({
  3286. index: e.index + currentIndex,
  3287. message: e.message
  3288. }, imports, fileInfo.filename);
  3289. }
  3290. }
  3291. //
  3292. // The Parser
  3293. //
  3294. return {
  3295. parserInput: parserInput,
  3296. imports: imports,
  3297. fileInfo: fileInfo,
  3298. parseNode: parseNode,
  3299. //
  3300. // Parse an input string into an abstract syntax tree,
  3301. // @param str A string containing 'less' markup
  3302. // @param callback call `callback` when done.
  3303. // @param [additionalData] An optional map which can contains vars - a map (key, value) of variables to apply
  3304. //
  3305. parse: function (str, callback, additionalData) {
  3306. var root;
  3307. var err = null;
  3308. var globalVars;
  3309. var modifyVars;
  3310. var ignored;
  3311. var preText = '';
  3312. // Optionally disable @plugin parsing
  3313. if (additionalData && additionalData.disablePluginRule) {
  3314. parsers.plugin = function () {
  3315. var dir = parserInput.$re(/^@plugin?\s+/);
  3316. if (dir) {
  3317. error('@plugin statements are not allowed when disablePluginRule is set to true');
  3318. }
  3319. };
  3320. }
  3321. globalVars = (additionalData && additionalData.globalVars) ? Parser.serializeVars(additionalData.globalVars) + "\n" : '';
  3322. modifyVars = (additionalData && additionalData.modifyVars) ? "\n" + Parser.serializeVars(additionalData.modifyVars) : '';
  3323. if (context.pluginManager) {
  3324. var preProcessors = context.pluginManager.getPreProcessors();
  3325. for (var i_1 = 0; i_1 < preProcessors.length; i_1++) {
  3326. str = preProcessors[i_1].process(str, { context: context, imports: imports, fileInfo: fileInfo });
  3327. }
  3328. }
  3329. if (globalVars || (additionalData && additionalData.banner)) {
  3330. preText = ((additionalData && additionalData.banner) ? additionalData.banner : '') + globalVars;
  3331. ignored = imports.contentsIgnoredChars;
  3332. ignored[fileInfo.filename] = ignored[fileInfo.filename] || 0;
  3333. ignored[fileInfo.filename] += preText.length;
  3334. }
  3335. str = str.replace(/\r\n?/g, '\n');
  3336. // Remove potential UTF Byte Order Mark
  3337. str = preText + str.replace(/^\uFEFF/, '') + modifyVars;
  3338. imports.contents[fileInfo.filename] = str;
  3339. // Start with the primary rule.
  3340. // The whole syntax tree is held under a Ruleset node,
  3341. // with the `root` property set to true, so no `{}` are
  3342. // output. The callback is called when the input is parsed.
  3343. try {
  3344. parserInput.start(str, context.chunkInput, function fail(msg, index) {
  3345. throw new LessError({
  3346. index: index,
  3347. type: 'Parse',
  3348. message: msg,
  3349. filename: fileInfo.filename
  3350. }, imports);
  3351. });
  3352. tree.Node.prototype.parse = this;
  3353. root = new tree.Ruleset(null, this.parsers.primary());
  3354. tree.Node.prototype.rootNode = root;
  3355. root.root = true;
  3356. root.firstRoot = true;
  3357. root.functionRegistry = functionRegistry.inherit();
  3358. }
  3359. catch (e) {
  3360. return callback(new LessError(e, imports, fileInfo.filename));
  3361. }
  3362. // If `i` is smaller than the `input.length - 1`,
  3363. // it means the parser wasn't able to parse the whole
  3364. // string, so we've got a parsing error.
  3365. //
  3366. // We try to extract a \n delimited string,
  3367. // showing the line where the parse error occurred.
  3368. // We split it up into two parts (the part which parsed,
  3369. // and the part which didn't), so we can color them differently.
  3370. var endInfo = parserInput.end();
  3371. if (!endInfo.isFinished) {
  3372. var message = endInfo.furthestPossibleErrorMessage;
  3373. if (!message) {
  3374. message = 'Unrecognised input';
  3375. if (endInfo.furthestChar === '}') {
  3376. message += '. Possibly missing opening \'{\'';
  3377. }
  3378. else if (endInfo.furthestChar === ')') {
  3379. message += '. Possibly missing opening \'(\'';
  3380. }
  3381. else if (endInfo.furthestReachedEnd) {
  3382. message += '. Possibly missing something';
  3383. }
  3384. }
  3385. err = new LessError({
  3386. type: 'Parse',
  3387. message: message,
  3388. index: endInfo.furthest,
  3389. filename: fileInfo.filename
  3390. }, imports);
  3391. }
  3392. var finish = function (e) {
  3393. e = err || e || imports.error;
  3394. if (e) {
  3395. if (!(e instanceof LessError)) {
  3396. e = new LessError(e, imports, fileInfo.filename);
  3397. }
  3398. return callback(e);
  3399. }
  3400. else {
  3401. return callback(null, root);
  3402. }
  3403. };
  3404. if (context.processImports !== false) {
  3405. new visitors.ImportVisitor(imports, finish)
  3406. .run(root);
  3407. }
  3408. else {
  3409. return finish();
  3410. }
  3411. },
  3412. //
  3413. // Here in, the parsing rules/functions
  3414. //
  3415. // The basic structure of the syntax tree generated is as follows:
  3416. //
  3417. // Ruleset -> Declaration -> Value -> Expression -> Entity
  3418. //
  3419. // Here's some Less code:
  3420. //
  3421. // .class {
  3422. // color: #fff;
  3423. // border: 1px solid #000;
  3424. // width: @w + 4px;
  3425. // > .child {...}
  3426. // }
  3427. //
  3428. // And here's what the parse tree might look like:
  3429. //
  3430. // Ruleset (Selector '.class', [
  3431. // Declaration ("color", Value ([Expression [Color #fff]]))
  3432. // Declaration ("border", Value ([Expression [Dimension 1px][Keyword "solid"][Color #000]]))
  3433. // Declaration ("width", Value ([Expression [Operation " + " [Variable "@w"][Dimension 4px]]]))
  3434. // Ruleset (Selector [Element '>', '.child'], [...])
  3435. // ])
  3436. //
  3437. // In general, most rules will try to parse a token with the `$re()` function, and if the return
  3438. // value is truly, will return a new node, of the relevant type. Sometimes, we need to check
  3439. // first, before parsing, that's when we use `peek()`.
  3440. //
  3441. parsers: parsers = {
  3442. //
  3443. // The `primary` rule is the *entry* and *exit* point of the parser.
  3444. // The rules here can appear at any level of the parse tree.
  3445. //
  3446. // The recursive nature of the grammar is an interplay between the `block`
  3447. // rule, which represents `{ ... }`, the `ruleset` rule, and this `primary` rule,
  3448. // as represented by this simplified grammar:
  3449. //
  3450. // primary → (ruleset | declaration)+
  3451. // ruleset → selector+ block
  3452. // block → '{' primary '}'
  3453. //
  3454. // Only at one point is the primary rule not called from the
  3455. // block rule: at the root level.
  3456. //
  3457. primary: function () {
  3458. var mixin = this.mixin;
  3459. var root = [];
  3460. var node;
  3461. while (true) {
  3462. while (true) {
  3463. node = this.comment();
  3464. if (!node) {
  3465. break;
  3466. }
  3467. root.push(node);
  3468. }
  3469. // always process comments before deciding if finished
  3470. if (parserInput.finished) {
  3471. break;
  3472. }
  3473. if (parserInput.peek('}')) {
  3474. break;
  3475. }
  3476. node = this.extendRule();
  3477. if (node) {
  3478. root = root.concat(node);
  3479. continue;
  3480. }
  3481. node = mixin.definition() || this.declaration() || mixin.call(false, false) ||
  3482. this.ruleset() || this.variableCall() || this.entities.call() || this.atrule();
  3483. if (node) {
  3484. root.push(node);
  3485. }
  3486. else {
  3487. var foundSemiColon = false;
  3488. while (parserInput.$char(';')) {
  3489. foundSemiColon = true;
  3490. }
  3491. if (!foundSemiColon) {
  3492. break;
  3493. }
  3494. }
  3495. }
  3496. return root;
  3497. },
  3498. // comments are collected by the main parsing mechanism and then assigned to nodes
  3499. // where the current structure allows it
  3500. comment: function () {
  3501. if (parserInput.commentStore.length) {
  3502. var comment = parserInput.commentStore.shift();
  3503. return new (tree.Comment)(comment.text, comment.isLineComment, comment.index + currentIndex, fileInfo);
  3504. }
  3505. },
  3506. //
  3507. // Entities are tokens which can be found inside an Expression
  3508. //
  3509. entities: {
  3510. mixinLookup: function () {
  3511. return parsers.mixin.call(true, true);
  3512. },
  3513. //
  3514. // A string, which supports escaping " and '
  3515. //
  3516. // "milky way" 'he\'s the one!'
  3517. //
  3518. quoted: function (forceEscaped) {
  3519. var str;
  3520. var index = parserInput.i;
  3521. var isEscaped = false;
  3522. parserInput.save();
  3523. if (parserInput.$char('~')) {
  3524. isEscaped = true;
  3525. }
  3526. else if (forceEscaped) {
  3527. parserInput.restore();
  3528. return;
  3529. }
  3530. str = parserInput.$quoted();
  3531. if (!str) {
  3532. parserInput.restore();
  3533. return;
  3534. }
  3535. parserInput.forget();
  3536. return new (tree.Quoted)(str.charAt(0), str.substr(1, str.length - 2), isEscaped, index + currentIndex, fileInfo);
  3537. },
  3538. //
  3539. // A catch-all word, such as:
  3540. //
  3541. // black border-collapse
  3542. //
  3543. keyword: function () {
  3544. var k = parserInput.$char('%') || parserInput.$re(/^\[?(?:[\w-]|\\(?:[A-Fa-f0-9]{1,6} ?|[^A-Fa-f0-9]))+\]?/);
  3545. if (k) {
  3546. return tree.Color.fromKeyword(k) || new (tree.Keyword)(k);
  3547. }
  3548. },
  3549. //
  3550. // A function call
  3551. //
  3552. // rgb(255, 0, 255)
  3553. //
  3554. // The arguments are parsed with the `entities.arguments` parser.
  3555. //
  3556. call: function () {
  3557. var name;
  3558. var args;
  3559. var func;
  3560. var index = parserInput.i;
  3561. // http://jsperf.com/case-insensitive-regex-vs-strtolower-then-regex/18
  3562. if (parserInput.peek(/^url\(/i)) {
  3563. return;
  3564. }
  3565. parserInput.save();
  3566. name = parserInput.$re(/^([\w-]+|%|~|progid:[\w.]+)\(/);
  3567. if (!name) {
  3568. parserInput.forget();
  3569. return;
  3570. }
  3571. name = name[1];
  3572. func = this.customFuncCall(name);
  3573. if (func) {
  3574. args = func.parse();
  3575. if (args && func.stop) {
  3576. parserInput.forget();
  3577. return args;
  3578. }
  3579. }
  3580. args = this.arguments(args);
  3581. if (!parserInput.$char(')')) {
  3582. parserInput.restore('Could not parse call arguments or missing \')\'');
  3583. return;
  3584. }
  3585. parserInput.forget();
  3586. return new (tree.Call)(name, args, index + currentIndex, fileInfo);
  3587. },
  3588. //
  3589. // Parsing rules for functions with non-standard args, e.g.:
  3590. //
  3591. // boolean(not(2 > 1))
  3592. //
  3593. // This is a quick prototype, to be modified/improved when
  3594. // more custom-parsed funcs come (e.g. `selector(...)`)
  3595. //
  3596. customFuncCall: function (name) {
  3597. /* Ideally the table is to be moved out of here for faster perf.,
  3598. but it's quite tricky since it relies on all these `parsers`
  3599. and `expect` available only here */
  3600. return {
  3601. alpha: f(parsers.ieAlpha, true),
  3602. boolean: f(condition),
  3603. 'if': f(condition)
  3604. }[name.toLowerCase()];
  3605. function f(parse, stop) {
  3606. return {
  3607. parse: parse,
  3608. stop: stop // when true - stop after parse() and return its result,
  3609. // otherwise continue for plain args
  3610. };
  3611. }
  3612. function condition() {
  3613. return [expect(parsers.condition, 'expected condition')];
  3614. }
  3615. },
  3616. arguments: function (prevArgs) {
  3617. var argsComma = prevArgs || [];
  3618. var argsSemiColon = [];
  3619. var isSemiColonSeparated;
  3620. var value;
  3621. parserInput.save();
  3622. while (true) {
  3623. if (prevArgs) {
  3624. prevArgs = false;
  3625. }
  3626. else {
  3627. value = parsers.detachedRuleset() || this.assignment() || parsers.expression();
  3628. if (!value) {
  3629. break;
  3630. }
  3631. if (value.value && value.value.length == 1) {
  3632. value = value.value[0];
  3633. }
  3634. argsComma.push(value);
  3635. }
  3636. if (parserInput.$char(',')) {
  3637. continue;
  3638. }
  3639. if (parserInput.$char(';') || isSemiColonSeparated) {
  3640. isSemiColonSeparated = true;
  3641. value = (argsComma.length < 1) ? argsComma[0]
  3642. : new tree.Value(argsComma);
  3643. argsSemiColon.push(value);
  3644. argsComma = [];
  3645. }
  3646. }
  3647. parserInput.forget();
  3648. return isSemiColonSeparated ? argsSemiColon : argsComma;
  3649. },
  3650. literal: function () {
  3651. return this.dimension() ||
  3652. this.color() ||
  3653. this.quoted() ||
  3654. this.unicodeDescriptor();
  3655. },
  3656. // Assignments are argument entities for calls.
  3657. // They are present in ie filter properties as shown below.
  3658. //
  3659. // filter: progid:DXImageTransform.Microsoft.Alpha( *opacity=50* )
  3660. //
  3661. assignment: function () {
  3662. var key;
  3663. var value;
  3664. parserInput.save();
  3665. key = parserInput.$re(/^\w+(?=\s?=)/i);
  3666. if (!key) {
  3667. parserInput.restore();
  3668. return;
  3669. }
  3670. if (!parserInput.$char('=')) {
  3671. parserInput.restore();
  3672. return;
  3673. }
  3674. value = parsers.entity();
  3675. if (value) {
  3676. parserInput.forget();
  3677. return new (tree.Assignment)(key, value);
  3678. }
  3679. else {
  3680. parserInput.restore();
  3681. }
  3682. },
  3683. //
  3684. // Parse url() tokens
  3685. //
  3686. // We use a specific rule for urls, because they don't really behave like
  3687. // standard function calls. The difference is that the argument doesn't have
  3688. // to be enclosed within a string, so it can't be parsed as an Expression.
  3689. //
  3690. url: function () {
  3691. var value;
  3692. var index = parserInput.i;
  3693. parserInput.autoCommentAbsorb = false;
  3694. if (!parserInput.$str('url(')) {
  3695. parserInput.autoCommentAbsorb = true;
  3696. return;
  3697. }
  3698. value = this.quoted() || this.variable() || this.property() ||
  3699. parserInput.$re(/^(?:(?:\\[()'"])|[^()'"])+/) || '';
  3700. parserInput.autoCommentAbsorb = true;
  3701. expectChar(')');
  3702. return new (tree.URL)((value.value !== undefined ||
  3703. value instanceof tree.Variable ||
  3704. value instanceof tree.Property) ?
  3705. value : new (tree.Anonymous)(value, index), index + currentIndex, fileInfo);
  3706. },
  3707. //
  3708. // A Variable entity, such as `@fink`, in
  3709. //
  3710. // width: @fink + 2px
  3711. //
  3712. // We use a different parser for variable definitions,
  3713. // see `parsers.variable`.
  3714. //
  3715. variable: function () {
  3716. var ch;
  3717. var name;
  3718. var index = parserInput.i;
  3719. parserInput.save();
  3720. if (parserInput.currentChar() === '@' && (name = parserInput.$re(/^@@?[\w-]+/))) {
  3721. ch = parserInput.currentChar();
  3722. if (ch === '(' || ch === '[' && !parserInput.prevChar().match(/^\s/)) {
  3723. // this may be a VariableCall lookup
  3724. var result = parsers.variableCall(name);
  3725. if (result) {
  3726. parserInput.forget();
  3727. return result;
  3728. }
  3729. }
  3730. parserInput.forget();
  3731. return new (tree.Variable)(name, index + currentIndex, fileInfo);
  3732. }
  3733. parserInput.restore();
  3734. },
  3735. // A variable entity using the protective {} e.g. @{var}
  3736. variableCurly: function () {
  3737. var curly;
  3738. var index = parserInput.i;
  3739. if (parserInput.currentChar() === '@' && (curly = parserInput.$re(/^@\{([\w-]+)\}/))) {
  3740. return new (tree.Variable)("@" + curly[1], index + currentIndex, fileInfo);
  3741. }
  3742. },
  3743. //
  3744. // A Property accessor, such as `$color`, in
  3745. //
  3746. // background-color: $color
  3747. //
  3748. property: function () {
  3749. var name;
  3750. var index = parserInput.i;
  3751. if (parserInput.currentChar() === '$' && (name = parserInput.$re(/^\$[\w-]+/))) {
  3752. return new (tree.Property)(name, index + currentIndex, fileInfo);
  3753. }
  3754. },
  3755. // A property entity useing the protective {} e.g. ${prop}
  3756. propertyCurly: function () {
  3757. var curly;
  3758. var index = parserInput.i;
  3759. if (parserInput.currentChar() === '$' && (curly = parserInput.$re(/^\$\{([\w-]+)\}/))) {
  3760. return new (tree.Property)("$" + curly[1], index + currentIndex, fileInfo);
  3761. }
  3762. },
  3763. //
  3764. // A Hexadecimal color
  3765. //
  3766. // #4F3C2F
  3767. //
  3768. // `rgb` and `hsl` colors are parsed through the `entities.call` parser.
  3769. //
  3770. color: function () {
  3771. var rgb;
  3772. parserInput.save();
  3773. if (parserInput.currentChar() === '#' && (rgb = parserInput.$re(/^#([A-Fa-f0-9]{8}|[A-Fa-f0-9]{6}|[A-Fa-f0-9]{3,4})([\w.#[])?/))) {
  3774. if (!rgb[2]) {
  3775. parserInput.forget();
  3776. return new (tree.Color)(rgb[1], undefined, rgb[0]);
  3777. }
  3778. }
  3779. parserInput.restore();
  3780. },
  3781. colorKeyword: function () {
  3782. parserInput.save();
  3783. var autoCommentAbsorb = parserInput.autoCommentAbsorb;
  3784. parserInput.autoCommentAbsorb = false;
  3785. var k = parserInput.$re(/^[_A-Za-z-][_A-Za-z0-9-]+/);
  3786. parserInput.autoCommentAbsorb = autoCommentAbsorb;
  3787. if (!k) {
  3788. parserInput.forget();
  3789. return;
  3790. }
  3791. parserInput.restore();
  3792. var color = tree.Color.fromKeyword(k);
  3793. if (color) {
  3794. parserInput.$str(k);
  3795. return color;
  3796. }
  3797. },
  3798. //
  3799. // A Dimension, that is, a number and a unit
  3800. //
  3801. // 0.5em 95%
  3802. //
  3803. dimension: function () {
  3804. if (parserInput.peekNotNumeric()) {
  3805. return;
  3806. }
  3807. var value = parserInput.$re(/^([+-]?\d*\.?\d+)(%|[a-z_]+)?/i);
  3808. if (value) {
  3809. return new (tree.Dimension)(value[1], value[2]);
  3810. }
  3811. },
  3812. //
  3813. // A unicode descriptor, as is used in unicode-range
  3814. //
  3815. // U+0?? or U+00A1-00A9
  3816. //
  3817. unicodeDescriptor: function () {
  3818. var ud;
  3819. ud = parserInput.$re(/^U\+[0-9a-fA-F?]+(-[0-9a-fA-F?]+)?/);
  3820. if (ud) {
  3821. return new (tree.UnicodeDescriptor)(ud[0]);
  3822. }
  3823. },
  3824. //
  3825. // JavaScript code to be evaluated
  3826. //
  3827. // `window.location.href`
  3828. //
  3829. javascript: function () {
  3830. var js;
  3831. var index = parserInput.i;
  3832. parserInput.save();
  3833. var escape = parserInput.$char('~');
  3834. var jsQuote = parserInput.$char('`');
  3835. if (!jsQuote) {
  3836. parserInput.restore();
  3837. return;
  3838. }
  3839. js = parserInput.$re(/^[^`]*`/);
  3840. if (js) {
  3841. parserInput.forget();
  3842. return new (tree.JavaScript)(js.substr(0, js.length - 1), Boolean(escape), index + currentIndex, fileInfo);
  3843. }
  3844. parserInput.restore('invalid javascript definition');
  3845. }
  3846. },
  3847. //
  3848. // The variable part of a variable definition. Used in the `rule` parser
  3849. //
  3850. // @fink:
  3851. //
  3852. variable: function () {
  3853. var name;
  3854. if (parserInput.currentChar() === '@' && (name = parserInput.$re(/^(@[\w-]+)\s*:/))) {
  3855. return name[1];
  3856. }
  3857. },
  3858. //
  3859. // Call a variable value to retrieve a detached ruleset
  3860. // or a value from a detached ruleset's rules.
  3861. //
  3862. // @fink();
  3863. // @fink;
  3864. // color: @fink[@color];
  3865. //
  3866. variableCall: function (parsedName) {
  3867. var lookups;
  3868. var i = parserInput.i;
  3869. var inValue = !!parsedName;
  3870. var name = parsedName;
  3871. parserInput.save();
  3872. if (name || (parserInput.currentChar() === '@'
  3873. && (name = parserInput.$re(/^(@[\w-]+)(\(\s*\))?/)))) {
  3874. lookups = this.mixin.ruleLookups();
  3875. if (!lookups && ((inValue && parserInput.$str('()') !== '()') || (name[2] !== '()'))) {
  3876. parserInput.restore('Missing \'[...]\' lookup in variable call');
  3877. return;
  3878. }
  3879. if (!inValue) {
  3880. name = name[1];
  3881. }
  3882. var call = new tree.VariableCall(name, i, fileInfo);
  3883. if (!inValue && parsers.end()) {
  3884. parserInput.forget();
  3885. return call;
  3886. }
  3887. else {
  3888. parserInput.forget();
  3889. return new tree.NamespaceValue(call, lookups, i, fileInfo);
  3890. }
  3891. }
  3892. parserInput.restore();
  3893. },
  3894. //
  3895. // extend syntax - used to extend selectors
  3896. //
  3897. extend: function (isRule) {
  3898. var elements;
  3899. var e;
  3900. var index = parserInput.i;
  3901. var option;
  3902. var extendList;
  3903. var extend;
  3904. if (!parserInput.$str(isRule ? '&:extend(' : ':extend(')) {
  3905. return;
  3906. }
  3907. do {
  3908. option = null;
  3909. elements = null;
  3910. while (!(option = parserInput.$re(/^(all)(?=\s*(\)|,))/))) {
  3911. e = this.element();
  3912. if (!e) {
  3913. break;
  3914. }
  3915. if (elements) {
  3916. elements.push(e);
  3917. }
  3918. else {
  3919. elements = [e];
  3920. }
  3921. }
  3922. option = option && option[1];
  3923. if (!elements) {
  3924. error('Missing target selector for :extend().');
  3925. }
  3926. extend = new (tree.Extend)(new (tree.Selector)(elements), option, index + currentIndex, fileInfo);
  3927. if (extendList) {
  3928. extendList.push(extend);
  3929. }
  3930. else {
  3931. extendList = [extend];
  3932. }
  3933. } while (parserInput.$char(','));
  3934. expect(/^\)/);
  3935. if (isRule) {
  3936. expect(/^;/);
  3937. }
  3938. return extendList;
  3939. },
  3940. //
  3941. // extendRule - used in a rule to extend all the parent selectors
  3942. //
  3943. extendRule: function () {
  3944. return this.extend(true);
  3945. },
  3946. //
  3947. // Mixins
  3948. //
  3949. mixin: {
  3950. //
  3951. // A Mixin call, with an optional argument list
  3952. //
  3953. // #mixins > .square(#fff);
  3954. // #mixins.square(#fff);
  3955. // .rounded(4px, black);
  3956. // .button;
  3957. //
  3958. // We can lookup / return a value using the lookup syntax:
  3959. //
  3960. // color: #mixin.square(#fff)[@color];
  3961. //
  3962. // The `while` loop is there because mixins can be
  3963. // namespaced, but we only support the child and descendant
  3964. // selector for now.
  3965. //
  3966. call: function (inValue, getLookup) {
  3967. var s = parserInput.currentChar();
  3968. var important = false;
  3969. var lookups;
  3970. var index = parserInput.i;
  3971. var elements;
  3972. var args;
  3973. var hasParens;
  3974. if (s !== '.' && s !== '#') {
  3975. return;
  3976. }
  3977. parserInput.save(); // stop us absorbing part of an invalid selector
  3978. elements = this.elements();
  3979. if (elements) {
  3980. if (parserInput.$char('(')) {
  3981. args = this.args(true).args;
  3982. expectChar(')');
  3983. hasParens = true;
  3984. }
  3985. if (getLookup !== false) {
  3986. lookups = this.ruleLookups();
  3987. }
  3988. if (getLookup === true && !lookups) {
  3989. parserInput.restore();
  3990. return;
  3991. }
  3992. if (inValue && !lookups && !hasParens) {
  3993. // This isn't a valid in-value mixin call
  3994. parserInput.restore();
  3995. return;
  3996. }
  3997. if (!inValue && parsers.important()) {
  3998. important = true;
  3999. }
  4000. if (inValue || parsers.end()) {
  4001. parserInput.forget();
  4002. var mixin = new (tree.mixin.Call)(elements, args, index + currentIndex, fileInfo, !lookups && important);
  4003. if (lookups) {
  4004. return new tree.NamespaceValue(mixin, lookups);
  4005. }
  4006. else {
  4007. return mixin;
  4008. }
  4009. }
  4010. }
  4011. parserInput.restore();
  4012. },
  4013. /**
  4014. * Matching elements for mixins
  4015. * (Start with . or # and can have > )
  4016. */
  4017. elements: function () {
  4018. var elements;
  4019. var e;
  4020. var c;
  4021. var elem;
  4022. var elemIndex;
  4023. var re = /^[#.](?:[\w-]|\\(?:[A-Fa-f0-9]{1,6} ?|[^A-Fa-f0-9]))+/;
  4024. while (true) {
  4025. elemIndex = parserInput.i;
  4026. e = parserInput.$re(re);
  4027. if (!e) {
  4028. break;
  4029. }
  4030. elem = new (tree.Element)(c, e, false, elemIndex + currentIndex, fileInfo);
  4031. if (elements) {
  4032. elements.push(elem);
  4033. }
  4034. else {
  4035. elements = [elem];
  4036. }
  4037. c = parserInput.$char('>');
  4038. }
  4039. return elements;
  4040. },
  4041. args: function (isCall) {
  4042. var entities = parsers.entities;
  4043. var returner = { args: null, variadic: false };
  4044. var expressions = [];
  4045. var argsSemiColon = [];
  4046. var argsComma = [];
  4047. var isSemiColonSeparated;
  4048. var expressionContainsNamed;
  4049. var name;
  4050. var nameLoop;
  4051. var value;
  4052. var arg;
  4053. var expand;
  4054. var hasSep = true;
  4055. parserInput.save();
  4056. while (true) {
  4057. if (isCall) {
  4058. arg = parsers.detachedRuleset() || parsers.expression();
  4059. }
  4060. else {
  4061. parserInput.commentStore.length = 0;
  4062. if (parserInput.$str('...')) {
  4063. returner.variadic = true;
  4064. if (parserInput.$char(';') && !isSemiColonSeparated) {
  4065. isSemiColonSeparated = true;
  4066. }
  4067. (isSemiColonSeparated ? argsSemiColon : argsComma)
  4068. .push({ variadic: true });
  4069. break;
  4070. }
  4071. arg = entities.variable() || entities.property() || entities.literal() || entities.keyword() || this.call(true);
  4072. }
  4073. if (!arg || !hasSep) {
  4074. break;
  4075. }
  4076. nameLoop = null;
  4077. if (arg.throwAwayComments) {
  4078. arg.throwAwayComments();
  4079. }
  4080. value = arg;
  4081. var val = null;
  4082. if (isCall) {
  4083. // Variable
  4084. if (arg.value && arg.value.length == 1) {
  4085. val = arg.value[0];
  4086. }
  4087. }
  4088. else {
  4089. val = arg;
  4090. }
  4091. if (val && (val instanceof tree.Variable || val instanceof tree.Property)) {
  4092. if (parserInput.$char(':')) {
  4093. if (expressions.length > 0) {
  4094. if (isSemiColonSeparated) {
  4095. error('Cannot mix ; and , as delimiter types');
  4096. }
  4097. expressionContainsNamed = true;
  4098. }
  4099. value = parsers.detachedRuleset() || parsers.expression();
  4100. if (!value) {
  4101. if (isCall) {
  4102. error('could not understand value for named argument');
  4103. }
  4104. else {
  4105. parserInput.restore();
  4106. returner.args = [];
  4107. return returner;
  4108. }
  4109. }
  4110. nameLoop = (name = val.name);
  4111. }
  4112. else if (parserInput.$str('...')) {
  4113. if (!isCall) {
  4114. returner.variadic = true;
  4115. if (parserInput.$char(';') && !isSemiColonSeparated) {
  4116. isSemiColonSeparated = true;
  4117. }
  4118. (isSemiColonSeparated ? argsSemiColon : argsComma)
  4119. .push({ name: arg.name, variadic: true });
  4120. break;
  4121. }
  4122. else {
  4123. expand = true;
  4124. }
  4125. }
  4126. else if (!isCall) {
  4127. name = nameLoop = val.name;
  4128. value = null;
  4129. }
  4130. }
  4131. if (value) {
  4132. expressions.push(value);
  4133. }
  4134. argsComma.push({ name: nameLoop, value: value, expand: expand });
  4135. if (parserInput.$char(',')) {
  4136. hasSep = true;
  4137. continue;
  4138. }
  4139. hasSep = parserInput.$char(';') === ';';
  4140. if (hasSep || isSemiColonSeparated) {
  4141. if (expressionContainsNamed) {
  4142. error('Cannot mix ; and , as delimiter types');
  4143. }
  4144. isSemiColonSeparated = true;
  4145. if (expressions.length > 1) {
  4146. value = new (tree.Value)(expressions);
  4147. }
  4148. argsSemiColon.push({ name: name, value: value, expand: expand });
  4149. name = null;
  4150. expressions = [];
  4151. expressionContainsNamed = false;
  4152. }
  4153. }
  4154. parserInput.forget();
  4155. returner.args = isSemiColonSeparated ? argsSemiColon : argsComma;
  4156. return returner;
  4157. },
  4158. //
  4159. // A Mixin definition, with a list of parameters
  4160. //
  4161. // .rounded (@radius: 2px, @color) {
  4162. // ...
  4163. // }
  4164. //
  4165. // Until we have a finer grained state-machine, we have to
  4166. // do a look-ahead, to make sure we don't have a mixin call.
  4167. // See the `rule` function for more information.
  4168. //
  4169. // We start by matching `.rounded (`, and then proceed on to
  4170. // the argument list, which has optional default values.
  4171. // We store the parameters in `params`, with a `value` key,
  4172. // if there is a value, such as in the case of `@radius`.
  4173. //
  4174. // Once we've got our params list, and a closing `)`, we parse
  4175. // the `{...}` block.
  4176. //
  4177. definition: function () {
  4178. var name;
  4179. var params = [];
  4180. var match;
  4181. var ruleset;
  4182. var cond;
  4183. var variadic = false;
  4184. if ((parserInput.currentChar() !== '.' && parserInput.currentChar() !== '#') ||
  4185. parserInput.peek(/^[^{]*\}/)) {
  4186. return;
  4187. }
  4188. parserInput.save();
  4189. match = parserInput.$re(/^([#.](?:[\w-]|\\(?:[A-Fa-f0-9]{1,6} ?|[^A-Fa-f0-9]))+)\s*\(/);
  4190. if (match) {
  4191. name = match[1];
  4192. var argInfo = this.args(false);
  4193. params = argInfo.args;
  4194. variadic = argInfo.variadic;
  4195. // .mixincall("@{a}");
  4196. // looks a bit like a mixin definition..
  4197. // also
  4198. // .mixincall(@a: {rule: set;});
  4199. // so we have to be nice and restore
  4200. if (!parserInput.$char(')')) {
  4201. parserInput.restore('Missing closing \')\'');
  4202. return;
  4203. }
  4204. parserInput.commentStore.length = 0;
  4205. if (parserInput.$str('when')) { // Guard
  4206. cond = expect(parsers.conditions, 'expected condition');
  4207. }
  4208. ruleset = parsers.block();
  4209. if (ruleset) {
  4210. parserInput.forget();
  4211. return new (tree.mixin.Definition)(name, params, ruleset, cond, variadic);
  4212. }
  4213. else {
  4214. parserInput.restore();
  4215. }
  4216. }
  4217. else {
  4218. parserInput.restore();
  4219. }
  4220. },
  4221. ruleLookups: function () {
  4222. var rule;
  4223. var lookups = [];
  4224. if (parserInput.currentChar() !== '[') {
  4225. return;
  4226. }
  4227. while (true) {
  4228. parserInput.save();
  4229. rule = this.lookupValue();
  4230. if (!rule && rule !== '') {
  4231. parserInput.restore();
  4232. break;
  4233. }
  4234. lookups.push(rule);
  4235. parserInput.forget();
  4236. }
  4237. if (lookups.length > 0) {
  4238. return lookups;
  4239. }
  4240. },
  4241. lookupValue: function () {
  4242. parserInput.save();
  4243. if (!parserInput.$char('[')) {
  4244. parserInput.restore();
  4245. return;
  4246. }
  4247. var name = parserInput.$re(/^(?:[@$]{0,2})[_a-zA-Z0-9-]*/);
  4248. if (!parserInput.$char(']')) {
  4249. parserInput.restore();
  4250. return;
  4251. }
  4252. if (name || name === '') {
  4253. parserInput.forget();
  4254. return name;
  4255. }
  4256. parserInput.restore();
  4257. }
  4258. },
  4259. //
  4260. // Entities are the smallest recognized token,
  4261. // and can be found inside a rule's value.
  4262. //
  4263. entity: function () {
  4264. var entities = this.entities;
  4265. return this.comment() || entities.literal() || entities.variable() || entities.url() ||
  4266. entities.property() || entities.call() || entities.keyword() || this.mixin.call(true) ||
  4267. entities.javascript();
  4268. },
  4269. //
  4270. // A Declaration terminator. Note that we use `peek()` to check for '}',
  4271. // because the `block` rule will be expecting it, but we still need to make sure
  4272. // it's there, if ';' was omitted.
  4273. //
  4274. end: function () {
  4275. return parserInput.$char(';') || parserInput.peek('}');
  4276. },
  4277. //
  4278. // IE's alpha function
  4279. //
  4280. // alpha(opacity=88)
  4281. //
  4282. ieAlpha: function () {
  4283. var value;
  4284. // http://jsperf.com/case-insensitive-regex-vs-strtolower-then-regex/18
  4285. if (!parserInput.$re(/^opacity=/i)) {
  4286. return;
  4287. }
  4288. value = parserInput.$re(/^\d+/);
  4289. if (!value) {
  4290. value = expect(parsers.entities.variable, 'Could not parse alpha');
  4291. value = "@{" + value.name.slice(1) + "}";
  4292. }
  4293. expectChar(')');
  4294. return new tree.Quoted('', "alpha(opacity=" + value + ")");
  4295. },
  4296. //
  4297. // A Selector Element
  4298. //
  4299. // div
  4300. // + h1
  4301. // #socks
  4302. // input[type="text"]
  4303. //
  4304. // Elements are the building blocks for Selectors,
  4305. // they are made out of a `Combinator` (see combinator rule),
  4306. // and an element name, such as a tag a class, or `*`.
  4307. //
  4308. element: function () {
  4309. var e;
  4310. var c;
  4311. var v;
  4312. var index = parserInput.i;
  4313. c = this.combinator();
  4314. e = parserInput.$re(/^(?:\d+\.\d+|\d+)%/) ||
  4315. // eslint-disable-next-line no-control-regex
  4316. parserInput.$re(/^(?:[.#]?|:*)(?:[\w-]|[^\x00-\x9f]|\\(?:[A-Fa-f0-9]{1,6} ?|[^A-Fa-f0-9]))+/) ||
  4317. parserInput.$char('*') || parserInput.$char('&') || this.attribute() ||
  4318. parserInput.$re(/^\([^&()@]+\)/) || parserInput.$re(/^[.#:](?=@)/) ||
  4319. this.entities.variableCurly();
  4320. if (!e) {
  4321. parserInput.save();
  4322. if (parserInput.$char('(')) {
  4323. if ((v = this.selector(false)) && parserInput.$char(')')) {
  4324. e = new (tree.Paren)(v);
  4325. parserInput.forget();
  4326. }
  4327. else {
  4328. parserInput.restore('Missing closing \')\'');
  4329. }
  4330. }
  4331. else {
  4332. parserInput.forget();
  4333. }
  4334. }
  4335. if (e) {
  4336. return new (tree.Element)(c, e, e instanceof tree.Variable, index + currentIndex, fileInfo);
  4337. }
  4338. },
  4339. //
  4340. // Combinators combine elements together, in a Selector.
  4341. //
  4342. // Because our parser isn't white-space sensitive, special care
  4343. // has to be taken, when parsing the descendant combinator, ` `,
  4344. // as it's an empty space. We have to check the previous character
  4345. // in the input, to see if it's a ` ` character. More info on how
  4346. // we deal with this in *combinator.js*.
  4347. //
  4348. combinator: function () {
  4349. var c = parserInput.currentChar();
  4350. if (c === '/') {
  4351. parserInput.save();
  4352. var slashedCombinator = parserInput.$re(/^\/[a-z]+\//i);
  4353. if (slashedCombinator) {
  4354. parserInput.forget();
  4355. return new (tree.Combinator)(slashedCombinator);
  4356. }
  4357. parserInput.restore();
  4358. }
  4359. if (c === '>' || c === '+' || c === '~' || c === '|' || c === '^') {
  4360. parserInput.i++;
  4361. if (c === '^' && parserInput.currentChar() === '^') {
  4362. c = '^^';
  4363. parserInput.i++;
  4364. }
  4365. while (parserInput.isWhitespace()) {
  4366. parserInput.i++;
  4367. }
  4368. return new (tree.Combinator)(c);
  4369. }
  4370. else if (parserInput.isWhitespace(-1)) {
  4371. return new (tree.Combinator)(' ');
  4372. }
  4373. else {
  4374. return new (tree.Combinator)(null);
  4375. }
  4376. },
  4377. //
  4378. // A CSS Selector
  4379. // with less extensions e.g. the ability to extend and guard
  4380. //
  4381. // .class > div + h1
  4382. // li a:hover
  4383. //
  4384. // Selectors are made out of one or more Elements, see above.
  4385. //
  4386. selector: function (isLess) {
  4387. var index = parserInput.i;
  4388. var elements;
  4389. var extendList;
  4390. var c;
  4391. var e;
  4392. var allExtends;
  4393. var when;
  4394. var condition;
  4395. isLess = isLess !== false;
  4396. while ((isLess && (extendList = this.extend())) || (isLess && (when = parserInput.$str('when'))) || (e = this.element())) {
  4397. if (when) {
  4398. condition = expect(this.conditions, 'expected condition');
  4399. }
  4400. else if (condition) {
  4401. error('CSS guard can only be used at the end of selector');
  4402. }
  4403. else if (extendList) {
  4404. if (allExtends) {
  4405. allExtends = allExtends.concat(extendList);
  4406. }
  4407. else {
  4408. allExtends = extendList;
  4409. }
  4410. }
  4411. else {
  4412. if (allExtends) {
  4413. error('Extend can only be used at the end of selector');
  4414. }
  4415. c = parserInput.currentChar();
  4416. if (elements) {
  4417. elements.push(e);
  4418. }
  4419. else {
  4420. elements = [e];
  4421. }
  4422. e = null;
  4423. }
  4424. if (c === '{' || c === '}' || c === ';' || c === ',' || c === ')') {
  4425. break;
  4426. }
  4427. }
  4428. if (elements) {
  4429. return new (tree.Selector)(elements, allExtends, condition, index + currentIndex, fileInfo);
  4430. }
  4431. if (allExtends) {
  4432. error('Extend must be used to extend a selector, it cannot be used on its own');
  4433. }
  4434. },
  4435. selectors: function () {
  4436. var s;
  4437. var selectors;
  4438. while (true) {
  4439. s = this.selector();
  4440. if (!s) {
  4441. break;
  4442. }
  4443. if (selectors) {
  4444. selectors.push(s);
  4445. }
  4446. else {
  4447. selectors = [s];
  4448. }
  4449. parserInput.commentStore.length = 0;
  4450. if (s.condition && selectors.length > 1) {
  4451. error('Guards are only currently allowed on a single selector.');
  4452. }
  4453. if (!parserInput.$char(',')) {
  4454. break;
  4455. }
  4456. if (s.condition) {
  4457. error('Guards are only currently allowed on a single selector.');
  4458. }
  4459. parserInput.commentStore.length = 0;
  4460. }
  4461. return selectors;
  4462. },
  4463. attribute: function () {
  4464. if (!parserInput.$char('[')) {
  4465. return;
  4466. }
  4467. var entities = this.entities;
  4468. var key;
  4469. var val;
  4470. var op;
  4471. //
  4472. // case-insensitive flag
  4473. // e.g. [attr operator value i]
  4474. //
  4475. var cif;
  4476. if (!(key = entities.variableCurly())) {
  4477. key = expect(/^(?:[_A-Za-z0-9-*]*\|)?(?:[_A-Za-z0-9-]|\\.)+/);
  4478. }
  4479. op = parserInput.$re(/^[|~*$^]?=/);
  4480. if (op) {
  4481. val = entities.quoted() || parserInput.$re(/^[0-9]+%/) || parserInput.$re(/^[\w-]+/) || entities.variableCurly();
  4482. if (val) {
  4483. cif = parserInput.$re(/^[iIsS]/);
  4484. }
  4485. }
  4486. expectChar(']');
  4487. return new (tree.Attribute)(key, op, val, cif);
  4488. },
  4489. //
  4490. // The `block` rule is used by `ruleset` and `mixin.definition`.
  4491. // It's a wrapper around the `primary` rule, with added `{}`.
  4492. //
  4493. block: function () {
  4494. var content;
  4495. if (parserInput.$char('{') && (content = this.primary()) && parserInput.$char('}')) {
  4496. return content;
  4497. }
  4498. },
  4499. blockRuleset: function () {
  4500. var block = this.block();
  4501. if (block) {
  4502. block = new tree.Ruleset(null, block);
  4503. }
  4504. return block;
  4505. },
  4506. detachedRuleset: function () {
  4507. var argInfo;
  4508. var params;
  4509. var variadic;
  4510. parserInput.save();
  4511. if (parserInput.$re(/^[.#]\(/)) {
  4512. /**
  4513. * DR args currently only implemented for each() function, and not
  4514. * yet settable as `@dr: #(@arg) {}`
  4515. * This should be done when DRs are merged with mixins.
  4516. * See: https://github.com/less/less-meta/issues/16
  4517. */
  4518. argInfo = this.mixin.args(false);
  4519. params = argInfo.args;
  4520. variadic = argInfo.variadic;
  4521. if (!parserInput.$char(')')) {
  4522. parserInput.restore();
  4523. return;
  4524. }
  4525. }
  4526. var blockRuleset = this.blockRuleset();
  4527. if (blockRuleset) {
  4528. parserInput.forget();
  4529. if (params) {
  4530. return new tree.mixin.Definition(null, params, blockRuleset, null, variadic);
  4531. }
  4532. return new tree.DetachedRuleset(blockRuleset);
  4533. }
  4534. parserInput.restore();
  4535. },
  4536. //
  4537. // div, .class, body > p {...}
  4538. //
  4539. ruleset: function () {
  4540. var selectors;
  4541. var rules;
  4542. var debugInfo;
  4543. parserInput.save();
  4544. if (context.dumpLineNumbers) {
  4545. debugInfo = getDebugInfo(parserInput.i);
  4546. }
  4547. selectors = this.selectors();
  4548. if (selectors && (rules = this.block())) {
  4549. parserInput.forget();
  4550. var ruleset = new (tree.Ruleset)(selectors, rules, context.strictImports);
  4551. if (context.dumpLineNumbers) {
  4552. ruleset.debugInfo = debugInfo;
  4553. }
  4554. return ruleset;
  4555. }
  4556. else {
  4557. parserInput.restore();
  4558. }
  4559. },
  4560. declaration: function () {
  4561. var name;
  4562. var value;
  4563. var index = parserInput.i;
  4564. var hasDR;
  4565. var c = parserInput.currentChar();
  4566. var important;
  4567. var merge;
  4568. var isVariable;
  4569. if (c === '.' || c === '#' || c === '&' || c === ':') {
  4570. return;
  4571. }
  4572. parserInput.save();
  4573. name = this.variable() || this.ruleProperty();
  4574. if (name) {
  4575. isVariable = typeof name === 'string';
  4576. if (isVariable) {
  4577. value = this.detachedRuleset();
  4578. if (value) {
  4579. hasDR = true;
  4580. }
  4581. }
  4582. parserInput.commentStore.length = 0;
  4583. if (!value) {
  4584. // a name returned by this.ruleProperty() is always an array of the form:
  4585. // [string-1, ..., string-n, ""] or [string-1, ..., string-n, "+"]
  4586. // where each item is a tree.Keyword or tree.Variable
  4587. merge = !isVariable && name.length > 1 && name.pop().value;
  4588. // Custom property values get permissive parsing
  4589. if (name[0].value && name[0].value.slice(0, 2) === '--') {
  4590. value = this.permissiveValue(/[;}]/);
  4591. }
  4592. // Try to store values as anonymous
  4593. // If we need the value later we'll re-parse it in ruleset.parseValue
  4594. else {
  4595. value = this.anonymousValue();
  4596. }
  4597. if (value) {
  4598. parserInput.forget();
  4599. // anonymous values absorb the end ';' which is required for them to work
  4600. return new (tree.Declaration)(name, value, false, merge, index + currentIndex, fileInfo);
  4601. }
  4602. if (!value) {
  4603. value = this.value();
  4604. }
  4605. if (value) {
  4606. important = this.important();
  4607. }
  4608. else if (isVariable) {
  4609. // As a last resort, try permissiveValue
  4610. value = this.permissiveValue();
  4611. }
  4612. }
  4613. if (value && (this.end() || hasDR)) {
  4614. parserInput.forget();
  4615. return new (tree.Declaration)(name, value, important, merge, index + currentIndex, fileInfo);
  4616. }
  4617. else {
  4618. parserInput.restore();
  4619. }
  4620. }
  4621. else {
  4622. parserInput.restore();
  4623. }
  4624. },
  4625. anonymousValue: function () {
  4626. var index = parserInput.i;
  4627. var match = parserInput.$re(/^([^.#@$+/'"*`(;{}-]*);/);
  4628. if (match) {
  4629. return new (tree.Anonymous)(match[1], index + currentIndex);
  4630. }
  4631. },
  4632. /**
  4633. * Used for custom properties, at-rules, and variables (as fallback)
  4634. * Parses almost anything inside of {} [] () "" blocks
  4635. * until it reaches outer-most tokens.
  4636. *
  4637. * First, it will try to parse comments and entities to reach
  4638. * the end. This is mostly like the Expression parser except no
  4639. * math is allowed.
  4640. */
  4641. permissiveValue: function (untilTokens) {
  4642. var i;
  4643. var e;
  4644. var done;
  4645. var value;
  4646. var tok = untilTokens || ';';
  4647. var index = parserInput.i;
  4648. var result = [];
  4649. function testCurrentChar() {
  4650. var char = parserInput.currentChar();
  4651. if (typeof tok === 'string') {
  4652. return char === tok;
  4653. }
  4654. else {
  4655. return tok.test(char);
  4656. }
  4657. }
  4658. if (testCurrentChar()) {
  4659. return;
  4660. }
  4661. value = [];
  4662. do {
  4663. e = this.comment();
  4664. if (e) {
  4665. value.push(e);
  4666. continue;
  4667. }
  4668. e = this.entity();
  4669. if (e) {
  4670. value.push(e);
  4671. }
  4672. } while (e);
  4673. done = testCurrentChar();
  4674. if (value.length > 0) {
  4675. value = new (tree.Expression)(value);
  4676. if (done) {
  4677. return value;
  4678. }
  4679. else {
  4680. result.push(value);
  4681. }
  4682. // Preserve space before $parseUntil as it will not
  4683. if (parserInput.prevChar() === ' ') {
  4684. result.push(new tree.Anonymous(' ', index));
  4685. }
  4686. }
  4687. parserInput.save();
  4688. value = parserInput.$parseUntil(tok);
  4689. if (value) {
  4690. if (typeof value === 'string') {
  4691. error("Expected '" + value + "'", 'Parse');
  4692. }
  4693. if (value.length === 1 && value[0] === ' ') {
  4694. parserInput.forget();
  4695. return new tree.Anonymous('', index);
  4696. }
  4697. var item = void 0;
  4698. for (i = 0; i < value.length; i++) {
  4699. item = value[i];
  4700. if (Array.isArray(item)) {
  4701. // Treat actual quotes as normal quoted values
  4702. result.push(new tree.Quoted(item[0], item[1], true, index, fileInfo));
  4703. }
  4704. else {
  4705. if (i === value.length - 1) {
  4706. item = item.trim();
  4707. }
  4708. // Treat like quoted values, but replace vars like unquoted expressions
  4709. var quote = new tree.Quoted('\'', item, true, index, fileInfo);
  4710. quote.variableRegex = /@([\w-]+)/g;
  4711. quote.propRegex = /\$([\w-]+)/g;
  4712. result.push(quote);
  4713. }
  4714. }
  4715. parserInput.forget();
  4716. return new tree.Expression(result, true);
  4717. }
  4718. parserInput.restore();
  4719. },
  4720. //
  4721. // An @import atrule
  4722. //
  4723. // @import "lib";
  4724. //
  4725. // Depending on our environment, importing is done differently:
  4726. // In the browser, it's an XHR request, in Node, it would be a
  4727. // file-system operation. The function used for importing is
  4728. // stored in `import`, which we pass to the Import constructor.
  4729. //
  4730. 'import': function () {
  4731. var path;
  4732. var features;
  4733. var index = parserInput.i;
  4734. var dir = parserInput.$re(/^@import\s+/);
  4735. if (dir) {
  4736. var options = (dir ? this.importOptions() : null) || {};
  4737. if ((path = this.entities.quoted() || this.entities.url())) {
  4738. features = this.mediaFeatures({});
  4739. if (!parserInput.$char(';')) {
  4740. parserInput.i = index;
  4741. error('missing semi-colon or unrecognised media features on import');
  4742. }
  4743. features = features && new (tree.Value)(features);
  4744. return new (tree.Import)(path, features, options, index + currentIndex, fileInfo);
  4745. }
  4746. else {
  4747. parserInput.i = index;
  4748. error('malformed import statement');
  4749. }
  4750. }
  4751. },
  4752. importOptions: function () {
  4753. var o;
  4754. var options = {};
  4755. var optionName;
  4756. var value;
  4757. // list of options, surrounded by parens
  4758. if (!parserInput.$char('(')) {
  4759. return null;
  4760. }
  4761. do {
  4762. o = this.importOption();
  4763. if (o) {
  4764. optionName = o;
  4765. value = true;
  4766. switch (optionName) {
  4767. case 'css':
  4768. optionName = 'less';
  4769. value = false;
  4770. break;
  4771. case 'once':
  4772. optionName = 'multiple';
  4773. value = false;
  4774. break;
  4775. }
  4776. options[optionName] = value;
  4777. if (!parserInput.$char(',')) {
  4778. break;
  4779. }
  4780. }
  4781. } while (o);
  4782. expectChar(')');
  4783. return options;
  4784. },
  4785. importOption: function () {
  4786. var opt = parserInput.$re(/^(less|css|multiple|once|inline|reference|optional)/);
  4787. if (opt) {
  4788. return opt[1];
  4789. }
  4790. },
  4791. mediaFeature: function (syntaxOptions) {
  4792. var entities = this.entities;
  4793. var nodes = [];
  4794. var e;
  4795. var p;
  4796. var rangeP;
  4797. parserInput.save();
  4798. do {
  4799. e = entities.keyword() || entities.variable() || entities.mixinLookup();
  4800. if (e) {
  4801. nodes.push(e);
  4802. }
  4803. else if (parserInput.$char('(')) {
  4804. p = this.property();
  4805. parserInput.save();
  4806. if (!p && syntaxOptions.queryInParens && parserInput.$re(/^[0-9a-z-]*\s*([<>]=|<=|>=|[<>]|=)/)) {
  4807. parserInput.restore();
  4808. p = this.condition();
  4809. parserInput.save();
  4810. rangeP = this.atomicCondition(null, p.rvalue);
  4811. if (!rangeP) {
  4812. parserInput.restore();
  4813. }
  4814. }
  4815. else {
  4816. parserInput.restore();
  4817. e = this.value();
  4818. }
  4819. if (parserInput.$char(')')) {
  4820. if (p && !e) {
  4821. nodes.push(new (tree.Paren)(new (tree.QueryInParens)(p.op, p.lvalue, p.rvalue, rangeP ? rangeP.op : null, rangeP ? rangeP.rvalue : null, p._index)));
  4822. e = p;
  4823. }
  4824. else if (p && e) {
  4825. nodes.push(new (tree.Paren)(new (tree.Declaration)(p, e, null, null, parserInput.i + currentIndex, fileInfo, true)));
  4826. }
  4827. else if (e) {
  4828. nodes.push(new (tree.Paren)(e));
  4829. }
  4830. else {
  4831. error('badly formed media feature definition');
  4832. }
  4833. }
  4834. else {
  4835. error('Missing closing \')\'', 'Parse');
  4836. }
  4837. }
  4838. } while (e);
  4839. parserInput.forget();
  4840. if (nodes.length > 0) {
  4841. return new (tree.Expression)(nodes);
  4842. }
  4843. },
  4844. mediaFeatures: function (syntaxOptions) {
  4845. var entities = this.entities;
  4846. var features = [];
  4847. var e;
  4848. do {
  4849. e = this.mediaFeature(syntaxOptions);
  4850. if (e) {
  4851. features.push(e);
  4852. if (!parserInput.$char(',')) {
  4853. break;
  4854. }
  4855. }
  4856. else {
  4857. e = entities.variable() || entities.mixinLookup();
  4858. if (e) {
  4859. features.push(e);
  4860. if (!parserInput.$char(',')) {
  4861. break;
  4862. }
  4863. }
  4864. }
  4865. } while (e);
  4866. return features.length > 0 ? features : null;
  4867. },
  4868. prepareAndGetNestableAtRule: function (treeType, index, debugInfo, syntaxOptions) {
  4869. var features = this.mediaFeatures(syntaxOptions);
  4870. var rules = this.block();
  4871. if (!rules) {
  4872. error('media definitions require block statements after any features');
  4873. }
  4874. parserInput.forget();
  4875. var atRule = new (treeType)(rules, features, index + currentIndex, fileInfo);
  4876. if (context.dumpLineNumbers) {
  4877. atRule.debugInfo = debugInfo;
  4878. }
  4879. return atRule;
  4880. },
  4881. nestableAtRule: function () {
  4882. var debugInfo;
  4883. var index = parserInput.i;
  4884. if (context.dumpLineNumbers) {
  4885. debugInfo = getDebugInfo(index);
  4886. }
  4887. parserInput.save();
  4888. if (parserInput.$peekChar('@')) {
  4889. if (parserInput.$str('@media')) {
  4890. return this.prepareAndGetNestableAtRule(tree.Media, index, debugInfo, MediaSyntaxOptions);
  4891. }
  4892. if (parserInput.$str('@container')) {
  4893. return this.prepareAndGetNestableAtRule(tree.Container, index, debugInfo, ContainerSyntaxOptions);
  4894. }
  4895. }
  4896. parserInput.restore();
  4897. },
  4898. //
  4899. // A @plugin directive, used to import plugins dynamically.
  4900. //
  4901. // @plugin (args) "lib";
  4902. //
  4903. plugin: function () {
  4904. var path;
  4905. var args;
  4906. var options;
  4907. var index = parserInput.i;
  4908. var dir = parserInput.$re(/^@plugin\s+/);
  4909. if (dir) {
  4910. args = this.pluginArgs();
  4911. if (args) {
  4912. options = {
  4913. pluginArgs: args,
  4914. isPlugin: true
  4915. };
  4916. }
  4917. else {
  4918. options = { isPlugin: true };
  4919. }
  4920. if ((path = this.entities.quoted() || this.entities.url())) {
  4921. if (!parserInput.$char(';')) {
  4922. parserInput.i = index;
  4923. error('missing semi-colon on @plugin');
  4924. }
  4925. return new (tree.Import)(path, null, options, index + currentIndex, fileInfo);
  4926. }
  4927. else {
  4928. parserInput.i = index;
  4929. error('malformed @plugin statement');
  4930. }
  4931. }
  4932. },
  4933. pluginArgs: function () {
  4934. // list of options, surrounded by parens
  4935. parserInput.save();
  4936. if (!parserInput.$char('(')) {
  4937. parserInput.restore();
  4938. return null;
  4939. }
  4940. var args = parserInput.$re(/^\s*([^);]+)\)\s*/);
  4941. if (args[1]) {
  4942. parserInput.forget();
  4943. return args[1].trim();
  4944. }
  4945. else {
  4946. parserInput.restore();
  4947. return null;
  4948. }
  4949. },
  4950. //
  4951. // A CSS AtRule
  4952. //
  4953. // @charset "utf-8";
  4954. //
  4955. atrule: function () {
  4956. var index = parserInput.i;
  4957. var name;
  4958. var value;
  4959. var rules;
  4960. var nonVendorSpecificName;
  4961. var hasIdentifier;
  4962. var hasExpression;
  4963. var hasUnknown;
  4964. var hasBlock = true;
  4965. var isRooted = true;
  4966. if (parserInput.currentChar() !== '@') {
  4967. return;
  4968. }
  4969. value = this['import']() || this.plugin() || this.nestableAtRule();
  4970. if (value) {
  4971. return value;
  4972. }
  4973. parserInput.save();
  4974. name = parserInput.$re(/^@[a-z-]+/);
  4975. if (!name) {
  4976. return;
  4977. }
  4978. nonVendorSpecificName = name;
  4979. if (name.charAt(1) == '-' && name.indexOf('-', 2) > 0) {
  4980. nonVendorSpecificName = "@" + name.slice(name.indexOf('-', 2) + 1);
  4981. }
  4982. switch (nonVendorSpecificName) {
  4983. case '@charset':
  4984. hasIdentifier = true;
  4985. hasBlock = false;
  4986. break;
  4987. case '@namespace':
  4988. hasExpression = true;
  4989. hasBlock = false;
  4990. break;
  4991. case '@keyframes':
  4992. case '@counter-style':
  4993. hasIdentifier = true;
  4994. break;
  4995. case '@document':
  4996. case '@supports':
  4997. hasUnknown = true;
  4998. isRooted = false;
  4999. break;
  5000. default:
  5001. hasUnknown = true;
  5002. break;
  5003. }
  5004. parserInput.commentStore.length = 0;
  5005. if (hasIdentifier) {
  5006. value = this.entity();
  5007. if (!value) {
  5008. error("expected " + name + " identifier");
  5009. }
  5010. }
  5011. else if (hasExpression) {
  5012. value = this.expression();
  5013. if (!value) {
  5014. error("expected " + name + " expression");
  5015. }
  5016. }
  5017. else if (hasUnknown) {
  5018. value = this.permissiveValue(/^[{;]/);
  5019. hasBlock = (parserInput.currentChar() === '{');
  5020. if (!value) {
  5021. if (!hasBlock && parserInput.currentChar() !== ';') {
  5022. error(name + " rule is missing block or ending semi-colon");
  5023. }
  5024. }
  5025. else if (!value.value) {
  5026. value = null;
  5027. }
  5028. }
  5029. if (hasBlock) {
  5030. rules = this.blockRuleset();
  5031. }
  5032. if (rules || (!hasBlock && value && parserInput.$char(';'))) {
  5033. parserInput.forget();
  5034. return new (tree.AtRule)(name, value, rules, index + currentIndex, fileInfo, context.dumpLineNumbers ? getDebugInfo(index) : null, isRooted);
  5035. }
  5036. parserInput.restore('at-rule options not recognised');
  5037. },
  5038. //
  5039. // A Value is a comma-delimited list of Expressions
  5040. //
  5041. // font-family: Baskerville, Georgia, serif;
  5042. //
  5043. // In a Rule, a Value represents everything after the `:`,
  5044. // and before the `;`.
  5045. //
  5046. value: function () {
  5047. var e;
  5048. var expressions = [];
  5049. var index = parserInput.i;
  5050. do {
  5051. e = this.expression();
  5052. if (e) {
  5053. expressions.push(e);
  5054. if (!parserInput.$char(',')) {
  5055. break;
  5056. }
  5057. }
  5058. } while (e);
  5059. if (expressions.length > 0) {
  5060. return new (tree.Value)(expressions, index + currentIndex);
  5061. }
  5062. },
  5063. important: function () {
  5064. if (parserInput.currentChar() === '!') {
  5065. return parserInput.$re(/^! *important/);
  5066. }
  5067. },
  5068. sub: function () {
  5069. var a;
  5070. var e;
  5071. parserInput.save();
  5072. if (parserInput.$char('(')) {
  5073. a = this.addition();
  5074. if (a && parserInput.$char(')')) {
  5075. parserInput.forget();
  5076. e = new (tree.Expression)([a]);
  5077. e.parens = true;
  5078. return e;
  5079. }
  5080. parserInput.restore('Expected \')\'');
  5081. return;
  5082. }
  5083. parserInput.restore();
  5084. },
  5085. multiplication: function () {
  5086. var m;
  5087. var a;
  5088. var op;
  5089. var operation;
  5090. var isSpaced;
  5091. m = this.operand();
  5092. if (m) {
  5093. isSpaced = parserInput.isWhitespace(-1);
  5094. while (true) {
  5095. if (parserInput.peek(/^\/[*/]/)) {
  5096. break;
  5097. }
  5098. parserInput.save();
  5099. op = parserInput.$char('/') || parserInput.$char('*') || parserInput.$str('./');
  5100. if (!op) {
  5101. parserInput.forget();
  5102. break;
  5103. }
  5104. a = this.operand();
  5105. if (!a) {
  5106. parserInput.restore();
  5107. break;
  5108. }
  5109. parserInput.forget();
  5110. m.parensInOp = true;
  5111. a.parensInOp = true;
  5112. operation = new (tree.Operation)(op, [operation || m, a], isSpaced);
  5113. isSpaced = parserInput.isWhitespace(-1);
  5114. }
  5115. return operation || m;
  5116. }
  5117. },
  5118. addition: function () {
  5119. var m;
  5120. var a;
  5121. var op;
  5122. var operation;
  5123. var isSpaced;
  5124. m = this.multiplication();
  5125. if (m) {
  5126. isSpaced = parserInput.isWhitespace(-1);
  5127. while (true) {
  5128. op = parserInput.$re(/^[-+]\s+/) || (!isSpaced && (parserInput.$char('+') || parserInput.$char('-')));
  5129. if (!op) {
  5130. break;
  5131. }
  5132. a = this.multiplication();
  5133. if (!a) {
  5134. break;
  5135. }
  5136. m.parensInOp = true;
  5137. a.parensInOp = true;
  5138. operation = new (tree.Operation)(op, [operation || m, a], isSpaced);
  5139. isSpaced = parserInput.isWhitespace(-1);
  5140. }
  5141. return operation || m;
  5142. }
  5143. },
  5144. conditions: function () {
  5145. var a;
  5146. var b;
  5147. var index = parserInput.i;
  5148. var condition;
  5149. a = this.condition(true);
  5150. if (a) {
  5151. while (true) {
  5152. if (!parserInput.peek(/^,\s*(not\s*)?\(/) || !parserInput.$char(',')) {
  5153. break;
  5154. }
  5155. b = this.condition(true);
  5156. if (!b) {
  5157. break;
  5158. }
  5159. condition = new (tree.Condition)('or', condition || a, b, index + currentIndex);
  5160. }
  5161. return condition || a;
  5162. }
  5163. },
  5164. condition: function (needsParens) {
  5165. var result;
  5166. var logical;
  5167. var next;
  5168. function or() {
  5169. return parserInput.$str('or');
  5170. }
  5171. result = this.conditionAnd(needsParens);
  5172. if (!result) {
  5173. return;
  5174. }
  5175. logical = or();
  5176. if (logical) {
  5177. next = this.condition(needsParens);
  5178. if (next) {
  5179. result = new (tree.Condition)(logical, result, next);
  5180. }
  5181. else {
  5182. return;
  5183. }
  5184. }
  5185. return result;
  5186. },
  5187. conditionAnd: function (needsParens) {
  5188. var result;
  5189. var logical;
  5190. var next;
  5191. var self = this;
  5192. function insideCondition() {
  5193. var cond = self.negatedCondition(needsParens) || self.parenthesisCondition(needsParens);
  5194. if (!cond && !needsParens) {
  5195. return self.atomicCondition(needsParens);
  5196. }
  5197. return cond;
  5198. }
  5199. function and() {
  5200. return parserInput.$str('and');
  5201. }
  5202. result = insideCondition();
  5203. if (!result) {
  5204. return;
  5205. }
  5206. logical = and();
  5207. if (logical) {
  5208. next = this.conditionAnd(needsParens);
  5209. if (next) {
  5210. result = new (tree.Condition)(logical, result, next);
  5211. }
  5212. else {
  5213. return;
  5214. }
  5215. }
  5216. return result;
  5217. },
  5218. negatedCondition: function (needsParens) {
  5219. if (parserInput.$str('not')) {
  5220. var result = this.parenthesisCondition(needsParens);
  5221. if (result) {
  5222. result.negate = !result.negate;
  5223. }
  5224. return result;
  5225. }
  5226. },
  5227. parenthesisCondition: function (needsParens) {
  5228. function tryConditionFollowedByParenthesis(me) {
  5229. var body;
  5230. parserInput.save();
  5231. body = me.condition(needsParens);
  5232. if (!body) {
  5233. parserInput.restore();
  5234. return;
  5235. }
  5236. if (!parserInput.$char(')')) {
  5237. parserInput.restore();
  5238. return;
  5239. }
  5240. parserInput.forget();
  5241. return body;
  5242. }
  5243. var body;
  5244. parserInput.save();
  5245. if (!parserInput.$str('(')) {
  5246. parserInput.restore();
  5247. return;
  5248. }
  5249. body = tryConditionFollowedByParenthesis(this);
  5250. if (body) {
  5251. parserInput.forget();
  5252. return body;
  5253. }
  5254. body = this.atomicCondition(needsParens);
  5255. if (!body) {
  5256. parserInput.restore();
  5257. return;
  5258. }
  5259. if (!parserInput.$char(')')) {
  5260. parserInput.restore("expected ')' got '" + parserInput.currentChar() + "'");
  5261. return;
  5262. }
  5263. parserInput.forget();
  5264. return body;
  5265. },
  5266. atomicCondition: function (needsParens, preparsedCond) {
  5267. var entities = this.entities;
  5268. var index = parserInput.i;
  5269. var a;
  5270. var b;
  5271. var c;
  5272. var op;
  5273. var cond = (function () {
  5274. return this.addition() || entities.keyword() || entities.quoted() || entities.mixinLookup();
  5275. }).bind(this);
  5276. if (preparsedCond) {
  5277. a = preparsedCond;
  5278. }
  5279. else {
  5280. a = cond();
  5281. }
  5282. if (a) {
  5283. if (parserInput.$char('>')) {
  5284. if (parserInput.$char('=')) {
  5285. op = '>=';
  5286. }
  5287. else {
  5288. op = '>';
  5289. }
  5290. }
  5291. else if (parserInput.$char('<')) {
  5292. if (parserInput.$char('=')) {
  5293. op = '<=';
  5294. }
  5295. else {
  5296. op = '<';
  5297. }
  5298. }
  5299. else if (parserInput.$char('=')) {
  5300. if (parserInput.$char('>')) {
  5301. op = '=>';
  5302. }
  5303. else if (parserInput.$char('<')) {
  5304. op = '=<';
  5305. }
  5306. else {
  5307. op = '=';
  5308. }
  5309. }
  5310. if (op) {
  5311. b = cond();
  5312. if (b) {
  5313. c = new (tree.Condition)(op, a, b, index + currentIndex, false);
  5314. }
  5315. else {
  5316. error('expected expression');
  5317. }
  5318. }
  5319. else if (!preparsedCond) {
  5320. c = new (tree.Condition)('=', a, new (tree.Keyword)('true'), index + currentIndex, false);
  5321. }
  5322. return c;
  5323. }
  5324. },
  5325. //
  5326. // An operand is anything that can be part of an operation,
  5327. // such as a Color, or a Variable
  5328. //
  5329. operand: function () {
  5330. var entities = this.entities;
  5331. var negate;
  5332. if (parserInput.peek(/^-[@$(]/)) {
  5333. negate = parserInput.$char('-');
  5334. }
  5335. var o = this.sub() || entities.dimension() ||
  5336. entities.color() || entities.variable() ||
  5337. entities.property() || entities.call() ||
  5338. entities.quoted(true) || entities.colorKeyword() ||
  5339. entities.mixinLookup();
  5340. if (negate) {
  5341. o.parensInOp = true;
  5342. o = new (tree.Negative)(o);
  5343. }
  5344. return o;
  5345. },
  5346. //
  5347. // Expressions either represent mathematical operations,
  5348. // or white-space delimited Entities.
  5349. //
  5350. // 1px solid black
  5351. // @var * 2
  5352. //
  5353. expression: function () {
  5354. var entities = [];
  5355. var e;
  5356. var delim;
  5357. var index = parserInput.i;
  5358. do {
  5359. e = this.comment();
  5360. if (e) {
  5361. entities.push(e);
  5362. continue;
  5363. }
  5364. e = this.addition() || this.entity();
  5365. if (e instanceof tree.Comment) {
  5366. e = null;
  5367. }
  5368. if (e) {
  5369. entities.push(e);
  5370. // operations do not allow keyword "/" dimension (e.g. small/20px) so we support that here
  5371. if (!parserInput.peek(/^\/[/*]/)) {
  5372. delim = parserInput.$char('/');
  5373. if (delim) {
  5374. entities.push(new (tree.Anonymous)(delim, index + currentIndex));
  5375. }
  5376. }
  5377. }
  5378. } while (e);
  5379. if (entities.length > 0) {
  5380. return new (tree.Expression)(entities);
  5381. }
  5382. },
  5383. property: function () {
  5384. var name = parserInput.$re(/^(\*?-?[_a-zA-Z0-9-]+)\s*:/);
  5385. if (name) {
  5386. return name[1];
  5387. }
  5388. },
  5389. ruleProperty: function () {
  5390. var name = [];
  5391. var index = [];
  5392. var s;
  5393. var k;
  5394. parserInput.save();
  5395. var simpleProperty = parserInput.$re(/^([_a-zA-Z0-9-]+)\s*:/);
  5396. if (simpleProperty) {
  5397. name = [new (tree.Keyword)(simpleProperty[1])];
  5398. parserInput.forget();
  5399. return name;
  5400. }
  5401. function match(re) {
  5402. var i = parserInput.i;
  5403. var chunk = parserInput.$re(re);
  5404. if (chunk) {
  5405. index.push(i);
  5406. return name.push(chunk[1]);
  5407. }
  5408. }
  5409. match(/^(\*?)/);
  5410. while (true) {
  5411. if (!match(/^((?:[\w-]+)|(?:[@$]\{[\w-]+\}))/)) {
  5412. break;
  5413. }
  5414. }
  5415. if ((name.length > 1) && match(/^((?:\+_|\+)?)\s*:/)) {
  5416. parserInput.forget();
  5417. // at last, we have the complete match now. move forward,
  5418. // convert name particles to tree objects and return:
  5419. if (name[0] === '') {
  5420. name.shift();
  5421. index.shift();
  5422. }
  5423. for (k = 0; k < name.length; k++) {
  5424. s = name[k];
  5425. name[k] = (s.charAt(0) !== '@' && s.charAt(0) !== '$') ?
  5426. new (tree.Keyword)(s) :
  5427. (s.charAt(0) === '@' ?
  5428. new (tree.Variable)("@" + s.slice(2, -1), index[k] + currentIndex, fileInfo) :
  5429. new (tree.Property)("$" + s.slice(2, -1), index[k] + currentIndex, fileInfo));
  5430. }
  5431. return name;
  5432. }
  5433. parserInput.restore();
  5434. }
  5435. }
  5436. };
  5437. };
  5438. Parser.serializeVars = function (vars) {
  5439. var s = '';
  5440. for (var name_1 in vars) {
  5441. if (Object.hasOwnProperty.call(vars, name_1)) {
  5442. var value = vars[name_1];
  5443. s += ((name_1[0] === '@') ? '' : '@') + name_1 + ": " + value + ((String(value).slice(-1) === ';') ? '' : ';');
  5444. }
  5445. }
  5446. return s;
  5447. };
  5448. var Selector = function (elements, extendList, condition, index, currentFileInfo, visibilityInfo) {
  5449. this.extendList = extendList;
  5450. this.condition = condition;
  5451. this.evaldCondition = !condition;
  5452. this._index = index;
  5453. this._fileInfo = currentFileInfo;
  5454. this.elements = this.getElements(elements);
  5455. this.mixinElements_ = undefined;
  5456. this.copyVisibilityInfo(visibilityInfo);
  5457. this.setParent(this.elements, this);
  5458. };
  5459. Selector.prototype = Object.assign(new Node(), {
  5460. type: 'Selector',
  5461. accept: function (visitor) {
  5462. if (this.elements) {
  5463. this.elements = visitor.visitArray(this.elements);
  5464. }
  5465. if (this.extendList) {
  5466. this.extendList = visitor.visitArray(this.extendList);
  5467. }
  5468. if (this.condition) {
  5469. this.condition = visitor.visit(this.condition);
  5470. }
  5471. },
  5472. createDerived: function (elements, extendList, evaldCondition) {
  5473. elements = this.getElements(elements);
  5474. var newSelector = new Selector(elements, extendList || this.extendList, null, this.getIndex(), this.fileInfo(), this.visibilityInfo());
  5475. newSelector.evaldCondition = (!isNullOrUndefined(evaldCondition)) ? evaldCondition : this.evaldCondition;
  5476. newSelector.mediaEmpty = this.mediaEmpty;
  5477. return newSelector;
  5478. },
  5479. getElements: function (els) {
  5480. if (!els) {
  5481. return [new Element('', '&', false, this._index, this._fileInfo)];
  5482. }
  5483. if (typeof els === 'string') {
  5484. new Parser(this.parse.context, this.parse.importManager, this._fileInfo, this._index).parseNode(els, ['selector'], function (err, result) {
  5485. if (err) {
  5486. throw new LessError({
  5487. index: err.index,
  5488. message: err.message
  5489. }, this.parse.imports, this._fileInfo.filename);
  5490. }
  5491. els = result[0].elements;
  5492. });
  5493. }
  5494. return els;
  5495. },
  5496. createEmptySelectors: function () {
  5497. var el = new Element('', '&', false, this._index, this._fileInfo), sels = [new Selector([el], null, null, this._index, this._fileInfo)];
  5498. sels[0].mediaEmpty = true;
  5499. return sels;
  5500. },
  5501. match: function (other) {
  5502. var elements = this.elements;
  5503. var len = elements.length;
  5504. var olen;
  5505. var i;
  5506. other = other.mixinElements();
  5507. olen = other.length;
  5508. if (olen === 0 || len < olen) {
  5509. return 0;
  5510. }
  5511. else {
  5512. for (i = 0; i < olen; i++) {
  5513. if (elements[i].value !== other[i]) {
  5514. return 0;
  5515. }
  5516. }
  5517. }
  5518. return olen; // return number of matched elements
  5519. },
  5520. mixinElements: function () {
  5521. if (this.mixinElements_) {
  5522. return this.mixinElements_;
  5523. }
  5524. var elements = this.elements.map(function (v) {
  5525. return v.combinator.value + (v.value.value || v.value);
  5526. }).join('').match(/[,&#*.\w-]([\w-]|(\\.))*/g);
  5527. if (elements) {
  5528. if (elements[0] === '&') {
  5529. elements.shift();
  5530. }
  5531. }
  5532. else {
  5533. elements = [];
  5534. }
  5535. return (this.mixinElements_ = elements);
  5536. },
  5537. isJustParentSelector: function () {
  5538. return !this.mediaEmpty &&
  5539. this.elements.length === 1 &&
  5540. this.elements[0].value === '&' &&
  5541. (this.elements[0].combinator.value === ' ' || this.elements[0].combinator.value === '');
  5542. },
  5543. eval: function (context) {
  5544. var evaldCondition = this.condition && this.condition.eval(context);
  5545. var elements = this.elements;
  5546. var extendList = this.extendList;
  5547. elements = elements && elements.map(function (e) { return e.eval(context); });
  5548. extendList = extendList && extendList.map(function (extend) { return extend.eval(context); });
  5549. return this.createDerived(elements, extendList, evaldCondition);
  5550. },
  5551. genCSS: function (context, output) {
  5552. var i, element;
  5553. if ((!context || !context.firstSelector) && this.elements[0].combinator.value === '') {
  5554. output.add(' ', this.fileInfo(), this.getIndex());
  5555. }
  5556. for (i = 0; i < this.elements.length; i++) {
  5557. element = this.elements[i];
  5558. element.genCSS(context, output);
  5559. }
  5560. },
  5561. getIsOutput: function () {
  5562. return this.evaldCondition;
  5563. }
  5564. });
  5565. var Value = function (value) {
  5566. if (!value) {
  5567. throw new Error('Value requires an array argument');
  5568. }
  5569. if (!Array.isArray(value)) {
  5570. this.value = [value];
  5571. }
  5572. else {
  5573. this.value = value;
  5574. }
  5575. };
  5576. Value.prototype = Object.assign(new Node(), {
  5577. type: 'Value',
  5578. accept: function (visitor) {
  5579. if (this.value) {
  5580. this.value = visitor.visitArray(this.value);
  5581. }
  5582. },
  5583. eval: function (context) {
  5584. if (this.value.length === 1) {
  5585. return this.value[0].eval(context);
  5586. }
  5587. else {
  5588. return new Value(this.value.map(function (v) {
  5589. return v.eval(context);
  5590. }));
  5591. }
  5592. },
  5593. genCSS: function (context, output) {
  5594. var i;
  5595. for (i = 0; i < this.value.length; i++) {
  5596. this.value[i].genCSS(context, output);
  5597. if (i + 1 < this.value.length) {
  5598. output.add((context && context.compress) ? ',' : ', ');
  5599. }
  5600. }
  5601. }
  5602. });
  5603. var Keyword = function (value) {
  5604. this.value = value;
  5605. };
  5606. Keyword.prototype = Object.assign(new Node(), {
  5607. type: 'Keyword',
  5608. genCSS: function (context, output) {
  5609. if (this.value === '%') {
  5610. throw { type: 'Syntax', message: 'Invalid % without number' };
  5611. }
  5612. output.add(this.value);
  5613. }
  5614. });
  5615. Keyword.True = new Keyword('true');
  5616. Keyword.False = new Keyword('false');
  5617. var Anonymous = function (value, index, currentFileInfo, mapLines, rulesetLike, visibilityInfo) {
  5618. this.value = value;
  5619. this._index = index;
  5620. this._fileInfo = currentFileInfo;
  5621. this.mapLines = mapLines;
  5622. this.rulesetLike = (typeof rulesetLike === 'undefined') ? false : rulesetLike;
  5623. this.allowRoot = true;
  5624. this.copyVisibilityInfo(visibilityInfo);
  5625. };
  5626. Anonymous.prototype = Object.assign(new Node(), {
  5627. type: 'Anonymous',
  5628. eval: function () {
  5629. return new Anonymous(this.value, this._index, this._fileInfo, this.mapLines, this.rulesetLike, this.visibilityInfo());
  5630. },
  5631. compare: function (other) {
  5632. return other.toCSS && this.toCSS() === other.toCSS() ? 0 : undefined;
  5633. },
  5634. isRulesetLike: function () {
  5635. return this.rulesetLike;
  5636. },
  5637. genCSS: function (context, output) {
  5638. this.nodeVisible = Boolean(this.value);
  5639. if (this.nodeVisible) {
  5640. output.add(this.value, this._fileInfo, this._index, this.mapLines);
  5641. }
  5642. }
  5643. });
  5644. var MATH$1 = Math$1;
  5645. function evalName(context, name) {
  5646. var value = '';
  5647. var i;
  5648. var n = name.length;
  5649. var output = { add: function (s) { value += s; } };
  5650. for (i = 0; i < n; i++) {
  5651. name[i].eval(context).genCSS(context, output);
  5652. }
  5653. return value;
  5654. }
  5655. var Declaration = function (name, value, important, merge, index, currentFileInfo, inline, variable) {
  5656. this.name = name;
  5657. this.value = (value instanceof Node) ? value : new Value([value ? new Anonymous(value) : null]);
  5658. this.important = important ? " " + important.trim() : '';
  5659. this.merge = merge;
  5660. this._index = index;
  5661. this._fileInfo = currentFileInfo;
  5662. this.inline = inline || false;
  5663. this.variable = (variable !== undefined) ? variable
  5664. : (name.charAt && (name.charAt(0) === '@'));
  5665. this.allowRoot = true;
  5666. this.setParent(this.value, this);
  5667. };
  5668. Declaration.prototype = Object.assign(new Node(), {
  5669. type: 'Declaration',
  5670. genCSS: function (context, output) {
  5671. output.add(this.name + (context.compress ? ':' : ': '), this.fileInfo(), this.getIndex());
  5672. try {
  5673. this.value.genCSS(context, output);
  5674. }
  5675. catch (e) {
  5676. e.index = this._index;
  5677. e.filename = this._fileInfo.filename;
  5678. throw e;
  5679. }
  5680. output.add(this.important + ((this.inline || (context.lastRule && context.compress)) ? '' : ';'), this._fileInfo, this._index);
  5681. },
  5682. eval: function (context) {
  5683. var mathBypass = false, prevMath, name = this.name, evaldValue, variable = this.variable;
  5684. if (typeof name !== 'string') {
  5685. // expand 'primitive' name directly to get
  5686. // things faster (~10% for benchmark.less):
  5687. name = (name.length === 1) && (name[0] instanceof Keyword) ?
  5688. name[0].value : evalName(context, name);
  5689. variable = false; // never treat expanded interpolation as new variable name
  5690. }
  5691. // @todo remove when parens-division is default
  5692. if (name === 'font' && context.math === MATH$1.ALWAYS) {
  5693. mathBypass = true;
  5694. prevMath = context.math;
  5695. context.math = MATH$1.PARENS_DIVISION;
  5696. }
  5697. try {
  5698. context.importantScope.push({});
  5699. evaldValue = this.value.eval(context);
  5700. if (!this.variable && evaldValue.type === 'DetachedRuleset') {
  5701. throw { message: 'Rulesets cannot be evaluated on a property.',
  5702. index: this.getIndex(), filename: this.fileInfo().filename };
  5703. }
  5704. var important = this.important;
  5705. var importantResult = context.importantScope.pop();
  5706. if (!important && importantResult.important) {
  5707. important = importantResult.important;
  5708. }
  5709. return new Declaration(name, evaldValue, important, this.merge, this.getIndex(), this.fileInfo(), this.inline, variable);
  5710. }
  5711. catch (e) {
  5712. if (typeof e.index !== 'number') {
  5713. e.index = this.getIndex();
  5714. e.filename = this.fileInfo().filename;
  5715. }
  5716. throw e;
  5717. }
  5718. finally {
  5719. if (mathBypass) {
  5720. context.math = prevMath;
  5721. }
  5722. }
  5723. },
  5724. makeImportant: function () {
  5725. return new Declaration(this.name, this.value, '!important', this.merge, this.getIndex(), this.fileInfo(), this.inline);
  5726. }
  5727. });
  5728. function asComment(ctx) {
  5729. return "/* line " + ctx.debugInfo.lineNumber + ", " + ctx.debugInfo.fileName + " */\n";
  5730. }
  5731. function asMediaQuery(ctx) {
  5732. var filenameWithProtocol = ctx.debugInfo.fileName;
  5733. if (!/^[a-z]+:\/\//i.test(filenameWithProtocol)) {
  5734. filenameWithProtocol = "file://" + filenameWithProtocol;
  5735. }
  5736. return "@media -sass-debug-info{filename{font-family:" + filenameWithProtocol.replace(/([.:/\\])/g, function (a) {
  5737. if (a == '\\') {
  5738. a = '/';
  5739. }
  5740. return "\\" + a;
  5741. }) + "}line{font-family:\\00003" + ctx.debugInfo.lineNumber + "}}\n";
  5742. }
  5743. function debugInfo(context, ctx, lineSeparator) {
  5744. var result = '';
  5745. if (context.dumpLineNumbers && !context.compress) {
  5746. switch (context.dumpLineNumbers) {
  5747. case 'comments':
  5748. result = asComment(ctx);
  5749. break;
  5750. case 'mediaquery':
  5751. result = asMediaQuery(ctx);
  5752. break;
  5753. case 'all':
  5754. result = asComment(ctx) + (lineSeparator || '') + asMediaQuery(ctx);
  5755. break;
  5756. }
  5757. }
  5758. return result;
  5759. }
  5760. var Comment = function (value, isLineComment, index, currentFileInfo) {
  5761. this.value = value;
  5762. this.isLineComment = isLineComment;
  5763. this._index = index;
  5764. this._fileInfo = currentFileInfo;
  5765. this.allowRoot = true;
  5766. };
  5767. Comment.prototype = Object.assign(new Node(), {
  5768. type: 'Comment',
  5769. genCSS: function (context, output) {
  5770. if (this.debugInfo) {
  5771. output.add(debugInfo(context, this), this.fileInfo(), this.getIndex());
  5772. }
  5773. output.add(this.value);
  5774. },
  5775. isSilent: function (context) {
  5776. var isCompressed = context.compress && this.value[2] !== '!';
  5777. return this.isLineComment || isCompressed;
  5778. }
  5779. });
  5780. var defaultFunc = {
  5781. eval: function () {
  5782. var v = this.value_;
  5783. var e = this.error_;
  5784. if (e) {
  5785. throw e;
  5786. }
  5787. if (!isNullOrUndefined(v)) {
  5788. return v ? Keyword.True : Keyword.False;
  5789. }
  5790. },
  5791. value: function (v) {
  5792. this.value_ = v;
  5793. },
  5794. error: function (e) {
  5795. this.error_ = e;
  5796. },
  5797. reset: function () {
  5798. this.value_ = this.error_ = null;
  5799. }
  5800. };
  5801. var Ruleset = function (selectors, rules, strictImports, visibilityInfo) {
  5802. this.selectors = selectors;
  5803. this.rules = rules;
  5804. this._lookups = {};
  5805. this._variables = null;
  5806. this._properties = null;
  5807. this.strictImports = strictImports;
  5808. this.copyVisibilityInfo(visibilityInfo);
  5809. this.allowRoot = true;
  5810. this.setParent(this.selectors, this);
  5811. this.setParent(this.rules, this);
  5812. };
  5813. Ruleset.prototype = Object.assign(new Node(), {
  5814. type: 'Ruleset',
  5815. isRuleset: true,
  5816. isRulesetLike: function () { return true; },
  5817. accept: function (visitor) {
  5818. if (this.paths) {
  5819. this.paths = visitor.visitArray(this.paths, true);
  5820. }
  5821. else if (this.selectors) {
  5822. this.selectors = visitor.visitArray(this.selectors);
  5823. }
  5824. if (this.rules && this.rules.length) {
  5825. this.rules = visitor.visitArray(this.rules);
  5826. }
  5827. },
  5828. eval: function (context) {
  5829. var selectors;
  5830. var selCnt;
  5831. var selector;
  5832. var i;
  5833. var hasVariable;
  5834. var hasOnePassingSelector = false;
  5835. if (this.selectors && (selCnt = this.selectors.length)) {
  5836. selectors = new Array(selCnt);
  5837. defaultFunc.error({
  5838. type: 'Syntax',
  5839. message: 'it is currently only allowed in parametric mixin guards,'
  5840. });
  5841. for (i = 0; i < selCnt; i++) {
  5842. selector = this.selectors[i].eval(context);
  5843. for (var j = 0; j < selector.elements.length; j++) {
  5844. if (selector.elements[j].isVariable) {
  5845. hasVariable = true;
  5846. break;
  5847. }
  5848. }
  5849. selectors[i] = selector;
  5850. if (selector.evaldCondition) {
  5851. hasOnePassingSelector = true;
  5852. }
  5853. }
  5854. if (hasVariable) {
  5855. var toParseSelectors = new Array(selCnt);
  5856. for (i = 0; i < selCnt; i++) {
  5857. selector = selectors[i];
  5858. toParseSelectors[i] = selector.toCSS(context);
  5859. }
  5860. var startingIndex = selectors[0].getIndex();
  5861. var selectorFileInfo = selectors[0].fileInfo();
  5862. new Parser(context, this.parse.importManager, selectorFileInfo, startingIndex).parseNode(toParseSelectors.join(','), ['selectors'], function (err, result) {
  5863. if (result) {
  5864. selectors = flattenArray(result);
  5865. }
  5866. });
  5867. }
  5868. defaultFunc.reset();
  5869. }
  5870. else {
  5871. hasOnePassingSelector = true;
  5872. }
  5873. var rules = this.rules ? copyArray(this.rules) : null;
  5874. var ruleset = new Ruleset(selectors, rules, this.strictImports, this.visibilityInfo());
  5875. var rule;
  5876. var subRule;
  5877. ruleset.originalRuleset = this;
  5878. ruleset.root = this.root;
  5879. ruleset.firstRoot = this.firstRoot;
  5880. ruleset.allowImports = this.allowImports;
  5881. if (this.debugInfo) {
  5882. ruleset.debugInfo = this.debugInfo;
  5883. }
  5884. if (!hasOnePassingSelector) {
  5885. rules.length = 0;
  5886. }
  5887. // inherit a function registry from the frames stack when possible;
  5888. // otherwise from the global registry
  5889. ruleset.functionRegistry = (function (frames) {
  5890. var i = 0;
  5891. var n = frames.length;
  5892. var found;
  5893. for (; i !== n; ++i) {
  5894. found = frames[i].functionRegistry;
  5895. if (found) {
  5896. return found;
  5897. }
  5898. }
  5899. return functionRegistry;
  5900. }(context.frames)).inherit();
  5901. // push the current ruleset to the frames stack
  5902. var ctxFrames = context.frames;
  5903. ctxFrames.unshift(ruleset);
  5904. // currrent selectors
  5905. var ctxSelectors = context.selectors;
  5906. if (!ctxSelectors) {
  5907. context.selectors = ctxSelectors = [];
  5908. }
  5909. ctxSelectors.unshift(this.selectors);
  5910. // Evaluate imports
  5911. if (ruleset.root || ruleset.allowImports || !ruleset.strictImports) {
  5912. ruleset.evalImports(context);
  5913. }
  5914. // Store the frames around mixin definitions,
  5915. // so they can be evaluated like closures when the time comes.
  5916. var rsRules = ruleset.rules;
  5917. for (i = 0; (rule = rsRules[i]); i++) {
  5918. if (rule.evalFirst) {
  5919. rsRules[i] = rule.eval(context);
  5920. }
  5921. }
  5922. var mediaBlockCount = (context.mediaBlocks && context.mediaBlocks.length) || 0;
  5923. // Evaluate mixin calls.
  5924. for (i = 0; (rule = rsRules[i]); i++) {
  5925. if (rule.type === 'MixinCall') {
  5926. /* jshint loopfunc:true */
  5927. rules = rule.eval(context).filter(function (r) {
  5928. if ((r instanceof Declaration) && r.variable) {
  5929. // do not pollute the scope if the variable is
  5930. // already there. consider returning false here
  5931. // but we need a way to "return" variable from mixins
  5932. return !(ruleset.variable(r.name));
  5933. }
  5934. return true;
  5935. });
  5936. rsRules.splice.apply(rsRules, [i, 1].concat(rules));
  5937. i += rules.length - 1;
  5938. ruleset.resetCache();
  5939. }
  5940. else if (rule.type === 'VariableCall') {
  5941. /* jshint loopfunc:true */
  5942. rules = rule.eval(context).rules.filter(function (r) {
  5943. if ((r instanceof Declaration) && r.variable) {
  5944. // do not pollute the scope at all
  5945. return false;
  5946. }
  5947. return true;
  5948. });
  5949. rsRules.splice.apply(rsRules, [i, 1].concat(rules));
  5950. i += rules.length - 1;
  5951. ruleset.resetCache();
  5952. }
  5953. }
  5954. // Evaluate everything else
  5955. for (i = 0; (rule = rsRules[i]); i++) {
  5956. if (!rule.evalFirst) {
  5957. rsRules[i] = rule = rule.eval ? rule.eval(context) : rule;
  5958. }
  5959. }
  5960. // Evaluate everything else
  5961. for (i = 0; (rule = rsRules[i]); i++) {
  5962. // for rulesets, check if it is a css guard and can be removed
  5963. if (rule instanceof Ruleset && rule.selectors && rule.selectors.length === 1) {
  5964. // check if it can be folded in (e.g. & where)
  5965. if (rule.selectors[0] && rule.selectors[0].isJustParentSelector()) {
  5966. rsRules.splice(i--, 1);
  5967. for (var j = 0; (subRule = rule.rules[j]); j++) {
  5968. if (subRule instanceof Node) {
  5969. subRule.copyVisibilityInfo(rule.visibilityInfo());
  5970. if (!(subRule instanceof Declaration) || !subRule.variable) {
  5971. rsRules.splice(++i, 0, subRule);
  5972. }
  5973. }
  5974. }
  5975. }
  5976. }
  5977. }
  5978. // Pop the stack
  5979. ctxFrames.shift();
  5980. ctxSelectors.shift();
  5981. if (context.mediaBlocks) {
  5982. for (i = mediaBlockCount; i < context.mediaBlocks.length; i++) {
  5983. context.mediaBlocks[i].bubbleSelectors(selectors);
  5984. }
  5985. }
  5986. return ruleset;
  5987. },
  5988. evalImports: function (context) {
  5989. var rules = this.rules;
  5990. var i;
  5991. var importRules;
  5992. if (!rules) {
  5993. return;
  5994. }
  5995. for (i = 0; i < rules.length; i++) {
  5996. if (rules[i].type === 'Import') {
  5997. importRules = rules[i].eval(context);
  5998. if (importRules && (importRules.length || importRules.length === 0)) {
  5999. rules.splice.apply(rules, [i, 1].concat(importRules));
  6000. i += importRules.length - 1;
  6001. }
  6002. else {
  6003. rules.splice(i, 1, importRules);
  6004. }
  6005. this.resetCache();
  6006. }
  6007. }
  6008. },
  6009. makeImportant: function () {
  6010. var result = new Ruleset(this.selectors, this.rules.map(function (r) {
  6011. if (r.makeImportant) {
  6012. return r.makeImportant();
  6013. }
  6014. else {
  6015. return r;
  6016. }
  6017. }), this.strictImports, this.visibilityInfo());
  6018. return result;
  6019. },
  6020. matchArgs: function (args) {
  6021. return !args || args.length === 0;
  6022. },
  6023. // lets you call a css selector with a guard
  6024. matchCondition: function (args, context) {
  6025. var lastSelector = this.selectors[this.selectors.length - 1];
  6026. if (!lastSelector.evaldCondition) {
  6027. return false;
  6028. }
  6029. if (lastSelector.condition &&
  6030. !lastSelector.condition.eval(new contexts.Eval(context, context.frames))) {
  6031. return false;
  6032. }
  6033. return true;
  6034. },
  6035. resetCache: function () {
  6036. this._rulesets = null;
  6037. this._variables = null;
  6038. this._properties = null;
  6039. this._lookups = {};
  6040. },
  6041. variables: function () {
  6042. if (!this._variables) {
  6043. this._variables = !this.rules ? {} : this.rules.reduce(function (hash, r) {
  6044. if (r instanceof Declaration && r.variable === true) {
  6045. hash[r.name] = r;
  6046. }
  6047. // when evaluating variables in an import statement, imports have not been eval'd
  6048. // so we need to go inside import statements.
  6049. // guard against root being a string (in the case of inlined less)
  6050. if (r.type === 'Import' && r.root && r.root.variables) {
  6051. var vars = r.root.variables();
  6052. for (var name_1 in vars) {
  6053. // eslint-disable-next-line no-prototype-builtins
  6054. if (vars.hasOwnProperty(name_1)) {
  6055. hash[name_1] = r.root.variable(name_1);
  6056. }
  6057. }
  6058. }
  6059. return hash;
  6060. }, {});
  6061. }
  6062. return this._variables;
  6063. },
  6064. properties: function () {
  6065. if (!this._properties) {
  6066. this._properties = !this.rules ? {} : this.rules.reduce(function (hash, r) {
  6067. if (r instanceof Declaration && r.variable !== true) {
  6068. var name_2 = (r.name.length === 1) && (r.name[0] instanceof Keyword) ?
  6069. r.name[0].value : r.name;
  6070. // Properties don't overwrite as they can merge
  6071. if (!hash["$" + name_2]) {
  6072. hash["$" + name_2] = [r];
  6073. }
  6074. else {
  6075. hash["$" + name_2].push(r);
  6076. }
  6077. }
  6078. return hash;
  6079. }, {});
  6080. }
  6081. return this._properties;
  6082. },
  6083. variable: function (name) {
  6084. var decl = this.variables()[name];
  6085. if (decl) {
  6086. return this.parseValue(decl);
  6087. }
  6088. },
  6089. property: function (name) {
  6090. var decl = this.properties()[name];
  6091. if (decl) {
  6092. return this.parseValue(decl);
  6093. }
  6094. },
  6095. lastDeclaration: function () {
  6096. for (var i_1 = this.rules.length; i_1 > 0; i_1--) {
  6097. var decl = this.rules[i_1 - 1];
  6098. if (decl instanceof Declaration) {
  6099. return this.parseValue(decl);
  6100. }
  6101. }
  6102. },
  6103. parseValue: function (toParse) {
  6104. var self = this;
  6105. function transformDeclaration(decl) {
  6106. if (decl.value instanceof Anonymous && !decl.parsed) {
  6107. if (typeof decl.value.value === 'string') {
  6108. new Parser(this.parse.context, this.parse.importManager, decl.fileInfo(), decl.value.getIndex()).parseNode(decl.value.value, ['value', 'important'], function (err, result) {
  6109. if (err) {
  6110. decl.parsed = true;
  6111. }
  6112. if (result) {
  6113. decl.value = result[0];
  6114. decl.important = result[1] || '';
  6115. decl.parsed = true;
  6116. }
  6117. });
  6118. }
  6119. else {
  6120. decl.parsed = true;
  6121. }
  6122. return decl;
  6123. }
  6124. else {
  6125. return decl;
  6126. }
  6127. }
  6128. if (!Array.isArray(toParse)) {
  6129. return transformDeclaration.call(self, toParse);
  6130. }
  6131. else {
  6132. var nodes_1 = [];
  6133. toParse.forEach(function (n) {
  6134. nodes_1.push(transformDeclaration.call(self, n));
  6135. });
  6136. return nodes_1;
  6137. }
  6138. },
  6139. rulesets: function () {
  6140. if (!this.rules) {
  6141. return [];
  6142. }
  6143. var filtRules = [];
  6144. var rules = this.rules;
  6145. var i;
  6146. var rule;
  6147. for (i = 0; (rule = rules[i]); i++) {
  6148. if (rule.isRuleset) {
  6149. filtRules.push(rule);
  6150. }
  6151. }
  6152. return filtRules;
  6153. },
  6154. prependRule: function (rule) {
  6155. var rules = this.rules;
  6156. if (rules) {
  6157. rules.unshift(rule);
  6158. }
  6159. else {
  6160. this.rules = [rule];
  6161. }
  6162. this.setParent(rule, this);
  6163. },
  6164. find: function (selector, self, filter) {
  6165. self = self || this;
  6166. var rules = [];
  6167. var match;
  6168. var foundMixins;
  6169. var key = selector.toCSS();
  6170. if (key in this._lookups) {
  6171. return this._lookups[key];
  6172. }
  6173. this.rulesets().forEach(function (rule) {
  6174. if (rule !== self) {
  6175. for (var j = 0; j < rule.selectors.length; j++) {
  6176. match = selector.match(rule.selectors[j]);
  6177. if (match) {
  6178. if (selector.elements.length > match) {
  6179. if (!filter || filter(rule)) {
  6180. foundMixins = rule.find(new Selector(selector.elements.slice(match)), self, filter);
  6181. for (var i_2 = 0; i_2 < foundMixins.length; ++i_2) {
  6182. foundMixins[i_2].path.push(rule);
  6183. }
  6184. Array.prototype.push.apply(rules, foundMixins);
  6185. }
  6186. }
  6187. else {
  6188. rules.push({ rule: rule, path: [] });
  6189. }
  6190. break;
  6191. }
  6192. }
  6193. }
  6194. });
  6195. this._lookups[key] = rules;
  6196. return rules;
  6197. },
  6198. genCSS: function (context, output) {
  6199. var i;
  6200. var j;
  6201. var charsetRuleNodes = [];
  6202. var ruleNodes = [];
  6203. var // Line number debugging
  6204. debugInfo$1;
  6205. var rule;
  6206. var path;
  6207. context.tabLevel = (context.tabLevel || 0);
  6208. if (!this.root) {
  6209. context.tabLevel++;
  6210. }
  6211. var tabRuleStr = context.compress ? '' : Array(context.tabLevel + 1).join(' ');
  6212. var tabSetStr = context.compress ? '' : Array(context.tabLevel).join(' ');
  6213. var sep;
  6214. var charsetNodeIndex = 0;
  6215. var importNodeIndex = 0;
  6216. for (i = 0; (rule = this.rules[i]); i++) {
  6217. if (rule instanceof Comment) {
  6218. if (importNodeIndex === i) {
  6219. importNodeIndex++;
  6220. }
  6221. ruleNodes.push(rule);
  6222. }
  6223. else if (rule.isCharset && rule.isCharset()) {
  6224. ruleNodes.splice(charsetNodeIndex, 0, rule);
  6225. charsetNodeIndex++;
  6226. importNodeIndex++;
  6227. }
  6228. else if (rule.type === 'Import') {
  6229. ruleNodes.splice(importNodeIndex, 0, rule);
  6230. importNodeIndex++;
  6231. }
  6232. else {
  6233. ruleNodes.push(rule);
  6234. }
  6235. }
  6236. ruleNodes = charsetRuleNodes.concat(ruleNodes);
  6237. // If this is the root node, we don't render
  6238. // a selector, or {}.
  6239. if (!this.root) {
  6240. debugInfo$1 = debugInfo(context, this, tabSetStr);
  6241. if (debugInfo$1) {
  6242. output.add(debugInfo$1);
  6243. output.add(tabSetStr);
  6244. }
  6245. var paths = this.paths;
  6246. var pathCnt = paths.length;
  6247. var pathSubCnt = void 0;
  6248. sep = context.compress ? ',' : (",\n" + tabSetStr);
  6249. for (i = 0; i < pathCnt; i++) {
  6250. path = paths[i];
  6251. if (!(pathSubCnt = path.length)) {
  6252. continue;
  6253. }
  6254. if (i > 0) {
  6255. output.add(sep);
  6256. }
  6257. context.firstSelector = true;
  6258. path[0].genCSS(context, output);
  6259. context.firstSelector = false;
  6260. for (j = 1; j < pathSubCnt; j++) {
  6261. path[j].genCSS(context, output);
  6262. }
  6263. }
  6264. output.add((context.compress ? '{' : ' {\n') + tabRuleStr);
  6265. }
  6266. // Compile rules and rulesets
  6267. for (i = 0; (rule = ruleNodes[i]); i++) {
  6268. if (i + 1 === ruleNodes.length) {
  6269. context.lastRule = true;
  6270. }
  6271. var currentLastRule = context.lastRule;
  6272. if (rule.isRulesetLike(rule)) {
  6273. context.lastRule = false;
  6274. }
  6275. if (rule.genCSS) {
  6276. rule.genCSS(context, output);
  6277. }
  6278. else if (rule.value) {
  6279. output.add(rule.value.toString());
  6280. }
  6281. context.lastRule = currentLastRule;
  6282. if (!context.lastRule && rule.isVisible()) {
  6283. output.add(context.compress ? '' : ("\n" + tabRuleStr));
  6284. }
  6285. else {
  6286. context.lastRule = false;
  6287. }
  6288. }
  6289. if (!this.root) {
  6290. output.add((context.compress ? '}' : "\n" + tabSetStr + "}"));
  6291. context.tabLevel--;
  6292. }
  6293. if (!output.isEmpty() && !context.compress && this.firstRoot) {
  6294. output.add('\n');
  6295. }
  6296. },
  6297. joinSelectors: function (paths, context, selectors) {
  6298. for (var s = 0; s < selectors.length; s++) {
  6299. this.joinSelector(paths, context, selectors[s]);
  6300. }
  6301. },
  6302. joinSelector: function (paths, context, selector) {
  6303. function createParenthesis(elementsToPak, originalElement) {
  6304. var replacementParen, j;
  6305. if (elementsToPak.length === 0) {
  6306. replacementParen = new Paren(elementsToPak[0]);
  6307. }
  6308. else {
  6309. var insideParent = new Array(elementsToPak.length);
  6310. for (j = 0; j < elementsToPak.length; j++) {
  6311. insideParent[j] = new Element(null, elementsToPak[j], originalElement.isVariable, originalElement._index, originalElement._fileInfo);
  6312. }
  6313. replacementParen = new Paren(new Selector(insideParent));
  6314. }
  6315. return replacementParen;
  6316. }
  6317. function createSelector(containedElement, originalElement) {
  6318. var element, selector;
  6319. element = new Element(null, containedElement, originalElement.isVariable, originalElement._index, originalElement._fileInfo);
  6320. selector = new Selector([element]);
  6321. return selector;
  6322. }
  6323. // joins selector path from `beginningPath` with selector path in `addPath`
  6324. // `replacedElement` contains element that is being replaced by `addPath`
  6325. // returns concatenated path
  6326. function addReplacementIntoPath(beginningPath, addPath, replacedElement, originalSelector) {
  6327. var newSelectorPath, lastSelector, newJoinedSelector;
  6328. // our new selector path
  6329. newSelectorPath = [];
  6330. // construct the joined selector - if & is the first thing this will be empty,
  6331. // if not newJoinedSelector will be the last set of elements in the selector
  6332. if (beginningPath.length > 0) {
  6333. newSelectorPath = copyArray(beginningPath);
  6334. lastSelector = newSelectorPath.pop();
  6335. newJoinedSelector = originalSelector.createDerived(copyArray(lastSelector.elements));
  6336. }
  6337. else {
  6338. newJoinedSelector = originalSelector.createDerived([]);
  6339. }
  6340. if (addPath.length > 0) {
  6341. // /deep/ is a CSS4 selector - (removed, so should deprecate)
  6342. // that is valid without anything in front of it
  6343. // so if the & does not have a combinator that is "" or " " then
  6344. // and there is a combinator on the parent, then grab that.
  6345. // this also allows + a { & .b { .a & { ... though not sure why you would want to do that
  6346. var combinator = replacedElement.combinator;
  6347. var parentEl = addPath[0].elements[0];
  6348. if (combinator.emptyOrWhitespace && !parentEl.combinator.emptyOrWhitespace) {
  6349. combinator = parentEl.combinator;
  6350. }
  6351. // join the elements so far with the first part of the parent
  6352. newJoinedSelector.elements.push(new Element(combinator, parentEl.value, replacedElement.isVariable, replacedElement._index, replacedElement._fileInfo));
  6353. newJoinedSelector.elements = newJoinedSelector.elements.concat(addPath[0].elements.slice(1));
  6354. }
  6355. // now add the joined selector - but only if it is not empty
  6356. if (newJoinedSelector.elements.length !== 0) {
  6357. newSelectorPath.push(newJoinedSelector);
  6358. }
  6359. // put together the parent selectors after the join (e.g. the rest of the parent)
  6360. if (addPath.length > 1) {
  6361. var restOfPath = addPath.slice(1);
  6362. restOfPath = restOfPath.map(function (selector) {
  6363. return selector.createDerived(selector.elements, []);
  6364. });
  6365. newSelectorPath = newSelectorPath.concat(restOfPath);
  6366. }
  6367. return newSelectorPath;
  6368. }
  6369. // joins selector path from `beginningPath` with every selector path in `addPaths` array
  6370. // `replacedElement` contains element that is being replaced by `addPath`
  6371. // returns array with all concatenated paths
  6372. function addAllReplacementsIntoPath(beginningPath, addPaths, replacedElement, originalSelector, result) {
  6373. var j;
  6374. for (j = 0; j < beginningPath.length; j++) {
  6375. var newSelectorPath = addReplacementIntoPath(beginningPath[j], addPaths, replacedElement, originalSelector);
  6376. result.push(newSelectorPath);
  6377. }
  6378. return result;
  6379. }
  6380. function mergeElementsOnToSelectors(elements, selectors) {
  6381. var i, sel;
  6382. if (elements.length === 0) {
  6383. return;
  6384. }
  6385. if (selectors.length === 0) {
  6386. selectors.push([new Selector(elements)]);
  6387. return;
  6388. }
  6389. for (i = 0; (sel = selectors[i]); i++) {
  6390. // if the previous thing in sel is a parent this needs to join on to it
  6391. if (sel.length > 0) {
  6392. sel[sel.length - 1] = sel[sel.length - 1].createDerived(sel[sel.length - 1].elements.concat(elements));
  6393. }
  6394. else {
  6395. sel.push(new Selector(elements));
  6396. }
  6397. }
  6398. }
  6399. // replace all parent selectors inside `inSelector` by content of `context` array
  6400. // resulting selectors are returned inside `paths` array
  6401. // returns true if `inSelector` contained at least one parent selector
  6402. function replaceParentSelector(paths, context, inSelector) {
  6403. // The paths are [[Selector]]
  6404. // The first list is a list of comma separated selectors
  6405. // The inner list is a list of inheritance separated selectors
  6406. // e.g.
  6407. // .a, .b {
  6408. // .c {
  6409. // }
  6410. // }
  6411. // == [[.a] [.c]] [[.b] [.c]]
  6412. //
  6413. var i, j, k, currentElements, newSelectors, selectorsMultiplied, sel, el, hadParentSelector = false, length, lastSelector;
  6414. function findNestedSelector(element) {
  6415. var maybeSelector;
  6416. if (!(element.value instanceof Paren)) {
  6417. return null;
  6418. }
  6419. maybeSelector = element.value.value;
  6420. if (!(maybeSelector instanceof Selector)) {
  6421. return null;
  6422. }
  6423. return maybeSelector;
  6424. }
  6425. // the elements from the current selector so far
  6426. currentElements = [];
  6427. // the current list of new selectors to add to the path.
  6428. // We will build it up. We initiate it with one empty selector as we "multiply" the new selectors
  6429. // by the parents
  6430. newSelectors = [
  6431. []
  6432. ];
  6433. for (i = 0; (el = inSelector.elements[i]); i++) {
  6434. // non parent reference elements just get added
  6435. if (el.value !== '&') {
  6436. var nestedSelector = findNestedSelector(el);
  6437. if (nestedSelector !== null) {
  6438. // merge the current list of non parent selector elements
  6439. // on to the current list of selectors to add
  6440. mergeElementsOnToSelectors(currentElements, newSelectors);
  6441. var nestedPaths = [];
  6442. var replaced = void 0;
  6443. var replacedNewSelectors = [];
  6444. replaced = replaceParentSelector(nestedPaths, context, nestedSelector);
  6445. hadParentSelector = hadParentSelector || replaced;
  6446. // the nestedPaths array should have only one member - replaceParentSelector does not multiply selectors
  6447. for (k = 0; k < nestedPaths.length; k++) {
  6448. var replacementSelector = createSelector(createParenthesis(nestedPaths[k], el), el);
  6449. addAllReplacementsIntoPath(newSelectors, [replacementSelector], el, inSelector, replacedNewSelectors);
  6450. }
  6451. newSelectors = replacedNewSelectors;
  6452. currentElements = [];
  6453. }
  6454. else {
  6455. currentElements.push(el);
  6456. }
  6457. }
  6458. else {
  6459. hadParentSelector = true;
  6460. // the new list of selectors to add
  6461. selectorsMultiplied = [];
  6462. // merge the current list of non parent selector elements
  6463. // on to the current list of selectors to add
  6464. mergeElementsOnToSelectors(currentElements, newSelectors);
  6465. // loop through our current selectors
  6466. for (j = 0; j < newSelectors.length; j++) {
  6467. sel = newSelectors[j];
  6468. // if we don't have any parent paths, the & might be in a mixin so that it can be used
  6469. // whether there are parents or not
  6470. if (context.length === 0) {
  6471. // the combinator used on el should now be applied to the next element instead so that
  6472. // it is not lost
  6473. if (sel.length > 0) {
  6474. sel[0].elements.push(new Element(el.combinator, '', el.isVariable, el._index, el._fileInfo));
  6475. }
  6476. selectorsMultiplied.push(sel);
  6477. }
  6478. else {
  6479. // and the parent selectors
  6480. for (k = 0; k < context.length; k++) {
  6481. // We need to put the current selectors
  6482. // then join the last selector's elements on to the parents selectors
  6483. var newSelectorPath = addReplacementIntoPath(sel, context[k], el, inSelector);
  6484. // add that to our new set of selectors
  6485. selectorsMultiplied.push(newSelectorPath);
  6486. }
  6487. }
  6488. }
  6489. // our new selectors has been multiplied, so reset the state
  6490. newSelectors = selectorsMultiplied;
  6491. currentElements = [];
  6492. }
  6493. }
  6494. // if we have any elements left over (e.g. .a& .b == .b)
  6495. // add them on to all the current selectors
  6496. mergeElementsOnToSelectors(currentElements, newSelectors);
  6497. for (i = 0; i < newSelectors.length; i++) {
  6498. length = newSelectors[i].length;
  6499. if (length > 0) {
  6500. paths.push(newSelectors[i]);
  6501. lastSelector = newSelectors[i][length - 1];
  6502. newSelectors[i][length - 1] = lastSelector.createDerived(lastSelector.elements, inSelector.extendList);
  6503. }
  6504. }
  6505. return hadParentSelector;
  6506. }
  6507. function deriveSelector(visibilityInfo, deriveFrom) {
  6508. var newSelector = deriveFrom.createDerived(deriveFrom.elements, deriveFrom.extendList, deriveFrom.evaldCondition);
  6509. newSelector.copyVisibilityInfo(visibilityInfo);
  6510. return newSelector;
  6511. }
  6512. // joinSelector code follows
  6513. var i, newPaths, hadParentSelector;
  6514. newPaths = [];
  6515. hadParentSelector = replaceParentSelector(newPaths, context, selector);
  6516. if (!hadParentSelector) {
  6517. if (context.length > 0) {
  6518. newPaths = [];
  6519. for (i = 0; i < context.length; i++) {
  6520. var concatenated = context[i].map(deriveSelector.bind(this, selector.visibilityInfo()));
  6521. concatenated.push(selector);
  6522. newPaths.push(concatenated);
  6523. }
  6524. }
  6525. else {
  6526. newPaths = [[selector]];
  6527. }
  6528. }
  6529. for (i = 0; i < newPaths.length; i++) {
  6530. paths.push(newPaths[i]);
  6531. }
  6532. }
  6533. });
  6534. var AtRule = function (name, value, rules, index, currentFileInfo, debugInfo, isRooted, visibilityInfo) {
  6535. var i;
  6536. this.name = name;
  6537. this.value = (value instanceof Node) ? value : (value ? new Anonymous(value) : value);
  6538. if (rules) {
  6539. if (Array.isArray(rules)) {
  6540. this.rules = rules;
  6541. }
  6542. else {
  6543. this.rules = [rules];
  6544. this.rules[0].selectors = (new Selector([], null, null, index, currentFileInfo)).createEmptySelectors();
  6545. }
  6546. for (i = 0; i < this.rules.length; i++) {
  6547. this.rules[i].allowImports = true;
  6548. }
  6549. this.setParent(this.rules, this);
  6550. }
  6551. this._index = index;
  6552. this._fileInfo = currentFileInfo;
  6553. this.debugInfo = debugInfo;
  6554. this.isRooted = isRooted || false;
  6555. this.copyVisibilityInfo(visibilityInfo);
  6556. this.allowRoot = true;
  6557. };
  6558. AtRule.prototype = Object.assign(new Node(), {
  6559. type: 'AtRule',
  6560. accept: function (visitor) {
  6561. var value = this.value, rules = this.rules;
  6562. if (rules) {
  6563. this.rules = visitor.visitArray(rules);
  6564. }
  6565. if (value) {
  6566. this.value = visitor.visit(value);
  6567. }
  6568. },
  6569. isRulesetLike: function () {
  6570. return this.rules || !this.isCharset();
  6571. },
  6572. isCharset: function () {
  6573. return '@charset' === this.name;
  6574. },
  6575. genCSS: function (context, output) {
  6576. var value = this.value, rules = this.rules;
  6577. output.add(this.name, this.fileInfo(), this.getIndex());
  6578. if (value) {
  6579. output.add(' ');
  6580. value.genCSS(context, output);
  6581. }
  6582. if (rules) {
  6583. this.outputRuleset(context, output, rules);
  6584. }
  6585. else {
  6586. output.add(';');
  6587. }
  6588. },
  6589. eval: function (context) {
  6590. var mediaPathBackup, mediaBlocksBackup, value = this.value, rules = this.rules;
  6591. // media stored inside other atrule should not bubble over it
  6592. // backpup media bubbling information
  6593. mediaPathBackup = context.mediaPath;
  6594. mediaBlocksBackup = context.mediaBlocks;
  6595. // deleted media bubbling information
  6596. context.mediaPath = [];
  6597. context.mediaBlocks = [];
  6598. if (value) {
  6599. value = value.eval(context);
  6600. }
  6601. if (rules) {
  6602. // assuming that there is only one rule at this point - that is how parser constructs the rule
  6603. rules = [rules[0].eval(context)];
  6604. rules[0].root = true;
  6605. }
  6606. // restore media bubbling information
  6607. context.mediaPath = mediaPathBackup;
  6608. context.mediaBlocks = mediaBlocksBackup;
  6609. return new AtRule(this.name, value, rules, this.getIndex(), this.fileInfo(), this.debugInfo, this.isRooted, this.visibilityInfo());
  6610. },
  6611. variable: function (name) {
  6612. if (this.rules) {
  6613. // assuming that there is only one rule at this point - that is how parser constructs the rule
  6614. return Ruleset.prototype.variable.call(this.rules[0], name);
  6615. }
  6616. },
  6617. find: function () {
  6618. if (this.rules) {
  6619. // assuming that there is only one rule at this point - that is how parser constructs the rule
  6620. return Ruleset.prototype.find.apply(this.rules[0], arguments);
  6621. }
  6622. },
  6623. rulesets: function () {
  6624. if (this.rules) {
  6625. // assuming that there is only one rule at this point - that is how parser constructs the rule
  6626. return Ruleset.prototype.rulesets.apply(this.rules[0]);
  6627. }
  6628. },
  6629. outputRuleset: function (context, output, rules) {
  6630. var ruleCnt = rules.length;
  6631. var i;
  6632. context.tabLevel = (context.tabLevel | 0) + 1;
  6633. // Compressed
  6634. if (context.compress) {
  6635. output.add('{');
  6636. for (i = 0; i < ruleCnt; i++) {
  6637. rules[i].genCSS(context, output);
  6638. }
  6639. output.add('}');
  6640. context.tabLevel--;
  6641. return;
  6642. }
  6643. // Non-compressed
  6644. var tabSetStr = "\n" + Array(context.tabLevel).join(' '), tabRuleStr = tabSetStr + " ";
  6645. if (!ruleCnt) {
  6646. output.add(" {" + tabSetStr + "}");
  6647. }
  6648. else {
  6649. output.add(" {" + tabRuleStr);
  6650. rules[0].genCSS(context, output);
  6651. for (i = 1; i < ruleCnt; i++) {
  6652. output.add(tabRuleStr);
  6653. rules[i].genCSS(context, output);
  6654. }
  6655. output.add(tabSetStr + "}");
  6656. }
  6657. context.tabLevel--;
  6658. }
  6659. });
  6660. var DetachedRuleset = function (ruleset, frames) {
  6661. this.ruleset = ruleset;
  6662. this.frames = frames;
  6663. this.setParent(this.ruleset, this);
  6664. };
  6665. DetachedRuleset.prototype = Object.assign(new Node(), {
  6666. type: 'DetachedRuleset',
  6667. evalFirst: true,
  6668. accept: function (visitor) {
  6669. this.ruleset = visitor.visit(this.ruleset);
  6670. },
  6671. eval: function (context) {
  6672. var frames = this.frames || copyArray(context.frames);
  6673. return new DetachedRuleset(this.ruleset, frames);
  6674. },
  6675. callEval: function (context) {
  6676. return this.ruleset.eval(this.frames ? new contexts.Eval(context, this.frames.concat(context.frames)) : context);
  6677. }
  6678. });
  6679. var Unit = function (numerator, denominator, backupUnit) {
  6680. this.numerator = numerator ? copyArray(numerator).sort() : [];
  6681. this.denominator = denominator ? copyArray(denominator).sort() : [];
  6682. if (backupUnit) {
  6683. this.backupUnit = backupUnit;
  6684. }
  6685. else if (numerator && numerator.length) {
  6686. this.backupUnit = numerator[0];
  6687. }
  6688. };
  6689. Unit.prototype = Object.assign(new Node(), {
  6690. type: 'Unit',
  6691. clone: function () {
  6692. return new Unit(copyArray(this.numerator), copyArray(this.denominator), this.backupUnit);
  6693. },
  6694. genCSS: function (context, output) {
  6695. // Dimension checks the unit is singular and throws an error if in strict math mode.
  6696. var strictUnits = context && context.strictUnits;
  6697. if (this.numerator.length === 1) {
  6698. output.add(this.numerator[0]); // the ideal situation
  6699. }
  6700. else if (!strictUnits && this.backupUnit) {
  6701. output.add(this.backupUnit);
  6702. }
  6703. else if (!strictUnits && this.denominator.length) {
  6704. output.add(this.denominator[0]);
  6705. }
  6706. },
  6707. toString: function () {
  6708. var i, returnStr = this.numerator.join('*');
  6709. for (i = 0; i < this.denominator.length; i++) {
  6710. returnStr += "/" + this.denominator[i];
  6711. }
  6712. return returnStr;
  6713. },
  6714. compare: function (other) {
  6715. return this.is(other.toString()) ? 0 : undefined;
  6716. },
  6717. is: function (unitString) {
  6718. return this.toString().toUpperCase() === unitString.toUpperCase();
  6719. },
  6720. isLength: function () {
  6721. return RegExp('^(px|em|ex|ch|rem|in|cm|mm|pc|pt|ex|vw|vh|vmin|vmax)$', 'gi').test(this.toCSS());
  6722. },
  6723. isEmpty: function () {
  6724. return this.numerator.length === 0 && this.denominator.length === 0;
  6725. },
  6726. isSingular: function () {
  6727. return this.numerator.length <= 1 && this.denominator.length === 0;
  6728. },
  6729. map: function (callback) {
  6730. var i;
  6731. for (i = 0; i < this.numerator.length; i++) {
  6732. this.numerator[i] = callback(this.numerator[i], false);
  6733. }
  6734. for (i = 0; i < this.denominator.length; i++) {
  6735. this.denominator[i] = callback(this.denominator[i], true);
  6736. }
  6737. },
  6738. usedUnits: function () {
  6739. var group;
  6740. var result = {};
  6741. var mapUnit;
  6742. var groupName;
  6743. mapUnit = function (atomicUnit) {
  6744. // eslint-disable-next-line no-prototype-builtins
  6745. if (group.hasOwnProperty(atomicUnit) && !result[groupName]) {
  6746. result[groupName] = atomicUnit;
  6747. }
  6748. return atomicUnit;
  6749. };
  6750. for (groupName in unitConversions) {
  6751. // eslint-disable-next-line no-prototype-builtins
  6752. if (unitConversions.hasOwnProperty(groupName)) {
  6753. group = unitConversions[groupName];
  6754. this.map(mapUnit);
  6755. }
  6756. }
  6757. return result;
  6758. },
  6759. cancel: function () {
  6760. var counter = {};
  6761. var atomicUnit;
  6762. var i;
  6763. for (i = 0; i < this.numerator.length; i++) {
  6764. atomicUnit = this.numerator[i];
  6765. counter[atomicUnit] = (counter[atomicUnit] || 0) + 1;
  6766. }
  6767. for (i = 0; i < this.denominator.length; i++) {
  6768. atomicUnit = this.denominator[i];
  6769. counter[atomicUnit] = (counter[atomicUnit] || 0) - 1;
  6770. }
  6771. this.numerator = [];
  6772. this.denominator = [];
  6773. for (atomicUnit in counter) {
  6774. // eslint-disable-next-line no-prototype-builtins
  6775. if (counter.hasOwnProperty(atomicUnit)) {
  6776. var count = counter[atomicUnit];
  6777. if (count > 0) {
  6778. for (i = 0; i < count; i++) {
  6779. this.numerator.push(atomicUnit);
  6780. }
  6781. }
  6782. else if (count < 0) {
  6783. for (i = 0; i < -count; i++) {
  6784. this.denominator.push(atomicUnit);
  6785. }
  6786. }
  6787. }
  6788. }
  6789. this.numerator.sort();
  6790. this.denominator.sort();
  6791. }
  6792. });
  6793. /* eslint-disable no-prototype-builtins */
  6794. //
  6795. // A number with a unit
  6796. //
  6797. var Dimension = function (value, unit) {
  6798. this.value = parseFloat(value);
  6799. if (isNaN(this.value)) {
  6800. throw new Error('Dimension is not a number.');
  6801. }
  6802. this.unit = (unit && unit instanceof Unit) ? unit :
  6803. new Unit(unit ? [unit] : undefined);
  6804. this.setParent(this.unit, this);
  6805. };
  6806. Dimension.prototype = Object.assign(new Node(), {
  6807. type: 'Dimension',
  6808. accept: function (visitor) {
  6809. this.unit = visitor.visit(this.unit);
  6810. },
  6811. // remove when Nodes have JSDoc types
  6812. // eslint-disable-next-line no-unused-vars
  6813. eval: function (context) {
  6814. return this;
  6815. },
  6816. toColor: function () {
  6817. return new Color([this.value, this.value, this.value]);
  6818. },
  6819. genCSS: function (context, output) {
  6820. if ((context && context.strictUnits) && !this.unit.isSingular()) {
  6821. throw new Error("Multiple units in dimension. Correct the units or use the unit function. Bad unit: " + this.unit.toString());
  6822. }
  6823. var value = this.fround(context, this.value);
  6824. var strValue = String(value);
  6825. if (value !== 0 && value < 0.000001 && value > -0.000001) {
  6826. // would be output 1e-6 etc.
  6827. strValue = value.toFixed(20).replace(/0+$/, '');
  6828. }
  6829. if (context && context.compress) {
  6830. // Zero values doesn't need a unit
  6831. if (value === 0 && this.unit.isLength()) {
  6832. output.add(strValue);
  6833. return;
  6834. }
  6835. // Float values doesn't need a leading zero
  6836. if (value > 0 && value < 1) {
  6837. strValue = (strValue).substr(1);
  6838. }
  6839. }
  6840. output.add(strValue);
  6841. this.unit.genCSS(context, output);
  6842. },
  6843. // In an operation between two Dimensions,
  6844. // we default to the first Dimension's unit,
  6845. // so `1px + 2` will yield `3px`.
  6846. operate: function (context, op, other) {
  6847. /* jshint noempty:false */
  6848. var value = this._operate(context, op, this.value, other.value);
  6849. var unit = this.unit.clone();
  6850. if (op === '+' || op === '-') {
  6851. if (unit.numerator.length === 0 && unit.denominator.length === 0) {
  6852. unit = other.unit.clone();
  6853. if (this.unit.backupUnit) {
  6854. unit.backupUnit = this.unit.backupUnit;
  6855. }
  6856. }
  6857. else if (other.unit.numerator.length === 0 && unit.denominator.length === 0) ;
  6858. else {
  6859. other = other.convertTo(this.unit.usedUnits());
  6860. if (context.strictUnits && other.unit.toString() !== unit.toString()) {
  6861. throw new Error('Incompatible units. Change the units or use the unit function. '
  6862. + ("Bad units: '" + unit.toString() + "' and '" + other.unit.toString() + "'."));
  6863. }
  6864. value = this._operate(context, op, this.value, other.value);
  6865. }
  6866. }
  6867. else if (op === '*') {
  6868. unit.numerator = unit.numerator.concat(other.unit.numerator).sort();
  6869. unit.denominator = unit.denominator.concat(other.unit.denominator).sort();
  6870. unit.cancel();
  6871. }
  6872. else if (op === '/') {
  6873. unit.numerator = unit.numerator.concat(other.unit.denominator).sort();
  6874. unit.denominator = unit.denominator.concat(other.unit.numerator).sort();
  6875. unit.cancel();
  6876. }
  6877. return new Dimension(value, unit);
  6878. },
  6879. compare: function (other) {
  6880. var a, b;
  6881. if (!(other instanceof Dimension)) {
  6882. return undefined;
  6883. }
  6884. if (this.unit.isEmpty() || other.unit.isEmpty()) {
  6885. a = this;
  6886. b = other;
  6887. }
  6888. else {
  6889. a = this.unify();
  6890. b = other.unify();
  6891. if (a.unit.compare(b.unit) !== 0) {
  6892. return undefined;
  6893. }
  6894. }
  6895. return Node.numericCompare(a.value, b.value);
  6896. },
  6897. unify: function () {
  6898. return this.convertTo({ length: 'px', duration: 's', angle: 'rad' });
  6899. },
  6900. convertTo: function (conversions) {
  6901. var value = this.value;
  6902. var unit = this.unit.clone();
  6903. var i;
  6904. var groupName;
  6905. var group;
  6906. var targetUnit;
  6907. var derivedConversions = {};
  6908. var applyUnit;
  6909. if (typeof conversions === 'string') {
  6910. for (i in unitConversions) {
  6911. if (unitConversions[i].hasOwnProperty(conversions)) {
  6912. derivedConversions = {};
  6913. derivedConversions[i] = conversions;
  6914. }
  6915. }
  6916. conversions = derivedConversions;
  6917. }
  6918. applyUnit = function (atomicUnit, denominator) {
  6919. if (group.hasOwnProperty(atomicUnit)) {
  6920. if (denominator) {
  6921. value = value / (group[atomicUnit] / group[targetUnit]);
  6922. }
  6923. else {
  6924. value = value * (group[atomicUnit] / group[targetUnit]);
  6925. }
  6926. return targetUnit;
  6927. }
  6928. return atomicUnit;
  6929. };
  6930. for (groupName in conversions) {
  6931. if (conversions.hasOwnProperty(groupName)) {
  6932. targetUnit = conversions[groupName];
  6933. group = unitConversions[groupName];
  6934. unit.map(applyUnit);
  6935. }
  6936. }
  6937. unit.cancel();
  6938. return new Dimension(value, unit);
  6939. }
  6940. });
  6941. var MATH = Math$1;
  6942. var Operation = function (op, operands, isSpaced) {
  6943. this.op = op.trim();
  6944. this.operands = operands;
  6945. this.isSpaced = isSpaced;
  6946. };
  6947. Operation.prototype = Object.assign(new Node(), {
  6948. type: 'Operation',
  6949. accept: function (visitor) {
  6950. this.operands = visitor.visitArray(this.operands);
  6951. },
  6952. eval: function (context) {
  6953. var a = this.operands[0].eval(context), b = this.operands[1].eval(context), op;
  6954. if (context.isMathOn(this.op)) {
  6955. op = this.op === './' ? '/' : this.op;
  6956. if (a instanceof Dimension && b instanceof Color) {
  6957. a = a.toColor();
  6958. }
  6959. if (b instanceof Dimension && a instanceof Color) {
  6960. b = b.toColor();
  6961. }
  6962. if (!a.operate || !b.operate) {
  6963. if ((a instanceof Operation || b instanceof Operation)
  6964. && a.op === '/' && context.math === MATH.PARENS_DIVISION) {
  6965. return new Operation(this.op, [a, b], this.isSpaced);
  6966. }
  6967. throw { type: 'Operation',
  6968. message: 'Operation on an invalid type' };
  6969. }
  6970. return a.operate(context, op, b);
  6971. }
  6972. else {
  6973. return new Operation(this.op, [a, b], this.isSpaced);
  6974. }
  6975. },
  6976. genCSS: function (context, output) {
  6977. this.operands[0].genCSS(context, output);
  6978. if (this.isSpaced) {
  6979. output.add(' ');
  6980. }
  6981. output.add(this.op);
  6982. if (this.isSpaced) {
  6983. output.add(' ');
  6984. }
  6985. this.operands[1].genCSS(context, output);
  6986. }
  6987. });
  6988. /*! *****************************************************************************
  6989. Copyright (c) Microsoft Corporation.
  6990. Permission to use, copy, modify, and/or distribute this software for any
  6991. purpose with or without fee is hereby granted.
  6992. THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH
  6993. REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY
  6994. AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,
  6995. INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM
  6996. LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR
  6997. OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
  6998. PERFORMANCE OF THIS SOFTWARE.
  6999. ***************************************************************************** */
  7000. var __assign = function () {
  7001. __assign = Object.assign || function __assign(t) {
  7002. for (var s, i = 1, n = arguments.length; i < n; i++) {
  7003. s = arguments[i];
  7004. for (var p in s)
  7005. if (Object.prototype.hasOwnProperty.call(s, p))
  7006. t[p] = s[p];
  7007. }
  7008. return t;
  7009. };
  7010. return __assign.apply(this, arguments);
  7011. };
  7012. function __spreadArray(to, from, pack) {
  7013. if (pack || arguments.length === 2)
  7014. for (var i = 0, l = from.length, ar; i < l; i++) {
  7015. if (ar || !(i in from)) {
  7016. if (!ar)
  7017. ar = Array.prototype.slice.call(from, 0, i);
  7018. ar[i] = from[i];
  7019. }
  7020. }
  7021. return to.concat(ar || from);
  7022. }
  7023. var Expression = function (value, noSpacing) {
  7024. this.value = value;
  7025. this.noSpacing = noSpacing;
  7026. if (!value) {
  7027. throw new Error('Expression requires an array parameter');
  7028. }
  7029. };
  7030. Expression.prototype = Object.assign(new Node(), {
  7031. type: 'Expression',
  7032. accept: function (visitor) {
  7033. this.value = visitor.visitArray(this.value);
  7034. },
  7035. eval: function (context) {
  7036. var returnValue;
  7037. var mathOn = context.isMathOn();
  7038. var inParenthesis = this.parens;
  7039. var doubleParen = false;
  7040. if (inParenthesis) {
  7041. context.inParenthesis();
  7042. }
  7043. if (this.value.length > 1) {
  7044. returnValue = new Expression(this.value.map(function (e) {
  7045. if (!e.eval) {
  7046. return e;
  7047. }
  7048. return e.eval(context);
  7049. }), this.noSpacing);
  7050. }
  7051. else if (this.value.length === 1) {
  7052. if (this.value[0].parens && !this.value[0].parensInOp && !context.inCalc) {
  7053. doubleParen = true;
  7054. }
  7055. returnValue = this.value[0].eval(context);
  7056. }
  7057. else {
  7058. returnValue = this;
  7059. }
  7060. if (inParenthesis) {
  7061. context.outOfParenthesis();
  7062. }
  7063. if (this.parens && this.parensInOp && !mathOn && !doubleParen
  7064. && (!(returnValue instanceof Dimension))) {
  7065. returnValue = new Paren(returnValue);
  7066. }
  7067. return returnValue;
  7068. },
  7069. genCSS: function (context, output) {
  7070. for (var i_1 = 0; i_1 < this.value.length; i_1++) {
  7071. this.value[i_1].genCSS(context, output);
  7072. if (!this.noSpacing && i_1 + 1 < this.value.length) {
  7073. output.add(' ');
  7074. }
  7075. }
  7076. },
  7077. throwAwayComments: function () {
  7078. this.value = this.value.filter(function (v) {
  7079. return !(v instanceof Comment);
  7080. });
  7081. }
  7082. });
  7083. var functionCaller = /** @class */ (function () {
  7084. function functionCaller(name, context, index, currentFileInfo) {
  7085. this.name = name.toLowerCase();
  7086. this.index = index;
  7087. this.context = context;
  7088. this.currentFileInfo = currentFileInfo;
  7089. this.func = context.frames[0].functionRegistry.get(this.name);
  7090. }
  7091. functionCaller.prototype.isValid = function () {
  7092. return Boolean(this.func);
  7093. };
  7094. functionCaller.prototype.call = function (args) {
  7095. var _this = this;
  7096. if (!(Array.isArray(args))) {
  7097. args = [args];
  7098. }
  7099. var evalArgs = this.func.evalArgs;
  7100. if (evalArgs !== false) {
  7101. args = args.map(function (a) { return a.eval(_this.context); });
  7102. }
  7103. var commentFilter = function (item) { return !(item.type === 'Comment'); };
  7104. // This code is terrible and should be replaced as per this issue...
  7105. // https://github.com/less/less.js/issues/2477
  7106. args = args
  7107. .filter(commentFilter)
  7108. .map(function (item) {
  7109. if (item.type === 'Expression') {
  7110. var subNodes = item.value.filter(commentFilter);
  7111. if (subNodes.length === 1) {
  7112. // https://github.com/less/less.js/issues/3616
  7113. if (item.parens && subNodes[0].op === '/') {
  7114. return item;
  7115. }
  7116. return subNodes[0];
  7117. }
  7118. else {
  7119. return new Expression(subNodes);
  7120. }
  7121. }
  7122. return item;
  7123. });
  7124. if (evalArgs === false) {
  7125. return this.func.apply(this, __spreadArray([this.context], args));
  7126. }
  7127. return this.func.apply(this, args);
  7128. };
  7129. return functionCaller;
  7130. }());
  7131. //
  7132. // A function call node.
  7133. //
  7134. var Call = function (name, args, index, currentFileInfo) {
  7135. this.name = name;
  7136. this.args = args;
  7137. this.calc = name === 'calc';
  7138. this._index = index;
  7139. this._fileInfo = currentFileInfo;
  7140. };
  7141. Call.prototype = Object.assign(new Node(), {
  7142. type: 'Call',
  7143. accept: function (visitor) {
  7144. if (this.args) {
  7145. this.args = visitor.visitArray(this.args);
  7146. }
  7147. },
  7148. //
  7149. // When evaluating a function call,
  7150. // we either find the function in the functionRegistry,
  7151. // in which case we call it, passing the evaluated arguments,
  7152. // if this returns null or we cannot find the function, we
  7153. // simply print it out as it appeared originally [2].
  7154. //
  7155. // The reason why we evaluate the arguments, is in the case where
  7156. // we try to pass a variable to a function, like: `saturate(@color)`.
  7157. // The function should receive the value, not the variable.
  7158. //
  7159. eval: function (context) {
  7160. var _this = this;
  7161. /**
  7162. * Turn off math for calc(), and switch back on for evaluating nested functions
  7163. */
  7164. var currentMathContext = context.mathOn;
  7165. context.mathOn = !this.calc;
  7166. if (this.calc || context.inCalc) {
  7167. context.enterCalc();
  7168. }
  7169. var exitCalc = function () {
  7170. if (_this.calc || context.inCalc) {
  7171. context.exitCalc();
  7172. }
  7173. context.mathOn = currentMathContext;
  7174. };
  7175. var result;
  7176. var funcCaller = new functionCaller(this.name, context, this.getIndex(), this.fileInfo());
  7177. if (funcCaller.isValid()) {
  7178. try {
  7179. result = funcCaller.call(this.args);
  7180. exitCalc();
  7181. }
  7182. catch (e) {
  7183. // eslint-disable-next-line no-prototype-builtins
  7184. if (e.hasOwnProperty('line') && e.hasOwnProperty('column')) {
  7185. throw e;
  7186. }
  7187. throw {
  7188. type: e.type || 'Runtime',
  7189. message: "Error evaluating function `" + this.name + "`" + (e.message ? ": " + e.message : ''),
  7190. index: this.getIndex(),
  7191. filename: this.fileInfo().filename,
  7192. line: e.lineNumber,
  7193. column: e.columnNumber
  7194. };
  7195. }
  7196. }
  7197. if (result !== null && result !== undefined) {
  7198. // Results that that are not nodes are cast as Anonymous nodes
  7199. // Falsy values or booleans are returned as empty nodes
  7200. if (!(result instanceof Node)) {
  7201. if (!result || result === true) {
  7202. result = new Anonymous(null);
  7203. }
  7204. else {
  7205. result = new Anonymous(result.toString());
  7206. }
  7207. }
  7208. result._index = this._index;
  7209. result._fileInfo = this._fileInfo;
  7210. return result;
  7211. }
  7212. var args = this.args.map(function (a) { return a.eval(context); });
  7213. exitCalc();
  7214. return new Call(this.name, args, this.getIndex(), this.fileInfo());
  7215. },
  7216. genCSS: function (context, output) {
  7217. output.add(this.name + "(", this.fileInfo(), this.getIndex());
  7218. for (var i_1 = 0; i_1 < this.args.length; i_1++) {
  7219. this.args[i_1].genCSS(context, output);
  7220. if (i_1 + 1 < this.args.length) {
  7221. output.add(', ');
  7222. }
  7223. }
  7224. output.add(')');
  7225. }
  7226. });
  7227. var Variable = function (name, index, currentFileInfo) {
  7228. this.name = name;
  7229. this._index = index;
  7230. this._fileInfo = currentFileInfo;
  7231. };
  7232. Variable.prototype = Object.assign(new Node(), {
  7233. type: 'Variable',
  7234. eval: function (context) {
  7235. var variable, name = this.name;
  7236. if (name.indexOf('@@') === 0) {
  7237. name = "@" + new Variable(name.slice(1), this.getIndex(), this.fileInfo()).eval(context).value;
  7238. }
  7239. if (this.evaluating) {
  7240. throw { type: 'Name',
  7241. message: "Recursive variable definition for " + name,
  7242. filename: this.fileInfo().filename,
  7243. index: this.getIndex() };
  7244. }
  7245. this.evaluating = true;
  7246. variable = this.find(context.frames, function (frame) {
  7247. var v = frame.variable(name);
  7248. if (v) {
  7249. if (v.important) {
  7250. var importantScope = context.importantScope[context.importantScope.length - 1];
  7251. importantScope.important = v.important;
  7252. }
  7253. // If in calc, wrap vars in a function call to cascade evaluate args first
  7254. if (context.inCalc) {
  7255. return (new Call('_SELF', [v.value])).eval(context);
  7256. }
  7257. else {
  7258. return v.value.eval(context);
  7259. }
  7260. }
  7261. });
  7262. if (variable) {
  7263. this.evaluating = false;
  7264. return variable;
  7265. }
  7266. else {
  7267. throw { type: 'Name',
  7268. message: "variable " + name + " is undefined",
  7269. filename: this.fileInfo().filename,
  7270. index: this.getIndex() };
  7271. }
  7272. },
  7273. find: function (obj, fun) {
  7274. for (var i_1 = 0, r = void 0; i_1 < obj.length; i_1++) {
  7275. r = fun.call(obj, obj[i_1]);
  7276. if (r) {
  7277. return r;
  7278. }
  7279. }
  7280. return null;
  7281. }
  7282. });
  7283. var Property = function (name, index, currentFileInfo) {
  7284. this.name = name;
  7285. this._index = index;
  7286. this._fileInfo = currentFileInfo;
  7287. };
  7288. Property.prototype = Object.assign(new Node(), {
  7289. type: 'Property',
  7290. eval: function (context) {
  7291. var property;
  7292. var name = this.name;
  7293. // TODO: shorten this reference
  7294. var mergeRules = context.pluginManager.less.visitors.ToCSSVisitor.prototype._mergeRules;
  7295. if (this.evaluating) {
  7296. throw { type: 'Name',
  7297. message: "Recursive property reference for " + name,
  7298. filename: this.fileInfo().filename,
  7299. index: this.getIndex() };
  7300. }
  7301. this.evaluating = true;
  7302. property = this.find(context.frames, function (frame) {
  7303. var v;
  7304. var vArr = frame.property(name);
  7305. if (vArr) {
  7306. for (var i_1 = 0; i_1 < vArr.length; i_1++) {
  7307. v = vArr[i_1];
  7308. vArr[i_1] = new Declaration(v.name, v.value, v.important, v.merge, v.index, v.currentFileInfo, v.inline, v.variable);
  7309. }
  7310. mergeRules(vArr);
  7311. v = vArr[vArr.length - 1];
  7312. if (v.important) {
  7313. var importantScope = context.importantScope[context.importantScope.length - 1];
  7314. importantScope.important = v.important;
  7315. }
  7316. v = v.value.eval(context);
  7317. return v;
  7318. }
  7319. });
  7320. if (property) {
  7321. this.evaluating = false;
  7322. return property;
  7323. }
  7324. else {
  7325. throw { type: 'Name',
  7326. message: "Property '" + name + "' is undefined",
  7327. filename: this.currentFileInfo.filename,
  7328. index: this.index };
  7329. }
  7330. },
  7331. find: function (obj, fun) {
  7332. for (var i_2 = 0, r = void 0; i_2 < obj.length; i_2++) {
  7333. r = fun.call(obj, obj[i_2]);
  7334. if (r) {
  7335. return r;
  7336. }
  7337. }
  7338. return null;
  7339. }
  7340. });
  7341. var Attribute = function (key, op, value, cif) {
  7342. this.key = key;
  7343. this.op = op;
  7344. this.value = value;
  7345. this.cif = cif;
  7346. };
  7347. Attribute.prototype = Object.assign(new Node(), {
  7348. type: 'Attribute',
  7349. eval: function (context) {
  7350. 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, this.cif);
  7351. },
  7352. genCSS: function (context, output) {
  7353. output.add(this.toCSS(context));
  7354. },
  7355. toCSS: function (context) {
  7356. var value = this.key.toCSS ? this.key.toCSS(context) : this.key;
  7357. if (this.op) {
  7358. value += this.op;
  7359. value += (this.value.toCSS ? this.value.toCSS(context) : this.value);
  7360. }
  7361. if (this.cif) {
  7362. value = value + ' ' + this.cif;
  7363. }
  7364. return "[" + value + "]";
  7365. }
  7366. });
  7367. var Quoted = function (str, content, escaped, index, currentFileInfo) {
  7368. this.escaped = (escaped === undefined) ? true : escaped;
  7369. this.value = content || '';
  7370. this.quote = str.charAt(0);
  7371. this._index = index;
  7372. this._fileInfo = currentFileInfo;
  7373. this.variableRegex = /@\{([\w-]+)\}/g;
  7374. this.propRegex = /\$\{([\w-]+)\}/g;
  7375. this.allowRoot = escaped;
  7376. };
  7377. Quoted.prototype = Object.assign(new Node(), {
  7378. type: 'Quoted',
  7379. genCSS: function (context, output) {
  7380. if (!this.escaped) {
  7381. output.add(this.quote, this.fileInfo(), this.getIndex());
  7382. }
  7383. output.add(this.value);
  7384. if (!this.escaped) {
  7385. output.add(this.quote);
  7386. }
  7387. },
  7388. containsVariables: function () {
  7389. return this.value.match(this.variableRegex);
  7390. },
  7391. eval: function (context) {
  7392. var that = this;
  7393. var value = this.value;
  7394. var variableReplacement = function (_, name) {
  7395. var v = new Variable("@" + name, that.getIndex(), that.fileInfo()).eval(context, true);
  7396. return (v instanceof Quoted) ? v.value : v.toCSS();
  7397. };
  7398. var propertyReplacement = function (_, name) {
  7399. var v = new Property("$" + name, that.getIndex(), that.fileInfo()).eval(context, true);
  7400. return (v instanceof Quoted) ? v.value : v.toCSS();
  7401. };
  7402. function iterativeReplace(value, regexp, replacementFnc) {
  7403. var evaluatedValue = value;
  7404. do {
  7405. value = evaluatedValue.toString();
  7406. evaluatedValue = value.replace(regexp, replacementFnc);
  7407. } while (value !== evaluatedValue);
  7408. return evaluatedValue;
  7409. }
  7410. value = iterativeReplace(value, this.variableRegex, variableReplacement);
  7411. value = iterativeReplace(value, this.propRegex, propertyReplacement);
  7412. return new Quoted(this.quote + value + this.quote, value, this.escaped, this.getIndex(), this.fileInfo());
  7413. },
  7414. compare: function (other) {
  7415. // when comparing quoted strings allow the quote to differ
  7416. if (other.type === 'Quoted' && !this.escaped && !other.escaped) {
  7417. return Node.numericCompare(this.value, other.value);
  7418. }
  7419. else {
  7420. return other.toCSS && this.toCSS() === other.toCSS() ? 0 : undefined;
  7421. }
  7422. }
  7423. });
  7424. function escapePath(path) {
  7425. return path.replace(/[()'"\s]/g, function (match) { return "\\" + match; });
  7426. }
  7427. var URL = function (val, index, currentFileInfo, isEvald) {
  7428. this.value = val;
  7429. this._index = index;
  7430. this._fileInfo = currentFileInfo;
  7431. this.isEvald = isEvald;
  7432. };
  7433. URL.prototype = Object.assign(new Node(), {
  7434. type: 'Url',
  7435. accept: function (visitor) {
  7436. this.value = visitor.visit(this.value);
  7437. },
  7438. genCSS: function (context, output) {
  7439. output.add('url(');
  7440. this.value.genCSS(context, output);
  7441. output.add(')');
  7442. },
  7443. eval: function (context) {
  7444. var val = this.value.eval(context);
  7445. var rootpath;
  7446. if (!this.isEvald) {
  7447. // Add the rootpath if the URL requires a rewrite
  7448. rootpath = this.fileInfo() && this.fileInfo().rootpath;
  7449. if (typeof rootpath === 'string' &&
  7450. typeof val.value === 'string' &&
  7451. context.pathRequiresRewrite(val.value)) {
  7452. if (!val.quote) {
  7453. rootpath = escapePath(rootpath);
  7454. }
  7455. val.value = context.rewritePath(val.value, rootpath);
  7456. }
  7457. else {
  7458. val.value = context.normalizePath(val.value);
  7459. }
  7460. // Add url args if enabled
  7461. if (context.urlArgs) {
  7462. if (!val.value.match(/^\s*data:/)) {
  7463. var delimiter = val.value.indexOf('?') === -1 ? '?' : '&';
  7464. var urlArgs = delimiter + context.urlArgs;
  7465. if (val.value.indexOf('#') !== -1) {
  7466. val.value = val.value.replace('#', urlArgs + "#");
  7467. }
  7468. else {
  7469. val.value += urlArgs;
  7470. }
  7471. }
  7472. }
  7473. }
  7474. return new URL(val, this.getIndex(), this.fileInfo(), true);
  7475. }
  7476. });
  7477. var NestableAtRulePrototype = {
  7478. isRulesetLike: function () {
  7479. return true;
  7480. },
  7481. accept: function (visitor) {
  7482. if (this.features) {
  7483. this.features = visitor.visit(this.features);
  7484. }
  7485. if (this.rules) {
  7486. this.rules = visitor.visitArray(this.rules);
  7487. }
  7488. },
  7489. evalTop: function (context) {
  7490. var result = this;
  7491. // Render all dependent Media blocks.
  7492. if (context.mediaBlocks.length > 1) {
  7493. var selectors = (new Selector([], null, null, this.getIndex(), this.fileInfo())).createEmptySelectors();
  7494. result = new Ruleset(selectors, context.mediaBlocks);
  7495. result.multiMedia = true;
  7496. result.copyVisibilityInfo(this.visibilityInfo());
  7497. this.setParent(result, this);
  7498. }
  7499. delete context.mediaBlocks;
  7500. delete context.mediaPath;
  7501. return result;
  7502. },
  7503. evalNested: function (context) {
  7504. var i;
  7505. var value;
  7506. var path = context.mediaPath.concat([this]);
  7507. // Extract the media-query conditions separated with `,` (OR).
  7508. for (i = 0; i < path.length; i++) {
  7509. value = path[i].features instanceof Value ?
  7510. path[i].features.value : path[i].features;
  7511. path[i] = Array.isArray(value) ? value : [value];
  7512. }
  7513. // Trace all permutations to generate the resulting media-query.
  7514. //
  7515. // (a, b and c) with nested (d, e) ->
  7516. // a and d
  7517. // a and e
  7518. // b and c and d
  7519. // b and c and e
  7520. this.features = new Value(this.permute(path).map(function (path) {
  7521. path = path.map(function (fragment) { return fragment.toCSS ? fragment : new Anonymous(fragment); });
  7522. for (i = path.length - 1; i > 0; i--) {
  7523. path.splice(i, 0, new Anonymous('and'));
  7524. }
  7525. return new Expression(path);
  7526. }));
  7527. this.setParent(this.features, this);
  7528. // Fake a tree-node that doesn't output anything.
  7529. return new Ruleset([], []);
  7530. },
  7531. permute: function (arr) {
  7532. if (arr.length === 0) {
  7533. return [];
  7534. }
  7535. else if (arr.length === 1) {
  7536. return arr[0];
  7537. }
  7538. else {
  7539. var result = [];
  7540. var rest = this.permute(arr.slice(1));
  7541. for (var i_1 = 0; i_1 < rest.length; i_1++) {
  7542. for (var j = 0; j < arr[0].length; j++) {
  7543. result.push([arr[0][j]].concat(rest[i_1]));
  7544. }
  7545. }
  7546. return result;
  7547. }
  7548. },
  7549. bubbleSelectors: function (selectors) {
  7550. if (!selectors) {
  7551. return;
  7552. }
  7553. this.rules = [new Ruleset(copyArray(selectors), [this.rules[0]])];
  7554. this.setParent(this.rules, this);
  7555. }
  7556. };
  7557. var Media = function (value, features, index, currentFileInfo, visibilityInfo) {
  7558. this._index = index;
  7559. this._fileInfo = currentFileInfo;
  7560. var selectors = (new Selector([], null, null, this._index, this._fileInfo)).createEmptySelectors();
  7561. this.features = new Value(features);
  7562. this.rules = [new Ruleset(selectors, value)];
  7563. this.rules[0].allowImports = true;
  7564. this.copyVisibilityInfo(visibilityInfo);
  7565. this.allowRoot = true;
  7566. this.setParent(selectors, this);
  7567. this.setParent(this.features, this);
  7568. this.setParent(this.rules, this);
  7569. };
  7570. Media.prototype = Object.assign(new AtRule(), __assign(__assign({ type: 'Media' }, NestableAtRulePrototype), { genCSS: function (context, output) {
  7571. output.add('@media ', this._fileInfo, this._index);
  7572. this.features.genCSS(context, output);
  7573. this.outputRuleset(context, output, this.rules);
  7574. }, eval: function (context) {
  7575. if (!context.mediaBlocks) {
  7576. context.mediaBlocks = [];
  7577. context.mediaPath = [];
  7578. }
  7579. var media = new Media(null, [], this._index, this._fileInfo, this.visibilityInfo());
  7580. if (this.debugInfo) {
  7581. this.rules[0].debugInfo = this.debugInfo;
  7582. media.debugInfo = this.debugInfo;
  7583. }
  7584. media.features = this.features.eval(context);
  7585. context.mediaPath.push(media);
  7586. context.mediaBlocks.push(media);
  7587. this.rules[0].functionRegistry = context.frames[0].functionRegistry.inherit();
  7588. context.frames.unshift(this.rules[0]);
  7589. media.rules = [this.rules[0].eval(context)];
  7590. context.frames.shift();
  7591. context.mediaPath.pop();
  7592. return context.mediaPath.length === 0 ? media.evalTop(context) :
  7593. media.evalNested(context);
  7594. } }));
  7595. //
  7596. // CSS @import node
  7597. //
  7598. // The general strategy here is that we don't want to wait
  7599. // for the parsing to be completed, before we start importing
  7600. // the file. That's because in the context of a browser,
  7601. // most of the time will be spent waiting for the server to respond.
  7602. //
  7603. // On creation, we push the import path to our import queue, though
  7604. // `import,push`, we also pass it a callback, which it'll call once
  7605. // the file has been fetched, and parsed.
  7606. //
  7607. var Import = function (path, features, options, index, currentFileInfo, visibilityInfo) {
  7608. this.options = options;
  7609. this._index = index;
  7610. this._fileInfo = currentFileInfo;
  7611. this.path = path;
  7612. this.features = features;
  7613. this.allowRoot = true;
  7614. if (this.options.less !== undefined || this.options.inline) {
  7615. this.css = !this.options.less || this.options.inline;
  7616. }
  7617. else {
  7618. var pathValue = this.getPath();
  7619. if (pathValue && /[#.&?]css([?;].*)?$/.test(pathValue)) {
  7620. this.css = true;
  7621. }
  7622. }
  7623. this.copyVisibilityInfo(visibilityInfo);
  7624. this.setParent(this.features, this);
  7625. this.setParent(this.path, this);
  7626. };
  7627. Import.prototype = Object.assign(new Node(), {
  7628. type: 'Import',
  7629. accept: function (visitor) {
  7630. if (this.features) {
  7631. this.features = visitor.visit(this.features);
  7632. }
  7633. this.path = visitor.visit(this.path);
  7634. if (!this.options.isPlugin && !this.options.inline && this.root) {
  7635. this.root = visitor.visit(this.root);
  7636. }
  7637. },
  7638. genCSS: function (context, output) {
  7639. if (this.css && this.path._fileInfo.reference === undefined) {
  7640. output.add('@import ', this._fileInfo, this._index);
  7641. this.path.genCSS(context, output);
  7642. if (this.features) {
  7643. output.add(' ');
  7644. this.features.genCSS(context, output);
  7645. }
  7646. output.add(';');
  7647. }
  7648. },
  7649. getPath: function () {
  7650. return (this.path instanceof URL) ?
  7651. this.path.value.value : this.path.value;
  7652. },
  7653. isVariableImport: function () {
  7654. var path = this.path;
  7655. if (path instanceof URL) {
  7656. path = path.value;
  7657. }
  7658. if (path instanceof Quoted) {
  7659. return path.containsVariables();
  7660. }
  7661. return true;
  7662. },
  7663. evalForImport: function (context) {
  7664. var path = this.path;
  7665. if (path instanceof URL) {
  7666. path = path.value;
  7667. }
  7668. return new Import(path.eval(context), this.features, this.options, this._index, this._fileInfo, this.visibilityInfo());
  7669. },
  7670. evalPath: function (context) {
  7671. var path = this.path.eval(context);
  7672. var fileInfo = this._fileInfo;
  7673. if (!(path instanceof URL)) {
  7674. // Add the rootpath if the URL requires a rewrite
  7675. var pathValue = path.value;
  7676. if (fileInfo &&
  7677. pathValue &&
  7678. context.pathRequiresRewrite(pathValue)) {
  7679. path.value = context.rewritePath(pathValue, fileInfo.rootpath);
  7680. }
  7681. else {
  7682. path.value = context.normalizePath(path.value);
  7683. }
  7684. }
  7685. return path;
  7686. },
  7687. eval: function (context) {
  7688. var result = this.doEval(context);
  7689. if (this.options.reference || this.blocksVisibility()) {
  7690. if (result.length || result.length === 0) {
  7691. result.forEach(function (node) {
  7692. node.addVisibilityBlock();
  7693. });
  7694. }
  7695. else {
  7696. result.addVisibilityBlock();
  7697. }
  7698. }
  7699. return result;
  7700. },
  7701. doEval: function (context) {
  7702. var ruleset;
  7703. var registry;
  7704. var features = this.features && this.features.eval(context);
  7705. if (this.options.isPlugin) {
  7706. if (this.root && this.root.eval) {
  7707. try {
  7708. this.root.eval(context);
  7709. }
  7710. catch (e) {
  7711. e.message = 'Plugin error during evaluation';
  7712. throw new LessError(e, this.root.imports, this.root.filename);
  7713. }
  7714. }
  7715. registry = context.frames[0] && context.frames[0].functionRegistry;
  7716. if (registry && this.root && this.root.functions) {
  7717. registry.addMultiple(this.root.functions);
  7718. }
  7719. return [];
  7720. }
  7721. if (this.skip) {
  7722. if (typeof this.skip === 'function') {
  7723. this.skip = this.skip();
  7724. }
  7725. if (this.skip) {
  7726. return [];
  7727. }
  7728. }
  7729. if (this.options.inline) {
  7730. var contents = new Anonymous(this.root, 0, {
  7731. filename: this.importedFilename,
  7732. reference: this.path._fileInfo && this.path._fileInfo.reference
  7733. }, true, true);
  7734. return this.features ? new Media([contents], this.features.value) : [contents];
  7735. }
  7736. else if (this.css) {
  7737. var newImport = new Import(this.evalPath(context), features, this.options, this._index);
  7738. if (!newImport.css && this.error) {
  7739. throw this.error;
  7740. }
  7741. return newImport;
  7742. }
  7743. else if (this.root) {
  7744. ruleset = new Ruleset(null, copyArray(this.root.rules));
  7745. ruleset.evalImports(context);
  7746. return this.features ? new Media(ruleset.rules, this.features.value) : ruleset.rules;
  7747. }
  7748. else {
  7749. return [];
  7750. }
  7751. }
  7752. });
  7753. var JsEvalNode = function () { };
  7754. JsEvalNode.prototype = Object.assign(new Node(), {
  7755. evaluateJavaScript: function (expression, context) {
  7756. var result;
  7757. var that = this;
  7758. var evalContext = {};
  7759. if (!context.javascriptEnabled) {
  7760. throw { message: 'Inline JavaScript is not enabled. Is it set in your options?',
  7761. filename: this.fileInfo().filename,
  7762. index: this.getIndex() };
  7763. }
  7764. expression = expression.replace(/@\{([\w-]+)\}/g, function (_, name) {
  7765. return that.jsify(new Variable("@" + name, that.getIndex(), that.fileInfo()).eval(context));
  7766. });
  7767. try {
  7768. expression = new Function("return (" + expression + ")");
  7769. }
  7770. catch (e) {
  7771. throw { message: "JavaScript evaluation error: " + e.message + " from `" + expression + "`",
  7772. filename: this.fileInfo().filename,
  7773. index: this.getIndex() };
  7774. }
  7775. var variables = context.frames[0].variables();
  7776. for (var k in variables) {
  7777. // eslint-disable-next-line no-prototype-builtins
  7778. if (variables.hasOwnProperty(k)) {
  7779. evalContext[k.slice(1)] = {
  7780. value: variables[k].value,
  7781. toJS: function () {
  7782. return this.value.eval(context).toCSS();
  7783. }
  7784. };
  7785. }
  7786. }
  7787. try {
  7788. result = expression.call(evalContext);
  7789. }
  7790. catch (e) {
  7791. throw { message: "JavaScript evaluation error: '" + e.name + ": " + e.message.replace(/["]/g, '\'') + "'",
  7792. filename: this.fileInfo().filename,
  7793. index: this.getIndex() };
  7794. }
  7795. return result;
  7796. },
  7797. jsify: function (obj) {
  7798. if (Array.isArray(obj.value) && (obj.value.length > 1)) {
  7799. return "[" + obj.value.map(function (v) { return v.toCSS(); }).join(', ') + "]";
  7800. }
  7801. else {
  7802. return obj.toCSS();
  7803. }
  7804. }
  7805. });
  7806. var JavaScript = function (string, escaped, index, currentFileInfo) {
  7807. this.escaped = escaped;
  7808. this.expression = string;
  7809. this._index = index;
  7810. this._fileInfo = currentFileInfo;
  7811. };
  7812. JavaScript.prototype = Object.assign(new JsEvalNode(), {
  7813. type: 'JavaScript',
  7814. eval: function (context) {
  7815. var result = this.evaluateJavaScript(this.expression, context);
  7816. var type = typeof result;
  7817. if (type === 'number' && !isNaN(result)) {
  7818. return new Dimension(result);
  7819. }
  7820. else if (type === 'string') {
  7821. return new Quoted("\"" + result + "\"", result, this.escaped, this._index);
  7822. }
  7823. else if (Array.isArray(result)) {
  7824. return new Anonymous(result.join(', '));
  7825. }
  7826. else {
  7827. return new Anonymous(result);
  7828. }
  7829. }
  7830. });
  7831. var Assignment = function (key, val) {
  7832. this.key = key;
  7833. this.value = val;
  7834. };
  7835. Assignment.prototype = Object.assign(new Node(), {
  7836. type: 'Assignment',
  7837. accept: function (visitor) {
  7838. this.value = visitor.visit(this.value);
  7839. },
  7840. eval: function (context) {
  7841. if (this.value.eval) {
  7842. return new Assignment(this.key, this.value.eval(context));
  7843. }
  7844. return this;
  7845. },
  7846. genCSS: function (context, output) {
  7847. output.add(this.key + "=");
  7848. if (this.value.genCSS) {
  7849. this.value.genCSS(context, output);
  7850. }
  7851. else {
  7852. output.add(this.value);
  7853. }
  7854. }
  7855. });
  7856. var Condition = function (op, l, r, i, negate) {
  7857. this.op = op.trim();
  7858. this.lvalue = l;
  7859. this.rvalue = r;
  7860. this._index = i;
  7861. this.negate = negate;
  7862. };
  7863. Condition.prototype = Object.assign(new Node(), {
  7864. type: 'Condition',
  7865. accept: function (visitor) {
  7866. this.lvalue = visitor.visit(this.lvalue);
  7867. this.rvalue = visitor.visit(this.rvalue);
  7868. },
  7869. eval: function (context) {
  7870. var result = (function (op, a, b) {
  7871. switch (op) {
  7872. case 'and': return a && b;
  7873. case 'or': return a || b;
  7874. default:
  7875. switch (Node.compare(a, b)) {
  7876. case -1:
  7877. return op === '<' || op === '=<' || op === '<=';
  7878. case 0:
  7879. return op === '=' || op === '>=' || op === '=<' || op === '<=';
  7880. case 1:
  7881. return op === '>' || op === '>=';
  7882. default:
  7883. return false;
  7884. }
  7885. }
  7886. })(this.op, this.lvalue.eval(context), this.rvalue.eval(context));
  7887. return this.negate ? !result : result;
  7888. }
  7889. });
  7890. var QueryInParens = function (op, l, m, op2, r, i) {
  7891. this.op = op.trim();
  7892. this.lvalue = l;
  7893. this.mvalue = m;
  7894. this.op2 = op2 ? op2.trim() : null;
  7895. this.rvalue = r;
  7896. this._index = i;
  7897. };
  7898. QueryInParens.prototype = Object.assign(new Node(), {
  7899. type: 'QueryInParens',
  7900. accept: function (visitor) {
  7901. this.lvalue = visitor.visit(this.lvalue);
  7902. this.mvalue = visitor.visit(this.mvalue);
  7903. if (this.rvalue) {
  7904. this.rvalue = visitor.visit(this.rvalue);
  7905. }
  7906. },
  7907. eval: function (context) {
  7908. this.lvalue = this.lvalue.eval(context);
  7909. this.mvalue = this.mvalue.eval(context);
  7910. if (this.rvalue) {
  7911. this.rvalue = this.rvalue.eval(context);
  7912. }
  7913. return this;
  7914. },
  7915. genCSS: function (context, output) {
  7916. this.lvalue.genCSS(context, output);
  7917. output.add(' ' + this.op + ' ');
  7918. this.mvalue.genCSS(context, output);
  7919. if (this.rvalue) {
  7920. output.add(' ' + this.op2 + ' ');
  7921. this.rvalue.genCSS(context, output);
  7922. }
  7923. },
  7924. });
  7925. var Container = function (value, features, index, currentFileInfo, visibilityInfo) {
  7926. this._index = index;
  7927. this._fileInfo = currentFileInfo;
  7928. var selectors = (new Selector([], null, null, this._index, this._fileInfo)).createEmptySelectors();
  7929. this.features = new Value(features);
  7930. this.rules = [new Ruleset(selectors, value)];
  7931. this.rules[0].allowImports = true;
  7932. this.copyVisibilityInfo(visibilityInfo);
  7933. this.allowRoot = true;
  7934. this.setParent(selectors, this);
  7935. this.setParent(this.features, this);
  7936. this.setParent(this.rules, this);
  7937. };
  7938. Container.prototype = Object.assign(new AtRule(), __assign(__assign({ type: 'Container' }, NestableAtRulePrototype), { genCSS: function (context, output) {
  7939. output.add('@container ', this._fileInfo, this._index);
  7940. this.features.genCSS(context, output);
  7941. this.outputRuleset(context, output, this.rules);
  7942. }, eval: function (context) {
  7943. if (!context.mediaBlocks) {
  7944. context.mediaBlocks = [];
  7945. context.mediaPath = [];
  7946. }
  7947. var media = new Container(null, [], this._index, this._fileInfo, this.visibilityInfo());
  7948. if (this.debugInfo) {
  7949. this.rules[0].debugInfo = this.debugInfo;
  7950. media.debugInfo = this.debugInfo;
  7951. }
  7952. media.features = this.features.eval(context);
  7953. context.mediaPath.push(media);
  7954. context.mediaBlocks.push(media);
  7955. this.rules[0].functionRegistry = context.frames[0].functionRegistry.inherit();
  7956. context.frames.unshift(this.rules[0]);
  7957. media.rules = [this.rules[0].eval(context)];
  7958. context.frames.shift();
  7959. context.mediaPath.pop();
  7960. return context.mediaPath.length === 0 ? media.evalTop(context) :
  7961. media.evalNested(context);
  7962. } }));
  7963. var UnicodeDescriptor = function (value) {
  7964. this.value = value;
  7965. };
  7966. UnicodeDescriptor.prototype = Object.assign(new Node(), {
  7967. type: 'UnicodeDescriptor'
  7968. });
  7969. var Negative = function (node) {
  7970. this.value = node;
  7971. };
  7972. Negative.prototype = Object.assign(new Node(), {
  7973. type: 'Negative',
  7974. genCSS: function (context, output) {
  7975. output.add('-');
  7976. this.value.genCSS(context, output);
  7977. },
  7978. eval: function (context) {
  7979. if (context.isMathOn()) {
  7980. return (new Operation('*', [new Dimension(-1), this.value])).eval(context);
  7981. }
  7982. return new Negative(this.value.eval(context));
  7983. }
  7984. });
  7985. var Extend = function (selector, option, index, currentFileInfo, visibilityInfo) {
  7986. this.selector = selector;
  7987. this.option = option;
  7988. this.object_id = Extend.next_id++;
  7989. this.parent_ids = [this.object_id];
  7990. this._index = index;
  7991. this._fileInfo = currentFileInfo;
  7992. this.copyVisibilityInfo(visibilityInfo);
  7993. this.allowRoot = true;
  7994. switch (option) {
  7995. case 'all':
  7996. this.allowBefore = true;
  7997. this.allowAfter = true;
  7998. break;
  7999. default:
  8000. this.allowBefore = false;
  8001. this.allowAfter = false;
  8002. break;
  8003. }
  8004. this.setParent(this.selector, this);
  8005. };
  8006. Extend.prototype = Object.assign(new Node(), {
  8007. type: 'Extend',
  8008. accept: function (visitor) {
  8009. this.selector = visitor.visit(this.selector);
  8010. },
  8011. eval: function (context) {
  8012. return new Extend(this.selector.eval(context), this.option, this.getIndex(), this.fileInfo(), this.visibilityInfo());
  8013. },
  8014. // remove when Nodes have JSDoc types
  8015. // eslint-disable-next-line no-unused-vars
  8016. clone: function (context) {
  8017. return new Extend(this.selector, this.option, this.getIndex(), this.fileInfo(), this.visibilityInfo());
  8018. },
  8019. // it concatenates (joins) all selectors in selector array
  8020. findSelfSelectors: function (selectors) {
  8021. var selfElements = [], i, selectorElements;
  8022. for (i = 0; i < selectors.length; i++) {
  8023. selectorElements = selectors[i].elements;
  8024. // duplicate the logic in genCSS function inside the selector node.
  8025. // future TODO - move both logics into the selector joiner visitor
  8026. if (i > 0 && selectorElements.length && selectorElements[0].combinator.value === '') {
  8027. selectorElements[0].combinator.value = ' ';
  8028. }
  8029. selfElements = selfElements.concat(selectors[i].elements);
  8030. }
  8031. this.selfSelectors = [new Selector(selfElements)];
  8032. this.selfSelectors[0].copyVisibilityInfo(this.visibilityInfo());
  8033. }
  8034. });
  8035. Extend.next_id = 0;
  8036. var VariableCall = function (variable, index, currentFileInfo) {
  8037. this.variable = variable;
  8038. this._index = index;
  8039. this._fileInfo = currentFileInfo;
  8040. this.allowRoot = true;
  8041. };
  8042. VariableCall.prototype = Object.assign(new Node(), {
  8043. type: 'VariableCall',
  8044. eval: function (context) {
  8045. var rules;
  8046. var detachedRuleset = new Variable(this.variable, this.getIndex(), this.fileInfo()).eval(context);
  8047. var error = new LessError({ message: "Could not evaluate variable call " + this.variable });
  8048. if (!detachedRuleset.ruleset) {
  8049. if (detachedRuleset.rules) {
  8050. rules = detachedRuleset;
  8051. }
  8052. else if (Array.isArray(detachedRuleset)) {
  8053. rules = new Ruleset('', detachedRuleset);
  8054. }
  8055. else if (Array.isArray(detachedRuleset.value)) {
  8056. rules = new Ruleset('', detachedRuleset.value);
  8057. }
  8058. else {
  8059. throw error;
  8060. }
  8061. detachedRuleset = new DetachedRuleset(rules);
  8062. }
  8063. if (detachedRuleset.ruleset) {
  8064. return detachedRuleset.callEval(context);
  8065. }
  8066. throw error;
  8067. }
  8068. });
  8069. var NamespaceValue = function (ruleCall, lookups, index, fileInfo) {
  8070. this.value = ruleCall;
  8071. this.lookups = lookups;
  8072. this._index = index;
  8073. this._fileInfo = fileInfo;
  8074. };
  8075. NamespaceValue.prototype = Object.assign(new Node(), {
  8076. type: 'NamespaceValue',
  8077. eval: function (context) {
  8078. var i, name, rules = this.value.eval(context);
  8079. for (i = 0; i < this.lookups.length; i++) {
  8080. name = this.lookups[i];
  8081. /**
  8082. * Eval'd DRs return rulesets.
  8083. * Eval'd mixins return rules, so let's make a ruleset if we need it.
  8084. * We need to do this because of late parsing of values
  8085. */
  8086. if (Array.isArray(rules)) {
  8087. rules = new Ruleset([new Selector()], rules);
  8088. }
  8089. if (name === '') {
  8090. rules = rules.lastDeclaration();
  8091. }
  8092. else if (name.charAt(0) === '@') {
  8093. if (name.charAt(1) === '@') {
  8094. name = "@" + new Variable(name.substr(1)).eval(context).value;
  8095. }
  8096. if (rules.variables) {
  8097. rules = rules.variable(name);
  8098. }
  8099. if (!rules) {
  8100. throw { type: 'Name',
  8101. message: "variable " + name + " not found",
  8102. filename: this.fileInfo().filename,
  8103. index: this.getIndex() };
  8104. }
  8105. }
  8106. else {
  8107. if (name.substring(0, 2) === '$@') {
  8108. name = "$" + new Variable(name.substr(1)).eval(context).value;
  8109. }
  8110. else {
  8111. name = name.charAt(0) === '$' ? name : "$" + name;
  8112. }
  8113. if (rules.properties) {
  8114. rules = rules.property(name);
  8115. }
  8116. if (!rules) {
  8117. throw { type: 'Name',
  8118. message: "property \"" + name.substr(1) + "\" not found",
  8119. filename: this.fileInfo().filename,
  8120. index: this.getIndex() };
  8121. }
  8122. // Properties are an array of values, since a ruleset can have multiple props.
  8123. // We pick the last one (the "cascaded" value)
  8124. rules = rules[rules.length - 1];
  8125. }
  8126. if (rules.value) {
  8127. rules = rules.eval(context).value;
  8128. }
  8129. if (rules.ruleset) {
  8130. rules = rules.ruleset.eval(context);
  8131. }
  8132. }
  8133. return rules;
  8134. }
  8135. });
  8136. var Definition = function (name, params, rules, condition, variadic, frames, visibilityInfo) {
  8137. this.name = name || 'anonymous mixin';
  8138. this.selectors = [new Selector([new Element(null, name, false, this._index, this._fileInfo)])];
  8139. this.params = params;
  8140. this.condition = condition;
  8141. this.variadic = variadic;
  8142. this.arity = params.length;
  8143. this.rules = rules;
  8144. this._lookups = {};
  8145. var optionalParameters = [];
  8146. this.required = params.reduce(function (count, p) {
  8147. if (!p.name || (p.name && !p.value)) {
  8148. return count + 1;
  8149. }
  8150. else {
  8151. optionalParameters.push(p.name);
  8152. return count;
  8153. }
  8154. }, 0);
  8155. this.optionalParameters = optionalParameters;
  8156. this.frames = frames;
  8157. this.copyVisibilityInfo(visibilityInfo);
  8158. this.allowRoot = true;
  8159. };
  8160. Definition.prototype = Object.assign(new Ruleset(), {
  8161. type: 'MixinDefinition',
  8162. evalFirst: true,
  8163. accept: function (visitor) {
  8164. if (this.params && this.params.length) {
  8165. this.params = visitor.visitArray(this.params);
  8166. }
  8167. this.rules = visitor.visitArray(this.rules);
  8168. if (this.condition) {
  8169. this.condition = visitor.visit(this.condition);
  8170. }
  8171. },
  8172. evalParams: function (context, mixinEnv, args, evaldArguments) {
  8173. /* jshint boss:true */
  8174. var frame = new Ruleset(null, null);
  8175. var varargs;
  8176. var arg;
  8177. var params = copyArray(this.params);
  8178. var i;
  8179. var j;
  8180. var val;
  8181. var name;
  8182. var isNamedFound;
  8183. var argIndex;
  8184. var argsLength = 0;
  8185. if (mixinEnv.frames && mixinEnv.frames[0] && mixinEnv.frames[0].functionRegistry) {
  8186. frame.functionRegistry = mixinEnv.frames[0].functionRegistry.inherit();
  8187. }
  8188. mixinEnv = new contexts.Eval(mixinEnv, [frame].concat(mixinEnv.frames));
  8189. if (args) {
  8190. args = copyArray(args);
  8191. argsLength = args.length;
  8192. for (i = 0; i < argsLength; i++) {
  8193. arg = args[i];
  8194. if (name = (arg && arg.name)) {
  8195. isNamedFound = false;
  8196. for (j = 0; j < params.length; j++) {
  8197. if (!evaldArguments[j] && name === params[j].name) {
  8198. evaldArguments[j] = arg.value.eval(context);
  8199. frame.prependRule(new Declaration(name, arg.value.eval(context)));
  8200. isNamedFound = true;
  8201. break;
  8202. }
  8203. }
  8204. if (isNamedFound) {
  8205. args.splice(i, 1);
  8206. i--;
  8207. continue;
  8208. }
  8209. else {
  8210. throw { type: 'Runtime', message: "Named argument for " + this.name + " " + args[i].name + " not found" };
  8211. }
  8212. }
  8213. }
  8214. }
  8215. argIndex = 0;
  8216. for (i = 0; i < params.length; i++) {
  8217. if (evaldArguments[i]) {
  8218. continue;
  8219. }
  8220. arg = args && args[argIndex];
  8221. if (name = params[i].name) {
  8222. if (params[i].variadic) {
  8223. varargs = [];
  8224. for (j = argIndex; j < argsLength; j++) {
  8225. varargs.push(args[j].value.eval(context));
  8226. }
  8227. frame.prependRule(new Declaration(name, new Expression(varargs).eval(context)));
  8228. }
  8229. else {
  8230. val = arg && arg.value;
  8231. if (val) {
  8232. // This was a mixin call, pass in a detached ruleset of it's eval'd rules
  8233. if (Array.isArray(val)) {
  8234. val = new DetachedRuleset(new Ruleset('', val));
  8235. }
  8236. else {
  8237. val = val.eval(context);
  8238. }
  8239. }
  8240. else if (params[i].value) {
  8241. val = params[i].value.eval(mixinEnv);
  8242. frame.resetCache();
  8243. }
  8244. else {
  8245. throw { type: 'Runtime', message: "wrong number of arguments for " + this.name + " (" + argsLength + " for " + this.arity + ")" };
  8246. }
  8247. frame.prependRule(new Declaration(name, val));
  8248. evaldArguments[i] = val;
  8249. }
  8250. }
  8251. if (params[i].variadic && args) {
  8252. for (j = argIndex; j < argsLength; j++) {
  8253. evaldArguments[j] = args[j].value.eval(context);
  8254. }
  8255. }
  8256. argIndex++;
  8257. }
  8258. return frame;
  8259. },
  8260. makeImportant: function () {
  8261. var rules = !this.rules ? this.rules : this.rules.map(function (r) {
  8262. if (r.makeImportant) {
  8263. return r.makeImportant(true);
  8264. }
  8265. else {
  8266. return r;
  8267. }
  8268. });
  8269. var result = new Definition(this.name, this.params, rules, this.condition, this.variadic, this.frames);
  8270. return result;
  8271. },
  8272. eval: function (context) {
  8273. return new Definition(this.name, this.params, this.rules, this.condition, this.variadic, this.frames || copyArray(context.frames));
  8274. },
  8275. evalCall: function (context, args, important) {
  8276. var _arguments = [];
  8277. var mixinFrames = this.frames ? this.frames.concat(context.frames) : context.frames;
  8278. var frame = this.evalParams(context, new contexts.Eval(context, mixinFrames), args, _arguments);
  8279. var rules;
  8280. var ruleset;
  8281. frame.prependRule(new Declaration('@arguments', new Expression(_arguments).eval(context)));
  8282. rules = copyArray(this.rules);
  8283. ruleset = new Ruleset(null, rules);
  8284. ruleset.originalRuleset = this;
  8285. ruleset = ruleset.eval(new contexts.Eval(context, [this, frame].concat(mixinFrames)));
  8286. if (important) {
  8287. ruleset = ruleset.makeImportant();
  8288. }
  8289. return ruleset;
  8290. },
  8291. matchCondition: function (args, context) {
  8292. if (this.condition && !this.condition.eval(new contexts.Eval(context, [this.evalParams(context, /* the parameter variables */ new contexts.Eval(context, this.frames ? this.frames.concat(context.frames) : context.frames), args, [])]
  8293. .concat(this.frames || []) // the parent namespace/mixin frames
  8294. .concat(context.frames)))) { // the current environment frames
  8295. return false;
  8296. }
  8297. return true;
  8298. },
  8299. matchArgs: function (args, context) {
  8300. var allArgsCnt = (args && args.length) || 0;
  8301. var len;
  8302. var optionalParameters = this.optionalParameters;
  8303. var requiredArgsCnt = !args ? 0 : args.reduce(function (count, p) {
  8304. if (optionalParameters.indexOf(p.name) < 0) {
  8305. return count + 1;
  8306. }
  8307. else {
  8308. return count;
  8309. }
  8310. }, 0);
  8311. if (!this.variadic) {
  8312. if (requiredArgsCnt < this.required) {
  8313. return false;
  8314. }
  8315. if (allArgsCnt > this.params.length) {
  8316. return false;
  8317. }
  8318. }
  8319. else {
  8320. if (requiredArgsCnt < (this.required - 1)) {
  8321. return false;
  8322. }
  8323. }
  8324. // check patterns
  8325. len = Math.min(requiredArgsCnt, this.arity);
  8326. for (var i_1 = 0; i_1 < len; i_1++) {
  8327. if (!this.params[i_1].name && !this.params[i_1].variadic) {
  8328. if (args[i_1].value.eval(context).toCSS() != this.params[i_1].value.eval(context).toCSS()) {
  8329. return false;
  8330. }
  8331. }
  8332. }
  8333. return true;
  8334. }
  8335. });
  8336. var MixinCall = function (elements, args, index, currentFileInfo, important) {
  8337. this.selector = new Selector(elements);
  8338. this.arguments = args || [];
  8339. this._index = index;
  8340. this._fileInfo = currentFileInfo;
  8341. this.important = important;
  8342. this.allowRoot = true;
  8343. this.setParent(this.selector, this);
  8344. };
  8345. MixinCall.prototype = Object.assign(new Node(), {
  8346. type: 'MixinCall',
  8347. accept: function (visitor) {
  8348. if (this.selector) {
  8349. this.selector = visitor.visit(this.selector);
  8350. }
  8351. if (this.arguments.length) {
  8352. this.arguments = visitor.visitArray(this.arguments);
  8353. }
  8354. },
  8355. eval: function (context) {
  8356. var mixins;
  8357. var mixin;
  8358. var mixinPath;
  8359. var args = [];
  8360. var arg;
  8361. var argValue;
  8362. var rules = [];
  8363. var match = false;
  8364. var i;
  8365. var m;
  8366. var f;
  8367. var isRecursive;
  8368. var isOneFound;
  8369. var candidates = [];
  8370. var candidate;
  8371. var conditionResult = [];
  8372. var defaultResult;
  8373. var defFalseEitherCase = -1;
  8374. var defNone = 0;
  8375. var defTrue = 1;
  8376. var defFalse = 2;
  8377. var count;
  8378. var originalRuleset;
  8379. var noArgumentsFilter;
  8380. this.selector = this.selector.eval(context);
  8381. function calcDefGroup(mixin, mixinPath) {
  8382. var f, p, namespace;
  8383. for (f = 0; f < 2; f++) {
  8384. conditionResult[f] = true;
  8385. defaultFunc.value(f);
  8386. for (p = 0; p < mixinPath.length && conditionResult[f]; p++) {
  8387. namespace = mixinPath[p];
  8388. if (namespace.matchCondition) {
  8389. conditionResult[f] = conditionResult[f] && namespace.matchCondition(null, context);
  8390. }
  8391. }
  8392. if (mixin.matchCondition) {
  8393. conditionResult[f] = conditionResult[f] && mixin.matchCondition(args, context);
  8394. }
  8395. }
  8396. if (conditionResult[0] || conditionResult[1]) {
  8397. if (conditionResult[0] != conditionResult[1]) {
  8398. return conditionResult[1] ?
  8399. defTrue : defFalse;
  8400. }
  8401. return defNone;
  8402. }
  8403. return defFalseEitherCase;
  8404. }
  8405. for (i = 0; i < this.arguments.length; i++) {
  8406. arg = this.arguments[i];
  8407. argValue = arg.value.eval(context);
  8408. if (arg.expand && Array.isArray(argValue.value)) {
  8409. argValue = argValue.value;
  8410. for (m = 0; m < argValue.length; m++) {
  8411. args.push({ value: argValue[m] });
  8412. }
  8413. }
  8414. else {
  8415. args.push({ name: arg.name, value: argValue });
  8416. }
  8417. }
  8418. noArgumentsFilter = function (rule) { return rule.matchArgs(null, context); };
  8419. for (i = 0; i < context.frames.length; i++) {
  8420. if ((mixins = context.frames[i].find(this.selector, null, noArgumentsFilter)).length > 0) {
  8421. isOneFound = true;
  8422. // To make `default()` function independent of definition order we have two "subpasses" here.
  8423. // At first we evaluate each guard *twice* (with `default() == true` and `default() == false`),
  8424. // and build candidate list with corresponding flags. Then, when we know all possible matches,
  8425. // we make a final decision.
  8426. for (m = 0; m < mixins.length; m++) {
  8427. mixin = mixins[m].rule;
  8428. mixinPath = mixins[m].path;
  8429. isRecursive = false;
  8430. for (f = 0; f < context.frames.length; f++) {
  8431. if ((!(mixin instanceof Definition)) && mixin === (context.frames[f].originalRuleset || context.frames[f])) {
  8432. isRecursive = true;
  8433. break;
  8434. }
  8435. }
  8436. if (isRecursive) {
  8437. continue;
  8438. }
  8439. if (mixin.matchArgs(args, context)) {
  8440. candidate = { mixin: mixin, group: calcDefGroup(mixin, mixinPath) };
  8441. if (candidate.group !== defFalseEitherCase) {
  8442. candidates.push(candidate);
  8443. }
  8444. match = true;
  8445. }
  8446. }
  8447. defaultFunc.reset();
  8448. count = [0, 0, 0];
  8449. for (m = 0; m < candidates.length; m++) {
  8450. count[candidates[m].group]++;
  8451. }
  8452. if (count[defNone] > 0) {
  8453. defaultResult = defFalse;
  8454. }
  8455. else {
  8456. defaultResult = defTrue;
  8457. if ((count[defTrue] + count[defFalse]) > 1) {
  8458. throw { type: 'Runtime',
  8459. message: "Ambiguous use of `default()` found when matching for `" + this.format(args) + "`",
  8460. index: this.getIndex(), filename: this.fileInfo().filename };
  8461. }
  8462. }
  8463. for (m = 0; m < candidates.length; m++) {
  8464. candidate = candidates[m].group;
  8465. if ((candidate === defNone) || (candidate === defaultResult)) {
  8466. try {
  8467. mixin = candidates[m].mixin;
  8468. if (!(mixin instanceof Definition)) {
  8469. originalRuleset = mixin.originalRuleset || mixin;
  8470. mixin = new Definition('', [], mixin.rules, null, false, null, originalRuleset.visibilityInfo());
  8471. mixin.originalRuleset = originalRuleset;
  8472. }
  8473. var newRules = mixin.evalCall(context, args, this.important).rules;
  8474. this._setVisibilityToReplacement(newRules);
  8475. Array.prototype.push.apply(rules, newRules);
  8476. }
  8477. catch (e) {
  8478. throw { message: e.message, index: this.getIndex(), filename: this.fileInfo().filename, stack: e.stack };
  8479. }
  8480. }
  8481. }
  8482. if (match) {
  8483. return rules;
  8484. }
  8485. }
  8486. }
  8487. if (isOneFound) {
  8488. throw { type: 'Runtime',
  8489. message: "No matching definition was found for `" + this.format(args) + "`",
  8490. index: this.getIndex(), filename: this.fileInfo().filename };
  8491. }
  8492. else {
  8493. throw { type: 'Name',
  8494. message: this.selector.toCSS().trim() + " is undefined",
  8495. index: this.getIndex(), filename: this.fileInfo().filename };
  8496. }
  8497. },
  8498. _setVisibilityToReplacement: function (replacement) {
  8499. var i, rule;
  8500. if (this.blocksVisibility()) {
  8501. for (i = 0; i < replacement.length; i++) {
  8502. rule = replacement[i];
  8503. rule.addVisibilityBlock();
  8504. }
  8505. }
  8506. },
  8507. format: function (args) {
  8508. return this.selector.toCSS().trim() + "(" + (args ? args.map(function (a) {
  8509. var argValue = '';
  8510. if (a.name) {
  8511. argValue += a.name + ":";
  8512. }
  8513. if (a.value.toCSS) {
  8514. argValue += a.value.toCSS();
  8515. }
  8516. else {
  8517. argValue += '???';
  8518. }
  8519. return argValue;
  8520. }).join(', ') : '') + ")";
  8521. }
  8522. });
  8523. var tree = {
  8524. Node: Node,
  8525. Color: Color,
  8526. AtRule: AtRule,
  8527. DetachedRuleset: DetachedRuleset,
  8528. Operation: Operation,
  8529. Dimension: Dimension,
  8530. Unit: Unit,
  8531. Keyword: Keyword,
  8532. Variable: Variable,
  8533. Property: Property,
  8534. Ruleset: Ruleset,
  8535. Element: Element,
  8536. Attribute: Attribute,
  8537. Combinator: Combinator,
  8538. Selector: Selector,
  8539. Quoted: Quoted,
  8540. Expression: Expression,
  8541. Declaration: Declaration,
  8542. Call: Call,
  8543. URL: URL,
  8544. Import: Import,
  8545. Comment: Comment,
  8546. Anonymous: Anonymous,
  8547. Value: Value,
  8548. JavaScript: JavaScript,
  8549. Assignment: Assignment,
  8550. Condition: Condition,
  8551. Paren: Paren,
  8552. Media: Media,
  8553. Container: Container,
  8554. QueryInParens: QueryInParens,
  8555. UnicodeDescriptor: UnicodeDescriptor,
  8556. Negative: Negative,
  8557. Extend: Extend,
  8558. VariableCall: VariableCall,
  8559. NamespaceValue: NamespaceValue,
  8560. mixin: {
  8561. Call: MixinCall,
  8562. Definition: Definition
  8563. }
  8564. };
  8565. var AbstractFileManager = /** @class */ (function () {
  8566. function AbstractFileManager() {
  8567. }
  8568. AbstractFileManager.prototype.getPath = function (filename) {
  8569. var j = filename.lastIndexOf('?');
  8570. if (j > 0) {
  8571. filename = filename.slice(0, j);
  8572. }
  8573. j = filename.lastIndexOf('/');
  8574. if (j < 0) {
  8575. j = filename.lastIndexOf('\\');
  8576. }
  8577. if (j < 0) {
  8578. return '';
  8579. }
  8580. return filename.slice(0, j + 1);
  8581. };
  8582. AbstractFileManager.prototype.tryAppendExtension = function (path, ext) {
  8583. return /(\.[a-z]*$)|([?;].*)$/.test(path) ? path : path + ext;
  8584. };
  8585. AbstractFileManager.prototype.tryAppendLessExtension = function (path) {
  8586. return this.tryAppendExtension(path, '.less');
  8587. };
  8588. AbstractFileManager.prototype.supportsSync = function () {
  8589. return false;
  8590. };
  8591. AbstractFileManager.prototype.alwaysMakePathsAbsolute = function () {
  8592. return false;
  8593. };
  8594. AbstractFileManager.prototype.isPathAbsolute = function (filename) {
  8595. return (/^(?:[a-z-]+:|\/|\\|#)/i).test(filename);
  8596. };
  8597. // TODO: pull out / replace?
  8598. AbstractFileManager.prototype.join = function (basePath, laterPath) {
  8599. if (!basePath) {
  8600. return laterPath;
  8601. }
  8602. return basePath + laterPath;
  8603. };
  8604. AbstractFileManager.prototype.pathDiff = function (url, baseUrl) {
  8605. // diff between two paths to create a relative path
  8606. var urlParts = this.extractUrlParts(url);
  8607. var baseUrlParts = this.extractUrlParts(baseUrl);
  8608. var i;
  8609. var max;
  8610. var urlDirectories;
  8611. var baseUrlDirectories;
  8612. var diff = '';
  8613. if (urlParts.hostPart !== baseUrlParts.hostPart) {
  8614. return '';
  8615. }
  8616. max = Math.max(baseUrlParts.directories.length, urlParts.directories.length);
  8617. for (i = 0; i < max; i++) {
  8618. if (baseUrlParts.directories[i] !== urlParts.directories[i]) {
  8619. break;
  8620. }
  8621. }
  8622. baseUrlDirectories = baseUrlParts.directories.slice(i);
  8623. urlDirectories = urlParts.directories.slice(i);
  8624. for (i = 0; i < baseUrlDirectories.length - 1; i++) {
  8625. diff += '../';
  8626. }
  8627. for (i = 0; i < urlDirectories.length - 1; i++) {
  8628. diff += urlDirectories[i] + "/";
  8629. }
  8630. return diff;
  8631. };
  8632. /**
  8633. * Helper function, not part of API.
  8634. * This should be replaceable by newer Node / Browser APIs
  8635. *
  8636. * @param {string} url
  8637. * @param {string} baseUrl
  8638. */
  8639. AbstractFileManager.prototype.extractUrlParts = function (url, baseUrl) {
  8640. // urlParts[1] = protocol://hostname/ OR /
  8641. // urlParts[2] = / if path relative to host base
  8642. // urlParts[3] = directories
  8643. // urlParts[4] = filename
  8644. // urlParts[5] = parameters
  8645. var urlPartsRegex = /^((?:[a-z-]+:)?\/{2}(?:[^/?#]*\/)|([/\\]))?((?:[^/\\?#]*[/\\])*)([^/\\?#]*)([#?].*)?$/i;
  8646. var urlParts = url.match(urlPartsRegex);
  8647. var returner = {};
  8648. var rawDirectories = [];
  8649. var directories = [];
  8650. var i;
  8651. var baseUrlParts;
  8652. if (!urlParts) {
  8653. throw new Error("Could not parse sheet href - '" + url + "'");
  8654. }
  8655. // Stylesheets in IE don't always return the full path
  8656. if (baseUrl && (!urlParts[1] || urlParts[2])) {
  8657. baseUrlParts = baseUrl.match(urlPartsRegex);
  8658. if (!baseUrlParts) {
  8659. throw new Error("Could not parse page url - '" + baseUrl + "'");
  8660. }
  8661. urlParts[1] = urlParts[1] || baseUrlParts[1] || '';
  8662. if (!urlParts[2]) {
  8663. urlParts[3] = baseUrlParts[3] + urlParts[3];
  8664. }
  8665. }
  8666. if (urlParts[3]) {
  8667. rawDirectories = urlParts[3].replace(/\\/g, '/').split('/');
  8668. // collapse '..' and skip '.'
  8669. for (i = 0; i < rawDirectories.length; i++) {
  8670. if (rawDirectories[i] === '..') {
  8671. directories.pop();
  8672. }
  8673. else if (rawDirectories[i] !== '.') {
  8674. directories.push(rawDirectories[i]);
  8675. }
  8676. }
  8677. }
  8678. returner.hostPart = urlParts[1];
  8679. returner.directories = directories;
  8680. returner.rawPath = (urlParts[1] || '') + rawDirectories.join('/');
  8681. returner.path = (urlParts[1] || '') + directories.join('/');
  8682. returner.filename = urlParts[4];
  8683. returner.fileUrl = returner.path + (urlParts[4] || '');
  8684. returner.url = returner.fileUrl + (urlParts[5] || '');
  8685. return returner;
  8686. };
  8687. return AbstractFileManager;
  8688. }());
  8689. var AbstractPluginLoader = /** @class */ (function () {
  8690. function AbstractPluginLoader() {
  8691. // Implemented by Node.js plugin loader
  8692. this.require = function () {
  8693. return null;
  8694. };
  8695. }
  8696. AbstractPluginLoader.prototype.evalPlugin = function (contents, context, imports, pluginOptions, fileInfo) {
  8697. var loader, registry, pluginObj, localModule, pluginManager, filename, result;
  8698. pluginManager = context.pluginManager;
  8699. if (fileInfo) {
  8700. if (typeof fileInfo === 'string') {
  8701. filename = fileInfo;
  8702. }
  8703. else {
  8704. filename = fileInfo.filename;
  8705. }
  8706. }
  8707. var shortname = (new this.less.FileManager()).extractUrlParts(filename).filename;
  8708. if (filename) {
  8709. pluginObj = pluginManager.get(filename);
  8710. if (pluginObj) {
  8711. result = this.trySetOptions(pluginObj, filename, shortname, pluginOptions);
  8712. if (result) {
  8713. return result;
  8714. }
  8715. try {
  8716. if (pluginObj.use) {
  8717. pluginObj.use.call(this.context, pluginObj);
  8718. }
  8719. }
  8720. catch (e) {
  8721. e.message = e.message || 'Error during @plugin call';
  8722. return new LessError(e, imports, filename);
  8723. }
  8724. return pluginObj;
  8725. }
  8726. }
  8727. localModule = {
  8728. exports: {},
  8729. pluginManager: pluginManager,
  8730. fileInfo: fileInfo
  8731. };
  8732. registry = functionRegistry.create();
  8733. var registerPlugin = function (obj) {
  8734. pluginObj = obj;
  8735. };
  8736. try {
  8737. loader = new Function('module', 'require', 'registerPlugin', 'functions', 'tree', 'less', 'fileInfo', contents);
  8738. loader(localModule, this.require(filename), registerPlugin, registry, this.less.tree, this.less, fileInfo);
  8739. }
  8740. catch (e) {
  8741. return new LessError(e, imports, filename);
  8742. }
  8743. if (!pluginObj) {
  8744. pluginObj = localModule.exports;
  8745. }
  8746. pluginObj = this.validatePlugin(pluginObj, filename, shortname);
  8747. if (pluginObj instanceof LessError) {
  8748. return pluginObj;
  8749. }
  8750. if (pluginObj) {
  8751. pluginObj.imports = imports;
  8752. pluginObj.filename = filename;
  8753. // For < 3.x (or unspecified minVersion) - setOptions() before install()
  8754. if (!pluginObj.minVersion || this.compareVersion('3.0.0', pluginObj.minVersion) < 0) {
  8755. result = this.trySetOptions(pluginObj, filename, shortname, pluginOptions);
  8756. if (result) {
  8757. return result;
  8758. }
  8759. }
  8760. // Run on first load
  8761. pluginManager.addPlugin(pluginObj, fileInfo.filename, registry);
  8762. pluginObj.functions = registry.getLocalFunctions();
  8763. // Need to call setOptions again because the pluginObj might have functions
  8764. result = this.trySetOptions(pluginObj, filename, shortname, pluginOptions);
  8765. if (result) {
  8766. return result;
  8767. }
  8768. // Run every @plugin call
  8769. try {
  8770. if (pluginObj.use) {
  8771. pluginObj.use.call(this.context, pluginObj);
  8772. }
  8773. }
  8774. catch (e) {
  8775. e.message = e.message || 'Error during @plugin call';
  8776. return new LessError(e, imports, filename);
  8777. }
  8778. }
  8779. else {
  8780. return new LessError({ message: 'Not a valid plugin' }, imports, filename);
  8781. }
  8782. return pluginObj;
  8783. };
  8784. AbstractPluginLoader.prototype.trySetOptions = function (plugin, filename, name, options) {
  8785. if (options && !plugin.setOptions) {
  8786. return new LessError({
  8787. message: "Options have been provided but the plugin " + name + " does not support any options."
  8788. });
  8789. }
  8790. try {
  8791. plugin.setOptions && plugin.setOptions(options);
  8792. }
  8793. catch (e) {
  8794. return new LessError(e);
  8795. }
  8796. };
  8797. AbstractPluginLoader.prototype.validatePlugin = function (plugin, filename, name) {
  8798. if (plugin) {
  8799. // support plugins being a function
  8800. // so that the plugin can be more usable programmatically
  8801. if (typeof plugin === 'function') {
  8802. plugin = new plugin();
  8803. }
  8804. if (plugin.minVersion) {
  8805. if (this.compareVersion(plugin.minVersion, this.less.version) < 0) {
  8806. return new LessError({
  8807. message: "Plugin " + name + " requires version " + this.versionToString(plugin.minVersion)
  8808. });
  8809. }
  8810. }
  8811. return plugin;
  8812. }
  8813. return null;
  8814. };
  8815. AbstractPluginLoader.prototype.compareVersion = function (aVersion, bVersion) {
  8816. if (typeof aVersion === 'string') {
  8817. aVersion = aVersion.match(/^(\d+)\.?(\d+)?\.?(\d+)?/);
  8818. aVersion.shift();
  8819. }
  8820. for (var i_1 = 0; i_1 < aVersion.length; i_1++) {
  8821. if (aVersion[i_1] !== bVersion[i_1]) {
  8822. return parseInt(aVersion[i_1]) > parseInt(bVersion[i_1]) ? -1 : 1;
  8823. }
  8824. }
  8825. return 0;
  8826. };
  8827. AbstractPluginLoader.prototype.versionToString = function (version) {
  8828. var versionString = '';
  8829. for (var i_2 = 0; i_2 < version.length; i_2++) {
  8830. versionString += (versionString ? '.' : '') + version[i_2];
  8831. }
  8832. return versionString;
  8833. };
  8834. AbstractPluginLoader.prototype.printUsage = function (plugins) {
  8835. for (var i_3 = 0; i_3 < plugins.length; i_3++) {
  8836. var plugin = plugins[i_3];
  8837. if (plugin.printUsage) {
  8838. plugin.printUsage();
  8839. }
  8840. }
  8841. };
  8842. return AbstractPluginLoader;
  8843. }());
  8844. function boolean(condition) {
  8845. return condition ? Keyword.True : Keyword.False;
  8846. }
  8847. /**
  8848. * Functions with evalArgs set to false are sent context
  8849. * as the first argument.
  8850. */
  8851. function If(context, condition, trueValue, falseValue) {
  8852. return condition.eval(context) ? trueValue.eval(context)
  8853. : (falseValue ? falseValue.eval(context) : new Anonymous);
  8854. }
  8855. If.evalArgs = false;
  8856. function isdefined(context, variable) {
  8857. try {
  8858. variable.eval(context);
  8859. return Keyword.True;
  8860. }
  8861. catch (e) {
  8862. return Keyword.False;
  8863. }
  8864. }
  8865. isdefined.evalArgs = false;
  8866. var boolean$1 = { isdefined: isdefined, boolean: boolean, 'if': If };
  8867. var colorFunctions;
  8868. function clamp(val) {
  8869. return Math.min(1, Math.max(0, val));
  8870. }
  8871. function hsla(origColor, hsl) {
  8872. var color = colorFunctions.hsla(hsl.h, hsl.s, hsl.l, hsl.a);
  8873. if (color) {
  8874. if (origColor.value &&
  8875. /^(rgb|hsl)/.test(origColor.value)) {
  8876. color.value = origColor.value;
  8877. }
  8878. else {
  8879. color.value = 'rgb';
  8880. }
  8881. return color;
  8882. }
  8883. }
  8884. function toHSL(color) {
  8885. if (color.toHSL) {
  8886. return color.toHSL();
  8887. }
  8888. else {
  8889. throw new Error('Argument cannot be evaluated to a color');
  8890. }
  8891. }
  8892. function toHSV(color) {
  8893. if (color.toHSV) {
  8894. return color.toHSV();
  8895. }
  8896. else {
  8897. throw new Error('Argument cannot be evaluated to a color');
  8898. }
  8899. }
  8900. function number$1(n) {
  8901. if (n instanceof Dimension) {
  8902. return parseFloat(n.unit.is('%') ? n.value / 100 : n.value);
  8903. }
  8904. else if (typeof n === 'number') {
  8905. return n;
  8906. }
  8907. else {
  8908. throw {
  8909. type: 'Argument',
  8910. message: 'color functions take numbers as parameters'
  8911. };
  8912. }
  8913. }
  8914. function scaled(n, size) {
  8915. if (n instanceof Dimension && n.unit.is('%')) {
  8916. return parseFloat(n.value * size / 100);
  8917. }
  8918. else {
  8919. return number$1(n);
  8920. }
  8921. }
  8922. colorFunctions = {
  8923. rgb: function (r, g, b) {
  8924. var a = 1;
  8925. /**
  8926. * Comma-less syntax
  8927. * e.g. rgb(0 128 255 / 50%)
  8928. */
  8929. if (r instanceof Expression) {
  8930. var val = r.value;
  8931. r = val[0];
  8932. g = val[1];
  8933. b = val[2];
  8934. /**
  8935. * @todo - should this be normalized in
  8936. * function caller? Or parsed differently?
  8937. */
  8938. if (b instanceof Operation) {
  8939. var op = b;
  8940. b = op.operands[0];
  8941. a = op.operands[1];
  8942. }
  8943. }
  8944. var color = colorFunctions.rgba(r, g, b, a);
  8945. if (color) {
  8946. color.value = 'rgb';
  8947. return color;
  8948. }
  8949. },
  8950. rgba: function (r, g, b, a) {
  8951. try {
  8952. if (r instanceof Color) {
  8953. if (g) {
  8954. a = number$1(g);
  8955. }
  8956. else {
  8957. a = r.alpha;
  8958. }
  8959. return new Color(r.rgb, a, 'rgba');
  8960. }
  8961. var rgb = [r, g, b].map(function (c) { return scaled(c, 255); });
  8962. a = number$1(a);
  8963. return new Color(rgb, a, 'rgba');
  8964. }
  8965. catch (e) { }
  8966. },
  8967. hsl: function (h, s, l) {
  8968. var a = 1;
  8969. if (h instanceof Expression) {
  8970. var val = h.value;
  8971. h = val[0];
  8972. s = val[1];
  8973. l = val[2];
  8974. if (l instanceof Operation) {
  8975. var op = l;
  8976. l = op.operands[0];
  8977. a = op.operands[1];
  8978. }
  8979. }
  8980. var color = colorFunctions.hsla(h, s, l, a);
  8981. if (color) {
  8982. color.value = 'hsl';
  8983. return color;
  8984. }
  8985. },
  8986. hsla: function (h, s, l, a) {
  8987. var m1;
  8988. var m2;
  8989. function hue(h) {
  8990. h = h < 0 ? h + 1 : (h > 1 ? h - 1 : h);
  8991. if (h * 6 < 1) {
  8992. return m1 + (m2 - m1) * h * 6;
  8993. }
  8994. else if (h * 2 < 1) {
  8995. return m2;
  8996. }
  8997. else if (h * 3 < 2) {
  8998. return m1 + (m2 - m1) * (2 / 3 - h) * 6;
  8999. }
  9000. else {
  9001. return m1;
  9002. }
  9003. }
  9004. try {
  9005. if (h instanceof Color) {
  9006. if (s) {
  9007. a = number$1(s);
  9008. }
  9009. else {
  9010. a = h.alpha;
  9011. }
  9012. return new Color(h.rgb, a, 'hsla');
  9013. }
  9014. h = (number$1(h) % 360) / 360;
  9015. s = clamp(number$1(s));
  9016. l = clamp(number$1(l));
  9017. a = clamp(number$1(a));
  9018. m2 = l <= 0.5 ? l * (s + 1) : l + s - l * s;
  9019. m1 = l * 2 - m2;
  9020. var rgb = [
  9021. hue(h + 1 / 3) * 255,
  9022. hue(h) * 255,
  9023. hue(h - 1 / 3) * 255
  9024. ];
  9025. a = number$1(a);
  9026. return new Color(rgb, a, 'hsla');
  9027. }
  9028. catch (e) { }
  9029. },
  9030. hsv: function (h, s, v) {
  9031. return colorFunctions.hsva(h, s, v, 1.0);
  9032. },
  9033. hsva: function (h, s, v, a) {
  9034. h = ((number$1(h) % 360) / 360) * 360;
  9035. s = number$1(s);
  9036. v = number$1(v);
  9037. a = number$1(a);
  9038. var i;
  9039. var f;
  9040. i = Math.floor((h / 60) % 6);
  9041. f = (h / 60) - i;
  9042. var vs = [v,
  9043. v * (1 - s),
  9044. v * (1 - f * s),
  9045. v * (1 - (1 - f) * s)];
  9046. var perm = [[0, 3, 1],
  9047. [2, 0, 1],
  9048. [1, 0, 3],
  9049. [1, 2, 0],
  9050. [3, 1, 0],
  9051. [0, 1, 2]];
  9052. return colorFunctions.rgba(vs[perm[i][0]] * 255, vs[perm[i][1]] * 255, vs[perm[i][2]] * 255, a);
  9053. },
  9054. hue: function (color) {
  9055. return new Dimension(toHSL(color).h);
  9056. },
  9057. saturation: function (color) {
  9058. return new Dimension(toHSL(color).s * 100, '%');
  9059. },
  9060. lightness: function (color) {
  9061. return new Dimension(toHSL(color).l * 100, '%');
  9062. },
  9063. hsvhue: function (color) {
  9064. return new Dimension(toHSV(color).h);
  9065. },
  9066. hsvsaturation: function (color) {
  9067. return new Dimension(toHSV(color).s * 100, '%');
  9068. },
  9069. hsvvalue: function (color) {
  9070. return new Dimension(toHSV(color).v * 100, '%');
  9071. },
  9072. red: function (color) {
  9073. return new Dimension(color.rgb[0]);
  9074. },
  9075. green: function (color) {
  9076. return new Dimension(color.rgb[1]);
  9077. },
  9078. blue: function (color) {
  9079. return new Dimension(color.rgb[2]);
  9080. },
  9081. alpha: function (color) {
  9082. return new Dimension(toHSL(color).a);
  9083. },
  9084. luma: function (color) {
  9085. return new Dimension(color.luma() * color.alpha * 100, '%');
  9086. },
  9087. luminance: function (color) {
  9088. var luminance = (0.2126 * color.rgb[0] / 255) +
  9089. (0.7152 * color.rgb[1] / 255) +
  9090. (0.0722 * color.rgb[2] / 255);
  9091. return new Dimension(luminance * color.alpha * 100, '%');
  9092. },
  9093. saturate: function (color, amount, method) {
  9094. // filter: saturate(3.2);
  9095. // should be kept as is, so check for color
  9096. if (!color.rgb) {
  9097. return null;
  9098. }
  9099. var hsl = toHSL(color);
  9100. if (typeof method !== 'undefined' && method.value === 'relative') {
  9101. hsl.s += hsl.s * amount.value / 100;
  9102. }
  9103. else {
  9104. hsl.s += amount.value / 100;
  9105. }
  9106. hsl.s = clamp(hsl.s);
  9107. return hsla(color, hsl);
  9108. },
  9109. desaturate: function (color, amount, method) {
  9110. var hsl = toHSL(color);
  9111. if (typeof method !== 'undefined' && method.value === 'relative') {
  9112. hsl.s -= hsl.s * amount.value / 100;
  9113. }
  9114. else {
  9115. hsl.s -= amount.value / 100;
  9116. }
  9117. hsl.s = clamp(hsl.s);
  9118. return hsla(color, hsl);
  9119. },
  9120. lighten: function (color, amount, method) {
  9121. var hsl = toHSL(color);
  9122. if (typeof method !== 'undefined' && method.value === 'relative') {
  9123. hsl.l += hsl.l * amount.value / 100;
  9124. }
  9125. else {
  9126. hsl.l += amount.value / 100;
  9127. }
  9128. hsl.l = clamp(hsl.l);
  9129. return hsla(color, hsl);
  9130. },
  9131. darken: function (color, amount, method) {
  9132. var hsl = toHSL(color);
  9133. if (typeof method !== 'undefined' && method.value === 'relative') {
  9134. hsl.l -= hsl.l * amount.value / 100;
  9135. }
  9136. else {
  9137. hsl.l -= amount.value / 100;
  9138. }
  9139. hsl.l = clamp(hsl.l);
  9140. return hsla(color, hsl);
  9141. },
  9142. fadein: function (color, amount, method) {
  9143. var hsl = toHSL(color);
  9144. if (typeof method !== 'undefined' && method.value === 'relative') {
  9145. hsl.a += hsl.a * amount.value / 100;
  9146. }
  9147. else {
  9148. hsl.a += amount.value / 100;
  9149. }
  9150. hsl.a = clamp(hsl.a);
  9151. return hsla(color, hsl);
  9152. },
  9153. fadeout: function (color, amount, method) {
  9154. var hsl = toHSL(color);
  9155. if (typeof method !== 'undefined' && method.value === 'relative') {
  9156. hsl.a -= hsl.a * amount.value / 100;
  9157. }
  9158. else {
  9159. hsl.a -= amount.value / 100;
  9160. }
  9161. hsl.a = clamp(hsl.a);
  9162. return hsla(color, hsl);
  9163. },
  9164. fade: function (color, amount) {
  9165. var hsl = toHSL(color);
  9166. hsl.a = amount.value / 100;
  9167. hsl.a = clamp(hsl.a);
  9168. return hsla(color, hsl);
  9169. },
  9170. spin: function (color, amount) {
  9171. var hsl = toHSL(color);
  9172. var hue = (hsl.h + amount.value) % 360;
  9173. hsl.h = hue < 0 ? 360 + hue : hue;
  9174. return hsla(color, hsl);
  9175. },
  9176. //
  9177. // Copyright (c) 2006-2009 Hampton Catlin, Natalie Weizenbaum, and Chris Eppstein
  9178. // http://sass-lang.com
  9179. //
  9180. mix: function (color1, color2, weight) {
  9181. if (!weight) {
  9182. weight = new Dimension(50);
  9183. }
  9184. var p = weight.value / 100.0;
  9185. var w = p * 2 - 1;
  9186. var a = toHSL(color1).a - toHSL(color2).a;
  9187. var w1 = (((w * a == -1) ? w : (w + a) / (1 + w * a)) + 1) / 2.0;
  9188. var w2 = 1 - w1;
  9189. var rgb = [color1.rgb[0] * w1 + color2.rgb[0] * w2,
  9190. color1.rgb[1] * w1 + color2.rgb[1] * w2,
  9191. color1.rgb[2] * w1 + color2.rgb[2] * w2];
  9192. var alpha = color1.alpha * p + color2.alpha * (1 - p);
  9193. return new Color(rgb, alpha);
  9194. },
  9195. greyscale: function (color) {
  9196. return colorFunctions.desaturate(color, new Dimension(100));
  9197. },
  9198. contrast: function (color, dark, light, threshold) {
  9199. // filter: contrast(3.2);
  9200. // should be kept as is, so check for color
  9201. if (!color.rgb) {
  9202. return null;
  9203. }
  9204. if (typeof light === 'undefined') {
  9205. light = colorFunctions.rgba(255, 255, 255, 1.0);
  9206. }
  9207. if (typeof dark === 'undefined') {
  9208. dark = colorFunctions.rgba(0, 0, 0, 1.0);
  9209. }
  9210. // Figure out which is actually light and dark:
  9211. if (dark.luma() > light.luma()) {
  9212. var t = light;
  9213. light = dark;
  9214. dark = t;
  9215. }
  9216. if (typeof threshold === 'undefined') {
  9217. threshold = 0.43;
  9218. }
  9219. else {
  9220. threshold = number$1(threshold);
  9221. }
  9222. if (color.luma() < threshold) {
  9223. return light;
  9224. }
  9225. else {
  9226. return dark;
  9227. }
  9228. },
  9229. // Changes made in 2.7.0 - Reverted in 3.0.0
  9230. // contrast: function (color, color1, color2, threshold) {
  9231. // // Return which of `color1` and `color2` has the greatest contrast with `color`
  9232. // // according to the standard WCAG contrast ratio calculation.
  9233. // // http://www.w3.org/TR/WCAG20/#contrast-ratiodef
  9234. // // The threshold param is no longer used, in line with SASS.
  9235. // // filter: contrast(3.2);
  9236. // // should be kept as is, so check for color
  9237. // if (!color.rgb) {
  9238. // return null;
  9239. // }
  9240. // if (typeof color1 === 'undefined') {
  9241. // color1 = colorFunctions.rgba(0, 0, 0, 1.0);
  9242. // }
  9243. // if (typeof color2 === 'undefined') {
  9244. // color2 = colorFunctions.rgba(255, 255, 255, 1.0);
  9245. // }
  9246. // var contrast1, contrast2;
  9247. // var luma = color.luma();
  9248. // var luma1 = color1.luma();
  9249. // var luma2 = color2.luma();
  9250. // // Calculate contrast ratios for each color
  9251. // if (luma > luma1) {
  9252. // contrast1 = (luma + 0.05) / (luma1 + 0.05);
  9253. // } else {
  9254. // contrast1 = (luma1 + 0.05) / (luma + 0.05);
  9255. // }
  9256. // if (luma > luma2) {
  9257. // contrast2 = (luma + 0.05) / (luma2 + 0.05);
  9258. // } else {
  9259. // contrast2 = (luma2 + 0.05) / (luma + 0.05);
  9260. // }
  9261. // if (contrast1 > contrast2) {
  9262. // return color1;
  9263. // } else {
  9264. // return color2;
  9265. // }
  9266. // },
  9267. argb: function (color) {
  9268. return new Anonymous(color.toARGB());
  9269. },
  9270. color: function (c) {
  9271. if ((c instanceof Quoted) &&
  9272. (/^#([A-Fa-f0-9]{8}|[A-Fa-f0-9]{6}|[A-Fa-f0-9]{3,4})$/i.test(c.value))) {
  9273. var val = c.value.slice(1);
  9274. return new Color(val, undefined, "#" + val);
  9275. }
  9276. if ((c instanceof Color) || (c = Color.fromKeyword(c.value))) {
  9277. c.value = undefined;
  9278. return c;
  9279. }
  9280. throw {
  9281. type: 'Argument',
  9282. message: 'argument must be a color keyword or 3|4|6|8 digit hex e.g. #FFF'
  9283. };
  9284. },
  9285. tint: function (color, amount) {
  9286. return colorFunctions.mix(colorFunctions.rgb(255, 255, 255), color, amount);
  9287. },
  9288. shade: function (color, amount) {
  9289. return colorFunctions.mix(colorFunctions.rgb(0, 0, 0), color, amount);
  9290. }
  9291. };
  9292. var color = colorFunctions;
  9293. // Color Blending
  9294. // ref: http://www.w3.org/TR/compositing-1
  9295. function colorBlend(mode, color1, color2) {
  9296. var ab = color1.alpha; // result
  9297. var // backdrop
  9298. cb;
  9299. var as = color2.alpha;
  9300. var // source
  9301. cs;
  9302. var ar;
  9303. var cr;
  9304. var r = [];
  9305. ar = as + ab * (1 - as);
  9306. for (var i_1 = 0; i_1 < 3; i_1++) {
  9307. cb = color1.rgb[i_1] / 255;
  9308. cs = color2.rgb[i_1] / 255;
  9309. cr = mode(cb, cs);
  9310. if (ar) {
  9311. cr = (as * cs + ab * (cb -
  9312. as * (cb + cs - cr))) / ar;
  9313. }
  9314. r[i_1] = cr * 255;
  9315. }
  9316. return new Color(r, ar);
  9317. }
  9318. var colorBlendModeFunctions = {
  9319. multiply: function (cb, cs) {
  9320. return cb * cs;
  9321. },
  9322. screen: function (cb, cs) {
  9323. return cb + cs - cb * cs;
  9324. },
  9325. overlay: function (cb, cs) {
  9326. cb *= 2;
  9327. return (cb <= 1) ?
  9328. colorBlendModeFunctions.multiply(cb, cs) :
  9329. colorBlendModeFunctions.screen(cb - 1, cs);
  9330. },
  9331. softlight: function (cb, cs) {
  9332. var d = 1;
  9333. var e = cb;
  9334. if (cs > 0.5) {
  9335. e = 1;
  9336. d = (cb > 0.25) ? Math.sqrt(cb)
  9337. : ((16 * cb - 12) * cb + 4) * cb;
  9338. }
  9339. return cb - (1 - 2 * cs) * e * (d - cb);
  9340. },
  9341. hardlight: function (cb, cs) {
  9342. return colorBlendModeFunctions.overlay(cs, cb);
  9343. },
  9344. difference: function (cb, cs) {
  9345. return Math.abs(cb - cs);
  9346. },
  9347. exclusion: function (cb, cs) {
  9348. return cb + cs - 2 * cb * cs;
  9349. },
  9350. // non-w3c functions:
  9351. average: function (cb, cs) {
  9352. return (cb + cs) / 2;
  9353. },
  9354. negation: function (cb, cs) {
  9355. return 1 - Math.abs(cb + cs - 1);
  9356. }
  9357. };
  9358. for (var f$1 in colorBlendModeFunctions) {
  9359. // eslint-disable-next-line no-prototype-builtins
  9360. if (colorBlendModeFunctions.hasOwnProperty(f$1)) {
  9361. colorBlend[f$1] = colorBlend.bind(null, colorBlendModeFunctions[f$1]);
  9362. }
  9363. }
  9364. var dataUri = (function (environment) {
  9365. var fallback = function (functionThis, node) { return new URL(node, functionThis.index, functionThis.currentFileInfo).eval(functionThis.context); };
  9366. return { 'data-uri': function (mimetypeNode, filePathNode) {
  9367. if (!filePathNode) {
  9368. filePathNode = mimetypeNode;
  9369. mimetypeNode = null;
  9370. }
  9371. var mimetype = mimetypeNode && mimetypeNode.value;
  9372. var filePath = filePathNode.value;
  9373. var currentFileInfo = this.currentFileInfo;
  9374. var currentDirectory = currentFileInfo.rewriteUrls ?
  9375. currentFileInfo.currentDirectory : currentFileInfo.entryPath;
  9376. var fragmentStart = filePath.indexOf('#');
  9377. var fragment = '';
  9378. if (fragmentStart !== -1) {
  9379. fragment = filePath.slice(fragmentStart);
  9380. filePath = filePath.slice(0, fragmentStart);
  9381. }
  9382. var context = clone(this.context);
  9383. context.rawBuffer = true;
  9384. var fileManager = environment.getFileManager(filePath, currentDirectory, context, environment, true);
  9385. if (!fileManager) {
  9386. return fallback(this, filePathNode);
  9387. }
  9388. var useBase64 = false;
  9389. // detect the mimetype if not given
  9390. if (!mimetypeNode) {
  9391. mimetype = environment.mimeLookup(filePath);
  9392. if (mimetype === 'image/svg+xml') {
  9393. useBase64 = false;
  9394. }
  9395. else {
  9396. // use base 64 unless it's an ASCII or UTF-8 format
  9397. var charset = environment.charsetLookup(mimetype);
  9398. useBase64 = ['US-ASCII', 'UTF-8'].indexOf(charset) < 0;
  9399. }
  9400. if (useBase64) {
  9401. mimetype += ';base64';
  9402. }
  9403. }
  9404. else {
  9405. useBase64 = /;base64$/.test(mimetype);
  9406. }
  9407. var fileSync = fileManager.loadFileSync(filePath, currentDirectory, context, environment);
  9408. if (!fileSync.contents) {
  9409. logger$1.warn("Skipped data-uri embedding of " + filePath + " because file not found");
  9410. return fallback(this, filePathNode || mimetypeNode);
  9411. }
  9412. var buf = fileSync.contents;
  9413. if (useBase64 && !environment.encodeBase64) {
  9414. return fallback(this, filePathNode);
  9415. }
  9416. buf = useBase64 ? environment.encodeBase64(buf) : encodeURIComponent(buf);
  9417. var uri = "data:" + mimetype + "," + buf + fragment;
  9418. return new URL(new Quoted("\"" + uri + "\"", uri, false, this.index, this.currentFileInfo), this.index, this.currentFileInfo);
  9419. } };
  9420. });
  9421. var getItemsFromNode = function (node) {
  9422. // handle non-array values as an array of length 1
  9423. // return 'undefined' if index is invalid
  9424. var items = Array.isArray(node.value) ?
  9425. node.value : Array(node);
  9426. return items;
  9427. };
  9428. var list = {
  9429. _SELF: function (n) {
  9430. return n;
  9431. },
  9432. '~': function () {
  9433. var expr = [];
  9434. for (var _i = 0; _i < arguments.length; _i++) {
  9435. expr[_i] = arguments[_i];
  9436. }
  9437. if (expr.length === 1) {
  9438. return expr[0];
  9439. }
  9440. return new Value(expr);
  9441. },
  9442. extract: function (values, index) {
  9443. // (1-based index)
  9444. index = index.value - 1;
  9445. return getItemsFromNode(values)[index];
  9446. },
  9447. length: function (values) {
  9448. return new Dimension(getItemsFromNode(values).length);
  9449. },
  9450. /**
  9451. * Creates a Less list of incremental values.
  9452. * Modeled after Lodash's range function, also exists natively in PHP
  9453. *
  9454. * @param {Dimension} [start=1]
  9455. * @param {Dimension} end - e.g. 10 or 10px - unit is added to output
  9456. * @param {Dimension} [step=1]
  9457. */
  9458. range: function (start, end, step) {
  9459. var from;
  9460. var to;
  9461. var stepValue = 1;
  9462. var list = [];
  9463. if (end) {
  9464. to = end;
  9465. from = start.value;
  9466. if (step) {
  9467. stepValue = step.value;
  9468. }
  9469. }
  9470. else {
  9471. from = 1;
  9472. to = start;
  9473. }
  9474. for (var i_1 = from; i_1 <= to.value; i_1 += stepValue) {
  9475. list.push(new Dimension(i_1, to.unit));
  9476. }
  9477. return new Expression(list);
  9478. },
  9479. each: function (list, rs) {
  9480. var _this = this;
  9481. var rules = [];
  9482. var newRules;
  9483. var iterator;
  9484. var tryEval = function (val) {
  9485. if (val instanceof Node) {
  9486. return val.eval(_this.context);
  9487. }
  9488. return val;
  9489. };
  9490. if (list.value && !(list instanceof Quoted)) {
  9491. if (Array.isArray(list.value)) {
  9492. iterator = list.value.map(tryEval);
  9493. }
  9494. else {
  9495. iterator = [tryEval(list.value)];
  9496. }
  9497. }
  9498. else if (list.ruleset) {
  9499. iterator = tryEval(list.ruleset).rules;
  9500. }
  9501. else if (list.rules) {
  9502. iterator = list.rules.map(tryEval);
  9503. }
  9504. else if (Array.isArray(list)) {
  9505. iterator = list.map(tryEval);
  9506. }
  9507. else {
  9508. iterator = [tryEval(list)];
  9509. }
  9510. var valueName = '@value';
  9511. var keyName = '@key';
  9512. var indexName = '@index';
  9513. if (rs.params) {
  9514. valueName = rs.params[0] && rs.params[0].name;
  9515. keyName = rs.params[1] && rs.params[1].name;
  9516. indexName = rs.params[2] && rs.params[2].name;
  9517. rs = rs.rules;
  9518. }
  9519. else {
  9520. rs = rs.ruleset;
  9521. }
  9522. for (var i_2 = 0; i_2 < iterator.length; i_2++) {
  9523. var key = void 0;
  9524. var value = void 0;
  9525. var item = iterator[i_2];
  9526. if (item instanceof Declaration) {
  9527. key = typeof item.name === 'string' ? item.name : item.name[0].value;
  9528. value = item.value;
  9529. }
  9530. else {
  9531. key = new Dimension(i_2 + 1);
  9532. value = item;
  9533. }
  9534. if (item instanceof Comment) {
  9535. continue;
  9536. }
  9537. newRules = rs.rules.slice(0);
  9538. if (valueName) {
  9539. newRules.push(new Declaration(valueName, value, false, false, this.index, this.currentFileInfo));
  9540. }
  9541. if (indexName) {
  9542. newRules.push(new Declaration(indexName, new Dimension(i_2 + 1), false, false, this.index, this.currentFileInfo));
  9543. }
  9544. if (keyName) {
  9545. newRules.push(new Declaration(keyName, key, false, false, this.index, this.currentFileInfo));
  9546. }
  9547. rules.push(new Ruleset([new (Selector)([new Element('', '&')])], newRules, rs.strictImports, rs.visibilityInfo()));
  9548. }
  9549. return new Ruleset([new (Selector)([new Element('', '&')])], rules, rs.strictImports, rs.visibilityInfo()).eval(this.context);
  9550. }
  9551. };
  9552. var MathHelper = function (fn, unit, n) {
  9553. if (!(n instanceof Dimension)) {
  9554. throw { type: 'Argument', message: 'argument must be a number' };
  9555. }
  9556. if (unit === null) {
  9557. unit = n.unit;
  9558. }
  9559. else {
  9560. n = n.unify();
  9561. }
  9562. return new Dimension(fn(parseFloat(n.value)), unit);
  9563. };
  9564. var mathFunctions = {
  9565. // name, unit
  9566. ceil: null,
  9567. floor: null,
  9568. sqrt: null,
  9569. abs: null,
  9570. tan: '',
  9571. sin: '',
  9572. cos: '',
  9573. atan: 'rad',
  9574. asin: 'rad',
  9575. acos: 'rad'
  9576. };
  9577. for (var f in mathFunctions) {
  9578. // eslint-disable-next-line no-prototype-builtins
  9579. if (mathFunctions.hasOwnProperty(f)) {
  9580. mathFunctions[f] = MathHelper.bind(null, Math[f], mathFunctions[f]);
  9581. }
  9582. }
  9583. mathFunctions.round = function (n, f) {
  9584. var fraction = typeof f === 'undefined' ? 0 : f.value;
  9585. return MathHelper(function (num) { return num.toFixed(fraction); }, null, n);
  9586. };
  9587. var minMax = function (isMin, args) {
  9588. var _this = this;
  9589. args = Array.prototype.slice.call(args);
  9590. switch (args.length) {
  9591. case 0: throw { type: 'Argument', message: 'one or more arguments required' };
  9592. }
  9593. var i; // key is the unit.toString() for unified Dimension values,
  9594. var j;
  9595. var current;
  9596. var currentUnified;
  9597. var referenceUnified;
  9598. var unit;
  9599. var unitStatic;
  9600. var unitClone;
  9601. var // elems only contains original argument values.
  9602. order = [];
  9603. var values = {};
  9604. // value is the index into the order array.
  9605. for (i = 0; i < args.length; i++) {
  9606. current = args[i];
  9607. if (!(current instanceof Dimension)) {
  9608. if (Array.isArray(args[i].value)) {
  9609. Array.prototype.push.apply(args, Array.prototype.slice.call(args[i].value));
  9610. }
  9611. continue;
  9612. }
  9613. currentUnified = current.unit.toString() === '' && unitClone !== undefined ? new Dimension(current.value, unitClone).unify() : current.unify();
  9614. unit = currentUnified.unit.toString() === '' && unitStatic !== undefined ? unitStatic : currentUnified.unit.toString();
  9615. unitStatic = unit !== '' && unitStatic === undefined || unit !== '' && order[0].unify().unit.toString() === '' ? unit : unitStatic;
  9616. unitClone = unit !== '' && unitClone === undefined ? current.unit.toString() : unitClone;
  9617. j = values[''] !== undefined && unit !== '' && unit === unitStatic ? values[''] : values[unit];
  9618. if (j === undefined) {
  9619. if (unitStatic !== undefined && unit !== unitStatic) {
  9620. throw { type: 'Argument', message: 'incompatible types' };
  9621. }
  9622. values[unit] = order.length;
  9623. order.push(current);
  9624. continue;
  9625. }
  9626. referenceUnified = order[j].unit.toString() === '' && unitClone !== undefined ? new Dimension(order[j].value, unitClone).unify() : order[j].unify();
  9627. if (isMin && currentUnified.value < referenceUnified.value ||
  9628. !isMin && currentUnified.value > referenceUnified.value) {
  9629. order[j] = current;
  9630. }
  9631. }
  9632. if (order.length == 1) {
  9633. return order[0];
  9634. }
  9635. args = order.map(function (a) { return a.toCSS(_this.context); }).join(this.context.compress ? ',' : ', ');
  9636. return new Anonymous((isMin ? 'min' : 'max') + "(" + args + ")");
  9637. };
  9638. var number = {
  9639. min: function () {
  9640. var args = [];
  9641. for (var _i = 0; _i < arguments.length; _i++) {
  9642. args[_i] = arguments[_i];
  9643. }
  9644. try {
  9645. return minMax.call(this, true, args);
  9646. }
  9647. catch (e) { }
  9648. },
  9649. max: function () {
  9650. var args = [];
  9651. for (var _i = 0; _i < arguments.length; _i++) {
  9652. args[_i] = arguments[_i];
  9653. }
  9654. try {
  9655. return minMax.call(this, false, args);
  9656. }
  9657. catch (e) { }
  9658. },
  9659. convert: function (val, unit) {
  9660. return val.convertTo(unit.value);
  9661. },
  9662. pi: function () {
  9663. return new Dimension(Math.PI);
  9664. },
  9665. mod: function (a, b) {
  9666. return new Dimension(a.value % b.value, a.unit);
  9667. },
  9668. pow: function (x, y) {
  9669. if (typeof x === 'number' && typeof y === 'number') {
  9670. x = new Dimension(x);
  9671. y = new Dimension(y);
  9672. }
  9673. else if (!(x instanceof Dimension) || !(y instanceof Dimension)) {
  9674. throw { type: 'Argument', message: 'arguments must be numbers' };
  9675. }
  9676. return new Dimension(Math.pow(x.value, y.value), x.unit);
  9677. },
  9678. percentage: function (n) {
  9679. var result = MathHelper(function (num) { return num * 100; }, '%', n);
  9680. return result;
  9681. }
  9682. };
  9683. var string = {
  9684. e: function (str) {
  9685. return new Quoted('"', str instanceof JavaScript ? str.evaluated : str.value, true);
  9686. },
  9687. escape: function (str) {
  9688. return new Anonymous(encodeURI(str.value).replace(/=/g, '%3D').replace(/:/g, '%3A').replace(/#/g, '%23').replace(/;/g, '%3B')
  9689. .replace(/\(/g, '%28').replace(/\)/g, '%29'));
  9690. },
  9691. replace: function (string, pattern, replacement, flags) {
  9692. var result = string.value;
  9693. replacement = (replacement.type === 'Quoted') ?
  9694. replacement.value : replacement.toCSS();
  9695. result = result.replace(new RegExp(pattern.value, flags ? flags.value : ''), replacement);
  9696. return new Quoted(string.quote || '', result, string.escaped);
  9697. },
  9698. '%': function (string /* arg, arg, ... */) {
  9699. var args = Array.prototype.slice.call(arguments, 1);
  9700. var result = string.value;
  9701. var _loop_1 = function (i_1) {
  9702. /* jshint loopfunc:true */
  9703. result = result.replace(/%[sda]/i, function (token) {
  9704. var value = ((args[i_1].type === 'Quoted') &&
  9705. token.match(/s/i)) ? args[i_1].value : args[i_1].toCSS();
  9706. return token.match(/[A-Z]$/) ? encodeURIComponent(value) : value;
  9707. });
  9708. };
  9709. for (var i_1 = 0; i_1 < args.length; i_1++) {
  9710. _loop_1(i_1);
  9711. }
  9712. result = result.replace(/%%/g, '%');
  9713. return new Quoted(string.quote || '', result, string.escaped);
  9714. }
  9715. };
  9716. var svg = (function () {
  9717. return { 'svg-gradient': function (direction) {
  9718. var stops;
  9719. var gradientDirectionSvg;
  9720. var gradientType = 'linear';
  9721. var rectangleDimension = 'x="0" y="0" width="1" height="1"';
  9722. var renderEnv = { compress: false };
  9723. var returner;
  9724. var directionValue = direction.toCSS(renderEnv);
  9725. var i;
  9726. var color;
  9727. var position;
  9728. var positionValue;
  9729. var alpha;
  9730. function throwArgumentDescriptor() {
  9731. throw { type: 'Argument',
  9732. message: 'svg-gradient expects direction, start_color [start_position], [color position,]...,' +
  9733. ' end_color [end_position] or direction, color list' };
  9734. }
  9735. if (arguments.length == 2) {
  9736. if (arguments[1].value.length < 2) {
  9737. throwArgumentDescriptor();
  9738. }
  9739. stops = arguments[1].value;
  9740. }
  9741. else if (arguments.length < 3) {
  9742. throwArgumentDescriptor();
  9743. }
  9744. else {
  9745. stops = Array.prototype.slice.call(arguments, 1);
  9746. }
  9747. switch (directionValue) {
  9748. case 'to bottom':
  9749. gradientDirectionSvg = 'x1="0%" y1="0%" x2="0%" y2="100%"';
  9750. break;
  9751. case 'to right':
  9752. gradientDirectionSvg = 'x1="0%" y1="0%" x2="100%" y2="0%"';
  9753. break;
  9754. case 'to bottom right':
  9755. gradientDirectionSvg = 'x1="0%" y1="0%" x2="100%" y2="100%"';
  9756. break;
  9757. case 'to top right':
  9758. gradientDirectionSvg = 'x1="0%" y1="100%" x2="100%" y2="0%"';
  9759. break;
  9760. case 'ellipse':
  9761. case 'ellipse at center':
  9762. gradientType = 'radial';
  9763. gradientDirectionSvg = 'cx="50%" cy="50%" r="75%"';
  9764. rectangleDimension = 'x="-50" y="-50" width="101" height="101"';
  9765. break;
  9766. default:
  9767. throw { type: 'Argument', message: 'svg-gradient direction must be \'to bottom\', \'to right\',' +
  9768. ' \'to bottom right\', \'to top right\' or \'ellipse at center\'' };
  9769. }
  9770. returner = "<svg xmlns=\"http://www.w3.org/2000/svg\" viewBox=\"0 0 1 1\"><" + gradientType + "Gradient id=\"g\" " + gradientDirectionSvg + ">";
  9771. for (i = 0; i < stops.length; i += 1) {
  9772. if (stops[i] instanceof Expression) {
  9773. color = stops[i].value[0];
  9774. position = stops[i].value[1];
  9775. }
  9776. else {
  9777. color = stops[i];
  9778. position = undefined;
  9779. }
  9780. if (!(color instanceof Color) || (!((i === 0 || i + 1 === stops.length) && position === undefined) && !(position instanceof Dimension))) {
  9781. throwArgumentDescriptor();
  9782. }
  9783. positionValue = position ? position.toCSS(renderEnv) : i === 0 ? '0%' : '100%';
  9784. alpha = color.alpha;
  9785. returner += "<stop offset=\"" + positionValue + "\" stop-color=\"" + color.toRGB() + "\"" + (alpha < 1 ? " stop-opacity=\"" + alpha + "\"" : '') + "/>";
  9786. }
  9787. returner += "</" + gradientType + "Gradient><rect " + rectangleDimension + " fill=\"url(#g)\" /></svg>";
  9788. returner = encodeURIComponent(returner);
  9789. returner = "data:image/svg+xml," + returner;
  9790. return new URL(new Quoted("'" + returner + "'", returner, false, this.index, this.currentFileInfo), this.index, this.currentFileInfo);
  9791. } };
  9792. });
  9793. var isa = function (n, Type) { return (n instanceof Type) ? Keyword.True : Keyword.False; };
  9794. var isunit = function (n, unit) {
  9795. if (unit === undefined) {
  9796. throw { type: 'Argument', message: 'missing the required second argument to isunit.' };
  9797. }
  9798. unit = typeof unit.value === 'string' ? unit.value : unit;
  9799. if (typeof unit !== 'string') {
  9800. throw { type: 'Argument', message: 'Second argument to isunit should be a unit or a string.' };
  9801. }
  9802. return (n instanceof Dimension) && n.unit.is(unit) ? Keyword.True : Keyword.False;
  9803. };
  9804. var types = {
  9805. isruleset: function (n) {
  9806. return isa(n, DetachedRuleset);
  9807. },
  9808. iscolor: function (n) {
  9809. return isa(n, Color);
  9810. },
  9811. isnumber: function (n) {
  9812. return isa(n, Dimension);
  9813. },
  9814. isstring: function (n) {
  9815. return isa(n, Quoted);
  9816. },
  9817. iskeyword: function (n) {
  9818. return isa(n, Keyword);
  9819. },
  9820. isurl: function (n) {
  9821. return isa(n, URL);
  9822. },
  9823. ispixel: function (n) {
  9824. return isunit(n, 'px');
  9825. },
  9826. ispercentage: function (n) {
  9827. return isunit(n, '%');
  9828. },
  9829. isem: function (n) {
  9830. return isunit(n, 'em');
  9831. },
  9832. isunit: isunit,
  9833. unit: function (val, unit) {
  9834. if (!(val instanceof Dimension)) {
  9835. throw { type: 'Argument',
  9836. message: "the first argument to unit must be a number" + (val instanceof Operation ? '. Have you forgotten parenthesis?' : '') };
  9837. }
  9838. if (unit) {
  9839. if (unit instanceof Keyword) {
  9840. unit = unit.value;
  9841. }
  9842. else {
  9843. unit = unit.toCSS();
  9844. }
  9845. }
  9846. else {
  9847. unit = '';
  9848. }
  9849. return new Dimension(val.value, unit);
  9850. },
  9851. 'get-unit': function (n) {
  9852. return new Anonymous(n.unit);
  9853. }
  9854. };
  9855. var functions = (function (environment) {
  9856. var functions = { functionRegistry: functionRegistry, functionCaller: functionCaller };
  9857. // register functions
  9858. functionRegistry.addMultiple(boolean$1);
  9859. functionRegistry.add('default', defaultFunc.eval.bind(defaultFunc));
  9860. functionRegistry.addMultiple(color);
  9861. functionRegistry.addMultiple(colorBlend);
  9862. functionRegistry.addMultiple(dataUri(environment));
  9863. functionRegistry.addMultiple(list);
  9864. functionRegistry.addMultiple(mathFunctions);
  9865. functionRegistry.addMultiple(number);
  9866. functionRegistry.addMultiple(string);
  9867. functionRegistry.addMultiple(svg());
  9868. functionRegistry.addMultiple(types);
  9869. return functions;
  9870. });
  9871. function transformTree (root, options) {
  9872. options = options || {};
  9873. var evaldRoot;
  9874. var variables = options.variables;
  9875. var evalEnv = new contexts.Eval(options);
  9876. //
  9877. // Allows setting variables with a hash, so:
  9878. //
  9879. // `{ color: new tree.Color('#f01') }` will become:
  9880. //
  9881. // new tree.Declaration('@color',
  9882. // new tree.Value([
  9883. // new tree.Expression([
  9884. // new tree.Color('#f01')
  9885. // ])
  9886. // ])
  9887. // )
  9888. //
  9889. if (typeof variables === 'object' && !Array.isArray(variables)) {
  9890. variables = Object.keys(variables).map(function (k) {
  9891. var value = variables[k];
  9892. if (!(value instanceof tree.Value)) {
  9893. if (!(value instanceof tree.Expression)) {
  9894. value = new tree.Expression([value]);
  9895. }
  9896. value = new tree.Value([value]);
  9897. }
  9898. return new tree.Declaration("@" + k, value, false, null, 0);
  9899. });
  9900. evalEnv.frames = [new tree.Ruleset(null, variables)];
  9901. }
  9902. var visitors$1 = [
  9903. new visitors.JoinSelectorVisitor(),
  9904. new visitors.MarkVisibleSelectorsVisitor(true),
  9905. new visitors.ExtendVisitor(),
  9906. new visitors.ToCSSVisitor({ compress: Boolean(options.compress) })
  9907. ];
  9908. var preEvalVisitors = [];
  9909. var v;
  9910. var visitorIterator;
  9911. /**
  9912. * first() / get() allows visitors to be added while visiting
  9913. *
  9914. * @todo Add scoping for visitors just like functions for @plugin; right now they're global
  9915. */
  9916. if (options.pluginManager) {
  9917. visitorIterator = options.pluginManager.visitor();
  9918. for (var i_1 = 0; i_1 < 2; i_1++) {
  9919. visitorIterator.first();
  9920. while ((v = visitorIterator.get())) {
  9921. if (v.isPreEvalVisitor) {
  9922. if (i_1 === 0 || preEvalVisitors.indexOf(v) === -1) {
  9923. preEvalVisitors.push(v);
  9924. v.run(root);
  9925. }
  9926. }
  9927. else {
  9928. if (i_1 === 0 || visitors$1.indexOf(v) === -1) {
  9929. if (v.isPreVisitor) {
  9930. visitors$1.unshift(v);
  9931. }
  9932. else {
  9933. visitors$1.push(v);
  9934. }
  9935. }
  9936. }
  9937. }
  9938. }
  9939. }
  9940. evaldRoot = root.eval(evalEnv);
  9941. for (var i_2 = 0; i_2 < visitors$1.length; i_2++) {
  9942. visitors$1[i_2].run(evaldRoot);
  9943. }
  9944. // Run any remaining visitors added after eval pass
  9945. if (options.pluginManager) {
  9946. visitorIterator.first();
  9947. while ((v = visitorIterator.get())) {
  9948. if (visitors$1.indexOf(v) === -1 && preEvalVisitors.indexOf(v) === -1) {
  9949. v.run(evaldRoot);
  9950. }
  9951. }
  9952. }
  9953. return evaldRoot;
  9954. }
  9955. /**
  9956. * Plugin Manager
  9957. */
  9958. var PluginManager = /** @class */ (function () {
  9959. function PluginManager(less) {
  9960. this.less = less;
  9961. this.visitors = [];
  9962. this.preProcessors = [];
  9963. this.postProcessors = [];
  9964. this.installedPlugins = [];
  9965. this.fileManagers = [];
  9966. this.iterator = -1;
  9967. this.pluginCache = {};
  9968. this.Loader = new less.PluginLoader(less);
  9969. }
  9970. /**
  9971. * Adds all the plugins in the array
  9972. * @param {Array} plugins
  9973. */
  9974. PluginManager.prototype.addPlugins = function (plugins) {
  9975. if (plugins) {
  9976. for (var i_1 = 0; i_1 < plugins.length; i_1++) {
  9977. this.addPlugin(plugins[i_1]);
  9978. }
  9979. }
  9980. };
  9981. /**
  9982. *
  9983. * @param plugin
  9984. * @param {String} filename
  9985. */
  9986. PluginManager.prototype.addPlugin = function (plugin, filename, functionRegistry) {
  9987. this.installedPlugins.push(plugin);
  9988. if (filename) {
  9989. this.pluginCache[filename] = plugin;
  9990. }
  9991. if (plugin.install) {
  9992. plugin.install(this.less, this, functionRegistry || this.less.functions.functionRegistry);
  9993. }
  9994. };
  9995. /**
  9996. *
  9997. * @param filename
  9998. */
  9999. PluginManager.prototype.get = function (filename) {
  10000. return this.pluginCache[filename];
  10001. };
  10002. /**
  10003. * Adds a visitor. The visitor object has options on itself to determine
  10004. * when it should run.
  10005. * @param visitor
  10006. */
  10007. PluginManager.prototype.addVisitor = function (visitor) {
  10008. this.visitors.push(visitor);
  10009. };
  10010. /**
  10011. * Adds a pre processor object
  10012. * @param {object} preProcessor
  10013. * @param {number} priority - guidelines 1 = before import, 1000 = import, 2000 = after import
  10014. */
  10015. PluginManager.prototype.addPreProcessor = function (preProcessor, priority) {
  10016. var indexToInsertAt;
  10017. for (indexToInsertAt = 0; indexToInsertAt < this.preProcessors.length; indexToInsertAt++) {
  10018. if (this.preProcessors[indexToInsertAt].priority >= priority) {
  10019. break;
  10020. }
  10021. }
  10022. this.preProcessors.splice(indexToInsertAt, 0, { preProcessor: preProcessor, priority: priority });
  10023. };
  10024. /**
  10025. * Adds a post processor object
  10026. * @param {object} postProcessor
  10027. * @param {number} priority - guidelines 1 = before compression, 1000 = compression, 2000 = after compression
  10028. */
  10029. PluginManager.prototype.addPostProcessor = function (postProcessor, priority) {
  10030. var indexToInsertAt;
  10031. for (indexToInsertAt = 0; indexToInsertAt < this.postProcessors.length; indexToInsertAt++) {
  10032. if (this.postProcessors[indexToInsertAt].priority >= priority) {
  10033. break;
  10034. }
  10035. }
  10036. this.postProcessors.splice(indexToInsertAt, 0, { postProcessor: postProcessor, priority: priority });
  10037. };
  10038. /**
  10039. *
  10040. * @param manager
  10041. */
  10042. PluginManager.prototype.addFileManager = function (manager) {
  10043. this.fileManagers.push(manager);
  10044. };
  10045. /**
  10046. *
  10047. * @returns {Array}
  10048. * @private
  10049. */
  10050. PluginManager.prototype.getPreProcessors = function () {
  10051. var preProcessors = [];
  10052. for (var i_2 = 0; i_2 < this.preProcessors.length; i_2++) {
  10053. preProcessors.push(this.preProcessors[i_2].preProcessor);
  10054. }
  10055. return preProcessors;
  10056. };
  10057. /**
  10058. *
  10059. * @returns {Array}
  10060. * @private
  10061. */
  10062. PluginManager.prototype.getPostProcessors = function () {
  10063. var postProcessors = [];
  10064. for (var i_3 = 0; i_3 < this.postProcessors.length; i_3++) {
  10065. postProcessors.push(this.postProcessors[i_3].postProcessor);
  10066. }
  10067. return postProcessors;
  10068. };
  10069. /**
  10070. *
  10071. * @returns {Array}
  10072. * @private
  10073. */
  10074. PluginManager.prototype.getVisitors = function () {
  10075. return this.visitors;
  10076. };
  10077. PluginManager.prototype.visitor = function () {
  10078. var self = this;
  10079. return {
  10080. first: function () {
  10081. self.iterator = -1;
  10082. return self.visitors[self.iterator];
  10083. },
  10084. get: function () {
  10085. self.iterator += 1;
  10086. return self.visitors[self.iterator];
  10087. }
  10088. };
  10089. };
  10090. /**
  10091. *
  10092. * @returns {Array}
  10093. * @private
  10094. */
  10095. PluginManager.prototype.getFileManagers = function () {
  10096. return this.fileManagers;
  10097. };
  10098. return PluginManager;
  10099. }());
  10100. var pm;
  10101. var PluginManagerFactory = function (less, newFactory) {
  10102. if (newFactory || !pm) {
  10103. pm = new PluginManager(less);
  10104. }
  10105. return pm;
  10106. };
  10107. function SourceMapOutput (environment) {
  10108. var SourceMapOutput = /** @class */ (function () {
  10109. function SourceMapOutput(options) {
  10110. this._css = [];
  10111. this._rootNode = options.rootNode;
  10112. this._contentsMap = options.contentsMap;
  10113. this._contentsIgnoredCharsMap = options.contentsIgnoredCharsMap;
  10114. if (options.sourceMapFilename) {
  10115. this._sourceMapFilename = options.sourceMapFilename.replace(/\\/g, '/');
  10116. }
  10117. this._outputFilename = options.outputFilename;
  10118. this.sourceMapURL = options.sourceMapURL;
  10119. if (options.sourceMapBasepath) {
  10120. this._sourceMapBasepath = options.sourceMapBasepath.replace(/\\/g, '/');
  10121. }
  10122. if (options.sourceMapRootpath) {
  10123. this._sourceMapRootpath = options.sourceMapRootpath.replace(/\\/g, '/');
  10124. if (this._sourceMapRootpath.charAt(this._sourceMapRootpath.length - 1) !== '/') {
  10125. this._sourceMapRootpath += '/';
  10126. }
  10127. }
  10128. else {
  10129. this._sourceMapRootpath = '';
  10130. }
  10131. this._outputSourceFiles = options.outputSourceFiles;
  10132. this._sourceMapGeneratorConstructor = environment.getSourceMapGenerator();
  10133. this._lineNumber = 0;
  10134. this._column = 0;
  10135. }
  10136. SourceMapOutput.prototype.removeBasepath = function (path) {
  10137. if (this._sourceMapBasepath && path.indexOf(this._sourceMapBasepath) === 0) {
  10138. path = path.substring(this._sourceMapBasepath.length);
  10139. if (path.charAt(0) === '\\' || path.charAt(0) === '/') {
  10140. path = path.substring(1);
  10141. }
  10142. }
  10143. return path;
  10144. };
  10145. SourceMapOutput.prototype.normalizeFilename = function (filename) {
  10146. filename = filename.replace(/\\/g, '/');
  10147. filename = this.removeBasepath(filename);
  10148. return (this._sourceMapRootpath || '') + filename;
  10149. };
  10150. SourceMapOutput.prototype.add = function (chunk, fileInfo, index, mapLines) {
  10151. // ignore adding empty strings
  10152. if (!chunk) {
  10153. return;
  10154. }
  10155. var lines, sourceLines, columns, sourceColumns, i;
  10156. if (fileInfo && fileInfo.filename) {
  10157. var inputSource = this._contentsMap[fileInfo.filename];
  10158. // remove vars/banner added to the top of the file
  10159. if (this._contentsIgnoredCharsMap[fileInfo.filename]) {
  10160. // adjust the index
  10161. index -= this._contentsIgnoredCharsMap[fileInfo.filename];
  10162. if (index < 0) {
  10163. index = 0;
  10164. }
  10165. // adjust the source
  10166. inputSource = inputSource.slice(this._contentsIgnoredCharsMap[fileInfo.filename]);
  10167. }
  10168. /**
  10169. * ignore empty content, or failsafe
  10170. * if contents map is incorrect
  10171. */
  10172. if (inputSource === undefined) {
  10173. this._css.push(chunk);
  10174. return;
  10175. }
  10176. inputSource = inputSource.substring(0, index);
  10177. sourceLines = inputSource.split('\n');
  10178. sourceColumns = sourceLines[sourceLines.length - 1];
  10179. }
  10180. lines = chunk.split('\n');
  10181. columns = lines[lines.length - 1];
  10182. if (fileInfo && fileInfo.filename) {
  10183. if (!mapLines) {
  10184. this._sourceMapGenerator.addMapping({ generated: { line: this._lineNumber + 1, column: this._column },
  10185. original: { line: sourceLines.length, column: sourceColumns.length },
  10186. source: this.normalizeFilename(fileInfo.filename) });
  10187. }
  10188. else {
  10189. for (i = 0; i < lines.length; i++) {
  10190. this._sourceMapGenerator.addMapping({ generated: { line: this._lineNumber + i + 1, column: i === 0 ? this._column : 0 },
  10191. original: { line: sourceLines.length + i, column: i === 0 ? sourceColumns.length : 0 },
  10192. source: this.normalizeFilename(fileInfo.filename) });
  10193. }
  10194. }
  10195. }
  10196. if (lines.length === 1) {
  10197. this._column += columns.length;
  10198. }
  10199. else {
  10200. this._lineNumber += lines.length - 1;
  10201. this._column = columns.length;
  10202. }
  10203. this._css.push(chunk);
  10204. };
  10205. SourceMapOutput.prototype.isEmpty = function () {
  10206. return this._css.length === 0;
  10207. };
  10208. SourceMapOutput.prototype.toCSS = function (context) {
  10209. this._sourceMapGenerator = new this._sourceMapGeneratorConstructor({ file: this._outputFilename, sourceRoot: null });
  10210. if (this._outputSourceFiles) {
  10211. for (var filename in this._contentsMap) {
  10212. // eslint-disable-next-line no-prototype-builtins
  10213. if (this._contentsMap.hasOwnProperty(filename)) {
  10214. var source = this._contentsMap[filename];
  10215. if (this._contentsIgnoredCharsMap[filename]) {
  10216. source = source.slice(this._contentsIgnoredCharsMap[filename]);
  10217. }
  10218. this._sourceMapGenerator.setSourceContent(this.normalizeFilename(filename), source);
  10219. }
  10220. }
  10221. }
  10222. this._rootNode.genCSS(context, this);
  10223. if (this._css.length > 0) {
  10224. var sourceMapURL = void 0;
  10225. var sourceMapContent = JSON.stringify(this._sourceMapGenerator.toJSON());
  10226. if (this.sourceMapURL) {
  10227. sourceMapURL = this.sourceMapURL;
  10228. }
  10229. else if (this._sourceMapFilename) {
  10230. sourceMapURL = this._sourceMapFilename;
  10231. }
  10232. this.sourceMapURL = sourceMapURL;
  10233. this.sourceMap = sourceMapContent;
  10234. }
  10235. return this._css.join('');
  10236. };
  10237. return SourceMapOutput;
  10238. }());
  10239. return SourceMapOutput;
  10240. }
  10241. function SourceMapBuilder (SourceMapOutput, environment) {
  10242. var SourceMapBuilder = /** @class */ (function () {
  10243. function SourceMapBuilder(options) {
  10244. this.options = options;
  10245. }
  10246. SourceMapBuilder.prototype.toCSS = function (rootNode, options, imports) {
  10247. var sourceMapOutput = new SourceMapOutput({
  10248. contentsIgnoredCharsMap: imports.contentsIgnoredChars,
  10249. rootNode: rootNode,
  10250. contentsMap: imports.contents,
  10251. sourceMapFilename: this.options.sourceMapFilename,
  10252. sourceMapURL: this.options.sourceMapURL,
  10253. outputFilename: this.options.sourceMapOutputFilename,
  10254. sourceMapBasepath: this.options.sourceMapBasepath,
  10255. sourceMapRootpath: this.options.sourceMapRootpath,
  10256. outputSourceFiles: this.options.outputSourceFiles,
  10257. sourceMapGenerator: this.options.sourceMapGenerator,
  10258. sourceMapFileInline: this.options.sourceMapFileInline,
  10259. disableSourcemapAnnotation: this.options.disableSourcemapAnnotation
  10260. });
  10261. var css = sourceMapOutput.toCSS(options);
  10262. this.sourceMap = sourceMapOutput.sourceMap;
  10263. this.sourceMapURL = sourceMapOutput.sourceMapURL;
  10264. if (this.options.sourceMapInputFilename) {
  10265. this.sourceMapInputFilename = sourceMapOutput.normalizeFilename(this.options.sourceMapInputFilename);
  10266. }
  10267. if (this.options.sourceMapBasepath !== undefined && this.sourceMapURL !== undefined) {
  10268. this.sourceMapURL = sourceMapOutput.removeBasepath(this.sourceMapURL);
  10269. }
  10270. return css + this.getCSSAppendage();
  10271. };
  10272. SourceMapBuilder.prototype.getCSSAppendage = function () {
  10273. var sourceMapURL = this.sourceMapURL;
  10274. if (this.options.sourceMapFileInline) {
  10275. if (this.sourceMap === undefined) {
  10276. return '';
  10277. }
  10278. sourceMapURL = "data:application/json;base64," + environment.encodeBase64(this.sourceMap);
  10279. }
  10280. if (this.options.disableSourcemapAnnotation) {
  10281. return '';
  10282. }
  10283. if (sourceMapURL) {
  10284. return "/*# sourceMappingURL=" + sourceMapURL + " */";
  10285. }
  10286. return '';
  10287. };
  10288. SourceMapBuilder.prototype.getExternalSourceMap = function () {
  10289. return this.sourceMap;
  10290. };
  10291. SourceMapBuilder.prototype.setExternalSourceMap = function (sourceMap) {
  10292. this.sourceMap = sourceMap;
  10293. };
  10294. SourceMapBuilder.prototype.isInline = function () {
  10295. return this.options.sourceMapFileInline;
  10296. };
  10297. SourceMapBuilder.prototype.getSourceMapURL = function () {
  10298. return this.sourceMapURL;
  10299. };
  10300. SourceMapBuilder.prototype.getOutputFilename = function () {
  10301. return this.options.sourceMapOutputFilename;
  10302. };
  10303. SourceMapBuilder.prototype.getInputFilename = function () {
  10304. return this.sourceMapInputFilename;
  10305. };
  10306. return SourceMapBuilder;
  10307. }());
  10308. return SourceMapBuilder;
  10309. }
  10310. function ParseTree (SourceMapBuilder) {
  10311. var ParseTree = /** @class */ (function () {
  10312. function ParseTree(root, imports) {
  10313. this.root = root;
  10314. this.imports = imports;
  10315. }
  10316. ParseTree.prototype.toCSS = function (options) {
  10317. var evaldRoot;
  10318. var result = {};
  10319. var sourceMapBuilder;
  10320. try {
  10321. evaldRoot = transformTree(this.root, options);
  10322. }
  10323. catch (e) {
  10324. throw new LessError(e, this.imports);
  10325. }
  10326. try {
  10327. var compress = Boolean(options.compress);
  10328. if (compress) {
  10329. logger$1.warn('The compress option has been deprecated. ' +
  10330. 'We recommend you use a dedicated css minifier, for instance see less-plugin-clean-css.');
  10331. }
  10332. var toCSSOptions = {
  10333. compress: compress,
  10334. dumpLineNumbers: options.dumpLineNumbers,
  10335. strictUnits: Boolean(options.strictUnits),
  10336. numPrecision: 8
  10337. };
  10338. if (options.sourceMap) {
  10339. sourceMapBuilder = new SourceMapBuilder(options.sourceMap);
  10340. result.css = sourceMapBuilder.toCSS(evaldRoot, toCSSOptions, this.imports);
  10341. }
  10342. else {
  10343. result.css = evaldRoot.toCSS(toCSSOptions);
  10344. }
  10345. }
  10346. catch (e) {
  10347. throw new LessError(e, this.imports);
  10348. }
  10349. if (options.pluginManager) {
  10350. var postProcessors = options.pluginManager.getPostProcessors();
  10351. for (var i_1 = 0; i_1 < postProcessors.length; i_1++) {
  10352. result.css = postProcessors[i_1].process(result.css, { sourceMap: sourceMapBuilder, options: options, imports: this.imports });
  10353. }
  10354. }
  10355. if (options.sourceMap) {
  10356. result.map = sourceMapBuilder.getExternalSourceMap();
  10357. }
  10358. result.imports = [];
  10359. for (var file_1 in this.imports.files) {
  10360. if (Object.prototype.hasOwnProperty.call(this.imports.files, file_1) && file_1 !== this.imports.rootFilename) {
  10361. result.imports.push(file_1);
  10362. }
  10363. }
  10364. return result;
  10365. };
  10366. return ParseTree;
  10367. }());
  10368. return ParseTree;
  10369. }
  10370. function ImportManager (environment) {
  10371. // FileInfo = {
  10372. // 'rewriteUrls' - option - whether to adjust URL's to be relative
  10373. // 'filename' - full resolved filename of current file
  10374. // 'rootpath' - path to append to normal URLs for this node
  10375. // 'currentDirectory' - path to the current file, absolute
  10376. // 'rootFilename' - filename of the base file
  10377. // 'entryPath' - absolute path to the entry file
  10378. // 'reference' - whether the file should not be output and only output parts that are referenced
  10379. var ImportManager = /** @class */ (function () {
  10380. function ImportManager(less, context, rootFileInfo) {
  10381. this.less = less;
  10382. this.rootFilename = rootFileInfo.filename;
  10383. this.paths = context.paths || []; // Search paths, when importing
  10384. this.contents = {}; // map - filename to contents of all the files
  10385. this.contentsIgnoredChars = {}; // map - filename to lines at the beginning of each file to ignore
  10386. this.mime = context.mime;
  10387. this.error = null;
  10388. this.context = context;
  10389. // Deprecated? Unused outside of here, could be useful.
  10390. this.queue = []; // Files which haven't been imported yet
  10391. this.files = {}; // Holds the imported parse trees.
  10392. }
  10393. /**
  10394. * Add an import to be imported
  10395. * @param path - the raw path
  10396. * @param tryAppendExtension - whether to try appending a file extension (.less or .js if the path has no extension)
  10397. * @param currentFileInfo - the current file info (used for instance to work out relative paths)
  10398. * @param importOptions - import options
  10399. * @param callback - callback for when it is imported
  10400. */
  10401. ImportManager.prototype.push = function (path, tryAppendExtension, currentFileInfo, importOptions, callback) {
  10402. var importManager = this, pluginLoader = this.context.pluginManager.Loader;
  10403. this.queue.push(path);
  10404. var fileParsedFunc = function (e, root, fullPath) {
  10405. importManager.queue.splice(importManager.queue.indexOf(path), 1); // Remove the path from the queue
  10406. var importedEqualsRoot = fullPath === importManager.rootFilename;
  10407. if (importOptions.optional && e) {
  10408. callback(null, { rules: [] }, false, null);
  10409. logger$1.info("The file " + fullPath + " was skipped because it was not found and the import was marked optional.");
  10410. }
  10411. else {
  10412. // Inline imports aren't cached here.
  10413. // If we start to cache them, please make sure they won't conflict with non-inline imports of the
  10414. // same name as they used to do before this comment and the condition below have been added.
  10415. if (!importManager.files[fullPath] && !importOptions.inline) {
  10416. importManager.files[fullPath] = { root: root, options: importOptions };
  10417. }
  10418. if (e && !importManager.error) {
  10419. importManager.error = e;
  10420. }
  10421. callback(e, root, importedEqualsRoot, fullPath);
  10422. }
  10423. };
  10424. var newFileInfo = {
  10425. rewriteUrls: this.context.rewriteUrls,
  10426. entryPath: currentFileInfo.entryPath,
  10427. rootpath: currentFileInfo.rootpath,
  10428. rootFilename: currentFileInfo.rootFilename
  10429. };
  10430. var fileManager = environment.getFileManager(path, currentFileInfo.currentDirectory, this.context, environment);
  10431. if (!fileManager) {
  10432. fileParsedFunc({ message: "Could not find a file-manager for " + path });
  10433. return;
  10434. }
  10435. var loadFileCallback = function (loadedFile) {
  10436. var plugin;
  10437. var resolvedFilename = loadedFile.filename;
  10438. var contents = loadedFile.contents.replace(/^\uFEFF/, '');
  10439. // Pass on an updated rootpath if path of imported file is relative and file
  10440. // is in a (sub|sup) directory
  10441. //
  10442. // Examples:
  10443. // - If path of imported file is 'module/nav/nav.less' and rootpath is 'less/',
  10444. // then rootpath should become 'less/module/nav/'
  10445. // - If path of imported file is '../mixins.less' and rootpath is 'less/',
  10446. // then rootpath should become 'less/../'
  10447. newFileInfo.currentDirectory = fileManager.getPath(resolvedFilename);
  10448. if (newFileInfo.rewriteUrls) {
  10449. newFileInfo.rootpath = fileManager.join((importManager.context.rootpath || ''), fileManager.pathDiff(newFileInfo.currentDirectory, newFileInfo.entryPath));
  10450. if (!fileManager.isPathAbsolute(newFileInfo.rootpath) && fileManager.alwaysMakePathsAbsolute()) {
  10451. newFileInfo.rootpath = fileManager.join(newFileInfo.entryPath, newFileInfo.rootpath);
  10452. }
  10453. }
  10454. newFileInfo.filename = resolvedFilename;
  10455. var newEnv = new contexts.Parse(importManager.context);
  10456. newEnv.processImports = false;
  10457. importManager.contents[resolvedFilename] = contents;
  10458. if (currentFileInfo.reference || importOptions.reference) {
  10459. newFileInfo.reference = true;
  10460. }
  10461. if (importOptions.isPlugin) {
  10462. plugin = pluginLoader.evalPlugin(contents, newEnv, importManager, importOptions.pluginArgs, newFileInfo);
  10463. if (plugin instanceof LessError) {
  10464. fileParsedFunc(plugin, null, resolvedFilename);
  10465. }
  10466. else {
  10467. fileParsedFunc(null, plugin, resolvedFilename);
  10468. }
  10469. }
  10470. else if (importOptions.inline) {
  10471. fileParsedFunc(null, contents, resolvedFilename);
  10472. }
  10473. else {
  10474. // import (multiple) parse trees apparently get altered and can't be cached.
  10475. // TODO: investigate why this is
  10476. if (importManager.files[resolvedFilename]
  10477. && !importManager.files[resolvedFilename].options.multiple
  10478. && !importOptions.multiple) {
  10479. fileParsedFunc(null, importManager.files[resolvedFilename].root, resolvedFilename);
  10480. }
  10481. else {
  10482. new Parser(newEnv, importManager, newFileInfo).parse(contents, function (e, root) {
  10483. fileParsedFunc(e, root, resolvedFilename);
  10484. });
  10485. }
  10486. }
  10487. };
  10488. var loadedFile;
  10489. var promise;
  10490. var context = clone(this.context);
  10491. if (tryAppendExtension) {
  10492. context.ext = importOptions.isPlugin ? '.js' : '.less';
  10493. }
  10494. if (importOptions.isPlugin) {
  10495. context.mime = 'application/javascript';
  10496. if (context.syncImport) {
  10497. loadedFile = pluginLoader.loadPluginSync(path, currentFileInfo.currentDirectory, context, environment, fileManager);
  10498. }
  10499. else {
  10500. promise = pluginLoader.loadPlugin(path, currentFileInfo.currentDirectory, context, environment, fileManager);
  10501. }
  10502. }
  10503. else {
  10504. if (context.syncImport) {
  10505. loadedFile = fileManager.loadFileSync(path, currentFileInfo.currentDirectory, context, environment);
  10506. }
  10507. else {
  10508. promise = fileManager.loadFile(path, currentFileInfo.currentDirectory, context, environment, function (err, loadedFile) {
  10509. if (err) {
  10510. fileParsedFunc(err);
  10511. }
  10512. else {
  10513. loadFileCallback(loadedFile);
  10514. }
  10515. });
  10516. }
  10517. }
  10518. if (loadedFile) {
  10519. if (!loadedFile.filename) {
  10520. fileParsedFunc(loadedFile);
  10521. }
  10522. else {
  10523. loadFileCallback(loadedFile);
  10524. }
  10525. }
  10526. else if (promise) {
  10527. promise.then(loadFileCallback, fileParsedFunc);
  10528. }
  10529. };
  10530. return ImportManager;
  10531. }());
  10532. return ImportManager;
  10533. }
  10534. function Parse (environment, ParseTree, ImportManager) {
  10535. var parse = function (input, options, callback) {
  10536. if (typeof options === 'function') {
  10537. callback = options;
  10538. options = copyOptions(this.options, {});
  10539. }
  10540. else {
  10541. options = copyOptions(this.options, options || {});
  10542. }
  10543. if (!callback) {
  10544. var self_1 = this;
  10545. return new Promise(function (resolve, reject) {
  10546. parse.call(self_1, input, options, function (err, output) {
  10547. if (err) {
  10548. reject(err);
  10549. }
  10550. else {
  10551. resolve(output);
  10552. }
  10553. });
  10554. });
  10555. }
  10556. else {
  10557. var context_1;
  10558. var rootFileInfo = void 0;
  10559. var pluginManager_1 = new PluginManagerFactory(this, !options.reUsePluginManager);
  10560. options.pluginManager = pluginManager_1;
  10561. context_1 = new contexts.Parse(options);
  10562. if (options.rootFileInfo) {
  10563. rootFileInfo = options.rootFileInfo;
  10564. }
  10565. else {
  10566. var filename = options.filename || 'input';
  10567. var entryPath = filename.replace(/[^/\\]*$/, '');
  10568. rootFileInfo = {
  10569. filename: filename,
  10570. rewriteUrls: context_1.rewriteUrls,
  10571. rootpath: context_1.rootpath || '',
  10572. currentDirectory: entryPath,
  10573. entryPath: entryPath,
  10574. rootFilename: filename
  10575. };
  10576. // add in a missing trailing slash
  10577. if (rootFileInfo.rootpath && rootFileInfo.rootpath.slice(-1) !== '/') {
  10578. rootFileInfo.rootpath += '/';
  10579. }
  10580. }
  10581. var imports_1 = new ImportManager(this, context_1, rootFileInfo);
  10582. this.importManager = imports_1;
  10583. // TODO: allow the plugins to be just a list of paths or names
  10584. // Do an async plugin queue like lessc
  10585. if (options.plugins) {
  10586. options.plugins.forEach(function (plugin) {
  10587. var evalResult, contents;
  10588. if (plugin.fileContent) {
  10589. contents = plugin.fileContent.replace(/^\uFEFF/, '');
  10590. evalResult = pluginManager_1.Loader.evalPlugin(contents, context_1, imports_1, plugin.options, plugin.filename);
  10591. if (evalResult instanceof LessError) {
  10592. return callback(evalResult);
  10593. }
  10594. }
  10595. else {
  10596. pluginManager_1.addPlugin(plugin);
  10597. }
  10598. });
  10599. }
  10600. new Parser(context_1, imports_1, rootFileInfo)
  10601. .parse(input, function (e, root) {
  10602. if (e) {
  10603. return callback(e);
  10604. }
  10605. callback(null, root, imports_1, options);
  10606. }, options);
  10607. }
  10608. };
  10609. return parse;
  10610. }
  10611. function Render (environment, ParseTree) {
  10612. var render = function (input, options, callback) {
  10613. if (typeof options === 'function') {
  10614. callback = options;
  10615. options = copyOptions(this.options, {});
  10616. }
  10617. else {
  10618. options = copyOptions(this.options, options || {});
  10619. }
  10620. if (!callback) {
  10621. var self_1 = this;
  10622. return new Promise(function (resolve, reject) {
  10623. render.call(self_1, input, options, function (err, output) {
  10624. if (err) {
  10625. reject(err);
  10626. }
  10627. else {
  10628. resolve(output);
  10629. }
  10630. });
  10631. });
  10632. }
  10633. else {
  10634. this.parse(input, options, function (err, root, imports, options) {
  10635. if (err) {
  10636. return callback(err);
  10637. }
  10638. var result;
  10639. try {
  10640. var parseTree = new ParseTree(root, imports);
  10641. result = parseTree.toCSS(options);
  10642. }
  10643. catch (err) {
  10644. return callback(err);
  10645. }
  10646. callback(null, result);
  10647. });
  10648. }
  10649. };
  10650. return render;
  10651. }
  10652. var version = "4.2.0";
  10653. function parseNodeVersion(version) {
  10654. var match = version.match(/^v(\d{1,2})\.(\d{1,2})\.(\d{1,2})(?:-([0-9A-Za-z-.]+))?(?:\+([0-9A-Za-z-.]+))?$/); // eslint-disable-line max-len
  10655. if (!match) {
  10656. throw new Error('Unable to parse: ' + version);
  10657. }
  10658. var res = {
  10659. major: parseInt(match[1], 10),
  10660. minor: parseInt(match[2], 10),
  10661. patch: parseInt(match[3], 10),
  10662. pre: match[4] || '',
  10663. build: match[5] || '',
  10664. };
  10665. return res;
  10666. }
  10667. var parseNodeVersion_1 = parseNodeVersion;
  10668. function lessRoot (environment, fileManagers) {
  10669. var sourceMapOutput, sourceMapBuilder, parseTree, importManager;
  10670. environment = new Environment(environment, fileManagers);
  10671. sourceMapOutput = SourceMapOutput(environment);
  10672. sourceMapBuilder = SourceMapBuilder(sourceMapOutput, environment);
  10673. parseTree = ParseTree(sourceMapBuilder);
  10674. importManager = ImportManager(environment);
  10675. var render = Render(environment, parseTree);
  10676. var parse = Parse(environment, parseTree, importManager);
  10677. var v = parseNodeVersion_1("v" + version);
  10678. var initial = {
  10679. version: [v.major, v.minor, v.patch],
  10680. data: data,
  10681. tree: tree,
  10682. Environment: Environment,
  10683. AbstractFileManager: AbstractFileManager,
  10684. AbstractPluginLoader: AbstractPluginLoader,
  10685. environment: environment,
  10686. visitors: visitors,
  10687. Parser: Parser,
  10688. functions: functions(environment),
  10689. contexts: contexts,
  10690. SourceMapOutput: sourceMapOutput,
  10691. SourceMapBuilder: sourceMapBuilder,
  10692. ParseTree: parseTree,
  10693. ImportManager: importManager,
  10694. render: render,
  10695. parse: parse,
  10696. LessError: LessError,
  10697. transformTree: transformTree,
  10698. utils: utils,
  10699. PluginManager: PluginManagerFactory,
  10700. logger: logger$1
  10701. };
  10702. // Create a public API
  10703. var ctor = function (t) {
  10704. return function () {
  10705. var obj = Object.create(t.prototype);
  10706. t.apply(obj, Array.prototype.slice.call(arguments, 0));
  10707. return obj;
  10708. };
  10709. };
  10710. var t;
  10711. var api = Object.create(initial);
  10712. for (var n in initial.tree) {
  10713. /* eslint guard-for-in: 0 */
  10714. t = initial.tree[n];
  10715. if (typeof t === 'function') {
  10716. api[n.toLowerCase()] = ctor(t);
  10717. }
  10718. else {
  10719. api[n] = Object.create(null);
  10720. for (var o in t) {
  10721. /* eslint guard-for-in: 0 */
  10722. api[n][o.toLowerCase()] = ctor(t[o]);
  10723. }
  10724. }
  10725. }
  10726. /**
  10727. * Some of the functions assume a `this` context of the API object,
  10728. * which causes it to fail when wrapped for ES6 imports.
  10729. *
  10730. * An assumed `this` should be removed in the future.
  10731. */
  10732. initial.parse = initial.parse.bind(api);
  10733. initial.render = initial.render.bind(api);
  10734. return api;
  10735. }
  10736. var options$1;
  10737. var logger;
  10738. var fileCache = {};
  10739. // TODOS - move log somewhere. pathDiff and doing something similar in node. use pathDiff in the other browser file for the initial load
  10740. var FileManager = function () { };
  10741. FileManager.prototype = Object.assign(new AbstractFileManager(), {
  10742. alwaysMakePathsAbsolute: function () {
  10743. return true;
  10744. },
  10745. join: function (basePath, laterPath) {
  10746. if (!basePath) {
  10747. return laterPath;
  10748. }
  10749. return this.extractUrlParts(laterPath, basePath).path;
  10750. },
  10751. doXHR: function (url, type, callback, errback) {
  10752. var xhr = new XMLHttpRequest();
  10753. var async = options$1.isFileProtocol ? options$1.fileAsync : true;
  10754. if (typeof xhr.overrideMimeType === 'function') {
  10755. xhr.overrideMimeType('text/css');
  10756. }
  10757. logger.debug("XHR: Getting '" + url + "'");
  10758. xhr.open('GET', url, async);
  10759. xhr.setRequestHeader('Accept', type || 'text/x-less, text/css; q=0.9, */*; q=0.5');
  10760. xhr.send(null);
  10761. function handleResponse(xhr, callback, errback) {
  10762. if (xhr.status >= 200 && xhr.status < 300) {
  10763. callback(xhr.responseText, xhr.getResponseHeader('Last-Modified'));
  10764. }
  10765. else if (typeof errback === 'function') {
  10766. errback(xhr.status, url);
  10767. }
  10768. }
  10769. if (options$1.isFileProtocol && !options$1.fileAsync) {
  10770. if (xhr.status === 0 || (xhr.status >= 200 && xhr.status < 300)) {
  10771. callback(xhr.responseText);
  10772. }
  10773. else {
  10774. errback(xhr.status, url);
  10775. }
  10776. }
  10777. else if (async) {
  10778. xhr.onreadystatechange = function () {
  10779. if (xhr.readyState == 4) {
  10780. handleResponse(xhr, callback, errback);
  10781. }
  10782. };
  10783. }
  10784. else {
  10785. handleResponse(xhr, callback, errback);
  10786. }
  10787. },
  10788. supports: function () {
  10789. return true;
  10790. },
  10791. clearFileCache: function () {
  10792. fileCache = {};
  10793. },
  10794. loadFile: function (filename, currentDirectory, options) {
  10795. // TODO: Add prefix support like less-node?
  10796. // What about multiple paths?
  10797. if (currentDirectory && !this.isPathAbsolute(filename)) {
  10798. filename = currentDirectory + filename;
  10799. }
  10800. filename = options.ext ? this.tryAppendExtension(filename, options.ext) : filename;
  10801. options = options || {};
  10802. // sheet may be set to the stylesheet for the initial load or a collection of properties including
  10803. // some context variables for imports
  10804. var hrefParts = this.extractUrlParts(filename, window.location.href);
  10805. var href = hrefParts.url;
  10806. var self = this;
  10807. return new Promise(function (resolve, reject) {
  10808. if (options.useFileCache && fileCache[href]) {
  10809. try {
  10810. var lessText_1 = fileCache[href];
  10811. return resolve({ contents: lessText_1, filename: href, webInfo: { lastModified: new Date() } });
  10812. }
  10813. catch (e) {
  10814. return reject({ filename: href, message: "Error loading file " + href + " error was " + e.message });
  10815. }
  10816. }
  10817. self.doXHR(href, options.mime, function doXHRCallback(data, lastModified) {
  10818. // per file cache
  10819. fileCache[href] = data;
  10820. // Use remote copy (re-parse)
  10821. resolve({ contents: data, filename: href, webInfo: { lastModified: lastModified } });
  10822. }, function doXHRError(status, url) {
  10823. reject({ type: 'File', message: "'" + url + "' wasn't found (" + status + ")", href: href });
  10824. });
  10825. });
  10826. }
  10827. });
  10828. var FM = (function (opts, log) {
  10829. options$1 = opts;
  10830. logger = log;
  10831. return FileManager;
  10832. });
  10833. /**
  10834. * @todo Add tests for browser `@plugin`
  10835. */
  10836. /**
  10837. * Browser Plugin Loader
  10838. */
  10839. var PluginLoader = function (less) {
  10840. this.less = less;
  10841. // Should we shim this.require for browser? Probably not?
  10842. };
  10843. PluginLoader.prototype = Object.assign(new AbstractPluginLoader(), {
  10844. loadPlugin: function (filename, basePath, context, environment, fileManager) {
  10845. return new Promise(function (fulfill, reject) {
  10846. fileManager.loadFile(filename, basePath, context, environment)
  10847. .then(fulfill).catch(reject);
  10848. });
  10849. }
  10850. });
  10851. var LogListener = (function (less, options) {
  10852. var logLevel_debug = 4;
  10853. var logLevel_info = 3;
  10854. var logLevel_warn = 2;
  10855. var logLevel_error = 1;
  10856. // The amount of logging in the javascript console.
  10857. // 3 - Debug, information and errors
  10858. // 2 - Information and errors
  10859. // 1 - Errors
  10860. // 0 - None
  10861. // Defaults to 2
  10862. options.logLevel = typeof options.logLevel !== 'undefined' ? options.logLevel : (options.env === 'development' ? logLevel_info : logLevel_error);
  10863. if (!options.loggers) {
  10864. options.loggers = [{
  10865. debug: function (msg) {
  10866. if (options.logLevel >= logLevel_debug) {
  10867. console.log(msg);
  10868. }
  10869. },
  10870. info: function (msg) {
  10871. if (options.logLevel >= logLevel_info) {
  10872. console.log(msg);
  10873. }
  10874. },
  10875. warn: function (msg) {
  10876. if (options.logLevel >= logLevel_warn) {
  10877. console.warn(msg);
  10878. }
  10879. },
  10880. error: function (msg) {
  10881. if (options.logLevel >= logLevel_error) {
  10882. console.error(msg);
  10883. }
  10884. }
  10885. }];
  10886. }
  10887. for (var i_1 = 0; i_1 < options.loggers.length; i_1++) {
  10888. less.logger.addListener(options.loggers[i_1]);
  10889. }
  10890. });
  10891. var ErrorReporting = (function (window, less, options) {
  10892. function errorHTML(e, rootHref) {
  10893. var id = "less-error-message:" + extractId(rootHref || '');
  10894. var template = '<li><label>{line}</label><pre class="{class}">{content}</pre></li>';
  10895. var elem = window.document.createElement('div');
  10896. var timer;
  10897. var content;
  10898. var errors = [];
  10899. var filename = e.filename || rootHref;
  10900. var filenameNoPath = filename.match(/([^/]+(\?.*)?)$/)[1];
  10901. elem.id = id;
  10902. elem.className = 'less-error-message';
  10903. content = "<h3>" + (e.type || 'Syntax') + "Error: " + (e.message || 'There is an error in your .less file') +
  10904. ("</h3><p>in <a href=\"" + filename + "\">" + filenameNoPath + "</a> ");
  10905. var errorline = function (e, i, classname) {
  10906. if (e.extract[i] !== undefined) {
  10907. errors.push(template.replace(/\{line\}/, (parseInt(e.line, 10) || 0) + (i - 1))
  10908. .replace(/\{class\}/, classname)
  10909. .replace(/\{content\}/, e.extract[i]));
  10910. }
  10911. };
  10912. if (e.line) {
  10913. errorline(e, 0, '');
  10914. errorline(e, 1, 'line');
  10915. errorline(e, 2, '');
  10916. content += "on line " + e.line + ", column " + (e.column + 1) + ":</p><ul>" + errors.join('') + "</ul>";
  10917. }
  10918. if (e.stack && (e.extract || options.logLevel >= 4)) {
  10919. content += "<br/>Stack Trace</br />" + e.stack.split('\n').slice(1).join('<br/>');
  10920. }
  10921. elem.innerHTML = content;
  10922. // CSS for error messages
  10923. browser.createCSS(window.document, [
  10924. '.less-error-message ul, .less-error-message li {',
  10925. 'list-style-type: none;',
  10926. 'margin-right: 15px;',
  10927. 'padding: 4px 0;',
  10928. 'margin: 0;',
  10929. '}',
  10930. '.less-error-message label {',
  10931. 'font-size: 12px;',
  10932. 'margin-right: 15px;',
  10933. 'padding: 4px 0;',
  10934. 'color: #cc7777;',
  10935. '}',
  10936. '.less-error-message pre {',
  10937. 'color: #dd6666;',
  10938. 'padding: 4px 0;',
  10939. 'margin: 0;',
  10940. 'display: inline-block;',
  10941. '}',
  10942. '.less-error-message pre.line {',
  10943. 'color: #ff0000;',
  10944. '}',
  10945. '.less-error-message h3 {',
  10946. 'font-size: 20px;',
  10947. 'font-weight: bold;',
  10948. 'padding: 15px 0 5px 0;',
  10949. 'margin: 0;',
  10950. '}',
  10951. '.less-error-message a {',
  10952. 'color: #10a',
  10953. '}',
  10954. '.less-error-message .error {',
  10955. 'color: red;',
  10956. 'font-weight: bold;',
  10957. 'padding-bottom: 2px;',
  10958. 'border-bottom: 1px dashed red;',
  10959. '}'
  10960. ].join('\n'), { title: 'error-message' });
  10961. elem.style.cssText = [
  10962. 'font-family: Arial, sans-serif',
  10963. 'border: 1px solid #e00',
  10964. 'background-color: #eee',
  10965. 'border-radius: 5px',
  10966. '-webkit-border-radius: 5px',
  10967. '-moz-border-radius: 5px',
  10968. 'color: #e00',
  10969. 'padding: 15px',
  10970. 'margin-bottom: 15px'
  10971. ].join(';');
  10972. if (options.env === 'development') {
  10973. timer = setInterval(function () {
  10974. var document = window.document;
  10975. var body = document.body;
  10976. if (body) {
  10977. if (document.getElementById(id)) {
  10978. body.replaceChild(elem, document.getElementById(id));
  10979. }
  10980. else {
  10981. body.insertBefore(elem, body.firstChild);
  10982. }
  10983. clearInterval(timer);
  10984. }
  10985. }, 10);
  10986. }
  10987. }
  10988. function removeErrorHTML(path) {
  10989. var node = window.document.getElementById("less-error-message:" + extractId(path));
  10990. if (node) {
  10991. node.parentNode.removeChild(node);
  10992. }
  10993. }
  10994. function removeError(path) {
  10995. if (!options.errorReporting || options.errorReporting === 'html') {
  10996. removeErrorHTML(path);
  10997. }
  10998. else if (options.errorReporting === 'console') ;
  10999. else if (typeof options.errorReporting === 'function') {
  11000. options.errorReporting('remove', path);
  11001. }
  11002. }
  11003. function errorConsole(e, rootHref) {
  11004. var template = '{line} {content}';
  11005. var filename = e.filename || rootHref;
  11006. var errors = [];
  11007. var content = (e.type || 'Syntax') + "Error: " + (e.message || 'There is an error in your .less file') + " in " + filename;
  11008. var errorline = function (e, i, classname) {
  11009. if (e.extract[i] !== undefined) {
  11010. errors.push(template.replace(/\{line\}/, (parseInt(e.line, 10) || 0) + (i - 1))
  11011. .replace(/\{class\}/, classname)
  11012. .replace(/\{content\}/, e.extract[i]));
  11013. }
  11014. };
  11015. if (e.line) {
  11016. errorline(e, 0, '');
  11017. errorline(e, 1, 'line');
  11018. errorline(e, 2, '');
  11019. content += " on line " + e.line + ", column " + (e.column + 1) + ":\n" + errors.join('\n');
  11020. }
  11021. if (e.stack && (e.extract || options.logLevel >= 4)) {
  11022. content += "\nStack Trace\n" + e.stack;
  11023. }
  11024. less.logger.error(content);
  11025. }
  11026. function error(e, rootHref) {
  11027. if (!options.errorReporting || options.errorReporting === 'html') {
  11028. errorHTML(e, rootHref);
  11029. }
  11030. else if (options.errorReporting === 'console') {
  11031. errorConsole(e, rootHref);
  11032. }
  11033. else if (typeof options.errorReporting === 'function') {
  11034. options.errorReporting('add', e, rootHref);
  11035. }
  11036. }
  11037. return {
  11038. add: error,
  11039. remove: removeError
  11040. };
  11041. });
  11042. // Cache system is a bit outdated and could do with work
  11043. var Cache = (function (window, options, logger) {
  11044. var cache = null;
  11045. if (options.env !== 'development') {
  11046. try {
  11047. cache = (typeof window.localStorage === 'undefined') ? null : window.localStorage;
  11048. }
  11049. catch (_) { }
  11050. }
  11051. return {
  11052. setCSS: function (path, lastModified, modifyVars, styles) {
  11053. if (cache) {
  11054. logger.info("saving " + path + " to cache.");
  11055. try {
  11056. cache.setItem(path, styles);
  11057. cache.setItem(path + ":timestamp", lastModified);
  11058. if (modifyVars) {
  11059. cache.setItem(path + ":vars", JSON.stringify(modifyVars));
  11060. }
  11061. }
  11062. catch (e) {
  11063. // TODO - could do with adding more robust error handling
  11064. logger.error("failed to save \"" + path + "\" to local storage for caching.");
  11065. }
  11066. }
  11067. },
  11068. getCSS: function (path, webInfo, modifyVars) {
  11069. var css = cache && cache.getItem(path);
  11070. var timestamp = cache && cache.getItem(path + ":timestamp");
  11071. var vars = cache && cache.getItem(path + ":vars");
  11072. modifyVars = modifyVars || {};
  11073. vars = vars || '{}'; // if not set, treat as the JSON representation of an empty object
  11074. if (timestamp && webInfo.lastModified &&
  11075. (new Date(webInfo.lastModified).valueOf() ===
  11076. new Date(timestamp).valueOf()) &&
  11077. JSON.stringify(modifyVars) === vars) {
  11078. // Use local copy
  11079. return css;
  11080. }
  11081. }
  11082. };
  11083. });
  11084. var ImageSize = (function () {
  11085. function imageSize() {
  11086. throw {
  11087. type: 'Runtime',
  11088. message: 'Image size functions are not supported in browser version of less'
  11089. };
  11090. }
  11091. var imageFunctions = {
  11092. 'image-size': function (filePathNode) {
  11093. imageSize();
  11094. return -1;
  11095. },
  11096. 'image-width': function (filePathNode) {
  11097. imageSize();
  11098. return -1;
  11099. },
  11100. 'image-height': function (filePathNode) {
  11101. imageSize();
  11102. return -1;
  11103. }
  11104. };
  11105. functionRegistry.addMultiple(imageFunctions);
  11106. });
  11107. //
  11108. var root = (function (window, options) {
  11109. var document = window.document;
  11110. var less = lessRoot();
  11111. less.options = options;
  11112. var environment = less.environment;
  11113. var FileManager = FM(options, less.logger);
  11114. var fileManager = new FileManager();
  11115. environment.addFileManager(fileManager);
  11116. less.FileManager = FileManager;
  11117. less.PluginLoader = PluginLoader;
  11118. LogListener(less, options);
  11119. var errors = ErrorReporting(window, less, options);
  11120. var cache = less.cache = options.cache || Cache(window, options, less.logger);
  11121. ImageSize(less.environment);
  11122. // Setup user functions - Deprecate?
  11123. if (options.functions) {
  11124. less.functions.functionRegistry.addMultiple(options.functions);
  11125. }
  11126. var typePattern = /^text\/(x-)?less$/;
  11127. function clone(obj) {
  11128. var cloned = {};
  11129. for (var prop in obj) {
  11130. if (Object.prototype.hasOwnProperty.call(obj, prop)) {
  11131. cloned[prop] = obj[prop];
  11132. }
  11133. }
  11134. return cloned;
  11135. }
  11136. // only really needed for phantom
  11137. function bind(func, thisArg) {
  11138. var curryArgs = Array.prototype.slice.call(arguments, 2);
  11139. return function () {
  11140. var args = curryArgs.concat(Array.prototype.slice.call(arguments, 0));
  11141. return func.apply(thisArg, args);
  11142. };
  11143. }
  11144. function loadStyles(modifyVars) {
  11145. var styles = document.getElementsByTagName('style');
  11146. var style;
  11147. for (var i_1 = 0; i_1 < styles.length; i_1++) {
  11148. style = styles[i_1];
  11149. if (style.type.match(typePattern)) {
  11150. var instanceOptions = clone(options);
  11151. instanceOptions.modifyVars = modifyVars;
  11152. var lessText_1 = style.innerHTML || '';
  11153. instanceOptions.filename = document.location.href.replace(/#.*$/, '');
  11154. /* jshint loopfunc:true */
  11155. // use closure to store current style
  11156. less.render(lessText_1, instanceOptions, bind(function (style, e, result) {
  11157. if (e) {
  11158. errors.add(e, 'inline');
  11159. }
  11160. else {
  11161. style.type = 'text/css';
  11162. if (style.styleSheet) {
  11163. style.styleSheet.cssText = result.css;
  11164. }
  11165. else {
  11166. style.innerHTML = result.css;
  11167. }
  11168. }
  11169. }, null, style));
  11170. }
  11171. }
  11172. }
  11173. function loadStyleSheet(sheet, callback, reload, remaining, modifyVars) {
  11174. var instanceOptions = clone(options);
  11175. addDataAttr(instanceOptions, sheet);
  11176. instanceOptions.mime = sheet.type;
  11177. if (modifyVars) {
  11178. instanceOptions.modifyVars = modifyVars;
  11179. }
  11180. function loadInitialFileCallback(loadedFile) {
  11181. var data = loadedFile.contents;
  11182. var path = loadedFile.filename;
  11183. var webInfo = loadedFile.webInfo;
  11184. var newFileInfo = {
  11185. currentDirectory: fileManager.getPath(path),
  11186. filename: path,
  11187. rootFilename: path,
  11188. rewriteUrls: instanceOptions.rewriteUrls
  11189. };
  11190. newFileInfo.entryPath = newFileInfo.currentDirectory;
  11191. newFileInfo.rootpath = instanceOptions.rootpath || newFileInfo.currentDirectory;
  11192. if (webInfo) {
  11193. webInfo.remaining = remaining;
  11194. var css = cache.getCSS(path, webInfo, instanceOptions.modifyVars);
  11195. if (!reload && css) {
  11196. webInfo.local = true;
  11197. callback(null, css, data, sheet, webInfo, path);
  11198. return;
  11199. }
  11200. }
  11201. // TODO add tests around how this behaves when reloading
  11202. errors.remove(path);
  11203. instanceOptions.rootFileInfo = newFileInfo;
  11204. less.render(data, instanceOptions, function (e, result) {
  11205. if (e) {
  11206. e.href = path;
  11207. callback(e);
  11208. }
  11209. else {
  11210. cache.setCSS(sheet.href, webInfo.lastModified, instanceOptions.modifyVars, result.css);
  11211. callback(null, result.css, data, sheet, webInfo, path);
  11212. }
  11213. });
  11214. }
  11215. fileManager.loadFile(sheet.href, null, instanceOptions, environment)
  11216. .then(function (loadedFile) {
  11217. loadInitialFileCallback(loadedFile);
  11218. }).catch(function (err) {
  11219. console.log(err);
  11220. callback(err);
  11221. });
  11222. }
  11223. function loadStyleSheets(callback, reload, modifyVars) {
  11224. for (var i_2 = 0; i_2 < less.sheets.length; i_2++) {
  11225. loadStyleSheet(less.sheets[i_2], callback, reload, less.sheets.length - (i_2 + 1), modifyVars);
  11226. }
  11227. }
  11228. function initRunningMode() {
  11229. if (less.env === 'development') {
  11230. less.watchTimer = setInterval(function () {
  11231. if (less.watchMode) {
  11232. fileManager.clearFileCache();
  11233. /**
  11234. * @todo remove when this is typed with JSDoc
  11235. */
  11236. // eslint-disable-next-line no-unused-vars
  11237. loadStyleSheets(function (e, css, _, sheet, webInfo) {
  11238. if (e) {
  11239. errors.add(e, e.href || sheet.href);
  11240. }
  11241. else if (css) {
  11242. browser.createCSS(window.document, css, sheet);
  11243. }
  11244. });
  11245. }
  11246. }, options.poll);
  11247. }
  11248. }
  11249. //
  11250. // Watch mode
  11251. //
  11252. less.watch = function () {
  11253. if (!less.watchMode) {
  11254. less.env = 'development';
  11255. initRunningMode();
  11256. }
  11257. this.watchMode = true;
  11258. return true;
  11259. };
  11260. less.unwatch = function () { clearInterval(less.watchTimer); this.watchMode = false; return false; };
  11261. //
  11262. // Synchronously get all <link> tags with the 'rel' attribute set to
  11263. // "stylesheet/less".
  11264. //
  11265. less.registerStylesheetsImmediately = function () {
  11266. var links = document.getElementsByTagName('link');
  11267. less.sheets = [];
  11268. for (var i_3 = 0; i_3 < links.length; i_3++) {
  11269. if (links[i_3].rel === 'stylesheet/less' || (links[i_3].rel.match(/stylesheet/) &&
  11270. (links[i_3].type.match(typePattern)))) {
  11271. less.sheets.push(links[i_3]);
  11272. }
  11273. }
  11274. };
  11275. //
  11276. // Asynchronously get all <link> tags with the 'rel' attribute set to
  11277. // "stylesheet/less", returning a Promise.
  11278. //
  11279. less.registerStylesheets = function () { return new Promise(function (resolve) {
  11280. less.registerStylesheetsImmediately();
  11281. resolve();
  11282. }); };
  11283. //
  11284. // With this function, it's possible to alter variables and re-render
  11285. // CSS without reloading less-files
  11286. //
  11287. less.modifyVars = function (record) { return less.refresh(true, record, false); };
  11288. less.refresh = function (reload, modifyVars, clearFileCache) {
  11289. if ((reload || clearFileCache) && clearFileCache !== false) {
  11290. fileManager.clearFileCache();
  11291. }
  11292. return new Promise(function (resolve, reject) {
  11293. var startTime;
  11294. var endTime;
  11295. var totalMilliseconds;
  11296. var remainingSheets;
  11297. startTime = endTime = new Date();
  11298. // Set counter for remaining unprocessed sheets
  11299. remainingSheets = less.sheets.length;
  11300. if (remainingSheets === 0) {
  11301. endTime = new Date();
  11302. totalMilliseconds = endTime - startTime;
  11303. less.logger.info('Less has finished and no sheets were loaded.');
  11304. resolve({
  11305. startTime: startTime,
  11306. endTime: endTime,
  11307. totalMilliseconds: totalMilliseconds,
  11308. sheets: less.sheets.length
  11309. });
  11310. }
  11311. else {
  11312. // Relies on less.sheets array, callback seems to be guaranteed to be called for every element of the array
  11313. loadStyleSheets(function (e, css, _, sheet, webInfo) {
  11314. if (e) {
  11315. errors.add(e, e.href || sheet.href);
  11316. reject(e);
  11317. return;
  11318. }
  11319. if (webInfo.local) {
  11320. less.logger.info("Loading " + sheet.href + " from cache.");
  11321. }
  11322. else {
  11323. less.logger.info("Rendered " + sheet.href + " successfully.");
  11324. }
  11325. browser.createCSS(window.document, css, sheet);
  11326. less.logger.info("CSS for " + sheet.href + " generated in " + (new Date() - endTime) + "ms");
  11327. // Count completed sheet
  11328. remainingSheets--;
  11329. // Check if the last remaining sheet was processed and then call the promise
  11330. if (remainingSheets === 0) {
  11331. totalMilliseconds = new Date() - startTime;
  11332. less.logger.info("Less has finished. CSS generated in " + totalMilliseconds + "ms");
  11333. resolve({
  11334. startTime: startTime,
  11335. endTime: endTime,
  11336. totalMilliseconds: totalMilliseconds,
  11337. sheets: less.sheets.length
  11338. });
  11339. }
  11340. endTime = new Date();
  11341. }, reload, modifyVars);
  11342. }
  11343. loadStyles(modifyVars);
  11344. });
  11345. };
  11346. less.refreshStyles = loadStyles;
  11347. return less;
  11348. });
  11349. /**
  11350. * Kicks off less and compiles any stylesheets
  11351. * used in the browser distributed version of less
  11352. * to kick-start less using the browser api
  11353. */
  11354. var options = defaultOptions();
  11355. if (window.less) {
  11356. for (var key in window.less) {
  11357. if (Object.prototype.hasOwnProperty.call(window.less, key)) {
  11358. options[key] = window.less[key];
  11359. }
  11360. }
  11361. }
  11362. addDefaultOptions(window, options);
  11363. options.plugins = options.plugins || [];
  11364. if (window.LESS_PLUGINS) {
  11365. options.plugins = options.plugins.concat(window.LESS_PLUGINS);
  11366. }
  11367. var less = root(window, options);
  11368. window.less = less;
  11369. var css;
  11370. var head;
  11371. var style;
  11372. // Always restore page visibility
  11373. function resolveOrReject(data) {
  11374. if (data.filename) {
  11375. console.warn(data);
  11376. }
  11377. if (!options.async) {
  11378. head.removeChild(style);
  11379. }
  11380. }
  11381. if (options.onReady) {
  11382. if (/!watch/.test(window.location.hash)) {
  11383. less.watch();
  11384. }
  11385. // Simulate synchronous stylesheet loading by hiding page rendering
  11386. if (!options.async) {
  11387. css = 'body { display: none !important }';
  11388. head = document.head || document.getElementsByTagName('head')[0];
  11389. style = document.createElement('style');
  11390. style.type = 'text/css';
  11391. if (style.styleSheet) {
  11392. style.styleSheet.cssText = css;
  11393. }
  11394. else {
  11395. style.appendChild(document.createTextNode(css));
  11396. }
  11397. head.appendChild(style);
  11398. }
  11399. less.registerStylesheetsImmediately();
  11400. less.pageLoadFinished = less.refresh(less.env === 'development').then(resolveOrReject, resolveOrReject);
  11401. }
  11402. return less;
  11403. })));