less.js 448 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320732173227323732473257326732773287329733073317332733373347335733673377338733973407341734273437344734573467347734873497350735173527353735473557356735773587359736073617362736373647365736673677368736973707371737273737374737573767377737873797380738173827383738473857386738773887389739073917392739373947395739673977398739974007401740274037404740574067407740874097410741174127413741474157416741774187419742074217422742374247425742674277428742974307431743274337434743574367437743874397440744174427443744474457446744774487449745074517452745374547455745674577458745974607461746274637464746574667467746874697470747174727473747474757476747774787479748074817482748374847485748674877488748974907491749274937494749574967497749874997500750175027503750475057506750775087509751075117512751375147515751675177518751975207521752275237524752575267527752875297530753175327533753475357536753775387539754075417542754375447545754675477548754975507551755275537554755575567557755875597560756175627563756475657566756775687569757075717572757375747575757675777578757975807581758275837584758575867587758875897590759175927593759475957596759775987599760076017602760376047605760676077608760976107611761276137614761576167617761876197620762176227623762476257626762776287629763076317632763376347635763676377638763976407641764276437644764576467647764876497650765176527653765476557656765776587659766076617662766376647665766676677668766976707671767276737674767576767677767876797680768176827683768476857686768776887689769076917692769376947695769676977698769977007701770277037704770577067707770877097710771177127713771477157716771777187719772077217722772377247725772677277728772977307731773277337734773577367737773877397740774177427743774477457746774777487749775077517752775377547755775677577758775977607761776277637764776577667767776877697770777177727773777477757776777777787779778077817782778377847785778677877788778977907791779277937794779577967797779877997800780178027803780478057806780778087809781078117812781378147815781678177818781978207821782278237824782578267827782878297830783178327833783478357836783778387839784078417842784378447845784678477848784978507851785278537854785578567857785878597860786178627863786478657866786778687869787078717872787378747875787678777878787978807881788278837884788578867887788878897890789178927893789478957896789778987899790079017902790379047905790679077908790979107911791279137914791579167917791879197920792179227923792479257926792779287929793079317932793379347935793679377938793979407941794279437944794579467947794879497950795179527953795479557956795779587959796079617962796379647965796679677968796979707971797279737974797579767977797879797980798179827983798479857986798779887989799079917992799379947995799679977998799980008001800280038004800580068007800880098010801180128013801480158016801780188019802080218022802380248025802680278028802980308031803280338034803580368037803880398040804180428043804480458046804780488049805080518052805380548055805680578058805980608061806280638064806580668067806880698070807180728073807480758076807780788079808080818082808380848085808680878088808980908091809280938094809580968097809880998100810181028103810481058106810781088109811081118112811381148115811681178118811981208121812281238124812581268127812881298130813181328133813481358136813781388139814081418142814381448145814681478148814981508151815281538154815581568157815881598160816181628163816481658166816781688169817081718172817381748175817681778178817981808181818281838184818581868187818881898190819181928193819481958196819781988199820082018202820382048205820682078208820982108211821282138214821582168217821882198220822182228223822482258226822782288229823082318232823382348235823682378238823982408241824282438244824582468247824882498250825182528253825482558256825782588259826082618262826382648265826682678268826982708271827282738274827582768277827882798280828182828283828482858286828782888289829082918292829382948295829682978298829983008301830283038304830583068307830883098310831183128313831483158316831783188319832083218322832383248325832683278328832983308331833283338334833583368337833883398340834183428343834483458346834783488349835083518352835383548355835683578358835983608361836283638364836583668367836883698370837183728373837483758376837783788379838083818382838383848385838683878388838983908391839283938394839583968397839883998400840184028403840484058406840784088409841084118412841384148415841684178418841984208421842284238424842584268427842884298430843184328433843484358436843784388439844084418442844384448445844684478448844984508451845284538454845584568457845884598460846184628463846484658466846784688469847084718472847384748475847684778478847984808481848284838484848584868487848884898490849184928493849484958496849784988499850085018502850385048505850685078508850985108511851285138514851585168517851885198520852185228523852485258526852785288529853085318532853385348535853685378538853985408541854285438544854585468547854885498550855185528553855485558556855785588559856085618562856385648565856685678568856985708571857285738574857585768577857885798580858185828583858485858586858785888589859085918592859385948595859685978598859986008601860286038604860586068607860886098610861186128613861486158616861786188619862086218622862386248625862686278628862986308631863286338634863586368637863886398640864186428643864486458646864786488649865086518652865386548655865686578658865986608661866286638664866586668667866886698670867186728673867486758676867786788679868086818682868386848685868686878688868986908691869286938694869586968697869886998700870187028703870487058706870787088709871087118712871387148715871687178718871987208721872287238724872587268727872887298730873187328733873487358736873787388739874087418742874387448745874687478748874987508751875287538754875587568757875887598760876187628763876487658766876787688769877087718772877387748775877687778778877987808781878287838784878587868787878887898790879187928793879487958796879787988799880088018802880388048805880688078808880988108811881288138814881588168817881888198820882188228823882488258826882788288829883088318832883388348835883688378838883988408841884288438844884588468847884888498850885188528853885488558856885788588859886088618862886388648865886688678868886988708871887288738874887588768877887888798880888188828883888488858886888788888889889088918892889388948895889688978898889989008901890289038904890589068907890889098910891189128913891489158916891789188919892089218922892389248925892689278928892989308931893289338934893589368937893889398940894189428943894489458946894789488949895089518952895389548955895689578958895989608961896289638964896589668967896889698970897189728973897489758976897789788979898089818982898389848985898689878988898989908991899289938994899589968997899889999000900190029003900490059006900790089009901090119012901390149015901690179018901990209021902290239024902590269027902890299030903190329033903490359036903790389039904090419042904390449045904690479048904990509051905290539054905590569057905890599060906190629063906490659066906790689069907090719072907390749075907690779078907990809081908290839084908590869087908890899090909190929093909490959096909790989099910091019102910391049105910691079108910991109111911291139114911591169117911891199120912191229123912491259126912791289129913091319132913391349135913691379138913991409141914291439144914591469147914891499150915191529153915491559156915791589159916091619162916391649165916691679168916991709171917291739174917591769177917891799180918191829183918491859186918791889189919091919192919391949195919691979198919992009201920292039204920592069207920892099210921192129213921492159216921792189219922092219222922392249225922692279228922992309231923292339234923592369237923892399240924192429243924492459246924792489249925092519252925392549255925692579258925992609261926292639264926592669267926892699270927192729273927492759276927792789279928092819282928392849285928692879288928992909291929292939294929592969297929892999300930193029303930493059306930793089309931093119312931393149315931693179318931993209321932293239324932593269327932893299330933193329333933493359336933793389339934093419342934393449345934693479348934993509351935293539354935593569357935893599360936193629363936493659366936793689369937093719372937393749375937693779378937993809381938293839384938593869387938893899390939193929393939493959396939793989399940094019402940394049405940694079408940994109411941294139414941594169417941894199420942194229423942494259426942794289429943094319432943394349435943694379438943994409441944294439444944594469447944894499450945194529453945494559456945794589459946094619462946394649465946694679468946994709471947294739474947594769477947894799480948194829483948494859486948794889489949094919492949394949495949694979498949995009501950295039504950595069507950895099510951195129513951495159516951795189519952095219522952395249525952695279528952995309531953295339534953595369537953895399540954195429543954495459546954795489549955095519552955395549555955695579558955995609561956295639564956595669567956895699570957195729573957495759576957795789579958095819582958395849585958695879588958995909591959295939594959595969597959895999600960196029603960496059606960796089609961096119612961396149615961696179618961996209621962296239624962596269627962896299630963196329633963496359636963796389639964096419642964396449645964696479648964996509651965296539654965596569657965896599660966196629663966496659666966796689669967096719672967396749675967696779678967996809681968296839684968596869687968896899690969196929693969496959696969796989699970097019702970397049705970697079708970997109711971297139714971597169717971897199720972197229723972497259726972797289729973097319732973397349735973697379738973997409741974297439744974597469747974897499750975197529753975497559756975797589759976097619762976397649765976697679768976997709771977297739774977597769777977897799780978197829783978497859786978797889789979097919792979397949795979697979798979998009801980298039804980598069807980898099810981198129813981498159816981798189819982098219822982398249825982698279828982998309831983298339834983598369837983898399840984198429843984498459846984798489849985098519852985398549855985698579858985998609861986298639864986598669867986898699870987198729873987498759876987798789879988098819882988398849885988698879888988998909891989298939894989598969897989898999900990199029903990499059906990799089909991099119912991399149915991699179918991999209921992299239924992599269927992899299930993199329933993499359936993799389939994099419942994399449945994699479948994999509951995299539954995599569957995899599960996199629963996499659966996799689969997099719972997399749975997699779978997999809981998299839984998599869987998899899990999199929993999499959996999799989999100001000110002100031000410005100061000710008100091001010011100121001310014100151001610017100181001910020100211002210023100241002510026100271002810029100301003110032100331003410035100361003710038100391004010041100421004310044100451004610047100481004910050100511005210053100541005510056100571005810059100601006110062100631006410065100661006710068100691007010071100721007310074100751007610077100781007910080100811008210083100841008510086100871008810089100901009110092100931009410095100961009710098100991010010101101021010310104101051010610107101081010910110101111011210113101141011510116101171011810119101201012110122101231012410125101261012710128101291013010131101321013310134101351013610137101381013910140101411014210143101441014510146101471014810149101501015110152101531015410155101561015710158101591016010161101621016310164101651016610167101681016910170101711017210173101741017510176101771017810179101801018110182101831018410185101861018710188101891019010191101921019310194101951019610197101981019910200102011020210203102041020510206102071020810209102101021110212102131021410215102161021710218102191022010221102221022310224102251022610227102281022910230102311023210233102341023510236102371023810239102401024110242102431024410245102461024710248102491025010251102521025310254102551025610257102581025910260102611026210263102641026510266102671026810269102701027110272102731027410275102761027710278102791028010281102821028310284102851028610287102881028910290102911029210293102941029510296102971029810299103001030110302103031030410305103061030710308103091031010311103121031310314103151031610317103181031910320103211032210323103241032510326103271032810329103301033110332103331033410335103361033710338103391034010341103421034310344103451034610347103481034910350103511035210353103541035510356103571035810359103601036110362103631036410365103661036710368103691037010371103721037310374103751037610377103781037910380103811038210383103841038510386103871038810389103901039110392103931039410395103961039710398103991040010401104021040310404104051040610407104081040910410104111041210413104141041510416104171041810419104201042110422104231042410425104261042710428104291043010431104321043310434104351043610437104381043910440104411044210443104441044510446104471044810449104501045110452104531045410455104561045710458104591046010461104621046310464104651046610467104681046910470104711047210473104741047510476104771047810479104801048110482104831048410485104861048710488104891049010491104921049310494104951049610497104981049910500105011050210503105041050510506105071050810509105101051110512105131051410515105161051710518105191052010521105221052310524105251052610527105281052910530105311053210533105341053510536105371053810539105401054110542105431054410545105461054710548105491055010551105521055310554105551055610557105581055910560105611056210563105641056510566105671056810569105701057110572105731057410575105761057710578105791058010581105821058310584105851058610587105881058910590105911059210593105941059510596105971059810599106001060110602106031060410605106061060710608106091061010611106121061310614106151061610617106181061910620106211062210623106241062510626106271062810629106301063110632106331063410635106361063710638106391064010641106421064310644106451064610647106481064910650106511065210653106541065510656106571065810659106601066110662106631066410665106661066710668106691067010671106721067310674106751067610677106781067910680106811068210683106841068510686106871068810689106901069110692106931069410695106961069710698106991070010701107021070310704107051070610707107081070910710107111071210713107141071510716107171071810719107201072110722107231072410725107261072710728107291073010731107321073310734107351073610737107381073910740107411074210743107441074510746107471074810749107501075110752107531075410755107561075710758107591076010761107621076310764107651076610767107681076910770107711077210773107741077510776107771077810779107801078110782107831078410785107861078710788107891079010791107921079310794107951079610797107981079910800108011080210803108041080510806108071080810809108101081110812108131081410815108161081710818108191082010821108221082310824108251082610827108281082910830108311083210833108341083510836108371083810839108401084110842108431084410845108461084710848108491085010851108521085310854108551085610857108581085910860108611086210863108641086510866108671086810869108701087110872108731087410875108761087710878108791088010881108821088310884108851088610887108881088910890108911089210893108941089510896108971089810899109001090110902109031090410905109061090710908109091091010911109121091310914109151091610917109181091910920109211092210923109241092510926109271092810929109301093110932109331093410935109361093710938109391094010941109421094310944109451094610947109481094910950109511095210953109541095510956109571095810959109601096110962109631096410965109661096710968109691097010971109721097310974109751097610977109781097910980109811098210983109841098510986109871098810989109901099110992109931099410995109961099710998109991100011001110021100311004110051100611007110081100911010110111101211013110141101511016110171101811019110201102111022110231102411025110261102711028110291103011031110321103311034110351103611037110381103911040110411104211043110441104511046110471104811049110501105111052110531105411055110561105711058110591106011061110621106311064110651106611067110681106911070110711107211073110741107511076110771107811079110801108111082110831108411085110861108711088110891109011091110921109311094110951109611097110981109911100111011110211103111041110511106111071110811109111101111111112111131111411115111161111711118111191112011121111221112311124111251112611127111281112911130111311113211133111341113511136111371113811139111401114111142111431114411145111461114711148111491115011151111521115311154111551115611157111581115911160111611116211163111641116511166111671116811169111701117111172111731117411175111761117711178111791118011181111821118311184111851118611187111881118911190111911119211193111941119511196111971119811199112001120111202112031120411205112061120711208112091121011211112121121311214112151121611217112181121911220112211122211223112241122511226112271122811229112301123111232112331123411235112361123711238112391124011241112421124311244112451124611247112481124911250112511125211253112541125511256112571125811259112601126111262112631126411265112661126711268112691127011271112721127311274112751127611277112781127911280112811128211283112841128511286112871128811289112901129111292112931129411295112961129711298112991130011301113021130311304113051130611307113081130911310113111131211313113141131511316113171131811319113201132111322113231132411325113261132711328113291133011331113321133311334
  1. /**
  2. * Less - Leaner CSS v3.12.2
  3. * http://lesscss.org
  4. *
  5. * Copyright (c) 2009-2020, Alexis Sellier <self@cloudhead.net>
  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 = global || self, global.less = factory());
  14. }(this, (function () { 'use strict';
  15. // Export a new default each time
  16. var defaultOptions = (function () { return ({
  17. /* Inline Javascript - @plugin still allowed */
  18. javascriptEnabled: false,
  19. /* Outputs a makefile import dependency list to stdout. */
  20. depends: false,
  21. /* (DEPRECATED) Compress using less built-in compression.
  22. * This does an okay job but does not utilise all the tricks of
  23. * dedicated css compression. */
  24. compress: false,
  25. /* Runs the less parser and just reports errors without any output. */
  26. lint: false,
  27. /* Sets available include paths.
  28. * If the file in an @import rule does not exist at that exact location,
  29. * less will look for it at the location(s) passed to this option.
  30. * You might use this for instance to specify a path to a library which
  31. * you want to be referenced simply and relatively in the less files. */
  32. paths: [],
  33. /* color output in the terminal */
  34. color: true,
  35. /* The strictImports controls whether the compiler will allow an @import inside of either
  36. * @media blocks or (a later addition) other selector blocks.
  37. * See: https://github.com/less/less.js/issues/656 */
  38. strictImports: false,
  39. /* Allow Imports from Insecure HTTPS Hosts */
  40. insecure: false,
  41. /* Allows you to add a path to every generated import and url in your css.
  42. * This does not affect less import statements that are processed, just ones
  43. * that are left in the output css. */
  44. rootpath: '',
  45. /* By default URLs are kept as-is, so if you import a file in a sub-directory
  46. * that references an image, exactly the same URL will be output in the css.
  47. * This option allows you to re-write URL's in imported files so that the
  48. * URL is always relative to the base imported file */
  49. rewriteUrls: false,
  50. /* How to process math
  51. * 0 always - eagerly try to solve all operations
  52. * 1 parens-division - require parens for division "/"
  53. * 2 parens | strict - require parens for all operations
  54. * 3 strict-legacy - legacy strict behavior (super-strict)
  55. */
  56. math: 0,
  57. /* Without this option, less attempts to guess at the output unit when it does maths. */
  58. strictUnits: false,
  59. /* Effectively the declaration is put at the top of your base Less file,
  60. * meaning it can be used but it also can be overridden if this variable
  61. * is defined in the file. */
  62. globalVars: null,
  63. /* As opposed to the global variable option, this puts the declaration at the
  64. * end of your base file, meaning it will override anything defined in your Less file. */
  65. modifyVars: null,
  66. /* This option allows you to specify a argument to go on to every URL. */
  67. urlArgs: ''
  68. }); });
  69. function extractId(href) {
  70. return href.replace(/^[a-z-]+:\/+?[^\/]+/, '') // Remove protocol & domain
  71. .replace(/[\?\&]livereload=\w+/, '') // Remove LiveReload cachebuster
  72. .replace(/^\//, '') // Remove root /
  73. .replace(/\.[a-zA-Z]+$/, '') // Remove simple extension
  74. .replace(/[^\.\w-]+/g, '-') // Replace illegal characters
  75. .replace(/\./g, ':'); // Replace dots with colons(for valid id)
  76. }
  77. function addDataAttr(options, tag) {
  78. for (var opt in tag.dataset) {
  79. if (tag.dataset.hasOwnProperty(opt)) {
  80. if (opt === 'env' || opt === 'dumpLineNumbers' || opt === 'rootpath' || opt === 'errorReporting') {
  81. options[opt] = tag.dataset[opt];
  82. }
  83. else {
  84. try {
  85. options[opt] = JSON.parse(tag.dataset[opt]);
  86. }
  87. catch (_) { }
  88. }
  89. }
  90. }
  91. }
  92. var browser = {
  93. createCSS: function (document, styles, sheet) {
  94. // Strip the query-string
  95. var href = sheet.href || '';
  96. // If there is no title set, use the filename, minus the extension
  97. var id = "less:" + (sheet.title || extractId(href));
  98. // If this has already been inserted into the DOM, we may need to replace it
  99. var oldStyleNode = document.getElementById(id);
  100. var keepOldStyleNode = false;
  101. // Create a new stylesheet node for insertion or (if necessary) replacement
  102. var styleNode = document.createElement('style');
  103. styleNode.setAttribute('type', 'text/css');
  104. if (sheet.media) {
  105. styleNode.setAttribute('media', sheet.media);
  106. }
  107. styleNode.id = id;
  108. if (!styleNode.styleSheet) {
  109. styleNode.appendChild(document.createTextNode(styles));
  110. // If new contents match contents of oldStyleNode, don't replace oldStyleNode
  111. keepOldStyleNode = (oldStyleNode !== null && oldStyleNode.childNodes.length > 0 && styleNode.childNodes.length > 0 &&
  112. oldStyleNode.firstChild.nodeValue === styleNode.firstChild.nodeValue);
  113. }
  114. var head = document.getElementsByTagName('head')[0];
  115. // If there is no oldStyleNode, just append; otherwise, only append if we need
  116. // to replace oldStyleNode with an updated stylesheet
  117. if (oldStyleNode === null || keepOldStyleNode === false) {
  118. var nextEl = sheet && sheet.nextSibling || null;
  119. if (nextEl) {
  120. nextEl.parentNode.insertBefore(styleNode, nextEl);
  121. }
  122. else {
  123. head.appendChild(styleNode);
  124. }
  125. }
  126. if (oldStyleNode && keepOldStyleNode === false) {
  127. oldStyleNode.parentNode.removeChild(oldStyleNode);
  128. }
  129. // For IE.
  130. // This needs to happen *after* the style element is added to the DOM, otherwise IE 7 and 8 may crash.
  131. // See http://social.msdn.microsoft.com/Forums/en-US/7e081b65-878a-4c22-8e68-c10d39c2ed32/internet-explorer-crashes-appending-style-element-to-head
  132. if (styleNode.styleSheet) {
  133. try {
  134. styleNode.styleSheet.cssText = styles;
  135. }
  136. catch (e) {
  137. throw new Error('Couldn\'t reassign styleSheet.cssText.');
  138. }
  139. }
  140. },
  141. currentScript: function (window) {
  142. var document = window.document;
  143. return document.currentScript || (function () {
  144. var scripts = document.getElementsByTagName('script');
  145. return scripts[scripts.length - 1];
  146. })();
  147. }
  148. };
  149. var addDefaultOptions = (function (window, options) {
  150. // use options from the current script tag data attribues
  151. addDataAttr(options, browser.currentScript(window));
  152. if (options.isFileProtocol === undefined) {
  153. options.isFileProtocol = /^(file|(chrome|safari)(-extension)?|resource|qrc|app):/.test(window.location.protocol);
  154. }
  155. // Load styles asynchronously (default: false)
  156. //
  157. // This is set to `false` by default, so that the body
  158. // doesn't start loading before the stylesheets are parsed.
  159. // Setting this to `true` can result in flickering.
  160. //
  161. options.async = options.async || false;
  162. options.fileAsync = options.fileAsync || false;
  163. // Interval between watch polls
  164. options.poll = options.poll || (options.isFileProtocol ? 1000 : 1500);
  165. options.env = options.env || (window.location.hostname == '127.0.0.1' ||
  166. window.location.hostname == '0.0.0.0' ||
  167. window.location.hostname == 'localhost' ||
  168. (window.location.port &&
  169. window.location.port.length > 0) ||
  170. options.isFileProtocol ? 'development'
  171. : 'production');
  172. var dumpLineNumbers = /!dumpLineNumbers:(comments|mediaquery|all)/.exec(window.location.hash);
  173. if (dumpLineNumbers) {
  174. options.dumpLineNumbers = dumpLineNumbers[1];
  175. }
  176. if (options.useFileCache === undefined) {
  177. options.useFileCache = true;
  178. }
  179. if (options.onReady === undefined) {
  180. options.onReady = true;
  181. }
  182. if (options.relativeUrls) {
  183. options.rewriteUrls = 'all';
  184. }
  185. });
  186. /*! *****************************************************************************
  187. Copyright (c) Microsoft Corporation.
  188. Permission to use, copy, modify, and/or distribute this software for any
  189. purpose with or without fee is hereby granted.
  190. THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH
  191. REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY
  192. AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,
  193. INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM
  194. LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR
  195. OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
  196. PERFORMANCE OF THIS SOFTWARE.
  197. ***************************************************************************** */
  198. /* global Reflect, Promise */
  199. var extendStatics = function (d, b) {
  200. extendStatics = Object.setPrototypeOf ||
  201. ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
  202. function (d, b) { for (var p in b)
  203. if (b.hasOwnProperty(p))
  204. d[p] = b[p]; };
  205. return extendStatics(d, b);
  206. };
  207. function __extends(d, b) {
  208. extendStatics(d, b);
  209. function __() { this.constructor = d; }
  210. d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
  211. }
  212. var __assign = function () {
  213. __assign = Object.assign || function __assign(t) {
  214. for (var s, i = 1, n = arguments.length; i < n; i++) {
  215. s = arguments[i];
  216. for (var p in s)
  217. if (Object.prototype.hasOwnProperty.call(s, p))
  218. t[p] = s[p];
  219. }
  220. return t;
  221. };
  222. return __assign.apply(this, arguments);
  223. };
  224. function __spreadArrays() {
  225. for (var s = 0, i = 0, il = arguments.length; i < il; i++)
  226. s += arguments[i].length;
  227. for (var r = Array(s), k = 0, i = 0; i < il; i++)
  228. for (var a = arguments[i], j = 0, jl = a.length; j < jl; j++, k++)
  229. r[k] = a[j];
  230. return r;
  231. }
  232. var colors = {
  233. 'aliceblue': '#f0f8ff',
  234. 'antiquewhite': '#faebd7',
  235. 'aqua': '#00ffff',
  236. 'aquamarine': '#7fffd4',
  237. 'azure': '#f0ffff',
  238. 'beige': '#f5f5dc',
  239. 'bisque': '#ffe4c4',
  240. 'black': '#000000',
  241. 'blanchedalmond': '#ffebcd',
  242. 'blue': '#0000ff',
  243. 'blueviolet': '#8a2be2',
  244. 'brown': '#a52a2a',
  245. 'burlywood': '#deb887',
  246. 'cadetblue': '#5f9ea0',
  247. 'chartreuse': '#7fff00',
  248. 'chocolate': '#d2691e',
  249. 'coral': '#ff7f50',
  250. 'cornflowerblue': '#6495ed',
  251. 'cornsilk': '#fff8dc',
  252. 'crimson': '#dc143c',
  253. 'cyan': '#00ffff',
  254. 'darkblue': '#00008b',
  255. 'darkcyan': '#008b8b',
  256. 'darkgoldenrod': '#b8860b',
  257. 'darkgray': '#a9a9a9',
  258. 'darkgrey': '#a9a9a9',
  259. 'darkgreen': '#006400',
  260. 'darkkhaki': '#bdb76b',
  261. 'darkmagenta': '#8b008b',
  262. 'darkolivegreen': '#556b2f',
  263. 'darkorange': '#ff8c00',
  264. 'darkorchid': '#9932cc',
  265. 'darkred': '#8b0000',
  266. 'darksalmon': '#e9967a',
  267. 'darkseagreen': '#8fbc8f',
  268. 'darkslateblue': '#483d8b',
  269. 'darkslategray': '#2f4f4f',
  270. 'darkslategrey': '#2f4f4f',
  271. 'darkturquoise': '#00ced1',
  272. 'darkviolet': '#9400d3',
  273. 'deeppink': '#ff1493',
  274. 'deepskyblue': '#00bfff',
  275. 'dimgray': '#696969',
  276. 'dimgrey': '#696969',
  277. 'dodgerblue': '#1e90ff',
  278. 'firebrick': '#b22222',
  279. 'floralwhite': '#fffaf0',
  280. 'forestgreen': '#228b22',
  281. 'fuchsia': '#ff00ff',
  282. 'gainsboro': '#dcdcdc',
  283. 'ghostwhite': '#f8f8ff',
  284. 'gold': '#ffd700',
  285. 'goldenrod': '#daa520',
  286. 'gray': '#808080',
  287. 'grey': '#808080',
  288. 'green': '#008000',
  289. 'greenyellow': '#adff2f',
  290. 'honeydew': '#f0fff0',
  291. 'hotpink': '#ff69b4',
  292. 'indianred': '#cd5c5c',
  293. 'indigo': '#4b0082',
  294. 'ivory': '#fffff0',
  295. 'khaki': '#f0e68c',
  296. 'lavender': '#e6e6fa',
  297. 'lavenderblush': '#fff0f5',
  298. 'lawngreen': '#7cfc00',
  299. 'lemonchiffon': '#fffacd',
  300. 'lightblue': '#add8e6',
  301. 'lightcoral': '#f08080',
  302. 'lightcyan': '#e0ffff',
  303. 'lightgoldenrodyellow': '#fafad2',
  304. 'lightgray': '#d3d3d3',
  305. 'lightgrey': '#d3d3d3',
  306. 'lightgreen': '#90ee90',
  307. 'lightpink': '#ffb6c1',
  308. 'lightsalmon': '#ffa07a',
  309. 'lightseagreen': '#20b2aa',
  310. 'lightskyblue': '#87cefa',
  311. 'lightslategray': '#778899',
  312. 'lightslategrey': '#778899',
  313. 'lightsteelblue': '#b0c4de',
  314. 'lightyellow': '#ffffe0',
  315. 'lime': '#00ff00',
  316. 'limegreen': '#32cd32',
  317. 'linen': '#faf0e6',
  318. 'magenta': '#ff00ff',
  319. 'maroon': '#800000',
  320. 'mediumaquamarine': '#66cdaa',
  321. 'mediumblue': '#0000cd',
  322. 'mediumorchid': '#ba55d3',
  323. 'mediumpurple': '#9370d8',
  324. 'mediumseagreen': '#3cb371',
  325. 'mediumslateblue': '#7b68ee',
  326. 'mediumspringgreen': '#00fa9a',
  327. 'mediumturquoise': '#48d1cc',
  328. 'mediumvioletred': '#c71585',
  329. 'midnightblue': '#191970',
  330. 'mintcream': '#f5fffa',
  331. 'mistyrose': '#ffe4e1',
  332. 'moccasin': '#ffe4b5',
  333. 'navajowhite': '#ffdead',
  334. 'navy': '#000080',
  335. 'oldlace': '#fdf5e6',
  336. 'olive': '#808000',
  337. 'olivedrab': '#6b8e23',
  338. 'orange': '#ffa500',
  339. 'orangered': '#ff4500',
  340. 'orchid': '#da70d6',
  341. 'palegoldenrod': '#eee8aa',
  342. 'palegreen': '#98fb98',
  343. 'paleturquoise': '#afeeee',
  344. 'palevioletred': '#d87093',
  345. 'papayawhip': '#ffefd5',
  346. 'peachpuff': '#ffdab9',
  347. 'peru': '#cd853f',
  348. 'pink': '#ffc0cb',
  349. 'plum': '#dda0dd',
  350. 'powderblue': '#b0e0e6',
  351. 'purple': '#800080',
  352. 'rebeccapurple': '#663399',
  353. 'red': '#ff0000',
  354. 'rosybrown': '#bc8f8f',
  355. 'royalblue': '#4169e1',
  356. 'saddlebrown': '#8b4513',
  357. 'salmon': '#fa8072',
  358. 'sandybrown': '#f4a460',
  359. 'seagreen': '#2e8b57',
  360. 'seashell': '#fff5ee',
  361. 'sienna': '#a0522d',
  362. 'silver': '#c0c0c0',
  363. 'skyblue': '#87ceeb',
  364. 'slateblue': '#6a5acd',
  365. 'slategray': '#708090',
  366. 'slategrey': '#708090',
  367. 'snow': '#fffafa',
  368. 'springgreen': '#00ff7f',
  369. 'steelblue': '#4682b4',
  370. 'tan': '#d2b48c',
  371. 'teal': '#008080',
  372. 'thistle': '#d8bfd8',
  373. 'tomato': '#ff6347',
  374. 'turquoise': '#40e0d0',
  375. 'violet': '#ee82ee',
  376. 'wheat': '#f5deb3',
  377. 'white': '#ffffff',
  378. 'whitesmoke': '#f5f5f5',
  379. 'yellow': '#ffff00',
  380. 'yellowgreen': '#9acd32'
  381. };
  382. var unitConversions = {
  383. length: {
  384. 'm': 1,
  385. 'cm': 0.01,
  386. 'mm': 0.001,
  387. 'in': 0.0254,
  388. 'px': 0.0254 / 96,
  389. 'pt': 0.0254 / 72,
  390. 'pc': 0.0254 / 72 * 12
  391. },
  392. duration: {
  393. 's': 1,
  394. 'ms': 0.001
  395. },
  396. angle: {
  397. 'rad': 1 / (2 * Math.PI),
  398. 'deg': 1 / 360,
  399. 'grad': 1 / 400,
  400. 'turn': 1
  401. }
  402. };
  403. var data = { colors: colors, unitConversions: unitConversions };
  404. var Node = /** @class */ (function () {
  405. function Node() {
  406. this.parent = null;
  407. this.visibilityBlocks = undefined;
  408. this.nodeVisible = undefined;
  409. this.rootNode = null;
  410. this.parsed = null;
  411. var self = this;
  412. Object.defineProperty(this, 'currentFileInfo', {
  413. get: function () { return self.fileInfo(); }
  414. });
  415. Object.defineProperty(this, 'index', {
  416. get: function () { return self.getIndex(); }
  417. });
  418. }
  419. Node.prototype.setParent = function (nodes, parent) {
  420. function set(node) {
  421. if (node && node instanceof Node) {
  422. node.parent = parent;
  423. }
  424. }
  425. if (Array.isArray(nodes)) {
  426. nodes.forEach(set);
  427. }
  428. else {
  429. set(nodes);
  430. }
  431. };
  432. Node.prototype.getIndex = function () {
  433. return this._index || (this.parent && this.parent.getIndex()) || 0;
  434. };
  435. Node.prototype.fileInfo = function () {
  436. return this._fileInfo || (this.parent && this.parent.fileInfo()) || {};
  437. };
  438. Node.prototype.isRulesetLike = function () {
  439. return false;
  440. };
  441. Node.prototype.toCSS = function (context) {
  442. var strs = [];
  443. this.genCSS(context, {
  444. add: function (chunk, fileInfo, index) {
  445. strs.push(chunk);
  446. },
  447. isEmpty: function () {
  448. return strs.length === 0;
  449. }
  450. });
  451. return strs.join('');
  452. };
  453. Node.prototype.genCSS = function (context, output) {
  454. output.add(this.value);
  455. };
  456. Node.prototype.accept = function (visitor) {
  457. this.value = visitor.visit(this.value);
  458. };
  459. Node.prototype.eval = function () { return this; };
  460. Node.prototype._operate = function (context, op, a, b) {
  461. switch (op) {
  462. case '+': return a + b;
  463. case '-': return a - b;
  464. case '*': return a * b;
  465. case '/': return a / b;
  466. }
  467. };
  468. Node.prototype.fround = function (context, value) {
  469. var precision = context && context.numPrecision;
  470. // add "epsilon" to ensure numbers like 1.000000005 (represented as 1.000000004999...) are properly rounded:
  471. return (precision) ? Number((value + 2e-16).toFixed(precision)) : value;
  472. };
  473. // Returns true if this node represents root of ast imported by reference
  474. Node.prototype.blocksVisibility = function () {
  475. if (this.visibilityBlocks == null) {
  476. this.visibilityBlocks = 0;
  477. }
  478. return this.visibilityBlocks !== 0;
  479. };
  480. Node.prototype.addVisibilityBlock = function () {
  481. if (this.visibilityBlocks == null) {
  482. this.visibilityBlocks = 0;
  483. }
  484. this.visibilityBlocks = this.visibilityBlocks + 1;
  485. };
  486. Node.prototype.removeVisibilityBlock = function () {
  487. if (this.visibilityBlocks == null) {
  488. this.visibilityBlocks = 0;
  489. }
  490. this.visibilityBlocks = this.visibilityBlocks - 1;
  491. };
  492. // Turns on node visibility - if called node will be shown in output regardless
  493. // of whether it comes from import by reference or not
  494. Node.prototype.ensureVisibility = function () {
  495. this.nodeVisible = true;
  496. };
  497. // Turns off node visibility - if called node will NOT be shown in output regardless
  498. // of whether it comes from import by reference or not
  499. Node.prototype.ensureInvisibility = function () {
  500. this.nodeVisible = false;
  501. };
  502. // return values:
  503. // false - the node must not be visible
  504. // true - the node must be visible
  505. // undefined or null - the node has the same visibility as its parent
  506. Node.prototype.isVisible = function () {
  507. return this.nodeVisible;
  508. };
  509. Node.prototype.visibilityInfo = function () {
  510. return {
  511. visibilityBlocks: this.visibilityBlocks,
  512. nodeVisible: this.nodeVisible
  513. };
  514. };
  515. Node.prototype.copyVisibilityInfo = function (info) {
  516. if (!info) {
  517. return;
  518. }
  519. this.visibilityBlocks = info.visibilityBlocks;
  520. this.nodeVisible = info.nodeVisible;
  521. };
  522. return Node;
  523. }());
  524. Node.compare = function (a, b) {
  525. /* returns:
  526. -1: a < b
  527. 0: a = b
  528. 1: a > b
  529. and *any* other value for a != b (e.g. undefined, NaN, -2 etc.) */
  530. if ((a.compare) &&
  531. // for "symmetric results" force toCSS-based comparison
  532. // of Quoted or Anonymous if either value is one of those
  533. !(b.type === 'Quoted' || b.type === 'Anonymous')) {
  534. return a.compare(b);
  535. }
  536. else if (b.compare) {
  537. return -b.compare(a);
  538. }
  539. else if (a.type !== b.type) {
  540. return undefined;
  541. }
  542. a = a.value;
  543. b = b.value;
  544. if (!Array.isArray(a)) {
  545. return a === b ? 0 : undefined;
  546. }
  547. if (a.length !== b.length) {
  548. return undefined;
  549. }
  550. for (var i = 0; i < a.length; i++) {
  551. if (Node.compare(a[i], b[i]) !== 0) {
  552. return undefined;
  553. }
  554. }
  555. return 0;
  556. };
  557. Node.numericCompare = function (a, b) { return a < b ? -1
  558. : a === b ? 0
  559. : a > b ? 1 : undefined; };
  560. //
  561. // RGB Colors - #ff0014, #eee
  562. //
  563. var Color = /** @class */ (function (_super) {
  564. __extends(Color, _super);
  565. function Color(rgb, a, originalForm) {
  566. var _this = _super.call(this) || this;
  567. var self = _this;
  568. //
  569. // The end goal here, is to parse the arguments
  570. // into an integer triplet, such as `128, 255, 0`
  571. //
  572. // This facilitates operations and conversions.
  573. //
  574. if (Array.isArray(rgb)) {
  575. _this.rgb = rgb;
  576. }
  577. else if (rgb.length >= 6) {
  578. _this.rgb = [];
  579. rgb.match(/.{2}/g).map(function (c, i) {
  580. if (i < 3) {
  581. self.rgb.push(parseInt(c, 16));
  582. }
  583. else {
  584. self.alpha = (parseInt(c, 16)) / 255;
  585. }
  586. });
  587. }
  588. else {
  589. _this.rgb = [];
  590. rgb.split('').map(function (c, i) {
  591. if (i < 3) {
  592. self.rgb.push(parseInt(c + c, 16));
  593. }
  594. else {
  595. self.alpha = (parseInt(c + c, 16)) / 255;
  596. }
  597. });
  598. }
  599. _this.alpha = _this.alpha || (typeof a === 'number' ? a : 1);
  600. if (typeof originalForm !== 'undefined') {
  601. _this.value = originalForm;
  602. }
  603. return _this;
  604. }
  605. Color.prototype.luma = function () {
  606. var r = this.rgb[0] / 255;
  607. var g = this.rgb[1] / 255;
  608. var b = this.rgb[2] / 255;
  609. r = (r <= 0.03928) ? r / 12.92 : Math.pow(((r + 0.055) / 1.055), 2.4);
  610. g = (g <= 0.03928) ? g / 12.92 : Math.pow(((g + 0.055) / 1.055), 2.4);
  611. b = (b <= 0.03928) ? b / 12.92 : Math.pow(((b + 0.055) / 1.055), 2.4);
  612. return 0.2126 * r + 0.7152 * g + 0.0722 * b;
  613. };
  614. Color.prototype.genCSS = function (context, output) {
  615. output.add(this.toCSS(context));
  616. };
  617. Color.prototype.toCSS = function (context, doNotCompress) {
  618. var compress = context && context.compress && !doNotCompress;
  619. var color;
  620. var alpha;
  621. var colorFunction;
  622. var args = [];
  623. // `value` is set if this color was originally
  624. // converted from a named color string so we need
  625. // to respect this and try to output named color too.
  626. alpha = this.fround(context, this.alpha);
  627. if (this.value) {
  628. if (this.value.indexOf('rgb') === 0) {
  629. if (alpha < 1) {
  630. colorFunction = 'rgba';
  631. }
  632. }
  633. else if (this.value.indexOf('hsl') === 0) {
  634. if (alpha < 1) {
  635. colorFunction = 'hsla';
  636. }
  637. else {
  638. colorFunction = 'hsl';
  639. }
  640. }
  641. else {
  642. return this.value;
  643. }
  644. }
  645. else {
  646. if (alpha < 1) {
  647. colorFunction = 'rgba';
  648. }
  649. }
  650. switch (colorFunction) {
  651. case 'rgba':
  652. args = this.rgb.map(function (c) { return clamp(Math.round(c), 255); }).concat(clamp(alpha, 1));
  653. break;
  654. case 'hsla':
  655. args.push(clamp(alpha, 1));
  656. case 'hsl':
  657. color = this.toHSL();
  658. args = [
  659. this.fround(context, color.h),
  660. this.fround(context, color.s * 100) + "%",
  661. this.fround(context, color.l * 100) + "%"
  662. ].concat(args);
  663. }
  664. if (colorFunction) {
  665. // Values are capped between `0` and `255`, rounded and zero-padded.
  666. return colorFunction + "(" + args.join("," + (compress ? '' : ' ')) + ")";
  667. }
  668. color = this.toRGB();
  669. if (compress) {
  670. var splitcolor = color.split('');
  671. // Convert color to short format
  672. if (splitcolor[1] === splitcolor[2] && splitcolor[3] === splitcolor[4] && splitcolor[5] === splitcolor[6]) {
  673. color = "#" + splitcolor[1] + splitcolor[3] + splitcolor[5];
  674. }
  675. }
  676. return color;
  677. };
  678. //
  679. // Operations have to be done per-channel, if not,
  680. // channels will spill onto each other. Once we have
  681. // our result, in the form of an integer triplet,
  682. // we create a new Color node to hold the result.
  683. //
  684. Color.prototype.operate = function (context, op, other) {
  685. var rgb = new Array(3);
  686. var alpha = this.alpha * (1 - other.alpha) + other.alpha;
  687. for (var c = 0; c < 3; c++) {
  688. rgb[c] = this._operate(context, op, this.rgb[c], other.rgb[c]);
  689. }
  690. return new Color(rgb, alpha);
  691. };
  692. Color.prototype.toRGB = function () {
  693. return toHex(this.rgb);
  694. };
  695. Color.prototype.toHSL = function () {
  696. var r = this.rgb[0] / 255;
  697. var g = this.rgb[1] / 255;
  698. var b = this.rgb[2] / 255;
  699. var a = this.alpha;
  700. var max = Math.max(r, g, b);
  701. var min = Math.min(r, g, b);
  702. var h;
  703. var s;
  704. var l = (max + min) / 2;
  705. var d = max - min;
  706. if (max === min) {
  707. h = s = 0;
  708. }
  709. else {
  710. s = l > 0.5 ? d / (2 - max - min) : d / (max + min);
  711. switch (max) {
  712. case r:
  713. h = (g - b) / d + (g < b ? 6 : 0);
  714. break;
  715. case g:
  716. h = (b - r) / d + 2;
  717. break;
  718. case b:
  719. h = (r - g) / d + 4;
  720. break;
  721. }
  722. h /= 6;
  723. }
  724. return { h: h * 360, s: s, l: l, a: a };
  725. };
  726. // Adapted from http://mjijackson.com/2008/02/rgb-to-hsl-and-rgb-to-hsv-color-model-conversion-algorithms-in-javascript
  727. Color.prototype.toHSV = function () {
  728. var r = this.rgb[0] / 255;
  729. var g = this.rgb[1] / 255;
  730. var b = this.rgb[2] / 255;
  731. var a = this.alpha;
  732. var max = Math.max(r, g, b);
  733. var min = Math.min(r, g, b);
  734. var h;
  735. var s;
  736. var v = max;
  737. var d = max - min;
  738. if (max === 0) {
  739. s = 0;
  740. }
  741. else {
  742. s = d / max;
  743. }
  744. if (max === min) {
  745. h = 0;
  746. }
  747. else {
  748. switch (max) {
  749. case r:
  750. h = (g - b) / d + (g < b ? 6 : 0);
  751. break;
  752. case g:
  753. h = (b - r) / d + 2;
  754. break;
  755. case b:
  756. h = (r - g) / d + 4;
  757. break;
  758. }
  759. h /= 6;
  760. }
  761. return { h: h * 360, s: s, v: v, a: a };
  762. };
  763. Color.prototype.toARGB = function () {
  764. return toHex([this.alpha * 255].concat(this.rgb));
  765. };
  766. Color.prototype.compare = function (x) {
  767. return (x.rgb &&
  768. x.rgb[0] === this.rgb[0] &&
  769. x.rgb[1] === this.rgb[1] &&
  770. x.rgb[2] === this.rgb[2] &&
  771. x.alpha === this.alpha) ? 0 : undefined;
  772. };
  773. return Color;
  774. }(Node));
  775. Color.prototype.type = 'Color';
  776. function clamp(v, max) {
  777. return Math.min(Math.max(v, 0), max);
  778. }
  779. function toHex(v) {
  780. return "#" + v.map(function (c) {
  781. c = clamp(Math.round(c), 255);
  782. return (c < 16 ? '0' : '') + c.toString(16);
  783. }).join('');
  784. }
  785. Color.fromKeyword = function (keyword) {
  786. var c;
  787. var key = keyword.toLowerCase();
  788. if (colors.hasOwnProperty(key)) {
  789. c = new Color(colors[key].slice(1));
  790. }
  791. else if (key === 'transparent') {
  792. c = new Color([0, 0, 0], 0);
  793. }
  794. if (c) {
  795. c.value = keyword;
  796. return c;
  797. }
  798. };
  799. var Paren = /** @class */ (function (_super) {
  800. __extends(Paren, _super);
  801. function Paren(node) {
  802. var _this = _super.call(this) || this;
  803. _this.value = node;
  804. return _this;
  805. }
  806. Paren.prototype.genCSS = function (context, output) {
  807. output.add('(');
  808. this.value.genCSS(context, output);
  809. output.add(')');
  810. };
  811. Paren.prototype.eval = function (context) {
  812. return new Paren(this.value.eval(context));
  813. };
  814. return Paren;
  815. }(Node));
  816. Paren.prototype.type = 'Paren';
  817. var _noSpaceCombinators = {
  818. '': true,
  819. ' ': true,
  820. '|': true
  821. };
  822. var Combinator = /** @class */ (function (_super) {
  823. __extends(Combinator, _super);
  824. function Combinator(value) {
  825. var _this = _super.call(this) || this;
  826. if (value === ' ') {
  827. _this.value = ' ';
  828. _this.emptyOrWhitespace = true;
  829. }
  830. else {
  831. _this.value = value ? value.trim() : '';
  832. _this.emptyOrWhitespace = _this.value === '';
  833. }
  834. return _this;
  835. }
  836. Combinator.prototype.genCSS = function (context, output) {
  837. var spaceOrEmpty = (context.compress || _noSpaceCombinators[this.value]) ? '' : ' ';
  838. output.add(spaceOrEmpty + this.value + spaceOrEmpty);
  839. };
  840. return Combinator;
  841. }(Node));
  842. Combinator.prototype.type = 'Combinator';
  843. var Element = /** @class */ (function (_super) {
  844. __extends(Element, _super);
  845. function Element(combinator, value, isVariable, index, currentFileInfo, visibilityInfo) {
  846. var _this = _super.call(this) || this;
  847. _this.combinator = combinator instanceof Combinator ?
  848. combinator : new Combinator(combinator);
  849. if (typeof value === 'string') {
  850. _this.value = value.trim();
  851. }
  852. else if (value) {
  853. _this.value = value;
  854. }
  855. else {
  856. _this.value = '';
  857. }
  858. _this.isVariable = isVariable;
  859. _this._index = index;
  860. _this._fileInfo = currentFileInfo;
  861. _this.copyVisibilityInfo(visibilityInfo);
  862. _this.setParent(_this.combinator, _this);
  863. return _this;
  864. }
  865. Element.prototype.accept = function (visitor) {
  866. var value = this.value;
  867. this.combinator = visitor.visit(this.combinator);
  868. if (typeof value === 'object') {
  869. this.value = visitor.visit(value);
  870. }
  871. };
  872. Element.prototype.eval = function (context) {
  873. return new Element(this.combinator, this.value.eval ? this.value.eval(context) : this.value, this.isVariable, this.getIndex(), this.fileInfo(), this.visibilityInfo());
  874. };
  875. Element.prototype.clone = function () {
  876. return new Element(this.combinator, this.value, this.isVariable, this.getIndex(), this.fileInfo(), this.visibilityInfo());
  877. };
  878. Element.prototype.genCSS = function (context, output) {
  879. output.add(this.toCSS(context), this.fileInfo(), this.getIndex());
  880. };
  881. Element.prototype.toCSS = function (context) {
  882. if (context === void 0) { context = {}; }
  883. var value = this.value;
  884. var firstSelector = context.firstSelector;
  885. if (value instanceof Paren) {
  886. // selector in parens should not be affected by outer selector
  887. // flags (breaks only interpolated selectors - see #1973)
  888. context.firstSelector = true;
  889. }
  890. value = value.toCSS ? value.toCSS(context) : value;
  891. context.firstSelector = firstSelector;
  892. if (value === '' && this.combinator.value.charAt(0) === '&') {
  893. return '';
  894. }
  895. else {
  896. return this.combinator.toCSS(context) + value;
  897. }
  898. };
  899. return Element;
  900. }(Node));
  901. Element.prototype.type = 'Element';
  902. var Math$1 = {
  903. ALWAYS: 0,
  904. PARENS_DIVISION: 1,
  905. PARENS: 2,
  906. STRICT_LEGACY: 3
  907. };
  908. var RewriteUrls = {
  909. OFF: 0,
  910. LOCAL: 1,
  911. ALL: 2
  912. };
  913. function getLocation(index, inputStream) {
  914. var n = index + 1;
  915. var line = null;
  916. var column = -1;
  917. while (--n >= 0 && inputStream.charAt(n) !== '\n') {
  918. column++;
  919. }
  920. if (typeof index === 'number') {
  921. line = (inputStream.slice(0, index).match(/\n/g) || '').length;
  922. }
  923. return {
  924. line: line,
  925. column: column
  926. };
  927. }
  928. function copyArray(arr) {
  929. var i;
  930. var length = arr.length;
  931. var copy = new Array(length);
  932. for (i = 0; i < length; i++) {
  933. copy[i] = arr[i];
  934. }
  935. return copy;
  936. }
  937. function clone(obj) {
  938. var cloned = {};
  939. for (var prop in obj) {
  940. if (obj.hasOwnProperty(prop)) {
  941. cloned[prop] = obj[prop];
  942. }
  943. }
  944. return cloned;
  945. }
  946. function defaults(obj1, obj2) {
  947. var newObj = obj2 || {};
  948. if (!obj2._defaults) {
  949. newObj = {};
  950. var defaults_1 = __assign({}, obj1);
  951. newObj._defaults = defaults_1;
  952. var cloned = obj2 ? __assign({}, obj2) : {};
  953. Object.assign(newObj, defaults_1, cloned);
  954. }
  955. return newObj;
  956. }
  957. function copyOptions(obj1, obj2) {
  958. if (obj2 && obj2._defaults) {
  959. return obj2;
  960. }
  961. var opts = defaults(obj1, obj2);
  962. if (opts.strictMath) {
  963. opts.math = Math$1.STRICT_LEGACY;
  964. }
  965. // Back compat with changed relativeUrls option
  966. if (opts.relativeUrls) {
  967. opts.rewriteUrls = RewriteUrls.ALL;
  968. }
  969. if (typeof opts.math === 'string') {
  970. switch (opts.math.toLowerCase()) {
  971. case 'always':
  972. opts.math = Math$1.ALWAYS;
  973. break;
  974. case 'parens-division':
  975. opts.math = Math$1.PARENS_DIVISION;
  976. break;
  977. case 'strict':
  978. case 'parens':
  979. opts.math = Math$1.PARENS;
  980. break;
  981. case 'strict-legacy':
  982. opts.math = Math$1.STRICT_LEGACY;
  983. }
  984. }
  985. if (typeof opts.rewriteUrls === 'string') {
  986. switch (opts.rewriteUrls.toLowerCase()) {
  987. case 'off':
  988. opts.rewriteUrls = RewriteUrls.OFF;
  989. break;
  990. case 'local':
  991. opts.rewriteUrls = RewriteUrls.LOCAL;
  992. break;
  993. case 'all':
  994. opts.rewriteUrls = RewriteUrls.ALL;
  995. break;
  996. }
  997. }
  998. return opts;
  999. }
  1000. function merge(obj1, obj2) {
  1001. for (var prop in obj2) {
  1002. if (obj2.hasOwnProperty(prop)) {
  1003. obj1[prop] = obj2[prop];
  1004. }
  1005. }
  1006. return obj1;
  1007. }
  1008. function flattenArray(arr, result) {
  1009. if (result === void 0) { result = []; }
  1010. for (var i = 0, length_1 = arr.length; i < length_1; i++) {
  1011. var value = arr[i];
  1012. if (Array.isArray(value)) {
  1013. flattenArray(value, result);
  1014. }
  1015. else {
  1016. if (value !== undefined) {
  1017. result.push(value);
  1018. }
  1019. }
  1020. }
  1021. return result;
  1022. }
  1023. var utils = /*#__PURE__*/Object.freeze({
  1024. __proto__: null,
  1025. getLocation: getLocation,
  1026. copyArray: copyArray,
  1027. clone: clone,
  1028. defaults: defaults,
  1029. copyOptions: copyOptions,
  1030. merge: merge,
  1031. flattenArray: flattenArray
  1032. });
  1033. var anonymousFunc = /(<anonymous>|Function):(\d+):(\d+)/;
  1034. /**
  1035. * This is a centralized class of any error that could be thrown internally (mostly by the parser).
  1036. * Besides standard .message it keeps some additional data like a path to the file where the error
  1037. * occurred along with line and column numbers.
  1038. *
  1039. * @class
  1040. * @extends Error
  1041. * @type {module.LessError}
  1042. *
  1043. * @prop {string} type
  1044. * @prop {string} filename
  1045. * @prop {number} index
  1046. * @prop {number} line
  1047. * @prop {number} column
  1048. * @prop {number} callLine
  1049. * @prop {number} callExtract
  1050. * @prop {string[]} extract
  1051. *
  1052. * @param {Object} e - An error object to wrap around or just a descriptive object
  1053. * @param {Object} fileContentMap - An object with file contents in 'contents' property (like importManager) @todo - move to fileManager?
  1054. * @param {string} [currentFilename]
  1055. */
  1056. var LessError = function LessError(e, fileContentMap, currentFilename) {
  1057. Error.call(this);
  1058. var filename = e.filename || currentFilename;
  1059. this.message = e.message;
  1060. this.stack = e.stack;
  1061. if (fileContentMap && filename) {
  1062. var input = fileContentMap.contents[filename];
  1063. var loc = getLocation(e.index, input);
  1064. var line = loc.line;
  1065. var col = loc.column;
  1066. var callLine = e.call && getLocation(e.call, input).line;
  1067. var lines = input ? input.split('\n') : '';
  1068. this.type = e.type || 'Syntax';
  1069. this.filename = filename;
  1070. this.index = e.index;
  1071. this.line = typeof line === 'number' ? line + 1 : null;
  1072. this.column = col;
  1073. if (!this.line && this.stack) {
  1074. var found = this.stack.match(anonymousFunc);
  1075. /**
  1076. * We have to figure out how this environment stringifies anonymous functions
  1077. * so we can correctly map plugin errors.
  1078. *
  1079. * Note, in Node 8, the output of anonymous funcs varied based on parameters
  1080. * being present or not, so we inject dummy params.
  1081. */
  1082. var func = new Function('a', 'throw new Error()');
  1083. var lineAdjust = 0;
  1084. try {
  1085. func();
  1086. }
  1087. catch (e) {
  1088. var match = e.stack.match(anonymousFunc);
  1089. var line_1 = parseInt(match[2]);
  1090. lineAdjust = 1 - line_1;
  1091. }
  1092. if (found) {
  1093. if (found[2]) {
  1094. this.line = parseInt(found[2]) + lineAdjust;
  1095. }
  1096. if (found[3]) {
  1097. this.column = parseInt(found[3]);
  1098. }
  1099. }
  1100. }
  1101. this.callLine = callLine + 1;
  1102. this.callExtract = lines[callLine];
  1103. this.extract = [
  1104. lines[this.line - 2],
  1105. lines[this.line - 1],
  1106. lines[this.line]
  1107. ];
  1108. }
  1109. };
  1110. if (typeof Object.create === 'undefined') {
  1111. var F = function () { };
  1112. F.prototype = Error.prototype;
  1113. LessError.prototype = new F();
  1114. }
  1115. else {
  1116. LessError.prototype = Object.create(Error.prototype);
  1117. }
  1118. LessError.prototype.constructor = LessError;
  1119. /**
  1120. * An overridden version of the default Object.prototype.toString
  1121. * which uses additional information to create a helpful message.
  1122. *
  1123. * @param {Object} options
  1124. * @returns {string}
  1125. */
  1126. LessError.prototype.toString = function (options) {
  1127. if (options === void 0) { options = {}; }
  1128. var message = '';
  1129. var extract = this.extract || [];
  1130. var error = [];
  1131. var stylize = function (str) { return str; };
  1132. if (options.stylize) {
  1133. var type = typeof options.stylize;
  1134. if (type !== 'function') {
  1135. throw Error("options.stylize should be a function, got a " + type + "!");
  1136. }
  1137. stylize = options.stylize;
  1138. }
  1139. if (this.line !== null) {
  1140. if (typeof extract[0] === 'string') {
  1141. error.push(stylize(this.line - 1 + " " + extract[0], 'grey'));
  1142. }
  1143. if (typeof extract[1] === 'string') {
  1144. var errorTxt = this.line + " ";
  1145. if (extract[1]) {
  1146. errorTxt += extract[1].slice(0, this.column) +
  1147. stylize(stylize(stylize(extract[1].substr(this.column, 1), 'bold') +
  1148. extract[1].slice(this.column + 1), 'red'), 'inverse');
  1149. }
  1150. error.push(errorTxt);
  1151. }
  1152. if (typeof extract[2] === 'string') {
  1153. error.push(stylize(this.line + 1 + " " + extract[2], 'grey'));
  1154. }
  1155. error = error.join('\n') + stylize('', 'reset') + "\n";
  1156. }
  1157. message += stylize(this.type + "Error: " + this.message, 'red');
  1158. if (this.filename) {
  1159. message += stylize(' in ', 'red') + this.filename;
  1160. }
  1161. if (this.line) {
  1162. message += stylize(" on line " + this.line + ", column " + (this.column + 1) + ":", 'grey');
  1163. }
  1164. message += "\n" + error;
  1165. if (this.callLine) {
  1166. message += stylize('from ', 'red') + (this.filename || '') + "/n";
  1167. message += stylize(this.callLine, 'grey') + " " + this.callExtract + "/n";
  1168. }
  1169. return message;
  1170. };
  1171. var Selector = /** @class */ (function (_super) {
  1172. __extends(Selector, _super);
  1173. function Selector(elements, extendList, condition, index, currentFileInfo, visibilityInfo) {
  1174. var _this = _super.call(this) || this;
  1175. _this.extendList = extendList;
  1176. _this.condition = condition;
  1177. _this.evaldCondition = !condition;
  1178. _this._index = index;
  1179. _this._fileInfo = currentFileInfo;
  1180. _this.elements = _this.getElements(elements);
  1181. _this.mixinElements_ = undefined;
  1182. _this.copyVisibilityInfo(visibilityInfo);
  1183. _this.setParent(_this.elements, _this);
  1184. return _this;
  1185. }
  1186. Selector.prototype.accept = function (visitor) {
  1187. if (this.elements) {
  1188. this.elements = visitor.visitArray(this.elements);
  1189. }
  1190. if (this.extendList) {
  1191. this.extendList = visitor.visitArray(this.extendList);
  1192. }
  1193. if (this.condition) {
  1194. this.condition = visitor.visit(this.condition);
  1195. }
  1196. };
  1197. Selector.prototype.createDerived = function (elements, extendList, evaldCondition) {
  1198. elements = this.getElements(elements);
  1199. var newSelector = new Selector(elements, extendList || this.extendList, null, this.getIndex(), this.fileInfo(), this.visibilityInfo());
  1200. newSelector.evaldCondition = (evaldCondition != null) ? evaldCondition : this.evaldCondition;
  1201. newSelector.mediaEmpty = this.mediaEmpty;
  1202. return newSelector;
  1203. };
  1204. Selector.prototype.getElements = function (els) {
  1205. if (!els) {
  1206. return [new Element('', '&', false, this._index, this._fileInfo)];
  1207. }
  1208. if (typeof els === 'string') {
  1209. this.parse.parseNode(els, ['selector'], this._index, this._fileInfo, function (err, result) {
  1210. if (err) {
  1211. throw new LessError({
  1212. index: err.index,
  1213. message: err.message
  1214. }, this.parse.imports, this._fileInfo.filename);
  1215. }
  1216. els = result[0].elements;
  1217. });
  1218. }
  1219. return els;
  1220. };
  1221. Selector.prototype.createEmptySelectors = function () {
  1222. var el = new Element('', '&', false, this._index, this._fileInfo);
  1223. var sels = [new Selector([el], null, null, this._index, this._fileInfo)];
  1224. sels[0].mediaEmpty = true;
  1225. return sels;
  1226. };
  1227. Selector.prototype.match = function (other) {
  1228. var elements = this.elements;
  1229. var len = elements.length;
  1230. var olen;
  1231. var i;
  1232. other = other.mixinElements();
  1233. olen = other.length;
  1234. if (olen === 0 || len < olen) {
  1235. return 0;
  1236. }
  1237. else {
  1238. for (i = 0; i < olen; i++) {
  1239. if (elements[i].value !== other[i]) {
  1240. return 0;
  1241. }
  1242. }
  1243. }
  1244. return olen; // return number of matched elements
  1245. };
  1246. Selector.prototype.mixinElements = function () {
  1247. if (this.mixinElements_) {
  1248. return this.mixinElements_;
  1249. }
  1250. var elements = this.elements.map(function (v) { return v.combinator.value + (v.value.value || v.value); }).join('').match(/[,&#\*\.\w-]([\w-]|(\\.))*/g);
  1251. if (elements) {
  1252. if (elements[0] === '&') {
  1253. elements.shift();
  1254. }
  1255. }
  1256. else {
  1257. elements = [];
  1258. }
  1259. return (this.mixinElements_ = elements);
  1260. };
  1261. Selector.prototype.isJustParentSelector = function () {
  1262. return !this.mediaEmpty &&
  1263. this.elements.length === 1 &&
  1264. this.elements[0].value === '&' &&
  1265. (this.elements[0].combinator.value === ' ' || this.elements[0].combinator.value === '');
  1266. };
  1267. Selector.prototype.eval = function (context) {
  1268. var evaldCondition = this.condition && this.condition.eval(context);
  1269. var elements = this.elements;
  1270. var extendList = this.extendList;
  1271. elements = elements && elements.map(function (e) { return e.eval(context); });
  1272. extendList = extendList && extendList.map(function (extend) { return extend.eval(context); });
  1273. return this.createDerived(elements, extendList, evaldCondition);
  1274. };
  1275. Selector.prototype.genCSS = function (context, output) {
  1276. var i;
  1277. var element;
  1278. if ((!context || !context.firstSelector) && this.elements[0].combinator.value === '') {
  1279. output.add(' ', this.fileInfo(), this.getIndex());
  1280. }
  1281. for (i = 0; i < this.elements.length; i++) {
  1282. element = this.elements[i];
  1283. element.genCSS(context, output);
  1284. }
  1285. };
  1286. Selector.prototype.getIsOutput = function () {
  1287. return this.evaldCondition;
  1288. };
  1289. return Selector;
  1290. }(Node));
  1291. Selector.prototype.type = 'Selector';
  1292. var Value = /** @class */ (function (_super) {
  1293. __extends(Value, _super);
  1294. function Value(value) {
  1295. var _this = _super.call(this) || this;
  1296. if (!value) {
  1297. throw new Error('Value requires an array argument');
  1298. }
  1299. if (!Array.isArray(value)) {
  1300. _this.value = [value];
  1301. }
  1302. else {
  1303. _this.value = value;
  1304. }
  1305. return _this;
  1306. }
  1307. Value.prototype.accept = function (visitor) {
  1308. if (this.value) {
  1309. this.value = visitor.visitArray(this.value);
  1310. }
  1311. };
  1312. Value.prototype.eval = function (context) {
  1313. if (this.value.length === 1) {
  1314. return this.value[0].eval(context);
  1315. }
  1316. else {
  1317. return new Value(this.value.map(function (v) { return v.eval(context); }));
  1318. }
  1319. };
  1320. Value.prototype.genCSS = function (context, output) {
  1321. var i;
  1322. for (i = 0; i < this.value.length; i++) {
  1323. this.value[i].genCSS(context, output);
  1324. if (i + 1 < this.value.length) {
  1325. output.add((context && context.compress) ? ',' : ', ');
  1326. }
  1327. }
  1328. };
  1329. return Value;
  1330. }(Node));
  1331. Value.prototype.type = 'Value';
  1332. var Keyword = /** @class */ (function (_super) {
  1333. __extends(Keyword, _super);
  1334. function Keyword(value) {
  1335. var _this = _super.call(this) || this;
  1336. _this.value = value;
  1337. return _this;
  1338. }
  1339. Keyword.prototype.genCSS = function (context, output) {
  1340. if (this.value === '%') {
  1341. throw { type: 'Syntax', message: 'Invalid % without number' };
  1342. }
  1343. output.add(this.value);
  1344. };
  1345. return Keyword;
  1346. }(Node));
  1347. Keyword.prototype.type = 'Keyword';
  1348. Keyword.True = new Keyword('true');
  1349. Keyword.False = new Keyword('false');
  1350. var Anonymous = /** @class */ (function (_super) {
  1351. __extends(Anonymous, _super);
  1352. function Anonymous(value, index, currentFileInfo, mapLines, rulesetLike, visibilityInfo) {
  1353. var _this = _super.call(this) || this;
  1354. _this.value = value;
  1355. _this._index = index;
  1356. _this._fileInfo = currentFileInfo;
  1357. _this.mapLines = mapLines;
  1358. _this.rulesetLike = (typeof rulesetLike === 'undefined') ? false : rulesetLike;
  1359. _this.allowRoot = true;
  1360. _this.copyVisibilityInfo(visibilityInfo);
  1361. return _this;
  1362. }
  1363. Anonymous.prototype.eval = function () {
  1364. return new Anonymous(this.value, this._index, this._fileInfo, this.mapLines, this.rulesetLike, this.visibilityInfo());
  1365. };
  1366. Anonymous.prototype.compare = function (other) {
  1367. return other.toCSS && this.toCSS() === other.toCSS() ? 0 : undefined;
  1368. };
  1369. Anonymous.prototype.isRulesetLike = function () {
  1370. return this.rulesetLike;
  1371. };
  1372. Anonymous.prototype.genCSS = function (context, output) {
  1373. this.nodeVisible = Boolean(this.value);
  1374. if (this.nodeVisible) {
  1375. output.add(this.value, this._fileInfo, this._index, this.mapLines);
  1376. }
  1377. };
  1378. return Anonymous;
  1379. }(Node));
  1380. Anonymous.prototype.type = 'Anonymous';
  1381. var MATH = Math$1;
  1382. var Declaration = /** @class */ (function (_super) {
  1383. __extends(Declaration, _super);
  1384. function Declaration(name, value, important, merge, index, currentFileInfo, inline, variable) {
  1385. var _this = _super.call(this) || this;
  1386. _this.name = name;
  1387. _this.value = (value instanceof Node) ? value : new Value([value ? new Anonymous(value) : null]);
  1388. _this.important = important ? " " + important.trim() : '';
  1389. _this.merge = merge;
  1390. _this._index = index;
  1391. _this._fileInfo = currentFileInfo;
  1392. _this.inline = inline || false;
  1393. _this.variable = (variable !== undefined) ? variable
  1394. : (name.charAt && (name.charAt(0) === '@'));
  1395. _this.allowRoot = true;
  1396. _this.setParent(_this.value, _this);
  1397. return _this;
  1398. }
  1399. Declaration.prototype.genCSS = function (context, output) {
  1400. output.add(this.name + (context.compress ? ':' : ': '), this.fileInfo(), this.getIndex());
  1401. try {
  1402. this.value.genCSS(context, output);
  1403. }
  1404. catch (e) {
  1405. e.index = this._index;
  1406. e.filename = this._fileInfo.filename;
  1407. throw e;
  1408. }
  1409. output.add(this.important + ((this.inline || (context.lastRule && context.compress)) ? '' : ';'), this._fileInfo, this._index);
  1410. };
  1411. Declaration.prototype.eval = function (context) {
  1412. var mathBypass = false;
  1413. var prevMath;
  1414. var name = this.name;
  1415. var evaldValue;
  1416. var variable = this.variable;
  1417. if (typeof name !== 'string') {
  1418. // expand 'primitive' name directly to get
  1419. // things faster (~10% for benchmark.less):
  1420. name = (name.length === 1) && (name[0] instanceof Keyword) ?
  1421. name[0].value : evalName(context, name);
  1422. variable = false; // never treat expanded interpolation as new variable name
  1423. }
  1424. // @todo remove when parens-division is default
  1425. if (name === 'font' && context.math === MATH.ALWAYS) {
  1426. mathBypass = true;
  1427. prevMath = context.math;
  1428. context.math = MATH.PARENS_DIVISION;
  1429. }
  1430. try {
  1431. context.importantScope.push({});
  1432. evaldValue = this.value.eval(context);
  1433. if (!this.variable && evaldValue.type === 'DetachedRuleset') {
  1434. throw { message: 'Rulesets cannot be evaluated on a property.',
  1435. index: this.getIndex(), filename: this.fileInfo().filename };
  1436. }
  1437. var important = this.important;
  1438. var importantResult = context.importantScope.pop();
  1439. if (!important && importantResult.important) {
  1440. important = importantResult.important;
  1441. }
  1442. return new Declaration(name, evaldValue, important, this.merge, this.getIndex(), this.fileInfo(), this.inline, variable);
  1443. }
  1444. catch (e) {
  1445. if (typeof e.index !== 'number') {
  1446. e.index = this.getIndex();
  1447. e.filename = this.fileInfo().filename;
  1448. }
  1449. throw e;
  1450. }
  1451. finally {
  1452. if (mathBypass) {
  1453. context.math = prevMath;
  1454. }
  1455. }
  1456. };
  1457. Declaration.prototype.makeImportant = function () {
  1458. return new Declaration(this.name, this.value, '!important', this.merge, this.getIndex(), this.fileInfo(), this.inline);
  1459. };
  1460. return Declaration;
  1461. }(Node));
  1462. function evalName(context, name) {
  1463. var value = '';
  1464. var i;
  1465. var n = name.length;
  1466. var output = { add: function (s) { value += s; } };
  1467. for (i = 0; i < n; i++) {
  1468. name[i].eval(context).genCSS(context, output);
  1469. }
  1470. return value;
  1471. }
  1472. Declaration.prototype.type = 'Declaration';
  1473. var debugInfo = function (context, ctx, lineSeparator) {
  1474. var result = '';
  1475. if (context.dumpLineNumbers && !context.compress) {
  1476. switch (context.dumpLineNumbers) {
  1477. case 'comments':
  1478. result = debugInfo.asComment(ctx);
  1479. break;
  1480. case 'mediaquery':
  1481. result = debugInfo.asMediaQuery(ctx);
  1482. break;
  1483. case 'all':
  1484. result = debugInfo.asComment(ctx) + (lineSeparator || '') + debugInfo.asMediaQuery(ctx);
  1485. break;
  1486. }
  1487. }
  1488. return result;
  1489. };
  1490. debugInfo.asComment = function (ctx) { return ctx.debugInfo ? "/* line " + ctx.debugInfo.lineNumber + ", " + ctx.debugInfo.fileName + " */\n" : ''; };
  1491. debugInfo.asMediaQuery = function (ctx) {
  1492. if (!ctx.debugInfo) {
  1493. return '';
  1494. }
  1495. var filenameWithProtocol = ctx.debugInfo.fileName;
  1496. if (!/^[a-z]+:\/\//i.test(filenameWithProtocol)) {
  1497. filenameWithProtocol = "file://" + filenameWithProtocol;
  1498. }
  1499. return "@media -sass-debug-info{filename{font-family:" + filenameWithProtocol.replace(/([.:\/\\])/g, function (a) {
  1500. if (a == '\\') {
  1501. a = '\/';
  1502. }
  1503. return "\\" + a;
  1504. }) + "}line{font-family:\\00003" + ctx.debugInfo.lineNumber + "}}\n";
  1505. };
  1506. var Comment = /** @class */ (function (_super) {
  1507. __extends(Comment, _super);
  1508. function Comment(value, isLineComment, index, currentFileInfo) {
  1509. var _this = _super.call(this) || this;
  1510. _this.value = value;
  1511. _this.isLineComment = isLineComment;
  1512. _this._index = index;
  1513. _this._fileInfo = currentFileInfo;
  1514. _this.allowRoot = true;
  1515. return _this;
  1516. }
  1517. Comment.prototype.genCSS = function (context, output) {
  1518. if (this.debugInfo) {
  1519. output.add(debugInfo(context, this), this.fileInfo(), this.getIndex());
  1520. }
  1521. output.add(this.value);
  1522. };
  1523. Comment.prototype.isSilent = function (context) {
  1524. var isCompressed = context.compress && this.value[2] !== '!';
  1525. return this.isLineComment || isCompressed;
  1526. };
  1527. return Comment;
  1528. }(Node));
  1529. Comment.prototype.type = 'Comment';
  1530. var contexts = {};
  1531. var copyFromOriginal = function copyFromOriginal(original, destination, propertiesToCopy) {
  1532. if (!original) {
  1533. return;
  1534. }
  1535. for (var i = 0; i < propertiesToCopy.length; i++) {
  1536. if (original.hasOwnProperty(propertiesToCopy[i])) {
  1537. destination[propertiesToCopy[i]] = original[propertiesToCopy[i]];
  1538. }
  1539. }
  1540. };
  1541. /*
  1542. parse is used whilst parsing
  1543. */
  1544. var parseCopyProperties = [
  1545. // options
  1546. 'paths',
  1547. 'rewriteUrls',
  1548. 'rootpath',
  1549. 'strictImports',
  1550. 'insecure',
  1551. 'dumpLineNumbers',
  1552. 'compress',
  1553. 'syncImport',
  1554. 'chunkInput',
  1555. 'mime',
  1556. 'useFileCache',
  1557. // context
  1558. 'processImports',
  1559. // Used by the import manager to stop multiple import visitors being created.
  1560. 'pluginManager' // Used as the plugin manager for the session
  1561. ];
  1562. contexts.Parse = function (options) {
  1563. copyFromOriginal(options, this, parseCopyProperties);
  1564. if (typeof this.paths === 'string') {
  1565. this.paths = [this.paths];
  1566. }
  1567. };
  1568. var evalCopyProperties = [
  1569. 'paths',
  1570. 'compress',
  1571. 'math',
  1572. 'strictUnits',
  1573. 'sourceMap',
  1574. 'importMultiple',
  1575. 'urlArgs',
  1576. 'javascriptEnabled',
  1577. 'pluginManager',
  1578. 'importantScope',
  1579. 'rewriteUrls' // option - whether to adjust URL's to be relative
  1580. ];
  1581. function isPathRelative(path) {
  1582. return !/^(?:[a-z-]+:|\/|#)/i.test(path);
  1583. }
  1584. function isPathLocalRelative(path) {
  1585. return path.charAt(0) === '.';
  1586. }
  1587. contexts.Eval = /** @class */ (function () {
  1588. function Eval(options, frames) {
  1589. copyFromOriginal(options, this, evalCopyProperties);
  1590. if (typeof this.paths === 'string') {
  1591. this.paths = [this.paths];
  1592. }
  1593. this.frames = frames || [];
  1594. this.importantScope = this.importantScope || [];
  1595. this.inCalc = false;
  1596. this.mathOn = true;
  1597. }
  1598. Eval.prototype.enterCalc = function () {
  1599. if (!this.calcStack) {
  1600. this.calcStack = [];
  1601. }
  1602. this.calcStack.push(true);
  1603. this.inCalc = true;
  1604. };
  1605. Eval.prototype.exitCalc = function () {
  1606. this.calcStack.pop();
  1607. if (!this.calcStack.length) {
  1608. this.inCalc = false;
  1609. }
  1610. };
  1611. Eval.prototype.inParenthesis = function () {
  1612. if (!this.parensStack) {
  1613. this.parensStack = [];
  1614. }
  1615. this.parensStack.push(true);
  1616. };
  1617. Eval.prototype.outOfParenthesis = function () {
  1618. this.parensStack.pop();
  1619. };
  1620. Eval.prototype.isMathOn = function (op) {
  1621. if (!this.mathOn) {
  1622. return false;
  1623. }
  1624. if (op === '/' && this.math !== Math$1.ALWAYS && (!this.parensStack || !this.parensStack.length)) {
  1625. return false;
  1626. }
  1627. if (this.math > Math$1.PARENS_DIVISION) {
  1628. return this.parensStack && this.parensStack.length;
  1629. }
  1630. return true;
  1631. };
  1632. Eval.prototype.pathRequiresRewrite = function (path) {
  1633. var isRelative = this.rewriteUrls === RewriteUrls.LOCAL ? isPathLocalRelative : isPathRelative;
  1634. return isRelative(path);
  1635. };
  1636. Eval.prototype.rewritePath = function (path, rootpath) {
  1637. var newPath;
  1638. rootpath = rootpath || '';
  1639. newPath = this.normalizePath(rootpath + path);
  1640. // If a path was explicit relative and the rootpath was not an absolute path
  1641. // we must ensure that the new path is also explicit relative.
  1642. if (isPathLocalRelative(path) &&
  1643. isPathRelative(rootpath) &&
  1644. isPathLocalRelative(newPath) === false) {
  1645. newPath = "./" + newPath;
  1646. }
  1647. return newPath;
  1648. };
  1649. Eval.prototype.normalizePath = function (path) {
  1650. var segments = path.split('/').reverse();
  1651. var segment;
  1652. path = [];
  1653. while (segments.length !== 0) {
  1654. segment = segments.pop();
  1655. switch (segment) {
  1656. case '.':
  1657. break;
  1658. case '..':
  1659. if ((path.length === 0) || (path[path.length - 1] === '..')) {
  1660. path.push(segment);
  1661. }
  1662. else {
  1663. path.pop();
  1664. }
  1665. break;
  1666. default:
  1667. path.push(segment);
  1668. break;
  1669. }
  1670. }
  1671. return path.join('/');
  1672. };
  1673. return Eval;
  1674. }());
  1675. function makeRegistry(base) {
  1676. return {
  1677. _data: {},
  1678. add: function (name, func) {
  1679. // precautionary case conversion, as later querying of
  1680. // the registry by function-caller uses lower case as well.
  1681. name = name.toLowerCase();
  1682. if (this._data.hasOwnProperty(name)) ;
  1683. this._data[name] = func;
  1684. },
  1685. addMultiple: function (functions) {
  1686. var _this = this;
  1687. Object.keys(functions).forEach(function (name) {
  1688. _this.add(name, functions[name]);
  1689. });
  1690. },
  1691. get: function (name) {
  1692. return this._data[name] || (base && base.get(name));
  1693. },
  1694. getLocalFunctions: function () {
  1695. return this._data;
  1696. },
  1697. inherit: function () {
  1698. return makeRegistry(this);
  1699. },
  1700. create: function (base) {
  1701. return makeRegistry(base);
  1702. }
  1703. };
  1704. }
  1705. var functionRegistry = makeRegistry(null);
  1706. var defaultFunc = {
  1707. eval: function () {
  1708. var v = this.value_;
  1709. var e = this.error_;
  1710. if (e) {
  1711. throw e;
  1712. }
  1713. if (v != null) {
  1714. return v ? Keyword.True : Keyword.False;
  1715. }
  1716. },
  1717. value: function (v) {
  1718. this.value_ = v;
  1719. },
  1720. error: function (e) {
  1721. this.error_ = e;
  1722. },
  1723. reset: function () {
  1724. this.value_ = this.error_ = null;
  1725. }
  1726. };
  1727. var Ruleset = /** @class */ (function (_super) {
  1728. __extends(Ruleset, _super);
  1729. function Ruleset(selectors, rules, strictImports, visibilityInfo) {
  1730. var _this = _super.call(this) || this;
  1731. _this.selectors = selectors;
  1732. _this.rules = rules;
  1733. _this._lookups = {};
  1734. _this._variables = null;
  1735. _this._properties = null;
  1736. _this.strictImports = strictImports;
  1737. _this.copyVisibilityInfo(visibilityInfo);
  1738. _this.allowRoot = true;
  1739. _this.setParent(_this.selectors, _this);
  1740. _this.setParent(_this.rules, _this);
  1741. return _this;
  1742. }
  1743. Ruleset.prototype.isRulesetLike = function () {
  1744. return true;
  1745. };
  1746. Ruleset.prototype.accept = function (visitor) {
  1747. if (this.paths) {
  1748. this.paths = visitor.visitArray(this.paths, true);
  1749. }
  1750. else if (this.selectors) {
  1751. this.selectors = visitor.visitArray(this.selectors);
  1752. }
  1753. if (this.rules && this.rules.length) {
  1754. this.rules = visitor.visitArray(this.rules);
  1755. }
  1756. };
  1757. Ruleset.prototype.eval = function (context) {
  1758. var selectors;
  1759. var selCnt;
  1760. var selector;
  1761. var i;
  1762. var hasVariable;
  1763. var hasOnePassingSelector = false;
  1764. if (this.selectors && (selCnt = this.selectors.length)) {
  1765. selectors = new Array(selCnt);
  1766. defaultFunc.error({
  1767. type: 'Syntax',
  1768. message: 'it is currently only allowed in parametric mixin guards,'
  1769. });
  1770. for (i = 0; i < selCnt; i++) {
  1771. selector = this.selectors[i].eval(context);
  1772. for (var j = 0; j < selector.elements.length; j++) {
  1773. if (selector.elements[j].isVariable) {
  1774. hasVariable = true;
  1775. break;
  1776. }
  1777. }
  1778. selectors[i] = selector;
  1779. if (selector.evaldCondition) {
  1780. hasOnePassingSelector = true;
  1781. }
  1782. }
  1783. if (hasVariable) {
  1784. var toParseSelectors = new Array(selCnt);
  1785. for (i = 0; i < selCnt; i++) {
  1786. selector = selectors[i];
  1787. toParseSelectors[i] = selector.toCSS(context);
  1788. }
  1789. this.parse.parseNode(toParseSelectors.join(','), ["selectors"], selectors[0].getIndex(), selectors[0].fileInfo(), function (err, result) {
  1790. if (result) {
  1791. selectors = flattenArray(result);
  1792. }
  1793. });
  1794. }
  1795. defaultFunc.reset();
  1796. }
  1797. else {
  1798. hasOnePassingSelector = true;
  1799. }
  1800. var rules = this.rules ? copyArray(this.rules) : null;
  1801. var ruleset = new Ruleset(selectors, rules, this.strictImports, this.visibilityInfo());
  1802. var rule;
  1803. var subRule;
  1804. ruleset.originalRuleset = this;
  1805. ruleset.root = this.root;
  1806. ruleset.firstRoot = this.firstRoot;
  1807. ruleset.allowImports = this.allowImports;
  1808. if (this.debugInfo) {
  1809. ruleset.debugInfo = this.debugInfo;
  1810. }
  1811. if (!hasOnePassingSelector) {
  1812. rules.length = 0;
  1813. }
  1814. // inherit a function registry from the frames stack when possible;
  1815. // otherwise from the global registry
  1816. ruleset.functionRegistry = (function (frames) {
  1817. var i = 0;
  1818. var n = frames.length;
  1819. var found;
  1820. for (; i !== n; ++i) {
  1821. found = frames[i].functionRegistry;
  1822. if (found) {
  1823. return found;
  1824. }
  1825. }
  1826. return functionRegistry;
  1827. })(context.frames).inherit();
  1828. // push the current ruleset to the frames stack
  1829. var ctxFrames = context.frames;
  1830. ctxFrames.unshift(ruleset);
  1831. // currrent selectors
  1832. var ctxSelectors = context.selectors;
  1833. if (!ctxSelectors) {
  1834. context.selectors = ctxSelectors = [];
  1835. }
  1836. ctxSelectors.unshift(this.selectors);
  1837. // Evaluate imports
  1838. if (ruleset.root || ruleset.allowImports || !ruleset.strictImports) {
  1839. ruleset.evalImports(context);
  1840. }
  1841. // Store the frames around mixin definitions,
  1842. // so they can be evaluated like closures when the time comes.
  1843. var rsRules = ruleset.rules;
  1844. for (i = 0; (rule = rsRules[i]); i++) {
  1845. if (rule.evalFirst) {
  1846. rsRules[i] = rule.eval(context);
  1847. }
  1848. }
  1849. var mediaBlockCount = (context.mediaBlocks && context.mediaBlocks.length) || 0;
  1850. // Evaluate mixin calls.
  1851. for (i = 0; (rule = rsRules[i]); i++) {
  1852. if (rule.type === 'MixinCall') {
  1853. /* jshint loopfunc:true */
  1854. rules = rule.eval(context).filter(function (r) {
  1855. if ((r instanceof Declaration) && r.variable) {
  1856. // do not pollute the scope if the variable is
  1857. // already there. consider returning false here
  1858. // but we need a way to "return" variable from mixins
  1859. return !(ruleset.variable(r.name));
  1860. }
  1861. return true;
  1862. });
  1863. rsRules.splice.apply(rsRules, [i, 1].concat(rules));
  1864. i += rules.length - 1;
  1865. ruleset.resetCache();
  1866. }
  1867. else if (rule.type === 'VariableCall') {
  1868. /* jshint loopfunc:true */
  1869. rules = rule.eval(context).rules.filter(function (r) {
  1870. if ((r instanceof Declaration) && r.variable) {
  1871. // do not pollute the scope at all
  1872. return false;
  1873. }
  1874. return true;
  1875. });
  1876. rsRules.splice.apply(rsRules, [i, 1].concat(rules));
  1877. i += rules.length - 1;
  1878. ruleset.resetCache();
  1879. }
  1880. }
  1881. // Evaluate everything else
  1882. for (i = 0; (rule = rsRules[i]); i++) {
  1883. if (!rule.evalFirst) {
  1884. rsRules[i] = rule = rule.eval ? rule.eval(context) : rule;
  1885. }
  1886. }
  1887. // Evaluate everything else
  1888. for (i = 0; (rule = rsRules[i]); i++) {
  1889. // for rulesets, check if it is a css guard and can be removed
  1890. if (rule instanceof Ruleset && rule.selectors && rule.selectors.length === 1) {
  1891. // check if it can be folded in (e.g. & where)
  1892. if (rule.selectors[0] && rule.selectors[0].isJustParentSelector()) {
  1893. rsRules.splice(i--, 1);
  1894. for (var j = 0; (subRule = rule.rules[j]); j++) {
  1895. if (subRule instanceof Node) {
  1896. subRule.copyVisibilityInfo(rule.visibilityInfo());
  1897. if (!(subRule instanceof Declaration) || !subRule.variable) {
  1898. rsRules.splice(++i, 0, subRule);
  1899. }
  1900. }
  1901. }
  1902. }
  1903. }
  1904. }
  1905. // Pop the stack
  1906. ctxFrames.shift();
  1907. ctxSelectors.shift();
  1908. if (context.mediaBlocks) {
  1909. for (i = mediaBlockCount; i < context.mediaBlocks.length; i++) {
  1910. context.mediaBlocks[i].bubbleSelectors(selectors);
  1911. }
  1912. }
  1913. return ruleset;
  1914. };
  1915. Ruleset.prototype.evalImports = function (context) {
  1916. var rules = this.rules;
  1917. var i;
  1918. var importRules;
  1919. if (!rules) {
  1920. return;
  1921. }
  1922. for (i = 0; i < rules.length; i++) {
  1923. if (rules[i].type === 'Import') {
  1924. importRules = rules[i].eval(context);
  1925. if (importRules && (importRules.length || importRules.length === 0)) {
  1926. rules.splice.apply(rules, [i, 1].concat(importRules));
  1927. i += importRules.length - 1;
  1928. }
  1929. else {
  1930. rules.splice(i, 1, importRules);
  1931. }
  1932. this.resetCache();
  1933. }
  1934. }
  1935. };
  1936. Ruleset.prototype.makeImportant = function () {
  1937. var result = new Ruleset(this.selectors, this.rules.map(function (r) {
  1938. if (r.makeImportant) {
  1939. return r.makeImportant();
  1940. }
  1941. else {
  1942. return r;
  1943. }
  1944. }), this.strictImports, this.visibilityInfo());
  1945. return result;
  1946. };
  1947. Ruleset.prototype.matchArgs = function (args) {
  1948. return !args || args.length === 0;
  1949. };
  1950. // lets you call a css selector with a guard
  1951. Ruleset.prototype.matchCondition = function (args, context) {
  1952. var lastSelector = this.selectors[this.selectors.length - 1];
  1953. if (!lastSelector.evaldCondition) {
  1954. return false;
  1955. }
  1956. if (lastSelector.condition &&
  1957. !lastSelector.condition.eval(new contexts.Eval(context, context.frames))) {
  1958. return false;
  1959. }
  1960. return true;
  1961. };
  1962. Ruleset.prototype.resetCache = function () {
  1963. this._rulesets = null;
  1964. this._variables = null;
  1965. this._properties = null;
  1966. this._lookups = {};
  1967. };
  1968. Ruleset.prototype.variables = function () {
  1969. if (!this._variables) {
  1970. this._variables = !this.rules ? {} : this.rules.reduce(function (hash, r) {
  1971. if (r instanceof Declaration && r.variable === true) {
  1972. hash[r.name] = r;
  1973. }
  1974. // when evaluating variables in an import statement, imports have not been eval'd
  1975. // so we need to go inside import statements.
  1976. // guard against root being a string (in the case of inlined less)
  1977. if (r.type === 'Import' && r.root && r.root.variables) {
  1978. var vars = r.root.variables();
  1979. for (var name_1 in vars) {
  1980. if (vars.hasOwnProperty(name_1)) {
  1981. hash[name_1] = r.root.variable(name_1);
  1982. }
  1983. }
  1984. }
  1985. return hash;
  1986. }, {});
  1987. }
  1988. return this._variables;
  1989. };
  1990. Ruleset.prototype.properties = function () {
  1991. if (!this._properties) {
  1992. this._properties = !this.rules ? {} : this.rules.reduce(function (hash, r) {
  1993. if (r instanceof Declaration && r.variable !== true) {
  1994. var name_2 = (r.name.length === 1) && (r.name[0] instanceof Keyword) ?
  1995. r.name[0].value : r.name;
  1996. // Properties don't overwrite as they can merge
  1997. if (!hash["$" + name_2]) {
  1998. hash["$" + name_2] = [r];
  1999. }
  2000. else {
  2001. hash["$" + name_2].push(r);
  2002. }
  2003. }
  2004. return hash;
  2005. }, {});
  2006. }
  2007. return this._properties;
  2008. };
  2009. Ruleset.prototype.variable = function (name) {
  2010. var decl = this.variables()[name];
  2011. if (decl) {
  2012. return this.parseValue(decl);
  2013. }
  2014. };
  2015. Ruleset.prototype.property = function (name) {
  2016. var decl = this.properties()[name];
  2017. if (decl) {
  2018. return this.parseValue(decl);
  2019. }
  2020. };
  2021. Ruleset.prototype.lastDeclaration = function () {
  2022. for (var i = this.rules.length; i > 0; i--) {
  2023. var decl = this.rules[i - 1];
  2024. if (decl instanceof Declaration) {
  2025. return this.parseValue(decl);
  2026. }
  2027. }
  2028. };
  2029. Ruleset.prototype.parseValue = function (toParse) {
  2030. var self = this;
  2031. function transformDeclaration(decl) {
  2032. if (decl.value instanceof Anonymous && !decl.parsed) {
  2033. if (typeof decl.value.value === 'string') {
  2034. this.parse.parseNode(decl.value.value, ['value', 'important'], decl.value.getIndex(), decl.fileInfo(), function (err, result) {
  2035. if (err) {
  2036. decl.parsed = true;
  2037. }
  2038. if (result) {
  2039. decl.value = result[0];
  2040. decl.important = result[1] || '';
  2041. decl.parsed = true;
  2042. }
  2043. });
  2044. }
  2045. else {
  2046. decl.parsed = true;
  2047. }
  2048. return decl;
  2049. }
  2050. else {
  2051. return decl;
  2052. }
  2053. }
  2054. if (!Array.isArray(toParse)) {
  2055. return transformDeclaration.call(self, toParse);
  2056. }
  2057. else {
  2058. var nodes_1 = [];
  2059. toParse.forEach(function (n) {
  2060. nodes_1.push(transformDeclaration.call(self, n));
  2061. });
  2062. return nodes_1;
  2063. }
  2064. };
  2065. Ruleset.prototype.rulesets = function () {
  2066. if (!this.rules) {
  2067. return [];
  2068. }
  2069. var filtRules = [];
  2070. var rules = this.rules;
  2071. var i;
  2072. var rule;
  2073. for (i = 0; (rule = rules[i]); i++) {
  2074. if (rule.isRuleset) {
  2075. filtRules.push(rule);
  2076. }
  2077. }
  2078. return filtRules;
  2079. };
  2080. Ruleset.prototype.prependRule = function (rule) {
  2081. var rules = this.rules;
  2082. if (rules) {
  2083. rules.unshift(rule);
  2084. }
  2085. else {
  2086. this.rules = [rule];
  2087. }
  2088. this.setParent(rule, this);
  2089. };
  2090. Ruleset.prototype.find = function (selector, self, filter) {
  2091. if (self === void 0) { self = this; }
  2092. var rules = [];
  2093. var match;
  2094. var foundMixins;
  2095. var key = selector.toCSS();
  2096. if (key in this._lookups) {
  2097. return this._lookups[key];
  2098. }
  2099. this.rulesets().forEach(function (rule) {
  2100. if (rule !== self) {
  2101. for (var j = 0; j < rule.selectors.length; j++) {
  2102. match = selector.match(rule.selectors[j]);
  2103. if (match) {
  2104. if (selector.elements.length > match) {
  2105. if (!filter || filter(rule)) {
  2106. foundMixins = rule.find(new Selector(selector.elements.slice(match)), self, filter);
  2107. for (var i = 0; i < foundMixins.length; ++i) {
  2108. foundMixins[i].path.push(rule);
  2109. }
  2110. Array.prototype.push.apply(rules, foundMixins);
  2111. }
  2112. }
  2113. else {
  2114. rules.push({ rule: rule, path: [] });
  2115. }
  2116. break;
  2117. }
  2118. }
  2119. }
  2120. });
  2121. this._lookups[key] = rules;
  2122. return rules;
  2123. };
  2124. Ruleset.prototype.genCSS = function (context, output) {
  2125. var i;
  2126. var j;
  2127. var charsetRuleNodes = [];
  2128. var ruleNodes = [];
  2129. var // Line number debugging
  2130. debugInfo$1;
  2131. var rule;
  2132. var path;
  2133. context.tabLevel = (context.tabLevel || 0);
  2134. if (!this.root) {
  2135. context.tabLevel++;
  2136. }
  2137. var tabRuleStr = context.compress ? '' : Array(context.tabLevel + 1).join(' ');
  2138. var tabSetStr = context.compress ? '' : Array(context.tabLevel).join(' ');
  2139. var sep;
  2140. var charsetNodeIndex = 0;
  2141. var importNodeIndex = 0;
  2142. for (i = 0; (rule = this.rules[i]); i++) {
  2143. if (rule instanceof Comment) {
  2144. if (importNodeIndex === i) {
  2145. importNodeIndex++;
  2146. }
  2147. ruleNodes.push(rule);
  2148. }
  2149. else if (rule.isCharset && rule.isCharset()) {
  2150. ruleNodes.splice(charsetNodeIndex, 0, rule);
  2151. charsetNodeIndex++;
  2152. importNodeIndex++;
  2153. }
  2154. else if (rule.type === 'Import') {
  2155. ruleNodes.splice(importNodeIndex, 0, rule);
  2156. importNodeIndex++;
  2157. }
  2158. else {
  2159. ruleNodes.push(rule);
  2160. }
  2161. }
  2162. ruleNodes = charsetRuleNodes.concat(ruleNodes);
  2163. // If this is the root node, we don't render
  2164. // a selector, or {}.
  2165. if (!this.root) {
  2166. debugInfo$1 = debugInfo(context, this, tabSetStr);
  2167. if (debugInfo$1) {
  2168. output.add(debugInfo$1);
  2169. output.add(tabSetStr);
  2170. }
  2171. var paths = this.paths;
  2172. var pathCnt = paths.length;
  2173. var pathSubCnt = void 0;
  2174. sep = context.compress ? ',' : (",\n" + tabSetStr);
  2175. for (i = 0; i < pathCnt; i++) {
  2176. path = paths[i];
  2177. if (!(pathSubCnt = path.length)) {
  2178. continue;
  2179. }
  2180. if (i > 0) {
  2181. output.add(sep);
  2182. }
  2183. context.firstSelector = true;
  2184. path[0].genCSS(context, output);
  2185. context.firstSelector = false;
  2186. for (j = 1; j < pathSubCnt; j++) {
  2187. path[j].genCSS(context, output);
  2188. }
  2189. }
  2190. output.add((context.compress ? '{' : ' {\n') + tabRuleStr);
  2191. }
  2192. // Compile rules and rulesets
  2193. for (i = 0; (rule = ruleNodes[i]); i++) {
  2194. if (i + 1 === ruleNodes.length) {
  2195. context.lastRule = true;
  2196. }
  2197. var currentLastRule = context.lastRule;
  2198. if (rule.isRulesetLike(rule)) {
  2199. context.lastRule = false;
  2200. }
  2201. if (rule.genCSS) {
  2202. rule.genCSS(context, output);
  2203. }
  2204. else if (rule.value) {
  2205. output.add(rule.value.toString());
  2206. }
  2207. context.lastRule = currentLastRule;
  2208. if (!context.lastRule && rule.isVisible()) {
  2209. output.add(context.compress ? '' : ("\n" + tabRuleStr));
  2210. }
  2211. else {
  2212. context.lastRule = false;
  2213. }
  2214. }
  2215. if (!this.root) {
  2216. output.add((context.compress ? '}' : "\n" + tabSetStr + "}"));
  2217. context.tabLevel--;
  2218. }
  2219. if (!output.isEmpty() && !context.compress && this.firstRoot) {
  2220. output.add('\n');
  2221. }
  2222. };
  2223. Ruleset.prototype.joinSelectors = function (paths, context, selectors) {
  2224. for (var s = 0; s < selectors.length; s++) {
  2225. this.joinSelector(paths, context, selectors[s]);
  2226. }
  2227. };
  2228. Ruleset.prototype.joinSelector = function (paths, context, selector) {
  2229. function createParenthesis(elementsToPak, originalElement) {
  2230. var replacementParen;
  2231. var j;
  2232. if (elementsToPak.length === 0) {
  2233. replacementParen = new Paren(elementsToPak[0]);
  2234. }
  2235. else {
  2236. var insideParent = new Array(elementsToPak.length);
  2237. for (j = 0; j < elementsToPak.length; j++) {
  2238. insideParent[j] = new Element(null, elementsToPak[j], originalElement.isVariable, originalElement._index, originalElement._fileInfo);
  2239. }
  2240. replacementParen = new Paren(new Selector(insideParent));
  2241. }
  2242. return replacementParen;
  2243. }
  2244. function createSelector(containedElement, originalElement) {
  2245. var element;
  2246. var selector;
  2247. element = new Element(null, containedElement, originalElement.isVariable, originalElement._index, originalElement._fileInfo);
  2248. selector = new Selector([element]);
  2249. return selector;
  2250. }
  2251. // joins selector path from `beginningPath` with selector path in `addPath`
  2252. // `replacedElement` contains element that is being replaced by `addPath`
  2253. // returns concatenated path
  2254. function addReplacementIntoPath(beginningPath, addPath, replacedElement, originalSelector) {
  2255. var newSelectorPath;
  2256. var lastSelector;
  2257. var newJoinedSelector;
  2258. // our new selector path
  2259. newSelectorPath = [];
  2260. // construct the joined selector - if & is the first thing this will be empty,
  2261. // if not newJoinedSelector will be the last set of elements in the selector
  2262. if (beginningPath.length > 0) {
  2263. newSelectorPath = copyArray(beginningPath);
  2264. lastSelector = newSelectorPath.pop();
  2265. newJoinedSelector = originalSelector.createDerived(copyArray(lastSelector.elements));
  2266. }
  2267. else {
  2268. newJoinedSelector = originalSelector.createDerived([]);
  2269. }
  2270. if (addPath.length > 0) {
  2271. // /deep/ is a CSS4 selector - (removed, so should deprecate)
  2272. // that is valid without anything in front of it
  2273. // so if the & does not have a combinator that is "" or " " then
  2274. // and there is a combinator on the parent, then grab that.
  2275. // this also allows + a { & .b { .a & { ... though not sure why you would want to do that
  2276. var combinator = replacedElement.combinator;
  2277. var parentEl = addPath[0].elements[0];
  2278. if (combinator.emptyOrWhitespace && !parentEl.combinator.emptyOrWhitespace) {
  2279. combinator = parentEl.combinator;
  2280. }
  2281. // join the elements so far with the first part of the parent
  2282. newJoinedSelector.elements.push(new Element(combinator, parentEl.value, replacedElement.isVariable, replacedElement._index, replacedElement._fileInfo));
  2283. newJoinedSelector.elements = newJoinedSelector.elements.concat(addPath[0].elements.slice(1));
  2284. }
  2285. // now add the joined selector - but only if it is not empty
  2286. if (newJoinedSelector.elements.length !== 0) {
  2287. newSelectorPath.push(newJoinedSelector);
  2288. }
  2289. // put together the parent selectors after the join (e.g. the rest of the parent)
  2290. if (addPath.length > 1) {
  2291. var restOfPath = addPath.slice(1);
  2292. restOfPath = restOfPath.map(function (selector) { return selector.createDerived(selector.elements, []); });
  2293. newSelectorPath = newSelectorPath.concat(restOfPath);
  2294. }
  2295. return newSelectorPath;
  2296. }
  2297. // joins selector path from `beginningPath` with every selector path in `addPaths` array
  2298. // `replacedElement` contains element that is being replaced by `addPath`
  2299. // returns array with all concatenated paths
  2300. function addAllReplacementsIntoPath(beginningPath, addPaths, replacedElement, originalSelector, result) {
  2301. var j;
  2302. for (j = 0; j < beginningPath.length; j++) {
  2303. var newSelectorPath = addReplacementIntoPath(beginningPath[j], addPaths, replacedElement, originalSelector);
  2304. result.push(newSelectorPath);
  2305. }
  2306. return result;
  2307. }
  2308. function mergeElementsOnToSelectors(elements, selectors) {
  2309. var i;
  2310. var sel;
  2311. if (elements.length === 0) {
  2312. return;
  2313. }
  2314. if (selectors.length === 0) {
  2315. selectors.push([new Selector(elements)]);
  2316. return;
  2317. }
  2318. for (i = 0; (sel = selectors[i]); i++) {
  2319. // if the previous thing in sel is a parent this needs to join on to it
  2320. if (sel.length > 0) {
  2321. sel[sel.length - 1] = sel[sel.length - 1].createDerived(sel[sel.length - 1].elements.concat(elements));
  2322. }
  2323. else {
  2324. sel.push(new Selector(elements));
  2325. }
  2326. }
  2327. }
  2328. // replace all parent selectors inside `inSelector` by content of `context` array
  2329. // resulting selectors are returned inside `paths` array
  2330. // returns true if `inSelector` contained at least one parent selector
  2331. function replaceParentSelector(paths, context, inSelector) {
  2332. // The paths are [[Selector]]
  2333. // The first list is a list of comma separated selectors
  2334. // The inner list is a list of inheritance separated selectors
  2335. // e.g.
  2336. // .a, .b {
  2337. // .c {
  2338. // }
  2339. // }
  2340. // == [[.a] [.c]] [[.b] [.c]]
  2341. //
  2342. var i;
  2343. var j;
  2344. var k;
  2345. var currentElements;
  2346. var newSelectors;
  2347. var selectorsMultiplied;
  2348. var sel;
  2349. var el;
  2350. var hadParentSelector = false;
  2351. var length;
  2352. var lastSelector;
  2353. function findNestedSelector(element) {
  2354. var maybeSelector;
  2355. if (!(element.value instanceof Paren)) {
  2356. return null;
  2357. }
  2358. maybeSelector = element.value.value;
  2359. if (!(maybeSelector instanceof Selector)) {
  2360. return null;
  2361. }
  2362. return maybeSelector;
  2363. }
  2364. // the elements from the current selector so far
  2365. currentElements = [];
  2366. // the current list of new selectors to add to the path.
  2367. // We will build it up. We initiate it with one empty selector as we "multiply" the new selectors
  2368. // by the parents
  2369. newSelectors = [
  2370. []
  2371. ];
  2372. for (i = 0; (el = inSelector.elements[i]); i++) {
  2373. // non parent reference elements just get added
  2374. if (el.value !== '&') {
  2375. var nestedSelector = findNestedSelector(el);
  2376. if (nestedSelector != null) {
  2377. // merge the current list of non parent selector elements
  2378. // on to the current list of selectors to add
  2379. mergeElementsOnToSelectors(currentElements, newSelectors);
  2380. var nestedPaths = [];
  2381. var replaced = void 0;
  2382. var replacedNewSelectors = [];
  2383. replaced = replaceParentSelector(nestedPaths, context, nestedSelector);
  2384. hadParentSelector = hadParentSelector || replaced;
  2385. // the nestedPaths array should have only one member - replaceParentSelector does not multiply selectors
  2386. for (k = 0; k < nestedPaths.length; k++) {
  2387. var replacementSelector = createSelector(createParenthesis(nestedPaths[k], el), el);
  2388. addAllReplacementsIntoPath(newSelectors, [replacementSelector], el, inSelector, replacedNewSelectors);
  2389. }
  2390. newSelectors = replacedNewSelectors;
  2391. currentElements = [];
  2392. }
  2393. else {
  2394. currentElements.push(el);
  2395. }
  2396. }
  2397. else {
  2398. hadParentSelector = true;
  2399. // the new list of selectors to add
  2400. selectorsMultiplied = [];
  2401. // merge the current list of non parent selector elements
  2402. // on to the current list of selectors to add
  2403. mergeElementsOnToSelectors(currentElements, newSelectors);
  2404. // loop through our current selectors
  2405. for (j = 0; j < newSelectors.length; j++) {
  2406. sel = newSelectors[j];
  2407. // if we don't have any parent paths, the & might be in a mixin so that it can be used
  2408. // whether there are parents or not
  2409. if (context.length === 0) {
  2410. // the combinator used on el should now be applied to the next element instead so that
  2411. // it is not lost
  2412. if (sel.length > 0) {
  2413. sel[0].elements.push(new Element(el.combinator, '', el.isVariable, el._index, el._fileInfo));
  2414. }
  2415. selectorsMultiplied.push(sel);
  2416. }
  2417. else {
  2418. // and the parent selectors
  2419. for (k = 0; k < context.length; k++) {
  2420. // We need to put the current selectors
  2421. // then join the last selector's elements on to the parents selectors
  2422. var newSelectorPath = addReplacementIntoPath(sel, context[k], el, inSelector);
  2423. // add that to our new set of selectors
  2424. selectorsMultiplied.push(newSelectorPath);
  2425. }
  2426. }
  2427. }
  2428. // our new selectors has been multiplied, so reset the state
  2429. newSelectors = selectorsMultiplied;
  2430. currentElements = [];
  2431. }
  2432. }
  2433. // if we have any elements left over (e.g. .a& .b == .b)
  2434. // add them on to all the current selectors
  2435. mergeElementsOnToSelectors(currentElements, newSelectors);
  2436. for (i = 0; i < newSelectors.length; i++) {
  2437. length = newSelectors[i].length;
  2438. if (length > 0) {
  2439. paths.push(newSelectors[i]);
  2440. lastSelector = newSelectors[i][length - 1];
  2441. newSelectors[i][length - 1] = lastSelector.createDerived(lastSelector.elements, inSelector.extendList);
  2442. }
  2443. }
  2444. return hadParentSelector;
  2445. }
  2446. function deriveSelector(visibilityInfo, deriveFrom) {
  2447. var newSelector = deriveFrom.createDerived(deriveFrom.elements, deriveFrom.extendList, deriveFrom.evaldCondition);
  2448. newSelector.copyVisibilityInfo(visibilityInfo);
  2449. return newSelector;
  2450. }
  2451. // joinSelector code follows
  2452. var i;
  2453. var newPaths;
  2454. var hadParentSelector;
  2455. newPaths = [];
  2456. hadParentSelector = replaceParentSelector(newPaths, context, selector);
  2457. if (!hadParentSelector) {
  2458. if (context.length > 0) {
  2459. newPaths = [];
  2460. for (i = 0; i < context.length; i++) {
  2461. var concatenated = context[i].map(deriveSelector.bind(this, selector.visibilityInfo()));
  2462. concatenated.push(selector);
  2463. newPaths.push(concatenated);
  2464. }
  2465. }
  2466. else {
  2467. newPaths = [[selector]];
  2468. }
  2469. }
  2470. for (i = 0; i < newPaths.length; i++) {
  2471. paths.push(newPaths[i]);
  2472. }
  2473. };
  2474. return Ruleset;
  2475. }(Node));
  2476. Ruleset.prototype.type = 'Ruleset';
  2477. Ruleset.prototype.isRuleset = true;
  2478. var AtRule = /** @class */ (function (_super) {
  2479. __extends(AtRule, _super);
  2480. function AtRule(name, value, rules, index, currentFileInfo, debugInfo, isRooted, visibilityInfo) {
  2481. var _this = _super.call(this) || this;
  2482. var i;
  2483. _this.name = name;
  2484. _this.value = (value instanceof Node) ? value : (value ? new Anonymous(value) : value);
  2485. if (rules) {
  2486. if (Array.isArray(rules)) {
  2487. _this.rules = rules;
  2488. }
  2489. else {
  2490. _this.rules = [rules];
  2491. _this.rules[0].selectors = (new Selector([], null, null, index, currentFileInfo)).createEmptySelectors();
  2492. }
  2493. for (i = 0; i < _this.rules.length; i++) {
  2494. _this.rules[i].allowImports = true;
  2495. }
  2496. _this.setParent(_this.rules, _this);
  2497. }
  2498. _this._index = index;
  2499. _this._fileInfo = currentFileInfo;
  2500. _this.debugInfo = debugInfo;
  2501. _this.isRooted = isRooted || false;
  2502. _this.copyVisibilityInfo(visibilityInfo);
  2503. _this.allowRoot = true;
  2504. return _this;
  2505. }
  2506. AtRule.prototype.accept = function (visitor) {
  2507. var value = this.value;
  2508. var rules = this.rules;
  2509. if (rules) {
  2510. this.rules = visitor.visitArray(rules);
  2511. }
  2512. if (value) {
  2513. this.value = visitor.visit(value);
  2514. }
  2515. };
  2516. AtRule.prototype.isRulesetLike = function () {
  2517. return this.rules || !this.isCharset();
  2518. };
  2519. AtRule.prototype.isCharset = function () {
  2520. return '@charset' === this.name;
  2521. };
  2522. AtRule.prototype.genCSS = function (context, output) {
  2523. var value = this.value;
  2524. var rules = this.rules;
  2525. output.add(this.name, this.fileInfo(), this.getIndex());
  2526. if (value) {
  2527. output.add(' ');
  2528. value.genCSS(context, output);
  2529. }
  2530. if (rules) {
  2531. this.outputRuleset(context, output, rules);
  2532. }
  2533. else {
  2534. output.add(';');
  2535. }
  2536. };
  2537. AtRule.prototype.eval = function (context) {
  2538. var mediaPathBackup;
  2539. var mediaBlocksBackup;
  2540. var value = this.value;
  2541. var rules = this.rules;
  2542. // media stored inside other atrule should not bubble over it
  2543. // backpup media bubbling information
  2544. mediaPathBackup = context.mediaPath;
  2545. mediaBlocksBackup = context.mediaBlocks;
  2546. // deleted media bubbling information
  2547. context.mediaPath = [];
  2548. context.mediaBlocks = [];
  2549. if (value) {
  2550. value = value.eval(context);
  2551. }
  2552. if (rules) {
  2553. // assuming that there is only one rule at this point - that is how parser constructs the rule
  2554. rules = [rules[0].eval(context)];
  2555. rules[0].root = true;
  2556. }
  2557. // restore media bubbling information
  2558. context.mediaPath = mediaPathBackup;
  2559. context.mediaBlocks = mediaBlocksBackup;
  2560. return new AtRule(this.name, value, rules, this.getIndex(), this.fileInfo(), this.debugInfo, this.isRooted, this.visibilityInfo());
  2561. };
  2562. AtRule.prototype.variable = function (name) {
  2563. if (this.rules) {
  2564. // assuming that there is only one rule at this point - that is how parser constructs the rule
  2565. return Ruleset.prototype.variable.call(this.rules[0], name);
  2566. }
  2567. };
  2568. AtRule.prototype.find = function () {
  2569. var args = [];
  2570. for (var _i = 0; _i < arguments.length; _i++) {
  2571. args[_i] = arguments[_i];
  2572. }
  2573. if (this.rules) {
  2574. // assuming that there is only one rule at this point - that is how parser constructs the rule
  2575. return Ruleset.prototype.find.apply(this.rules[0], args);
  2576. }
  2577. };
  2578. AtRule.prototype.rulesets = function () {
  2579. if (this.rules) {
  2580. // assuming that there is only one rule at this point - that is how parser constructs the rule
  2581. return Ruleset.prototype.rulesets.apply(this.rules[0]);
  2582. }
  2583. };
  2584. AtRule.prototype.outputRuleset = function (context, output, rules) {
  2585. var ruleCnt = rules.length;
  2586. var i;
  2587. context.tabLevel = (context.tabLevel | 0) + 1;
  2588. // Compressed
  2589. if (context.compress) {
  2590. output.add('{');
  2591. for (i = 0; i < ruleCnt; i++) {
  2592. rules[i].genCSS(context, output);
  2593. }
  2594. output.add('}');
  2595. context.tabLevel--;
  2596. return;
  2597. }
  2598. // Non-compressed
  2599. var tabSetStr = "\n" + Array(context.tabLevel).join(' ');
  2600. var tabRuleStr = tabSetStr + " ";
  2601. if (!ruleCnt) {
  2602. output.add(" {" + tabSetStr + "}");
  2603. }
  2604. else {
  2605. output.add(" {" + tabRuleStr);
  2606. rules[0].genCSS(context, output);
  2607. for (i = 1; i < ruleCnt; i++) {
  2608. output.add(tabRuleStr);
  2609. rules[i].genCSS(context, output);
  2610. }
  2611. output.add(tabSetStr + "}");
  2612. }
  2613. context.tabLevel--;
  2614. };
  2615. return AtRule;
  2616. }(Node));
  2617. AtRule.prototype.type = 'AtRule';
  2618. var DetachedRuleset = /** @class */ (function (_super) {
  2619. __extends(DetachedRuleset, _super);
  2620. function DetachedRuleset(ruleset, frames) {
  2621. var _this = _super.call(this) || this;
  2622. _this.ruleset = ruleset;
  2623. _this.frames = frames;
  2624. _this.setParent(_this.ruleset, _this);
  2625. return _this;
  2626. }
  2627. DetachedRuleset.prototype.accept = function (visitor) {
  2628. this.ruleset = visitor.visit(this.ruleset);
  2629. };
  2630. DetachedRuleset.prototype.eval = function (context) {
  2631. var frames = this.frames || copyArray(context.frames);
  2632. return new DetachedRuleset(this.ruleset, frames);
  2633. };
  2634. DetachedRuleset.prototype.callEval = function (context) {
  2635. return this.ruleset.eval(this.frames ? new contexts.Eval(context, this.frames.concat(context.frames)) : context);
  2636. };
  2637. return DetachedRuleset;
  2638. }(Node));
  2639. DetachedRuleset.prototype.type = 'DetachedRuleset';
  2640. DetachedRuleset.prototype.evalFirst = true;
  2641. var Unit = /** @class */ (function (_super) {
  2642. __extends(Unit, _super);
  2643. function Unit(numerator, denominator, backupUnit) {
  2644. var _this = _super.call(this) || this;
  2645. _this.numerator = numerator ? copyArray(numerator).sort() : [];
  2646. _this.denominator = denominator ? copyArray(denominator).sort() : [];
  2647. if (backupUnit) {
  2648. _this.backupUnit = backupUnit;
  2649. }
  2650. else if (numerator && numerator.length) {
  2651. _this.backupUnit = numerator[0];
  2652. }
  2653. return _this;
  2654. }
  2655. Unit.prototype.clone = function () {
  2656. return new Unit(copyArray(this.numerator), copyArray(this.denominator), this.backupUnit);
  2657. };
  2658. Unit.prototype.genCSS = function (context, output) {
  2659. // Dimension checks the unit is singular and throws an error if in strict math mode.
  2660. var strictUnits = context && context.strictUnits;
  2661. if (this.numerator.length === 1) {
  2662. output.add(this.numerator[0]); // the ideal situation
  2663. }
  2664. else if (!strictUnits && this.backupUnit) {
  2665. output.add(this.backupUnit);
  2666. }
  2667. else if (!strictUnits && this.denominator.length) {
  2668. output.add(this.denominator[0]);
  2669. }
  2670. };
  2671. Unit.prototype.toString = function () {
  2672. var i;
  2673. var returnStr = this.numerator.join('*');
  2674. for (i = 0; i < this.denominator.length; i++) {
  2675. returnStr += "/" + this.denominator[i];
  2676. }
  2677. return returnStr;
  2678. };
  2679. Unit.prototype.compare = function (other) {
  2680. return this.is(other.toString()) ? 0 : undefined;
  2681. };
  2682. Unit.prototype.is = function (unitString) {
  2683. return this.toString().toUpperCase() === unitString.toUpperCase();
  2684. };
  2685. Unit.prototype.isLength = function () {
  2686. return RegExp('^(px|em|ex|ch|rem|in|cm|mm|pc|pt|ex|vw|vh|vmin|vmax)$', 'gi').test(this.toCSS());
  2687. };
  2688. Unit.prototype.isEmpty = function () {
  2689. return this.numerator.length === 0 && this.denominator.length === 0;
  2690. };
  2691. Unit.prototype.isSingular = function () {
  2692. return this.numerator.length <= 1 && this.denominator.length === 0;
  2693. };
  2694. Unit.prototype.map = function (callback) {
  2695. var i;
  2696. for (i = 0; i < this.numerator.length; i++) {
  2697. this.numerator[i] = callback(this.numerator[i], false);
  2698. }
  2699. for (i = 0; i < this.denominator.length; i++) {
  2700. this.denominator[i] = callback(this.denominator[i], true);
  2701. }
  2702. };
  2703. Unit.prototype.usedUnits = function () {
  2704. var group;
  2705. var result = {};
  2706. var mapUnit;
  2707. var groupName;
  2708. mapUnit = function (atomicUnit) {
  2709. /* jshint loopfunc:true */
  2710. if (group.hasOwnProperty(atomicUnit) && !result[groupName]) {
  2711. result[groupName] = atomicUnit;
  2712. }
  2713. return atomicUnit;
  2714. };
  2715. for (groupName in unitConversions) {
  2716. if (unitConversions.hasOwnProperty(groupName)) {
  2717. group = unitConversions[groupName];
  2718. this.map(mapUnit);
  2719. }
  2720. }
  2721. return result;
  2722. };
  2723. Unit.prototype.cancel = function () {
  2724. var counter = {};
  2725. var atomicUnit;
  2726. var i;
  2727. for (i = 0; i < this.numerator.length; i++) {
  2728. atomicUnit = this.numerator[i];
  2729. counter[atomicUnit] = (counter[atomicUnit] || 0) + 1;
  2730. }
  2731. for (i = 0; i < this.denominator.length; i++) {
  2732. atomicUnit = this.denominator[i];
  2733. counter[atomicUnit] = (counter[atomicUnit] || 0) - 1;
  2734. }
  2735. this.numerator = [];
  2736. this.denominator = [];
  2737. for (atomicUnit in counter) {
  2738. if (counter.hasOwnProperty(atomicUnit)) {
  2739. var count = counter[atomicUnit];
  2740. if (count > 0) {
  2741. for (i = 0; i < count; i++) {
  2742. this.numerator.push(atomicUnit);
  2743. }
  2744. }
  2745. else if (count < 0) {
  2746. for (i = 0; i < -count; i++) {
  2747. this.denominator.push(atomicUnit);
  2748. }
  2749. }
  2750. }
  2751. }
  2752. this.numerator.sort();
  2753. this.denominator.sort();
  2754. };
  2755. return Unit;
  2756. }(Node));
  2757. Unit.prototype.type = 'Unit';
  2758. //
  2759. // A number with a unit
  2760. //
  2761. var Dimension = /** @class */ (function (_super) {
  2762. __extends(Dimension, _super);
  2763. function Dimension(value, unit) {
  2764. var _this = _super.call(this) || this;
  2765. _this.value = parseFloat(value);
  2766. if (isNaN(_this.value)) {
  2767. throw new Error('Dimension is not a number.');
  2768. }
  2769. _this.unit = (unit && unit instanceof Unit) ? unit :
  2770. new Unit(unit ? [unit] : undefined);
  2771. _this.setParent(_this.unit, _this);
  2772. return _this;
  2773. }
  2774. Dimension.prototype.accept = function (visitor) {
  2775. this.unit = visitor.visit(this.unit);
  2776. };
  2777. Dimension.prototype.eval = function (context) {
  2778. return this;
  2779. };
  2780. Dimension.prototype.toColor = function () {
  2781. return new Color([this.value, this.value, this.value]);
  2782. };
  2783. Dimension.prototype.genCSS = function (context, output) {
  2784. if ((context && context.strictUnits) && !this.unit.isSingular()) {
  2785. throw new Error("Multiple units in dimension. Correct the units or use the unit function. Bad unit: " + this.unit.toString());
  2786. }
  2787. var value = this.fround(context, this.value);
  2788. var strValue = String(value);
  2789. if (value !== 0 && value < 0.000001 && value > -0.000001) {
  2790. // would be output 1e-6 etc.
  2791. strValue = value.toFixed(20).replace(/0+$/, '');
  2792. }
  2793. if (context && context.compress) {
  2794. // Zero values doesn't need a unit
  2795. if (value === 0 && this.unit.isLength()) {
  2796. output.add(strValue);
  2797. return;
  2798. }
  2799. // Float values doesn't need a leading zero
  2800. if (value > 0 && value < 1) {
  2801. strValue = (strValue).substr(1);
  2802. }
  2803. }
  2804. output.add(strValue);
  2805. this.unit.genCSS(context, output);
  2806. };
  2807. // In an operation between two Dimensions,
  2808. // we default to the first Dimension's unit,
  2809. // so `1px + 2` will yield `3px`.
  2810. Dimension.prototype.operate = function (context, op, other) {
  2811. /* jshint noempty:false */
  2812. var value = this._operate(context, op, this.value, other.value);
  2813. var unit = this.unit.clone();
  2814. if (op === '+' || op === '-') {
  2815. if (unit.numerator.length === 0 && unit.denominator.length === 0) {
  2816. unit = other.unit.clone();
  2817. if (this.unit.backupUnit) {
  2818. unit.backupUnit = this.unit.backupUnit;
  2819. }
  2820. }
  2821. else if (other.unit.numerator.length === 0 && unit.denominator.length === 0) ;
  2822. else {
  2823. other = other.convertTo(this.unit.usedUnits());
  2824. if (context.strictUnits && other.unit.toString() !== unit.toString()) {
  2825. throw new Error("Incompatible units. Change the units or use the unit function. " +
  2826. ("Bad units: '" + unit.toString() + "' and '" + other.unit.toString() + "'."));
  2827. }
  2828. value = this._operate(context, op, this.value, other.value);
  2829. }
  2830. }
  2831. else if (op === '*') {
  2832. unit.numerator = unit.numerator.concat(other.unit.numerator).sort();
  2833. unit.denominator = unit.denominator.concat(other.unit.denominator).sort();
  2834. unit.cancel();
  2835. }
  2836. else if (op === '/') {
  2837. unit.numerator = unit.numerator.concat(other.unit.denominator).sort();
  2838. unit.denominator = unit.denominator.concat(other.unit.numerator).sort();
  2839. unit.cancel();
  2840. }
  2841. return new Dimension(value, unit);
  2842. };
  2843. Dimension.prototype.compare = function (other) {
  2844. var a;
  2845. var b;
  2846. if (!(other instanceof Dimension)) {
  2847. return undefined;
  2848. }
  2849. if (this.unit.isEmpty() || other.unit.isEmpty()) {
  2850. a = this;
  2851. b = other;
  2852. }
  2853. else {
  2854. a = this.unify();
  2855. b = other.unify();
  2856. if (a.unit.compare(b.unit) !== 0) {
  2857. return undefined;
  2858. }
  2859. }
  2860. return Node.numericCompare(a.value, b.value);
  2861. };
  2862. Dimension.prototype.unify = function () {
  2863. return this.convertTo({ length: 'px', duration: 's', angle: 'rad' });
  2864. };
  2865. Dimension.prototype.convertTo = function (conversions) {
  2866. var value = this.value;
  2867. var unit = this.unit.clone();
  2868. var i;
  2869. var groupName;
  2870. var group;
  2871. var targetUnit;
  2872. var derivedConversions = {};
  2873. var applyUnit;
  2874. if (typeof conversions === 'string') {
  2875. for (i in unitConversions) {
  2876. if (unitConversions[i].hasOwnProperty(conversions)) {
  2877. derivedConversions = {};
  2878. derivedConversions[i] = conversions;
  2879. }
  2880. }
  2881. conversions = derivedConversions;
  2882. }
  2883. applyUnit = function (atomicUnit, denominator) {
  2884. /* jshint loopfunc:true */
  2885. if (group.hasOwnProperty(atomicUnit)) {
  2886. if (denominator) {
  2887. value = value / (group[atomicUnit] / group[targetUnit]);
  2888. }
  2889. else {
  2890. value = value * (group[atomicUnit] / group[targetUnit]);
  2891. }
  2892. return targetUnit;
  2893. }
  2894. return atomicUnit;
  2895. };
  2896. for (groupName in conversions) {
  2897. if (conversions.hasOwnProperty(groupName)) {
  2898. targetUnit = conversions[groupName];
  2899. group = unitConversions[groupName];
  2900. unit.map(applyUnit);
  2901. }
  2902. }
  2903. unit.cancel();
  2904. return new Dimension(value, unit);
  2905. };
  2906. return Dimension;
  2907. }(Node));
  2908. Dimension.prototype.type = 'Dimension';
  2909. var MATH$1 = Math$1;
  2910. var Operation = /** @class */ (function (_super) {
  2911. __extends(Operation, _super);
  2912. function Operation(op, operands, isSpaced) {
  2913. var _this = _super.call(this) || this;
  2914. _this.op = op.trim();
  2915. _this.operands = operands;
  2916. _this.isSpaced = isSpaced;
  2917. return _this;
  2918. }
  2919. Operation.prototype.accept = function (visitor) {
  2920. this.operands = visitor.visitArray(this.operands);
  2921. };
  2922. Operation.prototype.eval = function (context) {
  2923. var a = this.operands[0].eval(context);
  2924. var b = this.operands[1].eval(context);
  2925. var op;
  2926. if (context.isMathOn(this.op)) {
  2927. op = this.op === './' ? '/' : this.op;
  2928. if (a instanceof Dimension && b instanceof Color) {
  2929. a = a.toColor();
  2930. }
  2931. if (b instanceof Dimension && a instanceof Color) {
  2932. b = b.toColor();
  2933. }
  2934. if (!a.operate) {
  2935. if (a instanceof Operation && a.op === '/' && context.math === MATH$1.PARENS_DIVISION) {
  2936. return new Operation(this.op, [a, b], this.isSpaced);
  2937. }
  2938. throw { type: 'Operation',
  2939. message: 'Operation on an invalid type' };
  2940. }
  2941. return a.operate(context, op, b);
  2942. }
  2943. else {
  2944. return new Operation(this.op, [a, b], this.isSpaced);
  2945. }
  2946. };
  2947. Operation.prototype.genCSS = function (context, output) {
  2948. this.operands[0].genCSS(context, output);
  2949. if (this.isSpaced) {
  2950. output.add(' ');
  2951. }
  2952. output.add(this.op);
  2953. if (this.isSpaced) {
  2954. output.add(' ');
  2955. }
  2956. this.operands[1].genCSS(context, output);
  2957. };
  2958. return Operation;
  2959. }(Node));
  2960. Operation.prototype.type = 'Operation';
  2961. var MATH$2 = Math$1;
  2962. var Expression = /** @class */ (function (_super) {
  2963. __extends(Expression, _super);
  2964. function Expression(value, noSpacing) {
  2965. var _this = _super.call(this) || this;
  2966. _this.value = value;
  2967. _this.noSpacing = noSpacing;
  2968. if (!value) {
  2969. throw new Error('Expression requires an array parameter');
  2970. }
  2971. return _this;
  2972. }
  2973. Expression.prototype.accept = function (visitor) {
  2974. this.value = visitor.visitArray(this.value);
  2975. };
  2976. Expression.prototype.eval = function (context) {
  2977. var returnValue;
  2978. var mathOn = context.isMathOn();
  2979. var inParenthesis = this.parens &&
  2980. (context.math !== MATH$2.STRICT_LEGACY || !this.parensInOp);
  2981. var doubleParen = false;
  2982. if (inParenthesis) {
  2983. context.inParenthesis();
  2984. }
  2985. if (this.value.length > 1) {
  2986. returnValue = new Expression(this.value.map(function (e) {
  2987. if (!e.eval) {
  2988. return e;
  2989. }
  2990. return e.eval(context);
  2991. }), this.noSpacing);
  2992. }
  2993. else if (this.value.length === 1) {
  2994. if (this.value[0].parens && !this.value[0].parensInOp && !context.inCalc) {
  2995. doubleParen = true;
  2996. }
  2997. returnValue = this.value[0].eval(context);
  2998. }
  2999. else {
  3000. returnValue = this;
  3001. }
  3002. if (inParenthesis) {
  3003. context.outOfParenthesis();
  3004. }
  3005. if (this.parens && this.parensInOp && !mathOn && !doubleParen
  3006. && (!(returnValue instanceof Dimension))) {
  3007. returnValue = new Paren(returnValue);
  3008. }
  3009. return returnValue;
  3010. };
  3011. Expression.prototype.genCSS = function (context, output) {
  3012. for (var i = 0; i < this.value.length; i++) {
  3013. this.value[i].genCSS(context, output);
  3014. if (!this.noSpacing && i + 1 < this.value.length) {
  3015. output.add(' ');
  3016. }
  3017. }
  3018. };
  3019. Expression.prototype.throwAwayComments = function () {
  3020. this.value = this.value.filter(function (v) { return !(v instanceof Comment); });
  3021. };
  3022. return Expression;
  3023. }(Node));
  3024. Expression.prototype.type = 'Expression';
  3025. var functionCaller = /** @class */ (function () {
  3026. function functionCaller(name, context, index, currentFileInfo) {
  3027. this.name = name.toLowerCase();
  3028. this.index = index;
  3029. this.context = context;
  3030. this.currentFileInfo = currentFileInfo;
  3031. this.func = context.frames[0].functionRegistry.get(this.name);
  3032. }
  3033. functionCaller.prototype.isValid = function () {
  3034. return Boolean(this.func);
  3035. };
  3036. functionCaller.prototype.call = function (args) {
  3037. var _this = this;
  3038. var evalArgs = this.func.evalArgs;
  3039. if (evalArgs !== false) {
  3040. args = args.map(function (a) { return a.eval(_this.context); });
  3041. }
  3042. // This code is terrible and should be replaced as per this issue...
  3043. // https://github.com/less/less.js/issues/2477
  3044. if (Array.isArray(args)) {
  3045. args = args.filter(function (item) {
  3046. if (item.type === 'Comment') {
  3047. return false;
  3048. }
  3049. return true;
  3050. })
  3051. .map(function (item) {
  3052. if (item.type === 'Expression') {
  3053. var subNodes = item.value.filter(function (item) {
  3054. if (item.type === 'Comment') {
  3055. return false;
  3056. }
  3057. return true;
  3058. });
  3059. if (subNodes.length === 1) {
  3060. return subNodes[0];
  3061. }
  3062. else {
  3063. return new Expression(subNodes);
  3064. }
  3065. }
  3066. return item;
  3067. });
  3068. }
  3069. if (evalArgs === false) {
  3070. return this.func.apply(this, __spreadArrays([this.context], args));
  3071. }
  3072. return this.func.apply(this, args);
  3073. };
  3074. return functionCaller;
  3075. }());
  3076. //
  3077. // A function call node.
  3078. //
  3079. var Call = /** @class */ (function (_super) {
  3080. __extends(Call, _super);
  3081. function Call(name, args, index, currentFileInfo) {
  3082. var _this = _super.call(this) || this;
  3083. _this.name = name;
  3084. _this.args = args;
  3085. _this.calc = name === 'calc';
  3086. _this._index = index;
  3087. _this._fileInfo = currentFileInfo;
  3088. return _this;
  3089. }
  3090. Call.prototype.accept = function (visitor) {
  3091. if (this.args) {
  3092. this.args = visitor.visitArray(this.args);
  3093. }
  3094. };
  3095. //
  3096. // When evaluating a function call,
  3097. // we either find the function in the functionRegistry,
  3098. // in which case we call it, passing the evaluated arguments,
  3099. // if this returns null or we cannot find the function, we
  3100. // simply print it out as it appeared originally [2].
  3101. //
  3102. // The reason why we evaluate the arguments, is in the case where
  3103. // we try to pass a variable to a function, like: `saturate(@color)`.
  3104. // The function should receive the value, not the variable.
  3105. //
  3106. Call.prototype.eval = function (context) {
  3107. var _this = this;
  3108. /**
  3109. * Turn off math for calc(), and switch back on for evaluating nested functions
  3110. */
  3111. var currentMathContext = context.mathOn;
  3112. context.mathOn = !this.calc;
  3113. if (this.calc || context.inCalc) {
  3114. context.enterCalc();
  3115. }
  3116. var exitCalc = function () {
  3117. if (_this.calc || context.inCalc) {
  3118. context.exitCalc();
  3119. }
  3120. context.mathOn = currentMathContext;
  3121. };
  3122. var result;
  3123. var funcCaller = new functionCaller(this.name, context, this.getIndex(), this.fileInfo());
  3124. if (funcCaller.isValid()) {
  3125. try {
  3126. result = funcCaller.call(this.args);
  3127. exitCalc();
  3128. }
  3129. catch (e) {
  3130. if (e.hasOwnProperty('line') && e.hasOwnProperty('column')) {
  3131. throw e;
  3132. }
  3133. throw {
  3134. type: e.type || 'Runtime',
  3135. message: "error evaluating function `" + this.name + "`" + (e.message ? ": " + e.message : ''),
  3136. index: this.getIndex(),
  3137. filename: this.fileInfo().filename,
  3138. line: e.lineNumber,
  3139. column: e.columnNumber
  3140. };
  3141. }
  3142. if (result !== null && result !== undefined) {
  3143. // Results that that are not nodes are cast as Anonymous nodes
  3144. // Falsy values or booleans are returned as empty nodes
  3145. if (!(result instanceof Node)) {
  3146. if (!result || result === true) {
  3147. result = new Anonymous(null);
  3148. }
  3149. else {
  3150. result = new Anonymous(result.toString());
  3151. }
  3152. }
  3153. result._index = this._index;
  3154. result._fileInfo = this._fileInfo;
  3155. return result;
  3156. }
  3157. }
  3158. var args = this.args.map(function (a) { return a.eval(context); });
  3159. exitCalc();
  3160. return new Call(this.name, args, this.getIndex(), this.fileInfo());
  3161. };
  3162. Call.prototype.genCSS = function (context, output) {
  3163. output.add(this.name + "(", this.fileInfo(), this.getIndex());
  3164. for (var i = 0; i < this.args.length; i++) {
  3165. this.args[i].genCSS(context, output);
  3166. if (i + 1 < this.args.length) {
  3167. output.add(', ');
  3168. }
  3169. }
  3170. output.add(')');
  3171. };
  3172. return Call;
  3173. }(Node));
  3174. Call.prototype.type = 'Call';
  3175. var Variable = /** @class */ (function (_super) {
  3176. __extends(Variable, _super);
  3177. function Variable(name, index, currentFileInfo) {
  3178. var _this = _super.call(this) || this;
  3179. _this.name = name;
  3180. _this._index = index;
  3181. _this._fileInfo = currentFileInfo;
  3182. return _this;
  3183. }
  3184. Variable.prototype.eval = function (context) {
  3185. var variable;
  3186. var name = this.name;
  3187. if (name.indexOf('@@') === 0) {
  3188. name = "@" + new Variable(name.slice(1), this.getIndex(), this.fileInfo()).eval(context).value;
  3189. }
  3190. if (this.evaluating) {
  3191. throw { type: 'Name', message: "Recursive variable definition for " + name, filename: this.fileInfo().filename,
  3192. index: this.getIndex() };
  3193. }
  3194. this.evaluating = true;
  3195. variable = this.find(context.frames, function (frame) {
  3196. var v = frame.variable(name);
  3197. if (v) {
  3198. if (v.important) {
  3199. var importantScope = context.importantScope[context.importantScope.length - 1];
  3200. importantScope.important = v.important;
  3201. }
  3202. // If in calc, wrap vars in a function call to cascade evaluate args first
  3203. if (context.inCalc) {
  3204. return (new Call('_SELF', [v.value])).eval(context);
  3205. }
  3206. else {
  3207. return v.value.eval(context);
  3208. }
  3209. }
  3210. });
  3211. if (variable) {
  3212. this.evaluating = false;
  3213. return variable;
  3214. }
  3215. else {
  3216. throw { type: 'Name', message: "variable " + name + " is undefined", filename: this.fileInfo().filename,
  3217. index: this.getIndex() };
  3218. }
  3219. };
  3220. Variable.prototype.find = function (obj, fun) {
  3221. for (var i = 0, r = void 0; i < obj.length; i++) {
  3222. r = fun.call(obj, obj[i]);
  3223. if (r) {
  3224. return r;
  3225. }
  3226. }
  3227. return null;
  3228. };
  3229. return Variable;
  3230. }(Node));
  3231. Variable.prototype.type = 'Variable';
  3232. var Property = /** @class */ (function (_super) {
  3233. __extends(Property, _super);
  3234. function Property(name, index, currentFileInfo) {
  3235. var _this = _super.call(this) || this;
  3236. _this.name = name;
  3237. _this._index = index;
  3238. _this._fileInfo = currentFileInfo;
  3239. return _this;
  3240. }
  3241. Property.prototype.eval = function (context) {
  3242. var property;
  3243. var name = this.name;
  3244. // TODO: shorten this reference
  3245. var mergeRules = context.pluginManager.less.visitors.ToCSSVisitor.prototype._mergeRules;
  3246. if (this.evaluating) {
  3247. throw { type: 'Name', message: "Recursive property reference for " + name, filename: this.fileInfo().filename,
  3248. index: this.getIndex() };
  3249. }
  3250. this.evaluating = true;
  3251. property = this.find(context.frames, function (frame) {
  3252. var v;
  3253. var vArr = frame.property(name);
  3254. if (vArr) {
  3255. for (var i = 0; i < vArr.length; i++) {
  3256. v = vArr[i];
  3257. vArr[i] = new Declaration(v.name, v.value, v.important, v.merge, v.index, v.currentFileInfo, v.inline, v.variable);
  3258. }
  3259. mergeRules(vArr);
  3260. v = vArr[vArr.length - 1];
  3261. if (v.important) {
  3262. var importantScope = context.importantScope[context.importantScope.length - 1];
  3263. importantScope.important = v.important;
  3264. }
  3265. v = v.value.eval(context);
  3266. return v;
  3267. }
  3268. });
  3269. if (property) {
  3270. this.evaluating = false;
  3271. return property;
  3272. }
  3273. else {
  3274. throw { type: 'Name', message: "Property '" + name + "' is undefined", filename: this.currentFileInfo.filename,
  3275. index: this.index };
  3276. }
  3277. };
  3278. Property.prototype.find = function (obj, fun) {
  3279. for (var i = 0, r = void 0; i < obj.length; i++) {
  3280. r = fun.call(obj, obj[i]);
  3281. if (r) {
  3282. return r;
  3283. }
  3284. }
  3285. return null;
  3286. };
  3287. return Property;
  3288. }(Node));
  3289. Property.prototype.type = 'Property';
  3290. var Attribute = /** @class */ (function (_super) {
  3291. __extends(Attribute, _super);
  3292. function Attribute(key, op, value) {
  3293. var _this = _super.call(this) || this;
  3294. _this.key = key;
  3295. _this.op = op;
  3296. _this.value = value;
  3297. return _this;
  3298. }
  3299. Attribute.prototype.eval = function (context) {
  3300. 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);
  3301. };
  3302. Attribute.prototype.genCSS = function (context, output) {
  3303. output.add(this.toCSS(context));
  3304. };
  3305. Attribute.prototype.toCSS = function (context) {
  3306. var value = this.key.toCSS ? this.key.toCSS(context) : this.key;
  3307. if (this.op) {
  3308. value += this.op;
  3309. value += (this.value.toCSS ? this.value.toCSS(context) : this.value);
  3310. }
  3311. return "[" + value + "]";
  3312. };
  3313. return Attribute;
  3314. }(Node));
  3315. Attribute.prototype.type = 'Attribute';
  3316. var Quoted = /** @class */ (function (_super) {
  3317. __extends(Quoted, _super);
  3318. function Quoted(str, content, escaped, index, currentFileInfo) {
  3319. var _this = _super.call(this) || this;
  3320. _this.escaped = (escaped == null) ? true : escaped;
  3321. _this.value = content || '';
  3322. _this.quote = str.charAt(0);
  3323. _this._index = index;
  3324. _this._fileInfo = currentFileInfo;
  3325. _this.variableRegex = /@\{([\w-]+)\}/g;
  3326. _this.propRegex = /\$\{([\w-]+)\}/g;
  3327. _this.allowRoot = escaped;
  3328. return _this;
  3329. }
  3330. Quoted.prototype.genCSS = function (context, output) {
  3331. if (!this.escaped) {
  3332. output.add(this.quote, this.fileInfo(), this.getIndex());
  3333. }
  3334. output.add(this.value);
  3335. if (!this.escaped) {
  3336. output.add(this.quote);
  3337. }
  3338. };
  3339. Quoted.prototype.containsVariables = function () {
  3340. return this.value.match(this.variableRegex);
  3341. };
  3342. Quoted.prototype.eval = function (context) {
  3343. var that = this;
  3344. var value = this.value;
  3345. var variableReplacement = function (_, name) {
  3346. var v = new Variable("@" + name, that.getIndex(), that.fileInfo()).eval(context, true);
  3347. return (v instanceof Quoted) ? v.value : v.toCSS();
  3348. };
  3349. var propertyReplacement = function (_, name) {
  3350. var v = new Property("$" + name, that.getIndex(), that.fileInfo()).eval(context, true);
  3351. return (v instanceof Quoted) ? v.value : v.toCSS();
  3352. };
  3353. function iterativeReplace(value, regexp, replacementFnc) {
  3354. var evaluatedValue = value;
  3355. do {
  3356. value = evaluatedValue.toString();
  3357. evaluatedValue = value.replace(regexp, replacementFnc);
  3358. } while (value !== evaluatedValue);
  3359. return evaluatedValue;
  3360. }
  3361. value = iterativeReplace(value, this.variableRegex, variableReplacement);
  3362. value = iterativeReplace(value, this.propRegex, propertyReplacement);
  3363. return new Quoted(this.quote + value + this.quote, value, this.escaped, this.getIndex(), this.fileInfo());
  3364. };
  3365. Quoted.prototype.compare = function (other) {
  3366. // when comparing quoted strings allow the quote to differ
  3367. if (other.type === 'Quoted' && !this.escaped && !other.escaped) {
  3368. return Node.numericCompare(this.value, other.value);
  3369. }
  3370. else {
  3371. return other.toCSS && this.toCSS() === other.toCSS() ? 0 : undefined;
  3372. }
  3373. };
  3374. return Quoted;
  3375. }(Node));
  3376. Quoted.prototype.type = 'Quoted';
  3377. var URL = /** @class */ (function (_super) {
  3378. __extends(URL, _super);
  3379. function URL(val, index, currentFileInfo, isEvald) {
  3380. var _this = _super.call(this) || this;
  3381. _this.value = val;
  3382. _this._index = index;
  3383. _this._fileInfo = currentFileInfo;
  3384. _this.isEvald = isEvald;
  3385. return _this;
  3386. }
  3387. URL.prototype.accept = function (visitor) {
  3388. this.value = visitor.visit(this.value);
  3389. };
  3390. URL.prototype.genCSS = function (context, output) {
  3391. output.add('url(');
  3392. this.value.genCSS(context, output);
  3393. output.add(')');
  3394. };
  3395. URL.prototype.eval = function (context) {
  3396. var val = this.value.eval(context);
  3397. var rootpath;
  3398. if (!this.isEvald) {
  3399. // Add the rootpath if the URL requires a rewrite
  3400. rootpath = this.fileInfo() && this.fileInfo().rootpath;
  3401. if (typeof rootpath === 'string' &&
  3402. typeof val.value === 'string' &&
  3403. context.pathRequiresRewrite(val.value)) {
  3404. if (!val.quote) {
  3405. rootpath = escapePath(rootpath);
  3406. }
  3407. val.value = context.rewritePath(val.value, rootpath);
  3408. }
  3409. else {
  3410. val.value = context.normalizePath(val.value);
  3411. }
  3412. // Add url args if enabled
  3413. if (context.urlArgs) {
  3414. if (!val.value.match(/^\s*data:/)) {
  3415. var delimiter = val.value.indexOf('?') === -1 ? '?' : '&';
  3416. var urlArgs = delimiter + context.urlArgs;
  3417. if (val.value.indexOf('#') !== -1) {
  3418. val.value = val.value.replace('#', urlArgs + "#");
  3419. }
  3420. else {
  3421. val.value += urlArgs;
  3422. }
  3423. }
  3424. }
  3425. }
  3426. return new URL(val, this.getIndex(), this.fileInfo(), true);
  3427. };
  3428. return URL;
  3429. }(Node));
  3430. URL.prototype.type = 'Url';
  3431. function escapePath(path) {
  3432. return path.replace(/[\(\)'"\s]/g, function (match) { return "\\" + match; });
  3433. }
  3434. var Media = /** @class */ (function (_super) {
  3435. __extends(Media, _super);
  3436. function Media(value, features, index, currentFileInfo, visibilityInfo) {
  3437. var _this = _super.call(this) || this;
  3438. _this._index = index;
  3439. _this._fileInfo = currentFileInfo;
  3440. var selectors = (new Selector([], null, null, _this._index, _this._fileInfo)).createEmptySelectors();
  3441. _this.features = new Value(features);
  3442. _this.rules = [new Ruleset(selectors, value)];
  3443. _this.rules[0].allowImports = true;
  3444. _this.copyVisibilityInfo(visibilityInfo);
  3445. _this.allowRoot = true;
  3446. _this.setParent(selectors, _this);
  3447. _this.setParent(_this.features, _this);
  3448. _this.setParent(_this.rules, _this);
  3449. return _this;
  3450. }
  3451. Media.prototype.isRulesetLike = function () {
  3452. return true;
  3453. };
  3454. Media.prototype.accept = function (visitor) {
  3455. if (this.features) {
  3456. this.features = visitor.visit(this.features);
  3457. }
  3458. if (this.rules) {
  3459. this.rules = visitor.visitArray(this.rules);
  3460. }
  3461. };
  3462. Media.prototype.genCSS = function (context, output) {
  3463. output.add('@media ', this._fileInfo, this._index);
  3464. this.features.genCSS(context, output);
  3465. this.outputRuleset(context, output, this.rules);
  3466. };
  3467. Media.prototype.eval = function (context) {
  3468. if (!context.mediaBlocks) {
  3469. context.mediaBlocks = [];
  3470. context.mediaPath = [];
  3471. }
  3472. var media = new Media(null, [], this._index, this._fileInfo, this.visibilityInfo());
  3473. if (this.debugInfo) {
  3474. this.rules[0].debugInfo = this.debugInfo;
  3475. media.debugInfo = this.debugInfo;
  3476. }
  3477. media.features = this.features.eval(context);
  3478. context.mediaPath.push(media);
  3479. context.mediaBlocks.push(media);
  3480. this.rules[0].functionRegistry = context.frames[0].functionRegistry.inherit();
  3481. context.frames.unshift(this.rules[0]);
  3482. media.rules = [this.rules[0].eval(context)];
  3483. context.frames.shift();
  3484. context.mediaPath.pop();
  3485. return context.mediaPath.length === 0 ? media.evalTop(context) :
  3486. media.evalNested(context);
  3487. };
  3488. Media.prototype.evalTop = function (context) {
  3489. var result = this;
  3490. // Render all dependent Media blocks.
  3491. if (context.mediaBlocks.length > 1) {
  3492. var selectors = (new Selector([], null, null, this.getIndex(), this.fileInfo())).createEmptySelectors();
  3493. result = new Ruleset(selectors, context.mediaBlocks);
  3494. result.multiMedia = true;
  3495. result.copyVisibilityInfo(this.visibilityInfo());
  3496. this.setParent(result, this);
  3497. }
  3498. delete context.mediaBlocks;
  3499. delete context.mediaPath;
  3500. return result;
  3501. };
  3502. Media.prototype.evalNested = function (context) {
  3503. var i;
  3504. var value;
  3505. var path = context.mediaPath.concat([this]);
  3506. // Extract the media-query conditions separated with `,` (OR).
  3507. for (i = 0; i < path.length; i++) {
  3508. value = path[i].features instanceof Value ?
  3509. path[i].features.value : path[i].features;
  3510. path[i] = Array.isArray(value) ? value : [value];
  3511. }
  3512. // Trace all permutations to generate the resulting media-query.
  3513. //
  3514. // (a, b and c) with nested (d, e) ->
  3515. // a and d
  3516. // a and e
  3517. // b and c and d
  3518. // b and c and e
  3519. this.features = new Value(this.permute(path).map(function (path) {
  3520. path = path.map(function (fragment) { return fragment.toCSS ? fragment : new Anonymous(fragment); });
  3521. for (i = path.length - 1; i > 0; i--) {
  3522. path.splice(i, 0, new Anonymous('and'));
  3523. }
  3524. return new Expression(path);
  3525. }));
  3526. this.setParent(this.features, this);
  3527. // Fake a tree-node that doesn't output anything.
  3528. return new Ruleset([], []);
  3529. };
  3530. Media.prototype.permute = function (arr) {
  3531. if (arr.length === 0) {
  3532. return [];
  3533. }
  3534. else if (arr.length === 1) {
  3535. return arr[0];
  3536. }
  3537. else {
  3538. var result = [];
  3539. var rest = this.permute(arr.slice(1));
  3540. for (var i = 0; i < rest.length; i++) {
  3541. for (var j = 0; j < arr[0].length; j++) {
  3542. result.push([arr[0][j]].concat(rest[i]));
  3543. }
  3544. }
  3545. return result;
  3546. }
  3547. };
  3548. Media.prototype.bubbleSelectors = function (selectors) {
  3549. if (!selectors) {
  3550. return;
  3551. }
  3552. this.rules = [new Ruleset(copyArray(selectors), [this.rules[0]])];
  3553. this.setParent(this.rules, this);
  3554. };
  3555. return Media;
  3556. }(AtRule));
  3557. Media.prototype.type = 'Media';
  3558. //
  3559. // CSS @import node
  3560. //
  3561. // The general strategy here is that we don't want to wait
  3562. // for the parsing to be completed, before we start importing
  3563. // the file. That's because in the context of a browser,
  3564. // most of the time will be spent waiting for the server to respond.
  3565. //
  3566. // On creation, we push the import path to our import queue, though
  3567. // `import,push`, we also pass it a callback, which it'll call once
  3568. // the file has been fetched, and parsed.
  3569. //
  3570. var Import = /** @class */ (function (_super) {
  3571. __extends(Import, _super);
  3572. function Import(path, features, options, index, currentFileInfo, visibilityInfo) {
  3573. var _this = _super.call(this) || this;
  3574. _this.options = options;
  3575. _this._index = index;
  3576. _this._fileInfo = currentFileInfo;
  3577. _this.path = path;
  3578. _this.features = features;
  3579. _this.allowRoot = true;
  3580. if (_this.options.less !== undefined || _this.options.inline) {
  3581. _this.css = !_this.options.less || _this.options.inline;
  3582. }
  3583. else {
  3584. var pathValue = _this.getPath();
  3585. if (pathValue && /[#\.\&\?]css([\?;].*)?$/.test(pathValue)) {
  3586. _this.css = true;
  3587. }
  3588. }
  3589. _this.copyVisibilityInfo(visibilityInfo);
  3590. _this.setParent(_this.features, _this);
  3591. _this.setParent(_this.path, _this);
  3592. return _this;
  3593. }
  3594. Import.prototype.accept = function (visitor) {
  3595. if (this.features) {
  3596. this.features = visitor.visit(this.features);
  3597. }
  3598. this.path = visitor.visit(this.path);
  3599. if (!this.options.isPlugin && !this.options.inline && this.root) {
  3600. this.root = visitor.visit(this.root);
  3601. }
  3602. };
  3603. Import.prototype.genCSS = function (context, output) {
  3604. if (this.css && this.path._fileInfo.reference === undefined) {
  3605. output.add('@import ', this._fileInfo, this._index);
  3606. this.path.genCSS(context, output);
  3607. if (this.features) {
  3608. output.add(' ');
  3609. this.features.genCSS(context, output);
  3610. }
  3611. output.add(';');
  3612. }
  3613. };
  3614. Import.prototype.getPath = function () {
  3615. return (this.path instanceof URL) ?
  3616. this.path.value.value : this.path.value;
  3617. };
  3618. Import.prototype.isVariableImport = function () {
  3619. var path = this.path;
  3620. if (path instanceof URL) {
  3621. path = path.value;
  3622. }
  3623. if (path instanceof Quoted) {
  3624. return path.containsVariables();
  3625. }
  3626. return true;
  3627. };
  3628. Import.prototype.evalForImport = function (context) {
  3629. var path = this.path;
  3630. if (path instanceof URL) {
  3631. path = path.value;
  3632. }
  3633. return new Import(path.eval(context), this.features, this.options, this._index, this._fileInfo, this.visibilityInfo());
  3634. };
  3635. Import.prototype.evalPath = function (context) {
  3636. var path = this.path.eval(context);
  3637. var fileInfo = this._fileInfo;
  3638. if (!(path instanceof URL)) {
  3639. // Add the rootpath if the URL requires a rewrite
  3640. var pathValue = path.value;
  3641. if (fileInfo &&
  3642. pathValue &&
  3643. context.pathRequiresRewrite(pathValue)) {
  3644. path.value = context.rewritePath(pathValue, fileInfo.rootpath);
  3645. }
  3646. else {
  3647. path.value = context.normalizePath(path.value);
  3648. }
  3649. }
  3650. return path;
  3651. };
  3652. Import.prototype.eval = function (context) {
  3653. var result = this.doEval(context);
  3654. if (this.options.reference || this.blocksVisibility()) {
  3655. if (result.length || result.length === 0) {
  3656. result.forEach(function (node) {
  3657. node.addVisibilityBlock();
  3658. });
  3659. }
  3660. else {
  3661. result.addVisibilityBlock();
  3662. }
  3663. }
  3664. return result;
  3665. };
  3666. Import.prototype.doEval = function (context) {
  3667. var ruleset;
  3668. var registry;
  3669. var features = this.features && this.features.eval(context);
  3670. if (this.options.isPlugin) {
  3671. if (this.root && this.root.eval) {
  3672. try {
  3673. this.root.eval(context);
  3674. }
  3675. catch (e) {
  3676. e.message = 'Plugin error during evaluation';
  3677. throw new LessError(e, this.root.imports, this.root.filename);
  3678. }
  3679. }
  3680. registry = context.frames[0] && context.frames[0].functionRegistry;
  3681. if (registry && this.root && this.root.functions) {
  3682. registry.addMultiple(this.root.functions);
  3683. }
  3684. return [];
  3685. }
  3686. if (this.skip) {
  3687. if (typeof this.skip === 'function') {
  3688. this.skip = this.skip();
  3689. }
  3690. if (this.skip) {
  3691. return [];
  3692. }
  3693. }
  3694. if (this.options.inline) {
  3695. var contents = new Anonymous(this.root, 0, {
  3696. filename: this.importedFilename,
  3697. reference: this.path._fileInfo && this.path._fileInfo.reference
  3698. }, true, true);
  3699. return this.features ? new Media([contents], this.features.value) : [contents];
  3700. }
  3701. else if (this.css) {
  3702. var newImport = new Import(this.evalPath(context), features, this.options, this._index);
  3703. if (!newImport.css && this.error) {
  3704. throw this.error;
  3705. }
  3706. return newImport;
  3707. }
  3708. else if (this.root) {
  3709. ruleset = new Ruleset(null, copyArray(this.root.rules));
  3710. ruleset.evalImports(context);
  3711. return this.features ? new Media(ruleset.rules, this.features.value) : ruleset.rules;
  3712. }
  3713. else {
  3714. return [];
  3715. }
  3716. };
  3717. return Import;
  3718. }(Node));
  3719. Import.prototype.type = 'Import';
  3720. var JsEvalNode = /** @class */ (function (_super) {
  3721. __extends(JsEvalNode, _super);
  3722. function JsEvalNode() {
  3723. return _super !== null && _super.apply(this, arguments) || this;
  3724. }
  3725. JsEvalNode.prototype.evaluateJavaScript = function (expression, context) {
  3726. var result;
  3727. var that = this;
  3728. var evalContext = {};
  3729. if (!context.javascriptEnabled) {
  3730. throw { message: 'Inline JavaScript is not enabled. Is it set in your options?',
  3731. filename: this.fileInfo().filename,
  3732. index: this.getIndex() };
  3733. }
  3734. expression = expression.replace(/@\{([\w-]+)\}/g, function (_, name) { return that.jsify(new Variable("@" + name, that.getIndex(), that.fileInfo()).eval(context)); });
  3735. try {
  3736. expression = new Function("return (" + expression + ")");
  3737. }
  3738. catch (e) {
  3739. throw { message: "JavaScript evaluation error: " + e.message + " from `" + expression + "`", filename: this.fileInfo().filename,
  3740. index: this.getIndex() };
  3741. }
  3742. var variables = context.frames[0].variables();
  3743. for (var k in variables) {
  3744. if (variables.hasOwnProperty(k)) {
  3745. /* jshint loopfunc:true */
  3746. evalContext[k.slice(1)] = {
  3747. value: variables[k].value,
  3748. toJS: function () {
  3749. return this.value.eval(context).toCSS();
  3750. }
  3751. };
  3752. }
  3753. }
  3754. try {
  3755. result = expression.call(evalContext);
  3756. }
  3757. catch (e) {
  3758. throw { message: "JavaScript evaluation error: '" + e.name + ": " + e.message.replace(/["]/g, '\'') + "'", filename: this.fileInfo().filename,
  3759. index: this.getIndex() };
  3760. }
  3761. return result;
  3762. };
  3763. JsEvalNode.prototype.jsify = function (obj) {
  3764. if (Array.isArray(obj.value) && (obj.value.length > 1)) {
  3765. return "[" + obj.value.map(function (v) { return v.toCSS(); }).join(', ') + "]";
  3766. }
  3767. else {
  3768. return obj.toCSS();
  3769. }
  3770. };
  3771. return JsEvalNode;
  3772. }(Node));
  3773. var JavaScript = /** @class */ (function (_super) {
  3774. __extends(JavaScript, _super);
  3775. function JavaScript(string, escaped, index, currentFileInfo) {
  3776. var _this = _super.call(this) || this;
  3777. _this.escaped = escaped;
  3778. _this.expression = string;
  3779. _this._index = index;
  3780. _this._fileInfo = currentFileInfo;
  3781. return _this;
  3782. }
  3783. JavaScript.prototype.eval = function (context) {
  3784. var result = this.evaluateJavaScript(this.expression, context);
  3785. var type = typeof result;
  3786. if (type === 'number' && !isNaN(result)) {
  3787. return new Dimension(result);
  3788. }
  3789. else if (type === 'string') {
  3790. return new Quoted("\"" + result + "\"", result, this.escaped, this._index);
  3791. }
  3792. else if (Array.isArray(result)) {
  3793. return new Anonymous(result.join(', '));
  3794. }
  3795. else {
  3796. return new Anonymous(result);
  3797. }
  3798. };
  3799. return JavaScript;
  3800. }(JsEvalNode));
  3801. JavaScript.prototype.type = 'JavaScript';
  3802. var Assignment = /** @class */ (function (_super) {
  3803. __extends(Assignment, _super);
  3804. function Assignment(key, val) {
  3805. var _this = _super.call(this) || this;
  3806. _this.key = key;
  3807. _this.value = val;
  3808. return _this;
  3809. }
  3810. Assignment.prototype.accept = function (visitor) {
  3811. this.value = visitor.visit(this.value);
  3812. };
  3813. Assignment.prototype.eval = function (context) {
  3814. if (this.value.eval) {
  3815. return new Assignment(this.key, this.value.eval(context));
  3816. }
  3817. return this;
  3818. };
  3819. Assignment.prototype.genCSS = function (context, output) {
  3820. output.add(this.key + "=");
  3821. if (this.value.genCSS) {
  3822. this.value.genCSS(context, output);
  3823. }
  3824. else {
  3825. output.add(this.value);
  3826. }
  3827. };
  3828. return Assignment;
  3829. }(Node));
  3830. Assignment.prototype.type = 'Assignment';
  3831. var Condition = /** @class */ (function (_super) {
  3832. __extends(Condition, _super);
  3833. function Condition(op, l, r, i, negate) {
  3834. var _this = _super.call(this) || this;
  3835. _this.op = op.trim();
  3836. _this.lvalue = l;
  3837. _this.rvalue = r;
  3838. _this._index = i;
  3839. _this.negate = negate;
  3840. return _this;
  3841. }
  3842. Condition.prototype.accept = function (visitor) {
  3843. this.lvalue = visitor.visit(this.lvalue);
  3844. this.rvalue = visitor.visit(this.rvalue);
  3845. };
  3846. Condition.prototype.eval = function (context) {
  3847. var result = (function (op, a, b) {
  3848. switch (op) {
  3849. case 'and': return a && b;
  3850. case 'or': return a || b;
  3851. default:
  3852. switch (Node.compare(a, b)) {
  3853. case -1:
  3854. return op === '<' || op === '=<' || op === '<=';
  3855. case 0:
  3856. return op === '=' || op === '>=' || op === '=<' || op === '<=';
  3857. case 1:
  3858. return op === '>' || op === '>=';
  3859. default:
  3860. return false;
  3861. }
  3862. }
  3863. })(this.op, this.lvalue.eval(context), this.rvalue.eval(context));
  3864. return this.negate ? !result : result;
  3865. };
  3866. return Condition;
  3867. }(Node));
  3868. Condition.prototype.type = 'Condition';
  3869. var UnicodeDescriptor = /** @class */ (function (_super) {
  3870. __extends(UnicodeDescriptor, _super);
  3871. function UnicodeDescriptor(value) {
  3872. var _this = _super.call(this) || this;
  3873. _this.value = value;
  3874. return _this;
  3875. }
  3876. return UnicodeDescriptor;
  3877. }(Node));
  3878. UnicodeDescriptor.prototype.type = 'UnicodeDescriptor';
  3879. var Negative = /** @class */ (function (_super) {
  3880. __extends(Negative, _super);
  3881. function Negative(node) {
  3882. var _this = _super.call(this) || this;
  3883. _this.value = node;
  3884. return _this;
  3885. }
  3886. Negative.prototype.genCSS = function (context, output) {
  3887. output.add('-');
  3888. this.value.genCSS(context, output);
  3889. };
  3890. Negative.prototype.eval = function (context) {
  3891. if (context.isMathOn()) {
  3892. return (new Operation('*', [new Dimension(-1), this.value])).eval(context);
  3893. }
  3894. return new Negative(this.value.eval(context));
  3895. };
  3896. return Negative;
  3897. }(Node));
  3898. Negative.prototype.type = 'Negative';
  3899. var Extend = /** @class */ (function (_super) {
  3900. __extends(Extend, _super);
  3901. function Extend(selector, option, index, currentFileInfo, visibilityInfo) {
  3902. var _this = _super.call(this) || this;
  3903. _this.selector = selector;
  3904. _this.option = option;
  3905. _this.object_id = Extend.next_id++;
  3906. _this.parent_ids = [_this.object_id];
  3907. _this._index = index;
  3908. _this._fileInfo = currentFileInfo;
  3909. _this.copyVisibilityInfo(visibilityInfo);
  3910. _this.allowRoot = true;
  3911. switch (option) {
  3912. case 'all':
  3913. _this.allowBefore = true;
  3914. _this.allowAfter = true;
  3915. break;
  3916. default:
  3917. _this.allowBefore = false;
  3918. _this.allowAfter = false;
  3919. break;
  3920. }
  3921. _this.setParent(_this.selector, _this);
  3922. return _this;
  3923. }
  3924. Extend.prototype.accept = function (visitor) {
  3925. this.selector = visitor.visit(this.selector);
  3926. };
  3927. Extend.prototype.eval = function (context) {
  3928. return new Extend(this.selector.eval(context), this.option, this.getIndex(), this.fileInfo(), this.visibilityInfo());
  3929. };
  3930. Extend.prototype.clone = function (context) {
  3931. return new Extend(this.selector, this.option, this.getIndex(), this.fileInfo(), this.visibilityInfo());
  3932. };
  3933. // it concatenates (joins) all selectors in selector array
  3934. Extend.prototype.findSelfSelectors = function (selectors) {
  3935. var selfElements = [];
  3936. var i;
  3937. var selectorElements;
  3938. for (i = 0; i < selectors.length; i++) {
  3939. selectorElements = selectors[i].elements;
  3940. // duplicate the logic in genCSS function inside the selector node.
  3941. // future TODO - move both logics into the selector joiner visitor
  3942. if (i > 0 && selectorElements.length && selectorElements[0].combinator.value === '') {
  3943. selectorElements[0].combinator.value = ' ';
  3944. }
  3945. selfElements = selfElements.concat(selectors[i].elements);
  3946. }
  3947. this.selfSelectors = [new Selector(selfElements)];
  3948. this.selfSelectors[0].copyVisibilityInfo(this.visibilityInfo());
  3949. };
  3950. return Extend;
  3951. }(Node));
  3952. Extend.next_id = 0;
  3953. Extend.prototype.type = 'Extend';
  3954. var VariableCall = /** @class */ (function (_super) {
  3955. __extends(VariableCall, _super);
  3956. function VariableCall(variable, index, currentFileInfo) {
  3957. var _this = _super.call(this) || this;
  3958. _this.variable = variable;
  3959. _this._index = index;
  3960. _this._fileInfo = currentFileInfo;
  3961. _this.allowRoot = true;
  3962. return _this;
  3963. }
  3964. VariableCall.prototype.eval = function (context) {
  3965. var rules;
  3966. var detachedRuleset = new Variable(this.variable, this.getIndex(), this.fileInfo()).eval(context);
  3967. var error = new LessError({ message: "Could not evaluate variable call " + this.variable });
  3968. if (!detachedRuleset.ruleset) {
  3969. if (detachedRuleset.rules) {
  3970. rules = detachedRuleset;
  3971. }
  3972. else if (Array.isArray(detachedRuleset)) {
  3973. rules = new Ruleset('', detachedRuleset);
  3974. }
  3975. else if (Array.isArray(detachedRuleset.value)) {
  3976. rules = new Ruleset('', detachedRuleset.value);
  3977. }
  3978. else {
  3979. throw error;
  3980. }
  3981. detachedRuleset = new DetachedRuleset(rules);
  3982. }
  3983. if (detachedRuleset.ruleset) {
  3984. return detachedRuleset.callEval(context);
  3985. }
  3986. throw error;
  3987. };
  3988. return VariableCall;
  3989. }(Node));
  3990. VariableCall.prototype.type = 'VariableCall';
  3991. var NamespaceValue = /** @class */ (function (_super) {
  3992. __extends(NamespaceValue, _super);
  3993. function NamespaceValue(ruleCall, lookups, index, fileInfo) {
  3994. var _this = _super.call(this) || this;
  3995. _this.value = ruleCall;
  3996. _this.lookups = lookups;
  3997. _this._index = index;
  3998. _this._fileInfo = fileInfo;
  3999. return _this;
  4000. }
  4001. NamespaceValue.prototype.eval = function (context) {
  4002. var i;
  4003. var name;
  4004. var rules = this.value.eval(context);
  4005. for (i = 0; i < this.lookups.length; i++) {
  4006. name = this.lookups[i];
  4007. /**
  4008. * Eval'd DRs return rulesets.
  4009. * Eval'd mixins return rules, so let's make a ruleset if we need it.
  4010. * We need to do this because of late parsing of values
  4011. */
  4012. if (Array.isArray(rules)) {
  4013. rules = new Ruleset([new Selector()], rules);
  4014. }
  4015. if (name === '') {
  4016. rules = rules.lastDeclaration();
  4017. }
  4018. else if (name.charAt(0) === '@') {
  4019. if (name.charAt(1) === '@') {
  4020. name = "@" + new Variable(name.substr(1)).eval(context).value;
  4021. }
  4022. if (rules.variables) {
  4023. rules = rules.variable(name);
  4024. }
  4025. if (!rules) {
  4026. throw { type: 'Name', message: "variable " + name + " not found", filename: this.fileInfo().filename,
  4027. index: this.getIndex() };
  4028. }
  4029. }
  4030. else {
  4031. if (name.substring(0, 2) === '$@') {
  4032. name = "$" + new Variable(name.substr(1)).eval(context).value;
  4033. }
  4034. else {
  4035. name = name.charAt(0) === '$' ? name : "$" + name;
  4036. }
  4037. if (rules.properties) {
  4038. rules = rules.property(name);
  4039. }
  4040. if (!rules) {
  4041. throw { type: 'Name', message: "property \"" + name.substr(1) + "\" not found", filename: this.fileInfo().filename,
  4042. index: this.getIndex() };
  4043. }
  4044. // Properties are an array of values, since a ruleset can have multiple props.
  4045. // We pick the last one (the "cascaded" value)
  4046. rules = rules[rules.length - 1];
  4047. }
  4048. if (rules.value) {
  4049. rules = rules.eval(context).value;
  4050. }
  4051. if (rules.ruleset) {
  4052. rules = rules.ruleset.eval(context);
  4053. }
  4054. }
  4055. return rules;
  4056. };
  4057. return NamespaceValue;
  4058. }(Node));
  4059. NamespaceValue.prototype.type = 'NamespaceValue';
  4060. var Definition = /** @class */ (function (_super) {
  4061. __extends(Definition, _super);
  4062. function Definition(name, params, rules, condition, variadic, frames, visibilityInfo) {
  4063. var _this = _super.call(this) || this;
  4064. _this.name = name || 'anonymous mixin';
  4065. _this.selectors = [new Selector([new Element(null, name, false, _this._index, _this._fileInfo)])];
  4066. _this.params = params;
  4067. _this.condition = condition;
  4068. _this.variadic = variadic;
  4069. _this.arity = params.length;
  4070. _this.rules = rules;
  4071. _this._lookups = {};
  4072. var optionalParameters = [];
  4073. _this.required = params.reduce(function (count, p) {
  4074. if (!p.name || (p.name && !p.value)) {
  4075. return count + 1;
  4076. }
  4077. else {
  4078. optionalParameters.push(p.name);
  4079. return count;
  4080. }
  4081. }, 0);
  4082. _this.optionalParameters = optionalParameters;
  4083. _this.frames = frames;
  4084. _this.copyVisibilityInfo(visibilityInfo);
  4085. _this.allowRoot = true;
  4086. return _this;
  4087. }
  4088. Definition.prototype.accept = function (visitor) {
  4089. if (this.params && this.params.length) {
  4090. this.params = visitor.visitArray(this.params);
  4091. }
  4092. this.rules = visitor.visitArray(this.rules);
  4093. if (this.condition) {
  4094. this.condition = visitor.visit(this.condition);
  4095. }
  4096. };
  4097. Definition.prototype.evalParams = function (context, mixinEnv, args, evaldArguments) {
  4098. /* jshint boss:true */
  4099. var frame = new Ruleset(null, null);
  4100. var varargs;
  4101. var arg;
  4102. var params = copyArray(this.params);
  4103. var i;
  4104. var j;
  4105. var val;
  4106. var name;
  4107. var isNamedFound;
  4108. var argIndex;
  4109. var argsLength = 0;
  4110. if (mixinEnv.frames && mixinEnv.frames[0] && mixinEnv.frames[0].functionRegistry) {
  4111. frame.functionRegistry = mixinEnv.frames[0].functionRegistry.inherit();
  4112. }
  4113. mixinEnv = new contexts.Eval(mixinEnv, [frame].concat(mixinEnv.frames));
  4114. if (args) {
  4115. args = copyArray(args);
  4116. argsLength = args.length;
  4117. for (i = 0; i < argsLength; i++) {
  4118. arg = args[i];
  4119. if (name = (arg && arg.name)) {
  4120. isNamedFound = false;
  4121. for (j = 0; j < params.length; j++) {
  4122. if (!evaldArguments[j] && name === params[j].name) {
  4123. evaldArguments[j] = arg.value.eval(context);
  4124. frame.prependRule(new Declaration(name, arg.value.eval(context)));
  4125. isNamedFound = true;
  4126. break;
  4127. }
  4128. }
  4129. if (isNamedFound) {
  4130. args.splice(i, 1);
  4131. i--;
  4132. continue;
  4133. }
  4134. else {
  4135. throw { type: 'Runtime', message: "Named argument for " + this.name + " " + args[i].name + " not found" };
  4136. }
  4137. }
  4138. }
  4139. }
  4140. argIndex = 0;
  4141. for (i = 0; i < params.length; i++) {
  4142. if (evaldArguments[i]) {
  4143. continue;
  4144. }
  4145. arg = args && args[argIndex];
  4146. if (name = params[i].name) {
  4147. if (params[i].variadic) {
  4148. varargs = [];
  4149. for (j = argIndex; j < argsLength; j++) {
  4150. varargs.push(args[j].value.eval(context));
  4151. }
  4152. frame.prependRule(new Declaration(name, new Expression(varargs).eval(context)));
  4153. }
  4154. else {
  4155. val = arg && arg.value;
  4156. if (val) {
  4157. // This was a mixin call, pass in a detached ruleset of it's eval'd rules
  4158. if (Array.isArray(val)) {
  4159. val = new DetachedRuleset(new Ruleset('', val));
  4160. }
  4161. else {
  4162. val = val.eval(context);
  4163. }
  4164. }
  4165. else if (params[i].value) {
  4166. val = params[i].value.eval(mixinEnv);
  4167. frame.resetCache();
  4168. }
  4169. else {
  4170. throw { type: 'Runtime', message: "wrong number of arguments for " + this.name + " (" + argsLength + " for " + this.arity + ")" };
  4171. }
  4172. frame.prependRule(new Declaration(name, val));
  4173. evaldArguments[i] = val;
  4174. }
  4175. }
  4176. if (params[i].variadic && args) {
  4177. for (j = argIndex; j < argsLength; j++) {
  4178. evaldArguments[j] = args[j].value.eval(context);
  4179. }
  4180. }
  4181. argIndex++;
  4182. }
  4183. return frame;
  4184. };
  4185. Definition.prototype.makeImportant = function () {
  4186. var rules = !this.rules ? this.rules : this.rules.map(function (r) {
  4187. if (r.makeImportant) {
  4188. return r.makeImportant(true);
  4189. }
  4190. else {
  4191. return r;
  4192. }
  4193. });
  4194. var result = new Definition(this.name, this.params, rules, this.condition, this.variadic, this.frames);
  4195. return result;
  4196. };
  4197. Definition.prototype.eval = function (context) {
  4198. return new Definition(this.name, this.params, this.rules, this.condition, this.variadic, this.frames || copyArray(context.frames));
  4199. };
  4200. Definition.prototype.evalCall = function (context, args, important) {
  4201. var _arguments = [];
  4202. var mixinFrames = this.frames ? this.frames.concat(context.frames) : context.frames;
  4203. var frame = this.evalParams(context, new contexts.Eval(context, mixinFrames), args, _arguments);
  4204. var rules;
  4205. var ruleset;
  4206. frame.prependRule(new Declaration('@arguments', new Expression(_arguments).eval(context)));
  4207. rules = copyArray(this.rules);
  4208. ruleset = new Ruleset(null, rules);
  4209. ruleset.originalRuleset = this;
  4210. ruleset = ruleset.eval(new contexts.Eval(context, [this, frame].concat(mixinFrames)));
  4211. if (important) {
  4212. ruleset = ruleset.makeImportant();
  4213. }
  4214. return ruleset;
  4215. };
  4216. Definition.prototype.matchCondition = function (args, context) {
  4217. 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, [])]
  4218. .concat(this.frames || []) // the parent namespace/mixin frames
  4219. .concat(context.frames)))) { // the current environment frames
  4220. return false;
  4221. }
  4222. return true;
  4223. };
  4224. Definition.prototype.matchArgs = function (args, context) {
  4225. var allArgsCnt = (args && args.length) || 0;
  4226. var len;
  4227. var optionalParameters = this.optionalParameters;
  4228. var requiredArgsCnt = !args ? 0 : args.reduce(function (count, p) {
  4229. if (optionalParameters.indexOf(p.name) < 0) {
  4230. return count + 1;
  4231. }
  4232. else {
  4233. return count;
  4234. }
  4235. }, 0);
  4236. if (!this.variadic) {
  4237. if (requiredArgsCnt < this.required) {
  4238. return false;
  4239. }
  4240. if (allArgsCnt > this.params.length) {
  4241. return false;
  4242. }
  4243. }
  4244. else {
  4245. if (requiredArgsCnt < (this.required - 1)) {
  4246. return false;
  4247. }
  4248. }
  4249. // check patterns
  4250. len = Math.min(requiredArgsCnt, this.arity);
  4251. for (var i = 0; i < len; i++) {
  4252. if (!this.params[i].name && !this.params[i].variadic) {
  4253. if (args[i].value.eval(context).toCSS() != this.params[i].value.eval(context).toCSS()) {
  4254. return false;
  4255. }
  4256. }
  4257. }
  4258. return true;
  4259. };
  4260. return Definition;
  4261. }(Ruleset));
  4262. Definition.prototype.type = 'MixinDefinition';
  4263. Definition.prototype.evalFirst = true;
  4264. var MixinCall = /** @class */ (function (_super) {
  4265. __extends(MixinCall, _super);
  4266. function MixinCall(elements, args, index, currentFileInfo, important) {
  4267. var _this = _super.call(this) || this;
  4268. _this.selector = new Selector(elements);
  4269. _this.arguments = args || [];
  4270. _this._index = index;
  4271. _this._fileInfo = currentFileInfo;
  4272. _this.important = important;
  4273. _this.allowRoot = true;
  4274. _this.setParent(_this.selector, _this);
  4275. return _this;
  4276. }
  4277. MixinCall.prototype.accept = function (visitor) {
  4278. if (this.selector) {
  4279. this.selector = visitor.visit(this.selector);
  4280. }
  4281. if (this.arguments.length) {
  4282. this.arguments = visitor.visitArray(this.arguments);
  4283. }
  4284. };
  4285. MixinCall.prototype.eval = function (context) {
  4286. var mixins;
  4287. var mixin;
  4288. var mixinPath;
  4289. var args = [];
  4290. var arg;
  4291. var argValue;
  4292. var rules = [];
  4293. var match = false;
  4294. var i;
  4295. var m;
  4296. var f;
  4297. var isRecursive;
  4298. var isOneFound;
  4299. var candidates = [];
  4300. var candidate;
  4301. var conditionResult = [];
  4302. var defaultResult;
  4303. var defFalseEitherCase = -1;
  4304. var defNone = 0;
  4305. var defTrue = 1;
  4306. var defFalse = 2;
  4307. var count;
  4308. var originalRuleset;
  4309. var noArgumentsFilter;
  4310. this.selector = this.selector.eval(context);
  4311. function calcDefGroup(mixin, mixinPath) {
  4312. var f;
  4313. var p;
  4314. var namespace;
  4315. for (f = 0; f < 2; f++) {
  4316. conditionResult[f] = true;
  4317. defaultFunc.value(f);
  4318. for (p = 0; p < mixinPath.length && conditionResult[f]; p++) {
  4319. namespace = mixinPath[p];
  4320. if (namespace.matchCondition) {
  4321. conditionResult[f] = conditionResult[f] && namespace.matchCondition(null, context);
  4322. }
  4323. }
  4324. if (mixin.matchCondition) {
  4325. conditionResult[f] = conditionResult[f] && mixin.matchCondition(args, context);
  4326. }
  4327. }
  4328. if (conditionResult[0] || conditionResult[1]) {
  4329. if (conditionResult[0] != conditionResult[1]) {
  4330. return conditionResult[1] ?
  4331. defTrue : defFalse;
  4332. }
  4333. return defNone;
  4334. }
  4335. return defFalseEitherCase;
  4336. }
  4337. for (i = 0; i < this.arguments.length; i++) {
  4338. arg = this.arguments[i];
  4339. argValue = arg.value.eval(context);
  4340. if (arg.expand && Array.isArray(argValue.value)) {
  4341. argValue = argValue.value;
  4342. for (m = 0; m < argValue.length; m++) {
  4343. args.push({ value: argValue[m] });
  4344. }
  4345. }
  4346. else {
  4347. args.push({ name: arg.name, value: argValue });
  4348. }
  4349. }
  4350. noArgumentsFilter = function (rule) { return rule.matchArgs(null, context); };
  4351. for (i = 0; i < context.frames.length; i++) {
  4352. if ((mixins = context.frames[i].find(this.selector, null, noArgumentsFilter)).length > 0) {
  4353. isOneFound = true;
  4354. // To make `default()` function independent of definition order we have two "subpasses" here.
  4355. // At first we evaluate each guard *twice* (with `default() == true` and `default() == false`),
  4356. // and build candidate list with corresponding flags. Then, when we know all possible matches,
  4357. // we make a final decision.
  4358. for (m = 0; m < mixins.length; m++) {
  4359. mixin = mixins[m].rule;
  4360. mixinPath = mixins[m].path;
  4361. isRecursive = false;
  4362. for (f = 0; f < context.frames.length; f++) {
  4363. if ((!(mixin instanceof Definition)) && mixin === (context.frames[f].originalRuleset || context.frames[f])) {
  4364. isRecursive = true;
  4365. break;
  4366. }
  4367. }
  4368. if (isRecursive) {
  4369. continue;
  4370. }
  4371. if (mixin.matchArgs(args, context)) {
  4372. candidate = { mixin: mixin, group: calcDefGroup(mixin, mixinPath) };
  4373. if (candidate.group !== defFalseEitherCase) {
  4374. candidates.push(candidate);
  4375. }
  4376. match = true;
  4377. }
  4378. }
  4379. defaultFunc.reset();
  4380. count = [0, 0, 0];
  4381. for (m = 0; m < candidates.length; m++) {
  4382. count[candidates[m].group]++;
  4383. }
  4384. if (count[defNone] > 0) {
  4385. defaultResult = defFalse;
  4386. }
  4387. else {
  4388. defaultResult = defTrue;
  4389. if ((count[defTrue] + count[defFalse]) > 1) {
  4390. throw { type: 'Runtime', message: "Ambiguous use of `default()` found when matching for `" + this.format(args) + "`", index: this.getIndex(), filename: this.fileInfo().filename };
  4391. }
  4392. }
  4393. for (m = 0; m < candidates.length; m++) {
  4394. candidate = candidates[m].group;
  4395. if ((candidate === defNone) || (candidate === defaultResult)) {
  4396. try {
  4397. mixin = candidates[m].mixin;
  4398. if (!(mixin instanceof Definition)) {
  4399. originalRuleset = mixin.originalRuleset || mixin;
  4400. mixin = new Definition('', [], mixin.rules, null, false, null, originalRuleset.visibilityInfo());
  4401. mixin.originalRuleset = originalRuleset;
  4402. }
  4403. var newRules = mixin.evalCall(context, args, this.important).rules;
  4404. this._setVisibilityToReplacement(newRules);
  4405. Array.prototype.push.apply(rules, newRules);
  4406. }
  4407. catch (e) {
  4408. throw { message: e.message, index: this.getIndex(), filename: this.fileInfo().filename, stack: e.stack };
  4409. }
  4410. }
  4411. }
  4412. if (match) {
  4413. return rules;
  4414. }
  4415. }
  4416. }
  4417. if (isOneFound) {
  4418. throw { type: 'Runtime', message: "No matching definition was found for `" + this.format(args) + "`", index: this.getIndex(), filename: this.fileInfo().filename };
  4419. }
  4420. else {
  4421. throw { type: 'Name', message: this.selector.toCSS().trim() + " is undefined", index: this.getIndex(), filename: this.fileInfo().filename };
  4422. }
  4423. };
  4424. MixinCall.prototype._setVisibilityToReplacement = function (replacement) {
  4425. var i;
  4426. var rule;
  4427. if (this.blocksVisibility()) {
  4428. for (i = 0; i < replacement.length; i++) {
  4429. rule = replacement[i];
  4430. rule.addVisibilityBlock();
  4431. }
  4432. }
  4433. };
  4434. MixinCall.prototype.format = function (args) {
  4435. return this.selector.toCSS().trim() + "(" + (args ? args.map(function (a) {
  4436. var argValue = '';
  4437. if (a.name) {
  4438. argValue += a.name + ":";
  4439. }
  4440. if (a.value.toCSS) {
  4441. argValue += a.value.toCSS();
  4442. }
  4443. else {
  4444. argValue += '???';
  4445. }
  4446. return argValue;
  4447. }).join(', ') : '') + ")";
  4448. };
  4449. return MixinCall;
  4450. }(Node));
  4451. MixinCall.prototype.type = 'MixinCall';
  4452. var tree = {
  4453. Node: Node, Color: Color, AtRule: AtRule, DetachedRuleset: DetachedRuleset, Operation: Operation,
  4454. Dimension: Dimension, Unit: Unit, Keyword: Keyword, Variable: Variable, Property: Property,
  4455. Ruleset: Ruleset, Element: Element, Attribute: Attribute, Combinator: Combinator, Selector: Selector,
  4456. Quoted: Quoted, Expression: Expression, Declaration: Declaration, Call: Call, URL: URL, Import: Import,
  4457. Comment: Comment, Anonymous: Anonymous, Value: Value, JavaScript: JavaScript, Assignment: Assignment,
  4458. Condition: Condition, Paren: Paren, Media: Media, UnicodeDescriptor: UnicodeDescriptor, Negative: Negative,
  4459. Extend: Extend, VariableCall: VariableCall, NamespaceValue: NamespaceValue,
  4460. mixin: {
  4461. Call: MixinCall,
  4462. Definition: Definition
  4463. }
  4464. };
  4465. var logger = {
  4466. error: function (msg) {
  4467. this._fireEvent('error', msg);
  4468. },
  4469. warn: function (msg) {
  4470. this._fireEvent('warn', msg);
  4471. },
  4472. info: function (msg) {
  4473. this._fireEvent('info', msg);
  4474. },
  4475. debug: function (msg) {
  4476. this._fireEvent('debug', msg);
  4477. },
  4478. addListener: function (listener) {
  4479. this._listeners.push(listener);
  4480. },
  4481. removeListener: function (listener) {
  4482. for (var i = 0; i < this._listeners.length; i++) {
  4483. if (this._listeners[i] === listener) {
  4484. this._listeners.splice(i, 1);
  4485. return;
  4486. }
  4487. }
  4488. },
  4489. _fireEvent: function (type, msg) {
  4490. for (var i = 0; i < this._listeners.length; i++) {
  4491. var logFunction = this._listeners[i][type];
  4492. if (logFunction) {
  4493. logFunction(msg);
  4494. }
  4495. }
  4496. },
  4497. _listeners: []
  4498. };
  4499. /**
  4500. * @todo Document why this abstraction exists, and the relationship between
  4501. * environment, file managers, and plugin manager
  4502. */
  4503. var environment = /** @class */ (function () {
  4504. function environment(externalEnvironment, fileManagers) {
  4505. this.fileManagers = fileManagers || [];
  4506. externalEnvironment = externalEnvironment || {};
  4507. var optionalFunctions = ['encodeBase64', 'mimeLookup', 'charsetLookup', 'getSourceMapGenerator'];
  4508. var requiredFunctions = [];
  4509. var functions = requiredFunctions.concat(optionalFunctions);
  4510. for (var i = 0; i < functions.length; i++) {
  4511. var propName = functions[i];
  4512. var environmentFunc = externalEnvironment[propName];
  4513. if (environmentFunc) {
  4514. this[propName] = environmentFunc.bind(externalEnvironment);
  4515. }
  4516. else if (i < requiredFunctions.length) {
  4517. this.warn("missing required function in environment - " + propName);
  4518. }
  4519. }
  4520. }
  4521. environment.prototype.getFileManager = function (filename, currentDirectory, options, environment, isSync) {
  4522. if (!filename) {
  4523. logger.warn('getFileManager called with no filename.. Please report this issue. continuing.');
  4524. }
  4525. if (currentDirectory == null) {
  4526. logger.warn('getFileManager called with null directory.. Please report this issue. continuing.');
  4527. }
  4528. var fileManagers = this.fileManagers;
  4529. if (options.pluginManager) {
  4530. fileManagers = [].concat(fileManagers).concat(options.pluginManager.getFileManagers());
  4531. }
  4532. for (var i = fileManagers.length - 1; i >= 0; i--) {
  4533. var fileManager = fileManagers[i];
  4534. if (fileManager[isSync ? 'supportsSync' : 'supports'](filename, currentDirectory, options, environment)) {
  4535. return fileManager;
  4536. }
  4537. }
  4538. return null;
  4539. };
  4540. environment.prototype.addFileManager = function (fileManager) {
  4541. this.fileManagers.push(fileManager);
  4542. };
  4543. environment.prototype.clearFileManagers = function () {
  4544. this.fileManagers = [];
  4545. };
  4546. return environment;
  4547. }());
  4548. var AbstractFileManager = /** @class */ (function () {
  4549. function AbstractFileManager() {
  4550. }
  4551. AbstractFileManager.prototype.getPath = function (filename) {
  4552. var j = filename.lastIndexOf('?');
  4553. if (j > 0) {
  4554. filename = filename.slice(0, j);
  4555. }
  4556. j = filename.lastIndexOf('/');
  4557. if (j < 0) {
  4558. j = filename.lastIndexOf('\\');
  4559. }
  4560. if (j < 0) {
  4561. return '';
  4562. }
  4563. return filename.slice(0, j + 1);
  4564. };
  4565. AbstractFileManager.prototype.tryAppendExtension = function (path, ext) {
  4566. return /(\.[a-z]*$)|([\?;].*)$/.test(path) ? path : path + ext;
  4567. };
  4568. AbstractFileManager.prototype.tryAppendLessExtension = function (path) {
  4569. return this.tryAppendExtension(path, '.less');
  4570. };
  4571. AbstractFileManager.prototype.supportsSync = function () { return false; };
  4572. AbstractFileManager.prototype.alwaysMakePathsAbsolute = function () { return false; };
  4573. AbstractFileManager.prototype.isPathAbsolute = function (filename) {
  4574. return (/^(?:[a-z-]+:|\/|\\|#)/i).test(filename);
  4575. };
  4576. // TODO: pull out / replace?
  4577. AbstractFileManager.prototype.join = function (basePath, laterPath) {
  4578. if (!basePath) {
  4579. return laterPath;
  4580. }
  4581. return basePath + laterPath;
  4582. };
  4583. AbstractFileManager.prototype.pathDiff = function (url, baseUrl) {
  4584. // diff between two paths to create a relative path
  4585. var urlParts = this.extractUrlParts(url);
  4586. var baseUrlParts = this.extractUrlParts(baseUrl);
  4587. var i;
  4588. var max;
  4589. var urlDirectories;
  4590. var baseUrlDirectories;
  4591. var diff = '';
  4592. if (urlParts.hostPart !== baseUrlParts.hostPart) {
  4593. return '';
  4594. }
  4595. max = Math.max(baseUrlParts.directories.length, urlParts.directories.length);
  4596. for (i = 0; i < max; i++) {
  4597. if (baseUrlParts.directories[i] !== urlParts.directories[i]) {
  4598. break;
  4599. }
  4600. }
  4601. baseUrlDirectories = baseUrlParts.directories.slice(i);
  4602. urlDirectories = urlParts.directories.slice(i);
  4603. for (i = 0; i < baseUrlDirectories.length - 1; i++) {
  4604. diff += '../';
  4605. }
  4606. for (i = 0; i < urlDirectories.length - 1; i++) {
  4607. diff += urlDirectories[i] + "/";
  4608. }
  4609. return diff;
  4610. };
  4611. // helper function, not part of API
  4612. AbstractFileManager.prototype.extractUrlParts = function (url, baseUrl) {
  4613. // urlParts[1] = protocol://hostname/ OR /
  4614. // urlParts[2] = / if path relative to host base
  4615. // urlParts[3] = directories
  4616. // urlParts[4] = filename
  4617. // urlParts[5] = parameters
  4618. var urlPartsRegex = /^((?:[a-z-]+:)?\/{2}(?:[^\/\?#]*\/)|([\/\\]))?((?:[^\/\\\?#]*[\/\\])*)([^\/\\\?#]*)([#\?].*)?$/i;
  4619. var urlParts = url.match(urlPartsRegex);
  4620. var returner = {};
  4621. var rawDirectories = [];
  4622. var directories = [];
  4623. var i;
  4624. var baseUrlParts;
  4625. if (!urlParts) {
  4626. throw new Error("Could not parse sheet href - '" + url + "'");
  4627. }
  4628. // Stylesheets in IE don't always return the full path
  4629. if (baseUrl && (!urlParts[1] || urlParts[2])) {
  4630. baseUrlParts = baseUrl.match(urlPartsRegex);
  4631. if (!baseUrlParts) {
  4632. throw new Error("Could not parse page url - '" + baseUrl + "'");
  4633. }
  4634. urlParts[1] = urlParts[1] || baseUrlParts[1] || '';
  4635. if (!urlParts[2]) {
  4636. urlParts[3] = baseUrlParts[3] + urlParts[3];
  4637. }
  4638. }
  4639. if (urlParts[3]) {
  4640. rawDirectories = urlParts[3].replace(/\\/g, '/').split('/');
  4641. // collapse '..' and skip '.'
  4642. for (i = 0; i < rawDirectories.length; i++) {
  4643. if (rawDirectories[i] === '..') {
  4644. directories.pop();
  4645. }
  4646. else if (rawDirectories[i] !== '.') {
  4647. directories.push(rawDirectories[i]);
  4648. }
  4649. }
  4650. }
  4651. returner.hostPart = urlParts[1];
  4652. returner.directories = directories;
  4653. returner.rawPath = (urlParts[1] || '') + rawDirectories.join('/');
  4654. returner.path = (urlParts[1] || '') + directories.join('/');
  4655. returner.filename = urlParts[4];
  4656. returner.fileUrl = returner.path + (urlParts[4] || '');
  4657. returner.url = returner.fileUrl + (urlParts[5] || '');
  4658. return returner;
  4659. };
  4660. return AbstractFileManager;
  4661. }());
  4662. var AbstractPluginLoader = /** @class */ (function () {
  4663. function AbstractPluginLoader() {
  4664. // Implemented by Node.js plugin loader
  4665. this.require = function () { return null; };
  4666. }
  4667. AbstractPluginLoader.prototype.evalPlugin = function (contents, context, imports, pluginOptions, fileInfo) {
  4668. var loader;
  4669. var registry;
  4670. var pluginObj;
  4671. var localModule;
  4672. var pluginManager;
  4673. var filename;
  4674. var result;
  4675. pluginManager = context.pluginManager;
  4676. if (fileInfo) {
  4677. if (typeof fileInfo === 'string') {
  4678. filename = fileInfo;
  4679. }
  4680. else {
  4681. filename = fileInfo.filename;
  4682. }
  4683. }
  4684. var shortname = (new this.less.FileManager()).extractUrlParts(filename).filename;
  4685. if (filename) {
  4686. pluginObj = pluginManager.get(filename);
  4687. if (pluginObj) {
  4688. result = this.trySetOptions(pluginObj, filename, shortname, pluginOptions);
  4689. if (result) {
  4690. return result;
  4691. }
  4692. try {
  4693. if (pluginObj.use) {
  4694. pluginObj.use.call(this.context, pluginObj);
  4695. }
  4696. }
  4697. catch (e) {
  4698. e.message = e.message || 'Error during @plugin call';
  4699. return new LessError(e, imports, filename);
  4700. }
  4701. return pluginObj;
  4702. }
  4703. }
  4704. localModule = {
  4705. exports: {},
  4706. pluginManager: pluginManager,
  4707. fileInfo: fileInfo
  4708. };
  4709. registry = functionRegistry.create();
  4710. var registerPlugin = function (obj) {
  4711. pluginObj = obj;
  4712. };
  4713. try {
  4714. loader = new Function('module', 'require', 'registerPlugin', 'functions', 'tree', 'less', 'fileInfo', contents);
  4715. loader(localModule, this.require(filename), registerPlugin, registry, this.less.tree, this.less, fileInfo);
  4716. }
  4717. catch (e) {
  4718. return new LessError(e, imports, filename);
  4719. }
  4720. if (!pluginObj) {
  4721. pluginObj = localModule.exports;
  4722. }
  4723. pluginObj = this.validatePlugin(pluginObj, filename, shortname);
  4724. if (pluginObj instanceof LessError) {
  4725. return pluginObj;
  4726. }
  4727. if (pluginObj) {
  4728. pluginObj.imports = imports;
  4729. pluginObj.filename = filename;
  4730. // For < 3.x (or unspecified minVersion) - setOptions() before install()
  4731. if (!pluginObj.minVersion || this.compareVersion('3.0.0', pluginObj.minVersion) < 0) {
  4732. result = this.trySetOptions(pluginObj, filename, shortname, pluginOptions);
  4733. if (result) {
  4734. return result;
  4735. }
  4736. }
  4737. // Run on first load
  4738. pluginManager.addPlugin(pluginObj, fileInfo.filename, registry);
  4739. pluginObj.functions = registry.getLocalFunctions();
  4740. // Need to call setOptions again because the pluginObj might have functions
  4741. result = this.trySetOptions(pluginObj, filename, shortname, pluginOptions);
  4742. if (result) {
  4743. return result;
  4744. }
  4745. // Run every @plugin call
  4746. try {
  4747. if (pluginObj.use) {
  4748. pluginObj.use.call(this.context, pluginObj);
  4749. }
  4750. }
  4751. catch (e) {
  4752. e.message = e.message || 'Error during @plugin call';
  4753. return new LessError(e, imports, filename);
  4754. }
  4755. }
  4756. else {
  4757. return new LessError({ message: 'Not a valid plugin' }, imports, filename);
  4758. }
  4759. return pluginObj;
  4760. };
  4761. AbstractPluginLoader.prototype.trySetOptions = function (plugin, filename, name, options) {
  4762. if (options && !plugin.setOptions) {
  4763. return new LessError({
  4764. message: "Options have been provided but the plugin " + name + " does not support any options."
  4765. });
  4766. }
  4767. try {
  4768. plugin.setOptions && plugin.setOptions(options);
  4769. }
  4770. catch (e) {
  4771. return new LessError(e);
  4772. }
  4773. };
  4774. AbstractPluginLoader.prototype.validatePlugin = function (plugin, filename, name) {
  4775. if (plugin) {
  4776. // support plugins being a function
  4777. // so that the plugin can be more usable programmatically
  4778. if (typeof plugin === 'function') {
  4779. plugin = new plugin();
  4780. }
  4781. if (plugin.minVersion) {
  4782. if (this.compareVersion(plugin.minVersion, this.less.version) < 0) {
  4783. return new LessError({
  4784. message: "Plugin " + name + " requires version " + this.versionToString(plugin.minVersion)
  4785. });
  4786. }
  4787. }
  4788. return plugin;
  4789. }
  4790. return null;
  4791. };
  4792. AbstractPluginLoader.prototype.compareVersion = function (aVersion, bVersion) {
  4793. if (typeof aVersion === 'string') {
  4794. aVersion = aVersion.match(/^(\d+)\.?(\d+)?\.?(\d+)?/);
  4795. aVersion.shift();
  4796. }
  4797. for (var i = 0; i < aVersion.length; i++) {
  4798. if (aVersion[i] !== bVersion[i]) {
  4799. return parseInt(aVersion[i]) > parseInt(bVersion[i]) ? -1 : 1;
  4800. }
  4801. }
  4802. return 0;
  4803. };
  4804. AbstractPluginLoader.prototype.versionToString = function (version) {
  4805. var versionString = '';
  4806. for (var i = 0; i < version.length; i++) {
  4807. versionString += (versionString ? '.' : '') + version[i];
  4808. }
  4809. return versionString;
  4810. };
  4811. AbstractPluginLoader.prototype.printUsage = function (plugins) {
  4812. for (var i = 0; i < plugins.length; i++) {
  4813. var plugin = plugins[i];
  4814. if (plugin.printUsage) {
  4815. plugin.printUsage();
  4816. }
  4817. }
  4818. };
  4819. return AbstractPluginLoader;
  4820. }());
  4821. var _visitArgs = { visitDeeper: true };
  4822. var _hasIndexed = false;
  4823. function _noop(node) {
  4824. return node;
  4825. }
  4826. function indexNodeTypes(parent, ticker) {
  4827. // add .typeIndex to tree node types for lookup table
  4828. var key;
  4829. var child;
  4830. for (key in parent) {
  4831. /* eslint guard-for-in: 0 */
  4832. child = parent[key];
  4833. switch (typeof child) {
  4834. case 'function':
  4835. // ignore bound functions directly on tree which do not have a prototype
  4836. // or aren't nodes
  4837. if (child.prototype && child.prototype.type) {
  4838. child.prototype.typeIndex = ticker++;
  4839. }
  4840. break;
  4841. case 'object':
  4842. ticker = indexNodeTypes(child, ticker);
  4843. break;
  4844. }
  4845. }
  4846. return ticker;
  4847. }
  4848. var Visitor = /** @class */ (function () {
  4849. function Visitor(implementation) {
  4850. this._implementation = implementation;
  4851. this._visitInCache = {};
  4852. this._visitOutCache = {};
  4853. if (!_hasIndexed) {
  4854. indexNodeTypes(tree, 1);
  4855. _hasIndexed = true;
  4856. }
  4857. }
  4858. Visitor.prototype.visit = function (node) {
  4859. if (!node) {
  4860. return node;
  4861. }
  4862. var nodeTypeIndex = node.typeIndex;
  4863. if (!nodeTypeIndex) {
  4864. // MixinCall args aren't a node type?
  4865. if (node.value && node.value.typeIndex) {
  4866. this.visit(node.value);
  4867. }
  4868. return node;
  4869. }
  4870. var impl = this._implementation;
  4871. var func = this._visitInCache[nodeTypeIndex];
  4872. var funcOut = this._visitOutCache[nodeTypeIndex];
  4873. var visitArgs = _visitArgs;
  4874. var fnName;
  4875. visitArgs.visitDeeper = true;
  4876. if (!func) {
  4877. fnName = "visit" + node.type;
  4878. func = impl[fnName] || _noop;
  4879. funcOut = impl[fnName + "Out"] || _noop;
  4880. this._visitInCache[nodeTypeIndex] = func;
  4881. this._visitOutCache[nodeTypeIndex] = funcOut;
  4882. }
  4883. if (func !== _noop) {
  4884. var newNode = func.call(impl, node, visitArgs);
  4885. if (node && impl.isReplacing) {
  4886. node = newNode;
  4887. }
  4888. }
  4889. if (visitArgs.visitDeeper && node) {
  4890. if (node.length) {
  4891. for (var i = 0, cnt = node.length; i < cnt; i++) {
  4892. if (node[i].accept) {
  4893. node[i].accept(this);
  4894. }
  4895. }
  4896. }
  4897. else if (node.accept) {
  4898. node.accept(this);
  4899. }
  4900. }
  4901. if (funcOut != _noop) {
  4902. funcOut.call(impl, node);
  4903. }
  4904. return node;
  4905. };
  4906. Visitor.prototype.visitArray = function (nodes, nonReplacing) {
  4907. if (!nodes) {
  4908. return nodes;
  4909. }
  4910. var cnt = nodes.length;
  4911. var i;
  4912. // Non-replacing
  4913. if (nonReplacing || !this._implementation.isReplacing) {
  4914. for (i = 0; i < cnt; i++) {
  4915. this.visit(nodes[i]);
  4916. }
  4917. return nodes;
  4918. }
  4919. // Replacing
  4920. var out = [];
  4921. for (i = 0; i < cnt; i++) {
  4922. var evald = this.visit(nodes[i]);
  4923. if (evald === undefined) {
  4924. continue;
  4925. }
  4926. if (!evald.splice) {
  4927. out.push(evald);
  4928. }
  4929. else if (evald.length) {
  4930. this.flatten(evald, out);
  4931. }
  4932. }
  4933. return out;
  4934. };
  4935. Visitor.prototype.flatten = function (arr, out) {
  4936. if (!out) {
  4937. out = [];
  4938. }
  4939. var cnt;
  4940. var i;
  4941. var item;
  4942. var nestedCnt;
  4943. var j;
  4944. var nestedItem;
  4945. for (i = 0, cnt = arr.length; i < cnt; i++) {
  4946. item = arr[i];
  4947. if (item === undefined) {
  4948. continue;
  4949. }
  4950. if (!item.splice) {
  4951. out.push(item);
  4952. continue;
  4953. }
  4954. for (j = 0, nestedCnt = item.length; j < nestedCnt; j++) {
  4955. nestedItem = item[j];
  4956. if (nestedItem === undefined) {
  4957. continue;
  4958. }
  4959. if (!nestedItem.splice) {
  4960. out.push(nestedItem);
  4961. }
  4962. else if (nestedItem.length) {
  4963. this.flatten(nestedItem, out);
  4964. }
  4965. }
  4966. }
  4967. return out;
  4968. };
  4969. return Visitor;
  4970. }());
  4971. var ImportSequencer = /** @class */ (function () {
  4972. function ImportSequencer(onSequencerEmpty) {
  4973. this.imports = [];
  4974. this.variableImports = [];
  4975. this._onSequencerEmpty = onSequencerEmpty;
  4976. this._currentDepth = 0;
  4977. }
  4978. ImportSequencer.prototype.addImport = function (callback) {
  4979. var importSequencer = this;
  4980. var importItem = {
  4981. callback: callback,
  4982. args: null,
  4983. isReady: false
  4984. };
  4985. this.imports.push(importItem);
  4986. return function () {
  4987. var args = [];
  4988. for (var _i = 0; _i < arguments.length; _i++) {
  4989. args[_i] = arguments[_i];
  4990. }
  4991. importItem.args = Array.prototype.slice.call(args, 0);
  4992. importItem.isReady = true;
  4993. importSequencer.tryRun();
  4994. };
  4995. };
  4996. ImportSequencer.prototype.addVariableImport = function (callback) {
  4997. this.variableImports.push(callback);
  4998. };
  4999. ImportSequencer.prototype.tryRun = function () {
  5000. this._currentDepth++;
  5001. try {
  5002. while (true) {
  5003. while (this.imports.length > 0) {
  5004. var importItem = this.imports[0];
  5005. if (!importItem.isReady) {
  5006. return;
  5007. }
  5008. this.imports = this.imports.slice(1);
  5009. importItem.callback.apply(null, importItem.args);
  5010. }
  5011. if (this.variableImports.length === 0) {
  5012. break;
  5013. }
  5014. var variableImport = this.variableImports[0];
  5015. this.variableImports = this.variableImports.slice(1);
  5016. variableImport();
  5017. }
  5018. }
  5019. finally {
  5020. this._currentDepth--;
  5021. }
  5022. if (this._currentDepth === 0 && this._onSequencerEmpty) {
  5023. this._onSequencerEmpty();
  5024. }
  5025. };
  5026. return ImportSequencer;
  5027. }());
  5028. var ImportVisitor = function (importer, finish) {
  5029. this._visitor = new Visitor(this);
  5030. this._importer = importer;
  5031. this._finish = finish;
  5032. this.context = new contexts.Eval();
  5033. this.importCount = 0;
  5034. this.onceFileDetectionMap = {};
  5035. this.recursionDetector = {};
  5036. this._sequencer = new ImportSequencer(this._onSequencerEmpty.bind(this));
  5037. };
  5038. ImportVisitor.prototype = {
  5039. isReplacing: false,
  5040. run: function (root) {
  5041. try {
  5042. // process the contents
  5043. this._visitor.visit(root);
  5044. }
  5045. catch (e) {
  5046. this.error = e;
  5047. }
  5048. this.isFinished = true;
  5049. this._sequencer.tryRun();
  5050. },
  5051. _onSequencerEmpty: function () {
  5052. if (!this.isFinished) {
  5053. return;
  5054. }
  5055. this._finish(this.error);
  5056. },
  5057. visitImport: function (importNode, visitArgs) {
  5058. var inlineCSS = importNode.options.inline;
  5059. if (!importNode.css || inlineCSS) {
  5060. var context = new contexts.Eval(this.context, copyArray(this.context.frames));
  5061. var importParent = context.frames[0];
  5062. this.importCount++;
  5063. if (importNode.isVariableImport()) {
  5064. this._sequencer.addVariableImport(this.processImportNode.bind(this, importNode, context, importParent));
  5065. }
  5066. else {
  5067. this.processImportNode(importNode, context, importParent);
  5068. }
  5069. }
  5070. visitArgs.visitDeeper = false;
  5071. },
  5072. processImportNode: function (importNode, context, importParent) {
  5073. var evaldImportNode;
  5074. var inlineCSS = importNode.options.inline;
  5075. try {
  5076. evaldImportNode = importNode.evalForImport(context);
  5077. }
  5078. catch (e) {
  5079. if (!e.filename) {
  5080. e.index = importNode.getIndex();
  5081. e.filename = importNode.fileInfo().filename;
  5082. }
  5083. // attempt to eval properly and treat as css
  5084. importNode.css = true;
  5085. // if that fails, this error will be thrown
  5086. importNode.error = e;
  5087. }
  5088. if (evaldImportNode && (!evaldImportNode.css || inlineCSS)) {
  5089. if (evaldImportNode.options.multiple) {
  5090. context.importMultiple = true;
  5091. }
  5092. // try appending if we haven't determined if it is css or not
  5093. var tryAppendLessExtension = evaldImportNode.css === undefined;
  5094. for (var i = 0; i < importParent.rules.length; i++) {
  5095. if (importParent.rules[i] === importNode) {
  5096. importParent.rules[i] = evaldImportNode;
  5097. break;
  5098. }
  5099. }
  5100. var onImported = this.onImported.bind(this, evaldImportNode, context);
  5101. var sequencedOnImported = this._sequencer.addImport(onImported);
  5102. this._importer.push(evaldImportNode.getPath(), tryAppendLessExtension, evaldImportNode.fileInfo(), evaldImportNode.options, sequencedOnImported);
  5103. }
  5104. else {
  5105. this.importCount--;
  5106. if (this.isFinished) {
  5107. this._sequencer.tryRun();
  5108. }
  5109. }
  5110. },
  5111. onImported: function (importNode, context, e, root, importedAtRoot, fullPath) {
  5112. if (e) {
  5113. if (!e.filename) {
  5114. e.index = importNode.getIndex();
  5115. e.filename = importNode.fileInfo().filename;
  5116. }
  5117. this.error = e;
  5118. }
  5119. var importVisitor = this;
  5120. var inlineCSS = importNode.options.inline;
  5121. var isPlugin = importNode.options.isPlugin;
  5122. var isOptional = importNode.options.optional;
  5123. var duplicateImport = importedAtRoot || fullPath in importVisitor.recursionDetector;
  5124. if (!context.importMultiple) {
  5125. if (duplicateImport) {
  5126. importNode.skip = true;
  5127. }
  5128. else {
  5129. importNode.skip = function () {
  5130. if (fullPath in importVisitor.onceFileDetectionMap) {
  5131. return true;
  5132. }
  5133. importVisitor.onceFileDetectionMap[fullPath] = true;
  5134. return false;
  5135. };
  5136. }
  5137. }
  5138. if (!fullPath && isOptional) {
  5139. importNode.skip = true;
  5140. }
  5141. if (root) {
  5142. importNode.root = root;
  5143. importNode.importedFilename = fullPath;
  5144. if (!inlineCSS && !isPlugin && (context.importMultiple || !duplicateImport)) {
  5145. importVisitor.recursionDetector[fullPath] = true;
  5146. var oldContext = this.context;
  5147. this.context = context;
  5148. try {
  5149. this._visitor.visit(root);
  5150. }
  5151. catch (e) {
  5152. this.error = e;
  5153. }
  5154. this.context = oldContext;
  5155. }
  5156. }
  5157. importVisitor.importCount--;
  5158. if (importVisitor.isFinished) {
  5159. importVisitor._sequencer.tryRun();
  5160. }
  5161. },
  5162. visitDeclaration: function (declNode, visitArgs) {
  5163. if (declNode.value.type === 'DetachedRuleset') {
  5164. this.context.frames.unshift(declNode);
  5165. }
  5166. else {
  5167. visitArgs.visitDeeper = false;
  5168. }
  5169. },
  5170. visitDeclarationOut: function (declNode) {
  5171. if (declNode.value.type === 'DetachedRuleset') {
  5172. this.context.frames.shift();
  5173. }
  5174. },
  5175. visitAtRule: function (atRuleNode, visitArgs) {
  5176. this.context.frames.unshift(atRuleNode);
  5177. },
  5178. visitAtRuleOut: function (atRuleNode) {
  5179. this.context.frames.shift();
  5180. },
  5181. visitMixinDefinition: function (mixinDefinitionNode, visitArgs) {
  5182. this.context.frames.unshift(mixinDefinitionNode);
  5183. },
  5184. visitMixinDefinitionOut: function (mixinDefinitionNode) {
  5185. this.context.frames.shift();
  5186. },
  5187. visitRuleset: function (rulesetNode, visitArgs) {
  5188. this.context.frames.unshift(rulesetNode);
  5189. },
  5190. visitRulesetOut: function (rulesetNode) {
  5191. this.context.frames.shift();
  5192. },
  5193. visitMedia: function (mediaNode, visitArgs) {
  5194. this.context.frames.unshift(mediaNode.rules[0]);
  5195. },
  5196. visitMediaOut: function (mediaNode) {
  5197. this.context.frames.shift();
  5198. }
  5199. };
  5200. var SetTreeVisibilityVisitor = /** @class */ (function () {
  5201. function SetTreeVisibilityVisitor(visible) {
  5202. this.visible = visible;
  5203. }
  5204. SetTreeVisibilityVisitor.prototype.run = function (root) {
  5205. this.visit(root);
  5206. };
  5207. SetTreeVisibilityVisitor.prototype.visitArray = function (nodes) {
  5208. if (!nodes) {
  5209. return nodes;
  5210. }
  5211. var cnt = nodes.length;
  5212. var i;
  5213. for (i = 0; i < cnt; i++) {
  5214. this.visit(nodes[i]);
  5215. }
  5216. return nodes;
  5217. };
  5218. SetTreeVisibilityVisitor.prototype.visit = function (node) {
  5219. if (!node) {
  5220. return node;
  5221. }
  5222. if (node.constructor === Array) {
  5223. return this.visitArray(node);
  5224. }
  5225. if (!node.blocksVisibility || node.blocksVisibility()) {
  5226. return node;
  5227. }
  5228. if (this.visible) {
  5229. node.ensureVisibility();
  5230. }
  5231. else {
  5232. node.ensureInvisibility();
  5233. }
  5234. node.accept(this);
  5235. return node;
  5236. };
  5237. return SetTreeVisibilityVisitor;
  5238. }());
  5239. /* jshint loopfunc:true */
  5240. var ExtendFinderVisitor = /** @class */ (function () {
  5241. function ExtendFinderVisitor() {
  5242. this._visitor = new Visitor(this);
  5243. this.contexts = [];
  5244. this.allExtendsStack = [[]];
  5245. }
  5246. ExtendFinderVisitor.prototype.run = function (root) {
  5247. root = this._visitor.visit(root);
  5248. root.allExtends = this.allExtendsStack[0];
  5249. return root;
  5250. };
  5251. ExtendFinderVisitor.prototype.visitDeclaration = function (declNode, visitArgs) {
  5252. visitArgs.visitDeeper = false;
  5253. };
  5254. ExtendFinderVisitor.prototype.visitMixinDefinition = function (mixinDefinitionNode, visitArgs) {
  5255. visitArgs.visitDeeper = false;
  5256. };
  5257. ExtendFinderVisitor.prototype.visitRuleset = function (rulesetNode, visitArgs) {
  5258. if (rulesetNode.root) {
  5259. return;
  5260. }
  5261. var i;
  5262. var j;
  5263. var extend;
  5264. var allSelectorsExtendList = [];
  5265. var extendList;
  5266. // get &:extend(.a); rules which apply to all selectors in this ruleset
  5267. var rules = rulesetNode.rules;
  5268. var ruleCnt = rules ? rules.length : 0;
  5269. for (i = 0; i < ruleCnt; i++) {
  5270. if (rulesetNode.rules[i] instanceof tree.Extend) {
  5271. allSelectorsExtendList.push(rules[i]);
  5272. rulesetNode.extendOnEveryPath = true;
  5273. }
  5274. }
  5275. // now find every selector and apply the extends that apply to all extends
  5276. // and the ones which apply to an individual extend
  5277. var paths = rulesetNode.paths;
  5278. for (i = 0; i < paths.length; i++) {
  5279. var selectorPath = paths[i];
  5280. var selector = selectorPath[selectorPath.length - 1];
  5281. var selExtendList = selector.extendList;
  5282. extendList = selExtendList ? copyArray(selExtendList).concat(allSelectorsExtendList)
  5283. : allSelectorsExtendList;
  5284. if (extendList) {
  5285. extendList = extendList.map(function (allSelectorsExtend) { return allSelectorsExtend.clone(); });
  5286. }
  5287. for (j = 0; j < extendList.length; j++) {
  5288. this.foundExtends = true;
  5289. extend = extendList[j];
  5290. extend.findSelfSelectors(selectorPath);
  5291. extend.ruleset = rulesetNode;
  5292. if (j === 0) {
  5293. extend.firstExtendOnThisSelectorPath = true;
  5294. }
  5295. this.allExtendsStack[this.allExtendsStack.length - 1].push(extend);
  5296. }
  5297. }
  5298. this.contexts.push(rulesetNode.selectors);
  5299. };
  5300. ExtendFinderVisitor.prototype.visitRulesetOut = function (rulesetNode) {
  5301. if (!rulesetNode.root) {
  5302. this.contexts.length = this.contexts.length - 1;
  5303. }
  5304. };
  5305. ExtendFinderVisitor.prototype.visitMedia = function (mediaNode, visitArgs) {
  5306. mediaNode.allExtends = [];
  5307. this.allExtendsStack.push(mediaNode.allExtends);
  5308. };
  5309. ExtendFinderVisitor.prototype.visitMediaOut = function (mediaNode) {
  5310. this.allExtendsStack.length = this.allExtendsStack.length - 1;
  5311. };
  5312. ExtendFinderVisitor.prototype.visitAtRule = function (atRuleNode, visitArgs) {
  5313. atRuleNode.allExtends = [];
  5314. this.allExtendsStack.push(atRuleNode.allExtends);
  5315. };
  5316. ExtendFinderVisitor.prototype.visitAtRuleOut = function (atRuleNode) {
  5317. this.allExtendsStack.length = this.allExtendsStack.length - 1;
  5318. };
  5319. return ExtendFinderVisitor;
  5320. }());
  5321. var ProcessExtendsVisitor = /** @class */ (function () {
  5322. function ProcessExtendsVisitor() {
  5323. this._visitor = new Visitor(this);
  5324. }
  5325. ProcessExtendsVisitor.prototype.run = function (root) {
  5326. var extendFinder = new ExtendFinderVisitor();
  5327. this.extendIndices = {};
  5328. extendFinder.run(root);
  5329. if (!extendFinder.foundExtends) {
  5330. return root;
  5331. }
  5332. root.allExtends = root.allExtends.concat(this.doExtendChaining(root.allExtends, root.allExtends));
  5333. this.allExtendsStack = [root.allExtends];
  5334. var newRoot = this._visitor.visit(root);
  5335. this.checkExtendsForNonMatched(root.allExtends);
  5336. return newRoot;
  5337. };
  5338. ProcessExtendsVisitor.prototype.checkExtendsForNonMatched = function (extendList) {
  5339. var indices = this.extendIndices;
  5340. extendList.filter(function (extend) { return !extend.hasFoundMatches && extend.parent_ids.length == 1; }).forEach(function (extend) {
  5341. var selector = '_unknown_';
  5342. try {
  5343. selector = extend.selector.toCSS({});
  5344. }
  5345. catch (_) { }
  5346. if (!indices[extend.index + " " + selector]) {
  5347. indices[extend.index + " " + selector] = true;
  5348. logger.warn("extend '" + selector + "' has no matches");
  5349. }
  5350. });
  5351. };
  5352. ProcessExtendsVisitor.prototype.doExtendChaining = function (extendsList, extendsListTarget, iterationCount) {
  5353. //
  5354. // chaining is different from normal extension.. if we extend an extend then we are not just copying, altering
  5355. // and pasting the selector we would do normally, but we are also adding an extend with the same target selector
  5356. // this means this new extend can then go and alter other extends
  5357. //
  5358. // this method deals with all the chaining work - without it, extend is flat and doesn't work on other extend selectors
  5359. // this is also the most expensive.. and a match on one selector can cause an extension of a selector we had already
  5360. // processed if we look at each selector at a time, as is done in visitRuleset
  5361. var extendIndex;
  5362. var targetExtendIndex;
  5363. var matches;
  5364. var extendsToAdd = [];
  5365. var newSelector;
  5366. var extendVisitor = this;
  5367. var selectorPath;
  5368. var extend;
  5369. var targetExtend;
  5370. var newExtend;
  5371. iterationCount = iterationCount || 0;
  5372. // loop through comparing every extend with every target extend.
  5373. // a target extend is the one on the ruleset we are looking at copy/edit/pasting in place
  5374. // e.g. .a:extend(.b) {} and .b:extend(.c) {} then the first extend extends the second one
  5375. // and the second is the target.
  5376. // the separation into two lists allows us to process a subset of chains with a bigger set, as is the
  5377. // case when processing media queries
  5378. for (extendIndex = 0; extendIndex < extendsList.length; extendIndex++) {
  5379. for (targetExtendIndex = 0; targetExtendIndex < extendsListTarget.length; targetExtendIndex++) {
  5380. extend = extendsList[extendIndex];
  5381. targetExtend = extendsListTarget[targetExtendIndex];
  5382. // look for circular references
  5383. if (extend.parent_ids.indexOf(targetExtend.object_id) >= 0) {
  5384. continue;
  5385. }
  5386. // find a match in the target extends self selector (the bit before :extend)
  5387. selectorPath = [targetExtend.selfSelectors[0]];
  5388. matches = extendVisitor.findMatch(extend, selectorPath);
  5389. if (matches.length) {
  5390. extend.hasFoundMatches = true;
  5391. // we found a match, so for each self selector..
  5392. extend.selfSelectors.forEach(function (selfSelector) {
  5393. var info = targetExtend.visibilityInfo();
  5394. // process the extend as usual
  5395. newSelector = extendVisitor.extendSelector(matches, selectorPath, selfSelector, extend.isVisible());
  5396. // but now we create a new extend from it
  5397. newExtend = new (tree.Extend)(targetExtend.selector, targetExtend.option, 0, targetExtend.fileInfo(), info);
  5398. newExtend.selfSelectors = newSelector;
  5399. // add the extend onto the list of extends for that selector
  5400. newSelector[newSelector.length - 1].extendList = [newExtend];
  5401. // record that we need to add it.
  5402. extendsToAdd.push(newExtend);
  5403. newExtend.ruleset = targetExtend.ruleset;
  5404. // remember its parents for circular references
  5405. newExtend.parent_ids = newExtend.parent_ids.concat(targetExtend.parent_ids, extend.parent_ids);
  5406. // only process the selector once.. if we have :extend(.a,.b) then multiple
  5407. // extends will look at the same selector path, so when extending
  5408. // we know that any others will be duplicates in terms of what is added to the css
  5409. if (targetExtend.firstExtendOnThisSelectorPath) {
  5410. newExtend.firstExtendOnThisSelectorPath = true;
  5411. targetExtend.ruleset.paths.push(newSelector);
  5412. }
  5413. });
  5414. }
  5415. }
  5416. }
  5417. if (extendsToAdd.length) {
  5418. // try to detect circular references to stop a stack overflow.
  5419. // may no longer be needed.
  5420. this.extendChainCount++;
  5421. if (iterationCount > 100) {
  5422. var selectorOne = '{unable to calculate}';
  5423. var selectorTwo = '{unable to calculate}';
  5424. try {
  5425. selectorOne = extendsToAdd[0].selfSelectors[0].toCSS();
  5426. selectorTwo = extendsToAdd[0].selector.toCSS();
  5427. }
  5428. catch (e) { }
  5429. throw { message: "extend circular reference detected. One of the circular extends is currently:" + selectorOne + ":extend(" + selectorTwo + ")" };
  5430. }
  5431. // now process the new extends on the existing rules so that we can handle a extending b extending c extending
  5432. // d extending e...
  5433. return extendsToAdd.concat(extendVisitor.doExtendChaining(extendsToAdd, extendsListTarget, iterationCount + 1));
  5434. }
  5435. else {
  5436. return extendsToAdd;
  5437. }
  5438. };
  5439. ProcessExtendsVisitor.prototype.visitDeclaration = function (ruleNode, visitArgs) {
  5440. visitArgs.visitDeeper = false;
  5441. };
  5442. ProcessExtendsVisitor.prototype.visitMixinDefinition = function (mixinDefinitionNode, visitArgs) {
  5443. visitArgs.visitDeeper = false;
  5444. };
  5445. ProcessExtendsVisitor.prototype.visitSelector = function (selectorNode, visitArgs) {
  5446. visitArgs.visitDeeper = false;
  5447. };
  5448. ProcessExtendsVisitor.prototype.visitRuleset = function (rulesetNode, visitArgs) {
  5449. if (rulesetNode.root) {
  5450. return;
  5451. }
  5452. var matches;
  5453. var pathIndex;
  5454. var extendIndex;
  5455. var allExtends = this.allExtendsStack[this.allExtendsStack.length - 1];
  5456. var selectorsToAdd = [];
  5457. var extendVisitor = this;
  5458. var selectorPath;
  5459. // look at each selector path in the ruleset, find any extend matches and then copy, find and replace
  5460. for (extendIndex = 0; extendIndex < allExtends.length; extendIndex++) {
  5461. for (pathIndex = 0; pathIndex < rulesetNode.paths.length; pathIndex++) {
  5462. selectorPath = rulesetNode.paths[pathIndex];
  5463. // extending extends happens initially, before the main pass
  5464. if (rulesetNode.extendOnEveryPath) {
  5465. continue;
  5466. }
  5467. var extendList = selectorPath[selectorPath.length - 1].extendList;
  5468. if (extendList && extendList.length) {
  5469. continue;
  5470. }
  5471. matches = this.findMatch(allExtends[extendIndex], selectorPath);
  5472. if (matches.length) {
  5473. allExtends[extendIndex].hasFoundMatches = true;
  5474. allExtends[extendIndex].selfSelectors.forEach(function (selfSelector) {
  5475. var extendedSelectors;
  5476. extendedSelectors = extendVisitor.extendSelector(matches, selectorPath, selfSelector, allExtends[extendIndex].isVisible());
  5477. selectorsToAdd.push(extendedSelectors);
  5478. });
  5479. }
  5480. }
  5481. }
  5482. rulesetNode.paths = rulesetNode.paths.concat(selectorsToAdd);
  5483. };
  5484. ProcessExtendsVisitor.prototype.findMatch = function (extend, haystackSelectorPath) {
  5485. //
  5486. // look through the haystack selector path to try and find the needle - extend.selector
  5487. // returns an array of selector matches that can then be replaced
  5488. //
  5489. var haystackSelectorIndex;
  5490. var hackstackSelector;
  5491. var hackstackElementIndex;
  5492. var haystackElement;
  5493. var targetCombinator;
  5494. var i;
  5495. var extendVisitor = this;
  5496. var needleElements = extend.selector.elements;
  5497. var potentialMatches = [];
  5498. var potentialMatch;
  5499. var matches = [];
  5500. // loop through the haystack elements
  5501. for (haystackSelectorIndex = 0; haystackSelectorIndex < haystackSelectorPath.length; haystackSelectorIndex++) {
  5502. hackstackSelector = haystackSelectorPath[haystackSelectorIndex];
  5503. for (hackstackElementIndex = 0; hackstackElementIndex < hackstackSelector.elements.length; hackstackElementIndex++) {
  5504. haystackElement = hackstackSelector.elements[hackstackElementIndex];
  5505. // if we allow elements before our match we can add a potential match every time. otherwise only at the first element.
  5506. if (extend.allowBefore || (haystackSelectorIndex === 0 && hackstackElementIndex === 0)) {
  5507. potentialMatches.push({ pathIndex: haystackSelectorIndex, index: hackstackElementIndex, matched: 0,
  5508. initialCombinator: haystackElement.combinator });
  5509. }
  5510. for (i = 0; i < potentialMatches.length; i++) {
  5511. potentialMatch = potentialMatches[i];
  5512. // selectors add " " onto the first element. When we use & it joins the selectors together, but if we don't
  5513. // then each selector in haystackSelectorPath has a space before it added in the toCSS phase. so we need to
  5514. // work out what the resulting combinator will be
  5515. targetCombinator = haystackElement.combinator.value;
  5516. if (targetCombinator === '' && hackstackElementIndex === 0) {
  5517. targetCombinator = ' ';
  5518. }
  5519. // if we don't match, null our match to indicate failure
  5520. if (!extendVisitor.isElementValuesEqual(needleElements[potentialMatch.matched].value, haystackElement.value) ||
  5521. (potentialMatch.matched > 0 && needleElements[potentialMatch.matched].combinator.value !== targetCombinator)) {
  5522. potentialMatch = null;
  5523. }
  5524. else {
  5525. potentialMatch.matched++;
  5526. }
  5527. // if we are still valid and have finished, test whether we have elements after and whether these are allowed
  5528. if (potentialMatch) {
  5529. potentialMatch.finished = potentialMatch.matched === needleElements.length;
  5530. if (potentialMatch.finished &&
  5531. (!extend.allowAfter &&
  5532. (hackstackElementIndex + 1 < hackstackSelector.elements.length || haystackSelectorIndex + 1 < haystackSelectorPath.length))) {
  5533. potentialMatch = null;
  5534. }
  5535. }
  5536. // if null we remove, if not, we are still valid, so either push as a valid match or continue
  5537. if (potentialMatch) {
  5538. if (potentialMatch.finished) {
  5539. potentialMatch.length = needleElements.length;
  5540. potentialMatch.endPathIndex = haystackSelectorIndex;
  5541. potentialMatch.endPathElementIndex = hackstackElementIndex + 1; // index after end of match
  5542. potentialMatches.length = 0; // we don't allow matches to overlap, so start matching again
  5543. matches.push(potentialMatch);
  5544. }
  5545. }
  5546. else {
  5547. potentialMatches.splice(i, 1);
  5548. i--;
  5549. }
  5550. }
  5551. }
  5552. }
  5553. return matches;
  5554. };
  5555. ProcessExtendsVisitor.prototype.isElementValuesEqual = function (elementValue1, elementValue2) {
  5556. if (typeof elementValue1 === 'string' || typeof elementValue2 === 'string') {
  5557. return elementValue1 === elementValue2;
  5558. }
  5559. if (elementValue1 instanceof tree.Attribute) {
  5560. if (elementValue1.op !== elementValue2.op || elementValue1.key !== elementValue2.key) {
  5561. return false;
  5562. }
  5563. if (!elementValue1.value || !elementValue2.value) {
  5564. if (elementValue1.value || elementValue2.value) {
  5565. return false;
  5566. }
  5567. return true;
  5568. }
  5569. elementValue1 = elementValue1.value.value || elementValue1.value;
  5570. elementValue2 = elementValue2.value.value || elementValue2.value;
  5571. return elementValue1 === elementValue2;
  5572. }
  5573. elementValue1 = elementValue1.value;
  5574. elementValue2 = elementValue2.value;
  5575. if (elementValue1 instanceof tree.Selector) {
  5576. if (!(elementValue2 instanceof tree.Selector) || elementValue1.elements.length !== elementValue2.elements.length) {
  5577. return false;
  5578. }
  5579. for (var i = 0; i < elementValue1.elements.length; i++) {
  5580. if (elementValue1.elements[i].combinator.value !== elementValue2.elements[i].combinator.value) {
  5581. if (i !== 0 || (elementValue1.elements[i].combinator.value || ' ') !== (elementValue2.elements[i].combinator.value || ' ')) {
  5582. return false;
  5583. }
  5584. }
  5585. if (!this.isElementValuesEqual(elementValue1.elements[i].value, elementValue2.elements[i].value)) {
  5586. return false;
  5587. }
  5588. }
  5589. return true;
  5590. }
  5591. return false;
  5592. };
  5593. ProcessExtendsVisitor.prototype.extendSelector = function (matches, selectorPath, replacementSelector, isVisible) {
  5594. // for a set of matches, replace each match with the replacement selector
  5595. var currentSelectorPathIndex = 0;
  5596. var currentSelectorPathElementIndex = 0;
  5597. var path = [];
  5598. var matchIndex;
  5599. var selector;
  5600. var firstElement;
  5601. var match;
  5602. var newElements;
  5603. for (matchIndex = 0; matchIndex < matches.length; matchIndex++) {
  5604. match = matches[matchIndex];
  5605. selector = selectorPath[match.pathIndex];
  5606. firstElement = new tree.Element(match.initialCombinator, replacementSelector.elements[0].value, replacementSelector.elements[0].isVariable, replacementSelector.elements[0].getIndex(), replacementSelector.elements[0].fileInfo());
  5607. if (match.pathIndex > currentSelectorPathIndex && currentSelectorPathElementIndex > 0) {
  5608. path[path.length - 1].elements = path[path.length - 1]
  5609. .elements.concat(selectorPath[currentSelectorPathIndex].elements.slice(currentSelectorPathElementIndex));
  5610. currentSelectorPathElementIndex = 0;
  5611. currentSelectorPathIndex++;
  5612. }
  5613. newElements = selector.elements
  5614. .slice(currentSelectorPathElementIndex, match.index)
  5615. .concat([firstElement])
  5616. .concat(replacementSelector.elements.slice(1));
  5617. if (currentSelectorPathIndex === match.pathIndex && matchIndex > 0) {
  5618. path[path.length - 1].elements =
  5619. path[path.length - 1].elements.concat(newElements);
  5620. }
  5621. else {
  5622. path = path.concat(selectorPath.slice(currentSelectorPathIndex, match.pathIndex));
  5623. path.push(new tree.Selector(newElements));
  5624. }
  5625. currentSelectorPathIndex = match.endPathIndex;
  5626. currentSelectorPathElementIndex = match.endPathElementIndex;
  5627. if (currentSelectorPathElementIndex >= selectorPath[currentSelectorPathIndex].elements.length) {
  5628. currentSelectorPathElementIndex = 0;
  5629. currentSelectorPathIndex++;
  5630. }
  5631. }
  5632. if (currentSelectorPathIndex < selectorPath.length && currentSelectorPathElementIndex > 0) {
  5633. path[path.length - 1].elements = path[path.length - 1]
  5634. .elements.concat(selectorPath[currentSelectorPathIndex].elements.slice(currentSelectorPathElementIndex));
  5635. currentSelectorPathIndex++;
  5636. }
  5637. path = path.concat(selectorPath.slice(currentSelectorPathIndex, selectorPath.length));
  5638. path = path.map(function (currentValue) {
  5639. // we can re-use elements here, because the visibility property matters only for selectors
  5640. var derived = currentValue.createDerived(currentValue.elements);
  5641. if (isVisible) {
  5642. derived.ensureVisibility();
  5643. }
  5644. else {
  5645. derived.ensureInvisibility();
  5646. }
  5647. return derived;
  5648. });
  5649. return path;
  5650. };
  5651. ProcessExtendsVisitor.prototype.visitMedia = function (mediaNode, visitArgs) {
  5652. var newAllExtends = mediaNode.allExtends.concat(this.allExtendsStack[this.allExtendsStack.length - 1]);
  5653. newAllExtends = newAllExtends.concat(this.doExtendChaining(newAllExtends, mediaNode.allExtends));
  5654. this.allExtendsStack.push(newAllExtends);
  5655. };
  5656. ProcessExtendsVisitor.prototype.visitMediaOut = function (mediaNode) {
  5657. var lastIndex = this.allExtendsStack.length - 1;
  5658. this.allExtendsStack.length = lastIndex;
  5659. };
  5660. ProcessExtendsVisitor.prototype.visitAtRule = function (atRuleNode, visitArgs) {
  5661. var newAllExtends = atRuleNode.allExtends.concat(this.allExtendsStack[this.allExtendsStack.length - 1]);
  5662. newAllExtends = newAllExtends.concat(this.doExtendChaining(newAllExtends, atRuleNode.allExtends));
  5663. this.allExtendsStack.push(newAllExtends);
  5664. };
  5665. ProcessExtendsVisitor.prototype.visitAtRuleOut = function (atRuleNode) {
  5666. var lastIndex = this.allExtendsStack.length - 1;
  5667. this.allExtendsStack.length = lastIndex;
  5668. };
  5669. return ProcessExtendsVisitor;
  5670. }());
  5671. var JoinSelectorVisitor = /** @class */ (function () {
  5672. function JoinSelectorVisitor() {
  5673. this.contexts = [[]];
  5674. this._visitor = new Visitor(this);
  5675. }
  5676. JoinSelectorVisitor.prototype.run = function (root) {
  5677. return this._visitor.visit(root);
  5678. };
  5679. JoinSelectorVisitor.prototype.visitDeclaration = function (declNode, visitArgs) {
  5680. visitArgs.visitDeeper = false;
  5681. };
  5682. JoinSelectorVisitor.prototype.visitMixinDefinition = function (mixinDefinitionNode, visitArgs) {
  5683. visitArgs.visitDeeper = false;
  5684. };
  5685. JoinSelectorVisitor.prototype.visitRuleset = function (rulesetNode, visitArgs) {
  5686. var context = this.contexts[this.contexts.length - 1];
  5687. var paths = [];
  5688. var selectors;
  5689. this.contexts.push(paths);
  5690. if (!rulesetNode.root) {
  5691. selectors = rulesetNode.selectors;
  5692. if (selectors) {
  5693. selectors = selectors.filter(function (selector) { return selector.getIsOutput(); });
  5694. rulesetNode.selectors = selectors.length ? selectors : (selectors = null);
  5695. if (selectors) {
  5696. rulesetNode.joinSelectors(paths, context, selectors);
  5697. }
  5698. }
  5699. if (!selectors) {
  5700. rulesetNode.rules = null;
  5701. }
  5702. rulesetNode.paths = paths;
  5703. }
  5704. };
  5705. JoinSelectorVisitor.prototype.visitRulesetOut = function (rulesetNode) {
  5706. this.contexts.length = this.contexts.length - 1;
  5707. };
  5708. JoinSelectorVisitor.prototype.visitMedia = function (mediaNode, visitArgs) {
  5709. var context = this.contexts[this.contexts.length - 1];
  5710. mediaNode.rules[0].root = (context.length === 0 || context[0].multiMedia);
  5711. };
  5712. JoinSelectorVisitor.prototype.visitAtRule = function (atRuleNode, visitArgs) {
  5713. var context = this.contexts[this.contexts.length - 1];
  5714. if (atRuleNode.rules && atRuleNode.rules.length) {
  5715. atRuleNode.rules[0].root = (atRuleNode.isRooted || context.length === 0 || null);
  5716. }
  5717. };
  5718. return JoinSelectorVisitor;
  5719. }());
  5720. var CSSVisitorUtils = /** @class */ (function () {
  5721. function CSSVisitorUtils(context) {
  5722. this._visitor = new Visitor(this);
  5723. this._context = context;
  5724. }
  5725. CSSVisitorUtils.prototype.containsSilentNonBlockedChild = function (bodyRules) {
  5726. var rule;
  5727. if (!bodyRules) {
  5728. return false;
  5729. }
  5730. for (var r = 0; r < bodyRules.length; r++) {
  5731. rule = bodyRules[r];
  5732. if (rule.isSilent && rule.isSilent(this._context) && !rule.blocksVisibility()) {
  5733. // the atrule contains something that was referenced (likely by extend)
  5734. // therefore it needs to be shown in output too
  5735. return true;
  5736. }
  5737. }
  5738. return false;
  5739. };
  5740. CSSVisitorUtils.prototype.keepOnlyVisibleChilds = function (owner) {
  5741. if (owner && owner.rules) {
  5742. owner.rules = owner.rules.filter(function (thing) { return thing.isVisible(); });
  5743. }
  5744. };
  5745. CSSVisitorUtils.prototype.isEmpty = function (owner) {
  5746. return (owner && owner.rules)
  5747. ? (owner.rules.length === 0) : true;
  5748. };
  5749. CSSVisitorUtils.prototype.hasVisibleSelector = function (rulesetNode) {
  5750. return (rulesetNode && rulesetNode.paths)
  5751. ? (rulesetNode.paths.length > 0) : false;
  5752. };
  5753. CSSVisitorUtils.prototype.resolveVisibility = function (node, originalRules) {
  5754. if (!node.blocksVisibility()) {
  5755. if (this.isEmpty(node) && !this.containsSilentNonBlockedChild(originalRules)) {
  5756. return;
  5757. }
  5758. return node;
  5759. }
  5760. var compiledRulesBody = node.rules[0];
  5761. this.keepOnlyVisibleChilds(compiledRulesBody);
  5762. if (this.isEmpty(compiledRulesBody)) {
  5763. return;
  5764. }
  5765. node.ensureVisibility();
  5766. node.removeVisibilityBlock();
  5767. return node;
  5768. };
  5769. CSSVisitorUtils.prototype.isVisibleRuleset = function (rulesetNode) {
  5770. if (rulesetNode.firstRoot) {
  5771. return true;
  5772. }
  5773. if (this.isEmpty(rulesetNode)) {
  5774. return false;
  5775. }
  5776. if (!rulesetNode.root && !this.hasVisibleSelector(rulesetNode)) {
  5777. return false;
  5778. }
  5779. return true;
  5780. };
  5781. return CSSVisitorUtils;
  5782. }());
  5783. var ToCSSVisitor = function (context) {
  5784. this._visitor = new Visitor(this);
  5785. this._context = context;
  5786. this.utils = new CSSVisitorUtils(context);
  5787. };
  5788. ToCSSVisitor.prototype = {
  5789. isReplacing: true,
  5790. run: function (root) {
  5791. return this._visitor.visit(root);
  5792. },
  5793. visitDeclaration: function (declNode, visitArgs) {
  5794. if (declNode.blocksVisibility() || declNode.variable) {
  5795. return;
  5796. }
  5797. return declNode;
  5798. },
  5799. visitMixinDefinition: function (mixinNode, visitArgs) {
  5800. // mixin definitions do not get eval'd - this means they keep state
  5801. // so we have to clear that state here so it isn't used if toCSS is called twice
  5802. mixinNode.frames = [];
  5803. },
  5804. visitExtend: function (extendNode, visitArgs) {
  5805. },
  5806. visitComment: function (commentNode, visitArgs) {
  5807. if (commentNode.blocksVisibility() || commentNode.isSilent(this._context)) {
  5808. return;
  5809. }
  5810. return commentNode;
  5811. },
  5812. visitMedia: function (mediaNode, visitArgs) {
  5813. var originalRules = mediaNode.rules[0].rules;
  5814. mediaNode.accept(this._visitor);
  5815. visitArgs.visitDeeper = false;
  5816. return this.utils.resolveVisibility(mediaNode, originalRules);
  5817. },
  5818. visitImport: function (importNode, visitArgs) {
  5819. if (importNode.blocksVisibility()) {
  5820. return;
  5821. }
  5822. return importNode;
  5823. },
  5824. visitAtRule: function (atRuleNode, visitArgs) {
  5825. if (atRuleNode.rules && atRuleNode.rules.length) {
  5826. return this.visitAtRuleWithBody(atRuleNode, visitArgs);
  5827. }
  5828. else {
  5829. return this.visitAtRuleWithoutBody(atRuleNode, visitArgs);
  5830. }
  5831. },
  5832. visitAnonymous: function (anonymousNode, visitArgs) {
  5833. if (!anonymousNode.blocksVisibility()) {
  5834. anonymousNode.accept(this._visitor);
  5835. return anonymousNode;
  5836. }
  5837. },
  5838. visitAtRuleWithBody: function (atRuleNode, visitArgs) {
  5839. // if there is only one nested ruleset and that one has no path, then it is
  5840. // just fake ruleset
  5841. function hasFakeRuleset(atRuleNode) {
  5842. var bodyRules = atRuleNode.rules;
  5843. return bodyRules.length === 1 && (!bodyRules[0].paths || bodyRules[0].paths.length === 0);
  5844. }
  5845. function getBodyRules(atRuleNode) {
  5846. var nodeRules = atRuleNode.rules;
  5847. if (hasFakeRuleset(atRuleNode)) {
  5848. return nodeRules[0].rules;
  5849. }
  5850. return nodeRules;
  5851. }
  5852. // it is still true that it is only one ruleset in array
  5853. // this is last such moment
  5854. // process childs
  5855. var originalRules = getBodyRules(atRuleNode);
  5856. atRuleNode.accept(this._visitor);
  5857. visitArgs.visitDeeper = false;
  5858. if (!this.utils.isEmpty(atRuleNode)) {
  5859. this._mergeRules(atRuleNode.rules[0].rules);
  5860. }
  5861. return this.utils.resolveVisibility(atRuleNode, originalRules);
  5862. },
  5863. visitAtRuleWithoutBody: function (atRuleNode, visitArgs) {
  5864. if (atRuleNode.blocksVisibility()) {
  5865. return;
  5866. }
  5867. if (atRuleNode.name === '@charset') {
  5868. // Only output the debug info together with subsequent @charset definitions
  5869. // a comment (or @media statement) before the actual @charset atrule would
  5870. // be considered illegal css as it has to be on the first line
  5871. if (this.charset) {
  5872. if (atRuleNode.debugInfo) {
  5873. var comment = new tree.Comment("/* " + atRuleNode.toCSS(this._context).replace(/\n/g, '') + " */\n");
  5874. comment.debugInfo = atRuleNode.debugInfo;
  5875. return this._visitor.visit(comment);
  5876. }
  5877. return;
  5878. }
  5879. this.charset = true;
  5880. }
  5881. return atRuleNode;
  5882. },
  5883. checkValidNodes: function (rules, isRoot) {
  5884. if (!rules) {
  5885. return;
  5886. }
  5887. for (var i = 0; i < rules.length; i++) {
  5888. var ruleNode = rules[i];
  5889. if (isRoot && ruleNode instanceof tree.Declaration && !ruleNode.variable) {
  5890. throw { message: 'Properties must be inside selector blocks. They cannot be in the root',
  5891. index: ruleNode.getIndex(), filename: ruleNode.fileInfo() && ruleNode.fileInfo().filename };
  5892. }
  5893. if (ruleNode instanceof tree.Call) {
  5894. throw { message: "Function '" + ruleNode.name + "' is undefined", index: ruleNode.getIndex(), filename: ruleNode.fileInfo() && ruleNode.fileInfo().filename };
  5895. }
  5896. if (ruleNode.type && !ruleNode.allowRoot) {
  5897. throw { message: ruleNode.type + " node returned by a function is not valid here", index: ruleNode.getIndex(), filename: ruleNode.fileInfo() && ruleNode.fileInfo().filename };
  5898. }
  5899. }
  5900. },
  5901. visitRuleset: function (rulesetNode, visitArgs) {
  5902. // at this point rulesets are nested into each other
  5903. var rule;
  5904. var rulesets = [];
  5905. this.checkValidNodes(rulesetNode.rules, rulesetNode.firstRoot);
  5906. if (!rulesetNode.root) {
  5907. // remove invisible paths
  5908. this._compileRulesetPaths(rulesetNode);
  5909. // remove rulesets from this ruleset body and compile them separately
  5910. var nodeRules = rulesetNode.rules;
  5911. var nodeRuleCnt = nodeRules ? nodeRules.length : 0;
  5912. for (var i = 0; i < nodeRuleCnt;) {
  5913. rule = nodeRules[i];
  5914. if (rule && rule.rules) {
  5915. // visit because we are moving them out from being a child
  5916. rulesets.push(this._visitor.visit(rule));
  5917. nodeRules.splice(i, 1);
  5918. nodeRuleCnt--;
  5919. continue;
  5920. }
  5921. i++;
  5922. }
  5923. // accept the visitor to remove rules and refactor itself
  5924. // then we can decide nogw whether we want it or not
  5925. // compile body
  5926. if (nodeRuleCnt > 0) {
  5927. rulesetNode.accept(this._visitor);
  5928. }
  5929. else {
  5930. rulesetNode.rules = null;
  5931. }
  5932. visitArgs.visitDeeper = false;
  5933. }
  5934. else { // if (! rulesetNode.root) {
  5935. rulesetNode.accept(this._visitor);
  5936. visitArgs.visitDeeper = false;
  5937. }
  5938. if (rulesetNode.rules) {
  5939. this._mergeRules(rulesetNode.rules);
  5940. this._removeDuplicateRules(rulesetNode.rules);
  5941. }
  5942. // now decide whether we keep the ruleset
  5943. if (this.utils.isVisibleRuleset(rulesetNode)) {
  5944. rulesetNode.ensureVisibility();
  5945. rulesets.splice(0, 0, rulesetNode);
  5946. }
  5947. if (rulesets.length === 1) {
  5948. return rulesets[0];
  5949. }
  5950. return rulesets;
  5951. },
  5952. _compileRulesetPaths: function (rulesetNode) {
  5953. if (rulesetNode.paths) {
  5954. rulesetNode.paths = rulesetNode.paths
  5955. .filter(function (p) {
  5956. var i;
  5957. if (p[0].elements[0].combinator.value === ' ') {
  5958. p[0].elements[0].combinator = new (tree.Combinator)('');
  5959. }
  5960. for (i = 0; i < p.length; i++) {
  5961. if (p[i].isVisible() && p[i].getIsOutput()) {
  5962. return true;
  5963. }
  5964. }
  5965. return false;
  5966. });
  5967. }
  5968. },
  5969. _removeDuplicateRules: function (rules) {
  5970. if (!rules) {
  5971. return;
  5972. }
  5973. // remove duplicates
  5974. var ruleCache = {};
  5975. var ruleList;
  5976. var rule;
  5977. var i;
  5978. for (i = rules.length - 1; i >= 0; i--) {
  5979. rule = rules[i];
  5980. if (rule instanceof tree.Declaration) {
  5981. if (!ruleCache[rule.name]) {
  5982. ruleCache[rule.name] = rule;
  5983. }
  5984. else {
  5985. ruleList = ruleCache[rule.name];
  5986. if (ruleList instanceof tree.Declaration) {
  5987. ruleList = ruleCache[rule.name] = [ruleCache[rule.name].toCSS(this._context)];
  5988. }
  5989. var ruleCSS = rule.toCSS(this._context);
  5990. if (ruleList.indexOf(ruleCSS) !== -1) {
  5991. rules.splice(i, 1);
  5992. }
  5993. else {
  5994. ruleList.push(ruleCSS);
  5995. }
  5996. }
  5997. }
  5998. }
  5999. },
  6000. _mergeRules: function (rules) {
  6001. if (!rules) {
  6002. return;
  6003. }
  6004. var groups = {};
  6005. var groupsArr = [];
  6006. for (var i = 0; i < rules.length; i++) {
  6007. var rule = rules[i];
  6008. if (rule.merge) {
  6009. var key = rule.name;
  6010. groups[key] ? rules.splice(i--, 1) :
  6011. groupsArr.push(groups[key] = []);
  6012. groups[key].push(rule);
  6013. }
  6014. }
  6015. groupsArr.forEach(function (group) {
  6016. if (group.length > 0) {
  6017. var result_1 = group[0];
  6018. var space_1 = [];
  6019. var comma_1 = [new tree.Expression(space_1)];
  6020. group.forEach(function (rule) {
  6021. if ((rule.merge === '+') && (space_1.length > 0)) {
  6022. comma_1.push(new tree.Expression(space_1 = []));
  6023. }
  6024. space_1.push(rule.value);
  6025. result_1.important = result_1.important || rule.important;
  6026. });
  6027. result_1.value = new tree.Value(comma_1);
  6028. }
  6029. });
  6030. }
  6031. };
  6032. var visitors = {
  6033. Visitor: Visitor,
  6034. ImportVisitor: ImportVisitor,
  6035. MarkVisibleSelectorsVisitor: SetTreeVisibilityVisitor,
  6036. ExtendVisitor: ProcessExtendsVisitor,
  6037. JoinSelectorVisitor: JoinSelectorVisitor,
  6038. ToCSSVisitor: ToCSSVisitor
  6039. };
  6040. // Split the input into chunks.
  6041. var chunker = (function (input, fail) {
  6042. var len = input.length;
  6043. var level = 0;
  6044. var parenLevel = 0;
  6045. var lastOpening;
  6046. var lastOpeningParen;
  6047. var lastMultiComment;
  6048. var lastMultiCommentEndBrace;
  6049. var chunks = [];
  6050. var emitFrom = 0;
  6051. var chunkerCurrentIndex;
  6052. var currentChunkStartIndex;
  6053. var cc;
  6054. var cc2;
  6055. var matched;
  6056. function emitChunk(force) {
  6057. var len = chunkerCurrentIndex - emitFrom;
  6058. if (((len < 512) && !force) || !len) {
  6059. return;
  6060. }
  6061. chunks.push(input.slice(emitFrom, chunkerCurrentIndex + 1));
  6062. emitFrom = chunkerCurrentIndex + 1;
  6063. }
  6064. for (chunkerCurrentIndex = 0; chunkerCurrentIndex < len; chunkerCurrentIndex++) {
  6065. cc = input.charCodeAt(chunkerCurrentIndex);
  6066. if (((cc >= 97) && (cc <= 122)) || (cc < 34)) {
  6067. // a-z or whitespace
  6068. continue;
  6069. }
  6070. switch (cc) {
  6071. case 40: // (
  6072. parenLevel++;
  6073. lastOpeningParen = chunkerCurrentIndex;
  6074. continue;
  6075. case 41: // )
  6076. if (--parenLevel < 0) {
  6077. return fail('missing opening `(`', chunkerCurrentIndex);
  6078. }
  6079. continue;
  6080. case 59: // ;
  6081. if (!parenLevel) {
  6082. emitChunk();
  6083. }
  6084. continue;
  6085. case 123: // {
  6086. level++;
  6087. lastOpening = chunkerCurrentIndex;
  6088. continue;
  6089. case 125: // }
  6090. if (--level < 0) {
  6091. return fail('missing opening `{`', chunkerCurrentIndex);
  6092. }
  6093. if (!level && !parenLevel) {
  6094. emitChunk();
  6095. }
  6096. continue;
  6097. case 92: // \
  6098. if (chunkerCurrentIndex < len - 1) {
  6099. chunkerCurrentIndex++;
  6100. continue;
  6101. }
  6102. return fail('unescaped `\\`', chunkerCurrentIndex);
  6103. case 34:
  6104. case 39:
  6105. case 96: // ", ' and `
  6106. matched = 0;
  6107. currentChunkStartIndex = chunkerCurrentIndex;
  6108. for (chunkerCurrentIndex = chunkerCurrentIndex + 1; chunkerCurrentIndex < len; chunkerCurrentIndex++) {
  6109. cc2 = input.charCodeAt(chunkerCurrentIndex);
  6110. if (cc2 > 96) {
  6111. continue;
  6112. }
  6113. if (cc2 == cc) {
  6114. matched = 1;
  6115. break;
  6116. }
  6117. if (cc2 == 92) { // \
  6118. if (chunkerCurrentIndex == len - 1) {
  6119. return fail('unescaped `\\`', chunkerCurrentIndex);
  6120. }
  6121. chunkerCurrentIndex++;
  6122. }
  6123. }
  6124. if (matched) {
  6125. continue;
  6126. }
  6127. return fail("unmatched `" + String.fromCharCode(cc) + "`", currentChunkStartIndex);
  6128. case 47: // /, check for comment
  6129. if (parenLevel || (chunkerCurrentIndex == len - 1)) {
  6130. continue;
  6131. }
  6132. cc2 = input.charCodeAt(chunkerCurrentIndex + 1);
  6133. if (cc2 == 47) {
  6134. // //, find lnfeed
  6135. for (chunkerCurrentIndex = chunkerCurrentIndex + 2; chunkerCurrentIndex < len; chunkerCurrentIndex++) {
  6136. cc2 = input.charCodeAt(chunkerCurrentIndex);
  6137. if ((cc2 <= 13) && ((cc2 == 10) || (cc2 == 13))) {
  6138. break;
  6139. }
  6140. }
  6141. }
  6142. else if (cc2 == 42) {
  6143. // /*, find */
  6144. lastMultiComment = currentChunkStartIndex = chunkerCurrentIndex;
  6145. for (chunkerCurrentIndex = chunkerCurrentIndex + 2; chunkerCurrentIndex < len - 1; chunkerCurrentIndex++) {
  6146. cc2 = input.charCodeAt(chunkerCurrentIndex);
  6147. if (cc2 == 125) {
  6148. lastMultiCommentEndBrace = chunkerCurrentIndex;
  6149. }
  6150. if (cc2 != 42) {
  6151. continue;
  6152. }
  6153. if (input.charCodeAt(chunkerCurrentIndex + 1) == 47) {
  6154. break;
  6155. }
  6156. }
  6157. if (chunkerCurrentIndex == len - 1) {
  6158. return fail('missing closing `*/`', currentChunkStartIndex);
  6159. }
  6160. chunkerCurrentIndex++;
  6161. }
  6162. continue;
  6163. case 42: // *, check for unmatched */
  6164. if ((chunkerCurrentIndex < len - 1) && (input.charCodeAt(chunkerCurrentIndex + 1) == 47)) {
  6165. return fail('unmatched `/*`', chunkerCurrentIndex);
  6166. }
  6167. continue;
  6168. }
  6169. }
  6170. if (level !== 0) {
  6171. if ((lastMultiComment > lastOpening) && (lastMultiCommentEndBrace > lastMultiComment)) {
  6172. return fail('missing closing `}` or `*/`', lastOpening);
  6173. }
  6174. else {
  6175. return fail('missing closing `}`', lastOpening);
  6176. }
  6177. }
  6178. else if (parenLevel !== 0) {
  6179. return fail('missing closing `)`', lastOpeningParen);
  6180. }
  6181. emitChunk(true);
  6182. return chunks;
  6183. });
  6184. var getParserInput = (function () {
  6185. var // Less input string
  6186. input;
  6187. var // current chunk
  6188. j;
  6189. var // holds state for backtracking
  6190. saveStack = [];
  6191. var // furthest index the parser has gone to
  6192. furthest;
  6193. var // if this is furthest we got to, this is the probably cause
  6194. furthestPossibleErrorMessage;
  6195. var // chunkified input
  6196. chunks;
  6197. var // current chunk
  6198. current;
  6199. var // index of current chunk, in `input`
  6200. currentPos;
  6201. var parserInput = {};
  6202. var CHARCODE_SPACE = 32;
  6203. var CHARCODE_TAB = 9;
  6204. var CHARCODE_LF = 10;
  6205. var CHARCODE_CR = 13;
  6206. var CHARCODE_PLUS = 43;
  6207. var CHARCODE_COMMA = 44;
  6208. var CHARCODE_FORWARD_SLASH = 47;
  6209. var CHARCODE_9 = 57;
  6210. function skipWhitespace(length) {
  6211. var oldi = parserInput.i;
  6212. var oldj = j;
  6213. var curr = parserInput.i - currentPos;
  6214. var endIndex = parserInput.i + current.length - curr;
  6215. var mem = (parserInput.i += length);
  6216. var inp = input;
  6217. var c;
  6218. var nextChar;
  6219. var comment;
  6220. for (; parserInput.i < endIndex; parserInput.i++) {
  6221. c = inp.charCodeAt(parserInput.i);
  6222. if (parserInput.autoCommentAbsorb && c === CHARCODE_FORWARD_SLASH) {
  6223. nextChar = inp.charAt(parserInput.i + 1);
  6224. if (nextChar === '/') {
  6225. comment = { index: parserInput.i, isLineComment: true };
  6226. var nextNewLine = inp.indexOf('\n', parserInput.i + 2);
  6227. if (nextNewLine < 0) {
  6228. nextNewLine = endIndex;
  6229. }
  6230. parserInput.i = nextNewLine;
  6231. comment.text = inp.substr(comment.index, parserInput.i - comment.index);
  6232. parserInput.commentStore.push(comment);
  6233. continue;
  6234. }
  6235. else if (nextChar === '*') {
  6236. var nextStarSlash = inp.indexOf('*/', parserInput.i + 2);
  6237. if (nextStarSlash >= 0) {
  6238. comment = {
  6239. index: parserInput.i,
  6240. text: inp.substr(parserInput.i, nextStarSlash + 2 - parserInput.i),
  6241. isLineComment: false
  6242. };
  6243. parserInput.i += comment.text.length - 1;
  6244. parserInput.commentStore.push(comment);
  6245. continue;
  6246. }
  6247. }
  6248. break;
  6249. }
  6250. if ((c !== CHARCODE_SPACE) && (c !== CHARCODE_LF) && (c !== CHARCODE_TAB) && (c !== CHARCODE_CR)) {
  6251. break;
  6252. }
  6253. }
  6254. current = current.slice(length + parserInput.i - mem + curr);
  6255. currentPos = parserInput.i;
  6256. if (!current.length) {
  6257. if (j < chunks.length - 1) {
  6258. current = chunks[++j];
  6259. skipWhitespace(0); // skip space at the beginning of a chunk
  6260. return true; // things changed
  6261. }
  6262. parserInput.finished = true;
  6263. }
  6264. return oldi !== parserInput.i || oldj !== j;
  6265. }
  6266. parserInput.save = function () {
  6267. currentPos = parserInput.i;
  6268. saveStack.push({ current: current, i: parserInput.i, j: j });
  6269. };
  6270. parserInput.restore = function (possibleErrorMessage) {
  6271. if (parserInput.i > furthest || (parserInput.i === furthest && possibleErrorMessage && !furthestPossibleErrorMessage)) {
  6272. furthest = parserInput.i;
  6273. furthestPossibleErrorMessage = possibleErrorMessage;
  6274. }
  6275. var state = saveStack.pop();
  6276. current = state.current;
  6277. currentPos = parserInput.i = state.i;
  6278. j = state.j;
  6279. };
  6280. parserInput.forget = function () {
  6281. saveStack.pop();
  6282. };
  6283. parserInput.isWhitespace = function (offset) {
  6284. var pos = parserInput.i + (offset || 0);
  6285. var code = input.charCodeAt(pos);
  6286. return (code === CHARCODE_SPACE || code === CHARCODE_CR || code === CHARCODE_TAB || code === CHARCODE_LF);
  6287. };
  6288. // Specialization of $(tok)
  6289. parserInput.$re = function (tok) {
  6290. if (parserInput.i > currentPos) {
  6291. current = current.slice(parserInput.i - currentPos);
  6292. currentPos = parserInput.i;
  6293. }
  6294. var m = tok.exec(current);
  6295. if (!m) {
  6296. return null;
  6297. }
  6298. skipWhitespace(m[0].length);
  6299. if (typeof m === 'string') {
  6300. return m;
  6301. }
  6302. return m.length === 1 ? m[0] : m;
  6303. };
  6304. parserInput.$char = function (tok) {
  6305. if (input.charAt(parserInput.i) !== tok) {
  6306. return null;
  6307. }
  6308. skipWhitespace(1);
  6309. return tok;
  6310. };
  6311. parserInput.$str = function (tok) {
  6312. var tokLength = tok.length;
  6313. // https://jsperf.com/string-startswith/21
  6314. for (var i = 0; i < tokLength; i++) {
  6315. if (input.charAt(parserInput.i + i) !== tok.charAt(i)) {
  6316. return null;
  6317. }
  6318. }
  6319. skipWhitespace(tokLength);
  6320. return tok;
  6321. };
  6322. parserInput.$quoted = function (loc) {
  6323. var pos = loc || parserInput.i;
  6324. var startChar = input.charAt(pos);
  6325. if (startChar !== '\'' && startChar !== '"') {
  6326. return;
  6327. }
  6328. var length = input.length;
  6329. var currentPosition = pos;
  6330. for (var i = 1; i + currentPosition < length; i++) {
  6331. var nextChar = input.charAt(i + currentPosition);
  6332. switch (nextChar) {
  6333. case '\\':
  6334. i++;
  6335. continue;
  6336. case '\r':
  6337. case '\n':
  6338. break;
  6339. case startChar:
  6340. var str = input.substr(currentPosition, i + 1);
  6341. if (!loc && loc !== 0) {
  6342. skipWhitespace(i + 1);
  6343. return str;
  6344. }
  6345. return [startChar, str];
  6346. }
  6347. }
  6348. return null;
  6349. };
  6350. /**
  6351. * Permissive parsing. Ignores everything except matching {} [] () and quotes
  6352. * until matching token (outside of blocks)
  6353. */
  6354. parserInput.$parseUntil = function (tok) {
  6355. var quote = '';
  6356. var returnVal = null;
  6357. var inComment = false;
  6358. var blockDepth = 0;
  6359. var blockStack = [];
  6360. var parseGroups = [];
  6361. var length = input.length;
  6362. var startPos = parserInput.i;
  6363. var lastPos = parserInput.i;
  6364. var i = parserInput.i;
  6365. var loop = true;
  6366. var testChar;
  6367. if (typeof tok === 'string') {
  6368. testChar = function (char) { return char === tok; };
  6369. }
  6370. else {
  6371. testChar = function (char) { return tok.test(char); };
  6372. }
  6373. do {
  6374. var nextChar = input.charAt(i);
  6375. if (blockDepth === 0 && testChar(nextChar)) {
  6376. returnVal = input.substr(lastPos, i - lastPos);
  6377. if (returnVal) {
  6378. parseGroups.push(returnVal);
  6379. }
  6380. else {
  6381. parseGroups.push(' ');
  6382. }
  6383. returnVal = parseGroups;
  6384. skipWhitespace(i - startPos);
  6385. loop = false;
  6386. }
  6387. else {
  6388. if (inComment) {
  6389. if (nextChar === '*' &&
  6390. input.charAt(i + 1) === '/') {
  6391. i++;
  6392. blockDepth--;
  6393. inComment = false;
  6394. }
  6395. i++;
  6396. continue;
  6397. }
  6398. switch (nextChar) {
  6399. case '\\':
  6400. i++;
  6401. nextChar = input.charAt(i);
  6402. parseGroups.push(input.substr(lastPos, i - lastPos + 1));
  6403. lastPos = i + 1;
  6404. break;
  6405. case '/':
  6406. if (input.charAt(i + 1) === '*') {
  6407. i++;
  6408. inComment = true;
  6409. blockDepth++;
  6410. }
  6411. break;
  6412. case '\'':
  6413. case '"':
  6414. quote = parserInput.$quoted(i);
  6415. if (quote) {
  6416. parseGroups.push(input.substr(lastPos, i - lastPos), quote);
  6417. i += quote[1].length - 1;
  6418. lastPos = i + 1;
  6419. }
  6420. else {
  6421. skipWhitespace(i - startPos);
  6422. returnVal = nextChar;
  6423. loop = false;
  6424. }
  6425. break;
  6426. case '{':
  6427. blockStack.push('}');
  6428. blockDepth++;
  6429. break;
  6430. case '(':
  6431. blockStack.push(')');
  6432. blockDepth++;
  6433. break;
  6434. case '[':
  6435. blockStack.push(']');
  6436. blockDepth++;
  6437. break;
  6438. case '}':
  6439. case ')':
  6440. case ']':
  6441. var expected = blockStack.pop();
  6442. if (nextChar === expected) {
  6443. blockDepth--;
  6444. }
  6445. else {
  6446. // move the parser to the error and return expected
  6447. skipWhitespace(i - startPos);
  6448. returnVal = expected;
  6449. loop = false;
  6450. }
  6451. }
  6452. i++;
  6453. if (i > length) {
  6454. loop = false;
  6455. }
  6456. }
  6457. } while (loop);
  6458. return returnVal ? returnVal : null;
  6459. };
  6460. parserInput.autoCommentAbsorb = true;
  6461. parserInput.commentStore = [];
  6462. parserInput.finished = false;
  6463. // Same as $(), but don't change the state of the parser,
  6464. // just return the match.
  6465. parserInput.peek = function (tok) {
  6466. if (typeof tok === 'string') {
  6467. // https://jsperf.com/string-startswith/21
  6468. for (var i = 0; i < tok.length; i++) {
  6469. if (input.charAt(parserInput.i + i) !== tok.charAt(i)) {
  6470. return false;
  6471. }
  6472. }
  6473. return true;
  6474. }
  6475. else {
  6476. return tok.test(current);
  6477. }
  6478. };
  6479. // Specialization of peek()
  6480. // TODO remove or change some currentChar calls to peekChar
  6481. parserInput.peekChar = function (tok) { return input.charAt(parserInput.i) === tok; };
  6482. parserInput.currentChar = function () { return input.charAt(parserInput.i); };
  6483. parserInput.prevChar = function () { return input.charAt(parserInput.i - 1); };
  6484. parserInput.getInput = function () { return input; };
  6485. parserInput.peekNotNumeric = function () {
  6486. var c = input.charCodeAt(parserInput.i);
  6487. // Is the first char of the dimension 0-9, '.', '+' or '-'
  6488. return (c > CHARCODE_9 || c < CHARCODE_PLUS) || c === CHARCODE_FORWARD_SLASH || c === CHARCODE_COMMA;
  6489. };
  6490. parserInput.start = function (str, chunkInput, failFunction) {
  6491. input = str;
  6492. parserInput.i = j = currentPos = furthest = 0;
  6493. // chunking apparently makes things quicker (but my tests indicate
  6494. // it might actually make things slower in node at least)
  6495. // and it is a non-perfect parse - it can't recognise
  6496. // unquoted urls, meaning it can't distinguish comments
  6497. // meaning comments with quotes or {}() in them get 'counted'
  6498. // and then lead to parse errors.
  6499. // In addition if the chunking chunks in the wrong place we might
  6500. // not be able to parse a parser statement in one go
  6501. // this is officially deprecated but can be switched on via an option
  6502. // in the case it causes too much performance issues.
  6503. if (chunkInput) {
  6504. chunks = chunker(str, failFunction);
  6505. }
  6506. else {
  6507. chunks = [str];
  6508. }
  6509. current = chunks[0];
  6510. skipWhitespace(0);
  6511. };
  6512. parserInput.end = function () {
  6513. var message;
  6514. var isFinished = parserInput.i >= input.length;
  6515. if (parserInput.i < furthest) {
  6516. message = furthestPossibleErrorMessage;
  6517. parserInput.i = furthest;
  6518. }
  6519. return {
  6520. isFinished: isFinished,
  6521. furthest: parserInput.i,
  6522. furthestPossibleErrorMessage: message,
  6523. furthestReachedEnd: parserInput.i >= input.length - 1,
  6524. furthestChar: input[parserInput.i]
  6525. };
  6526. };
  6527. return parserInput;
  6528. });
  6529. //
  6530. // less.js - parser
  6531. //
  6532. // A relatively straight-forward predictive parser.
  6533. // There is no tokenization/lexing stage, the input is parsed
  6534. // in one sweep.
  6535. //
  6536. // To make the parser fast enough to run in the browser, several
  6537. // optimization had to be made:
  6538. //
  6539. // - Matching and slicing on a huge input is often cause of slowdowns.
  6540. // The solution is to chunkify the input into smaller strings.
  6541. // The chunks are stored in the `chunks` var,
  6542. // `j` holds the current chunk index, and `currentPos` holds
  6543. // the index of the current chunk in relation to `input`.
  6544. // This gives us an almost 4x speed-up.
  6545. //
  6546. // - In many cases, we don't need to match individual tokens;
  6547. // for example, if a value doesn't hold any variables, operations
  6548. // or dynamic references, the parser can effectively 'skip' it,
  6549. // treating it as a literal.
  6550. // An example would be '1px solid #000' - which evaluates to itself,
  6551. // we don't need to know what the individual components are.
  6552. // The drawback, of course is that you don't get the benefits of
  6553. // syntax-checking on the CSS. This gives us a 50% speed-up in the parser,
  6554. // and a smaller speed-up in the code-gen.
  6555. //
  6556. //
  6557. // Token matching is done with the `$` function, which either takes
  6558. // a terminal string or regexp, or a non-terminal function to call.
  6559. // It also takes care of moving all the indices forwards.
  6560. //
  6561. var Parser = function Parser(context, imports, fileInfo) {
  6562. var parsers;
  6563. var parserInput = getParserInput();
  6564. function error(msg, type) {
  6565. throw new LessError({
  6566. index: parserInput.i,
  6567. filename: fileInfo.filename,
  6568. type: type || 'Syntax',
  6569. message: msg
  6570. }, imports);
  6571. }
  6572. function expect(arg, msg) {
  6573. // some older browsers return typeof 'function' for RegExp
  6574. var result = (arg instanceof Function) ? arg.call(parsers) : parserInput.$re(arg);
  6575. if (result) {
  6576. return result;
  6577. }
  6578. error(msg || (typeof arg === 'string'
  6579. ? "expected '" + arg + "' got '" + parserInput.currentChar() + "'"
  6580. : 'unexpected token'));
  6581. }
  6582. // Specialization of expect()
  6583. function expectChar(arg, msg) {
  6584. if (parserInput.$char(arg)) {
  6585. return arg;
  6586. }
  6587. error(msg || "expected '" + arg + "' got '" + parserInput.currentChar() + "'");
  6588. }
  6589. function getDebugInfo(index) {
  6590. var filename = fileInfo.filename;
  6591. return {
  6592. lineNumber: getLocation(index, parserInput.getInput()).line + 1,
  6593. fileName: filename
  6594. };
  6595. }
  6596. /**
  6597. * Used after initial parsing to create nodes on the fly
  6598. *
  6599. * @param {String} str - string to parse
  6600. * @param {Array} parseList - array of parsers to run input through e.g. ["value", "important"]
  6601. * @param {Number} currentIndex - start number to begin indexing
  6602. * @param {Object} fileInfo - fileInfo to attach to created nodes
  6603. */
  6604. function parseNode(str, parseList, currentIndex, fileInfo, callback) {
  6605. var result;
  6606. var returnNodes = [];
  6607. var parser = parserInput;
  6608. try {
  6609. parser.start(str, false, function fail(msg, index) {
  6610. callback({
  6611. message: msg,
  6612. index: index + currentIndex
  6613. });
  6614. });
  6615. for (var x = 0, p = void 0, i = void 0; (p = parseList[x]); x++) {
  6616. i = parser.i;
  6617. result = parsers[p]();
  6618. if (result) {
  6619. try {
  6620. result._index = i + currentIndex;
  6621. result._fileInfo = fileInfo;
  6622. }
  6623. catch (e) { }
  6624. returnNodes.push(result);
  6625. }
  6626. else {
  6627. returnNodes.push(null);
  6628. }
  6629. }
  6630. var endInfo = parser.end();
  6631. if (endInfo.isFinished) {
  6632. callback(null, returnNodes);
  6633. }
  6634. else {
  6635. callback(true, null);
  6636. }
  6637. }
  6638. catch (e) {
  6639. throw new LessError({
  6640. index: e.index + currentIndex,
  6641. message: e.message
  6642. }, imports, fileInfo.filename);
  6643. }
  6644. }
  6645. //
  6646. // The Parser
  6647. //
  6648. return {
  6649. parserInput: parserInput,
  6650. imports: imports,
  6651. fileInfo: fileInfo,
  6652. parseNode: parseNode,
  6653. //
  6654. // Parse an input string into an abstract syntax tree,
  6655. // @param str A string containing 'less' markup
  6656. // @param callback call `callback` when done.
  6657. // @param [additionalData] An optional map which can contains vars - a map (key, value) of variables to apply
  6658. //
  6659. parse: function (str, callback, additionalData) {
  6660. var root;
  6661. var error = null;
  6662. var globalVars;
  6663. var modifyVars;
  6664. var ignored;
  6665. var preText = '';
  6666. globalVars = (additionalData && additionalData.globalVars) ? Parser.serializeVars(additionalData.globalVars) + "\n" : '';
  6667. modifyVars = (additionalData && additionalData.modifyVars) ? "\n" + Parser.serializeVars(additionalData.modifyVars) : '';
  6668. if (context.pluginManager) {
  6669. var preProcessors = context.pluginManager.getPreProcessors();
  6670. for (var i = 0; i < preProcessors.length; i++) {
  6671. str = preProcessors[i].process(str, { context: context, imports: imports, fileInfo: fileInfo });
  6672. }
  6673. }
  6674. if (globalVars || (additionalData && additionalData.banner)) {
  6675. preText = ((additionalData && additionalData.banner) ? additionalData.banner : '') + globalVars;
  6676. ignored = imports.contentsIgnoredChars;
  6677. ignored[fileInfo.filename] = ignored[fileInfo.filename] || 0;
  6678. ignored[fileInfo.filename] += preText.length;
  6679. }
  6680. str = str.replace(/\r\n?/g, '\n');
  6681. // Remove potential UTF Byte Order Mark
  6682. str = preText + str.replace(/^\uFEFF/, '') + modifyVars;
  6683. imports.contents[fileInfo.filename] = str;
  6684. // Start with the primary rule.
  6685. // The whole syntax tree is held under a Ruleset node,
  6686. // with the `root` property set to true, so no `{}` are
  6687. // output. The callback is called when the input is parsed.
  6688. try {
  6689. parserInput.start(str, context.chunkInput, function fail(msg, index) {
  6690. throw new LessError({
  6691. index: index,
  6692. type: 'Parse',
  6693. message: msg,
  6694. filename: fileInfo.filename
  6695. }, imports);
  6696. });
  6697. tree.Node.prototype.parse = this;
  6698. root = new tree.Ruleset(null, this.parsers.primary());
  6699. tree.Node.prototype.rootNode = root;
  6700. root.root = true;
  6701. root.firstRoot = true;
  6702. root.functionRegistry = functionRegistry.inherit();
  6703. }
  6704. catch (e) {
  6705. return callback(new LessError(e, imports, fileInfo.filename));
  6706. }
  6707. // If `i` is smaller than the `input.length - 1`,
  6708. // it means the parser wasn't able to parse the whole
  6709. // string, so we've got a parsing error.
  6710. //
  6711. // We try to extract a \n delimited string,
  6712. // showing the line where the parse error occurred.
  6713. // We split it up into two parts (the part which parsed,
  6714. // and the part which didn't), so we can color them differently.
  6715. var endInfo = parserInput.end();
  6716. if (!endInfo.isFinished) {
  6717. var message = endInfo.furthestPossibleErrorMessage;
  6718. if (!message) {
  6719. message = 'Unrecognised input';
  6720. if (endInfo.furthestChar === '}') {
  6721. message += '. Possibly missing opening \'{\'';
  6722. }
  6723. else if (endInfo.furthestChar === ')') {
  6724. message += '. Possibly missing opening \'(\'';
  6725. }
  6726. else if (endInfo.furthestReachedEnd) {
  6727. message += '. Possibly missing something';
  6728. }
  6729. }
  6730. error = new LessError({
  6731. type: 'Parse',
  6732. message: message,
  6733. index: endInfo.furthest,
  6734. filename: fileInfo.filename
  6735. }, imports);
  6736. }
  6737. var finish = function (e) {
  6738. e = error || e || imports.error;
  6739. if (e) {
  6740. if (!(e instanceof LessError)) {
  6741. e = new LessError(e, imports, fileInfo.filename);
  6742. }
  6743. return callback(e);
  6744. }
  6745. else {
  6746. return callback(null, root);
  6747. }
  6748. };
  6749. if (context.processImports !== false) {
  6750. new visitors.ImportVisitor(imports, finish)
  6751. .run(root);
  6752. }
  6753. else {
  6754. return finish();
  6755. }
  6756. },
  6757. //
  6758. // Here in, the parsing rules/functions
  6759. //
  6760. // The basic structure of the syntax tree generated is as follows:
  6761. //
  6762. // Ruleset -> Declaration -> Value -> Expression -> Entity
  6763. //
  6764. // Here's some Less code:
  6765. //
  6766. // .class {
  6767. // color: #fff;
  6768. // border: 1px solid #000;
  6769. // width: @w + 4px;
  6770. // > .child {...}
  6771. // }
  6772. //
  6773. // And here's what the parse tree might look like:
  6774. //
  6775. // Ruleset (Selector '.class', [
  6776. // Declaration ("color", Value ([Expression [Color #fff]]))
  6777. // Declaration ("border", Value ([Expression [Dimension 1px][Keyword "solid"][Color #000]]))
  6778. // Declaration ("width", Value ([Expression [Operation " + " [Variable "@w"][Dimension 4px]]]))
  6779. // Ruleset (Selector [Element '>', '.child'], [...])
  6780. // ])
  6781. //
  6782. // In general, most rules will try to parse a token with the `$re()` function, and if the return
  6783. // value is truly, will return a new node, of the relevant type. Sometimes, we need to check
  6784. // first, before parsing, that's when we use `peek()`.
  6785. //
  6786. parsers: parsers = {
  6787. //
  6788. // The `primary` rule is the *entry* and *exit* point of the parser.
  6789. // The rules here can appear at any level of the parse tree.
  6790. //
  6791. // The recursive nature of the grammar is an interplay between the `block`
  6792. // rule, which represents `{ ... }`, the `ruleset` rule, and this `primary` rule,
  6793. // as represented by this simplified grammar:
  6794. //
  6795. // primary → (ruleset | declaration)+
  6796. // ruleset → selector+ block
  6797. // block → '{' primary '}'
  6798. //
  6799. // Only at one point is the primary rule not called from the
  6800. // block rule: at the root level.
  6801. //
  6802. primary: function () {
  6803. var mixin = this.mixin;
  6804. var root = [];
  6805. var node;
  6806. while (true) {
  6807. while (true) {
  6808. node = this.comment();
  6809. if (!node) {
  6810. break;
  6811. }
  6812. root.push(node);
  6813. }
  6814. // always process comments before deciding if finished
  6815. if (parserInput.finished) {
  6816. break;
  6817. }
  6818. if (parserInput.peek('}')) {
  6819. break;
  6820. }
  6821. node = this.extendRule();
  6822. if (node) {
  6823. root = root.concat(node);
  6824. continue;
  6825. }
  6826. node = mixin.definition() || this.declaration() || mixin.call(false, false) ||
  6827. this.ruleset() || this.variableCall() || this.entities.call() || this.atrule();
  6828. if (node) {
  6829. root.push(node);
  6830. }
  6831. else {
  6832. var foundSemiColon = false;
  6833. while (parserInput.$char(';')) {
  6834. foundSemiColon = true;
  6835. }
  6836. if (!foundSemiColon) {
  6837. break;
  6838. }
  6839. }
  6840. }
  6841. return root;
  6842. },
  6843. // comments are collected by the main parsing mechanism and then assigned to nodes
  6844. // where the current structure allows it
  6845. comment: function () {
  6846. if (parserInput.commentStore.length) {
  6847. var comment = parserInput.commentStore.shift();
  6848. return new (tree.Comment)(comment.text, comment.isLineComment, comment.index, fileInfo);
  6849. }
  6850. },
  6851. //
  6852. // Entities are tokens which can be found inside an Expression
  6853. //
  6854. entities: {
  6855. mixinLookup: function () {
  6856. return parsers.mixin.call(true, true);
  6857. },
  6858. //
  6859. // A string, which supports escaping " and '
  6860. //
  6861. // "milky way" 'he\'s the one!'
  6862. //
  6863. quoted: function (forceEscaped) {
  6864. var str;
  6865. var index = parserInput.i;
  6866. var isEscaped = false;
  6867. parserInput.save();
  6868. if (parserInput.$char('~')) {
  6869. isEscaped = true;
  6870. }
  6871. else if (forceEscaped) {
  6872. parserInput.restore();
  6873. return;
  6874. }
  6875. str = parserInput.$quoted();
  6876. if (!str) {
  6877. parserInput.restore();
  6878. return;
  6879. }
  6880. parserInput.forget();
  6881. return new (tree.Quoted)(str.charAt(0), str.substr(1, str.length - 2), isEscaped, index, fileInfo);
  6882. },
  6883. //
  6884. // A catch-all word, such as:
  6885. //
  6886. // black border-collapse
  6887. //
  6888. keyword: function () {
  6889. var k = parserInput.$char('%') || parserInput.$re(/^\[?(?:[\w-]|\\(?:[A-Fa-f0-9]{1,6} ?|[^A-Fa-f0-9]))+\]?/);
  6890. if (k) {
  6891. return tree.Color.fromKeyword(k) || new (tree.Keyword)(k);
  6892. }
  6893. },
  6894. //
  6895. // A function call
  6896. //
  6897. // rgb(255, 0, 255)
  6898. //
  6899. // The arguments are parsed with the `entities.arguments` parser.
  6900. //
  6901. call: function () {
  6902. var name;
  6903. var args;
  6904. var func;
  6905. var index = parserInput.i;
  6906. // http://jsperf.com/case-insensitive-regex-vs-strtolower-then-regex/18
  6907. if (parserInput.peek(/^url\(/i)) {
  6908. return;
  6909. }
  6910. parserInput.save();
  6911. name = parserInput.$re(/^([\w-]+|%|progid:[\w\.]+)\(/);
  6912. if (!name) {
  6913. parserInput.forget();
  6914. return;
  6915. }
  6916. name = name[1];
  6917. func = this.customFuncCall(name);
  6918. if (func) {
  6919. args = func.parse();
  6920. if (args && func.stop) {
  6921. parserInput.forget();
  6922. return args;
  6923. }
  6924. }
  6925. args = this.arguments(args);
  6926. if (!parserInput.$char(')')) {
  6927. parserInput.restore('Could not parse call arguments or missing \')\'');
  6928. return;
  6929. }
  6930. parserInput.forget();
  6931. return new (tree.Call)(name, args, index, fileInfo);
  6932. },
  6933. //
  6934. // Parsing rules for functions with non-standard args, e.g.:
  6935. //
  6936. // boolean(not(2 > 1))
  6937. //
  6938. // This is a quick prototype, to be modified/improved when
  6939. // more custom-parsed funcs come (e.g. `selector(...)`)
  6940. //
  6941. customFuncCall: function (name) {
  6942. /* Ideally the table is to be moved out of here for faster perf.,
  6943. but it's quite tricky since it relies on all these `parsers`
  6944. and `expect` available only here */
  6945. return {
  6946. alpha: f(parsers.ieAlpha, true),
  6947. boolean: f(condition),
  6948. 'if': f(condition)
  6949. }[name.toLowerCase()];
  6950. function f(parse, stop) {
  6951. return {
  6952. parse: parse,
  6953. stop: stop // when true - stop after parse() and return its result,
  6954. // otherwise continue for plain args
  6955. };
  6956. }
  6957. function condition() {
  6958. return [expect(parsers.condition, 'expected condition')];
  6959. }
  6960. },
  6961. arguments: function (prevArgs) {
  6962. var argsComma = prevArgs || [];
  6963. var argsSemiColon = [];
  6964. var isSemiColonSeparated;
  6965. var value;
  6966. parserInput.save();
  6967. while (true) {
  6968. if (prevArgs) {
  6969. prevArgs = false;
  6970. }
  6971. else {
  6972. value = parsers.detachedRuleset() || this.assignment() || parsers.expression();
  6973. if (!value) {
  6974. break;
  6975. }
  6976. if (value.value && value.value.length == 1) {
  6977. value = value.value[0];
  6978. }
  6979. argsComma.push(value);
  6980. }
  6981. if (parserInput.$char(',')) {
  6982. continue;
  6983. }
  6984. if (parserInput.$char(';') || isSemiColonSeparated) {
  6985. isSemiColonSeparated = true;
  6986. value = (argsComma.length < 1) ? argsComma[0]
  6987. : new tree.Value(argsComma);
  6988. argsSemiColon.push(value);
  6989. argsComma = [];
  6990. }
  6991. }
  6992. parserInput.forget();
  6993. return isSemiColonSeparated ? argsSemiColon : argsComma;
  6994. },
  6995. literal: function () {
  6996. return this.dimension() ||
  6997. this.color() ||
  6998. this.quoted() ||
  6999. this.unicodeDescriptor();
  7000. },
  7001. // Assignments are argument entities for calls.
  7002. // They are present in ie filter properties as shown below.
  7003. //
  7004. // filter: progid:DXImageTransform.Microsoft.Alpha( *opacity=50* )
  7005. //
  7006. assignment: function () {
  7007. var key;
  7008. var value;
  7009. parserInput.save();
  7010. key = parserInput.$re(/^\w+(?=\s?=)/i);
  7011. if (!key) {
  7012. parserInput.restore();
  7013. return;
  7014. }
  7015. if (!parserInput.$char('=')) {
  7016. parserInput.restore();
  7017. return;
  7018. }
  7019. value = parsers.entity();
  7020. if (value) {
  7021. parserInput.forget();
  7022. return new (tree.Assignment)(key, value);
  7023. }
  7024. else {
  7025. parserInput.restore();
  7026. }
  7027. },
  7028. //
  7029. // Parse url() tokens
  7030. //
  7031. // We use a specific rule for urls, because they don't really behave like
  7032. // standard function calls. The difference is that the argument doesn't have
  7033. // to be enclosed within a string, so it can't be parsed as an Expression.
  7034. //
  7035. url: function () {
  7036. var value;
  7037. var index = parserInput.i;
  7038. parserInput.autoCommentAbsorb = false;
  7039. if (!parserInput.$str('url(')) {
  7040. parserInput.autoCommentAbsorb = true;
  7041. return;
  7042. }
  7043. value = this.quoted() || this.variable() || this.property() ||
  7044. parserInput.$re(/^(?:(?:\\[\(\)'"])|[^\(\)'"])+/) || '';
  7045. parserInput.autoCommentAbsorb = true;
  7046. expectChar(')');
  7047. return new (tree.URL)((value.value != null ||
  7048. value instanceof tree.Variable ||
  7049. value instanceof tree.Property) ?
  7050. value : new (tree.Anonymous)(value, index), index, fileInfo);
  7051. },
  7052. //
  7053. // A Variable entity, such as `@fink`, in
  7054. //
  7055. // width: @fink + 2px
  7056. //
  7057. // We use a different parser for variable definitions,
  7058. // see `parsers.variable`.
  7059. //
  7060. variable: function () {
  7061. var ch;
  7062. var name;
  7063. var index = parserInput.i;
  7064. parserInput.save();
  7065. if (parserInput.currentChar() === '@' && (name = parserInput.$re(/^@@?[\w-]+/))) {
  7066. ch = parserInput.currentChar();
  7067. if (ch === '(' || ch === '[' && !parserInput.prevChar().match(/^\s/)) {
  7068. // this may be a VariableCall lookup
  7069. var result = parsers.variableCall(name);
  7070. if (result) {
  7071. parserInput.forget();
  7072. return result;
  7073. }
  7074. }
  7075. parserInput.forget();
  7076. return new (tree.Variable)(name, index, fileInfo);
  7077. }
  7078. parserInput.restore();
  7079. },
  7080. // A variable entity using the protective {} e.g. @{var}
  7081. variableCurly: function () {
  7082. var curly;
  7083. var index = parserInput.i;
  7084. if (parserInput.currentChar() === '@' && (curly = parserInput.$re(/^@\{([\w-]+)\}/))) {
  7085. return new (tree.Variable)("@" + curly[1], index, fileInfo);
  7086. }
  7087. },
  7088. //
  7089. // A Property accessor, such as `$color`, in
  7090. //
  7091. // background-color: $color
  7092. //
  7093. property: function () {
  7094. var name;
  7095. var index = parserInput.i;
  7096. if (parserInput.currentChar() === '$' && (name = parserInput.$re(/^\$[\w-]+/))) {
  7097. return new (tree.Property)(name, index, fileInfo);
  7098. }
  7099. },
  7100. // A property entity useing the protective {} e.g. ${prop}
  7101. propertyCurly: function () {
  7102. var curly;
  7103. var index = parserInput.i;
  7104. if (parserInput.currentChar() === '$' && (curly = parserInput.$re(/^\$\{([\w-]+)\}/))) {
  7105. return new (tree.Property)("$" + curly[1], index, fileInfo);
  7106. }
  7107. },
  7108. //
  7109. // A Hexadecimal color
  7110. //
  7111. // #4F3C2F
  7112. //
  7113. // `rgb` and `hsl` colors are parsed through the `entities.call` parser.
  7114. //
  7115. color: function () {
  7116. var rgb;
  7117. parserInput.save();
  7118. if (parserInput.currentChar() === '#' && (rgb = parserInput.$re(/^#([A-Fa-f0-9]{8}|[A-Fa-f0-9]{6}|[A-Fa-f0-9]{3,4})([\w.#\[])?/))) {
  7119. if (!rgb[2]) {
  7120. parserInput.forget();
  7121. return new (tree.Color)(rgb[1], undefined, rgb[0]);
  7122. }
  7123. }
  7124. parserInput.restore();
  7125. },
  7126. colorKeyword: function () {
  7127. parserInput.save();
  7128. var autoCommentAbsorb = parserInput.autoCommentAbsorb;
  7129. parserInput.autoCommentAbsorb = false;
  7130. var k = parserInput.$re(/^[_A-Za-z-][_A-Za-z0-9-]+/);
  7131. parserInput.autoCommentAbsorb = autoCommentAbsorb;
  7132. if (!k) {
  7133. parserInput.forget();
  7134. return;
  7135. }
  7136. parserInput.restore();
  7137. var color = tree.Color.fromKeyword(k);
  7138. if (color) {
  7139. parserInput.$str(k);
  7140. return color;
  7141. }
  7142. },
  7143. //
  7144. // A Dimension, that is, a number and a unit
  7145. //
  7146. // 0.5em 95%
  7147. //
  7148. dimension: function () {
  7149. if (parserInput.peekNotNumeric()) {
  7150. return;
  7151. }
  7152. var value = parserInput.$re(/^([+-]?\d*\.?\d+)(%|[a-z_]+)?/i);
  7153. if (value) {
  7154. return new (tree.Dimension)(value[1], value[2]);
  7155. }
  7156. },
  7157. //
  7158. // A unicode descriptor, as is used in unicode-range
  7159. //
  7160. // U+0?? or U+00A1-00A9
  7161. //
  7162. unicodeDescriptor: function () {
  7163. var ud;
  7164. ud = parserInput.$re(/^U\+[0-9a-fA-F?]+(\-[0-9a-fA-F?]+)?/);
  7165. if (ud) {
  7166. return new (tree.UnicodeDescriptor)(ud[0]);
  7167. }
  7168. },
  7169. //
  7170. // JavaScript code to be evaluated
  7171. //
  7172. // `window.location.href`
  7173. //
  7174. javascript: function () {
  7175. var js;
  7176. var index = parserInput.i;
  7177. parserInput.save();
  7178. var escape = parserInput.$char('~');
  7179. var jsQuote = parserInput.$char('`');
  7180. if (!jsQuote) {
  7181. parserInput.restore();
  7182. return;
  7183. }
  7184. js = parserInput.$re(/^[^`]*`/);
  7185. if (js) {
  7186. parserInput.forget();
  7187. return new (tree.JavaScript)(js.substr(0, js.length - 1), Boolean(escape), index, fileInfo);
  7188. }
  7189. parserInput.restore('invalid javascript definition');
  7190. }
  7191. },
  7192. //
  7193. // The variable part of a variable definition. Used in the `rule` parser
  7194. //
  7195. // @fink:
  7196. //
  7197. variable: function () {
  7198. var name;
  7199. if (parserInput.currentChar() === '@' && (name = parserInput.$re(/^(@[\w-]+)\s*:/))) {
  7200. return name[1];
  7201. }
  7202. },
  7203. //
  7204. // Call a variable value to retrieve a detached ruleset
  7205. // or a value from a detached ruleset's rules.
  7206. //
  7207. // @fink();
  7208. // @fink;
  7209. // color: @fink[@color];
  7210. //
  7211. variableCall: function (parsedName) {
  7212. var lookups;
  7213. var i = parserInput.i;
  7214. var inValue = !!parsedName;
  7215. var name = parsedName;
  7216. parserInput.save();
  7217. if (name || (parserInput.currentChar() === '@'
  7218. && (name = parserInput.$re(/^(@[\w-]+)(\(\s*\))?/)))) {
  7219. lookups = this.mixin.ruleLookups();
  7220. if (!lookups && ((inValue && parserInput.$str('()') !== '()') || (name[2] !== '()'))) {
  7221. parserInput.restore('Missing \'[...]\' lookup in variable call');
  7222. return;
  7223. }
  7224. if (!inValue) {
  7225. name = name[1];
  7226. }
  7227. var call = new tree.VariableCall(name, i, fileInfo);
  7228. if (!inValue && parsers.end()) {
  7229. parserInput.forget();
  7230. return call;
  7231. }
  7232. else {
  7233. parserInput.forget();
  7234. return new tree.NamespaceValue(call, lookups, i, fileInfo);
  7235. }
  7236. }
  7237. parserInput.restore();
  7238. },
  7239. //
  7240. // extend syntax - used to extend selectors
  7241. //
  7242. extend: function (isRule) {
  7243. var elements;
  7244. var e;
  7245. var index = parserInput.i;
  7246. var option;
  7247. var extendList;
  7248. var extend;
  7249. if (!parserInput.$str(isRule ? '&:extend(' : ':extend(')) {
  7250. return;
  7251. }
  7252. do {
  7253. option = null;
  7254. elements = null;
  7255. while (!(option = parserInput.$re(/^(all)(?=\s*(\)|,))/))) {
  7256. e = this.element();
  7257. if (!e) {
  7258. break;
  7259. }
  7260. if (elements) {
  7261. elements.push(e);
  7262. }
  7263. else {
  7264. elements = [e];
  7265. }
  7266. }
  7267. option = option && option[1];
  7268. if (!elements) {
  7269. error('Missing target selector for :extend().');
  7270. }
  7271. extend = new (tree.Extend)(new (tree.Selector)(elements), option, index, fileInfo);
  7272. if (extendList) {
  7273. extendList.push(extend);
  7274. }
  7275. else {
  7276. extendList = [extend];
  7277. }
  7278. } while (parserInput.$char(','));
  7279. expect(/^\)/);
  7280. if (isRule) {
  7281. expect(/^;/);
  7282. }
  7283. return extendList;
  7284. },
  7285. //
  7286. // extendRule - used in a rule to extend all the parent selectors
  7287. //
  7288. extendRule: function () {
  7289. return this.extend(true);
  7290. },
  7291. //
  7292. // Mixins
  7293. //
  7294. mixin: {
  7295. //
  7296. // A Mixin call, with an optional argument list
  7297. //
  7298. // #mixins > .square(#fff);
  7299. // #mixins.square(#fff);
  7300. // .rounded(4px, black);
  7301. // .button;
  7302. //
  7303. // We can lookup / return a value using the lookup syntax:
  7304. //
  7305. // color: #mixin.square(#fff)[@color];
  7306. //
  7307. // The `while` loop is there because mixins can be
  7308. // namespaced, but we only support the child and descendant
  7309. // selector for now.
  7310. //
  7311. call: function (inValue, getLookup) {
  7312. var s = parserInput.currentChar();
  7313. var important = false;
  7314. var lookups;
  7315. var index = parserInput.i;
  7316. var elements;
  7317. var args;
  7318. var hasParens;
  7319. if (s !== '.' && s !== '#') {
  7320. return;
  7321. }
  7322. parserInput.save(); // stop us absorbing part of an invalid selector
  7323. elements = this.elements();
  7324. if (elements) {
  7325. if (parserInput.$char('(')) {
  7326. args = this.args(true).args;
  7327. expectChar(')');
  7328. hasParens = true;
  7329. }
  7330. if (getLookup !== false) {
  7331. lookups = this.ruleLookups();
  7332. }
  7333. if (getLookup === true && !lookups) {
  7334. parserInput.restore();
  7335. return;
  7336. }
  7337. if (inValue && !lookups && !hasParens) {
  7338. // This isn't a valid in-value mixin call
  7339. parserInput.restore();
  7340. return;
  7341. }
  7342. if (!inValue && parsers.important()) {
  7343. important = true;
  7344. }
  7345. if (inValue || parsers.end()) {
  7346. parserInput.forget();
  7347. var mixin = new (tree.mixin.Call)(elements, args, index, fileInfo, !lookups && important);
  7348. if (lookups) {
  7349. return new tree.NamespaceValue(mixin, lookups);
  7350. }
  7351. else {
  7352. return mixin;
  7353. }
  7354. }
  7355. }
  7356. parserInput.restore();
  7357. },
  7358. /**
  7359. * Matching elements for mixins
  7360. * (Start with . or # and can have > )
  7361. */
  7362. elements: function () {
  7363. var elements;
  7364. var e;
  7365. var c;
  7366. var elem;
  7367. var elemIndex;
  7368. var re = /^[#.](?:[\w-]|\\(?:[A-Fa-f0-9]{1,6} ?|[^A-Fa-f0-9]))+/;
  7369. while (true) {
  7370. elemIndex = parserInput.i;
  7371. e = parserInput.$re(re);
  7372. if (!e) {
  7373. break;
  7374. }
  7375. elem = new (tree.Element)(c, e, false, elemIndex, fileInfo);
  7376. if (elements) {
  7377. elements.push(elem);
  7378. }
  7379. else {
  7380. elements = [elem];
  7381. }
  7382. c = parserInput.$char('>');
  7383. }
  7384. return elements;
  7385. },
  7386. args: function (isCall) {
  7387. var entities = parsers.entities;
  7388. var returner = { args: null, variadic: false };
  7389. var expressions = [];
  7390. var argsSemiColon = [];
  7391. var argsComma = [];
  7392. var isSemiColonSeparated;
  7393. var expressionContainsNamed;
  7394. var name;
  7395. var nameLoop;
  7396. var value;
  7397. var arg;
  7398. var expand;
  7399. var hasSep = true;
  7400. parserInput.save();
  7401. while (true) {
  7402. if (isCall) {
  7403. arg = parsers.detachedRuleset() || parsers.expression();
  7404. }
  7405. else {
  7406. parserInput.commentStore.length = 0;
  7407. if (parserInput.$str('...')) {
  7408. returner.variadic = true;
  7409. if (parserInput.$char(';') && !isSemiColonSeparated) {
  7410. isSemiColonSeparated = true;
  7411. }
  7412. (isSemiColonSeparated ? argsSemiColon : argsComma)
  7413. .push({ variadic: true });
  7414. break;
  7415. }
  7416. arg = entities.variable() || entities.property() || entities.literal() || entities.keyword() || this.call(true);
  7417. }
  7418. if (!arg || !hasSep) {
  7419. break;
  7420. }
  7421. nameLoop = null;
  7422. if (arg.throwAwayComments) {
  7423. arg.throwAwayComments();
  7424. }
  7425. value = arg;
  7426. var val = null;
  7427. if (isCall) {
  7428. // Variable
  7429. if (arg.value && arg.value.length == 1) {
  7430. val = arg.value[0];
  7431. }
  7432. }
  7433. else {
  7434. val = arg;
  7435. }
  7436. if (val && (val instanceof tree.Variable || val instanceof tree.Property)) {
  7437. if (parserInput.$char(':')) {
  7438. if (expressions.length > 0) {
  7439. if (isSemiColonSeparated) {
  7440. error('Cannot mix ; and , as delimiter types');
  7441. }
  7442. expressionContainsNamed = true;
  7443. }
  7444. value = parsers.detachedRuleset() || parsers.expression();
  7445. if (!value) {
  7446. if (isCall) {
  7447. error('could not understand value for named argument');
  7448. }
  7449. else {
  7450. parserInput.restore();
  7451. returner.args = [];
  7452. return returner;
  7453. }
  7454. }
  7455. nameLoop = (name = val.name);
  7456. }
  7457. else if (parserInput.$str('...')) {
  7458. if (!isCall) {
  7459. returner.variadic = true;
  7460. if (parserInput.$char(';') && !isSemiColonSeparated) {
  7461. isSemiColonSeparated = true;
  7462. }
  7463. (isSemiColonSeparated ? argsSemiColon : argsComma)
  7464. .push({ name: arg.name, variadic: true });
  7465. break;
  7466. }
  7467. else {
  7468. expand = true;
  7469. }
  7470. }
  7471. else if (!isCall) {
  7472. name = nameLoop = val.name;
  7473. value = null;
  7474. }
  7475. }
  7476. if (value) {
  7477. expressions.push(value);
  7478. }
  7479. argsComma.push({ name: nameLoop, value: value, expand: expand });
  7480. if (parserInput.$char(',')) {
  7481. hasSep = true;
  7482. continue;
  7483. }
  7484. hasSep = parserInput.$char(';') === ';';
  7485. if (hasSep || isSemiColonSeparated) {
  7486. if (expressionContainsNamed) {
  7487. error('Cannot mix ; and , as delimiter types');
  7488. }
  7489. isSemiColonSeparated = true;
  7490. if (expressions.length > 1) {
  7491. value = new (tree.Value)(expressions);
  7492. }
  7493. argsSemiColon.push({ name: name, value: value, expand: expand });
  7494. name = null;
  7495. expressions = [];
  7496. expressionContainsNamed = false;
  7497. }
  7498. }
  7499. parserInput.forget();
  7500. returner.args = isSemiColonSeparated ? argsSemiColon : argsComma;
  7501. return returner;
  7502. },
  7503. //
  7504. // A Mixin definition, with a list of parameters
  7505. //
  7506. // .rounded (@radius: 2px, @color) {
  7507. // ...
  7508. // }
  7509. //
  7510. // Until we have a finer grained state-machine, we have to
  7511. // do a look-ahead, to make sure we don't have a mixin call.
  7512. // See the `rule` function for more information.
  7513. //
  7514. // We start by matching `.rounded (`, and then proceed on to
  7515. // the argument list, which has optional default values.
  7516. // We store the parameters in `params`, with a `value` key,
  7517. // if there is a value, such as in the case of `@radius`.
  7518. //
  7519. // Once we've got our params list, and a closing `)`, we parse
  7520. // the `{...}` block.
  7521. //
  7522. definition: function () {
  7523. var name;
  7524. var params = [];
  7525. var match;
  7526. var ruleset;
  7527. var cond;
  7528. var variadic = false;
  7529. if ((parserInput.currentChar() !== '.' && parserInput.currentChar() !== '#') ||
  7530. parserInput.peek(/^[^{]*\}/)) {
  7531. return;
  7532. }
  7533. parserInput.save();
  7534. match = parserInput.$re(/^([#.](?:[\w-]|\\(?:[A-Fa-f0-9]{1,6} ?|[^A-Fa-f0-9]))+)\s*\(/);
  7535. if (match) {
  7536. name = match[1];
  7537. var argInfo = this.args(false);
  7538. params = argInfo.args;
  7539. variadic = argInfo.variadic;
  7540. // .mixincall("@{a}");
  7541. // looks a bit like a mixin definition..
  7542. // also
  7543. // .mixincall(@a: {rule: set;});
  7544. // so we have to be nice and restore
  7545. if (!parserInput.$char(')')) {
  7546. parserInput.restore('Missing closing \')\'');
  7547. return;
  7548. }
  7549. parserInput.commentStore.length = 0;
  7550. if (parserInput.$str('when')) { // Guard
  7551. cond = expect(parsers.conditions, 'expected condition');
  7552. }
  7553. ruleset = parsers.block();
  7554. if (ruleset) {
  7555. parserInput.forget();
  7556. return new (tree.mixin.Definition)(name, params, ruleset, cond, variadic);
  7557. }
  7558. else {
  7559. parserInput.restore();
  7560. }
  7561. }
  7562. else {
  7563. parserInput.restore();
  7564. }
  7565. },
  7566. ruleLookups: function () {
  7567. var rule;
  7568. var lookups = [];
  7569. if (parserInput.currentChar() !== '[') {
  7570. return;
  7571. }
  7572. while (true) {
  7573. parserInput.save();
  7574. rule = this.lookupValue();
  7575. if (!rule && rule !== '') {
  7576. parserInput.restore();
  7577. break;
  7578. }
  7579. lookups.push(rule);
  7580. parserInput.forget();
  7581. }
  7582. if (lookups.length > 0) {
  7583. return lookups;
  7584. }
  7585. },
  7586. lookupValue: function () {
  7587. parserInput.save();
  7588. if (!parserInput.$char('[')) {
  7589. parserInput.restore();
  7590. return;
  7591. }
  7592. var name = parserInput.$re(/^(?:[@$]{0,2})[_a-zA-Z0-9-]*/);
  7593. if (!parserInput.$char(']')) {
  7594. parserInput.restore();
  7595. return;
  7596. }
  7597. if (name || name === '') {
  7598. parserInput.forget();
  7599. return name;
  7600. }
  7601. parserInput.restore();
  7602. }
  7603. },
  7604. //
  7605. // Entities are the smallest recognized token,
  7606. // and can be found inside a rule's value.
  7607. //
  7608. entity: function () {
  7609. var entities = this.entities;
  7610. return this.comment() || entities.literal() || entities.variable() || entities.url() ||
  7611. entities.property() || entities.call() || entities.keyword() || this.mixin.call(true) ||
  7612. entities.javascript();
  7613. },
  7614. //
  7615. // A Declaration terminator. Note that we use `peek()` to check for '}',
  7616. // because the `block` rule will be expecting it, but we still need to make sure
  7617. // it's there, if ';' was omitted.
  7618. //
  7619. end: function () {
  7620. return parserInput.$char(';') || parserInput.peek('}');
  7621. },
  7622. //
  7623. // IE's alpha function
  7624. //
  7625. // alpha(opacity=88)
  7626. //
  7627. ieAlpha: function () {
  7628. var value;
  7629. // http://jsperf.com/case-insensitive-regex-vs-strtolower-then-regex/18
  7630. if (!parserInput.$re(/^opacity=/i)) {
  7631. return;
  7632. }
  7633. value = parserInput.$re(/^\d+/);
  7634. if (!value) {
  7635. value = expect(parsers.entities.variable, 'Could not parse alpha');
  7636. value = "@{" + value.name.slice(1) + "}";
  7637. }
  7638. expectChar(')');
  7639. return new tree.Quoted('', "alpha(opacity=" + value + ")");
  7640. },
  7641. //
  7642. // A Selector Element
  7643. //
  7644. // div
  7645. // + h1
  7646. // #socks
  7647. // input[type="text"]
  7648. //
  7649. // Elements are the building blocks for Selectors,
  7650. // they are made out of a `Combinator` (see combinator rule),
  7651. // and an element name, such as a tag a class, or `*`.
  7652. //
  7653. element: function () {
  7654. var e;
  7655. var c;
  7656. var v;
  7657. var index = parserInput.i;
  7658. c = this.combinator();
  7659. e = parserInput.$re(/^(?:\d+\.\d+|\d+)%/) ||
  7660. parserInput.$re(/^(?:[.#]?|:*)(?:[\w-]|[^\x00-\x9f]|\\(?:[A-Fa-f0-9]{1,6} ?|[^A-Fa-f0-9]))+/) ||
  7661. parserInput.$char('*') || parserInput.$char('&') || this.attribute() ||
  7662. parserInput.$re(/^\([^&()@]+\)/) || parserInput.$re(/^[\.#:](?=@)/) ||
  7663. this.entities.variableCurly();
  7664. if (!e) {
  7665. parserInput.save();
  7666. if (parserInput.$char('(')) {
  7667. if ((v = this.selector(false)) && parserInput.$char(')')) {
  7668. e = new (tree.Paren)(v);
  7669. parserInput.forget();
  7670. }
  7671. else {
  7672. parserInput.restore('Missing closing \')\'');
  7673. }
  7674. }
  7675. else {
  7676. parserInput.forget();
  7677. }
  7678. }
  7679. if (e) {
  7680. return new (tree.Element)(c, e, e instanceof tree.Variable, index, fileInfo);
  7681. }
  7682. },
  7683. //
  7684. // Combinators combine elements together, in a Selector.
  7685. //
  7686. // Because our parser isn't white-space sensitive, special care
  7687. // has to be taken, when parsing the descendant combinator, ` `,
  7688. // as it's an empty space. We have to check the previous character
  7689. // in the input, to see if it's a ` ` character. More info on how
  7690. // we deal with this in *combinator.js*.
  7691. //
  7692. combinator: function () {
  7693. var c = parserInput.currentChar();
  7694. if (c === '/') {
  7695. parserInput.save();
  7696. var slashedCombinator = parserInput.$re(/^\/[a-z]+\//i);
  7697. if (slashedCombinator) {
  7698. parserInput.forget();
  7699. return new (tree.Combinator)(slashedCombinator);
  7700. }
  7701. parserInput.restore();
  7702. }
  7703. if (c === '>' || c === '+' || c === '~' || c === '|' || c === '^') {
  7704. parserInput.i++;
  7705. if (c === '^' && parserInput.currentChar() === '^') {
  7706. c = '^^';
  7707. parserInput.i++;
  7708. }
  7709. while (parserInput.isWhitespace()) {
  7710. parserInput.i++;
  7711. }
  7712. return new (tree.Combinator)(c);
  7713. }
  7714. else if (parserInput.isWhitespace(-1)) {
  7715. return new (tree.Combinator)(' ');
  7716. }
  7717. else {
  7718. return new (tree.Combinator)(null);
  7719. }
  7720. },
  7721. //
  7722. // A CSS Selector
  7723. // with less extensions e.g. the ability to extend and guard
  7724. //
  7725. // .class > div + h1
  7726. // li a:hover
  7727. //
  7728. // Selectors are made out of one or more Elements, see above.
  7729. //
  7730. selector: function (isLess) {
  7731. var index = parserInput.i;
  7732. var elements;
  7733. var extendList;
  7734. var c;
  7735. var e;
  7736. var allExtends;
  7737. var when;
  7738. var condition;
  7739. isLess = isLess !== false;
  7740. while ((isLess && (extendList = this.extend())) || (isLess && (when = parserInput.$str('when'))) || (e = this.element())) {
  7741. if (when) {
  7742. condition = expect(this.conditions, 'expected condition');
  7743. }
  7744. else if (condition) {
  7745. error('CSS guard can only be used at the end of selector');
  7746. }
  7747. else if (extendList) {
  7748. if (allExtends) {
  7749. allExtends = allExtends.concat(extendList);
  7750. }
  7751. else {
  7752. allExtends = extendList;
  7753. }
  7754. }
  7755. else {
  7756. if (allExtends) {
  7757. error('Extend can only be used at the end of selector');
  7758. }
  7759. c = parserInput.currentChar();
  7760. if (elements) {
  7761. elements.push(e);
  7762. }
  7763. else {
  7764. elements = [e];
  7765. }
  7766. e = null;
  7767. }
  7768. if (c === '{' || c === '}' || c === ';' || c === ',' || c === ')') {
  7769. break;
  7770. }
  7771. }
  7772. if (elements) {
  7773. return new (tree.Selector)(elements, allExtends, condition, index, fileInfo);
  7774. }
  7775. if (allExtends) {
  7776. error('Extend must be used to extend a selector, it cannot be used on its own');
  7777. }
  7778. },
  7779. selectors: function () {
  7780. var s;
  7781. var selectors;
  7782. while (true) {
  7783. s = this.selector();
  7784. if (!s) {
  7785. break;
  7786. }
  7787. if (selectors) {
  7788. selectors.push(s);
  7789. }
  7790. else {
  7791. selectors = [s];
  7792. }
  7793. parserInput.commentStore.length = 0;
  7794. if (s.condition && selectors.length > 1) {
  7795. error("Guards are only currently allowed on a single selector.");
  7796. }
  7797. if (!parserInput.$char(',')) {
  7798. break;
  7799. }
  7800. if (s.condition) {
  7801. error("Guards are only currently allowed on a single selector.");
  7802. }
  7803. parserInput.commentStore.length = 0;
  7804. }
  7805. return selectors;
  7806. },
  7807. attribute: function () {
  7808. if (!parserInput.$char('[')) {
  7809. return;
  7810. }
  7811. var entities = this.entities;
  7812. var key;
  7813. var val;
  7814. var op;
  7815. if (!(key = entities.variableCurly())) {
  7816. key = expect(/^(?:[_A-Za-z0-9-\*]*\|)?(?:[_A-Za-z0-9-]|\\.)+/);
  7817. }
  7818. op = parserInput.$re(/^[|~*$^]?=/);
  7819. if (op) {
  7820. val = entities.quoted() || parserInput.$re(/^[0-9]+%/) || parserInput.$re(/^[\w-]+/) || entities.variableCurly();
  7821. }
  7822. expectChar(']');
  7823. return new (tree.Attribute)(key, op, val);
  7824. },
  7825. //
  7826. // The `block` rule is used by `ruleset` and `mixin.definition`.
  7827. // It's a wrapper around the `primary` rule, with added `{}`.
  7828. //
  7829. block: function () {
  7830. var content;
  7831. if (parserInput.$char('{') && (content = this.primary()) && parserInput.$char('}')) {
  7832. return content;
  7833. }
  7834. },
  7835. blockRuleset: function () {
  7836. var block = this.block();
  7837. if (block) {
  7838. block = new tree.Ruleset(null, block);
  7839. }
  7840. return block;
  7841. },
  7842. detachedRuleset: function () {
  7843. var argInfo;
  7844. var params;
  7845. var variadic;
  7846. parserInput.save();
  7847. if (parserInput.$re(/^[.#]\(/)) {
  7848. /**
  7849. * DR args currently only implemented for each() function, and not
  7850. * yet settable as `@dr: #(@arg) {}`
  7851. * This should be done when DRs are merged with mixins.
  7852. * See: https://github.com/less/less-meta/issues/16
  7853. */
  7854. argInfo = this.mixin.args(false);
  7855. params = argInfo.args;
  7856. variadic = argInfo.variadic;
  7857. if (!parserInput.$char(')')) {
  7858. parserInput.restore();
  7859. return;
  7860. }
  7861. }
  7862. var blockRuleset = this.blockRuleset();
  7863. if (blockRuleset) {
  7864. parserInput.forget();
  7865. if (params) {
  7866. return new tree.mixin.Definition(null, params, blockRuleset, null, variadic);
  7867. }
  7868. return new tree.DetachedRuleset(blockRuleset);
  7869. }
  7870. parserInput.restore();
  7871. },
  7872. //
  7873. // div, .class, body > p {...}
  7874. //
  7875. ruleset: function () {
  7876. var selectors;
  7877. var rules;
  7878. var debugInfo;
  7879. parserInput.save();
  7880. if (context.dumpLineNumbers) {
  7881. debugInfo = getDebugInfo(parserInput.i);
  7882. }
  7883. selectors = this.selectors();
  7884. if (selectors && (rules = this.block())) {
  7885. parserInput.forget();
  7886. var ruleset = new (tree.Ruleset)(selectors, rules, context.strictImports);
  7887. if (context.dumpLineNumbers) {
  7888. ruleset.debugInfo = debugInfo;
  7889. }
  7890. return ruleset;
  7891. }
  7892. else {
  7893. parserInput.restore();
  7894. }
  7895. },
  7896. declaration: function () {
  7897. var name;
  7898. var value;
  7899. var index = parserInput.i;
  7900. var hasDR;
  7901. var c = parserInput.currentChar();
  7902. var important;
  7903. var merge;
  7904. var isVariable;
  7905. if (c === '.' || c === '#' || c === '&' || c === ':') {
  7906. return;
  7907. }
  7908. parserInput.save();
  7909. name = this.variable() || this.ruleProperty();
  7910. if (name) {
  7911. isVariable = typeof name === 'string';
  7912. if (isVariable) {
  7913. value = this.detachedRuleset();
  7914. if (value) {
  7915. hasDR = true;
  7916. }
  7917. }
  7918. parserInput.commentStore.length = 0;
  7919. if (!value) {
  7920. // a name returned by this.ruleProperty() is always an array of the form:
  7921. // [string-1, ..., string-n, ""] or [string-1, ..., string-n, "+"]
  7922. // where each item is a tree.Keyword or tree.Variable
  7923. merge = !isVariable && name.length > 1 && name.pop().value;
  7924. // Custom property values get permissive parsing
  7925. if (name[0].value && name[0].value.slice(0, 2) === '--') {
  7926. value = this.permissiveValue();
  7927. }
  7928. // Try to store values as anonymous
  7929. // If we need the value later we'll re-parse it in ruleset.parseValue
  7930. else {
  7931. value = this.anonymousValue();
  7932. }
  7933. if (value) {
  7934. parserInput.forget();
  7935. // anonymous values absorb the end ';' which is required for them to work
  7936. return new (tree.Declaration)(name, value, false, merge, index, fileInfo);
  7937. }
  7938. if (!value) {
  7939. value = this.value();
  7940. }
  7941. if (value) {
  7942. important = this.important();
  7943. }
  7944. else if (isVariable) {
  7945. // As a last resort, try permissiveValue
  7946. value = this.permissiveValue();
  7947. }
  7948. }
  7949. if (value && (this.end() || hasDR)) {
  7950. parserInput.forget();
  7951. return new (tree.Declaration)(name, value, important, merge, index, fileInfo);
  7952. }
  7953. else {
  7954. parserInput.restore();
  7955. }
  7956. }
  7957. else {
  7958. parserInput.restore();
  7959. }
  7960. },
  7961. anonymousValue: function () {
  7962. var index = parserInput.i;
  7963. var match = parserInput.$re(/^([^.#@\$+\/'"*`(;{}-]*);/);
  7964. if (match) {
  7965. return new (tree.Anonymous)(match[1], index);
  7966. }
  7967. },
  7968. /**
  7969. * Used for custom properties, at-rules, and variables (as fallback)
  7970. * Parses almost anything inside of {} [] () "" blocks
  7971. * until it reaches outer-most tokens.
  7972. *
  7973. * First, it will try to parse comments and entities to reach
  7974. * the end. This is mostly like the Expression parser except no
  7975. * math is allowed.
  7976. */
  7977. permissiveValue: function (untilTokens) {
  7978. var i;
  7979. var e;
  7980. var done;
  7981. var value;
  7982. var tok = untilTokens || ';';
  7983. var index = parserInput.i;
  7984. var result = [];
  7985. function testCurrentChar() {
  7986. var char = parserInput.currentChar();
  7987. if (typeof tok === 'string') {
  7988. return char === tok;
  7989. }
  7990. else {
  7991. return tok.test(char);
  7992. }
  7993. }
  7994. if (testCurrentChar()) {
  7995. return;
  7996. }
  7997. value = [];
  7998. do {
  7999. e = this.comment();
  8000. if (e) {
  8001. value.push(e);
  8002. continue;
  8003. }
  8004. e = this.entity();
  8005. if (e) {
  8006. value.push(e);
  8007. }
  8008. } while (e);
  8009. done = testCurrentChar();
  8010. if (value.length > 0) {
  8011. value = new (tree.Expression)(value);
  8012. if (done) {
  8013. return value;
  8014. }
  8015. else {
  8016. result.push(value);
  8017. }
  8018. // Preserve space before $parseUntil as it will not
  8019. if (parserInput.prevChar() === ' ') {
  8020. result.push(new tree.Anonymous(' ', index));
  8021. }
  8022. }
  8023. parserInput.save();
  8024. value = parserInput.$parseUntil(tok);
  8025. if (value) {
  8026. if (typeof value === 'string') {
  8027. error("Expected '" + value + "'", 'Parse');
  8028. }
  8029. if (value.length === 1 && value[0] === ' ') {
  8030. parserInput.forget();
  8031. return new tree.Anonymous('', index);
  8032. }
  8033. var item = void 0;
  8034. for (i = 0; i < value.length; i++) {
  8035. item = value[i];
  8036. if (Array.isArray(item)) {
  8037. // Treat actual quotes as normal quoted values
  8038. result.push(new tree.Quoted(item[0], item[1], true, index, fileInfo));
  8039. }
  8040. else {
  8041. if (i === value.length - 1) {
  8042. item = item.trim();
  8043. }
  8044. // Treat like quoted values, but replace vars like unquoted expressions
  8045. var quote = new tree.Quoted('\'', item, true, index, fileInfo);
  8046. quote.variableRegex = /@([\w-]+)/g;
  8047. quote.propRegex = /\$([\w-]+)/g;
  8048. result.push(quote);
  8049. }
  8050. }
  8051. parserInput.forget();
  8052. return new tree.Expression(result, true);
  8053. }
  8054. parserInput.restore();
  8055. },
  8056. //
  8057. // An @import atrule
  8058. //
  8059. // @import "lib";
  8060. //
  8061. // Depending on our environment, importing is done differently:
  8062. // In the browser, it's an XHR request, in Node, it would be a
  8063. // file-system operation. The function used for importing is
  8064. // stored in `import`, which we pass to the Import constructor.
  8065. //
  8066. 'import': function () {
  8067. var path;
  8068. var features;
  8069. var index = parserInput.i;
  8070. var dir = parserInput.$re(/^@import?\s+/);
  8071. if (dir) {
  8072. var options = (dir ? this.importOptions() : null) || {};
  8073. if ((path = this.entities.quoted() || this.entities.url())) {
  8074. features = this.mediaFeatures();
  8075. if (!parserInput.$char(';')) {
  8076. parserInput.i = index;
  8077. error('missing semi-colon or unrecognised media features on import');
  8078. }
  8079. features = features && new (tree.Value)(features);
  8080. return new (tree.Import)(path, features, options, index, fileInfo);
  8081. }
  8082. else {
  8083. parserInput.i = index;
  8084. error('malformed import statement');
  8085. }
  8086. }
  8087. },
  8088. importOptions: function () {
  8089. var o;
  8090. var options = {};
  8091. var optionName;
  8092. var value;
  8093. // list of options, surrounded by parens
  8094. if (!parserInput.$char('(')) {
  8095. return null;
  8096. }
  8097. do {
  8098. o = this.importOption();
  8099. if (o) {
  8100. optionName = o;
  8101. value = true;
  8102. switch (optionName) {
  8103. case 'css':
  8104. optionName = 'less';
  8105. value = false;
  8106. break;
  8107. case 'once':
  8108. optionName = 'multiple';
  8109. value = false;
  8110. break;
  8111. }
  8112. options[optionName] = value;
  8113. if (!parserInput.$char(',')) {
  8114. break;
  8115. }
  8116. }
  8117. } while (o);
  8118. expectChar(')');
  8119. return options;
  8120. },
  8121. importOption: function () {
  8122. var opt = parserInput.$re(/^(less|css|multiple|once|inline|reference|optional)/);
  8123. if (opt) {
  8124. return opt[1];
  8125. }
  8126. },
  8127. mediaFeature: function () {
  8128. var entities = this.entities;
  8129. var nodes = [];
  8130. var e;
  8131. var p;
  8132. parserInput.save();
  8133. do {
  8134. e = entities.keyword() || entities.variable() || entities.mixinLookup();
  8135. if (e) {
  8136. nodes.push(e);
  8137. }
  8138. else if (parserInput.$char('(')) {
  8139. p = this.property();
  8140. e = this.value();
  8141. if (parserInput.$char(')')) {
  8142. if (p && e) {
  8143. nodes.push(new (tree.Paren)(new (tree.Declaration)(p, e, null, null, parserInput.i, fileInfo, true)));
  8144. }
  8145. else if (e) {
  8146. nodes.push(new (tree.Paren)(e));
  8147. }
  8148. else {
  8149. error('badly formed media feature definition');
  8150. }
  8151. }
  8152. else {
  8153. error('Missing closing \')\'', 'Parse');
  8154. }
  8155. }
  8156. } while (e);
  8157. parserInput.forget();
  8158. if (nodes.length > 0) {
  8159. return new (tree.Expression)(nodes);
  8160. }
  8161. },
  8162. mediaFeatures: function () {
  8163. var entities = this.entities;
  8164. var features = [];
  8165. var e;
  8166. do {
  8167. e = this.mediaFeature();
  8168. if (e) {
  8169. features.push(e);
  8170. if (!parserInput.$char(',')) {
  8171. break;
  8172. }
  8173. }
  8174. else {
  8175. e = entities.variable() || entities.mixinLookup();
  8176. if (e) {
  8177. features.push(e);
  8178. if (!parserInput.$char(',')) {
  8179. break;
  8180. }
  8181. }
  8182. }
  8183. } while (e);
  8184. return features.length > 0 ? features : null;
  8185. },
  8186. media: function () {
  8187. var features;
  8188. var rules;
  8189. var media;
  8190. var debugInfo;
  8191. var index = parserInput.i;
  8192. if (context.dumpLineNumbers) {
  8193. debugInfo = getDebugInfo(index);
  8194. }
  8195. parserInput.save();
  8196. if (parserInput.$str('@media')) {
  8197. features = this.mediaFeatures();
  8198. rules = this.block();
  8199. if (!rules) {
  8200. error('media definitions require block statements after any features');
  8201. }
  8202. parserInput.forget();
  8203. media = new (tree.Media)(rules, features, index, fileInfo);
  8204. if (context.dumpLineNumbers) {
  8205. media.debugInfo = debugInfo;
  8206. }
  8207. return media;
  8208. }
  8209. parserInput.restore();
  8210. },
  8211. //
  8212. // A @plugin directive, used to import plugins dynamically.
  8213. //
  8214. // @plugin (args) "lib";
  8215. //
  8216. plugin: function () {
  8217. var path;
  8218. var args;
  8219. var options;
  8220. var index = parserInput.i;
  8221. var dir = parserInput.$re(/^@plugin?\s+/);
  8222. if (dir) {
  8223. args = this.pluginArgs();
  8224. if (args) {
  8225. options = {
  8226. pluginArgs: args,
  8227. isPlugin: true
  8228. };
  8229. }
  8230. else {
  8231. options = { isPlugin: true };
  8232. }
  8233. if ((path = this.entities.quoted() || this.entities.url())) {
  8234. if (!parserInput.$char(';')) {
  8235. parserInput.i = index;
  8236. error('missing semi-colon on @plugin');
  8237. }
  8238. return new (tree.Import)(path, null, options, index, fileInfo);
  8239. }
  8240. else {
  8241. parserInput.i = index;
  8242. error('malformed @plugin statement');
  8243. }
  8244. }
  8245. },
  8246. pluginArgs: function () {
  8247. // list of options, surrounded by parens
  8248. parserInput.save();
  8249. if (!parserInput.$char('(')) {
  8250. parserInput.restore();
  8251. return null;
  8252. }
  8253. var args = parserInput.$re(/^\s*([^\);]+)\)\s*/);
  8254. if (args[1]) {
  8255. parserInput.forget();
  8256. return args[1].trim();
  8257. }
  8258. else {
  8259. parserInput.restore();
  8260. return null;
  8261. }
  8262. },
  8263. //
  8264. // A CSS AtRule
  8265. //
  8266. // @charset "utf-8";
  8267. //
  8268. atrule: function () {
  8269. var index = parserInput.i;
  8270. var name;
  8271. var value;
  8272. var rules;
  8273. var nonVendorSpecificName;
  8274. var hasIdentifier;
  8275. var hasExpression;
  8276. var hasUnknown;
  8277. var hasBlock = true;
  8278. var isRooted = true;
  8279. if (parserInput.currentChar() !== '@') {
  8280. return;
  8281. }
  8282. value = this['import']() || this.plugin() || this.media();
  8283. if (value) {
  8284. return value;
  8285. }
  8286. parserInput.save();
  8287. name = parserInput.$re(/^@[a-z-]+/);
  8288. if (!name) {
  8289. return;
  8290. }
  8291. nonVendorSpecificName = name;
  8292. if (name.charAt(1) == '-' && name.indexOf('-', 2) > 0) {
  8293. nonVendorSpecificName = "@" + name.slice(name.indexOf('-', 2) + 1);
  8294. }
  8295. switch (nonVendorSpecificName) {
  8296. case '@charset':
  8297. hasIdentifier = true;
  8298. hasBlock = false;
  8299. break;
  8300. case '@namespace':
  8301. hasExpression = true;
  8302. hasBlock = false;
  8303. break;
  8304. case '@keyframes':
  8305. case '@counter-style':
  8306. hasIdentifier = true;
  8307. break;
  8308. case '@document':
  8309. case '@supports':
  8310. hasUnknown = true;
  8311. isRooted = false;
  8312. break;
  8313. default:
  8314. hasUnknown = true;
  8315. break;
  8316. }
  8317. parserInput.commentStore.length = 0;
  8318. if (hasIdentifier) {
  8319. value = this.entity();
  8320. if (!value) {
  8321. error("expected " + name + " identifier");
  8322. }
  8323. }
  8324. else if (hasExpression) {
  8325. value = this.expression();
  8326. if (!value) {
  8327. error("expected " + name + " expression");
  8328. }
  8329. }
  8330. else if (hasUnknown) {
  8331. value = this.permissiveValue(/^[{;]/);
  8332. hasBlock = (parserInput.currentChar() === '{');
  8333. if (!value) {
  8334. if (!hasBlock && parserInput.currentChar() !== ';') {
  8335. error(name + " rule is missing block or ending semi-colon");
  8336. }
  8337. }
  8338. else if (!value.value) {
  8339. value = null;
  8340. }
  8341. }
  8342. if (hasBlock) {
  8343. rules = this.blockRuleset();
  8344. }
  8345. if (rules || (!hasBlock && value && parserInput.$char(';'))) {
  8346. parserInput.forget();
  8347. return new (tree.AtRule)(name, value, rules, index, fileInfo, context.dumpLineNumbers ? getDebugInfo(index) : null, isRooted);
  8348. }
  8349. parserInput.restore('at-rule options not recognised');
  8350. },
  8351. //
  8352. // A Value is a comma-delimited list of Expressions
  8353. //
  8354. // font-family: Baskerville, Georgia, serif;
  8355. //
  8356. // In a Rule, a Value represents everything after the `:`,
  8357. // and before the `;`.
  8358. //
  8359. value: function () {
  8360. var e;
  8361. var expressions = [];
  8362. var index = parserInput.i;
  8363. do {
  8364. e = this.expression();
  8365. if (e) {
  8366. expressions.push(e);
  8367. if (!parserInput.$char(',')) {
  8368. break;
  8369. }
  8370. }
  8371. } while (e);
  8372. if (expressions.length > 0) {
  8373. return new (tree.Value)(expressions, index);
  8374. }
  8375. },
  8376. important: function () {
  8377. if (parserInput.currentChar() === '!') {
  8378. return parserInput.$re(/^! *important/);
  8379. }
  8380. },
  8381. sub: function () {
  8382. var a;
  8383. var e;
  8384. parserInput.save();
  8385. if (parserInput.$char('(')) {
  8386. a = this.addition();
  8387. if (a && parserInput.$char(')')) {
  8388. parserInput.forget();
  8389. e = new (tree.Expression)([a]);
  8390. e.parens = true;
  8391. return e;
  8392. }
  8393. parserInput.restore('Expected \')\'');
  8394. return;
  8395. }
  8396. parserInput.restore();
  8397. },
  8398. multiplication: function () {
  8399. var m;
  8400. var a;
  8401. var op;
  8402. var operation;
  8403. var isSpaced;
  8404. m = this.operand();
  8405. if (m) {
  8406. isSpaced = parserInput.isWhitespace(-1);
  8407. while (true) {
  8408. if (parserInput.peek(/^\/[*\/]/)) {
  8409. break;
  8410. }
  8411. parserInput.save();
  8412. op = parserInput.$char('/') || parserInput.$char('*') || parserInput.$str('./');
  8413. if (!op) {
  8414. parserInput.forget();
  8415. break;
  8416. }
  8417. a = this.operand();
  8418. if (!a) {
  8419. parserInput.restore();
  8420. break;
  8421. }
  8422. parserInput.forget();
  8423. m.parensInOp = true;
  8424. a.parensInOp = true;
  8425. operation = new (tree.Operation)(op, [operation || m, a], isSpaced);
  8426. isSpaced = parserInput.isWhitespace(-1);
  8427. }
  8428. return operation || m;
  8429. }
  8430. },
  8431. addition: function () {
  8432. var m;
  8433. var a;
  8434. var op;
  8435. var operation;
  8436. var isSpaced;
  8437. m = this.multiplication();
  8438. if (m) {
  8439. isSpaced = parserInput.isWhitespace(-1);
  8440. while (true) {
  8441. op = parserInput.$re(/^[-+]\s+/) || (!isSpaced && (parserInput.$char('+') || parserInput.$char('-')));
  8442. if (!op) {
  8443. break;
  8444. }
  8445. a = this.multiplication();
  8446. if (!a) {
  8447. break;
  8448. }
  8449. m.parensInOp = true;
  8450. a.parensInOp = true;
  8451. operation = new (tree.Operation)(op, [operation || m, a], isSpaced);
  8452. isSpaced = parserInput.isWhitespace(-1);
  8453. }
  8454. return operation || m;
  8455. }
  8456. },
  8457. conditions: function () {
  8458. var a;
  8459. var b;
  8460. var index = parserInput.i;
  8461. var condition;
  8462. a = this.condition(true);
  8463. if (a) {
  8464. while (true) {
  8465. if (!parserInput.peek(/^,\s*(not\s*)?\(/) || !parserInput.$char(',')) {
  8466. break;
  8467. }
  8468. b = this.condition(true);
  8469. if (!b) {
  8470. break;
  8471. }
  8472. condition = new (tree.Condition)('or', condition || a, b, index);
  8473. }
  8474. return condition || a;
  8475. }
  8476. },
  8477. condition: function (needsParens) {
  8478. var result;
  8479. var logical;
  8480. var next;
  8481. function or() {
  8482. return parserInput.$str('or');
  8483. }
  8484. result = this.conditionAnd(needsParens);
  8485. if (!result) {
  8486. return;
  8487. }
  8488. logical = or();
  8489. if (logical) {
  8490. next = this.condition(needsParens);
  8491. if (next) {
  8492. result = new (tree.Condition)(logical, result, next);
  8493. }
  8494. else {
  8495. return;
  8496. }
  8497. }
  8498. return result;
  8499. },
  8500. conditionAnd: function (needsParens) {
  8501. var result;
  8502. var logical;
  8503. var next;
  8504. var self = this;
  8505. function insideCondition() {
  8506. var cond = self.negatedCondition(needsParens) || self.parenthesisCondition(needsParens);
  8507. if (!cond && !needsParens) {
  8508. return self.atomicCondition(needsParens);
  8509. }
  8510. return cond;
  8511. }
  8512. function and() {
  8513. return parserInput.$str('and');
  8514. }
  8515. result = insideCondition();
  8516. if (!result) {
  8517. return;
  8518. }
  8519. logical = and();
  8520. if (logical) {
  8521. next = this.conditionAnd(needsParens);
  8522. if (next) {
  8523. result = new (tree.Condition)(logical, result, next);
  8524. }
  8525. else {
  8526. return;
  8527. }
  8528. }
  8529. return result;
  8530. },
  8531. negatedCondition: function (needsParens) {
  8532. if (parserInput.$str('not')) {
  8533. var result = this.parenthesisCondition(needsParens);
  8534. if (result) {
  8535. result.negate = !result.negate;
  8536. }
  8537. return result;
  8538. }
  8539. },
  8540. parenthesisCondition: function (needsParens) {
  8541. function tryConditionFollowedByParenthesis(me) {
  8542. var body;
  8543. parserInput.save();
  8544. body = me.condition(needsParens);
  8545. if (!body) {
  8546. parserInput.restore();
  8547. return;
  8548. }
  8549. if (!parserInput.$char(')')) {
  8550. parserInput.restore();
  8551. return;
  8552. }
  8553. parserInput.forget();
  8554. return body;
  8555. }
  8556. var body;
  8557. parserInput.save();
  8558. if (!parserInput.$str('(')) {
  8559. parserInput.restore();
  8560. return;
  8561. }
  8562. body = tryConditionFollowedByParenthesis(this);
  8563. if (body) {
  8564. parserInput.forget();
  8565. return body;
  8566. }
  8567. body = this.atomicCondition(needsParens);
  8568. if (!body) {
  8569. parserInput.restore();
  8570. return;
  8571. }
  8572. if (!parserInput.$char(')')) {
  8573. parserInput.restore("expected ')' got '" + parserInput.currentChar() + "'");
  8574. return;
  8575. }
  8576. parserInput.forget();
  8577. return body;
  8578. },
  8579. atomicCondition: function (needsParens) {
  8580. var entities = this.entities;
  8581. var index = parserInput.i;
  8582. var a;
  8583. var b;
  8584. var c;
  8585. var op;
  8586. function cond() {
  8587. return this.addition() || entities.keyword() || entities.quoted() || entities.mixinLookup();
  8588. }
  8589. cond = cond.bind(this);
  8590. a = cond();
  8591. if (a) {
  8592. if (parserInput.$char('>')) {
  8593. if (parserInput.$char('=')) {
  8594. op = '>=';
  8595. }
  8596. else {
  8597. op = '>';
  8598. }
  8599. }
  8600. else if (parserInput.$char('<')) {
  8601. if (parserInput.$char('=')) {
  8602. op = '<=';
  8603. }
  8604. else {
  8605. op = '<';
  8606. }
  8607. }
  8608. else if (parserInput.$char('=')) {
  8609. if (parserInput.$char('>')) {
  8610. op = '=>';
  8611. }
  8612. else if (parserInput.$char('<')) {
  8613. op = '=<';
  8614. }
  8615. else {
  8616. op = '=';
  8617. }
  8618. }
  8619. if (op) {
  8620. b = cond();
  8621. if (b) {
  8622. c = new (tree.Condition)(op, a, b, index, false);
  8623. }
  8624. else {
  8625. error('expected expression');
  8626. }
  8627. }
  8628. else {
  8629. c = new (tree.Condition)('=', a, new (tree.Keyword)('true'), index, false);
  8630. }
  8631. return c;
  8632. }
  8633. },
  8634. //
  8635. // An operand is anything that can be part of an operation,
  8636. // such as a Color, or a Variable
  8637. //
  8638. operand: function () {
  8639. var entities = this.entities;
  8640. var negate;
  8641. if (parserInput.peek(/^-[@\$\(]/)) {
  8642. negate = parserInput.$char('-');
  8643. }
  8644. var o = this.sub() || entities.dimension() ||
  8645. entities.color() || entities.variable() ||
  8646. entities.property() || entities.call() ||
  8647. entities.quoted(true) || entities.colorKeyword() ||
  8648. entities.mixinLookup();
  8649. if (negate) {
  8650. o.parensInOp = true;
  8651. o = new (tree.Negative)(o);
  8652. }
  8653. return o;
  8654. },
  8655. //
  8656. // Expressions either represent mathematical operations,
  8657. // or white-space delimited Entities.
  8658. //
  8659. // 1px solid black
  8660. // @var * 2
  8661. //
  8662. expression: function () {
  8663. var entities = [];
  8664. var e;
  8665. var delim;
  8666. var index = parserInput.i;
  8667. do {
  8668. e = this.comment();
  8669. if (e) {
  8670. entities.push(e);
  8671. continue;
  8672. }
  8673. e = this.addition() || this.entity();
  8674. if (e instanceof tree.Comment) {
  8675. e = null;
  8676. }
  8677. if (e) {
  8678. entities.push(e);
  8679. // operations do not allow keyword "/" dimension (e.g. small/20px) so we support that here
  8680. if (!parserInput.peek(/^\/[\/*]/)) {
  8681. delim = parserInput.$char('/');
  8682. if (delim) {
  8683. entities.push(new (tree.Anonymous)(delim, index));
  8684. }
  8685. }
  8686. }
  8687. } while (e);
  8688. if (entities.length > 0) {
  8689. return new (tree.Expression)(entities);
  8690. }
  8691. },
  8692. property: function () {
  8693. var name = parserInput.$re(/^(\*?-?[_a-zA-Z0-9-]+)\s*:/);
  8694. if (name) {
  8695. return name[1];
  8696. }
  8697. },
  8698. ruleProperty: function () {
  8699. var name = [];
  8700. var index = [];
  8701. var s;
  8702. var k;
  8703. parserInput.save();
  8704. var simpleProperty = parserInput.$re(/^([_a-zA-Z0-9-]+)\s*:/);
  8705. if (simpleProperty) {
  8706. name = [new (tree.Keyword)(simpleProperty[1])];
  8707. parserInput.forget();
  8708. return name;
  8709. }
  8710. function match(re) {
  8711. var i = parserInput.i;
  8712. var chunk = parserInput.$re(re);
  8713. if (chunk) {
  8714. index.push(i);
  8715. return name.push(chunk[1]);
  8716. }
  8717. }
  8718. match(/^(\*?)/);
  8719. while (true) {
  8720. if (!match(/^((?:[\w-]+)|(?:[@\$]\{[\w-]+\}))/)) {
  8721. break;
  8722. }
  8723. }
  8724. if ((name.length > 1) && match(/^((?:\+_|\+)?)\s*:/)) {
  8725. parserInput.forget();
  8726. // at last, we have the complete match now. move forward,
  8727. // convert name particles to tree objects and return:
  8728. if (name[0] === '') {
  8729. name.shift();
  8730. index.shift();
  8731. }
  8732. for (k = 0; k < name.length; k++) {
  8733. s = name[k];
  8734. name[k] = (s.charAt(0) !== '@' && s.charAt(0) !== '$') ?
  8735. new (tree.Keyword)(s) :
  8736. (s.charAt(0) === '@' ?
  8737. new (tree.Variable)("@" + s.slice(2, -1), index[k], fileInfo) :
  8738. new (tree.Property)("$" + s.slice(2, -1), index[k], fileInfo));
  8739. }
  8740. return name;
  8741. }
  8742. parserInput.restore();
  8743. }
  8744. }
  8745. };
  8746. };
  8747. Parser.serializeVars = function (vars) {
  8748. var s = '';
  8749. for (var name_1 in vars) {
  8750. if (Object.hasOwnProperty.call(vars, name_1)) {
  8751. var value = vars[name_1];
  8752. s += ((name_1[0] === '@') ? '' : '@') + name_1 + ": " + value + ((String(value).slice(-1) === ';') ? '' : ';');
  8753. }
  8754. }
  8755. return s;
  8756. };
  8757. function boolean(condition) {
  8758. return condition ? Keyword.True : Keyword.False;
  8759. }
  8760. /**
  8761. * Functions with evalArgs set to false are sent context
  8762. * as the first argument.
  8763. */
  8764. function If(context, condition, trueValue, falseValue) {
  8765. return condition.eval(context) ? trueValue.eval(context)
  8766. : (falseValue ? falseValue.eval(context) : new Anonymous);
  8767. }
  8768. If.evalArgs = false;
  8769. var boolean$1 = { boolean: boolean, 'if': If };
  8770. var colorFunctions;
  8771. function clamp$1(val) {
  8772. return Math.min(1, Math.max(0, val));
  8773. }
  8774. function hsla(origColor, hsl) {
  8775. var color = colorFunctions.hsla(hsl.h, hsl.s, hsl.l, hsl.a);
  8776. if (color) {
  8777. if (origColor.value &&
  8778. /^(rgb|hsl)/.test(origColor.value)) {
  8779. color.value = origColor.value;
  8780. }
  8781. else {
  8782. color.value = 'rgb';
  8783. }
  8784. return color;
  8785. }
  8786. }
  8787. function toHSL(color) {
  8788. if (color.toHSL) {
  8789. return color.toHSL();
  8790. }
  8791. else {
  8792. throw new Error('Argument cannot be evaluated to a color');
  8793. }
  8794. }
  8795. function toHSV(color) {
  8796. if (color.toHSV) {
  8797. return color.toHSV();
  8798. }
  8799. else {
  8800. throw new Error('Argument cannot be evaluated to a color');
  8801. }
  8802. }
  8803. function number(n) {
  8804. if (n instanceof Dimension) {
  8805. return parseFloat(n.unit.is('%') ? n.value / 100 : n.value);
  8806. }
  8807. else if (typeof n === 'number') {
  8808. return n;
  8809. }
  8810. else {
  8811. throw {
  8812. type: 'Argument',
  8813. message: 'color functions take numbers as parameters'
  8814. };
  8815. }
  8816. }
  8817. function scaled(n, size) {
  8818. if (n instanceof Dimension && n.unit.is('%')) {
  8819. return parseFloat(n.value * size / 100);
  8820. }
  8821. else {
  8822. return number(n);
  8823. }
  8824. }
  8825. colorFunctions = {
  8826. rgb: function (r, g, b) {
  8827. var color = colorFunctions.rgba(r, g, b, 1.0);
  8828. if (color) {
  8829. color.value = 'rgb';
  8830. return color;
  8831. }
  8832. },
  8833. rgba: function (r, g, b, a) {
  8834. try {
  8835. if (r instanceof Color) {
  8836. if (g) {
  8837. a = number(g);
  8838. }
  8839. else {
  8840. a = r.alpha;
  8841. }
  8842. return new Color(r.rgb, a, 'rgba');
  8843. }
  8844. var rgb = [r, g, b].map(function (c) { return scaled(c, 255); });
  8845. a = number(a);
  8846. return new Color(rgb, a, 'rgba');
  8847. }
  8848. catch (e) { }
  8849. },
  8850. hsl: function (h, s, l) {
  8851. var color = colorFunctions.hsla(h, s, l, 1.0);
  8852. if (color) {
  8853. color.value = 'hsl';
  8854. return color;
  8855. }
  8856. },
  8857. hsla: function (h, s, l, a) {
  8858. try {
  8859. if (h instanceof Color) {
  8860. if (s) {
  8861. a = number(s);
  8862. }
  8863. else {
  8864. a = h.alpha;
  8865. }
  8866. return new Color(h.rgb, a, 'hsla');
  8867. }
  8868. var m1_1;
  8869. var m2_1;
  8870. function hue(h) {
  8871. h = h < 0 ? h + 1 : (h > 1 ? h - 1 : h);
  8872. if (h * 6 < 1) {
  8873. return m1_1 + (m2_1 - m1_1) * h * 6;
  8874. }
  8875. else if (h * 2 < 1) {
  8876. return m2_1;
  8877. }
  8878. else if (h * 3 < 2) {
  8879. return m1_1 + (m2_1 - m1_1) * (2 / 3 - h) * 6;
  8880. }
  8881. else {
  8882. return m1_1;
  8883. }
  8884. }
  8885. h = (number(h) % 360) / 360;
  8886. s = clamp$1(number(s));
  8887. l = clamp$1(number(l));
  8888. a = clamp$1(number(a));
  8889. m2_1 = l <= 0.5 ? l * (s + 1) : l + s - l * s;
  8890. m1_1 = l * 2 - m2_1;
  8891. var rgb = [
  8892. hue(h + 1 / 3) * 255,
  8893. hue(h) * 255,
  8894. hue(h - 1 / 3) * 255
  8895. ];
  8896. a = number(a);
  8897. return new Color(rgb, a, 'hsla');
  8898. }
  8899. catch (e) { }
  8900. },
  8901. hsv: function (h, s, v) {
  8902. return colorFunctions.hsva(h, s, v, 1.0);
  8903. },
  8904. hsva: function (h, s, v, a) {
  8905. h = ((number(h) % 360) / 360) * 360;
  8906. s = number(s);
  8907. v = number(v);
  8908. a = number(a);
  8909. var i;
  8910. var f;
  8911. i = Math.floor((h / 60) % 6);
  8912. f = (h / 60) - i;
  8913. var vs = [v,
  8914. v * (1 - s),
  8915. v * (1 - f * s),
  8916. v * (1 - (1 - f) * s)];
  8917. var perm = [[0, 3, 1],
  8918. [2, 0, 1],
  8919. [1, 0, 3],
  8920. [1, 2, 0],
  8921. [3, 1, 0],
  8922. [0, 1, 2]];
  8923. return colorFunctions.rgba(vs[perm[i][0]] * 255, vs[perm[i][1]] * 255, vs[perm[i][2]] * 255, a);
  8924. },
  8925. hue: function (color) {
  8926. return new Dimension(toHSL(color).h);
  8927. },
  8928. saturation: function (color) {
  8929. return new Dimension(toHSL(color).s * 100, '%');
  8930. },
  8931. lightness: function (color) {
  8932. return new Dimension(toHSL(color).l * 100, '%');
  8933. },
  8934. hsvhue: function (color) {
  8935. return new Dimension(toHSV(color).h);
  8936. },
  8937. hsvsaturation: function (color) {
  8938. return new Dimension(toHSV(color).s * 100, '%');
  8939. },
  8940. hsvvalue: function (color) {
  8941. return new Dimension(toHSV(color).v * 100, '%');
  8942. },
  8943. red: function (color) {
  8944. return new Dimension(color.rgb[0]);
  8945. },
  8946. green: function (color) {
  8947. return new Dimension(color.rgb[1]);
  8948. },
  8949. blue: function (color) {
  8950. return new Dimension(color.rgb[2]);
  8951. },
  8952. alpha: function (color) {
  8953. return new Dimension(toHSL(color).a);
  8954. },
  8955. luma: function (color) {
  8956. return new Dimension(color.luma() * color.alpha * 100, '%');
  8957. },
  8958. luminance: function (color) {
  8959. var luminance = (0.2126 * color.rgb[0] / 255) +
  8960. (0.7152 * color.rgb[1] / 255) +
  8961. (0.0722 * color.rgb[2] / 255);
  8962. return new Dimension(luminance * color.alpha * 100, '%');
  8963. },
  8964. saturate: function (color, amount, method) {
  8965. // filter: saturate(3.2);
  8966. // should be kept as is, so check for color
  8967. if (!color.rgb) {
  8968. return null;
  8969. }
  8970. var hsl = toHSL(color);
  8971. if (typeof method !== 'undefined' && method.value === 'relative') {
  8972. hsl.s += hsl.s * amount.value / 100;
  8973. }
  8974. else {
  8975. hsl.s += amount.value / 100;
  8976. }
  8977. hsl.s = clamp$1(hsl.s);
  8978. return hsla(color, hsl);
  8979. },
  8980. desaturate: function (color, amount, method) {
  8981. var hsl = toHSL(color);
  8982. if (typeof method !== 'undefined' && method.value === 'relative') {
  8983. hsl.s -= hsl.s * amount.value / 100;
  8984. }
  8985. else {
  8986. hsl.s -= amount.value / 100;
  8987. }
  8988. hsl.s = clamp$1(hsl.s);
  8989. return hsla(color, hsl);
  8990. },
  8991. lighten: function (color, amount, method) {
  8992. var hsl = toHSL(color);
  8993. if (typeof method !== 'undefined' && method.value === 'relative') {
  8994. hsl.l += hsl.l * amount.value / 100;
  8995. }
  8996. else {
  8997. hsl.l += amount.value / 100;
  8998. }
  8999. hsl.l = clamp$1(hsl.l);
  9000. return hsla(color, hsl);
  9001. },
  9002. darken: function (color, amount, method) {
  9003. var hsl = toHSL(color);
  9004. if (typeof method !== 'undefined' && method.value === 'relative') {
  9005. hsl.l -= hsl.l * amount.value / 100;
  9006. }
  9007. else {
  9008. hsl.l -= amount.value / 100;
  9009. }
  9010. hsl.l = clamp$1(hsl.l);
  9011. return hsla(color, hsl);
  9012. },
  9013. fadein: function (color, amount, method) {
  9014. var hsl = toHSL(color);
  9015. if (typeof method !== 'undefined' && method.value === 'relative') {
  9016. hsl.a += hsl.a * amount.value / 100;
  9017. }
  9018. else {
  9019. hsl.a += amount.value / 100;
  9020. }
  9021. hsl.a = clamp$1(hsl.a);
  9022. return hsla(color, hsl);
  9023. },
  9024. fadeout: function (color, amount, method) {
  9025. var hsl = toHSL(color);
  9026. if (typeof method !== 'undefined' && method.value === 'relative') {
  9027. hsl.a -= hsl.a * amount.value / 100;
  9028. }
  9029. else {
  9030. hsl.a -= amount.value / 100;
  9031. }
  9032. hsl.a = clamp$1(hsl.a);
  9033. return hsla(color, hsl);
  9034. },
  9035. fade: function (color, amount) {
  9036. var hsl = toHSL(color);
  9037. hsl.a = amount.value / 100;
  9038. hsl.a = clamp$1(hsl.a);
  9039. return hsla(color, hsl);
  9040. },
  9041. spin: function (color, amount) {
  9042. var hsl = toHSL(color);
  9043. var hue = (hsl.h + amount.value) % 360;
  9044. hsl.h = hue < 0 ? 360 + hue : hue;
  9045. return hsla(color, hsl);
  9046. },
  9047. //
  9048. // Copyright (c) 2006-2009 Hampton Catlin, Natalie Weizenbaum, and Chris Eppstein
  9049. // http://sass-lang.com
  9050. //
  9051. mix: function (color1, color2, weight) {
  9052. if (!weight) {
  9053. weight = new Dimension(50);
  9054. }
  9055. var p = weight.value / 100.0;
  9056. var w = p * 2 - 1;
  9057. var a = toHSL(color1).a - toHSL(color2).a;
  9058. var w1 = (((w * a == -1) ? w : (w + a) / (1 + w * a)) + 1) / 2.0;
  9059. var w2 = 1 - w1;
  9060. var rgb = [color1.rgb[0] * w1 + color2.rgb[0] * w2,
  9061. color1.rgb[1] * w1 + color2.rgb[1] * w2,
  9062. color1.rgb[2] * w1 + color2.rgb[2] * w2];
  9063. var alpha = color1.alpha * p + color2.alpha * (1 - p);
  9064. return new Color(rgb, alpha);
  9065. },
  9066. greyscale: function (color) {
  9067. return colorFunctions.desaturate(color, new Dimension(100));
  9068. },
  9069. contrast: function (color, dark, light, threshold) {
  9070. // filter: contrast(3.2);
  9071. // should be kept as is, so check for color
  9072. if (!color.rgb) {
  9073. return null;
  9074. }
  9075. if (typeof light === 'undefined') {
  9076. light = colorFunctions.rgba(255, 255, 255, 1.0);
  9077. }
  9078. if (typeof dark === 'undefined') {
  9079. dark = colorFunctions.rgba(0, 0, 0, 1.0);
  9080. }
  9081. // Figure out which is actually light and dark:
  9082. if (dark.luma() > light.luma()) {
  9083. var t = light;
  9084. light = dark;
  9085. dark = t;
  9086. }
  9087. if (typeof threshold === 'undefined') {
  9088. threshold = 0.43;
  9089. }
  9090. else {
  9091. threshold = number(threshold);
  9092. }
  9093. if (color.luma() < threshold) {
  9094. return light;
  9095. }
  9096. else {
  9097. return dark;
  9098. }
  9099. },
  9100. // Changes made in 2.7.0 - Reverted in 3.0.0
  9101. // contrast: function (color, color1, color2, threshold) {
  9102. // // Return which of `color1` and `color2` has the greatest contrast with `color`
  9103. // // according to the standard WCAG contrast ratio calculation.
  9104. // // http://www.w3.org/TR/WCAG20/#contrast-ratiodef
  9105. // // The threshold param is no longer used, in line with SASS.
  9106. // // filter: contrast(3.2);
  9107. // // should be kept as is, so check for color
  9108. // if (!color.rgb) {
  9109. // return null;
  9110. // }
  9111. // if (typeof color1 === 'undefined') {
  9112. // color1 = colorFunctions.rgba(0, 0, 0, 1.0);
  9113. // }
  9114. // if (typeof color2 === 'undefined') {
  9115. // color2 = colorFunctions.rgba(255, 255, 255, 1.0);
  9116. // }
  9117. // var contrast1, contrast2;
  9118. // var luma = color.luma();
  9119. // var luma1 = color1.luma();
  9120. // var luma2 = color2.luma();
  9121. // // Calculate contrast ratios for each color
  9122. // if (luma > luma1) {
  9123. // contrast1 = (luma + 0.05) / (luma1 + 0.05);
  9124. // } else {
  9125. // contrast1 = (luma1 + 0.05) / (luma + 0.05);
  9126. // }
  9127. // if (luma > luma2) {
  9128. // contrast2 = (luma + 0.05) / (luma2 + 0.05);
  9129. // } else {
  9130. // contrast2 = (luma2 + 0.05) / (luma + 0.05);
  9131. // }
  9132. // if (contrast1 > contrast2) {
  9133. // return color1;
  9134. // } else {
  9135. // return color2;
  9136. // }
  9137. // },
  9138. argb: function (color) {
  9139. return new Anonymous(color.toARGB());
  9140. },
  9141. color: function (c) {
  9142. if ((c instanceof Quoted) &&
  9143. (/^#([A-Fa-f0-9]{8}|[A-Fa-f0-9]{6}|[A-Fa-f0-9]{3,4})$/i.test(c.value))) {
  9144. var val = c.value.slice(1);
  9145. return new Color(val, undefined, "#" + val);
  9146. }
  9147. if ((c instanceof Color) || (c = Color.fromKeyword(c.value))) {
  9148. c.value = undefined;
  9149. return c;
  9150. }
  9151. throw {
  9152. type: 'Argument',
  9153. message: 'argument must be a color keyword or 3|4|6|8 digit hex e.g. #FFF'
  9154. };
  9155. },
  9156. tint: function (color, amount) {
  9157. return colorFunctions.mix(colorFunctions.rgb(255, 255, 255), color, amount);
  9158. },
  9159. shade: function (color, amount) {
  9160. return colorFunctions.mix(colorFunctions.rgb(0, 0, 0), color, amount);
  9161. }
  9162. };
  9163. var color = colorFunctions;
  9164. // Color Blending
  9165. // ref: http://www.w3.org/TR/compositing-1
  9166. function colorBlend(mode, color1, color2) {
  9167. var ab = color1.alpha; // result
  9168. var // backdrop
  9169. cb;
  9170. var as = color2.alpha;
  9171. var // source
  9172. cs;
  9173. var ar;
  9174. var cr;
  9175. var r = [];
  9176. ar = as + ab * (1 - as);
  9177. for (var i = 0; i < 3; i++) {
  9178. cb = color1.rgb[i] / 255;
  9179. cs = color2.rgb[i] / 255;
  9180. cr = mode(cb, cs);
  9181. if (ar) {
  9182. cr = (as * cs + ab * (cb -
  9183. as * (cb + cs - cr))) / ar;
  9184. }
  9185. r[i] = cr * 255;
  9186. }
  9187. return new Color(r, ar);
  9188. }
  9189. var colorBlendModeFunctions = {
  9190. multiply: function (cb, cs) {
  9191. return cb * cs;
  9192. },
  9193. screen: function (cb, cs) {
  9194. return cb + cs - cb * cs;
  9195. },
  9196. overlay: function (cb, cs) {
  9197. cb *= 2;
  9198. return (cb <= 1) ?
  9199. colorBlendModeFunctions.multiply(cb, cs) :
  9200. colorBlendModeFunctions.screen(cb - 1, cs);
  9201. },
  9202. softlight: function (cb, cs) {
  9203. var d = 1;
  9204. var e = cb;
  9205. if (cs > 0.5) {
  9206. e = 1;
  9207. d = (cb > 0.25) ? Math.sqrt(cb)
  9208. : ((16 * cb - 12) * cb + 4) * cb;
  9209. }
  9210. return cb - (1 - 2 * cs) * e * (d - cb);
  9211. },
  9212. hardlight: function (cb, cs) {
  9213. return colorBlendModeFunctions.overlay(cs, cb);
  9214. },
  9215. difference: function (cb, cs) {
  9216. return Math.abs(cb - cs);
  9217. },
  9218. exclusion: function (cb, cs) {
  9219. return cb + cs - 2 * cb * cs;
  9220. },
  9221. // non-w3c functions:
  9222. average: function (cb, cs) {
  9223. return (cb + cs) / 2;
  9224. },
  9225. negation: function (cb, cs) {
  9226. return 1 - Math.abs(cb + cs - 1);
  9227. }
  9228. };
  9229. for (var f in colorBlendModeFunctions) {
  9230. if (colorBlendModeFunctions.hasOwnProperty(f)) {
  9231. colorBlend[f] = colorBlend.bind(null, colorBlendModeFunctions[f]);
  9232. }
  9233. }
  9234. var dataUri = (function (environment) {
  9235. var fallback = function (functionThis, node) { return new URL(node, functionThis.index, functionThis.currentFileInfo).eval(functionThis.context); };
  9236. return { 'data-uri': function (mimetypeNode, filePathNode) {
  9237. if (!filePathNode) {
  9238. filePathNode = mimetypeNode;
  9239. mimetypeNode = null;
  9240. }
  9241. var mimetype = mimetypeNode && mimetypeNode.value;
  9242. var filePath = filePathNode.value;
  9243. var currentFileInfo = this.currentFileInfo;
  9244. var currentDirectory = currentFileInfo.rewriteUrls ?
  9245. currentFileInfo.currentDirectory : currentFileInfo.entryPath;
  9246. var fragmentStart = filePath.indexOf('#');
  9247. var fragment = '';
  9248. if (fragmentStart !== -1) {
  9249. fragment = filePath.slice(fragmentStart);
  9250. filePath = filePath.slice(0, fragmentStart);
  9251. }
  9252. var context = clone(this.context);
  9253. context.rawBuffer = true;
  9254. var fileManager = environment.getFileManager(filePath, currentDirectory, context, environment, true);
  9255. if (!fileManager) {
  9256. return fallback(this, filePathNode);
  9257. }
  9258. var useBase64 = false;
  9259. // detect the mimetype if not given
  9260. if (!mimetypeNode) {
  9261. mimetype = environment.mimeLookup(filePath);
  9262. if (mimetype === 'image/svg+xml') {
  9263. useBase64 = false;
  9264. }
  9265. else {
  9266. // use base 64 unless it's an ASCII or UTF-8 format
  9267. var charset = environment.charsetLookup(mimetype);
  9268. useBase64 = ['US-ASCII', 'UTF-8'].indexOf(charset) < 0;
  9269. }
  9270. if (useBase64) {
  9271. mimetype += ';base64';
  9272. }
  9273. }
  9274. else {
  9275. useBase64 = /;base64$/.test(mimetype);
  9276. }
  9277. var fileSync = fileManager.loadFileSync(filePath, currentDirectory, context, environment);
  9278. if (!fileSync.contents) {
  9279. logger.warn("Skipped data-uri embedding of " + filePath + " because file not found");
  9280. return fallback(this, filePathNode || mimetypeNode);
  9281. }
  9282. var buf = fileSync.contents;
  9283. if (useBase64 && !environment.encodeBase64) {
  9284. return fallback(this, filePathNode);
  9285. }
  9286. buf = useBase64 ? environment.encodeBase64(buf) : encodeURIComponent(buf);
  9287. var uri = "data:" + mimetype + "," + buf + fragment;
  9288. return new URL(new Quoted("\"" + uri + "\"", uri, false, this.index, this.currentFileInfo), this.index, this.currentFileInfo);
  9289. } };
  9290. });
  9291. var getItemsFromNode = function (node) {
  9292. // handle non-array values as an array of length 1
  9293. // return 'undefined' if index is invalid
  9294. var items = Array.isArray(node.value) ?
  9295. node.value : Array(node);
  9296. return items;
  9297. };
  9298. var list = {
  9299. _SELF: function (n) {
  9300. return n;
  9301. },
  9302. extract: function (values, index) {
  9303. // (1-based index)
  9304. index = index.value - 1;
  9305. return getItemsFromNode(values)[index];
  9306. },
  9307. length: function (values) {
  9308. return new Dimension(getItemsFromNode(values).length);
  9309. },
  9310. /**
  9311. * Creates a Less list of incremental values.
  9312. * Modeled after Lodash's range function, also exists natively in PHP
  9313. *
  9314. * @param {Dimension} [start=1]
  9315. * @param {Dimension} end - e.g. 10 or 10px - unit is added to output
  9316. * @param {Dimension} [step=1]
  9317. */
  9318. range: function (start, end, step) {
  9319. var from;
  9320. var to;
  9321. var stepValue = 1;
  9322. var list = [];
  9323. if (end) {
  9324. to = end;
  9325. from = start.value;
  9326. if (step) {
  9327. stepValue = step.value;
  9328. }
  9329. }
  9330. else {
  9331. from = 1;
  9332. to = start;
  9333. }
  9334. for (var i = from; i <= to.value; i += stepValue) {
  9335. list.push(new Dimension(i, to.unit));
  9336. }
  9337. return new Expression(list);
  9338. },
  9339. each: function (list, rs) {
  9340. var rules = [];
  9341. var newRules;
  9342. var iterator;
  9343. if (list.value && !(list instanceof Quoted)) {
  9344. if (Array.isArray(list.value)) {
  9345. iterator = list.value;
  9346. }
  9347. else {
  9348. iterator = [list.value];
  9349. }
  9350. }
  9351. else if (list.ruleset) {
  9352. iterator = list.ruleset.rules;
  9353. }
  9354. else if (list.rules) {
  9355. iterator = list.rules;
  9356. }
  9357. else if (Array.isArray(list)) {
  9358. iterator = list;
  9359. }
  9360. else {
  9361. iterator = [list];
  9362. }
  9363. var valueName = '@value';
  9364. var keyName = '@key';
  9365. var indexName = '@index';
  9366. if (rs.params) {
  9367. valueName = rs.params[0] && rs.params[0].name;
  9368. keyName = rs.params[1] && rs.params[1].name;
  9369. indexName = rs.params[2] && rs.params[2].name;
  9370. rs = rs.rules;
  9371. }
  9372. else {
  9373. rs = rs.ruleset;
  9374. }
  9375. for (var i = 0; i < iterator.length; i++) {
  9376. var key = void 0;
  9377. var value = void 0;
  9378. var item = iterator[i];
  9379. if (item instanceof Declaration) {
  9380. key = typeof item.name === 'string' ? item.name : item.name[0].value;
  9381. value = item.value;
  9382. }
  9383. else {
  9384. key = new Dimension(i + 1);
  9385. value = item;
  9386. }
  9387. if (item instanceof Comment) {
  9388. continue;
  9389. }
  9390. newRules = rs.rules.slice(0);
  9391. if (valueName) {
  9392. newRules.push(new Declaration(valueName, value, false, false, this.index, this.currentFileInfo));
  9393. }
  9394. if (indexName) {
  9395. newRules.push(new Declaration(indexName, new Dimension(i + 1), false, false, this.index, this.currentFileInfo));
  9396. }
  9397. if (keyName) {
  9398. newRules.push(new Declaration(keyName, key, false, false, this.index, this.currentFileInfo));
  9399. }
  9400. rules.push(new Ruleset([new (Selector)([new Element("", '&')])], newRules, rs.strictImports, rs.visibilityInfo()));
  9401. }
  9402. return new Ruleset([new (Selector)([new Element("", '&')])], rules, rs.strictImports, rs.visibilityInfo()).eval(this.context);
  9403. }
  9404. };
  9405. var MathHelper = function (fn, unit, n) {
  9406. if (!(n instanceof Dimension)) {
  9407. throw { type: 'Argument', message: 'argument must be a number' };
  9408. }
  9409. if (unit == null) {
  9410. unit = n.unit;
  9411. }
  9412. else {
  9413. n = n.unify();
  9414. }
  9415. return new Dimension(fn(parseFloat(n.value)), unit);
  9416. };
  9417. var mathFunctions = {
  9418. // name, unit
  9419. ceil: null,
  9420. floor: null,
  9421. sqrt: null,
  9422. abs: null,
  9423. tan: '',
  9424. sin: '',
  9425. cos: '',
  9426. atan: 'rad',
  9427. asin: 'rad',
  9428. acos: 'rad'
  9429. };
  9430. for (var f$1 in mathFunctions) {
  9431. if (mathFunctions.hasOwnProperty(f$1)) {
  9432. mathFunctions[f$1] = MathHelper.bind(null, Math[f$1], mathFunctions[f$1]);
  9433. }
  9434. }
  9435. mathFunctions.round = function (n, f) {
  9436. var fraction = typeof f === 'undefined' ? 0 : f.value;
  9437. return MathHelper(function (num) { return num.toFixed(fraction); }, null, n);
  9438. };
  9439. var minMax = function (isMin, args) {
  9440. args = Array.prototype.slice.call(args);
  9441. switch (args.length) {
  9442. case 0: throw { type: 'Argument', message: 'one or more arguments required' };
  9443. }
  9444. var i; // key is the unit.toString() for unified Dimension values,
  9445. var j;
  9446. var current;
  9447. var currentUnified;
  9448. var referenceUnified;
  9449. var unit;
  9450. var unitStatic;
  9451. var unitClone;
  9452. var // elems only contains original argument values.
  9453. order = [];
  9454. var values = {};
  9455. // value is the index into the order array.
  9456. for (i = 0; i < args.length; i++) {
  9457. current = args[i];
  9458. if (!(current instanceof Dimension)) {
  9459. if (Array.isArray(args[i].value)) {
  9460. Array.prototype.push.apply(args, Array.prototype.slice.call(args[i].value));
  9461. }
  9462. continue;
  9463. }
  9464. currentUnified = current.unit.toString() === '' && unitClone !== undefined ? new Dimension(current.value, unitClone).unify() : current.unify();
  9465. unit = currentUnified.unit.toString() === '' && unitStatic !== undefined ? unitStatic : currentUnified.unit.toString();
  9466. unitStatic = unit !== '' && unitStatic === undefined || unit !== '' && order[0].unify().unit.toString() === '' ? unit : unitStatic;
  9467. unitClone = unit !== '' && unitClone === undefined ? current.unit.toString() : unitClone;
  9468. j = values[''] !== undefined && unit !== '' && unit === unitStatic ? values[''] : values[unit];
  9469. if (j === undefined) {
  9470. if (unitStatic !== undefined && unit !== unitStatic) {
  9471. throw { type: 'Argument', message: 'incompatible types' };
  9472. }
  9473. values[unit] = order.length;
  9474. order.push(current);
  9475. continue;
  9476. }
  9477. referenceUnified = order[j].unit.toString() === '' && unitClone !== undefined ? new Dimension(order[j].value, unitClone).unify() : order[j].unify();
  9478. if (isMin && currentUnified.value < referenceUnified.value ||
  9479. !isMin && currentUnified.value > referenceUnified.value) {
  9480. order[j] = current;
  9481. }
  9482. }
  9483. if (order.length == 1) {
  9484. return order[0];
  9485. }
  9486. args = order.map(function (a) { return a.toCSS(this.context); }).join(this.context.compress ? ',' : ', ');
  9487. return new Anonymous((isMin ? 'min' : 'max') + "(" + args + ")");
  9488. };
  9489. var number$1 = {
  9490. min: function () {
  9491. var args = [];
  9492. for (var _i = 0; _i < arguments.length; _i++) {
  9493. args[_i] = arguments[_i];
  9494. }
  9495. return minMax(true, args);
  9496. },
  9497. max: function () {
  9498. var args = [];
  9499. for (var _i = 0; _i < arguments.length; _i++) {
  9500. args[_i] = arguments[_i];
  9501. }
  9502. return minMax(false, args);
  9503. },
  9504. convert: function (val, unit) {
  9505. return val.convertTo(unit.value);
  9506. },
  9507. pi: function () {
  9508. return new Dimension(Math.PI);
  9509. },
  9510. mod: function (a, b) {
  9511. return new Dimension(a.value % b.value, a.unit);
  9512. },
  9513. pow: function (x, y) {
  9514. if (typeof x === 'number' && typeof y === 'number') {
  9515. x = new Dimension(x);
  9516. y = new Dimension(y);
  9517. }
  9518. else if (!(x instanceof Dimension) || !(y instanceof Dimension)) {
  9519. throw { type: 'Argument', message: 'arguments must be numbers' };
  9520. }
  9521. return new Dimension(Math.pow(x.value, y.value), x.unit);
  9522. },
  9523. percentage: function (n) {
  9524. var result = MathHelper(function (num) { return num * 100; }, '%', n);
  9525. return result;
  9526. }
  9527. };
  9528. var string = {
  9529. e: function (str) {
  9530. return new Quoted('"', str instanceof JavaScript ? str.evaluated : str.value, true);
  9531. },
  9532. escape: function (str) {
  9533. return new Anonymous(encodeURI(str.value).replace(/=/g, '%3D').replace(/:/g, '%3A').replace(/#/g, '%23').replace(/;/g, '%3B')
  9534. .replace(/\(/g, '%28').replace(/\)/g, '%29'));
  9535. },
  9536. replace: function (string, pattern, replacement, flags) {
  9537. var result = string.value;
  9538. replacement = (replacement.type === 'Quoted') ?
  9539. replacement.value : replacement.toCSS();
  9540. result = result.replace(new RegExp(pattern.value, flags ? flags.value : ''), replacement);
  9541. return new Quoted(string.quote || '', result, string.escaped);
  9542. },
  9543. '%': function (string /* arg, arg, ... */) {
  9544. var args = Array.prototype.slice.call(arguments, 1);
  9545. var result = string.value;
  9546. var _loop_1 = function (i) {
  9547. /* jshint loopfunc:true */
  9548. result = result.replace(/%[sda]/i, function (token) {
  9549. var value = ((args[i].type === 'Quoted') &&
  9550. token.match(/s/i)) ? args[i].value : args[i].toCSS();
  9551. return token.match(/[A-Z]$/) ? encodeURIComponent(value) : value;
  9552. });
  9553. };
  9554. for (var i = 0; i < args.length; i++) {
  9555. _loop_1(i);
  9556. }
  9557. result = result.replace(/%%/g, '%');
  9558. return new Quoted(string.quote || '', result, string.escaped);
  9559. }
  9560. };
  9561. var svg = (function (environment) {
  9562. return { 'svg-gradient': function (direction) {
  9563. var stops;
  9564. var gradientDirectionSvg;
  9565. var gradientType = 'linear';
  9566. var rectangleDimension = 'x="0" y="0" width="1" height="1"';
  9567. var renderEnv = { compress: false };
  9568. var returner;
  9569. var directionValue = direction.toCSS(renderEnv);
  9570. var i;
  9571. var color;
  9572. var position;
  9573. var positionValue;
  9574. var alpha;
  9575. function throwArgumentDescriptor() {
  9576. throw { type: 'Argument',
  9577. message: 'svg-gradient expects direction, start_color [start_position], [color position,]...,' +
  9578. ' end_color [end_position] or direction, color list' };
  9579. }
  9580. if (arguments.length == 2) {
  9581. if (arguments[1].value.length < 2) {
  9582. throwArgumentDescriptor();
  9583. }
  9584. stops = arguments[1].value;
  9585. }
  9586. else if (arguments.length < 3) {
  9587. throwArgumentDescriptor();
  9588. }
  9589. else {
  9590. stops = Array.prototype.slice.call(arguments, 1);
  9591. }
  9592. switch (directionValue) {
  9593. case 'to bottom':
  9594. gradientDirectionSvg = 'x1="0%" y1="0%" x2="0%" y2="100%"';
  9595. break;
  9596. case 'to right':
  9597. gradientDirectionSvg = 'x1="0%" y1="0%" x2="100%" y2="0%"';
  9598. break;
  9599. case 'to bottom right':
  9600. gradientDirectionSvg = 'x1="0%" y1="0%" x2="100%" y2="100%"';
  9601. break;
  9602. case 'to top right':
  9603. gradientDirectionSvg = 'x1="0%" y1="100%" x2="100%" y2="0%"';
  9604. break;
  9605. case 'ellipse':
  9606. case 'ellipse at center':
  9607. gradientType = 'radial';
  9608. gradientDirectionSvg = 'cx="50%" cy="50%" r="75%"';
  9609. rectangleDimension = 'x="-50" y="-50" width="101" height="101"';
  9610. break;
  9611. default:
  9612. throw { type: 'Argument', message: 'svg-gradient direction must be \'to bottom\', \'to right\',' +
  9613. ' \'to bottom right\', \'to top right\' or \'ellipse at center\'' };
  9614. }
  9615. returner = "<svg xmlns=\"http://www.w3.org/2000/svg\" viewBox=\"0 0 1 1\"><" + gradientType + "Gradient id=\"g\" " + gradientDirectionSvg + ">";
  9616. for (i = 0; i < stops.length; i += 1) {
  9617. if (stops[i] instanceof Expression) {
  9618. color = stops[i].value[0];
  9619. position = stops[i].value[1];
  9620. }
  9621. else {
  9622. color = stops[i];
  9623. position = undefined;
  9624. }
  9625. if (!(color instanceof Color) || (!((i === 0 || i + 1 === stops.length) && position === undefined) && !(position instanceof Dimension))) {
  9626. throwArgumentDescriptor();
  9627. }
  9628. positionValue = position ? position.toCSS(renderEnv) : i === 0 ? '0%' : '100%';
  9629. alpha = color.alpha;
  9630. returner += "<stop offset=\"" + positionValue + "\" stop-color=\"" + color.toRGB() + "\"" + (alpha < 1 ? " stop-opacity=\"" + alpha + "\"" : '') + "/>";
  9631. }
  9632. returner += "</" + gradientType + "Gradient><rect " + rectangleDimension + " fill=\"url(#g)\" /></svg>";
  9633. returner = encodeURIComponent(returner);
  9634. returner = "data:image/svg+xml," + returner;
  9635. return new URL(new Quoted("'" + returner + "'", returner, false, this.index, this.currentFileInfo), this.index, this.currentFileInfo);
  9636. } };
  9637. });
  9638. var isa = function (n, Type) { return (n instanceof Type) ? Keyword.True : Keyword.False; };
  9639. var isunit = function (n, unit) {
  9640. if (unit === undefined) {
  9641. throw { type: 'Argument', message: 'missing the required second argument to isunit.' };
  9642. }
  9643. unit = typeof unit.value === 'string' ? unit.value : unit;
  9644. if (typeof unit !== 'string') {
  9645. throw { type: 'Argument', message: 'Second argument to isunit should be a unit or a string.' };
  9646. }
  9647. return (n instanceof Dimension) && n.unit.is(unit) ? Keyword.True : Keyword.False;
  9648. };
  9649. var types = {
  9650. isruleset: function (n) {
  9651. return isa(n, DetachedRuleset);
  9652. },
  9653. iscolor: function (n) {
  9654. return isa(n, Color);
  9655. },
  9656. isnumber: function (n) {
  9657. return isa(n, Dimension);
  9658. },
  9659. isstring: function (n) {
  9660. return isa(n, Quoted);
  9661. },
  9662. iskeyword: function (n) {
  9663. return isa(n, Keyword);
  9664. },
  9665. isurl: function (n) {
  9666. return isa(n, URL);
  9667. },
  9668. ispixel: function (n) {
  9669. return isunit(n, 'px');
  9670. },
  9671. ispercentage: function (n) {
  9672. return isunit(n, '%');
  9673. },
  9674. isem: function (n) {
  9675. return isunit(n, 'em');
  9676. },
  9677. isunit: isunit,
  9678. unit: function (val, unit) {
  9679. if (!(val instanceof Dimension)) {
  9680. throw { type: 'Argument', message: "the first argument to unit must be a number" + (val instanceof Operation ? '. Have you forgotten parenthesis?' : '') };
  9681. }
  9682. if (unit) {
  9683. if (unit instanceof Keyword) {
  9684. unit = unit.value;
  9685. }
  9686. else {
  9687. unit = unit.toCSS();
  9688. }
  9689. }
  9690. else {
  9691. unit = '';
  9692. }
  9693. return new Dimension(val.value, unit);
  9694. },
  9695. 'get-unit': function (n) {
  9696. return new Anonymous(n.unit);
  9697. }
  9698. };
  9699. var Functions = (function (environment) {
  9700. var functions = { functionRegistry: functionRegistry, functionCaller: functionCaller };
  9701. // register functions
  9702. functionRegistry.addMultiple(boolean$1);
  9703. functionRegistry.add('default', defaultFunc.eval.bind(defaultFunc));
  9704. functionRegistry.addMultiple(color);
  9705. functionRegistry.addMultiple(colorBlend);
  9706. functionRegistry.addMultiple(dataUri(environment));
  9707. functionRegistry.addMultiple(list);
  9708. functionRegistry.addMultiple(mathFunctions);
  9709. functionRegistry.addMultiple(number$1);
  9710. functionRegistry.addMultiple(string);
  9711. functionRegistry.addMultiple(svg());
  9712. functionRegistry.addMultiple(types);
  9713. return functions;
  9714. });
  9715. var sourceMapOutput = (function (environment) {
  9716. var SourceMapOutput = /** @class */ (function () {
  9717. function SourceMapOutput(options) {
  9718. this._css = [];
  9719. this._rootNode = options.rootNode;
  9720. this._contentsMap = options.contentsMap;
  9721. this._contentsIgnoredCharsMap = options.contentsIgnoredCharsMap;
  9722. if (options.sourceMapFilename) {
  9723. this._sourceMapFilename = options.sourceMapFilename.replace(/\\/g, '/');
  9724. }
  9725. this._outputFilename = options.outputFilename;
  9726. this.sourceMapURL = options.sourceMapURL;
  9727. if (options.sourceMapBasepath) {
  9728. this._sourceMapBasepath = options.sourceMapBasepath.replace(/\\/g, '/');
  9729. }
  9730. if (options.sourceMapRootpath) {
  9731. this._sourceMapRootpath = options.sourceMapRootpath.replace(/\\/g, '/');
  9732. if (this._sourceMapRootpath.charAt(this._sourceMapRootpath.length - 1) !== '/') {
  9733. this._sourceMapRootpath += '/';
  9734. }
  9735. }
  9736. else {
  9737. this._sourceMapRootpath = '';
  9738. }
  9739. this._outputSourceFiles = options.outputSourceFiles;
  9740. this._sourceMapGeneratorConstructor = environment.getSourceMapGenerator();
  9741. this._lineNumber = 0;
  9742. this._column = 0;
  9743. }
  9744. SourceMapOutput.prototype.removeBasepath = function (path) {
  9745. if (this._sourceMapBasepath && path.indexOf(this._sourceMapBasepath) === 0) {
  9746. path = path.substring(this._sourceMapBasepath.length);
  9747. if (path.charAt(0) === '\\' || path.charAt(0) === '/') {
  9748. path = path.substring(1);
  9749. }
  9750. }
  9751. return path;
  9752. };
  9753. SourceMapOutput.prototype.normalizeFilename = function (filename) {
  9754. filename = filename.replace(/\\/g, '/');
  9755. filename = this.removeBasepath(filename);
  9756. return (this._sourceMapRootpath || '') + filename;
  9757. };
  9758. SourceMapOutput.prototype.add = function (chunk, fileInfo, index, mapLines) {
  9759. // ignore adding empty strings
  9760. if (!chunk) {
  9761. return;
  9762. }
  9763. var lines;
  9764. var sourceLines;
  9765. var columns;
  9766. var sourceColumns;
  9767. var i;
  9768. if (fileInfo && fileInfo.filename) {
  9769. var inputSource = this._contentsMap[fileInfo.filename];
  9770. // remove vars/banner added to the top of the file
  9771. if (this._contentsIgnoredCharsMap[fileInfo.filename]) {
  9772. // adjust the index
  9773. index -= this._contentsIgnoredCharsMap[fileInfo.filename];
  9774. if (index < 0) {
  9775. index = 0;
  9776. }
  9777. // adjust the source
  9778. inputSource = inputSource.slice(this._contentsIgnoredCharsMap[fileInfo.filename]);
  9779. }
  9780. // ignore empty content
  9781. if (inputSource === undefined) {
  9782. return;
  9783. }
  9784. inputSource = inputSource.substring(0, index);
  9785. sourceLines = inputSource.split('\n');
  9786. sourceColumns = sourceLines[sourceLines.length - 1];
  9787. }
  9788. lines = chunk.split('\n');
  9789. columns = lines[lines.length - 1];
  9790. if (fileInfo && fileInfo.filename) {
  9791. if (!mapLines) {
  9792. this._sourceMapGenerator.addMapping({ generated: { line: this._lineNumber + 1, column: this._column },
  9793. original: { line: sourceLines.length, column: sourceColumns.length },
  9794. source: this.normalizeFilename(fileInfo.filename) });
  9795. }
  9796. else {
  9797. for (i = 0; i < lines.length; i++) {
  9798. this._sourceMapGenerator.addMapping({ generated: { line: this._lineNumber + i + 1, column: i === 0 ? this._column : 0 },
  9799. original: { line: sourceLines.length + i, column: i === 0 ? sourceColumns.length : 0 },
  9800. source: this.normalizeFilename(fileInfo.filename) });
  9801. }
  9802. }
  9803. }
  9804. if (lines.length === 1) {
  9805. this._column += columns.length;
  9806. }
  9807. else {
  9808. this._lineNumber += lines.length - 1;
  9809. this._column = columns.length;
  9810. }
  9811. this._css.push(chunk);
  9812. };
  9813. SourceMapOutput.prototype.isEmpty = function () {
  9814. return this._css.length === 0;
  9815. };
  9816. SourceMapOutput.prototype.toCSS = function (context) {
  9817. this._sourceMapGenerator = new this._sourceMapGeneratorConstructor({ file: this._outputFilename, sourceRoot: null });
  9818. if (this._outputSourceFiles) {
  9819. for (var filename in this._contentsMap) {
  9820. if (this._contentsMap.hasOwnProperty(filename)) {
  9821. var source = this._contentsMap[filename];
  9822. if (this._contentsIgnoredCharsMap[filename]) {
  9823. source = source.slice(this._contentsIgnoredCharsMap[filename]);
  9824. }
  9825. this._sourceMapGenerator.setSourceContent(this.normalizeFilename(filename), source);
  9826. }
  9827. }
  9828. }
  9829. this._rootNode.genCSS(context, this);
  9830. if (this._css.length > 0) {
  9831. var sourceMapURL = void 0;
  9832. var sourceMapContent = JSON.stringify(this._sourceMapGenerator.toJSON());
  9833. if (this.sourceMapURL) {
  9834. sourceMapURL = this.sourceMapURL;
  9835. }
  9836. else if (this._sourceMapFilename) {
  9837. sourceMapURL = this._sourceMapFilename;
  9838. }
  9839. this.sourceMapURL = sourceMapURL;
  9840. this.sourceMap = sourceMapContent;
  9841. }
  9842. return this._css.join('');
  9843. };
  9844. return SourceMapOutput;
  9845. }());
  9846. return SourceMapOutput;
  9847. });
  9848. var sourceMapBuilder = (function (SourceMapOutput, environment) {
  9849. var SourceMapBuilder = /** @class */ (function () {
  9850. function SourceMapBuilder(options) {
  9851. this.options = options;
  9852. }
  9853. SourceMapBuilder.prototype.toCSS = function (rootNode, options, imports) {
  9854. var sourceMapOutput = new SourceMapOutput({
  9855. contentsIgnoredCharsMap: imports.contentsIgnoredChars,
  9856. rootNode: rootNode,
  9857. contentsMap: imports.contents,
  9858. sourceMapFilename: this.options.sourceMapFilename,
  9859. sourceMapURL: this.options.sourceMapURL,
  9860. outputFilename: this.options.sourceMapOutputFilename,
  9861. sourceMapBasepath: this.options.sourceMapBasepath,
  9862. sourceMapRootpath: this.options.sourceMapRootpath,
  9863. outputSourceFiles: this.options.outputSourceFiles,
  9864. sourceMapGenerator: this.options.sourceMapGenerator,
  9865. sourceMapFileInline: this.options.sourceMapFileInline,
  9866. disableSourcemapAnnotation: this.options.disableSourcemapAnnotation
  9867. });
  9868. var css = sourceMapOutput.toCSS(options);
  9869. this.sourceMap = sourceMapOutput.sourceMap;
  9870. this.sourceMapURL = sourceMapOutput.sourceMapURL;
  9871. if (this.options.sourceMapInputFilename) {
  9872. this.sourceMapInputFilename = sourceMapOutput.normalizeFilename(this.options.sourceMapInputFilename);
  9873. }
  9874. if (this.options.sourceMapBasepath !== undefined && this.sourceMapURL !== undefined) {
  9875. this.sourceMapURL = sourceMapOutput.removeBasepath(this.sourceMapURL);
  9876. }
  9877. return css + this.getCSSAppendage();
  9878. };
  9879. SourceMapBuilder.prototype.getCSSAppendage = function () {
  9880. var sourceMapURL = this.sourceMapURL;
  9881. if (this.options.sourceMapFileInline) {
  9882. if (this.sourceMap === undefined) {
  9883. return '';
  9884. }
  9885. sourceMapURL = "data:application/json;base64," + environment.encodeBase64(this.sourceMap);
  9886. }
  9887. if (this.options.disableSourcemapAnnotation) {
  9888. return '';
  9889. }
  9890. if (sourceMapURL) {
  9891. return "/*# sourceMappingURL=" + sourceMapURL + " */";
  9892. }
  9893. return '';
  9894. };
  9895. SourceMapBuilder.prototype.getExternalSourceMap = function () {
  9896. return this.sourceMap;
  9897. };
  9898. SourceMapBuilder.prototype.setExternalSourceMap = function (sourceMap) {
  9899. this.sourceMap = sourceMap;
  9900. };
  9901. SourceMapBuilder.prototype.isInline = function () {
  9902. return this.options.sourceMapFileInline;
  9903. };
  9904. SourceMapBuilder.prototype.getSourceMapURL = function () {
  9905. return this.sourceMapURL;
  9906. };
  9907. SourceMapBuilder.prototype.getOutputFilename = function () {
  9908. return this.options.sourceMapOutputFilename;
  9909. };
  9910. SourceMapBuilder.prototype.getInputFilename = function () {
  9911. return this.sourceMapInputFilename;
  9912. };
  9913. return SourceMapBuilder;
  9914. }());
  9915. return SourceMapBuilder;
  9916. });
  9917. var transformTree = (function (root, options) {
  9918. if (options === void 0) { options = {}; }
  9919. var evaldRoot;
  9920. var variables = options.variables;
  9921. var evalEnv = new contexts.Eval(options);
  9922. //
  9923. // Allows setting variables with a hash, so:
  9924. //
  9925. // `{ color: new tree.Color('#f01') }` will become:
  9926. //
  9927. // new tree.Declaration('@color',
  9928. // new tree.Value([
  9929. // new tree.Expression([
  9930. // new tree.Color('#f01')
  9931. // ])
  9932. // ])
  9933. // )
  9934. //
  9935. if (typeof variables === 'object' && !Array.isArray(variables)) {
  9936. variables = Object.keys(variables).map(function (k) {
  9937. var value = variables[k];
  9938. if (!(value instanceof tree.Value)) {
  9939. if (!(value instanceof tree.Expression)) {
  9940. value = new tree.Expression([value]);
  9941. }
  9942. value = new tree.Value([value]);
  9943. }
  9944. return new tree.Declaration("@" + k, value, false, null, 0);
  9945. });
  9946. evalEnv.frames = [new tree.Ruleset(null, variables)];
  9947. }
  9948. var visitors$1 = [
  9949. new visitors.JoinSelectorVisitor(),
  9950. new visitors.MarkVisibleSelectorsVisitor(true),
  9951. new visitors.ExtendVisitor(),
  9952. new visitors.ToCSSVisitor({ compress: Boolean(options.compress) })
  9953. ];
  9954. var preEvalVisitors = [];
  9955. var v;
  9956. var visitorIterator;
  9957. /**
  9958. * first() / get() allows visitors to be added while visiting
  9959. *
  9960. * @todo Add scoping for visitors just like functions for @plugin; right now they're global
  9961. */
  9962. if (options.pluginManager) {
  9963. visitorIterator = options.pluginManager.visitor();
  9964. for (var i = 0; i < 2; i++) {
  9965. visitorIterator.first();
  9966. while ((v = visitorIterator.get())) {
  9967. if (v.isPreEvalVisitor) {
  9968. if (i === 0 || preEvalVisitors.indexOf(v) === -1) {
  9969. preEvalVisitors.push(v);
  9970. v.run(root);
  9971. }
  9972. }
  9973. else {
  9974. if (i === 0 || visitors$1.indexOf(v) === -1) {
  9975. if (v.isPreVisitor) {
  9976. visitors$1.unshift(v);
  9977. }
  9978. else {
  9979. visitors$1.push(v);
  9980. }
  9981. }
  9982. }
  9983. }
  9984. }
  9985. }
  9986. evaldRoot = root.eval(evalEnv);
  9987. for (var i = 0; i < visitors$1.length; i++) {
  9988. visitors$1[i].run(evaldRoot);
  9989. }
  9990. // Run any remaining visitors added after eval pass
  9991. if (options.pluginManager) {
  9992. visitorIterator.first();
  9993. while ((v = visitorIterator.get())) {
  9994. if (visitors$1.indexOf(v) === -1 && preEvalVisitors.indexOf(v) === -1) {
  9995. v.run(evaldRoot);
  9996. }
  9997. }
  9998. }
  9999. return evaldRoot;
  10000. });
  10001. var parseTree = (function (SourceMapBuilder) {
  10002. var ParseTree = /** @class */ (function () {
  10003. function ParseTree(root, imports) {
  10004. this.root = root;
  10005. this.imports = imports;
  10006. }
  10007. ParseTree.prototype.toCSS = function (options) {
  10008. var evaldRoot;
  10009. var result = {};
  10010. var sourceMapBuilder;
  10011. try {
  10012. evaldRoot = transformTree(this.root, options);
  10013. }
  10014. catch (e) {
  10015. throw new LessError(e, this.imports);
  10016. }
  10017. try {
  10018. var compress = Boolean(options.compress);
  10019. if (compress) {
  10020. logger.warn('The compress option has been deprecated. ' +
  10021. 'We recommend you use a dedicated css minifier, for instance see less-plugin-clean-css.');
  10022. }
  10023. var toCSSOptions = {
  10024. compress: compress,
  10025. dumpLineNumbers: options.dumpLineNumbers,
  10026. strictUnits: Boolean(options.strictUnits),
  10027. numPrecision: 8
  10028. };
  10029. if (options.sourceMap) {
  10030. sourceMapBuilder = new SourceMapBuilder(options.sourceMap);
  10031. result.css = sourceMapBuilder.toCSS(evaldRoot, toCSSOptions, this.imports);
  10032. }
  10033. else {
  10034. result.css = evaldRoot.toCSS(toCSSOptions);
  10035. }
  10036. }
  10037. catch (e) {
  10038. throw new LessError(e, this.imports);
  10039. }
  10040. if (options.pluginManager) {
  10041. var postProcessors = options.pluginManager.getPostProcessors();
  10042. for (var i = 0; i < postProcessors.length; i++) {
  10043. result.css = postProcessors[i].process(result.css, { sourceMap: sourceMapBuilder, options: options, imports: this.imports });
  10044. }
  10045. }
  10046. if (options.sourceMap) {
  10047. result.map = sourceMapBuilder.getExternalSourceMap();
  10048. }
  10049. var rootFilename = this.imports.rootFilename;
  10050. result.imports = this.imports.files.filter(function (file) { return file !== rootFilename; });
  10051. return result;
  10052. };
  10053. return ParseTree;
  10054. }());
  10055. return ParseTree;
  10056. });
  10057. var importManager = (function (environment) {
  10058. // FileInfo = {
  10059. // 'rewriteUrls' - option - whether to adjust URL's to be relative
  10060. // 'filename' - full resolved filename of current file
  10061. // 'rootpath' - path to append to normal URLs for this node
  10062. // 'currentDirectory' - path to the current file, absolute
  10063. // 'rootFilename' - filename of the base file
  10064. // 'entryPath' - absolute path to the entry file
  10065. // 'reference' - whether the file should not be output and only output parts that are referenced
  10066. var ImportManager = /** @class */ (function () {
  10067. function ImportManager(less, context, rootFileInfo) {
  10068. this.less = less;
  10069. this.rootFilename = rootFileInfo.filename;
  10070. this.paths = context.paths || []; // Search paths, when importing
  10071. this.contents = {}; // map - filename to contents of all the files
  10072. this.contentsIgnoredChars = {}; // map - filename to lines at the beginning of each file to ignore
  10073. this.mime = context.mime;
  10074. this.error = null;
  10075. this.context = context;
  10076. // Deprecated? Unused outside of here, could be useful.
  10077. this.queue = []; // Files which haven't been imported yet
  10078. this.files = []; // List of files imported
  10079. }
  10080. /**
  10081. * Add an import to be imported
  10082. * @param path - the raw path
  10083. * @param tryAppendExtension - whether to try appending a file extension (.less or .js if the path has no extension)
  10084. * @param currentFileInfo - the current file info (used for instance to work out relative paths)
  10085. * @param importOptions - import options
  10086. * @param callback - callback for when it is imported
  10087. */
  10088. ImportManager.prototype.push = function (path, tryAppendExtension, currentFileInfo, importOptions, callback) {
  10089. var importManager = this;
  10090. var pluginLoader = this.context.pluginManager.Loader;
  10091. this.queue.push(path);
  10092. var fileParsedFunc = function (e, root, fullPath) {
  10093. importManager.queue.splice(importManager.queue.indexOf(path), 1); // Remove the path from the queue
  10094. var importedEqualsRoot = fullPath === importManager.rootFilename;
  10095. if (importOptions.optional && e) {
  10096. callback(null, { rules: [] }, false, null);
  10097. logger.info("The file " + fullPath + " was skipped because it was not found and the import was marked optional.");
  10098. }
  10099. else {
  10100. var files = importManager.files;
  10101. if (files.indexOf(fullPath) === -1) {
  10102. files.push(fullPath);
  10103. }
  10104. if (e && !importManager.error) {
  10105. importManager.error = e;
  10106. }
  10107. callback(e, root, importedEqualsRoot, fullPath);
  10108. }
  10109. };
  10110. var newFileInfo = {
  10111. rewriteUrls: this.context.rewriteUrls,
  10112. entryPath: currentFileInfo.entryPath,
  10113. rootpath: currentFileInfo.rootpath,
  10114. rootFilename: currentFileInfo.rootFilename
  10115. };
  10116. var fileManager = environment.getFileManager(path, currentFileInfo.currentDirectory, this.context, environment);
  10117. if (!fileManager) {
  10118. fileParsedFunc({ message: "Could not find a file-manager for " + path });
  10119. return;
  10120. }
  10121. var loadFileCallback = function (loadedFile) {
  10122. var plugin;
  10123. var resolvedFilename = loadedFile.filename;
  10124. var contents = loadedFile.contents.replace(/^\uFEFF/, '');
  10125. // Pass on an updated rootpath if path of imported file is relative and file
  10126. // is in a (sub|sup) directory
  10127. //
  10128. // Examples:
  10129. // - If path of imported file is 'module/nav/nav.less' and rootpath is 'less/',
  10130. // then rootpath should become 'less/module/nav/'
  10131. // - If path of imported file is '../mixins.less' and rootpath is 'less/',
  10132. // then rootpath should become 'less/../'
  10133. newFileInfo.currentDirectory = fileManager.getPath(resolvedFilename);
  10134. if (newFileInfo.rewriteUrls) {
  10135. newFileInfo.rootpath = fileManager.join((importManager.context.rootpath || ''), fileManager.pathDiff(newFileInfo.currentDirectory, newFileInfo.entryPath));
  10136. if (!fileManager.isPathAbsolute(newFileInfo.rootpath) && fileManager.alwaysMakePathsAbsolute()) {
  10137. newFileInfo.rootpath = fileManager.join(newFileInfo.entryPath, newFileInfo.rootpath);
  10138. }
  10139. }
  10140. newFileInfo.filename = resolvedFilename;
  10141. var newEnv = new contexts.Parse(importManager.context);
  10142. newEnv.processImports = false;
  10143. importManager.contents[resolvedFilename] = contents;
  10144. if (currentFileInfo.reference || importOptions.reference) {
  10145. newFileInfo.reference = true;
  10146. }
  10147. if (importOptions.isPlugin) {
  10148. plugin = pluginLoader.evalPlugin(contents, newEnv, importManager, importOptions.pluginArgs, newFileInfo);
  10149. if (plugin instanceof LessError) {
  10150. fileParsedFunc(plugin, null, resolvedFilename);
  10151. }
  10152. else {
  10153. fileParsedFunc(null, plugin, resolvedFilename);
  10154. }
  10155. }
  10156. else if (importOptions.inline) {
  10157. fileParsedFunc(null, contents, resolvedFilename);
  10158. }
  10159. else {
  10160. new Parser(newEnv, importManager, newFileInfo).parse(contents, function (e, root) {
  10161. fileParsedFunc(e, root, resolvedFilename);
  10162. });
  10163. }
  10164. };
  10165. var loadedFile;
  10166. var promise;
  10167. var context = clone(this.context);
  10168. if (tryAppendExtension) {
  10169. context.ext = importOptions.isPlugin ? '.js' : '.less';
  10170. }
  10171. if (importOptions.isPlugin) {
  10172. context.mime = 'application/javascript';
  10173. if (context.syncImport) {
  10174. loadedFile = pluginLoader.loadPluginSync(path, currentFileInfo.currentDirectory, context, environment, fileManager);
  10175. }
  10176. else {
  10177. promise = pluginLoader.loadPlugin(path, currentFileInfo.currentDirectory, context, environment, fileManager);
  10178. }
  10179. }
  10180. else {
  10181. if (context.syncImport) {
  10182. loadedFile = fileManager.loadFileSync(path, currentFileInfo.currentDirectory, context, environment);
  10183. }
  10184. else {
  10185. promise = fileManager.loadFile(path, currentFileInfo.currentDirectory, context, environment, function (err, loadedFile) {
  10186. if (err) {
  10187. fileParsedFunc(err);
  10188. }
  10189. else {
  10190. loadFileCallback(loadedFile);
  10191. }
  10192. });
  10193. }
  10194. }
  10195. if (loadedFile) {
  10196. if (!loadedFile.filename) {
  10197. fileParsedFunc(loadedFile);
  10198. }
  10199. else {
  10200. loadFileCallback(loadedFile);
  10201. }
  10202. }
  10203. else if (promise) {
  10204. promise.then(loadFileCallback, fileParsedFunc);
  10205. }
  10206. };
  10207. return ImportManager;
  10208. }());
  10209. return ImportManager;
  10210. });
  10211. var Render = (function (environment, ParseTree, ImportManager) {
  10212. var render = function (input, options, callback) {
  10213. if (typeof options === 'function') {
  10214. callback = options;
  10215. options = copyOptions(this.options, {});
  10216. }
  10217. else {
  10218. options = copyOptions(this.options, options || {});
  10219. }
  10220. if (!callback) {
  10221. var self_1 = this;
  10222. return new Promise(function (resolve, reject) {
  10223. render.call(self_1, input, options, function (err, output) {
  10224. if (err) {
  10225. reject(err);
  10226. }
  10227. else {
  10228. resolve(output);
  10229. }
  10230. });
  10231. });
  10232. }
  10233. else {
  10234. this.parse(input, options, function (err, root, imports, options) {
  10235. if (err) {
  10236. return callback(err);
  10237. }
  10238. var result;
  10239. try {
  10240. var parseTree = new ParseTree(root, imports);
  10241. result = parseTree.toCSS(options);
  10242. }
  10243. catch (err) {
  10244. return callback(err);
  10245. }
  10246. callback(null, result);
  10247. });
  10248. }
  10249. };
  10250. return render;
  10251. });
  10252. /**
  10253. * Plugin Manager
  10254. */
  10255. var PluginManager = /** @class */ (function () {
  10256. function PluginManager(less) {
  10257. this.less = less;
  10258. this.visitors = [];
  10259. this.preProcessors = [];
  10260. this.postProcessors = [];
  10261. this.installedPlugins = [];
  10262. this.fileManagers = [];
  10263. this.iterator = -1;
  10264. this.pluginCache = {};
  10265. this.Loader = new less.PluginLoader(less);
  10266. }
  10267. /**
  10268. * Adds all the plugins in the array
  10269. * @param {Array} plugins
  10270. */
  10271. PluginManager.prototype.addPlugins = function (plugins) {
  10272. if (plugins) {
  10273. for (var i = 0; i < plugins.length; i++) {
  10274. this.addPlugin(plugins[i]);
  10275. }
  10276. }
  10277. };
  10278. /**
  10279. *
  10280. * @param plugin
  10281. * @param {String} filename
  10282. */
  10283. PluginManager.prototype.addPlugin = function (plugin, filename, functionRegistry) {
  10284. this.installedPlugins.push(plugin);
  10285. if (filename) {
  10286. this.pluginCache[filename] = plugin;
  10287. }
  10288. if (plugin.install) {
  10289. plugin.install(this.less, this, functionRegistry || this.less.functions.functionRegistry);
  10290. }
  10291. };
  10292. /**
  10293. *
  10294. * @param filename
  10295. */
  10296. PluginManager.prototype.get = function (filename) {
  10297. return this.pluginCache[filename];
  10298. };
  10299. /**
  10300. * Adds a visitor. The visitor object has options on itself to determine
  10301. * when it should run.
  10302. * @param visitor
  10303. */
  10304. PluginManager.prototype.addVisitor = function (visitor) {
  10305. this.visitors.push(visitor);
  10306. };
  10307. /**
  10308. * Adds a pre processor object
  10309. * @param {object} preProcessor
  10310. * @param {number} priority - guidelines 1 = before import, 1000 = import, 2000 = after import
  10311. */
  10312. PluginManager.prototype.addPreProcessor = function (preProcessor, priority) {
  10313. var indexToInsertAt;
  10314. for (indexToInsertAt = 0; indexToInsertAt < this.preProcessors.length; indexToInsertAt++) {
  10315. if (this.preProcessors[indexToInsertAt].priority >= priority) {
  10316. break;
  10317. }
  10318. }
  10319. this.preProcessors.splice(indexToInsertAt, 0, { preProcessor: preProcessor, priority: priority });
  10320. };
  10321. /**
  10322. * Adds a post processor object
  10323. * @param {object} postProcessor
  10324. * @param {number} priority - guidelines 1 = before compression, 1000 = compression, 2000 = after compression
  10325. */
  10326. PluginManager.prototype.addPostProcessor = function (postProcessor, priority) {
  10327. var indexToInsertAt;
  10328. for (indexToInsertAt = 0; indexToInsertAt < this.postProcessors.length; indexToInsertAt++) {
  10329. if (this.postProcessors[indexToInsertAt].priority >= priority) {
  10330. break;
  10331. }
  10332. }
  10333. this.postProcessors.splice(indexToInsertAt, 0, { postProcessor: postProcessor, priority: priority });
  10334. };
  10335. /**
  10336. *
  10337. * @param manager
  10338. */
  10339. PluginManager.prototype.addFileManager = function (manager) {
  10340. this.fileManagers.push(manager);
  10341. };
  10342. /**
  10343. *
  10344. * @returns {Array}
  10345. * @private
  10346. */
  10347. PluginManager.prototype.getPreProcessors = function () {
  10348. var preProcessors = [];
  10349. for (var i = 0; i < this.preProcessors.length; i++) {
  10350. preProcessors.push(this.preProcessors[i].preProcessor);
  10351. }
  10352. return preProcessors;
  10353. };
  10354. /**
  10355. *
  10356. * @returns {Array}
  10357. * @private
  10358. */
  10359. PluginManager.prototype.getPostProcessors = function () {
  10360. var postProcessors = [];
  10361. for (var i = 0; i < this.postProcessors.length; i++) {
  10362. postProcessors.push(this.postProcessors[i].postProcessor);
  10363. }
  10364. return postProcessors;
  10365. };
  10366. /**
  10367. *
  10368. * @returns {Array}
  10369. * @private
  10370. */
  10371. PluginManager.prototype.getVisitors = function () {
  10372. return this.visitors;
  10373. };
  10374. PluginManager.prototype.visitor = function () {
  10375. var self = this;
  10376. return {
  10377. first: function () {
  10378. self.iterator = -1;
  10379. return self.visitors[self.iterator];
  10380. },
  10381. get: function () {
  10382. self.iterator += 1;
  10383. return self.visitors[self.iterator];
  10384. }
  10385. };
  10386. };
  10387. /**
  10388. *
  10389. * @returns {Array}
  10390. * @private
  10391. */
  10392. PluginManager.prototype.getFileManagers = function () {
  10393. return this.fileManagers;
  10394. };
  10395. return PluginManager;
  10396. }());
  10397. var pm;
  10398. function PluginManagerFactory(less, newFactory) {
  10399. if (newFactory || !pm) {
  10400. pm = new PluginManager(less);
  10401. }
  10402. return pm;
  10403. }
  10404. var Parse = (function (environment, ParseTree, ImportManager) {
  10405. var parse = function (input, options, callback) {
  10406. if (typeof options === 'function') {
  10407. callback = options;
  10408. options = copyOptions(this.options, {});
  10409. }
  10410. else {
  10411. options = copyOptions(this.options, options || {});
  10412. }
  10413. if (!callback) {
  10414. var self_1 = this;
  10415. return new Promise(function (resolve, reject) {
  10416. parse.call(self_1, input, options, function (err, output) {
  10417. if (err) {
  10418. reject(err);
  10419. }
  10420. else {
  10421. resolve(output);
  10422. }
  10423. });
  10424. });
  10425. }
  10426. else {
  10427. var context_1;
  10428. var rootFileInfo = void 0;
  10429. var pluginManager_1 = new PluginManagerFactory(this, !options.reUsePluginManager);
  10430. options.pluginManager = pluginManager_1;
  10431. context_1 = new contexts.Parse(options);
  10432. if (options.rootFileInfo) {
  10433. rootFileInfo = options.rootFileInfo;
  10434. }
  10435. else {
  10436. var filename = options.filename || 'input';
  10437. var entryPath = filename.replace(/[^\/\\]*$/, '');
  10438. rootFileInfo = {
  10439. filename: filename,
  10440. rewriteUrls: context_1.rewriteUrls,
  10441. rootpath: context_1.rootpath || '',
  10442. currentDirectory: entryPath,
  10443. entryPath: entryPath,
  10444. rootFilename: filename
  10445. };
  10446. // add in a missing trailing slash
  10447. if (rootFileInfo.rootpath && rootFileInfo.rootpath.slice(-1) !== '/') {
  10448. rootFileInfo.rootpath += '/';
  10449. }
  10450. }
  10451. var imports_1 = new ImportManager(this, context_1, rootFileInfo);
  10452. this.importManager = imports_1;
  10453. // TODO: allow the plugins to be just a list of paths or names
  10454. // Do an async plugin queue like lessc
  10455. if (options.plugins) {
  10456. options.plugins.forEach(function (plugin) {
  10457. var evalResult;
  10458. var contents;
  10459. if (plugin.fileContent) {
  10460. contents = plugin.fileContent.replace(/^\uFEFF/, '');
  10461. evalResult = pluginManager_1.Loader.evalPlugin(contents, context_1, imports_1, plugin.options, plugin.filename);
  10462. if (evalResult instanceof LessError) {
  10463. return callback(evalResult);
  10464. }
  10465. }
  10466. else {
  10467. pluginManager_1.addPlugin(plugin);
  10468. }
  10469. });
  10470. }
  10471. new Parser(context_1, imports_1, rootFileInfo)
  10472. .parse(input, function (e, root) {
  10473. if (e) {
  10474. return callback(e);
  10475. }
  10476. callback(null, root, imports_1, options);
  10477. }, options);
  10478. }
  10479. };
  10480. return parse;
  10481. });
  10482. var lessRoot = (function (environment$1, fileManagers) {
  10483. /**
  10484. * @todo
  10485. * This original code could be improved quite a bit.
  10486. * Many classes / modules currently add side-effects / mutations to passed in objects,
  10487. * which makes it hard to refactor and reason about.
  10488. */
  10489. environment$1 = new environment(environment$1, fileManagers);
  10490. var SourceMapOutput = sourceMapOutput(environment$1);
  10491. var SourceMapBuilder = sourceMapBuilder(SourceMapOutput, environment$1);
  10492. var ParseTree = parseTree(SourceMapBuilder);
  10493. var ImportManager = importManager(environment$1);
  10494. var render = Render(environment$1, ParseTree);
  10495. var parse = Parse(environment$1, ParseTree, ImportManager);
  10496. var functions = Functions(environment$1);
  10497. /**
  10498. * @todo
  10499. * This root properties / methods need to be organized.
  10500. * It's not clear what should / must be public and why.
  10501. */
  10502. var initial = {
  10503. version: [3, 12, 2],
  10504. data: data,
  10505. tree: tree,
  10506. Environment: environment,
  10507. AbstractFileManager: AbstractFileManager,
  10508. AbstractPluginLoader: AbstractPluginLoader,
  10509. environment: environment$1,
  10510. visitors: visitors,
  10511. Parser: Parser,
  10512. functions: functions,
  10513. contexts: contexts,
  10514. SourceMapOutput: SourceMapOutput,
  10515. SourceMapBuilder: SourceMapBuilder,
  10516. ParseTree: ParseTree,
  10517. ImportManager: ImportManager,
  10518. render: render,
  10519. parse: parse,
  10520. LessError: LessError,
  10521. transformTree: transformTree,
  10522. utils: utils,
  10523. PluginManager: PluginManagerFactory,
  10524. logger: logger
  10525. };
  10526. // Create a public API
  10527. var ctor = function (t) { return function () {
  10528. var args = [];
  10529. for (var _i = 0; _i < arguments.length; _i++) {
  10530. args[_i] = arguments[_i];
  10531. }
  10532. return new (t.bind.apply(t, __spreadArrays([void 0], args)))();
  10533. }; };
  10534. var t;
  10535. var api = Object.create(initial);
  10536. for (var n in initial.tree) {
  10537. /* eslint guard-for-in: 0 */
  10538. t = initial.tree[n];
  10539. if (typeof t === 'function') {
  10540. api[n.toLowerCase()] = ctor(t);
  10541. }
  10542. else {
  10543. api[n] = Object.create(null);
  10544. for (var o in t) {
  10545. /* eslint guard-for-in: 0 */
  10546. api[n][o.toLowerCase()] = ctor(t[o]);
  10547. }
  10548. }
  10549. }
  10550. /**
  10551. * Some of the functions assume a `this` context of the API object,
  10552. * which causes it to fail when wrapped for ES6 imports.
  10553. *
  10554. * An assumed `this` should be removed in the future.
  10555. */
  10556. initial.parse = initial.parse.bind(api);
  10557. initial.render = initial.render.bind(api);
  10558. return api;
  10559. });
  10560. /* global window, XMLHttpRequest */
  10561. var options;
  10562. var logger$1;
  10563. var fileCache = {};
  10564. // TODOS - move log somewhere. pathDiff and doing something similar in node. use pathDiff in the other browser file for the initial load
  10565. var FileManager = /** @class */ (function (_super) {
  10566. __extends(FileManager, _super);
  10567. function FileManager() {
  10568. return _super !== null && _super.apply(this, arguments) || this;
  10569. }
  10570. FileManager.prototype.alwaysMakePathsAbsolute = function () {
  10571. return true;
  10572. };
  10573. FileManager.prototype.join = function (basePath, laterPath) {
  10574. if (!basePath) {
  10575. return laterPath;
  10576. }
  10577. return this.extractUrlParts(laterPath, basePath).path;
  10578. };
  10579. FileManager.prototype.doXHR = function (url, type, callback, errback) {
  10580. var xhr = new XMLHttpRequest();
  10581. var async = options.isFileProtocol ? options.fileAsync : true;
  10582. if (typeof xhr.overrideMimeType === 'function') {
  10583. xhr.overrideMimeType('text/css');
  10584. }
  10585. logger$1.debug("XHR: Getting '" + url + "'");
  10586. xhr.open('GET', url, async);
  10587. xhr.setRequestHeader('Accept', type || 'text/x-less, text/css; q=0.9, */*; q=0.5');
  10588. xhr.send(null);
  10589. function handleResponse(xhr, callback, errback) {
  10590. if (xhr.status >= 200 && xhr.status < 300) {
  10591. callback(xhr.responseText, xhr.getResponseHeader('Last-Modified'));
  10592. }
  10593. else if (typeof errback === 'function') {
  10594. errback(xhr.status, url);
  10595. }
  10596. }
  10597. if (options.isFileProtocol && !options.fileAsync) {
  10598. if (xhr.status === 0 || (xhr.status >= 200 && xhr.status < 300)) {
  10599. callback(xhr.responseText);
  10600. }
  10601. else {
  10602. errback(xhr.status, url);
  10603. }
  10604. }
  10605. else if (async) {
  10606. xhr.onreadystatechange = function () {
  10607. if (xhr.readyState == 4) {
  10608. handleResponse(xhr, callback, errback);
  10609. }
  10610. };
  10611. }
  10612. else {
  10613. handleResponse(xhr, callback, errback);
  10614. }
  10615. };
  10616. FileManager.prototype.supports = function () {
  10617. return true;
  10618. };
  10619. FileManager.prototype.clearFileCache = function () {
  10620. fileCache = {};
  10621. };
  10622. FileManager.prototype.loadFile = function (filename, currentDirectory, options, environment) {
  10623. // TODO: Add prefix support like less-node?
  10624. // What about multiple paths?
  10625. if (currentDirectory && !this.isPathAbsolute(filename)) {
  10626. filename = currentDirectory + filename;
  10627. }
  10628. filename = options.ext ? this.tryAppendExtension(filename, options.ext) : filename;
  10629. options = options || {};
  10630. // sheet may be set to the stylesheet for the initial load or a collection of properties including
  10631. // some context variables for imports
  10632. var hrefParts = this.extractUrlParts(filename, window.location.href);
  10633. var href = hrefParts.url;
  10634. var self = this;
  10635. return new Promise(function (resolve, reject) {
  10636. if (options.useFileCache && fileCache[href]) {
  10637. try {
  10638. var lessText = fileCache[href];
  10639. return resolve({ contents: lessText, filename: href, webInfo: { lastModified: new Date() } });
  10640. }
  10641. catch (e) {
  10642. return reject({ filename: href, message: "Error loading file " + href + " error was " + e.message });
  10643. }
  10644. }
  10645. self.doXHR(href, options.mime, function doXHRCallback(data, lastModified) {
  10646. // per file cache
  10647. fileCache[href] = data;
  10648. // Use remote copy (re-parse)
  10649. resolve({ contents: data, filename: href, webInfo: { lastModified: lastModified } });
  10650. }, function doXHRError(status, url) {
  10651. reject({ type: 'File', message: "'" + url + "' wasn't found (" + status + ")", href: href });
  10652. });
  10653. });
  10654. };
  10655. return FileManager;
  10656. }(AbstractFileManager));
  10657. var FM = (function (opts, log) {
  10658. options = opts;
  10659. logger$1 = log;
  10660. return FileManager;
  10661. });
  10662. // TODO: Add tests for browser @plugin
  10663. /**
  10664. * Browser Plugin Loader
  10665. */
  10666. var PluginLoader = /** @class */ (function (_super) {
  10667. __extends(PluginLoader, _super);
  10668. function PluginLoader(less) {
  10669. var _this = _super.call(this) || this;
  10670. _this.less = less;
  10671. return _this;
  10672. // Should we shim this.require for browser? Probably not?
  10673. }
  10674. PluginLoader.prototype.loadPlugin = function (filename, basePath, context, environment, fileManager) {
  10675. return new Promise(function (fulfill, reject) {
  10676. fileManager.loadFile(filename, basePath, context, environment)
  10677. .then(fulfill).catch(reject);
  10678. });
  10679. };
  10680. return PluginLoader;
  10681. }(AbstractPluginLoader));
  10682. var LogListener = (function (less, options) {
  10683. var logLevel_debug = 4;
  10684. var logLevel_info = 3;
  10685. var logLevel_warn = 2;
  10686. var logLevel_error = 1;
  10687. // The amount of logging in the javascript console.
  10688. // 3 - Debug, information and errors
  10689. // 2 - Information and errors
  10690. // 1 - Errors
  10691. // 0 - None
  10692. // Defaults to 2
  10693. options.logLevel = typeof options.logLevel !== 'undefined' ? options.logLevel : (options.env === 'development' ? logLevel_info : logLevel_error);
  10694. if (!options.loggers) {
  10695. options.loggers = [{
  10696. debug: function (msg) {
  10697. if (options.logLevel >= logLevel_debug) {
  10698. console.log(msg);
  10699. }
  10700. },
  10701. info: function (msg) {
  10702. if (options.logLevel >= logLevel_info) {
  10703. console.log(msg);
  10704. }
  10705. },
  10706. warn: function (msg) {
  10707. if (options.logLevel >= logLevel_warn) {
  10708. console.warn(msg);
  10709. }
  10710. },
  10711. error: function (msg) {
  10712. if (options.logLevel >= logLevel_error) {
  10713. console.error(msg);
  10714. }
  10715. }
  10716. }];
  10717. }
  10718. for (var i = 0; i < options.loggers.length; i++) {
  10719. less.logger.addListener(options.loggers[i]);
  10720. }
  10721. });
  10722. var ErrorReporting = (function (window, less, options) {
  10723. function errorHTML(e, rootHref) {
  10724. var id = "less-error-message:" + extractId(rootHref || '');
  10725. var template = '<li><label>{line}</label><pre class="{class}">{content}</pre></li>';
  10726. var elem = window.document.createElement('div');
  10727. var timer;
  10728. var content;
  10729. var errors = [];
  10730. var filename = e.filename || rootHref;
  10731. var filenameNoPath = filename.match(/([^\/]+(\?.*)?)$/)[1];
  10732. elem.id = id;
  10733. elem.className = 'less-error-message';
  10734. content = "<h3>" + (e.type || 'Syntax') + "Error: " + (e.message || 'There is an error in your .less file') +
  10735. ("</h3><p>in <a href=\"" + filename + "\">" + filenameNoPath + "</a> ");
  10736. var errorline = function (e, i, classname) {
  10737. if (e.extract[i] !== undefined) {
  10738. errors.push(template.replace(/\{line\}/, (parseInt(e.line, 10) || 0) + (i - 1))
  10739. .replace(/\{class\}/, classname)
  10740. .replace(/\{content\}/, e.extract[i]));
  10741. }
  10742. };
  10743. if (e.line) {
  10744. errorline(e, 0, '');
  10745. errorline(e, 1, 'line');
  10746. errorline(e, 2, '');
  10747. content += "on line " + e.line + ", column " + (e.column + 1) + ":</p><ul>" + errors.join('') + "</ul>";
  10748. }
  10749. if (e.stack && (e.extract || options.logLevel >= 4)) {
  10750. content += "<br/>Stack Trace</br />" + e.stack.split('\n').slice(1).join('<br/>');
  10751. }
  10752. elem.innerHTML = content;
  10753. // CSS for error messages
  10754. browser.createCSS(window.document, [
  10755. '.less-error-message ul, .less-error-message li {',
  10756. 'list-style-type: none;',
  10757. 'margin-right: 15px;',
  10758. 'padding: 4px 0;',
  10759. 'margin: 0;',
  10760. '}',
  10761. '.less-error-message label {',
  10762. 'font-size: 12px;',
  10763. 'margin-right: 15px;',
  10764. 'padding: 4px 0;',
  10765. 'color: #cc7777;',
  10766. '}',
  10767. '.less-error-message pre {',
  10768. 'color: #dd6666;',
  10769. 'padding: 4px 0;',
  10770. 'margin: 0;',
  10771. 'display: inline-block;',
  10772. '}',
  10773. '.less-error-message pre.line {',
  10774. 'color: #ff0000;',
  10775. '}',
  10776. '.less-error-message h3 {',
  10777. 'font-size: 20px;',
  10778. 'font-weight: bold;',
  10779. 'padding: 15px 0 5px 0;',
  10780. 'margin: 0;',
  10781. '}',
  10782. '.less-error-message a {',
  10783. 'color: #10a',
  10784. '}',
  10785. '.less-error-message .error {',
  10786. 'color: red;',
  10787. 'font-weight: bold;',
  10788. 'padding-bottom: 2px;',
  10789. 'border-bottom: 1px dashed red;',
  10790. '}'
  10791. ].join('\n'), { title: 'error-message' });
  10792. elem.style.cssText = [
  10793. 'font-family: Arial, sans-serif',
  10794. 'border: 1px solid #e00',
  10795. 'background-color: #eee',
  10796. 'border-radius: 5px',
  10797. '-webkit-border-radius: 5px',
  10798. '-moz-border-radius: 5px',
  10799. 'color: #e00',
  10800. 'padding: 15px',
  10801. 'margin-bottom: 15px'
  10802. ].join(';');
  10803. if (options.env === 'development') {
  10804. timer = setInterval(function () {
  10805. var document = window.document;
  10806. var body = document.body;
  10807. if (body) {
  10808. if (document.getElementById(id)) {
  10809. body.replaceChild(elem, document.getElementById(id));
  10810. }
  10811. else {
  10812. body.insertBefore(elem, body.firstChild);
  10813. }
  10814. clearInterval(timer);
  10815. }
  10816. }, 10);
  10817. }
  10818. }
  10819. function removeErrorHTML(path) {
  10820. var node = window.document.getElementById("less-error-message:" + extractId(path));
  10821. if (node) {
  10822. node.parentNode.removeChild(node);
  10823. }
  10824. }
  10825. function removeError(path) {
  10826. if (!options.errorReporting || options.errorReporting === 'html') {
  10827. removeErrorHTML(path);
  10828. }
  10829. else if (options.errorReporting === 'console') ;
  10830. else if (typeof options.errorReporting === 'function') {
  10831. options.errorReporting('remove', path);
  10832. }
  10833. }
  10834. function errorConsole(e, rootHref) {
  10835. var template = '{line} {content}';
  10836. var filename = e.filename || rootHref;
  10837. var errors = [];
  10838. var content = (e.type || 'Syntax') + "Error: " + (e.message || 'There is an error in your .less file') + " in " + filename;
  10839. var errorline = function (e, i, classname) {
  10840. if (e.extract[i] !== undefined) {
  10841. errors.push(template.replace(/\{line\}/, (parseInt(e.line, 10) || 0) + (i - 1))
  10842. .replace(/\{class\}/, classname)
  10843. .replace(/\{content\}/, e.extract[i]));
  10844. }
  10845. };
  10846. if (e.line) {
  10847. errorline(e, 0, '');
  10848. errorline(e, 1, 'line');
  10849. errorline(e, 2, '');
  10850. content += " on line " + e.line + ", column " + (e.column + 1) + ":\n" + errors.join('\n');
  10851. }
  10852. if (e.stack && (e.extract || options.logLevel >= 4)) {
  10853. content += "\nStack Trace\n" + e.stack;
  10854. }
  10855. less.logger.error(content);
  10856. }
  10857. function error(e, rootHref) {
  10858. if (!options.errorReporting || options.errorReporting === 'html') {
  10859. errorHTML(e, rootHref);
  10860. }
  10861. else if (options.errorReporting === 'console') {
  10862. errorConsole(e, rootHref);
  10863. }
  10864. else if (typeof options.errorReporting === 'function') {
  10865. options.errorReporting('add', e, rootHref);
  10866. }
  10867. }
  10868. return {
  10869. add: error,
  10870. remove: removeError
  10871. };
  10872. });
  10873. // Cache system is a bit outdated and could do with work
  10874. var Cache = (function (window, options, logger) {
  10875. var cache = null;
  10876. if (options.env !== 'development') {
  10877. try {
  10878. cache = (typeof window.localStorage === 'undefined') ? null : window.localStorage;
  10879. }
  10880. catch (_) { }
  10881. }
  10882. return {
  10883. setCSS: function (path, lastModified, modifyVars, styles) {
  10884. if (cache) {
  10885. logger.info("saving " + path + " to cache.");
  10886. try {
  10887. cache.setItem(path, styles);
  10888. cache.setItem(path + ":timestamp", lastModified);
  10889. if (modifyVars) {
  10890. cache.setItem(path + ":vars", JSON.stringify(modifyVars));
  10891. }
  10892. }
  10893. catch (e) {
  10894. // TODO - could do with adding more robust error handling
  10895. logger.error("failed to save \"" + path + "\" to local storage for caching.");
  10896. }
  10897. }
  10898. },
  10899. getCSS: function (path, webInfo, modifyVars) {
  10900. var css = cache && cache.getItem(path);
  10901. var timestamp = cache && cache.getItem(path + ":timestamp");
  10902. var vars = cache && cache.getItem(path + ":vars");
  10903. modifyVars = modifyVars || {};
  10904. vars = vars || "{}"; // if not set, treat as the JSON representation of an empty object
  10905. if (timestamp && webInfo.lastModified &&
  10906. (new Date(webInfo.lastModified).valueOf() ===
  10907. new Date(timestamp).valueOf()) &&
  10908. JSON.stringify(modifyVars) === vars) {
  10909. // Use local copy
  10910. return css;
  10911. }
  10912. }
  10913. };
  10914. });
  10915. var ImageSize = (function () {
  10916. function imageSize() {
  10917. throw {
  10918. type: 'Runtime',
  10919. message: 'Image size functions are not supported in browser version of less'
  10920. };
  10921. }
  10922. var imageFunctions = {
  10923. 'image-size': function (filePathNode) {
  10924. imageSize();
  10925. return -1;
  10926. },
  10927. 'image-width': function (filePathNode) {
  10928. imageSize();
  10929. return -1;
  10930. },
  10931. 'image-height': function (filePathNode) {
  10932. imageSize();
  10933. return -1;
  10934. }
  10935. };
  10936. functionRegistry.addMultiple(imageFunctions);
  10937. });
  10938. //
  10939. var root = (function (window, options) {
  10940. var document = window.document;
  10941. var less = lessRoot();
  10942. less.options = options;
  10943. var environment = less.environment;
  10944. var FileManager = FM(options, less.logger);
  10945. var fileManager = new FileManager();
  10946. environment.addFileManager(fileManager);
  10947. less.FileManager = FileManager;
  10948. less.PluginLoader = PluginLoader;
  10949. LogListener(less, options);
  10950. var errors = ErrorReporting(window, less, options);
  10951. var cache = less.cache = options.cache || Cache(window, options, less.logger);
  10952. ImageSize(less.environment);
  10953. // Setup user functions - Deprecate?
  10954. if (options.functions) {
  10955. less.functions.functionRegistry.addMultiple(options.functions);
  10956. }
  10957. var typePattern = /^text\/(x-)?less$/;
  10958. function clone(obj) {
  10959. var cloned = {};
  10960. for (var prop in obj) {
  10961. if (obj.hasOwnProperty(prop)) {
  10962. cloned[prop] = obj[prop];
  10963. }
  10964. }
  10965. return cloned;
  10966. }
  10967. // only really needed for phantom
  10968. function bind(func, thisArg) {
  10969. var curryArgs = Array.prototype.slice.call(arguments, 2);
  10970. return function () {
  10971. var args = curryArgs.concat(Array.prototype.slice.call(arguments, 0));
  10972. return func.apply(thisArg, args);
  10973. };
  10974. }
  10975. function loadStyles(modifyVars) {
  10976. var styles = document.getElementsByTagName('style');
  10977. var style;
  10978. for (var i = 0; i < styles.length; i++) {
  10979. style = styles[i];
  10980. if (style.type.match(typePattern)) {
  10981. var instanceOptions = clone(options);
  10982. instanceOptions.modifyVars = modifyVars;
  10983. var lessText = style.innerHTML || '';
  10984. instanceOptions.filename = document.location.href.replace(/#.*$/, '');
  10985. /* jshint loopfunc:true */
  10986. // use closure to store current style
  10987. less.render(lessText, instanceOptions, bind(function (style, e, result) {
  10988. if (e) {
  10989. errors.add(e, 'inline');
  10990. }
  10991. else {
  10992. style.type = 'text/css';
  10993. if (style.styleSheet) {
  10994. style.styleSheet.cssText = result.css;
  10995. }
  10996. else {
  10997. style.innerHTML = result.css;
  10998. }
  10999. }
  11000. }, null, style));
  11001. }
  11002. }
  11003. }
  11004. function loadStyleSheet(sheet, callback, reload, remaining, modifyVars) {
  11005. var instanceOptions = clone(options);
  11006. addDataAttr(instanceOptions, sheet);
  11007. instanceOptions.mime = sheet.type;
  11008. if (modifyVars) {
  11009. instanceOptions.modifyVars = modifyVars;
  11010. }
  11011. function loadInitialFileCallback(loadedFile) {
  11012. var data = loadedFile.contents;
  11013. var path = loadedFile.filename;
  11014. var webInfo = loadedFile.webInfo;
  11015. var newFileInfo = {
  11016. currentDirectory: fileManager.getPath(path),
  11017. filename: path,
  11018. rootFilename: path,
  11019. rewriteUrls: instanceOptions.rewriteUrls
  11020. };
  11021. newFileInfo.entryPath = newFileInfo.currentDirectory;
  11022. newFileInfo.rootpath = instanceOptions.rootpath || newFileInfo.currentDirectory;
  11023. if (webInfo) {
  11024. webInfo.remaining = remaining;
  11025. var css = cache.getCSS(path, webInfo, instanceOptions.modifyVars);
  11026. if (!reload && css) {
  11027. webInfo.local = true;
  11028. callback(null, css, data, sheet, webInfo, path);
  11029. return;
  11030. }
  11031. }
  11032. // TODO add tests around how this behaves when reloading
  11033. errors.remove(path);
  11034. instanceOptions.rootFileInfo = newFileInfo;
  11035. less.render(data, instanceOptions, function (e, result) {
  11036. if (e) {
  11037. e.href = path;
  11038. callback(e);
  11039. }
  11040. else {
  11041. cache.setCSS(sheet.href, webInfo.lastModified, instanceOptions.modifyVars, result.css);
  11042. callback(null, result.css, data, sheet, webInfo, path);
  11043. }
  11044. });
  11045. }
  11046. fileManager.loadFile(sheet.href, null, instanceOptions, environment)
  11047. .then(function (loadedFile) {
  11048. loadInitialFileCallback(loadedFile);
  11049. }).catch(function (err) {
  11050. console.log(err);
  11051. callback(err);
  11052. });
  11053. }
  11054. function loadStyleSheets(callback, reload, modifyVars) {
  11055. for (var i = 0; i < less.sheets.length; i++) {
  11056. loadStyleSheet(less.sheets[i], callback, reload, less.sheets.length - (i + 1), modifyVars);
  11057. }
  11058. }
  11059. function initRunningMode() {
  11060. if (less.env === 'development') {
  11061. less.watchTimer = setInterval(function () {
  11062. if (less.watchMode) {
  11063. fileManager.clearFileCache();
  11064. loadStyleSheets(function (e, css, _, sheet, webInfo) {
  11065. if (e) {
  11066. errors.add(e, e.href || sheet.href);
  11067. }
  11068. else if (css) {
  11069. browser.createCSS(window.document, css, sheet);
  11070. }
  11071. });
  11072. }
  11073. }, options.poll);
  11074. }
  11075. }
  11076. //
  11077. // Watch mode
  11078. //
  11079. less.watch = function () {
  11080. if (!less.watchMode) {
  11081. less.env = 'development';
  11082. initRunningMode();
  11083. }
  11084. this.watchMode = true;
  11085. return true;
  11086. };
  11087. less.unwatch = function () { clearInterval(less.watchTimer); this.watchMode = false; return false; };
  11088. //
  11089. // Synchronously get all <link> tags with the 'rel' attribute set to
  11090. // "stylesheet/less".
  11091. //
  11092. less.registerStylesheetsImmediately = function () {
  11093. var links = document.getElementsByTagName('link');
  11094. less.sheets = [];
  11095. for (var i = 0; i < links.length; i++) {
  11096. if (links[i].rel === 'stylesheet/less' || (links[i].rel.match(/stylesheet/) &&
  11097. (links[i].type.match(typePattern)))) {
  11098. less.sheets.push(links[i]);
  11099. }
  11100. }
  11101. };
  11102. //
  11103. // Asynchronously get all <link> tags with the 'rel' attribute set to
  11104. // "stylesheet/less", returning a Promise.
  11105. //
  11106. less.registerStylesheets = function () { return new Promise(function (resolve, reject) {
  11107. less.registerStylesheetsImmediately();
  11108. resolve();
  11109. }); };
  11110. //
  11111. // With this function, it's possible to alter variables and re-render
  11112. // CSS without reloading less-files
  11113. //
  11114. less.modifyVars = function (record) { return less.refresh(true, record, false); };
  11115. less.refresh = function (reload, modifyVars, clearFileCache) {
  11116. if ((reload || clearFileCache) && clearFileCache !== false) {
  11117. fileManager.clearFileCache();
  11118. }
  11119. return new Promise(function (resolve, reject) {
  11120. var startTime;
  11121. var endTime;
  11122. var totalMilliseconds;
  11123. var remainingSheets;
  11124. startTime = endTime = new Date();
  11125. // Set counter for remaining unprocessed sheets
  11126. remainingSheets = less.sheets.length;
  11127. if (remainingSheets === 0) {
  11128. endTime = new Date();
  11129. totalMilliseconds = endTime - startTime;
  11130. less.logger.info('Less has finished and no sheets were loaded.');
  11131. resolve({
  11132. startTime: startTime,
  11133. endTime: endTime,
  11134. totalMilliseconds: totalMilliseconds,
  11135. sheets: less.sheets.length
  11136. });
  11137. }
  11138. else {
  11139. // Relies on less.sheets array, callback seems to be guaranteed to be called for every element of the array
  11140. loadStyleSheets(function (e, css, _, sheet, webInfo) {
  11141. if (e) {
  11142. errors.add(e, e.href || sheet.href);
  11143. reject(e);
  11144. return;
  11145. }
  11146. if (webInfo.local) {
  11147. less.logger.info("Loading " + sheet.href + " from cache.");
  11148. }
  11149. else {
  11150. less.logger.info("Rendered " + sheet.href + " successfully.");
  11151. }
  11152. browser.createCSS(window.document, css, sheet);
  11153. less.logger.info("CSS for " + sheet.href + " generated in " + (new Date() - endTime) + "ms");
  11154. // Count completed sheet
  11155. remainingSheets--;
  11156. // Check if the last remaining sheet was processed and then call the promise
  11157. if (remainingSheets === 0) {
  11158. totalMilliseconds = new Date() - startTime;
  11159. less.logger.info("Less has finished. CSS generated in " + totalMilliseconds + "ms");
  11160. resolve({
  11161. startTime: startTime,
  11162. endTime: endTime,
  11163. totalMilliseconds: totalMilliseconds,
  11164. sheets: less.sheets.length
  11165. });
  11166. }
  11167. endTime = new Date();
  11168. }, reload, modifyVars);
  11169. }
  11170. loadStyles(modifyVars);
  11171. });
  11172. };
  11173. less.refreshStyles = loadStyles;
  11174. return less;
  11175. });
  11176. /**
  11177. * Kicks off less and compiles any stylesheets
  11178. * used in the browser distributed version of less
  11179. * to kick-start less using the browser api
  11180. */
  11181. var options$1 = defaultOptions();
  11182. if (window.less) {
  11183. for (var key in window.less) {
  11184. if (window.less.hasOwnProperty(key)) {
  11185. options$1[key] = window.less[key];
  11186. }
  11187. }
  11188. }
  11189. addDefaultOptions(window, options$1);
  11190. options$1.plugins = options$1.plugins || [];
  11191. if (window.LESS_PLUGINS) {
  11192. options$1.plugins = options$1.plugins.concat(window.LESS_PLUGINS);
  11193. }
  11194. var less = root(window, options$1);
  11195. window.less = less;
  11196. var css;
  11197. var head;
  11198. var style;
  11199. // Always restore page visibility
  11200. function resolveOrReject(data) {
  11201. if (data.filename) {
  11202. console.warn(data);
  11203. }
  11204. if (!options$1.async) {
  11205. head.removeChild(style);
  11206. }
  11207. }
  11208. if (options$1.onReady) {
  11209. if (/!watch/.test(window.location.hash)) {
  11210. less.watch();
  11211. }
  11212. // Simulate synchronous stylesheet loading by hiding page rendering
  11213. if (!options$1.async) {
  11214. css = 'body { display: none !important }';
  11215. head = document.head || document.getElementsByTagName('head')[0];
  11216. style = document.createElement('style');
  11217. style.type = 'text/css';
  11218. if (style.styleSheet) {
  11219. style.styleSheet.cssText = css;
  11220. }
  11221. else {
  11222. style.appendChild(document.createTextNode(css));
  11223. }
  11224. head.appendChild(style);
  11225. }
  11226. less.registerStylesheetsImmediately();
  11227. less.pageLoadFinished = less.refresh(less.env === 'development').then(resolveOrReject, resolveOrReject);
  11228. }
  11229. return less;
  11230. })));