less.js 443 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214621562166217621862196220622162226223622462256226622762286229623062316232623362346235623662376238623962406241624262436244624562466247624862496250625162526253625462556256625762586259626062616262626362646265626662676268626962706271627262736274627562766277627862796280628162826283628462856286628762886289629062916292629362946295629662976298629963006301630263036304630563066307630863096310631163126313631463156316631763186319632063216322632363246325632663276328632963306331633263336334633563366337633863396340634163426343634463456346634763486349635063516352635363546355635663576358635963606361636263636364636563666367636863696370637163726373637463756376637763786379638063816382638363846385638663876388638963906391639263936394639563966397639863996400640164026403640464056406640764086409641064116412641364146415641664176418641964206421642264236424642564266427642864296430643164326433643464356436643764386439644064416442644364446445644664476448644964506451645264536454645564566457645864596460646164626463646464656466646764686469647064716472647364746475647664776478647964806481648264836484648564866487648864896490649164926493649464956496649764986499650065016502650365046505650665076508650965106511651265136514651565166517651865196520652165226523652465256526652765286529653065316532653365346535653665376538653965406541654265436544654565466547654865496550655165526553655465556556655765586559656065616562656365646565656665676568656965706571657265736574657565766577657865796580658165826583658465856586658765886589659065916592659365946595659665976598659966006601660266036604660566066607660866096610661166126613661466156616661766186619662066216622662366246625662666276628662966306631663266336634663566366637663866396640664166426643664466456646664766486649665066516652665366546655665666576658665966606661666266636664666566666667666866696670667166726673667466756676667766786679668066816682668366846685668666876688668966906691669266936694669566966697669866996700670167026703670467056706670767086709671067116712671367146715671667176718671967206721672267236724672567266727672867296730673167326733673467356736673767386739674067416742674367446745674667476748674967506751675267536754675567566757675867596760676167626763676467656766676767686769677067716772677367746775677667776778677967806781678267836784678567866787678867896790679167926793679467956796679767986799680068016802680368046805680668076808680968106811681268136814681568166817681868196820682168226823682468256826682768286829683068316832683368346835683668376838683968406841684268436844684568466847684868496850685168526853685468556856685768586859686068616862686368646865686668676868686968706871687268736874687568766877687868796880688168826883688468856886688768886889689068916892689368946895689668976898689969006901690269036904690569066907690869096910691169126913691469156916691769186919692069216922692369246925692669276928692969306931693269336934693569366937693869396940694169426943694469456946694769486949695069516952695369546955695669576958695969606961696269636964696569666967696869696970697169726973697469756976697769786979698069816982698369846985698669876988698969906991699269936994699569966997699869997000700170027003700470057006700770087009701070117012701370147015701670177018701970207021702270237024702570267027702870297030703170327033703470357036703770387039704070417042704370447045704670477048704970507051705270537054705570567057705870597060706170627063706470657066706770687069707070717072707370747075707670777078707970807081708270837084708570867087708870897090709170927093709470957096709770987099710071017102710371047105710671077108710971107111711271137114711571167117711871197120712171227123712471257126712771287129713071317132713371347135713671377138713971407141714271437144714571467147714871497150715171527153715471557156715771587159716071617162716371647165716671677168716971707171717271737174717571767177717871797180718171827183718471857186718771887189719071917192719371947195719671977198719972007201720272037204720572067207720872097210721172127213721472157216721772187219722072217222722372247225722672277228722972307231723272337234723572367237723872397240724172427243724472457246724772487249725072517252725372547255725672577258725972607261726272637264726572667267726872697270727172727273727472757276727772787279728072817282728372847285728672877288728972907291729272937294729572967297729872997300730173027303730473057306730773087309731073117312731373147315731673177318731973207321732273237324732573267327732873297330733173327333733473357336733773387339734073417342734373447345734673477348734973507351735273537354735573567357735873597360736173627363736473657366736773687369737073717372737373747375737673777378737973807381738273837384738573867387738873897390739173927393739473957396739773987399740074017402740374047405740674077408740974107411741274137414741574167417741874197420742174227423742474257426742774287429743074317432743374347435743674377438743974407441744274437444744574467447744874497450745174527453745474557456745774587459746074617462746374647465746674677468746974707471747274737474747574767477747874797480748174827483748474857486748774887489749074917492749374947495749674977498749975007501750275037504750575067507750875097510751175127513751475157516751775187519752075217522752375247525752675277528752975307531753275337534753575367537753875397540754175427543754475457546754775487549755075517552755375547555755675577558755975607561756275637564756575667567756875697570757175727573757475757576757775787579758075817582758375847585758675877588758975907591759275937594759575967597759875997600760176027603760476057606760776087609761076117612761376147615761676177618761976207621762276237624762576267627762876297630763176327633763476357636763776387639764076417642764376447645764676477648764976507651765276537654765576567657765876597660766176627663766476657666766776687669767076717672767376747675767676777678767976807681768276837684768576867687768876897690769176927693769476957696769776987699770077017702770377047705770677077708770977107711771277137714771577167717771877197720772177227723772477257726772777287729773077317732773377347735773677377738773977407741774277437744774577467747774877497750775177527753775477557756775777587759776077617762776377647765776677677768776977707771777277737774777577767777777877797780778177827783778477857786778777887789779077917792779377947795779677977798779978007801780278037804780578067807780878097810781178127813781478157816781778187819782078217822782378247825782678277828782978307831783278337834783578367837783878397840784178427843784478457846784778487849785078517852785378547855785678577858785978607861786278637864786578667867786878697870787178727873787478757876787778787879788078817882788378847885788678877888788978907891789278937894789578967897789878997900790179027903790479057906790779087909791079117912791379147915791679177918791979207921792279237924792579267927792879297930793179327933793479357936793779387939794079417942794379447945794679477948794979507951795279537954795579567957795879597960796179627963796479657966796779687969797079717972797379747975797679777978797979807981798279837984798579867987798879897990799179927993799479957996799779987999800080018002800380048005800680078008800980108011801280138014801580168017801880198020802180228023802480258026802780288029803080318032803380348035803680378038803980408041804280438044804580468047804880498050805180528053805480558056805780588059806080618062806380648065806680678068806980708071807280738074807580768077807880798080808180828083808480858086808780888089809080918092809380948095809680978098809981008101810281038104810581068107810881098110811181128113811481158116811781188119812081218122812381248125812681278128812981308131813281338134813581368137813881398140814181428143814481458146814781488149815081518152815381548155815681578158815981608161816281638164816581668167816881698170817181728173817481758176817781788179818081818182818381848185818681878188818981908191819281938194819581968197819881998200820182028203820482058206820782088209821082118212821382148215821682178218821982208221822282238224822582268227822882298230823182328233823482358236823782388239824082418242824382448245824682478248824982508251825282538254825582568257825882598260826182628263826482658266826782688269827082718272827382748275827682778278827982808281828282838284828582868287828882898290829182928293829482958296829782988299830083018302830383048305830683078308830983108311831283138314831583168317831883198320832183228323832483258326832783288329833083318332833383348335833683378338833983408341834283438344834583468347834883498350835183528353835483558356835783588359836083618362836383648365836683678368836983708371837283738374837583768377837883798380838183828383838483858386838783888389839083918392839383948395839683978398839984008401840284038404840584068407840884098410841184128413841484158416841784188419842084218422842384248425842684278428842984308431843284338434843584368437843884398440844184428443844484458446844784488449845084518452845384548455845684578458845984608461846284638464846584668467846884698470847184728473847484758476847784788479848084818482848384848485848684878488848984908491849284938494849584968497849884998500850185028503850485058506850785088509851085118512851385148515851685178518851985208521852285238524852585268527852885298530853185328533853485358536853785388539854085418542854385448545854685478548854985508551855285538554855585568557855885598560856185628563856485658566856785688569857085718572857385748575857685778578857985808581858285838584858585868587858885898590859185928593859485958596859785988599860086018602860386048605860686078608860986108611861286138614861586168617861886198620862186228623862486258626862786288629863086318632863386348635863686378638863986408641864286438644864586468647864886498650865186528653865486558656865786588659866086618662866386648665866686678668866986708671867286738674867586768677867886798680868186828683868486858686868786888689869086918692869386948695869686978698869987008701870287038704870587068707870887098710871187128713871487158716871787188719872087218722872387248725872687278728872987308731873287338734873587368737873887398740874187428743874487458746874787488749875087518752875387548755875687578758875987608761876287638764876587668767876887698770877187728773877487758776877787788779878087818782878387848785878687878788878987908791879287938794879587968797879887998800880188028803880488058806880788088809881088118812881388148815881688178818881988208821882288238824882588268827882888298830883188328833883488358836883788388839884088418842884388448845884688478848884988508851885288538854885588568857885888598860886188628863886488658866886788688869887088718872887388748875887688778878887988808881888288838884888588868887888888898890889188928893889488958896889788988899890089018902890389048905890689078908890989108911891289138914891589168917891889198920892189228923892489258926892789288929893089318932893389348935893689378938893989408941894289438944894589468947894889498950895189528953895489558956895789588959896089618962896389648965896689678968896989708971897289738974897589768977897889798980898189828983898489858986898789888989899089918992899389948995899689978998899990009001900290039004900590069007900890099010901190129013901490159016901790189019902090219022902390249025902690279028902990309031903290339034903590369037903890399040904190429043904490459046904790489049905090519052905390549055905690579058905990609061906290639064906590669067906890699070907190729073907490759076907790789079908090819082908390849085908690879088908990909091909290939094909590969097909890999100910191029103910491059106910791089109911091119112911391149115911691179118911991209121912291239124912591269127912891299130913191329133913491359136913791389139914091419142914391449145914691479148914991509151915291539154915591569157915891599160916191629163916491659166916791689169917091719172917391749175917691779178917991809181918291839184918591869187918891899190919191929193919491959196919791989199920092019202920392049205920692079208920992109211921292139214921592169217921892199220922192229223922492259226922792289229923092319232923392349235923692379238923992409241924292439244924592469247924892499250925192529253925492559256925792589259926092619262926392649265926692679268926992709271927292739274927592769277927892799280928192829283928492859286928792889289929092919292929392949295929692979298929993009301930293039304930593069307930893099310931193129313931493159316931793189319932093219322932393249325932693279328932993309331933293339334933593369337933893399340934193429343934493459346934793489349935093519352935393549355935693579358935993609361936293639364936593669367936893699370937193729373937493759376937793789379938093819382938393849385938693879388938993909391939293939394939593969397939893999400940194029403940494059406940794089409941094119412941394149415941694179418941994209421942294239424942594269427942894299430943194329433943494359436943794389439944094419442944394449445944694479448944994509451945294539454945594569457945894599460946194629463946494659466946794689469947094719472947394749475947694779478947994809481948294839484948594869487948894899490949194929493949494959496949794989499950095019502950395049505950695079508950995109511951295139514951595169517951895199520952195229523952495259526952795289529953095319532953395349535953695379538953995409541954295439544954595469547954895499550955195529553955495559556955795589559956095619562956395649565956695679568956995709571957295739574957595769577957895799580958195829583958495859586958795889589959095919592959395949595959695979598959996009601960296039604960596069607960896099610961196129613961496159616961796189619962096219622962396249625962696279628962996309631963296339634963596369637963896399640964196429643964496459646964796489649965096519652965396549655965696579658965996609661966296639664966596669667966896699670967196729673967496759676967796789679968096819682968396849685968696879688968996909691969296939694969596969697969896999700970197029703970497059706970797089709971097119712971397149715971697179718971997209721972297239724972597269727972897299730973197329733973497359736973797389739974097419742974397449745974697479748974997509751975297539754975597569757975897599760976197629763976497659766976797689769977097719772977397749775977697779778977997809781978297839784978597869787978897899790979197929793979497959796979797989799980098019802980398049805980698079808980998109811981298139814981598169817981898199820982198229823982498259826982798289829983098319832983398349835983698379838983998409841984298439844984598469847984898499850985198529853985498559856985798589859986098619862986398649865986698679868986998709871987298739874987598769877987898799880988198829883988498859886988798889889989098919892989398949895989698979898989999009901990299039904990599069907990899099910991199129913991499159916991799189919992099219922992399249925992699279928992999309931993299339934993599369937993899399940994199429943994499459946994799489949995099519952995399549955995699579958995999609961996299639964996599669967996899699970997199729973997499759976997799789979998099819982998399849985998699879988998999909991999299939994999599969997999899991000010001100021000310004100051000610007100081000910010100111001210013100141001510016100171001810019100201002110022100231002410025100261002710028100291003010031100321003310034100351003610037100381003910040100411004210043100441004510046100471004810049100501005110052100531005410055100561005710058100591006010061100621006310064100651006610067100681006910070100711007210073100741007510076100771007810079100801008110082100831008410085100861008710088100891009010091100921009310094100951009610097100981009910100101011010210103101041010510106101071010810109101101011110112101131011410115101161011710118101191012010121101221012310124101251012610127101281012910130101311013210133101341013510136101371013810139101401014110142101431014410145101461014710148101491015010151101521015310154101551015610157101581015910160101611016210163101641016510166101671016810169101701017110172101731017410175101761017710178101791018010181101821018310184101851018610187101881018910190101911019210193101941019510196101971019810199102001020110202102031020410205102061020710208102091021010211102121021310214102151021610217102181021910220102211022210223102241022510226102271022810229102301023110232102331023410235102361023710238102391024010241102421024310244102451024610247102481024910250102511025210253102541025510256102571025810259102601026110262102631026410265102661026710268102691027010271102721027310274102751027610277102781027910280102811028210283102841028510286102871028810289102901029110292102931029410295102961029710298102991030010301103021030310304103051030610307103081030910310103111031210313103141031510316103171031810319103201032110322103231032410325103261032710328103291033010331103321033310334103351033610337103381033910340103411034210343103441034510346103471034810349103501035110352103531035410355103561035710358103591036010361103621036310364103651036610367103681036910370103711037210373103741037510376103771037810379103801038110382103831038410385103861038710388103891039010391103921039310394103951039610397103981039910400104011040210403104041040510406104071040810409104101041110412104131041410415104161041710418104191042010421104221042310424104251042610427104281042910430104311043210433104341043510436104371043810439104401044110442104431044410445104461044710448104491045010451104521045310454104551045610457104581045910460104611046210463104641046510466104671046810469104701047110472104731047410475104761047710478104791048010481104821048310484104851048610487104881048910490104911049210493104941049510496104971049810499105001050110502105031050410505105061050710508105091051010511105121051310514105151051610517105181051910520105211052210523105241052510526105271052810529105301053110532105331053410535105361053710538105391054010541105421054310544105451054610547105481054910550105511055210553105541055510556105571055810559105601056110562105631056410565105661056710568105691057010571105721057310574105751057610577105781057910580105811058210583105841058510586105871058810589105901059110592105931059410595105961059710598105991060010601106021060310604106051060610607106081060910610106111061210613106141061510616106171061810619106201062110622106231062410625106261062710628106291063010631106321063310634106351063610637106381063910640106411064210643106441064510646106471064810649106501065110652106531065410655106561065710658106591066010661106621066310664106651066610667106681066910670106711067210673106741067510676106771067810679106801068110682106831068410685106861068710688106891069010691106921069310694106951069610697106981069910700107011070210703107041070510706107071070810709107101071110712107131071410715107161071710718107191072010721107221072310724107251072610727107281072910730107311073210733107341073510736107371073810739107401074110742107431074410745107461074710748107491075010751107521075310754107551075610757107581075910760107611076210763107641076510766107671076810769107701077110772107731077410775107761077710778107791078010781107821078310784107851078610787107881078910790107911079210793107941079510796107971079810799108001080110802108031080410805108061080710808108091081010811108121081310814108151081610817108181081910820108211082210823108241082510826108271082810829108301083110832108331083410835108361083710838108391084010841108421084310844108451084610847108481084910850108511085210853108541085510856108571085810859108601086110862108631086410865108661086710868108691087010871108721087310874108751087610877108781087910880108811088210883108841088510886108871088810889108901089110892108931089410895108961089710898108991090010901109021090310904109051090610907109081090910910109111091210913109141091510916109171091810919109201092110922109231092410925109261092710928109291093010931109321093310934109351093610937109381093910940109411094210943109441094510946109471094810949109501095110952109531095410955109561095710958109591096010961109621096310964109651096610967109681096910970109711097210973109741097510976109771097810979109801098110982109831098410985109861098710988109891099010991109921099310994109951099610997109981099911000110011100211003110041100511006110071100811009110101101111012110131101411015110161101711018110191102011021110221102311024110251102611027110281102911030110311103211033110341103511036110371103811039110401104111042110431104411045110461104711048110491105011051110521105311054110551105611057110581105911060110611106211063110641106511066110671106811069110701107111072110731107411075110761107711078110791108011081110821108311084110851108611087110881108911090110911109211093110941109511096110971109811099111001110111102111031110411105111061110711108111091111011111111121111311114111151111611117111181111911120111211112211123111241112511126111271112811129111301113111132111331113411135111361113711138111391114011141111421114311144111451114611147111481114911150111511115211153111541115511156111571115811159111601116111162111631116411165111661116711168111691117011171111721117311174111751117611177111781117911180111811118211183111841118511186111871118811189111901119111192111931119411195111961119711198111991120011201112021120311204112051120611207112081120911210112111121211213112141121511216112171121811219112201122111222112231122411225112261122711228112291123011231112321123311234112351123611237112381123911240112411124211243112441124511246112471124811249112501125111252112531125411255112561125711258112591126011261112621126311264112651126611267112681126911270112711127211273112741127511276112771127811279112801128111282112831128411285112861128711288112891129011291112921129311294112951129611297112981129911300113011130211303113041130511306113071130811309113101131111312113131131411315113161131711318113191132011321113221132311324113251132611327113281132911330113311133211333113341133511336113371133811339113401134111342113431134411345113461134711348113491135011351113521135311354113551135611357113581135911360113611136211363113641136511366113671136811369113701137111372113731137411375113761137711378113791138011381113821138311384113851138611387113881138911390113911139211393113941139511396113971139811399114001140111402114031140411405114061140711408114091141011411114121141311414114151141611417114181141911420114211142211423114241142511426114271142811429114301143111432114331143411435114361143711438114391144011441114421144311444114451144611447114481144911450114511145211453114541145511456114571145811459114601146111462114631146411465114661146711468114691147011471114721147311474114751147611477114781147911480114811148211483114841148511486114871148811489114901149111492114931149411495114961149711498114991150011501115021150311504115051150611507115081150911510115111151211513115141151511516115171151811519115201152111522115231152411525115261152711528115291153011531115321153311534115351153611537115381153911540115411154211543115441154511546115471154811549115501155111552115531155411555115561155711558115591156011561115621156311564115651156611567115681156911570115711157211573115741157511576115771157811579115801158111582115831158411585115861158711588115891159011591115921159311594115951159611597115981159911600116011160211603116041160511606116071160811609116101161111612116131161411615116161161711618116191162011621116221162311624116251162611627116281162911630116311163211633116341163511636116371163811639116401164111642116431164411645116461164711648116491165011651116521165311654116551165611657116581165911660116611166211663116641166511666116671166811669116701167111672116731167411675116761167711678116791168011681116821168311684116851168611687116881168911690116911169211693116941169511696116971169811699117001170111702117031170411705117061170711708117091171011711117121171311714117151171611717117181171911720117211172211723117241172511726117271172811729117301173111732117331173411735117361173711738117391174011741117421174311744117451174611747117481174911750117511175211753117541175511756117571175811759117601176111762117631176411765117661176711768117691177011771117721177311774117751177611777117781177911780117811178211783117841178511786117871178811789117901179111792117931179411795117961179711798117991180011801118021180311804118051180611807118081180911810118111181211813118141181511816118171181811819118201182111822118231182411825118261182711828118291183011831118321183311834118351183611837118381183911840118411184211843118441184511846118471184811849118501185111852118531185411855118561185711858118591186011861118621186311864118651186611867118681186911870118711187211873118741187511876118771187811879118801188111882118831188411885118861188711888118891189011891118921189311894118951189611897118981189911900119011190211903119041190511906119071190811909119101191111912119131191411915119161191711918119191192011921119221192311924119251192611927119281192911930119311193211933119341193511936119371193811939119401194111942119431194411945119461194711948119491195011951119521195311954119551195611957119581195911960119611196211963119641196511966119671196811969119701197111972119731197411975119761197711978119791198011981119821198311984119851198611987119881198911990119911199211993119941199511996119971199811999120001200112002120031200412005120061200712008120091201012011120121201312014120151201612017120181201912020120211202212023120241202512026120271202812029120301203112032120331203412035120361203712038120391204012041120421204312044120451204612047120481204912050120511205212053120541205512056120571205812059120601206112062120631206412065120661206712068120691207012071120721207312074120751207612077120781207912080120811208212083120841208512086120871208812089120901209112092120931209412095120961209712098120991210012101121021210312104121051210612107121081210912110121111211212113121141211512116121171211812119121201212112122121231212412125121261212712128121291213012131121321213312134121351213612137121381213912140121411214212143121441214512146121471214812149121501215112152121531215412155121561215712158121591216012161121621216312164121651216612167121681216912170121711217212173121741217512176121771217812179121801218112182121831218412185121861218712188121891219012191121921219312194121951219612197121981219912200122011220212203122041220512206122071220812209122101221112212122131221412215122161221712218122191222012221122221222312224122251222612227122281222912230122311223212233122341223512236122371223812239122401224112242122431224412245122461224712248122491225012251122521225312254122551225612257122581225912260122611226212263122641226512266122671226812269122701227112272122731227412275122761227712278122791228012281122821228312284122851228612287122881228912290122911229212293122941229512296122971229812299123001230112302123031230412305123061230712308123091231012311123121231312314123151231612317123181231912320123211232212323123241232512326123271232812329123301233112332123331233412335123361233712338123391234012341123421234312344123451234612347123481234912350123511235212353123541235512356123571235812359123601236112362123631236412365123661236712368123691237012371123721237312374123751237612377123781237912380123811238212383123841238512386123871238812389123901239112392123931239412395123961239712398123991240012401124021240312404124051240612407124081240912410124111241212413124141241512416124171241812419124201242112422124231242412425124261242712428124291243012431124321243312434124351243612437124381243912440124411244212443124441244512446124471244812449124501245112452124531245412455124561245712458124591246012461124621246312464124651246612467124681246912470124711247212473124741247512476124771247812479124801248112482124831248412485124861248712488124891249012491124921249312494124951249612497124981249912500125011250212503125041250512506125071250812509125101251112512125131251412515125161251712518125191252012521125221252312524125251252612527125281252912530125311253212533125341253512536125371253812539125401254112542125431254412545125461254712548125491255012551125521255312554125551255612557125581255912560125611256212563125641256512566125671256812569125701257112572125731257412575125761257712578125791258012581125821258312584125851258612587125881258912590125911259212593125941259512596125971259812599126001260112602126031260412605126061260712608126091261012611126121261312614126151261612617126181261912620126211262212623126241262512626126271262812629126301263112632126331263412635126361263712638126391264012641126421264312644126451264612647126481264912650126511265212653126541265512656126571265812659126601266112662126631266412665126661266712668126691267012671126721267312674126751267612677126781267912680126811268212683126841268512686126871268812689126901269112692126931269412695126961269712698126991270012701127021270312704127051270612707127081270912710127111271212713127141271512716127171271812719127201272112722127231272412725127261272712728127291273012731127321273312734127351273612737127381273912740127411274212743127441274512746127471274812749127501275112752127531275412755127561275712758127591276012761127621276312764127651276612767127681276912770127711277212773127741277512776127771277812779127801278112782127831278412785127861278712788127891279012791127921279312794127951279612797127981279912800128011280212803128041280512806128071280812809128101281112812128131281412815128161281712818128191282012821128221282312824128251282612827128281282912830128311283212833128341283512836128371283812839128401284112842128431284412845128461284712848128491285012851128521285312854128551285612857128581285912860128611286212863128641286512866128671286812869128701287112872128731287412875128761287712878128791288012881128821288312884128851288612887128881288912890128911289212893128941289512896128971289812899129001290112902129031290412905129061290712908129091291012911129121291312914129151291612917129181291912920129211292212923129241292512926129271292812929129301293112932129331293412935129361293712938129391294012941129421294312944129451294612947129481294912950129511295212953129541295512956
  1. /*!
  2. * Less - Leaner CSS v3.9.0
  3. * http://lesscss.org
  4. *
  5. * Copyright (c) 2009-2018, Alexis Sellier <self@cloudhead.net>
  6. * Licensed under the Apache-2.0 License.
  7. *
  8. */
  9. /** * @license Apache-2.0
  10. */
  11. (function(f){if(typeof exports==="object"&&typeof module!=="undefined"){module.exports=f()}else if(typeof define==="function"&&define.amd){define([],f)}else{var g;if(typeof window!=="undefined"){g=window}else if(typeof global!=="undefined"){g=global}else if(typeof self!=="undefined"){g=self}else{g=this}g.less = f()}})(function(){var define,module,exports;return (function e(t,n,r){function s(o,u){if(!n[o]){if(!t[o]){var a=typeof require=="function"&&require;if(!u&&a)return a(o,!0);if(i)return i(o,!0);var f=new Error("Cannot find module '"+o+"'");throw f.code="MODULE_NOT_FOUND",f}var l=n[o]={exports:{}};t[o][0].call(l.exports,function(e){var n=t[o][1][e];return s(n?n:e)},l,l.exports,e,t,n,r)}return n[o].exports}var i=typeof require=="function"&&require;for(var o=0;o<r.length;o++)s(r[o]);return s})({1:[function(require,module,exports){
  12. var addDataAttr = require('./utils').addDataAttr,
  13. browser = require('./browser');
  14. module.exports = function(window, options) {
  15. // use options from the current script tag data attribues
  16. addDataAttr(options, browser.currentScript(window));
  17. if (options.isFileProtocol === undefined) {
  18. options.isFileProtocol = /^(file|(chrome|safari)(-extension)?|resource|qrc|app):/.test(window.location.protocol);
  19. }
  20. // Load styles asynchronously (default: false)
  21. //
  22. // This is set to `false` by default, so that the body
  23. // doesn't start loading before the stylesheets are parsed.
  24. // Setting this to `true` can result in flickering.
  25. //
  26. options.async = options.async || false;
  27. options.fileAsync = options.fileAsync || false;
  28. // Interval between watch polls
  29. options.poll = options.poll || (options.isFileProtocol ? 1000 : 1500);
  30. options.env = options.env || (window.location.hostname == '127.0.0.1' ||
  31. window.location.hostname == '0.0.0.0' ||
  32. window.location.hostname == 'localhost' ||
  33. (window.location.port &&
  34. window.location.port.length > 0) ||
  35. options.isFileProtocol ? 'development'
  36. : 'production');
  37. var dumpLineNumbers = /!dumpLineNumbers:(comments|mediaquery|all)/.exec(window.location.hash);
  38. if (dumpLineNumbers) {
  39. options.dumpLineNumbers = dumpLineNumbers[1];
  40. }
  41. if (options.useFileCache === undefined) {
  42. options.useFileCache = true;
  43. }
  44. if (options.onReady === undefined) {
  45. options.onReady = true;
  46. }
  47. if (options.relativeUrls) {
  48. options.rewriteUrls = 'all';
  49. }
  50. };
  51. },{"./browser":3,"./utils":11}],2:[function(require,module,exports){
  52. /**
  53. * Kicks off less and compiles any stylesheets
  54. * used in the browser distributed version of less
  55. * to kick-start less using the browser api
  56. */
  57. /* global window, document */
  58. // TODO - consider switching this out for a recommendation for this polyfill?
  59. // <script src="https://cdn.polyfill.io/v2/polyfill.min.js"></script>
  60. // Browsers have good Promise support
  61. require('promise/polyfill');
  62. var options = require('../less/default-options')();
  63. if (window.less) {
  64. for (key in window.less) {
  65. if (window.less.hasOwnProperty(key)) {
  66. options[key] = window.less[key];
  67. }
  68. }
  69. }
  70. require('./add-default-options')(window, options);
  71. options.plugins = options.plugins || [];
  72. if (window.LESS_PLUGINS) {
  73. options.plugins = options.plugins.concat(window.LESS_PLUGINS);
  74. }
  75. var less = module.exports = require('./index')(window, options);
  76. window.less = less;
  77. var css, head, style;
  78. // Always restore page visibility
  79. function resolveOrReject(data) {
  80. if (data.filename) {
  81. console.warn(data);
  82. }
  83. if (!options.async) {
  84. head.removeChild(style);
  85. }
  86. }
  87. if (options.onReady) {
  88. if (/!watch/.test(window.location.hash)) {
  89. less.watch();
  90. }
  91. // Simulate synchronous stylesheet loading by hiding page rendering
  92. if (!options.async) {
  93. css = 'body { display: none !important }';
  94. head = document.head || document.getElementsByTagName('head')[0];
  95. style = document.createElement('style');
  96. style.type = 'text/css';
  97. if (style.styleSheet) {
  98. style.styleSheet.cssText = css;
  99. } else {
  100. style.appendChild(document.createTextNode(css));
  101. }
  102. head.appendChild(style);
  103. }
  104. less.registerStylesheetsImmediately();
  105. less.pageLoadFinished = less.refresh(less.env === 'development').then(resolveOrReject, resolveOrReject);
  106. }
  107. },{"../less/default-options":17,"./add-default-options":1,"./index":8,"promise/polyfill":104}],3:[function(require,module,exports){
  108. var utils = require('./utils');
  109. module.exports = {
  110. createCSS: function (document, styles, sheet) {
  111. // Strip the query-string
  112. var href = sheet.href || '';
  113. // If there is no title set, use the filename, minus the extension
  114. var id = 'less:' + (sheet.title || utils.extractId(href));
  115. // If this has already been inserted into the DOM, we may need to replace it
  116. var oldStyleNode = document.getElementById(id);
  117. var keepOldStyleNode = false;
  118. // Create a new stylesheet node for insertion or (if necessary) replacement
  119. var styleNode = document.createElement('style');
  120. styleNode.setAttribute('type', 'text/css');
  121. if (sheet.media) {
  122. styleNode.setAttribute('media', sheet.media);
  123. }
  124. styleNode.id = id;
  125. if (!styleNode.styleSheet) {
  126. styleNode.appendChild(document.createTextNode(styles));
  127. // If new contents match contents of oldStyleNode, don't replace oldStyleNode
  128. keepOldStyleNode = (oldStyleNode !== null && oldStyleNode.childNodes.length > 0 && styleNode.childNodes.length > 0 &&
  129. oldStyleNode.firstChild.nodeValue === styleNode.firstChild.nodeValue);
  130. }
  131. var head = document.getElementsByTagName('head')[0];
  132. // If there is no oldStyleNode, just append; otherwise, only append if we need
  133. // to replace oldStyleNode with an updated stylesheet
  134. if (oldStyleNode === null || keepOldStyleNode === false) {
  135. var nextEl = sheet && sheet.nextSibling || null;
  136. if (nextEl) {
  137. nextEl.parentNode.insertBefore(styleNode, nextEl);
  138. } else {
  139. head.appendChild(styleNode);
  140. }
  141. }
  142. if (oldStyleNode && keepOldStyleNode === false) {
  143. oldStyleNode.parentNode.removeChild(oldStyleNode);
  144. }
  145. // For IE.
  146. // This needs to happen *after* the style element is added to the DOM, otherwise IE 7 and 8 may crash.
  147. // See http://social.msdn.microsoft.com/Forums/en-US/7e081b65-878a-4c22-8e68-c10d39c2ed32/internet-explorer-crashes-appending-style-element-to-head
  148. if (styleNode.styleSheet) {
  149. try {
  150. styleNode.styleSheet.cssText = styles;
  151. } catch (e) {
  152. throw new Error('Couldn\'t reassign styleSheet.cssText.');
  153. }
  154. }
  155. },
  156. currentScript: function(window) {
  157. var document = window.document;
  158. return document.currentScript || (function() {
  159. var scripts = document.getElementsByTagName('script');
  160. return scripts[scripts.length - 1];
  161. })();
  162. }
  163. };
  164. },{"./utils":11}],4:[function(require,module,exports){
  165. // Cache system is a bit outdated and could do with work
  166. module.exports = function(window, options, logger) {
  167. var cache = null;
  168. if (options.env !== 'development') {
  169. try {
  170. cache = (typeof window.localStorage === 'undefined') ? null : window.localStorage;
  171. } catch (_) {}
  172. }
  173. return {
  174. setCSS: function(path, lastModified, modifyVars, styles) {
  175. if (cache) {
  176. logger.info('saving ' + path + ' to cache.');
  177. try {
  178. cache.setItem(path, styles);
  179. cache.setItem(path + ':timestamp', lastModified);
  180. if (modifyVars) {
  181. cache.setItem(path + ':vars', JSON.stringify(modifyVars));
  182. }
  183. } catch (e) {
  184. // TODO - could do with adding more robust error handling
  185. logger.error('failed to save "' + path + '" to local storage for caching.');
  186. }
  187. }
  188. },
  189. getCSS: function(path, webInfo, modifyVars) {
  190. var css = cache && cache.getItem(path),
  191. timestamp = cache && cache.getItem(path + ':timestamp'),
  192. vars = cache && cache.getItem(path + ':vars');
  193. modifyVars = modifyVars || {};
  194. vars = vars || "{}"; // if not set, treat as the JSON representation of an empty object
  195. if (timestamp && webInfo.lastModified &&
  196. (new Date(webInfo.lastModified).valueOf() ===
  197. new Date(timestamp).valueOf()) &&
  198. JSON.stringify(modifyVars) === vars) {
  199. // Use local copy
  200. return css;
  201. }
  202. }
  203. };
  204. };
  205. },{}],5:[function(require,module,exports){
  206. var utils = require('./utils'),
  207. browser = require('./browser');
  208. module.exports = function(window, less, options) {
  209. function errorHTML(e, rootHref) {
  210. var id = 'less-error-message:' + utils.extractId(rootHref || '');
  211. var template = '<li><label>{line}</label><pre class="{class}">{content}</pre></li>';
  212. var elem = window.document.createElement('div'), timer, content, errors = [];
  213. var filename = e.filename || rootHref;
  214. var filenameNoPath = filename.match(/([^\/]+(\?.*)?)$/)[1];
  215. elem.id = id;
  216. elem.className = 'less-error-message';
  217. content = '<h3>' + (e.type || 'Syntax') + 'Error: ' + (e.message || 'There is an error in your .less file') +
  218. '</h3>' + '<p>in <a href="' + filename + '">' + filenameNoPath + '</a> ';
  219. var errorline = function (e, i, classname) {
  220. if (e.extract[i] !== undefined) {
  221. errors.push(template.replace(/\{line\}/, (parseInt(e.line, 10) || 0) + (i - 1))
  222. .replace(/\{class\}/, classname)
  223. .replace(/\{content\}/, e.extract[i]));
  224. }
  225. };
  226. if (e.line) {
  227. errorline(e, 0, '');
  228. errorline(e, 1, 'line');
  229. errorline(e, 2, '');
  230. content += 'on line ' + e.line + ', column ' + (e.column + 1) + ':</p>' +
  231. '<ul>' + errors.join('') + '</ul>';
  232. }
  233. if (e.stack && (e.extract || options.logLevel >= 4)) {
  234. content += '<br/>Stack Trace</br />' + e.stack.split('\n').slice(1).join('<br/>');
  235. }
  236. elem.innerHTML = content;
  237. // CSS for error messages
  238. browser.createCSS(window.document, [
  239. '.less-error-message ul, .less-error-message li {',
  240. 'list-style-type: none;',
  241. 'margin-right: 15px;',
  242. 'padding: 4px 0;',
  243. 'margin: 0;',
  244. '}',
  245. '.less-error-message label {',
  246. 'font-size: 12px;',
  247. 'margin-right: 15px;',
  248. 'padding: 4px 0;',
  249. 'color: #cc7777;',
  250. '}',
  251. '.less-error-message pre {',
  252. 'color: #dd6666;',
  253. 'padding: 4px 0;',
  254. 'margin: 0;',
  255. 'display: inline-block;',
  256. '}',
  257. '.less-error-message pre.line {',
  258. 'color: #ff0000;',
  259. '}',
  260. '.less-error-message h3 {',
  261. 'font-size: 20px;',
  262. 'font-weight: bold;',
  263. 'padding: 15px 0 5px 0;',
  264. 'margin: 0;',
  265. '}',
  266. '.less-error-message a {',
  267. 'color: #10a',
  268. '}',
  269. '.less-error-message .error {',
  270. 'color: red;',
  271. 'font-weight: bold;',
  272. 'padding-bottom: 2px;',
  273. 'border-bottom: 1px dashed red;',
  274. '}'
  275. ].join('\n'), { title: 'error-message' });
  276. elem.style.cssText = [
  277. 'font-family: Arial, sans-serif',
  278. 'border: 1px solid #e00',
  279. 'background-color: #eee',
  280. 'border-radius: 5px',
  281. '-webkit-border-radius: 5px',
  282. '-moz-border-radius: 5px',
  283. 'color: #e00',
  284. 'padding: 15px',
  285. 'margin-bottom: 15px'
  286. ].join(';');
  287. if (options.env === 'development') {
  288. timer = setInterval(function () {
  289. var document = window.document,
  290. body = document.body;
  291. if (body) {
  292. if (document.getElementById(id)) {
  293. body.replaceChild(elem, document.getElementById(id));
  294. } else {
  295. body.insertBefore(elem, body.firstChild);
  296. }
  297. clearInterval(timer);
  298. }
  299. }, 10);
  300. }
  301. }
  302. function removeErrorHTML(path) {
  303. var node = window.document.getElementById('less-error-message:' + utils.extractId(path));
  304. if (node) {
  305. node.parentNode.removeChild(node);
  306. }
  307. }
  308. function removeErrorConsole(path) {
  309. // no action
  310. }
  311. function removeError(path) {
  312. if (!options.errorReporting || options.errorReporting === 'html') {
  313. removeErrorHTML(path);
  314. } else if (options.errorReporting === 'console') {
  315. removeErrorConsole(path);
  316. } else if (typeof options.errorReporting === 'function') {
  317. options.errorReporting('remove', path);
  318. }
  319. }
  320. function errorConsole(e, rootHref) {
  321. var template = '{line} {content}';
  322. var filename = e.filename || rootHref;
  323. var errors = [];
  324. var content = (e.type || 'Syntax') + 'Error: ' + (e.message || 'There is an error in your .less file') +
  325. ' in ' + filename;
  326. var errorline = function (e, i, classname) {
  327. if (e.extract[i] !== undefined) {
  328. errors.push(template.replace(/\{line\}/, (parseInt(e.line, 10) || 0) + (i - 1))
  329. .replace(/\{class\}/, classname)
  330. .replace(/\{content\}/, e.extract[i]));
  331. }
  332. };
  333. if (e.line) {
  334. errorline(e, 0, '');
  335. errorline(e, 1, 'line');
  336. errorline(e, 2, '');
  337. content += ' on line ' + e.line + ', column ' + (e.column + 1) + ':\n' +
  338. errors.join('\n');
  339. }
  340. if (e.stack && (e.extract || options.logLevel >= 4)) {
  341. content += '\nStack Trace\n' + e.stack;
  342. }
  343. less.logger.error(content);
  344. }
  345. function error(e, rootHref) {
  346. if (!options.errorReporting || options.errorReporting === 'html') {
  347. errorHTML(e, rootHref);
  348. } else if (options.errorReporting === 'console') {
  349. errorConsole(e, rootHref);
  350. } else if (typeof options.errorReporting === 'function') {
  351. options.errorReporting('add', e, rootHref);
  352. }
  353. }
  354. return {
  355. add: error,
  356. remove: removeError
  357. };
  358. };
  359. },{"./browser":3,"./utils":11}],6:[function(require,module,exports){
  360. /* global window, XMLHttpRequest */
  361. module.exports = function(options, logger) {
  362. var AbstractFileManager = require('../less/environment/abstract-file-manager.js');
  363. var fileCache = {};
  364. // TODOS - move log somewhere. pathDiff and doing something similar in node. use pathDiff in the other browser file for the initial load
  365. var FileManager = function() {
  366. };
  367. FileManager.prototype = new AbstractFileManager();
  368. FileManager.prototype.alwaysMakePathsAbsolute = function alwaysMakePathsAbsolute() {
  369. return true;
  370. };
  371. FileManager.prototype.join = function join(basePath, laterPath) {
  372. if (!basePath) {
  373. return laterPath;
  374. }
  375. return this.extractUrlParts(laterPath, basePath).path;
  376. };
  377. FileManager.prototype.doXHR = function doXHR(url, type, callback, errback) {
  378. var xhr = new XMLHttpRequest();
  379. var async = options.isFileProtocol ? options.fileAsync : true;
  380. if (typeof xhr.overrideMimeType === 'function') {
  381. xhr.overrideMimeType('text/css');
  382. }
  383. logger.debug('XHR: Getting \'' + url + '\'');
  384. xhr.open('GET', url, async);
  385. xhr.setRequestHeader('Accept', type || 'text/x-less, text/css; q=0.9, */*; q=0.5');
  386. xhr.send(null);
  387. function handleResponse(xhr, callback, errback) {
  388. if (xhr.status >= 200 && xhr.status < 300) {
  389. callback(xhr.responseText,
  390. xhr.getResponseHeader('Last-Modified'));
  391. } else if (typeof errback === 'function') {
  392. errback(xhr.status, url);
  393. }
  394. }
  395. if (options.isFileProtocol && !options.fileAsync) {
  396. if (xhr.status === 0 || (xhr.status >= 200 && xhr.status < 300)) {
  397. callback(xhr.responseText);
  398. } else {
  399. errback(xhr.status, url);
  400. }
  401. } else if (async) {
  402. xhr.onreadystatechange = function () {
  403. if (xhr.readyState == 4) {
  404. handleResponse(xhr, callback, errback);
  405. }
  406. };
  407. } else {
  408. handleResponse(xhr, callback, errback);
  409. }
  410. };
  411. FileManager.prototype.supports = function(filename, currentDirectory, options, environment) {
  412. return true;
  413. };
  414. FileManager.prototype.clearFileCache = function() {
  415. fileCache = {};
  416. };
  417. FileManager.prototype.loadFile = function loadFile(filename, currentDirectory, options, environment) {
  418. // TODO: Add prefix support like less-node?
  419. // What about multiple paths?
  420. if (currentDirectory && !this.isPathAbsolute(filename)) {
  421. filename = currentDirectory + filename;
  422. }
  423. filename = options.ext ? this.tryAppendExtension(filename, options.ext) : filename;
  424. options = options || {};
  425. // sheet may be set to the stylesheet for the initial load or a collection of properties including
  426. // some context variables for imports
  427. var hrefParts = this.extractUrlParts(filename, window.location.href);
  428. var href = hrefParts.url;
  429. var self = this;
  430. return new Promise(function(resolve, reject) {
  431. if (options.useFileCache && fileCache[href]) {
  432. try {
  433. var lessText = fileCache[href];
  434. return resolve({ contents: lessText, filename: href, webInfo: { lastModified: new Date() }});
  435. } catch (e) {
  436. return reject({ filename: href, message: 'Error loading file ' + href + ' error was ' + e.message });
  437. }
  438. }
  439. self.doXHR(href, options.mime, function doXHRCallback(data, lastModified) {
  440. // per file cache
  441. fileCache[href] = data;
  442. // Use remote copy (re-parse)
  443. resolve({ contents: data, filename: href, webInfo: { lastModified: lastModified }});
  444. }, function doXHRError(status, url) {
  445. reject({ type: 'File', message: '\'' + url + '\' wasn\'t found (' + status + ')', href: href });
  446. });
  447. });
  448. };
  449. return FileManager;
  450. };
  451. },{"../less/environment/abstract-file-manager.js":18}],7:[function(require,module,exports){
  452. module.exports = function() {
  453. var functionRegistry = require('./../less/functions/function-registry');
  454. function imageSize() {
  455. throw {
  456. type: 'Runtime',
  457. message: 'Image size functions are not supported in browser version of less'
  458. };
  459. }
  460. var imageFunctions = {
  461. 'image-size': function(filePathNode) {
  462. imageSize(this, filePathNode);
  463. return -1;
  464. },
  465. 'image-width': function(filePathNode) {
  466. imageSize(this, filePathNode);
  467. return -1;
  468. },
  469. 'image-height': function(filePathNode) {
  470. imageSize(this, filePathNode);
  471. return -1;
  472. }
  473. };
  474. functionRegistry.addMultiple(imageFunctions);
  475. };
  476. },{"./../less/functions/function-registry":27}],8:[function(require,module,exports){
  477. //
  478. // index.js
  479. // Should expose the additional browser functions on to the less object
  480. //
  481. var addDataAttr = require('./utils').addDataAttr,
  482. browser = require('./browser');
  483. module.exports = function(window, options) {
  484. var document = window.document;
  485. var less = require('../less')();
  486. less.options = options;
  487. var environment = less.environment,
  488. FileManager = require('./file-manager')(options, less.logger),
  489. fileManager = new FileManager();
  490. environment.addFileManager(fileManager);
  491. less.FileManager = FileManager;
  492. less.PluginLoader = require('./plugin-loader');
  493. require('./log-listener')(less, options);
  494. var errors = require('./error-reporting')(window, less, options);
  495. var cache = less.cache = options.cache || require('./cache')(window, options, less.logger);
  496. require('./image-size')(less.environment);
  497. // Setup user functions - Deprecate?
  498. if (options.functions) {
  499. less.functions.functionRegistry.addMultiple(options.functions);
  500. }
  501. var typePattern = /^text\/(x-)?less$/;
  502. function clone(obj) {
  503. var cloned = {};
  504. for (var prop in obj) {
  505. if (obj.hasOwnProperty(prop)) {
  506. cloned[prop] = obj[prop];
  507. }
  508. }
  509. return cloned;
  510. }
  511. // only really needed for phantom
  512. function bind(func, thisArg) {
  513. var curryArgs = Array.prototype.slice.call(arguments, 2);
  514. return function() {
  515. var args = curryArgs.concat(Array.prototype.slice.call(arguments, 0));
  516. return func.apply(thisArg, args);
  517. };
  518. }
  519. function loadStyles(modifyVars) {
  520. var styles = document.getElementsByTagName('style'),
  521. style;
  522. for (var i = 0; i < styles.length; i++) {
  523. style = styles[i];
  524. if (style.type.match(typePattern)) {
  525. var instanceOptions = clone(options);
  526. instanceOptions.modifyVars = modifyVars;
  527. var lessText = style.innerHTML || '';
  528. instanceOptions.filename = document.location.href.replace(/#.*$/, '');
  529. /* jshint loopfunc:true */
  530. // use closure to store current style
  531. less.render(lessText, instanceOptions,
  532. bind(function(style, e, result) {
  533. if (e) {
  534. errors.add(e, 'inline');
  535. } else {
  536. style.type = 'text/css';
  537. if (style.styleSheet) {
  538. style.styleSheet.cssText = result.css;
  539. } else {
  540. style.innerHTML = result.css;
  541. }
  542. }
  543. }, null, style));
  544. }
  545. }
  546. }
  547. function loadStyleSheet(sheet, callback, reload, remaining, modifyVars) {
  548. var instanceOptions = clone(options);
  549. addDataAttr(instanceOptions, sheet);
  550. instanceOptions.mime = sheet.type;
  551. if (modifyVars) {
  552. instanceOptions.modifyVars = modifyVars;
  553. }
  554. function loadInitialFileCallback(loadedFile) {
  555. var data = loadedFile.contents,
  556. path = loadedFile.filename,
  557. webInfo = loadedFile.webInfo;
  558. var newFileInfo = {
  559. currentDirectory: fileManager.getPath(path),
  560. filename: path,
  561. rootFilename: path,
  562. rewriteUrls: instanceOptions.rewriteUrls
  563. };
  564. newFileInfo.entryPath = newFileInfo.currentDirectory;
  565. newFileInfo.rootpath = instanceOptions.rootpath || newFileInfo.currentDirectory;
  566. if (webInfo) {
  567. webInfo.remaining = remaining;
  568. var css = cache.getCSS(path, webInfo, instanceOptions.modifyVars);
  569. if (!reload && css) {
  570. webInfo.local = true;
  571. callback(null, css, data, sheet, webInfo, path);
  572. return;
  573. }
  574. }
  575. // TODO add tests around how this behaves when reloading
  576. errors.remove(path);
  577. instanceOptions.rootFileInfo = newFileInfo;
  578. less.render(data, instanceOptions, function(e, result) {
  579. if (e) {
  580. e.href = path;
  581. callback(e);
  582. } else {
  583. cache.setCSS(sheet.href, webInfo.lastModified, instanceOptions.modifyVars, result.css);
  584. callback(null, result.css, data, sheet, webInfo, path);
  585. }
  586. });
  587. }
  588. fileManager.loadFile(sheet.href, null, instanceOptions, environment)
  589. .then(function(loadedFile) {
  590. loadInitialFileCallback(loadedFile);
  591. }).catch(function(err) {
  592. console.log(err);
  593. callback(err);
  594. });
  595. }
  596. function loadStyleSheets(callback, reload, modifyVars) {
  597. for (var i = 0; i < less.sheets.length; i++) {
  598. loadStyleSheet(less.sheets[i], callback, reload, less.sheets.length - (i + 1), modifyVars);
  599. }
  600. }
  601. function initRunningMode() {
  602. if (less.env === 'development') {
  603. less.watchTimer = setInterval(function () {
  604. if (less.watchMode) {
  605. fileManager.clearFileCache();
  606. loadStyleSheets(function (e, css, _, sheet, webInfo) {
  607. if (e) {
  608. errors.add(e, e.href || sheet.href);
  609. } else if (css) {
  610. browser.createCSS(window.document, css, sheet);
  611. }
  612. });
  613. }
  614. }, options.poll);
  615. }
  616. }
  617. //
  618. // Watch mode
  619. //
  620. less.watch = function () {
  621. if (!less.watchMode ) {
  622. less.env = 'development';
  623. initRunningMode();
  624. }
  625. this.watchMode = true;
  626. return true;
  627. };
  628. less.unwatch = function () {clearInterval(less.watchTimer); this.watchMode = false; return false; };
  629. //
  630. // Synchronously get all <link> tags with the 'rel' attribute set to
  631. // "stylesheet/less".
  632. //
  633. less.registerStylesheetsImmediately = function() {
  634. var links = document.getElementsByTagName('link');
  635. less.sheets = [];
  636. for (var i = 0; i < links.length; i++) {
  637. if (links[i].rel === 'stylesheet/less' || (links[i].rel.match(/stylesheet/) &&
  638. (links[i].type.match(typePattern)))) {
  639. less.sheets.push(links[i]);
  640. }
  641. }
  642. };
  643. //
  644. // Asynchronously get all <link> tags with the 'rel' attribute set to
  645. // "stylesheet/less", returning a Promise.
  646. //
  647. less.registerStylesheets = function() {
  648. return new Promise(function(resolve, reject) {
  649. less.registerStylesheetsImmediately();
  650. resolve();
  651. });
  652. };
  653. //
  654. // With this function, it's possible to alter variables and re-render
  655. // CSS without reloading less-files
  656. //
  657. less.modifyVars = function(record) {
  658. return less.refresh(true, record, false);
  659. };
  660. less.refresh = function (reload, modifyVars, clearFileCache) {
  661. if ((reload || clearFileCache) && clearFileCache !== false) {
  662. fileManager.clearFileCache();
  663. }
  664. return new Promise(function (resolve, reject) {
  665. var startTime, endTime, totalMilliseconds, remainingSheets;
  666. startTime = endTime = new Date();
  667. // Set counter for remaining unprocessed sheets
  668. remainingSheets = less.sheets.length;
  669. if (remainingSheets === 0) {
  670. endTime = new Date();
  671. totalMilliseconds = endTime - startTime;
  672. less.logger.info('Less has finished and no sheets were loaded.');
  673. resolve({
  674. startTime: startTime,
  675. endTime: endTime,
  676. totalMilliseconds: totalMilliseconds,
  677. sheets: less.sheets.length
  678. });
  679. } else {
  680. // Relies on less.sheets array, callback seems to be guaranteed to be called for every element of the array
  681. loadStyleSheets(function (e, css, _, sheet, webInfo) {
  682. if (e) {
  683. errors.add(e, e.href || sheet.href);
  684. reject(e);
  685. return;
  686. }
  687. if (webInfo.local) {
  688. less.logger.info('Loading ' + sheet.href + ' from cache.');
  689. } else {
  690. less.logger.info('Rendered ' + sheet.href + ' successfully.');
  691. }
  692. browser.createCSS(window.document, css, sheet);
  693. less.logger.info('CSS for ' + sheet.href + ' generated in ' + (new Date() - endTime) + 'ms');
  694. // Count completed sheet
  695. remainingSheets--;
  696. // Check if the last remaining sheet was processed and then call the promise
  697. if (remainingSheets === 0) {
  698. totalMilliseconds = new Date() - startTime;
  699. less.logger.info('Less has finished. CSS generated in ' + totalMilliseconds + 'ms');
  700. resolve({
  701. startTime: startTime,
  702. endTime: endTime,
  703. totalMilliseconds: totalMilliseconds,
  704. sheets: less.sheets.length
  705. });
  706. }
  707. endTime = new Date();
  708. }, reload, modifyVars);
  709. }
  710. loadStyles(modifyVars);
  711. });
  712. };
  713. less.refreshStyles = loadStyles;
  714. return less;
  715. };
  716. },{"../less":37,"./browser":3,"./cache":4,"./error-reporting":5,"./file-manager":6,"./image-size":7,"./log-listener":9,"./plugin-loader":10,"./utils":11}],9:[function(require,module,exports){
  717. module.exports = function(less, options) {
  718. var logLevel_debug = 4,
  719. logLevel_info = 3,
  720. logLevel_warn = 2,
  721. logLevel_error = 1;
  722. // The amount of logging in the javascript console.
  723. // 3 - Debug, information and errors
  724. // 2 - Information and errors
  725. // 1 - Errors
  726. // 0 - None
  727. // Defaults to 2
  728. options.logLevel = typeof options.logLevel !== 'undefined' ? options.logLevel : (options.env === 'development' ? logLevel_info : logLevel_error);
  729. if (!options.loggers) {
  730. options.loggers = [{
  731. debug: function(msg) {
  732. if (options.logLevel >= logLevel_debug) {
  733. console.log(msg);
  734. }
  735. },
  736. info: function(msg) {
  737. if (options.logLevel >= logLevel_info) {
  738. console.log(msg);
  739. }
  740. },
  741. warn: function(msg) {
  742. if (options.logLevel >= logLevel_warn) {
  743. console.warn(msg);
  744. }
  745. },
  746. error: function(msg) {
  747. if (options.logLevel >= logLevel_error) {
  748. console.error(msg);
  749. }
  750. }
  751. }];
  752. }
  753. for (var i = 0; i < options.loggers.length; i++) {
  754. less.logger.addListener(options.loggers[i]);
  755. }
  756. };
  757. },{}],10:[function(require,module,exports){
  758. // TODO: Add tests for browser @plugin
  759. /* global window */
  760. var AbstractPluginLoader = require('../less/environment/abstract-plugin-loader.js');
  761. /**
  762. * Browser Plugin Loader
  763. */
  764. var PluginLoader = function(less) {
  765. this.less = less;
  766. // Should we shim this.require for browser? Probably not?
  767. };
  768. PluginLoader.prototype = new AbstractPluginLoader();
  769. PluginLoader.prototype.loadPlugin = function(filename, basePath, context, environment, fileManager) {
  770. return new Promise(function(fulfill, reject) {
  771. fileManager.loadFile(filename, basePath, context, environment)
  772. .then(fulfill).catch(reject);
  773. });
  774. };
  775. module.exports = PluginLoader;
  776. },{"../less/environment/abstract-plugin-loader.js":19}],11:[function(require,module,exports){
  777. module.exports = {
  778. extractId: function(href) {
  779. return href.replace(/^[a-z-]+:\/+?[^\/]+/, '') // Remove protocol & domain
  780. .replace(/[\?\&]livereload=\w+/, '') // Remove LiveReload cachebuster
  781. .replace(/^\//, '') // Remove root /
  782. .replace(/\.[a-zA-Z]+$/, '') // Remove simple extension
  783. .replace(/[^\.\w-]+/g, '-') // Replace illegal characters
  784. .replace(/\./g, ':'); // Replace dots with colons(for valid id)
  785. },
  786. addDataAttr: function(options, tag) {
  787. for (var opt in tag.dataset) {
  788. if (tag.dataset.hasOwnProperty(opt)) {
  789. if (opt === 'env' || opt === 'dumpLineNumbers' || opt === 'rootpath' || opt === 'errorReporting') {
  790. options[opt] = tag.dataset[opt];
  791. } else {
  792. try {
  793. options[opt] = JSON.parse(tag.dataset[opt]);
  794. }
  795. catch (_) {}
  796. }
  797. }
  798. }
  799. }
  800. };
  801. },{}],12:[function(require,module,exports){
  802. module.exports = {
  803. Math: {
  804. ALWAYS: 0,
  805. PARENS_DIVISION: 1,
  806. PARENS: 2,
  807. STRICT_LEGACY: 3
  808. },
  809. RewriteUrls: {
  810. OFF: 0,
  811. LOCAL: 1,
  812. ALL: 2
  813. }
  814. };
  815. },{}],13:[function(require,module,exports){
  816. var contexts = {};
  817. module.exports = contexts;
  818. var Constants = require('./constants');
  819. var copyFromOriginal = function copyFromOriginal(original, destination, propertiesToCopy) {
  820. if (!original) { return; }
  821. for (var i = 0; i < propertiesToCopy.length; i++) {
  822. if (original.hasOwnProperty(propertiesToCopy[i])) {
  823. destination[propertiesToCopy[i]] = original[propertiesToCopy[i]];
  824. }
  825. }
  826. };
  827. /*
  828. parse is used whilst parsing
  829. */
  830. var parseCopyProperties = [
  831. // options
  832. 'paths', // option - unmodified - paths to search for imports on
  833. 'rewriteUrls', // option - whether to adjust URL's to be relative
  834. 'rootpath', // option - rootpath to append to URL's
  835. 'strictImports', // option -
  836. 'insecure', // option - whether to allow imports from insecure ssl hosts
  837. 'dumpLineNumbers', // option - whether to dump line numbers
  838. 'compress', // option - whether to compress
  839. 'syncImport', // option - whether to import synchronously
  840. 'chunkInput', // option - whether to chunk input. more performant but causes parse issues.
  841. 'mime', // browser only - mime type for sheet import
  842. 'useFileCache', // browser only - whether to use the per file session cache
  843. // context
  844. 'processImports', // option & context - whether to process imports. if false then imports will not be imported.
  845. // Used by the import manager to stop multiple import visitors being created.
  846. 'pluginManager' // Used as the plugin manager for the session
  847. ];
  848. contexts.Parse = function(options) {
  849. copyFromOriginal(options, this, parseCopyProperties);
  850. if (typeof this.paths === 'string') { this.paths = [this.paths]; }
  851. };
  852. var evalCopyProperties = [
  853. 'paths', // additional include paths
  854. 'compress', // whether to compress
  855. 'ieCompat', // whether to enforce IE compatibility (IE8 data-uri)
  856. 'math', // whether math has to be within parenthesis
  857. 'strictUnits', // whether units need to evaluate correctly
  858. 'sourceMap', // whether to output a source map
  859. 'importMultiple', // whether we are currently importing multiple copies
  860. 'urlArgs', // whether to add args into url tokens
  861. 'javascriptEnabled', // option - whether Inline JavaScript is enabled. if undefined, defaults to false
  862. 'pluginManager', // Used as the plugin manager for the session
  863. 'importantScope', // used to bubble up !important statements
  864. 'rewriteUrls' // option - whether to adjust URL's to be relative
  865. ];
  866. contexts.Eval = function(options, frames) {
  867. copyFromOriginal(options, this, evalCopyProperties);
  868. if (typeof this.paths === 'string') { this.paths = [this.paths]; }
  869. this.frames = frames || [];
  870. this.importantScope = this.importantScope || [];
  871. };
  872. contexts.Eval.prototype.enterCalc = function () {
  873. if (!this.calcStack) {
  874. this.calcStack = [];
  875. }
  876. this.calcStack.push(true);
  877. this.inCalc = true;
  878. };
  879. contexts.Eval.prototype.exitCalc = function () {
  880. this.calcStack.pop();
  881. if (!this.calcStack) {
  882. this.inCalc = false;
  883. }
  884. };
  885. contexts.Eval.prototype.inParenthesis = function () {
  886. if (!this.parensStack) {
  887. this.parensStack = [];
  888. }
  889. this.parensStack.push(true);
  890. };
  891. contexts.Eval.prototype.outOfParenthesis = function () {
  892. this.parensStack.pop();
  893. };
  894. contexts.Eval.prototype.inCalc = false;
  895. contexts.Eval.prototype.mathOn = true;
  896. contexts.Eval.prototype.isMathOn = function (op) {
  897. if (!this.mathOn) {
  898. return false;
  899. }
  900. if (op === '/' && this.math !== Constants.Math.ALWAYS && (!this.parensStack || !this.parensStack.length)) {
  901. return false;
  902. }
  903. if (this.math > Constants.Math.PARENS_DIVISION) {
  904. return this.parensStack && this.parensStack.length;
  905. }
  906. return true;
  907. };
  908. contexts.Eval.prototype.pathRequiresRewrite = function (path) {
  909. var isRelative = this.rewriteUrls === Constants.RewriteUrls.LOCAL ? isPathLocalRelative : isPathRelative;
  910. return isRelative(path);
  911. };
  912. contexts.Eval.prototype.rewritePath = function (path, rootpath) {
  913. var newPath;
  914. rootpath = rootpath || '';
  915. newPath = this.normalizePath(rootpath + path);
  916. // If a path was explicit relative and the rootpath was not an absolute path
  917. // we must ensure that the new path is also explicit relative.
  918. if (isPathLocalRelative(path) &&
  919. isPathRelative(rootpath) &&
  920. isPathLocalRelative(newPath) === false) {
  921. newPath = './' + newPath;
  922. }
  923. return newPath;
  924. };
  925. contexts.Eval.prototype.normalizePath = function (path) {
  926. var
  927. segments = path.split('/').reverse(),
  928. segment;
  929. path = [];
  930. while (segments.length !== 0) {
  931. segment = segments.pop();
  932. switch ( segment ) {
  933. case '.':
  934. break;
  935. case '..':
  936. if ((path.length === 0) || (path[path.length - 1] === '..')) {
  937. path.push( segment );
  938. } else {
  939. path.pop();
  940. }
  941. break;
  942. default:
  943. path.push(segment);
  944. break;
  945. }
  946. }
  947. return path.join('/');
  948. };
  949. function isPathRelative(path) {
  950. return !/^(?:[a-z-]+:|\/|#)/i.test(path);
  951. }
  952. function isPathLocalRelative(path) {
  953. return path.charAt(0) === '.';
  954. }
  955. // todo - do the same for the toCSS ?
  956. },{"./constants":12}],14:[function(require,module,exports){
  957. module.exports = {
  958. 'aliceblue':'#f0f8ff',
  959. 'antiquewhite':'#faebd7',
  960. 'aqua':'#00ffff',
  961. 'aquamarine':'#7fffd4',
  962. 'azure':'#f0ffff',
  963. 'beige':'#f5f5dc',
  964. 'bisque':'#ffe4c4',
  965. 'black':'#000000',
  966. 'blanchedalmond':'#ffebcd',
  967. 'blue':'#0000ff',
  968. 'blueviolet':'#8a2be2',
  969. 'brown':'#a52a2a',
  970. 'burlywood':'#deb887',
  971. 'cadetblue':'#5f9ea0',
  972. 'chartreuse':'#7fff00',
  973. 'chocolate':'#d2691e',
  974. 'coral':'#ff7f50',
  975. 'cornflowerblue':'#6495ed',
  976. 'cornsilk':'#fff8dc',
  977. 'crimson':'#dc143c',
  978. 'cyan':'#00ffff',
  979. 'darkblue':'#00008b',
  980. 'darkcyan':'#008b8b',
  981. 'darkgoldenrod':'#b8860b',
  982. 'darkgray':'#a9a9a9',
  983. 'darkgrey':'#a9a9a9',
  984. 'darkgreen':'#006400',
  985. 'darkkhaki':'#bdb76b',
  986. 'darkmagenta':'#8b008b',
  987. 'darkolivegreen':'#556b2f',
  988. 'darkorange':'#ff8c00',
  989. 'darkorchid':'#9932cc',
  990. 'darkred':'#8b0000',
  991. 'darksalmon':'#e9967a',
  992. 'darkseagreen':'#8fbc8f',
  993. 'darkslateblue':'#483d8b',
  994. 'darkslategray':'#2f4f4f',
  995. 'darkslategrey':'#2f4f4f',
  996. 'darkturquoise':'#00ced1',
  997. 'darkviolet':'#9400d3',
  998. 'deeppink':'#ff1493',
  999. 'deepskyblue':'#00bfff',
  1000. 'dimgray':'#696969',
  1001. 'dimgrey':'#696969',
  1002. 'dodgerblue':'#1e90ff',
  1003. 'firebrick':'#b22222',
  1004. 'floralwhite':'#fffaf0',
  1005. 'forestgreen':'#228b22',
  1006. 'fuchsia':'#ff00ff',
  1007. 'gainsboro':'#dcdcdc',
  1008. 'ghostwhite':'#f8f8ff',
  1009. 'gold':'#ffd700',
  1010. 'goldenrod':'#daa520',
  1011. 'gray':'#808080',
  1012. 'grey':'#808080',
  1013. 'green':'#008000',
  1014. 'greenyellow':'#adff2f',
  1015. 'honeydew':'#f0fff0',
  1016. 'hotpink':'#ff69b4',
  1017. 'indianred':'#cd5c5c',
  1018. 'indigo':'#4b0082',
  1019. 'ivory':'#fffff0',
  1020. 'khaki':'#f0e68c',
  1021. 'lavender':'#e6e6fa',
  1022. 'lavenderblush':'#fff0f5',
  1023. 'lawngreen':'#7cfc00',
  1024. 'lemonchiffon':'#fffacd',
  1025. 'lightblue':'#add8e6',
  1026. 'lightcoral':'#f08080',
  1027. 'lightcyan':'#e0ffff',
  1028. 'lightgoldenrodyellow':'#fafad2',
  1029. 'lightgray':'#d3d3d3',
  1030. 'lightgrey':'#d3d3d3',
  1031. 'lightgreen':'#90ee90',
  1032. 'lightpink':'#ffb6c1',
  1033. 'lightsalmon':'#ffa07a',
  1034. 'lightseagreen':'#20b2aa',
  1035. 'lightskyblue':'#87cefa',
  1036. 'lightslategray':'#778899',
  1037. 'lightslategrey':'#778899',
  1038. 'lightsteelblue':'#b0c4de',
  1039. 'lightyellow':'#ffffe0',
  1040. 'lime':'#00ff00',
  1041. 'limegreen':'#32cd32',
  1042. 'linen':'#faf0e6',
  1043. 'magenta':'#ff00ff',
  1044. 'maroon':'#800000',
  1045. 'mediumaquamarine':'#66cdaa',
  1046. 'mediumblue':'#0000cd',
  1047. 'mediumorchid':'#ba55d3',
  1048. 'mediumpurple':'#9370d8',
  1049. 'mediumseagreen':'#3cb371',
  1050. 'mediumslateblue':'#7b68ee',
  1051. 'mediumspringgreen':'#00fa9a',
  1052. 'mediumturquoise':'#48d1cc',
  1053. 'mediumvioletred':'#c71585',
  1054. 'midnightblue':'#191970',
  1055. 'mintcream':'#f5fffa',
  1056. 'mistyrose':'#ffe4e1',
  1057. 'moccasin':'#ffe4b5',
  1058. 'navajowhite':'#ffdead',
  1059. 'navy':'#000080',
  1060. 'oldlace':'#fdf5e6',
  1061. 'olive':'#808000',
  1062. 'olivedrab':'#6b8e23',
  1063. 'orange':'#ffa500',
  1064. 'orangered':'#ff4500',
  1065. 'orchid':'#da70d6',
  1066. 'palegoldenrod':'#eee8aa',
  1067. 'palegreen':'#98fb98',
  1068. 'paleturquoise':'#afeeee',
  1069. 'palevioletred':'#d87093',
  1070. 'papayawhip':'#ffefd5',
  1071. 'peachpuff':'#ffdab9',
  1072. 'peru':'#cd853f',
  1073. 'pink':'#ffc0cb',
  1074. 'plum':'#dda0dd',
  1075. 'powderblue':'#b0e0e6',
  1076. 'purple':'#800080',
  1077. 'rebeccapurple':'#663399',
  1078. 'red':'#ff0000',
  1079. 'rosybrown':'#bc8f8f',
  1080. 'royalblue':'#4169e1',
  1081. 'saddlebrown':'#8b4513',
  1082. 'salmon':'#fa8072',
  1083. 'sandybrown':'#f4a460',
  1084. 'seagreen':'#2e8b57',
  1085. 'seashell':'#fff5ee',
  1086. 'sienna':'#a0522d',
  1087. 'silver':'#c0c0c0',
  1088. 'skyblue':'#87ceeb',
  1089. 'slateblue':'#6a5acd',
  1090. 'slategray':'#708090',
  1091. 'slategrey':'#708090',
  1092. 'snow':'#fffafa',
  1093. 'springgreen':'#00ff7f',
  1094. 'steelblue':'#4682b4',
  1095. 'tan':'#d2b48c',
  1096. 'teal':'#008080',
  1097. 'thistle':'#d8bfd8',
  1098. 'tomato':'#ff6347',
  1099. 'turquoise':'#40e0d0',
  1100. 'violet':'#ee82ee',
  1101. 'wheat':'#f5deb3',
  1102. 'white':'#ffffff',
  1103. 'whitesmoke':'#f5f5f5',
  1104. 'yellow':'#ffff00',
  1105. 'yellowgreen':'#9acd32'
  1106. };
  1107. },{}],15:[function(require,module,exports){
  1108. module.exports = {
  1109. colors: require('./colors'),
  1110. unitConversions: require('./unit-conversions')
  1111. };
  1112. },{"./colors":14,"./unit-conversions":16}],16:[function(require,module,exports){
  1113. module.exports = {
  1114. length: {
  1115. 'm': 1,
  1116. 'cm': 0.01,
  1117. 'mm': 0.001,
  1118. 'in': 0.0254,
  1119. 'px': 0.0254 / 96,
  1120. 'pt': 0.0254 / 72,
  1121. 'pc': 0.0254 / 72 * 12
  1122. },
  1123. duration: {
  1124. 's': 1,
  1125. 'ms': 0.001
  1126. },
  1127. angle: {
  1128. 'rad': 1 / (2 * Math.PI),
  1129. 'deg': 1 / 360,
  1130. 'grad': 1 / 400,
  1131. 'turn': 1
  1132. }
  1133. };
  1134. },{}],17:[function(require,module,exports){
  1135. // Export a new default each time
  1136. module.exports = function() {
  1137. return {
  1138. /* Inline Javascript - @plugin still allowed */
  1139. javascriptEnabled: false,
  1140. /* Outputs a makefile import dependency list to stdout. */
  1141. depends: false,
  1142. /* (DEPRECATED) Compress using less built-in compression.
  1143. * This does an okay job but does not utilise all the tricks of
  1144. * dedicated css compression. */
  1145. compress: false,
  1146. /* Runs the less parser and just reports errors without any output. */
  1147. lint: false,
  1148. /* Sets available include paths.
  1149. * If the file in an @import rule does not exist at that exact location,
  1150. * less will look for it at the location(s) passed to this option.
  1151. * You might use this for instance to specify a path to a library which
  1152. * you want to be referenced simply and relatively in the less files. */
  1153. paths: [],
  1154. /* color output in the terminal */
  1155. color: true,
  1156. /* The strictImports controls whether the compiler will allow an @import inside of either
  1157. * @media blocks or (a later addition) other selector blocks.
  1158. * See: https://github.com/less/less.js/issues/656 */
  1159. strictImports: false,
  1160. /* Allow Imports from Insecure HTTPS Hosts */
  1161. insecure: false,
  1162. /* Allows you to add a path to every generated import and url in your css.
  1163. * This does not affect less import statements that are processed, just ones
  1164. * that are left in the output css. */
  1165. rootpath: '',
  1166. /* By default URLs are kept as-is, so if you import a file in a sub-directory
  1167. * that references an image, exactly the same URL will be output in the css.
  1168. * This option allows you to re-write URL's in imported files so that the
  1169. * URL is always relative to the base imported file */
  1170. rewriteUrls: false,
  1171. /* Compatibility with IE8. Used for limiting data-uri length */
  1172. ieCompat: false, // true until 3.0
  1173. /* How to process math
  1174. * 0 always - eagerly try to solve all operations
  1175. * 1 parens-division - require parens for division "/"
  1176. * 2 parens | strict - require parens for all operations
  1177. * 3 strict-legacy - legacy strict behavior (super-strict)
  1178. */
  1179. math: 0,
  1180. /* Without this option, less attempts to guess at the output unit when it does maths. */
  1181. strictUnits: false,
  1182. /* Effectively the declaration is put at the top of your base Less file,
  1183. * meaning it can be used but it also can be overridden if this variable
  1184. * is defined in the file. */
  1185. globalVars: null,
  1186. /* As opposed to the global variable option, this puts the declaration at the
  1187. * end of your base file, meaning it will override anything defined in your Less file. */
  1188. modifyVars: null,
  1189. /* This option allows you to specify a argument to go on to every URL. */
  1190. urlArgs: ''
  1191. }
  1192. }
  1193. },{}],18:[function(require,module,exports){
  1194. var abstractFileManager = function() {
  1195. };
  1196. abstractFileManager.prototype.getPath = function (filename) {
  1197. var j = filename.lastIndexOf('?');
  1198. if (j > 0) {
  1199. filename = filename.slice(0, j);
  1200. }
  1201. j = filename.lastIndexOf('/');
  1202. if (j < 0) {
  1203. j = filename.lastIndexOf('\\');
  1204. }
  1205. if (j < 0) {
  1206. return '';
  1207. }
  1208. return filename.slice(0, j + 1);
  1209. };
  1210. abstractFileManager.prototype.tryAppendExtension = function(path, ext) {
  1211. return /(\.[a-z]*$)|([\?;].*)$/.test(path) ? path : path + ext;
  1212. };
  1213. abstractFileManager.prototype.tryAppendLessExtension = function(path) {
  1214. return this.tryAppendExtension(path, '.less');
  1215. };
  1216. abstractFileManager.prototype.supportsSync = function() {
  1217. return false;
  1218. };
  1219. abstractFileManager.prototype.alwaysMakePathsAbsolute = function() {
  1220. return false;
  1221. };
  1222. abstractFileManager.prototype.isPathAbsolute = function(filename) {
  1223. return (/^(?:[a-z-]+:|\/|\\|#)/i).test(filename);
  1224. };
  1225. // TODO: pull out / replace?
  1226. abstractFileManager.prototype.join = function(basePath, laterPath) {
  1227. if (!basePath) {
  1228. return laterPath;
  1229. }
  1230. return basePath + laterPath;
  1231. };
  1232. abstractFileManager.prototype.pathDiff = function pathDiff(url, baseUrl) {
  1233. // diff between two paths to create a relative path
  1234. var urlParts = this.extractUrlParts(url),
  1235. baseUrlParts = this.extractUrlParts(baseUrl),
  1236. i, max, urlDirectories, baseUrlDirectories, diff = '';
  1237. if (urlParts.hostPart !== baseUrlParts.hostPart) {
  1238. return '';
  1239. }
  1240. max = Math.max(baseUrlParts.directories.length, urlParts.directories.length);
  1241. for (i = 0; i < max; i++) {
  1242. if (baseUrlParts.directories[i] !== urlParts.directories[i]) { break; }
  1243. }
  1244. baseUrlDirectories = baseUrlParts.directories.slice(i);
  1245. urlDirectories = urlParts.directories.slice(i);
  1246. for (i = 0; i < baseUrlDirectories.length - 1; i++) {
  1247. diff += '../';
  1248. }
  1249. for (i = 0; i < urlDirectories.length - 1; i++) {
  1250. diff += urlDirectories[i] + '/';
  1251. }
  1252. return diff;
  1253. };
  1254. // helper function, not part of API
  1255. abstractFileManager.prototype.extractUrlParts = function extractUrlParts(url, baseUrl) {
  1256. // urlParts[1] = protocol://hostname/ OR /
  1257. // urlParts[2] = / if path relative to host base
  1258. // urlParts[3] = directories
  1259. // urlParts[4] = filename
  1260. // urlParts[5] = parameters
  1261. var urlPartsRegex = /^((?:[a-z-]+:)?\/{2}(?:[^\/\?#]*\/)|([\/\\]))?((?:[^\/\\\?#]*[\/\\])*)([^\/\\\?#]*)([#\?].*)?$/i,
  1262. urlParts = url.match(urlPartsRegex),
  1263. returner = {}, rawDirectories = [], directories = [], i, baseUrlParts;
  1264. if (!urlParts) {
  1265. throw new Error('Could not parse sheet href - \'' + url + '\'');
  1266. }
  1267. // Stylesheets in IE don't always return the full path
  1268. if (baseUrl && (!urlParts[1] || urlParts[2])) {
  1269. baseUrlParts = baseUrl.match(urlPartsRegex);
  1270. if (!baseUrlParts) {
  1271. throw new Error('Could not parse page url - \'' + baseUrl + '\'');
  1272. }
  1273. urlParts[1] = urlParts[1] || baseUrlParts[1] || '';
  1274. if (!urlParts[2]) {
  1275. urlParts[3] = baseUrlParts[3] + urlParts[3];
  1276. }
  1277. }
  1278. if (urlParts[3]) {
  1279. rawDirectories = urlParts[3].replace(/\\/g, '/').split('/');
  1280. // collapse '..' and skip '.'
  1281. for (i = 0; i < rawDirectories.length; i++) {
  1282. if (rawDirectories[i] === '..') {
  1283. directories.pop();
  1284. }
  1285. else if (rawDirectories[i] !== '.') {
  1286. directories.push(rawDirectories[i]);
  1287. }
  1288. }
  1289. }
  1290. returner.hostPart = urlParts[1];
  1291. returner.directories = directories;
  1292. returner.rawPath = (urlParts[1] || '') + rawDirectories.join('/');
  1293. returner.path = (urlParts[1] || '') + directories.join('/');
  1294. returner.filename = urlParts[4];
  1295. returner.fileUrl = returner.path + (urlParts[4] || '');
  1296. returner.url = returner.fileUrl + (urlParts[5] || '');
  1297. return returner;
  1298. };
  1299. module.exports = abstractFileManager;
  1300. },{}],19:[function(require,module,exports){
  1301. var functionRegistry = require('../functions/function-registry'),
  1302. LessError = require('../less-error');
  1303. var AbstractPluginLoader = function() {
  1304. // Implemented by Node.js plugin loader
  1305. this.require = function() {
  1306. return null;
  1307. }
  1308. };
  1309. AbstractPluginLoader.prototype.evalPlugin = function(contents, context, imports, pluginOptions, fileInfo) {
  1310. var loader,
  1311. registry,
  1312. pluginObj,
  1313. localModule,
  1314. pluginManager,
  1315. filename,
  1316. result;
  1317. pluginManager = context.pluginManager;
  1318. if (fileInfo) {
  1319. if (typeof fileInfo === 'string') {
  1320. filename = fileInfo;
  1321. }
  1322. else {
  1323. filename = fileInfo.filename;
  1324. }
  1325. }
  1326. var shortname = (new this.less.FileManager()).extractUrlParts(filename).filename;
  1327. if (filename) {
  1328. pluginObj = pluginManager.get(filename);
  1329. if (pluginObj) {
  1330. result = this.trySetOptions(pluginObj, filename, shortname, pluginOptions);
  1331. if (result) {
  1332. return result;
  1333. }
  1334. try {
  1335. if (pluginObj.use) {
  1336. pluginObj.use.call(this.context, pluginObj);
  1337. }
  1338. }
  1339. catch (e) {
  1340. e.message = e.message || 'Error during @plugin call';
  1341. return new LessError(e, imports, filename);
  1342. }
  1343. return pluginObj;
  1344. }
  1345. }
  1346. localModule = {
  1347. exports: {},
  1348. pluginManager: pluginManager,
  1349. fileInfo: fileInfo
  1350. };
  1351. registry = functionRegistry.create();
  1352. var registerPlugin = function(obj) {
  1353. pluginObj = obj;
  1354. };
  1355. try {
  1356. loader = new Function('module', 'require', 'registerPlugin', 'functions', 'tree', 'less', 'fileInfo', contents);
  1357. loader(localModule, this.require(filename), registerPlugin, registry, this.less.tree, this.less, fileInfo);
  1358. }
  1359. catch (e) {
  1360. return new LessError(e, imports, filename);
  1361. }
  1362. if (!pluginObj) {
  1363. pluginObj = localModule.exports;
  1364. }
  1365. pluginObj = this.validatePlugin(pluginObj, filename, shortname);
  1366. if (pluginObj instanceof LessError) {
  1367. return pluginObj;
  1368. }
  1369. if (pluginObj) {
  1370. pluginObj.imports = imports;
  1371. pluginObj.filename = filename;
  1372. // For < 3.x (or unspecified minVersion) - setOptions() before install()
  1373. if (!pluginObj.minVersion || this.compareVersion('3.0.0', pluginObj.minVersion) < 0) {
  1374. result = this.trySetOptions(pluginObj, filename, shortname, pluginOptions);
  1375. if (result) {
  1376. return result;
  1377. }
  1378. }
  1379. // Run on first load
  1380. pluginManager.addPlugin(pluginObj, fileInfo.filename, registry);
  1381. pluginObj.functions = registry.getLocalFunctions();
  1382. // Need to call setOptions again because the pluginObj might have functions
  1383. result = this.trySetOptions(pluginObj, filename, shortname, pluginOptions);
  1384. if (result) {
  1385. return result;
  1386. }
  1387. // Run every @plugin call
  1388. try {
  1389. if (pluginObj.use) {
  1390. pluginObj.use.call(this.context, pluginObj);
  1391. }
  1392. }
  1393. catch (e) {
  1394. e.message = e.message || 'Error during @plugin call';
  1395. return new LessError(e, imports, filename);
  1396. }
  1397. }
  1398. else {
  1399. return new LessError({ message: 'Not a valid plugin' }, imports, filename);
  1400. }
  1401. return pluginObj;
  1402. };
  1403. AbstractPluginLoader.prototype.trySetOptions = function(plugin, filename, name, options) {
  1404. if (options && !plugin.setOptions) {
  1405. return new LessError({
  1406. message: 'Options have been provided but the plugin ' +
  1407. name + ' does not support any options.'
  1408. });
  1409. }
  1410. try {
  1411. plugin.setOptions && plugin.setOptions(options);
  1412. }
  1413. catch (e) {
  1414. return new LessError(e);
  1415. }
  1416. };
  1417. AbstractPluginLoader.prototype.validatePlugin = function(plugin, filename, name) {
  1418. if (plugin) {
  1419. // support plugins being a function
  1420. // so that the plugin can be more usable programmatically
  1421. if (typeof plugin === 'function') {
  1422. plugin = new plugin();
  1423. }
  1424. if (plugin.minVersion) {
  1425. if (this.compareVersion(plugin.minVersion, this.less.version) < 0) {
  1426. return new LessError({
  1427. message: 'Plugin ' + name + ' requires version ' +
  1428. this.versionToString(plugin.minVersion)
  1429. });
  1430. }
  1431. }
  1432. return plugin;
  1433. }
  1434. return null;
  1435. };
  1436. AbstractPluginLoader.prototype.compareVersion = function(aVersion, bVersion) {
  1437. if (typeof aVersion === 'string') {
  1438. aVersion = aVersion.match(/^(\d+)\.?(\d+)?\.?(\d+)?/);
  1439. aVersion.shift();
  1440. }
  1441. for (var i = 0; i < aVersion.length; i++) {
  1442. if (aVersion[i] !== bVersion[i]) {
  1443. return parseInt(aVersion[i]) > parseInt(bVersion[i]) ? -1 : 1;
  1444. }
  1445. }
  1446. return 0;
  1447. };
  1448. AbstractPluginLoader.prototype.versionToString = function(version) {
  1449. var versionString = '';
  1450. for (var i = 0; i < version.length; i++) {
  1451. versionString += (versionString ? '.' : '') + version[i];
  1452. }
  1453. return versionString;
  1454. };
  1455. AbstractPluginLoader.prototype.printUsage = function(plugins) {
  1456. for (var i = 0; i < plugins.length; i++) {
  1457. var plugin = plugins[i];
  1458. if (plugin.printUsage) {
  1459. plugin.printUsage();
  1460. }
  1461. }
  1462. };
  1463. module.exports = AbstractPluginLoader;
  1464. },{"../functions/function-registry":27,"../less-error":38}],20:[function(require,module,exports){
  1465. /**
  1466. * @todo Document why this abstraction exists, and the relationship between
  1467. * environment, file managers, and plugin manager
  1468. */
  1469. var logger = require('../logger');
  1470. var environment = function(externalEnvironment, fileManagers) {
  1471. this.fileManagers = fileManagers || [];
  1472. externalEnvironment = externalEnvironment || {};
  1473. var optionalFunctions = ['encodeBase64', 'mimeLookup', 'charsetLookup', 'getSourceMapGenerator'],
  1474. requiredFunctions = [],
  1475. functions = requiredFunctions.concat(optionalFunctions);
  1476. for (var i = 0; i < functions.length; i++) {
  1477. var propName = functions[i],
  1478. environmentFunc = externalEnvironment[propName];
  1479. if (environmentFunc) {
  1480. this[propName] = environmentFunc.bind(externalEnvironment);
  1481. } else if (i < requiredFunctions.length) {
  1482. this.warn('missing required function in environment - ' + propName);
  1483. }
  1484. }
  1485. };
  1486. environment.prototype.getFileManager = function (filename, currentDirectory, options, environment, isSync) {
  1487. if (!filename) {
  1488. logger.warn('getFileManager called with no filename.. Please report this issue. continuing.');
  1489. }
  1490. if (currentDirectory == null) {
  1491. logger.warn('getFileManager called with null directory.. Please report this issue. continuing.');
  1492. }
  1493. var fileManagers = this.fileManagers;
  1494. if (options.pluginManager) {
  1495. fileManagers = [].concat(fileManagers).concat(options.pluginManager.getFileManagers());
  1496. }
  1497. for (var i = fileManagers.length - 1; i >= 0 ; i--) {
  1498. var fileManager = fileManagers[i];
  1499. if (fileManager[isSync ? 'supportsSync' : 'supports'](filename, currentDirectory, options, environment)) {
  1500. return fileManager;
  1501. }
  1502. }
  1503. return null;
  1504. };
  1505. environment.prototype.addFileManager = function (fileManager) {
  1506. this.fileManagers.push(fileManager);
  1507. };
  1508. environment.prototype.clearFileManagers = function () {
  1509. this.fileManagers = [];
  1510. };
  1511. module.exports = environment;
  1512. },{"../logger":39}],21:[function(require,module,exports){
  1513. var functionRegistry = require('./function-registry'),
  1514. Anonymous = require('../tree/anonymous'),
  1515. Keyword = require('../tree/keyword');
  1516. functionRegistry.addMultiple({
  1517. boolean: function(condition) {
  1518. return condition ? Keyword.True : Keyword.False;
  1519. },
  1520. 'if': function(condition, trueValue, falseValue) {
  1521. return condition ? trueValue
  1522. : (falseValue || new Anonymous);
  1523. }
  1524. });
  1525. },{"../tree/anonymous":50,"../tree/keyword":70,"./function-registry":27}],22:[function(require,module,exports){
  1526. var Color = require('../tree/color'),
  1527. functionRegistry = require('./function-registry');
  1528. // Color Blending
  1529. // ref: http://www.w3.org/TR/compositing-1
  1530. function colorBlend(mode, color1, color2) {
  1531. var ab = color1.alpha, cb, // backdrop
  1532. as = color2.alpha, cs, // source
  1533. ar, cr, r = []; // result
  1534. ar = as + ab * (1 - as);
  1535. for (var i = 0; i < 3; i++) {
  1536. cb = color1.rgb[i] / 255;
  1537. cs = color2.rgb[i] / 255;
  1538. cr = mode(cb, cs);
  1539. if (ar) {
  1540. cr = (as * cs + ab * (cb -
  1541. as * (cb + cs - cr))) / ar;
  1542. }
  1543. r[i] = cr * 255;
  1544. }
  1545. return new Color(r, ar);
  1546. }
  1547. var colorBlendModeFunctions = {
  1548. multiply: function(cb, cs) {
  1549. return cb * cs;
  1550. },
  1551. screen: function(cb, cs) {
  1552. return cb + cs - cb * cs;
  1553. },
  1554. overlay: function(cb, cs) {
  1555. cb *= 2;
  1556. return (cb <= 1) ?
  1557. colorBlendModeFunctions.multiply(cb, cs) :
  1558. colorBlendModeFunctions.screen(cb - 1, cs);
  1559. },
  1560. softlight: function(cb, cs) {
  1561. var d = 1, e = cb;
  1562. if (cs > 0.5) {
  1563. e = 1;
  1564. d = (cb > 0.25) ? Math.sqrt(cb)
  1565. : ((16 * cb - 12) * cb + 4) * cb;
  1566. }
  1567. return cb - (1 - 2 * cs) * e * (d - cb);
  1568. },
  1569. hardlight: function(cb, cs) {
  1570. return colorBlendModeFunctions.overlay(cs, cb);
  1571. },
  1572. difference: function(cb, cs) {
  1573. return Math.abs(cb - cs);
  1574. },
  1575. exclusion: function(cb, cs) {
  1576. return cb + cs - 2 * cb * cs;
  1577. },
  1578. // non-w3c functions:
  1579. average: function(cb, cs) {
  1580. return (cb + cs) / 2;
  1581. },
  1582. negation: function(cb, cs) {
  1583. return 1 - Math.abs(cb + cs - 1);
  1584. }
  1585. };
  1586. for (var f in colorBlendModeFunctions) {
  1587. if (colorBlendModeFunctions.hasOwnProperty(f)) {
  1588. colorBlend[f] = colorBlend.bind(null, colorBlendModeFunctions[f]);
  1589. }
  1590. }
  1591. functionRegistry.addMultiple(colorBlend);
  1592. },{"../tree/color":55,"./function-registry":27}],23:[function(require,module,exports){
  1593. var Dimension = require('../tree/dimension'),
  1594. Color = require('../tree/color'),
  1595. Quoted = require('../tree/quoted'),
  1596. Anonymous = require('../tree/anonymous'),
  1597. functionRegistry = require('./function-registry'),
  1598. colorFunctions;
  1599. function clamp(val) {
  1600. return Math.min(1, Math.max(0, val));
  1601. }
  1602. function hsla(origColor, hsl) {
  1603. var color = colorFunctions.hsla(hsl.h, hsl.s, hsl.l, hsl.a);
  1604. if (color) {
  1605. if (origColor.value &&
  1606. /^(rgb|hsl)/.test(origColor.value)) {
  1607. color.value = origColor.value;
  1608. } else {
  1609. color.value = 'rgb';
  1610. }
  1611. return color;
  1612. }
  1613. }
  1614. function number(n) {
  1615. if (n instanceof Dimension) {
  1616. return parseFloat(n.unit.is('%') ? n.value / 100 : n.value);
  1617. } else if (typeof n === 'number') {
  1618. return n;
  1619. } else {
  1620. throw {
  1621. type: 'Argument',
  1622. message: 'color functions take numbers as parameters'
  1623. };
  1624. }
  1625. }
  1626. function scaled(n, size) {
  1627. if (n instanceof Dimension && n.unit.is('%')) {
  1628. return parseFloat(n.value * size / 100);
  1629. } else {
  1630. return number(n);
  1631. }
  1632. }
  1633. colorFunctions = {
  1634. rgb: function (r, g, b) {
  1635. var color = colorFunctions.rgba(r, g, b, 1.0);
  1636. if (color) {
  1637. color.value = 'rgb';
  1638. return color;
  1639. }
  1640. },
  1641. rgba: function (r, g, b, a) {
  1642. try {
  1643. if (r instanceof Color) {
  1644. if (g) {
  1645. a = number(g);
  1646. } else {
  1647. a = r.alpha;
  1648. }
  1649. return new Color(r.rgb, a, 'rgba');
  1650. }
  1651. var rgb = [r, g, b].map(function (c) { return scaled(c, 255); });
  1652. a = number(a);
  1653. return new Color(rgb, a, 'rgba');
  1654. }
  1655. catch (e) {}
  1656. },
  1657. hsl: function (h, s, l) {
  1658. var color = colorFunctions.hsla(h, s, l, 1.0);
  1659. if (color) {
  1660. color.value = 'hsl';
  1661. return color;
  1662. }
  1663. },
  1664. hsla: function (h, s, l, a) {
  1665. try {
  1666. if (h instanceof Color) {
  1667. if (s) {
  1668. a = number(s);
  1669. } else {
  1670. a = h.alpha;
  1671. }
  1672. return new Color(h.rgb, a, 'hsla');
  1673. }
  1674. var m1, m2;
  1675. function hue(h) {
  1676. h = h < 0 ? h + 1 : (h > 1 ? h - 1 : h);
  1677. if (h * 6 < 1) {
  1678. return m1 + (m2 - m1) * h * 6;
  1679. }
  1680. else if (h * 2 < 1) {
  1681. return m2;
  1682. }
  1683. else if (h * 3 < 2) {
  1684. return m1 + (m2 - m1) * (2 / 3 - h) * 6;
  1685. }
  1686. else {
  1687. return m1;
  1688. }
  1689. }
  1690. h = (number(h) % 360) / 360;
  1691. s = clamp(number(s)); l = clamp(number(l)); a = clamp(number(a));
  1692. m2 = l <= 0.5 ? l * (s + 1) : l + s - l * s;
  1693. m1 = l * 2 - m2;
  1694. var rgb = [
  1695. hue(h + 1 / 3) * 255,
  1696. hue(h) * 255,
  1697. hue(h - 1 / 3) * 255
  1698. ];
  1699. a = number(a);
  1700. return new Color(rgb, a, 'hsla');
  1701. }
  1702. catch (e) {}
  1703. },
  1704. hsv: function(h, s, v) {
  1705. return colorFunctions.hsva(h, s, v, 1.0);
  1706. },
  1707. hsva: function(h, s, v, a) {
  1708. h = ((number(h) % 360) / 360) * 360;
  1709. s = number(s); v = number(v); a = number(a);
  1710. var i, f;
  1711. i = Math.floor((h / 60) % 6);
  1712. f = (h / 60) - i;
  1713. var vs = [v,
  1714. v * (1 - s),
  1715. v * (1 - f * s),
  1716. v * (1 - (1 - f) * s)];
  1717. var perm = [[0, 3, 1],
  1718. [2, 0, 1],
  1719. [1, 0, 3],
  1720. [1, 2, 0],
  1721. [3, 1, 0],
  1722. [0, 1, 2]];
  1723. return colorFunctions.rgba(vs[perm[i][0]] * 255,
  1724. vs[perm[i][1]] * 255,
  1725. vs[perm[i][2]] * 255,
  1726. a);
  1727. },
  1728. hue: function (color) {
  1729. return new Dimension(color.toHSL().h);
  1730. },
  1731. saturation: function (color) {
  1732. return new Dimension(color.toHSL().s * 100, '%');
  1733. },
  1734. lightness: function (color) {
  1735. return new Dimension(color.toHSL().l * 100, '%');
  1736. },
  1737. hsvhue: function(color) {
  1738. return new Dimension(color.toHSV().h);
  1739. },
  1740. hsvsaturation: function (color) {
  1741. return new Dimension(color.toHSV().s * 100, '%');
  1742. },
  1743. hsvvalue: function (color) {
  1744. return new Dimension(color.toHSV().v * 100, '%');
  1745. },
  1746. red: function (color) {
  1747. return new Dimension(color.rgb[0]);
  1748. },
  1749. green: function (color) {
  1750. return new Dimension(color.rgb[1]);
  1751. },
  1752. blue: function (color) {
  1753. return new Dimension(color.rgb[2]);
  1754. },
  1755. alpha: function (color) {
  1756. return new Dimension(color.toHSL().a);
  1757. },
  1758. luma: function (color) {
  1759. return new Dimension(color.luma() * color.alpha * 100, '%');
  1760. },
  1761. luminance: function (color) {
  1762. var luminance =
  1763. (0.2126 * color.rgb[0] / 255) +
  1764. (0.7152 * color.rgb[1] / 255) +
  1765. (0.0722 * color.rgb[2] / 255);
  1766. return new Dimension(luminance * color.alpha * 100, '%');
  1767. },
  1768. saturate: function (color, amount, method) {
  1769. // filter: saturate(3.2);
  1770. // should be kept as is, so check for color
  1771. if (!color.rgb) {
  1772. return null;
  1773. }
  1774. var hsl = color.toHSL();
  1775. if (typeof method !== 'undefined' && method.value === 'relative') {
  1776. hsl.s += hsl.s * amount.value / 100;
  1777. }
  1778. else {
  1779. hsl.s += amount.value / 100;
  1780. }
  1781. hsl.s = clamp(hsl.s);
  1782. return hsla(color, hsl);
  1783. },
  1784. desaturate: function (color, amount, method) {
  1785. var hsl = color.toHSL();
  1786. if (typeof method !== 'undefined' && method.value === 'relative') {
  1787. hsl.s -= hsl.s * amount.value / 100;
  1788. }
  1789. else {
  1790. hsl.s -= amount.value / 100;
  1791. }
  1792. hsl.s = clamp(hsl.s);
  1793. return hsla(color, hsl);
  1794. },
  1795. lighten: function (color, amount, method) {
  1796. var hsl = color.toHSL();
  1797. if (typeof method !== 'undefined' && method.value === 'relative') {
  1798. hsl.l += hsl.l * amount.value / 100;
  1799. }
  1800. else {
  1801. hsl.l += amount.value / 100;
  1802. }
  1803. hsl.l = clamp(hsl.l);
  1804. return hsla(color, hsl);
  1805. },
  1806. darken: function (color, amount, method) {
  1807. var hsl = color.toHSL();
  1808. if (typeof method !== 'undefined' && method.value === 'relative') {
  1809. hsl.l -= hsl.l * amount.value / 100;
  1810. }
  1811. else {
  1812. hsl.l -= amount.value / 100;
  1813. }
  1814. hsl.l = clamp(hsl.l);
  1815. return hsla(color, hsl);
  1816. },
  1817. fadein: function (color, amount, method) {
  1818. var hsl = color.toHSL();
  1819. if (typeof method !== 'undefined' && method.value === 'relative') {
  1820. hsl.a += hsl.a * amount.value / 100;
  1821. }
  1822. else {
  1823. hsl.a += amount.value / 100;
  1824. }
  1825. hsl.a = clamp(hsl.a);
  1826. return hsla(color, hsl);
  1827. },
  1828. fadeout: function (color, amount, method) {
  1829. var hsl = color.toHSL();
  1830. if (typeof method !== 'undefined' && method.value === 'relative') {
  1831. hsl.a -= hsl.a * amount.value / 100;
  1832. }
  1833. else {
  1834. hsl.a -= amount.value / 100;
  1835. }
  1836. hsl.a = clamp(hsl.a);
  1837. return hsla(color, hsl);
  1838. },
  1839. fade: function (color, amount) {
  1840. var hsl = color.toHSL();
  1841. hsl.a = amount.value / 100;
  1842. hsl.a = clamp(hsl.a);
  1843. return hsla(color, hsl);
  1844. },
  1845. spin: function (color, amount) {
  1846. var hsl = color.toHSL();
  1847. var hue = (hsl.h + amount.value) % 360;
  1848. hsl.h = hue < 0 ? 360 + hue : hue;
  1849. return hsla(color, hsl);
  1850. },
  1851. //
  1852. // Copyright (c) 2006-2009 Hampton Catlin, Natalie Weizenbaum, and Chris Eppstein
  1853. // http://sass-lang.com
  1854. //
  1855. mix: function (color1, color2, weight) {
  1856. if (!color1.toHSL || !color2.toHSL) {
  1857. console.log(color2.type);
  1858. console.dir(color2);
  1859. }
  1860. if (!weight) {
  1861. weight = new Dimension(50);
  1862. }
  1863. var p = weight.value / 100.0;
  1864. var w = p * 2 - 1;
  1865. var a = color1.toHSL().a - color2.toHSL().a;
  1866. var w1 = (((w * a == -1) ? w : (w + a) / (1 + w * a)) + 1) / 2.0;
  1867. var w2 = 1 - w1;
  1868. var rgb = [color1.rgb[0] * w1 + color2.rgb[0] * w2,
  1869. color1.rgb[1] * w1 + color2.rgb[1] * w2,
  1870. color1.rgb[2] * w1 + color2.rgb[2] * w2];
  1871. var alpha = color1.alpha * p + color2.alpha * (1 - p);
  1872. return new Color(rgb, alpha);
  1873. },
  1874. greyscale: function (color) {
  1875. return colorFunctions.desaturate(color, new Dimension(100));
  1876. },
  1877. contrast: function (color, dark, light, threshold) {
  1878. // filter: contrast(3.2);
  1879. // should be kept as is, so check for color
  1880. if (!color.rgb) {
  1881. return null;
  1882. }
  1883. if (typeof light === 'undefined') {
  1884. light = colorFunctions.rgba(255, 255, 255, 1.0);
  1885. }
  1886. if (typeof dark === 'undefined') {
  1887. dark = colorFunctions.rgba(0, 0, 0, 1.0);
  1888. }
  1889. // Figure out which is actually light and dark:
  1890. if (dark.luma() > light.luma()) {
  1891. var t = light;
  1892. light = dark;
  1893. dark = t;
  1894. }
  1895. if (typeof threshold === 'undefined') {
  1896. threshold = 0.43;
  1897. } else {
  1898. threshold = number(threshold);
  1899. }
  1900. if (color.luma() < threshold) {
  1901. return light;
  1902. } else {
  1903. return dark;
  1904. }
  1905. },
  1906. // Changes made in 2.7.0 - Reverted in 3.0.0
  1907. // contrast: function (color, color1, color2, threshold) {
  1908. // // Return which of `color1` and `color2` has the greatest contrast with `color`
  1909. // // according to the standard WCAG contrast ratio calculation.
  1910. // // http://www.w3.org/TR/WCAG20/#contrast-ratiodef
  1911. // // The threshold param is no longer used, in line with SASS.
  1912. // // filter: contrast(3.2);
  1913. // // should be kept as is, so check for color
  1914. // if (!color.rgb) {
  1915. // return null;
  1916. // }
  1917. // if (typeof color1 === 'undefined') {
  1918. // color1 = colorFunctions.rgba(0, 0, 0, 1.0);
  1919. // }
  1920. // if (typeof color2 === 'undefined') {
  1921. // color2 = colorFunctions.rgba(255, 255, 255, 1.0);
  1922. // }
  1923. // var contrast1, contrast2;
  1924. // var luma = color.luma();
  1925. // var luma1 = color1.luma();
  1926. // var luma2 = color2.luma();
  1927. // // Calculate contrast ratios for each color
  1928. // if (luma > luma1) {
  1929. // contrast1 = (luma + 0.05) / (luma1 + 0.05);
  1930. // } else {
  1931. // contrast1 = (luma1 + 0.05) / (luma + 0.05);
  1932. // }
  1933. // if (luma > luma2) {
  1934. // contrast2 = (luma + 0.05) / (luma2 + 0.05);
  1935. // } else {
  1936. // contrast2 = (luma2 + 0.05) / (luma + 0.05);
  1937. // }
  1938. // if (contrast1 > contrast2) {
  1939. // return color1;
  1940. // } else {
  1941. // return color2;
  1942. // }
  1943. // },
  1944. argb: function (color) {
  1945. return new Anonymous(color.toARGB());
  1946. },
  1947. color: function(c) {
  1948. if ((c instanceof Quoted) &&
  1949. (/^#([A-Fa-f0-9]{8}|[A-Fa-f0-9]{6}|[A-Fa-f0-9]{3,4})$/i.test(c.value))) {
  1950. var val = c.value.slice(1);
  1951. return new Color(val, undefined, '#' + val);
  1952. }
  1953. if ((c instanceof Color) || (c = Color.fromKeyword(c.value))) {
  1954. c.value = undefined;
  1955. return c;
  1956. }
  1957. throw {
  1958. type: 'Argument',
  1959. message: 'argument must be a color keyword or 3|4|6|8 digit hex e.g. #FFF'
  1960. };
  1961. },
  1962. tint: function(color, amount) {
  1963. return colorFunctions.mix(colorFunctions.rgb(255, 255, 255), color, amount);
  1964. },
  1965. shade: function(color, amount) {
  1966. return colorFunctions.mix(colorFunctions.rgb(0, 0, 0), color, amount);
  1967. }
  1968. };
  1969. functionRegistry.addMultiple(colorFunctions);
  1970. },{"../tree/anonymous":50,"../tree/color":55,"../tree/dimension":62,"../tree/quoted":80,"./function-registry":27}],24:[function(require,module,exports){
  1971. module.exports = function(environment) {
  1972. var Quoted = require('../tree/quoted'),
  1973. URL = require('../tree/url'),
  1974. utils = require('../utils'),
  1975. functionRegistry = require('./function-registry'),
  1976. fallback = function(functionThis, node) {
  1977. return new URL(node, functionThis.index, functionThis.currentFileInfo).eval(functionThis.context);
  1978. },
  1979. logger = require('../logger');
  1980. functionRegistry.add('data-uri', function(mimetypeNode, filePathNode) {
  1981. if (!filePathNode) {
  1982. filePathNode = mimetypeNode;
  1983. mimetypeNode = null;
  1984. }
  1985. var mimetype = mimetypeNode && mimetypeNode.value;
  1986. var filePath = filePathNode.value;
  1987. var currentFileInfo = this.currentFileInfo;
  1988. var currentDirectory = currentFileInfo.rewriteUrls ?
  1989. currentFileInfo.currentDirectory : currentFileInfo.entryPath;
  1990. var fragmentStart = filePath.indexOf('#');
  1991. var fragment = '';
  1992. if (fragmentStart !== -1) {
  1993. fragment = filePath.slice(fragmentStart);
  1994. filePath = filePath.slice(0, fragmentStart);
  1995. }
  1996. var context = utils.clone(this.context);
  1997. context.rawBuffer = true;
  1998. var fileManager = environment.getFileManager(filePath, currentDirectory, context, environment, true);
  1999. if (!fileManager) {
  2000. return fallback(this, filePathNode);
  2001. }
  2002. var useBase64 = false;
  2003. // detect the mimetype if not given
  2004. if (!mimetypeNode) {
  2005. mimetype = environment.mimeLookup(filePath);
  2006. if (mimetype === 'image/svg+xml') {
  2007. useBase64 = false;
  2008. } else {
  2009. // use base 64 unless it's an ASCII or UTF-8 format
  2010. var charset = environment.charsetLookup(mimetype);
  2011. useBase64 = ['US-ASCII', 'UTF-8'].indexOf(charset) < 0;
  2012. }
  2013. if (useBase64) { mimetype += ';base64'; }
  2014. }
  2015. else {
  2016. useBase64 = /;base64$/.test(mimetype);
  2017. }
  2018. var fileSync = fileManager.loadFileSync(filePath, currentDirectory, context, environment);
  2019. if (!fileSync.contents) {
  2020. logger.warn('Skipped data-uri embedding of ' + filePath + ' because file not found');
  2021. return fallback(this, filePathNode || mimetypeNode);
  2022. }
  2023. var buf = fileSync.contents;
  2024. if (useBase64 && !environment.encodeBase64) {
  2025. return fallback(this, filePathNode);
  2026. }
  2027. buf = useBase64 ? environment.encodeBase64(buf) : encodeURIComponent(buf);
  2028. var uri = 'data:' + mimetype + ',' + buf + fragment;
  2029. // IE8 cannot handle a data-uri larger than 32,768 characters. If this is exceeded
  2030. // and the --ieCompat flag is enabled, return a normal url() instead.
  2031. var DATA_URI_MAX = 32768;
  2032. if (uri.length >= DATA_URI_MAX) {
  2033. if (this.context.ieCompat !== false) {
  2034. logger.warn('Skipped data-uri embedding of ' + filePath + ' because its size (' + uri.length +
  2035. ' characters) exceeds IE8-safe ' + DATA_URI_MAX + ' characters!');
  2036. return fallback(this, filePathNode || mimetypeNode);
  2037. }
  2038. }
  2039. return new URL(new Quoted('"' + uri + '"', uri, false, this.index, this.currentFileInfo), this.index, this.currentFileInfo);
  2040. });
  2041. };
  2042. },{"../logger":39,"../tree/quoted":80,"../tree/url":85,"../utils":89,"./function-registry":27}],25:[function(require,module,exports){
  2043. var Keyword = require('../tree/keyword'),
  2044. functionRegistry = require('./function-registry');
  2045. var defaultFunc = {
  2046. eval: function () {
  2047. var v = this.value_, e = this.error_;
  2048. if (e) {
  2049. throw e;
  2050. }
  2051. if (v != null) {
  2052. return v ? Keyword.True : Keyword.False;
  2053. }
  2054. },
  2055. value: function (v) {
  2056. this.value_ = v;
  2057. },
  2058. error: function (e) {
  2059. this.error_ = e;
  2060. },
  2061. reset: function () {
  2062. this.value_ = this.error_ = null;
  2063. }
  2064. };
  2065. functionRegistry.add('default', defaultFunc.eval.bind(defaultFunc));
  2066. module.exports = defaultFunc;
  2067. },{"../tree/keyword":70,"./function-registry":27}],26:[function(require,module,exports){
  2068. var Expression = require('../tree/expression');
  2069. var functionCaller = function(name, context, index, currentFileInfo) {
  2070. this.name = name.toLowerCase();
  2071. this.index = index;
  2072. this.context = context;
  2073. this.currentFileInfo = currentFileInfo;
  2074. this.func = context.frames[0].functionRegistry.get(this.name);
  2075. };
  2076. functionCaller.prototype.isValid = function() {
  2077. return Boolean(this.func);
  2078. };
  2079. functionCaller.prototype.call = function(args) {
  2080. // This code is terrible and should be replaced as per this issue...
  2081. // https://github.com/less/less.js/issues/2477
  2082. if (Array.isArray(args)) {
  2083. args = args.filter(function (item) {
  2084. if (item.type === 'Comment') {
  2085. return false;
  2086. }
  2087. return true;
  2088. })
  2089. .map(function(item) {
  2090. if (item.type === 'Expression') {
  2091. var subNodes = item.value.filter(function (item) {
  2092. if (item.type === 'Comment') {
  2093. return false;
  2094. }
  2095. return true;
  2096. });
  2097. if (subNodes.length === 1) {
  2098. return subNodes[0];
  2099. } else {
  2100. return new Expression(subNodes);
  2101. }
  2102. }
  2103. return item;
  2104. });
  2105. }
  2106. return this.func.apply(this, args);
  2107. };
  2108. module.exports = functionCaller;
  2109. },{"../tree/expression":64}],27:[function(require,module,exports){
  2110. function makeRegistry( base ) {
  2111. return {
  2112. _data: {},
  2113. add: function(name, func) {
  2114. // precautionary case conversion, as later querying of
  2115. // the registry by function-caller uses lower case as well.
  2116. name = name.toLowerCase();
  2117. if (this._data.hasOwnProperty(name)) {
  2118. // TODO warn
  2119. }
  2120. this._data[name] = func;
  2121. },
  2122. addMultiple: function(functions) {
  2123. Object.keys(functions).forEach(
  2124. function(name) {
  2125. this.add(name, functions[name]);
  2126. }.bind(this));
  2127. },
  2128. get: function(name) {
  2129. return this._data[name] || ( base && base.get( name ));
  2130. },
  2131. getLocalFunctions: function() {
  2132. return this._data;
  2133. },
  2134. inherit: function() {
  2135. return makeRegistry( this );
  2136. },
  2137. create: function(base) {
  2138. return makeRegistry(base);
  2139. }
  2140. };
  2141. }
  2142. module.exports = makeRegistry( null );
  2143. },{}],28:[function(require,module,exports){
  2144. module.exports = function(environment) {
  2145. var functions = {
  2146. functionRegistry: require('./function-registry'),
  2147. functionCaller: require('./function-caller')
  2148. };
  2149. // register functions
  2150. require('./boolean');
  2151. require('./default');
  2152. require('./color');
  2153. require('./color-blending');
  2154. require('./data-uri')(environment);
  2155. require('./list');
  2156. require('./math');
  2157. require('./number');
  2158. require('./string');
  2159. require('./svg')(environment);
  2160. require('./types');
  2161. return functions;
  2162. };
  2163. },{"./boolean":21,"./color":23,"./color-blending":22,"./data-uri":24,"./default":25,"./function-caller":26,"./function-registry":27,"./list":29,"./math":31,"./number":32,"./string":33,"./svg":34,"./types":35}],29:[function(require,module,exports){
  2164. var Comment = require('../tree/comment'),
  2165. Dimension = require('../tree/dimension'),
  2166. Declaration = require('../tree/declaration'),
  2167. Expression = require('../tree/expression'),
  2168. Ruleset = require('../tree/ruleset'),
  2169. Selector = require('../tree/selector'),
  2170. Element = require('../tree/element'),
  2171. functionRegistry = require('./function-registry');
  2172. var getItemsFromNode = function(node) {
  2173. // handle non-array values as an array of length 1
  2174. // return 'undefined' if index is invalid
  2175. var items = Array.isArray(node.value) ?
  2176. node.value : Array(node);
  2177. return items;
  2178. };
  2179. functionRegistry.addMultiple({
  2180. _SELF: function(n) {
  2181. return n;
  2182. },
  2183. extract: function(values, index) {
  2184. index = index.value - 1; // (1-based index)
  2185. return getItemsFromNode(values)[index];
  2186. },
  2187. length: function(values) {
  2188. return new Dimension(getItemsFromNode(values).length);
  2189. },
  2190. /**
  2191. * Creates a Less list of incremental values.
  2192. * Modeled after Lodash's range function, also exists natively in PHP
  2193. *
  2194. * @param {Dimension} [start=1]
  2195. * @param {Dimension} end - e.g. 10 or 10px - unit is added to output
  2196. * @param {Dimension} [step=1]
  2197. */
  2198. range: function(start, end, step) {
  2199. var from, to, stepValue = 1, list = [];
  2200. if (end) {
  2201. to = end;
  2202. from = start.value;
  2203. if (step) {
  2204. stepValue = step.value;
  2205. }
  2206. }
  2207. else {
  2208. from = 1;
  2209. to = start;
  2210. }
  2211. for (var i = from; i <= to.value; i += stepValue) {
  2212. list.push(new Dimension(i, to.unit));
  2213. }
  2214. return new Expression(list);
  2215. },
  2216. each: function(list, rs) {
  2217. var rules = [], newRules, iterator;
  2218. if (list.value) {
  2219. if (Array.isArray(list.value)) {
  2220. iterator = list.value;
  2221. } else {
  2222. iterator = [list.value];
  2223. }
  2224. } else if (list.ruleset) {
  2225. iterator = list.ruleset.rules;
  2226. } else if (list.rules) {
  2227. iterator = list.rules;
  2228. } else if (Array.isArray(list)) {
  2229. iterator = list;
  2230. } else {
  2231. iterator = [list];
  2232. }
  2233. var valueName = '@value',
  2234. keyName = '@key',
  2235. indexName = '@index';
  2236. if (rs.params) {
  2237. valueName = rs.params[0] && rs.params[0].name;
  2238. keyName = rs.params[1] && rs.params[1].name;
  2239. indexName = rs.params[2] && rs.params[2].name;
  2240. rs = rs.rules;
  2241. } else {
  2242. rs = rs.ruleset;
  2243. }
  2244. for (var i = 0; i < iterator.length; i++) {
  2245. var key, value, item = iterator[i];
  2246. if (item instanceof Declaration) {
  2247. key = typeof item.name === 'string' ? item.name : item.name[0].value;
  2248. value = item.value;
  2249. } else {
  2250. key = new Dimension(i + 1);
  2251. value = item;
  2252. }
  2253. if (item instanceof Comment) {
  2254. continue;
  2255. }
  2256. newRules = rs.rules.slice(0);
  2257. if (valueName) {
  2258. newRules.push(new Declaration(valueName,
  2259. value,
  2260. false, false, this.index, this.currentFileInfo));
  2261. }
  2262. if (indexName) {
  2263. newRules.push(new Declaration(indexName,
  2264. new Dimension(i + 1),
  2265. false, false, this.index, this.currentFileInfo));
  2266. }
  2267. if (keyName) {
  2268. newRules.push(new Declaration(keyName,
  2269. key,
  2270. false, false, this.index, this.currentFileInfo));
  2271. }
  2272. rules.push(new Ruleset([ new(Selector)([ new Element("", '&') ]) ],
  2273. newRules,
  2274. rs.strictImports,
  2275. rs.visibilityInfo()
  2276. ));
  2277. }
  2278. return new Ruleset([ new(Selector)([ new Element("", '&') ]) ],
  2279. rules,
  2280. rs.strictImports,
  2281. rs.visibilityInfo()
  2282. ).eval(this.context);
  2283. }
  2284. });
  2285. },{"../tree/comment":57,"../tree/declaration":60,"../tree/dimension":62,"../tree/element":63,"../tree/expression":64,"../tree/ruleset":81,"../tree/selector":82,"./function-registry":27}],30:[function(require,module,exports){
  2286. var Dimension = require('../tree/dimension');
  2287. var MathHelper = function() {
  2288. };
  2289. MathHelper._math = function (fn, unit, n) {
  2290. if (!(n instanceof Dimension)) {
  2291. throw { type: 'Argument', message: 'argument must be a number' };
  2292. }
  2293. if (unit == null) {
  2294. unit = n.unit;
  2295. } else {
  2296. n = n.unify();
  2297. }
  2298. return new Dimension(fn(parseFloat(n.value)), unit);
  2299. };
  2300. module.exports = MathHelper;
  2301. },{"../tree/dimension":62}],31:[function(require,module,exports){
  2302. var functionRegistry = require('./function-registry'),
  2303. mathHelper = require('./math-helper.js');
  2304. var mathFunctions = {
  2305. // name, unit
  2306. ceil: null,
  2307. floor: null,
  2308. sqrt: null,
  2309. abs: null,
  2310. tan: '',
  2311. sin: '',
  2312. cos: '',
  2313. atan: 'rad',
  2314. asin: 'rad',
  2315. acos: 'rad'
  2316. };
  2317. for (var f in mathFunctions) {
  2318. if (mathFunctions.hasOwnProperty(f)) {
  2319. mathFunctions[f] = mathHelper._math.bind(null, Math[f], mathFunctions[f]);
  2320. }
  2321. }
  2322. mathFunctions.round = function (n, f) {
  2323. var fraction = typeof f === 'undefined' ? 0 : f.value;
  2324. return mathHelper._math(function(num) { return num.toFixed(fraction); }, null, n);
  2325. };
  2326. functionRegistry.addMultiple(mathFunctions);
  2327. },{"./function-registry":27,"./math-helper.js":30}],32:[function(require,module,exports){
  2328. var Dimension = require('../tree/dimension'),
  2329. Anonymous = require('../tree/anonymous'),
  2330. functionRegistry = require('./function-registry'),
  2331. mathHelper = require('./math-helper.js');
  2332. var minMax = function (isMin, args) {
  2333. args = Array.prototype.slice.call(args);
  2334. switch (args.length) {
  2335. case 0: throw { type: 'Argument', message: 'one or more arguments required' };
  2336. }
  2337. var i, j, current, currentUnified, referenceUnified, unit, unitStatic, unitClone,
  2338. order = [], // elems only contains original argument values.
  2339. values = {}; // key is the unit.toString() for unified Dimension values,
  2340. // value is the index into the order array.
  2341. for (i = 0; i < args.length; i++) {
  2342. current = args[i];
  2343. if (!(current instanceof Dimension)) {
  2344. if (Array.isArray(args[i].value)) {
  2345. Array.prototype.push.apply(args, Array.prototype.slice.call(args[i].value));
  2346. }
  2347. continue;
  2348. }
  2349. currentUnified = current.unit.toString() === '' && unitClone !== undefined ? new Dimension(current.value, unitClone).unify() : current.unify();
  2350. unit = currentUnified.unit.toString() === '' && unitStatic !== undefined ? unitStatic : currentUnified.unit.toString();
  2351. unitStatic = unit !== '' && unitStatic === undefined || unit !== '' && order[0].unify().unit.toString() === '' ? unit : unitStatic;
  2352. unitClone = unit !== '' && unitClone === undefined ? current.unit.toString() : unitClone;
  2353. j = values[''] !== undefined && unit !== '' && unit === unitStatic ? values[''] : values[unit];
  2354. if (j === undefined) {
  2355. if (unitStatic !== undefined && unit !== unitStatic) {
  2356. throw { type: 'Argument', message: 'incompatible types' };
  2357. }
  2358. values[unit] = order.length;
  2359. order.push(current);
  2360. continue;
  2361. }
  2362. referenceUnified = order[j].unit.toString() === '' && unitClone !== undefined ? new Dimension(order[j].value, unitClone).unify() : order[j].unify();
  2363. if ( isMin && currentUnified.value < referenceUnified.value ||
  2364. !isMin && currentUnified.value > referenceUnified.value) {
  2365. order[j] = current;
  2366. }
  2367. }
  2368. if (order.length == 1) {
  2369. return order[0];
  2370. }
  2371. args = order.map(function (a) { return a.toCSS(this.context); }).join(this.context.compress ? ',' : ', ');
  2372. return new Anonymous((isMin ? 'min' : 'max') + '(' + args + ')');
  2373. };
  2374. functionRegistry.addMultiple({
  2375. min: function () {
  2376. return minMax(true, arguments);
  2377. },
  2378. max: function () {
  2379. return minMax(false, arguments);
  2380. },
  2381. convert: function (val, unit) {
  2382. return val.convertTo(unit.value);
  2383. },
  2384. pi: function () {
  2385. return new Dimension(Math.PI);
  2386. },
  2387. mod: function(a, b) {
  2388. return new Dimension(a.value % b.value, a.unit);
  2389. },
  2390. pow: function(x, y) {
  2391. if (typeof x === 'number' && typeof y === 'number') {
  2392. x = new Dimension(x);
  2393. y = new Dimension(y);
  2394. } else if (!(x instanceof Dimension) || !(y instanceof Dimension)) {
  2395. throw { type: 'Argument', message: 'arguments must be numbers' };
  2396. }
  2397. return new Dimension(Math.pow(x.value, y.value), x.unit);
  2398. },
  2399. percentage: function (n) {
  2400. var result = mathHelper._math(function(num) {
  2401. return num * 100;
  2402. }, '%', n);
  2403. return result;
  2404. }
  2405. });
  2406. },{"../tree/anonymous":50,"../tree/dimension":62,"./function-registry":27,"./math-helper.js":30}],33:[function(require,module,exports){
  2407. var Quoted = require('../tree/quoted'),
  2408. Anonymous = require('../tree/anonymous'),
  2409. JavaScript = require('../tree/javascript'),
  2410. functionRegistry = require('./function-registry');
  2411. functionRegistry.addMultiple({
  2412. e: function (str) {
  2413. return new Anonymous(str instanceof JavaScript ? str.evaluated : str.value);
  2414. },
  2415. escape: function (str) {
  2416. return new Anonymous(
  2417. encodeURI(str.value).replace(/=/g, '%3D').replace(/:/g, '%3A').replace(/#/g, '%23').replace(/;/g, '%3B')
  2418. .replace(/\(/g, '%28').replace(/\)/g, '%29'));
  2419. },
  2420. replace: function (string, pattern, replacement, flags) {
  2421. var result = string.value;
  2422. replacement = (replacement.type === 'Quoted') ?
  2423. replacement.value : replacement.toCSS();
  2424. result = result.replace(new RegExp(pattern.value, flags ? flags.value : ''), replacement);
  2425. return new Quoted(string.quote || '', result, string.escaped);
  2426. },
  2427. '%': function (string /* arg, arg, ... */) {
  2428. var args = Array.prototype.slice.call(arguments, 1),
  2429. result = string.value;
  2430. for (var i = 0; i < args.length; i++) {
  2431. /* jshint loopfunc:true */
  2432. result = result.replace(/%[sda]/i, function(token) {
  2433. var value = ((args[i].type === 'Quoted') &&
  2434. token.match(/s/i)) ? args[i].value : args[i].toCSS();
  2435. return token.match(/[A-Z]$/) ? encodeURIComponent(value) : value;
  2436. });
  2437. }
  2438. result = result.replace(/%%/g, '%');
  2439. return new Quoted(string.quote || '', result, string.escaped);
  2440. }
  2441. });
  2442. },{"../tree/anonymous":50,"../tree/javascript":68,"../tree/quoted":80,"./function-registry":27}],34:[function(require,module,exports){
  2443. module.exports = function(environment) {
  2444. var Dimension = require('../tree/dimension'),
  2445. Color = require('../tree/color'),
  2446. Expression = require('../tree/expression'),
  2447. Quoted = require('../tree/quoted'),
  2448. URL = require('../tree/url'),
  2449. functionRegistry = require('./function-registry');
  2450. functionRegistry.add('svg-gradient', function(direction) {
  2451. var stops,
  2452. gradientDirectionSvg,
  2453. gradientType = 'linear',
  2454. rectangleDimension = 'x="0" y="0" width="1" height="1"',
  2455. renderEnv = {compress: false},
  2456. returner,
  2457. directionValue = direction.toCSS(renderEnv),
  2458. i, color, position, positionValue, alpha;
  2459. function throwArgumentDescriptor() {
  2460. throw { type: 'Argument',
  2461. message: 'svg-gradient expects direction, start_color [start_position], [color position,]...,' +
  2462. ' end_color [end_position] or direction, color list' };
  2463. }
  2464. if (arguments.length == 2) {
  2465. if (arguments[1].value.length < 2) {
  2466. throwArgumentDescriptor();
  2467. }
  2468. stops = arguments[1].value;
  2469. } else if (arguments.length < 3) {
  2470. throwArgumentDescriptor();
  2471. } else {
  2472. stops = Array.prototype.slice.call(arguments, 1);
  2473. }
  2474. switch (directionValue) {
  2475. case 'to bottom':
  2476. gradientDirectionSvg = 'x1="0%" y1="0%" x2="0%" y2="100%"';
  2477. break;
  2478. case 'to right':
  2479. gradientDirectionSvg = 'x1="0%" y1="0%" x2="100%" y2="0%"';
  2480. break;
  2481. case 'to bottom right':
  2482. gradientDirectionSvg = 'x1="0%" y1="0%" x2="100%" y2="100%"';
  2483. break;
  2484. case 'to top right':
  2485. gradientDirectionSvg = 'x1="0%" y1="100%" x2="100%" y2="0%"';
  2486. break;
  2487. case 'ellipse':
  2488. case 'ellipse at center':
  2489. gradientType = 'radial';
  2490. gradientDirectionSvg = 'cx="50%" cy="50%" r="75%"';
  2491. rectangleDimension = 'x="-50" y="-50" width="101" height="101"';
  2492. break;
  2493. default:
  2494. throw { type: 'Argument', message: 'svg-gradient direction must be \'to bottom\', \'to right\',' +
  2495. ' \'to bottom right\', \'to top right\' or \'ellipse at center\'' };
  2496. }
  2497. returner = '<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 1 1">' +
  2498. '<' + gradientType + 'Gradient id="g" ' + gradientDirectionSvg + '>';
  2499. for (i = 0; i < stops.length; i += 1) {
  2500. if (stops[i] instanceof Expression) {
  2501. color = stops[i].value[0];
  2502. position = stops[i].value[1];
  2503. } else {
  2504. color = stops[i];
  2505. position = undefined;
  2506. }
  2507. if (!(color instanceof Color) || (!((i === 0 || i + 1 === stops.length) && position === undefined) && !(position instanceof Dimension))) {
  2508. throwArgumentDescriptor();
  2509. }
  2510. positionValue = position ? position.toCSS(renderEnv) : i === 0 ? '0%' : '100%';
  2511. alpha = color.alpha;
  2512. returner += '<stop offset="' + positionValue + '" stop-color="' + color.toRGB() + '"' + (alpha < 1 ? ' stop-opacity="' + alpha + '"' : '') + '/>';
  2513. }
  2514. returner += '</' + gradientType + 'Gradient>' +
  2515. '<rect ' + rectangleDimension + ' fill="url(#g)" /></svg>';
  2516. returner = encodeURIComponent(returner);
  2517. returner = 'data:image/svg+xml,' + returner;
  2518. return new URL(new Quoted('\'' + returner + '\'', returner, false, this.index, this.currentFileInfo), this.index, this.currentFileInfo);
  2519. });
  2520. };
  2521. },{"../tree/color":55,"../tree/dimension":62,"../tree/expression":64,"../tree/quoted":80,"../tree/url":85,"./function-registry":27}],35:[function(require,module,exports){
  2522. var Keyword = require('../tree/keyword'),
  2523. DetachedRuleset = require('../tree/detached-ruleset'),
  2524. Dimension = require('../tree/dimension'),
  2525. Color = require('../tree/color'),
  2526. Quoted = require('../tree/quoted'),
  2527. Anonymous = require('../tree/anonymous'),
  2528. URL = require('../tree/url'),
  2529. Operation = require('../tree/operation'),
  2530. functionRegistry = require('./function-registry');
  2531. var isa = function (n, Type) {
  2532. return (n instanceof Type) ? Keyword.True : Keyword.False;
  2533. },
  2534. isunit = function (n, unit) {
  2535. if (unit === undefined) {
  2536. throw { type: 'Argument', message: 'missing the required second argument to isunit.' };
  2537. }
  2538. unit = typeof unit.value === 'string' ? unit.value : unit;
  2539. if (typeof unit !== 'string') {
  2540. throw { type: 'Argument', message: 'Second argument to isunit should be a unit or a string.' };
  2541. }
  2542. return (n instanceof Dimension) && n.unit.is(unit) ? Keyword.True : Keyword.False;
  2543. };
  2544. functionRegistry.addMultiple({
  2545. isruleset: function (n) {
  2546. return isa(n, DetachedRuleset);
  2547. },
  2548. iscolor: function (n) {
  2549. return isa(n, Color);
  2550. },
  2551. isnumber: function (n) {
  2552. return isa(n, Dimension);
  2553. },
  2554. isstring: function (n) {
  2555. return isa(n, Quoted);
  2556. },
  2557. iskeyword: function (n) {
  2558. return isa(n, Keyword);
  2559. },
  2560. isurl: function (n) {
  2561. return isa(n, URL);
  2562. },
  2563. ispixel: function (n) {
  2564. return isunit(n, 'px');
  2565. },
  2566. ispercentage: function (n) {
  2567. return isunit(n, '%');
  2568. },
  2569. isem: function (n) {
  2570. return isunit(n, 'em');
  2571. },
  2572. isunit: isunit,
  2573. unit: function (val, unit) {
  2574. if (!(val instanceof Dimension)) {
  2575. throw { type: 'Argument',
  2576. message: 'the first argument to unit must be a number' +
  2577. (val instanceof Operation ? '. Have you forgotten parenthesis?' : '') };
  2578. }
  2579. if (unit) {
  2580. if (unit instanceof Keyword) {
  2581. unit = unit.value;
  2582. } else {
  2583. unit = unit.toCSS();
  2584. }
  2585. } else {
  2586. unit = '';
  2587. }
  2588. return new Dimension(val.value, unit);
  2589. },
  2590. 'get-unit': function (n) {
  2591. return new Anonymous(n.unit);
  2592. }
  2593. });
  2594. },{"../tree/anonymous":50,"../tree/color":55,"../tree/detached-ruleset":61,"../tree/dimension":62,"../tree/keyword":70,"../tree/operation":77,"../tree/quoted":80,"../tree/url":85,"./function-registry":27}],36:[function(require,module,exports){
  2595. var contexts = require('./contexts'),
  2596. Parser = require('./parser/parser'),
  2597. LessError = require('./less-error'),
  2598. utils = require('./utils'),
  2599. PromiseConstructor = typeof Promise === 'undefined' ? require('promise') : Promise,
  2600. logger = require('./logger');
  2601. module.exports = function(environment) {
  2602. // FileInfo = {
  2603. // 'rewriteUrls' - option - whether to adjust URL's to be relative
  2604. // 'filename' - full resolved filename of current file
  2605. // 'rootpath' - path to append to normal URLs for this node
  2606. // 'currentDirectory' - path to the current file, absolute
  2607. // 'rootFilename' - filename of the base file
  2608. // 'entryPath' - absolute path to the entry file
  2609. // 'reference' - whether the file should not be output and only output parts that are referenced
  2610. var ImportManager = function(less, context, rootFileInfo) {
  2611. this.less = less;
  2612. this.rootFilename = rootFileInfo.filename;
  2613. this.paths = context.paths || []; // Search paths, when importing
  2614. this.contents = {}; // map - filename to contents of all the files
  2615. this.contentsIgnoredChars = {}; // map - filename to lines at the beginning of each file to ignore
  2616. this.mime = context.mime;
  2617. this.error = null;
  2618. this.context = context;
  2619. // Deprecated? Unused outside of here, could be useful.
  2620. this.queue = []; // Files which haven't been imported yet
  2621. this.files = {}; // Holds the imported parse trees.
  2622. };
  2623. /**
  2624. * Add an import to be imported
  2625. * @param path - the raw path
  2626. * @param tryAppendExtension - whether to try appending a file extension (.less or .js if the path has no extension)
  2627. * @param currentFileInfo - the current file info (used for instance to work out relative paths)
  2628. * @param importOptions - import options
  2629. * @param callback - callback for when it is imported
  2630. */
  2631. ImportManager.prototype.push = function (path, tryAppendExtension, currentFileInfo, importOptions, callback) {
  2632. var importManager = this,
  2633. pluginLoader = this.context.pluginManager.Loader;
  2634. this.queue.push(path);
  2635. var fileParsedFunc = function (e, root, fullPath) {
  2636. importManager.queue.splice(importManager.queue.indexOf(path), 1); // Remove the path from the queue
  2637. var importedEqualsRoot = fullPath === importManager.rootFilename;
  2638. if (importOptions.optional && e) {
  2639. callback(null, {rules:[]}, false, null);
  2640. logger.info('The file ' + fullPath + ' was skipped because it was not found and the import was marked optional.');
  2641. }
  2642. else {
  2643. // Inline imports aren't cached here.
  2644. // If we start to cache them, please make sure they won't conflict with non-inline imports of the
  2645. // same name as they used to do before this comment and the condition below have been added.
  2646. if (!importManager.files[fullPath] && !importOptions.inline) {
  2647. importManager.files[fullPath] = { root: root, options: importOptions };
  2648. }
  2649. if (e && !importManager.error) { importManager.error = e; }
  2650. callback(e, root, importedEqualsRoot, fullPath);
  2651. }
  2652. };
  2653. var newFileInfo = {
  2654. rewriteUrls: this.context.rewriteUrls,
  2655. entryPath: currentFileInfo.entryPath,
  2656. rootpath: currentFileInfo.rootpath,
  2657. rootFilename: currentFileInfo.rootFilename
  2658. };
  2659. var fileManager = environment.getFileManager(path, currentFileInfo.currentDirectory, this.context, environment);
  2660. if (!fileManager) {
  2661. fileParsedFunc({ message: 'Could not find a file-manager for ' + path });
  2662. return;
  2663. }
  2664. var loadFileCallback = function(loadedFile) {
  2665. var plugin,
  2666. resolvedFilename = loadedFile.filename,
  2667. contents = loadedFile.contents.replace(/^\uFEFF/, '');
  2668. // Pass on an updated rootpath if path of imported file is relative and file
  2669. // is in a (sub|sup) directory
  2670. //
  2671. // Examples:
  2672. // - If path of imported file is 'module/nav/nav.less' and rootpath is 'less/',
  2673. // then rootpath should become 'less/module/nav/'
  2674. // - If path of imported file is '../mixins.less' and rootpath is 'less/',
  2675. // then rootpath should become 'less/../'
  2676. newFileInfo.currentDirectory = fileManager.getPath(resolvedFilename);
  2677. if (newFileInfo.rewriteUrls) {
  2678. newFileInfo.rootpath = fileManager.join(
  2679. (importManager.context.rootpath || ''),
  2680. fileManager.pathDiff(newFileInfo.currentDirectory, newFileInfo.entryPath));
  2681. if (!fileManager.isPathAbsolute(newFileInfo.rootpath) && fileManager.alwaysMakePathsAbsolute()) {
  2682. newFileInfo.rootpath = fileManager.join(newFileInfo.entryPath, newFileInfo.rootpath);
  2683. }
  2684. }
  2685. newFileInfo.filename = resolvedFilename;
  2686. var newEnv = new contexts.Parse(importManager.context);
  2687. newEnv.processImports = false;
  2688. importManager.contents[resolvedFilename] = contents;
  2689. if (currentFileInfo.reference || importOptions.reference) {
  2690. newFileInfo.reference = true;
  2691. }
  2692. if (importOptions.isPlugin) {
  2693. plugin = pluginLoader.evalPlugin(contents, newEnv, importManager, importOptions.pluginArgs, newFileInfo);
  2694. if (plugin instanceof LessError) {
  2695. fileParsedFunc(plugin, null, resolvedFilename);
  2696. }
  2697. else {
  2698. fileParsedFunc(null, plugin, resolvedFilename);
  2699. }
  2700. } else if (importOptions.inline) {
  2701. fileParsedFunc(null, contents, resolvedFilename);
  2702. } else {
  2703. // import (multiple) parse trees apparently get altered and can't be cached.
  2704. // TODO: investigate why this is
  2705. if (importManager.files[resolvedFilename]
  2706. && !importManager.files[resolvedFilename].options.multiple
  2707. && !importOptions.multiple) {
  2708. fileParsedFunc(null, importManager.files[resolvedFilename].root, resolvedFilename);
  2709. }
  2710. else {
  2711. new Parser(newEnv, importManager, newFileInfo).parse(contents, function (e, root) {
  2712. fileParsedFunc(e, root, resolvedFilename);
  2713. });
  2714. }
  2715. }
  2716. };
  2717. var promise, context = utils.clone(this.context);
  2718. if (tryAppendExtension) {
  2719. context.ext = importOptions.isPlugin ? '.js' : '.less';
  2720. }
  2721. if (importOptions.isPlugin) {
  2722. promise = pluginLoader.loadPlugin(path, currentFileInfo.currentDirectory, context, environment, fileManager);
  2723. }
  2724. else {
  2725. promise = fileManager.loadFile(path, currentFileInfo.currentDirectory, context, environment,
  2726. function(err, loadedFile) {
  2727. if (err) {
  2728. fileParsedFunc(err);
  2729. } else {
  2730. loadFileCallback(loadedFile);
  2731. }
  2732. });
  2733. }
  2734. if (promise) {
  2735. promise.then(loadFileCallback, fileParsedFunc);
  2736. }
  2737. };
  2738. return ImportManager;
  2739. };
  2740. },{"./contexts":13,"./less-error":38,"./logger":39,"./parser/parser":44,"./utils":89,"promise":undefined}],37:[function(require,module,exports){
  2741. module.exports = function(environment, fileManagers) {
  2742. var SourceMapOutput, SourceMapBuilder, ParseTree, ImportManager, Environment;
  2743. var initial = {
  2744. version: [3, 9, 0],
  2745. data: require('./data'),
  2746. tree: require('./tree'),
  2747. Environment: (Environment = require('./environment/environment')),
  2748. AbstractFileManager: require('./environment/abstract-file-manager'),
  2749. AbstractPluginLoader: require('./environment/abstract-plugin-loader'),
  2750. environment: (environment = new Environment(environment, fileManagers)),
  2751. visitors: require('./visitors'),
  2752. Parser: require('./parser/parser'),
  2753. functions: require('./functions')(environment),
  2754. contexts: require('./contexts'),
  2755. SourceMapOutput: (SourceMapOutput = require('./source-map-output')(environment)),
  2756. SourceMapBuilder: (SourceMapBuilder = require('./source-map-builder')(SourceMapOutput, environment)),
  2757. ParseTree: (ParseTree = require('./parse-tree')(SourceMapBuilder)),
  2758. ImportManager: (ImportManager = require('./import-manager')(environment)),
  2759. render: require('./render')(environment, ParseTree, ImportManager),
  2760. parse: require('./parse')(environment, ParseTree, ImportManager),
  2761. LessError: require('./less-error'),
  2762. transformTree: require('./transform-tree'),
  2763. utils: require('./utils'),
  2764. PluginManager: require('./plugin-manager'),
  2765. logger: require('./logger')
  2766. };
  2767. // Create a public API
  2768. var ctor = function(t) {
  2769. return function() {
  2770. var obj = Object.create(t.prototype);
  2771. t.apply(obj, Array.prototype.slice.call(arguments, 0));
  2772. return obj;
  2773. };
  2774. };
  2775. var t, api = Object.create(initial);
  2776. for (var n in initial.tree) {
  2777. /* eslint guard-for-in: 0 */
  2778. t = initial.tree[n];
  2779. if (typeof t === 'function') {
  2780. api[n.toLowerCase()] = ctor(t);
  2781. }
  2782. else {
  2783. api[n] = Object.create(null);
  2784. for (var o in t) {
  2785. /* eslint guard-for-in: 0 */
  2786. api[n][o.toLowerCase()] = ctor(t[o]);
  2787. }
  2788. }
  2789. }
  2790. return api;
  2791. };
  2792. },{"./contexts":13,"./data":15,"./environment/abstract-file-manager":18,"./environment/abstract-plugin-loader":19,"./environment/environment":20,"./functions":28,"./import-manager":36,"./less-error":38,"./logger":39,"./parse":41,"./parse-tree":40,"./parser/parser":44,"./plugin-manager":45,"./render":46,"./source-map-builder":47,"./source-map-output":48,"./transform-tree":49,"./tree":67,"./utils":89,"./visitors":93}],38:[function(require,module,exports){
  2793. var utils = require('./utils');
  2794. /**
  2795. * This is a centralized class of any error that could be thrown internally (mostly by the parser).
  2796. * Besides standard .message it keeps some additional data like a path to the file where the error
  2797. * occurred along with line and column numbers.
  2798. *
  2799. * @class
  2800. * @extends Error
  2801. * @type {module.LessError}
  2802. *
  2803. * @prop {string} type
  2804. * @prop {string} filename
  2805. * @prop {number} index
  2806. * @prop {number} line
  2807. * @prop {number} column
  2808. * @prop {number} callLine
  2809. * @prop {number} callExtract
  2810. * @prop {string[]} extract
  2811. *
  2812. * @param {Object} e - An error object to wrap around or just a descriptive object
  2813. * @param {Object} fileContentMap - An object with file contents in 'contents' property (like importManager) @todo - move to fileManager?
  2814. * @param {string} [currentFilename]
  2815. */
  2816. var LessError = module.exports = function LessError(e, fileContentMap, currentFilename) {
  2817. Error.call(this);
  2818. var filename = e.filename || currentFilename;
  2819. this.message = e.message;
  2820. this.stack = e.stack;
  2821. if (fileContentMap && filename) {
  2822. var input = fileContentMap.contents[filename],
  2823. loc = utils.getLocation(e.index, input),
  2824. line = loc.line,
  2825. col = loc.column,
  2826. callLine = e.call && utils.getLocation(e.call, input).line,
  2827. lines = input ? input.split('\n') : '';
  2828. this.type = e.type || 'Syntax';
  2829. this.filename = filename;
  2830. this.index = e.index;
  2831. this.line = typeof line === 'number' ? line + 1 : null;
  2832. this.column = col;
  2833. if (!this.line && this.stack) {
  2834. var found = this.stack.match(/(<anonymous>|Function):(\d+):(\d+)/);
  2835. if (found) {
  2836. if (found[2]) {
  2837. this.line = parseInt(found[2]) - 2;
  2838. }
  2839. if (found[3]) {
  2840. this.column = parseInt(found[3]);
  2841. }
  2842. }
  2843. }
  2844. this.callLine = callLine + 1;
  2845. this.callExtract = lines[callLine];
  2846. this.extract = [
  2847. lines[this.line - 2],
  2848. lines[this.line - 1],
  2849. lines[this.line]
  2850. ];
  2851. }
  2852. };
  2853. if (typeof Object.create === 'undefined') {
  2854. var F = function () {};
  2855. F.prototype = Error.prototype;
  2856. LessError.prototype = new F();
  2857. } else {
  2858. LessError.prototype = Object.create(Error.prototype);
  2859. }
  2860. LessError.prototype.constructor = LessError;
  2861. /**
  2862. * An overridden version of the default Object.prototype.toString
  2863. * which uses additional information to create a helpful message.
  2864. *
  2865. * @param {Object} options
  2866. * @returns {string}
  2867. */
  2868. LessError.prototype.toString = function(options) {
  2869. options = options || {};
  2870. var message = '';
  2871. var extract = this.extract || [];
  2872. var error = [];
  2873. var stylize = function (str) { return str; };
  2874. if (options.stylize) {
  2875. var type = typeof options.stylize;
  2876. if (type !== 'function') {
  2877. throw Error('options.stylize should be a function, got a ' + type + '!');
  2878. }
  2879. stylize = options.stylize;
  2880. }
  2881. if (this.line !== null) {
  2882. if (typeof extract[0] === 'string') {
  2883. error.push(stylize((this.line - 1) + ' ' + extract[0], 'grey'));
  2884. }
  2885. if (typeof extract[1] === 'string') {
  2886. var errorTxt = this.line + ' ';
  2887. if (extract[1]) {
  2888. errorTxt += extract[1].slice(0, this.column) +
  2889. stylize(stylize(stylize(extract[1].substr(this.column, 1), 'bold') +
  2890. extract[1].slice(this.column + 1), 'red'), 'inverse');
  2891. }
  2892. error.push(errorTxt);
  2893. }
  2894. if (typeof extract[2] === 'string') {
  2895. error.push(stylize((this.line + 1) + ' ' + extract[2], 'grey'));
  2896. }
  2897. error = error.join('\n') + stylize('', 'reset') + '\n';
  2898. }
  2899. message += stylize(this.type + 'Error: ' + this.message, 'red');
  2900. if (this.filename) {
  2901. message += stylize(' in ', 'red') + this.filename;
  2902. }
  2903. if (this.line) {
  2904. message += stylize(' on line ' + this.line + ', column ' + (this.column + 1) + ':', 'grey');
  2905. }
  2906. message += '\n' + error;
  2907. if (this.callLine) {
  2908. message += stylize('from ', 'red') + (this.filename || '') + '/n';
  2909. message += stylize(this.callLine, 'grey') + ' ' + this.callExtract + '/n';
  2910. }
  2911. return message;
  2912. };
  2913. },{"./utils":89}],39:[function(require,module,exports){
  2914. module.exports = {
  2915. error: function(msg) {
  2916. this._fireEvent('error', msg);
  2917. },
  2918. warn: function(msg) {
  2919. this._fireEvent('warn', msg);
  2920. },
  2921. info: function(msg) {
  2922. this._fireEvent('info', msg);
  2923. },
  2924. debug: function(msg) {
  2925. this._fireEvent('debug', msg);
  2926. },
  2927. addListener: function(listener) {
  2928. this._listeners.push(listener);
  2929. },
  2930. removeListener: function(listener) {
  2931. for (var i = 0; i < this._listeners.length; i++) {
  2932. if (this._listeners[i] === listener) {
  2933. this._listeners.splice(i, 1);
  2934. return;
  2935. }
  2936. }
  2937. },
  2938. _fireEvent: function(type, msg) {
  2939. for (var i = 0; i < this._listeners.length; i++) {
  2940. var logFunction = this._listeners[i][type];
  2941. if (logFunction) {
  2942. logFunction(msg);
  2943. }
  2944. }
  2945. },
  2946. _listeners: []
  2947. };
  2948. },{}],40:[function(require,module,exports){
  2949. var LessError = require('./less-error'),
  2950. transformTree = require('./transform-tree'),
  2951. logger = require('./logger');
  2952. module.exports = function(SourceMapBuilder) {
  2953. var ParseTree = function(root, imports) {
  2954. this.root = root;
  2955. this.imports = imports;
  2956. };
  2957. ParseTree.prototype.toCSS = function(options) {
  2958. var evaldRoot, result = {}, sourceMapBuilder;
  2959. try {
  2960. evaldRoot = transformTree(this.root, options);
  2961. } catch (e) {
  2962. throw new LessError(e, this.imports);
  2963. }
  2964. try {
  2965. var compress = Boolean(options.compress);
  2966. if (compress) {
  2967. logger.warn('The compress option has been deprecated. We recommend you use a dedicated css minifier, for instance see less-plugin-clean-css.');
  2968. }
  2969. var toCSSOptions = {
  2970. compress: compress,
  2971. dumpLineNumbers: options.dumpLineNumbers,
  2972. strictUnits: Boolean(options.strictUnits),
  2973. numPrecision: 8};
  2974. if (options.sourceMap) {
  2975. sourceMapBuilder = new SourceMapBuilder(options.sourceMap);
  2976. result.css = sourceMapBuilder.toCSS(evaldRoot, toCSSOptions, this.imports);
  2977. } else {
  2978. result.css = evaldRoot.toCSS(toCSSOptions);
  2979. }
  2980. } catch (e) {
  2981. throw new LessError(e, this.imports);
  2982. }
  2983. if (options.pluginManager) {
  2984. var postProcessors = options.pluginManager.getPostProcessors();
  2985. for (var i = 0; i < postProcessors.length; i++) {
  2986. result.css = postProcessors[i].process(result.css, { sourceMap: sourceMapBuilder, options: options, imports: this.imports });
  2987. }
  2988. }
  2989. if (options.sourceMap) {
  2990. result.map = sourceMapBuilder.getExternalSourceMap();
  2991. }
  2992. result.imports = [];
  2993. for (var file in this.imports.files) {
  2994. if (this.imports.files.hasOwnProperty(file) && file !== this.imports.rootFilename) {
  2995. result.imports.push(file);
  2996. }
  2997. }
  2998. return result;
  2999. };
  3000. return ParseTree;
  3001. };
  3002. },{"./less-error":38,"./logger":39,"./transform-tree":49}],41:[function(require,module,exports){
  3003. var PromiseConstructor,
  3004. contexts = require('./contexts'),
  3005. Parser = require('./parser/parser'),
  3006. PluginManager = require('./plugin-manager'),
  3007. LessError = require('./less-error'),
  3008. utils = require('./utils');
  3009. module.exports = function(environment, ParseTree, ImportManager) {
  3010. var parse = function (input, options, callback) {
  3011. if (typeof options === 'function') {
  3012. callback = options;
  3013. options = utils.copyOptions(this.options, {});
  3014. }
  3015. else {
  3016. options = utils.copyOptions(this.options, options || {});
  3017. }
  3018. if (!callback) {
  3019. if (!PromiseConstructor) {
  3020. PromiseConstructor = typeof Promise === 'undefined' ? require('promise') : Promise;
  3021. }
  3022. var self = this;
  3023. return new PromiseConstructor(function (resolve, reject) {
  3024. parse.call(self, input, options, function(err, output) {
  3025. if (err) {
  3026. reject(err);
  3027. } else {
  3028. resolve(output);
  3029. }
  3030. });
  3031. });
  3032. } else {
  3033. var context,
  3034. rootFileInfo,
  3035. pluginManager = new PluginManager(this, !options.reUsePluginManager);
  3036. options.pluginManager = pluginManager;
  3037. context = new contexts.Parse(options);
  3038. if (options.rootFileInfo) {
  3039. rootFileInfo = options.rootFileInfo;
  3040. } else {
  3041. var filename = options.filename || 'input';
  3042. var entryPath = filename.replace(/[^\/\\]*$/, '');
  3043. rootFileInfo = {
  3044. filename: filename,
  3045. rewriteUrls: context.rewriteUrls,
  3046. rootpath: context.rootpath || '',
  3047. currentDirectory: entryPath,
  3048. entryPath: entryPath,
  3049. rootFilename: filename
  3050. };
  3051. // add in a missing trailing slash
  3052. if (rootFileInfo.rootpath && rootFileInfo.rootpath.slice(-1) !== '/') {
  3053. rootFileInfo.rootpath += '/';
  3054. }
  3055. }
  3056. var imports = new ImportManager(this, context, rootFileInfo);
  3057. this.importManager = imports;
  3058. // TODO: allow the plugins to be just a list of paths or names
  3059. // Do an async plugin queue like lessc
  3060. if (options.plugins) {
  3061. options.plugins.forEach(function(plugin) {
  3062. var evalResult, contents;
  3063. if (plugin.fileContent) {
  3064. contents = plugin.fileContent.replace(/^\uFEFF/, '');
  3065. evalResult = pluginManager.Loader.evalPlugin(contents, context, imports, plugin.options, plugin.filename);
  3066. if (evalResult instanceof LessError) {
  3067. return callback(evalResult);
  3068. }
  3069. }
  3070. else {
  3071. pluginManager.addPlugin(plugin);
  3072. }
  3073. });
  3074. }
  3075. new Parser(context, imports, rootFileInfo)
  3076. .parse(input, function (e, root) {
  3077. if (e) { return callback(e); }
  3078. callback(null, root, imports, options);
  3079. }, options);
  3080. }
  3081. };
  3082. return parse;
  3083. };
  3084. },{"./contexts":13,"./less-error":38,"./parser/parser":44,"./plugin-manager":45,"./utils":89,"promise":undefined}],42:[function(require,module,exports){
  3085. // Split the input into chunks.
  3086. module.exports = function (input, fail) {
  3087. var len = input.length, level = 0, parenLevel = 0,
  3088. lastOpening, lastOpeningParen, lastMultiComment, lastMultiCommentEndBrace,
  3089. chunks = [], emitFrom = 0,
  3090. chunkerCurrentIndex, currentChunkStartIndex, cc, cc2, matched;
  3091. function emitChunk(force) {
  3092. var len = chunkerCurrentIndex - emitFrom;
  3093. if (((len < 512) && !force) || !len) {
  3094. return;
  3095. }
  3096. chunks.push(input.slice(emitFrom, chunkerCurrentIndex + 1));
  3097. emitFrom = chunkerCurrentIndex + 1;
  3098. }
  3099. for (chunkerCurrentIndex = 0; chunkerCurrentIndex < len; chunkerCurrentIndex++) {
  3100. cc = input.charCodeAt(chunkerCurrentIndex);
  3101. if (((cc >= 97) && (cc <= 122)) || (cc < 34)) {
  3102. // a-z or whitespace
  3103. continue;
  3104. }
  3105. switch (cc) {
  3106. case 40: // (
  3107. parenLevel++;
  3108. lastOpeningParen = chunkerCurrentIndex;
  3109. continue;
  3110. case 41: // )
  3111. if (--parenLevel < 0) {
  3112. return fail('missing opening `(`', chunkerCurrentIndex);
  3113. }
  3114. continue;
  3115. case 59: // ;
  3116. if (!parenLevel) { emitChunk(); }
  3117. continue;
  3118. case 123: // {
  3119. level++;
  3120. lastOpening = chunkerCurrentIndex;
  3121. continue;
  3122. case 125: // }
  3123. if (--level < 0) {
  3124. return fail('missing opening `{`', chunkerCurrentIndex);
  3125. }
  3126. if (!level && !parenLevel) { emitChunk(); }
  3127. continue;
  3128. case 92: // \
  3129. if (chunkerCurrentIndex < len - 1) { chunkerCurrentIndex++; continue; }
  3130. return fail('unescaped `\\`', chunkerCurrentIndex);
  3131. case 34:
  3132. case 39:
  3133. case 96: // ", ' and `
  3134. matched = 0;
  3135. currentChunkStartIndex = chunkerCurrentIndex;
  3136. for (chunkerCurrentIndex = chunkerCurrentIndex + 1; chunkerCurrentIndex < len; chunkerCurrentIndex++) {
  3137. cc2 = input.charCodeAt(chunkerCurrentIndex);
  3138. if (cc2 > 96) { continue; }
  3139. if (cc2 == cc) { matched = 1; break; }
  3140. if (cc2 == 92) { // \
  3141. if (chunkerCurrentIndex == len - 1) {
  3142. return fail('unescaped `\\`', chunkerCurrentIndex);
  3143. }
  3144. chunkerCurrentIndex++;
  3145. }
  3146. }
  3147. if (matched) { continue; }
  3148. return fail('unmatched `' + String.fromCharCode(cc) + '`', currentChunkStartIndex);
  3149. case 47: // /, check for comment
  3150. if (parenLevel || (chunkerCurrentIndex == len - 1)) { continue; }
  3151. cc2 = input.charCodeAt(chunkerCurrentIndex + 1);
  3152. if (cc2 == 47) {
  3153. // //, find lnfeed
  3154. for (chunkerCurrentIndex = chunkerCurrentIndex + 2; chunkerCurrentIndex < len; chunkerCurrentIndex++) {
  3155. cc2 = input.charCodeAt(chunkerCurrentIndex);
  3156. if ((cc2 <= 13) && ((cc2 == 10) || (cc2 == 13))) { break; }
  3157. }
  3158. } else if (cc2 == 42) {
  3159. // /*, find */
  3160. lastMultiComment = currentChunkStartIndex = chunkerCurrentIndex;
  3161. for (chunkerCurrentIndex = chunkerCurrentIndex + 2; chunkerCurrentIndex < len - 1; chunkerCurrentIndex++) {
  3162. cc2 = input.charCodeAt(chunkerCurrentIndex);
  3163. if (cc2 == 125) { lastMultiCommentEndBrace = chunkerCurrentIndex; }
  3164. if (cc2 != 42) { continue; }
  3165. if (input.charCodeAt(chunkerCurrentIndex + 1) == 47) { break; }
  3166. }
  3167. if (chunkerCurrentIndex == len - 1) {
  3168. return fail('missing closing `*/`', currentChunkStartIndex);
  3169. }
  3170. chunkerCurrentIndex++;
  3171. }
  3172. continue;
  3173. case 42: // *, check for unmatched */
  3174. if ((chunkerCurrentIndex < len - 1) && (input.charCodeAt(chunkerCurrentIndex + 1) == 47)) {
  3175. return fail('unmatched `/*`', chunkerCurrentIndex);
  3176. }
  3177. continue;
  3178. }
  3179. }
  3180. if (level !== 0) {
  3181. if ((lastMultiComment > lastOpening) && (lastMultiCommentEndBrace > lastMultiComment)) {
  3182. return fail('missing closing `}` or `*/`', lastOpening);
  3183. } else {
  3184. return fail('missing closing `}`', lastOpening);
  3185. }
  3186. } else if (parenLevel !== 0) {
  3187. return fail('missing closing `)`', lastOpeningParen);
  3188. }
  3189. emitChunk(true);
  3190. return chunks;
  3191. };
  3192. },{}],43:[function(require,module,exports){
  3193. var chunker = require('./chunker');
  3194. module.exports = function() {
  3195. var input, // Less input string
  3196. j, // current chunk
  3197. saveStack = [], // holds state for backtracking
  3198. furthest, // furthest index the parser has gone to
  3199. furthestPossibleErrorMessage, // if this is furthest we got to, this is the probably cause
  3200. chunks, // chunkified input
  3201. current, // current chunk
  3202. currentPos, // index of current chunk, in `input`
  3203. parserInput = {};
  3204. var CHARCODE_SPACE = 32,
  3205. CHARCODE_TAB = 9,
  3206. CHARCODE_LF = 10,
  3207. CHARCODE_CR = 13,
  3208. CHARCODE_PLUS = 43,
  3209. CHARCODE_COMMA = 44,
  3210. CHARCODE_FORWARD_SLASH = 47,
  3211. CHARCODE_9 = 57;
  3212. function skipWhitespace(length) {
  3213. var oldi = parserInput.i, oldj = j,
  3214. curr = parserInput.i - currentPos,
  3215. endIndex = parserInput.i + current.length - curr,
  3216. mem = (parserInput.i += length),
  3217. inp = input,
  3218. c, nextChar, comment;
  3219. for (; parserInput.i < endIndex; parserInput.i++) {
  3220. c = inp.charCodeAt(parserInput.i);
  3221. if (parserInput.autoCommentAbsorb && c === CHARCODE_FORWARD_SLASH) {
  3222. nextChar = inp.charAt(parserInput.i + 1);
  3223. if (nextChar === '/') {
  3224. comment = {index: parserInput.i, isLineComment: true};
  3225. var nextNewLine = inp.indexOf('\n', parserInput.i + 2);
  3226. if (nextNewLine < 0) {
  3227. nextNewLine = endIndex;
  3228. }
  3229. parserInput.i = nextNewLine;
  3230. comment.text = inp.substr(comment.index, parserInput.i - comment.index);
  3231. parserInput.commentStore.push(comment);
  3232. continue;
  3233. } else if (nextChar === '*') {
  3234. var nextStarSlash = inp.indexOf('*/', parserInput.i + 2);
  3235. if (nextStarSlash >= 0) {
  3236. comment = {
  3237. index: parserInput.i,
  3238. text: inp.substr(parserInput.i, nextStarSlash + 2 - parserInput.i),
  3239. isLineComment: false
  3240. };
  3241. parserInput.i += comment.text.length - 1;
  3242. parserInput.commentStore.push(comment);
  3243. continue;
  3244. }
  3245. }
  3246. break;
  3247. }
  3248. if ((c !== CHARCODE_SPACE) && (c !== CHARCODE_LF) && (c !== CHARCODE_TAB) && (c !== CHARCODE_CR)) {
  3249. break;
  3250. }
  3251. }
  3252. current = current.slice(length + parserInput.i - mem + curr);
  3253. currentPos = parserInput.i;
  3254. if (!current.length) {
  3255. if (j < chunks.length - 1) {
  3256. current = chunks[++j];
  3257. skipWhitespace(0); // skip space at the beginning of a chunk
  3258. return true; // things changed
  3259. }
  3260. parserInput.finished = true;
  3261. }
  3262. return oldi !== parserInput.i || oldj !== j;
  3263. }
  3264. parserInput.save = function() {
  3265. currentPos = parserInput.i;
  3266. saveStack.push( { current: current, i: parserInput.i, j: j });
  3267. };
  3268. parserInput.restore = function(possibleErrorMessage) {
  3269. if (parserInput.i > furthest || (parserInput.i === furthest && possibleErrorMessage && !furthestPossibleErrorMessage)) {
  3270. furthest = parserInput.i;
  3271. furthestPossibleErrorMessage = possibleErrorMessage;
  3272. }
  3273. var state = saveStack.pop();
  3274. current = state.current;
  3275. currentPos = parserInput.i = state.i;
  3276. j = state.j;
  3277. };
  3278. parserInput.forget = function() {
  3279. saveStack.pop();
  3280. };
  3281. parserInput.isWhitespace = function (offset) {
  3282. var pos = parserInput.i + (offset || 0),
  3283. code = input.charCodeAt(pos);
  3284. return (code === CHARCODE_SPACE || code === CHARCODE_CR || code === CHARCODE_TAB || code === CHARCODE_LF);
  3285. };
  3286. // Specialization of $(tok)
  3287. parserInput.$re = function(tok) {
  3288. if (parserInput.i > currentPos) {
  3289. current = current.slice(parserInput.i - currentPos);
  3290. currentPos = parserInput.i;
  3291. }
  3292. var m = tok.exec(current);
  3293. if (!m) {
  3294. return null;
  3295. }
  3296. skipWhitespace(m[0].length);
  3297. if (typeof m === 'string') {
  3298. return m;
  3299. }
  3300. return m.length === 1 ? m[0] : m;
  3301. };
  3302. parserInput.$char = function(tok) {
  3303. if (input.charAt(parserInput.i) !== tok) {
  3304. return null;
  3305. }
  3306. skipWhitespace(1);
  3307. return tok;
  3308. };
  3309. parserInput.$str = function(tok) {
  3310. var tokLength = tok.length;
  3311. // https://jsperf.com/string-startswith/21
  3312. for (var i = 0; i < tokLength; i++) {
  3313. if (input.charAt(parserInput.i + i) !== tok.charAt(i)) {
  3314. return null;
  3315. }
  3316. }
  3317. skipWhitespace(tokLength);
  3318. return tok;
  3319. };
  3320. parserInput.$quoted = function(loc) {
  3321. var pos = loc || parserInput.i,
  3322. startChar = input.charAt(pos);
  3323. if (startChar !== '\'' && startChar !== '"') {
  3324. return;
  3325. }
  3326. var length = input.length,
  3327. currentPosition = pos;
  3328. for (var i = 1; i + currentPosition < length; i++) {
  3329. var nextChar = input.charAt(i + currentPosition);
  3330. switch (nextChar) {
  3331. case '\\':
  3332. i++;
  3333. continue;
  3334. case '\r':
  3335. case '\n':
  3336. break;
  3337. case startChar:
  3338. var str = input.substr(currentPosition, i + 1);
  3339. if (!loc && loc !== 0) {
  3340. skipWhitespace(i + 1);
  3341. return str
  3342. }
  3343. return [startChar, str];
  3344. default:
  3345. }
  3346. }
  3347. return null;
  3348. };
  3349. /**
  3350. * Permissive parsing. Ignores everything except matching {} [] () and quotes
  3351. * until matching token (outside of blocks)
  3352. */
  3353. parserInput.$parseUntil = function(tok) {
  3354. var quote = '',
  3355. returnVal = null,
  3356. inComment = false,
  3357. blockDepth = 0,
  3358. blockStack = [],
  3359. parseGroups = [],
  3360. length = input.length,
  3361. startPos = parserInput.i,
  3362. lastPos = parserInput.i,
  3363. i = parserInput.i,
  3364. loop = true,
  3365. testChar;
  3366. if (typeof tok === 'string') {
  3367. testChar = function(char) {
  3368. return char === tok;
  3369. }
  3370. } else {
  3371. testChar = function(char) {
  3372. return tok.test(char);
  3373. }
  3374. }
  3375. do {
  3376. var prevChar, nextChar = input.charAt(i);
  3377. if (blockDepth === 0 && testChar(nextChar)) {
  3378. returnVal = input.substr(lastPos, i - lastPos);
  3379. if (returnVal) {
  3380. parseGroups.push(returnVal);
  3381. }
  3382. else {
  3383. parseGroups.push(' ');
  3384. }
  3385. returnVal = parseGroups;
  3386. skipWhitespace(i - startPos);
  3387. loop = false
  3388. } else {
  3389. if (inComment) {
  3390. if (nextChar === '*' &&
  3391. input.charAt(i + 1) === '/') {
  3392. i++;
  3393. blockDepth--;
  3394. inComment = false;
  3395. }
  3396. i++;
  3397. continue;
  3398. }
  3399. switch (nextChar) {
  3400. case '\\':
  3401. i++;
  3402. nextChar = input.charAt(i);
  3403. parseGroups.push(input.substr(lastPos, i - lastPos + 1));
  3404. lastPos = i + 1;
  3405. break;
  3406. case '/':
  3407. if (input.charAt(i + 1) === '*') {
  3408. i++;
  3409. inComment = true;
  3410. blockDepth++;
  3411. }
  3412. break;
  3413. case '\'':
  3414. case '"':
  3415. quote = parserInput.$quoted(i);
  3416. if (quote) {
  3417. parseGroups.push(input.substr(lastPos, i - lastPos), quote);
  3418. i += quote[1].length - 1;
  3419. lastPos = i + 1;
  3420. }
  3421. else {
  3422. skipWhitespace(i - startPos);
  3423. returnVal = nextChar;
  3424. loop = false;
  3425. }
  3426. break;
  3427. case '{':
  3428. blockStack.push('}');
  3429. blockDepth++;
  3430. break;
  3431. case '(':
  3432. blockStack.push(')');
  3433. blockDepth++;
  3434. break;
  3435. case '[':
  3436. blockStack.push(']');
  3437. blockDepth++;
  3438. break;
  3439. case '}':
  3440. case ')':
  3441. case ']':
  3442. var expected = blockStack.pop();
  3443. if (nextChar === expected) {
  3444. blockDepth--;
  3445. } else {
  3446. // move the parser to the error and return expected
  3447. skipWhitespace(i - startPos);
  3448. returnVal = expected;
  3449. loop = false;
  3450. }
  3451. }
  3452. i++;
  3453. if (i > length) {
  3454. loop = false;
  3455. }
  3456. }
  3457. prevChar = nextChar;
  3458. } while (loop);
  3459. return returnVal ? returnVal : null;
  3460. }
  3461. parserInput.autoCommentAbsorb = true;
  3462. parserInput.commentStore = [];
  3463. parserInput.finished = false;
  3464. // Same as $(), but don't change the state of the parser,
  3465. // just return the match.
  3466. parserInput.peek = function(tok) {
  3467. if (typeof tok === 'string') {
  3468. // https://jsperf.com/string-startswith/21
  3469. for (var i = 0; i < tok.length; i++) {
  3470. if (input.charAt(parserInput.i + i) !== tok.charAt(i)) {
  3471. return false;
  3472. }
  3473. }
  3474. return true;
  3475. } else {
  3476. return tok.test(current);
  3477. }
  3478. };
  3479. // Specialization of peek()
  3480. // TODO remove or change some currentChar calls to peekChar
  3481. parserInput.peekChar = function(tok) {
  3482. return input.charAt(parserInput.i) === tok;
  3483. };
  3484. parserInput.currentChar = function() {
  3485. return input.charAt(parserInput.i);
  3486. };
  3487. parserInput.prevChar = function() {
  3488. return input.charAt(parserInput.i - 1);
  3489. };
  3490. parserInput.getInput = function() {
  3491. return input;
  3492. };
  3493. parserInput.peekNotNumeric = function() {
  3494. var c = input.charCodeAt(parserInput.i);
  3495. // Is the first char of the dimension 0-9, '.', '+' or '-'
  3496. return (c > CHARCODE_9 || c < CHARCODE_PLUS) || c === CHARCODE_FORWARD_SLASH || c === CHARCODE_COMMA;
  3497. };
  3498. parserInput.start = function(str, chunkInput, failFunction) {
  3499. input = str;
  3500. parserInput.i = j = currentPos = furthest = 0;
  3501. // chunking apparently makes things quicker (but my tests indicate
  3502. // it might actually make things slower in node at least)
  3503. // and it is a non-perfect parse - it can't recognise
  3504. // unquoted urls, meaning it can't distinguish comments
  3505. // meaning comments with quotes or {}() in them get 'counted'
  3506. // and then lead to parse errors.
  3507. // In addition if the chunking chunks in the wrong place we might
  3508. // not be able to parse a parser statement in one go
  3509. // this is officially deprecated but can be switched on via an option
  3510. // in the case it causes too much performance issues.
  3511. if (chunkInput) {
  3512. chunks = chunker(str, failFunction);
  3513. } else {
  3514. chunks = [str];
  3515. }
  3516. current = chunks[0];
  3517. skipWhitespace(0);
  3518. };
  3519. parserInput.end = function() {
  3520. var message,
  3521. isFinished = parserInput.i >= input.length;
  3522. if (parserInput.i < furthest) {
  3523. message = furthestPossibleErrorMessage;
  3524. parserInput.i = furthest;
  3525. }
  3526. return {
  3527. isFinished: isFinished,
  3528. furthest: parserInput.i,
  3529. furthestPossibleErrorMessage: message,
  3530. furthestReachedEnd: parserInput.i >= input.length - 1,
  3531. furthestChar: input[parserInput.i]
  3532. };
  3533. };
  3534. return parserInput;
  3535. };
  3536. },{"./chunker":42}],44:[function(require,module,exports){
  3537. var LessError = require('../less-error'),
  3538. tree = require('../tree'),
  3539. visitors = require('../visitors'),
  3540. getParserInput = require('./parser-input'),
  3541. utils = require('../utils'),
  3542. functionRegistry = require('../functions/function-registry');
  3543. //
  3544. // less.js - parser
  3545. //
  3546. // A relatively straight-forward predictive parser.
  3547. // There is no tokenization/lexing stage, the input is parsed
  3548. // in one sweep.
  3549. //
  3550. // To make the parser fast enough to run in the browser, several
  3551. // optimization had to be made:
  3552. //
  3553. // - Matching and slicing on a huge input is often cause of slowdowns.
  3554. // The solution is to chunkify the input into smaller strings.
  3555. // The chunks are stored in the `chunks` var,
  3556. // `j` holds the current chunk index, and `currentPos` holds
  3557. // the index of the current chunk in relation to `input`.
  3558. // This gives us an almost 4x speed-up.
  3559. //
  3560. // - In many cases, we don't need to match individual tokens;
  3561. // for example, if a value doesn't hold any variables, operations
  3562. // or dynamic references, the parser can effectively 'skip' it,
  3563. // treating it as a literal.
  3564. // An example would be '1px solid #000' - which evaluates to itself,
  3565. // we don't need to know what the individual components are.
  3566. // The drawback, of course is that you don't get the benefits of
  3567. // syntax-checking on the CSS. This gives us a 50% speed-up in the parser,
  3568. // and a smaller speed-up in the code-gen.
  3569. //
  3570. //
  3571. // Token matching is done with the `$` function, which either takes
  3572. // a terminal string or regexp, or a non-terminal function to call.
  3573. // It also takes care of moving all the indices forwards.
  3574. //
  3575. var Parser = function Parser(context, imports, fileInfo) {
  3576. var parsers,
  3577. parserInput = getParserInput();
  3578. function error(msg, type) {
  3579. throw new LessError(
  3580. {
  3581. index: parserInput.i,
  3582. filename: fileInfo.filename,
  3583. type: type || 'Syntax',
  3584. message: msg
  3585. },
  3586. imports
  3587. );
  3588. }
  3589. function expect(arg, msg) {
  3590. // some older browsers return typeof 'function' for RegExp
  3591. var result = (arg instanceof Function) ? arg.call(parsers) : parserInput.$re(arg);
  3592. if (result) {
  3593. return result;
  3594. }
  3595. error(msg || (typeof arg === 'string'
  3596. ? 'expected \'' + arg + '\' got \'' + parserInput.currentChar() + '\''
  3597. : 'unexpected token'));
  3598. }
  3599. // Specialization of expect()
  3600. function expectChar(arg, msg) {
  3601. if (parserInput.$char(arg)) {
  3602. return arg;
  3603. }
  3604. error(msg || 'expected \'' + arg + '\' got \'' + parserInput.currentChar() + '\'');
  3605. }
  3606. function getDebugInfo(index) {
  3607. var filename = fileInfo.filename;
  3608. return {
  3609. lineNumber: utils.getLocation(index, parserInput.getInput()).line + 1,
  3610. fileName: filename
  3611. };
  3612. }
  3613. /**
  3614. * Used after initial parsing to create nodes on the fly
  3615. *
  3616. * @param {String} str - string to parse
  3617. * @param {Array} parseList - array of parsers to run input through e.g. ["value", "important"]
  3618. * @param {Number} currentIndex - start number to begin indexing
  3619. * @param {Object} fileInfo - fileInfo to attach to created nodes
  3620. */
  3621. function parseNode(str, parseList, currentIndex, fileInfo, callback) {
  3622. var result, returnNodes = [];
  3623. var parser = parserInput;
  3624. try {
  3625. parser.start(str, false, function fail(msg, index) {
  3626. callback({
  3627. message: msg,
  3628. index: index + currentIndex
  3629. });
  3630. });
  3631. for (var x = 0, p, i; (p = parseList[x]); x++) {
  3632. i = parser.i;
  3633. result = parsers[p]();
  3634. if (result) {
  3635. result._index = i + currentIndex;
  3636. result._fileInfo = fileInfo;
  3637. returnNodes.push(result);
  3638. }
  3639. else {
  3640. returnNodes.push(null);
  3641. }
  3642. }
  3643. var endInfo = parser.end();
  3644. if (endInfo.isFinished) {
  3645. callback(null, returnNodes);
  3646. }
  3647. else {
  3648. callback(true, null);
  3649. }
  3650. } catch (e) {
  3651. throw new LessError({
  3652. index: e.index + currentIndex,
  3653. message: e.message
  3654. }, imports, fileInfo.filename);
  3655. }
  3656. }
  3657. //
  3658. // The Parser
  3659. //
  3660. return {
  3661. parserInput: parserInput,
  3662. imports: imports,
  3663. fileInfo: fileInfo,
  3664. parseNode: parseNode,
  3665. //
  3666. // Parse an input string into an abstract syntax tree,
  3667. // @param str A string containing 'less' markup
  3668. // @param callback call `callback` when done.
  3669. // @param [additionalData] An optional map which can contains vars - a map (key, value) of variables to apply
  3670. //
  3671. parse: function (str, callback, additionalData) {
  3672. var root, error = null, globalVars, modifyVars, ignored, preText = '';
  3673. globalVars = (additionalData && additionalData.globalVars) ? Parser.serializeVars(additionalData.globalVars) + '\n' : '';
  3674. modifyVars = (additionalData && additionalData.modifyVars) ? '\n' + Parser.serializeVars(additionalData.modifyVars) : '';
  3675. if (context.pluginManager) {
  3676. var preProcessors = context.pluginManager.getPreProcessors();
  3677. for (var i = 0; i < preProcessors.length; i++) {
  3678. str = preProcessors[i].process(str, { context: context, imports: imports, fileInfo: fileInfo });
  3679. }
  3680. }
  3681. if (globalVars || (additionalData && additionalData.banner)) {
  3682. preText = ((additionalData && additionalData.banner) ? additionalData.banner : '') + globalVars;
  3683. ignored = imports.contentsIgnoredChars;
  3684. ignored[fileInfo.filename] = ignored[fileInfo.filename] || 0;
  3685. ignored[fileInfo.filename] += preText.length;
  3686. }
  3687. str = str.replace(/\r\n?/g, '\n');
  3688. // Remove potential UTF Byte Order Mark
  3689. str = preText + str.replace(/^\uFEFF/, '') + modifyVars;
  3690. imports.contents[fileInfo.filename] = str;
  3691. // Start with the primary rule.
  3692. // The whole syntax tree is held under a Ruleset node,
  3693. // with the `root` property set to true, so no `{}` are
  3694. // output. The callback is called when the input is parsed.
  3695. try {
  3696. parserInput.start(str, context.chunkInput, function fail(msg, index) {
  3697. throw new LessError({
  3698. index: index,
  3699. type: 'Parse',
  3700. message: msg,
  3701. filename: fileInfo.filename
  3702. }, imports);
  3703. });
  3704. tree.Node.prototype.parse = this;
  3705. root = new tree.Ruleset(null, this.parsers.primary());
  3706. tree.Node.prototype.rootNode = root;
  3707. root.root = true;
  3708. root.firstRoot = true;
  3709. root.functionRegistry = functionRegistry.inherit();
  3710. } catch (e) {
  3711. return callback(new LessError(e, imports, fileInfo.filename));
  3712. }
  3713. // If `i` is smaller than the `input.length - 1`,
  3714. // it means the parser wasn't able to parse the whole
  3715. // string, so we've got a parsing error.
  3716. //
  3717. // We try to extract a \n delimited string,
  3718. // showing the line where the parse error occurred.
  3719. // We split it up into two parts (the part which parsed,
  3720. // and the part which didn't), so we can color them differently.
  3721. var endInfo = parserInput.end();
  3722. if (!endInfo.isFinished) {
  3723. var message = endInfo.furthestPossibleErrorMessage;
  3724. if (!message) {
  3725. message = 'Unrecognised input';
  3726. if (endInfo.furthestChar === '}') {
  3727. message += '. Possibly missing opening \'{\'';
  3728. } else if (endInfo.furthestChar === ')') {
  3729. message += '. Possibly missing opening \'(\'';
  3730. } else if (endInfo.furthestReachedEnd) {
  3731. message += '. Possibly missing something';
  3732. }
  3733. }
  3734. error = new LessError({
  3735. type: 'Parse',
  3736. message: message,
  3737. index: endInfo.furthest,
  3738. filename: fileInfo.filename
  3739. }, imports);
  3740. }
  3741. var finish = function (e) {
  3742. e = error || e || imports.error;
  3743. if (e) {
  3744. if (!(e instanceof LessError)) {
  3745. e = new LessError(e, imports, fileInfo.filename);
  3746. }
  3747. return callback(e);
  3748. }
  3749. else {
  3750. return callback(null, root);
  3751. }
  3752. };
  3753. if (context.processImports !== false) {
  3754. new visitors.ImportVisitor(imports, finish)
  3755. .run(root);
  3756. } else {
  3757. return finish();
  3758. }
  3759. },
  3760. //
  3761. // Here in, the parsing rules/functions
  3762. //
  3763. // The basic structure of the syntax tree generated is as follows:
  3764. //
  3765. // Ruleset -> Declaration -> Value -> Expression -> Entity
  3766. //
  3767. // Here's some Less code:
  3768. //
  3769. // .class {
  3770. // color: #fff;
  3771. // border: 1px solid #000;
  3772. // width: @w + 4px;
  3773. // > .child {...}
  3774. // }
  3775. //
  3776. // And here's what the parse tree might look like:
  3777. //
  3778. // Ruleset (Selector '.class', [
  3779. // Declaration ("color", Value ([Expression [Color #fff]]))
  3780. // Declaration ("border", Value ([Expression [Dimension 1px][Keyword "solid"][Color #000]]))
  3781. // Declaration ("width", Value ([Expression [Operation " + " [Variable "@w"][Dimension 4px]]]))
  3782. // Ruleset (Selector [Element '>', '.child'], [...])
  3783. // ])
  3784. //
  3785. // In general, most rules will try to parse a token with the `$re()` function, and if the return
  3786. // value is truly, will return a new node, of the relevant type. Sometimes, we need to check
  3787. // first, before parsing, that's when we use `peek()`.
  3788. //
  3789. parsers: parsers = {
  3790. //
  3791. // The `primary` rule is the *entry* and *exit* point of the parser.
  3792. // The rules here can appear at any level of the parse tree.
  3793. //
  3794. // The recursive nature of the grammar is an interplay between the `block`
  3795. // rule, which represents `{ ... }`, the `ruleset` rule, and this `primary` rule,
  3796. // as represented by this simplified grammar:
  3797. //
  3798. // primary → (ruleset | declaration)+
  3799. // ruleset → selector+ block
  3800. // block → '{' primary '}'
  3801. //
  3802. // Only at one point is the primary rule not called from the
  3803. // block rule: at the root level.
  3804. //
  3805. primary: function () {
  3806. var mixin = this.mixin, root = [], node;
  3807. while (true) {
  3808. while (true) {
  3809. node = this.comment();
  3810. if (!node) { break; }
  3811. root.push(node);
  3812. }
  3813. // always process comments before deciding if finished
  3814. if (parserInput.finished) {
  3815. break;
  3816. }
  3817. if (parserInput.peek('}')) {
  3818. break;
  3819. }
  3820. node = this.extendRule();
  3821. if (node) {
  3822. root = root.concat(node);
  3823. continue;
  3824. }
  3825. node = mixin.definition() || this.declaration() || this.ruleset() ||
  3826. mixin.call(false, false) || this.variableCall() || this.entities.call() || this.atrule();
  3827. if (node) {
  3828. root.push(node);
  3829. } else {
  3830. var foundSemiColon = false;
  3831. while (parserInput.$char(';')) {
  3832. foundSemiColon = true;
  3833. }
  3834. if (!foundSemiColon) {
  3835. break;
  3836. }
  3837. }
  3838. }
  3839. return root;
  3840. },
  3841. // comments are collected by the main parsing mechanism and then assigned to nodes
  3842. // where the current structure allows it
  3843. comment: function () {
  3844. if (parserInput.commentStore.length) {
  3845. var comment = parserInput.commentStore.shift();
  3846. return new(tree.Comment)(comment.text, comment.isLineComment, comment.index, fileInfo);
  3847. }
  3848. },
  3849. //
  3850. // Entities are tokens which can be found inside an Expression
  3851. //
  3852. entities: {
  3853. mixinLookup: function() {
  3854. return parsers.mixin.call(true, true);
  3855. },
  3856. //
  3857. // A string, which supports escaping " and '
  3858. //
  3859. // "milky way" 'he\'s the one!'
  3860. //
  3861. quoted: function (forceEscaped) {
  3862. var str, index = parserInput.i, isEscaped = false;
  3863. parserInput.save();
  3864. if (parserInput.$char('~')) {
  3865. isEscaped = true;
  3866. } else if (forceEscaped) {
  3867. parserInput.restore();
  3868. return;
  3869. }
  3870. str = parserInput.$quoted();
  3871. if (!str) {
  3872. parserInput.restore();
  3873. return;
  3874. }
  3875. parserInput.forget();
  3876. return new(tree.Quoted)(str.charAt(0), str.substr(1, str.length - 2), isEscaped, index, fileInfo);
  3877. },
  3878. //
  3879. // A catch-all word, such as:
  3880. //
  3881. // black border-collapse
  3882. //
  3883. keyword: function () {
  3884. var k = parserInput.$char('%') || parserInput.$re(/^\[?(?:[\w-]|\\(?:[A-Fa-f0-9]{1,6} ?|[^A-Fa-f0-9]))+\]?/);
  3885. if (k) {
  3886. return tree.Color.fromKeyword(k) || new(tree.Keyword)(k);
  3887. }
  3888. },
  3889. //
  3890. // A function call
  3891. //
  3892. // rgb(255, 0, 255)
  3893. //
  3894. // The arguments are parsed with the `entities.arguments` parser.
  3895. //
  3896. call: function () {
  3897. var name, args, func, index = parserInput.i;
  3898. // http://jsperf.com/case-insensitive-regex-vs-strtolower-then-regex/18
  3899. if (parserInput.peek(/^url\(/i)) {
  3900. return;
  3901. }
  3902. parserInput.save();
  3903. name = parserInput.$re(/^([\w-]+|%|progid:[\w\.]+)\(/);
  3904. if (!name) {
  3905. parserInput.forget();
  3906. return;
  3907. }
  3908. name = name[1];
  3909. func = this.customFuncCall(name);
  3910. if (func) {
  3911. args = func.parse();
  3912. if (args && func.stop) {
  3913. parserInput.forget();
  3914. return args;
  3915. }
  3916. }
  3917. args = this.arguments(args);
  3918. if (!parserInput.$char(')')) {
  3919. parserInput.restore('Could not parse call arguments or missing \')\'');
  3920. return;
  3921. }
  3922. parserInput.forget();
  3923. return new(tree.Call)(name, args, index, fileInfo);
  3924. },
  3925. //
  3926. // Parsing rules for functions with non-standard args, e.g.:
  3927. //
  3928. // boolean(not(2 > 1))
  3929. //
  3930. // This is a quick prototype, to be modified/improved when
  3931. // more custom-parsed funcs come (e.g. `selector(...)`)
  3932. //
  3933. customFuncCall: function (name) {
  3934. /* Ideally the table is to be moved out of here for faster perf.,
  3935. but it's quite tricky since it relies on all these `parsers`
  3936. and `expect` available only here */
  3937. return {
  3938. alpha: f(parsers.ieAlpha, true),
  3939. boolean: f(condition),
  3940. 'if': f(condition)
  3941. }[name.toLowerCase()];
  3942. function f(parse, stop) {
  3943. return {
  3944. parse: parse, // parsing function
  3945. stop: stop // when true - stop after parse() and return its result,
  3946. // otherwise continue for plain args
  3947. };
  3948. }
  3949. function condition() {
  3950. return [expect(parsers.condition, 'expected condition')];
  3951. }
  3952. },
  3953. arguments: function (prevArgs) {
  3954. var argsComma = prevArgs || [],
  3955. argsSemiColon = [],
  3956. isSemiColonSeparated, value;
  3957. parserInput.save();
  3958. while (true) {
  3959. if (prevArgs) {
  3960. prevArgs = false;
  3961. } else {
  3962. value = parsers.detachedRuleset() || this.assignment() || parsers.expression();
  3963. if (!value) {
  3964. break;
  3965. }
  3966. if (value.value && value.value.length == 1) {
  3967. value = value.value[0];
  3968. }
  3969. argsComma.push(value);
  3970. }
  3971. if (parserInput.$char(',')) {
  3972. continue;
  3973. }
  3974. if (parserInput.$char(';') || isSemiColonSeparated) {
  3975. isSemiColonSeparated = true;
  3976. value = (argsComma.length < 1) ? argsComma[0]
  3977. : new tree.Value(argsComma);
  3978. argsSemiColon.push(value);
  3979. argsComma = [];
  3980. }
  3981. }
  3982. parserInput.forget();
  3983. return isSemiColonSeparated ? argsSemiColon : argsComma;
  3984. },
  3985. literal: function () {
  3986. return this.dimension() ||
  3987. this.color() ||
  3988. this.quoted() ||
  3989. this.unicodeDescriptor();
  3990. },
  3991. // Assignments are argument entities for calls.
  3992. // They are present in ie filter properties as shown below.
  3993. //
  3994. // filter: progid:DXImageTransform.Microsoft.Alpha( *opacity=50* )
  3995. //
  3996. assignment: function () {
  3997. var key, value;
  3998. parserInput.save();
  3999. key = parserInput.$re(/^\w+(?=\s?=)/i);
  4000. if (!key) {
  4001. parserInput.restore();
  4002. return;
  4003. }
  4004. if (!parserInput.$char('=')) {
  4005. parserInput.restore();
  4006. return;
  4007. }
  4008. value = parsers.entity();
  4009. if (value) {
  4010. parserInput.forget();
  4011. return new(tree.Assignment)(key, value);
  4012. } else {
  4013. parserInput.restore();
  4014. }
  4015. },
  4016. //
  4017. // Parse url() tokens
  4018. //
  4019. // We use a specific rule for urls, because they don't really behave like
  4020. // standard function calls. The difference is that the argument doesn't have
  4021. // to be enclosed within a string, so it can't be parsed as an Expression.
  4022. //
  4023. url: function () {
  4024. var value, index = parserInput.i;
  4025. parserInput.autoCommentAbsorb = false;
  4026. if (!parserInput.$str('url(')) {
  4027. parserInput.autoCommentAbsorb = true;
  4028. return;
  4029. }
  4030. value = this.quoted() || this.variable() || this.property() ||
  4031. parserInput.$re(/^(?:(?:\\[\(\)'"])|[^\(\)'"])+/) || '';
  4032. parserInput.autoCommentAbsorb = true;
  4033. expectChar(')');
  4034. return new(tree.URL)((value.value != null ||
  4035. value instanceof tree.Variable ||
  4036. value instanceof tree.Property) ?
  4037. value : new(tree.Anonymous)(value, index), index, fileInfo);
  4038. },
  4039. //
  4040. // A Variable entity, such as `@fink`, in
  4041. //
  4042. // width: @fink + 2px
  4043. //
  4044. // We use a different parser for variable definitions,
  4045. // see `parsers.variable`.
  4046. //
  4047. variable: function () {
  4048. var ch, name, index = parserInput.i;
  4049. parserInput.save();
  4050. if (parserInput.currentChar() === '@' && (name = parserInput.$re(/^@@?[\w-]+/))) {
  4051. ch = parserInput.currentChar();
  4052. if (ch === '(' || ch === '[' && !parserInput.prevChar().match(/^\s/)) {
  4053. // this may be a VariableCall lookup
  4054. var result = parsers.variableCall(name);
  4055. if (result) {
  4056. parserInput.forget();
  4057. return result;
  4058. }
  4059. }
  4060. parserInput.forget();
  4061. return new(tree.Variable)(name, index, fileInfo);
  4062. }
  4063. parserInput.restore();
  4064. },
  4065. // A variable entity using the protective {} e.g. @{var}
  4066. variableCurly: function () {
  4067. var curly, index = parserInput.i;
  4068. if (parserInput.currentChar() === '@' && (curly = parserInput.$re(/^@\{([\w-]+)\}/))) {
  4069. return new(tree.Variable)('@' + curly[1], index, fileInfo);
  4070. }
  4071. },
  4072. //
  4073. // A Property accessor, such as `$color`, in
  4074. //
  4075. // background-color: $color
  4076. //
  4077. property: function () {
  4078. var name, index = parserInput.i;
  4079. if (parserInput.currentChar() === '$' && (name = parserInput.$re(/^\$[\w-]+/))) {
  4080. return new(tree.Property)(name, index, fileInfo);
  4081. }
  4082. },
  4083. // A property entity useing the protective {} e.g. ${prop}
  4084. propertyCurly: function () {
  4085. var curly, index = parserInput.i;
  4086. if (parserInput.currentChar() === '$' && (curly = parserInput.$re(/^\$\{([\w-]+)\}/))) {
  4087. return new(tree.Property)('$' + curly[1], index, fileInfo);
  4088. }
  4089. },
  4090. //
  4091. // A Hexadecimal color
  4092. //
  4093. // #4F3C2F
  4094. //
  4095. // `rgb` and `hsl` colors are parsed through the `entities.call` parser.
  4096. //
  4097. color: function () {
  4098. var rgb;
  4099. if (parserInput.currentChar() === '#' && (rgb = parserInput.$re(/^#([A-Fa-f0-9]{8}|[A-Fa-f0-9]{6}|[A-Fa-f0-9]{3,4})/))) {
  4100. return new(tree.Color)(rgb[1], undefined, rgb[0]);
  4101. }
  4102. },
  4103. colorKeyword: function () {
  4104. parserInput.save();
  4105. var autoCommentAbsorb = parserInput.autoCommentAbsorb;
  4106. parserInput.autoCommentAbsorb = false;
  4107. var k = parserInput.$re(/^[_A-Za-z-][_A-Za-z0-9-]+/);
  4108. parserInput.autoCommentAbsorb = autoCommentAbsorb;
  4109. if (!k) {
  4110. parserInput.forget();
  4111. return;
  4112. }
  4113. parserInput.restore();
  4114. var color = tree.Color.fromKeyword(k);
  4115. if (color) {
  4116. parserInput.$str(k);
  4117. return color;
  4118. }
  4119. },
  4120. //
  4121. // A Dimension, that is, a number and a unit
  4122. //
  4123. // 0.5em 95%
  4124. //
  4125. dimension: function () {
  4126. if (parserInput.peekNotNumeric()) {
  4127. return;
  4128. }
  4129. var value = parserInput.$re(/^([+-]?\d*\.?\d+)(%|[a-z_]+)?/i);
  4130. if (value) {
  4131. return new(tree.Dimension)(value[1], value[2]);
  4132. }
  4133. },
  4134. //
  4135. // A unicode descriptor, as is used in unicode-range
  4136. //
  4137. // U+0?? or U+00A1-00A9
  4138. //
  4139. unicodeDescriptor: function () {
  4140. var ud;
  4141. ud = parserInput.$re(/^U\+[0-9a-fA-F?]+(\-[0-9a-fA-F?]+)?/);
  4142. if (ud) {
  4143. return new(tree.UnicodeDescriptor)(ud[0]);
  4144. }
  4145. },
  4146. //
  4147. // JavaScript code to be evaluated
  4148. //
  4149. // `window.location.href`
  4150. //
  4151. javascript: function () {
  4152. var js, index = parserInput.i;
  4153. parserInput.save();
  4154. var escape = parserInput.$char('~');
  4155. var jsQuote = parserInput.$char('`');
  4156. if (!jsQuote) {
  4157. parserInput.restore();
  4158. return;
  4159. }
  4160. js = parserInput.$re(/^[^`]*`/);
  4161. if (js) {
  4162. parserInput.forget();
  4163. return new(tree.JavaScript)(js.substr(0, js.length - 1), Boolean(escape), index, fileInfo);
  4164. }
  4165. parserInput.restore('invalid javascript definition');
  4166. }
  4167. },
  4168. //
  4169. // The variable part of a variable definition. Used in the `rule` parser
  4170. //
  4171. // @fink:
  4172. //
  4173. variable: function () {
  4174. var name;
  4175. if (parserInput.currentChar() === '@' && (name = parserInput.$re(/^(@[\w-]+)\s*:/))) { return name[1]; }
  4176. },
  4177. //
  4178. // Call a variable value to retrieve a detached ruleset
  4179. // or a value from a detached ruleset's rules.
  4180. //
  4181. // @fink();
  4182. // @fink;
  4183. // color: @fink[@color];
  4184. //
  4185. variableCall: function (parsedName) {
  4186. var lookups, important, i = parserInput.i,
  4187. inValue = !!parsedName, name = parsedName;
  4188. parserInput.save();
  4189. if (name || (parserInput.currentChar() === '@'
  4190. && (name = parserInput.$re(/^(@[\w-]+)(\(\s*\))?/)))) {
  4191. lookups = this.mixin.ruleLookups();
  4192. if (!lookups && ((inValue && parserInput.$str('()') !== '()') || (name[2] !== '()'))) {
  4193. parserInput.restore('Missing \'[...]\' lookup in variable call');
  4194. return;
  4195. }
  4196. if (!inValue) {
  4197. name = name[1];
  4198. }
  4199. if (lookups && parsers.important()) {
  4200. important = true;
  4201. }
  4202. var call = new tree.VariableCall(name, i, fileInfo);
  4203. if (!inValue && parsers.end()) {
  4204. parserInput.forget();
  4205. return call;
  4206. }
  4207. else {
  4208. parserInput.forget();
  4209. return new tree.NamespaceValue(call, lookups, important, i, fileInfo);
  4210. }
  4211. }
  4212. parserInput.restore();
  4213. },
  4214. //
  4215. // extend syntax - used to extend selectors
  4216. //
  4217. extend: function(isRule) {
  4218. var elements, e, index = parserInput.i, option, extendList, extend;
  4219. if (!parserInput.$str(isRule ? '&:extend(' : ':extend(')) {
  4220. return;
  4221. }
  4222. do {
  4223. option = null;
  4224. elements = null;
  4225. while (!(option = parserInput.$re(/^(all)(?=\s*(\)|,))/))) {
  4226. e = this.element();
  4227. if (!e) {
  4228. break;
  4229. }
  4230. if (elements) {
  4231. elements.push(e);
  4232. } else {
  4233. elements = [ e ];
  4234. }
  4235. }
  4236. option = option && option[1];
  4237. if (!elements) {
  4238. error('Missing target selector for :extend().');
  4239. }
  4240. extend = new(tree.Extend)(new(tree.Selector)(elements), option, index, fileInfo);
  4241. if (extendList) {
  4242. extendList.push(extend);
  4243. } else {
  4244. extendList = [ extend ];
  4245. }
  4246. } while (parserInput.$char(','));
  4247. expect(/^\)/);
  4248. if (isRule) {
  4249. expect(/^;/);
  4250. }
  4251. return extendList;
  4252. },
  4253. //
  4254. // extendRule - used in a rule to extend all the parent selectors
  4255. //
  4256. extendRule: function() {
  4257. return this.extend(true);
  4258. },
  4259. //
  4260. // Mixins
  4261. //
  4262. mixin: {
  4263. //
  4264. // A Mixin call, with an optional argument list
  4265. //
  4266. // #mixins > .square(#fff);
  4267. // #mixins.square(#fff);
  4268. // .rounded(4px, black);
  4269. // .button;
  4270. //
  4271. // We can lookup / return a value using the lookup syntax:
  4272. //
  4273. // color: #mixin.square(#fff)[@color];
  4274. //
  4275. // The `while` loop is there because mixins can be
  4276. // namespaced, but we only support the child and descendant
  4277. // selector for now.
  4278. //
  4279. call: function (inValue, getLookup) {
  4280. var s = parserInput.currentChar(), important = false, lookups,
  4281. index = parserInput.i, elements, args, hasParens;
  4282. if (s !== '.' && s !== '#') { return; }
  4283. parserInput.save(); // stop us absorbing part of an invalid selector
  4284. elements = this.elements();
  4285. if (elements) {
  4286. if (parserInput.$char('(')) {
  4287. args = this.args(true).args;
  4288. expectChar(')');
  4289. hasParens = true;
  4290. }
  4291. if (getLookup !== false) {
  4292. lookups = this.ruleLookups();
  4293. }
  4294. if (getLookup === true && !lookups) {
  4295. parserInput.restore();
  4296. return;
  4297. }
  4298. if (inValue && !lookups && !hasParens) {
  4299. // This isn't a valid in-value mixin call
  4300. parserInput.restore();
  4301. return;
  4302. }
  4303. if (!inValue && parsers.important()) {
  4304. important = true;
  4305. }
  4306. if (inValue || parsers.end()) {
  4307. parserInput.forget();
  4308. var mixin = new(tree.mixin.Call)(elements, args, index, fileInfo, !lookups && important);
  4309. if (lookups) {
  4310. return new tree.NamespaceValue(mixin, lookups, important);
  4311. }
  4312. else {
  4313. return mixin;
  4314. }
  4315. }
  4316. }
  4317. parserInput.restore();
  4318. },
  4319. /**
  4320. * Matching elements for mixins
  4321. * (Start with . or # and can have > )
  4322. */
  4323. elements: function() {
  4324. var elements, e, c, elem, elemIndex,
  4325. re = /^[#.](?:[\w-]|\\(?:[A-Fa-f0-9]{1,6} ?|[^A-Fa-f0-9]))+/;
  4326. while (true) {
  4327. elemIndex = parserInput.i;
  4328. e = parserInput.$re(re);
  4329. if (!e) {
  4330. break;
  4331. }
  4332. elem = new(tree.Element)(c, e, false, elemIndex, fileInfo);
  4333. if (elements) {
  4334. elements.push(elem);
  4335. } else {
  4336. elements = [ elem ];
  4337. }
  4338. c = parserInput.$char('>');
  4339. }
  4340. return elements;
  4341. },
  4342. args: function (isCall) {
  4343. var entities = parsers.entities,
  4344. returner = { args:null, variadic: false },
  4345. expressions = [], argsSemiColon = [], argsComma = [],
  4346. isSemiColonSeparated, expressionContainsNamed, name, nameLoop,
  4347. value, arg, expand, hasSep = true;
  4348. parserInput.save();
  4349. while (true) {
  4350. if (isCall) {
  4351. arg = parsers.detachedRuleset() || parsers.expression();
  4352. } else {
  4353. parserInput.commentStore.length = 0;
  4354. if (parserInput.$str('...')) {
  4355. returner.variadic = true;
  4356. if (parserInput.$char(';') && !isSemiColonSeparated) {
  4357. isSemiColonSeparated = true;
  4358. }
  4359. (isSemiColonSeparated ? argsSemiColon : argsComma)
  4360. .push({ variadic: true });
  4361. break;
  4362. }
  4363. arg = entities.variable() || entities.property() || entities.literal() || entities.keyword() || this.call(true);
  4364. }
  4365. if (!arg || !hasSep) {
  4366. break;
  4367. }
  4368. nameLoop = null;
  4369. if (arg.throwAwayComments) {
  4370. arg.throwAwayComments();
  4371. }
  4372. value = arg;
  4373. var val = null;
  4374. if (isCall) {
  4375. // Variable
  4376. if (arg.value && arg.value.length == 1) {
  4377. val = arg.value[0];
  4378. }
  4379. } else {
  4380. val = arg;
  4381. }
  4382. if (val && (val instanceof tree.Variable || val instanceof tree.Property)) {
  4383. if (parserInput.$char(':')) {
  4384. if (expressions.length > 0) {
  4385. if (isSemiColonSeparated) {
  4386. error('Cannot mix ; and , as delimiter types');
  4387. }
  4388. expressionContainsNamed = true;
  4389. }
  4390. value = parsers.detachedRuleset() || parsers.expression();
  4391. if (!value) {
  4392. if (isCall) {
  4393. error('could not understand value for named argument');
  4394. } else {
  4395. parserInput.restore();
  4396. returner.args = [];
  4397. return returner;
  4398. }
  4399. }
  4400. nameLoop = (name = val.name);
  4401. } else if (parserInput.$str('...')) {
  4402. if (!isCall) {
  4403. returner.variadic = true;
  4404. if (parserInput.$char(';') && !isSemiColonSeparated) {
  4405. isSemiColonSeparated = true;
  4406. }
  4407. (isSemiColonSeparated ? argsSemiColon : argsComma)
  4408. .push({ name: arg.name, variadic: true });
  4409. break;
  4410. } else {
  4411. expand = true;
  4412. }
  4413. } else if (!isCall) {
  4414. name = nameLoop = val.name;
  4415. value = null;
  4416. }
  4417. }
  4418. if (value) {
  4419. expressions.push(value);
  4420. }
  4421. argsComma.push({ name:nameLoop, value:value, expand:expand });
  4422. if (parserInput.$char(',')) {
  4423. hasSep = true;
  4424. continue;
  4425. }
  4426. hasSep = parserInput.$char(';') === ';';
  4427. if (hasSep || isSemiColonSeparated) {
  4428. if (expressionContainsNamed) {
  4429. error('Cannot mix ; and , as delimiter types');
  4430. }
  4431. isSemiColonSeparated = true;
  4432. if (expressions.length > 1) {
  4433. value = new(tree.Value)(expressions);
  4434. }
  4435. argsSemiColon.push({ name:name, value:value, expand:expand });
  4436. name = null;
  4437. expressions = [];
  4438. expressionContainsNamed = false;
  4439. }
  4440. }
  4441. parserInput.forget();
  4442. returner.args = isSemiColonSeparated ? argsSemiColon : argsComma;
  4443. return returner;
  4444. },
  4445. //
  4446. // A Mixin definition, with a list of parameters
  4447. //
  4448. // .rounded (@radius: 2px, @color) {
  4449. // ...
  4450. // }
  4451. //
  4452. // Until we have a finer grained state-machine, we have to
  4453. // do a look-ahead, to make sure we don't have a mixin call.
  4454. // See the `rule` function for more information.
  4455. //
  4456. // We start by matching `.rounded (`, and then proceed on to
  4457. // the argument list, which has optional default values.
  4458. // We store the parameters in `params`, with a `value` key,
  4459. // if there is a value, such as in the case of `@radius`.
  4460. //
  4461. // Once we've got our params list, and a closing `)`, we parse
  4462. // the `{...}` block.
  4463. //
  4464. definition: function () {
  4465. var name, params = [], match, ruleset, cond, variadic = false;
  4466. if ((parserInput.currentChar() !== '.' && parserInput.currentChar() !== '#') ||
  4467. parserInput.peek(/^[^{]*\}/)) {
  4468. return;
  4469. }
  4470. parserInput.save();
  4471. match = parserInput.$re(/^([#.](?:[\w-]|\\(?:[A-Fa-f0-9]{1,6} ?|[^A-Fa-f0-9]))+)\s*\(/);
  4472. if (match) {
  4473. name = match[1];
  4474. var argInfo = this.args(false);
  4475. params = argInfo.args;
  4476. variadic = argInfo.variadic;
  4477. // .mixincall("@{a}");
  4478. // looks a bit like a mixin definition..
  4479. // also
  4480. // .mixincall(@a: {rule: set;});
  4481. // so we have to be nice and restore
  4482. if (!parserInput.$char(')')) {
  4483. parserInput.restore('Missing closing \')\'');
  4484. return;
  4485. }
  4486. parserInput.commentStore.length = 0;
  4487. if (parserInput.$str('when')) { // Guard
  4488. cond = expect(parsers.conditions, 'expected condition');
  4489. }
  4490. ruleset = parsers.block();
  4491. if (ruleset) {
  4492. parserInput.forget();
  4493. return new(tree.mixin.Definition)(name, params, ruleset, cond, variadic);
  4494. } else {
  4495. parserInput.restore();
  4496. }
  4497. } else {
  4498. parserInput.forget();
  4499. }
  4500. },
  4501. ruleLookups: function() {
  4502. var rule, args, lookups = [];
  4503. if (parserInput.currentChar() !== '[') {
  4504. return;
  4505. }
  4506. while (true) {
  4507. parserInput.save();
  4508. args = null;
  4509. rule = this.lookupValue();
  4510. if (!rule && rule !== '') {
  4511. parserInput.restore();
  4512. break;
  4513. }
  4514. lookups.push(rule);
  4515. parserInput.forget();
  4516. }
  4517. if (lookups.length > 0) {
  4518. return lookups;
  4519. }
  4520. },
  4521. lookupValue: function() {
  4522. parserInput.save();
  4523. if (!parserInput.$char('[')) {
  4524. parserInput.restore();
  4525. return;
  4526. }
  4527. var name = parserInput.$re(/^(?:[@$]{0,2})[_a-zA-Z0-9-]*/);
  4528. if (!parserInput.$char(']')) {
  4529. parserInput.restore();
  4530. return;
  4531. }
  4532. if (name || name === '') {
  4533. parserInput.forget();
  4534. return name;
  4535. }
  4536. parserInput.restore();
  4537. }
  4538. },
  4539. //
  4540. // Entities are the smallest recognized token,
  4541. // and can be found inside a rule's value.
  4542. //
  4543. entity: function () {
  4544. var entities = this.entities;
  4545. return this.comment() || entities.literal() || entities.variable() || entities.url() ||
  4546. entities.property() || entities.call() || entities.keyword() || this.mixin.call(true) ||
  4547. entities.javascript();
  4548. },
  4549. //
  4550. // A Declaration terminator. Note that we use `peek()` to check for '}',
  4551. // because the `block` rule will be expecting it, but we still need to make sure
  4552. // it's there, if ';' was omitted.
  4553. //
  4554. end: function () {
  4555. return parserInput.$char(';') || parserInput.peek('}');
  4556. },
  4557. //
  4558. // IE's alpha function
  4559. //
  4560. // alpha(opacity=88)
  4561. //
  4562. ieAlpha: function () {
  4563. var value;
  4564. // http://jsperf.com/case-insensitive-regex-vs-strtolower-then-regex/18
  4565. if (!parserInput.$re(/^opacity=/i)) { return; }
  4566. value = parserInput.$re(/^\d+/);
  4567. if (!value) {
  4568. value = expect(parsers.entities.variable, 'Could not parse alpha');
  4569. value = '@{' + value.name.slice(1) + '}';
  4570. }
  4571. expectChar(')');
  4572. return new tree.Quoted('', 'alpha(opacity=' + value + ')');
  4573. },
  4574. //
  4575. // A Selector Element
  4576. //
  4577. // div
  4578. // + h1
  4579. // #socks
  4580. // input[type="text"]
  4581. //
  4582. // Elements are the building blocks for Selectors,
  4583. // they are made out of a `Combinator` (see combinator rule),
  4584. // and an element name, such as a tag a class, or `*`.
  4585. //
  4586. element: function () {
  4587. var e, c, v, index = parserInput.i;
  4588. c = this.combinator();
  4589. e = parserInput.$re(/^(?:\d+\.\d+|\d+)%/) ||
  4590. parserInput.$re(/^(?:[.#]?|:*)(?:[\w-]|[^\x00-\x9f]|\\(?:[A-Fa-f0-9]{1,6} ?|[^A-Fa-f0-9]))+/) ||
  4591. parserInput.$char('*') || parserInput.$char('&') || this.attribute() ||
  4592. parserInput.$re(/^\([^&()@]+\)/) || parserInput.$re(/^[\.#:](?=@)/) ||
  4593. this.entities.variableCurly();
  4594. if (!e) {
  4595. parserInput.save();
  4596. if (parserInput.$char('(')) {
  4597. if ((v = this.selector(false)) && parserInput.$char(')')) {
  4598. e = new(tree.Paren)(v);
  4599. parserInput.forget();
  4600. } else {
  4601. parserInput.restore('Missing closing \')\'');
  4602. }
  4603. } else {
  4604. parserInput.forget();
  4605. }
  4606. }
  4607. if (e) { return new(tree.Element)(c, e, e instanceof tree.Variable, index, fileInfo); }
  4608. },
  4609. //
  4610. // Combinators combine elements together, in a Selector.
  4611. //
  4612. // Because our parser isn't white-space sensitive, special care
  4613. // has to be taken, when parsing the descendant combinator, ` `,
  4614. // as it's an empty space. We have to check the previous character
  4615. // in the input, to see if it's a ` ` character. More info on how
  4616. // we deal with this in *combinator.js*.
  4617. //
  4618. combinator: function () {
  4619. var c = parserInput.currentChar();
  4620. if (c === '/') {
  4621. parserInput.save();
  4622. var slashedCombinator = parserInput.$re(/^\/[a-z]+\//i);
  4623. if (slashedCombinator) {
  4624. parserInput.forget();
  4625. return new(tree.Combinator)(slashedCombinator);
  4626. }
  4627. parserInput.restore();
  4628. }
  4629. if (c === '>' || c === '+' || c === '~' || c === '|' || c === '^') {
  4630. parserInput.i++;
  4631. if (c === '^' && parserInput.currentChar() === '^') {
  4632. c = '^^';
  4633. parserInput.i++;
  4634. }
  4635. while (parserInput.isWhitespace()) { parserInput.i++; }
  4636. return new(tree.Combinator)(c);
  4637. } else if (parserInput.isWhitespace(-1)) {
  4638. return new(tree.Combinator)(' ');
  4639. } else {
  4640. return new(tree.Combinator)(null);
  4641. }
  4642. },
  4643. //
  4644. // A CSS Selector
  4645. // with less extensions e.g. the ability to extend and guard
  4646. //
  4647. // .class > div + h1
  4648. // li a:hover
  4649. //
  4650. // Selectors are made out of one or more Elements, see above.
  4651. //
  4652. selector: function (isLess) {
  4653. var index = parserInput.i, elements, extendList, c, e, allExtends, when, condition;
  4654. isLess = isLess !== false;
  4655. while ((isLess && (extendList = this.extend())) || (isLess && (when = parserInput.$str('when'))) || (e = this.element())) {
  4656. if (when) {
  4657. condition = expect(this.conditions, 'expected condition');
  4658. } else if (condition) {
  4659. error('CSS guard can only be used at the end of selector');
  4660. } else if (extendList) {
  4661. if (allExtends) {
  4662. allExtends = allExtends.concat(extendList);
  4663. } else {
  4664. allExtends = extendList;
  4665. }
  4666. } else {
  4667. if (allExtends) { error('Extend can only be used at the end of selector'); }
  4668. c = parserInput.currentChar();
  4669. if (elements) {
  4670. elements.push(e);
  4671. } else {
  4672. elements = [ e ];
  4673. }
  4674. e = null;
  4675. }
  4676. if (c === '{' || c === '}' || c === ';' || c === ',' || c === ')') {
  4677. break;
  4678. }
  4679. }
  4680. if (elements) { return new(tree.Selector)(elements, allExtends, condition, index, fileInfo); }
  4681. if (allExtends) { error('Extend must be used to extend a selector, it cannot be used on its own'); }
  4682. },
  4683. selectors: function () {
  4684. var s, selectors;
  4685. while (true) {
  4686. s = this.selector();
  4687. if (!s) {
  4688. break;
  4689. }
  4690. if (selectors) {
  4691. selectors.push(s);
  4692. } else {
  4693. selectors = [ s ];
  4694. }
  4695. parserInput.commentStore.length = 0;
  4696. if (s.condition && selectors.length > 1) {
  4697. error("Guards are only currently allowed on a single selector.");
  4698. }
  4699. if (!parserInput.$char(',')) { break; }
  4700. if (s.condition) {
  4701. error("Guards are only currently allowed on a single selector.");
  4702. }
  4703. parserInput.commentStore.length = 0;
  4704. }
  4705. return selectors;
  4706. },
  4707. attribute: function () {
  4708. if (!parserInput.$char('[')) { return; }
  4709. var entities = this.entities,
  4710. key, val, op;
  4711. if (!(key = entities.variableCurly())) {
  4712. key = expect(/^(?:[_A-Za-z0-9-\*]*\|)?(?:[_A-Za-z0-9-]|\\.)+/);
  4713. }
  4714. op = parserInput.$re(/^[|~*$^]?=/);
  4715. if (op) {
  4716. val = entities.quoted() || parserInput.$re(/^[0-9]+%/) || parserInput.$re(/^[\w-]+/) || entities.variableCurly();
  4717. }
  4718. expectChar(']');
  4719. return new(tree.Attribute)(key, op, val);
  4720. },
  4721. //
  4722. // The `block` rule is used by `ruleset` and `mixin.definition`.
  4723. // It's a wrapper around the `primary` rule, with added `{}`.
  4724. //
  4725. block: function () {
  4726. var content;
  4727. if (parserInput.$char('{') && (content = this.primary()) && parserInput.$char('}')) {
  4728. return content;
  4729. }
  4730. },
  4731. blockRuleset: function() {
  4732. var block = this.block();
  4733. if (block) {
  4734. block = new tree.Ruleset(null, block);
  4735. }
  4736. return block;
  4737. },
  4738. detachedRuleset: function() {
  4739. var argInfo, params, variadic;
  4740. parserInput.save();
  4741. if (parserInput.$re(/^[.#]\(/)) {
  4742. /**
  4743. * DR args currently only implemented for each() function, and not
  4744. * yet settable as `@dr: #(@arg) {}`
  4745. * This should be done when DRs are merged with mixins.
  4746. * See: https://github.com/less/less-meta/issues/16
  4747. */
  4748. argInfo = this.mixin.args(false);
  4749. params = argInfo.args;
  4750. variadic = argInfo.variadic;
  4751. if (!parserInput.$char(')')) {
  4752. parserInput.restore();
  4753. return;
  4754. }
  4755. }
  4756. var blockRuleset = this.blockRuleset();
  4757. if (blockRuleset) {
  4758. parserInput.forget();
  4759. if (params) {
  4760. return new tree.mixin.Definition(null, params, blockRuleset, null, variadic);
  4761. }
  4762. return new tree.DetachedRuleset(blockRuleset);
  4763. }
  4764. parserInput.restore();
  4765. },
  4766. //
  4767. // div, .class, body > p {...}
  4768. //
  4769. ruleset: function () {
  4770. var selectors, rules, debugInfo;
  4771. parserInput.save();
  4772. if (context.dumpLineNumbers) {
  4773. debugInfo = getDebugInfo(parserInput.i);
  4774. }
  4775. selectors = this.selectors();
  4776. if (selectors && (rules = this.block())) {
  4777. parserInput.forget();
  4778. var ruleset = new(tree.Ruleset)(selectors, rules, context.strictImports);
  4779. if (context.dumpLineNumbers) {
  4780. ruleset.debugInfo = debugInfo;
  4781. }
  4782. return ruleset;
  4783. } else {
  4784. parserInput.restore();
  4785. }
  4786. },
  4787. declaration: function () {
  4788. var name, value, index = parserInput.i, hasDR,
  4789. c = parserInput.currentChar(), important, merge, isVariable;
  4790. if (c === '.' || c === '#' || c === '&' || c === ':') { return; }
  4791. parserInput.save();
  4792. name = this.variable() || this.ruleProperty();
  4793. if (name) {
  4794. isVariable = typeof name === 'string';
  4795. if (isVariable) {
  4796. value = this.detachedRuleset();
  4797. if (value) {
  4798. hasDR = true;
  4799. }
  4800. }
  4801. parserInput.commentStore.length = 0;
  4802. if (!value) {
  4803. // a name returned by this.ruleProperty() is always an array of the form:
  4804. // [string-1, ..., string-n, ""] or [string-1, ..., string-n, "+"]
  4805. // where each item is a tree.Keyword or tree.Variable
  4806. merge = !isVariable && name.length > 1 && name.pop().value;
  4807. // Custom property values get permissive parsing
  4808. if (name[0].value && name[0].value.slice(0, 2) === '--') {
  4809. value = this.permissiveValue();
  4810. }
  4811. // Try to store values as anonymous
  4812. // If we need the value later we'll re-parse it in ruleset.parseValue
  4813. else {
  4814. value = this.anonymousValue();
  4815. }
  4816. if (value) {
  4817. parserInput.forget();
  4818. // anonymous values absorb the end ';' which is required for them to work
  4819. return new (tree.Declaration)(name, value, false, merge, index, fileInfo);
  4820. }
  4821. if (!value) {
  4822. value = this.value();
  4823. }
  4824. if (value) {
  4825. important = this.important();
  4826. } else if (isVariable) {
  4827. // As a last resort, try permissiveValue
  4828. value = this.permissiveValue();
  4829. }
  4830. }
  4831. if (value && (this.end() || hasDR)) {
  4832. parserInput.forget();
  4833. return new (tree.Declaration)(name, value, important, merge, index, fileInfo);
  4834. }
  4835. else {
  4836. parserInput.restore();
  4837. }
  4838. } else {
  4839. parserInput.restore();
  4840. }
  4841. },
  4842. anonymousValue: function () {
  4843. var index = parserInput.i;
  4844. var match = parserInput.$re(/^([^.#@\$+\/'"*`(;{}-]*);/);
  4845. if (match) {
  4846. return new(tree.Anonymous)(match[1], index);
  4847. }
  4848. },
  4849. /**
  4850. * Used for custom properties, at-rules, and variables (as fallback)
  4851. * Parses almost anything inside of {} [] () "" blocks
  4852. * until it reaches outer-most tokens.
  4853. *
  4854. * First, it will try to parse comments and entities to reach
  4855. * the end. This is mostly like the Expression parser except no
  4856. * math is allowed.
  4857. */
  4858. permissiveValue: function (untilTokens) {
  4859. var i, e, done, value,
  4860. tok = untilTokens || ';',
  4861. index = parserInput.i, result = [];
  4862. function testCurrentChar() {
  4863. var char = parserInput.currentChar();
  4864. if (typeof tok === 'string') {
  4865. return char === tok;
  4866. } else {
  4867. return tok.test(char);
  4868. }
  4869. }
  4870. if (testCurrentChar()) {
  4871. return;
  4872. }
  4873. value = [];
  4874. do {
  4875. e = this.comment();
  4876. if (e) {
  4877. value.push(e);
  4878. continue;
  4879. }
  4880. e = this.entity();
  4881. if (e) {
  4882. value.push(e);
  4883. }
  4884. } while (e);
  4885. done = testCurrentChar();
  4886. if (value.length > 0) {
  4887. value = new(tree.Expression)(value);
  4888. if (done) {
  4889. return value;
  4890. }
  4891. else {
  4892. result.push(value);
  4893. }
  4894. // Preserve space before $parseUntil as it will not
  4895. if (parserInput.prevChar() === ' ') {
  4896. result.push(new tree.Anonymous(' ', index));
  4897. }
  4898. }
  4899. parserInput.save();
  4900. value = parserInput.$parseUntil(tok);
  4901. if (value) {
  4902. if (typeof value === 'string') {
  4903. error('Expected \'' + value + '\'', 'Parse');
  4904. }
  4905. if (value.length === 1 && value[0] === ' ') {
  4906. parserInput.forget();
  4907. return new tree.Anonymous('', index);
  4908. }
  4909. var item;
  4910. for (i = 0; i < value.length; i++) {
  4911. item = value[i];
  4912. if (Array.isArray(item)) {
  4913. // Treat actual quotes as normal quoted values
  4914. result.push(new tree.Quoted(item[0], item[1], true, index, fileInfo));
  4915. }
  4916. else {
  4917. if (i === value.length - 1) {
  4918. item = item.trim();
  4919. }
  4920. // Treat like quoted values, but replace vars like unquoted expressions
  4921. var quote = new tree.Quoted('\'', item, true, index, fileInfo);
  4922. quote.variableRegex = /@([\w-]+)/g;
  4923. quote.propRegex = /\$([\w-]+)/g;
  4924. result.push(quote);
  4925. }
  4926. }
  4927. parserInput.forget();
  4928. return new tree.Expression(result, true);
  4929. }
  4930. parserInput.restore();
  4931. },
  4932. //
  4933. // An @import atrule
  4934. //
  4935. // @import "lib";
  4936. //
  4937. // Depending on our environment, importing is done differently:
  4938. // In the browser, it's an XHR request, in Node, it would be a
  4939. // file-system operation. The function used for importing is
  4940. // stored in `import`, which we pass to the Import constructor.
  4941. //
  4942. 'import': function () {
  4943. var path, features, index = parserInput.i;
  4944. var dir = parserInput.$re(/^@import?\s+/);
  4945. if (dir) {
  4946. var options = (dir ? this.importOptions() : null) || {};
  4947. if ((path = this.entities.quoted() || this.entities.url())) {
  4948. features = this.mediaFeatures();
  4949. if (!parserInput.$char(';')) {
  4950. parserInput.i = index;
  4951. error('missing semi-colon or unrecognised media features on import');
  4952. }
  4953. features = features && new(tree.Value)(features);
  4954. return new(tree.Import)(path, features, options, index, fileInfo);
  4955. }
  4956. else {
  4957. parserInput.i = index;
  4958. error('malformed import statement');
  4959. }
  4960. }
  4961. },
  4962. importOptions: function() {
  4963. var o, options = {}, optionName, value;
  4964. // list of options, surrounded by parens
  4965. if (!parserInput.$char('(')) { return null; }
  4966. do {
  4967. o = this.importOption();
  4968. if (o) {
  4969. optionName = o;
  4970. value = true;
  4971. switch (optionName) {
  4972. case 'css':
  4973. optionName = 'less';
  4974. value = false;
  4975. break;
  4976. case 'once':
  4977. optionName = 'multiple';
  4978. value = false;
  4979. break;
  4980. }
  4981. options[optionName] = value;
  4982. if (!parserInput.$char(',')) { break; }
  4983. }
  4984. } while (o);
  4985. expectChar(')');
  4986. return options;
  4987. },
  4988. importOption: function() {
  4989. var opt = parserInput.$re(/^(less|css|multiple|once|inline|reference|optional)/);
  4990. if (opt) {
  4991. return opt[1];
  4992. }
  4993. },
  4994. mediaFeature: function () {
  4995. var entities = this.entities, nodes = [], e, p;
  4996. parserInput.save();
  4997. do {
  4998. e = entities.keyword() || entities.variable() || entities.mixinLookup();
  4999. if (e) {
  5000. nodes.push(e);
  5001. } else if (parserInput.$char('(')) {
  5002. p = this.property();
  5003. e = this.value();
  5004. if (parserInput.$char(')')) {
  5005. if (p && e) {
  5006. nodes.push(new(tree.Paren)(new(tree.Declaration)(p, e, null, null, parserInput.i, fileInfo, true)));
  5007. } else if (e) {
  5008. nodes.push(new(tree.Paren)(e));
  5009. } else {
  5010. error('badly formed media feature definition');
  5011. }
  5012. } else {
  5013. error('Missing closing \')\'', 'Parse');
  5014. }
  5015. }
  5016. } while (e);
  5017. parserInput.forget();
  5018. if (nodes.length > 0) {
  5019. return new(tree.Expression)(nodes);
  5020. }
  5021. },
  5022. mediaFeatures: function () {
  5023. var entities = this.entities, features = [], e;
  5024. do {
  5025. e = this.mediaFeature();
  5026. if (e) {
  5027. features.push(e);
  5028. if (!parserInput.$char(',')) { break; }
  5029. } else {
  5030. e = entities.variable() || entities.mixinLookup();
  5031. if (e) {
  5032. features.push(e);
  5033. if (!parserInput.$char(',')) { break; }
  5034. }
  5035. }
  5036. } while (e);
  5037. return features.length > 0 ? features : null;
  5038. },
  5039. media: function () {
  5040. var features, rules, media, debugInfo, index = parserInput.i;
  5041. if (context.dumpLineNumbers) {
  5042. debugInfo = getDebugInfo(index);
  5043. }
  5044. parserInput.save();
  5045. if (parserInput.$str('@media')) {
  5046. features = this.mediaFeatures();
  5047. rules = this.block();
  5048. if (!rules) {
  5049. error('media definitions require block statements after any features');
  5050. }
  5051. parserInput.forget();
  5052. media = new(tree.Media)(rules, features, index, fileInfo);
  5053. if (context.dumpLineNumbers) {
  5054. media.debugInfo = debugInfo;
  5055. }
  5056. return media;
  5057. }
  5058. parserInput.restore();
  5059. },
  5060. //
  5061. // A @plugin directive, used to import plugins dynamically.
  5062. //
  5063. // @plugin (args) "lib";
  5064. //
  5065. plugin: function () {
  5066. var path, args, options,
  5067. index = parserInput.i,
  5068. dir = parserInput.$re(/^@plugin?\s+/);
  5069. if (dir) {
  5070. args = this.pluginArgs();
  5071. if (args) {
  5072. options = {
  5073. pluginArgs: args,
  5074. isPlugin: true
  5075. };
  5076. }
  5077. else {
  5078. options = { isPlugin: true };
  5079. }
  5080. if ((path = this.entities.quoted() || this.entities.url())) {
  5081. if (!parserInput.$char(';')) {
  5082. parserInput.i = index;
  5083. error('missing semi-colon on @plugin');
  5084. }
  5085. return new(tree.Import)(path, null, options, index, fileInfo);
  5086. }
  5087. else {
  5088. parserInput.i = index;
  5089. error('malformed @plugin statement');
  5090. }
  5091. }
  5092. },
  5093. pluginArgs: function() {
  5094. // list of options, surrounded by parens
  5095. parserInput.save();
  5096. if (!parserInput.$char('(')) {
  5097. parserInput.restore();
  5098. return null;
  5099. }
  5100. var args = parserInput.$re(/^\s*([^\);]+)\)\s*/);
  5101. if (args[1]) {
  5102. parserInput.forget();
  5103. return args[1].trim();
  5104. }
  5105. else {
  5106. parserInput.restore();
  5107. return null;
  5108. }
  5109. },
  5110. //
  5111. // A CSS AtRule
  5112. //
  5113. // @charset "utf-8";
  5114. //
  5115. atrule: function () {
  5116. var index = parserInput.i, name, value, rules, nonVendorSpecificName,
  5117. hasIdentifier, hasExpression, hasUnknown, hasBlock = true, isRooted = true;
  5118. if (parserInput.currentChar() !== '@') { return; }
  5119. value = this['import']() || this.plugin() || this.media();
  5120. if (value) {
  5121. return value;
  5122. }
  5123. parserInput.save();
  5124. name = parserInput.$re(/^@[a-z-]+/);
  5125. if (!name) { return; }
  5126. nonVendorSpecificName = name;
  5127. if (name.charAt(1) == '-' && name.indexOf('-', 2) > 0) {
  5128. nonVendorSpecificName = '@' + name.slice(name.indexOf('-', 2) + 1);
  5129. }
  5130. switch (nonVendorSpecificName) {
  5131. case '@charset':
  5132. hasIdentifier = true;
  5133. hasBlock = false;
  5134. break;
  5135. case '@namespace':
  5136. hasExpression = true;
  5137. hasBlock = false;
  5138. break;
  5139. case '@keyframes':
  5140. case '@counter-style':
  5141. hasIdentifier = true;
  5142. break;
  5143. case '@document':
  5144. case '@supports':
  5145. hasUnknown = true;
  5146. isRooted = false;
  5147. break;
  5148. default:
  5149. hasUnknown = true;
  5150. break;
  5151. }
  5152. parserInput.commentStore.length = 0;
  5153. if (hasIdentifier) {
  5154. value = this.entity();
  5155. if (!value) {
  5156. error('expected ' + name + ' identifier');
  5157. }
  5158. } else if (hasExpression) {
  5159. value = this.expression();
  5160. if (!value) {
  5161. error('expected ' + name + ' expression');
  5162. }
  5163. } else if (hasUnknown) {
  5164. value = this.permissiveValue(/^[{;]/);
  5165. hasBlock = (parserInput.currentChar() === '{');
  5166. if (!value) {
  5167. if (!hasBlock && parserInput.currentChar() !== ';') {
  5168. error(name + ' rule is missing block or ending semi-colon');
  5169. }
  5170. }
  5171. else if (!value.value) {
  5172. value = null;
  5173. }
  5174. }
  5175. if (hasBlock) {
  5176. rules = this.blockRuleset();
  5177. }
  5178. if (rules || (!hasBlock && value && parserInput.$char(';'))) {
  5179. parserInput.forget();
  5180. return new (tree.AtRule)(name, value, rules, index, fileInfo,
  5181. context.dumpLineNumbers ? getDebugInfo(index) : null,
  5182. isRooted
  5183. );
  5184. }
  5185. parserInput.restore('at-rule options not recognised');
  5186. },
  5187. //
  5188. // A Value is a comma-delimited list of Expressions
  5189. //
  5190. // font-family: Baskerville, Georgia, serif;
  5191. //
  5192. // In a Rule, a Value represents everything after the `:`,
  5193. // and before the `;`.
  5194. //
  5195. value: function () {
  5196. var e, expressions = [], index = parserInput.i;
  5197. do {
  5198. e = this.expression();
  5199. if (e) {
  5200. expressions.push(e);
  5201. if (!parserInput.$char(',')) { break; }
  5202. }
  5203. } while (e);
  5204. if (expressions.length > 0) {
  5205. return new(tree.Value)(expressions, index);
  5206. }
  5207. },
  5208. important: function () {
  5209. if (parserInput.currentChar() === '!') {
  5210. return parserInput.$re(/^! *important/);
  5211. }
  5212. },
  5213. sub: function () {
  5214. var a, e;
  5215. parserInput.save();
  5216. if (parserInput.$char('(')) {
  5217. a = this.addition();
  5218. if (a && parserInput.$char(')')) {
  5219. parserInput.forget();
  5220. e = new(tree.Expression)([a]);
  5221. e.parens = true;
  5222. return e;
  5223. }
  5224. parserInput.restore('Expected \')\'');
  5225. return;
  5226. }
  5227. parserInput.restore();
  5228. },
  5229. multiplication: function () {
  5230. var m, a, op, operation, isSpaced;
  5231. m = this.operand();
  5232. if (m) {
  5233. isSpaced = parserInput.isWhitespace(-1);
  5234. while (true) {
  5235. if (parserInput.peek(/^\/[*\/]/)) {
  5236. break;
  5237. }
  5238. parserInput.save();
  5239. op = parserInput.$char('/') || parserInput.$char('*') || parserInput.$str('./');
  5240. if (!op) { parserInput.forget(); break; }
  5241. a = this.operand();
  5242. if (!a) { parserInput.restore(); break; }
  5243. parserInput.forget();
  5244. m.parensInOp = true;
  5245. a.parensInOp = true;
  5246. operation = new(tree.Operation)(op, [operation || m, a], isSpaced);
  5247. isSpaced = parserInput.isWhitespace(-1);
  5248. }
  5249. return operation || m;
  5250. }
  5251. },
  5252. addition: function () {
  5253. var m, a, op, operation, isSpaced;
  5254. m = this.multiplication();
  5255. if (m) {
  5256. isSpaced = parserInput.isWhitespace(-1);
  5257. while (true) {
  5258. op = parserInput.$re(/^[-+]\s+/) || (!isSpaced && (parserInput.$char('+') || parserInput.$char('-')));
  5259. if (!op) {
  5260. break;
  5261. }
  5262. a = this.multiplication();
  5263. if (!a) {
  5264. break;
  5265. }
  5266. m.parensInOp = true;
  5267. a.parensInOp = true;
  5268. operation = new(tree.Operation)(op, [operation || m, a], isSpaced);
  5269. isSpaced = parserInput.isWhitespace(-1);
  5270. }
  5271. return operation || m;
  5272. }
  5273. },
  5274. conditions: function () {
  5275. var a, b, index = parserInput.i, condition;
  5276. a = this.condition(true);
  5277. if (a) {
  5278. while (true) {
  5279. if (!parserInput.peek(/^,\s*(not\s*)?\(/) || !parserInput.$char(',')) {
  5280. break;
  5281. }
  5282. b = this.condition(true);
  5283. if (!b) {
  5284. break;
  5285. }
  5286. condition = new(tree.Condition)('or', condition || a, b, index);
  5287. }
  5288. return condition || a;
  5289. }
  5290. },
  5291. condition: function (needsParens) {
  5292. var result, logical, next;
  5293. function or() {
  5294. return parserInput.$str('or');
  5295. }
  5296. result = this.conditionAnd(needsParens);
  5297. if (!result) {
  5298. return ;
  5299. }
  5300. logical = or();
  5301. if (logical) {
  5302. next = this.condition(needsParens);
  5303. if (next) {
  5304. result = new(tree.Condition)(logical, result, next);
  5305. } else {
  5306. return ;
  5307. }
  5308. }
  5309. return result;
  5310. },
  5311. conditionAnd: function (needsParens) {
  5312. var result, logical, next, self = this;
  5313. function insideCondition() {
  5314. var cond = self.negatedCondition(needsParens) || self.parenthesisCondition(needsParens);
  5315. if (!cond && !needsParens) {
  5316. return self.atomicCondition(needsParens);
  5317. }
  5318. return cond;
  5319. }
  5320. function and() {
  5321. return parserInput.$str('and');
  5322. }
  5323. result = insideCondition();
  5324. if (!result) {
  5325. return ;
  5326. }
  5327. logical = and();
  5328. if (logical) {
  5329. next = this.conditionAnd(needsParens);
  5330. if (next) {
  5331. result = new(tree.Condition)(logical, result, next);
  5332. } else {
  5333. return ;
  5334. }
  5335. }
  5336. return result;
  5337. },
  5338. negatedCondition: function (needsParens) {
  5339. if (parserInput.$str('not')) {
  5340. var result = this.parenthesisCondition(needsParens);
  5341. if (result) {
  5342. result.negate = !result.negate;
  5343. }
  5344. return result;
  5345. }
  5346. },
  5347. parenthesisCondition: function (needsParens) {
  5348. function tryConditionFollowedByParenthesis(me) {
  5349. var body;
  5350. parserInput.save();
  5351. body = me.condition(needsParens);
  5352. if (!body) {
  5353. parserInput.restore();
  5354. return ;
  5355. }
  5356. if (!parserInput.$char(')')) {
  5357. parserInput.restore();
  5358. return ;
  5359. }
  5360. parserInput.forget();
  5361. return body;
  5362. }
  5363. var body;
  5364. parserInput.save();
  5365. if (!parserInput.$str('(')) {
  5366. parserInput.restore();
  5367. return ;
  5368. }
  5369. body = tryConditionFollowedByParenthesis(this);
  5370. if (body) {
  5371. parserInput.forget();
  5372. return body;
  5373. }
  5374. body = this.atomicCondition(needsParens);
  5375. if (!body) {
  5376. parserInput.restore();
  5377. return ;
  5378. }
  5379. if (!parserInput.$char(')')) {
  5380. parserInput.restore('expected \')\' got \'' + parserInput.currentChar() + '\'');
  5381. return ;
  5382. }
  5383. parserInput.forget();
  5384. return body;
  5385. },
  5386. atomicCondition: function (needsParens) {
  5387. var entities = this.entities, index = parserInput.i, a, b, c, op;
  5388. function cond() {
  5389. return this.addition() || entities.keyword() || entities.quoted() || entities.mixinLookup();
  5390. }
  5391. cond = cond.bind(this);
  5392. a = cond();
  5393. if (a) {
  5394. if (parserInput.$char('>')) {
  5395. if (parserInput.$char('=')) {
  5396. op = '>=';
  5397. } else {
  5398. op = '>';
  5399. }
  5400. } else
  5401. if (parserInput.$char('<')) {
  5402. if (parserInput.$char('=')) {
  5403. op = '<=';
  5404. } else {
  5405. op = '<';
  5406. }
  5407. } else
  5408. if (parserInput.$char('=')) {
  5409. if (parserInput.$char('>')) {
  5410. op = '=>';
  5411. } else if (parserInput.$char('<')) {
  5412. op = '=<';
  5413. } else {
  5414. op = '=';
  5415. }
  5416. }
  5417. if (op) {
  5418. b = cond();
  5419. if (b) {
  5420. c = new(tree.Condition)(op, a, b, index, false);
  5421. } else {
  5422. error('expected expression');
  5423. }
  5424. } else {
  5425. c = new(tree.Condition)('=', a, new(tree.Keyword)('true'), index, false);
  5426. }
  5427. return c;
  5428. }
  5429. },
  5430. //
  5431. // An operand is anything that can be part of an operation,
  5432. // such as a Color, or a Variable
  5433. //
  5434. operand: function () {
  5435. var entities = this.entities, negate;
  5436. if (parserInput.peek(/^-[@\$\(]/)) {
  5437. negate = parserInput.$char('-');
  5438. }
  5439. var o = this.sub() || entities.dimension() ||
  5440. entities.color() || entities.variable() ||
  5441. entities.property() || entities.call() ||
  5442. entities.quoted(true) || entities.colorKeyword() ||
  5443. entities.mixinLookup();
  5444. if (negate) {
  5445. o.parensInOp = true;
  5446. o = new(tree.Negative)(o);
  5447. }
  5448. return o;
  5449. },
  5450. //
  5451. // Expressions either represent mathematical operations,
  5452. // or white-space delimited Entities.
  5453. //
  5454. // 1px solid black
  5455. // @var * 2
  5456. //
  5457. expression: function () {
  5458. var entities = [], e, delim, index = parserInput.i;
  5459. do {
  5460. e = this.comment();
  5461. if (e) {
  5462. entities.push(e);
  5463. continue;
  5464. }
  5465. e = this.addition() || this.entity();
  5466. if (e) {
  5467. entities.push(e);
  5468. // operations do not allow keyword "/" dimension (e.g. small/20px) so we support that here
  5469. if (!parserInput.peek(/^\/[\/*]/)) {
  5470. delim = parserInput.$char('/');
  5471. if (delim) {
  5472. entities.push(new(tree.Anonymous)(delim, index));
  5473. }
  5474. }
  5475. }
  5476. } while (e);
  5477. if (entities.length > 0) {
  5478. return new(tree.Expression)(entities);
  5479. }
  5480. },
  5481. property: function () {
  5482. var name = parserInput.$re(/^(\*?-?[_a-zA-Z0-9-]+)\s*:/);
  5483. if (name) {
  5484. return name[1];
  5485. }
  5486. },
  5487. ruleProperty: function () {
  5488. var name = [], index = [], s, k;
  5489. parserInput.save();
  5490. var simpleProperty = parserInput.$re(/^([_a-zA-Z0-9-]+)\s*:/);
  5491. if (simpleProperty) {
  5492. name = [new(tree.Keyword)(simpleProperty[1])];
  5493. parserInput.forget();
  5494. return name;
  5495. }
  5496. function match(re) {
  5497. var i = parserInput.i,
  5498. chunk = parserInput.$re(re);
  5499. if (chunk) {
  5500. index.push(i);
  5501. return name.push(chunk[1]);
  5502. }
  5503. }
  5504. match(/^(\*?)/);
  5505. while (true) {
  5506. if (!match(/^((?:[\w-]+)|(?:[@\$]\{[\w-]+\}))/)) {
  5507. break;
  5508. }
  5509. }
  5510. if ((name.length > 1) && match(/^((?:\+_|\+)?)\s*:/)) {
  5511. parserInput.forget();
  5512. // at last, we have the complete match now. move forward,
  5513. // convert name particles to tree objects and return:
  5514. if (name[0] === '') {
  5515. name.shift();
  5516. index.shift();
  5517. }
  5518. for (k = 0; k < name.length; k++) {
  5519. s = name[k];
  5520. name[k] = (s.charAt(0) !== '@' && s.charAt(0) !== '$') ?
  5521. new(tree.Keyword)(s) :
  5522. (s.charAt(0) === '@' ?
  5523. new(tree.Variable)('@' + s.slice(2, -1), index[k], fileInfo) :
  5524. new(tree.Property)('$' + s.slice(2, -1), index[k], fileInfo));
  5525. }
  5526. return name;
  5527. }
  5528. parserInput.restore();
  5529. }
  5530. }
  5531. };
  5532. };
  5533. Parser.serializeVars = function(vars) {
  5534. var s = '';
  5535. for (var name in vars) {
  5536. if (Object.hasOwnProperty.call(vars, name)) {
  5537. var value = vars[name];
  5538. s += ((name[0] === '@') ? '' : '@') + name + ': ' + value +
  5539. ((String(value).slice(-1) === ';') ? '' : ';');
  5540. }
  5541. }
  5542. return s;
  5543. };
  5544. module.exports = Parser;
  5545. },{"../functions/function-registry":27,"../less-error":38,"../tree":67,"../utils":89,"../visitors":93,"./parser-input":43}],45:[function(require,module,exports){
  5546. /**
  5547. * Plugin Manager
  5548. */
  5549. var PluginManager = function(less) {
  5550. this.less = less;
  5551. this.visitors = [];
  5552. this.preProcessors = [];
  5553. this.postProcessors = [];
  5554. this.installedPlugins = [];
  5555. this.fileManagers = [];
  5556. this.iterator = -1;
  5557. this.pluginCache = {};
  5558. this.Loader = new less.PluginLoader(less);
  5559. };
  5560. var pm, PluginManagerFactory = function(less, newFactory) {
  5561. if (newFactory || !pm) {
  5562. pm = new PluginManager(less);
  5563. }
  5564. return pm;
  5565. };
  5566. /**
  5567. * Adds all the plugins in the array
  5568. * @param {Array} plugins
  5569. */
  5570. PluginManager.prototype.addPlugins = function(plugins) {
  5571. if (plugins) {
  5572. for (var i = 0; i < plugins.length; i++) {
  5573. this.addPlugin(plugins[i]);
  5574. }
  5575. }
  5576. };
  5577. /**
  5578. *
  5579. * @param plugin
  5580. * @param {String} filename
  5581. */
  5582. PluginManager.prototype.addPlugin = function(plugin, filename, functionRegistry) {
  5583. this.installedPlugins.push(plugin);
  5584. if (filename) {
  5585. this.pluginCache[filename] = plugin;
  5586. }
  5587. if (plugin.install) {
  5588. plugin.install(this.less, this, functionRegistry || this.less.functions.functionRegistry);
  5589. }
  5590. };
  5591. /**
  5592. *
  5593. * @param filename
  5594. */
  5595. PluginManager.prototype.get = function(filename) {
  5596. return this.pluginCache[filename];
  5597. };
  5598. /**
  5599. * Adds a visitor. The visitor object has options on itself to determine
  5600. * when it should run.
  5601. * @param visitor
  5602. */
  5603. PluginManager.prototype.addVisitor = function(visitor) {
  5604. this.visitors.push(visitor);
  5605. };
  5606. /**
  5607. * Adds a pre processor object
  5608. * @param {object} preProcessor
  5609. * @param {number} priority - guidelines 1 = before import, 1000 = import, 2000 = after import
  5610. */
  5611. PluginManager.prototype.addPreProcessor = function(preProcessor, priority) {
  5612. var indexToInsertAt;
  5613. for (indexToInsertAt = 0; indexToInsertAt < this.preProcessors.length; indexToInsertAt++) {
  5614. if (this.preProcessors[indexToInsertAt].priority >= priority) {
  5615. break;
  5616. }
  5617. }
  5618. this.preProcessors.splice(indexToInsertAt, 0, {preProcessor: preProcessor, priority: priority});
  5619. };
  5620. /**
  5621. * Adds a post processor object
  5622. * @param {object} postProcessor
  5623. * @param {number} priority - guidelines 1 = before compression, 1000 = compression, 2000 = after compression
  5624. */
  5625. PluginManager.prototype.addPostProcessor = function(postProcessor, priority) {
  5626. var indexToInsertAt;
  5627. for (indexToInsertAt = 0; indexToInsertAt < this.postProcessors.length; indexToInsertAt++) {
  5628. if (this.postProcessors[indexToInsertAt].priority >= priority) {
  5629. break;
  5630. }
  5631. }
  5632. this.postProcessors.splice(indexToInsertAt, 0, {postProcessor: postProcessor, priority: priority});
  5633. };
  5634. /**
  5635. *
  5636. * @param manager
  5637. */
  5638. PluginManager.prototype.addFileManager = function(manager) {
  5639. this.fileManagers.push(manager);
  5640. };
  5641. /**
  5642. *
  5643. * @returns {Array}
  5644. * @private
  5645. */
  5646. PluginManager.prototype.getPreProcessors = function() {
  5647. var preProcessors = [];
  5648. for (var i = 0; i < this.preProcessors.length; i++) {
  5649. preProcessors.push(this.preProcessors[i].preProcessor);
  5650. }
  5651. return preProcessors;
  5652. };
  5653. /**
  5654. *
  5655. * @returns {Array}
  5656. * @private
  5657. */
  5658. PluginManager.prototype.getPostProcessors = function() {
  5659. var postProcessors = [];
  5660. for (var i = 0; i < this.postProcessors.length; i++) {
  5661. postProcessors.push(this.postProcessors[i].postProcessor);
  5662. }
  5663. return postProcessors;
  5664. };
  5665. /**
  5666. *
  5667. * @returns {Array}
  5668. * @private
  5669. */
  5670. PluginManager.prototype.getVisitors = function() {
  5671. return this.visitors;
  5672. };
  5673. PluginManager.prototype.visitor = function() {
  5674. var self = this;
  5675. return {
  5676. first: function() {
  5677. self.iterator = -1;
  5678. return self.visitors[self.iterator];
  5679. },
  5680. get: function() {
  5681. self.iterator += 1;
  5682. return self.visitors[self.iterator];
  5683. }
  5684. };
  5685. };
  5686. /**
  5687. *
  5688. * @returns {Array}
  5689. * @private
  5690. */
  5691. PluginManager.prototype.getFileManagers = function() {
  5692. return this.fileManagers;
  5693. };
  5694. //
  5695. module.exports = PluginManagerFactory;
  5696. },{}],46:[function(require,module,exports){
  5697. var PromiseConstructor,
  5698. utils = require('./utils');
  5699. module.exports = function(environment, ParseTree, ImportManager) {
  5700. var render = function (input, options, callback) {
  5701. if (typeof options === 'function') {
  5702. callback = options;
  5703. options = utils.copyOptions(this.options, {});
  5704. }
  5705. else {
  5706. options = utils.copyOptions(this.options, options || {});
  5707. }
  5708. if (!callback) {
  5709. if (!PromiseConstructor) {
  5710. PromiseConstructor = typeof Promise === 'undefined' ? require('promise') : Promise;
  5711. }
  5712. var self = this;
  5713. return new PromiseConstructor(function (resolve, reject) {
  5714. render.call(self, input, options, function(err, output) {
  5715. if (err) {
  5716. reject(err);
  5717. } else {
  5718. resolve(output);
  5719. }
  5720. });
  5721. });
  5722. } else {
  5723. this.parse(input, options, function(err, root, imports, options) {
  5724. if (err) { return callback(err); }
  5725. var result;
  5726. try {
  5727. var parseTree = new ParseTree(root, imports);
  5728. result = parseTree.toCSS(options);
  5729. }
  5730. catch (err) { return callback(err); }
  5731. callback(null, result);
  5732. });
  5733. }
  5734. };
  5735. return render;
  5736. };
  5737. },{"./utils":89,"promise":undefined}],47:[function(require,module,exports){
  5738. module.exports = function (SourceMapOutput, environment) {
  5739. var SourceMapBuilder = function (options) {
  5740. this.options = options;
  5741. };
  5742. SourceMapBuilder.prototype.toCSS = function(rootNode, options, imports) {
  5743. var sourceMapOutput = new SourceMapOutput(
  5744. {
  5745. contentsIgnoredCharsMap: imports.contentsIgnoredChars,
  5746. rootNode: rootNode,
  5747. contentsMap: imports.contents,
  5748. sourceMapFilename: this.options.sourceMapFilename,
  5749. sourceMapURL: this.options.sourceMapURL,
  5750. outputFilename: this.options.sourceMapOutputFilename,
  5751. sourceMapBasepath: this.options.sourceMapBasepath,
  5752. sourceMapRootpath: this.options.sourceMapRootpath,
  5753. outputSourceFiles: this.options.outputSourceFiles,
  5754. sourceMapGenerator: this.options.sourceMapGenerator,
  5755. sourceMapFileInline: this.options.sourceMapFileInline
  5756. });
  5757. var css = sourceMapOutput.toCSS(options);
  5758. this.sourceMap = sourceMapOutput.sourceMap;
  5759. this.sourceMapURL = sourceMapOutput.sourceMapURL;
  5760. if (this.options.sourceMapInputFilename) {
  5761. this.sourceMapInputFilename = sourceMapOutput.normalizeFilename(this.options.sourceMapInputFilename);
  5762. }
  5763. if (this.options.sourceMapBasepath !== undefined && this.sourceMapURL !== undefined) {
  5764. this.sourceMapURL = sourceMapOutput.removeBasepath(this.sourceMapURL);
  5765. }
  5766. return css + this.getCSSAppendage();
  5767. };
  5768. SourceMapBuilder.prototype.getCSSAppendage = function() {
  5769. var sourceMapURL = this.sourceMapURL;
  5770. if (this.options.sourceMapFileInline) {
  5771. if (this.sourceMap === undefined) {
  5772. return '';
  5773. }
  5774. sourceMapURL = 'data:application/json;base64,' + environment.encodeBase64(this.sourceMap);
  5775. }
  5776. if (sourceMapURL) {
  5777. return '/*# sourceMappingURL=' + sourceMapURL + ' */';
  5778. }
  5779. return '';
  5780. };
  5781. SourceMapBuilder.prototype.getExternalSourceMap = function() {
  5782. return this.sourceMap;
  5783. };
  5784. SourceMapBuilder.prototype.setExternalSourceMap = function(sourceMap) {
  5785. this.sourceMap = sourceMap;
  5786. };
  5787. SourceMapBuilder.prototype.isInline = function() {
  5788. return this.options.sourceMapFileInline;
  5789. };
  5790. SourceMapBuilder.prototype.getSourceMapURL = function() {
  5791. return this.sourceMapURL;
  5792. };
  5793. SourceMapBuilder.prototype.getOutputFilename = function() {
  5794. return this.options.sourceMapOutputFilename;
  5795. };
  5796. SourceMapBuilder.prototype.getInputFilename = function() {
  5797. return this.sourceMapInputFilename;
  5798. };
  5799. return SourceMapBuilder;
  5800. };
  5801. },{}],48:[function(require,module,exports){
  5802. module.exports = function (environment) {
  5803. var SourceMapOutput = function (options) {
  5804. this._css = [];
  5805. this._rootNode = options.rootNode;
  5806. this._contentsMap = options.contentsMap;
  5807. this._contentsIgnoredCharsMap = options.contentsIgnoredCharsMap;
  5808. if (options.sourceMapFilename) {
  5809. this._sourceMapFilename = options.sourceMapFilename.replace(/\\/g, '/');
  5810. }
  5811. this._outputFilename = options.outputFilename;
  5812. this.sourceMapURL = options.sourceMapURL;
  5813. if (options.sourceMapBasepath) {
  5814. this._sourceMapBasepath = options.sourceMapBasepath.replace(/\\/g, '/');
  5815. }
  5816. if (options.sourceMapRootpath) {
  5817. this._sourceMapRootpath = options.sourceMapRootpath.replace(/\\/g, '/');
  5818. if (this._sourceMapRootpath.charAt(this._sourceMapRootpath.length - 1) !== '/') {
  5819. this._sourceMapRootpath += '/';
  5820. }
  5821. } else {
  5822. this._sourceMapRootpath = '';
  5823. }
  5824. this._outputSourceFiles = options.outputSourceFiles;
  5825. this._sourceMapGeneratorConstructor = environment.getSourceMapGenerator();
  5826. this._lineNumber = 0;
  5827. this._column = 0;
  5828. };
  5829. SourceMapOutput.prototype.removeBasepath = function(path) {
  5830. if (this._sourceMapBasepath && path.indexOf(this._sourceMapBasepath) === 0) {
  5831. path = path.substring(this._sourceMapBasepath.length);
  5832. if (path.charAt(0) === '\\' || path.charAt(0) === '/') {
  5833. path = path.substring(1);
  5834. }
  5835. }
  5836. return path;
  5837. };
  5838. SourceMapOutput.prototype.normalizeFilename = function(filename) {
  5839. filename = filename.replace(/\\/g, '/');
  5840. filename = this.removeBasepath(filename);
  5841. return (this._sourceMapRootpath || '') + filename;
  5842. };
  5843. SourceMapOutput.prototype.add = function(chunk, fileInfo, index, mapLines) {
  5844. // ignore adding empty strings
  5845. if (!chunk) {
  5846. return;
  5847. }
  5848. var lines,
  5849. sourceLines,
  5850. columns,
  5851. sourceColumns,
  5852. i;
  5853. if (fileInfo && fileInfo.filename) {
  5854. var inputSource = this._contentsMap[fileInfo.filename];
  5855. // remove vars/banner added to the top of the file
  5856. if (this._contentsIgnoredCharsMap[fileInfo.filename]) {
  5857. // adjust the index
  5858. index -= this._contentsIgnoredCharsMap[fileInfo.filename];
  5859. if (index < 0) { index = 0; }
  5860. // adjust the source
  5861. inputSource = inputSource.slice(this._contentsIgnoredCharsMap[fileInfo.filename]);
  5862. }
  5863. inputSource = inputSource.substring(0, index);
  5864. sourceLines = inputSource.split('\n');
  5865. sourceColumns = sourceLines[sourceLines.length - 1];
  5866. }
  5867. lines = chunk.split('\n');
  5868. columns = lines[lines.length - 1];
  5869. if (fileInfo && fileInfo.filename) {
  5870. if (!mapLines) {
  5871. this._sourceMapGenerator.addMapping({ generated: { line: this._lineNumber + 1, column: this._column},
  5872. original: { line: sourceLines.length, column: sourceColumns.length},
  5873. source: this.normalizeFilename(fileInfo.filename)});
  5874. } else {
  5875. for (i = 0; i < lines.length; i++) {
  5876. this._sourceMapGenerator.addMapping({ generated: { line: this._lineNumber + i + 1, column: i === 0 ? this._column : 0},
  5877. original: { line: sourceLines.length + i, column: i === 0 ? sourceColumns.length : 0},
  5878. source: this.normalizeFilename(fileInfo.filename)});
  5879. }
  5880. }
  5881. }
  5882. if (lines.length === 1) {
  5883. this._column += columns.length;
  5884. } else {
  5885. this._lineNumber += lines.length - 1;
  5886. this._column = columns.length;
  5887. }
  5888. this._css.push(chunk);
  5889. };
  5890. SourceMapOutput.prototype.isEmpty = function() {
  5891. return this._css.length === 0;
  5892. };
  5893. SourceMapOutput.prototype.toCSS = function(context) {
  5894. this._sourceMapGenerator = new this._sourceMapGeneratorConstructor({ file: this._outputFilename, sourceRoot: null });
  5895. if (this._outputSourceFiles) {
  5896. for (var filename in this._contentsMap) {
  5897. if (this._contentsMap.hasOwnProperty(filename)) {
  5898. var source = this._contentsMap[filename];
  5899. if (this._contentsIgnoredCharsMap[filename]) {
  5900. source = source.slice(this._contentsIgnoredCharsMap[filename]);
  5901. }
  5902. this._sourceMapGenerator.setSourceContent(this.normalizeFilename(filename), source);
  5903. }
  5904. }
  5905. }
  5906. this._rootNode.genCSS(context, this);
  5907. if (this._css.length > 0) {
  5908. var sourceMapURL,
  5909. sourceMapContent = JSON.stringify(this._sourceMapGenerator.toJSON());
  5910. if (this.sourceMapURL) {
  5911. sourceMapURL = this.sourceMapURL;
  5912. } else if (this._sourceMapFilename) {
  5913. sourceMapURL = this._sourceMapFilename;
  5914. }
  5915. this.sourceMapURL = sourceMapURL;
  5916. this.sourceMap = sourceMapContent;
  5917. }
  5918. return this._css.join('');
  5919. };
  5920. return SourceMapOutput;
  5921. };
  5922. },{}],49:[function(require,module,exports){
  5923. var contexts = require('./contexts'),
  5924. visitor = require('./visitors'),
  5925. tree = require('./tree');
  5926. module.exports = function(root, options) {
  5927. options = options || {};
  5928. var evaldRoot,
  5929. variables = options.variables,
  5930. evalEnv = new contexts.Eval(options);
  5931. //
  5932. // Allows setting variables with a hash, so:
  5933. //
  5934. // `{ color: new tree.Color('#f01') }` will become:
  5935. //
  5936. // new tree.Declaration('@color',
  5937. // new tree.Value([
  5938. // new tree.Expression([
  5939. // new tree.Color('#f01')
  5940. // ])
  5941. // ])
  5942. // )
  5943. //
  5944. if (typeof variables === 'object' && !Array.isArray(variables)) {
  5945. variables = Object.keys(variables).map(function (k) {
  5946. var value = variables[k];
  5947. if (!(value instanceof tree.Value)) {
  5948. if (!(value instanceof tree.Expression)) {
  5949. value = new tree.Expression([value]);
  5950. }
  5951. value = new tree.Value([value]);
  5952. }
  5953. return new tree.Declaration('@' + k, value, false, null, 0);
  5954. });
  5955. evalEnv.frames = [new tree.Ruleset(null, variables)];
  5956. }
  5957. var visitors = [
  5958. new visitor.JoinSelectorVisitor(),
  5959. new visitor.MarkVisibleSelectorsVisitor(true),
  5960. new visitor.ExtendVisitor(),
  5961. new visitor.ToCSSVisitor({compress: Boolean(options.compress)})
  5962. ], preEvalVisitors = [], v, visitorIterator;
  5963. /**
  5964. * first() / get() allows visitors to be added while visiting
  5965. *
  5966. * @todo Add scoping for visitors just like functions for @plugin; right now they're global
  5967. */
  5968. if (options.pluginManager) {
  5969. visitorIterator = options.pluginManager.visitor();
  5970. for (var i = 0; i < 2; i++) {
  5971. visitorIterator.first();
  5972. while ((v = visitorIterator.get())) {
  5973. if (v.isPreEvalVisitor) {
  5974. if (i === 0 || preEvalVisitors.indexOf(v) === -1) {
  5975. preEvalVisitors.push(v);
  5976. v.run(root);
  5977. }
  5978. }
  5979. else {
  5980. if (i === 0 || visitors.indexOf(v) === -1) {
  5981. if (v.isPreVisitor) {
  5982. visitors.unshift(v);
  5983. }
  5984. else {
  5985. visitors.push(v);
  5986. }
  5987. }
  5988. }
  5989. }
  5990. }
  5991. }
  5992. evaldRoot = root.eval(evalEnv);
  5993. for (var i = 0; i < visitors.length; i++) {
  5994. visitors[i].run(evaldRoot);
  5995. }
  5996. // Run any remaining visitors added after eval pass
  5997. if (options.pluginManager) {
  5998. visitorIterator.first();
  5999. while ((v = visitorIterator.get())) {
  6000. if (visitors.indexOf(v) === -1 && preEvalVisitors.indexOf(v) === -1) {
  6001. v.run(evaldRoot);
  6002. }
  6003. }
  6004. }
  6005. return evaldRoot;
  6006. };
  6007. },{"./contexts":13,"./tree":67,"./visitors":93}],50:[function(require,module,exports){
  6008. var Node = require('./node');
  6009. var Anonymous = function (value, index, currentFileInfo, mapLines, rulesetLike, visibilityInfo) {
  6010. this.value = value;
  6011. this._index = index;
  6012. this._fileInfo = currentFileInfo;
  6013. this.mapLines = mapLines;
  6014. this.rulesetLike = (typeof rulesetLike === 'undefined') ? false : rulesetLike;
  6015. this.allowRoot = true;
  6016. this.copyVisibilityInfo(visibilityInfo);
  6017. };
  6018. Anonymous.prototype = new Node();
  6019. Anonymous.prototype.type = 'Anonymous';
  6020. Anonymous.prototype.eval = function () {
  6021. return new Anonymous(this.value, this._index, this._fileInfo, this.mapLines, this.rulesetLike, this.visibilityInfo());
  6022. };
  6023. Anonymous.prototype.compare = function (other) {
  6024. return other.toCSS && this.toCSS() === other.toCSS() ? 0 : undefined;
  6025. };
  6026. Anonymous.prototype.isRulesetLike = function() {
  6027. return this.rulesetLike;
  6028. };
  6029. Anonymous.prototype.genCSS = function (context, output) {
  6030. this.nodeVisible = Boolean(this.value);
  6031. if (this.nodeVisible) {
  6032. output.add(this.value, this._fileInfo, this._index, this.mapLines);
  6033. }
  6034. };
  6035. module.exports = Anonymous;
  6036. },{"./node":76}],51:[function(require,module,exports){
  6037. var Node = require('./node');
  6038. var Assignment = function (key, val) {
  6039. this.key = key;
  6040. this.value = val;
  6041. };
  6042. Assignment.prototype = new Node();
  6043. Assignment.prototype.type = 'Assignment';
  6044. Assignment.prototype.accept = function (visitor) {
  6045. this.value = visitor.visit(this.value);
  6046. };
  6047. Assignment.prototype.eval = function (context) {
  6048. if (this.value.eval) {
  6049. return new Assignment(this.key, this.value.eval(context));
  6050. }
  6051. return this;
  6052. };
  6053. Assignment.prototype.genCSS = function (context, output) {
  6054. output.add(this.key + '=');
  6055. if (this.value.genCSS) {
  6056. this.value.genCSS(context, output);
  6057. } else {
  6058. output.add(this.value);
  6059. }
  6060. };
  6061. module.exports = Assignment;
  6062. },{"./node":76}],52:[function(require,module,exports){
  6063. var Node = require('./node'),
  6064. Selector = require('./selector'),
  6065. Ruleset = require('./ruleset'),
  6066. Anonymous = require('./anonymous');
  6067. var AtRule = function (name, value, rules, index, currentFileInfo, debugInfo, isRooted, visibilityInfo) {
  6068. var i;
  6069. this.name = name;
  6070. this.value = (value instanceof Node) ? value : (value ? new Anonymous(value) : value);
  6071. if (rules) {
  6072. if (Array.isArray(rules)) {
  6073. this.rules = rules;
  6074. } else {
  6075. this.rules = [rules];
  6076. this.rules[0].selectors = (new Selector([], null, null, index, currentFileInfo)).createEmptySelectors();
  6077. }
  6078. for (i = 0; i < this.rules.length; i++) {
  6079. this.rules[i].allowImports = true;
  6080. }
  6081. this.setParent(this.rules, this);
  6082. }
  6083. this._index = index;
  6084. this._fileInfo = currentFileInfo;
  6085. this.debugInfo = debugInfo;
  6086. this.isRooted = isRooted || false;
  6087. this.copyVisibilityInfo(visibilityInfo);
  6088. this.allowRoot = true;
  6089. };
  6090. AtRule.prototype = new Node();
  6091. AtRule.prototype.type = 'AtRule';
  6092. AtRule.prototype.accept = function (visitor) {
  6093. var value = this.value, rules = this.rules;
  6094. if (rules) {
  6095. this.rules = visitor.visitArray(rules);
  6096. }
  6097. if (value) {
  6098. this.value = visitor.visit(value);
  6099. }
  6100. };
  6101. AtRule.prototype.isRulesetLike = function() {
  6102. return this.rules || !this.isCharset();
  6103. };
  6104. AtRule.prototype.isCharset = function() {
  6105. return '@charset' === this.name;
  6106. };
  6107. AtRule.prototype.genCSS = function (context, output) {
  6108. var value = this.value, rules = this.rules;
  6109. output.add(this.name, this.fileInfo(), this.getIndex());
  6110. if (value) {
  6111. output.add(' ');
  6112. value.genCSS(context, output);
  6113. }
  6114. if (rules) {
  6115. this.outputRuleset(context, output, rules);
  6116. } else {
  6117. output.add(';');
  6118. }
  6119. };
  6120. AtRule.prototype.eval = function (context) {
  6121. var mediaPathBackup, mediaBlocksBackup, value = this.value, rules = this.rules;
  6122. // media stored inside other atrule should not bubble over it
  6123. // backpup media bubbling information
  6124. mediaPathBackup = context.mediaPath;
  6125. mediaBlocksBackup = context.mediaBlocks;
  6126. // deleted media bubbling information
  6127. context.mediaPath = [];
  6128. context.mediaBlocks = [];
  6129. if (value) {
  6130. value = value.eval(context);
  6131. }
  6132. if (rules) {
  6133. // assuming that there is only one rule at this point - that is how parser constructs the rule
  6134. rules = [rules[0].eval(context)];
  6135. rules[0].root = true;
  6136. }
  6137. // restore media bubbling information
  6138. context.mediaPath = mediaPathBackup;
  6139. context.mediaBlocks = mediaBlocksBackup;
  6140. return new AtRule(this.name, value, rules,
  6141. this.getIndex(), this.fileInfo(), this.debugInfo, this.isRooted, this.visibilityInfo());
  6142. };
  6143. AtRule.prototype.variable = function (name) {
  6144. if (this.rules) {
  6145. // assuming that there is only one rule at this point - that is how parser constructs the rule
  6146. return Ruleset.prototype.variable.call(this.rules[0], name);
  6147. }
  6148. };
  6149. AtRule.prototype.find = function () {
  6150. if (this.rules) {
  6151. // assuming that there is only one rule at this point - that is how parser constructs the rule
  6152. return Ruleset.prototype.find.apply(this.rules[0], arguments);
  6153. }
  6154. };
  6155. AtRule.prototype.rulesets = function () {
  6156. if (this.rules) {
  6157. // assuming that there is only one rule at this point - that is how parser constructs the rule
  6158. return Ruleset.prototype.rulesets.apply(this.rules[0]);
  6159. }
  6160. };
  6161. AtRule.prototype.outputRuleset = function (context, output, rules) {
  6162. var ruleCnt = rules.length, i;
  6163. context.tabLevel = (context.tabLevel | 0) + 1;
  6164. // Compressed
  6165. if (context.compress) {
  6166. output.add('{');
  6167. for (i = 0; i < ruleCnt; i++) {
  6168. rules[i].genCSS(context, output);
  6169. }
  6170. output.add('}');
  6171. context.tabLevel--;
  6172. return;
  6173. }
  6174. // Non-compressed
  6175. var tabSetStr = '\n' + Array(context.tabLevel).join(' '), tabRuleStr = tabSetStr + ' ';
  6176. if (!ruleCnt) {
  6177. output.add(' {' + tabSetStr + '}');
  6178. } else {
  6179. output.add(' {' + tabRuleStr);
  6180. rules[0].genCSS(context, output);
  6181. for (i = 1; i < ruleCnt; i++) {
  6182. output.add(tabRuleStr);
  6183. rules[i].genCSS(context, output);
  6184. }
  6185. output.add(tabSetStr + '}');
  6186. }
  6187. context.tabLevel--;
  6188. };
  6189. module.exports = AtRule;
  6190. },{"./anonymous":50,"./node":76,"./ruleset":81,"./selector":82}],53:[function(require,module,exports){
  6191. var Node = require('./node');
  6192. var Attribute = function (key, op, value) {
  6193. this.key = key;
  6194. this.op = op;
  6195. this.value = value;
  6196. };
  6197. Attribute.prototype = new Node();
  6198. Attribute.prototype.type = 'Attribute';
  6199. Attribute.prototype.eval = function (context) {
  6200. return new Attribute(this.key.eval ? this.key.eval(context) : this.key,
  6201. this.op, (this.value && this.value.eval) ? this.value.eval(context) : this.value);
  6202. };
  6203. Attribute.prototype.genCSS = function (context, output) {
  6204. output.add(this.toCSS(context));
  6205. };
  6206. Attribute.prototype.toCSS = function (context) {
  6207. var value = this.key.toCSS ? this.key.toCSS(context) : this.key;
  6208. if (this.op) {
  6209. value += this.op;
  6210. value += (this.value.toCSS ? this.value.toCSS(context) : this.value);
  6211. }
  6212. return '[' + value + ']';
  6213. };
  6214. module.exports = Attribute;
  6215. },{"./node":76}],54:[function(require,module,exports){
  6216. var Node = require('./node'),
  6217. Anonymous = require('./anonymous'),
  6218. FunctionCaller = require('../functions/function-caller');
  6219. //
  6220. // A function call node.
  6221. //
  6222. var Call = function (name, args, index, currentFileInfo) {
  6223. this.name = name;
  6224. this.args = args;
  6225. this.calc = name === 'calc';
  6226. this._index = index;
  6227. this._fileInfo = currentFileInfo;
  6228. };
  6229. Call.prototype = new Node();
  6230. Call.prototype.type = 'Call';
  6231. Call.prototype.accept = function (visitor) {
  6232. if (this.args) {
  6233. this.args = visitor.visitArray(this.args);
  6234. }
  6235. };
  6236. //
  6237. // When evaluating a function call,
  6238. // we either find the function in the functionRegistry,
  6239. // in which case we call it, passing the evaluated arguments,
  6240. // if this returns null or we cannot find the function, we
  6241. // simply print it out as it appeared originally [2].
  6242. //
  6243. // The reason why we evaluate the arguments, is in the case where
  6244. // we try to pass a variable to a function, like: `saturate(@color)`.
  6245. // The function should receive the value, not the variable.
  6246. //
  6247. Call.prototype.eval = function (context) {
  6248. /**
  6249. * Turn off math for calc(), and switch back on for evaluating nested functions
  6250. */
  6251. var currentMathContext = context.mathOn;
  6252. context.mathOn = !this.calc;
  6253. if (this.calc || context.inCalc) {
  6254. context.enterCalc();
  6255. }
  6256. var args = this.args.map(function (a) { return a.eval(context); });
  6257. if (this.calc || context.inCalc) {
  6258. context.exitCalc();
  6259. }
  6260. context.mathOn = currentMathContext;
  6261. var result, funcCaller = new FunctionCaller(this.name, context, this.getIndex(), this.fileInfo());
  6262. if (funcCaller.isValid()) {
  6263. try {
  6264. result = funcCaller.call(args);
  6265. } catch (e) {
  6266. throw {
  6267. type: e.type || 'Runtime',
  6268. message: 'error evaluating function `' + this.name + '`' +
  6269. (e.message ? ': ' + e.message : ''),
  6270. index: this.getIndex(),
  6271. filename: this.fileInfo().filename,
  6272. line: e.lineNumber,
  6273. column: e.columnNumber
  6274. };
  6275. }
  6276. if (result !== null && result !== undefined) {
  6277. // Results that that are not nodes are cast as Anonymous nodes
  6278. // Falsy values or booleans are returned as empty nodes
  6279. if (!(result instanceof Node)) {
  6280. if (!result || result === true) {
  6281. result = new Anonymous(null);
  6282. }
  6283. else {
  6284. result = new Anonymous(result.toString());
  6285. }
  6286. }
  6287. result._index = this._index;
  6288. result._fileInfo = this._fileInfo;
  6289. return result;
  6290. }
  6291. }
  6292. return new Call(this.name, args, this.getIndex(), this.fileInfo());
  6293. };
  6294. Call.prototype.genCSS = function (context, output) {
  6295. output.add(this.name + '(', this.fileInfo(), this.getIndex());
  6296. for (var i = 0; i < this.args.length; i++) {
  6297. this.args[i].genCSS(context, output);
  6298. if (i + 1 < this.args.length) {
  6299. output.add(', ');
  6300. }
  6301. }
  6302. output.add(')');
  6303. };
  6304. module.exports = Call;
  6305. },{"../functions/function-caller":26,"./anonymous":50,"./node":76}],55:[function(require,module,exports){
  6306. var Node = require('./node'),
  6307. colors = require('../data/colors');
  6308. //
  6309. // RGB Colors - #ff0014, #eee
  6310. //
  6311. var Color = function (rgb, a, originalForm) {
  6312. var self = this;
  6313. //
  6314. // The end goal here, is to parse the arguments
  6315. // into an integer triplet, such as `128, 255, 0`
  6316. //
  6317. // This facilitates operations and conversions.
  6318. //
  6319. if (Array.isArray(rgb)) {
  6320. this.rgb = rgb;
  6321. } else if (rgb.length >= 6) {
  6322. this.rgb = [];
  6323. rgb.match(/.{2}/g).map(function (c, i) {
  6324. if (i < 3) {
  6325. self.rgb.push(parseInt(c, 16));
  6326. } else {
  6327. self.alpha = (parseInt(c, 16)) / 255;
  6328. }
  6329. });
  6330. } else {
  6331. this.rgb = [];
  6332. rgb.split('').map(function (c, i) {
  6333. if (i < 3) {
  6334. self.rgb.push(parseInt(c + c, 16));
  6335. } else {
  6336. self.alpha = (parseInt(c + c, 16)) / 255;
  6337. }
  6338. });
  6339. }
  6340. this.alpha = this.alpha || (typeof a === 'number' ? a : 1);
  6341. if (typeof originalForm !== 'undefined') {
  6342. this.value = originalForm;
  6343. }
  6344. };
  6345. Color.prototype = new Node();
  6346. Color.prototype.type = 'Color';
  6347. function clamp(v, max) {
  6348. return Math.min(Math.max(v, 0), max);
  6349. }
  6350. function toHex(v) {
  6351. return '#' + v.map(function (c) {
  6352. c = clamp(Math.round(c), 255);
  6353. return (c < 16 ? '0' : '') + c.toString(16);
  6354. }).join('');
  6355. }
  6356. Color.prototype.luma = function () {
  6357. var r = this.rgb[0] / 255,
  6358. g = this.rgb[1] / 255,
  6359. b = this.rgb[2] / 255;
  6360. r = (r <= 0.03928) ? r / 12.92 : Math.pow(((r + 0.055) / 1.055), 2.4);
  6361. g = (g <= 0.03928) ? g / 12.92 : Math.pow(((g + 0.055) / 1.055), 2.4);
  6362. b = (b <= 0.03928) ? b / 12.92 : Math.pow(((b + 0.055) / 1.055), 2.4);
  6363. return 0.2126 * r + 0.7152 * g + 0.0722 * b;
  6364. };
  6365. Color.prototype.genCSS = function (context, output) {
  6366. output.add(this.toCSS(context));
  6367. };
  6368. Color.prototype.toCSS = function (context, doNotCompress) {
  6369. var compress = context && context.compress && !doNotCompress, color, alpha,
  6370. colorFunction, args = [];
  6371. // `value` is set if this color was originally
  6372. // converted from a named color string so we need
  6373. // to respect this and try to output named color too.
  6374. alpha = this.fround(context, this.alpha);
  6375. if (this.value) {
  6376. if (this.value.indexOf('rgb') === 0) {
  6377. if (alpha < 1) {
  6378. colorFunction = 'rgba';
  6379. }
  6380. } else if (this.value.indexOf('hsl') === 0) {
  6381. if (alpha < 1) {
  6382. colorFunction = 'hsla';
  6383. } else {
  6384. colorFunction = 'hsl';
  6385. }
  6386. } else {
  6387. return this.value;
  6388. }
  6389. } else {
  6390. if (alpha < 1) {
  6391. colorFunction = 'rgba';
  6392. }
  6393. }
  6394. switch (colorFunction) {
  6395. case 'rgba':
  6396. args = this.rgb.map(function (c) {
  6397. return clamp(Math.round(c), 255);
  6398. }).concat(clamp(alpha, 1));
  6399. break;
  6400. case 'hsla':
  6401. args.push(clamp(alpha, 1));
  6402. case 'hsl':
  6403. color = this.toHSL();
  6404. args = [
  6405. this.fround(context, color.h),
  6406. this.fround(context, color.s * 100) + '%',
  6407. this.fround(context, color.l * 100) + '%'
  6408. ].concat(args);
  6409. }
  6410. if (colorFunction) {
  6411. // Values are capped between `0` and `255`, rounded and zero-padded.
  6412. return colorFunction + '(' + args.join(',' + (compress ? '' : ' ')) + ')';
  6413. }
  6414. color = this.toRGB();
  6415. if (compress) {
  6416. var splitcolor = color.split('');
  6417. // Convert color to short format
  6418. if (splitcolor[1] === splitcolor[2] && splitcolor[3] === splitcolor[4] && splitcolor[5] === splitcolor[6]) {
  6419. color = '#' + splitcolor[1] + splitcolor[3] + splitcolor[5];
  6420. }
  6421. }
  6422. return color;
  6423. };
  6424. //
  6425. // Operations have to be done per-channel, if not,
  6426. // channels will spill onto each other. Once we have
  6427. // our result, in the form of an integer triplet,
  6428. // we create a new Color node to hold the result.
  6429. //
  6430. Color.prototype.operate = function (context, op, other) {
  6431. var rgb = new Array(3);
  6432. var alpha = this.alpha * (1 - other.alpha) + other.alpha;
  6433. for (var c = 0; c < 3; c++) {
  6434. rgb[c] = this._operate(context, op, this.rgb[c], other.rgb[c]);
  6435. }
  6436. return new Color(rgb, alpha);
  6437. };
  6438. Color.prototype.toRGB = function () {
  6439. return toHex(this.rgb);
  6440. };
  6441. Color.prototype.toHSL = function () {
  6442. var r = this.rgb[0] / 255,
  6443. g = this.rgb[1] / 255,
  6444. b = this.rgb[2] / 255,
  6445. a = this.alpha;
  6446. var max = Math.max(r, g, b), min = Math.min(r, g, b);
  6447. var h, s, l = (max + min) / 2, d = max - min;
  6448. if (max === min) {
  6449. h = s = 0;
  6450. } else {
  6451. s = l > 0.5 ? d / (2 - max - min) : d / (max + min);
  6452. switch (max) {
  6453. case r: h = (g - b) / d + (g < b ? 6 : 0); break;
  6454. case g: h = (b - r) / d + 2; break;
  6455. case b: h = (r - g) / d + 4; break;
  6456. }
  6457. h /= 6;
  6458. }
  6459. return { h: h * 360, s: s, l: l, a: a };
  6460. };
  6461. // Adapted from http://mjijackson.com/2008/02/rgb-to-hsl-and-rgb-to-hsv-color-model-conversion-algorithms-in-javascript
  6462. Color.prototype.toHSV = function () {
  6463. var r = this.rgb[0] / 255,
  6464. g = this.rgb[1] / 255,
  6465. b = this.rgb[2] / 255,
  6466. a = this.alpha;
  6467. var max = Math.max(r, g, b), min = Math.min(r, g, b);
  6468. var h, s, v = max;
  6469. var d = max - min;
  6470. if (max === 0) {
  6471. s = 0;
  6472. } else {
  6473. s = d / max;
  6474. }
  6475. if (max === min) {
  6476. h = 0;
  6477. } else {
  6478. switch (max) {
  6479. case r: h = (g - b) / d + (g < b ? 6 : 0); break;
  6480. case g: h = (b - r) / d + 2; break;
  6481. case b: h = (r - g) / d + 4; break;
  6482. }
  6483. h /= 6;
  6484. }
  6485. return { h: h * 360, s: s, v: v, a: a };
  6486. };
  6487. Color.prototype.toARGB = function () {
  6488. return toHex([this.alpha * 255].concat(this.rgb));
  6489. };
  6490. Color.prototype.compare = function (x) {
  6491. return (x.rgb &&
  6492. x.rgb[0] === this.rgb[0] &&
  6493. x.rgb[1] === this.rgb[1] &&
  6494. x.rgb[2] === this.rgb[2] &&
  6495. x.alpha === this.alpha) ? 0 : undefined;
  6496. };
  6497. Color.fromKeyword = function(keyword) {
  6498. var c, key = keyword.toLowerCase();
  6499. if (colors.hasOwnProperty(key)) {
  6500. c = new Color(colors[key].slice(1));
  6501. }
  6502. else if (key === 'transparent') {
  6503. c = new Color([0, 0, 0], 0);
  6504. }
  6505. if (c) {
  6506. c.value = keyword;
  6507. return c;
  6508. }
  6509. };
  6510. module.exports = Color;
  6511. },{"../data/colors":14,"./node":76}],56:[function(require,module,exports){
  6512. var Node = require('./node');
  6513. var Combinator = function (value) {
  6514. if (value === ' ') {
  6515. this.value = ' ';
  6516. this.emptyOrWhitespace = true;
  6517. } else {
  6518. this.value = value ? value.trim() : '';
  6519. this.emptyOrWhitespace = this.value === '';
  6520. }
  6521. };
  6522. Combinator.prototype = new Node();
  6523. Combinator.prototype.type = 'Combinator';
  6524. var _noSpaceCombinators = {
  6525. '': true,
  6526. ' ': true,
  6527. '|': true
  6528. };
  6529. Combinator.prototype.genCSS = function (context, output) {
  6530. var spaceOrEmpty = (context.compress || _noSpaceCombinators[this.value]) ? '' : ' ';
  6531. output.add(spaceOrEmpty + this.value + spaceOrEmpty);
  6532. };
  6533. module.exports = Combinator;
  6534. },{"./node":76}],57:[function(require,module,exports){
  6535. var Node = require('./node'),
  6536. getDebugInfo = require('./debug-info');
  6537. var Comment = function (value, isLineComment, index, currentFileInfo) {
  6538. this.value = value;
  6539. this.isLineComment = isLineComment;
  6540. this._index = index;
  6541. this._fileInfo = currentFileInfo;
  6542. this.allowRoot = true;
  6543. };
  6544. Comment.prototype = new Node();
  6545. Comment.prototype.type = 'Comment';
  6546. Comment.prototype.genCSS = function (context, output) {
  6547. if (this.debugInfo) {
  6548. output.add(getDebugInfo(context, this), this.fileInfo(), this.getIndex());
  6549. }
  6550. output.add(this.value);
  6551. };
  6552. Comment.prototype.isSilent = function(context) {
  6553. var isCompressed = context.compress && this.value[2] !== '!';
  6554. return this.isLineComment || isCompressed;
  6555. };
  6556. module.exports = Comment;
  6557. },{"./debug-info":59,"./node":76}],58:[function(require,module,exports){
  6558. var Node = require('./node');
  6559. var Condition = function (op, l, r, i, negate) {
  6560. this.op = op.trim();
  6561. this.lvalue = l;
  6562. this.rvalue = r;
  6563. this._index = i;
  6564. this.negate = negate;
  6565. };
  6566. Condition.prototype = new Node();
  6567. Condition.prototype.type = 'Condition';
  6568. Condition.prototype.accept = function (visitor) {
  6569. this.lvalue = visitor.visit(this.lvalue);
  6570. this.rvalue = visitor.visit(this.rvalue);
  6571. };
  6572. Condition.prototype.eval = function (context) {
  6573. var result = (function (op, a, b) {
  6574. switch (op) {
  6575. case 'and': return a && b;
  6576. case 'or': return a || b;
  6577. default:
  6578. switch (Node.compare(a, b)) {
  6579. case -1:
  6580. return op === '<' || op === '=<' || op === '<=';
  6581. case 0:
  6582. return op === '=' || op === '>=' || op === '=<' || op === '<=';
  6583. case 1:
  6584. return op === '>' || op === '>=';
  6585. default:
  6586. return false;
  6587. }
  6588. }
  6589. })(this.op, this.lvalue.eval(context), this.rvalue.eval(context));
  6590. return this.negate ? !result : result;
  6591. };
  6592. module.exports = Condition;
  6593. },{"./node":76}],59:[function(require,module,exports){
  6594. var debugInfo = function(context, ctx, lineSeparator) {
  6595. var result = '';
  6596. if (context.dumpLineNumbers && !context.compress) {
  6597. switch (context.dumpLineNumbers) {
  6598. case 'comments':
  6599. result = debugInfo.asComment(ctx);
  6600. break;
  6601. case 'mediaquery':
  6602. result = debugInfo.asMediaQuery(ctx);
  6603. break;
  6604. case 'all':
  6605. result = debugInfo.asComment(ctx) + (lineSeparator || '') + debugInfo.asMediaQuery(ctx);
  6606. break;
  6607. }
  6608. }
  6609. return result;
  6610. };
  6611. debugInfo.asComment = function(ctx) {
  6612. return '/* line ' + ctx.debugInfo.lineNumber + ', ' + ctx.debugInfo.fileName + ' */\n';
  6613. };
  6614. debugInfo.asMediaQuery = function(ctx) {
  6615. var filenameWithProtocol = ctx.debugInfo.fileName;
  6616. if (!/^[a-z]+:\/\//i.test(filenameWithProtocol)) {
  6617. filenameWithProtocol = 'file://' + filenameWithProtocol;
  6618. }
  6619. return '@media -sass-debug-info{filename{font-family:' +
  6620. filenameWithProtocol.replace(/([.:\/\\])/g, function (a) {
  6621. if (a == '\\') {
  6622. a = '\/';
  6623. }
  6624. return '\\' + a;
  6625. }) +
  6626. '}line{font-family:\\00003' + ctx.debugInfo.lineNumber + '}}\n';
  6627. };
  6628. module.exports = debugInfo;
  6629. },{}],60:[function(require,module,exports){
  6630. var Node = require('./node'),
  6631. Value = require('./value'),
  6632. Keyword = require('./keyword'),
  6633. Anonymous = require('./anonymous'),
  6634. MATH = require('../constants').Math;
  6635. var Declaration = function (name, value, important, merge, index, currentFileInfo, inline, variable) {
  6636. this.name = name;
  6637. this.value = (value instanceof Node) ? value : new Value([value ? new Anonymous(value) : null]);
  6638. this.important = important ? ' ' + important.trim() : '';
  6639. this.merge = merge;
  6640. this._index = index;
  6641. this._fileInfo = currentFileInfo;
  6642. this.inline = inline || false;
  6643. this.variable = (variable !== undefined) ? variable
  6644. : (name.charAt && (name.charAt(0) === '@'));
  6645. this.allowRoot = true;
  6646. this.setParent(this.value, this);
  6647. };
  6648. function evalName(context, name) {
  6649. var value = '', i, n = name.length,
  6650. output = {add: function (s) {value += s;}};
  6651. for (i = 0; i < n; i++) {
  6652. name[i].eval(context).genCSS(context, output);
  6653. }
  6654. return value;
  6655. }
  6656. Declaration.prototype = new Node();
  6657. Declaration.prototype.type = 'Declaration';
  6658. Declaration.prototype.genCSS = function (context, output) {
  6659. output.add(this.name + (context.compress ? ':' : ': '), this.fileInfo(), this.getIndex());
  6660. try {
  6661. this.value.genCSS(context, output);
  6662. }
  6663. catch (e) {
  6664. e.index = this._index;
  6665. e.filename = this._fileInfo.filename;
  6666. throw e;
  6667. }
  6668. output.add(this.important + ((this.inline || (context.lastRule && context.compress)) ? '' : ';'), this._fileInfo, this._index);
  6669. };
  6670. Declaration.prototype.eval = function (context) {
  6671. var mathBypass = false, prevMath, name = this.name, evaldValue, variable = this.variable;
  6672. if (typeof name !== 'string') {
  6673. // expand 'primitive' name directly to get
  6674. // things faster (~10% for benchmark.less):
  6675. name = (name.length === 1) && (name[0] instanceof Keyword) ?
  6676. name[0].value : evalName(context, name);
  6677. variable = false; // never treat expanded interpolation as new variable name
  6678. }
  6679. // @todo remove when parens-division is default
  6680. if (name === 'font' && context.math === MATH.ALWAYS) {
  6681. mathBypass = true;
  6682. prevMath = context.math;
  6683. context.math = MATH.PARENS_DIVISION;
  6684. }
  6685. try {
  6686. context.importantScope.push({});
  6687. evaldValue = this.value.eval(context);
  6688. if (!this.variable && evaldValue.type === 'DetachedRuleset') {
  6689. throw { message: 'Rulesets cannot be evaluated on a property.',
  6690. index: this.getIndex(), filename: this.fileInfo().filename };
  6691. }
  6692. var important = this.important,
  6693. importantResult = context.importantScope.pop();
  6694. if (!important && importantResult.important) {
  6695. important = importantResult.important;
  6696. }
  6697. return new Declaration(name,
  6698. evaldValue,
  6699. important,
  6700. this.merge,
  6701. this.getIndex(), this.fileInfo(), this.inline,
  6702. variable);
  6703. }
  6704. catch (e) {
  6705. if (typeof e.index !== 'number') {
  6706. e.index = this.getIndex();
  6707. e.filename = this.fileInfo().filename;
  6708. }
  6709. throw e;
  6710. }
  6711. finally {
  6712. if (mathBypass) {
  6713. context.math = prevMath;
  6714. }
  6715. }
  6716. };
  6717. Declaration.prototype.makeImportant = function () {
  6718. return new Declaration(this.name,
  6719. this.value,
  6720. '!important',
  6721. this.merge,
  6722. this.getIndex(), this.fileInfo(), this.inline);
  6723. };
  6724. module.exports = Declaration;
  6725. },{"../constants":12,"./anonymous":50,"./keyword":70,"./node":76,"./value":86}],61:[function(require,module,exports){
  6726. var Node = require('./node'),
  6727. contexts = require('../contexts'),
  6728. utils = require('../utils');
  6729. var DetachedRuleset = function (ruleset, frames) {
  6730. this.ruleset = ruleset;
  6731. this.frames = frames;
  6732. this.setParent(this.ruleset, this);
  6733. };
  6734. DetachedRuleset.prototype = new Node();
  6735. DetachedRuleset.prototype.type = 'DetachedRuleset';
  6736. DetachedRuleset.prototype.evalFirst = true;
  6737. DetachedRuleset.prototype.accept = function (visitor) {
  6738. this.ruleset = visitor.visit(this.ruleset);
  6739. };
  6740. DetachedRuleset.prototype.eval = function (context) {
  6741. var frames = this.frames || utils.copyArray(context.frames);
  6742. return new DetachedRuleset(this.ruleset, frames);
  6743. };
  6744. DetachedRuleset.prototype.callEval = function (context) {
  6745. return this.ruleset.eval(this.frames ? new contexts.Eval(context, this.frames.concat(context.frames)) : context);
  6746. };
  6747. module.exports = DetachedRuleset;
  6748. },{"../contexts":13,"../utils":89,"./node":76}],62:[function(require,module,exports){
  6749. var Node = require('./node'),
  6750. unitConversions = require('../data/unit-conversions'),
  6751. Unit = require('./unit'),
  6752. Color = require('./color');
  6753. //
  6754. // A number with a unit
  6755. //
  6756. var Dimension = function (value, unit) {
  6757. this.value = parseFloat(value);
  6758. if (isNaN(this.value)) {
  6759. throw new Error('Dimension is not a number.');
  6760. }
  6761. this.unit = (unit && unit instanceof Unit) ? unit :
  6762. new Unit(unit ? [unit] : undefined);
  6763. this.setParent(this.unit, this);
  6764. };
  6765. Dimension.prototype = new Node();
  6766. Dimension.prototype.type = 'Dimension';
  6767. Dimension.prototype.accept = function (visitor) {
  6768. this.unit = visitor.visit(this.unit);
  6769. };
  6770. Dimension.prototype.eval = function (context) {
  6771. return this;
  6772. };
  6773. Dimension.prototype.toColor = function () {
  6774. return new Color([this.value, this.value, this.value]);
  6775. };
  6776. Dimension.prototype.genCSS = function (context, output) {
  6777. if ((context && context.strictUnits) && !this.unit.isSingular()) {
  6778. throw new Error('Multiple units in dimension. Correct the units or use the unit function. Bad unit: ' + this.unit.toString());
  6779. }
  6780. var value = this.fround(context, this.value),
  6781. strValue = String(value);
  6782. if (value !== 0 && value < 0.000001 && value > -0.000001) {
  6783. // would be output 1e-6 etc.
  6784. strValue = value.toFixed(20).replace(/0+$/, '');
  6785. }
  6786. if (context && context.compress) {
  6787. // Zero values doesn't need a unit
  6788. if (value === 0 && this.unit.isLength()) {
  6789. output.add(strValue);
  6790. return;
  6791. }
  6792. // Float values doesn't need a leading zero
  6793. if (value > 0 && value < 1) {
  6794. strValue = (strValue).substr(1);
  6795. }
  6796. }
  6797. output.add(strValue);
  6798. this.unit.genCSS(context, output);
  6799. };
  6800. // In an operation between two Dimensions,
  6801. // we default to the first Dimension's unit,
  6802. // so `1px + 2` will yield `3px`.
  6803. Dimension.prototype.operate = function (context, op, other) {
  6804. /* jshint noempty:false */
  6805. var value = this._operate(context, op, this.value, other.value),
  6806. unit = this.unit.clone();
  6807. if (op === '+' || op === '-') {
  6808. if (unit.numerator.length === 0 && unit.denominator.length === 0) {
  6809. unit = other.unit.clone();
  6810. if (this.unit.backupUnit) {
  6811. unit.backupUnit = this.unit.backupUnit;
  6812. }
  6813. } else if (other.unit.numerator.length === 0 && unit.denominator.length === 0) {
  6814. // do nothing
  6815. } else {
  6816. other = other.convertTo(this.unit.usedUnits());
  6817. if (context.strictUnits && other.unit.toString() !== unit.toString()) {
  6818. throw new Error('Incompatible units. Change the units or use the unit function. Bad units: \'' + unit.toString() +
  6819. '\' and \'' + other.unit.toString() + '\'.');
  6820. }
  6821. value = this._operate(context, op, this.value, other.value);
  6822. }
  6823. } else if (op === '*') {
  6824. unit.numerator = unit.numerator.concat(other.unit.numerator).sort();
  6825. unit.denominator = unit.denominator.concat(other.unit.denominator).sort();
  6826. unit.cancel();
  6827. } else if (op === '/') {
  6828. unit.numerator = unit.numerator.concat(other.unit.denominator).sort();
  6829. unit.denominator = unit.denominator.concat(other.unit.numerator).sort();
  6830. unit.cancel();
  6831. }
  6832. return new Dimension(value, unit);
  6833. };
  6834. Dimension.prototype.compare = function (other) {
  6835. var a, b;
  6836. if (!(other instanceof Dimension)) {
  6837. return undefined;
  6838. }
  6839. if (this.unit.isEmpty() || other.unit.isEmpty()) {
  6840. a = this;
  6841. b = other;
  6842. } else {
  6843. a = this.unify();
  6844. b = other.unify();
  6845. if (a.unit.compare(b.unit) !== 0) {
  6846. return undefined;
  6847. }
  6848. }
  6849. return Node.numericCompare(a.value, b.value);
  6850. };
  6851. Dimension.prototype.unify = function () {
  6852. return this.convertTo({ length: 'px', duration: 's', angle: 'rad' });
  6853. };
  6854. Dimension.prototype.convertTo = function (conversions) {
  6855. var value = this.value, unit = this.unit.clone(),
  6856. i, groupName, group, targetUnit, derivedConversions = {}, applyUnit;
  6857. if (typeof conversions === 'string') {
  6858. for (i in unitConversions) {
  6859. if (unitConversions[i].hasOwnProperty(conversions)) {
  6860. derivedConversions = {};
  6861. derivedConversions[i] = conversions;
  6862. }
  6863. }
  6864. conversions = derivedConversions;
  6865. }
  6866. applyUnit = function (atomicUnit, denominator) {
  6867. /* jshint loopfunc:true */
  6868. if (group.hasOwnProperty(atomicUnit)) {
  6869. if (denominator) {
  6870. value = value / (group[atomicUnit] / group[targetUnit]);
  6871. } else {
  6872. value = value * (group[atomicUnit] / group[targetUnit]);
  6873. }
  6874. return targetUnit;
  6875. }
  6876. return atomicUnit;
  6877. };
  6878. for (groupName in conversions) {
  6879. if (conversions.hasOwnProperty(groupName)) {
  6880. targetUnit = conversions[groupName];
  6881. group = unitConversions[groupName];
  6882. unit.map(applyUnit);
  6883. }
  6884. }
  6885. unit.cancel();
  6886. return new Dimension(value, unit);
  6887. };
  6888. module.exports = Dimension;
  6889. },{"../data/unit-conversions":16,"./color":55,"./node":76,"./unit":84}],63:[function(require,module,exports){
  6890. var Node = require('./node'),
  6891. Paren = require('./paren'),
  6892. Combinator = require('./combinator');
  6893. var Element = function (combinator, value, isVariable, index, currentFileInfo, visibilityInfo) {
  6894. this.combinator = combinator instanceof Combinator ?
  6895. combinator : new Combinator(combinator);
  6896. if (typeof value === 'string') {
  6897. this.value = value.trim();
  6898. } else if (value) {
  6899. this.value = value;
  6900. } else {
  6901. this.value = '';
  6902. }
  6903. this.isVariable = isVariable;
  6904. this._index = index;
  6905. this._fileInfo = currentFileInfo;
  6906. this.copyVisibilityInfo(visibilityInfo);
  6907. this.setParent(this.combinator, this);
  6908. };
  6909. Element.prototype = new Node();
  6910. Element.prototype.type = 'Element';
  6911. Element.prototype.accept = function (visitor) {
  6912. var value = this.value;
  6913. this.combinator = visitor.visit(this.combinator);
  6914. if (typeof value === 'object') {
  6915. this.value = visitor.visit(value);
  6916. }
  6917. };
  6918. Element.prototype.eval = function (context) {
  6919. return new Element(this.combinator,
  6920. this.value.eval ? this.value.eval(context) : this.value,
  6921. this.isVariable,
  6922. this.getIndex(),
  6923. this.fileInfo(), this.visibilityInfo());
  6924. };
  6925. Element.prototype.clone = function () {
  6926. return new Element(this.combinator,
  6927. this.value,
  6928. this.isVariable,
  6929. this.getIndex(),
  6930. this.fileInfo(), this.visibilityInfo());
  6931. };
  6932. Element.prototype.genCSS = function (context, output) {
  6933. output.add(this.toCSS(context), this.fileInfo(), this.getIndex());
  6934. };
  6935. Element.prototype.toCSS = function (context) {
  6936. context = context || {};
  6937. var value = this.value, firstSelector = context.firstSelector;
  6938. if (value instanceof Paren) {
  6939. // selector in parens should not be affected by outer selector
  6940. // flags (breaks only interpolated selectors - see #1973)
  6941. context.firstSelector = true;
  6942. }
  6943. value = value.toCSS ? value.toCSS(context) : value;
  6944. context.firstSelector = firstSelector;
  6945. if (value === '' && this.combinator.value.charAt(0) === '&') {
  6946. return '';
  6947. } else {
  6948. return this.combinator.toCSS(context) + value;
  6949. }
  6950. };
  6951. module.exports = Element;
  6952. },{"./combinator":56,"./node":76,"./paren":78}],64:[function(require,module,exports){
  6953. var Node = require('./node'),
  6954. Paren = require('./paren'),
  6955. Comment = require('./comment'),
  6956. Dimension = require('./dimension'),
  6957. MATH = require('../constants').Math;
  6958. var Expression = function (value, noSpacing) {
  6959. this.value = value;
  6960. this.noSpacing = noSpacing;
  6961. if (!value) {
  6962. throw new Error('Expression requires an array parameter');
  6963. }
  6964. };
  6965. Expression.prototype = new Node();
  6966. Expression.prototype.type = 'Expression';
  6967. Expression.prototype.accept = function (visitor) {
  6968. this.value = visitor.visitArray(this.value);
  6969. };
  6970. Expression.prototype.eval = function (context) {
  6971. var returnValue,
  6972. mathOn = context.isMathOn(),
  6973. inParenthesis = this.parens &&
  6974. (context.math !== MATH.STRICT_LEGACY || !this.parensInOp),
  6975. doubleParen = false;
  6976. if (inParenthesis) {
  6977. context.inParenthesis();
  6978. }
  6979. if (this.value.length > 1) {
  6980. returnValue = new Expression(this.value.map(function (e) {
  6981. if (!e.eval) {
  6982. return e;
  6983. }
  6984. return e.eval(context);
  6985. }), this.noSpacing);
  6986. } else if (this.value.length === 1) {
  6987. if (this.value[0].parens && !this.value[0].parensInOp && !context.inCalc) {
  6988. doubleParen = true;
  6989. }
  6990. returnValue = this.value[0].eval(context);
  6991. } else {
  6992. returnValue = this;
  6993. }
  6994. if (inParenthesis) {
  6995. context.outOfParenthesis();
  6996. }
  6997. if (this.parens && this.parensInOp && !mathOn && !doubleParen
  6998. && (!(returnValue instanceof Dimension))) {
  6999. returnValue = new Paren(returnValue);
  7000. }
  7001. return returnValue;
  7002. };
  7003. Expression.prototype.genCSS = function (context, output) {
  7004. for (var i = 0; i < this.value.length; i++) {
  7005. this.value[i].genCSS(context, output);
  7006. if (!this.noSpacing && i + 1 < this.value.length) {
  7007. output.add(' ');
  7008. }
  7009. }
  7010. };
  7011. Expression.prototype.throwAwayComments = function () {
  7012. this.value = this.value.filter(function(v) {
  7013. return !(v instanceof Comment);
  7014. });
  7015. };
  7016. module.exports = Expression;
  7017. },{"../constants":12,"./comment":57,"./dimension":62,"./node":76,"./paren":78}],65:[function(require,module,exports){
  7018. var Node = require('./node'),
  7019. Selector = require('./selector');
  7020. var Extend = function Extend(selector, option, index, currentFileInfo, visibilityInfo) {
  7021. this.selector = selector;
  7022. this.option = option;
  7023. this.object_id = Extend.next_id++;
  7024. this.parent_ids = [this.object_id];
  7025. this._index = index;
  7026. this._fileInfo = currentFileInfo;
  7027. this.copyVisibilityInfo(visibilityInfo);
  7028. this.allowRoot = true;
  7029. switch (option) {
  7030. case 'all':
  7031. this.allowBefore = true;
  7032. this.allowAfter = true;
  7033. break;
  7034. default:
  7035. this.allowBefore = false;
  7036. this.allowAfter = false;
  7037. break;
  7038. }
  7039. this.setParent(this.selector, this);
  7040. };
  7041. Extend.next_id = 0;
  7042. Extend.prototype = new Node();
  7043. Extend.prototype.type = 'Extend';
  7044. Extend.prototype.accept = function (visitor) {
  7045. this.selector = visitor.visit(this.selector);
  7046. };
  7047. Extend.prototype.eval = function (context) {
  7048. return new Extend(this.selector.eval(context), this.option, this.getIndex(), this.fileInfo(), this.visibilityInfo());
  7049. };
  7050. Extend.prototype.clone = function (context) {
  7051. return new Extend(this.selector, this.option, this.getIndex(), this.fileInfo(), this.visibilityInfo());
  7052. };
  7053. // it concatenates (joins) all selectors in selector array
  7054. Extend.prototype.findSelfSelectors = function (selectors) {
  7055. var selfElements = [],
  7056. i,
  7057. selectorElements;
  7058. for (i = 0; i < selectors.length; i++) {
  7059. selectorElements = selectors[i].elements;
  7060. // duplicate the logic in genCSS function inside the selector node.
  7061. // future TODO - move both logics into the selector joiner visitor
  7062. if (i > 0 && selectorElements.length && selectorElements[0].combinator.value === '') {
  7063. selectorElements[0].combinator.value = ' ';
  7064. }
  7065. selfElements = selfElements.concat(selectors[i].elements);
  7066. }
  7067. this.selfSelectors = [new Selector(selfElements)];
  7068. this.selfSelectors[0].copyVisibilityInfo(this.visibilityInfo());
  7069. };
  7070. module.exports = Extend;
  7071. },{"./node":76,"./selector":82}],66:[function(require,module,exports){
  7072. var Node = require('./node'),
  7073. Media = require('./media'),
  7074. URL = require('./url'),
  7075. Quoted = require('./quoted'),
  7076. Ruleset = require('./ruleset'),
  7077. Anonymous = require('./anonymous'),
  7078. utils = require('../utils'),
  7079. LessError = require('../less-error');
  7080. //
  7081. // CSS @import node
  7082. //
  7083. // The general strategy here is that we don't want to wait
  7084. // for the parsing to be completed, before we start importing
  7085. // the file. That's because in the context of a browser,
  7086. // most of the time will be spent waiting for the server to respond.
  7087. //
  7088. // On creation, we push the import path to our import queue, though
  7089. // `import,push`, we also pass it a callback, which it'll call once
  7090. // the file has been fetched, and parsed.
  7091. //
  7092. var Import = function (path, features, options, index, currentFileInfo, visibilityInfo) {
  7093. this.options = options;
  7094. this._index = index;
  7095. this._fileInfo = currentFileInfo;
  7096. this.path = path;
  7097. this.features = features;
  7098. this.allowRoot = true;
  7099. if (this.options.less !== undefined || this.options.inline) {
  7100. this.css = !this.options.less || this.options.inline;
  7101. } else {
  7102. var pathValue = this.getPath();
  7103. if (pathValue && /[#\.\&\?]css([\?;].*)?$/.test(pathValue)) {
  7104. this.css = true;
  7105. }
  7106. }
  7107. this.copyVisibilityInfo(visibilityInfo);
  7108. this.setParent(this.features, this);
  7109. this.setParent(this.path, this);
  7110. };
  7111. //
  7112. // The actual import node doesn't return anything, when converted to CSS.
  7113. // The reason is that it's used at the evaluation stage, so that the rules
  7114. // it imports can be treated like any other rules.
  7115. //
  7116. // In `eval`, we make sure all Import nodes get evaluated, recursively, so
  7117. // we end up with a flat structure, which can easily be imported in the parent
  7118. // ruleset.
  7119. //
  7120. Import.prototype = new Node();
  7121. Import.prototype.type = 'Import';
  7122. Import.prototype.accept = function (visitor) {
  7123. if (this.features) {
  7124. this.features = visitor.visit(this.features);
  7125. }
  7126. this.path = visitor.visit(this.path);
  7127. if (!this.options.isPlugin && !this.options.inline && this.root) {
  7128. this.root = visitor.visit(this.root);
  7129. }
  7130. };
  7131. Import.prototype.genCSS = function (context, output) {
  7132. if (this.css && this.path._fileInfo.reference === undefined) {
  7133. output.add('@import ', this._fileInfo, this._index);
  7134. this.path.genCSS(context, output);
  7135. if (this.features) {
  7136. output.add(' ');
  7137. this.features.genCSS(context, output);
  7138. }
  7139. output.add(';');
  7140. }
  7141. };
  7142. Import.prototype.getPath = function () {
  7143. return (this.path instanceof URL) ?
  7144. this.path.value.value : this.path.value;
  7145. };
  7146. Import.prototype.isVariableImport = function () {
  7147. var path = this.path;
  7148. if (path instanceof URL) {
  7149. path = path.value;
  7150. }
  7151. if (path instanceof Quoted) {
  7152. return path.containsVariables();
  7153. }
  7154. return true;
  7155. };
  7156. Import.prototype.evalForImport = function (context) {
  7157. var path = this.path;
  7158. if (path instanceof URL) {
  7159. path = path.value;
  7160. }
  7161. return new Import(path.eval(context), this.features, this.options, this._index, this._fileInfo, this.visibilityInfo());
  7162. };
  7163. Import.prototype.evalPath = function (context) {
  7164. var path = this.path.eval(context);
  7165. var fileInfo = this._fileInfo;
  7166. if (!(path instanceof URL)) {
  7167. // Add the rootpath if the URL requires a rewrite
  7168. var pathValue = path.value;
  7169. if (fileInfo &&
  7170. pathValue &&
  7171. context.pathRequiresRewrite(pathValue)) {
  7172. path.value = context.rewritePath(pathValue, fileInfo.rootpath);
  7173. } else {
  7174. path.value = context.normalizePath(path.value);
  7175. }
  7176. }
  7177. return path;
  7178. };
  7179. Import.prototype.eval = function (context) {
  7180. var result = this.doEval(context);
  7181. if (this.options.reference || this.blocksVisibility()) {
  7182. if (result.length || result.length === 0) {
  7183. result.forEach(function (node) {
  7184. node.addVisibilityBlock();
  7185. }
  7186. );
  7187. } else {
  7188. result.addVisibilityBlock();
  7189. }
  7190. }
  7191. return result;
  7192. };
  7193. Import.prototype.doEval = function (context) {
  7194. var ruleset, registry,
  7195. features = this.features && this.features.eval(context);
  7196. if (this.options.isPlugin) {
  7197. if (this.root && this.root.eval) {
  7198. try {
  7199. this.root.eval(context);
  7200. }
  7201. catch (e) {
  7202. e.message = 'Plugin error during evaluation';
  7203. throw new LessError(e, this.root.imports, this.root.filename);
  7204. }
  7205. }
  7206. registry = context.frames[0] && context.frames[0].functionRegistry;
  7207. if ( registry && this.root && this.root.functions ) {
  7208. registry.addMultiple( this.root.functions );
  7209. }
  7210. return [];
  7211. }
  7212. if (this.skip) {
  7213. if (typeof this.skip === 'function') {
  7214. this.skip = this.skip();
  7215. }
  7216. if (this.skip) {
  7217. return [];
  7218. }
  7219. }
  7220. if (this.options.inline) {
  7221. var contents = new Anonymous(this.root, 0,
  7222. {
  7223. filename: this.importedFilename,
  7224. reference: this.path._fileInfo && this.path._fileInfo.reference
  7225. }, true, true);
  7226. return this.features ? new Media([contents], this.features.value) : [contents];
  7227. } else if (this.css) {
  7228. var newImport = new Import(this.evalPath(context), features, this.options, this._index);
  7229. if (!newImport.css && this.error) {
  7230. throw this.error;
  7231. }
  7232. return newImport;
  7233. } else {
  7234. ruleset = new Ruleset(null, utils.copyArray(this.root.rules));
  7235. ruleset.evalImports(context);
  7236. return this.features ? new Media(ruleset.rules, this.features.value) : ruleset.rules;
  7237. }
  7238. };
  7239. module.exports = Import;
  7240. },{"../less-error":38,"../utils":89,"./anonymous":50,"./media":71,"./node":76,"./quoted":80,"./ruleset":81,"./url":85}],67:[function(require,module,exports){
  7241. var tree = Object.create(null);
  7242. tree.Node = require('./node');
  7243. tree.Color = require('./color');
  7244. tree.AtRule = require('./atrule');
  7245. tree.DetachedRuleset = require('./detached-ruleset');
  7246. tree.Operation = require('./operation');
  7247. tree.Dimension = require('./dimension');
  7248. tree.Unit = require('./unit');
  7249. tree.Keyword = require('./keyword');
  7250. tree.Variable = require('./variable');
  7251. tree.Property = require('./property');
  7252. tree.Ruleset = require('./ruleset');
  7253. tree.Element = require('./element');
  7254. tree.Attribute = require('./attribute');
  7255. tree.Combinator = require('./combinator');
  7256. tree.Selector = require('./selector');
  7257. tree.Quoted = require('./quoted');
  7258. tree.Expression = require('./expression');
  7259. tree.Declaration = require('./declaration');
  7260. tree.Call = require('./call');
  7261. tree.URL = require('./url');
  7262. tree.Import = require('./import');
  7263. tree.mixin = {
  7264. Call: require('./mixin-call'),
  7265. Definition: require('./mixin-definition')
  7266. };
  7267. tree.Comment = require('./comment');
  7268. tree.Anonymous = require('./anonymous');
  7269. tree.Value = require('./value');
  7270. tree.JavaScript = require('./javascript');
  7271. tree.Assignment = require('./assignment');
  7272. tree.Condition = require('./condition');
  7273. tree.Paren = require('./paren');
  7274. tree.Media = require('./media');
  7275. tree.UnicodeDescriptor = require('./unicode-descriptor');
  7276. tree.Negative = require('./negative');
  7277. tree.Extend = require('./extend');
  7278. tree.VariableCall = require('./variable-call');
  7279. tree.NamespaceValue = require('./namespace-value');
  7280. module.exports = tree;
  7281. },{"./anonymous":50,"./assignment":51,"./atrule":52,"./attribute":53,"./call":54,"./color":55,"./combinator":56,"./comment":57,"./condition":58,"./declaration":60,"./detached-ruleset":61,"./dimension":62,"./element":63,"./expression":64,"./extend":65,"./import":66,"./javascript":68,"./keyword":70,"./media":71,"./mixin-call":72,"./mixin-definition":73,"./namespace-value":74,"./negative":75,"./node":76,"./operation":77,"./paren":78,"./property":79,"./quoted":80,"./ruleset":81,"./selector":82,"./unicode-descriptor":83,"./unit":84,"./url":85,"./value":86,"./variable":88,"./variable-call":87}],68:[function(require,module,exports){
  7282. var JsEvalNode = require('./js-eval-node'),
  7283. Dimension = require('./dimension'),
  7284. Quoted = require('./quoted'),
  7285. Anonymous = require('./anonymous');
  7286. var JavaScript = function (string, escaped, index, currentFileInfo) {
  7287. this.escaped = escaped;
  7288. this.expression = string;
  7289. this._index = index;
  7290. this._fileInfo = currentFileInfo;
  7291. };
  7292. JavaScript.prototype = new JsEvalNode();
  7293. JavaScript.prototype.type = 'JavaScript';
  7294. JavaScript.prototype.eval = function(context) {
  7295. var result = this.evaluateJavaScript(this.expression, context);
  7296. var type = typeof result;
  7297. if (type === 'number' && !isNaN(result)) {
  7298. return new Dimension(result);
  7299. } else if (type === 'string') {
  7300. return new Quoted('"' + result + '"', result, this.escaped, this._index);
  7301. } else if (Array.isArray(result)) {
  7302. return new Anonymous(result.join(', '));
  7303. } else {
  7304. return new Anonymous(result);
  7305. }
  7306. };
  7307. module.exports = JavaScript;
  7308. },{"./anonymous":50,"./dimension":62,"./js-eval-node":69,"./quoted":80}],69:[function(require,module,exports){
  7309. var Node = require('./node'),
  7310. Variable = require('./variable');
  7311. var JsEvalNode = function() {
  7312. };
  7313. JsEvalNode.prototype = new Node();
  7314. JsEvalNode.prototype.evaluateJavaScript = function (expression, context) {
  7315. var result,
  7316. that = this,
  7317. evalContext = {};
  7318. if (!context.javascriptEnabled) {
  7319. throw { message: 'Inline JavaScript is not enabled. Is it set in your options?',
  7320. filename: this.fileInfo().filename,
  7321. index: this.getIndex() };
  7322. }
  7323. expression = expression.replace(/@\{([\w-]+)\}/g, function (_, name) {
  7324. return that.jsify(new Variable('@' + name, that.getIndex(), that.fileInfo()).eval(context));
  7325. });
  7326. try {
  7327. expression = new Function('return (' + expression + ')');
  7328. } catch (e) {
  7329. throw { message: 'JavaScript evaluation error: ' + e.message + ' from `' + expression + '`' ,
  7330. filename: this.fileInfo().filename,
  7331. index: this.getIndex() };
  7332. }
  7333. var variables = context.frames[0].variables();
  7334. for (var k in variables) {
  7335. if (variables.hasOwnProperty(k)) {
  7336. /* jshint loopfunc:true */
  7337. evalContext[k.slice(1)] = {
  7338. value: variables[k].value,
  7339. toJS: function () {
  7340. return this.value.eval(context).toCSS();
  7341. }
  7342. };
  7343. }
  7344. }
  7345. try {
  7346. result = expression.call(evalContext);
  7347. } catch (e) {
  7348. throw { message: 'JavaScript evaluation error: \'' + e.name + ': ' + e.message.replace(/["]/g, '\'') + '\'' ,
  7349. filename: this.fileInfo().filename,
  7350. index: this.getIndex() };
  7351. }
  7352. return result;
  7353. };
  7354. JsEvalNode.prototype.jsify = function (obj) {
  7355. if (Array.isArray(obj.value) && (obj.value.length > 1)) {
  7356. return '[' + obj.value.map(function (v) { return v.toCSS(); }).join(', ') + ']';
  7357. } else {
  7358. return obj.toCSS();
  7359. }
  7360. };
  7361. module.exports = JsEvalNode;
  7362. },{"./node":76,"./variable":88}],70:[function(require,module,exports){
  7363. var Node = require('./node');
  7364. var Keyword = function (value) { this.value = value; };
  7365. Keyword.prototype = new Node();
  7366. Keyword.prototype.type = 'Keyword';
  7367. Keyword.prototype.genCSS = function (context, output) {
  7368. if (this.value === '%') { throw { type: 'Syntax', message: 'Invalid % without number' }; }
  7369. output.add(this.value);
  7370. };
  7371. Keyword.True = new Keyword('true');
  7372. Keyword.False = new Keyword('false');
  7373. module.exports = Keyword;
  7374. },{"./node":76}],71:[function(require,module,exports){
  7375. var Ruleset = require('./ruleset'),
  7376. Value = require('./value'),
  7377. Selector = require('./selector'),
  7378. Anonymous = require('./anonymous'),
  7379. Expression = require('./expression'),
  7380. AtRule = require('./atrule'),
  7381. utils = require('../utils');
  7382. var Media = function (value, features, index, currentFileInfo, visibilityInfo) {
  7383. this._index = index;
  7384. this._fileInfo = currentFileInfo;
  7385. var selectors = (new Selector([], null, null, this._index, this._fileInfo)).createEmptySelectors();
  7386. this.features = new Value(features);
  7387. this.rules = [new Ruleset(selectors, value)];
  7388. this.rules[0].allowImports = true;
  7389. this.copyVisibilityInfo(visibilityInfo);
  7390. this.allowRoot = true;
  7391. this.setParent(selectors, this);
  7392. this.setParent(this.features, this);
  7393. this.setParent(this.rules, this);
  7394. };
  7395. Media.prototype = new AtRule();
  7396. Media.prototype.type = 'Media';
  7397. Media.prototype.isRulesetLike = function() { return true; };
  7398. Media.prototype.accept = function (visitor) {
  7399. if (this.features) {
  7400. this.features = visitor.visit(this.features);
  7401. }
  7402. if (this.rules) {
  7403. this.rules = visitor.visitArray(this.rules);
  7404. }
  7405. };
  7406. Media.prototype.genCSS = function (context, output) {
  7407. output.add('@media ', this._fileInfo, this._index);
  7408. this.features.genCSS(context, output);
  7409. this.outputRuleset(context, output, this.rules);
  7410. };
  7411. Media.prototype.eval = function (context) {
  7412. if (!context.mediaBlocks) {
  7413. context.mediaBlocks = [];
  7414. context.mediaPath = [];
  7415. }
  7416. var media = new Media(null, [], this._index, this._fileInfo, this.visibilityInfo());
  7417. if (this.debugInfo) {
  7418. this.rules[0].debugInfo = this.debugInfo;
  7419. media.debugInfo = this.debugInfo;
  7420. }
  7421. media.features = this.features.eval(context);
  7422. context.mediaPath.push(media);
  7423. context.mediaBlocks.push(media);
  7424. this.rules[0].functionRegistry = context.frames[0].functionRegistry.inherit();
  7425. context.frames.unshift(this.rules[0]);
  7426. media.rules = [this.rules[0].eval(context)];
  7427. context.frames.shift();
  7428. context.mediaPath.pop();
  7429. return context.mediaPath.length === 0 ? media.evalTop(context) :
  7430. media.evalNested(context);
  7431. };
  7432. Media.prototype.evalTop = function (context) {
  7433. var result = this;
  7434. // Render all dependent Media blocks.
  7435. if (context.mediaBlocks.length > 1) {
  7436. var selectors = (new Selector([], null, null, this.getIndex(), this.fileInfo())).createEmptySelectors();
  7437. result = new Ruleset(selectors, context.mediaBlocks);
  7438. result.multiMedia = true;
  7439. result.copyVisibilityInfo(this.visibilityInfo());
  7440. this.setParent(result, this);
  7441. }
  7442. delete context.mediaBlocks;
  7443. delete context.mediaPath;
  7444. return result;
  7445. };
  7446. Media.prototype.evalNested = function (context) {
  7447. var i, value,
  7448. path = context.mediaPath.concat([this]);
  7449. // Extract the media-query conditions separated with `,` (OR).
  7450. for (i = 0; i < path.length; i++) {
  7451. value = path[i].features instanceof Value ?
  7452. path[i].features.value : path[i].features;
  7453. path[i] = Array.isArray(value) ? value : [value];
  7454. }
  7455. // Trace all permutations to generate the resulting media-query.
  7456. //
  7457. // (a, b and c) with nested (d, e) ->
  7458. // a and d
  7459. // a and e
  7460. // b and c and d
  7461. // b and c and e
  7462. this.features = new Value(this.permute(path).map(function (path) {
  7463. path = path.map(function (fragment) {
  7464. return fragment.toCSS ? fragment : new Anonymous(fragment);
  7465. });
  7466. for (i = path.length - 1; i > 0; i--) {
  7467. path.splice(i, 0, new Anonymous('and'));
  7468. }
  7469. return new Expression(path);
  7470. }));
  7471. this.setParent(this.features, this);
  7472. // Fake a tree-node that doesn't output anything.
  7473. return new Ruleset([], []);
  7474. };
  7475. Media.prototype.permute = function (arr) {
  7476. if (arr.length === 0) {
  7477. return [];
  7478. } else if (arr.length === 1) {
  7479. return arr[0];
  7480. } else {
  7481. var result = [];
  7482. var rest = this.permute(arr.slice(1));
  7483. for (var i = 0; i < rest.length; i++) {
  7484. for (var j = 0; j < arr[0].length; j++) {
  7485. result.push([arr[0][j]].concat(rest[i]));
  7486. }
  7487. }
  7488. return result;
  7489. }
  7490. };
  7491. Media.prototype.bubbleSelectors = function (selectors) {
  7492. if (!selectors) {
  7493. return;
  7494. }
  7495. this.rules = [new Ruleset(utils.copyArray(selectors), [this.rules[0]])];
  7496. this.setParent(this.rules, this);
  7497. };
  7498. module.exports = Media;
  7499. },{"../utils":89,"./anonymous":50,"./atrule":52,"./expression":64,"./ruleset":81,"./selector":82,"./value":86}],72:[function(require,module,exports){
  7500. var Node = require('./node'),
  7501. Selector = require('./selector'),
  7502. MixinDefinition = require('./mixin-definition'),
  7503. defaultFunc = require('../functions/default');
  7504. var MixinCall = function (elements, args, index, currentFileInfo, important) {
  7505. this.selector = new Selector(elements);
  7506. this.arguments = args || [];
  7507. this._index = index;
  7508. this._fileInfo = currentFileInfo;
  7509. this.important = important;
  7510. this.allowRoot = true;
  7511. this.setParent(this.selector, this);
  7512. };
  7513. MixinCall.prototype = new Node();
  7514. MixinCall.prototype.type = 'MixinCall';
  7515. MixinCall.prototype.accept = function (visitor) {
  7516. if (this.selector) {
  7517. this.selector = visitor.visit(this.selector);
  7518. }
  7519. if (this.arguments.length) {
  7520. this.arguments = visitor.visitArray(this.arguments);
  7521. }
  7522. };
  7523. MixinCall.prototype.eval = function (context) {
  7524. var mixins, mixin, mixinPath, args = [], arg, argValue,
  7525. rules = [], match = false, i, m, f, isRecursive, isOneFound,
  7526. candidates = [], candidate, conditionResult = [], defaultResult, defFalseEitherCase = -1,
  7527. defNone = 0, defTrue = 1, defFalse = 2, count, originalRuleset, noArgumentsFilter;
  7528. this.selector = this.selector.eval(context);
  7529. function calcDefGroup(mixin, mixinPath) {
  7530. var f, p, namespace;
  7531. for (f = 0; f < 2; f++) {
  7532. conditionResult[f] = true;
  7533. defaultFunc.value(f);
  7534. for (p = 0; p < mixinPath.length && conditionResult[f]; p++) {
  7535. namespace = mixinPath[p];
  7536. if (namespace.matchCondition) {
  7537. conditionResult[f] = conditionResult[f] && namespace.matchCondition(null, context);
  7538. }
  7539. }
  7540. if (mixin.matchCondition) {
  7541. conditionResult[f] = conditionResult[f] && mixin.matchCondition(args, context);
  7542. }
  7543. }
  7544. if (conditionResult[0] || conditionResult[1]) {
  7545. if (conditionResult[0] != conditionResult[1]) {
  7546. return conditionResult[1] ?
  7547. defTrue : defFalse;
  7548. }
  7549. return defNone;
  7550. }
  7551. return defFalseEitherCase;
  7552. }
  7553. for (i = 0; i < this.arguments.length; i++) {
  7554. arg = this.arguments[i];
  7555. argValue = arg.value.eval(context);
  7556. if (arg.expand && Array.isArray(argValue.value)) {
  7557. argValue = argValue.value;
  7558. for (m = 0; m < argValue.length; m++) {
  7559. args.push({value: argValue[m]});
  7560. }
  7561. } else {
  7562. args.push({name: arg.name, value: argValue});
  7563. }
  7564. }
  7565. noArgumentsFilter = function(rule) {return rule.matchArgs(null, context);};
  7566. for (i = 0; i < context.frames.length; i++) {
  7567. if ((mixins = context.frames[i].find(this.selector, null, noArgumentsFilter)).length > 0) {
  7568. isOneFound = true;
  7569. // To make `default()` function independent of definition order we have two "subpasses" here.
  7570. // At first we evaluate each guard *twice* (with `default() == true` and `default() == false`),
  7571. // and build candidate list with corresponding flags. Then, when we know all possible matches,
  7572. // we make a final decision.
  7573. for (m = 0; m < mixins.length; m++) {
  7574. mixin = mixins[m].rule;
  7575. mixinPath = mixins[m].path;
  7576. isRecursive = false;
  7577. for (f = 0; f < context.frames.length; f++) {
  7578. if ((!(mixin instanceof MixinDefinition)) && mixin === (context.frames[f].originalRuleset || context.frames[f])) {
  7579. isRecursive = true;
  7580. break;
  7581. }
  7582. }
  7583. if (isRecursive) {
  7584. continue;
  7585. }
  7586. if (mixin.matchArgs(args, context)) {
  7587. candidate = {mixin: mixin, group: calcDefGroup(mixin, mixinPath)};
  7588. if (candidate.group !== defFalseEitherCase) {
  7589. candidates.push(candidate);
  7590. }
  7591. match = true;
  7592. }
  7593. }
  7594. defaultFunc.reset();
  7595. count = [0, 0, 0];
  7596. for (m = 0; m < candidates.length; m++) {
  7597. count[candidates[m].group]++;
  7598. }
  7599. if (count[defNone] > 0) {
  7600. defaultResult = defFalse;
  7601. } else {
  7602. defaultResult = defTrue;
  7603. if ((count[defTrue] + count[defFalse]) > 1) {
  7604. throw { type: 'Runtime',
  7605. message: 'Ambiguous use of `default()` found when matching for `' + this.format(args) + '`',
  7606. index: this.getIndex(), filename: this.fileInfo().filename };
  7607. }
  7608. }
  7609. for (m = 0; m < candidates.length; m++) {
  7610. candidate = candidates[m].group;
  7611. if ((candidate === defNone) || (candidate === defaultResult)) {
  7612. try {
  7613. mixin = candidates[m].mixin;
  7614. if (!(mixin instanceof MixinDefinition)) {
  7615. originalRuleset = mixin.originalRuleset || mixin;
  7616. mixin = new MixinDefinition('', [], mixin.rules, null, false, null, originalRuleset.visibilityInfo());
  7617. mixin.originalRuleset = originalRuleset;
  7618. }
  7619. var newRules = mixin.evalCall(context, args, this.important).rules;
  7620. this._setVisibilityToReplacement(newRules);
  7621. Array.prototype.push.apply(rules, newRules);
  7622. } catch (e) {
  7623. throw { message: e.message, index: this.getIndex(), filename: this.fileInfo().filename, stack: e.stack };
  7624. }
  7625. }
  7626. }
  7627. if (match) {
  7628. return rules;
  7629. }
  7630. }
  7631. }
  7632. if (isOneFound) {
  7633. throw { type: 'Runtime',
  7634. message: 'No matching definition was found for `' + this.format(args) + '`',
  7635. index: this.getIndex(), filename: this.fileInfo().filename };
  7636. } else {
  7637. throw { type: 'Name',
  7638. message: this.selector.toCSS().trim() + ' is undefined',
  7639. index: this.getIndex(), filename: this.fileInfo().filename };
  7640. }
  7641. };
  7642. MixinCall.prototype._setVisibilityToReplacement = function (replacement) {
  7643. var i, rule;
  7644. if (this.blocksVisibility()) {
  7645. for (i = 0; i < replacement.length; i++) {
  7646. rule = replacement[i];
  7647. rule.addVisibilityBlock();
  7648. }
  7649. }
  7650. };
  7651. MixinCall.prototype.format = function (args) {
  7652. return this.selector.toCSS().trim() + '(' +
  7653. (args ? args.map(function (a) {
  7654. var argValue = '';
  7655. if (a.name) {
  7656. argValue += a.name + ':';
  7657. }
  7658. if (a.value.toCSS) {
  7659. argValue += a.value.toCSS();
  7660. } else {
  7661. argValue += '???';
  7662. }
  7663. return argValue;
  7664. }).join(', ') : '') + ')';
  7665. };
  7666. module.exports = MixinCall;
  7667. },{"../functions/default":25,"./mixin-definition":73,"./node":76,"./selector":82}],73:[function(require,module,exports){
  7668. var Selector = require('./selector'),
  7669. Element = require('./element'),
  7670. Ruleset = require('./ruleset'),
  7671. Declaration = require('./declaration'),
  7672. DetachedRuleset = require('./detached-ruleset'),
  7673. Expression = require('./expression'),
  7674. contexts = require('../contexts'),
  7675. utils = require('../utils');
  7676. var Definition = function (name, params, rules, condition, variadic, frames, visibilityInfo) {
  7677. this.name = name || 'anonymous mixin';
  7678. this.selectors = [new Selector([new Element(null, name, false, this._index, this._fileInfo)])];
  7679. this.params = params;
  7680. this.condition = condition;
  7681. this.variadic = variadic;
  7682. this.arity = params.length;
  7683. this.rules = rules;
  7684. this._lookups = {};
  7685. var optionalParameters = [];
  7686. this.required = params.reduce(function (count, p) {
  7687. if (!p.name || (p.name && !p.value)) {
  7688. return count + 1;
  7689. }
  7690. else {
  7691. optionalParameters.push(p.name);
  7692. return count;
  7693. }
  7694. }, 0);
  7695. this.optionalParameters = optionalParameters;
  7696. this.frames = frames;
  7697. this.copyVisibilityInfo(visibilityInfo);
  7698. this.allowRoot = true;
  7699. };
  7700. Definition.prototype = new Ruleset();
  7701. Definition.prototype.type = 'MixinDefinition';
  7702. Definition.prototype.evalFirst = true;
  7703. Definition.prototype.accept = function (visitor) {
  7704. if (this.params && this.params.length) {
  7705. this.params = visitor.visitArray(this.params);
  7706. }
  7707. this.rules = visitor.visitArray(this.rules);
  7708. if (this.condition) {
  7709. this.condition = visitor.visit(this.condition);
  7710. }
  7711. };
  7712. Definition.prototype.evalParams = function (context, mixinEnv, args, evaldArguments) {
  7713. /* jshint boss:true */
  7714. var frame = new Ruleset(null, null),
  7715. varargs, arg,
  7716. params = utils.copyArray(this.params),
  7717. i, j, val, name, isNamedFound, argIndex, argsLength = 0;
  7718. if (mixinEnv.frames && mixinEnv.frames[0] && mixinEnv.frames[0].functionRegistry) {
  7719. frame.functionRegistry = mixinEnv.frames[0].functionRegistry.inherit();
  7720. }
  7721. mixinEnv = new contexts.Eval(mixinEnv, [frame].concat(mixinEnv.frames));
  7722. if (args) {
  7723. args = utils.copyArray(args);
  7724. argsLength = args.length;
  7725. for (i = 0; i < argsLength; i++) {
  7726. arg = args[i];
  7727. if (name = (arg && arg.name)) {
  7728. isNamedFound = false;
  7729. for (j = 0; j < params.length; j++) {
  7730. if (!evaldArguments[j] && name === params[j].name) {
  7731. evaldArguments[j] = arg.value.eval(context);
  7732. frame.prependRule(new Declaration(name, arg.value.eval(context)));
  7733. isNamedFound = true;
  7734. break;
  7735. }
  7736. }
  7737. if (isNamedFound) {
  7738. args.splice(i, 1);
  7739. i--;
  7740. continue;
  7741. } else {
  7742. throw { type: 'Runtime', message: 'Named argument for ' + this.name +
  7743. ' ' + args[i].name + ' not found' };
  7744. }
  7745. }
  7746. }
  7747. }
  7748. argIndex = 0;
  7749. for (i = 0; i < params.length; i++) {
  7750. if (evaldArguments[i]) { continue; }
  7751. arg = args && args[argIndex];
  7752. if (name = params[i].name) {
  7753. if (params[i].variadic) {
  7754. varargs = [];
  7755. for (j = argIndex; j < argsLength; j++) {
  7756. varargs.push(args[j].value.eval(context));
  7757. }
  7758. frame.prependRule(new Declaration(name, new Expression(varargs).eval(context)));
  7759. } else {
  7760. val = arg && arg.value;
  7761. if (val) {
  7762. // This was a mixin call, pass in a detached ruleset of it's eval'd rules
  7763. if (Array.isArray(val)) {
  7764. val = new DetachedRuleset(new Ruleset('', val));
  7765. }
  7766. else {
  7767. val = val.eval(context);
  7768. }
  7769. } else if (params[i].value) {
  7770. val = params[i].value.eval(mixinEnv);
  7771. frame.resetCache();
  7772. } else {
  7773. throw { type: 'Runtime', message: 'wrong number of arguments for ' + this.name +
  7774. ' (' + argsLength + ' for ' + this.arity + ')' };
  7775. }
  7776. frame.prependRule(new Declaration(name, val));
  7777. evaldArguments[i] = val;
  7778. }
  7779. }
  7780. if (params[i].variadic && args) {
  7781. for (j = argIndex; j < argsLength; j++) {
  7782. evaldArguments[j] = args[j].value.eval(context);
  7783. }
  7784. }
  7785. argIndex++;
  7786. }
  7787. return frame;
  7788. };
  7789. Definition.prototype.makeImportant = function() {
  7790. var rules = !this.rules ? this.rules : this.rules.map(function (r) {
  7791. if (r.makeImportant) {
  7792. return r.makeImportant(true);
  7793. } else {
  7794. return r;
  7795. }
  7796. });
  7797. var result = new Definition(this.name, this.params, rules, this.condition, this.variadic, this.frames);
  7798. return result;
  7799. };
  7800. Definition.prototype.eval = function (context) {
  7801. return new Definition(this.name, this.params, this.rules, this.condition, this.variadic, this.frames || utils.copyArray(context.frames));
  7802. };
  7803. Definition.prototype.evalCall = function (context, args, important) {
  7804. var _arguments = [],
  7805. mixinFrames = this.frames ? this.frames.concat(context.frames) : context.frames,
  7806. frame = this.evalParams(context, new contexts.Eval(context, mixinFrames), args, _arguments),
  7807. rules, ruleset;
  7808. frame.prependRule(new Declaration('@arguments', new Expression(_arguments).eval(context)));
  7809. rules = utils.copyArray(this.rules);
  7810. ruleset = new Ruleset(null, rules);
  7811. ruleset.originalRuleset = this;
  7812. ruleset = ruleset.eval(new contexts.Eval(context, [this, frame].concat(mixinFrames)));
  7813. if (important) {
  7814. ruleset = ruleset.makeImportant();
  7815. }
  7816. return ruleset;
  7817. };
  7818. Definition.prototype.matchCondition = function (args, context) {
  7819. if (this.condition && !this.condition.eval(
  7820. new contexts.Eval(context,
  7821. [this.evalParams(context, /* the parameter variables */
  7822. new contexts.Eval(context, this.frames ? this.frames.concat(context.frames) : context.frames), args, [])]
  7823. .concat(this.frames || []) // the parent namespace/mixin frames
  7824. .concat(context.frames)))) { // the current environment frames
  7825. return false;
  7826. }
  7827. return true;
  7828. };
  7829. Definition.prototype.matchArgs = function (args, context) {
  7830. var allArgsCnt = (args && args.length) || 0, len, optionalParameters = this.optionalParameters;
  7831. var requiredArgsCnt = !args ? 0 : args.reduce(function (count, p) {
  7832. if (optionalParameters.indexOf(p.name) < 0) {
  7833. return count + 1;
  7834. } else {
  7835. return count;
  7836. }
  7837. }, 0);
  7838. if (!this.variadic) {
  7839. if (requiredArgsCnt < this.required) {
  7840. return false;
  7841. }
  7842. if (allArgsCnt > this.params.length) {
  7843. return false;
  7844. }
  7845. } else {
  7846. if (requiredArgsCnt < (this.required - 1)) {
  7847. return false;
  7848. }
  7849. }
  7850. // check patterns
  7851. len = Math.min(requiredArgsCnt, this.arity);
  7852. for (var i = 0; i < len; i++) {
  7853. if (!this.params[i].name && !this.params[i].variadic) {
  7854. if (args[i].value.eval(context).toCSS() != this.params[i].value.eval(context).toCSS()) {
  7855. return false;
  7856. }
  7857. }
  7858. }
  7859. return true;
  7860. };
  7861. module.exports = Definition;
  7862. },{"../contexts":13,"../utils":89,"./declaration":60,"./detached-ruleset":61,"./element":63,"./expression":64,"./ruleset":81,"./selector":82}],74:[function(require,module,exports){
  7863. var Node = require('./node'),
  7864. Variable = require('./variable'),
  7865. Ruleset = require('./ruleset'),
  7866. Selector = require('./selector');
  7867. var NamespaceValue = function (ruleCall, lookups, important, index, fileInfo) {
  7868. this.value = ruleCall;
  7869. this.lookups = lookups;
  7870. this.important = important;
  7871. this._index = index;
  7872. this._fileInfo = fileInfo;
  7873. };
  7874. NamespaceValue.prototype = new Node();
  7875. NamespaceValue.prototype.type = 'NamespaceValue';
  7876. NamespaceValue.prototype.eval = function (context) {
  7877. var i, j, name, rules = this.value.eval(context);
  7878. for (i = 0; i < this.lookups.length; i++) {
  7879. name = this.lookups[i];
  7880. /**
  7881. * Eval'd DRs return rulesets.
  7882. * Eval'd mixins return rules, so let's make a ruleset if we need it.
  7883. * We need to do this because of late parsing of values
  7884. */
  7885. if (Array.isArray(rules)) {
  7886. rules = new Ruleset([new Selector()], rules);
  7887. }
  7888. if (name === '') {
  7889. rules = rules.lastDeclaration();
  7890. }
  7891. else if (name.charAt(0) === '@') {
  7892. if (name.charAt(1) === '@') {
  7893. name = '@' + new Variable(name.substr(1)).eval(context).value;
  7894. }
  7895. if (rules.variables) {
  7896. rules = rules.variable(name);
  7897. }
  7898. if (!rules) {
  7899. throw { type: 'Name',
  7900. message: 'variable ' + name + ' not found',
  7901. filename: this.fileInfo().filename,
  7902. index: this.getIndex() };
  7903. }
  7904. }
  7905. else {
  7906. if (name.substring(0, 2) === '$@') {
  7907. name = '$' + new Variable(name.substr(1)).eval(context).value;
  7908. }
  7909. else {
  7910. name = name.charAt(0) === '$' ? name : '$' + name;
  7911. }
  7912. if (rules.properties) {
  7913. rules = rules.property(name);
  7914. }
  7915. if (!rules) {
  7916. throw { type: 'Name',
  7917. message: 'property "' + name.substr(1) + '" not found',
  7918. filename: this.fileInfo().filename,
  7919. index: this.getIndex() };
  7920. }
  7921. // Properties are an array of values, since a ruleset can have multiple props.
  7922. // We pick the last one (the "cascaded" value)
  7923. rules = rules[rules.length - 1];
  7924. }
  7925. if (rules.value) {
  7926. rules = rules.eval(context).value;
  7927. }
  7928. if (rules.ruleset) {
  7929. rules = rules.ruleset.eval(context);
  7930. }
  7931. }
  7932. return rules;
  7933. };
  7934. module.exports = NamespaceValue;
  7935. },{"./node":76,"./ruleset":81,"./selector":82,"./variable":88}],75:[function(require,module,exports){
  7936. var Node = require('./node'),
  7937. Operation = require('./operation'),
  7938. Dimension = require('./dimension');
  7939. var Negative = function (node) {
  7940. this.value = node;
  7941. };
  7942. Negative.prototype = new Node();
  7943. Negative.prototype.type = 'Negative';
  7944. Negative.prototype.genCSS = function (context, output) {
  7945. output.add('-');
  7946. this.value.genCSS(context, output);
  7947. };
  7948. Negative.prototype.eval = function (context) {
  7949. if (context.isMathOn()) {
  7950. return (new Operation('*', [new Dimension(-1), this.value])).eval(context);
  7951. }
  7952. return new Negative(this.value.eval(context));
  7953. };
  7954. module.exports = Negative;
  7955. },{"./dimension":62,"./node":76,"./operation":77}],76:[function(require,module,exports){
  7956. var Node = function() {
  7957. this.parent = null;
  7958. this.visibilityBlocks = undefined;
  7959. this.nodeVisible = undefined;
  7960. this.rootNode = null;
  7961. this.parsed = null;
  7962. var self = this;
  7963. Object.defineProperty(this, 'currentFileInfo', {
  7964. get: function() { return self.fileInfo(); }
  7965. });
  7966. Object.defineProperty(this, 'index', {
  7967. get: function() { return self.getIndex(); }
  7968. });
  7969. };
  7970. Node.prototype.setParent = function(nodes, parent) {
  7971. function set(node) {
  7972. if (node && node instanceof Node) {
  7973. node.parent = parent;
  7974. }
  7975. }
  7976. if (Array.isArray(nodes)) {
  7977. nodes.forEach(set);
  7978. }
  7979. else {
  7980. set(nodes);
  7981. }
  7982. };
  7983. Node.prototype.getIndex = function() {
  7984. return this._index || (this.parent && this.parent.getIndex()) || 0;
  7985. };
  7986. Node.prototype.fileInfo = function() {
  7987. return this._fileInfo || (this.parent && this.parent.fileInfo()) || {};
  7988. };
  7989. Node.prototype.isRulesetLike = function() { return false; };
  7990. Node.prototype.toCSS = function (context) {
  7991. var strs = [];
  7992. this.genCSS(context, {
  7993. add: function(chunk, fileInfo, index) {
  7994. strs.push(chunk);
  7995. },
  7996. isEmpty: function () {
  7997. return strs.length === 0;
  7998. }
  7999. });
  8000. return strs.join('');
  8001. };
  8002. Node.prototype.genCSS = function (context, output) {
  8003. output.add(this.value);
  8004. };
  8005. Node.prototype.accept = function (visitor) {
  8006. this.value = visitor.visit(this.value);
  8007. };
  8008. Node.prototype.eval = function () { return this; };
  8009. Node.prototype._operate = function (context, op, a, b) {
  8010. switch (op) {
  8011. case '+': return a + b;
  8012. case '-': return a - b;
  8013. case '*': return a * b;
  8014. case '/': return a / b;
  8015. }
  8016. };
  8017. Node.prototype.fround = function(context, value) {
  8018. var precision = context && context.numPrecision;
  8019. // add "epsilon" to ensure numbers like 1.000000005 (represented as 1.000000004999...) are properly rounded:
  8020. return (precision) ? Number((value + 2e-16).toFixed(precision)) : value;
  8021. };
  8022. Node.compare = function (a, b) {
  8023. /* returns:
  8024. -1: a < b
  8025. 0: a = b
  8026. 1: a > b
  8027. and *any* other value for a != b (e.g. undefined, NaN, -2 etc.) */
  8028. if ((a.compare) &&
  8029. // for "symmetric results" force toCSS-based comparison
  8030. // of Quoted or Anonymous if either value is one of those
  8031. !(b.type === 'Quoted' || b.type === 'Anonymous')) {
  8032. return a.compare(b);
  8033. } else if (b.compare) {
  8034. return -b.compare(a);
  8035. } else if (a.type !== b.type) {
  8036. return undefined;
  8037. }
  8038. a = a.value;
  8039. b = b.value;
  8040. if (!Array.isArray(a)) {
  8041. return a === b ? 0 : undefined;
  8042. }
  8043. if (a.length !== b.length) {
  8044. return undefined;
  8045. }
  8046. for (var i = 0; i < a.length; i++) {
  8047. if (Node.compare(a[i], b[i]) !== 0) {
  8048. return undefined;
  8049. }
  8050. }
  8051. return 0;
  8052. };
  8053. Node.numericCompare = function (a, b) {
  8054. return a < b ? -1
  8055. : a === b ? 0
  8056. : a > b ? 1 : undefined;
  8057. };
  8058. // Returns true if this node represents root of ast imported by reference
  8059. Node.prototype.blocksVisibility = function () {
  8060. if (this.visibilityBlocks == null) {
  8061. this.visibilityBlocks = 0;
  8062. }
  8063. return this.visibilityBlocks !== 0;
  8064. };
  8065. Node.prototype.addVisibilityBlock = function () {
  8066. if (this.visibilityBlocks == null) {
  8067. this.visibilityBlocks = 0;
  8068. }
  8069. this.visibilityBlocks = this.visibilityBlocks + 1;
  8070. };
  8071. Node.prototype.removeVisibilityBlock = function () {
  8072. if (this.visibilityBlocks == null) {
  8073. this.visibilityBlocks = 0;
  8074. }
  8075. this.visibilityBlocks = this.visibilityBlocks - 1;
  8076. };
  8077. // Turns on node visibility - if called node will be shown in output regardless
  8078. // of whether it comes from import by reference or not
  8079. Node.prototype.ensureVisibility = function () {
  8080. this.nodeVisible = true;
  8081. };
  8082. // Turns off node visibility - if called node will NOT be shown in output regardless
  8083. // of whether it comes from import by reference or not
  8084. Node.prototype.ensureInvisibility = function () {
  8085. this.nodeVisible = false;
  8086. };
  8087. // return values:
  8088. // false - the node must not be visible
  8089. // true - the node must be visible
  8090. // undefined or null - the node has the same visibility as its parent
  8091. Node.prototype.isVisible = function () {
  8092. return this.nodeVisible;
  8093. };
  8094. Node.prototype.visibilityInfo = function() {
  8095. return {
  8096. visibilityBlocks: this.visibilityBlocks,
  8097. nodeVisible: this.nodeVisible
  8098. };
  8099. };
  8100. Node.prototype.copyVisibilityInfo = function(info) {
  8101. if (!info) {
  8102. return;
  8103. }
  8104. this.visibilityBlocks = info.visibilityBlocks;
  8105. this.nodeVisible = info.nodeVisible;
  8106. };
  8107. module.exports = Node;
  8108. },{}],77:[function(require,module,exports){
  8109. var Node = require('./node'),
  8110. Color = require('./color'),
  8111. Dimension = require('./dimension'),
  8112. MATH = require('../constants').Math;
  8113. var Operation = function (op, operands, isSpaced) {
  8114. this.op = op.trim();
  8115. this.operands = operands;
  8116. this.isSpaced = isSpaced;
  8117. };
  8118. Operation.prototype = new Node();
  8119. Operation.prototype.type = 'Operation';
  8120. Operation.prototype.accept = function (visitor) {
  8121. this.operands = visitor.visit(this.operands);
  8122. };
  8123. Operation.prototype.eval = function (context) {
  8124. var a = this.operands[0].eval(context),
  8125. b = this.operands[1].eval(context),
  8126. op;
  8127. if (context.isMathOn(this.op)) {
  8128. op = this.op === './' ? '/' : this.op;
  8129. if (a instanceof Dimension && b instanceof Color) {
  8130. a = a.toColor();
  8131. }
  8132. if (b instanceof Dimension && a instanceof Color) {
  8133. b = b.toColor();
  8134. }
  8135. if (!a.operate) {
  8136. if (a instanceof Operation && a.op === '/' && context.math === MATH.PARENS_DIVISION) {
  8137. return new Operation(this.op, [a, b], this.isSpaced);
  8138. }
  8139. throw { type: 'Operation',
  8140. message: 'Operation on an invalid type' };
  8141. }
  8142. return a.operate(context, op, b);
  8143. } else {
  8144. return new Operation(this.op, [a, b], this.isSpaced);
  8145. }
  8146. };
  8147. Operation.prototype.genCSS = function (context, output) {
  8148. this.operands[0].genCSS(context, output);
  8149. if (this.isSpaced) {
  8150. output.add(' ');
  8151. }
  8152. output.add(this.op);
  8153. if (this.isSpaced) {
  8154. output.add(' ');
  8155. }
  8156. this.operands[1].genCSS(context, output);
  8157. };
  8158. module.exports = Operation;
  8159. },{"../constants":12,"./color":55,"./dimension":62,"./node":76}],78:[function(require,module,exports){
  8160. var Node = require('./node');
  8161. var Paren = function (node) {
  8162. this.value = node;
  8163. };
  8164. Paren.prototype = new Node();
  8165. Paren.prototype.type = 'Paren';
  8166. Paren.prototype.genCSS = function (context, output) {
  8167. output.add('(');
  8168. this.value.genCSS(context, output);
  8169. output.add(')');
  8170. };
  8171. Paren.prototype.eval = function (context) {
  8172. return new Paren(this.value.eval(context));
  8173. };
  8174. module.exports = Paren;
  8175. },{"./node":76}],79:[function(require,module,exports){
  8176. var Node = require('./node'),
  8177. Declaration = require('./declaration');
  8178. var Property = function (name, index, currentFileInfo) {
  8179. this.name = name;
  8180. this._index = index;
  8181. this._fileInfo = currentFileInfo;
  8182. };
  8183. Property.prototype = new Node();
  8184. Property.prototype.type = 'Property';
  8185. Property.prototype.eval = function (context) {
  8186. var property, name = this.name;
  8187. // TODO: shorten this reference
  8188. var mergeRules = context.pluginManager.less.visitors.ToCSSVisitor.prototype._mergeRules;
  8189. if (this.evaluating) {
  8190. throw { type: 'Name',
  8191. message: 'Recursive property reference for ' + name,
  8192. filename: this.fileInfo().filename,
  8193. index: this.getIndex() };
  8194. }
  8195. this.evaluating = true;
  8196. property = this.find(context.frames, function (frame) {
  8197. var v, vArr = frame.property(name);
  8198. if (vArr) {
  8199. for (var i = 0; i < vArr.length; i++) {
  8200. v = vArr[i];
  8201. vArr[i] = new Declaration(v.name,
  8202. v.value,
  8203. v.important,
  8204. v.merge,
  8205. v.index,
  8206. v.currentFileInfo,
  8207. v.inline,
  8208. v.variable
  8209. );
  8210. }
  8211. mergeRules(vArr);
  8212. v = vArr[vArr.length - 1];
  8213. if (v.important) {
  8214. var importantScope = context.importantScope[context.importantScope.length - 1];
  8215. importantScope.important = v.important;
  8216. }
  8217. v = v.value.eval(context);
  8218. return v;
  8219. }
  8220. });
  8221. if (property) {
  8222. this.evaluating = false;
  8223. return property;
  8224. } else {
  8225. throw { type: 'Name',
  8226. message: 'Property \'' + name + '\' is undefined',
  8227. filename: this.currentFileInfo.filename,
  8228. index: this.index };
  8229. }
  8230. };
  8231. Property.prototype.find = function (obj, fun) {
  8232. for (var i = 0, r; i < obj.length; i++) {
  8233. r = fun.call(obj, obj[i]);
  8234. if (r) { return r; }
  8235. }
  8236. return null;
  8237. };
  8238. module.exports = Property;
  8239. },{"./declaration":60,"./node":76}],80:[function(require,module,exports){
  8240. var Node = require('./node'),
  8241. Variable = require('./variable'),
  8242. Property = require('./property');
  8243. var Quoted = function (str, content, escaped, index, currentFileInfo) {
  8244. this.escaped = (escaped == null) ? true : escaped;
  8245. this.value = content || '';
  8246. this.quote = str.charAt(0);
  8247. this._index = index;
  8248. this._fileInfo = currentFileInfo;
  8249. this.variableRegex = /@\{([\w-]+)\}/g;
  8250. this.propRegex = /\$\{([\w-]+)\}/g;
  8251. };
  8252. Quoted.prototype = new Node();
  8253. Quoted.prototype.type = 'Quoted';
  8254. Quoted.prototype.genCSS = function (context, output) {
  8255. if (!this.escaped) {
  8256. output.add(this.quote, this.fileInfo(), this.getIndex());
  8257. }
  8258. output.add(this.value);
  8259. if (!this.escaped) {
  8260. output.add(this.quote);
  8261. }
  8262. };
  8263. Quoted.prototype.containsVariables = function() {
  8264. return this.value.match(this.variableRegex);
  8265. };
  8266. Quoted.prototype.eval = function (context) {
  8267. var that = this, value = this.value;
  8268. var variableReplacement = function (_, name) {
  8269. var v = new Variable('@' + name, that.getIndex(), that.fileInfo()).eval(context, true);
  8270. return (v instanceof Quoted) ? v.value : v.toCSS();
  8271. };
  8272. var propertyReplacement = function (_, name) {
  8273. var v = new Property('$' + name, that.getIndex(), that.fileInfo()).eval(context, true);
  8274. return (v instanceof Quoted) ? v.value : v.toCSS();
  8275. };
  8276. function iterativeReplace(value, regexp, replacementFnc) {
  8277. var evaluatedValue = value;
  8278. do {
  8279. value = evaluatedValue;
  8280. evaluatedValue = value.replace(regexp, replacementFnc);
  8281. } while (value !== evaluatedValue);
  8282. return evaluatedValue;
  8283. }
  8284. value = iterativeReplace(value, this.variableRegex, variableReplacement);
  8285. value = iterativeReplace(value, this.propRegex, propertyReplacement);
  8286. return new Quoted(this.quote + value + this.quote, value, this.escaped, this.getIndex(), this.fileInfo());
  8287. };
  8288. Quoted.prototype.compare = function (other) {
  8289. // when comparing quoted strings allow the quote to differ
  8290. if (other.type === 'Quoted' && !this.escaped && !other.escaped) {
  8291. return Node.numericCompare(this.value, other.value);
  8292. } else {
  8293. return other.toCSS && this.toCSS() === other.toCSS() ? 0 : undefined;
  8294. }
  8295. };
  8296. module.exports = Quoted;
  8297. },{"./node":76,"./property":79,"./variable":88}],81:[function(require,module,exports){
  8298. var Node = require('./node'),
  8299. Declaration = require('./declaration'),
  8300. Keyword = require('./keyword'),
  8301. Comment = require('./comment'),
  8302. Paren = require('./paren'),
  8303. Selector = require('./selector'),
  8304. Element = require('./element'),
  8305. Anonymous = require('./anonymous'),
  8306. contexts = require('../contexts'),
  8307. globalFunctionRegistry = require('../functions/function-registry'),
  8308. defaultFunc = require('../functions/default'),
  8309. getDebugInfo = require('./debug-info'),
  8310. utils = require('../utils');
  8311. var Ruleset = function (selectors, rules, strictImports, visibilityInfo) {
  8312. this.selectors = selectors;
  8313. this.rules = rules;
  8314. this._lookups = {};
  8315. this._variables = null;
  8316. this._properties = null;
  8317. this.strictImports = strictImports;
  8318. this.copyVisibilityInfo(visibilityInfo);
  8319. this.allowRoot = true;
  8320. this.setParent(this.selectors, this);
  8321. this.setParent(this.rules, this);
  8322. };
  8323. Ruleset.prototype = new Node();
  8324. Ruleset.prototype.type = 'Ruleset';
  8325. Ruleset.prototype.isRuleset = true;
  8326. Ruleset.prototype.isRulesetLike = function() { return true; };
  8327. Ruleset.prototype.accept = function (visitor) {
  8328. if (this.paths) {
  8329. this.paths = visitor.visitArray(this.paths, true);
  8330. } else if (this.selectors) {
  8331. this.selectors = visitor.visitArray(this.selectors);
  8332. }
  8333. if (this.rules && this.rules.length) {
  8334. this.rules = visitor.visitArray(this.rules);
  8335. }
  8336. };
  8337. Ruleset.prototype.eval = function (context) {
  8338. var that = this, selectors, selCnt, selector, i, hasVariable, hasOnePassingSelector = false;
  8339. if (this.selectors && (selCnt = this.selectors.length)) {
  8340. selectors = new Array(selCnt);
  8341. defaultFunc.error({
  8342. type: 'Syntax',
  8343. message: 'it is currently only allowed in parametric mixin guards,'
  8344. });
  8345. for (i = 0; i < selCnt; i++) {
  8346. selector = this.selectors[i].eval(context);
  8347. for (var j = 0; j < selector.elements.length; j++) {
  8348. if (selector.elements[j].isVariable) {
  8349. hasVariable = true;
  8350. break;
  8351. }
  8352. }
  8353. selectors[i] = selector;
  8354. if (selector.evaldCondition) {
  8355. hasOnePassingSelector = true;
  8356. }
  8357. }
  8358. if (hasVariable) {
  8359. var toParseSelectors = new Array(selCnt);
  8360. for (i = 0; i < selCnt; i++) {
  8361. selector = selectors[i];
  8362. toParseSelectors[i] = selector.toCSS(context);
  8363. }
  8364. this.parse.parseNode(
  8365. toParseSelectors.join(','),
  8366. ["selectors"],
  8367. selectors[0].getIndex(),
  8368. selectors[0].fileInfo(),
  8369. function(err, result) {
  8370. if (result) {
  8371. selectors = utils.flattenArray(result);
  8372. }
  8373. });
  8374. }
  8375. defaultFunc.reset();
  8376. } else {
  8377. hasOnePassingSelector = true;
  8378. }
  8379. var rules = this.rules ? utils.copyArray(this.rules) : null,
  8380. ruleset = new Ruleset(selectors, rules, this.strictImports, this.visibilityInfo()),
  8381. rule, subRule;
  8382. ruleset.originalRuleset = this;
  8383. ruleset.root = this.root;
  8384. ruleset.firstRoot = this.firstRoot;
  8385. ruleset.allowImports = this.allowImports;
  8386. if (this.debugInfo) {
  8387. ruleset.debugInfo = this.debugInfo;
  8388. }
  8389. if (!hasOnePassingSelector) {
  8390. rules.length = 0;
  8391. }
  8392. // inherit a function registry from the frames stack when possible;
  8393. // otherwise from the global registry
  8394. ruleset.functionRegistry = (function (frames) {
  8395. var i = 0,
  8396. n = frames.length,
  8397. found;
  8398. for ( ; i !== n ; ++i ) {
  8399. found = frames[ i ].functionRegistry;
  8400. if ( found ) { return found; }
  8401. }
  8402. return globalFunctionRegistry;
  8403. }(context.frames)).inherit();
  8404. // push the current ruleset to the frames stack
  8405. var ctxFrames = context.frames;
  8406. ctxFrames.unshift(ruleset);
  8407. // currrent selectors
  8408. var ctxSelectors = context.selectors;
  8409. if (!ctxSelectors) {
  8410. context.selectors = ctxSelectors = [];
  8411. }
  8412. ctxSelectors.unshift(this.selectors);
  8413. // Evaluate imports
  8414. if (ruleset.root || ruleset.allowImports || !ruleset.strictImports) {
  8415. ruleset.evalImports(context);
  8416. }
  8417. // Store the frames around mixin definitions,
  8418. // so they can be evaluated like closures when the time comes.
  8419. var rsRules = ruleset.rules;
  8420. for (i = 0; (rule = rsRules[i]); i++) {
  8421. if (rule.evalFirst) {
  8422. rsRules[i] = rule.eval(context);
  8423. }
  8424. }
  8425. var mediaBlockCount = (context.mediaBlocks && context.mediaBlocks.length) || 0;
  8426. // Evaluate mixin calls.
  8427. for (i = 0; (rule = rsRules[i]); i++) {
  8428. if (rule.type === 'MixinCall') {
  8429. /* jshint loopfunc:true */
  8430. rules = rule.eval(context).filter(function(r) {
  8431. if ((r instanceof Declaration) && r.variable) {
  8432. // do not pollute the scope if the variable is
  8433. // already there. consider returning false here
  8434. // but we need a way to "return" variable from mixins
  8435. return !(ruleset.variable(r.name));
  8436. }
  8437. return true;
  8438. });
  8439. rsRules.splice.apply(rsRules, [i, 1].concat(rules));
  8440. i += rules.length - 1;
  8441. ruleset.resetCache();
  8442. } else if (rule.type === 'VariableCall') {
  8443. /* jshint loopfunc:true */
  8444. rules = rule.eval(context).rules.filter(function(r) {
  8445. if ((r instanceof Declaration) && r.variable) {
  8446. // do not pollute the scope at all
  8447. return false;
  8448. }
  8449. return true;
  8450. });
  8451. rsRules.splice.apply(rsRules, [i, 1].concat(rules));
  8452. i += rules.length - 1;
  8453. ruleset.resetCache();
  8454. }
  8455. }
  8456. // Evaluate everything else
  8457. for (i = 0; (rule = rsRules[i]); i++) {
  8458. if (!rule.evalFirst) {
  8459. rsRules[i] = rule = rule.eval ? rule.eval(context) : rule;
  8460. }
  8461. }
  8462. // Evaluate everything else
  8463. for (i = 0; (rule = rsRules[i]); i++) {
  8464. // for rulesets, check if it is a css guard and can be removed
  8465. if (rule instanceof Ruleset && rule.selectors && rule.selectors.length === 1) {
  8466. // check if it can be folded in (e.g. & where)
  8467. if (rule.selectors[0] && rule.selectors[0].isJustParentSelector()) {
  8468. rsRules.splice(i--, 1);
  8469. for (var j = 0; (subRule = rule.rules[j]); j++) {
  8470. if (subRule instanceof Node) {
  8471. subRule.copyVisibilityInfo(rule.visibilityInfo());
  8472. if (!(subRule instanceof Declaration) || !subRule.variable) {
  8473. rsRules.splice(++i, 0, subRule);
  8474. }
  8475. }
  8476. }
  8477. }
  8478. }
  8479. }
  8480. // Pop the stack
  8481. ctxFrames.shift();
  8482. ctxSelectors.shift();
  8483. if (context.mediaBlocks) {
  8484. for (i = mediaBlockCount; i < context.mediaBlocks.length; i++) {
  8485. context.mediaBlocks[i].bubbleSelectors(selectors);
  8486. }
  8487. }
  8488. return ruleset;
  8489. };
  8490. Ruleset.prototype.evalImports = function(context) {
  8491. var rules = this.rules, i, importRules;
  8492. if (!rules) { return; }
  8493. for (i = 0; i < rules.length; i++) {
  8494. if (rules[i].type === 'Import') {
  8495. importRules = rules[i].eval(context);
  8496. if (importRules && (importRules.length || importRules.length === 0)) {
  8497. rules.splice.apply(rules, [i, 1].concat(importRules));
  8498. i += importRules.length - 1;
  8499. } else {
  8500. rules.splice(i, 1, importRules);
  8501. }
  8502. this.resetCache();
  8503. }
  8504. }
  8505. };
  8506. Ruleset.prototype.makeImportant = function() {
  8507. var result = new Ruleset(this.selectors, this.rules.map(function (r) {
  8508. if (r.makeImportant) {
  8509. return r.makeImportant();
  8510. } else {
  8511. return r;
  8512. }
  8513. }), this.strictImports, this.visibilityInfo());
  8514. return result;
  8515. };
  8516. Ruleset.prototype.matchArgs = function (args) {
  8517. return !args || args.length === 0;
  8518. };
  8519. // lets you call a css selector with a guard
  8520. Ruleset.prototype.matchCondition = function (args, context) {
  8521. var lastSelector = this.selectors[this.selectors.length - 1];
  8522. if (!lastSelector.evaldCondition) {
  8523. return false;
  8524. }
  8525. if (lastSelector.condition &&
  8526. !lastSelector.condition.eval(
  8527. new contexts.Eval(context,
  8528. context.frames))) {
  8529. return false;
  8530. }
  8531. return true;
  8532. };
  8533. Ruleset.prototype.resetCache = function () {
  8534. this._rulesets = null;
  8535. this._variables = null;
  8536. this._properties = null;
  8537. this._lookups = {};
  8538. };
  8539. Ruleset.prototype.variables = function () {
  8540. if (!this._variables) {
  8541. this._variables = !this.rules ? {} : this.rules.reduce(function (hash, r) {
  8542. if (r instanceof Declaration && r.variable === true) {
  8543. hash[r.name] = r;
  8544. }
  8545. // when evaluating variables in an import statement, imports have not been eval'd
  8546. // so we need to go inside import statements.
  8547. // guard against root being a string (in the case of inlined less)
  8548. if (r.type === 'Import' && r.root && r.root.variables) {
  8549. var vars = r.root.variables();
  8550. for (var name in vars) {
  8551. if (vars.hasOwnProperty(name)) {
  8552. hash[name] = r.root.variable(name);
  8553. }
  8554. }
  8555. }
  8556. return hash;
  8557. }, {});
  8558. }
  8559. return this._variables;
  8560. };
  8561. Ruleset.prototype.properties = function () {
  8562. if (!this._properties) {
  8563. this._properties = !this.rules ? {} : this.rules.reduce(function (hash, r) {
  8564. if (r instanceof Declaration && r.variable !== true) {
  8565. var name = (r.name.length === 1) && (r.name[0] instanceof Keyword) ?
  8566. r.name[0].value : r.name;
  8567. // Properties don't overwrite as they can merge
  8568. if (!hash['$' + name]) {
  8569. hash['$' + name] = [ r ];
  8570. }
  8571. else {
  8572. hash['$' + name].push(r);
  8573. }
  8574. }
  8575. return hash;
  8576. }, {});
  8577. }
  8578. return this._properties;
  8579. };
  8580. Ruleset.prototype.variable = function (name) {
  8581. var decl = this.variables()[name];
  8582. if (decl) {
  8583. return this.parseValue(decl);
  8584. }
  8585. };
  8586. Ruleset.prototype.property = function (name) {
  8587. var decl = this.properties()[name];
  8588. if (decl) {
  8589. return this.parseValue(decl);
  8590. }
  8591. };
  8592. Ruleset.prototype.lastDeclaration = function () {
  8593. for (var i = this.rules.length; i > 0; i--) {
  8594. var decl = this.rules[i - 1];
  8595. if (decl instanceof Declaration) {
  8596. return this.parseValue(decl);
  8597. }
  8598. }
  8599. };
  8600. Ruleset.prototype.parseValue = function(toParse) {
  8601. var self = this;
  8602. function transformDeclaration(decl) {
  8603. if (decl.value instanceof Anonymous && !decl.parsed) {
  8604. if (typeof decl.value.value === 'string') {
  8605. this.parse.parseNode(
  8606. decl.value.value,
  8607. ['value', 'important'],
  8608. decl.value.getIndex(),
  8609. decl.fileInfo(),
  8610. function(err, result) {
  8611. if (err) {
  8612. decl.parsed = true;
  8613. }
  8614. if (result) {
  8615. decl.value = result[0];
  8616. decl.important = result[1] || '';
  8617. decl.parsed = true;
  8618. }
  8619. });
  8620. } else {
  8621. decl.parsed = true;
  8622. }
  8623. return decl;
  8624. }
  8625. else {
  8626. return decl;
  8627. }
  8628. }
  8629. if (!Array.isArray(toParse)) {
  8630. return transformDeclaration.call(self, toParse);
  8631. }
  8632. else {
  8633. var nodes = [];
  8634. toParse.forEach(function(n) {
  8635. nodes.push(transformDeclaration.call(self, n));
  8636. });
  8637. return nodes;
  8638. }
  8639. };
  8640. Ruleset.prototype.rulesets = function () {
  8641. if (!this.rules) { return []; }
  8642. var filtRules = [], rules = this.rules,
  8643. i, rule;
  8644. for (i = 0; (rule = rules[i]); i++) {
  8645. if (rule.isRuleset) {
  8646. filtRules.push(rule);
  8647. }
  8648. }
  8649. return filtRules;
  8650. };
  8651. Ruleset.prototype.prependRule = function (rule) {
  8652. var rules = this.rules;
  8653. if (rules) {
  8654. rules.unshift(rule);
  8655. } else {
  8656. this.rules = [ rule ];
  8657. }
  8658. this.setParent(rule, this);
  8659. };
  8660. Ruleset.prototype.find = function (selector, self, filter) {
  8661. self = self || this;
  8662. var rules = [], match, foundMixins,
  8663. key = selector.toCSS();
  8664. if (key in this._lookups) { return this._lookups[key]; }
  8665. this.rulesets().forEach(function (rule) {
  8666. if (rule !== self) {
  8667. for (var j = 0; j < rule.selectors.length; j++) {
  8668. match = selector.match(rule.selectors[j]);
  8669. if (match) {
  8670. if (selector.elements.length > match) {
  8671. if (!filter || filter(rule)) {
  8672. foundMixins = rule.find(new Selector(selector.elements.slice(match)), self, filter);
  8673. for (var i = 0; i < foundMixins.length; ++i) {
  8674. foundMixins[i].path.push(rule);
  8675. }
  8676. Array.prototype.push.apply(rules, foundMixins);
  8677. }
  8678. } else {
  8679. rules.push({ rule: rule, path: []});
  8680. }
  8681. break;
  8682. }
  8683. }
  8684. }
  8685. });
  8686. this._lookups[key] = rules;
  8687. return rules;
  8688. };
  8689. Ruleset.prototype.genCSS = function (context, output) {
  8690. var i, j,
  8691. charsetRuleNodes = [],
  8692. ruleNodes = [],
  8693. debugInfo, // Line number debugging
  8694. rule,
  8695. path;
  8696. context.tabLevel = (context.tabLevel || 0);
  8697. if (!this.root) {
  8698. context.tabLevel++;
  8699. }
  8700. var tabRuleStr = context.compress ? '' : Array(context.tabLevel + 1).join(' '),
  8701. tabSetStr = context.compress ? '' : Array(context.tabLevel).join(' '),
  8702. sep;
  8703. var charsetNodeIndex = 0;
  8704. var importNodeIndex = 0;
  8705. for (i = 0; (rule = this.rules[i]); i++) {
  8706. if (rule instanceof Comment) {
  8707. if (importNodeIndex === i) {
  8708. importNodeIndex++;
  8709. }
  8710. ruleNodes.push(rule);
  8711. } else if (rule.isCharset && rule.isCharset()) {
  8712. ruleNodes.splice(charsetNodeIndex, 0, rule);
  8713. charsetNodeIndex++;
  8714. importNodeIndex++;
  8715. } else if (rule.type === 'Import') {
  8716. ruleNodes.splice(importNodeIndex, 0, rule);
  8717. importNodeIndex++;
  8718. } else {
  8719. ruleNodes.push(rule);
  8720. }
  8721. }
  8722. ruleNodes = charsetRuleNodes.concat(ruleNodes);
  8723. // If this is the root node, we don't render
  8724. // a selector, or {}.
  8725. if (!this.root) {
  8726. debugInfo = getDebugInfo(context, this, tabSetStr);
  8727. if (debugInfo) {
  8728. output.add(debugInfo);
  8729. output.add(tabSetStr);
  8730. }
  8731. var paths = this.paths, pathCnt = paths.length,
  8732. pathSubCnt;
  8733. sep = context.compress ? ',' : (',\n' + tabSetStr);
  8734. for (i = 0; i < pathCnt; i++) {
  8735. path = paths[i];
  8736. if (!(pathSubCnt = path.length)) { continue; }
  8737. if (i > 0) { output.add(sep); }
  8738. context.firstSelector = true;
  8739. path[0].genCSS(context, output);
  8740. context.firstSelector = false;
  8741. for (j = 1; j < pathSubCnt; j++) {
  8742. path[j].genCSS(context, output);
  8743. }
  8744. }
  8745. output.add((context.compress ? '{' : ' {\n') + tabRuleStr);
  8746. }
  8747. // Compile rules and rulesets
  8748. for (i = 0; (rule = ruleNodes[i]); i++) {
  8749. if (i + 1 === ruleNodes.length) {
  8750. context.lastRule = true;
  8751. }
  8752. var currentLastRule = context.lastRule;
  8753. if (rule.isRulesetLike(rule)) {
  8754. context.lastRule = false;
  8755. }
  8756. if (rule.genCSS) {
  8757. rule.genCSS(context, output);
  8758. } else if (rule.value) {
  8759. output.add(rule.value.toString());
  8760. }
  8761. context.lastRule = currentLastRule;
  8762. if (!context.lastRule && rule.isVisible()) {
  8763. output.add(context.compress ? '' : ('\n' + tabRuleStr));
  8764. } else {
  8765. context.lastRule = false;
  8766. }
  8767. }
  8768. if (!this.root) {
  8769. output.add((context.compress ? '}' : '\n' + tabSetStr + '}'));
  8770. context.tabLevel--;
  8771. }
  8772. if (!output.isEmpty() && !context.compress && this.firstRoot) {
  8773. output.add('\n');
  8774. }
  8775. };
  8776. Ruleset.prototype.joinSelectors = function (paths, context, selectors) {
  8777. for (var s = 0; s < selectors.length; s++) {
  8778. this.joinSelector(paths, context, selectors[s]);
  8779. }
  8780. };
  8781. Ruleset.prototype.joinSelector = function (paths, context, selector) {
  8782. function createParenthesis(elementsToPak, originalElement) {
  8783. var replacementParen, j;
  8784. if (elementsToPak.length === 0) {
  8785. replacementParen = new Paren(elementsToPak[0]);
  8786. } else {
  8787. var insideParent = new Array(elementsToPak.length);
  8788. for (j = 0; j < elementsToPak.length; j++) {
  8789. insideParent[j] = new Element(
  8790. null,
  8791. elementsToPak[j],
  8792. originalElement.isVariable,
  8793. originalElement._index,
  8794. originalElement._fileInfo
  8795. );
  8796. }
  8797. replacementParen = new Paren(new Selector(insideParent));
  8798. }
  8799. return replacementParen;
  8800. }
  8801. function createSelector(containedElement, originalElement) {
  8802. var element, selector;
  8803. element = new Element(null, containedElement, originalElement.isVariable, originalElement._index, originalElement._fileInfo);
  8804. selector = new Selector([element]);
  8805. return selector;
  8806. }
  8807. // joins selector path from `beginningPath` with selector path in `addPath`
  8808. // `replacedElement` contains element that is being replaced by `addPath`
  8809. // returns concatenated path
  8810. function addReplacementIntoPath(beginningPath, addPath, replacedElement, originalSelector) {
  8811. var newSelectorPath, lastSelector, newJoinedSelector;
  8812. // our new selector path
  8813. newSelectorPath = [];
  8814. // construct the joined selector - if & is the first thing this will be empty,
  8815. // if not newJoinedSelector will be the last set of elements in the selector
  8816. if (beginningPath.length > 0) {
  8817. newSelectorPath = utils.copyArray(beginningPath);
  8818. lastSelector = newSelectorPath.pop();
  8819. newJoinedSelector = originalSelector.createDerived(utils.copyArray(lastSelector.elements));
  8820. }
  8821. else {
  8822. newJoinedSelector = originalSelector.createDerived([]);
  8823. }
  8824. if (addPath.length > 0) {
  8825. // /deep/ is a CSS4 selector - (removed, so should deprecate)
  8826. // that is valid without anything in front of it
  8827. // so if the & does not have a combinator that is "" or " " then
  8828. // and there is a combinator on the parent, then grab that.
  8829. // this also allows + a { & .b { .a & { ... though not sure why you would want to do that
  8830. var combinator = replacedElement.combinator, parentEl = addPath[0].elements[0];
  8831. if (combinator.emptyOrWhitespace && !parentEl.combinator.emptyOrWhitespace) {
  8832. combinator = parentEl.combinator;
  8833. }
  8834. // join the elements so far with the first part of the parent
  8835. newJoinedSelector.elements.push(new Element(
  8836. combinator,
  8837. parentEl.value,
  8838. replacedElement.isVariable,
  8839. replacedElement._index,
  8840. replacedElement._fileInfo
  8841. ));
  8842. newJoinedSelector.elements = newJoinedSelector.elements.concat(addPath[0].elements.slice(1));
  8843. }
  8844. // now add the joined selector - but only if it is not empty
  8845. if (newJoinedSelector.elements.length !== 0) {
  8846. newSelectorPath.push(newJoinedSelector);
  8847. }
  8848. // put together the parent selectors after the join (e.g. the rest of the parent)
  8849. if (addPath.length > 1) {
  8850. var restOfPath = addPath.slice(1);
  8851. restOfPath = restOfPath.map(function (selector) {
  8852. return selector.createDerived(selector.elements, []);
  8853. });
  8854. newSelectorPath = newSelectorPath.concat(restOfPath);
  8855. }
  8856. return newSelectorPath;
  8857. }
  8858. // joins selector path from `beginningPath` with every selector path in `addPaths` array
  8859. // `replacedElement` contains element that is being replaced by `addPath`
  8860. // returns array with all concatenated paths
  8861. function addAllReplacementsIntoPath( beginningPath, addPaths, replacedElement, originalSelector, result) {
  8862. var j;
  8863. for (j = 0; j < beginningPath.length; j++) {
  8864. var newSelectorPath = addReplacementIntoPath(beginningPath[j], addPaths, replacedElement, originalSelector);
  8865. result.push(newSelectorPath);
  8866. }
  8867. return result;
  8868. }
  8869. function mergeElementsOnToSelectors(elements, selectors) {
  8870. var i, sel;
  8871. if (elements.length === 0) {
  8872. return ;
  8873. }
  8874. if (selectors.length === 0) {
  8875. selectors.push([ new Selector(elements) ]);
  8876. return;
  8877. }
  8878. for (i = 0; (sel = selectors[i]); i++) {
  8879. // if the previous thing in sel is a parent this needs to join on to it
  8880. if (sel.length > 0) {
  8881. sel[sel.length - 1] = sel[sel.length - 1].createDerived(sel[sel.length - 1].elements.concat(elements));
  8882. }
  8883. else {
  8884. sel.push(new Selector(elements));
  8885. }
  8886. }
  8887. }
  8888. // replace all parent selectors inside `inSelector` by content of `context` array
  8889. // resulting selectors are returned inside `paths` array
  8890. // returns true if `inSelector` contained at least one parent selector
  8891. function replaceParentSelector(paths, context, inSelector) {
  8892. // The paths are [[Selector]]
  8893. // The first list is a list of comma separated selectors
  8894. // The inner list is a list of inheritance separated selectors
  8895. // e.g.
  8896. // .a, .b {
  8897. // .c {
  8898. // }
  8899. // }
  8900. // == [[.a] [.c]] [[.b] [.c]]
  8901. //
  8902. var i, j, k, currentElements, newSelectors, selectorsMultiplied, sel, el, hadParentSelector = false, length, lastSelector;
  8903. function findNestedSelector(element) {
  8904. var maybeSelector;
  8905. if (!(element.value instanceof Paren)) {
  8906. return null;
  8907. }
  8908. maybeSelector = element.value.value;
  8909. if (!(maybeSelector instanceof Selector)) {
  8910. return null;
  8911. }
  8912. return maybeSelector;
  8913. }
  8914. // the elements from the current selector so far
  8915. currentElements = [];
  8916. // the current list of new selectors to add to the path.
  8917. // We will build it up. We initiate it with one empty selector as we "multiply" the new selectors
  8918. // by the parents
  8919. newSelectors = [
  8920. []
  8921. ];
  8922. for (i = 0; (el = inSelector.elements[i]); i++) {
  8923. // non parent reference elements just get added
  8924. if (el.value !== '&') {
  8925. var nestedSelector = findNestedSelector(el);
  8926. if (nestedSelector != null) {
  8927. // merge the current list of non parent selector elements
  8928. // on to the current list of selectors to add
  8929. mergeElementsOnToSelectors(currentElements, newSelectors);
  8930. var nestedPaths = [], replaced, replacedNewSelectors = [];
  8931. replaced = replaceParentSelector(nestedPaths, context, nestedSelector);
  8932. hadParentSelector = hadParentSelector || replaced;
  8933. // the nestedPaths array should have only one member - replaceParentSelector does not multiply selectors
  8934. for (k = 0; k < nestedPaths.length; k++) {
  8935. var replacementSelector = createSelector(createParenthesis(nestedPaths[k], el), el);
  8936. addAllReplacementsIntoPath(newSelectors, [replacementSelector], el, inSelector, replacedNewSelectors);
  8937. }
  8938. newSelectors = replacedNewSelectors;
  8939. currentElements = [];
  8940. } else {
  8941. currentElements.push(el);
  8942. }
  8943. } else {
  8944. hadParentSelector = true;
  8945. // the new list of selectors to add
  8946. selectorsMultiplied = [];
  8947. // merge the current list of non parent selector elements
  8948. // on to the current list of selectors to add
  8949. mergeElementsOnToSelectors(currentElements, newSelectors);
  8950. // loop through our current selectors
  8951. for (j = 0; j < newSelectors.length; j++) {
  8952. sel = newSelectors[j];
  8953. // if we don't have any parent paths, the & might be in a mixin so that it can be used
  8954. // whether there are parents or not
  8955. if (context.length === 0) {
  8956. // the combinator used on el should now be applied to the next element instead so that
  8957. // it is not lost
  8958. if (sel.length > 0) {
  8959. sel[0].elements.push(new Element(el.combinator, '', el.isVariable, el._index, el._fileInfo));
  8960. }
  8961. selectorsMultiplied.push(sel);
  8962. }
  8963. else {
  8964. // and the parent selectors
  8965. for (k = 0; k < context.length; k++) {
  8966. // We need to put the current selectors
  8967. // then join the last selector's elements on to the parents selectors
  8968. var newSelectorPath = addReplacementIntoPath(sel, context[k], el, inSelector);
  8969. // add that to our new set of selectors
  8970. selectorsMultiplied.push(newSelectorPath);
  8971. }
  8972. }
  8973. }
  8974. // our new selectors has been multiplied, so reset the state
  8975. newSelectors = selectorsMultiplied;
  8976. currentElements = [];
  8977. }
  8978. }
  8979. // if we have any elements left over (e.g. .a& .b == .b)
  8980. // add them on to all the current selectors
  8981. mergeElementsOnToSelectors(currentElements, newSelectors);
  8982. for (i = 0; i < newSelectors.length; i++) {
  8983. length = newSelectors[i].length;
  8984. if (length > 0) {
  8985. paths.push(newSelectors[i]);
  8986. lastSelector = newSelectors[i][length - 1];
  8987. newSelectors[i][length - 1] = lastSelector.createDerived(lastSelector.elements, inSelector.extendList);
  8988. }
  8989. }
  8990. return hadParentSelector;
  8991. }
  8992. function deriveSelector(visibilityInfo, deriveFrom) {
  8993. var newSelector = deriveFrom.createDerived(deriveFrom.elements, deriveFrom.extendList, deriveFrom.evaldCondition);
  8994. newSelector.copyVisibilityInfo(visibilityInfo);
  8995. return newSelector;
  8996. }
  8997. // joinSelector code follows
  8998. var i, newPaths, hadParentSelector;
  8999. newPaths = [];
  9000. hadParentSelector = replaceParentSelector(newPaths, context, selector);
  9001. if (!hadParentSelector) {
  9002. if (context.length > 0) {
  9003. newPaths = [];
  9004. for (i = 0; i < context.length; i++) {
  9005. var concatenated = context[i].map(deriveSelector.bind(this, selector.visibilityInfo()));
  9006. concatenated.push(selector);
  9007. newPaths.push(concatenated);
  9008. }
  9009. }
  9010. else {
  9011. newPaths = [[selector]];
  9012. }
  9013. }
  9014. for (i = 0; i < newPaths.length; i++) {
  9015. paths.push(newPaths[i]);
  9016. }
  9017. };
  9018. module.exports = Ruleset;
  9019. },{"../contexts":13,"../functions/default":25,"../functions/function-registry":27,"../utils":89,"./anonymous":50,"./comment":57,"./debug-info":59,"./declaration":60,"./element":63,"./keyword":70,"./node":76,"./paren":78,"./selector":82}],82:[function(require,module,exports){
  9020. var Node = require('./node'),
  9021. Element = require('./element'),
  9022. LessError = require('../less-error');
  9023. var Selector = function (elements, extendList, condition, index, currentFileInfo, visibilityInfo) {
  9024. this.extendList = extendList;
  9025. this.condition = condition;
  9026. this.evaldCondition = !condition;
  9027. this._index = index;
  9028. this._fileInfo = currentFileInfo;
  9029. this.elements = this.getElements(elements);
  9030. this.mixinElements_ = undefined;
  9031. this.copyVisibilityInfo(visibilityInfo);
  9032. this.setParent(this.elements, this);
  9033. };
  9034. Selector.prototype = new Node();
  9035. Selector.prototype.type = 'Selector';
  9036. Selector.prototype.accept = function (visitor) {
  9037. if (this.elements) {
  9038. this.elements = visitor.visitArray(this.elements);
  9039. }
  9040. if (this.extendList) {
  9041. this.extendList = visitor.visitArray(this.extendList);
  9042. }
  9043. if (this.condition) {
  9044. this.condition = visitor.visit(this.condition);
  9045. }
  9046. };
  9047. Selector.prototype.createDerived = function(elements, extendList, evaldCondition) {
  9048. elements = this.getElements(elements);
  9049. var newSelector = new Selector(elements, extendList || this.extendList,
  9050. null, this.getIndex(), this.fileInfo(), this.visibilityInfo());
  9051. newSelector.evaldCondition = (evaldCondition != null) ? evaldCondition : this.evaldCondition;
  9052. newSelector.mediaEmpty = this.mediaEmpty;
  9053. return newSelector;
  9054. };
  9055. Selector.prototype.getElements = function(els) {
  9056. if (!els) {
  9057. return [new Element('', '&', false, this._index, this._fileInfo)];
  9058. }
  9059. if (typeof els === 'string') {
  9060. this.parse.parseNode(
  9061. els,
  9062. ['selector'],
  9063. this._index,
  9064. this._fileInfo,
  9065. function(err, result) {
  9066. if (err) {
  9067. throw new LessError({
  9068. index: err.index,
  9069. message: err.message
  9070. }, this.parse.imports, this._fileInfo.filename);
  9071. }
  9072. els = result[0].elements;
  9073. });
  9074. }
  9075. return els;
  9076. };
  9077. Selector.prototype.createEmptySelectors = function() {
  9078. var el = new Element('', '&', false, this._index, this._fileInfo),
  9079. sels = [new Selector([el], null, null, this._index, this._fileInfo)];
  9080. sels[0].mediaEmpty = true;
  9081. return sels;
  9082. };
  9083. Selector.prototype.match = function (other) {
  9084. var elements = this.elements,
  9085. len = elements.length,
  9086. olen, i;
  9087. other = other.mixinElements();
  9088. olen = other.length;
  9089. if (olen === 0 || len < olen) {
  9090. return 0;
  9091. } else {
  9092. for (i = 0; i < olen; i++) {
  9093. if (elements[i].value !== other[i]) {
  9094. return 0;
  9095. }
  9096. }
  9097. }
  9098. return olen; // return number of matched elements
  9099. };
  9100. Selector.prototype.mixinElements = function() {
  9101. if (this.mixinElements_) {
  9102. return this.mixinElements_;
  9103. }
  9104. var elements = this.elements.map( function(v) {
  9105. return v.combinator.value + (v.value.value || v.value);
  9106. }).join('').match(/[,&#\*\.\w-]([\w-]|(\\.))*/g);
  9107. if (elements) {
  9108. if (elements[0] === '&') {
  9109. elements.shift();
  9110. }
  9111. } else {
  9112. elements = [];
  9113. }
  9114. return (this.mixinElements_ = elements);
  9115. };
  9116. Selector.prototype.isJustParentSelector = function() {
  9117. return !this.mediaEmpty &&
  9118. this.elements.length === 1 &&
  9119. this.elements[0].value === '&' &&
  9120. (this.elements[0].combinator.value === ' ' || this.elements[0].combinator.value === '');
  9121. };
  9122. Selector.prototype.eval = function (context) {
  9123. var evaldCondition = this.condition && this.condition.eval(context),
  9124. elements = this.elements, extendList = this.extendList;
  9125. elements = elements && elements.map(function (e) { return e.eval(context); });
  9126. extendList = extendList && extendList.map(function(extend) { return extend.eval(context); });
  9127. return this.createDerived(elements, extendList, evaldCondition);
  9128. };
  9129. Selector.prototype.genCSS = function (context, output) {
  9130. var i, element;
  9131. if ((!context || !context.firstSelector) && this.elements[0].combinator.value === '') {
  9132. output.add(' ', this.fileInfo(), this.getIndex());
  9133. }
  9134. for (i = 0; i < this.elements.length; i++) {
  9135. element = this.elements[i];
  9136. element.genCSS(context, output);
  9137. }
  9138. };
  9139. Selector.prototype.getIsOutput = function() {
  9140. return this.evaldCondition;
  9141. };
  9142. module.exports = Selector;
  9143. },{"../less-error":38,"./element":63,"./node":76}],83:[function(require,module,exports){
  9144. var Node = require('./node');
  9145. var UnicodeDescriptor = function (value) {
  9146. this.value = value;
  9147. };
  9148. UnicodeDescriptor.prototype = new Node();
  9149. UnicodeDescriptor.prototype.type = 'UnicodeDescriptor';
  9150. module.exports = UnicodeDescriptor;
  9151. },{"./node":76}],84:[function(require,module,exports){
  9152. var Node = require('./node'),
  9153. unitConversions = require('../data/unit-conversions'),
  9154. utils = require('../utils');
  9155. var Unit = function (numerator, denominator, backupUnit) {
  9156. this.numerator = numerator ? utils.copyArray(numerator).sort() : [];
  9157. this.denominator = denominator ? utils.copyArray(denominator).sort() : [];
  9158. if (backupUnit) {
  9159. this.backupUnit = backupUnit;
  9160. } else if (numerator && numerator.length) {
  9161. this.backupUnit = numerator[0];
  9162. }
  9163. };
  9164. Unit.prototype = new Node();
  9165. Unit.prototype.type = 'Unit';
  9166. Unit.prototype.clone = function () {
  9167. return new Unit(utils.copyArray(this.numerator), utils.copyArray(this.denominator), this.backupUnit);
  9168. };
  9169. Unit.prototype.genCSS = function (context, output) {
  9170. // Dimension checks the unit is singular and throws an error if in strict math mode.
  9171. var strictUnits = context && context.strictUnits;
  9172. if (this.numerator.length === 1) {
  9173. output.add(this.numerator[0]); // the ideal situation
  9174. } else if (!strictUnits && this.backupUnit) {
  9175. output.add(this.backupUnit);
  9176. } else if (!strictUnits && this.denominator.length) {
  9177. output.add(this.denominator[0]);
  9178. }
  9179. };
  9180. Unit.prototype.toString = function () {
  9181. var i, returnStr = this.numerator.join('*');
  9182. for (i = 0; i < this.denominator.length; i++) {
  9183. returnStr += '/' + this.denominator[i];
  9184. }
  9185. return returnStr;
  9186. };
  9187. Unit.prototype.compare = function (other) {
  9188. return this.is(other.toString()) ? 0 : undefined;
  9189. };
  9190. Unit.prototype.is = function (unitString) {
  9191. return this.toString().toUpperCase() === unitString.toUpperCase();
  9192. };
  9193. Unit.prototype.isLength = function () {
  9194. return RegExp('^(px|em|ex|ch|rem|in|cm|mm|pc|pt|ex|vw|vh|vmin|vmax)$', 'gi').test(this.toCSS());
  9195. };
  9196. Unit.prototype.isEmpty = function () {
  9197. return this.numerator.length === 0 && this.denominator.length === 0;
  9198. };
  9199. Unit.prototype.isSingular = function() {
  9200. return this.numerator.length <= 1 && this.denominator.length === 0;
  9201. };
  9202. Unit.prototype.map = function(callback) {
  9203. var i;
  9204. for (i = 0; i < this.numerator.length; i++) {
  9205. this.numerator[i] = callback(this.numerator[i], false);
  9206. }
  9207. for (i = 0; i < this.denominator.length; i++) {
  9208. this.denominator[i] = callback(this.denominator[i], true);
  9209. }
  9210. };
  9211. Unit.prototype.usedUnits = function() {
  9212. var group, result = {}, mapUnit, groupName;
  9213. mapUnit = function (atomicUnit) {
  9214. /* jshint loopfunc:true */
  9215. if (group.hasOwnProperty(atomicUnit) && !result[groupName]) {
  9216. result[groupName] = atomicUnit;
  9217. }
  9218. return atomicUnit;
  9219. };
  9220. for (groupName in unitConversions) {
  9221. if (unitConversions.hasOwnProperty(groupName)) {
  9222. group = unitConversions[groupName];
  9223. this.map(mapUnit);
  9224. }
  9225. }
  9226. return result;
  9227. };
  9228. Unit.prototype.cancel = function () {
  9229. var counter = {}, atomicUnit, i;
  9230. for (i = 0; i < this.numerator.length; i++) {
  9231. atomicUnit = this.numerator[i];
  9232. counter[atomicUnit] = (counter[atomicUnit] || 0) + 1;
  9233. }
  9234. for (i = 0; i < this.denominator.length; i++) {
  9235. atomicUnit = this.denominator[i];
  9236. counter[atomicUnit] = (counter[atomicUnit] || 0) - 1;
  9237. }
  9238. this.numerator = [];
  9239. this.denominator = [];
  9240. for (atomicUnit in counter) {
  9241. if (counter.hasOwnProperty(atomicUnit)) {
  9242. var count = counter[atomicUnit];
  9243. if (count > 0) {
  9244. for (i = 0; i < count; i++) {
  9245. this.numerator.push(atomicUnit);
  9246. }
  9247. } else if (count < 0) {
  9248. for (i = 0; i < -count; i++) {
  9249. this.denominator.push(atomicUnit);
  9250. }
  9251. }
  9252. }
  9253. }
  9254. this.numerator.sort();
  9255. this.denominator.sort();
  9256. };
  9257. module.exports = Unit;
  9258. },{"../data/unit-conversions":16,"../utils":89,"./node":76}],85:[function(require,module,exports){
  9259. var Node = require('./node');
  9260. var URL = function (val, index, currentFileInfo, isEvald) {
  9261. this.value = val;
  9262. this._index = index;
  9263. this._fileInfo = currentFileInfo;
  9264. this.isEvald = isEvald;
  9265. };
  9266. URL.prototype = new Node();
  9267. URL.prototype.type = 'Url';
  9268. URL.prototype.accept = function (visitor) {
  9269. this.value = visitor.visit(this.value);
  9270. };
  9271. URL.prototype.genCSS = function (context, output) {
  9272. output.add('url(');
  9273. this.value.genCSS(context, output);
  9274. output.add(')');
  9275. };
  9276. URL.prototype.eval = function (context) {
  9277. var val = this.value.eval(context),
  9278. rootpath;
  9279. if (!this.isEvald) {
  9280. // Add the rootpath if the URL requires a rewrite
  9281. rootpath = this.fileInfo() && this.fileInfo().rootpath;
  9282. if (typeof rootpath === 'string' &&
  9283. typeof val.value === 'string' &&
  9284. context.pathRequiresRewrite(val.value)) {
  9285. if (!val.quote) {
  9286. rootpath = escapePath(rootpath);
  9287. }
  9288. val.value = context.rewritePath(val.value, rootpath);
  9289. } else {
  9290. val.value = context.normalizePath(val.value);
  9291. }
  9292. // Add url args if enabled
  9293. if (context.urlArgs) {
  9294. if (!val.value.match(/^\s*data:/)) {
  9295. var delimiter = val.value.indexOf('?') === -1 ? '?' : '&';
  9296. var urlArgs = delimiter + context.urlArgs;
  9297. if (val.value.indexOf('#') !== -1) {
  9298. val.value = val.value.replace('#', urlArgs + '#');
  9299. } else {
  9300. val.value += urlArgs;
  9301. }
  9302. }
  9303. }
  9304. }
  9305. return new URL(val, this.getIndex(), this.fileInfo(), true);
  9306. };
  9307. function escapePath(path) {
  9308. return path.replace(/[\(\)'"\s]/g, function(match) { return '\\' + match; });
  9309. }
  9310. module.exports = URL;
  9311. },{"./node":76}],86:[function(require,module,exports){
  9312. var Node = require('./node');
  9313. var Value = function (value) {
  9314. if (!value) {
  9315. throw new Error('Value requires an array argument');
  9316. }
  9317. if (!Array.isArray(value)) {
  9318. this.value = [ value ];
  9319. }
  9320. else {
  9321. this.value = value;
  9322. }
  9323. };
  9324. Value.prototype = new Node();
  9325. Value.prototype.type = 'Value';
  9326. Value.prototype.accept = function (visitor) {
  9327. if (this.value) {
  9328. this.value = visitor.visitArray(this.value);
  9329. }
  9330. };
  9331. Value.prototype.eval = function (context) {
  9332. if (this.value.length === 1) {
  9333. return this.value[0].eval(context);
  9334. } else {
  9335. return new Value(this.value.map(function (v) {
  9336. return v.eval(context);
  9337. }));
  9338. }
  9339. };
  9340. Value.prototype.genCSS = function (context, output) {
  9341. var i;
  9342. for (i = 0; i < this.value.length; i++) {
  9343. this.value[i].genCSS(context, output);
  9344. if (i + 1 < this.value.length) {
  9345. output.add((context && context.compress) ? ',' : ', ');
  9346. }
  9347. }
  9348. };
  9349. module.exports = Value;
  9350. },{"./node":76}],87:[function(require,module,exports){
  9351. var Node = require('./node'),
  9352. Variable = require('./variable'),
  9353. Ruleset = require('./ruleset'),
  9354. DetachedRuleset = require('./detached-ruleset'),
  9355. LessError = require('../less-error');
  9356. var VariableCall = function (variable, index, currentFileInfo) {
  9357. this.variable = variable;
  9358. this._index = index;
  9359. this._fileInfo = currentFileInfo;
  9360. this.allowRoot = true;
  9361. };
  9362. VariableCall.prototype = new Node();
  9363. VariableCall.prototype.type = 'VariableCall';
  9364. VariableCall.prototype.eval = function (context) {
  9365. var rules, detachedRuleset = new Variable(this.variable, this.getIndex(), this.fileInfo()).eval(context),
  9366. error = new LessError({message: 'Could not evaluate variable call ' + this.variable});
  9367. if (!detachedRuleset.ruleset) {
  9368. if (detachedRuleset.rules) {
  9369. rules = detachedRuleset;
  9370. }
  9371. else if (Array.isArray(detachedRuleset)) {
  9372. rules = new Ruleset('', detachedRuleset);
  9373. }
  9374. else if (Array.isArray(detachedRuleset.value)) {
  9375. rules = new Ruleset('', detachedRuleset.value);
  9376. }
  9377. else {
  9378. throw error;
  9379. }
  9380. detachedRuleset = new DetachedRuleset(rules);
  9381. }
  9382. if (detachedRuleset.ruleset) {
  9383. return detachedRuleset.callEval(context);
  9384. }
  9385. throw error;
  9386. };
  9387. module.exports = VariableCall;
  9388. },{"../less-error":38,"./detached-ruleset":61,"./node":76,"./ruleset":81,"./variable":88}],88:[function(require,module,exports){
  9389. var Node = require('./node'),
  9390. Call = require('./call');
  9391. var Variable = function (name, index, currentFileInfo) {
  9392. this.name = name;
  9393. this._index = index;
  9394. this._fileInfo = currentFileInfo;
  9395. };
  9396. Variable.prototype = new Node();
  9397. Variable.prototype.type = 'Variable';
  9398. Variable.prototype.eval = function (context) {
  9399. var variable, name = this.name;
  9400. if (name.indexOf('@@') === 0) {
  9401. name = '@' + new Variable(name.slice(1), this.getIndex(), this.fileInfo()).eval(context).value;
  9402. }
  9403. if (this.evaluating) {
  9404. throw { type: 'Name',
  9405. message: 'Recursive variable definition for ' + name,
  9406. filename: this.fileInfo().filename,
  9407. index: this.getIndex() };
  9408. }
  9409. this.evaluating = true;
  9410. variable = this.find(context.frames, function (frame) {
  9411. var v = frame.variable(name);
  9412. if (v) {
  9413. if (v.important) {
  9414. var importantScope = context.importantScope[context.importantScope.length - 1];
  9415. importantScope.important = v.important;
  9416. }
  9417. // If in calc, wrap vars in a function call to cascade evaluate args first
  9418. if (context.inCalc) {
  9419. return (new Call('_SELF', [v.value])).eval(context);
  9420. }
  9421. else {
  9422. return v.value.eval(context);
  9423. }
  9424. }
  9425. });
  9426. if (variable) {
  9427. this.evaluating = false;
  9428. return variable;
  9429. } else {
  9430. throw { type: 'Name',
  9431. message: 'variable ' + name + ' is undefined',
  9432. filename: this.fileInfo().filename,
  9433. index: this.getIndex() };
  9434. }
  9435. };
  9436. Variable.prototype.find = function (obj, fun) {
  9437. for (var i = 0, r; i < obj.length; i++) {
  9438. r = fun.call(obj, obj[i]);
  9439. if (r) { return r; }
  9440. }
  9441. return null;
  9442. };
  9443. module.exports = Variable;
  9444. },{"./call":54,"./node":76}],89:[function(require,module,exports){
  9445. /* jshint proto: true */
  9446. var Constants = require('./constants');
  9447. var clone = require('clone');
  9448. var utils = {
  9449. getLocation: function(index, inputStream) {
  9450. var n = index + 1,
  9451. line = null,
  9452. column = -1;
  9453. while (--n >= 0 && inputStream.charAt(n) !== '\n') {
  9454. column++;
  9455. }
  9456. if (typeof index === 'number') {
  9457. line = (inputStream.slice(0, index).match(/\n/g) || '').length;
  9458. }
  9459. return {
  9460. line: line,
  9461. column: column
  9462. };
  9463. },
  9464. copyArray: function(arr) {
  9465. var i, length = arr.length,
  9466. copy = new Array(length);
  9467. for (i = 0; i < length; i++) {
  9468. copy[i] = arr[i];
  9469. }
  9470. return copy;
  9471. },
  9472. clone: function (obj) {
  9473. var cloned = {};
  9474. for (var prop in obj) {
  9475. if (obj.hasOwnProperty(prop)) {
  9476. cloned[prop] = obj[prop];
  9477. }
  9478. }
  9479. return cloned;
  9480. },
  9481. copyOptions: function(obj1, obj2) {
  9482. if (obj2 && obj2._defaults) {
  9483. return obj2;
  9484. }
  9485. var opts = utils.defaults(obj1, obj2);
  9486. if (opts.strictMath) {
  9487. opts.math = Constants.Math.STRICT_LEGACY;
  9488. }
  9489. // Back compat with changed relativeUrls option
  9490. if (opts.relativeUrls) {
  9491. opts.rewriteUrls = Constants.RewriteUrls.ALL;
  9492. }
  9493. if (typeof opts.math === 'string') {
  9494. switch (opts.math.toLowerCase()) {
  9495. case 'always':
  9496. opts.math = Constants.Math.ALWAYS;
  9497. break;
  9498. case 'parens-division':
  9499. opts.math = Constants.Math.PARENS_DIVISION;
  9500. break;
  9501. case 'strict':
  9502. case 'parens':
  9503. opts.math = Constants.Math.PARENS;
  9504. break;
  9505. case 'strict-legacy':
  9506. opts.math = Constants.Math.STRICT_LEGACY;
  9507. }
  9508. }
  9509. if (typeof opts.rewriteUrls === 'string') {
  9510. switch (opts.rewriteUrls.toLowerCase()) {
  9511. case 'off':
  9512. opts.rewriteUrls = Constants.RewriteUrls.OFF;
  9513. break;
  9514. case 'local':
  9515. opts.rewriteUrls = Constants.RewriteUrls.LOCAL;
  9516. break;
  9517. case 'all':
  9518. opts.rewriteUrls = Constants.RewriteUrls.ALL;
  9519. break;
  9520. }
  9521. }
  9522. return opts;
  9523. },
  9524. defaults: function(obj1, obj2) {
  9525. var newObj = obj2 || {};
  9526. if (!obj2._defaults) {
  9527. newObj = {};
  9528. var defaults = clone(obj1);
  9529. newObj._defaults = defaults;
  9530. var cloned = obj2 ? clone(obj2) : {};
  9531. Object.assign(newObj, defaults, cloned);
  9532. }
  9533. return newObj;
  9534. },
  9535. merge: function(obj1, obj2) {
  9536. for (var prop in obj2) {
  9537. if (obj2.hasOwnProperty(prop)) {
  9538. obj1[prop] = obj2[prop];
  9539. }
  9540. }
  9541. return obj1;
  9542. },
  9543. flattenArray: function(arr, result) {
  9544. result = result || [];
  9545. for (var i = 0, length = arr.length; i < length; i++) {
  9546. var value = arr[i];
  9547. if (Array.isArray(value)) {
  9548. utils.flattenArray(value, result);
  9549. } else {
  9550. if (value !== undefined) {
  9551. result.push(value);
  9552. }
  9553. }
  9554. }
  9555. return result;
  9556. }
  9557. };
  9558. module.exports = utils;
  9559. },{"./constants":12,"clone":100}],90:[function(require,module,exports){
  9560. var tree = require('../tree'),
  9561. Visitor = require('./visitor'),
  9562. logger = require('../logger'),
  9563. utils = require('../utils');
  9564. /* jshint loopfunc:true */
  9565. var ExtendFinderVisitor = function() {
  9566. this._visitor = new Visitor(this);
  9567. this.contexts = [];
  9568. this.allExtendsStack = [[]];
  9569. };
  9570. ExtendFinderVisitor.prototype = {
  9571. run: function (root) {
  9572. root = this._visitor.visit(root);
  9573. root.allExtends = this.allExtendsStack[0];
  9574. return root;
  9575. },
  9576. visitDeclaration: function (declNode, visitArgs) {
  9577. visitArgs.visitDeeper = false;
  9578. },
  9579. visitMixinDefinition: function (mixinDefinitionNode, visitArgs) {
  9580. visitArgs.visitDeeper = false;
  9581. },
  9582. visitRuleset: function (rulesetNode, visitArgs) {
  9583. if (rulesetNode.root) {
  9584. return;
  9585. }
  9586. var i, j, extend, allSelectorsExtendList = [], extendList;
  9587. // get &:extend(.a); rules which apply to all selectors in this ruleset
  9588. var rules = rulesetNode.rules, ruleCnt = rules ? rules.length : 0;
  9589. for (i = 0; i < ruleCnt; i++) {
  9590. if (rulesetNode.rules[i] instanceof tree.Extend) {
  9591. allSelectorsExtendList.push(rules[i]);
  9592. rulesetNode.extendOnEveryPath = true;
  9593. }
  9594. }
  9595. // now find every selector and apply the extends that apply to all extends
  9596. // and the ones which apply to an individual extend
  9597. var paths = rulesetNode.paths;
  9598. for (i = 0; i < paths.length; i++) {
  9599. var selectorPath = paths[i],
  9600. selector = selectorPath[selectorPath.length - 1],
  9601. selExtendList = selector.extendList;
  9602. extendList = selExtendList ? utils.copyArray(selExtendList).concat(allSelectorsExtendList)
  9603. : allSelectorsExtendList;
  9604. if (extendList) {
  9605. extendList = extendList.map(function(allSelectorsExtend) {
  9606. return allSelectorsExtend.clone();
  9607. });
  9608. }
  9609. for (j = 0; j < extendList.length; j++) {
  9610. this.foundExtends = true;
  9611. extend = extendList[j];
  9612. extend.findSelfSelectors(selectorPath);
  9613. extend.ruleset = rulesetNode;
  9614. if (j === 0) { extend.firstExtendOnThisSelectorPath = true; }
  9615. this.allExtendsStack[this.allExtendsStack.length - 1].push(extend);
  9616. }
  9617. }
  9618. this.contexts.push(rulesetNode.selectors);
  9619. },
  9620. visitRulesetOut: function (rulesetNode) {
  9621. if (!rulesetNode.root) {
  9622. this.contexts.length = this.contexts.length - 1;
  9623. }
  9624. },
  9625. visitMedia: function (mediaNode, visitArgs) {
  9626. mediaNode.allExtends = [];
  9627. this.allExtendsStack.push(mediaNode.allExtends);
  9628. },
  9629. visitMediaOut: function (mediaNode) {
  9630. this.allExtendsStack.length = this.allExtendsStack.length - 1;
  9631. },
  9632. visitAtRule: function (atRuleNode, visitArgs) {
  9633. atRuleNode.allExtends = [];
  9634. this.allExtendsStack.push(atRuleNode.allExtends);
  9635. },
  9636. visitAtRuleOut: function (atRuleNode) {
  9637. this.allExtendsStack.length = this.allExtendsStack.length - 1;
  9638. }
  9639. };
  9640. var ProcessExtendsVisitor = function() {
  9641. this._visitor = new Visitor(this);
  9642. };
  9643. ProcessExtendsVisitor.prototype = {
  9644. run: function(root) {
  9645. var extendFinder = new ExtendFinderVisitor();
  9646. this.extendIndices = {};
  9647. extendFinder.run(root);
  9648. if (!extendFinder.foundExtends) { return root; }
  9649. root.allExtends = root.allExtends.concat(this.doExtendChaining(root.allExtends, root.allExtends));
  9650. this.allExtendsStack = [root.allExtends];
  9651. var newRoot = this._visitor.visit(root);
  9652. this.checkExtendsForNonMatched(root.allExtends);
  9653. return newRoot;
  9654. },
  9655. checkExtendsForNonMatched: function(extendList) {
  9656. var indices = this.extendIndices;
  9657. extendList.filter(function(extend) {
  9658. return !extend.hasFoundMatches && extend.parent_ids.length == 1;
  9659. }).forEach(function(extend) {
  9660. var selector = '_unknown_';
  9661. try {
  9662. selector = extend.selector.toCSS({});
  9663. }
  9664. catch (_) {}
  9665. if (!indices[extend.index + ' ' + selector]) {
  9666. indices[extend.index + ' ' + selector] = true;
  9667. logger.warn('extend \'' + selector + '\' has no matches');
  9668. }
  9669. });
  9670. },
  9671. doExtendChaining: function (extendsList, extendsListTarget, iterationCount) {
  9672. //
  9673. // chaining is different from normal extension.. if we extend an extend then we are not just copying, altering
  9674. // and pasting the selector we would do normally, but we are also adding an extend with the same target selector
  9675. // this means this new extend can then go and alter other extends
  9676. //
  9677. // this method deals with all the chaining work - without it, extend is flat and doesn't work on other extend selectors
  9678. // this is also the most expensive.. and a match on one selector can cause an extension of a selector we had already
  9679. // processed if we look at each selector at a time, as is done in visitRuleset
  9680. var extendIndex, targetExtendIndex, matches, extendsToAdd = [], newSelector, extendVisitor = this, selectorPath,
  9681. extend, targetExtend, newExtend;
  9682. iterationCount = iterationCount || 0;
  9683. // loop through comparing every extend with every target extend.
  9684. // a target extend is the one on the ruleset we are looking at copy/edit/pasting in place
  9685. // e.g. .a:extend(.b) {} and .b:extend(.c) {} then the first extend extends the second one
  9686. // and the second is the target.
  9687. // the separation into two lists allows us to process a subset of chains with a bigger set, as is the
  9688. // case when processing media queries
  9689. for (extendIndex = 0; extendIndex < extendsList.length; extendIndex++) {
  9690. for (targetExtendIndex = 0; targetExtendIndex < extendsListTarget.length; targetExtendIndex++) {
  9691. extend = extendsList[extendIndex];
  9692. targetExtend = extendsListTarget[targetExtendIndex];
  9693. // look for circular references
  9694. if ( extend.parent_ids.indexOf( targetExtend.object_id ) >= 0 ) { continue; }
  9695. // find a match in the target extends self selector (the bit before :extend)
  9696. selectorPath = [targetExtend.selfSelectors[0]];
  9697. matches = extendVisitor.findMatch(extend, selectorPath);
  9698. if (matches.length) {
  9699. extend.hasFoundMatches = true;
  9700. // we found a match, so for each self selector..
  9701. extend.selfSelectors.forEach(function(selfSelector) {
  9702. var info = targetExtend.visibilityInfo();
  9703. // process the extend as usual
  9704. newSelector = extendVisitor.extendSelector(matches, selectorPath, selfSelector, extend.isVisible());
  9705. // but now we create a new extend from it
  9706. newExtend = new(tree.Extend)(targetExtend.selector, targetExtend.option, 0, targetExtend.fileInfo(), info);
  9707. newExtend.selfSelectors = newSelector;
  9708. // add the extend onto the list of extends for that selector
  9709. newSelector[newSelector.length - 1].extendList = [newExtend];
  9710. // record that we need to add it.
  9711. extendsToAdd.push(newExtend);
  9712. newExtend.ruleset = targetExtend.ruleset;
  9713. // remember its parents for circular references
  9714. newExtend.parent_ids = newExtend.parent_ids.concat(targetExtend.parent_ids, extend.parent_ids);
  9715. // only process the selector once.. if we have :extend(.a,.b) then multiple
  9716. // extends will look at the same selector path, so when extending
  9717. // we know that any others will be duplicates in terms of what is added to the css
  9718. if (targetExtend.firstExtendOnThisSelectorPath) {
  9719. newExtend.firstExtendOnThisSelectorPath = true;
  9720. targetExtend.ruleset.paths.push(newSelector);
  9721. }
  9722. });
  9723. }
  9724. }
  9725. }
  9726. if (extendsToAdd.length) {
  9727. // try to detect circular references to stop a stack overflow.
  9728. // may no longer be needed.
  9729. this.extendChainCount++;
  9730. if (iterationCount > 100) {
  9731. var selectorOne = '{unable to calculate}';
  9732. var selectorTwo = '{unable to calculate}';
  9733. try {
  9734. selectorOne = extendsToAdd[0].selfSelectors[0].toCSS();
  9735. selectorTwo = extendsToAdd[0].selector.toCSS();
  9736. }
  9737. catch (e) {}
  9738. throw { message: 'extend circular reference detected. One of the circular extends is currently:' +
  9739. selectorOne + ':extend(' + selectorTwo + ')'};
  9740. }
  9741. // now process the new extends on the existing rules so that we can handle a extending b extending c extending
  9742. // d extending e...
  9743. return extendsToAdd.concat(extendVisitor.doExtendChaining(extendsToAdd, extendsListTarget, iterationCount + 1));
  9744. } else {
  9745. return extendsToAdd;
  9746. }
  9747. },
  9748. visitDeclaration: function (ruleNode, visitArgs) {
  9749. visitArgs.visitDeeper = false;
  9750. },
  9751. visitMixinDefinition: function (mixinDefinitionNode, visitArgs) {
  9752. visitArgs.visitDeeper = false;
  9753. },
  9754. visitSelector: function (selectorNode, visitArgs) {
  9755. visitArgs.visitDeeper = false;
  9756. },
  9757. visitRuleset: function (rulesetNode, visitArgs) {
  9758. if (rulesetNode.root) {
  9759. return;
  9760. }
  9761. var matches, pathIndex, extendIndex, allExtends = this.allExtendsStack[this.allExtendsStack.length - 1],
  9762. selectorsToAdd = [], extendVisitor = this, selectorPath;
  9763. // look at each selector path in the ruleset, find any extend matches and then copy, find and replace
  9764. for (extendIndex = 0; extendIndex < allExtends.length; extendIndex++) {
  9765. for (pathIndex = 0; pathIndex < rulesetNode.paths.length; pathIndex++) {
  9766. selectorPath = rulesetNode.paths[pathIndex];
  9767. // extending extends happens initially, before the main pass
  9768. if (rulesetNode.extendOnEveryPath) { continue; }
  9769. var extendList = selectorPath[selectorPath.length - 1].extendList;
  9770. if (extendList && extendList.length) { continue; }
  9771. matches = this.findMatch(allExtends[extendIndex], selectorPath);
  9772. if (matches.length) {
  9773. allExtends[extendIndex].hasFoundMatches = true;
  9774. allExtends[extendIndex].selfSelectors.forEach(function(selfSelector) {
  9775. var extendedSelectors;
  9776. extendedSelectors = extendVisitor.extendSelector(matches, selectorPath, selfSelector, allExtends[extendIndex].isVisible());
  9777. selectorsToAdd.push(extendedSelectors);
  9778. });
  9779. }
  9780. }
  9781. }
  9782. rulesetNode.paths = rulesetNode.paths.concat(selectorsToAdd);
  9783. },
  9784. findMatch: function (extend, haystackSelectorPath) {
  9785. //
  9786. // look through the haystack selector path to try and find the needle - extend.selector
  9787. // returns an array of selector matches that can then be replaced
  9788. //
  9789. var haystackSelectorIndex, hackstackSelector, hackstackElementIndex, haystackElement,
  9790. targetCombinator, i,
  9791. extendVisitor = this,
  9792. needleElements = extend.selector.elements,
  9793. potentialMatches = [], potentialMatch, matches = [];
  9794. // loop through the haystack elements
  9795. for (haystackSelectorIndex = 0; haystackSelectorIndex < haystackSelectorPath.length; haystackSelectorIndex++) {
  9796. hackstackSelector = haystackSelectorPath[haystackSelectorIndex];
  9797. for (hackstackElementIndex = 0; hackstackElementIndex < hackstackSelector.elements.length; hackstackElementIndex++) {
  9798. haystackElement = hackstackSelector.elements[hackstackElementIndex];
  9799. // if we allow elements before our match we can add a potential match every time. otherwise only at the first element.
  9800. if (extend.allowBefore || (haystackSelectorIndex === 0 && hackstackElementIndex === 0)) {
  9801. potentialMatches.push({pathIndex: haystackSelectorIndex, index: hackstackElementIndex, matched: 0,
  9802. initialCombinator: haystackElement.combinator});
  9803. }
  9804. for (i = 0; i < potentialMatches.length; i++) {
  9805. potentialMatch = potentialMatches[i];
  9806. // selectors add " " onto the first element. When we use & it joins the selectors together, but if we don't
  9807. // then each selector in haystackSelectorPath has a space before it added in the toCSS phase. so we need to
  9808. // work out what the resulting combinator will be
  9809. targetCombinator = haystackElement.combinator.value;
  9810. if (targetCombinator === '' && hackstackElementIndex === 0) {
  9811. targetCombinator = ' ';
  9812. }
  9813. // if we don't match, null our match to indicate failure
  9814. if (!extendVisitor.isElementValuesEqual(needleElements[potentialMatch.matched].value, haystackElement.value) ||
  9815. (potentialMatch.matched > 0 && needleElements[potentialMatch.matched].combinator.value !== targetCombinator)) {
  9816. potentialMatch = null;
  9817. } else {
  9818. potentialMatch.matched++;
  9819. }
  9820. // if we are still valid and have finished, test whether we have elements after and whether these are allowed
  9821. if (potentialMatch) {
  9822. potentialMatch.finished = potentialMatch.matched === needleElements.length;
  9823. if (potentialMatch.finished &&
  9824. (!extend.allowAfter &&
  9825. (hackstackElementIndex + 1 < hackstackSelector.elements.length || haystackSelectorIndex + 1 < haystackSelectorPath.length))) {
  9826. potentialMatch = null;
  9827. }
  9828. }
  9829. // if null we remove, if not, we are still valid, so either push as a valid match or continue
  9830. if (potentialMatch) {
  9831. if (potentialMatch.finished) {
  9832. potentialMatch.length = needleElements.length;
  9833. potentialMatch.endPathIndex = haystackSelectorIndex;
  9834. potentialMatch.endPathElementIndex = hackstackElementIndex + 1; // index after end of match
  9835. potentialMatches.length = 0; // we don't allow matches to overlap, so start matching again
  9836. matches.push(potentialMatch);
  9837. }
  9838. } else {
  9839. potentialMatches.splice(i, 1);
  9840. i--;
  9841. }
  9842. }
  9843. }
  9844. }
  9845. return matches;
  9846. },
  9847. isElementValuesEqual: function(elementValue1, elementValue2) {
  9848. if (typeof elementValue1 === 'string' || typeof elementValue2 === 'string') {
  9849. return elementValue1 === elementValue2;
  9850. }
  9851. if (elementValue1 instanceof tree.Attribute) {
  9852. if (elementValue1.op !== elementValue2.op || elementValue1.key !== elementValue2.key) {
  9853. return false;
  9854. }
  9855. if (!elementValue1.value || !elementValue2.value) {
  9856. if (elementValue1.value || elementValue2.value) {
  9857. return false;
  9858. }
  9859. return true;
  9860. }
  9861. elementValue1 = elementValue1.value.value || elementValue1.value;
  9862. elementValue2 = elementValue2.value.value || elementValue2.value;
  9863. return elementValue1 === elementValue2;
  9864. }
  9865. elementValue1 = elementValue1.value;
  9866. elementValue2 = elementValue2.value;
  9867. if (elementValue1 instanceof tree.Selector) {
  9868. if (!(elementValue2 instanceof tree.Selector) || elementValue1.elements.length !== elementValue2.elements.length) {
  9869. return false;
  9870. }
  9871. for (var i = 0; i < elementValue1.elements.length; i++) {
  9872. if (elementValue1.elements[i].combinator.value !== elementValue2.elements[i].combinator.value) {
  9873. if (i !== 0 || (elementValue1.elements[i].combinator.value || ' ') !== (elementValue2.elements[i].combinator.value || ' ')) {
  9874. return false;
  9875. }
  9876. }
  9877. if (!this.isElementValuesEqual(elementValue1.elements[i].value, elementValue2.elements[i].value)) {
  9878. return false;
  9879. }
  9880. }
  9881. return true;
  9882. }
  9883. return false;
  9884. },
  9885. extendSelector:function (matches, selectorPath, replacementSelector, isVisible) {
  9886. // for a set of matches, replace each match with the replacement selector
  9887. var currentSelectorPathIndex = 0,
  9888. currentSelectorPathElementIndex = 0,
  9889. path = [],
  9890. matchIndex,
  9891. selector,
  9892. firstElement,
  9893. match,
  9894. newElements;
  9895. for (matchIndex = 0; matchIndex < matches.length; matchIndex++) {
  9896. match = matches[matchIndex];
  9897. selector = selectorPath[match.pathIndex];
  9898. firstElement = new tree.Element(
  9899. match.initialCombinator,
  9900. replacementSelector.elements[0].value,
  9901. replacementSelector.elements[0].isVariable,
  9902. replacementSelector.elements[0].getIndex(),
  9903. replacementSelector.elements[0].fileInfo()
  9904. );
  9905. if (match.pathIndex > currentSelectorPathIndex && currentSelectorPathElementIndex > 0) {
  9906. path[path.length - 1].elements = path[path.length - 1]
  9907. .elements.concat(selectorPath[currentSelectorPathIndex].elements.slice(currentSelectorPathElementIndex));
  9908. currentSelectorPathElementIndex = 0;
  9909. currentSelectorPathIndex++;
  9910. }
  9911. newElements = selector.elements
  9912. .slice(currentSelectorPathElementIndex, match.index)
  9913. .concat([firstElement])
  9914. .concat(replacementSelector.elements.slice(1));
  9915. if (currentSelectorPathIndex === match.pathIndex && matchIndex > 0) {
  9916. path[path.length - 1].elements =
  9917. path[path.length - 1].elements.concat(newElements);
  9918. } else {
  9919. path = path.concat(selectorPath.slice(currentSelectorPathIndex, match.pathIndex));
  9920. path.push(new tree.Selector(
  9921. newElements
  9922. ));
  9923. }
  9924. currentSelectorPathIndex = match.endPathIndex;
  9925. currentSelectorPathElementIndex = match.endPathElementIndex;
  9926. if (currentSelectorPathElementIndex >= selectorPath[currentSelectorPathIndex].elements.length) {
  9927. currentSelectorPathElementIndex = 0;
  9928. currentSelectorPathIndex++;
  9929. }
  9930. }
  9931. if (currentSelectorPathIndex < selectorPath.length && currentSelectorPathElementIndex > 0) {
  9932. path[path.length - 1].elements = path[path.length - 1]
  9933. .elements.concat(selectorPath[currentSelectorPathIndex].elements.slice(currentSelectorPathElementIndex));
  9934. currentSelectorPathIndex++;
  9935. }
  9936. path = path.concat(selectorPath.slice(currentSelectorPathIndex, selectorPath.length));
  9937. path = path.map(function (currentValue) {
  9938. // we can re-use elements here, because the visibility property matters only for selectors
  9939. var derived = currentValue.createDerived(currentValue.elements);
  9940. if (isVisible) {
  9941. derived.ensureVisibility();
  9942. } else {
  9943. derived.ensureInvisibility();
  9944. }
  9945. return derived;
  9946. });
  9947. return path;
  9948. },
  9949. visitMedia: function (mediaNode, visitArgs) {
  9950. var newAllExtends = mediaNode.allExtends.concat(this.allExtendsStack[this.allExtendsStack.length - 1]);
  9951. newAllExtends = newAllExtends.concat(this.doExtendChaining(newAllExtends, mediaNode.allExtends));
  9952. this.allExtendsStack.push(newAllExtends);
  9953. },
  9954. visitMediaOut: function (mediaNode) {
  9955. var lastIndex = this.allExtendsStack.length - 1;
  9956. this.allExtendsStack.length = lastIndex;
  9957. },
  9958. visitAtRule: function (atRuleNode, visitArgs) {
  9959. var newAllExtends = atRuleNode.allExtends.concat(this.allExtendsStack[this.allExtendsStack.length - 1]);
  9960. newAllExtends = newAllExtends.concat(this.doExtendChaining(newAllExtends, atRuleNode.allExtends));
  9961. this.allExtendsStack.push(newAllExtends);
  9962. },
  9963. visitAtRuleOut: function (atRuleNode) {
  9964. var lastIndex = this.allExtendsStack.length - 1;
  9965. this.allExtendsStack.length = lastIndex;
  9966. }
  9967. };
  9968. module.exports = ProcessExtendsVisitor;
  9969. },{"../logger":39,"../tree":67,"../utils":89,"./visitor":97}],91:[function(require,module,exports){
  9970. function ImportSequencer(onSequencerEmpty) {
  9971. this.imports = [];
  9972. this.variableImports = [];
  9973. this._onSequencerEmpty = onSequencerEmpty;
  9974. this._currentDepth = 0;
  9975. }
  9976. ImportSequencer.prototype.addImport = function(callback) {
  9977. var importSequencer = this,
  9978. importItem = {
  9979. callback: callback,
  9980. args: null,
  9981. isReady: false
  9982. };
  9983. this.imports.push(importItem);
  9984. return function() {
  9985. importItem.args = Array.prototype.slice.call(arguments, 0);
  9986. importItem.isReady = true;
  9987. importSequencer.tryRun();
  9988. };
  9989. };
  9990. ImportSequencer.prototype.addVariableImport = function(callback) {
  9991. this.variableImports.push(callback);
  9992. };
  9993. ImportSequencer.prototype.tryRun = function() {
  9994. this._currentDepth++;
  9995. try {
  9996. while (true) {
  9997. while (this.imports.length > 0) {
  9998. var importItem = this.imports[0];
  9999. if (!importItem.isReady) {
  10000. return;
  10001. }
  10002. this.imports = this.imports.slice(1);
  10003. importItem.callback.apply(null, importItem.args);
  10004. }
  10005. if (this.variableImports.length === 0) {
  10006. break;
  10007. }
  10008. var variableImport = this.variableImports[0];
  10009. this.variableImports = this.variableImports.slice(1);
  10010. variableImport();
  10011. }
  10012. } finally {
  10013. this._currentDepth--;
  10014. }
  10015. if (this._currentDepth === 0 && this._onSequencerEmpty) {
  10016. this._onSequencerEmpty();
  10017. }
  10018. };
  10019. module.exports = ImportSequencer;
  10020. },{}],92:[function(require,module,exports){
  10021. var contexts = require('../contexts'),
  10022. Visitor = require('./visitor'),
  10023. ImportSequencer = require('./import-sequencer'),
  10024. utils = require('../utils');
  10025. var ImportVisitor = function(importer, finish) {
  10026. this._visitor = new Visitor(this);
  10027. this._importer = importer;
  10028. this._finish = finish;
  10029. this.context = new contexts.Eval();
  10030. this.importCount = 0;
  10031. this.onceFileDetectionMap = {};
  10032. this.recursionDetector = {};
  10033. this._sequencer = new ImportSequencer(this._onSequencerEmpty.bind(this));
  10034. };
  10035. ImportVisitor.prototype = {
  10036. isReplacing: false,
  10037. run: function (root) {
  10038. try {
  10039. // process the contents
  10040. this._visitor.visit(root);
  10041. }
  10042. catch (e) {
  10043. this.error = e;
  10044. }
  10045. this.isFinished = true;
  10046. this._sequencer.tryRun();
  10047. },
  10048. _onSequencerEmpty: function() {
  10049. if (!this.isFinished) {
  10050. return;
  10051. }
  10052. this._finish(this.error);
  10053. },
  10054. visitImport: function (importNode, visitArgs) {
  10055. var inlineCSS = importNode.options.inline;
  10056. if (!importNode.css || inlineCSS) {
  10057. var context = new contexts.Eval(this.context, utils.copyArray(this.context.frames));
  10058. var importParent = context.frames[0];
  10059. this.importCount++;
  10060. if (importNode.isVariableImport()) {
  10061. this._sequencer.addVariableImport(this.processImportNode.bind(this, importNode, context, importParent));
  10062. } else {
  10063. this.processImportNode(importNode, context, importParent);
  10064. }
  10065. }
  10066. visitArgs.visitDeeper = false;
  10067. },
  10068. processImportNode: function(importNode, context, importParent) {
  10069. var evaldImportNode,
  10070. inlineCSS = importNode.options.inline;
  10071. try {
  10072. evaldImportNode = importNode.evalForImport(context);
  10073. } catch (e) {
  10074. if (!e.filename) { e.index = importNode.getIndex(); e.filename = importNode.fileInfo().filename; }
  10075. // attempt to eval properly and treat as css
  10076. importNode.css = true;
  10077. // if that fails, this error will be thrown
  10078. importNode.error = e;
  10079. }
  10080. if (evaldImportNode && (!evaldImportNode.css || inlineCSS)) {
  10081. if (evaldImportNode.options.multiple) {
  10082. context.importMultiple = true;
  10083. }
  10084. // try appending if we haven't determined if it is css or not
  10085. var tryAppendLessExtension = evaldImportNode.css === undefined;
  10086. for (var i = 0; i < importParent.rules.length; i++) {
  10087. if (importParent.rules[i] === importNode) {
  10088. importParent.rules[i] = evaldImportNode;
  10089. break;
  10090. }
  10091. }
  10092. var onImported = this.onImported.bind(this, evaldImportNode, context),
  10093. sequencedOnImported = this._sequencer.addImport(onImported);
  10094. this._importer.push(evaldImportNode.getPath(), tryAppendLessExtension, evaldImportNode.fileInfo(),
  10095. evaldImportNode.options, sequencedOnImported);
  10096. } else {
  10097. this.importCount--;
  10098. if (this.isFinished) {
  10099. this._sequencer.tryRun();
  10100. }
  10101. }
  10102. },
  10103. onImported: function (importNode, context, e, root, importedAtRoot, fullPath) {
  10104. if (e) {
  10105. if (!e.filename) {
  10106. e.index = importNode.getIndex(); e.filename = importNode.fileInfo().filename;
  10107. }
  10108. this.error = e;
  10109. }
  10110. var importVisitor = this,
  10111. inlineCSS = importNode.options.inline,
  10112. isPlugin = importNode.options.isPlugin,
  10113. isOptional = importNode.options.optional,
  10114. duplicateImport = importedAtRoot || fullPath in importVisitor.recursionDetector;
  10115. if (!context.importMultiple) {
  10116. if (duplicateImport) {
  10117. importNode.skip = true;
  10118. } else {
  10119. importNode.skip = function() {
  10120. if (fullPath in importVisitor.onceFileDetectionMap) {
  10121. return true;
  10122. }
  10123. importVisitor.onceFileDetectionMap[fullPath] = true;
  10124. return false;
  10125. };
  10126. }
  10127. }
  10128. if (!fullPath && isOptional) {
  10129. importNode.skip = true;
  10130. }
  10131. if (root) {
  10132. importNode.root = root;
  10133. importNode.importedFilename = fullPath;
  10134. if (!inlineCSS && !isPlugin && (context.importMultiple || !duplicateImport)) {
  10135. importVisitor.recursionDetector[fullPath] = true;
  10136. var oldContext = this.context;
  10137. this.context = context;
  10138. try {
  10139. this._visitor.visit(root);
  10140. } catch (e) {
  10141. this.error = e;
  10142. }
  10143. this.context = oldContext;
  10144. }
  10145. }
  10146. importVisitor.importCount--;
  10147. if (importVisitor.isFinished) {
  10148. importVisitor._sequencer.tryRun();
  10149. }
  10150. },
  10151. visitDeclaration: function (declNode, visitArgs) {
  10152. if (declNode.value.type === 'DetachedRuleset') {
  10153. this.context.frames.unshift(declNode);
  10154. } else {
  10155. visitArgs.visitDeeper = false;
  10156. }
  10157. },
  10158. visitDeclarationOut: function(declNode) {
  10159. if (declNode.value.type === 'DetachedRuleset') {
  10160. this.context.frames.shift();
  10161. }
  10162. },
  10163. visitAtRule: function (atRuleNode, visitArgs) {
  10164. this.context.frames.unshift(atRuleNode);
  10165. },
  10166. visitAtRuleOut: function (atRuleNode) {
  10167. this.context.frames.shift();
  10168. },
  10169. visitMixinDefinition: function (mixinDefinitionNode, visitArgs) {
  10170. this.context.frames.unshift(mixinDefinitionNode);
  10171. },
  10172. visitMixinDefinitionOut: function (mixinDefinitionNode) {
  10173. this.context.frames.shift();
  10174. },
  10175. visitRuleset: function (rulesetNode, visitArgs) {
  10176. this.context.frames.unshift(rulesetNode);
  10177. },
  10178. visitRulesetOut: function (rulesetNode) {
  10179. this.context.frames.shift();
  10180. },
  10181. visitMedia: function (mediaNode, visitArgs) {
  10182. this.context.frames.unshift(mediaNode.rules[0]);
  10183. },
  10184. visitMediaOut: function (mediaNode) {
  10185. this.context.frames.shift();
  10186. }
  10187. };
  10188. module.exports = ImportVisitor;
  10189. },{"../contexts":13,"../utils":89,"./import-sequencer":91,"./visitor":97}],93:[function(require,module,exports){
  10190. var visitors = {
  10191. Visitor: require('./visitor'),
  10192. ImportVisitor: require('./import-visitor'),
  10193. MarkVisibleSelectorsVisitor: require('./set-tree-visibility-visitor'),
  10194. ExtendVisitor: require('./extend-visitor'),
  10195. JoinSelectorVisitor: require('./join-selector-visitor'),
  10196. ToCSSVisitor: require('./to-css-visitor')
  10197. };
  10198. module.exports = visitors;
  10199. },{"./extend-visitor":90,"./import-visitor":92,"./join-selector-visitor":94,"./set-tree-visibility-visitor":95,"./to-css-visitor":96,"./visitor":97}],94:[function(require,module,exports){
  10200. var Visitor = require('./visitor');
  10201. var JoinSelectorVisitor = function() {
  10202. this.contexts = [[]];
  10203. this._visitor = new Visitor(this);
  10204. };
  10205. JoinSelectorVisitor.prototype = {
  10206. run: function (root) {
  10207. return this._visitor.visit(root);
  10208. },
  10209. visitDeclaration: function (declNode, visitArgs) {
  10210. visitArgs.visitDeeper = false;
  10211. },
  10212. visitMixinDefinition: function (mixinDefinitionNode, visitArgs) {
  10213. visitArgs.visitDeeper = false;
  10214. },
  10215. visitRuleset: function (rulesetNode, visitArgs) {
  10216. var context = this.contexts[this.contexts.length - 1],
  10217. paths = [], selectors;
  10218. this.contexts.push(paths);
  10219. if (!rulesetNode.root) {
  10220. selectors = rulesetNode.selectors;
  10221. if (selectors) {
  10222. selectors = selectors.filter(function(selector) { return selector.getIsOutput(); });
  10223. rulesetNode.selectors = selectors.length ? selectors : (selectors = null);
  10224. if (selectors) { rulesetNode.joinSelectors(paths, context, selectors); }
  10225. }
  10226. if (!selectors) { rulesetNode.rules = null; }
  10227. rulesetNode.paths = paths;
  10228. }
  10229. },
  10230. visitRulesetOut: function (rulesetNode) {
  10231. this.contexts.length = this.contexts.length - 1;
  10232. },
  10233. visitMedia: function (mediaNode, visitArgs) {
  10234. var context = this.contexts[this.contexts.length - 1];
  10235. mediaNode.rules[0].root = (context.length === 0 || context[0].multiMedia);
  10236. },
  10237. visitAtRule: function (atRuleNode, visitArgs) {
  10238. var context = this.contexts[this.contexts.length - 1];
  10239. if (atRuleNode.rules && atRuleNode.rules.length) {
  10240. atRuleNode.rules[0].root = (atRuleNode.isRooted || context.length === 0 || null);
  10241. }
  10242. }
  10243. };
  10244. module.exports = JoinSelectorVisitor;
  10245. },{"./visitor":97}],95:[function(require,module,exports){
  10246. var SetTreeVisibilityVisitor = function(visible) {
  10247. this.visible = visible;
  10248. };
  10249. SetTreeVisibilityVisitor.prototype.run = function(root) {
  10250. this.visit(root);
  10251. };
  10252. SetTreeVisibilityVisitor.prototype.visitArray = function(nodes) {
  10253. if (!nodes) {
  10254. return nodes;
  10255. }
  10256. var cnt = nodes.length, i;
  10257. for (i = 0; i < cnt; i++) {
  10258. this.visit(nodes[i]);
  10259. }
  10260. return nodes;
  10261. };
  10262. SetTreeVisibilityVisitor.prototype.visit = function(node) {
  10263. if (!node) {
  10264. return node;
  10265. }
  10266. if (node.constructor === Array) {
  10267. return this.visitArray(node);
  10268. }
  10269. if (!node.blocksVisibility || node.blocksVisibility()) {
  10270. return node;
  10271. }
  10272. if (this.visible) {
  10273. node.ensureVisibility();
  10274. } else {
  10275. node.ensureInvisibility();
  10276. }
  10277. node.accept(this);
  10278. return node;
  10279. };
  10280. module.exports = SetTreeVisibilityVisitor;
  10281. },{}],96:[function(require,module,exports){
  10282. var tree = require('../tree'),
  10283. Visitor = require('./visitor');
  10284. var CSSVisitorUtils = function(context) {
  10285. this._visitor = new Visitor(this);
  10286. this._context = context;
  10287. };
  10288. CSSVisitorUtils.prototype = {
  10289. containsSilentNonBlockedChild: function(bodyRules) {
  10290. var rule;
  10291. if (!bodyRules) {
  10292. return false;
  10293. }
  10294. for (var r = 0; r < bodyRules.length; r++) {
  10295. rule = bodyRules[r];
  10296. if (rule.isSilent && rule.isSilent(this._context) && !rule.blocksVisibility()) {
  10297. // the atrule contains something that was referenced (likely by extend)
  10298. // therefore it needs to be shown in output too
  10299. return true;
  10300. }
  10301. }
  10302. return false;
  10303. },
  10304. keepOnlyVisibleChilds: function(owner) {
  10305. if (owner && owner.rules) {
  10306. owner.rules = owner.rules.filter(function(thing) {
  10307. return thing.isVisible();
  10308. });
  10309. }
  10310. },
  10311. isEmpty: function(owner) {
  10312. return (owner && owner.rules)
  10313. ? (owner.rules.length === 0) : true;
  10314. },
  10315. hasVisibleSelector: function(rulesetNode) {
  10316. return (rulesetNode && rulesetNode.paths)
  10317. ? (rulesetNode.paths.length > 0) : false;
  10318. },
  10319. resolveVisibility: function (node, originalRules) {
  10320. if (!node.blocksVisibility()) {
  10321. if (this.isEmpty(node) && !this.containsSilentNonBlockedChild(originalRules)) {
  10322. return ;
  10323. }
  10324. return node;
  10325. }
  10326. var compiledRulesBody = node.rules[0];
  10327. this.keepOnlyVisibleChilds(compiledRulesBody);
  10328. if (this.isEmpty(compiledRulesBody)) {
  10329. return ;
  10330. }
  10331. node.ensureVisibility();
  10332. node.removeVisibilityBlock();
  10333. return node;
  10334. },
  10335. isVisibleRuleset: function(rulesetNode) {
  10336. if (rulesetNode.firstRoot) {
  10337. return true;
  10338. }
  10339. if (this.isEmpty(rulesetNode)) {
  10340. return false;
  10341. }
  10342. if (!rulesetNode.root && !this.hasVisibleSelector(rulesetNode)) {
  10343. return false;
  10344. }
  10345. return true;
  10346. }
  10347. };
  10348. var ToCSSVisitor = function(context) {
  10349. this._visitor = new Visitor(this);
  10350. this._context = context;
  10351. this.utils = new CSSVisitorUtils(context);
  10352. };
  10353. ToCSSVisitor.prototype = {
  10354. isReplacing: true,
  10355. run: function (root) {
  10356. return this._visitor.visit(root);
  10357. },
  10358. visitDeclaration: function (declNode, visitArgs) {
  10359. if (declNode.blocksVisibility() || declNode.variable) {
  10360. return;
  10361. }
  10362. return declNode;
  10363. },
  10364. visitMixinDefinition: function (mixinNode, visitArgs) {
  10365. // mixin definitions do not get eval'd - this means they keep state
  10366. // so we have to clear that state here so it isn't used if toCSS is called twice
  10367. mixinNode.frames = [];
  10368. },
  10369. visitExtend: function (extendNode, visitArgs) {
  10370. },
  10371. visitComment: function (commentNode, visitArgs) {
  10372. if (commentNode.blocksVisibility() || commentNode.isSilent(this._context)) {
  10373. return;
  10374. }
  10375. return commentNode;
  10376. },
  10377. visitMedia: function(mediaNode, visitArgs) {
  10378. var originalRules = mediaNode.rules[0].rules;
  10379. mediaNode.accept(this._visitor);
  10380. visitArgs.visitDeeper = false;
  10381. return this.utils.resolveVisibility(mediaNode, originalRules);
  10382. },
  10383. visitImport: function (importNode, visitArgs) {
  10384. if (importNode.blocksVisibility()) {
  10385. return ;
  10386. }
  10387. return importNode;
  10388. },
  10389. visitAtRule: function(atRuleNode, visitArgs) {
  10390. if (atRuleNode.rules && atRuleNode.rules.length) {
  10391. return this.visitAtRuleWithBody(atRuleNode, visitArgs);
  10392. } else {
  10393. return this.visitAtRuleWithoutBody(atRuleNode, visitArgs);
  10394. }
  10395. },
  10396. visitAnonymous: function(anonymousNode, visitArgs) {
  10397. if (!anonymousNode.blocksVisibility()) {
  10398. anonymousNode.accept(this._visitor);
  10399. return anonymousNode;
  10400. }
  10401. },
  10402. visitAtRuleWithBody: function(atRuleNode, visitArgs) {
  10403. // if there is only one nested ruleset and that one has no path, then it is
  10404. // just fake ruleset
  10405. function hasFakeRuleset(atRuleNode) {
  10406. var bodyRules = atRuleNode.rules;
  10407. return bodyRules.length === 1 && (!bodyRules[0].paths || bodyRules[0].paths.length === 0);
  10408. }
  10409. function getBodyRules(atRuleNode) {
  10410. var nodeRules = atRuleNode.rules;
  10411. if (hasFakeRuleset(atRuleNode)) {
  10412. return nodeRules[0].rules;
  10413. }
  10414. return nodeRules;
  10415. }
  10416. // it is still true that it is only one ruleset in array
  10417. // this is last such moment
  10418. // process childs
  10419. var originalRules = getBodyRules(atRuleNode);
  10420. atRuleNode.accept(this._visitor);
  10421. visitArgs.visitDeeper = false;
  10422. if (!this.utils.isEmpty(atRuleNode)) {
  10423. this._mergeRules(atRuleNode.rules[0].rules);
  10424. }
  10425. return this.utils.resolveVisibility(atRuleNode, originalRules);
  10426. },
  10427. visitAtRuleWithoutBody: function(atRuleNode, visitArgs) {
  10428. if (atRuleNode.blocksVisibility()) {
  10429. return;
  10430. }
  10431. if (atRuleNode.name === '@charset') {
  10432. // Only output the debug info together with subsequent @charset definitions
  10433. // a comment (or @media statement) before the actual @charset atrule would
  10434. // be considered illegal css as it has to be on the first line
  10435. if (this.charset) {
  10436. if (atRuleNode.debugInfo) {
  10437. var comment = new tree.Comment('/* ' + atRuleNode.toCSS(this._context).replace(/\n/g, '') + ' */\n');
  10438. comment.debugInfo = atRuleNode.debugInfo;
  10439. return this._visitor.visit(comment);
  10440. }
  10441. return;
  10442. }
  10443. this.charset = true;
  10444. }
  10445. return atRuleNode;
  10446. },
  10447. checkValidNodes: function(rules, isRoot) {
  10448. if (!rules) {
  10449. return;
  10450. }
  10451. for (var i = 0; i < rules.length; i++) {
  10452. var ruleNode = rules[i];
  10453. if (isRoot && ruleNode instanceof tree.Declaration && !ruleNode.variable) {
  10454. throw { message: 'Properties must be inside selector blocks. They cannot be in the root',
  10455. index: ruleNode.getIndex(), filename: ruleNode.fileInfo() && ruleNode.fileInfo().filename};
  10456. }
  10457. if (ruleNode instanceof tree.Call) {
  10458. throw { message: 'Function \'' + ruleNode.name + '\' is undefined',
  10459. index: ruleNode.getIndex(), filename: ruleNode.fileInfo() && ruleNode.fileInfo().filename};
  10460. }
  10461. if (ruleNode.type && !ruleNode.allowRoot) {
  10462. throw { message: ruleNode.type + ' node returned by a function is not valid here',
  10463. index: ruleNode.getIndex(), filename: ruleNode.fileInfo() && ruleNode.fileInfo().filename};
  10464. }
  10465. }
  10466. },
  10467. visitRuleset: function (rulesetNode, visitArgs) {
  10468. // at this point rulesets are nested into each other
  10469. var rule, rulesets = [];
  10470. this.checkValidNodes(rulesetNode.rules, rulesetNode.firstRoot);
  10471. if (!rulesetNode.root) {
  10472. // remove invisible paths
  10473. this._compileRulesetPaths(rulesetNode);
  10474. // remove rulesets from this ruleset body and compile them separately
  10475. var nodeRules = rulesetNode.rules, nodeRuleCnt = nodeRules ? nodeRules.length : 0;
  10476. for (var i = 0; i < nodeRuleCnt; ) {
  10477. rule = nodeRules[i];
  10478. if (rule && rule.rules) {
  10479. // visit because we are moving them out from being a child
  10480. rulesets.push(this._visitor.visit(rule));
  10481. nodeRules.splice(i, 1);
  10482. nodeRuleCnt--;
  10483. continue;
  10484. }
  10485. i++;
  10486. }
  10487. // accept the visitor to remove rules and refactor itself
  10488. // then we can decide nogw whether we want it or not
  10489. // compile body
  10490. if (nodeRuleCnt > 0) {
  10491. rulesetNode.accept(this._visitor);
  10492. } else {
  10493. rulesetNode.rules = null;
  10494. }
  10495. visitArgs.visitDeeper = false;
  10496. } else { // if (! rulesetNode.root) {
  10497. rulesetNode.accept(this._visitor);
  10498. visitArgs.visitDeeper = false;
  10499. }
  10500. if (rulesetNode.rules) {
  10501. this._mergeRules(rulesetNode.rules);
  10502. this._removeDuplicateRules(rulesetNode.rules);
  10503. }
  10504. // now decide whether we keep the ruleset
  10505. if (this.utils.isVisibleRuleset(rulesetNode)) {
  10506. rulesetNode.ensureVisibility();
  10507. rulesets.splice(0, 0, rulesetNode);
  10508. }
  10509. if (rulesets.length === 1) {
  10510. return rulesets[0];
  10511. }
  10512. return rulesets;
  10513. },
  10514. _compileRulesetPaths: function(rulesetNode) {
  10515. if (rulesetNode.paths) {
  10516. rulesetNode.paths = rulesetNode.paths
  10517. .filter(function(p) {
  10518. var i;
  10519. if (p[0].elements[0].combinator.value === ' ') {
  10520. p[0].elements[0].combinator = new(tree.Combinator)('');
  10521. }
  10522. for (i = 0; i < p.length; i++) {
  10523. if (p[i].isVisible() && p[i].getIsOutput()) {
  10524. return true;
  10525. }
  10526. }
  10527. return false;
  10528. });
  10529. }
  10530. },
  10531. _removeDuplicateRules: function(rules) {
  10532. if (!rules) { return; }
  10533. // remove duplicates
  10534. var ruleCache = {},
  10535. ruleList, rule, i;
  10536. for (i = rules.length - 1; i >= 0 ; i--) {
  10537. rule = rules[i];
  10538. if (rule instanceof tree.Declaration) {
  10539. if (!ruleCache[rule.name]) {
  10540. ruleCache[rule.name] = rule;
  10541. } else {
  10542. ruleList = ruleCache[rule.name];
  10543. if (ruleList instanceof tree.Declaration) {
  10544. ruleList = ruleCache[rule.name] = [ruleCache[rule.name].toCSS(this._context)];
  10545. }
  10546. var ruleCSS = rule.toCSS(this._context);
  10547. if (ruleList.indexOf(ruleCSS) !== -1) {
  10548. rules.splice(i, 1);
  10549. } else {
  10550. ruleList.push(ruleCSS);
  10551. }
  10552. }
  10553. }
  10554. }
  10555. },
  10556. _mergeRules: function(rules) {
  10557. if (!rules) {
  10558. return;
  10559. }
  10560. var groups = {},
  10561. groupsArr = [];
  10562. for (var i = 0; i < rules.length; i++) {
  10563. var rule = rules[i];
  10564. if (rule.merge) {
  10565. var key = rule.name;
  10566. groups[key] ? rules.splice(i--, 1) :
  10567. groupsArr.push(groups[key] = []);
  10568. groups[key].push(rule);
  10569. }
  10570. }
  10571. groupsArr.forEach(function(group) {
  10572. if (group.length > 0) {
  10573. var result = group[0],
  10574. space = [],
  10575. comma = [new tree.Expression(space)];
  10576. group.forEach(function(rule) {
  10577. if ((rule.merge === '+') && (space.length > 0)) {
  10578. comma.push(new tree.Expression(space = []));
  10579. }
  10580. space.push(rule.value);
  10581. result.important = result.important || rule.important;
  10582. });
  10583. result.value = new tree.Value(comma);
  10584. }
  10585. });
  10586. }
  10587. };
  10588. module.exports = ToCSSVisitor;
  10589. },{"../tree":67,"./visitor":97}],97:[function(require,module,exports){
  10590. var tree = require('../tree');
  10591. var _visitArgs = { visitDeeper: true },
  10592. _hasIndexed = false;
  10593. function _noop(node) {
  10594. return node;
  10595. }
  10596. function indexNodeTypes(parent, ticker) {
  10597. // add .typeIndex to tree node types for lookup table
  10598. var key, child;
  10599. for (key in parent) {
  10600. /* eslint guard-for-in: 0 */
  10601. child = parent[key];
  10602. switch (typeof child) {
  10603. case 'function':
  10604. // ignore bound functions directly on tree which do not have a prototype
  10605. // or aren't nodes
  10606. if (child.prototype && child.prototype.type) {
  10607. child.prototype.typeIndex = ticker++;
  10608. }
  10609. break;
  10610. case 'object':
  10611. ticker = indexNodeTypes(child, ticker);
  10612. break;
  10613. }
  10614. }
  10615. return ticker;
  10616. }
  10617. var Visitor = function(implementation) {
  10618. this._implementation = implementation;
  10619. this._visitInCache = {};
  10620. this._visitOutCache = {};
  10621. if (!_hasIndexed) {
  10622. indexNodeTypes(tree, 1);
  10623. _hasIndexed = true;
  10624. }
  10625. };
  10626. Visitor.prototype = {
  10627. visit: function(node) {
  10628. if (!node) {
  10629. return node;
  10630. }
  10631. var nodeTypeIndex = node.typeIndex;
  10632. if (!nodeTypeIndex) {
  10633. // MixinCall args aren't a node type?
  10634. if (node.value && node.value.typeIndex) {
  10635. this.visit(node.value);
  10636. }
  10637. return node;
  10638. }
  10639. var impl = this._implementation,
  10640. func = this._visitInCache[nodeTypeIndex],
  10641. funcOut = this._visitOutCache[nodeTypeIndex],
  10642. visitArgs = _visitArgs,
  10643. fnName;
  10644. visitArgs.visitDeeper = true;
  10645. if (!func) {
  10646. fnName = 'visit' + node.type;
  10647. func = impl[fnName] || _noop;
  10648. funcOut = impl[fnName + 'Out'] || _noop;
  10649. this._visitInCache[nodeTypeIndex] = func;
  10650. this._visitOutCache[nodeTypeIndex] = funcOut;
  10651. }
  10652. if (func !== _noop) {
  10653. var newNode = func.call(impl, node, visitArgs);
  10654. if (node && impl.isReplacing) {
  10655. node = newNode;
  10656. }
  10657. }
  10658. if (visitArgs.visitDeeper && node && node.accept) {
  10659. node.accept(this);
  10660. }
  10661. if (funcOut != _noop) {
  10662. funcOut.call(impl, node);
  10663. }
  10664. return node;
  10665. },
  10666. visitArray: function(nodes, nonReplacing) {
  10667. if (!nodes) {
  10668. return nodes;
  10669. }
  10670. var cnt = nodes.length, i;
  10671. // Non-replacing
  10672. if (nonReplacing || !this._implementation.isReplacing) {
  10673. for (i = 0; i < cnt; i++) {
  10674. this.visit(nodes[i]);
  10675. }
  10676. return nodes;
  10677. }
  10678. // Replacing
  10679. var out = [];
  10680. for (i = 0; i < cnt; i++) {
  10681. var evald = this.visit(nodes[i]);
  10682. if (evald === undefined) { continue; }
  10683. if (!evald.splice) {
  10684. out.push(evald);
  10685. } else if (evald.length) {
  10686. this.flatten(evald, out);
  10687. }
  10688. }
  10689. return out;
  10690. },
  10691. flatten: function(arr, out) {
  10692. if (!out) {
  10693. out = [];
  10694. }
  10695. var cnt, i, item,
  10696. nestedCnt, j, nestedItem;
  10697. for (i = 0, cnt = arr.length; i < cnt; i++) {
  10698. item = arr[i];
  10699. if (item === undefined) {
  10700. continue;
  10701. }
  10702. if (!item.splice) {
  10703. out.push(item);
  10704. continue;
  10705. }
  10706. for (j = 0, nestedCnt = item.length; j < nestedCnt; j++) {
  10707. nestedItem = item[j];
  10708. if (nestedItem === undefined) {
  10709. continue;
  10710. }
  10711. if (!nestedItem.splice) {
  10712. out.push(nestedItem);
  10713. } else if (nestedItem.length) {
  10714. this.flatten(nestedItem, out);
  10715. }
  10716. }
  10717. }
  10718. return out;
  10719. }
  10720. };
  10721. module.exports = Visitor;
  10722. },{"../tree":67}],98:[function(require,module,exports){
  10723. "use strict";
  10724. // rawAsap provides everything we need except exception management.
  10725. var rawAsap = require("./raw");
  10726. // RawTasks are recycled to reduce GC churn.
  10727. var freeTasks = [];
  10728. // We queue errors to ensure they are thrown in right order (FIFO).
  10729. // Array-as-queue is good enough here, since we are just dealing with exceptions.
  10730. var pendingErrors = [];
  10731. var requestErrorThrow = rawAsap.makeRequestCallFromTimer(throwFirstError);
  10732. function throwFirstError() {
  10733. if (pendingErrors.length) {
  10734. throw pendingErrors.shift();
  10735. }
  10736. }
  10737. /**
  10738. * Calls a task as soon as possible after returning, in its own event, with priority
  10739. * over other events like animation, reflow, and repaint. An error thrown from an
  10740. * event will not interrupt, nor even substantially slow down the processing of
  10741. * other events, but will be rather postponed to a lower priority event.
  10742. * @param {{call}} task A callable object, typically a function that takes no
  10743. * arguments.
  10744. */
  10745. module.exports = asap;
  10746. function asap(task) {
  10747. var rawTask;
  10748. if (freeTasks.length) {
  10749. rawTask = freeTasks.pop();
  10750. } else {
  10751. rawTask = new RawTask();
  10752. }
  10753. rawTask.task = task;
  10754. rawAsap(rawTask);
  10755. }
  10756. // We wrap tasks with recyclable task objects. A task object implements
  10757. // `call`, just like a function.
  10758. function RawTask() {
  10759. this.task = null;
  10760. }
  10761. // The sole purpose of wrapping the task is to catch the exception and recycle
  10762. // the task object after its single use.
  10763. RawTask.prototype.call = function () {
  10764. try {
  10765. this.task.call();
  10766. } catch (error) {
  10767. if (asap.onerror) {
  10768. // This hook exists purely for testing purposes.
  10769. // Its name will be periodically randomized to break any code that
  10770. // depends on its existence.
  10771. asap.onerror(error);
  10772. } else {
  10773. // In a web browser, exceptions are not fatal. However, to avoid
  10774. // slowing down the queue of pending tasks, we rethrow the error in a
  10775. // lower priority turn.
  10776. pendingErrors.push(error);
  10777. requestErrorThrow();
  10778. }
  10779. } finally {
  10780. this.task = null;
  10781. freeTasks[freeTasks.length] = this;
  10782. }
  10783. };
  10784. },{"./raw":99}],99:[function(require,module,exports){
  10785. (function (global){
  10786. "use strict";
  10787. // Use the fastest means possible to execute a task in its own turn, with
  10788. // priority over other events including IO, animation, reflow, and redraw
  10789. // events in browsers.
  10790. //
  10791. // An exception thrown by a task will permanently interrupt the processing of
  10792. // subsequent tasks. The higher level `asap` function ensures that if an
  10793. // exception is thrown by a task, that the task queue will continue flushing as
  10794. // soon as possible, but if you use `rawAsap` directly, you are responsible to
  10795. // either ensure that no exceptions are thrown from your task, or to manually
  10796. // call `rawAsap.requestFlush` if an exception is thrown.
  10797. module.exports = rawAsap;
  10798. function rawAsap(task) {
  10799. if (!queue.length) {
  10800. requestFlush();
  10801. flushing = true;
  10802. }
  10803. // Equivalent to push, but avoids a function call.
  10804. queue[queue.length] = task;
  10805. }
  10806. var queue = [];
  10807. // Once a flush has been requested, no further calls to `requestFlush` are
  10808. // necessary until the next `flush` completes.
  10809. var flushing = false;
  10810. // `requestFlush` is an implementation-specific method that attempts to kick
  10811. // off a `flush` event as quickly as possible. `flush` will attempt to exhaust
  10812. // the event queue before yielding to the browser's own event loop.
  10813. var requestFlush;
  10814. // The position of the next task to execute in the task queue. This is
  10815. // preserved between calls to `flush` so that it can be resumed if
  10816. // a task throws an exception.
  10817. var index = 0;
  10818. // If a task schedules additional tasks recursively, the task queue can grow
  10819. // unbounded. To prevent memory exhaustion, the task queue will periodically
  10820. // truncate already-completed tasks.
  10821. var capacity = 1024;
  10822. // The flush function processes all tasks that have been scheduled with
  10823. // `rawAsap` unless and until one of those tasks throws an exception.
  10824. // If a task throws an exception, `flush` ensures that its state will remain
  10825. // consistent and will resume where it left off when called again.
  10826. // However, `flush` does not make any arrangements to be called again if an
  10827. // exception is thrown.
  10828. function flush() {
  10829. while (index < queue.length) {
  10830. var currentIndex = index;
  10831. // Advance the index before calling the task. This ensures that we will
  10832. // begin flushing on the next task the task throws an error.
  10833. index = index + 1;
  10834. queue[currentIndex].call();
  10835. // Prevent leaking memory for long chains of recursive calls to `asap`.
  10836. // If we call `asap` within tasks scheduled by `asap`, the queue will
  10837. // grow, but to avoid an O(n) walk for every task we execute, we don't
  10838. // shift tasks off the queue after they have been executed.
  10839. // Instead, we periodically shift 1024 tasks off the queue.
  10840. if (index > capacity) {
  10841. // Manually shift all values starting at the index back to the
  10842. // beginning of the queue.
  10843. for (var scan = 0, newLength = queue.length - index; scan < newLength; scan++) {
  10844. queue[scan] = queue[scan + index];
  10845. }
  10846. queue.length -= index;
  10847. index = 0;
  10848. }
  10849. }
  10850. queue.length = 0;
  10851. index = 0;
  10852. flushing = false;
  10853. }
  10854. // `requestFlush` is implemented using a strategy based on data collected from
  10855. // every available SauceLabs Selenium web driver worker at time of writing.
  10856. // https://docs.google.com/spreadsheets/d/1mG-5UYGup5qxGdEMWkhP6BWCz053NUb2E1QoUTU16uA/edit#gid=783724593
  10857. // Safari 6 and 6.1 for desktop, iPad, and iPhone are the only browsers that
  10858. // have WebKitMutationObserver but not un-prefixed MutationObserver.
  10859. // Must use `global` or `self` instead of `window` to work in both frames and web
  10860. // workers. `global` is a provision of Browserify, Mr, Mrs, or Mop.
  10861. /* globals self */
  10862. var scope = typeof global !== "undefined" ? global : self;
  10863. var BrowserMutationObserver = scope.MutationObserver || scope.WebKitMutationObserver;
  10864. // MutationObservers are desirable because they have high priority and work
  10865. // reliably everywhere they are implemented.
  10866. // They are implemented in all modern browsers.
  10867. //
  10868. // - Android 4-4.3
  10869. // - Chrome 26-34
  10870. // - Firefox 14-29
  10871. // - Internet Explorer 11
  10872. // - iPad Safari 6-7.1
  10873. // - iPhone Safari 7-7.1
  10874. // - Safari 6-7
  10875. if (typeof BrowserMutationObserver === "function") {
  10876. requestFlush = makeRequestCallFromMutationObserver(flush);
  10877. // MessageChannels are desirable because they give direct access to the HTML
  10878. // task queue, are implemented in Internet Explorer 10, Safari 5.0-1, and Opera
  10879. // 11-12, and in web workers in many engines.
  10880. // Although message channels yield to any queued rendering and IO tasks, they
  10881. // would be better than imposing the 4ms delay of timers.
  10882. // However, they do not work reliably in Internet Explorer or Safari.
  10883. // Internet Explorer 10 is the only browser that has setImmediate but does
  10884. // not have MutationObservers.
  10885. // Although setImmediate yields to the browser's renderer, it would be
  10886. // preferrable to falling back to setTimeout since it does not have
  10887. // the minimum 4ms penalty.
  10888. // Unfortunately there appears to be a bug in Internet Explorer 10 Mobile (and
  10889. // Desktop to a lesser extent) that renders both setImmediate and
  10890. // MessageChannel useless for the purposes of ASAP.
  10891. // https://github.com/kriskowal/q/issues/396
  10892. // Timers are implemented universally.
  10893. // We fall back to timers in workers in most engines, and in foreground
  10894. // contexts in the following browsers.
  10895. // However, note that even this simple case requires nuances to operate in a
  10896. // broad spectrum of browsers.
  10897. //
  10898. // - Firefox 3-13
  10899. // - Internet Explorer 6-9
  10900. // - iPad Safari 4.3
  10901. // - Lynx 2.8.7
  10902. } else {
  10903. requestFlush = makeRequestCallFromTimer(flush);
  10904. }
  10905. // `requestFlush` requests that the high priority event queue be flushed as
  10906. // soon as possible.
  10907. // This is useful to prevent an error thrown in a task from stalling the event
  10908. // queue if the exception handled by Node.js’s
  10909. // `process.on("uncaughtException")` or by a domain.
  10910. rawAsap.requestFlush = requestFlush;
  10911. // To request a high priority event, we induce a mutation observer by toggling
  10912. // the text of a text node between "1" and "-1".
  10913. function makeRequestCallFromMutationObserver(callback) {
  10914. var toggle = 1;
  10915. var observer = new BrowserMutationObserver(callback);
  10916. var node = document.createTextNode("");
  10917. observer.observe(node, {characterData: true});
  10918. return function requestCall() {
  10919. toggle = -toggle;
  10920. node.data = toggle;
  10921. };
  10922. }
  10923. // The message channel technique was discovered by Malte Ubl and was the
  10924. // original foundation for this library.
  10925. // http://www.nonblocking.io/2011/06/windownexttick.html
  10926. // Safari 6.0.5 (at least) intermittently fails to create message ports on a
  10927. // page's first load. Thankfully, this version of Safari supports
  10928. // MutationObservers, so we don't need to fall back in that case.
  10929. // function makeRequestCallFromMessageChannel(callback) {
  10930. // var channel = new MessageChannel();
  10931. // channel.port1.onmessage = callback;
  10932. // return function requestCall() {
  10933. // channel.port2.postMessage(0);
  10934. // };
  10935. // }
  10936. // For reasons explained above, we are also unable to use `setImmediate`
  10937. // under any circumstances.
  10938. // Even if we were, there is another bug in Internet Explorer 10.
  10939. // It is not sufficient to assign `setImmediate` to `requestFlush` because
  10940. // `setImmediate` must be called *by name* and therefore must be wrapped in a
  10941. // closure.
  10942. // Never forget.
  10943. // function makeRequestCallFromSetImmediate(callback) {
  10944. // return function requestCall() {
  10945. // setImmediate(callback);
  10946. // };
  10947. // }
  10948. // Safari 6.0 has a problem where timers will get lost while the user is
  10949. // scrolling. This problem does not impact ASAP because Safari 6.0 supports
  10950. // mutation observers, so that implementation is used instead.
  10951. // However, if we ever elect to use timers in Safari, the prevalent work-around
  10952. // is to add a scroll event listener that calls for a flush.
  10953. // `setTimeout` does not call the passed callback if the delay is less than
  10954. // approximately 7 in web workers in Firefox 8 through 18, and sometimes not
  10955. // even then.
  10956. function makeRequestCallFromTimer(callback) {
  10957. return function requestCall() {
  10958. // We dispatch a timeout with a specified delay of 0 for engines that
  10959. // can reliably accommodate that request. This will usually be snapped
  10960. // to a 4 milisecond delay, but once we're flushing, there's no delay
  10961. // between events.
  10962. var timeoutHandle = setTimeout(handleTimer, 0);
  10963. // However, since this timer gets frequently dropped in Firefox
  10964. // workers, we enlist an interval handle that will try to fire
  10965. // an event 20 times per second until it succeeds.
  10966. var intervalHandle = setInterval(handleTimer, 50);
  10967. function handleTimer() {
  10968. // Whichever timer succeeds will cancel both timers and
  10969. // execute the callback.
  10970. clearTimeout(timeoutHandle);
  10971. clearInterval(intervalHandle);
  10972. callback();
  10973. }
  10974. };
  10975. }
  10976. // This is for `asap.js` only.
  10977. // Its name will be periodically randomized to break any code that depends on
  10978. // its existence.
  10979. rawAsap.makeRequestCallFromTimer = makeRequestCallFromTimer;
  10980. // ASAP was originally a nextTick shim included in Q. This was factored out
  10981. // into this ASAP package. It was later adapted to RSVP which made further
  10982. // amendments. These decisions, particularly to marginalize MessageChannel and
  10983. // to capture the MutationObserver implementation in a closure, were integrated
  10984. // back into ASAP proper.
  10985. // https://github.com/tildeio/rsvp.js/blob/cddf7232546a9cf858524b75cde6f9edf72620a7/lib/rsvp/asap.js
  10986. }).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
  10987. },{}],100:[function(require,module,exports){
  10988. var clone = (function() {
  10989. 'use strict';
  10990. function _instanceof(obj, type) {
  10991. return type != null && obj instanceof type;
  10992. }
  10993. var nativeMap;
  10994. try {
  10995. nativeMap = Map;
  10996. } catch(_) {
  10997. // maybe a reference error because no `Map`. Give it a dummy value that no
  10998. // value will ever be an instanceof.
  10999. nativeMap = function() {};
  11000. }
  11001. var nativeSet;
  11002. try {
  11003. nativeSet = Set;
  11004. } catch(_) {
  11005. nativeSet = function() {};
  11006. }
  11007. var nativePromise;
  11008. try {
  11009. nativePromise = Promise;
  11010. } catch(_) {
  11011. nativePromise = function() {};
  11012. }
  11013. /**
  11014. * Clones (copies) an Object using deep copying.
  11015. *
  11016. * This function supports circular references by default, but if you are certain
  11017. * there are no circular references in your object, you can save some CPU time
  11018. * by calling clone(obj, false).
  11019. *
  11020. * Caution: if `circular` is false and `parent` contains circular references,
  11021. * your program may enter an infinite loop and crash.
  11022. *
  11023. * @param `parent` - the object to be cloned
  11024. * @param `circular` - set to true if the object to be cloned may contain
  11025. * circular references. (optional - true by default)
  11026. * @param `depth` - set to a number if the object is only to be cloned to
  11027. * a particular depth. (optional - defaults to Infinity)
  11028. * @param `prototype` - sets the prototype to be used when cloning an object.
  11029. * (optional - defaults to parent prototype).
  11030. * @param `includeNonEnumerable` - set to true if the non-enumerable properties
  11031. * should be cloned as well. Non-enumerable properties on the prototype
  11032. * chain will be ignored. (optional - false by default)
  11033. */
  11034. function clone(parent, circular, depth, prototype, includeNonEnumerable) {
  11035. if (typeof circular === 'object') {
  11036. depth = circular.depth;
  11037. prototype = circular.prototype;
  11038. includeNonEnumerable = circular.includeNonEnumerable;
  11039. circular = circular.circular;
  11040. }
  11041. // maintain two arrays for circular references, where corresponding parents
  11042. // and children have the same index
  11043. var allParents = [];
  11044. var allChildren = [];
  11045. var useBuffer = typeof Buffer != 'undefined';
  11046. if (typeof circular == 'undefined')
  11047. circular = true;
  11048. if (typeof depth == 'undefined')
  11049. depth = Infinity;
  11050. // recurse this function so we don't reset allParents and allChildren
  11051. function _clone(parent, depth) {
  11052. // cloning null always returns null
  11053. if (parent === null)
  11054. return null;
  11055. if (depth === 0)
  11056. return parent;
  11057. var child;
  11058. var proto;
  11059. if (typeof parent != 'object') {
  11060. return parent;
  11061. }
  11062. if (_instanceof(parent, nativeMap)) {
  11063. child = new nativeMap();
  11064. } else if (_instanceof(parent, nativeSet)) {
  11065. child = new nativeSet();
  11066. } else if (_instanceof(parent, nativePromise)) {
  11067. child = new nativePromise(function (resolve, reject) {
  11068. parent.then(function(value) {
  11069. resolve(_clone(value, depth - 1));
  11070. }, function(err) {
  11071. reject(_clone(err, depth - 1));
  11072. });
  11073. });
  11074. } else if (clone.__isArray(parent)) {
  11075. child = [];
  11076. } else if (clone.__isRegExp(parent)) {
  11077. child = new RegExp(parent.source, __getRegExpFlags(parent));
  11078. if (parent.lastIndex) child.lastIndex = parent.lastIndex;
  11079. } else if (clone.__isDate(parent)) {
  11080. child = new Date(parent.getTime());
  11081. } else if (useBuffer && Buffer.isBuffer(parent)) {
  11082. if (Buffer.allocUnsafe) {
  11083. // Node.js >= 4.5.0
  11084. child = Buffer.allocUnsafe(parent.length);
  11085. } else {
  11086. // Older Node.js versions
  11087. child = new Buffer(parent.length);
  11088. }
  11089. parent.copy(child);
  11090. return child;
  11091. } else if (_instanceof(parent, Error)) {
  11092. child = Object.create(parent);
  11093. } else {
  11094. if (typeof prototype == 'undefined') {
  11095. proto = Object.getPrototypeOf(parent);
  11096. child = Object.create(proto);
  11097. }
  11098. else {
  11099. child = Object.create(prototype);
  11100. proto = prototype;
  11101. }
  11102. }
  11103. if (circular) {
  11104. var index = allParents.indexOf(parent);
  11105. if (index != -1) {
  11106. return allChildren[index];
  11107. }
  11108. allParents.push(parent);
  11109. allChildren.push(child);
  11110. }
  11111. if (_instanceof(parent, nativeMap)) {
  11112. parent.forEach(function(value, key) {
  11113. var keyChild = _clone(key, depth - 1);
  11114. var valueChild = _clone(value, depth - 1);
  11115. child.set(keyChild, valueChild);
  11116. });
  11117. }
  11118. if (_instanceof(parent, nativeSet)) {
  11119. parent.forEach(function(value) {
  11120. var entryChild = _clone(value, depth - 1);
  11121. child.add(entryChild);
  11122. });
  11123. }
  11124. for (var i in parent) {
  11125. var attrs;
  11126. if (proto) {
  11127. attrs = Object.getOwnPropertyDescriptor(proto, i);
  11128. }
  11129. if (attrs && attrs.set == null) {
  11130. continue;
  11131. }
  11132. child[i] = _clone(parent[i], depth - 1);
  11133. }
  11134. if (Object.getOwnPropertySymbols) {
  11135. var symbols = Object.getOwnPropertySymbols(parent);
  11136. for (var i = 0; i < symbols.length; i++) {
  11137. // Don't need to worry about cloning a symbol because it is a primitive,
  11138. // like a number or string.
  11139. var symbol = symbols[i];
  11140. var descriptor = Object.getOwnPropertyDescriptor(parent, symbol);
  11141. if (descriptor && !descriptor.enumerable && !includeNonEnumerable) {
  11142. continue;
  11143. }
  11144. child[symbol] = _clone(parent[symbol], depth - 1);
  11145. if (!descriptor.enumerable) {
  11146. Object.defineProperty(child, symbol, {
  11147. enumerable: false
  11148. });
  11149. }
  11150. }
  11151. }
  11152. if (includeNonEnumerable) {
  11153. var allPropertyNames = Object.getOwnPropertyNames(parent);
  11154. for (var i = 0; i < allPropertyNames.length; i++) {
  11155. var propertyName = allPropertyNames[i];
  11156. var descriptor = Object.getOwnPropertyDescriptor(parent, propertyName);
  11157. if (descriptor && descriptor.enumerable) {
  11158. continue;
  11159. }
  11160. child[propertyName] = _clone(parent[propertyName], depth - 1);
  11161. Object.defineProperty(child, propertyName, {
  11162. enumerable: false
  11163. });
  11164. }
  11165. }
  11166. return child;
  11167. }
  11168. return _clone(parent, depth);
  11169. }
  11170. /**
  11171. * Simple flat clone using prototype, accepts only objects, usefull for property
  11172. * override on FLAT configuration object (no nested props).
  11173. *
  11174. * USE WITH CAUTION! This may not behave as you wish if you do not know how this
  11175. * works.
  11176. */
  11177. clone.clonePrototype = function clonePrototype(parent) {
  11178. if (parent === null)
  11179. return null;
  11180. var c = function () {};
  11181. c.prototype = parent;
  11182. return new c();
  11183. };
  11184. // private utility functions
  11185. function __objToStr(o) {
  11186. return Object.prototype.toString.call(o);
  11187. }
  11188. clone.__objToStr = __objToStr;
  11189. function __isDate(o) {
  11190. return typeof o === 'object' && __objToStr(o) === '[object Date]';
  11191. }
  11192. clone.__isDate = __isDate;
  11193. function __isArray(o) {
  11194. return typeof o === 'object' && __objToStr(o) === '[object Array]';
  11195. }
  11196. clone.__isArray = __isArray;
  11197. function __isRegExp(o) {
  11198. return typeof o === 'object' && __objToStr(o) === '[object RegExp]';
  11199. }
  11200. clone.__isRegExp = __isRegExp;
  11201. function __getRegExpFlags(re) {
  11202. var flags = '';
  11203. if (re.global) flags += 'g';
  11204. if (re.ignoreCase) flags += 'i';
  11205. if (re.multiline) flags += 'm';
  11206. return flags;
  11207. }
  11208. clone.__getRegExpFlags = __getRegExpFlags;
  11209. return clone;
  11210. })();
  11211. if (typeof module === 'object' && module.exports) {
  11212. module.exports = clone;
  11213. }
  11214. },{}],101:[function(require,module,exports){
  11215. 'use strict';
  11216. var asap = require('asap/raw');
  11217. function noop() {}
  11218. // States:
  11219. //
  11220. // 0 - pending
  11221. // 1 - fulfilled with _value
  11222. // 2 - rejected with _value
  11223. // 3 - adopted the state of another promise, _value
  11224. //
  11225. // once the state is no longer pending (0) it is immutable
  11226. // All `_` prefixed properties will be reduced to `_{random number}`
  11227. // at build time to obfuscate them and discourage their use.
  11228. // We don't use symbols or Object.defineProperty to fully hide them
  11229. // because the performance isn't good enough.
  11230. // to avoid using try/catch inside critical functions, we
  11231. // extract them to here.
  11232. var LAST_ERROR = null;
  11233. var IS_ERROR = {};
  11234. function getThen(obj) {
  11235. try {
  11236. return obj.then;
  11237. } catch (ex) {
  11238. LAST_ERROR = ex;
  11239. return IS_ERROR;
  11240. }
  11241. }
  11242. function tryCallOne(fn, a) {
  11243. try {
  11244. return fn(a);
  11245. } catch (ex) {
  11246. LAST_ERROR = ex;
  11247. return IS_ERROR;
  11248. }
  11249. }
  11250. function tryCallTwo(fn, a, b) {
  11251. try {
  11252. fn(a, b);
  11253. } catch (ex) {
  11254. LAST_ERROR = ex;
  11255. return IS_ERROR;
  11256. }
  11257. }
  11258. module.exports = Promise;
  11259. function Promise(fn) {
  11260. if (typeof this !== 'object') {
  11261. throw new TypeError('Promises must be constructed via new');
  11262. }
  11263. if (typeof fn !== 'function') {
  11264. throw new TypeError('Promise constructor\'s argument is not a function');
  11265. }
  11266. this._40 = 0;
  11267. this._65 = 0;
  11268. this._55 = null;
  11269. this._72 = null;
  11270. if (fn === noop) return;
  11271. doResolve(fn, this);
  11272. }
  11273. Promise._37 = null;
  11274. Promise._87 = null;
  11275. Promise._61 = noop;
  11276. Promise.prototype.then = function(onFulfilled, onRejected) {
  11277. if (this.constructor !== Promise) {
  11278. return safeThen(this, onFulfilled, onRejected);
  11279. }
  11280. var res = new Promise(noop);
  11281. handle(this, new Handler(onFulfilled, onRejected, res));
  11282. return res;
  11283. };
  11284. function safeThen(self, onFulfilled, onRejected) {
  11285. return new self.constructor(function (resolve, reject) {
  11286. var res = new Promise(noop);
  11287. res.then(resolve, reject);
  11288. handle(self, new Handler(onFulfilled, onRejected, res));
  11289. });
  11290. }
  11291. function handle(self, deferred) {
  11292. while (self._65 === 3) {
  11293. self = self._55;
  11294. }
  11295. if (Promise._37) {
  11296. Promise._37(self);
  11297. }
  11298. if (self._65 === 0) {
  11299. if (self._40 === 0) {
  11300. self._40 = 1;
  11301. self._72 = deferred;
  11302. return;
  11303. }
  11304. if (self._40 === 1) {
  11305. self._40 = 2;
  11306. self._72 = [self._72, deferred];
  11307. return;
  11308. }
  11309. self._72.push(deferred);
  11310. return;
  11311. }
  11312. handleResolved(self, deferred);
  11313. }
  11314. function handleResolved(self, deferred) {
  11315. asap(function() {
  11316. var cb = self._65 === 1 ? deferred.onFulfilled : deferred.onRejected;
  11317. if (cb === null) {
  11318. if (self._65 === 1) {
  11319. resolve(deferred.promise, self._55);
  11320. } else {
  11321. reject(deferred.promise, self._55);
  11322. }
  11323. return;
  11324. }
  11325. var ret = tryCallOne(cb, self._55);
  11326. if (ret === IS_ERROR) {
  11327. reject(deferred.promise, LAST_ERROR);
  11328. } else {
  11329. resolve(deferred.promise, ret);
  11330. }
  11331. });
  11332. }
  11333. function resolve(self, newValue) {
  11334. // Promise Resolution Procedure: https://github.com/promises-aplus/promises-spec#the-promise-resolution-procedure
  11335. if (newValue === self) {
  11336. return reject(
  11337. self,
  11338. new TypeError('A promise cannot be resolved with itself.')
  11339. );
  11340. }
  11341. if (
  11342. newValue &&
  11343. (typeof newValue === 'object' || typeof newValue === 'function')
  11344. ) {
  11345. var then = getThen(newValue);
  11346. if (then === IS_ERROR) {
  11347. return reject(self, LAST_ERROR);
  11348. }
  11349. if (
  11350. then === self.then &&
  11351. newValue instanceof Promise
  11352. ) {
  11353. self._65 = 3;
  11354. self._55 = newValue;
  11355. finale(self);
  11356. return;
  11357. } else if (typeof then === 'function') {
  11358. doResolve(then.bind(newValue), self);
  11359. return;
  11360. }
  11361. }
  11362. self._65 = 1;
  11363. self._55 = newValue;
  11364. finale(self);
  11365. }
  11366. function reject(self, newValue) {
  11367. self._65 = 2;
  11368. self._55 = newValue;
  11369. if (Promise._87) {
  11370. Promise._87(self, newValue);
  11371. }
  11372. finale(self);
  11373. }
  11374. function finale(self) {
  11375. if (self._40 === 1) {
  11376. handle(self, self._72);
  11377. self._72 = null;
  11378. }
  11379. if (self._40 === 2) {
  11380. for (var i = 0; i < self._72.length; i++) {
  11381. handle(self, self._72[i]);
  11382. }
  11383. self._72 = null;
  11384. }
  11385. }
  11386. function Handler(onFulfilled, onRejected, promise){
  11387. this.onFulfilled = typeof onFulfilled === 'function' ? onFulfilled : null;
  11388. this.onRejected = typeof onRejected === 'function' ? onRejected : null;
  11389. this.promise = promise;
  11390. }
  11391. /**
  11392. * Take a potentially misbehaving resolver function and make sure
  11393. * onFulfilled and onRejected are only called once.
  11394. *
  11395. * Makes no guarantees about asynchrony.
  11396. */
  11397. function doResolve(fn, promise) {
  11398. var done = false;
  11399. var res = tryCallTwo(fn, function (value) {
  11400. if (done) return;
  11401. done = true;
  11402. resolve(promise, value);
  11403. }, function (reason) {
  11404. if (done) return;
  11405. done = true;
  11406. reject(promise, reason);
  11407. });
  11408. if (!done && res === IS_ERROR) {
  11409. done = true;
  11410. reject(promise, LAST_ERROR);
  11411. }
  11412. }
  11413. },{"asap/raw":99}],102:[function(require,module,exports){
  11414. 'use strict';
  11415. //This file contains the ES6 extensions to the core Promises/A+ API
  11416. var Promise = require('./core.js');
  11417. module.exports = Promise;
  11418. /* Static Functions */
  11419. var TRUE = valuePromise(true);
  11420. var FALSE = valuePromise(false);
  11421. var NULL = valuePromise(null);
  11422. var UNDEFINED = valuePromise(undefined);
  11423. var ZERO = valuePromise(0);
  11424. var EMPTYSTRING = valuePromise('');
  11425. function valuePromise(value) {
  11426. var p = new Promise(Promise._61);
  11427. p._65 = 1;
  11428. p._55 = value;
  11429. return p;
  11430. }
  11431. Promise.resolve = function (value) {
  11432. if (value instanceof Promise) return value;
  11433. if (value === null) return NULL;
  11434. if (value === undefined) return UNDEFINED;
  11435. if (value === true) return TRUE;
  11436. if (value === false) return FALSE;
  11437. if (value === 0) return ZERO;
  11438. if (value === '') return EMPTYSTRING;
  11439. if (typeof value === 'object' || typeof value === 'function') {
  11440. try {
  11441. var then = value.then;
  11442. if (typeof then === 'function') {
  11443. return new Promise(then.bind(value));
  11444. }
  11445. } catch (ex) {
  11446. return new Promise(function (resolve, reject) {
  11447. reject(ex);
  11448. });
  11449. }
  11450. }
  11451. return valuePromise(value);
  11452. };
  11453. Promise.all = function (arr) {
  11454. var args = Array.prototype.slice.call(arr);
  11455. return new Promise(function (resolve, reject) {
  11456. if (args.length === 0) return resolve([]);
  11457. var remaining = args.length;
  11458. function res(i, val) {
  11459. if (val && (typeof val === 'object' || typeof val === 'function')) {
  11460. if (val instanceof Promise && val.then === Promise.prototype.then) {
  11461. while (val._65 === 3) {
  11462. val = val._55;
  11463. }
  11464. if (val._65 === 1) return res(i, val._55);
  11465. if (val._65 === 2) reject(val._55);
  11466. val.then(function (val) {
  11467. res(i, val);
  11468. }, reject);
  11469. return;
  11470. } else {
  11471. var then = val.then;
  11472. if (typeof then === 'function') {
  11473. var p = new Promise(then.bind(val));
  11474. p.then(function (val) {
  11475. res(i, val);
  11476. }, reject);
  11477. return;
  11478. }
  11479. }
  11480. }
  11481. args[i] = val;
  11482. if (--remaining === 0) {
  11483. resolve(args);
  11484. }
  11485. }
  11486. for (var i = 0; i < args.length; i++) {
  11487. res(i, args[i]);
  11488. }
  11489. });
  11490. };
  11491. Promise.reject = function (value) {
  11492. return new Promise(function (resolve, reject) {
  11493. reject(value);
  11494. });
  11495. };
  11496. Promise.race = function (values) {
  11497. return new Promise(function (resolve, reject) {
  11498. values.forEach(function(value){
  11499. Promise.resolve(value).then(resolve, reject);
  11500. });
  11501. });
  11502. };
  11503. /* Prototype Methods */
  11504. Promise.prototype['catch'] = function (onRejected) {
  11505. return this.then(null, onRejected);
  11506. };
  11507. },{"./core.js":101}],103:[function(require,module,exports){
  11508. // should work in any browser without browserify
  11509. if (typeof Promise.prototype.done !== 'function') {
  11510. Promise.prototype.done = function (onFulfilled, onRejected) {
  11511. var self = arguments.length ? this.then.apply(this, arguments) : this
  11512. self.then(null, function (err) {
  11513. setTimeout(function () {
  11514. throw err
  11515. }, 0)
  11516. })
  11517. }
  11518. }
  11519. },{}],104:[function(require,module,exports){
  11520. // not "use strict" so we can declare global "Promise"
  11521. var asap = require('asap');
  11522. if (typeof Promise === 'undefined') {
  11523. Promise = require('./lib/core.js')
  11524. require('./lib/es6-extensions.js')
  11525. }
  11526. require('./polyfill-done.js');
  11527. },{"./lib/core.js":101,"./lib/es6-extensions.js":102,"./polyfill-done.js":103,"asap":98}]},{},[2])(2)
  11528. });