"+(b.type||"Syntax")+"Error: "+(b.message||"There is an error in your .less file")+'
in '+n+" ";var o=function(a,b,c){void 0!==a.extract[b]&&l.push(j.replace(/\{line\}/,(parseInt(a.line,10)||0)+(b-1)).replace(/\{class\}/,c).replace(/\{content\}/,a.extract[b]))};b.extract&&(o(b,0,""),o(b,1,"line"),o(b,2,""),h+="on line "+b.line+", column "+(b.column+1)+":
"+l.join("")+"
"),b.stack&&(b.extract||c.logLevel>=4)&&(h+=" Stack Trace"+b.stack.split("\n").slice(1).join(" ")),k.innerHTML=h,e.createCSS(a.document,[".less-error-message ul, .less-error-message li {","list-style-type: none;","margin-right: 15px;","padding: 4px 0;","margin: 0;","}",".less-error-message label {","font-size: 12px;","margin-right: 15px;","padding: 4px 0;","color: #cc7777;","}",".less-error-message pre {","color: #dd6666;","padding: 4px 0;","margin: 0;","display: inline-block;","}",".less-error-message pre.line {","color: #ff0000;","}",".less-error-message h3 {","font-size: 20px;","font-weight: bold;","padding: 15px 0 5px 0;","margin: 0;","}",".less-error-message a {","color: #10a","}",".less-error-message .error {","color: red;","font-weight: bold;","padding-bottom: 2px;","border-bottom: 1px dashed red;","}"].join("\n"),{title:"error-message"}),k.style.cssText=["font-family: Arial, sans-serif","border: 1px solid #e00","background-color: #eee","border-radius: 5px","-webkit-border-radius: 5px","-moz-border-radius: 5px","color: #e00","padding: 15px","margin-bottom: 15px"].join(";"),"development"===c.env&&(g=setInterval(function(){var b=a.document,c=b.body;c&&(b.getElementById(i)?c.replaceChild(k,b.getElementById(i)):c.insertBefore(k,c.firstChild),clearInterval(g))},10))}function g(b){var c=a.document.getElementById("less-error-message:"+d.extractId(b));c&&c.parentNode.removeChild(c)}function h(a){}function i(a){c.errorReporting&&"html"!==c.errorReporting?"console"===c.errorReporting?h(a):"function"==typeof c.errorReporting&&c.errorReporting("remove",a):g(a)}function j(a,d){var e="{line} {content}",f=a.filename||d,g=[],h=(a.type||"Syntax")+"Error: "+(a.message||"There is an error in your .less file")+" in "+f+" ",i=function(a,b,c){void 0!==a.extract[b]&&g.push(e.replace(/\{line\}/,(parseInt(a.line,10)||0)+(b-1)).replace(/\{class\}/,c).replace(/\{content\}/,a.extract[b]))};a.extract&&(i(a,0,""),i(a,1,"line"),i(a,2,""),h+="on line "+a.line+", column "+(a.column+1)+":\n"+g.join("\n")),a.stack&&(a.extract||c.logLevel>=4)&&(h+="\nStack Trace\n"+a.stack),b.logger.error(h)}function k(a,b){c.errorReporting&&"html"!==c.errorReporting?"console"===c.errorReporting?j(a,b):"function"==typeof c.errorReporting&&c.errorReporting("add",a,b):f(a,b)}return{add:k,remove:i}}},{"./browser":3,"./utils":10}],6:[function(a,b,c){b.exports=function(b,c){function d(){if(window.XMLHttpRequest&&!("file:"===window.location.protocol&&"ActiveXObject"in window))return new XMLHttpRequest;try{return new ActiveXObject("Microsoft.XMLHTTP")}catch(a){return c.error("browser doesn't support AJAX."),null}}var e=a("../less/environment/abstract-file-manager.js"),f={},g=function(){};return g.prototype=new e,g.prototype.alwaysMakePathsAbsolute=function(){return!0},g.prototype.join=function(a,b){return a?this.extractUrlParts(b,a).path:b},g.prototype.doXHR=function(a,e,f,g){function h(b,c,d){b.status>=200&&300>b.status?c(b.responseText,b.getResponseHeader("Last-Modified")):"function"==typeof d&&d(b.status,a)}var i=d(),j=b.isFileProtocol?b.fileAsync:!0;"function"==typeof i.overrideMimeType&&i.overrideMimeType("text/css"),c.debug("XHR: Getting '"+a+"'"),i.open("GET",a,j),i.setRequestHeader("Accept",e||"text/x-less, text/css; q=0.9, */*; q=0.5"),i.send(null),b.isFileProtocol&&!b.fileAsync?0===i.status||i.status>=200&&300>i.status?f(i.responseText):g(i.status,a):j?i.onreadystatechange=function(){4==i.readyState&&h(i,f,g)}:h(i,f,g)},g.prototype.supports=function(a,b,c,d){return!0},g.prototype.clearFileCache=function(){f={}},g.prototype.loadFile=function(a,b,c,d,e){b&&!this.isPathAbsolute(a)&&(a=b+a),c=c||{};var g=this.extractUrlParts(a,window.location.href),h=g.url;if(c.useFileCache&&f[h])try{var i=f[h];e(null,{contents:i,filename:h,webInfo:{lastModified:new Date}})}catch(j){e({filename:h,message:"Error loading file "+h+" error was "+j.message})}else this.doXHR(h,c.mime,function(a,b){f[h]=a,e(null,{contents:a,filename:h,webInfo:{lastModified:b}})},function(a,b){e({type:"File",message:"'"+b+"' wasn't found ("+a+")",href:h})})},g}},{"../less/environment/abstract-file-manager.js":15}],7:[function(a,b,c){b.exports=function(){function b(){throw{type:"Runtime",message:"Image size functions are not supported in browser version of less"}}var c=a("./../less/functions/function-registry"),d={"image-size":function(a){return b(this,a),-1},"image-width":function(a){return b(this,a),-1},"image-height":function(a){return b(this,a),-1}};c.addMultiple(d)}},{"./../less/functions/function-registry":22}],8:[function(a,b,c){var d=a("./utils").addDataAttr,e=a("./browser");b.exports=function(b,c){function f(a){return c.postProcessor&&"function"==typeof c.postProcessor&&(a=c.postProcessor.call(a,a)||a),a}function g(a){var b={};for(var c in a)a.hasOwnProperty(c)&&(b[c]=a[c]);return b}function h(a,b){var c=Array.prototype.slice.call(arguments,2);return function(){var d=c.concat(Array.prototype.slice.call(arguments,0));return a.apply(b,d)}}function i(a){for(var b,d=m.getElementsByTagName("style"),e=0;d.length>e;e++)if(b=d[e],b.type.match(t)){var f=g(c);f.modifyVars=a;var i=b.innerHTML||"";f.filename=m.location.href.replace(/#.*$/,""),n.render(i,f,h(function(a,b,c){b?r.add(b,"inline"):(a.type="text/css",a.styleSheet?a.styleSheet.cssText=c.css:a.innerHTML=c.css)},null,b))}}function j(a,b,e,h,i){function j(c){var d=c.contents,g=c.filename,i=c.webInfo,j={currentDirectory:q.getPath(g),filename:g,rootFilename:g,relativeUrls:k.relativeUrls};if(j.entryPath=j.currentDirectory,j.rootpath=k.rootpath||j.currentDirectory,i){i.remaining=h;var l=s.getCSS(g,i,k.modifyVars);if(!e&&l)return i.local=!0,void b(null,l,d,a,i,g)}r.remove(g),k.rootFileInfo=j,n.render(d,k,function(c,e){c?(c.href=g,b(c)):(e.css=f(e.css),s.setCSS(a.href,i.lastModified,k.modifyVars,e.css),b(null,e.css,d,a,i,g))})}var k=g(c);d(k,a),k.mime=a.type,i&&(k.modifyVars=i),q.loadFile(a.href,null,k,o,function(a,c){return a?void b(a):void j(c)})}function k(a,b,c){for(var d=0;n.sheets.length>d;d++)j(n.sheets[d],a,b,n.sheets.length-(d+1),c)}function l(){"development"===n.env&&(n.watchTimer=setInterval(function(){n.watchMode&&(q.clearFileCache(),k(function(a,c,d,f,g){a?r.add(a,a.href||f.href):c&&e.createCSS(b.document,c,f)}))},c.poll))}var m=b.document,n=a("../less")();n.options=c;var o=n.environment,p=a("./file-manager")(c,n.logger),q=new p;o.addFileManager(q),n.FileManager=p,a("./log-listener")(n,c);var r=a("./error-reporting")(b,n,c),s=n.cache=c.cache||a("./cache")(b,c,n.logger);a("./image-size")(n.environment),c.functions&&n.functions.functionRegistry.addMultiple(c.functions);var t=/^text\/(x-)?less$/;return n.watch=function(){return n.watchMode||(n.env="development",l()),this.watchMode=!0,!0},n.unwatch=function(){return clearInterval(n.watchTimer),this.watchMode=!1,!1},n.registerStylesheetsImmediately=function(){var a=m.getElementsByTagName("link");n.sheets=[];for(var b=0;a.length>b;b++)("stylesheet/less"===a[b].rel||a[b].rel.match(/stylesheet/)&&a[b].type.match(t))&&n.sheets.push(a[b])},n.registerStylesheets=function(){return new Promise(function(a,b){n.registerStylesheetsImmediately(),a()})},n.modifyVars=function(a){return n.refresh(!0,a,!1)},n.refresh=function(a,c,d){return(a||d)&&d!==!1&&q.clearFileCache(),new Promise(function(d,f){var g,h,j,l;g=h=new Date,l=n.sheets.length,0===l?(h=new Date,j=h-g,n.logger.info("Less has finished and no sheets were loaded."),d({startTime:g,endTime:h,totalMilliseconds:j,sheets:n.sheets.length})):k(function(a,c,i,k,m){return a?(r.add(a,a.href||k.href),void f(a)):(n.logger.info(m.local?"Loading "+k.href+" from cache.":"Rendered "+k.href+" successfully."),e.createCSS(b.document,c,k),n.logger.info("CSS for "+k.href+" generated in "+(new Date-h)+"ms"),l--,0===l&&(j=new Date-g,n.logger.info("Less has finished. CSS generated in "+j+"ms"),d({startTime:g,endTime:h,totalMilliseconds:j,sheets:n.sheets.length})),void(h=new Date))},a,c),i(c)})},n.refreshStyles=i,n}},{"../less":31,"./browser":3,"./cache":4,"./error-reporting":5,"./file-manager":6,"./image-size":7,"./log-listener":9,"./utils":10}],9:[function(a,b,c){b.exports=function(a,b){var c=4,d=3,e=2,f=1;b.logLevel="undefined"!=typeof b.logLevel?b.logLevel:"development"===b.env?d:f,b.loggers||(b.loggers=[{debug:function(a){b.logLevel>=c&&console.log(a)},info:function(a){b.logLevel>=d&&console.log(a)},warn:function(a){b.logLevel>=e&&console.warn(a)},error:function(a){b.logLevel>=f&&console.error(a)}}]);for(var g=0;b.loggers.length>g;g++)a.logger.addListener(b.loggers[g])}},{}],10:[function(a,b,c){b.exports={extractId:function(a){return a.replace(/^[a-z-]+:\/+?[^\/]+/,"").replace(/[\?\&]livereload=\w+/,"").replace(/^\//,"").replace(/\.[a-zA-Z]+$/,"").replace(/[^\.\w-]+/g,"-").replace(/\./g,":")},addDataAttr:function(a,b){for(var c in b.dataset)if(b.dataset.hasOwnProperty(c))if("env"===c||"dumpLineNumbers"===c||"rootpath"===c||"errorReporting"===c)a[c]=b.dataset[c];else try{a[c]=JSON.parse(b.dataset[c])}catch(d){}}}},{}],11:[function(a,b,c){var d={};b.exports=d;var e=function(a,b,c){if(a)for(var d=0;c.length>d;d++)a.hasOwnProperty(c[d])&&(b[c[d]]=a[c[d]])},f=["paths","relativeUrls","rootpath","strictImports","insecure","dumpLineNumbers","compress","syncImport","chunkInput","mime","useFileCache","processImports","pluginManager"];d.Parse=function(a){e(a,this,f),"string"==typeof this.paths&&(this.paths=[this.paths])};var g=["paths","compress","ieCompat","strictMath","strictUnits","sourceMap","importMultiple","urlArgs","javascriptEnabled","pluginManager","importantScope"];d.Eval=function(a,b){e(a,this,g),"string"==typeof this.paths&&(this.paths=[this.paths]),this.frames=b||[],this.importantScope=this.importantScope||[]},d.Eval.prototype.inParenthesis=function(){this.parensStack||(this.parensStack=[]),this.parensStack.push(!0)},d.Eval.prototype.outOfParenthesis=function(){this.parensStack.pop()},d.Eval.prototype.isMathOn=function(){return this.strictMath?this.parensStack&&this.parensStack.length:!0},d.Eval.prototype.isPathRelative=function(a){return!/^(?:[a-z-]+:|\/|#)/i.test(a)},d.Eval.prototype.normalizePath=function(a){var b,c=a.split("/").reverse();for(a=[];0!==c.length;)switch(b=c.pop()){case".":break;case"..":0===a.length||".."===a[a.length-1]?a.push(b):a.pop();break;default:a.push(b)}return a.join("/")}},{}],12:[function(a,b,c){b.exports={aliceblue:"#f0f8ff",antiquewhite:"#faebd7",aqua:"#00ffff",aquamarine:"#7fffd4",azure:"#f0ffff",beige:"#f5f5dc",bisque:"#ffe4c4",black:"#000000",blanchedalmond:"#ffebcd",blue:"#0000ff",blueviolet:"#8a2be2",brown:"#a52a2a",burlywood:"#deb887",cadetblue:"#5f9ea0",chartreuse:"#7fff00",chocolate:"#d2691e",coral:"#ff7f50",cornflowerblue:"#6495ed",cornsilk:"#fff8dc",crimson:"#dc143c",cyan:"#00ffff",darkblue:"#00008b",darkcyan:"#008b8b",darkgoldenrod:"#b8860b",darkgray:"#a9a9a9",darkgrey:"#a9a9a9",darkgreen:"#006400",darkkhaki:"#bdb76b",darkmagenta:"#8b008b",darkolivegreen:"#556b2f",darkorange:"#ff8c00",darkorchid:"#9932cc",darkred:"#8b0000",darksalmon:"#e9967a",darkseagreen:"#8fbc8f",darkslateblue:"#483d8b",darkslategray:"#2f4f4f",darkslategrey:"#2f4f4f",darkturquoise:"#00ced1",darkviolet:"#9400d3",deeppink:"#ff1493",deepskyblue:"#00bfff",dimgray:"#696969",dimgrey:"#696969",dodgerblue:"#1e90ff",firebrick:"#b22222",floralwhite:"#fffaf0",forestgreen:"#228b22",fuchsia:"#ff00ff",gainsboro:"#dcdcdc",ghostwhite:"#f8f8ff",gold:"#ffd700",goldenrod:"#daa520",gray:"#808080",grey:"#808080",green:"#008000",greenyellow:"#adff2f",honeydew:"#f0fff0",hotpink:"#ff69b4",indianred:"#cd5c5c",indigo:"#4b0082",ivory:"#fffff0",khaki:"#f0e68c",lavender:"#e6e6fa",lavenderblush:"#fff0f5",lawngreen:"#7cfc00",lemonchiffon:"#fffacd",lightblue:"#add8e6",lightcoral:"#f08080",lightcyan:"#e0ffff",lightgoldenrodyellow:"#fafad2",lightgray:"#d3d3d3",lightgrey:"#d3d3d3",lightgreen:"#90ee90",lightpink:"#ffb6c1",lightsalmon:"#ffa07a",lightseagreen:"#20b2aa",lightskyblue:"#87cefa",lightslategray:"#778899",lightslategrey:"#778899",lightsteelblue:"#b0c4de",lightyellow:"#ffffe0",lime:"#00ff00",limegreen:"#32cd32",linen:"#faf0e6",magenta:"#ff00ff",maroon:"#800000",mediumaquamarine:"#66cdaa",mediumblue:"#0000cd",mediumorchid:"#ba55d3",mediumpurple:"#9370d8",mediumseagreen:"#3cb371",mediumslateblue:"#7b68ee",mediumspringgreen:"#00fa9a",mediumturquoise:"#48d1cc",mediumvioletred:"#c71585",midnightblue:"#191970",mintcream:"#f5fffa",mistyrose:"#ffe4e1",moccasin:"#ffe4b5",navajowhite:"#ffdead",navy:"#000080",oldlace:"#fdf5e6",olive:"#808000",olivedrab:"#6b8e23",orange:"#ffa500",orangered:"#ff4500",orchid:"#da70d6",palegoldenrod:"#eee8aa",palegreen:"#98fb98",paleturquoise:"#afeeee",palevioletred:"#d87093",papayawhip:"#ffefd5",peachpuff:"#ffdab9",peru:"#cd853f",pink:"#ffc0cb",plum:"#dda0dd",powderblue:"#b0e0e6",purple:"#800080",rebeccapurple:"#663399",red:"#ff0000",rosybrown:"#bc8f8f",royalblue:"#4169e1",saddlebrown:"#8b4513",salmon:"#fa8072",sandybrown:"#f4a460",seagreen:"#2e8b57",seashell:"#fff5ee",sienna:"#a0522d",silver:"#c0c0c0",skyblue:"#87ceeb",slateblue:"#6a5acd",slategray:"#708090",slategrey:"#708090",snow:"#fffafa",springgreen:"#00ff7f",steelblue:"#4682b4",tan:"#d2b48c",teal:"#008080",thistle:"#d8bfd8",tomato:"#ff6347",turquoise:"#40e0d0",violet:"#ee82ee",wheat:"#f5deb3",white:"#ffffff",whitesmoke:"#f5f5f5",yellow:"#ffff00",yellowgreen:"#9acd32"}},{}],13:[function(a,b,c){b.exports={colors:a("./colors"),unitConversions:a("./unit-conversions")}},{"./colors":12,"./unit-conversions":14}],14:[function(a,b,c){b.exports={length:{m:1,cm:.01,mm:.001,"in":.0254,px:.0254/96,pt:.0254/72,pc:.0254/72*12},duration:{s:1,ms:.001},angle:{rad:1/(2*Math.PI),deg:1/360,grad:.0025,turn:1}}},{}],15:[function(a,b,c){var d=function(){};d.prototype.getPath=function(a){var b=a.lastIndexOf("?");return b>0&&(a=a.slice(0,b)),b=a.lastIndexOf("/"),0>b&&(b=a.lastIndexOf("\\")),0>b?"":a.slice(0,b+1)},d.prototype.tryAppendExtension=function(a,b){return/(\.[a-z]*$)|([\?;].*)$/.test(a)?a:a+b},d.prototype.tryAppendLessExtension=function(a){return this.tryAppendExtension(a,".less")},d.prototype.supportsSync=function(){return!1},d.prototype.alwaysMakePathsAbsolute=function(){return!1},d.prototype.isPathAbsolute=function(a){return/^(?:[a-z-]+:|\/|\\|#)/i.test(a)},d.prototype.join=function(a,b){return a?a+b:b},d.prototype.pathDiff=function(a,b){var c,d,e,f,g=this.extractUrlParts(a),h=this.extractUrlParts(b),i="";if(g.hostPart!==h.hostPart)return"";for(d=Math.max(h.directories.length,g.directories.length),c=0;d>c&&h.directories[c]===g.directories[c];c++);for(f=h.directories.slice(c),e=g.directories.slice(c),c=0;f.length-1>c;c++)i+="../";for(c=0;e.length-1>c;c++)i+=e[c]+"/";return i},d.prototype.extractUrlParts=function(a,b){var c,d,e=/^((?:[a-z-]+:)?\/{2}(?:[^\/\?#]*\/)|([\/\\]))?((?:[^\/\\\?#]*[\/\\])*)([^\/\\\?#]*)([#\?].*)?$/i,f=a.match(e),g={},h=[];if(!f)throw new Error("Could not parse sheet href - '"+a+"'");if(b&&(!f[1]||f[2])){if(d=b.match(e),!d)throw new Error("Could not parse page url - '"+b+"'");f[1]=f[1]||d[1]||"",f[2]||(f[3]=d[3]+f[3])}if(f[3]){for(h=f[3].replace(/\\/g,"/").split("/"),c=0;h.length>c;c++)"."===h[c]&&(h.splice(c,1),c-=1);for(c=0;h.length>c;c++)".."===h[c]&&c>0&&(h.splice(c-1,2),c-=2)}return g.hostPart=f[1],g.directories=h,g.path=(f[1]||"")+h.join("/"),g.fileUrl=g.path+(f[4]||""),g.url=g.fileUrl+(f[5]||""),g},b.exports=d},{}],16:[function(a,b,c){var d=a("../logger"),e=function(a,b){this.fileManagers=b||[],a=a||{};for(var c=["encodeBase64","mimeLookup","charsetLookup","getSourceMapGenerator"],d=[],e=d.concat(c),f=0;e.length>f;f++){var g=e[f],h=a[g];h?this[g]=h.bind(a):d.length>f&&this.warn("missing required function in environment - "+g)}};e.prototype.getFileManager=function(a,b,c,e,f){a||d.warn("getFileManager called with no filename.. Please report this issue. continuing."),null==b&&d.warn("getFileManager called with null directory.. Please report this issue. continuing.");var g=this.fileManagers;c.pluginManager&&(g=[].concat(g).concat(c.pluginManager.getFileManagers()));for(var h=g.length-1;h>=0;h--){var i=g[h];if(i[f?"supportsSync":"supports"](a,b,c,e))return i}return null},e.prototype.addFileManager=function(a){this.fileManagers.push(a)},e.prototype.clearFileManagers=function(){this.fileManagers=[]},b.exports=e},{"../logger":33}],17:[function(a,b,c){function d(a,b,c){var d,f,g,h,i=b.alpha,j=c.alpha,k=[];g=j+i*(1-j);for(var l=0;3>l;l++)d=b.rgb[l]/255,f=c.rgb[l]/255,h=a(d,f),g&&(h=(j*f+i*(d-j*(d+f-h)))/g),k[l]=255*h;return new e(k,g)}var e=a("../tree/color"),f=a("./function-registry"),g={multiply:function(a,b){return a*b},screen:function(a,b){return a+b-a*b},overlay:function(a,b){return a*=2,1>=a?g.multiply(a,b):g.screen(a-1,b)},softlight:function(a,b){var c=1,d=a;return b>.5&&(d=1,c=a>.25?Math.sqrt(a):((16*a-12)*a+4)*a),a-(1-2*b)*d*(c-a)},hardlight:function(a,b){return g.overlay(b,a)},difference:function(a,b){return Math.abs(a-b)},exclusion:function(a,b){return a+b-2*a*b},average:function(a,b){return(a+b)/2},negation:function(a,b){return 1-Math.abs(a+b-1)}};for(var h in g)g.hasOwnProperty(h)&&(d[h]=d.bind(null,g[h]));f.addMultiple(d)},{"../tree/color":50,"./function-registry":22}],18:[function(a,b,c){function d(a){return Math.min(1,Math.max(0,a))}function e(a){return h.hsla(a.h,a.s,a.l,a.a)}function f(a){if(a instanceof i)return parseFloat(a.unit.is("%")?a.value/100:a.value);if("number"==typeof a)return a;throw{type:"Argument",message:"color functions take numbers as parameters"}}function g(a,b){return a instanceof i&&a.unit.is("%")?parseFloat(a.value*b/100):f(a)}var h,i=a("../tree/dimension"),j=a("../tree/color"),k=a("../tree/quoted"),l=a("../tree/anonymous"),m=a("./function-registry");h={rgb:function(a,b,c){return h.rgba(a,b,c,1)},rgba:function(a,b,c,d){var e=[a,b,c].map(function(a){return g(a,255)});return d=f(d),new j(e,d)},hsl:function(a,b,c){return h.hsla(a,b,c,1)},hsla:function(a,b,c,e){function g(a){return a=0>a?a+1:a>1?a-1:a,1>6*a?i+(j-i)*a*6:1>2*a?j:2>3*a?i+(j-i)*(2/3-a)*6:i}var i,j;return a=f(a)%360/360,b=d(f(b)),c=d(f(c)),e=d(f(e)),j=.5>=c?c*(b+1):c+b-c*b,i=2*c-j,h.rgba(255*g(a+1/3),255*g(a),255*g(a-1/3),e)},hsv:function(a,b,c){return h.hsva(a,b,c,1)},hsva:function(a,b,c,d){a=f(a)%360/360*360,b=f(b),c=f(c),d=f(d);var e,g;e=Math.floor(a/60%6),g=a/60-e;var i=[c,c*(1-b),c*(1-g*b),c*(1-(1-g)*b)],j=[[0,3,1],[2,0,1],[1,0,3],[1,2,0],[3,1,0],[0,1,2]];return h.rgba(255*i[j[e][0]],255*i[j[e][1]],255*i[j[e][2]],d)},hue:function(a){return new i(a.toHSL().h)},saturation:function(a){return new i(100*a.toHSL().s,"%")},lightness:function(a){return new i(100*a.toHSL().l,"%")},hsvhue:function(a){return new i(a.toHSV().h)},hsvsaturation:function(a){return new i(100*a.toHSV().s,"%")},hsvvalue:function(a){return new i(100*a.toHSV().v,"%")},red:function(a){return new i(a.rgb[0])},green:function(a){return new i(a.rgb[1])},blue:function(a){return new i(a.rgb[2])},alpha:function(a){return new i(a.toHSL().a)},luma:function(a){return new i(a.luma()*a.alpha*100,"%")},luminance:function(a){var b=.2126*a.rgb[0]/255+.7152*a.rgb[1]/255+.0722*a.rgb[2]/255;return new i(b*a.alpha*100,"%")},saturate:function(a,b,c){if(!a.rgb)return null;var f=a.toHSL();return f.s+="undefined"!=typeof c&&"relative"===c.value?f.s*b.value/100:b.value/100,f.s=d(f.s),e(f)},desaturate:function(a,b,c){var f=a.toHSL();return f.s-="undefined"!=typeof c&&"relative"===c.value?f.s*b.value/100:b.value/100,f.s=d(f.s),e(f)},lighten:function(a,b,c){var f=a.toHSL();return f.l+="undefined"!=typeof c&&"relative"===c.value?f.l*b.value/100:b.value/100,f.l=d(f.l),e(f)},darken:function(a,b,c){var f=a.toHSL();return f.l-="undefined"!=typeof c&&"relative"===c.value?f.l*b.value/100:b.value/100,f.l=d(f.l),e(f)},fadein:function(a,b,c){var f=a.toHSL();return f.a+="undefined"!=typeof c&&"relative"===c.value?f.a*b.value/100:b.value/100,f.a=d(f.a),e(f)},fadeout:function(a,b,c){var f=a.toHSL();return f.a-="undefined"!=typeof c&&"relative"===c.value?f.a*b.value/100:b.value/100,f.a=d(f.a),e(f)},fade:function(a,b){var c=a.toHSL();return c.a=b.value/100,c.a=d(c.a),e(c)},spin:function(a,b){var c=a.toHSL(),d=(c.h+b.value)%360;return c.h=0>d?360+d:d,e(c)},mix:function(a,b,c){a.toHSL&&b.toHSL||(console.log(b.type),console.dir(b)),c||(c=new i(50));var d=c.value/100,e=2*d-1,f=a.toHSL().a-b.toHSL().a,g=((e*f==-1?e:(e+f)/(1+e*f))+1)/2,h=1-g,k=[a.rgb[0]*g+b.rgb[0]*h,a.rgb[1]*g+b.rgb[1]*h,a.rgb[2]*g+b.rgb[2]*h],l=a.alpha*d+b.alpha*(1-d);return new j(k,l)},greyscale:function(a){return h.desaturate(a,new i(100))},contrast:function(a,b,c,d){if(!a.rgb)return null;"undefined"==typeof b&&(b=h.rgba(0,0,0,1)),"undefined"==typeof c&&(c=h.rgba(255,255,255,1));var e,f,g=a.luma(),i=b.luma(),j=c.luma();return e=g>i?(g+.05)/(i+.05):(i+.05)/(g+.05),f=g>j?(g+.05)/(j+.05):(j+.05)/(g+.05),e>f?b:c},argb:function(a){return new l(a.toARGB())},color:function(a){if(a instanceof k&&/^#([a-f0-9]{6}|[a-f0-9]{3})$/i.test(a.value))return new j(a.value.slice(1));if(a instanceof j||(a=j.fromKeyword(a.value)))return a.value=void 0,a;throw{type:"Argument",message:"argument must be a color keyword or 3/6 digit hex e.g. #FFF"}},tint:function(a,b){return h.mix(h.rgb(255,255,255),a,b)},shade:function(a,b){return h.mix(h.rgb(0,0,0),a,b)}},m.addMultiple(h)},{"../tree/anonymous":46,"../tree/color":50,"../tree/dimension":56,"../tree/quoted":73,"./function-registry":22}],19:[function(a,b,c){b.exports=function(b){var c=a("../tree/quoted"),d=a("../tree/url"),e=a("./function-registry"),f=function(a,b){return new d(b,a.index,a.currentFileInfo).eval(a.context)},g=a("../logger");e.add("data-uri",function(a,e){e||(e=a,a=null);var h=a&&a.value,i=e.value,j=this.currentFileInfo,k=j.relativeUrls?j.currentDirectory:j.entryPath,l=i.indexOf("#"),m="";-1!==l&&(m=i.slice(l),i=i.slice(0,l));var n=b.getFileManager(i,k,this.context,b,!0);if(!n)return f(this,e);var o=!1;if(a)o=/;base64$/.test(h);else{if(h=b.mimeLookup(i),"image/svg+xml"===h)o=!1;else{var p=b.charsetLookup(h);o=["US-ASCII","UTF-8"].indexOf(p)<0}o&&(h+=";base64")}var q=n.loadFileSync(i,k,this.context,b);if(!q.contents)return g.warn("Skipped data-uri embedding of "+i+" because file not found"),f(this,e||a);var r=q.contents;if(o&&!b.encodeBase64)return f(this,e);r=o?b.encodeBase64(r):encodeURIComponent(r);var s="data:"+h+","+r+m,t=32768;return s.length>=t&&this.context.ieCompat!==!1?(g.warn("Skipped data-uri embedding of "+i+" because its size ("+s.length+" characters) exceeds IE8-safe "+t+" characters!"),f(this,e||a)):new d(new c('"'+s+'"',s,!1,this.index,this.currentFileInfo),this.index,this.currentFileInfo)})}},{"../logger":33,"../tree/quoted":73,"../tree/url":80,"./function-registry":22}],20:[function(a,b,c){var d=a("../tree/keyword"),e=a("./function-registry"),f={eval:function(){var a=this.value_,b=this.error_;if(b)throw b;return null!=a?a?d.True:d.False:void 0},value:function(a){this.value_=a},error:function(a){this.error_=a},reset:function(){this.value_=this.error_=null}};e.add("default",f.eval.bind(f)),b.exports=f},{"../tree/keyword":65,"./function-registry":22}],21:[function(a,b,c){var d=a("../tree/expression"),e=function(a,b,c,d){this.name=a.toLowerCase(),this.index=c,this.context=b,this.currentFileInfo=d,this.func=b.frames[0].functionRegistry.get(this.name)};e.prototype.isValid=function(){return Boolean(this.func)},e.prototype.call=function(a){return Array.isArray(a)&&(a=a.filter(function(a){return"Comment"!==a.type}).map(function(a){if("Expression"===a.type){var b=a.value.filter(function(a){return"Comment"!==a.type});return 1===b.length?b[0]:new d(b)}return a})),this.func.apply(this,a)},b.exports=e},{"../tree/expression":59}],22:[function(a,b,c){function d(a){return{_data:{},add:function(a,b){a=a.toLowerCase(),this._data.hasOwnProperty(a),this._data[a]=b},addMultiple:function(a){Object.keys(a).forEach(function(b){this.add(b,a[b])}.bind(this))},get:function(b){return this._data[b]||a&&a.get(b)},inherit:function(){return d(this)}}}b.exports=d(null)},{}],23:[function(a,b,c){b.exports=function(b){var c={functionRegistry:a("./function-registry"),functionCaller:a("./function-caller")};return a("./default"),a("./color"),a("./color-blending"),a("./data-uri")(b),a("./math"),a("./number"),a("./string"),a("./svg")(b),a("./types"),c}},{"./color":18,"./color-blending":17,"./data-uri":19,"./default":20,"./function-caller":21,"./function-registry":22,"./math":25,"./number":26,"./string":27,"./svg":28,"./types":29}],24:[function(a,b,c){var d=a("../tree/dimension"),e=function(){};e._math=function(a,b,c){if(!(c instanceof d))throw{type:"Argument",message:"argument must be a number"};return null==b?b=c.unit:c=c.unify(),new d(a(parseFloat(c.value)),b)},b.exports=e},{"../tree/dimension":56}],25:[function(a,b,c){var d=a("./function-registry"),e=a("./math-helper.js"),f={ceil:null,floor:null,sqrt:null,abs:null,tan:"",sin:"",cos:"",atan:"rad",asin:"rad",acos:"rad"};for(var g in f)f.hasOwnProperty(g)&&(f[g]=e._math.bind(null,Math[g],f[g]));f.round=function(a,b){var c="undefined"==typeof b?0:b.value;return e._math(function(a){return a.toFixed(c)},null,a)},d.addMultiple(f)},{"./function-registry":22,"./math-helper.js":24}],26:[function(a,b,c){var d=a("../tree/dimension"),e=a("../tree/anonymous"),f=a("./function-registry"),g=a("./math-helper.js"),h=function(a,b){switch(b=Array.prototype.slice.call(b),b.length){case 0:throw{type:"Argument",message:"one or more arguments required"}}var c,f,g,h,i,j,k,l,m=[],n={};for(c=0;b.length>c;c++)if(g=b[c],g instanceof d)if(h=""===g.unit.toString()&&void 0!==l?new d(g.value,l).unify():g.unify(),j=""===h.unit.toString()&&void 0!==k?k:h.unit.toString(),k=""!==j&&void 0===k||""!==j&&""===m[0].unify().unit.toString()?j:k,l=""!==j&&void 0===l?g.unit.toString():l,f=void 0!==n[""]&&""!==j&&j===k?n[""]:n[j],void 0!==f)i=""===m[f].unit.toString()&&void 0!==l?new d(m[f].value,l).unify():m[f].unify(),(a&&i.value>h.value||!a&&h.value>i.value)&&(m[f]=g);else{if(void 0!==k&&j!==k)throw{type:"Argument",message:"incompatible types"};n[j]=m.length,m.push(g)}else Array.isArray(b[c].value)&&Array.prototype.push.apply(b,Array.prototype.slice.call(b[c].value));return 1==m.length?m[0]:(b=m.map(function(a){return a.toCSS(this.context)}).join(this.context.compress?",":", "),new e((a?"min":"max")+"("+b+")"))};f.addMultiple({min:function(){return h(!0,arguments)},max:function(){return h(!1,arguments)},convert:function(a,b){return a.convertTo(b.value)},pi:function(){return new d(Math.PI)},mod:function(a,b){return new d(a.value%b.value,a.unit)},pow:function(a,b){if("number"==typeof a&&"number"==typeof b)a=new d(a),b=new d(b);else if(!(a instanceof d&&b instanceof d))throw{type:"Argument",message:"arguments must be numbers"};return new d(Math.pow(a.value,b.value),a.unit)},percentage:function(a){var b=g._math(function(a){return 100*a},"%",a);return b}})},{"../tree/anonymous":46,"../tree/dimension":56,"./function-registry":22,"./math-helper.js":24}],27:[function(a,b,c){var d=a("../tree/quoted"),e=a("../tree/anonymous"),f=a("../tree/javascript"),g=a("./function-registry");g.addMultiple({e:function(a){return new e(a instanceof f?a.evaluated:a.value)},escape:function(a){return new e(encodeURI(a.value).replace(/=/g,"%3D").replace(/:/g,"%3A").replace(/#/g,"%23").replace(/;/g,"%3B").replace(/\(/g,"%28").replace(/\)/g,"%29"))},replace:function(a,b,c,e){var f=a.value;return c="Quoted"===c.type?c.value:c.toCSS(),f=f.replace(new RegExp(b.value,e?e.value:""),c),new d(a.quote||"",f,a.escaped)},"%":function(a){for(var b=Array.prototype.slice.call(arguments,1),c=a.value,e=0;b.length>e;e++)c=c.replace(/%[sda]/i,function(a){var c="Quoted"===b[e].type&&a.match(/s/i)?b[e].value:b[e].toCSS();return a.match(/[A-Z]$/)?encodeURIComponent(c):c});return c=c.replace(/%%/g,"%"),new d(a.quote||"",c,a.escaped);
-}})},{"../tree/anonymous":46,"../tree/javascript":63,"../tree/quoted":73,"./function-registry":22}],28:[function(a,b,c){b.exports=function(b){var c=a("../tree/dimension"),d=a("../tree/color"),e=a("../tree/expression"),f=a("../tree/quoted"),g=a("../tree/url"),h=a("./function-registry");h.add("svg-gradient",function(a){function b(){throw{type:"Argument",message:"svg-gradient expects direction, start_color [start_position], [color position,]..., end_color [end_position] or direction, color list"}}var h,i,j,k,l,m,n,o,p="linear",q='x="0" y="0" width="1" height="1"',r={compress:!1},s=a.toCSS(r);switch(2==arguments.length?(2>arguments[1].value.length&&b(),h=arguments[1].value):3>arguments.length?b():h=Array.prototype.slice.call(arguments,1),s){case"to bottom":i='x1="0%" y1="0%" x2="0%" y2="100%"';break;case"to right":i='x1="0%" y1="0%" x2="100%" y2="0%"';break;case"to bottom right":i='x1="0%" y1="0%" x2="100%" y2="100%"';break;case"to top right":i='x1="0%" y1="100%" x2="100%" y2="0%"';break;case"ellipse":case"ellipse at center":p="radial",i='cx="50%" cy="50%" r="75%"',q='x="-50" y="-50" width="101" height="101"';break;default:throw{type:"Argument",message:"svg-gradient direction must be 'to bottom', 'to right', 'to bottom right', 'to top right' or 'ellipse at center'"}}for(j='',j=encodeURIComponent(j),j="data:image/svg+xml,"+j,new g(new f("'"+j+"'",j,!1,this.index,this.currentFileInfo),this.index,this.currentFileInfo)})}},{"../tree/color":50,"../tree/dimension":56,"../tree/expression":59,"../tree/quoted":73,"../tree/url":80,"./function-registry":22}],29:[function(a,b,c){var d=a("../tree/keyword"),e=a("../tree/detached-ruleset"),f=a("../tree/dimension"),g=a("../tree/color"),h=a("../tree/quoted"),i=a("../tree/anonymous"),j=a("../tree/url"),k=a("../tree/operation"),l=a("./function-registry"),m=function(a,b){return a instanceof b?d.True:d.False},n=function(a,b){if(void 0===b)throw{type:"Argument",message:"missing the required second argument to isunit."};if(b="string"==typeof b.value?b.value:b,"string"!=typeof b)throw{type:"Argument",message:"Second argument to isunit should be a unit or a string."};return a instanceof f&&a.unit.is(b)?d.True:d.False},o=function(a){var b=Array.isArray(a.value)?a.value:Array(a);return b};l.addMultiple({isruleset:function(a){return m(a,e)},iscolor:function(a){return m(a,g)},isnumber:function(a){return m(a,f)},isstring:function(a){return m(a,h)},iskeyword:function(a){return m(a,d)},isurl:function(a){return m(a,j)},ispixel:function(a){return n(a,"px")},ispercentage:function(a){return n(a,"%")},isem:function(a){return n(a,"em")},isunit:n,unit:function(a,b){if(!(a instanceof f))throw{type:"Argument",message:"the first argument to unit must be a number"+(a instanceof k?". Have you forgotten parenthesis?":"")};return b=b?b instanceof d?b.value:b.toCSS():"",new f(a.value,b)},"get-unit":function(a){return new i(a.unit)},extract:function(a,b){return b=b.value-1,o(a)[b]},length:function(a){return new f(o(a).length)}})},{"../tree/anonymous":46,"../tree/color":50,"../tree/detached-ruleset":55,"../tree/dimension":56,"../tree/keyword":65,"../tree/operation":71,"../tree/quoted":73,"../tree/url":80,"./function-registry":22}],30:[function(a,b,c){var d=a("./contexts"),e=a("./parser/parser"),f=a("./plugins/function-importer");b.exports=function(a){var b=function(a,b){this.rootFilename=b.filename,this.paths=a.paths||[],this.contents={},this.contentsIgnoredChars={},this.mime=a.mime,this.error=null,this.context=a,this.queue=[],this.files={}};return b.prototype.push=function(b,c,g,h,i){var j=this;this.queue.push(b);var k=function(a,c,d){j.queue.splice(j.queue.indexOf(b),1);var e=d===j.rootFilename;h.optional&&a?i(null,{rules:[]},!1,null):(j.files[d]=c,a&&!j.error&&(j.error=a),i(a,c,e,d))},l={relativeUrls:this.context.relativeUrls,entryPath:g.entryPath,rootpath:g.rootpath,rootFilename:g.rootFilename},m=a.getFileManager(b,g.currentDirectory,this.context,a);if(!m)return void k({message:"Could not find a file-manager for "+b});c&&(b=m.tryAppendExtension(b,h.plugin?".js":".less"));var n=function(a){var b=a.filename,c=a.contents.replace(/^\uFEFF/,"");l.currentDirectory=m.getPath(b),l.relativeUrls&&(l.rootpath=m.join(j.context.rootpath||"",m.pathDiff(l.currentDirectory,l.entryPath)),!m.isPathAbsolute(l.rootpath)&&m.alwaysMakePathsAbsolute()&&(l.rootpath=m.join(l.entryPath,l.rootpath))),l.filename=b;var i=new d.Parse(j.context);i.processImports=!1,j.contents[b]=c,(g.reference||h.reference)&&(l.reference=!0),h.plugin?new f(i,l).eval(c,function(a,c){k(a,c,b)}):h.inline?k(null,c,b):new e(i,j,l).parse(c,function(a,c){k(a,c,b)})},o=m.loadFile(b,g.currentDirectory,this.context,a,function(a,b){a?k(a):n(b)});o&&o.then(n,k)},b}},{"./contexts":11,"./parser/parser":38,"./plugins/function-importer":40}],31:[function(a,b,c){b.exports=function(b,c){var d,e,f,g,h,i={version:[2,7,1],data:a("./data"),tree:a("./tree"),Environment:h=a("./environment/environment"),AbstractFileManager:a("./environment/abstract-file-manager"),environment:b=new h(b,c),visitors:a("./visitors"),Parser:a("./parser/parser"),functions:a("./functions")(b),contexts:a("./contexts"),SourceMapOutput:d=a("./source-map-output")(b),SourceMapBuilder:e=a("./source-map-builder")(d,b),ParseTree:f=a("./parse-tree")(e),ImportManager:g=a("./import-manager")(b),render:a("./render")(b,f,g),parse:a("./parse")(b,f,g),LessError:a("./less-error"),transformTree:a("./transform-tree"),utils:a("./utils"),PluginManager:a("./plugin-manager"),logger:a("./logger")};return i}},{"./contexts":11,"./data":13,"./environment/abstract-file-manager":15,"./environment/environment":16,"./functions":23,"./import-manager":30,"./less-error":32,"./logger":33,"./parse":35,"./parse-tree":34,"./parser/parser":38,"./plugin-manager":39,"./render":41,"./source-map-builder":42,"./source-map-output":43,"./transform-tree":44,"./tree":62,"./utils":83,"./visitors":87}],32:[function(a,b,c){var d=a("./utils"),e=b.exports=function(a,b,c){Error.call(this);var e=a.filename||c;if(b&&e){var f=b.contents[e],g=d.getLocation(a.index,f),h=g.line,i=g.column,j=a.call&&d.getLocation(a.call,f).line,k=f.split("\n");this.type=a.type||"Syntax",this.filename=e,this.index=a.index,this.line="number"==typeof h?h+1:null,this.callLine=j+1,this.callExtract=k[j],this.column=i,this.extract=[k[h-1],k[h],k[h+1]]}this.message=a.message,this.stack=a.stack};if("undefined"==typeof Object.create){var f=function(){};f.prototype=Error.prototype,e.prototype=new f}else e.prototype=Object.create(Error.prototype);e.prototype.constructor=e},{"./utils":83}],33:[function(a,b,c){b.exports={error:function(a){this._fireEvent("error",a)},warn:function(a){this._fireEvent("warn",a)},info:function(a){this._fireEvent("info",a)},debug:function(a){this._fireEvent("debug",a)},addListener:function(a){this._listeners.push(a)},removeListener:function(a){for(var b=0;this._listeners.length>b;b++)if(this._listeners[b]===a)return void this._listeners.splice(b,1)},_fireEvent:function(a,b){for(var c=0;this._listeners.length>c;c++){var d=this._listeners[c][a];d&&d(b)}},_listeners:[]}},{}],34:[function(a,b,c){var d=a("./less-error"),e=a("./transform-tree"),f=a("./logger");b.exports=function(a){var b=function(a,b){this.root=a,this.imports=b};return b.prototype.toCSS=function(b){var c,g,h={};try{c=e(this.root,b)}catch(i){throw new d(i,this.imports)}try{var j=Boolean(b.compress);j&&f.warn("The compress option has been deprecated. We recommend you use a dedicated css minifier, for instance see less-plugin-clean-css.");var k={compress:j,dumpLineNumbers:b.dumpLineNumbers,strictUnits:Boolean(b.strictUnits),numPrecision:8};b.sourceMap?(g=new a(b.sourceMap),h.css=g.toCSS(c,k,this.imports)):h.css=c.toCSS(k)}catch(i){throw new d(i,this.imports)}if(b.pluginManager)for(var l=b.pluginManager.getPostProcessors(),m=0;l.length>m;m++)h.css=l[m].process(h.css,{sourceMap:g,options:b,imports:this.imports});b.sourceMap&&(h.map=g.getExternalSourceMap()),h.imports=[];for(var n in this.imports.files)this.imports.files.hasOwnProperty(n)&&n!==this.imports.rootFilename&&h.imports.push(n);return h},b}},{"./less-error":32,"./logger":33,"./transform-tree":44}],35:[function(a,b,c){var d,e=a("./contexts"),f=a("./parser/parser"),g=a("./plugin-manager");b.exports=function(b,c,h){var i=function(b,c,j){if(c=c||{},"function"==typeof c&&(j=c,c={}),!j){d||(d="undefined"==typeof Promise?a("promise"):Promise);var k=this;return new d(function(a,d){i.call(k,b,c,function(b,c){b?d(b):a(c)})})}var l,m,n=new g(this);if(n.addPlugins(c.plugins),c.pluginManager=n,l=new e.Parse(c),c.rootFileInfo)m=c.rootFileInfo;else{var o=c.filename||"input",p=o.replace(/[^\/\\]*$/,"");m={filename:o,relativeUrls:l.relativeUrls,rootpath:l.rootpath||"",currentDirectory:p,entryPath:p,rootFilename:o},m.rootpath&&"/"!==m.rootpath.slice(-1)&&(m.rootpath+="/")}var q=new h(l,m);new f(l,q,m).parse(b,function(a,b){return a?j(a):void j(null,b,q,c)},c)};return i}},{"./contexts":11,"./parser/parser":38,"./plugin-manager":39,promise:void 0}],36:[function(a,b,c){b.exports=function(a,b){function c(b){var c=h-q;512>c&&!b||!c||(p.push(a.slice(q,h+1)),q=h+1)}var d,e,f,g,h,i,j,k,l,m=a.length,n=0,o=0,p=[],q=0;for(h=0;m>h;h++)if(j=a.charCodeAt(h),!(j>=97&&122>=j||34>j))switch(j){case 40:o++,e=h;continue;case 41:if(--o<0)return b("missing opening `(`",h);continue;case 59:o||c();continue;case 123:n++,d=h;continue;case 125:if(--n<0)return b("missing opening `{`",h);n||o||c();continue;case 92:if(m-1>h){h++;continue}return b("unescaped `\\`",h);case 34:case 39:case 96:for(l=0,i=h,h+=1;m>h;h++)if(k=a.charCodeAt(h),!(k>96)){if(k==j){l=1;break}if(92==k){if(h==m-1)return b("unescaped `\\`",h);h++}}if(l)continue;return b("unmatched `"+String.fromCharCode(j)+"`",i);case 47:if(o||h==m-1)continue;if(k=a.charCodeAt(h+1),47==k)for(h+=2;m>h&&(k=a.charCodeAt(h),!(13>=k)||10!=k&&13!=k);h++);else if(42==k){for(f=i=h,h+=2;m-1>h&&(k=a.charCodeAt(h),125==k&&(g=h),42!=k||47!=a.charCodeAt(h+1));h++);if(h==m-1)return b("missing closing `*/`",i);h++}continue;case 42:if(m-1>h&&47==a.charCodeAt(h+1))return b("unmatched `/*`",h);continue}return 0!==n?f>d&&g>f?b("missing closing `}` or `*/`",d):b("missing closing `}`",d):0!==o?b("missing closing `)`",e):(c(!0),p)}},{}],37:[function(a,b,c){var d=a("./chunker");b.exports=function(){function a(d){for(var e,f,j,p=k.i,q=c,s=k.i-i,t=k.i+h.length-s,u=k.i+=d,v=b;t>k.i;k.i++){if(e=v.charCodeAt(k.i),k.autoCommentAbsorb&&e===r){if(f=v.charAt(k.i+1),"/"===f){j={index:k.i,isLineComment:!0};var w=v.indexOf("\n",k.i+2);0>w&&(w=t),k.i=w,j.text=v.substr(j.index,k.i-j.index),k.commentStore.push(j);continue}if("*"===f){var x=v.indexOf("*/",k.i+2);if(x>=0){j={index:k.i,text:v.substr(k.i,x+2-k.i),isLineComment:!1},k.i+=j.text.length-1,k.commentStore.push(j);continue}}break}if(e!==l&&e!==n&&e!==m&&e!==o)break}if(h=h.slice(d+k.i-u+s),i=k.i,!h.length){if(g.length-1>c)return h=g[++c],a(0),!0;k.finished=!0}return p!==k.i||q!==c}var b,c,e,f,g,h,i,j=[],k={},l=32,m=9,n=10,o=13,p=43,q=44,r=47,s=57;return k.save=function(){i=k.i,j.push({current:h,i:k.i,j:c})},k.restore=function(a){(k.i>e||k.i===e&&a&&!f)&&(e=k.i,f=a);var b=j.pop();h=b.current,i=k.i=b.i,c=b.j},k.forget=function(){j.pop()},k.isWhitespace=function(a){var c=k.i+(a||0),d=b.charCodeAt(c);return d===l||d===o||d===m||d===n},k.$re=function(b){k.i>i&&(h=h.slice(k.i-i),i=k.i);var c=b.exec(h);return c?(a(c[0].length),"string"==typeof c?c:1===c.length?c[0]:c):null},k.$char=function(c){return b.charAt(k.i)!==c?null:(a(1),c)},k.$str=function(c){for(var d=c.length,e=0;d>e;e++)if(b.charAt(k.i+e)!==c.charAt(e))return null;return a(d),c},k.$quoted=function(){var c=b.charAt(k.i);if("'"===c||'"'===c){for(var d=b.length,e=k.i,f=1;d>f+e;f++){var g=b.charAt(f+e);switch(g){case"\\":f++;continue;case"\r":case"\n":break;case c:var h=b.substr(e,f+1);return a(f+1),h}}return null}},k.autoCommentAbsorb=!0,k.commentStore=[],k.finished=!1,k.peek=function(a){if("string"==typeof a){for(var c=0;a.length>c;c++)if(b.charAt(k.i+c)!==a.charAt(c))return!1;return!0}return a.test(h)},k.peekChar=function(a){return b.charAt(k.i)===a},k.currentChar=function(){return b.charAt(k.i)},k.getInput=function(){return b},k.peekNotNumeric=function(){var a=b.charCodeAt(k.i);return a>s||p>a||a===r||a===q},k.start=function(f,j,l){b=f,k.i=c=i=e=0,g=j?d(f,l):[f],h=g[0],a(0)},k.end=function(){var a,c=k.i>=b.length;return e>k.i&&(a=f,k.i=e),{isFinished:c,furthest:k.i,furthestPossibleErrorMessage:a,furthestReachedEnd:k.i>=b.length-1,furthestChar:b[k.i]}},k}},{"./chunker":36}],38:[function(a,b,c){var d=a("../less-error"),e=a("../tree"),f=a("../visitors"),g=a("./parser-input"),h=a("../utils"),i=function j(a,b,c){function i(a,e){throw new d({index:o.i,filename:c.filename,type:e||"Syntax",message:a},b)}function k(a,b,c){var d=a instanceof Function?a.call(n):o.$re(a);return d?d:void i(b||("string"==typeof a?"expected '"+a+"' got '"+o.currentChar()+"'":"unexpected token"))}function l(a,b){return o.$char(a)?a:void i(b||"expected '"+a+"' got '"+o.currentChar()+"'")}function m(a){var b=c.filename;return{lineNumber:h.getLocation(a,o.getInput()).line+1,fileName:b}}var n,o=g();return{parse:function(g,h,i){var k,l,m,n,p=null,q="";if(l=i&&i.globalVars?j.serializeVars(i.globalVars)+"\n":"",m=i&&i.modifyVars?"\n"+j.serializeVars(i.modifyVars):"",a.pluginManager)for(var r=a.pluginManager.getPreProcessors(),s=0;r.length>s;s++)g=r[s].process(g,{context:a,imports:b,fileInfo:c});(l||i&&i.banner)&&(q=(i&&i.banner?i.banner:"")+l,n=b.contentsIgnoredChars,n[c.filename]=n[c.filename]||0,n[c.filename]+=q.length),g=g.replace(/\r\n?/g,"\n"),g=q+g.replace(/^\uFEFF/,"")+m,b.contents[c.filename]=g;try{o.start(g,a.chunkInput,function(a,e){throw new d({index:e,type:"Parse",message:a,filename:c.filename},b)}),k=new e.Ruleset(null,this.parsers.primary()),k.root=!0,k.firstRoot=!0}catch(t){return h(new d(t,b,c.filename))}var u=o.end();if(!u.isFinished){var v=u.furthestPossibleErrorMessage;v||(v="Unrecognised input","}"===u.furthestChar?v+=". Possibly missing opening '{'":")"===u.furthestChar?v+=". Possibly missing opening '('":u.furthestReachedEnd&&(v+=". Possibly missing something")),p=new d({type:"Parse",message:v,index:u.furthest,filename:c.filename},b)}var w=function(a){return a=p||a||b.error,a?(a instanceof d||(a=new d(a,b,c.filename)),h(a)):h(null,k)};return a.processImports===!1?w():void new f.ImportVisitor(b,w).run(k)},parsers:n={primary:function(){for(var a,b=this.mixin,c=[];;){for(;;){if(a=this.comment(),!a)break;c.push(a)}if(o.finished)break;if(o.peek("}"))break;if(a=this.extendRule())c=c.concat(a);else if(a=b.definition()||this.rule()||this.ruleset()||b.call()||this.rulesetCall()||this.entities.call()||this.directive())c.push(a);else{for(var d=!1;o.$char(";");)d=!0;if(!d)break}}return c},comment:function(){if(o.commentStore.length){var a=o.commentStore.shift();return new e.Comment(a.text,a.isLineComment,a.index,c)}},entities:{quoted:function(){var a,b=o.i,d=!1;return o.save(),o.$char("~")&&(d=!0),(a=o.$quoted())?(o.forget(),new e.Quoted(a.charAt(0),a.substr(1,a.length-2),d,b,c)):void o.restore()},keyword:function(){var a=o.$char("%")||o.$re(/^[_A-Za-z-][_A-Za-z0-9-]*/);return a?e.Color.fromKeyword(a)||new e.Keyword(a):void 0},call:function(){var a,b,d,f,g=o.i;if(!o.peek(/^url\(/i))return o.save(),(a=o.$re(/^([\w-]+|%|progid:[\w\.]+)\(/))?(a=a[1],b=a.toLowerCase(),"alpha"===b&&(f=n.alpha())?(o.forget(),f):(d=this.arguments(),o.$char(")")?(o.forget(),new e.Call(a,d,g,c)):void o.restore("Could not parse call arguments or missing ')'"))):void o.forget()},arguments:function(){var a,b,c,d=[],f=[],g=[];for(o.save();;){if(c=n.detachedRuleset()||this.assignment()||n.expression(),!c)break;b=c,c.value&&1==c.value.length&&(b=c.value[0]),b&&g.push(b),f.push(b),o.$char(",")||(o.$char(";")||a)&&(a=!0,g.length>1&&(b=new e.Value(g)),d.push(b),g=[])}return o.forget(),a?d:f},literal:function(){return this.dimension()||this.color()||this.quoted()||this.unicodeDescriptor()},assignment:function(){var a,b;return o.save(),(a=o.$re(/^\w+(?=\s?=)/i))&&o.$char("=")&&(b=n.entity())?(o.forget(),new e.Assignment(a,b)):void o.restore()},url:function(){var a,b=o.i;return o.autoCommentAbsorb=!1,o.$str("url(")?(a=this.quoted()||this.variable()||o.$re(/^(?:(?:\\[\(\)'"])|[^\(\)'"])+/)||"",o.autoCommentAbsorb=!0,l(")"),new e.URL(null!=a.value||a instanceof e.Variable?a:new e.Anonymous(a),b,c)):void(o.autoCommentAbsorb=!0)},variable:function(){var a,b=o.i;return"@"===o.currentChar()&&(a=o.$re(/^@@?[\w-]+/))?new e.Variable(a,b,c):void 0},variableCurly:function(){var a,b=o.i;return"@"===o.currentChar()&&(a=o.$re(/^@\{([\w-]+)\}/))?new e.Variable("@"+a[1],b,c):void 0},color:function(){var a;if("#"===o.currentChar()&&(a=o.$re(/^#([A-Fa-f0-9]{6}|[A-Fa-f0-9]{3})/))){var b=a.input.match(/^#([\w]+).*/);return b=b[1],b.match(/^[A-Fa-f0-9]+$/)||i("Invalid HEX color code"),new e.Color(a[1],void 0,"#"+b)}},colorKeyword:function(){o.save();var a=o.autoCommentAbsorb;o.autoCommentAbsorb=!1;var b=o.$re(/^[_A-Za-z-][_A-Za-z0-9-]+/);if(o.autoCommentAbsorb=a,!b)return void o.forget();o.restore();var c=e.Color.fromKeyword(b);return c?(o.$str(b),c):void 0},dimension:function(){if(!o.peekNotNumeric()){var a=o.$re(/^([+-]?\d*\.?\d+)(%|[a-z_]+)?/i);return a?new e.Dimension(a[1],a[2]):void 0}},unicodeDescriptor:function(){var a;return a=o.$re(/^U\+[0-9a-fA-F?]+(\-[0-9a-fA-F?]+)?/),a?new e.UnicodeDescriptor(a[0]):void 0},javascript:function(){var a,b=o.i;o.save();var d=o.$char("~"),f=o.$char("`");return f?(a=o.$re(/^[^`]*`/))?(o.forget(),new e.JavaScript(a.substr(0,a.length-1),Boolean(d),b,c)):void o.restore("invalid javascript definition"):void o.restore()}},variable:function(){var a;return"@"===o.currentChar()&&(a=o.$re(/^(@[\w-]+)\s*:/))?a[1]:void 0},rulesetCall:function(){var a;return"@"===o.currentChar()&&(a=o.$re(/^(@[\w-]+)\(\s*\)\s*;/))?new e.RulesetCall(a[1]):void 0},extend:function(a){var b,d,f,g,h,j=o.i;if(o.$str(a?"&:extend(":":extend(")){do{for(f=null,b=null;!(f=o.$re(/^(all)(?=\s*(\)|,))/))&&(d=this.element());)b?b.push(d):b=[d];f=f&&f[1],b||i("Missing target selector for :extend()."),h=new e.Extend(new e.Selector(b),f,j,c),g?g.push(h):g=[h]}while(o.$char(","));return k(/^\)/),a&&k(/^;/),g}},extendRule:function(){return this.extend(!0)},mixin:{call:function(){var a,b,d,f,g,h,i=o.currentChar(),j=!1,k=o.i;if("."===i||"#"===i){for(o.save();;){if(a=o.i,f=o.$re(/^[#.](?:[\w-]|\\(?:[A-Fa-f0-9]{1,6} ?|[^A-Fa-f0-9]))+/),!f)break;d=new e.Element(g,f,a,c),b?b.push(d):b=[d],g=o.$char(">")}return b&&(o.$char("(")&&(h=this.args(!0).args,l(")")),n.important()&&(j=!0),n.end())?(o.forget(),new e.mixin.Call(b,h,k,c,j)):void o.restore()}},args:function(a){var b,c,d,f,g,h,j,k=n.entities,l={args:null,variadic:!1},m=[],p=[],q=[];for(o.save();;){if(a)h=n.detachedRuleset()||n.expression();else{if(o.commentStore.length=0,o.$str("...")){l.variadic=!0,o.$char(";")&&!b&&(b=!0),(b?p:q).push({variadic:!0});break}h=k.variable()||k.literal()||k.keyword()}if(!h)break;f=null,h.throwAwayComments&&h.throwAwayComments(),g=h;var r=null;if(a?h.value&&1==h.value.length&&(r=h.value[0]):r=h,r&&r instanceof e.Variable)if(o.$char(":")){if(m.length>0&&(b&&i("Cannot mix ; and , as delimiter types"),c=!0),g=n.detachedRuleset()||n.expression(),!g){if(!a)return o.restore(),l.args=[],l;i("could not understand value for named argument")}f=d=r.name}else if(o.$str("...")){if(!a){l.variadic=!0,o.$char(";")&&!b&&(b=!0),(b?p:q).push({name:h.name,variadic:!0});break}j=!0}else a||(d=f=r.name,g=null);g&&m.push(g),q.push({name:f,value:g,expand:j}),o.$char(",")||(o.$char(";")||b)&&(c&&i("Cannot mix ; and , as delimiter types"),b=!0,m.length>1&&(g=new e.Value(m)),p.push({name:d,value:g,expand:j}),d=null,m=[],c=!1)}return o.forget(),l.args=b?p:q,l},definition:function(){var a,b,c,d,f=[],g=!1;if(!("."!==o.currentChar()&&"#"!==o.currentChar()||o.peek(/^[^{]*\}/)))if(o.save(),b=o.$re(/^([#.](?:[\w-]|\\(?:[A-Fa-f0-9]{1,6} ?|[^A-Fa-f0-9]))+)\s*\(/)){a=b[1];var h=this.args(!1);if(f=h.args,g=h.variadic,!o.$char(")"))return void o.restore("Missing closing ')'");if(o.commentStore.length=0,o.$str("when")&&(d=k(n.conditions,"expected condition")),c=n.block())return o.forget(),new e.mixin.Definition(a,f,c,d,g);o.restore()}else o.forget()}},entity:function(){var a=this.entities;return this.comment()||a.literal()||a.variable()||a.url()||a.call()||a.keyword()||a.javascript()},end:function(){return o.$char(";")||o.peek("}")},alpha:function(){var a;if(o.$re(/^opacity=/i))return a=o.$re(/^\d+/),a||(a=k(this.entities.variable,"Could not parse alpha")),l(")"),new e.Alpha(a)},element:function(){var a,b,d,f=o.i;return b=this.combinator(),a=o.$re(/^(?:\d+\.\d+|\d+)%/)||o.$re(/^(?:[.#]?|:*)(?:[\w-]|[^\x00-\x9f]|\\(?:[A-Fa-f0-9]{1,6} ?|[^A-Fa-f0-9]))+/)||o.$char("*")||o.$char("&")||this.attribute()||o.$re(/^\([^&()@]+\)/)||o.$re(/^[\.#:](?=@)/)||this.entities.variableCurly(),a||(o.save(),o.$char("(")?(d=this.selector())&&o.$char(")")?(a=new e.Paren(d),o.forget()):o.restore("Missing closing ')'"):o.forget()),a?new e.Element(b,a,f,c):void 0},combinator:function(){var a=o.currentChar();if("/"===a){o.save();var b=o.$re(/^\/[a-z]+\//i);if(b)return o.forget(),new e.Combinator(b);o.restore()}if(">"===a||"+"===a||"~"===a||"|"===a||"^"===a){for(o.i++,"^"===a&&"^"===o.currentChar()&&(a="^^",o.i++);o.isWhitespace();)o.i++;return new e.Combinator(a)}return new e.Combinator(o.isWhitespace(-1)?" ":null)},lessSelector:function(){return this.selector(!0)},selector:function(a){for(var b,d,f,g,h,j,l,m=o.i;(a&&(d=this.extend())||a&&(j=o.$str("when"))||(g=this.element()))&&(j?l=k(this.conditions,"expected condition"):l?i("CSS guard can only be used at the end of selector"):d?h=h?h.concat(d):d:(h&&i("Extend can only be used at the end of selector"),f=o.currentChar(),b?b.push(g):b=[g],g=null),"{"!==f&&"}"!==f&&";"!==f&&","!==f&&")"!==f););return b?new e.Selector(b,h,l,m,c):void(h&&i("Extend must be used to extend a selector, it cannot be used on its own"))},attribute:function(){if(o.$char("[")){var a,b,c,d=this.entities;return(a=d.variableCurly())||(a=k(/^(?:[_A-Za-z0-9-\*]*\|)?(?:[_A-Za-z0-9-]|\\.)+/)),c=o.$re(/^[|~*$^]?=/),c&&(b=d.quoted()||o.$re(/^[0-9]+%/)||o.$re(/^[\w-]+/)||d.variableCurly()),l("]"),new e.Attribute(a,c,b)}},block:function(){var a;return o.$char("{")&&(a=this.primary())&&o.$char("}")?a:void 0},blockRuleset:function(){var a=this.block();return a&&(a=new e.Ruleset(null,a)),a},detachedRuleset:function(){var a=this.blockRuleset();return a?new e.DetachedRuleset(a):void 0},ruleset:function(){var b,c,d,f;for(o.save(),a.dumpLineNumbers&&(f=m(o.i));;){if(c=this.lessSelector(),!c)break;if(b?b.push(c):b=[c],o.commentStore.length=0,c.condition&&b.length>1&&i("Guards are only currently allowed on a single selector."),!o.$char(","))break;c.condition&&i("Guards are only currently allowed on a single selector."),o.commentStore.length=0}if(b&&(d=this.block())){o.forget();var g=new e.Ruleset(b,d,a.strictImports);return a.dumpLineNumbers&&(g.debugInfo=f),g}o.restore()},rule:function(b){var d,f,g,h,i,j=o.i,k=o.currentChar();if("."!==k&&"#"!==k&&"&"!==k&&":"!==k)if(o.save(),d=this.variable()||this.ruleProperty()){if(i="string"==typeof d,i&&(f=this.detachedRuleset()),o.commentStore.length=0,!f){h=!i&&d.length>1&&d.pop().value;var l=!b&&(a.compress||i);if(l&&(f=this.value()),!f&&(f=this.anonymousValue()))return o.forget(),new e.Rule(d,f,!1,h,j,c);l||f||(f=this.value()),g=this.important()}if(f&&this.end())return o.forget(),new e.Rule(d,f,g,h,j,c);if(o.restore(),f&&!b)return this.rule(!0)}else o.forget()},anonymousValue:function(){var a=o.$re(/^([^@+\/'"*`(;{}-]*);/);return a?new e.Anonymous(a[1]):void 0},"import":function(){var a,b,d=o.i,f=o.$re(/^@import?\s+/);if(f){var g=(f?this.importOptions():null)||{};if(a=this.entities.quoted()||this.entities.url())return b=this.mediaFeatures(),o.$char(";")||(o.i=d,i("missing semi-colon or unrecognised media features on import")),b=b&&new e.Value(b),new e.Import(a,b,g,d,c);o.i=d,i("malformed import statement")}},importOptions:function(){var a,b,c,d={};if(!o.$char("("))return null;do if(a=this.importOption()){switch(b=a,c=!0,b){case"css":b="less",c=!1;break;case"once":b="multiple",c=!1}if(d[b]=c,!o.$char(","))break}while(a);return l(")"),d},importOption:function(){var a=o.$re(/^(less|css|multiple|once|inline|reference|optional)/);return a?a[1]:void 0},mediaFeature:function(){var a,b,d=this.entities,f=[];o.save();do a=d.keyword()||d.variable(),a?f.push(a):o.$char("(")&&(b=this.property(),a=this.value(),o.$char(")")?b&&a?f.push(new e.Paren(new e.Rule(b,a,null,null,o.i,c,!0))):a?f.push(new e.Paren(a)):i("badly formed media feature definition"):i("Missing closing ')'","Parse"));while(a);return o.forget(),f.length>0?new e.Expression(f):void 0},mediaFeatures:function(){var a,b=this.entities,c=[];do if(a=this.mediaFeature()){if(c.push(a),!o.$char(","))break}else if(a=b.variable(),a&&(c.push(a),!o.$char(",")))break;while(a);return c.length>0?c:null},media:function(){var b,d,f,g,h=o.i;return a.dumpLineNumbers&&(g=m(h)),o.save(),o.$str("@media")?(b=this.mediaFeatures(),d=this.block(),d||i("media definitions require block statements after any features"),o.forget(),f=new e.Media(d,b,h,c),a.dumpLineNumbers&&(f.debugInfo=g),f):void o.restore()},plugin:function(){var a,b=o.i,d=o.$re(/^@plugin?\s+/);if(d){var f={plugin:!0};if(a=this.entities.quoted()||this.entities.url())return o.$char(";")||(o.i=b,i("missing semi-colon on plugin")),new e.Import(a,null,f,b,c);o.i=b,i("malformed plugin statement")}},directive:function(){var b,d,f,g,h,j,k,l=o.i,n=!0,p=!0;if("@"===o.currentChar()){if(d=this["import"]()||this.plugin()||this.media())return d;if(o.save(),b=o.$re(/^@[a-z-]+/)){switch(g=b,"-"==b.charAt(1)&&b.indexOf("-",2)>0&&(g="@"+b.slice(b.indexOf("-",2)+1)),g){case"@charset":h=!0,n=!1;break;case"@namespace":j=!0,n=!1;break;case"@keyframes":case"@counter-style":h=!0;break;case"@document":case"@supports":k=!0,p=!1;break;default:k=!0}return o.commentStore.length=0,h?(d=this.entity(),d||i("expected "+b+" identifier")):j?(d=this.expression(),d||i("expected "+b+" expression")):k&&(d=(o.$re(/^[^{;]+/)||"").trim(),n="{"==o.currentChar(),d&&(d=new e.Anonymous(d))),n&&(f=this.blockRuleset()),f||!n&&d&&o.$char(";")?(o.forget(),new e.Directive(b,d,f,l,c,a.dumpLineNumbers?m(l):null,p)):void o.restore("directive options not recognised")}}},value:function(){var a,b=[];do if(a=this.expression(),a&&(b.push(a),!o.$char(",")))break;while(a);return b.length>0?new e.Value(b):void 0},important:function(){return"!"===o.currentChar()?o.$re(/^! *important/):void 0},sub:function(){var a,b;return o.save(),o.$char("(")?(a=this.addition(),a&&o.$char(")")?(o.forget(),b=new e.Expression([a]),b.parens=!0,b):void o.restore("Expected ')'")):void o.restore()},multiplication:function(){var a,b,c,d,f;if(a=this.operand()){for(f=o.isWhitespace(-1);;){if(o.peek(/^\/[*\/]/))break;if(o.save(),c=o.$char("/")||o.$char("*"),!c){o.forget();break}if(b=this.operand(),!b){o.restore();break}o.forget(),a.parensInOp=!0,b.parensInOp=!0,d=new e.Operation(c,[d||a,b],f),f=o.isWhitespace(-1)}return d||a}},addition:function(){var a,b,c,d,f;if(a=this.multiplication()){for(f=o.isWhitespace(-1);;){if(c=o.$re(/^[-+]\s+/)||!f&&(o.$char("+")||o.$char("-")),!c)break;if(b=this.multiplication(),!b)break;a.parensInOp=!0,b.parensInOp=!0,d=new e.Operation(c,[d||a,b],f),f=o.isWhitespace(-1)}return d||a}},conditions:function(){var a,b,c,d=o.i;if(a=this.condition()){for(;;){if(!o.peek(/^,\s*(not\s*)?\(/)||!o.$char(","))break;if(b=this.condition(),!b)break;c=new e.Condition("or",c||a,b,d)}return c||a}},condition:function(){function a(){return o.$str("or")}var b,c,d;if(b=this.conditionAnd(this)){if(c=a()){if(d=this.condition(),!d)return;b=new e.Condition(c,b,d)}return b}},conditionAnd:function(){function a(a){return a.negatedCondition()||a.parenthesisCondition()}function b(){return o.$str("and")}var c,d,f;if(c=a(this)){if(d=b()){if(f=this.conditionAnd(),!f)return;c=new e.Condition(d,c,f)}return c}},negatedCondition:function(){if(o.$str("not")){var a=this.parenthesisCondition();return a&&(a.negate=!a.negate),a}},parenthesisCondition:function(){function a(a){var b;return o.save(),(b=a.condition())&&o.$char(")")?(o.forget(),b):void o.restore()}var b;return o.save(),o.$str("(")?(b=a(this))?(o.forget(),b):(b=this.atomicCondition())?o.$char(")")?(o.forget(),b):void o.restore("expected ')' got '"+o.currentChar()+"'"):void o.restore():void o.restore()},atomicCondition:function(){var a,b,c,d,f=this.entities,g=o.i;return a=this.addition()||f.keyword()||f.quoted(),a?(o.$char(">")?d=o.$char("=")?">=":">":o.$char("<")?d=o.$char("=")?"<=":"<":o.$char("=")&&(d=o.$char(">")?"=>":o.$char("<")?"=<":"="),d?(b=this.addition()||f.keyword()||f.quoted(),b?c=new e.Condition(d,a,b,g,!1):i("expected expression")):c=new e.Condition("=",a,new e.Keyword("true"),g,!1),c):void 0},operand:function(){var a,b=this.entities;o.peek(/^-[@\(]/)&&(a=o.$char("-"));var c=this.sub()||b.dimension()||b.color()||b.variable()||b.call()||b.colorKeyword();return a&&(c.parensInOp=!0,c=new e.Negative(c)),c},expression:function(){var a,b,c=[];do a=this.comment(),a?c.push(a):(a=this.addition()||this.entity(),a&&(c.push(a),o.peek(/^\/[\/*]/)||(b=o.$char("/"),b&&c.push(new e.Anonymous(b)))));while(a);return c.length>0?new e.Expression(c):void 0},property:function(){var a=o.$re(/^(\*?-?[_a-zA-Z0-9-]+)\s*:/);return a?a[1]:void 0},ruleProperty:function(){function a(a){var b=o.i,c=o.$re(a);return c?(g.push(b),f.push(c[1])):void 0}var b,d,f=[],g=[];o.save();var h=o.$re(/^([_a-zA-Z0-9-]+)\s*:/);if(h)return f=[new e.Keyword(h[1])],o.forget(),f;for(a(/^(\*?)/);;)if(!a(/^((?:[\w-]+)|(?:@\{[\w-]+\}))/))break;if(f.length>1&&a(/^((?:\+_|\+)?)\s*:/)){for(o.forget(),""===f[0]&&(f.shift(),g.shift()),d=0;f.length>d;d++)b=f[d],f[d]="@"!==b.charAt(0)?new e.Keyword(b):new e.Variable("@"+b.slice(2,-1),g[d],c);return f}o.restore()}}}};i.serializeVars=function(a){var b="";for(var c in a)if(Object.hasOwnProperty.call(a,c)){var d=a[c];b+=("@"===c[0]?"":"@")+c+": "+d+(";"===String(d).slice(-1)?"":";")}return b},b.exports=i},{"../less-error":32,"../tree":62,"../utils":83,"../visitors":87,"./parser-input":37}],39:[function(a,b,c){var d=function(a){this.less=a,this.visitors=[],this.preProcessors=[],this.postProcessors=[],this.installedPlugins=[],this.fileManagers=[]};d.prototype.addPlugins=function(a){if(a)for(var b=0;a.length>b;b++)this.addPlugin(a[b])},d.prototype.addPlugin=function(a){this.installedPlugins.push(a),a.install(this.less,this)},d.prototype.addVisitor=function(a){this.visitors.push(a)},d.prototype.addPreProcessor=function(a,b){var c;for(c=0;this.preProcessors.length>c&&!(this.preProcessors[c].priority>=b);c++);this.preProcessors.splice(c,0,{preProcessor:a,priority:b})},d.prototype.addPostProcessor=function(a,b){var c;for(c=0;this.postProcessors.length>c&&!(this.postProcessors[c].priority>=b);c++);this.postProcessors.splice(c,0,{postProcessor:a,priority:b})},d.prototype.addFileManager=function(a){this.fileManagers.push(a)},d.prototype.getPreProcessors=function(){for(var a=[],b=0;this.preProcessors.length>b;b++)a.push(this.preProcessors[b].preProcessor);return a},d.prototype.getPostProcessors=function(){for(var a=[],b=0;this.postProcessors.length>b;b++)a.push(this.postProcessors[b].postProcessor);return a},d.prototype.getVisitors=function(){return this.visitors},d.prototype.getFileManagers=function(){return this.fileManagers},b.exports=d},{}],40:[function(a,b,c){var d=a("../less-error"),e=a("../tree"),f=b.exports=function(a,b){this.fileInfo=b};f.prototype.eval=function(a,b){var c,f,g={};
-f={add:function(a,b){g[a]=b},addMultiple:function(a){Object.keys(a).forEach(function(b){g[b]=a[b]})}};try{c=new Function("functions","tree","fileInfo",a),c(f,e,this.fileInfo)}catch(h){b(new d({message:"Plugin evaluation error: '"+h.name+": "+h.message.replace(/["]/g,"'")+"'",filename:this.fileInfo.filename}),null)}b(null,{functions:g})}},{"../less-error":32,"../tree":62}],41:[function(a,b,c){var d;b.exports=function(b,c,e){var f=function(b,e,g){if("function"==typeof e&&(g=e,e={}),!g){d||(d="undefined"==typeof Promise?a("promise"):Promise);var h=this;return new d(function(a,c){f.call(h,b,e,function(b,d){b?c(b):a(d)})})}this.parse(b,e,function(a,b,d,e){if(a)return g(a);var f;try{var h=new c(b,d);f=h.toCSS(e)}catch(a){return g(a)}g(null,f)})};return f}},{promise:void 0}],42:[function(a,b,c){b.exports=function(a,b){var c=function(a){this.options=a};return c.prototype.toCSS=function(b,c,d){var e=new a({contentsIgnoredCharsMap:d.contentsIgnoredChars,rootNode:b,contentsMap:d.contents,sourceMapFilename:this.options.sourceMapFilename,sourceMapURL:this.options.sourceMapURL,outputFilename:this.options.sourceMapOutputFilename,sourceMapBasepath:this.options.sourceMapBasepath,sourceMapRootpath:this.options.sourceMapRootpath,outputSourceFiles:this.options.outputSourceFiles,sourceMapGenerator:this.options.sourceMapGenerator,sourceMapFileInline:this.options.sourceMapFileInline}),f=e.toCSS(c);return this.sourceMap=e.sourceMap,this.sourceMapURL=e.sourceMapURL,this.options.sourceMapInputFilename&&(this.sourceMapInputFilename=e.normalizeFilename(this.options.sourceMapInputFilename)),f+this.getCSSAppendage()},c.prototype.getCSSAppendage=function(){var a=this.sourceMapURL;if(this.options.sourceMapFileInline){if(void 0===this.sourceMap)return"";a="data:application/json;base64,"+b.encodeBase64(this.sourceMap)}return a?"/*# sourceMappingURL="+a+" */":""},c.prototype.getExternalSourceMap=function(){return this.sourceMap},c.prototype.setExternalSourceMap=function(a){this.sourceMap=a},c.prototype.isInline=function(){return this.options.sourceMapFileInline},c.prototype.getSourceMapURL=function(){return this.sourceMapURL},c.prototype.getOutputFilename=function(){return this.options.sourceMapOutputFilename},c.prototype.getInputFilename=function(){return this.sourceMapInputFilename},c}},{}],43:[function(a,b,c){b.exports=function(a){var b=function(b){this._css=[],this._rootNode=b.rootNode,this._contentsMap=b.contentsMap,this._contentsIgnoredCharsMap=b.contentsIgnoredCharsMap,b.sourceMapFilename&&(this._sourceMapFilename=b.sourceMapFilename.replace(/\\/g,"/")),this._outputFilename=b.outputFilename,this.sourceMapURL=b.sourceMapURL,b.sourceMapBasepath&&(this._sourceMapBasepath=b.sourceMapBasepath.replace(/\\/g,"/")),b.sourceMapRootpath?(this._sourceMapRootpath=b.sourceMapRootpath.replace(/\\/g,"/"),"/"!==this._sourceMapRootpath.charAt(this._sourceMapRootpath.length-1)&&(this._sourceMapRootpath+="/")):this._sourceMapRootpath="",this._outputSourceFiles=b.outputSourceFiles,this._sourceMapGeneratorConstructor=a.getSourceMapGenerator(),this._lineNumber=0,this._column=0};return b.prototype.normalizeFilename=function(a){return a=a.replace(/\\/g,"/"),this._sourceMapBasepath&&0===a.indexOf(this._sourceMapBasepath)&&(a=a.substring(this._sourceMapBasepath.length),"\\"!==a.charAt(0)&&"/"!==a.charAt(0)||(a=a.substring(1))),(this._sourceMapRootpath||"")+a},b.prototype.add=function(a,b,c,d){if(a){var e,f,g,h,i;if(b){var j=this._contentsMap[b.filename];this._contentsIgnoredCharsMap[b.filename]&&(c-=this._contentsIgnoredCharsMap[b.filename],0>c&&(c=0),j=j.slice(this._contentsIgnoredCharsMap[b.filename])),j=j.substring(0,c),f=j.split("\n"),h=f[f.length-1]}if(e=a.split("\n"),g=e[e.length-1],b)if(d)for(i=0;e.length>i;i++)this._sourceMapGenerator.addMapping({generated:{line:this._lineNumber+i+1,column:0===i?this._column:0},original:{line:f.length+i,column:0===i?h.length:0},source:this.normalizeFilename(b.filename)});else this._sourceMapGenerator.addMapping({generated:{line:this._lineNumber+1,column:this._column},original:{line:f.length,column:h.length},source:this.normalizeFilename(b.filename)});1===e.length?this._column+=g.length:(this._lineNumber+=e.length-1,this._column=g.length),this._css.push(a)}},b.prototype.isEmpty=function(){return 0===this._css.length},b.prototype.toCSS=function(a){if(this._sourceMapGenerator=new this._sourceMapGeneratorConstructor({file:this._outputFilename,sourceRoot:null}),this._outputSourceFiles)for(var b in this._contentsMap)if(this._contentsMap.hasOwnProperty(b)){var c=this._contentsMap[b];this._contentsIgnoredCharsMap[b]&&(c=c.slice(this._contentsIgnoredCharsMap[b])),this._sourceMapGenerator.setSourceContent(this.normalizeFilename(b),c)}if(this._rootNode.genCSS(a,this),this._css.length>0){var d,e=JSON.stringify(this._sourceMapGenerator.toJSON());this.sourceMapURL?d=this.sourceMapURL:this._sourceMapFilename&&(d=this._sourceMapFilename),this.sourceMapURL=d,this.sourceMap=e}return this._css.join("")},b}},{}],44:[function(a,b,c){var d=a("./contexts"),e=a("./visitors"),f=a("./tree");b.exports=function(a,b){b=b||{};var c,g=b.variables,h=new d.Eval(b);"object"!=typeof g||Array.isArray(g)||(g=Object.keys(g).map(function(a){var b=g[a];return b instanceof f.Value||(b instanceof f.Expression||(b=new f.Expression([b])),b=new f.Value([b])),new f.Rule("@"+a,b,!1,null,0)}),h.frames=[new f.Ruleset(null,g)]);var i,j=[],k=[new e.JoinSelectorVisitor,new e.MarkVisibleSelectorsVisitor(!0),new e.ExtendVisitor,new e.ToCSSVisitor({compress:Boolean(b.compress)})];if(b.pluginManager){var l=b.pluginManager.getVisitors();for(i=0;l.length>i;i++){var m=l[i];m.isPreEvalVisitor?j.push(m):m.isPreVisitor?k.splice(0,0,m):k.push(m)}}for(i=0;j.length>i;i++)j[i].run(a);for(c=a.eval(h),i=0;k.length>i;i++)k[i].run(c);return c}},{"./contexts":11,"./tree":62,"./visitors":87}],45:[function(a,b,c){var d=a("./node"),e=function(a){this.value=a};e.prototype=new d,e.prototype.type="Alpha",e.prototype.accept=function(a){this.value=a.visit(this.value)},e.prototype.eval=function(a){return this.value.eval?new e(this.value.eval(a)):this},e.prototype.genCSS=function(a,b){b.add("alpha(opacity="),this.value.genCSS?this.value.genCSS(a,b):b.add(this.value),b.add(")")},b.exports=e},{"./node":70}],46:[function(a,b,c){var d=a("./node"),e=function(a,b,c,d,e,f){this.value=a,this.index=b,this.mapLines=d,this.currentFileInfo=c,this.rulesetLike="undefined"==typeof e?!1:e,this.allowRoot=!0,this.copyVisibilityInfo(f)};e.prototype=new d,e.prototype.type="Anonymous",e.prototype.eval=function(){return new e(this.value,this.index,this.currentFileInfo,this.mapLines,this.rulesetLike,this.visibilityInfo())},e.prototype.compare=function(a){return a.toCSS&&this.toCSS()===a.toCSS()?0:void 0},e.prototype.isRulesetLike=function(){return this.rulesetLike},e.prototype.genCSS=function(a,b){b.add(this.value,this.currentFileInfo,this.index,this.mapLines)},b.exports=e},{"./node":70}],47:[function(a,b,c){var d=a("./node"),e=function(a,b){this.key=a,this.value=b};e.prototype=new d,e.prototype.type="Assignment",e.prototype.accept=function(a){this.value=a.visit(this.value)},e.prototype.eval=function(a){return this.value.eval?new e(this.key,this.value.eval(a)):this},e.prototype.genCSS=function(a,b){b.add(this.key+"="),this.value.genCSS?this.value.genCSS(a,b):b.add(this.value)},b.exports=e},{"./node":70}],48:[function(a,b,c){var d=a("./node"),e=function(a,b,c){this.key=a,this.op=b,this.value=c};e.prototype=new d,e.prototype.type="Attribute",e.prototype.eval=function(a){return new e(this.key.eval?this.key.eval(a):this.key,this.op,this.value&&this.value.eval?this.value.eval(a):this.value)},e.prototype.genCSS=function(a,b){b.add(this.toCSS(a))},e.prototype.toCSS=function(a){var b=this.key.toCSS?this.key.toCSS(a):this.key;return this.op&&(b+=this.op,b+=this.value.toCSS?this.value.toCSS(a):this.value),"["+b+"]"},b.exports=e},{"./node":70}],49:[function(a,b,c){var d=a("./node"),e=a("../functions/function-caller"),f=function(a,b,c,d){this.name=a,this.args=b,this.index=c,this.currentFileInfo=d};f.prototype=new d,f.prototype.type="Call",f.prototype.accept=function(a){this.args&&(this.args=a.visitArray(this.args))},f.prototype.eval=function(a){var b,c=this.args.map(function(b){return b.eval(a)}),d=new e(this.name,a,this.index,this.currentFileInfo);if(d.isValid()){try{b=d.call(c)}catch(g){throw{type:g.type||"Runtime",message:"error evaluating function `"+this.name+"`"+(g.message?": "+g.message:""),index:this.index,filename:this.currentFileInfo.filename}}if(null!=b)return b.index=this.index,b.currentFileInfo=this.currentFileInfo,b}return new f(this.name,c,this.index,this.currentFileInfo)},f.prototype.genCSS=function(a,b){b.add(this.name+"(",this.currentFileInfo,this.index);for(var c=0;this.args.length>c;c++)this.args[c].genCSS(a,b),this.args.length>c+1&&b.add(", ");b.add(")")},b.exports=f},{"../functions/function-caller":21,"./node":70}],50:[function(a,b,c){function d(a,b){return Math.min(Math.max(a,0),b)}function e(a){return"#"+a.map(function(a){return a=d(Math.round(a),255),(16>a?"0":"")+a.toString(16)}).join("")}var f=a("./node"),g=a("../data/colors"),h=function(a,b,c){this.rgb=Array.isArray(a)?a:6==a.length?a.match(/.{2}/g).map(function(a){return parseInt(a,16)}):a.split("").map(function(a){return parseInt(a+a,16)}),this.alpha="number"==typeof b?b:1,"undefined"!=typeof c&&(this.value=c)};h.prototype=new f,h.prototype.type="Color",h.prototype.luma=function(){var a=this.rgb[0]/255,b=this.rgb[1]/255,c=this.rgb[2]/255;return a=.03928>=a?a/12.92:Math.pow((a+.055)/1.055,2.4),b=.03928>=b?b/12.92:Math.pow((b+.055)/1.055,2.4),c=.03928>=c?c/12.92:Math.pow((c+.055)/1.055,2.4),.2126*a+.7152*b+.0722*c},h.prototype.genCSS=function(a,b){b.add(this.toCSS(a))},h.prototype.toCSS=function(a,b){var c,e,f=a&&a.compress&&!b;if(this.value)return this.value;if(e=this.fround(a,this.alpha),1>e)return"rgba("+this.rgb.map(function(a){return d(Math.round(a),255)}).concat(d(e,1)).join(","+(f?"":" "))+")";if(c=this.toRGB(),f){var g=c.split("");g[1]===g[2]&&g[3]===g[4]&&g[5]===g[6]&&(c="#"+g[1]+g[3]+g[5])}return c},h.prototype.operate=function(a,b,c){for(var d=[],e=this.alpha*(1-c.alpha)+c.alpha,f=0;3>f;f++)d[f]=this._operate(a,b,this.rgb[f],c.rgb[f]);return new h(d,e)},h.prototype.toRGB=function(){return e(this.rgb)},h.prototype.toHSL=function(){var a,b,c=this.rgb[0]/255,d=this.rgb[1]/255,e=this.rgb[2]/255,f=this.alpha,g=Math.max(c,d,e),h=Math.min(c,d,e),i=(g+h)/2,j=g-h;if(g===h)a=b=0;else{switch(b=i>.5?j/(2-g-h):j/(g+h),g){case c:a=(d-e)/j+(e>d?6:0);break;case d:a=(e-c)/j+2;break;case e:a=(c-d)/j+4}a/=6}return{h:360*a,s:b,l:i,a:f}},h.prototype.toHSV=function(){var a,b,c=this.rgb[0]/255,d=this.rgb[1]/255,e=this.rgb[2]/255,f=this.alpha,g=Math.max(c,d,e),h=Math.min(c,d,e),i=g,j=g-h;if(b=0===g?0:j/g,g===h)a=0;else{switch(g){case c:a=(d-e)/j+(e>d?6:0);break;case d:a=(e-c)/j+2;break;case e:a=(c-d)/j+4}a/=6}return{h:360*a,s:b,v:i,a:f}},h.prototype.toARGB=function(){return e([255*this.alpha].concat(this.rgb))},h.prototype.compare=function(a){return a.rgb&&a.rgb[0]===this.rgb[0]&&a.rgb[1]===this.rgb[1]&&a.rgb[2]===this.rgb[2]&&a.alpha===this.alpha?0:void 0},h.fromKeyword=function(a){var b,c=a.toLowerCase();return g.hasOwnProperty(c)?b=new h(g[c].slice(1)):"transparent"===c&&(b=new h([0,0,0],0)),b?(b.value=a,b):void 0},b.exports=h},{"../data/colors":12,"./node":70}],51:[function(a,b,c){var d=a("./node"),e=function(a){" "===a?(this.value=" ",this.emptyOrWhitespace=!0):(this.value=a?a.trim():"",this.emptyOrWhitespace=""===this.value)};e.prototype=new d,e.prototype.type="Combinator";var f={"":!0," ":!0,"|":!0};e.prototype.genCSS=function(a,b){var c=a.compress||f[this.value]?"":" ";b.add(c+this.value+c)},b.exports=e},{"./node":70}],52:[function(a,b,c){var d=a("./node"),e=a("./debug-info"),f=function(a,b,c,d){this.value=a,this.isLineComment=b,this.currentFileInfo=d,this.allowRoot=!0};f.prototype=new d,f.prototype.type="Comment",f.prototype.genCSS=function(a,b){this.debugInfo&&b.add(e(a,this),this.currentFileInfo,this.index),b.add(this.value)},f.prototype.isSilent=function(a){var b=a.compress&&"!"!==this.value[2];return this.isLineComment||b},b.exports=f},{"./debug-info":54,"./node":70}],53:[function(a,b,c){var d=a("./node"),e=function(a,b,c,d,e){this.op=a.trim(),this.lvalue=b,this.rvalue=c,this.index=d,this.negate=e};e.prototype=new d,e.prototype.type="Condition",e.prototype.accept=function(a){this.lvalue=a.visit(this.lvalue),this.rvalue=a.visit(this.rvalue)},e.prototype.eval=function(a){var b=function(a,b,c){switch(a){case"and":return b&&c;case"or":return b||c;default:switch(d.compare(b,c)){case-1:return"<"===a||"=<"===a||"<="===a;case 0:return"="===a||">="===a||"=<"===a||"<="===a;case 1:return">"===a||">="===a;default:return!1}}}(this.op,this.lvalue.eval(a),this.rvalue.eval(a));return this.negate?!b:b},b.exports=e},{"./node":70}],54:[function(a,b,c){var d=function(a,b,c){var e="";if(a.dumpLineNumbers&&!a.compress)switch(a.dumpLineNumbers){case"comments":e=d.asComment(b);break;case"mediaquery":e=d.asMediaQuery(b);break;case"all":e=d.asComment(b)+(c||"")+d.asMediaQuery(b)}return e};d.asComment=function(a){return"/* line "+a.debugInfo.lineNumber+", "+a.debugInfo.fileName+" */\n"},d.asMediaQuery=function(a){var b=a.debugInfo.fileName;return/^[a-z]+:\/\//i.test(b)||(b="file://"+b),"@media -sass-debug-info{filename{font-family:"+b.replace(/([.:\/\\])/g,function(a){return"\\"==a&&(a="/"),"\\"+a})+"}line{font-family:\\00003"+a.debugInfo.lineNumber+"}}\n"},b.exports=d},{}],55:[function(a,b,c){var d=a("./node"),e=a("../contexts"),f=function(a,b){this.ruleset=a,this.frames=b};f.prototype=new d,f.prototype.type="DetachedRuleset",f.prototype.evalFirst=!0,f.prototype.accept=function(a){this.ruleset=a.visit(this.ruleset)},f.prototype.eval=function(a){var b=this.frames||a.frames.slice(0);return new f(this.ruleset,b)},f.prototype.callEval=function(a){return this.ruleset.eval(this.frames?new e.Eval(a,this.frames.concat(a.frames)):a)},b.exports=f},{"../contexts":11,"./node":70}],56:[function(a,b,c){var d=a("./node"),e=a("../data/unit-conversions"),f=a("./unit"),g=a("./color"),h=function(a,b){this.value=parseFloat(a),this.unit=b&&b instanceof f?b:new f(b?[b]:void 0)};h.prototype=new d,h.prototype.type="Dimension",h.prototype.accept=function(a){this.unit=a.visit(this.unit)},h.prototype.eval=function(a){return this},h.prototype.toColor=function(){return new g([this.value,this.value,this.value])},h.prototype.genCSS=function(a,b){if(a&&a.strictUnits&&!this.unit.isSingular())throw new Error("Multiple units in dimension. Correct the units or use the unit function. Bad unit: "+this.unit.toString());var c=this.fround(a,this.value),d=String(c);if(0!==c&&1e-6>c&&c>-1e-6&&(d=c.toFixed(20).replace(/0+$/,"")),a&&a.compress){if(0===c&&this.unit.isLength())return void b.add(d);c>0&&1>c&&(d=d.substr(1))}b.add(d),this.unit.genCSS(a,b)},h.prototype.operate=function(a,b,c){var d=this._operate(a,b,this.value,c.value),e=this.unit.clone();if("+"===b||"-"===b)if(0===e.numerator.length&&0===e.denominator.length)e=c.unit.clone(),this.unit.backupUnit&&(e.backupUnit=this.unit.backupUnit);else if(0===c.unit.numerator.length&&0===e.denominator.length);else{if(c=c.convertTo(this.unit.usedUnits()),a.strictUnits&&c.unit.toString()!==e.toString())throw new Error("Incompatible units. Change the units or use the unit function. Bad units: '"+e.toString()+"' and '"+c.unit.toString()+"'.");d=this._operate(a,b,this.value,c.value)}else"*"===b?(e.numerator=e.numerator.concat(c.unit.numerator).sort(),e.denominator=e.denominator.concat(c.unit.denominator).sort(),e.cancel()):"/"===b&&(e.numerator=e.numerator.concat(c.unit.denominator).sort(),e.denominator=e.denominator.concat(c.unit.numerator).sort(),e.cancel());return new h(d,e)},h.prototype.compare=function(a){var b,c;if(a instanceof h){if(this.unit.isEmpty()||a.unit.isEmpty())b=this,c=a;else if(b=this.unify(),c=a.unify(),0!==b.unit.compare(c.unit))return;return d.numericCompare(b.value,c.value)}},h.prototype.unify=function(){return this.convertTo({length:"px",duration:"s",angle:"rad"})},h.prototype.convertTo=function(a){var b,c,d,f,g,i=this.value,j=this.unit.clone(),k={};if("string"==typeof a){for(b in e)e[b].hasOwnProperty(a)&&(k={},k[b]=a);a=k}g=function(a,b){return d.hasOwnProperty(a)?(b?i/=d[a]/d[f]:i*=d[a]/d[f],f):a};for(c in a)a.hasOwnProperty(c)&&(f=a[c],d=e[c],j.map(g));return j.cancel(),new h(i,j)},b.exports=h},{"../data/unit-conversions":14,"./color":50,"./node":70,"./unit":79}],57:[function(a,b,c){var d=a("./node"),e=a("./selector"),f=a("./ruleset"),g=function(a,b,c,d,f,g,h,i){var j;if(this.name=a,this.value=b,c)for(Array.isArray(c)?this.rules=c:(this.rules=[c],this.rules[0].selectors=new e([],null,null,this.index,f).createEmptySelectors()),j=0;this.rules.length>j;j++)this.rules[j].allowImports=!0;this.index=d,this.currentFileInfo=f,this.debugInfo=g,this.isRooted=h||!1,this.copyVisibilityInfo(i),this.allowRoot=!0};g.prototype=new d,g.prototype.type="Directive",g.prototype.accept=function(a){var b=this.value,c=this.rules;c&&(this.rules=a.visitArray(c)),b&&(this.value=a.visit(b))},g.prototype.isRulesetLike=function(){return this.rules||!this.isCharset()},g.prototype.isCharset=function(){return"@charset"===this.name},g.prototype.genCSS=function(a,b){var c=this.value,d=this.rules;b.add(this.name,this.currentFileInfo,this.index),c&&(b.add(" "),c.genCSS(a,b)),d?this.outputRuleset(a,b,d):b.add(";")},g.prototype.eval=function(a){var b,c,d=this.value,e=this.rules;return b=a.mediaPath,c=a.mediaBlocks,a.mediaPath=[],a.mediaBlocks=[],d&&(d=d.eval(a)),e&&(e=[e[0].eval(a)],e[0].root=!0),a.mediaPath=b,a.mediaBlocks=c,new g(this.name,d,e,this.index,this.currentFileInfo,this.debugInfo,this.isRooted,this.visibilityInfo())},g.prototype.variable=function(a){return this.rules?f.prototype.variable.call(this.rules[0],a):void 0},g.prototype.find=function(){return this.rules?f.prototype.find.apply(this.rules[0],arguments):void 0},g.prototype.rulesets=function(){return this.rules?f.prototype.rulesets.apply(this.rules[0]):void 0},g.prototype.outputRuleset=function(a,b,c){var d,e=c.length;if(a.tabLevel=(0|a.tabLevel)+1,a.compress){for(b.add("{"),d=0;e>d;d++)c[d].genCSS(a,b);return b.add("}"),void a.tabLevel--}var f="\n"+Array(a.tabLevel).join(" "),g=f+" ";if(e){for(b.add(" {"+g),c[0].genCSS(a,b),d=1;e>d;d++)b.add(g),c[d].genCSS(a,b);b.add(f+"}")}else b.add(" {"+f+"}");a.tabLevel--},b.exports=g},{"./node":70,"./ruleset":76,"./selector":77}],58:[function(a,b,c){var d=a("./node"),e=a("./paren"),f=a("./combinator"),g=function(a,b,c,d,e){this.combinator=a instanceof f?a:new f(a),this.value="string"==typeof b?b.trim():b?b:"",this.index=c,this.currentFileInfo=d,this.copyVisibilityInfo(e)};g.prototype=new d,g.prototype.type="Element",g.prototype.accept=function(a){var b=this.value;this.combinator=a.visit(this.combinator),"object"==typeof b&&(this.value=a.visit(b))},g.prototype.eval=function(a){return new g(this.combinator,this.value.eval?this.value.eval(a):this.value,this.index,this.currentFileInfo,this.visibilityInfo())},g.prototype.clone=function(){return new g(this.combinator,this.value,this.index,this.currentFileInfo,this.visibilityInfo())},g.prototype.genCSS=function(a,b){b.add(this.toCSS(a),this.currentFileInfo,this.index)},g.prototype.toCSS=function(a){a=a||{};var b=this.value,c=a.firstSelector;return b instanceof e&&(a.firstSelector=!0),b=b.toCSS?b.toCSS(a):b,a.firstSelector=c,""===b&&"&"===this.combinator.value.charAt(0)?"":this.combinator.toCSS(a)+b},b.exports=g},{"./combinator":51,"./node":70,"./paren":72}],59:[function(a,b,c){var d=a("./node"),e=a("./paren"),f=a("./comment"),g=function(a){if(this.value=a,!a)throw new Error("Expression requires an array parameter")};g.prototype=new d,g.prototype.type="Expression",g.prototype.accept=function(a){this.value=a.visitArray(this.value)},g.prototype.eval=function(a){var b,c=this.parens&&!this.parensInOp,d=!1;return c&&a.inParenthesis(),this.value.length>1?b=new g(this.value.map(function(b){return b.eval(a)})):1===this.value.length?(this.value[0].parens&&!this.value[0].parensInOp&&(d=!0),b=this.value[0].eval(a)):b=this,c&&a.outOfParenthesis(),this.parens&&this.parensInOp&&!a.isMathOn()&&!d&&(b=new e(b)),b},g.prototype.genCSS=function(a,b){for(var c=0;this.value.length>c;c++)this.value[c].genCSS(a,b),this.value.length>c+1&&b.add(" ")},g.prototype.throwAwayComments=function(){this.value=this.value.filter(function(a){return!(a instanceof f)})},b.exports=g},{"./comment":52,"./node":70,"./paren":72}],60:[function(a,b,c){var d=a("./node"),e=a("./selector"),f=function g(a,b,c,d,e){switch(this.selector=a,this.option=b,this.index=c,this.object_id=g.next_id++,this.parent_ids=[this.object_id],this.currentFileInfo=d||{},this.copyVisibilityInfo(e),this.allowRoot=!0,b){case"all":this.allowBefore=!0,this.allowAfter=!0;break;default:this.allowBefore=!1,this.allowAfter=!1}};f.next_id=0,f.prototype=new d,f.prototype.type="Extend",f.prototype.accept=function(a){this.selector=a.visit(this.selector)},f.prototype.eval=function(a){return new f(this.selector.eval(a),this.option,this.index,this.currentFileInfo,this.visibilityInfo())},f.prototype.clone=function(a){return new f(this.selector,this.option,this.index,this.currentFileInfo,this.visibilityInfo())},f.prototype.findSelfSelectors=function(a){var b,c,d=[];for(b=0;a.length>b;b++)c=a[b].elements,b>0&&c.length&&""===c[0].combinator.value&&(c[0].combinator.value=" "),d=d.concat(a[b].elements);this.selfSelectors=[new e(d)],this.selfSelectors[0].copyVisibilityInfo(this.visibilityInfo())},b.exports=f},{"./node":70,"./selector":77}],61:[function(a,b,c){var d=a("./node"),e=a("./media"),f=a("./url"),g=a("./quoted"),h=a("./ruleset"),i=a("./anonymous"),j=function(a,b,c,d,e,f){if(this.options=c,this.index=d,this.path=a,this.features=b,this.currentFileInfo=e,this.allowRoot=!0,void 0!==this.options.less||this.options.inline)this.css=!this.options.less||this.options.inline;else{var g=this.getPath();g&&/[#\.\&\?\/]css([\?;].*)?$/.test(g)&&(this.css=!0)}this.copyVisibilityInfo(f)};j.prototype=new d,j.prototype.type="Import",j.prototype.accept=function(a){this.features&&(this.features=a.visit(this.features)),this.path=a.visit(this.path),this.options.plugin||this.options.inline||!this.root||(this.root=a.visit(this.root))},j.prototype.genCSS=function(a,b){this.css&&void 0===this.path.currentFileInfo.reference&&(b.add("@import ",this.currentFileInfo,this.index),this.path.genCSS(a,b),this.features&&(b.add(" "),this.features.genCSS(a,b)),b.add(";"))},j.prototype.getPath=function(){return this.path instanceof f?this.path.value.value:this.path.value},j.prototype.isVariableImport=function(){var a=this.path;return a instanceof f&&(a=a.value),a instanceof g?a.containsVariables():!0},j.prototype.evalForImport=function(a){var b=this.path;return b instanceof f&&(b=b.value),new j(b.eval(a),this.features,this.options,this.index,this.currentFileInfo,this.visibilityInfo())},j.prototype.evalPath=function(a){var b=this.path.eval(a),c=this.currentFileInfo&&this.currentFileInfo.rootpath;if(!(b instanceof f)){if(c){var d=b.value;d&&a.isPathRelative(d)&&(b.value=c+d)}b.value=a.normalizePath(b.value)}return b},j.prototype.eval=function(a){var b=this.doEval(a);return(this.options.reference||this.blocksVisibility())&&(b.length||0===b.length?b.forEach(function(a){a.addVisibilityBlock()}):b.addVisibilityBlock()),b},j.prototype.doEval=function(a){var b,c,d=this.features&&this.features.eval(a);if(this.options.plugin)return c=a.frames[0]&&a.frames[0].functionRegistry,c&&this.root&&this.root.functions&&c.addMultiple(this.root.functions),[];if(this.skip&&("function"==typeof this.skip&&(this.skip=this.skip()),this.skip))return[];if(this.options.inline){var f=new i(this.root,0,{filename:this.importedFilename,reference:this.path.currentFileInfo&&this.path.currentFileInfo.reference},!0,!0);return this.features?new e([f],this.features.value):[f]}if(this.css){var g=new j(this.evalPath(a),d,this.options,this.index);if(!g.css&&this.error)throw this.error;return g}return b=new h(null,this.root.rules.slice(0)),b.evalImports(a),this.features?new e(b.rules,this.features.value):b.rules},b.exports=j},{"./anonymous":46,"./media":66,"./node":70,"./quoted":73,"./ruleset":76,"./url":80}],62:[function(a,b,c){var d={};d.Node=a("./node"),d.Alpha=a("./alpha"),d.Color=a("./color"),d.Directive=a("./directive"),d.DetachedRuleset=a("./detached-ruleset"),d.Operation=a("./operation"),d.Dimension=a("./dimension"),d.Unit=a("./unit"),d.Keyword=a("./keyword"),d.Variable=a("./variable"),d.Ruleset=a("./ruleset"),d.Element=a("./element"),d.Attribute=a("./attribute"),d.Combinator=a("./combinator"),d.Selector=a("./selector"),d.Quoted=a("./quoted"),d.Expression=a("./expression"),d.Rule=a("./rule"),d.Call=a("./call"),d.URL=a("./url"),d.Import=a("./import"),d.mixin={Call:a("./mixin-call"),Definition:a("./mixin-definition")},d.Comment=a("./comment"),d.Anonymous=a("./anonymous"),d.Value=a("./value"),d.JavaScript=a("./javascript"),d.Assignment=a("./assignment"),d.Condition=a("./condition"),d.Paren=a("./paren"),d.Media=a("./media"),d.UnicodeDescriptor=a("./unicode-descriptor"),d.Negative=a("./negative"),d.Extend=a("./extend"),d.RulesetCall=a("./ruleset-call"),b.exports=d},{"./alpha":45,"./anonymous":46,"./assignment":47,"./attribute":48,"./call":49,"./color":50,"./combinator":51,"./comment":52,"./condition":53,"./detached-ruleset":55,"./dimension":56,"./directive":57,"./element":58,"./expression":59,"./extend":60,"./import":61,"./javascript":63,"./keyword":65,"./media":66,"./mixin-call":67,"./mixin-definition":68,"./negative":69,"./node":70,"./operation":71,"./paren":72,"./quoted":73,"./rule":74,"./ruleset":76,"./ruleset-call":75,"./selector":77,"./unicode-descriptor":78,"./unit":79,"./url":80,"./value":81,"./variable":82}],63:[function(a,b,c){var d=a("./js-eval-node"),e=a("./dimension"),f=a("./quoted"),g=a("./anonymous"),h=function(a,b,c,d){this.escaped=b,this.expression=a,this.index=c,this.currentFileInfo=d};h.prototype=new d,h.prototype.type="JavaScript",h.prototype.eval=function(a){var b=this.evaluateJavaScript(this.expression,a);return"number"==typeof b?new e(b):"string"==typeof b?new f('"'+b+'"',b,this.escaped,this.index):new g(Array.isArray(b)?b.join(", "):b)},b.exports=h},{"./anonymous":46,"./dimension":56,"./js-eval-node":64,"./quoted":73}],64:[function(a,b,c){var d=a("./node"),e=a("./variable"),f=function(){};f.prototype=new d,f.prototype.evaluateJavaScript=function(a,b){var c,d=this,f={};if(void 0!==b.javascriptEnabled&&!b.javascriptEnabled)throw{message:"You are using JavaScript, which has been disabled.",filename:this.currentFileInfo.filename,index:this.index};a=a.replace(/@\{([\w-]+)\}/g,function(a,c){return d.jsify(new e("@"+c,d.index,d.currentFileInfo).eval(b))});try{a=new Function("return ("+a+")")}catch(g){throw{message:"JavaScript evaluation error: "+g.message+" from `"+a+"`",filename:this.currentFileInfo.filename,index:this.index}}var h=b.frames[0].variables();for(var i in h)h.hasOwnProperty(i)&&(f[i.slice(1)]={value:h[i].value,toJS:function(){return this.value.eval(b).toCSS()}});try{c=a.call(f)}catch(g){throw{message:"JavaScript evaluation error: '"+g.name+": "+g.message.replace(/["]/g,"'")+"'",filename:this.currentFileInfo.filename,index:this.index}}return c},f.prototype.jsify=function(a){return Array.isArray(a.value)&&a.value.length>1?"["+a.value.map(function(a){return a.toCSS()}).join(", ")+"]":a.toCSS()},b.exports=f},{"./node":70,"./variable":82}],65:[function(a,b,c){var d=a("./node"),e=function(a){this.value=a};e.prototype=new d,e.prototype.type="Keyword",e.prototype.genCSS=function(a,b){if("%"===this.value)throw{type:"Syntax",message:"Invalid % without number"};b.add(this.value)},e.True=new e("true"),e.False=new e("false"),b.exports=e},{"./node":70}],66:[function(a,b,c){var d=a("./ruleset"),e=a("./value"),f=a("./selector"),g=a("./anonymous"),h=a("./expression"),i=a("./directive"),j=function(a,b,c,g,h){this.index=c,this.currentFileInfo=g;var i=new f([],null,null,this.index,this.currentFileInfo).createEmptySelectors();this.features=new e(b),this.rules=[new d(i,a)],this.rules[0].allowImports=!0,this.copyVisibilityInfo(h),this.allowRoot=!0};j.prototype=new i,j.prototype.type="Media",j.prototype.isRulesetLike=!0,j.prototype.accept=function(a){this.features&&(this.features=a.visit(this.features)),this.rules&&(this.rules=a.visitArray(this.rules))},j.prototype.genCSS=function(a,b){b.add("@media ",this.currentFileInfo,this.index),this.features.genCSS(a,b),this.outputRuleset(a,b,this.rules)},j.prototype.eval=function(a){a.mediaBlocks||(a.mediaBlocks=[],a.mediaPath=[]);var b=new j(null,[],this.index,this.currentFileInfo,this.visibilityInfo());this.debugInfo&&(this.rules[0].debugInfo=this.debugInfo,b.debugInfo=this.debugInfo);var c=!1;a.strictMath||(c=!0,a.strictMath=!0);try{b.features=this.features.eval(a)}finally{c&&(a.strictMath=!1)}return a.mediaPath.push(b),a.mediaBlocks.push(b),this.rules[0].functionRegistry=a.frames[0].functionRegistry.inherit(),a.frames.unshift(this.rules[0]),b.rules=[this.rules[0].eval(a)],a.frames.shift(),a.mediaPath.pop(),0===a.mediaPath.length?b.evalTop(a):b.evalNested(a)},j.prototype.evalTop=function(a){var b=this;if(a.mediaBlocks.length>1){var c=new f([],null,null,this.index,this.currentFileInfo).createEmptySelectors();b=new d(c,a.mediaBlocks),b.multiMedia=!0,b.copyVisibilityInfo(this.visibilityInfo())}return delete a.mediaBlocks,delete a.mediaPath,b},j.prototype.evalNested=function(a){var b,c,f=a.mediaPath.concat([this]);for(b=0;f.length>b;b++)c=f[b].features instanceof e?f[b].features.value:f[b].features,f[b]=Array.isArray(c)?c:[c];return this.features=new e(this.permute(f).map(function(a){for(a=a.map(function(a){return a.toCSS?a:new g(a)}),b=a.length-1;b>0;b--)a.splice(b,0,new g("and"));return new h(a)})),new d([],[])},j.prototype.permute=function(a){if(0===a.length)return[];if(1===a.length)return a[0];for(var b=[],c=this.permute(a.slice(1)),d=0;c.length>d;d++)for(var e=0;a[0].length>e;e++)b.push([a[0][e]].concat(c[d]));return b},j.prototype.bubbleSelectors=function(a){a&&(this.rules=[new d(a.slice(0),[this.rules[0]])])},b.exports=j},{"./anonymous":46,"./directive":57,"./expression":59,"./ruleset":76,"./selector":77,"./value":81}],67:[function(a,b,c){var d=a("./node"),e=a("./selector"),f=a("./mixin-definition"),g=a("../functions/default"),h=function(a,b,c,d,f){this.selector=new e(a),this.arguments=b||[],this.index=c,this.currentFileInfo=d,this.important=f,this.allowRoot=!0};h.prototype=new d,h.prototype.type="MixinCall",h.prototype.accept=function(a){this.selector&&(this.selector=a.visit(this.selector)),this.arguments.length&&(this.arguments=a.visitArray(this.arguments))},h.prototype.eval=function(a){function b(b,c){var d,e,f;for(d=0;2>d;d++){for(x[d]=!0,g.value(d),e=0;c.length>e&&x[d];e++)f=c[e],f.matchCondition&&(x[d]=x[d]&&f.matchCondition(null,a));b.matchCondition&&(x[d]=x[d]&&b.matchCondition(t,a))}return x[0]||x[1]?x[0]!=x[1]?x[1]?A:B:z:y}var c,d,e,h,i,j,k,l,m,n,o,p,q,r,s,t=[],u=[],v=!1,w=[],x=[],y=-1,z=0,A=1,B=2;for(j=0;this.arguments.length>j;j++)if(h=this.arguments[j],i=h.value.eval(a),h.expand&&Array.isArray(i.value))for(i=i.value,k=0;i.length>k;k++)t.push({value:i[k]});else t.push({name:h.name,value:i});for(s=function(b){return b.matchArgs(null,a)},j=0;a.frames.length>j;j++)if((c=a.frames[j].find(this.selector,null,s)).length>0){for(n=!0,k=0;c.length>k;k++){for(d=c[k].rule,e=c[k].path,m=!1,l=0;a.frames.length>l;l++)if(!(d instanceof f)&&d===(a.frames[l].originalRuleset||a.frames[l])){m=!0;break}m||d.matchArgs(t,a)&&(o={mixin:d,group:b(d,e)},o.group!==y&&w.push(o),v=!0)}for(g.reset(),q=[0,0,0],k=0;w.length>k;k++)q[w[k].group]++;if(q[z]>0)p=B;else if(p=A,q[A]+q[B]>1)throw{type:"Runtime",message:"Ambiguous use of `default()` found when matching for `"+this.format(t)+"`",index:this.index,filename:this.currentFileInfo.filename};for(k=0;w.length>k;k++)if(o=w[k].group,o===z||o===p)try{d=w[k].mixin,d instanceof f||(r=d.originalRuleset||d,d=new f("",[],d.rules,null,!1,null,r.visibilityInfo()),d.originalRuleset=r);var C=d.evalCall(a,t,this.important).rules;
-this._setVisibilityToReplacement(C),Array.prototype.push.apply(u,C)}catch(D){throw{message:D.message,index:this.index,filename:this.currentFileInfo.filename,stack:D.stack}}if(v)return u}throw n?{type:"Runtime",message:"No matching definition was found for `"+this.format(t)+"`",index:this.index,filename:this.currentFileInfo.filename}:{type:"Name",message:this.selector.toCSS().trim()+" is undefined",index:this.index,filename:this.currentFileInfo.filename}},h.prototype._setVisibilityToReplacement=function(a){var b,c;if(this.blocksVisibility())for(b=0;a.length>b;b++)c=a[b],c.addVisibilityBlock()},h.prototype.format=function(a){return this.selector.toCSS().trim()+"("+(a?a.map(function(a){var b="";return a.name&&(b+=a.name+":"),b+=a.value.toCSS?a.value.toCSS():"???"}).join(", "):"")+")"},b.exports=h},{"../functions/default":20,"./mixin-definition":68,"./node":70,"./selector":77}],68:[function(a,b,c){var d=a("./selector"),e=a("./element"),f=a("./ruleset"),g=a("./rule"),h=a("./expression"),i=a("../contexts"),j=function(a,b,c,f,g,h,i){this.name=a,this.selectors=[new d([new e(null,a,this.index,this.currentFileInfo)])],this.params=b,this.condition=f,this.variadic=g,this.arity=b.length,this.rules=c,this._lookups={};var j=[];this.required=b.reduce(function(a,b){return!b.name||b.name&&!b.value?a+1:(j.push(b.name),a)},0),this.optionalParameters=j,this.frames=h,this.copyVisibilityInfo(i),this.allowRoot=!0};j.prototype=new f,j.prototype.type="MixinDefinition",j.prototype.evalFirst=!0,j.prototype.accept=function(a){this.params&&this.params.length&&(this.params=a.visitArray(this.params)),this.rules=a.visitArray(this.rules),this.condition&&(this.condition=a.visit(this.condition))},j.prototype.evalParams=function(a,b,c,d){var e,j,k,l,m,n,o,p,q=new f(null,null),r=this.params.slice(0),s=0;if(b.frames&&b.frames[0]&&b.frames[0].functionRegistry&&(q.functionRegistry=b.frames[0].functionRegistry.inherit()),b=new i.Eval(b,[q].concat(b.frames)),c)for(c=c.slice(0),s=c.length,k=0;s>k;k++)if(j=c[k],n=j&&j.name){for(o=!1,l=0;r.length>l;l++)if(!d[l]&&n===r[l].name){d[l]=j.value.eval(a),q.prependRule(new g(n,j.value.eval(a))),o=!0;break}if(o){c.splice(k,1),k--;continue}throw{type:"Runtime",message:"Named argument for "+this.name+" "+c[k].name+" not found"}}for(p=0,k=0;r.length>k;k++)if(!d[k]){if(j=c&&c[p],n=r[k].name)if(r[k].variadic){for(e=[],l=p;s>l;l++)e.push(c[l].value.eval(a));q.prependRule(new g(n,new h(e).eval(a)))}else{if(m=j&&j.value)m=m.eval(a);else{if(!r[k].value)throw{type:"Runtime",message:"wrong number of arguments for "+this.name+" ("+s+" for "+this.arity+")"};m=r[k].value.eval(b),q.resetCache()}q.prependRule(new g(n,m)),d[k]=m}if(r[k].variadic&&c)for(l=p;s>l;l++)d[l]=c[l].value.eval(a);p++}return q},j.prototype.makeImportant=function(){var a=this.rules?this.rules.map(function(a){return a.makeImportant?a.makeImportant(!0):a}):this.rules,b=new j(this.name,this.params,a,this.condition,this.variadic,this.frames);return b},j.prototype.eval=function(a){return new j(this.name,this.params,this.rules,this.condition,this.variadic,this.frames||a.frames.slice(0))},j.prototype.evalCall=function(a,b,c){var d,e,j=[],k=this.frames?this.frames.concat(a.frames):a.frames,l=this.evalParams(a,new i.Eval(a,k),b,j);return l.prependRule(new g("@arguments",new h(j).eval(a))),d=this.rules.slice(0),e=new f(null,d),e.originalRuleset=this,e=e.eval(new i.Eval(a,[this,l].concat(k))),c&&(e=e.makeImportant()),e},j.prototype.matchCondition=function(a,b){return!this.condition||this.condition.eval(new i.Eval(b,[this.evalParams(b,new i.Eval(b,this.frames?this.frames.concat(b.frames):b.frames),a,[])].concat(this.frames||[]).concat(b.frames)))},j.prototype.matchArgs=function(a,b){var c,d=a&&a.length||0,e=this.optionalParameters,f=a?a.reduce(function(a,b){return e.indexOf(b.name)<0?a+1:a},0):0;if(this.variadic){if(this.required-1>f)return!1}else{if(this.required>f)return!1;if(d>this.params.length)return!1}c=Math.min(f,this.arity);for(var g=0;c>g;g++)if(!this.params[g].name&&!this.params[g].variadic&&a[g].value.eval(b).toCSS()!=this.params[g].value.eval(b).toCSS())return!1;return!0},b.exports=j},{"../contexts":11,"./element":58,"./expression":59,"./rule":74,"./ruleset":76,"./selector":77}],69:[function(a,b,c){var d=a("./node"),e=a("./operation"),f=a("./dimension"),g=function(a){this.value=a};g.prototype=new d,g.prototype.type="Negative",g.prototype.genCSS=function(a,b){b.add("-"),this.value.genCSS(a,b)},g.prototype.eval=function(a){return a.isMathOn()?new e("*",[new f(-1),this.value]).eval(a):new g(this.value.eval(a))},b.exports=g},{"./dimension":56,"./node":70,"./operation":71}],70:[function(a,b,c){var d=function(){};d.prototype.toCSS=function(a){var b=[];return this.genCSS(a,{add:function(a,c,d){b.push(a)},isEmpty:function(){return 0===b.length}}),b.join("")},d.prototype.genCSS=function(a,b){b.add(this.value)},d.prototype.accept=function(a){this.value=a.visit(this.value)},d.prototype.eval=function(){return this},d.prototype._operate=function(a,b,c,d){switch(b){case"+":return c+d;case"-":return c-d;case"*":return c*d;case"/":return c/d}},d.prototype.fround=function(a,b){var c=a&&a.numPrecision;return null==c?b:Number((b+2e-16).toFixed(c))},d.compare=function(a,b){if(a.compare&&"Quoted"!==b.type&&"Anonymous"!==b.type)return a.compare(b);if(b.compare)return-b.compare(a);if(a.type===b.type){if(a=a.value,b=b.value,!Array.isArray(a))return a===b?0:void 0;if(a.length===b.length){for(var c=0;a.length>c;c++)if(0!==d.compare(a[c],b[c]))return;return 0}}},d.numericCompare=function(a,b){return b>a?-1:a===b?0:a>b?1:void 0},d.prototype.blocksVisibility=function(){return null==this.visibilityBlocks&&(this.visibilityBlocks=0),0!==this.visibilityBlocks},d.prototype.addVisibilityBlock=function(){null==this.visibilityBlocks&&(this.visibilityBlocks=0),this.visibilityBlocks=this.visibilityBlocks+1},d.prototype.removeVisibilityBlock=function(){null==this.visibilityBlocks&&(this.visibilityBlocks=0),this.visibilityBlocks=this.visibilityBlocks-1},d.prototype.ensureVisibility=function(){this.nodeVisible=!0},d.prototype.ensureInvisibility=function(){this.nodeVisible=!1},d.prototype.isVisible=function(){return this.nodeVisible},d.prototype.visibilityInfo=function(){return{visibilityBlocks:this.visibilityBlocks,nodeVisible:this.nodeVisible}},d.prototype.copyVisibilityInfo=function(a){a&&(this.visibilityBlocks=a.visibilityBlocks,this.nodeVisible=a.nodeVisible)},b.exports=d},{}],71:[function(a,b,c){var d=a("./node"),e=a("./color"),f=a("./dimension"),g=function(a,b,c){this.op=a.trim(),this.operands=b,this.isSpaced=c};g.prototype=new d,g.prototype.type="Operation",g.prototype.accept=function(a){this.operands=a.visit(this.operands)},g.prototype.eval=function(a){var b=this.operands[0].eval(a),c=this.operands[1].eval(a);if(a.isMathOn()){if(b instanceof f&&c instanceof e&&(b=b.toColor()),c instanceof f&&b instanceof e&&(c=c.toColor()),!b.operate)throw{type:"Operation",message:"Operation on an invalid type"};return b.operate(a,this.op,c)}return new g(this.op,[b,c],this.isSpaced)},g.prototype.genCSS=function(a,b){this.operands[0].genCSS(a,b),this.isSpaced&&b.add(" "),b.add(this.op),this.isSpaced&&b.add(" "),this.operands[1].genCSS(a,b)},b.exports=g},{"./color":50,"./dimension":56,"./node":70}],72:[function(a,b,c){var d=a("./node"),e=function(a){this.value=a};e.prototype=new d,e.prototype.type="Paren",e.prototype.genCSS=function(a,b){b.add("("),this.value.genCSS(a,b),b.add(")")},e.prototype.eval=function(a){return new e(this.value.eval(a))},b.exports=e},{"./node":70}],73:[function(a,b,c){var d=a("./node"),e=a("./js-eval-node"),f=a("./variable"),g=function(a,b,c,d,e){this.escaped=null==c?!0:c,this.value=b||"",this.quote=a.charAt(0),this.index=d,this.currentFileInfo=e};g.prototype=new e,g.prototype.type="Quoted",g.prototype.genCSS=function(a,b){this.escaped||b.add(this.quote,this.currentFileInfo,this.index),b.add(this.value),this.escaped||b.add(this.quote)},g.prototype.containsVariables=function(){return this.value.match(/(`([^`]+)`)|@\{([\w-]+)\}/)},g.prototype.eval=function(a){function b(a,b,c){var d=a;do a=d,d=a.replace(b,c);while(a!==d);return d}var c=this,d=this.value,e=function(b,d){return String(c.evaluateJavaScript(d,a))},h=function(b,d){var e=new f("@"+d,c.index,c.currentFileInfo).eval(a,!0);return e instanceof g?e.value:e.toCSS()};return d=b(d,/`([^`]+)`/g,e),d=b(d,/@\{([\w-]+)\}/g,h),new g(this.quote+d+this.quote,d,this.escaped,this.index,this.currentFileInfo)},g.prototype.compare=function(a){return"Quoted"!==a.type||this.escaped||a.escaped?a.toCSS&&this.toCSS()===a.toCSS()?0:void 0:d.numericCompare(this.value,a.value)},b.exports=g},{"./js-eval-node":64,"./node":70,"./variable":82}],74:[function(a,b,c){function d(a,b){var c,d="",e=b.length,f={add:function(a){d+=a}};for(c=0;e>c;c++)b[c].eval(a).genCSS(a,f);return d}var e=a("./node"),f=a("./value"),g=a("./keyword"),h=function(a,b,c,d,g,h,i,j){this.name=a,this.value=b instanceof e?b:new f([b]),this.important=c?" "+c.trim():"",this.merge=d,this.index=g,this.currentFileInfo=h,this.inline=i||!1,this.variable=void 0!==j?j:a.charAt&&"@"===a.charAt(0),this.allowRoot=!0};h.prototype=new e,h.prototype.type="Rule",h.prototype.genCSS=function(a,b){b.add(this.name+(a.compress?":":": "),this.currentFileInfo,this.index);try{this.value.genCSS(a,b)}catch(c){throw c.index=this.index,c.filename=this.currentFileInfo.filename,c}b.add(this.important+(this.inline||a.lastRule&&a.compress?"":";"),this.currentFileInfo,this.index)},h.prototype.eval=function(a){var b,c=!1,e=this.name,f=this.variable;"string"!=typeof e&&(e=1===e.length&&e[0]instanceof g?e[0].value:d(a,e),f=!1),"font"!==e||a.strictMath||(c=!0,a.strictMath=!0);try{if(a.importantScope.push({}),b=this.value.eval(a),!this.variable&&"DetachedRuleset"===b.type)throw{message:"Rulesets cannot be evaluated on a property.",index:this.index,filename:this.currentFileInfo.filename};var i=this.important,j=a.importantScope.pop();return!i&&j.important&&(i=j.important),new h(e,b,i,this.merge,this.index,this.currentFileInfo,this.inline,f)}catch(k){throw"number"!=typeof k.index&&(k.index=this.index,k.filename=this.currentFileInfo.filename),k}finally{c&&(a.strictMath=!1)}},h.prototype.makeImportant=function(){return new h(this.name,this.value,"!important",this.merge,this.index,this.currentFileInfo,this.inline)},b.exports=h},{"./keyword":65,"./node":70,"./value":81}],75:[function(a,b,c){var d=a("./node"),e=a("./variable"),f=function(a){this.variable=a,this.allowRoot=!0};f.prototype=new d,f.prototype.type="RulesetCall",f.prototype.eval=function(a){var b=new e(this.variable).eval(a);return b.callEval(a)},b.exports=f},{"./node":70,"./variable":82}],76:[function(a,b,c){var d=a("./node"),e=a("./rule"),f=a("./selector"),g=a("./element"),h=a("./paren"),i=a("../contexts"),j=a("../functions/function-registry"),k=a("../functions/default"),l=a("./debug-info"),m=function(a,b,c,d){this.selectors=a,this.rules=b,this._lookups={},this.strictImports=c,this.copyVisibilityInfo(d),this.allowRoot=!0};m.prototype=new d,m.prototype.type="Ruleset",m.prototype.isRuleset=!0,m.prototype.isRulesetLike=!0,m.prototype.accept=function(a){this.paths?this.paths=a.visitArray(this.paths,!0):this.selectors&&(this.selectors=a.visitArray(this.selectors)),this.rules&&this.rules.length&&(this.rules=a.visitArray(this.rules))},m.prototype.eval=function(a){var b,c,d,f,g=this.selectors,h=!1;if(g&&(c=g.length)){for(b=[],k.error({type:"Syntax",message:"it is currently only allowed in parametric mixin guards,"}),f=0;c>f;f++)d=g[f].eval(a),b.push(d),d.evaldCondition&&(h=!0);k.reset()}else h=!0;var i,l,n=this.rules?this.rules.slice(0):null,o=new m(b,n,this.strictImports,this.visibilityInfo());o.originalRuleset=this,o.root=this.root,o.firstRoot=this.firstRoot,o.allowImports=this.allowImports,this.debugInfo&&(o.debugInfo=this.debugInfo),h||(n.length=0),o.functionRegistry=function(a){for(var b,c=0,d=a.length;c!==d;++c)if(b=a[c].functionRegistry)return b;return j}(a.frames).inherit();var p=a.frames;p.unshift(o);var q=a.selectors;q||(a.selectors=q=[]),q.unshift(this.selectors),(o.root||o.allowImports||!o.strictImports)&&o.evalImports(a);var r=o.rules,s=r?r.length:0;for(f=0;s>f;f++)r[f].evalFirst&&(r[f]=r[f].eval(a));var t=a.mediaBlocks&&a.mediaBlocks.length||0;for(f=0;s>f;f++)"MixinCall"===r[f].type?(n=r[f].eval(a).filter(function(a){return a instanceof e&&a.variable?!o.variable(a.name):!0}),r.splice.apply(r,[f,1].concat(n)),s+=n.length-1,f+=n.length-1,o.resetCache()):"RulesetCall"===r[f].type&&(n=r[f].eval(a).rules.filter(function(a){return!(a instanceof e&&a.variable)}),r.splice.apply(r,[f,1].concat(n)),s+=n.length-1,f+=n.length-1,o.resetCache());for(f=0;r.length>f;f++)i=r[f],i.evalFirst||(r[f]=i=i.eval?i.eval(a):i);for(f=0;r.length>f;f++)if(i=r[f],i instanceof m&&i.selectors&&1===i.selectors.length&&i.selectors[0].isJustParentSelector()){r.splice(f--,1);for(var u=0;i.rules.length>u;u++)l=i.rules[u],l.copyVisibilityInfo(i.visibilityInfo()),l instanceof e&&l.variable||r.splice(++f,0,l)}if(p.shift(),q.shift(),a.mediaBlocks)for(f=t;a.mediaBlocks.length>f;f++)a.mediaBlocks[f].bubbleSelectors(b);return o},m.prototype.evalImports=function(a){var b,c,d=this.rules;if(d)for(b=0;d.length>b;b++)"Import"===d[b].type&&(c=d[b].eval(a),c&&(c.length||0===c.length)?(d.splice.apply(d,[b,1].concat(c)),b+=c.length-1):d.splice(b,1,c),this.resetCache())},m.prototype.makeImportant=function(){var a=new m(this.selectors,this.rules.map(function(a){return a.makeImportant?a.makeImportant():a}),this.strictImports,this.visibilityInfo());return a},m.prototype.matchArgs=function(a){return!a||0===a.length},m.prototype.matchCondition=function(a,b){var c=this.selectors[this.selectors.length-1];return c.evaldCondition?!c.condition||c.condition.eval(new i.Eval(b,b.frames)):!1},m.prototype.resetCache=function(){this._rulesets=null,this._variables=null,this._lookups={}},m.prototype.variables=function(){return this._variables||(this._variables=this.rules?this.rules.reduce(function(a,b){if(b instanceof e&&b.variable===!0&&(a[b.name]=b),"Import"===b.type&&b.root&&b.root.variables){var c=b.root.variables();for(var d in c)c.hasOwnProperty(d)&&(a[d]=c[d])}return a},{}):{}),this._variables},m.prototype.variable=function(a){return this.variables()[a]},m.prototype.rulesets=function(){if(!this.rules)return[];var a,b,c=[],d=this.rules,e=d.length;for(a=0;e>a;a++)b=d[a],b.isRuleset&&c.push(b);return c},m.prototype.prependRule=function(a){var b=this.rules;b?b.unshift(a):this.rules=[a]},m.prototype.find=function(a,b,c){b=b||this;var d,e,g=[],h=a.toCSS();return h in this._lookups?this._lookups[h]:(this.rulesets().forEach(function(h){if(h!==b)for(var i=0;h.selectors.length>i;i++)if(d=a.match(h.selectors[i])){if(a.elements.length>d){if(!c||c(h)){e=h.find(new f(a.elements.slice(d)),b,c);for(var j=0;e.length>j;++j)e[j].path.push(h);Array.prototype.push.apply(g,e)}}else g.push({rule:h,path:[]});break}}),this._lookups[h]=g,g)},m.prototype.genCSS=function(a,b){function c(a){return"boolean"==typeof a.isRulesetLike?a.isRulesetLike:"function"==typeof a.isRulesetLike?a.isRulesetLike():!1}var d,e,f,g,h,i=[],j=[];a.tabLevel=a.tabLevel||0,this.root||a.tabLevel++;var k,m=a.compress?"":Array(a.tabLevel+1).join(" "),n=a.compress?"":Array(a.tabLevel).join(" "),o=0,p=0;for(d=0;this.rules.length>d;d++)g=this.rules[d],"Comment"===g.type?(p===d&&p++,j.push(g)):g.isCharset&&g.isCharset()?(j.splice(o,0,g),o++,p++):"Import"===g.type?(j.splice(p,0,g),p++):j.push(g);if(j=i.concat(j),!this.root){f=l(a,this,n),f&&(b.add(f),b.add(n));var q,r=this.paths,s=r.length;for(k=a.compress?",":",\n"+n,d=0;s>d;d++)if(h=r[d],q=h.length)for(d>0&&b.add(k),a.firstSelector=!0,h[0].genCSS(a,b),a.firstSelector=!1,e=1;q>e;e++)h[e].genCSS(a,b);b.add((a.compress?"{":" {\n")+m)}for(d=0;j.length>d;d++){g=j[d],d+1===j.length&&(a.lastRule=!0);var t=a.lastRule;c(g)&&(a.lastRule=!1),g.genCSS?g.genCSS(a,b):g.value&&b.add(g.value.toString()),a.lastRule=t,a.lastRule?a.lastRule=!1:b.add(a.compress?"":"\n"+m)}this.root||(b.add(a.compress?"}":"\n"+n+"}"),a.tabLevel--),b.isEmpty()||a.compress||!this.firstRoot||b.add("\n")},m.prototype.joinSelectors=function(a,b,c){for(var d=0;c.length>d;d++)this.joinSelector(a,b,c[d])},m.prototype.joinSelector=function(a,b,c){function d(a,b){var c,d;if(0===a.length)c=new h(a[0]);else{var e=[];for(d=0;a.length>d;d++)e.push(new g(null,a[d],b.index,b.currentFileInfo));c=new h(new f(e))}return c}function e(a,b){var c,d;return c=new g(null,a,b.index,b.currentFileInfo),d=new f([c])}function i(a,b,c,d){var e,f,h;if(e=[],a.length>0?(e=a.slice(0),f=e.pop(),h=d.createDerived(f.elements.slice(0))):h=d.createDerived([]),b.length>0){var i=c.combinator,j=b[0].elements[0];i.emptyOrWhitespace&&!j.combinator.emptyOrWhitespace&&(i=j.combinator),h.elements.push(new g(i,j.value,c.index,c.currentFileInfo)),h.elements=h.elements.concat(b[0].elements.slice(1))}if(0!==h.elements.length&&e.push(h),b.length>1){var k=b.slice(1);k=k.map(function(a){return a.createDerived(a.elements,[])}),e=e.concat(k)}return e}function j(a,b,c,d,e){var f;for(f=0;a.length>f;f++){var g=i(a[f],b,c,d);e.push(g)}return e}function k(a,b){var c,d;if(0!==a.length){if(0===b.length)return void b.push([new f(a)]);for(c=0;b.length>c;c++)d=b[c],d.length>0?d[d.length-1]=d[d.length-1].createDerived(d[d.length-1].elements.concat(a)):d.push(new f(a))}}function l(a,b,c){function f(a){var b;return"Paren"!==a.value.type?null:(b=a.value.value,"Selector"!==b.type?null:b)}var h,m,n,o,p,q,r,s,t,u,v=!1;for(o=[],p=[[]],h=0;c.elements.length>h;h++)if(s=c.elements[h],"&"!==s.value){var w=f(s);if(null!=w){k(o,p);var x,y=[],z=[];for(x=l(y,b,w),v=v||x,n=0;y.length>n;n++){var A=e(d(y[n],s),s);j(p,[A],s,c,z)}p=z,o=[]}else o.push(s)}else{for(v=!0,q=[],k(o,p),m=0;p.length>m;m++)if(r=p[m],0===b.length)r.length>0&&r[0].elements.push(new g(s.combinator,"",s.index,s.currentFileInfo)),q.push(r);else for(n=0;b.length>n;n++){var B=i(r,b[n],s,c);q.push(B)}p=q,o=[]}for(k(o,p),h=0;p.length>h;h++)t=p[h].length,t>0&&(a.push(p[h]),u=p[h][t-1],p[h][t-1]=u.createDerived(u.elements,c.extendList));return v}function m(a,b){var c=b.createDerived(b.elements,b.extendList,b.evaldCondition);return c.copyVisibilityInfo(a),c}var n,o,p;if(o=[],p=l(o,b,c),!p)if(b.length>0)for(o=[],n=0;b.length>n;n++){var q=b[n].map(m.bind(this,c.visibilityInfo()));q.push(c),o.push(q)}else o=[[c]];for(n=0;o.length>n;n++)a.push(o[n])},b.exports=m},{"../contexts":11,"../functions/default":20,"../functions/function-registry":22,"./debug-info":54,"./element":58,"./node":70,"./paren":72,"./rule":74,"./selector":77}],77:[function(a,b,c){var d=a("./node"),e=a("./element"),f=function(a,b,c,d,e,f){this.elements=a,this.extendList=b,this.condition=c,this.currentFileInfo=e||{},c||(this.evaldCondition=!0),this.copyVisibilityInfo(f)};f.prototype=new d,f.prototype.type="Selector",f.prototype.accept=function(a){this.elements&&(this.elements=a.visitArray(this.elements)),this.extendList&&(this.extendList=a.visitArray(this.extendList)),this.condition&&(this.condition=a.visit(this.condition))},f.prototype.createDerived=function(a,b,c){var d=this.visibilityInfo();c=null!=c?c:this.evaldCondition;var e=new f(a,b||this.extendList,null,this.index,this.currentFileInfo,d);return e.evaldCondition=c,e.mediaEmpty=this.mediaEmpty,e},f.prototype.createEmptySelectors=function(){var a=new e("","&",this.index,this.currentFileInfo),b=[new f([a],null,null,this.index,this.currentFileInfo)];return b[0].mediaEmpty=!0,b},f.prototype.match=function(a){var b,c,d=this.elements,e=d.length;if(a.CacheElements(),b=a._elements.length,0===b||b>e)return 0;for(c=0;b>c;c++)if(d[c].value!==a._elements[c])return 0;return b},f.prototype.CacheElements=function(){if(!this._elements){var a=this.elements.map(function(a){return a.combinator.value+(a.value.value||a.value)}).join("").match(/[,\*\.\w-]([\w-]|(\\.))*/g);a?"&"===a[0]&&a.shift():a=[],this._elements=a}},f.prototype.isJustParentSelector=function(){return!this.mediaEmpty&&1===this.elements.length&&"&"===this.elements[0].value&&(" "===this.elements[0].combinator.value||""===this.elements[0].combinator.value)},f.prototype.eval=function(a){var b=this.condition&&this.condition.eval(a),c=this.elements,d=this.extendList;return c=c&&c.map(function(b){return b.eval(a)}),d=d&&d.map(function(b){return b.eval(a)}),this.createDerived(c,d,b)},f.prototype.genCSS=function(a,b){var c,d;if(a&&a.firstSelector||""!==this.elements[0].combinator.value||b.add(" ",this.currentFileInfo,this.index),!this._css)for(c=0;this.elements.length>c;c++)d=this.elements[c],d.genCSS(a,b)},f.prototype.getIsOutput=function(){return this.evaldCondition},b.exports=f},{"./element":58,"./node":70}],78:[function(a,b,c){var d=a("./node"),e=function(a){this.value=a};e.prototype=new d,e.prototype.type="UnicodeDescriptor",b.exports=e},{"./node":70}],79:[function(a,b,c){var d=a("./node"),e=a("../data/unit-conversions"),f=function(a,b,c){this.numerator=a?a.slice(0).sort():[],this.denominator=b?b.slice(0).sort():[],c?this.backupUnit=c:a&&a.length&&(this.backupUnit=a[0])};f.prototype=new d,f.prototype.type="Unit",f.prototype.clone=function(){return new f(this.numerator.slice(0),this.denominator.slice(0),this.backupUnit)},f.prototype.genCSS=function(a,b){var c=a&&a.strictUnits;1===this.numerator.length?b.add(this.numerator[0]):!c&&this.backupUnit?b.add(this.backupUnit):!c&&this.denominator.length&&b.add(this.denominator[0])},f.prototype.toString=function(){var a,b=this.numerator.join("*");for(a=0;this.denominator.length>a;a++)b+="/"+this.denominator[a];return b},f.prototype.compare=function(a){return this.is(a.toString())?0:void 0},f.prototype.is=function(a){return this.toString().toUpperCase()===a.toUpperCase()},f.prototype.isLength=function(){return Boolean(this.toCSS().match(/px|em|%|in|cm|mm|pc|pt|ex/))},f.prototype.isEmpty=function(){return 0===this.numerator.length&&0===this.denominator.length},f.prototype.isSingular=function(){return 1>=this.numerator.length&&0===this.denominator.length},f.prototype.map=function(a){var b;for(b=0;this.numerator.length>b;b++)this.numerator[b]=a(this.numerator[b],!1);for(b=0;this.denominator.length>b;b++)this.denominator[b]=a(this.denominator[b],!0)},f.prototype.usedUnits=function(){var a,b,c,d={};b=function(b){return a.hasOwnProperty(b)&&!d[c]&&(d[c]=b),b};for(c in e)e.hasOwnProperty(c)&&(a=e[c],this.map(b));return d},f.prototype.cancel=function(){var a,b,c={};for(b=0;this.numerator.length>b;b++)a=this.numerator[b],c[a]=(c[a]||0)+1;for(b=0;this.denominator.length>b;b++)a=this.denominator[b],c[a]=(c[a]||0)-1;this.numerator=[],this.denominator=[];for(a in c)if(c.hasOwnProperty(a)){var d=c[a];if(d>0)for(b=0;d>b;b++)this.numerator.push(a);else if(0>d)for(b=0;-d>b;b++)this.denominator.push(a)}this.numerator.sort(),this.denominator.sort()},b.exports=f},{"../data/unit-conversions":14,"./node":70}],80:[function(a,b,c){var d=a("./node"),e=function(a,b,c,d){this.value=a,this.currentFileInfo=c,this.index=b,this.isEvald=d};e.prototype=new d,e.prototype.type="Url",e.prototype.accept=function(a){this.value=a.visit(this.value)},e.prototype.genCSS=function(a,b){b.add("url("),this.value.genCSS(a,b),b.add(")")},e.prototype.eval=function(a){var b,c=this.value.eval(a);if(!this.isEvald&&(b=this.currentFileInfo&&this.currentFileInfo.rootpath,b&&"string"==typeof c.value&&a.isPathRelative(c.value)&&(c.quote||(b=b.replace(/[\(\)'"\s]/g,function(a){return"\\"+a})),c.value=b+c.value),c.value=a.normalizePath(c.value),a.urlArgs&&!c.value.match(/^\s*data:/))){var d=-1===c.value.indexOf("?")?"?":"&",f=d+a.urlArgs;-1!==c.value.indexOf("#")?c.value=c.value.replace("#",f+"#"):c.value+=f}return new e(c,this.index,this.currentFileInfo,!0)},b.exports=e},{"./node":70}],81:[function(a,b,c){var d=a("./node"),e=function(a){if(this.value=a,!a)throw new Error("Value requires an array argument")};e.prototype=new d,e.prototype.type="Value",e.prototype.accept=function(a){this.value&&(this.value=a.visitArray(this.value))},e.prototype.eval=function(a){return 1===this.value.length?this.value[0].eval(a):new e(this.value.map(function(b){return b.eval(a)}))},e.prototype.genCSS=function(a,b){var c;for(c=0;this.value.length>c;c++)this.value[c].genCSS(a,b),this.value.length>c+1&&b.add(a&&a.compress?",":", ")},b.exports=e},{"./node":70}],82:[function(a,b,c){var d=a("./node"),e=function(a,b,c){this.name=a,this.index=b,this.currentFileInfo=c||{}};e.prototype=new d,e.prototype.type="Variable",e.prototype.eval=function(a){var b,c=this.name;if(0===c.indexOf("@@")&&(c="@"+new e(c.slice(1),this.index,this.currentFileInfo).eval(a).value),this.evaluating)throw{type:"Name",message:"Recursive variable definition for "+c,filename:this.currentFileInfo.filename,index:this.index};if(this.evaluating=!0,b=this.find(a.frames,function(b){var d=b.variable(c);if(d){if(d.important){var e=a.importantScope[a.importantScope.length-1];e.important=d.important}return d.value.eval(a)}}))return this.evaluating=!1,b;throw{type:"Name",message:"variable "+c+" is undefined",filename:this.currentFileInfo.filename,index:this.index}},e.prototype.find=function(a,b){for(var c,d=0;a.length>d;d++)if(c=b.call(a,a[d]))return c;return null},b.exports=e},{"./node":70}],83:[function(a,b,c){b.exports={getLocation:function(a,b){for(var c=a+1,d=null,e=-1;--c>=0&&"\n"!==b.charAt(c);)e++;return"number"==typeof a&&(d=(b.slice(0,a).match(/\n/g)||"").length),{line:d,column:e}}}},{}],84:[function(a,b,c){var d=a("../tree"),e=a("./visitor"),f=a("../logger"),g=function(){this._visitor=new e(this),this.contexts=[],this.allExtendsStack=[[]]};g.prototype={run:function(a){return a=this._visitor.visit(a),a.allExtends=this.allExtendsStack[0],a},visitRule:function(a,b){b.visitDeeper=!1},visitMixinDefinition:function(a,b){b.visitDeeper=!1},visitRuleset:function(a,b){if(!a.root){var c,e,f,g,h=[],i=a.rules,j=i?i.length:0;for(c=0;j>c;c++)a.rules[c]instanceof d.Extend&&(h.push(i[c]),a.extendOnEveryPath=!0);var k=a.paths;for(c=0;k.length>c;c++){var l=k[c],m=l[l.length-1],n=m.extendList;for(g=n?n.slice(0).concat(h):h,g&&(g=g.map(function(a){return a.clone()})),e=0;g.length>e;e++)this.foundExtends=!0,f=g[e],f.findSelfSelectors(l),f.ruleset=a,0===e&&(f.firstExtendOnThisSelectorPath=!0),this.allExtendsStack[this.allExtendsStack.length-1].push(f)}this.contexts.push(a.selectors)}},visitRulesetOut:function(a){a.root||(this.contexts.length=this.contexts.length-1)},visitMedia:function(a,b){a.allExtends=[],this.allExtendsStack.push(a.allExtends)},visitMediaOut:function(a){this.allExtendsStack.length=this.allExtendsStack.length-1},visitDirective:function(a,b){a.allExtends=[],this.allExtendsStack.push(a.allExtends)},visitDirectiveOut:function(a){this.allExtendsStack.length=this.allExtendsStack.length-1}};var h=function(){this._visitor=new e(this)};h.prototype={run:function(a){var b=new g;if(this.extendIndices={},b.run(a),!b.foundExtends)return a;a.allExtends=a.allExtends.concat(this.doExtendChaining(a.allExtends,a.allExtends)),this.allExtendsStack=[a.allExtends];var c=this._visitor.visit(a);return this.checkExtendsForNonMatched(a.allExtends),c},checkExtendsForNonMatched:function(a){var b=this.extendIndices;a.filter(function(a){return!a.hasFoundMatches&&1==a.parent_ids.length}).forEach(function(a){var c="_unknown_";try{c=a.selector.toCSS({})}catch(d){}b[a.index+" "+c]||(b[a.index+" "+c]=!0,f.warn("extend '"+c+"' has no matches"))})},doExtendChaining:function(a,b,c){var e,f,g,h,i,j,k,l,m=[],n=this;for(c=c||0,e=0;a.length>e;e++)for(f=0;b.length>f;f++)j=a[e],k=b[f],j.parent_ids.indexOf(k.object_id)>=0||(i=[k.selfSelectors[0]],g=n.findMatch(j,i),g.length&&(j.hasFoundMatches=!0,j.selfSelectors.forEach(function(a){var b=k.visibilityInfo();h=n.extendSelector(g,i,a,j.isVisible()),l=new d.Extend(k.selector,k.option,0,k.currentFileInfo,b),l.selfSelectors=h,h[h.length-1].extendList=[l],m.push(l),l.ruleset=k.ruleset,l.parent_ids=l.parent_ids.concat(k.parent_ids,j.parent_ids),k.firstExtendOnThisSelectorPath&&(l.firstExtendOnThisSelectorPath=!0,k.ruleset.paths.push(h))})));if(m.length){if(this.extendChainCount++,c>100){var o="{unable to calculate}",p="{unable to calculate}";try{o=m[0].selfSelectors[0].toCSS(),p=m[0].selector.toCSS()}catch(q){}throw{message:"extend circular reference detected. One of the circular extends is currently:"+o+":extend("+p+")"}}return m.concat(n.doExtendChaining(m,b,c+1))}return m},visitRule:function(a,b){b.visitDeeper=!1},visitMixinDefinition:function(a,b){b.visitDeeper=!1},visitSelector:function(a,b){b.visitDeeper=!1},visitRuleset:function(a,b){if(!a.root){var c,d,e,f,g=this.allExtendsStack[this.allExtendsStack.length-1],h=[],i=this;for(e=0;g.length>e;e++)for(d=0;a.paths.length>d;d++)if(f=a.paths[d],!a.extendOnEveryPath){var j=f[f.length-1].extendList;j&&j.length||(c=this.findMatch(g[e],f),c.length&&(g[e].hasFoundMatches=!0,g[e].selfSelectors.forEach(function(a){var b;b=i.extendSelector(c,f,a,g[e].isVisible()),h.push(b)})))}a.paths=a.paths.concat(h)}},findMatch:function(a,b){var c,d,e,f,g,h,i,j=this,k=a.selector.elements,l=[],m=[];for(c=0;b.length>c;c++)for(d=b[c],e=0;d.elements.length>e;e++)for(f=d.elements[e],(a.allowBefore||0===c&&0===e)&&l.push({pathIndex:c,index:e,matched:0,initialCombinator:f.combinator}),h=0;l.length>h;h++)i=l[h],g=f.combinator.value,""===g&&0===e&&(g=" "),!j.isElementValuesEqual(k[i.matched].value,f.value)||i.matched>0&&k[i.matched].combinator.value!==g?i=null:i.matched++,i&&(i.finished=i.matched===k.length,i.finished&&!a.allowAfter&&(d.elements.length>e+1||b.length>c+1)&&(i=null)),i?i.finished&&(i.length=k.length,i.endPathIndex=c,i.endPathElementIndex=e+1,l.length=0,m.push(i)):(l.splice(h,1),h--);return m},isElementValuesEqual:function(a,b){if("string"==typeof a||"string"==typeof b)return a===b;if(a instanceof d.Attribute)return a.op!==b.op||a.key!==b.key?!1:a.value&&b.value?(a=a.value.value||a.value,b=b.value.value||b.value,a===b):!a.value&&!b.value;if(a=a.value,b=b.value,a instanceof d.Selector){if(!(b instanceof d.Selector)||a.elements.length!==b.elements.length)return!1;for(var c=0;a.elements.length>c;c++){if(a.elements[c].combinator.value!==b.elements[c].combinator.value&&(0!==c||(a.elements[c].combinator.value||" ")!==(b.elements[c].combinator.value||" ")))return!1;if(!this.isElementValuesEqual(a.elements[c].value,b.elements[c].value))return!1}return!0}return!1},extendSelector:function(a,b,c,e){var f,g,h,i,j,k=0,l=0,m=[];for(f=0;a.length>f;f++)i=a[f],g=b[i.pathIndex],h=new d.Element(i.initialCombinator,c.elements[0].value,c.elements[0].index,c.elements[0].currentFileInfo),i.pathIndex>k&&l>0&&(m[m.length-1].elements=m[m.length-1].elements.concat(b[k].elements.slice(l)),l=0,k++),j=g.elements.slice(l,i.index).concat([h]).concat(c.elements.slice(1)),k===i.pathIndex&&f>0?m[m.length-1].elements=m[m.length-1].elements.concat(j):(m=m.concat(b.slice(k,i.pathIndex)),m.push(new d.Selector(j))),k=i.endPathIndex,l=i.endPathElementIndex,l>=b[k].elements.length&&(l=0,k++);return b.length>k&&l>0&&(m[m.length-1].elements=m[m.length-1].elements.concat(b[k].elements.slice(l)),k++),m=m.concat(b.slice(k,b.length)),m=m.map(function(a){var b=a.createDerived(a.elements);return e?b.ensureVisibility():b.ensureInvisibility(),b})},visitMedia:function(a,b){var c=a.allExtends.concat(this.allExtendsStack[this.allExtendsStack.length-1]);c=c.concat(this.doExtendChaining(c,a.allExtends)),this.allExtendsStack.push(c)},visitMediaOut:function(a){var b=this.allExtendsStack.length-1;this.allExtendsStack.length=b},visitDirective:function(a,b){var c=a.allExtends.concat(this.allExtendsStack[this.allExtendsStack.length-1]);c=c.concat(this.doExtendChaining(c,a.allExtends)),this.allExtendsStack.push(c)},visitDirectiveOut:function(a){var b=this.allExtendsStack.length-1;this.allExtendsStack.length=b}},b.exports=h},{"../logger":33,"../tree":62,"./visitor":91}],85:[function(a,b,c){function d(a){this.imports=[],this.variableImports=[],this._onSequencerEmpty=a,this._currentDepth=0}d.prototype.addImport=function(a){var b=this,c={callback:a,args:null,isReady:!1};return this.imports.push(c),function(){c.args=Array.prototype.slice.call(arguments,0),c.isReady=!0,b.tryRun()}},d.prototype.addVariableImport=function(a){
-this.variableImports.push(a)},d.prototype.tryRun=function(){this._currentDepth++;try{for(;;){for(;this.imports.length>0;){var a=this.imports[0];if(!a.isReady)return;this.imports=this.imports.slice(1),a.callback.apply(null,a.args)}if(0===this.variableImports.length)break;var b=this.variableImports[0];this.variableImports=this.variableImports.slice(1),b()}}finally{this._currentDepth--}0===this._currentDepth&&this._onSequencerEmpty&&this._onSequencerEmpty()},b.exports=d},{}],86:[function(a,b,c){var d=a("../contexts"),e=a("./visitor"),f=a("./import-sequencer"),g=function(a,b){this._visitor=new e(this),this._importer=a,this._finish=b,this.context=new d.Eval,this.importCount=0,this.onceFileDetectionMap={},this.recursionDetector={},this._sequencer=new f(this._onSequencerEmpty.bind(this))};g.prototype={isReplacing:!1,run:function(a){try{this._visitor.visit(a)}catch(b){this.error=b}this.isFinished=!0,this._sequencer.tryRun()},_onSequencerEmpty:function(){this.isFinished&&this._finish(this.error)},visitImport:function(a,b){var c=a.options.inline;if(!a.css||c){var e=new d.Eval(this.context,this.context.frames.slice(0)),f=e.frames[0];this.importCount++,a.isVariableImport()?this._sequencer.addVariableImport(this.processImportNode.bind(this,a,e,f)):this.processImportNode(a,e,f)}b.visitDeeper=!1},processImportNode:function(a,b,c){var d,e=a.options.inline;try{d=a.evalForImport(b)}catch(f){f.filename||(f.index=a.index,f.filename=a.currentFileInfo.filename),a.css=!0,a.error=f}if(!d||d.css&&!e)this.importCount--,this.isFinished&&this._sequencer.tryRun();else{d.options.multiple&&(b.importMultiple=!0);for(var g=void 0===d.css,h=0;c.rules.length>h;h++)if(c.rules[h]===a){c.rules[h]=d;break}var i=this.onImported.bind(this,d,b),j=this._sequencer.addImport(i);this._importer.push(d.getPath(),g,d.currentFileInfo,d.options,j)}},onImported:function(a,b,c,d,e,f){c&&(c.filename||(c.index=a.index,c.filename=a.currentFileInfo.filename),this.error=c);var g=this,h=a.options.inline,i=a.options.plugin,j=a.options.optional,k=e||f in g.recursionDetector;if(b.importMultiple||(a.skip=k?!0:function(){return f in g.onceFileDetectionMap?!0:(g.onceFileDetectionMap[f]=!0,!1)}),!f&&j&&(a.skip=!0),d&&(a.root=d,a.importedFilename=f,!h&&!i&&(b.importMultiple||!k))){g.recursionDetector[f]=!0;var l=this.context;this.context=b;try{this._visitor.visit(d)}catch(c){this.error=c}this.context=l}g.importCount--,g.isFinished&&g._sequencer.tryRun()},visitRule:function(a,b){"DetachedRuleset"===a.value.type?this.context.frames.unshift(a):b.visitDeeper=!1},visitRuleOut:function(a){"DetachedRuleset"===a.value.type&&this.context.frames.shift()},visitDirective:function(a,b){this.context.frames.unshift(a)},visitDirectiveOut:function(a){this.context.frames.shift()},visitMixinDefinition:function(a,b){this.context.frames.unshift(a)},visitMixinDefinitionOut:function(a){this.context.frames.shift()},visitRuleset:function(a,b){this.context.frames.unshift(a)},visitRulesetOut:function(a){this.context.frames.shift()},visitMedia:function(a,b){this.context.frames.unshift(a.rules[0])},visitMediaOut:function(a){this.context.frames.shift()}},b.exports=g},{"../contexts":11,"./import-sequencer":85,"./visitor":91}],87:[function(a,b,c){var d={Visitor:a("./visitor"),ImportVisitor:a("./import-visitor"),MarkVisibleSelectorsVisitor:a("./set-tree-visibility-visitor"),ExtendVisitor:a("./extend-visitor"),JoinSelectorVisitor:a("./join-selector-visitor"),ToCSSVisitor:a("./to-css-visitor")};b.exports=d},{"./extend-visitor":84,"./import-visitor":86,"./join-selector-visitor":88,"./set-tree-visibility-visitor":89,"./to-css-visitor":90,"./visitor":91}],88:[function(a,b,c){var d=a("./visitor"),e=function(){this.contexts=[[]],this._visitor=new d(this)};e.prototype={run:function(a){return this._visitor.visit(a)},visitRule:function(a,b){b.visitDeeper=!1},visitMixinDefinition:function(a,b){b.visitDeeper=!1},visitRuleset:function(a,b){var c,d=this.contexts[this.contexts.length-1],e=[];this.contexts.push(e),a.root||(c=a.selectors,c&&(c=c.filter(function(a){return a.getIsOutput()}),a.selectors=c.length?c:c=null,c&&a.joinSelectors(e,d,c)),c||(a.rules=null),a.paths=e)},visitRulesetOut:function(a){this.contexts.length=this.contexts.length-1},visitMedia:function(a,b){var c=this.contexts[this.contexts.length-1];a.rules[0].root=0===c.length||c[0].multiMedia},visitDirective:function(a,b){var c=this.contexts[this.contexts.length-1];a.rules&&a.rules.length&&(a.rules[0].root=a.isRooted||0===c.length||null)}},b.exports=e},{"./visitor":91}],89:[function(a,b,c){var d=function(a){this.visible=a};d.prototype.run=function(a){this.visit(a)},d.prototype.visitArray=function(a){if(!a)return a;var b,c=a.length;for(b=0;c>b;b++)this.visit(a[b]);return a},d.prototype.visit=function(a){return a?a.constructor===Array?this.visitArray(a):!a.blocksVisibility||a.blocksVisibility()?a:(this.visible?a.ensureVisibility():a.ensureInvisibility(),a.accept(this),a):a},b.exports=d},{}],90:[function(a,b,c){var d=a("../tree"),e=a("./visitor"),f=function(a){this._visitor=new e(this),this._context=a};f.prototype={containsSilentNonBlockedChild:function(a){var b;if(null==a)return!1;for(var c=0;a.length>c;c++)if(b=a[c],b.isSilent&&b.isSilent(this._context)&&!b.blocksVisibility())return!0;return!1},keepOnlyVisibleChilds:function(a){null!=a&&null!=a.rules&&(a.rules=a.rules.filter(function(a){return a.isVisible()}))},isEmpty:function(a){return null==a||null==a.rules?!0:0===a.rules.length},hasVisibleSelector:function(a){return null==a||null==a.paths?!1:a.paths.length>0},resolveVisibility:function(a,b){if(!a.blocksVisibility()){if(this.isEmpty(a)&&!this.containsSilentNonBlockedChild(b))return;return a}var c=a.rules[0];return this.keepOnlyVisibleChilds(c),this.isEmpty(c)?void 0:(a.ensureVisibility(),a.removeVisibilityBlock(),a)},isVisibleRuleset:function(a){return a.firstRoot?!0:this.isEmpty(a)?!1:!(!a.root&&!this.hasVisibleSelector(a))}};var g=function(a){this._visitor=new e(this),this._context=a,this.utils=new f(a)};g.prototype={isReplacing:!0,run:function(a){return this._visitor.visit(a)},visitRule:function(a,b){return a.blocksVisibility()||a.variable?void 0:a},visitMixinDefinition:function(a,b){a.frames=[]},visitExtend:function(a,b){},visitComment:function(a,b){return a.blocksVisibility()||a.isSilent(this._context)?void 0:a},visitMedia:function(a,b){var c=a.rules[0].rules;return a.accept(this._visitor),b.visitDeeper=!1,this.utils.resolveVisibility(a,c)},visitImport:function(a,b){return a.blocksVisibility()?void 0:a},visitDirective:function(a,b){return a.rules&&a.rules.length?this.visitDirectiveWithBody(a,b):this.visitDirectiveWithoutBody(a,b)},visitDirectiveWithBody:function(a,b){function c(a){var b=a.rules;return 1===b.length&&(!b[0].paths||0===b[0].paths.length)}function d(a){var b=a.rules;return c(a)?b[0].rules:b}var e=d(a);return a.accept(this._visitor),b.visitDeeper=!1,this.utils.isEmpty(a)||this._mergeRules(a.rules[0].rules),this.utils.resolveVisibility(a,e)},visitDirectiveWithoutBody:function(a,b){if(!a.blocksVisibility()){if("@charset"===a.name){if(this.charset){if(a.debugInfo){var c=new d.Comment("/* "+a.toCSS(this._context).replace(/\n/g,"")+" */\n");return c.debugInfo=a.debugInfo,this._visitor.visit(c)}return}this.charset=!0}return a}},checkValidNodes:function(a,b){if(a)for(var c=0;a.length>c;c++){var e=a[c];if(b&&e instanceof d.Rule&&!e.variable)throw{message:"Properties must be inside selector blocks. They cannot be in the root",index:e.index,filename:e.currentFileInfo&&e.currentFileInfo.filename};if(e instanceof d.Call)throw{message:"Function '"+e.name+"' is undefined",index:e.index,filename:e.currentFileInfo&&e.currentFileInfo.filename};if(e.type&&!e.allowRoot)throw{message:e.type+" node returned by a function is not valid here",index:e.index,filename:e.currentFileInfo&&e.currentFileInfo.filename}}},visitRuleset:function(a,b){var c,d=[];if(this.checkValidNodes(a.rules,a.firstRoot),a.root)a.accept(this._visitor),b.visitDeeper=!1;else{this._compileRulesetPaths(a);for(var e=a.rules,f=e?e.length:0,g=0;f>g;)c=e[g],c&&c.rules?(d.push(this._visitor.visit(c)),e.splice(g,1),f--):g++;f>0?a.accept(this._visitor):a.rules=null,b.visitDeeper=!1}return a.rules&&(this._mergeRules(a.rules),this._removeDuplicateRules(a.rules)),this.utils.isVisibleRuleset(a)&&(a.ensureVisibility(),d.splice(0,0,a)),1===d.length?d[0]:d},_compileRulesetPaths:function(a){a.paths&&(a.paths=a.paths.filter(function(a){var b;for(" "===a[0].elements[0].combinator.value&&(a[0].elements[0].combinator=new d.Combinator("")),b=0;a.length>b;b++)if(a[b].isVisible()&&a[b].getIsOutput())return!0;return!1}))},_removeDuplicateRules:function(a){if(a){var b,c,e,f={};for(e=a.length-1;e>=0;e--)if(c=a[e],c instanceof d.Rule)if(f[c.name]){b=f[c.name],b instanceof d.Rule&&(b=f[c.name]=[f[c.name].toCSS(this._context)]);var g=c.toCSS(this._context);-1!==b.indexOf(g)?a.splice(e,1):b.push(g)}else f[c.name]=c}},_mergeRules:function(a){if(a){for(var b,c,e,f={},g=0;a.length>g;g++)c=a[g],c instanceof d.Rule&&c.merge&&(e=[c.name,c.important?"!":""].join(","),f[e]?a.splice(g--,1):f[e]=[],f[e].push(c));Object.keys(f).map(function(a){function e(a){return new d.Expression(a.map(function(a){return a.value}))}function g(a){return new d.Value(a.map(function(a){return a}))}if(b=f[a],b.length>1){c=b[0];var h=[],i=[];b.map(function(a){"+"===a.merge&&(i.length>0&&h.push(e(i)),i=[]),i.push(a)}),h.push(e(i)),c.value=g(h)}})}},visitAnonymous:function(a,b){return a.blocksVisibility()?void 0:(a.accept(this._visitor),a)}},b.exports=g},{"../tree":62,"./visitor":91}],91:[function(a,b,c){function d(a){return a}function e(a,b){var c,d;for(c in a)if(a.hasOwnProperty(c))switch(d=a[c],typeof d){case"function":d.prototype&&d.prototype.type&&(d.prototype.typeIndex=b++);break;case"object":b=e(d,b)}return b}var f=a("../tree"),g={visitDeeper:!0},h=!1,i=function(a){this._implementation=a,this._visitFnCache=[],h||(e(f,1),h=!0)};i.prototype={visit:function(a){if(!a)return a;var b=a.typeIndex;if(!b)return a;var c,e=this._visitFnCache,f=this._implementation,h=b<<1,i=1|h,j=e[h],k=e[i],l=g;if(l.visitDeeper=!0,j||(c="visit"+a.type,j=f[c]||d,k=f[c+"Out"]||d,e[h]=j,e[i]=k),j!==d){var m=j.call(f,a,l);f.isReplacing&&(a=m)}return l.visitDeeper&&a&&a.accept&&a.accept(this),k!=d&&k.call(f,a),a},visitArray:function(a,b){if(!a)return a;var c,d=a.length;if(b||!this._implementation.isReplacing){for(c=0;d>c;c++)this.visit(a[c]);return a}var e=[];for(c=0;d>c;c++){var f=this.visit(a[c]);void 0!==f&&(f.splice?f.length&&this.flatten(f,e):e.push(f))}return e},flatten:function(a,b){b||(b=[]);var c,d,e,f,g,h;for(d=0,c=a.length;c>d;d++)if(e=a[d],void 0!==e)if(e.splice)for(g=0,f=e.length;f>g;g++)h=e[g],void 0!==h&&(h.splice?h.length&&this.flatten(h,b):b.push(h));else b.push(e);return b}},b.exports=i},{"../tree":62}],92:[function(a,b,c){"use strict";function d(){if(i.length)throw i.shift()}function e(a){var b;b=h.length?h.pop():new f,b.task=a,g(b)}function f(){this.task=null}var g=a("./raw"),h=[],i=[],j=g.makeRequestCallFromTimer(d);b.exports=e,f.prototype.call=function(){try{this.task.call()}catch(a){e.onerror?e.onerror(a):(i.push(a),j())}finally{this.task=null,h[h.length]=this}}},{"./raw":93}],93:[function(a,b,c){(function(a){"use strict";function c(a){h.length||(g(),i=!0),h[h.length]=a}function d(){for(;h.length>j;){var a=j;if(j+=1,h[a].call(),j>k){for(var b=0,c=h.length-j;c>b;b++)h[b]=h[b+j];h.length-=j,j=0}}h.length=0,j=0,i=!1}function e(a){var b=1,c=new l(a),d=document.createTextNode("");return c.observe(d,{characterData:!0}),function(){b=-b,d.data=b}}function f(a){return function(){function b(){clearTimeout(c),clearInterval(d),a()}var c=setTimeout(b,0),d=setInterval(b,50)}}b.exports=c;var g,h=[],i=!1,j=0,k=1024,l=a.MutationObserver||a.WebKitMutationObserver;g="function"==typeof l?e(d):f(d),c.requestFlush=g,c.makeRequestCallFromTimer=f}).call(this,"undefined"!=typeof global?global:"undefined"!=typeof self?self:"undefined"!=typeof window?window:{})},{}],94:[function(a,b,c){"use strict";function d(){}function e(a){try{return a.then}catch(b){return r=b,s}}function f(a,b){try{return a(b)}catch(c){return r=c,s}}function g(a,b,c){try{a(b,c)}catch(d){return r=d,s}}function h(a){if("object"!=typeof this)throw new TypeError("Promises must be constructed via new");if("function"!=typeof a)throw new TypeError("not a function");this._45=0,this._81=0,this._65=null,this._54=null,a!==d&&p(a,this)}function i(a,b,c){return new a.constructor(function(e,f){var g=new h(d);g.then(e,f),j(a,new o(b,c,g))})}function j(a,b){for(;3===a._81;)a=a._65;return h._10&&h._10(a),0===a._81?0===a._45?(a._45=1,void(a._54=b)):1===a._45?(a._45=2,void(a._54=[a._54,b])):void a._54.push(b):void k(a,b)}function k(a,b){q(function(){var c=1===a._81?b.onFulfilled:b.onRejected;if(null===c)return void(1===a._81?l(b.promise,a._65):m(b.promise,a._65));var d=f(c,a._65);d===s?m(b.promise,r):l(b.promise,d)})}function l(a,b){if(b===a)return m(a,new TypeError("A promise cannot be resolved with itself."));if(b&&("object"==typeof b||"function"==typeof b)){var c=e(b);if(c===s)return m(a,r);if(c===a.then&&b instanceof h)return a._81=3,a._65=b,void n(a);if("function"==typeof c)return void p(c.bind(b),a)}a._81=1,a._65=b,n(a)}function m(a,b){a._81=2,a._65=b,h._97&&h._97(a,b),n(a)}function n(a){if(1===a._45&&(j(a,a._54),a._54=null),2===a._45){for(var b=0;a._54.length>b;b++)j(a,a._54[b]);a._54=null}}function o(a,b,c){this.onFulfilled="function"==typeof a?a:null,this.onRejected="function"==typeof b?b:null,this.promise=c}function p(a,b){var c=!1,d=g(a,function(a){c||(c=!0,l(b,a))},function(a){c||(c=!0,m(b,a))});c||d!==s||(c=!0,m(b,r))}var q=a("asap/raw"),r=null,s={};b.exports=h,h._10=null,h._97=null,h._61=d,h.prototype.then=function(a,b){if(this.constructor!==h)return i(this,a,b);var c=new h(d);return j(this,new o(a,b,c)),c}},{"asap/raw":93}],95:[function(a,b,c){"use strict";function d(a){var b=new e(e._61);return b._81=1,b._65=a,b}var e=a("./core.js");b.exports=e;var f=d(!0),g=d(!1),h=d(null),i=d(void 0),j=d(0),k=d("");e.resolve=function(a){if(a instanceof e)return a;if(null===a)return h;if(void 0===a)return i;if(a===!0)return f;if(a===!1)return g;if(0===a)return j;if(""===a)return k;if("object"==typeof a||"function"==typeof a)try{var b=a.then;if("function"==typeof b)return new e(b.bind(a))}catch(c){return new e(function(a,b){b(c)})}return d(a)},e.all=function(a){var b=Array.prototype.slice.call(a);return new e(function(a,c){function d(g,h){if(h&&("object"==typeof h||"function"==typeof h)){if(h instanceof e&&h.then===e.prototype.then){for(;3===h._81;)h=h._65;return 1===h._81?d(g,h._65):(2===h._81&&c(h._65),void h.then(function(a){d(g,a)},c))}var i=h.then;if("function"==typeof i){var j=new e(i.bind(h));return void j.then(function(a){d(g,a)},c)}}b[g]=h,0===--f&&a(b)}if(0===b.length)return a([]);for(var f=b.length,g=0;b.length>g;g++)d(g,b[g])})},e.reject=function(a){return new e(function(b,c){c(a)})},e.race=function(a){return new e(function(b,c){a.forEach(function(a){e.resolve(a).then(b,c)})})},e.prototype["catch"]=function(a){return this.then(null,a)}},{"./core.js":94}],96:[function(a,b,c){"function"!=typeof Promise.prototype.done&&(Promise.prototype.done=function(a,b){var c=arguments.length?this.then.apply(this,arguments):this;c.then(null,function(a){setTimeout(function(){throw a},0)})})},{}],97:[function(a,b,c){a("asap");"undefined"==typeof Promise&&(Promise=a("./lib/core.js"),a("./lib/es6-extensions.js")),a("./polyfill-done.js")},{"./lib/core.js":94,"./lib/es6-extensions.js":95,"./polyfill-done.js":96,asap:92}]},{},[2])(2)});
\ No newline at end of file
diff --git a/vendor/less/dist/less.cjs.js b/vendor/less/dist/less.cjs.js
deleted file mode 100644
index b08dee514..000000000
--- a/vendor/less/dist/less.cjs.js
+++ /dev/null
@@ -1,13716 +0,0 @@
-'use strict';
-
-var path = require('path');
-var url = require('url');
-var CloneHelper = require('clone');
-
-var environment = {
- encodeBase64: function encodeBase64(str) {
- // Avoid Buffer constructor on newer versions of Node.js.
- var buffer = Buffer.from ? Buffer.from(str) : new Buffer(str);
- return buffer.toString('base64');
- },
- mimeLookup: function mimeLookup(filename) {
- return require('mime').lookup(filename);
- },
- charsetLookup: function charsetLookup(mime) {
- return require('mime').charsets.lookup(mime);
- },
- getSourceMapGenerator: function getSourceMapGenerator() {
- return require('source-map').SourceMapGenerator;
- }
-};
-
-function _classCallCheck(instance, Constructor) {
- if (!(instance instanceof Constructor)) {
- throw new TypeError("Cannot call a class as a function");
- }
-}
-
-function _defineProperties(target, props) {
- for (var i = 0; i < props.length; i++) {
- var descriptor = props[i];
- descriptor.enumerable = descriptor.enumerable || false;
- descriptor.configurable = true;
- if ("value" in descriptor) descriptor.writable = true;
- Object.defineProperty(target, descriptor.key, descriptor);
- }
-}
-
-function _createClass(Constructor, protoProps, staticProps) {
- if (protoProps) _defineProperties(Constructor.prototype, protoProps);
- if (staticProps) _defineProperties(Constructor, staticProps);
- return Constructor;
-}
-
-function _inherits(subClass, superClass) {
- if (typeof superClass !== "function" && superClass !== null) {
- throw new TypeError("Super expression must either be null or a function");
- }
-
- subClass.prototype = Object.create(superClass && superClass.prototype, {
- constructor: {
- value: subClass,
- writable: true,
- configurable: true
- }
- });
- if (superClass) _setPrototypeOf(subClass, superClass);
-}
-
-function _getPrototypeOf(o) {
- _getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf : function _getPrototypeOf(o) {
- return o.__proto__ || Object.getPrototypeOf(o);
- };
- return _getPrototypeOf(o);
-}
-
-function _setPrototypeOf(o, p) {
- _setPrototypeOf = Object.setPrototypeOf || function _setPrototypeOf(o, p) {
- o.__proto__ = p;
- return o;
- };
-
- return _setPrototypeOf(o, p);
-}
-
-function isNativeReflectConstruct() {
- if (typeof Reflect === "undefined" || !Reflect.construct) return false;
- if (Reflect.construct.sham) return false;
- if (typeof Proxy === "function") return true;
-
- try {
- Date.prototype.toString.call(Reflect.construct(Date, [], function () {}));
- return true;
- } catch (e) {
- return false;
- }
-}
-
-function _construct(Parent, args, Class) {
- if (isNativeReflectConstruct()) {
- _construct = Reflect.construct;
- } else {
- _construct = function _construct(Parent, args, Class) {
- var a = [null];
- a.push.apply(a, args);
- var Constructor = Function.bind.apply(Parent, a);
- var instance = new Constructor();
- if (Class) _setPrototypeOf(instance, Class.prototype);
- return instance;
- };
- }
-
- return _construct.apply(null, arguments);
-}
-
-function _assertThisInitialized(self) {
- if (self === void 0) {
- throw new ReferenceError("this hasn't been initialised - super() hasn't been called");
- }
-
- return self;
-}
-
-function _possibleConstructorReturn(self, call) {
- if (call && (typeof call === "object" || typeof call === "function")) {
- return call;
- }
-
- return _assertThisInitialized(self);
-}
-
-function _toConsumableArray(arr) {
- return _arrayWithoutHoles(arr) || _iterableToArray(arr) || _nonIterableSpread();
-}
-
-function _arrayWithoutHoles(arr) {
- if (Array.isArray(arr)) {
- for (var i = 0, arr2 = new Array(arr.length); i < arr.length; i++) arr2[i] = arr[i];
-
- return arr2;
- }
-}
-
-function _iterableToArray(iter) {
- if (Symbol.iterator in Object(iter) || Object.prototype.toString.call(iter) === "[object Arguments]") return Array.from(iter);
-}
-
-function _nonIterableSpread() {
- throw new TypeError("Invalid attempt to spread non-iterable instance");
-}
-
-var fs;
-
-try {
- fs = require('graceful-fs');
-} catch (e) {
- fs = require('fs');
-}
-
-var fs$1 = fs;
-
-var AbstractFileManager =
-/*#__PURE__*/
-function () {
- function AbstractFileManager() {
- _classCallCheck(this, AbstractFileManager);
- }
-
- _createClass(AbstractFileManager, [{
- key: "getPath",
- value: function getPath(filename) {
- var j = filename.lastIndexOf('?');
-
- if (j > 0) {
- filename = filename.slice(0, j);
- }
-
- j = filename.lastIndexOf('/');
-
- if (j < 0) {
- j = filename.lastIndexOf('\\');
- }
-
- if (j < 0) {
- return '';
- }
-
- return filename.slice(0, j + 1);
- }
- }, {
- key: "tryAppendExtension",
- value: function tryAppendExtension(path, ext) {
- return /(\.[a-z]*$)|([\?;].*)$/.test(path) ? path : path + ext;
- }
- }, {
- key: "tryAppendLessExtension",
- value: function tryAppendLessExtension(path) {
- return this.tryAppendExtension(path, '.less');
- }
- }, {
- key: "supportsSync",
- value: function supportsSync() {
- return false;
- }
- }, {
- key: "alwaysMakePathsAbsolute",
- value: function alwaysMakePathsAbsolute() {
- return false;
- }
- }, {
- key: "isPathAbsolute",
- value: function isPathAbsolute(filename) {
- return /^(?:[a-z-]+:|\/|\\|#)/i.test(filename);
- } // TODO: pull out / replace?
-
- }, {
- key: "join",
- value: function join(basePath, laterPath) {
- if (!basePath) {
- return laterPath;
- }
-
- return basePath + laterPath;
- }
- }, {
- key: "pathDiff",
- value: function pathDiff(url, baseUrl) {
- // diff between two paths to create a relative path
- var urlParts = this.extractUrlParts(url);
- var baseUrlParts = this.extractUrlParts(baseUrl);
- var i;
- var max;
- var urlDirectories;
- var baseUrlDirectories;
- var diff = '';
-
- if (urlParts.hostPart !== baseUrlParts.hostPart) {
- return '';
- }
-
- max = Math.max(baseUrlParts.directories.length, urlParts.directories.length);
-
- for (i = 0; i < max; i++) {
- if (baseUrlParts.directories[i] !== urlParts.directories[i]) {
- break;
- }
- }
-
- baseUrlDirectories = baseUrlParts.directories.slice(i);
- urlDirectories = urlParts.directories.slice(i);
-
- for (i = 0; i < baseUrlDirectories.length - 1; i++) {
- diff += '../';
- }
-
- for (i = 0; i < urlDirectories.length - 1; i++) {
- diff += `${urlDirectories[i]}/`;
- }
-
- return diff;
- }
- }, {
- key: "extractUrlParts",
- // helper function, not part of API
- value: function extractUrlParts(url, baseUrl) {
- // urlParts[1] = protocol://hostname/ OR /
- // urlParts[2] = / if path relative to host base
- // urlParts[3] = directories
- // urlParts[4] = filename
- // urlParts[5] = parameters
- var urlPartsRegex = /^((?:[a-z-]+:)?\/{2}(?:[^\/\?#]*\/)|([\/\\]))?((?:[^\/\\\?#]*[\/\\])*)([^\/\\\?#]*)([#\?].*)?$/i;
- var urlParts = url.match(urlPartsRegex);
- var returner = {};
- var rawDirectories = [];
- var directories = [];
- var i;
- var baseUrlParts;
-
- if (!urlParts) {
- throw new Error(`Could not parse sheet href - '${url}'`);
- } // Stylesheets in IE don't always return the full path
-
-
- if (baseUrl && (!urlParts[1] || urlParts[2])) {
- baseUrlParts = baseUrl.match(urlPartsRegex);
-
- if (!baseUrlParts) {
- throw new Error(`Could not parse page url - '${baseUrl}'`);
- }
-
- urlParts[1] = urlParts[1] || baseUrlParts[1] || '';
-
- if (!urlParts[2]) {
- urlParts[3] = baseUrlParts[3] + urlParts[3];
- }
- }
-
- if (urlParts[3]) {
- rawDirectories = urlParts[3].replace(/\\/g, '/').split('/'); // collapse '..' and skip '.'
-
- for (i = 0; i < rawDirectories.length; i++) {
- if (rawDirectories[i] === '..') {
- directories.pop();
- } else if (rawDirectories[i] !== '.') {
- directories.push(rawDirectories[i]);
- }
- }
- }
-
- returner.hostPart = urlParts[1];
- returner.directories = directories;
- returner.rawPath = (urlParts[1] || '') + rawDirectories.join('/');
- returner.path = (urlParts[1] || '') + directories.join('/');
- returner.filename = urlParts[4];
- returner.fileUrl = returner.path + (urlParts[4] || '');
- returner.url = returner.fileUrl + (urlParts[5] || '');
- return returner;
- }
- }]);
-
- return AbstractFileManager;
-}();
-
-var FileManager =
-/*#__PURE__*/
-function (_AbstractFileManager) {
- _inherits(FileManager, _AbstractFileManager);
-
- function FileManager() {
- var _this;
-
- _classCallCheck(this, FileManager);
-
- _this = _possibleConstructorReturn(this, _getPrototypeOf(FileManager).call(this));
- _this.contents = {};
- return _this;
- }
-
- _createClass(FileManager, [{
- key: "supports",
- value: function supports(filename, currentDirectory, options, environment) {
- return true;
- }
- }, {
- key: "supportsSync",
- value: function supportsSync(filename, currentDirectory, options, environment) {
- return true;
- }
- }, {
- key: "loadFile",
- value: function loadFile(filename, currentDirectory, options, environment, callback) {
- var fullFilename;
- var isAbsoluteFilename = this.isPathAbsolute(filename);
- var filenamesTried = [];
- var self = this;
- var prefix = filename.slice(0, 1);
- var explicit = prefix === '.' || prefix === '/';
- var result = null;
- var isNodeModule = false;
- var npmPrefix = 'npm://';
- options = options || {};
- var paths = isAbsoluteFilename ? [''] : [currentDirectory];
-
- if (options.paths) {
- paths.push.apply(paths, _toConsumableArray(options.paths));
- }
-
- if (!isAbsoluteFilename && paths.indexOf('.') === -1) {
- paths.push('.');
- }
-
- var prefixes = options.prefixes || [''];
- var fileParts = this.extractUrlParts(filename);
-
- if (options.syncImport) {
- getFileData(returnData, returnData);
-
- if (callback) {
- callback(result.error, result);
- } else {
- return result;
- }
- } else {
- // promise is guaranteed to be asyncronous
- // which helps as it allows the file handle
- // to be closed before it continues with the next file
- return new Promise(getFileData);
- }
-
- function returnData(data) {
- if (!data.filename) {
- result = {
- error: data
- };
- } else {
- result = data;
- }
- }
-
- function getFileData(fulfill, reject) {
- (function tryPathIndex(i) {
- if (i < paths.length) {
- (function tryPrefix(j) {
- if (j < prefixes.length) {
- isNodeModule = false;
- fullFilename = fileParts.rawPath + prefixes[j] + fileParts.filename;
-
- if (paths[i]) {
- fullFilename = path.join(paths[i], fullFilename);
- }
-
- if (!explicit && paths[i] === '.') {
- try {
- fullFilename = require.resolve(fullFilename);
- isNodeModule = true;
- } catch (e) {
- filenamesTried.push(npmPrefix + fullFilename);
- tryWithExtension();
- }
- } else {
- tryWithExtension();
- }
-
- function tryWithExtension() {
- var extFilename = options.ext ? self.tryAppendExtension(fullFilename, options.ext) : fullFilename;
-
- if (extFilename !== fullFilename && !explicit && paths[i] === '.') {
- try {
- fullFilename = require.resolve(extFilename);
- isNodeModule = true;
- } catch (e) {
- filenamesTried.push(npmPrefix + extFilename);
- fullFilename = extFilename;
- }
- } else {
- fullFilename = extFilename;
- }
- }
-
- var modified = false;
-
- if (self.contents[fullFilename]) {
- try {
- var stat = fs$1.statSync.apply(this, [fullFilename]);
-
- if (stat.mtime.getTime() === self.contents[fullFilename].mtime.getTime()) {
- fulfill({
- contents: self.contents[fullFilename].data,
- filename: fullFilename
- });
- } else {
- modified = true;
- }
- } catch (e) {
- modified = true;
- }
- }
-
- if (modified || !self.contents[fullFilename]) {
- var readFileArgs = [fullFilename];
-
- if (!options.rawBuffer) {
- readFileArgs.push('utf-8');
- }
-
- if (options.syncImport) {
- try {
- var data = fs$1.readFileSync.apply(this, readFileArgs);
- var stat = fs$1.statSync.apply(this, [fullFilename]);
- self.contents[fullFilename] = {
- data,
- mtime: stat.mtime
- };
- fulfill({
- contents: data,
- filename: fullFilename
- });
- } catch (e) {
- filenamesTried.push(isNodeModule ? npmPrefix + fullFilename : fullFilename);
- return tryPrefix(j + 1);
- }
- } else {
- readFileArgs.push(function (e, data) {
- if (e) {
- filenamesTried.push(isNodeModule ? npmPrefix + fullFilename : fullFilename);
- return tryPrefix(j + 1);
- }
-
- var stat = fs$1.statSync.apply(this, [fullFilename]);
- self.contents[fullFilename] = {
- data,
- mtime: stat.mtime
- };
- fulfill({
- contents: data,
- filename: fullFilename
- });
- });
- fs$1.readFile.apply(this, readFileArgs);
- }
- }
- } else {
- tryPathIndex(i + 1);
- }
- })(0);
- } else {
- reject({
- type: 'File',
- message: `'${filename}' wasn't found. Tried - ${filenamesTried.join(',')}`
- });
- }
- })(0);
- }
- }
- }, {
- key: "loadFileSync",
- value: function loadFileSync(filename, currentDirectory, options, environment) {
- options.syncImport = true;
- return this.loadFile(filename, currentDirectory, options, environment);
- }
- }]);
-
- return FileManager;
-}(AbstractFileManager);
-
-var logger = {
- error: function error(msg) {
- this._fireEvent('error', msg);
- },
- warn: function warn(msg) {
- this._fireEvent('warn', msg);
- },
- info: function info(msg) {
- this._fireEvent('info', msg);
- },
- debug: function debug(msg) {
- this._fireEvent('debug', msg);
- },
- addListener: function addListener(listener) {
- this._listeners.push(listener);
- },
- removeListener: function removeListener(listener) {
- for (var i = 0; i < this._listeners.length; i++) {
- if (this._listeners[i] === listener) {
- this._listeners.splice(i, 1);
-
- return;
- }
- }
- },
- _fireEvent: function _fireEvent(type, msg) {
- for (var i = 0; i < this._listeners.length; i++) {
- var logFunction = this._listeners[i][type];
-
- if (logFunction) {
- logFunction(msg);
- }
- }
- },
- _listeners: []
-};
-
-var isUrlRe = /^(?:https?:)?\/\//i;
-var request;
-
-var UrlFileManager =
-/*#__PURE__*/
-function (_AbstractFileManager) {
- _inherits(UrlFileManager, _AbstractFileManager);
-
- function UrlFileManager() {
- _classCallCheck(this, UrlFileManager);
-
- return _possibleConstructorReturn(this, _getPrototypeOf(UrlFileManager).apply(this, arguments));
- }
-
- _createClass(UrlFileManager, [{
- key: "supports",
- value: function supports(filename, currentDirectory, options, environment) {
- return isUrlRe.test(filename) || isUrlRe.test(currentDirectory);
- }
- }, {
- key: "loadFile",
- value: function loadFile(filename, currentDirectory, options, environment) {
- return new Promise(function (fulfill, reject) {
- if (request === undefined) {
- try {
- request = require('request');
- } catch (e) {
- request = null;
- }
- }
-
- if (!request) {
- reject({
- type: 'File',
- message: 'optional dependency \'request\' required to import over http(s)\n'
- });
- return;
- }
-
- var urlStr = isUrlRe.test(filename) ? filename : url.resolve(currentDirectory, filename);
- var urlObj = url.parse(urlStr);
-
- if (!urlObj.protocol) {
- urlObj.protocol = 'http';
- urlStr = urlObj.format();
- }
-
- request.get({
- uri: urlStr,
- strictSSL: !options.insecure
- }, function (error, res, body) {
- if (error) {
- reject({
- type: 'File',
- message: `resource '${urlStr}' gave this Error:\n ${error}\n`
- });
- return;
- }
-
- if (res && res.statusCode === 404) {
- reject({
- type: 'File',
- message: `resource '${urlStr}' was not found\n`
- });
- return;
- }
-
- if (!body) {
- logger.warn(`Warning: Empty body (HTTP ${res.statusCode}) returned by "${urlStr}"`);
- }
-
- fulfill({
- contents: body,
- filename: urlStr
- });
- });
- });
- }
- }]);
-
- return UrlFileManager;
-}(AbstractFileManager);
-
-var colors = {
- 'aliceblue': '#f0f8ff',
- 'antiquewhite': '#faebd7',
- 'aqua': '#00ffff',
- 'aquamarine': '#7fffd4',
- 'azure': '#f0ffff',
- 'beige': '#f5f5dc',
- 'bisque': '#ffe4c4',
- 'black': '#000000',
- 'blanchedalmond': '#ffebcd',
- 'blue': '#0000ff',
- 'blueviolet': '#8a2be2',
- 'brown': '#a52a2a',
- 'burlywood': '#deb887',
- 'cadetblue': '#5f9ea0',
- 'chartreuse': '#7fff00',
- 'chocolate': '#d2691e',
- 'coral': '#ff7f50',
- 'cornflowerblue': '#6495ed',
- 'cornsilk': '#fff8dc',
- 'crimson': '#dc143c',
- 'cyan': '#00ffff',
- 'darkblue': '#00008b',
- 'darkcyan': '#008b8b',
- 'darkgoldenrod': '#b8860b',
- 'darkgray': '#a9a9a9',
- 'darkgrey': '#a9a9a9',
- 'darkgreen': '#006400',
- 'darkkhaki': '#bdb76b',
- 'darkmagenta': '#8b008b',
- 'darkolivegreen': '#556b2f',
- 'darkorange': '#ff8c00',
- 'darkorchid': '#9932cc',
- 'darkred': '#8b0000',
- 'darksalmon': '#e9967a',
- 'darkseagreen': '#8fbc8f',
- 'darkslateblue': '#483d8b',
- 'darkslategray': '#2f4f4f',
- 'darkslategrey': '#2f4f4f',
- 'darkturquoise': '#00ced1',
- 'darkviolet': '#9400d3',
- 'deeppink': '#ff1493',
- 'deepskyblue': '#00bfff',
- 'dimgray': '#696969',
- 'dimgrey': '#696969',
- 'dodgerblue': '#1e90ff',
- 'firebrick': '#b22222',
- 'floralwhite': '#fffaf0',
- 'forestgreen': '#228b22',
- 'fuchsia': '#ff00ff',
- 'gainsboro': '#dcdcdc',
- 'ghostwhite': '#f8f8ff',
- 'gold': '#ffd700',
- 'goldenrod': '#daa520',
- 'gray': '#808080',
- 'grey': '#808080',
- 'green': '#008000',
- 'greenyellow': '#adff2f',
- 'honeydew': '#f0fff0',
- 'hotpink': '#ff69b4',
- 'indianred': '#cd5c5c',
- 'indigo': '#4b0082',
- 'ivory': '#fffff0',
- 'khaki': '#f0e68c',
- 'lavender': '#e6e6fa',
- 'lavenderblush': '#fff0f5',
- 'lawngreen': '#7cfc00',
- 'lemonchiffon': '#fffacd',
- 'lightblue': '#add8e6',
- 'lightcoral': '#f08080',
- 'lightcyan': '#e0ffff',
- 'lightgoldenrodyellow': '#fafad2',
- 'lightgray': '#d3d3d3',
- 'lightgrey': '#d3d3d3',
- 'lightgreen': '#90ee90',
- 'lightpink': '#ffb6c1',
- 'lightsalmon': '#ffa07a',
- 'lightseagreen': '#20b2aa',
- 'lightskyblue': '#87cefa',
- 'lightslategray': '#778899',
- 'lightslategrey': '#778899',
- 'lightsteelblue': '#b0c4de',
- 'lightyellow': '#ffffe0',
- 'lime': '#00ff00',
- 'limegreen': '#32cd32',
- 'linen': '#faf0e6',
- 'magenta': '#ff00ff',
- 'maroon': '#800000',
- 'mediumaquamarine': '#66cdaa',
- 'mediumblue': '#0000cd',
- 'mediumorchid': '#ba55d3',
- 'mediumpurple': '#9370d8',
- 'mediumseagreen': '#3cb371',
- 'mediumslateblue': '#7b68ee',
- 'mediumspringgreen': '#00fa9a',
- 'mediumturquoise': '#48d1cc',
- 'mediumvioletred': '#c71585',
- 'midnightblue': '#191970',
- 'mintcream': '#f5fffa',
- 'mistyrose': '#ffe4e1',
- 'moccasin': '#ffe4b5',
- 'navajowhite': '#ffdead',
- 'navy': '#000080',
- 'oldlace': '#fdf5e6',
- 'olive': '#808000',
- 'olivedrab': '#6b8e23',
- 'orange': '#ffa500',
- 'orangered': '#ff4500',
- 'orchid': '#da70d6',
- 'palegoldenrod': '#eee8aa',
- 'palegreen': '#98fb98',
- 'paleturquoise': '#afeeee',
- 'palevioletred': '#d87093',
- 'papayawhip': '#ffefd5',
- 'peachpuff': '#ffdab9',
- 'peru': '#cd853f',
- 'pink': '#ffc0cb',
- 'plum': '#dda0dd',
- 'powderblue': '#b0e0e6',
- 'purple': '#800080',
- 'rebeccapurple': '#663399',
- 'red': '#ff0000',
- 'rosybrown': '#bc8f8f',
- 'royalblue': '#4169e1',
- 'saddlebrown': '#8b4513',
- 'salmon': '#fa8072',
- 'sandybrown': '#f4a460',
- 'seagreen': '#2e8b57',
- 'seashell': '#fff5ee',
- 'sienna': '#a0522d',
- 'silver': '#c0c0c0',
- 'skyblue': '#87ceeb',
- 'slateblue': '#6a5acd',
- 'slategray': '#708090',
- 'slategrey': '#708090',
- 'snow': '#fffafa',
- 'springgreen': '#00ff7f',
- 'steelblue': '#4682b4',
- 'tan': '#d2b48c',
- 'teal': '#008080',
- 'thistle': '#d8bfd8',
- 'tomato': '#ff6347',
- 'turquoise': '#40e0d0',
- 'violet': '#ee82ee',
- 'wheat': '#f5deb3',
- 'white': '#ffffff',
- 'whitesmoke': '#f5f5f5',
- 'yellow': '#ffff00',
- 'yellowgreen': '#9acd32'
-};
-
-var unitConversions = {
- length: {
- 'm': 1,
- 'cm': 0.01,
- 'mm': 0.001,
- 'in': 0.0254,
- 'px': 0.0254 / 96,
- 'pt': 0.0254 / 72,
- 'pc': 0.0254 / 72 * 12
- },
- duration: {
- 's': 1,
- 'ms': 0.001
- },
- angle: {
- 'rad': 1 / (2 * Math.PI),
- 'deg': 1 / 360,
- 'grad': 1 / 400,
- 'turn': 1
- }
-};
-
-var data = {
- colors,
- unitConversions
-};
-
-var Node =
-/*#__PURE__*/
-function () {
- function Node() {
- _classCallCheck(this, Node);
-
- this.parent = null;
- this.visibilityBlocks = undefined;
- this.nodeVisible = undefined;
- this.rootNode = null;
- this.parsed = null;
- var self = this;
- Object.defineProperty(this, 'currentFileInfo', {
- get: function get() {
- return self.fileInfo();
- }
- });
- Object.defineProperty(this, 'index', {
- get: function get() {
- return self.getIndex();
- }
- });
- }
-
- _createClass(Node, [{
- key: "setParent",
- value: function setParent(nodes, parent) {
- function set(node) {
- if (node && node instanceof Node) {
- node.parent = parent;
- }
- }
-
- if (Array.isArray(nodes)) {
- nodes.forEach(set);
- } else {
- set(nodes);
- }
- }
- }, {
- key: "getIndex",
- value: function getIndex() {
- return this._index || this.parent && this.parent.getIndex() || 0;
- }
- }, {
- key: "fileInfo",
- value: function fileInfo() {
- return this._fileInfo || this.parent && this.parent.fileInfo() || {};
- }
- }, {
- key: "isRulesetLike",
- value: function isRulesetLike() {
- return false;
- }
- }, {
- key: "toCSS",
- value: function toCSS(context) {
- var strs = [];
- this.genCSS(context, {
- add: function add(chunk, fileInfo, index) {
- strs.push(chunk);
- },
- isEmpty: function isEmpty() {
- return strs.length === 0;
- }
- });
- return strs.join('');
- }
- }, {
- key: "genCSS",
- value: function genCSS(context, output) {
- output.add(this.value);
- }
- }, {
- key: "accept",
- value: function accept(visitor) {
- this.value = visitor.visit(this.value);
- }
- }, {
- key: "eval",
- value: function _eval() {
- return this;
- }
- }, {
- key: "_operate",
- value: function _operate(context, op, a, b) {
- switch (op) {
- case '+':
- return a + b;
-
- case '-':
- return a - b;
-
- case '*':
- return a * b;
-
- case '/':
- return a / b;
- }
- }
- }, {
- key: "fround",
- value: function fround(context, value) {
- var precision = context && context.numPrecision; // add "epsilon" to ensure numbers like 1.000000005 (represented as 1.000000004999...) are properly rounded:
-
- return precision ? Number((value + 2e-16).toFixed(precision)) : value;
- } // Returns true if this node represents root of ast imported by reference
-
- }, {
- key: "blocksVisibility",
- value: function blocksVisibility() {
- if (this.visibilityBlocks == null) {
- this.visibilityBlocks = 0;
- }
-
- return this.visibilityBlocks !== 0;
- }
- }, {
- key: "addVisibilityBlock",
- value: function addVisibilityBlock() {
- if (this.visibilityBlocks == null) {
- this.visibilityBlocks = 0;
- }
-
- this.visibilityBlocks = this.visibilityBlocks + 1;
- }
- }, {
- key: "removeVisibilityBlock",
- value: function removeVisibilityBlock() {
- if (this.visibilityBlocks == null) {
- this.visibilityBlocks = 0;
- }
-
- this.visibilityBlocks = this.visibilityBlocks - 1;
- } // Turns on node visibility - if called node will be shown in output regardless
- // of whether it comes from import by reference or not
-
- }, {
- key: "ensureVisibility",
- value: function ensureVisibility() {
- this.nodeVisible = true;
- } // Turns off node visibility - if called node will NOT be shown in output regardless
- // of whether it comes from import by reference or not
-
- }, {
- key: "ensureInvisibility",
- value: function ensureInvisibility() {
- this.nodeVisible = false;
- } // return values:
- // false - the node must not be visible
- // true - the node must be visible
- // undefined or null - the node has the same visibility as its parent
-
- }, {
- key: "isVisible",
- value: function isVisible() {
- return this.nodeVisible;
- }
- }, {
- key: "visibilityInfo",
- value: function visibilityInfo() {
- return {
- visibilityBlocks: this.visibilityBlocks,
- nodeVisible: this.nodeVisible
- };
- }
- }, {
- key: "copyVisibilityInfo",
- value: function copyVisibilityInfo(info) {
- if (!info) {
- return;
- }
-
- this.visibilityBlocks = info.visibilityBlocks;
- this.nodeVisible = info.nodeVisible;
- }
- }]);
-
- return Node;
-}();
-
-Node.compare = function (a, b) {
- /* returns:
- -1: a < b
- 0: a = b
- 1: a > b
- and *any* other value for a != b (e.g. undefined, NaN, -2 etc.) */
- if (a.compare && // for "symmetric results" force toCSS-based comparison
- // of Quoted or Anonymous if either value is one of those
- !(b.type === 'Quoted' || b.type === 'Anonymous')) {
- return a.compare(b);
- } else if (b.compare) {
- return -b.compare(a);
- } else if (a.type !== b.type) {
- return undefined;
- }
-
- a = a.value;
- b = b.value;
-
- if (!Array.isArray(a)) {
- return a === b ? 0 : undefined;
- }
-
- if (a.length !== b.length) {
- return undefined;
- }
-
- for (var i = 0; i < a.length; i++) {
- if (Node.compare(a[i], b[i]) !== 0) {
- return undefined;
- }
- }
-
- return 0;
-};
-
-Node.numericCompare = function (a, b) {
- return a < b ? -1 : a === b ? 0 : a > b ? 1 : undefined;
-};
-
-// RGB Colors - #ff0014, #eee
-//
-
-var Color =
-/*#__PURE__*/
-function (_Node) {
- _inherits(Color, _Node);
-
- function Color(rgb, a, originalForm) {
- var _this;
-
- _classCallCheck(this, Color);
-
- _this = _possibleConstructorReturn(this, _getPrototypeOf(Color).call(this));
-
- var self = _assertThisInitialized(_this); //
- // The end goal here, is to parse the arguments
- // into an integer triplet, such as `128, 255, 0`
- //
- // This facilitates operations and conversions.
- //
-
-
- if (Array.isArray(rgb)) {
- _this.rgb = rgb;
- } else if (rgb.length >= 6) {
- _this.rgb = [];
- rgb.match(/.{2}/g).map(function (c, i) {
- if (i < 3) {
- self.rgb.push(parseInt(c, 16));
- } else {
- self.alpha = parseInt(c, 16) / 255;
- }
- });
- } else {
- _this.rgb = [];
- rgb.split('').map(function (c, i) {
- if (i < 3) {
- self.rgb.push(parseInt(c + c, 16));
- } else {
- self.alpha = parseInt(c + c, 16) / 255;
- }
- });
- }
-
- _this.alpha = _this.alpha || (typeof a === 'number' ? a : 1);
-
- if (typeof originalForm !== 'undefined') {
- _this.value = originalForm;
- }
-
- return _this;
- }
-
- _createClass(Color, [{
- key: "luma",
- value: function luma() {
- var r = this.rgb[0] / 255;
- var g = this.rgb[1] / 255;
- var b = this.rgb[2] / 255;
- r = r <= 0.03928 ? r / 12.92 : Math.pow((r + 0.055) / 1.055, 2.4);
- g = g <= 0.03928 ? g / 12.92 : Math.pow((g + 0.055) / 1.055, 2.4);
- b = b <= 0.03928 ? b / 12.92 : Math.pow((b + 0.055) / 1.055, 2.4);
- return 0.2126 * r + 0.7152 * g + 0.0722 * b;
- }
- }, {
- key: "genCSS",
- value: function genCSS(context, output) {
- output.add(this.toCSS(context));
- }
- }, {
- key: "toCSS",
- value: function toCSS(context, doNotCompress) {
- var compress = context && context.compress && !doNotCompress;
- var color;
- var alpha;
- var colorFunction;
- var args = []; // `value` is set if this color was originally
- // converted from a named color string so we need
- // to respect this and try to output named color too.
-
- alpha = this.fround(context, this.alpha);
-
- if (this.value) {
- if (this.value.indexOf('rgb') === 0) {
- if (alpha < 1) {
- colorFunction = 'rgba';
- }
- } else if (this.value.indexOf('hsl') === 0) {
- if (alpha < 1) {
- colorFunction = 'hsla';
- } else {
- colorFunction = 'hsl';
- }
- } else {
- return this.value;
- }
- } else {
- if (alpha < 1) {
- colorFunction = 'rgba';
- }
- }
-
- switch (colorFunction) {
- case 'rgba':
- args = this.rgb.map(function (c) {
- return clamp(Math.round(c), 255);
- }).concat(clamp(alpha, 1));
- break;
-
- case 'hsla':
- args.push(clamp(alpha, 1));
-
- case 'hsl':
- color = this.toHSL();
- args = [this.fround(context, color.h), `${this.fround(context, color.s * 100)}%`, `${this.fround(context, color.l * 100)}%`].concat(args);
- }
-
- if (colorFunction) {
- // Values are capped between `0` and `255`, rounded and zero-padded.
- return `${colorFunction}(${args.join(`,${compress ? '' : ' '}`)})`;
- }
-
- color = this.toRGB();
-
- if (compress) {
- var splitcolor = color.split(''); // Convert color to short format
-
- if (splitcolor[1] === splitcolor[2] && splitcolor[3] === splitcolor[4] && splitcolor[5] === splitcolor[6]) {
- color = `#${splitcolor[1]}${splitcolor[3]}${splitcolor[5]}`;
- }
- }
-
- return color;
- } //
- // Operations have to be done per-channel, if not,
- // channels will spill onto each other. Once we have
- // our result, in the form of an integer triplet,
- // we create a new Color node to hold the result.
- //
-
- }, {
- key: "operate",
- value: function operate(context, op, other) {
- var rgb = new Array(3);
- var alpha = this.alpha * (1 - other.alpha) + other.alpha;
-
- for (var c = 0; c < 3; c++) {
- rgb[c] = this._operate(context, op, this.rgb[c], other.rgb[c]);
- }
-
- return new Color(rgb, alpha);
- }
- }, {
- key: "toRGB",
- value: function toRGB() {
- return toHex(this.rgb);
- }
- }, {
- key: "toHSL",
- value: function toHSL() {
- var r = this.rgb[0] / 255;
- var g = this.rgb[1] / 255;
- var b = this.rgb[2] / 255;
- var a = this.alpha;
- var max = Math.max(r, g, b);
- var min = Math.min(r, g, b);
- var h;
- var s;
- var l = (max + min) / 2;
- var d = max - min;
-
- if (max === min) {
- h = s = 0;
- } else {
- s = l > 0.5 ? d / (2 - max - min) : d / (max + min);
-
- switch (max) {
- case r:
- h = (g - b) / d + (g < b ? 6 : 0);
- break;
-
- case g:
- h = (b - r) / d + 2;
- break;
-
- case b:
- h = (r - g) / d + 4;
- break;
- }
-
- h /= 6;
- }
-
- return {
- h: h * 360,
- s,
- l,
- a
- };
- } // Adapted from http://mjijackson.com/2008/02/rgb-to-hsl-and-rgb-to-hsv-color-model-conversion-algorithms-in-javascript
-
- }, {
- key: "toHSV",
- value: function toHSV() {
- var r = this.rgb[0] / 255;
- var g = this.rgb[1] / 255;
- var b = this.rgb[2] / 255;
- var a = this.alpha;
- var max = Math.max(r, g, b);
- var min = Math.min(r, g, b);
- var h;
- var s;
- var v = max;
- var d = max - min;
-
- if (max === 0) {
- s = 0;
- } else {
- s = d / max;
- }
-
- if (max === min) {
- h = 0;
- } else {
- switch (max) {
- case r:
- h = (g - b) / d + (g < b ? 6 : 0);
- break;
-
- case g:
- h = (b - r) / d + 2;
- break;
-
- case b:
- h = (r - g) / d + 4;
- break;
- }
-
- h /= 6;
- }
-
- return {
- h: h * 360,
- s,
- v,
- a
- };
- }
- }, {
- key: "toARGB",
- value: function toARGB() {
- return toHex([this.alpha * 255].concat(this.rgb));
- }
- }, {
- key: "compare",
- value: function compare(x) {
- return x.rgb && x.rgb[0] === this.rgb[0] && x.rgb[1] === this.rgb[1] && x.rgb[2] === this.rgb[2] && x.alpha === this.alpha ? 0 : undefined;
- }
- }]);
-
- return Color;
-}(Node);
-
-Color.prototype.type = 'Color';
-
-function clamp(v, max) {
- return Math.min(Math.max(v, 0), max);
-}
-
-function toHex(v) {
- return `#${v.map(function (c) {
- c = clamp(Math.round(c), 255);
- return (c < 16 ? '0' : '') + c.toString(16);
- }).join('')}`;
-}
-
-Color.fromKeyword = function (keyword) {
- var c;
- var key = keyword.toLowerCase();
-
- if (colors.hasOwnProperty(key)) {
- c = new Color(colors[key].slice(1));
- } else if (key === 'transparent') {
- c = new Color([0, 0, 0], 0);
- }
-
- if (c) {
- c.value = keyword;
- return c;
- }
-};
-
-var Paren =
-/*#__PURE__*/
-function (_Node) {
- _inherits(Paren, _Node);
-
- function Paren(node) {
- var _this;
-
- _classCallCheck(this, Paren);
-
- _this = _possibleConstructorReturn(this, _getPrototypeOf(Paren).call(this));
- _this.value = node;
- return _this;
- }
-
- _createClass(Paren, [{
- key: "genCSS",
- value: function genCSS(context, output) {
- output.add('(');
- this.value.genCSS(context, output);
- output.add(')');
- }
- }, {
- key: "eval",
- value: function _eval(context) {
- return new Paren(this.value.eval(context));
- }
- }]);
-
- return Paren;
-}(Node);
-
-Paren.prototype.type = 'Paren';
-
-var _noSpaceCombinators = {
- '': true,
- ' ': true,
- '|': true
-};
-
-var Combinator =
-/*#__PURE__*/
-function (_Node) {
- _inherits(Combinator, _Node);
-
- function Combinator(value) {
- var _this;
-
- _classCallCheck(this, Combinator);
-
- _this = _possibleConstructorReturn(this, _getPrototypeOf(Combinator).call(this));
-
- if (value === ' ') {
- _this.value = ' ';
- _this.emptyOrWhitespace = true;
- } else {
- _this.value = value ? value.trim() : '';
- _this.emptyOrWhitespace = _this.value === '';
- }
-
- return _this;
- }
-
- _createClass(Combinator, [{
- key: "genCSS",
- value: function genCSS(context, output) {
- var spaceOrEmpty = context.compress || _noSpaceCombinators[this.value] ? '' : ' ';
- output.add(spaceOrEmpty + this.value + spaceOrEmpty);
- }
- }]);
-
- return Combinator;
-}(Node);
-
-Combinator.prototype.type = 'Combinator';
-
-var Element =
-/*#__PURE__*/
-function (_Node) {
- _inherits(Element, _Node);
-
- function Element(combinator, value, isVariable, index, currentFileInfo, visibilityInfo) {
- var _this;
-
- _classCallCheck(this, Element);
-
- _this = _possibleConstructorReturn(this, _getPrototypeOf(Element).call(this));
- _this.combinator = combinator instanceof Combinator ? combinator : new Combinator(combinator);
-
- if (typeof value === 'string') {
- _this.value = value.trim();
- } else if (value) {
- _this.value = value;
- } else {
- _this.value = '';
- }
-
- _this.isVariable = isVariable;
- _this._index = index;
- _this._fileInfo = currentFileInfo;
-
- _this.copyVisibilityInfo(visibilityInfo);
-
- _this.setParent(_this.combinator, _assertThisInitialized(_this));
-
- return _this;
- }
-
- _createClass(Element, [{
- key: "accept",
- value: function accept(visitor) {
- var value = this.value;
- this.combinator = visitor.visit(this.combinator);
-
- if (typeof value === 'object') {
- this.value = visitor.visit(value);
- }
- }
- }, {
- key: "eval",
- value: function _eval(context) {
- return new Element(this.combinator, this.value.eval ? this.value.eval(context) : this.value, this.isVariable, this.getIndex(), this.fileInfo(), this.visibilityInfo());
- }
- }, {
- key: "clone",
- value: function clone() {
- return new Element(this.combinator, this.value, this.isVariable, this.getIndex(), this.fileInfo(), this.visibilityInfo());
- }
- }, {
- key: "genCSS",
- value: function genCSS(context, output) {
- output.add(this.toCSS(context), this.fileInfo(), this.getIndex());
- }
- }, {
- key: "toCSS",
- value: function toCSS() {
- var context = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};
- var value = this.value;
- var firstSelector = context.firstSelector;
-
- if (value instanceof Paren) {
- // selector in parens should not be affected by outer selector
- // flags (breaks only interpolated selectors - see #1973)
- context.firstSelector = true;
- }
-
- value = value.toCSS ? value.toCSS(context) : value;
- context.firstSelector = firstSelector;
-
- if (value === '' && this.combinator.value.charAt(0) === '&') {
- return '';
- } else {
- return this.combinator.toCSS(context) + value;
- }
- }
- }]);
-
- return Element;
-}(Node);
-
-Element.prototype.type = 'Element';
-
-var Math$1 = {
- ALWAYS: 0,
- PARENS_DIVISION: 1,
- PARENS: 2,
- STRICT_LEGACY: 3
-};
-var RewriteUrls = {
- OFF: 0,
- LOCAL: 1,
- ALL: 2
-};
-
-/* jshint proto: true */
-function getLocation(index, inputStream) {
- var n = index + 1;
- var line = null;
- var column = -1;
-
- while (--n >= 0 && inputStream.charAt(n) !== '\n') {
- column++;
- }
-
- if (typeof index === 'number') {
- line = (inputStream.slice(0, index).match(/\n/g) || '').length;
- }
-
- return {
- line,
- column
- };
-}
-function copyArray(arr) {
- var i;
- var length = arr.length;
- var copy = new Array(length);
-
- for (i = 0; i < length; i++) {
- copy[i] = arr[i];
- }
-
- return copy;
-}
-function clone(obj) {
- var cloned = {};
-
- for (var prop in obj) {
- if (obj.hasOwnProperty(prop)) {
- cloned[prop] = obj[prop];
- }
- }
-
- return cloned;
-}
-function defaults(obj1, obj2) {
- var newObj = obj2 || {};
-
- if (!obj2._defaults) {
- newObj = {};
-
- var _defaults = CloneHelper(obj1);
-
- newObj._defaults = _defaults;
- var cloned = obj2 ? CloneHelper(obj2) : {};
- Object.assign(newObj, _defaults, cloned);
- }
-
- return newObj;
-}
-function copyOptions(obj1, obj2) {
- if (obj2 && obj2._defaults) {
- return obj2;
- }
-
- var opts = defaults(obj1, obj2);
-
- if (opts.strictMath) {
- opts.math = Math$1.STRICT_LEGACY;
- } // Back compat with changed relativeUrls option
-
-
- if (opts.relativeUrls) {
- opts.rewriteUrls = RewriteUrls.ALL;
- }
-
- if (typeof opts.math === 'string') {
- switch (opts.math.toLowerCase()) {
- case 'always':
- opts.math = Math$1.ALWAYS;
- break;
-
- case 'parens-division':
- opts.math = Math$1.PARENS_DIVISION;
- break;
-
- case 'strict':
- case 'parens':
- opts.math = Math$1.PARENS;
- break;
-
- case 'strict-legacy':
- opts.math = Math$1.STRICT_LEGACY;
- }
- }
-
- if (typeof opts.rewriteUrls === 'string') {
- switch (opts.rewriteUrls.toLowerCase()) {
- case 'off':
- opts.rewriteUrls = RewriteUrls.OFF;
- break;
-
- case 'local':
- opts.rewriteUrls = RewriteUrls.LOCAL;
- break;
-
- case 'all':
- opts.rewriteUrls = RewriteUrls.ALL;
- break;
- }
- }
-
- return opts;
-}
-function merge(obj1, obj2) {
- for (var prop in obj2) {
- if (obj2.hasOwnProperty(prop)) {
- obj1[prop] = obj2[prop];
- }
- }
-
- return obj1;
-}
-function flattenArray(arr) {
- var result = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : [];
-
- for (var i = 0, length = arr.length; i < length; i++) {
- var value = arr[i];
-
- if (Array.isArray(value)) {
- flattenArray(value, result);
- } else {
- if (value !== undefined) {
- result.push(value);
- }
- }
- }
-
- return result;
-}
-
-var utils = /*#__PURE__*/Object.freeze({
- getLocation: getLocation,
- copyArray: copyArray,
- clone: clone,
- defaults: defaults,
- copyOptions: copyOptions,
- merge: merge,
- flattenArray: flattenArray
-});
-
-/**
- * This is a centralized class of any error that could be thrown internally (mostly by the parser).
- * Besides standard .message it keeps some additional data like a path to the file where the error
- * occurred along with line and column numbers.
- *
- * @class
- * @extends Error
- * @type {module.LessError}
- *
- * @prop {string} type
- * @prop {string} filename
- * @prop {number} index
- * @prop {number} line
- * @prop {number} column
- * @prop {number} callLine
- * @prop {number} callExtract
- * @prop {string[]} extract
- *
- * @param {Object} e - An error object to wrap around or just a descriptive object
- * @param {Object} fileContentMap - An object with file contents in 'contents' property (like importManager) @todo - move to fileManager?
- * @param {string} [currentFilename]
- */
-
-var LessError = function LessError(e, fileContentMap, currentFilename) {
- Error.call(this);
- var filename = e.filename || currentFilename;
- this.message = e.message;
- this.stack = e.stack;
-
- if (fileContentMap && filename) {
- var input = fileContentMap.contents[filename];
- var loc = getLocation(e.index, input);
- var line = loc.line;
- var col = loc.column;
- var callLine = e.call && getLocation(e.call, input).line;
- var lines = input ? input.split('\n') : '';
- this.type = e.type || 'Syntax';
- this.filename = filename;
- this.index = e.index;
- this.line = typeof line === 'number' ? line + 1 : null;
- this.column = col;
-
- if (!this.line && this.stack) {
- var found = this.stack.match(/(|Function):(\d+):(\d+)/);
-
- if (found) {
- if (found[2]) {
- this.line = parseInt(found[2]) - 2;
- }
-
- if (found[3]) {
- this.column = parseInt(found[3]);
- }
- }
- }
-
- this.callLine = callLine + 1;
- this.callExtract = lines[callLine];
- this.extract = [lines[this.line - 2], lines[this.line - 1], lines[this.line]];
- }
-};
-
-if (typeof Object.create === 'undefined') {
- var F = function F() {};
-
- F.prototype = Error.prototype;
- LessError.prototype = new F();
-} else {
- LessError.prototype = Object.create(Error.prototype);
-}
-
-LessError.prototype.constructor = LessError;
-/**
- * An overridden version of the default Object.prototype.toString
- * which uses additional information to create a helpful message.
- *
- * @param {Object} options
- * @returns {string}
- */
-
-LessError.prototype.toString = function () {
- var options = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};
- var message = '';
- var extract = this.extract || [];
- var error = [];
-
- var stylize = function stylize(str) {
- return str;
- };
-
- if (options.stylize) {
- var type = typeof options.stylize;
-
- if (type !== 'function') {
- throw Error(`options.stylize should be a function, got a ${type}!`);
- }
-
- stylize = options.stylize;
- }
-
- if (this.line !== null) {
- if (typeof extract[0] === 'string') {
- error.push(stylize(`${this.line - 1} ${extract[0]}`, 'grey'));
- }
-
- if (typeof extract[1] === 'string') {
- var errorTxt = `${this.line} `;
-
- if (extract[1]) {
- errorTxt += extract[1].slice(0, this.column) + stylize(stylize(stylize(extract[1].substr(this.column, 1), 'bold') + extract[1].slice(this.column + 1), 'red'), 'inverse');
- }
-
- error.push(errorTxt);
- }
-
- if (typeof extract[2] === 'string') {
- error.push(stylize(`${this.line + 1} ${extract[2]}`, 'grey'));
- }
-
- error = `${error.join('\n') + stylize('', 'reset')}\n`;
- }
-
- message += stylize(`${this.type}Error: ${this.message}`, 'red');
-
- if (this.filename) {
- message += stylize(' in ', 'red') + this.filename;
- }
-
- if (this.line) {
- message += stylize(` on line ${this.line}, column ${this.column + 1}:`, 'grey');
- }
-
- message += `\n${error}`;
-
- if (this.callLine) {
- message += `${stylize('from ', 'red') + (this.filename || '')}/n`;
- message += `${stylize(this.callLine, 'grey')} ${this.callExtract}/n`;
- }
-
- return message;
-};
-
-var Selector =
-/*#__PURE__*/
-function (_Node) {
- _inherits(Selector, _Node);
-
- function Selector(elements, extendList, condition, index, currentFileInfo, visibilityInfo) {
- var _this;
-
- _classCallCheck(this, Selector);
-
- _this = _possibleConstructorReturn(this, _getPrototypeOf(Selector).call(this));
- _this.extendList = extendList;
- _this.condition = condition;
- _this.evaldCondition = !condition;
- _this._index = index;
- _this._fileInfo = currentFileInfo;
- _this.elements = _this.getElements(elements);
- _this.mixinElements_ = undefined;
-
- _this.copyVisibilityInfo(visibilityInfo);
-
- _this.setParent(_this.elements, _assertThisInitialized(_this));
-
- return _this;
- }
-
- _createClass(Selector, [{
- key: "accept",
- value: function accept(visitor) {
- if (this.elements) {
- this.elements = visitor.visitArray(this.elements);
- }
-
- if (this.extendList) {
- this.extendList = visitor.visitArray(this.extendList);
- }
-
- if (this.condition) {
- this.condition = visitor.visit(this.condition);
- }
- }
- }, {
- key: "createDerived",
- value: function createDerived(elements, extendList, evaldCondition) {
- elements = this.getElements(elements);
- var newSelector = new Selector(elements, extendList || this.extendList, null, this.getIndex(), this.fileInfo(), this.visibilityInfo());
- newSelector.evaldCondition = evaldCondition != null ? evaldCondition : this.evaldCondition;
- newSelector.mediaEmpty = this.mediaEmpty;
- return newSelector;
- }
- }, {
- key: "getElements",
- value: function getElements(els) {
- if (!els) {
- return [new Element('', '&', false, this._index, this._fileInfo)];
- }
-
- if (typeof els === 'string') {
- this.parse.parseNode(els, ['selector'], this._index, this._fileInfo, function (err, result) {
- if (err) {
- throw new LessError({
- index: err.index,
- message: err.message
- }, this.parse.imports, this._fileInfo.filename);
- }
-
- els = result[0].elements;
- });
- }
-
- return els;
- }
- }, {
- key: "createEmptySelectors",
- value: function createEmptySelectors() {
- var el = new Element('', '&', false, this._index, this._fileInfo);
- var sels = [new Selector([el], null, null, this._index, this._fileInfo)];
- sels[0].mediaEmpty = true;
- return sels;
- }
- }, {
- key: "match",
- value: function match(other) {
- var elements = this.elements;
- var len = elements.length;
- var olen;
- var i;
- other = other.mixinElements();
- olen = other.length;
-
- if (olen === 0 || len < olen) {
- return 0;
- } else {
- for (i = 0; i < olen; i++) {
- if (elements[i].value !== other[i]) {
- return 0;
- }
- }
- }
-
- return olen; // return number of matched elements
- }
- }, {
- key: "mixinElements",
- value: function mixinElements() {
- if (this.mixinElements_) {
- return this.mixinElements_;
- }
-
- var elements = this.elements.map(function (v) {
- return v.combinator.value + (v.value.value || v.value);
- }).join('').match(/[,\*\.\w-]([\w-]|(\\.))*/g);
-
- if (elements) {
- if (elements[0] === '&') {
- elements.shift();
- }
- } else {
- elements = [];
- }
-
- return this.mixinElements_ = elements;
- }
- }, {
- key: "isJustParentSelector",
- value: function isJustParentSelector() {
- return !this.mediaEmpty && this.elements.length === 1 && this.elements[0].value === '&' && (this.elements[0].combinator.value === ' ' || this.elements[0].combinator.value === '');
- }
- }, {
- key: "eval",
- value: function _eval(context) {
- var evaldCondition = this.condition && this.condition.eval(context);
- var elements = this.elements;
- var extendList = this.extendList;
- elements = elements && elements.map(function (e) {
- return e.eval(context);
- });
- extendList = extendList && extendList.map(function (extend) {
- return extend.eval(context);
- });
- return this.createDerived(elements, extendList, evaldCondition);
- }
- }, {
- key: "genCSS",
- value: function genCSS(context, output) {
- var i;
- var element;
-
- if ((!context || !context.firstSelector) && this.elements[0].combinator.value === '') {
- output.add(' ', this.fileInfo(), this.getIndex());
- }
-
- for (i = 0; i < this.elements.length; i++) {
- element = this.elements[i];
- element.genCSS(context, output);
- }
- }
- }, {
- key: "getIsOutput",
- value: function getIsOutput() {
- return this.evaldCondition;
- }
- }]);
-
- return Selector;
-}(Node);
-
-Selector.prototype.type = 'Selector';
-
-var Value =
-/*#__PURE__*/
-function (_Node) {
- _inherits(Value, _Node);
-
- function Value(value) {
- var _this;
-
- _classCallCheck(this, Value);
-
- _this = _possibleConstructorReturn(this, _getPrototypeOf(Value).call(this));
-
- if (!value) {
- throw new Error('Value requires an array argument');
- }
-
- if (!Array.isArray(value)) {
- _this.value = [value];
- } else {
- _this.value = value;
- }
-
- return _this;
- }
-
- _createClass(Value, [{
- key: "accept",
- value: function accept(visitor) {
- if (this.value) {
- this.value = visitor.visitArray(this.value);
- }
- }
- }, {
- key: "eval",
- value: function _eval(context) {
- if (this.value.length === 1) {
- return this.value[0].eval(context);
- } else {
- return new Value(this.value.map(function (v) {
- return v.eval(context);
- }));
- }
- }
- }, {
- key: "genCSS",
- value: function genCSS(context, output) {
- var i;
-
- for (i = 0; i < this.value.length; i++) {
- this.value[i].genCSS(context, output);
-
- if (i + 1 < this.value.length) {
- output.add(context && context.compress ? ',' : ', ');
- }
- }
- }
- }]);
-
- return Value;
-}(Node);
-
-Value.prototype.type = 'Value';
-
-var Keyword =
-/*#__PURE__*/
-function (_Node) {
- _inherits(Keyword, _Node);
-
- function Keyword(value) {
- var _this;
-
- _classCallCheck(this, Keyword);
-
- _this = _possibleConstructorReturn(this, _getPrototypeOf(Keyword).call(this));
- _this.value = value;
- return _this;
- }
-
- _createClass(Keyword, [{
- key: "genCSS",
- value: function genCSS(context, output) {
- if (this.value === '%') {
- throw {
- type: 'Syntax',
- message: 'Invalid % without number'
- };
- }
-
- output.add(this.value);
- }
- }]);
-
- return Keyword;
-}(Node);
-
-Keyword.prototype.type = 'Keyword';
-Keyword.True = new Keyword('true');
-Keyword.False = new Keyword('false');
-
-var Anonymous =
-/*#__PURE__*/
-function (_Node) {
- _inherits(Anonymous, _Node);
-
- function Anonymous(value, index, currentFileInfo, mapLines, rulesetLike, visibilityInfo) {
- var _this;
-
- _classCallCheck(this, Anonymous);
-
- _this = _possibleConstructorReturn(this, _getPrototypeOf(Anonymous).call(this));
- _this.value = value;
- _this._index = index;
- _this._fileInfo = currentFileInfo;
- _this.mapLines = mapLines;
- _this.rulesetLike = typeof rulesetLike === 'undefined' ? false : rulesetLike;
- _this.allowRoot = true;
-
- _this.copyVisibilityInfo(visibilityInfo);
-
- return _this;
- }
-
- _createClass(Anonymous, [{
- key: "eval",
- value: function _eval() {
- return new Anonymous(this.value, this._index, this._fileInfo, this.mapLines, this.rulesetLike, this.visibilityInfo());
- }
- }, {
- key: "compare",
- value: function compare(other) {
- return other.toCSS && this.toCSS() === other.toCSS() ? 0 : undefined;
- }
- }, {
- key: "isRulesetLike",
- value: function isRulesetLike() {
- return this.rulesetLike;
- }
- }, {
- key: "genCSS",
- value: function genCSS(context, output) {
- this.nodeVisible = Boolean(this.value);
-
- if (this.nodeVisible) {
- output.add(this.value, this._fileInfo, this._index, this.mapLines);
- }
- }
- }]);
-
- return Anonymous;
-}(Node);
-
-Anonymous.prototype.type = 'Anonymous';
-
-var MATH = Math$1;
-
-var Declaration =
-/*#__PURE__*/
-function (_Node) {
- _inherits(Declaration, _Node);
-
- function Declaration(name, value, important, merge, index, currentFileInfo, inline, variable) {
- var _this;
-
- _classCallCheck(this, Declaration);
-
- _this = _possibleConstructorReturn(this, _getPrototypeOf(Declaration).call(this));
- _this.name = name;
- _this.value = value instanceof Node ? value : new Value([value ? new Anonymous(value) : null]);
- _this.important = important ? ` ${important.trim()}` : '';
- _this.merge = merge;
- _this._index = index;
- _this._fileInfo = currentFileInfo;
- _this.inline = inline || false;
- _this.variable = variable !== undefined ? variable : name.charAt && name.charAt(0) === '@';
- _this.allowRoot = true;
-
- _this.setParent(_this.value, _assertThisInitialized(_this));
-
- return _this;
- }
-
- _createClass(Declaration, [{
- key: "genCSS",
- value: function genCSS(context, output) {
- output.add(this.name + (context.compress ? ':' : ': '), this.fileInfo(), this.getIndex());
-
- try {
- this.value.genCSS(context, output);
- } catch (e) {
- e.index = this._index;
- e.filename = this._fileInfo.filename;
- throw e;
- }
-
- output.add(this.important + (this.inline || context.lastRule && context.compress ? '' : ';'), this._fileInfo, this._index);
- }
- }, {
- key: "eval",
- value: function _eval(context) {
- var mathBypass = false;
- var prevMath;
- var name = this.name;
- var evaldValue;
- var variable = this.variable;
-
- if (typeof name !== 'string') {
- // expand 'primitive' name directly to get
- // things faster (~10% for benchmark.less):
- name = name.length === 1 && name[0] instanceof Keyword ? name[0].value : evalName(context, name);
- variable = false; // never treat expanded interpolation as new variable name
- } // @todo remove when parens-division is default
-
-
- if (name === 'font' && context.math === MATH.ALWAYS) {
- mathBypass = true;
- prevMath = context.math;
- context.math = MATH.PARENS_DIVISION;
- }
-
- try {
- context.importantScope.push({});
- evaldValue = this.value.eval(context);
-
- if (!this.variable && evaldValue.type === 'DetachedRuleset') {
- throw {
- message: 'Rulesets cannot be evaluated on a property.',
- index: this.getIndex(),
- filename: this.fileInfo().filename
- };
- }
-
- var important = this.important;
- var importantResult = context.importantScope.pop();
-
- if (!important && importantResult.important) {
- important = importantResult.important;
- }
-
- return new Declaration(name, evaldValue, important, this.merge, this.getIndex(), this.fileInfo(), this.inline, variable);
- } catch (e) {
- if (typeof e.index !== 'number') {
- e.index = this.getIndex();
- e.filename = this.fileInfo().filename;
- }
-
- throw e;
- } finally {
- if (mathBypass) {
- context.math = prevMath;
- }
- }
- }
- }, {
- key: "makeImportant",
- value: function makeImportant() {
- return new Declaration(this.name, this.value, '!important', this.merge, this.getIndex(), this.fileInfo(), this.inline);
- }
- }]);
-
- return Declaration;
-}(Node);
-
-function evalName(context, name) {
- var value = '';
- var i;
- var n = name.length;
- var output = {
- add: function add(s) {
- value += s;
- }
- };
-
- for (i = 0; i < n; i++) {
- name[i].eval(context).genCSS(context, output);
- }
-
- return value;
-}
-
-Declaration.prototype.type = 'Declaration';
-
-var debugInfo = function debugInfo(context, ctx, lineSeparator) {
- var result = '';
-
- if (context.dumpLineNumbers && !context.compress) {
- switch (context.dumpLineNumbers) {
- case 'comments':
- result = debugInfo.asComment(ctx);
- break;
-
- case 'mediaquery':
- result = debugInfo.asMediaQuery(ctx);
- break;
-
- case 'all':
- result = debugInfo.asComment(ctx) + (lineSeparator || '') + debugInfo.asMediaQuery(ctx);
- break;
- }
- }
-
- return result;
-};
-
-debugInfo.asComment = function (ctx) {
- return `/* line ${ctx.debugInfo.lineNumber}, ${ctx.debugInfo.fileName} */\n`;
-};
-
-debugInfo.asMediaQuery = function (ctx) {
- var filenameWithProtocol = ctx.debugInfo.fileName;
-
- if (!/^[a-z]+:\/\//i.test(filenameWithProtocol)) {
- filenameWithProtocol = `file://${filenameWithProtocol}`;
- }
-
- return `@media -sass-debug-info{filename{font-family:${filenameWithProtocol.replace(/([.:\/\\])/g, function (a) {
- if (a == '\\') {
- a = '\/';
- }
-
- return `\\${a}`;
- })}}line{font-family:\\00003${ctx.debugInfo.lineNumber}}}\n`;
-};
-
-var Comment =
-/*#__PURE__*/
-function (_Node) {
- _inherits(Comment, _Node);
-
- function Comment(value, isLineComment, index, currentFileInfo) {
- var _this;
-
- _classCallCheck(this, Comment);
-
- _this = _possibleConstructorReturn(this, _getPrototypeOf(Comment).call(this));
- _this.value = value;
- _this.isLineComment = isLineComment;
- _this._index = index;
- _this._fileInfo = currentFileInfo;
- _this.allowRoot = true;
- return _this;
- }
-
- _createClass(Comment, [{
- key: "genCSS",
- value: function genCSS(context, output) {
- if (this.debugInfo) {
- output.add(debugInfo(context, this), this.fileInfo(), this.getIndex());
- }
-
- output.add(this.value);
- }
- }, {
- key: "isSilent",
- value: function isSilent(context) {
- var isCompressed = context.compress && this.value[2] !== '!';
- return this.isLineComment || isCompressed;
- }
- }]);
-
- return Comment;
-}(Node);
-
-Comment.prototype.type = 'Comment';
-
-var contexts = {};
-
-var copyFromOriginal = function copyFromOriginal(original, destination, propertiesToCopy) {
- if (!original) {
- return;
- }
-
- for (var i = 0; i < propertiesToCopy.length; i++) {
- if (original.hasOwnProperty(propertiesToCopy[i])) {
- destination[propertiesToCopy[i]] = original[propertiesToCopy[i]];
- }
- }
-};
-/*
- parse is used whilst parsing
- */
-
-
-var parseCopyProperties = [// options
-'paths', // option - unmodified - paths to search for imports on
-'rewriteUrls', // option - whether to adjust URL's to be relative
-'rootpath', // option - rootpath to append to URL's
-'strictImports', // option -
-'insecure', // option - whether to allow imports from insecure ssl hosts
-'dumpLineNumbers', // option - whether to dump line numbers
-'compress', // option - whether to compress
-'syncImport', // option - whether to import synchronously
-'chunkInput', // option - whether to chunk input. more performant but causes parse issues.
-'mime', // browser only - mime type for sheet import
-'useFileCache', // browser only - whether to use the per file session cache
-// context
-'processImports', // option & context - whether to process imports. if false then imports will not be imported.
-// Used by the import manager to stop multiple import visitors being created.
-'pluginManager' // Used as the plugin manager for the session
-];
-
-contexts.Parse = function (options) {
- copyFromOriginal(options, this, parseCopyProperties);
-
- if (typeof this.paths === 'string') {
- this.paths = [this.paths];
- }
-};
-
-var evalCopyProperties = ['paths', // additional include paths
-'compress', // whether to compress
-'math', // whether math has to be within parenthesis
-'strictUnits', // whether units need to evaluate correctly
-'sourceMap', // whether to output a source map
-'importMultiple', // whether we are currently importing multiple copies
-'urlArgs', // whether to add args into url tokens
-'javascriptEnabled', // option - whether Inline JavaScript is enabled. if undefined, defaults to false
-'pluginManager', // Used as the plugin manager for the session
-'importantScope', // used to bubble up !important statements
-'rewriteUrls' // option - whether to adjust URL's to be relative
-];
-
-function isPathRelative(path) {
- return !/^(?:[a-z-]+:|\/|#)/i.test(path);
-}
-
-function isPathLocalRelative(path) {
- return path.charAt(0) === '.';
-}
-
-contexts.Eval =
-/*#__PURE__*/
-function () {
- function _class(options, frames) {
- _classCallCheck(this, _class);
-
- copyFromOriginal(options, this, evalCopyProperties);
-
- if (typeof this.paths === 'string') {
- this.paths = [this.paths];
- }
-
- this.frames = frames || [];
- this.importantScope = this.importantScope || [];
- this.inCalc = false;
- this.mathOn = true;
- }
-
- _createClass(_class, [{
- key: "enterCalc",
- value: function enterCalc() {
- if (!this.calcStack) {
- this.calcStack = [];
- }
-
- this.calcStack.push(true);
- this.inCalc = true;
- }
- }, {
- key: "exitCalc",
- value: function exitCalc() {
- this.calcStack.pop();
-
- if (!this.calcStack) {
- this.inCalc = false;
- }
- }
- }, {
- key: "inParenthesis",
- value: function inParenthesis() {
- if (!this.parensStack) {
- this.parensStack = [];
- }
-
- this.parensStack.push(true);
- }
- }, {
- key: "outOfParenthesis",
- value: function outOfParenthesis() {
- this.parensStack.pop();
- }
- }, {
- key: "isMathOn",
- value: function isMathOn(op) {
- if (!this.mathOn) {
- return false;
- }
-
- if (op === '/' && this.math !== Math$1.ALWAYS && (!this.parensStack || !this.parensStack.length)) {
- return false;
- }
-
- if (this.math > Math$1.PARENS_DIVISION) {
- return this.parensStack && this.parensStack.length;
- }
-
- return true;
- }
- }, {
- key: "pathRequiresRewrite",
- value: function pathRequiresRewrite(path) {
- var isRelative = this.rewriteUrls === RewriteUrls.LOCAL ? isPathLocalRelative : isPathRelative;
- return isRelative(path);
- }
- }, {
- key: "rewritePath",
- value: function rewritePath(path, rootpath) {
- var newPath;
- rootpath = rootpath || '';
- newPath = this.normalizePath(rootpath + path); // If a path was explicit relative and the rootpath was not an absolute path
- // we must ensure that the new path is also explicit relative.
-
- if (isPathLocalRelative(path) && isPathRelative(rootpath) && isPathLocalRelative(newPath) === false) {
- newPath = `./${newPath}`;
- }
-
- return newPath;
- }
- }, {
- key: "normalizePath",
- value: function normalizePath(path) {
- var segments = path.split('/').reverse();
- var segment;
- path = [];
-
- while (segments.length !== 0) {
- segment = segments.pop();
-
- switch (segment) {
- case '.':
- break;
-
- case '..':
- if (path.length === 0 || path[path.length - 1] === '..') {
- path.push(segment);
- } else {
- path.pop();
- }
-
- break;
-
- default:
- path.push(segment);
- break;
- }
- }
-
- return path.join('/');
- }
- }]);
-
- return _class;
-}();
-
-function makeRegistry(base) {
- return {
- _data: {},
- add: function add(name, func) {
- // precautionary case conversion, as later querying of
- // the registry by function-caller uses lower case as well.
- name = name.toLowerCase();
-
- if (this._data.hasOwnProperty(name)) ;
-
- this._data[name] = func;
- },
- addMultiple: function addMultiple(functions) {
- var _this = this;
-
- Object.keys(functions).forEach(function (name) {
- _this.add(name, functions[name]);
- });
- },
- get: function get(name) {
- return this._data[name] || base && base.get(name);
- },
- getLocalFunctions: function getLocalFunctions() {
- return this._data;
- },
- inherit: function inherit() {
- return makeRegistry(this);
- },
- create: function create(base) {
- return makeRegistry(base);
- }
- };
-}
-
-var functionRegistry = makeRegistry(null);
-
-var defaultFunc = {
- eval: function _eval() {
- var v = this.value_;
- var e = this.error_;
-
- if (e) {
- throw e;
- }
-
- if (v != null) {
- return v ? Keyword.True : Keyword.False;
- }
- },
- value: function value(v) {
- this.value_ = v;
- },
- error: function error(e) {
- this.error_ = e;
- },
- reset: function reset() {
- this.value_ = this.error_ = null;
- }
-};
-
-var Ruleset =
-/*#__PURE__*/
-function (_Node) {
- _inherits(Ruleset, _Node);
-
- function Ruleset(selectors, rules, strictImports, visibilityInfo) {
- var _this;
-
- _classCallCheck(this, Ruleset);
-
- _this = _possibleConstructorReturn(this, _getPrototypeOf(Ruleset).call(this));
- _this.selectors = selectors;
- _this.rules = rules;
- _this._lookups = {};
- _this._variables = null;
- _this._properties = null;
- _this.strictImports = strictImports;
-
- _this.copyVisibilityInfo(visibilityInfo);
-
- _this.allowRoot = true;
-
- _this.setParent(_this.selectors, _assertThisInitialized(_this));
-
- _this.setParent(_this.rules, _assertThisInitialized(_this));
-
- return _this;
- }
-
- _createClass(Ruleset, [{
- key: "isRulesetLike",
- value: function isRulesetLike() {
- return true;
- }
- }, {
- key: "accept",
- value: function accept(visitor) {
- if (this.paths) {
- this.paths = visitor.visitArray(this.paths, true);
- } else if (this.selectors) {
- this.selectors = visitor.visitArray(this.selectors);
- }
-
- if (this.rules && this.rules.length) {
- this.rules = visitor.visitArray(this.rules);
- }
- }
- }, {
- key: "eval",
- value: function _eval(context) {
- var selectors;
- var selCnt;
- var selector;
- var i;
- var hasVariable;
- var hasOnePassingSelector = false;
-
- if (this.selectors && (selCnt = this.selectors.length)) {
- selectors = new Array(selCnt);
- defaultFunc.error({
- type: 'Syntax',
- message: 'it is currently only allowed in parametric mixin guards,'
- });
-
- for (i = 0; i < selCnt; i++) {
- selector = this.selectors[i].eval(context);
-
- for (var j = 0; j < selector.elements.length; j++) {
- if (selector.elements[j].isVariable) {
- hasVariable = true;
- break;
- }
- }
-
- selectors[i] = selector;
-
- if (selector.evaldCondition) {
- hasOnePassingSelector = true;
- }
- }
-
- if (hasVariable) {
- var toParseSelectors = new Array(selCnt);
-
- for (i = 0; i < selCnt; i++) {
- selector = selectors[i];
- toParseSelectors[i] = selector.toCSS(context);
- }
-
- this.parse.parseNode(toParseSelectors.join(','), ["selectors"], selectors[0].getIndex(), selectors[0].fileInfo(), function (err, result) {
- if (result) {
- selectors = flattenArray(result);
- }
- });
- }
-
- defaultFunc.reset();
- } else {
- hasOnePassingSelector = true;
- }
-
- var rules = this.rules ? copyArray(this.rules) : null;
- var ruleset = new Ruleset(selectors, rules, this.strictImports, this.visibilityInfo());
- var rule;
- var subRule;
- ruleset.originalRuleset = this;
- ruleset.root = this.root;
- ruleset.firstRoot = this.firstRoot;
- ruleset.allowImports = this.allowImports;
-
- if (this.debugInfo) {
- ruleset.debugInfo = this.debugInfo;
- }
-
- if (!hasOnePassingSelector) {
- rules.length = 0;
- } // inherit a function registry from the frames stack when possible;
- // otherwise from the global registry
-
-
- ruleset.functionRegistry = function (frames) {
- var i = 0;
- var n = frames.length;
- var found;
-
- for (; i !== n; ++i) {
- found = frames[i].functionRegistry;
-
- if (found) {
- return found;
- }
- }
-
- return functionRegistry;
- }(context.frames).inherit(); // push the current ruleset to the frames stack
-
-
- var ctxFrames = context.frames;
- ctxFrames.unshift(ruleset); // currrent selectors
-
- var ctxSelectors = context.selectors;
-
- if (!ctxSelectors) {
- context.selectors = ctxSelectors = [];
- }
-
- ctxSelectors.unshift(this.selectors); // Evaluate imports
-
- if (ruleset.root || ruleset.allowImports || !ruleset.strictImports) {
- ruleset.evalImports(context);
- } // Store the frames around mixin definitions,
- // so they can be evaluated like closures when the time comes.
-
-
- var rsRules = ruleset.rules;
-
- for (i = 0; rule = rsRules[i]; i++) {
- if (rule.evalFirst) {
- rsRules[i] = rule.eval(context);
- }
- }
-
- var mediaBlockCount = context.mediaBlocks && context.mediaBlocks.length || 0; // Evaluate mixin calls.
-
- for (i = 0; rule = rsRules[i]; i++) {
- if (rule.type === 'MixinCall') {
- /* jshint loopfunc:true */
- rules = rule.eval(context).filter(function (r) {
- if (r instanceof Declaration && r.variable) {
- // do not pollute the scope if the variable is
- // already there. consider returning false here
- // but we need a way to "return" variable from mixins
- return !ruleset.variable(r.name);
- }
-
- return true;
- });
- rsRules.splice.apply(rsRules, _toConsumableArray([i, 1].concat(rules)));
- i += rules.length - 1;
- ruleset.resetCache();
- } else if (rule.type === 'VariableCall') {
- /* jshint loopfunc:true */
- rules = rule.eval(context).rules.filter(function (r) {
- if (r instanceof Declaration && r.variable) {
- // do not pollute the scope at all
- return false;
- }
-
- return true;
- });
- rsRules.splice.apply(rsRules, _toConsumableArray([i, 1].concat(rules)));
- i += rules.length - 1;
- ruleset.resetCache();
- }
- } // Evaluate everything else
-
-
- for (i = 0; rule = rsRules[i]; i++) {
- if (!rule.evalFirst) {
- rsRules[i] = rule = rule.eval ? rule.eval(context) : rule;
- }
- } // Evaluate everything else
-
-
- for (i = 0; rule = rsRules[i]; i++) {
- // for rulesets, check if it is a css guard and can be removed
- if (rule instanceof Ruleset && rule.selectors && rule.selectors.length === 1) {
- // check if it can be folded in (e.g. & where)
- if (rule.selectors[0] && rule.selectors[0].isJustParentSelector()) {
- rsRules.splice(i--, 1);
-
- for (var j = 0; subRule = rule.rules[j]; j++) {
- if (subRule instanceof Node) {
- subRule.copyVisibilityInfo(rule.visibilityInfo());
-
- if (!(subRule instanceof Declaration) || !subRule.variable) {
- rsRules.splice(++i, 0, subRule);
- }
- }
- }
- }
- }
- } // Pop the stack
-
-
- ctxFrames.shift();
- ctxSelectors.shift();
-
- if (context.mediaBlocks) {
- for (i = mediaBlockCount; i < context.mediaBlocks.length; i++) {
- context.mediaBlocks[i].bubbleSelectors(selectors);
- }
- }
-
- return ruleset;
- }
- }, {
- key: "evalImports",
- value: function evalImports(context) {
- var rules = this.rules;
- var i;
- var importRules;
-
- if (!rules) {
- return;
- }
-
- for (i = 0; i < rules.length; i++) {
- if (rules[i].type === 'Import') {
- importRules = rules[i].eval(context);
-
- if (importRules && (importRules.length || importRules.length === 0)) {
- rules.splice.apply(rules, _toConsumableArray([i, 1].concat(importRules)));
- i += importRules.length - 1;
- } else {
- rules.splice(i, 1, importRules);
- }
-
- this.resetCache();
- }
- }
- }
- }, {
- key: "makeImportant",
- value: function makeImportant() {
- var result = new Ruleset(this.selectors, this.rules.map(function (r) {
- if (r.makeImportant) {
- return r.makeImportant();
- } else {
- return r;
- }
- }), this.strictImports, this.visibilityInfo());
- return result;
- }
- }, {
- key: "matchArgs",
- value: function matchArgs(args) {
- return !args || args.length === 0;
- } // lets you call a css selector with a guard
-
- }, {
- key: "matchCondition",
- value: function matchCondition(args, context) {
- var lastSelector = this.selectors[this.selectors.length - 1];
-
- if (!lastSelector.evaldCondition) {
- return false;
- }
-
- if (lastSelector.condition && !lastSelector.condition.eval(new contexts.Eval(context, context.frames))) {
- return false;
- }
-
- return true;
- }
- }, {
- key: "resetCache",
- value: function resetCache() {
- this._rulesets = null;
- this._variables = null;
- this._properties = null;
- this._lookups = {};
- }
- }, {
- key: "variables",
- value: function variables() {
- if (!this._variables) {
- this._variables = !this.rules ? {} : this.rules.reduce(function (hash, r) {
- if (r instanceof Declaration && r.variable === true) {
- hash[r.name] = r;
- } // when evaluating variables in an import statement, imports have not been eval'd
- // so we need to go inside import statements.
- // guard against root being a string (in the case of inlined less)
-
-
- if (r.type === 'Import' && r.root && r.root.variables) {
- var vars = r.root.variables();
-
- for (var name in vars) {
- if (vars.hasOwnProperty(name)) {
- hash[name] = r.root.variable(name);
- }
- }
- }
-
- return hash;
- }, {});
- }
-
- return this._variables;
- }
- }, {
- key: "properties",
- value: function properties() {
- if (!this._properties) {
- this._properties = !this.rules ? {} : this.rules.reduce(function (hash, r) {
- if (r instanceof Declaration && r.variable !== true) {
- var name = r.name.length === 1 && r.name[0] instanceof Keyword ? r.name[0].value : r.name; // Properties don't overwrite as they can merge
-
- if (!hash[`$${name}`]) {
- hash[`$${name}`] = [r];
- } else {
- hash[`$${name}`].push(r);
- }
- }
-
- return hash;
- }, {});
- }
-
- return this._properties;
- }
- }, {
- key: "variable",
- value: function variable(name) {
- var decl = this.variables()[name];
-
- if (decl) {
- return this.parseValue(decl);
- }
- }
- }, {
- key: "property",
- value: function property(name) {
- var decl = this.properties()[name];
-
- if (decl) {
- return this.parseValue(decl);
- }
- }
- }, {
- key: "lastDeclaration",
- value: function lastDeclaration() {
- for (var i = this.rules.length; i > 0; i--) {
- var decl = this.rules[i - 1];
-
- if (decl instanceof Declaration) {
- return this.parseValue(decl);
- }
- }
- }
- }, {
- key: "parseValue",
- value: function parseValue(toParse) {
- var self = this;
-
- function transformDeclaration(decl) {
- if (decl.value instanceof Anonymous && !decl.parsed) {
- if (typeof decl.value.value === 'string') {
- this.parse.parseNode(decl.value.value, ['value', 'important'], decl.value.getIndex(), decl.fileInfo(), function (err, result) {
- if (err) {
- decl.parsed = true;
- }
-
- if (result) {
- decl.value = result[0];
- decl.important = result[1] || '';
- decl.parsed = true;
- }
- });
- } else {
- decl.parsed = true;
- }
-
- return decl;
- } else {
- return decl;
- }
- }
-
- if (!Array.isArray(toParse)) {
- return transformDeclaration.call(self, toParse);
- } else {
- var nodes = [];
- toParse.forEach(function (n) {
- nodes.push(transformDeclaration.call(self, n));
- });
- return nodes;
- }
- }
- }, {
- key: "rulesets",
- value: function rulesets() {
- if (!this.rules) {
- return [];
- }
-
- var filtRules = [];
- var rules = this.rules;
- var i;
- var rule;
-
- for (i = 0; rule = rules[i]; i++) {
- if (rule.isRuleset) {
- filtRules.push(rule);
- }
- }
-
- return filtRules;
- }
- }, {
- key: "prependRule",
- value: function prependRule(rule) {
- var rules = this.rules;
-
- if (rules) {
- rules.unshift(rule);
- } else {
- this.rules = [rule];
- }
-
- this.setParent(rule, this);
- }
- }, {
- key: "find",
- value: function find(selector) {
- var self = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : this;
- var filter = arguments.length > 2 ? arguments[2] : undefined;
- var rules = [];
- var match;
- var foundMixins;
- var key = selector.toCSS();
-
- if (key in this._lookups) {
- return this._lookups[key];
- }
-
- this.rulesets().forEach(function (rule) {
- if (rule !== self) {
- for (var j = 0; j < rule.selectors.length; j++) {
- match = selector.match(rule.selectors[j]);
-
- if (match) {
- if (selector.elements.length > match) {
- if (!filter || filter(rule)) {
- foundMixins = rule.find(new Selector(selector.elements.slice(match)), self, filter);
-
- for (var i = 0; i < foundMixins.length; ++i) {
- foundMixins[i].path.push(rule);
- }
-
- Array.prototype.push.apply(rules, foundMixins);
- }
- } else {
- rules.push({
- rule,
- path: []
- });
- }
-
- break;
- }
- }
- }
- });
- this._lookups[key] = rules;
- return rules;
- }
- }, {
- key: "genCSS",
- value: function genCSS(context, output) {
- var i;
- var j;
- var charsetRuleNodes = [];
- var ruleNodes = [];
- var // Line number debugging
- debugInfo$1;
- var rule;
- var path;
- context.tabLevel = context.tabLevel || 0;
-
- if (!this.root) {
- context.tabLevel++;
- }
-
- var tabRuleStr = context.compress ? '' : Array(context.tabLevel + 1).join(' ');
- var tabSetStr = context.compress ? '' : Array(context.tabLevel).join(' ');
- var sep;
- var charsetNodeIndex = 0;
- var importNodeIndex = 0;
-
- for (i = 0; rule = this.rules[i]; i++) {
- if (rule instanceof Comment) {
- if (importNodeIndex === i) {
- importNodeIndex++;
- }
-
- ruleNodes.push(rule);
- } else if (rule.isCharset && rule.isCharset()) {
- ruleNodes.splice(charsetNodeIndex, 0, rule);
- charsetNodeIndex++;
- importNodeIndex++;
- } else if (rule.type === 'Import') {
- ruleNodes.splice(importNodeIndex, 0, rule);
- importNodeIndex++;
- } else {
- ruleNodes.push(rule);
- }
- }
-
- ruleNodes = charsetRuleNodes.concat(ruleNodes); // If this is the root node, we don't render
- // a selector, or {}.
-
- if (!this.root) {
- debugInfo$1 = debugInfo(context, this, tabSetStr);
-
- if (debugInfo$1) {
- output.add(debugInfo$1);
- output.add(tabSetStr);
- }
-
- var paths = this.paths;
- var pathCnt = paths.length;
- var pathSubCnt;
- sep = context.compress ? ',' : `,\n${tabSetStr}`;
-
- for (i = 0; i < pathCnt; i++) {
- path = paths[i];
-
- if (!(pathSubCnt = path.length)) {
- continue;
- }
-
- if (i > 0) {
- output.add(sep);
- }
-
- context.firstSelector = true;
- path[0].genCSS(context, output);
- context.firstSelector = false;
-
- for (j = 1; j < pathSubCnt; j++) {
- path[j].genCSS(context, output);
- }
- }
-
- output.add((context.compress ? '{' : ' {\n') + tabRuleStr);
- } // Compile rules and rulesets
-
-
- for (i = 0; rule = ruleNodes[i]; i++) {
- if (i + 1 === ruleNodes.length) {
- context.lastRule = true;
- }
-
- var currentLastRule = context.lastRule;
-
- if (rule.isRulesetLike(rule)) {
- context.lastRule = false;
- }
-
- if (rule.genCSS) {
- rule.genCSS(context, output);
- } else if (rule.value) {
- output.add(rule.value.toString());
- }
-
- context.lastRule = currentLastRule;
-
- if (!context.lastRule && rule.isVisible()) {
- output.add(context.compress ? '' : `\n${tabRuleStr}`);
- } else {
- context.lastRule = false;
- }
- }
-
- if (!this.root) {
- output.add(context.compress ? '}' : `\n${tabSetStr}}`);
- context.tabLevel--;
- }
-
- if (!output.isEmpty() && !context.compress && this.firstRoot) {
- output.add('\n');
- }
- }
- }, {
- key: "joinSelectors",
- value: function joinSelectors(paths, context, selectors) {
- for (var s = 0; s < selectors.length; s++) {
- this.joinSelector(paths, context, selectors[s]);
- }
- }
- }, {
- key: "joinSelector",
- value: function joinSelector(paths, context, selector) {
- function createParenthesis(elementsToPak, originalElement) {
- var replacementParen;
- var j;
-
- if (elementsToPak.length === 0) {
- replacementParen = new Paren(elementsToPak[0]);
- } else {
- var insideParent = new Array(elementsToPak.length);
-
- for (j = 0; j < elementsToPak.length; j++) {
- insideParent[j] = new Element(null, elementsToPak[j], originalElement.isVariable, originalElement._index, originalElement._fileInfo);
- }
-
- replacementParen = new Paren(new Selector(insideParent));
- }
-
- return replacementParen;
- }
-
- function createSelector(containedElement, originalElement) {
- var element;
- var selector;
- element = new Element(null, containedElement, originalElement.isVariable, originalElement._index, originalElement._fileInfo);
- selector = new Selector([element]);
- return selector;
- } // joins selector path from `beginningPath` with selector path in `addPath`
- // `replacedElement` contains element that is being replaced by `addPath`
- // returns concatenated path
-
-
- function addReplacementIntoPath(beginningPath, addPath, replacedElement, originalSelector) {
- var newSelectorPath;
- var lastSelector;
- var newJoinedSelector; // our new selector path
-
- newSelectorPath = []; // construct the joined selector - if & is the first thing this will be empty,
- // if not newJoinedSelector will be the last set of elements in the selector
-
- if (beginningPath.length > 0) {
- newSelectorPath = copyArray(beginningPath);
- lastSelector = newSelectorPath.pop();
- newJoinedSelector = originalSelector.createDerived(copyArray(lastSelector.elements));
- } else {
- newJoinedSelector = originalSelector.createDerived([]);
- }
-
- if (addPath.length > 0) {
- // /deep/ is a CSS4 selector - (removed, so should deprecate)
- // that is valid without anything in front of it
- // so if the & does not have a combinator that is "" or " " then
- // and there is a combinator on the parent, then grab that.
- // this also allows + a { & .b { .a & { ... though not sure why you would want to do that
- var combinator = replacedElement.combinator;
- var parentEl = addPath[0].elements[0];
-
- if (combinator.emptyOrWhitespace && !parentEl.combinator.emptyOrWhitespace) {
- combinator = parentEl.combinator;
- } // join the elements so far with the first part of the parent
-
-
- newJoinedSelector.elements.push(new Element(combinator, parentEl.value, replacedElement.isVariable, replacedElement._index, replacedElement._fileInfo));
- newJoinedSelector.elements = newJoinedSelector.elements.concat(addPath[0].elements.slice(1));
- } // now add the joined selector - but only if it is not empty
-
-
- if (newJoinedSelector.elements.length !== 0) {
- newSelectorPath.push(newJoinedSelector);
- } // put together the parent selectors after the join (e.g. the rest of the parent)
-
-
- if (addPath.length > 1) {
- var restOfPath = addPath.slice(1);
- restOfPath = restOfPath.map(function (selector) {
- return selector.createDerived(selector.elements, []);
- });
- newSelectorPath = newSelectorPath.concat(restOfPath);
- }
-
- return newSelectorPath;
- } // joins selector path from `beginningPath` with every selector path in `addPaths` array
- // `replacedElement` contains element that is being replaced by `addPath`
- // returns array with all concatenated paths
-
-
- function addAllReplacementsIntoPath(beginningPath, addPaths, replacedElement, originalSelector, result) {
- var j;
-
- for (j = 0; j < beginningPath.length; j++) {
- var newSelectorPath = addReplacementIntoPath(beginningPath[j], addPaths, replacedElement, originalSelector);
- result.push(newSelectorPath);
- }
-
- return result;
- }
-
- function mergeElementsOnToSelectors(elements, selectors) {
- var i;
- var sel;
-
- if (elements.length === 0) {
- return;
- }
-
- if (selectors.length === 0) {
- selectors.push([new Selector(elements)]);
- return;
- }
-
- for (i = 0; sel = selectors[i]; i++) {
- // if the previous thing in sel is a parent this needs to join on to it
- if (sel.length > 0) {
- sel[sel.length - 1] = sel[sel.length - 1].createDerived(sel[sel.length - 1].elements.concat(elements));
- } else {
- sel.push(new Selector(elements));
- }
- }
- } // replace all parent selectors inside `inSelector` by content of `context` array
- // resulting selectors are returned inside `paths` array
- // returns true if `inSelector` contained at least one parent selector
-
-
- function replaceParentSelector(paths, context, inSelector) {
- // The paths are [[Selector]]
- // The first list is a list of comma separated selectors
- // The inner list is a list of inheritance separated selectors
- // e.g.
- // .a, .b {
- // .c {
- // }
- // }
- // == [[.a] [.c]] [[.b] [.c]]
- //
- var i;
- var j;
- var k;
- var currentElements;
- var newSelectors;
- var selectorsMultiplied;
- var sel;
- var el;
- var hadParentSelector = false;
- var length;
- var lastSelector;
-
- function findNestedSelector(element) {
- var maybeSelector;
-
- if (!(element.value instanceof Paren)) {
- return null;
- }
-
- maybeSelector = element.value.value;
-
- if (!(maybeSelector instanceof Selector)) {
- return null;
- }
-
- return maybeSelector;
- } // the elements from the current selector so far
-
-
- currentElements = []; // the current list of new selectors to add to the path.
- // We will build it up. We initiate it with one empty selector as we "multiply" the new selectors
- // by the parents
-
- newSelectors = [[]];
-
- for (i = 0; el = inSelector.elements[i]; i++) {
- // non parent reference elements just get added
- if (el.value !== '&') {
- var nestedSelector = findNestedSelector(el);
-
- if (nestedSelector != null) {
- // merge the current list of non parent selector elements
- // on to the current list of selectors to add
- mergeElementsOnToSelectors(currentElements, newSelectors);
- var nestedPaths = [];
- var replaced = void 0;
- var replacedNewSelectors = [];
- replaced = replaceParentSelector(nestedPaths, context, nestedSelector);
- hadParentSelector = hadParentSelector || replaced; // the nestedPaths array should have only one member - replaceParentSelector does not multiply selectors
-
- for (k = 0; k < nestedPaths.length; k++) {
- var replacementSelector = createSelector(createParenthesis(nestedPaths[k], el), el);
- addAllReplacementsIntoPath(newSelectors, [replacementSelector], el, inSelector, replacedNewSelectors);
- }
-
- newSelectors = replacedNewSelectors;
- currentElements = [];
- } else {
- currentElements.push(el);
- }
- } else {
- hadParentSelector = true; // the new list of selectors to add
-
- selectorsMultiplied = []; // merge the current list of non parent selector elements
- // on to the current list of selectors to add
-
- mergeElementsOnToSelectors(currentElements, newSelectors); // loop through our current selectors
-
- for (j = 0; j < newSelectors.length; j++) {
- sel = newSelectors[j]; // if we don't have any parent paths, the & might be in a mixin so that it can be used
- // whether there are parents or not
-
- if (context.length === 0) {
- // the combinator used on el should now be applied to the next element instead so that
- // it is not lost
- if (sel.length > 0) {
- sel[0].elements.push(new Element(el.combinator, '', el.isVariable, el._index, el._fileInfo));
- }
-
- selectorsMultiplied.push(sel);
- } else {
- // and the parent selectors
- for (k = 0; k < context.length; k++) {
- // We need to put the current selectors
- // then join the last selector's elements on to the parents selectors
- var newSelectorPath = addReplacementIntoPath(sel, context[k], el, inSelector); // add that to our new set of selectors
-
- selectorsMultiplied.push(newSelectorPath);
- }
- }
- } // our new selectors has been multiplied, so reset the state
-
-
- newSelectors = selectorsMultiplied;
- currentElements = [];
- }
- } // if we have any elements left over (e.g. .a& .b == .b)
- // add them on to all the current selectors
-
-
- mergeElementsOnToSelectors(currentElements, newSelectors);
-
- for (i = 0; i < newSelectors.length; i++) {
- length = newSelectors[i].length;
-
- if (length > 0) {
- paths.push(newSelectors[i]);
- lastSelector = newSelectors[i][length - 1];
- newSelectors[i][length - 1] = lastSelector.createDerived(lastSelector.elements, inSelector.extendList);
- }
- }
-
- return hadParentSelector;
- }
-
- function deriveSelector(visibilityInfo, deriveFrom) {
- var newSelector = deriveFrom.createDerived(deriveFrom.elements, deriveFrom.extendList, deriveFrom.evaldCondition);
- newSelector.copyVisibilityInfo(visibilityInfo);
- return newSelector;
- } // joinSelector code follows
-
-
- var i;
- var newPaths;
- var hadParentSelector;
- newPaths = [];
- hadParentSelector = replaceParentSelector(newPaths, context, selector);
-
- if (!hadParentSelector) {
- if (context.length > 0) {
- newPaths = [];
-
- for (i = 0; i < context.length; i++) {
- var concatenated = context[i].map(deriveSelector.bind(this, selector.visibilityInfo()));
- concatenated.push(selector);
- newPaths.push(concatenated);
- }
- } else {
- newPaths = [[selector]];
- }
- }
-
- for (i = 0; i < newPaths.length; i++) {
- paths.push(newPaths[i]);
- }
- }
- }]);
-
- return Ruleset;
-}(Node);
-
-Ruleset.prototype.type = 'Ruleset';
-Ruleset.prototype.isRuleset = true;
-
-var AtRule =
-/*#__PURE__*/
-function (_Node) {
- _inherits(AtRule, _Node);
-
- function AtRule(name, value, rules, index, currentFileInfo, debugInfo, isRooted, visibilityInfo) {
- var _this;
-
- _classCallCheck(this, AtRule);
-
- _this = _possibleConstructorReturn(this, _getPrototypeOf(AtRule).call(this));
- var i;
- _this.name = name;
- _this.value = value instanceof Node ? value : value ? new Anonymous(value) : value;
-
- if (rules) {
- if (Array.isArray(rules)) {
- _this.rules = rules;
- } else {
- _this.rules = [rules];
- _this.rules[0].selectors = new Selector([], null, null, index, currentFileInfo).createEmptySelectors();
- }
-
- for (i = 0; i < _this.rules.length; i++) {
- _this.rules[i].allowImports = true;
- }
-
- _this.setParent(_this.rules, _assertThisInitialized(_this));
- }
-
- _this._index = index;
- _this._fileInfo = currentFileInfo;
- _this.debugInfo = debugInfo;
- _this.isRooted = isRooted || false;
-
- _this.copyVisibilityInfo(visibilityInfo);
-
- _this.allowRoot = true;
- return _this;
- }
-
- _createClass(AtRule, [{
- key: "accept",
- value: function accept(visitor) {
- var value = this.value;
- var rules = this.rules;
-
- if (rules) {
- this.rules = visitor.visitArray(rules);
- }
-
- if (value) {
- this.value = visitor.visit(value);
- }
- }
- }, {
- key: "isRulesetLike",
- value: function isRulesetLike() {
- return this.rules || !this.isCharset();
- }
- }, {
- key: "isCharset",
- value: function isCharset() {
- return '@charset' === this.name;
- }
- }, {
- key: "genCSS",
- value: function genCSS(context, output) {
- var value = this.value;
- var rules = this.rules;
- output.add(this.name, this.fileInfo(), this.getIndex());
-
- if (value) {
- output.add(' ');
- value.genCSS(context, output);
- }
-
- if (rules) {
- this.outputRuleset(context, output, rules);
- } else {
- output.add(';');
- }
- }
- }, {
- key: "eval",
- value: function _eval(context) {
- var mediaPathBackup;
- var mediaBlocksBackup;
- var value = this.value;
- var rules = this.rules; // media stored inside other atrule should not bubble over it
- // backpup media bubbling information
-
- mediaPathBackup = context.mediaPath;
- mediaBlocksBackup = context.mediaBlocks; // deleted media bubbling information
-
- context.mediaPath = [];
- context.mediaBlocks = [];
-
- if (value) {
- value = value.eval(context);
- }
-
- if (rules) {
- // assuming that there is only one rule at this point - that is how parser constructs the rule
- rules = [rules[0].eval(context)];
- rules[0].root = true;
- } // restore media bubbling information
-
-
- context.mediaPath = mediaPathBackup;
- context.mediaBlocks = mediaBlocksBackup;
- return new AtRule(this.name, value, rules, this.getIndex(), this.fileInfo(), this.debugInfo, this.isRooted, this.visibilityInfo());
- }
- }, {
- key: "variable",
- value: function variable(name) {
- if (this.rules) {
- // assuming that there is only one rule at this point - that is how parser constructs the rule
- return Ruleset.prototype.variable.call(this.rules[0], name);
- }
- }
- }, {
- key: "find",
- value: function find() {
- if (this.rules) {
- for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
- args[_key] = arguments[_key];
- }
-
- // assuming that there is only one rule at this point - that is how parser constructs the rule
- return Ruleset.prototype.find.apply(this.rules[0], args);
- }
- }
- }, {
- key: "rulesets",
- value: function rulesets() {
- if (this.rules) {
- // assuming that there is only one rule at this point - that is how parser constructs the rule
- return Ruleset.prototype.rulesets.apply(this.rules[0]);
- }
- }
- }, {
- key: "outputRuleset",
- value: function outputRuleset(context, output, rules) {
- var ruleCnt = rules.length;
- var i;
- context.tabLevel = (context.tabLevel | 0) + 1; // Compressed
-
- if (context.compress) {
- output.add('{');
-
- for (i = 0; i < ruleCnt; i++) {
- rules[i].genCSS(context, output);
- }
-
- output.add('}');
- context.tabLevel--;
- return;
- } // Non-compressed
-
-
- var tabSetStr = `\n${Array(context.tabLevel).join(' ')}`;
- var tabRuleStr = `${tabSetStr} `;
-
- if (!ruleCnt) {
- output.add(` {${tabSetStr}}`);
- } else {
- output.add(` {${tabRuleStr}`);
- rules[0].genCSS(context, output);
-
- for (i = 1; i < ruleCnt; i++) {
- output.add(tabRuleStr);
- rules[i].genCSS(context, output);
- }
-
- output.add(`${tabSetStr}}`);
- }
-
- context.tabLevel--;
- }
- }]);
-
- return AtRule;
-}(Node);
-
-AtRule.prototype.type = 'AtRule';
-
-var DetachedRuleset =
-/*#__PURE__*/
-function (_Node) {
- _inherits(DetachedRuleset, _Node);
-
- function DetachedRuleset(ruleset, frames) {
- var _this;
-
- _classCallCheck(this, DetachedRuleset);
-
- _this = _possibleConstructorReturn(this, _getPrototypeOf(DetachedRuleset).call(this));
- _this.ruleset = ruleset;
- _this.frames = frames;
-
- _this.setParent(_this.ruleset, _assertThisInitialized(_this));
-
- return _this;
- }
-
- _createClass(DetachedRuleset, [{
- key: "accept",
- value: function accept(visitor) {
- this.ruleset = visitor.visit(this.ruleset);
- }
- }, {
- key: "eval",
- value: function _eval(context) {
- var frames = this.frames || copyArray(context.frames);
- return new DetachedRuleset(this.ruleset, frames);
- }
- }, {
- key: "callEval",
- value: function callEval(context) {
- return this.ruleset.eval(this.frames ? new contexts.Eval(context, this.frames.concat(context.frames)) : context);
- }
- }]);
-
- return DetachedRuleset;
-}(Node);
-
-DetachedRuleset.prototype.type = 'DetachedRuleset';
-DetachedRuleset.prototype.evalFirst = true;
-
-var Unit =
-/*#__PURE__*/
-function (_Node) {
- _inherits(Unit, _Node);
-
- function Unit(numerator, denominator, backupUnit) {
- var _this;
-
- _classCallCheck(this, Unit);
-
- _this = _possibleConstructorReturn(this, _getPrototypeOf(Unit).call(this));
- _this.numerator = numerator ? copyArray(numerator).sort() : [];
- _this.denominator = denominator ? copyArray(denominator).sort() : [];
-
- if (backupUnit) {
- _this.backupUnit = backupUnit;
- } else if (numerator && numerator.length) {
- _this.backupUnit = numerator[0];
- }
-
- return _this;
- }
-
- _createClass(Unit, [{
- key: "clone",
- value: function clone() {
- return new Unit(copyArray(this.numerator), copyArray(this.denominator), this.backupUnit);
- }
- }, {
- key: "genCSS",
- value: function genCSS(context, output) {
- // Dimension checks the unit is singular and throws an error if in strict math mode.
- var strictUnits = context && context.strictUnits;
-
- if (this.numerator.length === 1) {
- output.add(this.numerator[0]); // the ideal situation
- } else if (!strictUnits && this.backupUnit) {
- output.add(this.backupUnit);
- } else if (!strictUnits && this.denominator.length) {
- output.add(this.denominator[0]);
- }
- }
- }, {
- key: "toString",
- value: function toString() {
- var i;
- var returnStr = this.numerator.join('*');
-
- for (i = 0; i < this.denominator.length; i++) {
- returnStr += `/${this.denominator[i]}`;
- }
-
- return returnStr;
- }
- }, {
- key: "compare",
- value: function compare(other) {
- return this.is(other.toString()) ? 0 : undefined;
- }
- }, {
- key: "is",
- value: function is(unitString) {
- return this.toString().toUpperCase() === unitString.toUpperCase();
- }
- }, {
- key: "isLength",
- value: function isLength() {
- return RegExp('^(px|em|ex|ch|rem|in|cm|mm|pc|pt|ex|vw|vh|vmin|vmax)$', 'gi').test(this.toCSS());
- }
- }, {
- key: "isEmpty",
- value: function isEmpty() {
- return this.numerator.length === 0 && this.denominator.length === 0;
- }
- }, {
- key: "isSingular",
- value: function isSingular() {
- return this.numerator.length <= 1 && this.denominator.length === 0;
- }
- }, {
- key: "map",
- value: function map(callback) {
- var i;
-
- for (i = 0; i < this.numerator.length; i++) {
- this.numerator[i] = callback(this.numerator[i], false);
- }
-
- for (i = 0; i < this.denominator.length; i++) {
- this.denominator[i] = callback(this.denominator[i], true);
- }
- }
- }, {
- key: "usedUnits",
- value: function usedUnits() {
- var group;
- var result = {};
- var mapUnit;
- var groupName;
-
- mapUnit = function mapUnit(atomicUnit) {
- /* jshint loopfunc:true */
- if (group.hasOwnProperty(atomicUnit) && !result[groupName]) {
- result[groupName] = atomicUnit;
- }
-
- return atomicUnit;
- };
-
- for (groupName in unitConversions) {
- if (unitConversions.hasOwnProperty(groupName)) {
- group = unitConversions[groupName];
- this.map(mapUnit);
- }
- }
-
- return result;
- }
- }, {
- key: "cancel",
- value: function cancel() {
- var counter = {};
- var atomicUnit;
- var i;
-
- for (i = 0; i < this.numerator.length; i++) {
- atomicUnit = this.numerator[i];
- counter[atomicUnit] = (counter[atomicUnit] || 0) + 1;
- }
-
- for (i = 0; i < this.denominator.length; i++) {
- atomicUnit = this.denominator[i];
- counter[atomicUnit] = (counter[atomicUnit] || 0) - 1;
- }
-
- this.numerator = [];
- this.denominator = [];
-
- for (atomicUnit in counter) {
- if (counter.hasOwnProperty(atomicUnit)) {
- var count = counter[atomicUnit];
-
- if (count > 0) {
- for (i = 0; i < count; i++) {
- this.numerator.push(atomicUnit);
- }
- } else if (count < 0) {
- for (i = 0; i < -count; i++) {
- this.denominator.push(atomicUnit);
- }
- }
- }
- }
-
- this.numerator.sort();
- this.denominator.sort();
- }
- }]);
-
- return Unit;
-}(Node);
-
-Unit.prototype.type = 'Unit';
-
-// A number with a unit
-//
-
-var Dimension =
-/*#__PURE__*/
-function (_Node) {
- _inherits(Dimension, _Node);
-
- function Dimension(value, unit) {
- var _this;
-
- _classCallCheck(this, Dimension);
-
- _this = _possibleConstructorReturn(this, _getPrototypeOf(Dimension).call(this));
- _this.value = parseFloat(value);
-
- if (isNaN(_this.value)) {
- throw new Error('Dimension is not a number.');
- }
-
- _this.unit = unit && unit instanceof Unit ? unit : new Unit(unit ? [unit] : undefined);
-
- _this.setParent(_this.unit, _assertThisInitialized(_this));
-
- return _this;
- }
-
- _createClass(Dimension, [{
- key: "accept",
- value: function accept(visitor) {
- this.unit = visitor.visit(this.unit);
- }
- }, {
- key: "eval",
- value: function _eval(context) {
- return this;
- }
- }, {
- key: "toColor",
- value: function toColor() {
- return new Color([this.value, this.value, this.value]);
- }
- }, {
- key: "genCSS",
- value: function genCSS(context, output) {
- if (context && context.strictUnits && !this.unit.isSingular()) {
- throw new Error(`Multiple units in dimension. Correct the units or use the unit function. Bad unit: ${this.unit.toString()}`);
- }
-
- var value = this.fround(context, this.value);
- var strValue = String(value);
-
- if (value !== 0 && value < 0.000001 && value > -0.000001) {
- // would be output 1e-6 etc.
- strValue = value.toFixed(20).replace(/0+$/, '');
- }
-
- if (context && context.compress) {
- // Zero values doesn't need a unit
- if (value === 0 && this.unit.isLength()) {
- output.add(strValue);
- return;
- } // Float values doesn't need a leading zero
-
-
- if (value > 0 && value < 1) {
- strValue = strValue.substr(1);
- }
- }
-
- output.add(strValue);
- this.unit.genCSS(context, output);
- } // In an operation between two Dimensions,
- // we default to the first Dimension's unit,
- // so `1px + 2` will yield `3px`.
-
- }, {
- key: "operate",
- value: function operate(context, op, other) {
- /* jshint noempty:false */
- var value = this._operate(context, op, this.value, other.value);
-
- var unit = this.unit.clone();
-
- if (op === '+' || op === '-') {
- if (unit.numerator.length === 0 && unit.denominator.length === 0) {
- unit = other.unit.clone();
-
- if (this.unit.backupUnit) {
- unit.backupUnit = this.unit.backupUnit;
- }
- } else if (other.unit.numerator.length === 0 && unit.denominator.length === 0) ; else {
- other = other.convertTo(this.unit.usedUnits());
-
- if (context.strictUnits && other.unit.toString() !== unit.toString()) {
- throw new Error(`Incompatible units. Change the units or use the unit function. ` + `Bad units: '${unit.toString()}' and '${other.unit.toString()}'.`);
- }
-
- value = this._operate(context, op, this.value, other.value);
- }
- } else if (op === '*') {
- unit.numerator = unit.numerator.concat(other.unit.numerator).sort();
- unit.denominator = unit.denominator.concat(other.unit.denominator).sort();
- unit.cancel();
- } else if (op === '/') {
- unit.numerator = unit.numerator.concat(other.unit.denominator).sort();
- unit.denominator = unit.denominator.concat(other.unit.numerator).sort();
- unit.cancel();
- }
-
- return new Dimension(value, unit);
- }
- }, {
- key: "compare",
- value: function compare(other) {
- var a;
- var b;
-
- if (!(other instanceof Dimension)) {
- return undefined;
- }
-
- if (this.unit.isEmpty() || other.unit.isEmpty()) {
- a = this;
- b = other;
- } else {
- a = this.unify();
- b = other.unify();
-
- if (a.unit.compare(b.unit) !== 0) {
- return undefined;
- }
- }
-
- return Node.numericCompare(a.value, b.value);
- }
- }, {
- key: "unify",
- value: function unify() {
- return this.convertTo({
- length: 'px',
- duration: 's',
- angle: 'rad'
- });
- }
- }, {
- key: "convertTo",
- value: function convertTo(conversions) {
- var value = this.value;
- var unit = this.unit.clone();
- var i;
- var groupName;
- var group;
- var targetUnit;
- var derivedConversions = {};
- var applyUnit;
-
- if (typeof conversions === 'string') {
- for (i in unitConversions) {
- if (unitConversions[i].hasOwnProperty(conversions)) {
- derivedConversions = {};
- derivedConversions[i] = conversions;
- }
- }
-
- conversions = derivedConversions;
- }
-
- applyUnit = function applyUnit(atomicUnit, denominator) {
- /* jshint loopfunc:true */
- if (group.hasOwnProperty(atomicUnit)) {
- if (denominator) {
- value = value / (group[atomicUnit] / group[targetUnit]);
- } else {
- value = value * (group[atomicUnit] / group[targetUnit]);
- }
-
- return targetUnit;
- }
-
- return atomicUnit;
- };
-
- for (groupName in conversions) {
- if (conversions.hasOwnProperty(groupName)) {
- targetUnit = conversions[groupName];
- group = unitConversions[groupName];
- unit.map(applyUnit);
- }
- }
-
- unit.cancel();
- return new Dimension(value, unit);
- }
- }]);
-
- return Dimension;
-}(Node);
-
-Dimension.prototype.type = 'Dimension';
-
-var MATH$1 = Math$1;
-
-var Operation =
-/*#__PURE__*/
-function (_Node) {
- _inherits(Operation, _Node);
-
- function Operation(op, operands, isSpaced) {
- var _this;
-
- _classCallCheck(this, Operation);
-
- _this = _possibleConstructorReturn(this, _getPrototypeOf(Operation).call(this));
- _this.op = op.trim();
- _this.operands = operands;
- _this.isSpaced = isSpaced;
- return _this;
- }
-
- _createClass(Operation, [{
- key: "accept",
- value: function accept(visitor) {
- this.operands = visitor.visitArray(this.operands);
- }
- }, {
- key: "eval",
- value: function _eval(context) {
- var a = this.operands[0].eval(context);
- var b = this.operands[1].eval(context);
- var op;
-
- if (context.isMathOn(this.op)) {
- op = this.op === './' ? '/' : this.op;
-
- if (a instanceof Dimension && b instanceof Color) {
- a = a.toColor();
- }
-
- if (b instanceof Dimension && a instanceof Color) {
- b = b.toColor();
- }
-
- if (!a.operate) {
- if (a instanceof Operation && a.op === '/' && context.math === MATH$1.PARENS_DIVISION) {
- return new Operation(this.op, [a, b], this.isSpaced);
- }
-
- throw {
- type: 'Operation',
- message: 'Operation on an invalid type'
- };
- }
-
- return a.operate(context, op, b);
- } else {
- return new Operation(this.op, [a, b], this.isSpaced);
- }
- }
- }, {
- key: "genCSS",
- value: function genCSS(context, output) {
- this.operands[0].genCSS(context, output);
-
- if (this.isSpaced) {
- output.add(' ');
- }
-
- output.add(this.op);
-
- if (this.isSpaced) {
- output.add(' ');
- }
-
- this.operands[1].genCSS(context, output);
- }
- }]);
-
- return Operation;
-}(Node);
-
-Operation.prototype.type = 'Operation';
-
-var MATH$2 = Math$1;
-
-var Expression =
-/*#__PURE__*/
-function (_Node) {
- _inherits(Expression, _Node);
-
- function Expression(value, noSpacing) {
- var _this;
-
- _classCallCheck(this, Expression);
-
- _this = _possibleConstructorReturn(this, _getPrototypeOf(Expression).call(this));
- _this.value = value;
- _this.noSpacing = noSpacing;
-
- if (!value) {
- throw new Error('Expression requires an array parameter');
- }
-
- return _this;
- }
-
- _createClass(Expression, [{
- key: "accept",
- value: function accept(visitor) {
- this.value = visitor.visitArray(this.value);
- }
- }, {
- key: "eval",
- value: function _eval(context) {
- var returnValue;
- var mathOn = context.isMathOn();
- var inParenthesis = this.parens && (context.math !== MATH$2.STRICT_LEGACY || !this.parensInOp);
- var doubleParen = false;
-
- if (inParenthesis) {
- context.inParenthesis();
- }
-
- if (this.value.length > 1) {
- returnValue = new Expression(this.value.map(function (e) {
- if (!e.eval) {
- return e;
- }
-
- return e.eval(context);
- }), this.noSpacing);
- } else if (this.value.length === 1) {
- if (this.value[0].parens && !this.value[0].parensInOp && !context.inCalc) {
- doubleParen = true;
- }
-
- returnValue = this.value[0].eval(context);
- } else {
- returnValue = this;
- }
-
- if (inParenthesis) {
- context.outOfParenthesis();
- }
-
- if (this.parens && this.parensInOp && !mathOn && !doubleParen && !(returnValue instanceof Dimension)) {
- returnValue = new Paren(returnValue);
- }
-
- return returnValue;
- }
- }, {
- key: "genCSS",
- value: function genCSS(context, output) {
- for (var i = 0; i < this.value.length; i++) {
- this.value[i].genCSS(context, output);
-
- if (!this.noSpacing && i + 1 < this.value.length) {
- output.add(' ');
- }
- }
- }
- }, {
- key: "throwAwayComments",
- value: function throwAwayComments() {
- this.value = this.value.filter(function (v) {
- return !(v instanceof Comment);
- });
- }
- }]);
-
- return Expression;
-}(Node);
-
-Expression.prototype.type = 'Expression';
-
-var functionCaller =
-/*#__PURE__*/
-function () {
- function functionCaller(name, context, index, currentFileInfo) {
- _classCallCheck(this, functionCaller);
-
- this.name = name.toLowerCase();
- this.index = index;
- this.context = context;
- this.currentFileInfo = currentFileInfo;
- this.func = context.frames[0].functionRegistry.get(this.name);
- }
-
- _createClass(functionCaller, [{
- key: "isValid",
- value: function isValid() {
- return Boolean(this.func);
- }
- }, {
- key: "call",
- value: function call(args) {
- // This code is terrible and should be replaced as per this issue...
- // https://github.com/less/less.js/issues/2477
- if (Array.isArray(args)) {
- args = args.filter(function (item) {
- if (item.type === 'Comment') {
- return false;
- }
-
- return true;
- }).map(function (item) {
- if (item.type === 'Expression') {
- var subNodes = item.value.filter(function (item) {
- if (item.type === 'Comment') {
- return false;
- }
-
- return true;
- });
-
- if (subNodes.length === 1) {
- return subNodes[0];
- } else {
- return new Expression(subNodes);
- }
- }
-
- return item;
- });
- }
-
- return this.func.apply(this, _toConsumableArray(args));
- }
- }]);
-
- return functionCaller;
-}();
-
-// A function call node.
-//
-
-var Call =
-/*#__PURE__*/
-function (_Node) {
- _inherits(Call, _Node);
-
- function Call(name, args, index, currentFileInfo) {
- var _this;
-
- _classCallCheck(this, Call);
-
- _this = _possibleConstructorReturn(this, _getPrototypeOf(Call).call(this));
- _this.name = name;
- _this.args = args;
- _this.calc = name === 'calc';
- _this._index = index;
- _this._fileInfo = currentFileInfo;
- return _this;
- }
-
- _createClass(Call, [{
- key: "accept",
- value: function accept(visitor) {
- if (this.args) {
- this.args = visitor.visitArray(this.args);
- }
- } //
- // When evaluating a function call,
- // we either find the function in the functionRegistry,
- // in which case we call it, passing the evaluated arguments,
- // if this returns null or we cannot find the function, we
- // simply print it out as it appeared originally [2].
- //
- // The reason why we evaluate the arguments, is in the case where
- // we try to pass a variable to a function, like: `saturate(@color)`.
- // The function should receive the value, not the variable.
- //
-
- }, {
- key: "eval",
- value: function _eval(context) {
- /**
- * Turn off math for calc(), and switch back on for evaluating nested functions
- */
- var currentMathContext = context.mathOn;
- context.mathOn = !this.calc;
-
- if (this.calc || context.inCalc) {
- context.enterCalc();
- }
-
- var args = this.args.map(function (a) {
- return a.eval(context);
- });
-
- if (this.calc || context.inCalc) {
- context.exitCalc();
- }
-
- context.mathOn = currentMathContext;
- var result;
- var funcCaller = new functionCaller(this.name, context, this.getIndex(), this.fileInfo());
-
- if (funcCaller.isValid()) {
- try {
- result = funcCaller.call(args);
- } catch (e) {
- throw {
- type: e.type || 'Runtime',
- message: `error evaluating function \`${this.name}\`${e.message ? `: ${e.message}` : ''}`,
- index: this.getIndex(),
- filename: this.fileInfo().filename,
- line: e.lineNumber,
- column: e.columnNumber
- };
- }
-
- if (result !== null && result !== undefined) {
- // Results that that are not nodes are cast as Anonymous nodes
- // Falsy values or booleans are returned as empty nodes
- if (!(result instanceof Node)) {
- if (!result || result === true) {
- result = new Anonymous(null);
- } else {
- result = new Anonymous(result.toString());
- }
- }
-
- result._index = this._index;
- result._fileInfo = this._fileInfo;
- return result;
- }
- }
-
- return new Call(this.name, args, this.getIndex(), this.fileInfo());
- }
- }, {
- key: "genCSS",
- value: function genCSS(context, output) {
- output.add(`${this.name}(`, this.fileInfo(), this.getIndex());
-
- for (var i = 0; i < this.args.length; i++) {
- this.args[i].genCSS(context, output);
-
- if (i + 1 < this.args.length) {
- output.add(', ');
- }
- }
-
- output.add(')');
- }
- }]);
-
- return Call;
-}(Node);
-
-Call.prototype.type = 'Call';
-
-var Variable =
-/*#__PURE__*/
-function (_Node) {
- _inherits(Variable, _Node);
-
- function Variable(name, index, currentFileInfo) {
- var _this;
-
- _classCallCheck(this, Variable);
-
- _this = _possibleConstructorReturn(this, _getPrototypeOf(Variable).call(this));
- _this.name = name;
- _this._index = index;
- _this._fileInfo = currentFileInfo;
- return _this;
- }
-
- _createClass(Variable, [{
- key: "eval",
- value: function _eval(context) {
- var variable;
- var name = this.name;
-
- if (name.indexOf('@@') === 0) {
- name = `@${new Variable(name.slice(1), this.getIndex(), this.fileInfo()).eval(context).value}`;
- }
-
- if (this.evaluating) {
- throw {
- type: 'Name',
- message: `Recursive variable definition for ${name}`,
- filename: this.fileInfo().filename,
- index: this.getIndex()
- };
- }
-
- this.evaluating = true;
- variable = this.find(context.frames, function (frame) {
- var v = frame.variable(name);
-
- if (v) {
- if (v.important) {
- var importantScope = context.importantScope[context.importantScope.length - 1];
- importantScope.important = v.important;
- } // If in calc, wrap vars in a function call to cascade evaluate args first
-
-
- if (context.inCalc) {
- return new Call('_SELF', [v.value]).eval(context);
- } else {
- return v.value.eval(context);
- }
- }
- });
-
- if (variable) {
- this.evaluating = false;
- return variable;
- } else {
- throw {
- type: 'Name',
- message: `variable ${name} is undefined`,
- filename: this.fileInfo().filename,
- index: this.getIndex()
- };
- }
- }
- }, {
- key: "find",
- value: function find(obj, fun) {
- for (var i = 0, r; i < obj.length; i++) {
- r = fun.call(obj, obj[i]);
-
- if (r) {
- return r;
- }
- }
-
- return null;
- }
- }]);
-
- return Variable;
-}(Node);
-
-Variable.prototype.type = 'Variable';
-
-var Property =
-/*#__PURE__*/
-function (_Node) {
- _inherits(Property, _Node);
-
- function Property(name, index, currentFileInfo) {
- var _this;
-
- _classCallCheck(this, Property);
-
- _this = _possibleConstructorReturn(this, _getPrototypeOf(Property).call(this));
- _this.name = name;
- _this._index = index;
- _this._fileInfo = currentFileInfo;
- return _this;
- }
-
- _createClass(Property, [{
- key: "eval",
- value: function _eval(context) {
- var property;
- var name = this.name; // TODO: shorten this reference
-
- var mergeRules = context.pluginManager.less.visitors.ToCSSVisitor.prototype._mergeRules;
-
- if (this.evaluating) {
- throw {
- type: 'Name',
- message: `Recursive property reference for ${name}`,
- filename: this.fileInfo().filename,
- index: this.getIndex()
- };
- }
-
- this.evaluating = true;
- property = this.find(context.frames, function (frame) {
- var v;
- var vArr = frame.property(name);
-
- if (vArr) {
- for (var i = 0; i < vArr.length; i++) {
- v = vArr[i];
- vArr[i] = new Declaration(v.name, v.value, v.important, v.merge, v.index, v.currentFileInfo, v.inline, v.variable);
- }
-
- mergeRules(vArr);
- v = vArr[vArr.length - 1];
-
- if (v.important) {
- var importantScope = context.importantScope[context.importantScope.length - 1];
- importantScope.important = v.important;
- }
-
- v = v.value.eval(context);
- return v;
- }
- });
-
- if (property) {
- this.evaluating = false;
- return property;
- } else {
- throw {
- type: 'Name',
- message: `Property '${name}' is undefined`,
- filename: this.currentFileInfo.filename,
- index: this.index
- };
- }
- }
- }, {
- key: "find",
- value: function find(obj, fun) {
- for (var i = 0, r; i < obj.length; i++) {
- r = fun.call(obj, obj[i]);
-
- if (r) {
- return r;
- }
- }
-
- return null;
- }
- }]);
-
- return Property;
-}(Node);
-
-Property.prototype.type = 'Property';
-
-var Attribute =
-/*#__PURE__*/
-function (_Node) {
- _inherits(Attribute, _Node);
-
- function Attribute(key, op, value) {
- var _this;
-
- _classCallCheck(this, Attribute);
-
- _this = _possibleConstructorReturn(this, _getPrototypeOf(Attribute).call(this));
- _this.key = key;
- _this.op = op;
- _this.value = value;
- return _this;
- }
-
- _createClass(Attribute, [{
- key: "eval",
- value: function _eval(context) {
- return new Attribute(this.key.eval ? this.key.eval(context) : this.key, this.op, this.value && this.value.eval ? this.value.eval(context) : this.value);
- }
- }, {
- key: "genCSS",
- value: function genCSS(context, output) {
- output.add(this.toCSS(context));
- }
- }, {
- key: "toCSS",
- value: function toCSS(context) {
- var value = this.key.toCSS ? this.key.toCSS(context) : this.key;
-
- if (this.op) {
- value += this.op;
- value += this.value.toCSS ? this.value.toCSS(context) : this.value;
- }
-
- return `[${value}]`;
- }
- }]);
-
- return Attribute;
-}(Node);
-
-Attribute.prototype.type = 'Attribute';
-
-var Quoted =
-/*#__PURE__*/
-function (_Node) {
- _inherits(Quoted, _Node);
-
- function Quoted(str, content, escaped, index, currentFileInfo) {
- var _this;
-
- _classCallCheck(this, Quoted);
-
- _this = _possibleConstructorReturn(this, _getPrototypeOf(Quoted).call(this));
- _this.escaped = escaped == null ? true : escaped;
- _this.value = content || '';
- _this.quote = str.charAt(0);
- _this._index = index;
- _this._fileInfo = currentFileInfo;
- _this.variableRegex = /@\{([\w-]+)\}/g;
- _this.propRegex = /\$\{([\w-]+)\}/g;
- _this.allowRoot = escaped;
- return _this;
- }
-
- _createClass(Quoted, [{
- key: "genCSS",
- value: function genCSS(context, output) {
- if (!this.escaped) {
- output.add(this.quote, this.fileInfo(), this.getIndex());
- }
-
- output.add(this.value);
-
- if (!this.escaped) {
- output.add(this.quote);
- }
- }
- }, {
- key: "containsVariables",
- value: function containsVariables() {
- return this.value.match(this.variableRegex);
- }
- }, {
- key: "eval",
- value: function _eval(context) {
- var that = this;
- var value = this.value;
-
- var variableReplacement = function variableReplacement(_, name) {
- var v = new Variable(`@${name}`, that.getIndex(), that.fileInfo()).eval(context, true);
- return v instanceof Quoted ? v.value : v.toCSS();
- };
-
- var propertyReplacement = function propertyReplacement(_, name) {
- var v = new Property(`$${name}`, that.getIndex(), that.fileInfo()).eval(context, true);
- return v instanceof Quoted ? v.value : v.toCSS();
- };
-
- function iterativeReplace(value, regexp, replacementFnc) {
- var evaluatedValue = value;
-
- do {
- value = evaluatedValue.toString();
- evaluatedValue = value.replace(regexp, replacementFnc);
- } while (value !== evaluatedValue);
-
- return evaluatedValue;
- }
-
- value = iterativeReplace(value, this.variableRegex, variableReplacement);
- value = iterativeReplace(value, this.propRegex, propertyReplacement);
- return new Quoted(this.quote + value + this.quote, value, this.escaped, this.getIndex(), this.fileInfo());
- }
- }, {
- key: "compare",
- value: function compare(other) {
- // when comparing quoted strings allow the quote to differ
- if (other.type === 'Quoted' && !this.escaped && !other.escaped) {
- return Node.numericCompare(this.value, other.value);
- } else {
- return other.toCSS && this.toCSS() === other.toCSS() ? 0 : undefined;
- }
- }
- }]);
-
- return Quoted;
-}(Node);
-
-Quoted.prototype.type = 'Quoted';
-
-var URL =
-/*#__PURE__*/
-function (_Node) {
- _inherits(URL, _Node);
-
- function URL(val, index, currentFileInfo, isEvald) {
- var _this;
-
- _classCallCheck(this, URL);
-
- _this = _possibleConstructorReturn(this, _getPrototypeOf(URL).call(this));
- _this.value = val;
- _this._index = index;
- _this._fileInfo = currentFileInfo;
- _this.isEvald = isEvald;
- return _this;
- }
-
- _createClass(URL, [{
- key: "accept",
- value: function accept(visitor) {
- this.value = visitor.visit(this.value);
- }
- }, {
- key: "genCSS",
- value: function genCSS(context, output) {
- output.add('url(');
- this.value.genCSS(context, output);
- output.add(')');
- }
- }, {
- key: "eval",
- value: function _eval(context) {
- var val = this.value.eval(context);
- var rootpath;
-
- if (!this.isEvald) {
- // Add the rootpath if the URL requires a rewrite
- rootpath = this.fileInfo() && this.fileInfo().rootpath;
-
- if (typeof rootpath === 'string' && typeof val.value === 'string' && context.pathRequiresRewrite(val.value)) {
- if (!val.quote) {
- rootpath = escapePath(rootpath);
- }
-
- val.value = context.rewritePath(val.value, rootpath);
- } else {
- val.value = context.normalizePath(val.value);
- } // Add url args if enabled
-
-
- if (context.urlArgs) {
- if (!val.value.match(/^\s*data:/)) {
- var delimiter = val.value.indexOf('?') === -1 ? '?' : '&';
- var urlArgs = delimiter + context.urlArgs;
-
- if (val.value.indexOf('#') !== -1) {
- val.value = val.value.replace('#', `${urlArgs}#`);
- } else {
- val.value += urlArgs;
- }
- }
- }
- }
-
- return new URL(val, this.getIndex(), this.fileInfo(), true);
- }
- }]);
-
- return URL;
-}(Node);
-
-URL.prototype.type = 'Url';
-
-function escapePath(path) {
- return path.replace(/[\(\)'"\s]/g, function (match) {
- return `\\${match}`;
- });
-}
-
-var Media =
-/*#__PURE__*/
-function (_AtRule) {
- _inherits(Media, _AtRule);
-
- function Media(value, features, index, currentFileInfo, visibilityInfo) {
- var _this;
-
- _classCallCheck(this, Media);
-
- _this = _possibleConstructorReturn(this, _getPrototypeOf(Media).call(this));
- _this._index = index;
- _this._fileInfo = currentFileInfo;
- var selectors = new Selector([], null, null, _this._index, _this._fileInfo).createEmptySelectors();
- _this.features = new Value(features);
- _this.rules = [new Ruleset(selectors, value)];
- _this.rules[0].allowImports = true;
-
- _this.copyVisibilityInfo(visibilityInfo);
-
- _this.allowRoot = true;
-
- _this.setParent(selectors, _assertThisInitialized(_this));
-
- _this.setParent(_this.features, _assertThisInitialized(_this));
-
- _this.setParent(_this.rules, _assertThisInitialized(_this));
-
- return _this;
- }
-
- _createClass(Media, [{
- key: "isRulesetLike",
- value: function isRulesetLike() {
- return true;
- }
- }, {
- key: "accept",
- value: function accept(visitor) {
- if (this.features) {
- this.features = visitor.visit(this.features);
- }
-
- if (this.rules) {
- this.rules = visitor.visitArray(this.rules);
- }
- }
- }, {
- key: "genCSS",
- value: function genCSS(context, output) {
- output.add('@media ', this._fileInfo, this._index);
- this.features.genCSS(context, output);
- this.outputRuleset(context, output, this.rules);
- }
- }, {
- key: "eval",
- value: function _eval(context) {
- if (!context.mediaBlocks) {
- context.mediaBlocks = [];
- context.mediaPath = [];
- }
-
- var media = new Media(null, [], this._index, this._fileInfo, this.visibilityInfo());
-
- if (this.debugInfo) {
- this.rules[0].debugInfo = this.debugInfo;
- media.debugInfo = this.debugInfo;
- }
-
- media.features = this.features.eval(context);
- context.mediaPath.push(media);
- context.mediaBlocks.push(media);
- this.rules[0].functionRegistry = context.frames[0].functionRegistry.inherit();
- context.frames.unshift(this.rules[0]);
- media.rules = [this.rules[0].eval(context)];
- context.frames.shift();
- context.mediaPath.pop();
- return context.mediaPath.length === 0 ? media.evalTop(context) : media.evalNested(context);
- }
- }, {
- key: "evalTop",
- value: function evalTop(context) {
- var result = this; // Render all dependent Media blocks.
-
- if (context.mediaBlocks.length > 1) {
- var selectors = new Selector([], null, null, this.getIndex(), this.fileInfo()).createEmptySelectors();
- result = new Ruleset(selectors, context.mediaBlocks);
- result.multiMedia = true;
- result.copyVisibilityInfo(this.visibilityInfo());
- this.setParent(result, this);
- }
-
- delete context.mediaBlocks;
- delete context.mediaPath;
- return result;
- }
- }, {
- key: "evalNested",
- value: function evalNested(context) {
- var i;
- var value;
- var path = context.mediaPath.concat([this]); // Extract the media-query conditions separated with `,` (OR).
-
- for (i = 0; i < path.length; i++) {
- value = path[i].features instanceof Value ? path[i].features.value : path[i].features;
- path[i] = Array.isArray(value) ? value : [value];
- } // Trace all permutations to generate the resulting media-query.
- //
- // (a, b and c) with nested (d, e) ->
- // a and d
- // a and e
- // b and c and d
- // b and c and e
-
-
- this.features = new Value(this.permute(path).map(function (path) {
- path = path.map(function (fragment) {
- return fragment.toCSS ? fragment : new Anonymous(fragment);
- });
-
- for (i = path.length - 1; i > 0; i--) {
- path.splice(i, 0, new Anonymous('and'));
- }
-
- return new Expression(path);
- }));
- this.setParent(this.features, this); // Fake a tree-node that doesn't output anything.
-
- return new Ruleset([], []);
- }
- }, {
- key: "permute",
- value: function permute(arr) {
- if (arr.length === 0) {
- return [];
- } else if (arr.length === 1) {
- return arr[0];
- } else {
- var result = [];
- var rest = this.permute(arr.slice(1));
-
- for (var i = 0; i < rest.length; i++) {
- for (var j = 0; j < arr[0].length; j++) {
- result.push([arr[0][j]].concat(rest[i]));
- }
- }
-
- return result;
- }
- }
- }, {
- key: "bubbleSelectors",
- value: function bubbleSelectors(selectors) {
- if (!selectors) {
- return;
- }
-
- this.rules = [new Ruleset(copyArray(selectors), [this.rules[0]])];
- this.setParent(this.rules, this);
- }
- }]);
-
- return Media;
-}(AtRule);
-
-Media.prototype.type = 'Media';
-
-// CSS @import node
-//
-// The general strategy here is that we don't want to wait
-// for the parsing to be completed, before we start importing
-// the file. That's because in the context of a browser,
-// most of the time will be spent waiting for the server to respond.
-//
-// On creation, we push the import path to our import queue, though
-// `import,push`, we also pass it a callback, which it'll call once
-// the file has been fetched, and parsed.
-//
-
-var Import =
-/*#__PURE__*/
-function (_Node) {
- _inherits(Import, _Node);
-
- function Import(path, features, options, index, currentFileInfo, visibilityInfo) {
- var _this;
-
- _classCallCheck(this, Import);
-
- _this = _possibleConstructorReturn(this, _getPrototypeOf(Import).call(this));
- _this.options = options;
- _this._index = index;
- _this._fileInfo = currentFileInfo;
- _this.path = path;
- _this.features = features;
- _this.allowRoot = true;
-
- if (_this.options.less !== undefined || _this.options.inline) {
- _this.css = !_this.options.less || _this.options.inline;
- } else {
- var pathValue = _this.getPath();
-
- if (pathValue && /[#\.\&\?]css([\?;].*)?$/.test(pathValue)) {
- _this.css = true;
- }
- }
-
- _this.copyVisibilityInfo(visibilityInfo);
-
- _this.setParent(_this.features, _assertThisInitialized(_this));
-
- _this.setParent(_this.path, _assertThisInitialized(_this));
-
- return _this;
- }
-
- _createClass(Import, [{
- key: "accept",
- value: function accept(visitor) {
- if (this.features) {
- this.features = visitor.visit(this.features);
- }
-
- this.path = visitor.visit(this.path);
-
- if (!this.options.isPlugin && !this.options.inline && this.root) {
- this.root = visitor.visit(this.root);
- }
- }
- }, {
- key: "genCSS",
- value: function genCSS(context, output) {
- if (this.css && this.path._fileInfo.reference === undefined) {
- output.add('@import ', this._fileInfo, this._index);
- this.path.genCSS(context, output);
-
- if (this.features) {
- output.add(' ');
- this.features.genCSS(context, output);
- }
-
- output.add(';');
- }
- }
- }, {
- key: "getPath",
- value: function getPath() {
- return this.path instanceof URL ? this.path.value.value : this.path.value;
- }
- }, {
- key: "isVariableImport",
- value: function isVariableImport() {
- var path = this.path;
-
- if (path instanceof URL) {
- path = path.value;
- }
-
- if (path instanceof Quoted) {
- return path.containsVariables();
- }
-
- return true;
- }
- }, {
- key: "evalForImport",
- value: function evalForImport(context) {
- var path = this.path;
-
- if (path instanceof URL) {
- path = path.value;
- }
-
- return new Import(path.eval(context), this.features, this.options, this._index, this._fileInfo, this.visibilityInfo());
- }
- }, {
- key: "evalPath",
- value: function evalPath(context) {
- var path = this.path.eval(context);
- var fileInfo = this._fileInfo;
-
- if (!(path instanceof URL)) {
- // Add the rootpath if the URL requires a rewrite
- var pathValue = path.value;
-
- if (fileInfo && pathValue && context.pathRequiresRewrite(pathValue)) {
- path.value = context.rewritePath(pathValue, fileInfo.rootpath);
- } else {
- path.value = context.normalizePath(path.value);
- }
- }
-
- return path;
- }
- }, {
- key: "eval",
- value: function _eval(context) {
- var result = this.doEval(context);
-
- if (this.options.reference || this.blocksVisibility()) {
- if (result.length || result.length === 0) {
- result.forEach(function (node) {
- node.addVisibilityBlock();
- });
- } else {
- result.addVisibilityBlock();
- }
- }
-
- return result;
- }
- }, {
- key: "doEval",
- value: function doEval(context) {
- var ruleset;
- var registry;
- var features = this.features && this.features.eval(context);
-
- if (this.options.isPlugin) {
- if (this.root && this.root.eval) {
- try {
- this.root.eval(context);
- } catch (e) {
- e.message = 'Plugin error during evaluation';
- throw new LessError(e, this.root.imports, this.root.filename);
- }
- }
-
- registry = context.frames[0] && context.frames[0].functionRegistry;
-
- if (registry && this.root && this.root.functions) {
- registry.addMultiple(this.root.functions);
- }
-
- return [];
- }
-
- if (this.skip) {
- if (typeof this.skip === 'function') {
- this.skip = this.skip();
- }
-
- if (this.skip) {
- return [];
- }
- }
-
- if (this.options.inline) {
- var contents = new Anonymous(this.root, 0, {
- filename: this.importedFilename,
- reference: this.path._fileInfo && this.path._fileInfo.reference
- }, true, true);
- return this.features ? new Media([contents], this.features.value) : [contents];
- } else if (this.css) {
- var newImport = new Import(this.evalPath(context), features, this.options, this._index);
-
- if (!newImport.css && this.error) {
- throw this.error;
- }
-
- return newImport;
- } else {
- ruleset = new Ruleset(null, copyArray(this.root.rules));
- ruleset.evalImports(context);
- return this.features ? new Media(ruleset.rules, this.features.value) : ruleset.rules;
- }
- }
- }]);
-
- return Import;
-}(Node);
-
-Import.prototype.type = 'Import';
-
-var JsEvalNode =
-/*#__PURE__*/
-function (_Node) {
- _inherits(JsEvalNode, _Node);
-
- function JsEvalNode() {
- _classCallCheck(this, JsEvalNode);
-
- return _possibleConstructorReturn(this, _getPrototypeOf(JsEvalNode).apply(this, arguments));
- }
-
- _createClass(JsEvalNode, [{
- key: "evaluateJavaScript",
- value: function evaluateJavaScript(expression, context) {
- var result;
- var that = this;
- var evalContext = {};
-
- if (!context.javascriptEnabled) {
- throw {
- message: 'Inline JavaScript is not enabled. Is it set in your options?',
- filename: this.fileInfo().filename,
- index: this.getIndex()
- };
- }
-
- expression = expression.replace(/@\{([\w-]+)\}/g, function (_, name) {
- return that.jsify(new Variable(`@${name}`, that.getIndex(), that.fileInfo()).eval(context));
- });
-
- try {
- expression = new Function(`return (${expression})`);
- } catch (e) {
- throw {
- message: `JavaScript evaluation error: ${e.message} from \`${expression}\``,
- filename: this.fileInfo().filename,
- index: this.getIndex()
- };
- }
-
- var variables = context.frames[0].variables();
-
- for (var k in variables) {
- if (variables.hasOwnProperty(k)) {
- /* jshint loopfunc:true */
- evalContext[k.slice(1)] = {
- value: variables[k].value,
- toJS: function toJS() {
- return this.value.eval(context).toCSS();
- }
- };
- }
- }
-
- try {
- result = expression.call(evalContext);
- } catch (e) {
- throw {
- message: `JavaScript evaluation error: '${e.name}: ${e.message.replace(/["]/g, '\'')}'`,
- filename: this.fileInfo().filename,
- index: this.getIndex()
- };
- }
-
- return result;
- }
- }, {
- key: "jsify",
- value: function jsify(obj) {
- if (Array.isArray(obj.value) && obj.value.length > 1) {
- return `[${obj.value.map(function (v) {
- return v.toCSS();
- }).join(', ')}]`;
- } else {
- return obj.toCSS();
- }
- }
- }]);
-
- return JsEvalNode;
-}(Node);
-
-var JavaScript =
-/*#__PURE__*/
-function (_JsEvalNode) {
- _inherits(JavaScript, _JsEvalNode);
-
- function JavaScript(string, escaped, index, currentFileInfo) {
- var _this;
-
- _classCallCheck(this, JavaScript);
-
- _this = _possibleConstructorReturn(this, _getPrototypeOf(JavaScript).call(this));
- _this.escaped = escaped;
- _this.expression = string;
- _this._index = index;
- _this._fileInfo = currentFileInfo;
- return _this;
- }
-
- _createClass(JavaScript, [{
- key: "eval",
- value: function _eval(context) {
- var result = this.evaluateJavaScript(this.expression, context);
- var type = typeof result;
-
- if (type === 'number' && !isNaN(result)) {
- return new Dimension(result);
- } else if (type === 'string') {
- return new Quoted(`"${result}"`, result, this.escaped, this._index);
- } else if (Array.isArray(result)) {
- return new Anonymous(result.join(', '));
- } else {
- return new Anonymous(result);
- }
- }
- }]);
-
- return JavaScript;
-}(JsEvalNode);
-
-JavaScript.prototype.type = 'JavaScript';
-
-var Assignment =
-/*#__PURE__*/
-function (_Node) {
- _inherits(Assignment, _Node);
-
- function Assignment(key, val) {
- var _this;
-
- _classCallCheck(this, Assignment);
-
- _this = _possibleConstructorReturn(this, _getPrototypeOf(Assignment).call(this));
- _this.key = key;
- _this.value = val;
- return _this;
- }
-
- _createClass(Assignment, [{
- key: "accept",
- value: function accept(visitor) {
- this.value = visitor.visit(this.value);
- }
- }, {
- key: "eval",
- value: function _eval(context) {
- if (this.value.eval) {
- return new Assignment(this.key, this.value.eval(context));
- }
-
- return this;
- }
- }, {
- key: "genCSS",
- value: function genCSS(context, output) {
- output.add(`${this.key}=`);
-
- if (this.value.genCSS) {
- this.value.genCSS(context, output);
- } else {
- output.add(this.value);
- }
- }
- }]);
-
- return Assignment;
-}(Node);
-
-Assignment.prototype.type = 'Assignment';
-
-var Condition =
-/*#__PURE__*/
-function (_Node) {
- _inherits(Condition, _Node);
-
- function Condition(op, l, r, i, negate) {
- var _this;
-
- _classCallCheck(this, Condition);
-
- _this = _possibleConstructorReturn(this, _getPrototypeOf(Condition).call(this));
- _this.op = op.trim();
- _this.lvalue = l;
- _this.rvalue = r;
- _this._index = i;
- _this.negate = negate;
- return _this;
- }
-
- _createClass(Condition, [{
- key: "accept",
- value: function accept(visitor) {
- this.lvalue = visitor.visit(this.lvalue);
- this.rvalue = visitor.visit(this.rvalue);
- }
- }, {
- key: "eval",
- value: function _eval(context) {
- var result = function (op, a, b) {
- switch (op) {
- case 'and':
- return a && b;
-
- case 'or':
- return a || b;
-
- default:
- switch (Node.compare(a, b)) {
- case -1:
- return op === '<' || op === '=<' || op === '<=';
-
- case 0:
- return op === '=' || op === '>=' || op === '=<' || op === '<=';
-
- case 1:
- return op === '>' || op === '>=';
-
- default:
- return false;
- }
-
- }
- }(this.op, this.lvalue.eval(context), this.rvalue.eval(context));
-
- return this.negate ? !result : result;
- }
- }]);
-
- return Condition;
-}(Node);
-
-Condition.prototype.type = 'Condition';
-
-var UnicodeDescriptor =
-/*#__PURE__*/
-function (_Node) {
- _inherits(UnicodeDescriptor, _Node);
-
- function UnicodeDescriptor(value) {
- var _this;
-
- _classCallCheck(this, UnicodeDescriptor);
-
- _this = _possibleConstructorReturn(this, _getPrototypeOf(UnicodeDescriptor).call(this));
- _this.value = value;
- return _this;
- }
-
- return UnicodeDescriptor;
-}(Node);
-
-UnicodeDescriptor.prototype.type = 'UnicodeDescriptor';
-
-var Negative =
-/*#__PURE__*/
-function (_Node) {
- _inherits(Negative, _Node);
-
- function Negative(node) {
- var _this;
-
- _classCallCheck(this, Negative);
-
- _this = _possibleConstructorReturn(this, _getPrototypeOf(Negative).call(this));
- _this.value = node;
- return _this;
- }
-
- _createClass(Negative, [{
- key: "genCSS",
- value: function genCSS(context, output) {
- output.add('-');
- this.value.genCSS(context, output);
- }
- }, {
- key: "eval",
- value: function _eval(context) {
- if (context.isMathOn()) {
- return new Operation('*', [new Dimension(-1), this.value]).eval(context);
- }
-
- return new Negative(this.value.eval(context));
- }
- }]);
-
- return Negative;
-}(Node);
-
-Negative.prototype.type = 'Negative';
-
-var Extend =
-/*#__PURE__*/
-function (_Node) {
- _inherits(Extend, _Node);
-
- function Extend(selector, option, index, currentFileInfo, visibilityInfo) {
- var _this;
-
- _classCallCheck(this, Extend);
-
- _this = _possibleConstructorReturn(this, _getPrototypeOf(Extend).call(this));
- _this.selector = selector;
- _this.option = option;
- _this.object_id = Extend.next_id++;
- _this.parent_ids = [_this.object_id];
- _this._index = index;
- _this._fileInfo = currentFileInfo;
-
- _this.copyVisibilityInfo(visibilityInfo);
-
- _this.allowRoot = true;
-
- switch (option) {
- case 'all':
- _this.allowBefore = true;
- _this.allowAfter = true;
- break;
-
- default:
- _this.allowBefore = false;
- _this.allowAfter = false;
- break;
- }
-
- _this.setParent(_this.selector, _assertThisInitialized(_this));
-
- return _this;
- }
-
- _createClass(Extend, [{
- key: "accept",
- value: function accept(visitor) {
- this.selector = visitor.visit(this.selector);
- }
- }, {
- key: "eval",
- value: function _eval(context) {
- return new Extend(this.selector.eval(context), this.option, this.getIndex(), this.fileInfo(), this.visibilityInfo());
- }
- }, {
- key: "clone",
- value: function clone(context) {
- return new Extend(this.selector, this.option, this.getIndex(), this.fileInfo(), this.visibilityInfo());
- } // it concatenates (joins) all selectors in selector array
-
- }, {
- key: "findSelfSelectors",
- value: function findSelfSelectors(selectors) {
- var selfElements = [];
- var i;
- var selectorElements;
-
- for (i = 0; i < selectors.length; i++) {
- selectorElements = selectors[i].elements; // duplicate the logic in genCSS function inside the selector node.
- // future TODO - move both logics into the selector joiner visitor
-
- if (i > 0 && selectorElements.length && selectorElements[0].combinator.value === '') {
- selectorElements[0].combinator.value = ' ';
- }
-
- selfElements = selfElements.concat(selectors[i].elements);
- }
-
- this.selfSelectors = [new Selector(selfElements)];
- this.selfSelectors[0].copyVisibilityInfo(this.visibilityInfo());
- }
- }]);
-
- return Extend;
-}(Node);
-
-Extend.next_id = 0;
-Extend.prototype.type = 'Extend';
-
-var VariableCall =
-/*#__PURE__*/
-function (_Node) {
- _inherits(VariableCall, _Node);
-
- function VariableCall(variable, index, currentFileInfo) {
- var _this;
-
- _classCallCheck(this, VariableCall);
-
- _this = _possibleConstructorReturn(this, _getPrototypeOf(VariableCall).call(this));
- _this.variable = variable;
- _this._index = index;
- _this._fileInfo = currentFileInfo;
- _this.allowRoot = true;
- return _this;
- }
-
- _createClass(VariableCall, [{
- key: "eval",
- value: function _eval(context) {
- var rules;
- var detachedRuleset = new Variable(this.variable, this.getIndex(), this.fileInfo()).eval(context);
- var error = new LessError({
- message: `Could not evaluate variable call ${this.variable}`
- });
-
- if (!detachedRuleset.ruleset) {
- if (detachedRuleset.rules) {
- rules = detachedRuleset;
- } else if (Array.isArray(detachedRuleset)) {
- rules = new Ruleset('', detachedRuleset);
- } else if (Array.isArray(detachedRuleset.value)) {
- rules = new Ruleset('', detachedRuleset.value);
- } else {
- throw error;
- }
-
- detachedRuleset = new DetachedRuleset(rules);
- }
-
- if (detachedRuleset.ruleset) {
- return detachedRuleset.callEval(context);
- }
-
- throw error;
- }
- }]);
-
- return VariableCall;
-}(Node);
-
-VariableCall.prototype.type = 'VariableCall';
-
-var NamespaceValue =
-/*#__PURE__*/
-function (_Node) {
- _inherits(NamespaceValue, _Node);
-
- function NamespaceValue(ruleCall, lookups, important, index, fileInfo) {
- var _this;
-
- _classCallCheck(this, NamespaceValue);
-
- _this = _possibleConstructorReturn(this, _getPrototypeOf(NamespaceValue).call(this));
- _this.value = ruleCall;
- _this.lookups = lookups;
- _this.important = important;
- _this._index = index;
- _this._fileInfo = fileInfo;
- return _this;
- }
-
- _createClass(NamespaceValue, [{
- key: "eval",
- value: function _eval(context) {
- var i;
- var name;
- var rules = this.value.eval(context);
-
- for (i = 0; i < this.lookups.length; i++) {
- name = this.lookups[i];
- /**
- * Eval'd DRs return rulesets.
- * Eval'd mixins return rules, so let's make a ruleset if we need it.
- * We need to do this because of late parsing of values
- */
-
- if (Array.isArray(rules)) {
- rules = new Ruleset([new Selector()], rules);
- }
-
- if (name === '') {
- rules = rules.lastDeclaration();
- } else if (name.charAt(0) === '@') {
- if (name.charAt(1) === '@') {
- name = `@${new Variable(name.substr(1)).eval(context).value}`;
- }
-
- if (rules.variables) {
- rules = rules.variable(name);
- }
-
- if (!rules) {
- throw {
- type: 'Name',
- message: `variable ${name} not found`,
- filename: this.fileInfo().filename,
- index: this.getIndex()
- };
- }
- } else {
- if (name.substring(0, 2) === '$@') {
- name = `$${new Variable(name.substr(1)).eval(context).value}`;
- } else {
- name = name.charAt(0) === '$' ? name : `$${name}`;
- }
-
- if (rules.properties) {
- rules = rules.property(name);
- }
-
- if (!rules) {
- throw {
- type: 'Name',
- message: `property "${name.substr(1)}" not found`,
- filename: this.fileInfo().filename,
- index: this.getIndex()
- };
- } // Properties are an array of values, since a ruleset can have multiple props.
- // We pick the last one (the "cascaded" value)
-
-
- rules = rules[rules.length - 1];
- }
-
- if (rules.value) {
- rules = rules.eval(context).value;
- }
-
- if (rules.ruleset) {
- rules = rules.ruleset.eval(context);
- }
- }
-
- return rules;
- }
- }]);
-
- return NamespaceValue;
-}(Node);
-
-NamespaceValue.prototype.type = 'NamespaceValue';
-
-var Definition =
-/*#__PURE__*/
-function (_Ruleset) {
- _inherits(Definition, _Ruleset);
-
- function Definition(name, params, rules, condition, variadic, frames, visibilityInfo) {
- var _this;
-
- _classCallCheck(this, Definition);
-
- _this = _possibleConstructorReturn(this, _getPrototypeOf(Definition).call(this));
- _this.name = name || 'anonymous mixin';
- _this.selectors = [new Selector([new Element(null, name, false, _this._index, _this._fileInfo)])];
- _this.params = params;
- _this.condition = condition;
- _this.variadic = variadic;
- _this.arity = params.length;
- _this.rules = rules;
- _this._lookups = {};
- var optionalParameters = [];
- _this.required = params.reduce(function (count, p) {
- if (!p.name || p.name && !p.value) {
- return count + 1;
- } else {
- optionalParameters.push(p.name);
- return count;
- }
- }, 0);
- _this.optionalParameters = optionalParameters;
- _this.frames = frames;
-
- _this.copyVisibilityInfo(visibilityInfo);
-
- _this.allowRoot = true;
- return _this;
- }
-
- _createClass(Definition, [{
- key: "accept",
- value: function accept(visitor) {
- if (this.params && this.params.length) {
- this.params = visitor.visitArray(this.params);
- }
-
- this.rules = visitor.visitArray(this.rules);
-
- if (this.condition) {
- this.condition = visitor.visit(this.condition);
- }
- }
- }, {
- key: "evalParams",
- value: function evalParams(context, mixinEnv, args, evaldArguments) {
- /* jshint boss:true */
- var frame = new Ruleset(null, null);
- var varargs;
- var arg;
- var params = copyArray(this.params);
- var i;
- var j;
- var val;
- var name;
- var isNamedFound;
- var argIndex;
- var argsLength = 0;
-
- if (mixinEnv.frames && mixinEnv.frames[0] && mixinEnv.frames[0].functionRegistry) {
- frame.functionRegistry = mixinEnv.frames[0].functionRegistry.inherit();
- }
-
- mixinEnv = new contexts.Eval(mixinEnv, [frame].concat(mixinEnv.frames));
-
- if (args) {
- args = copyArray(args);
- argsLength = args.length;
-
- for (i = 0; i < argsLength; i++) {
- arg = args[i];
-
- if (name = arg && arg.name) {
- isNamedFound = false;
-
- for (j = 0; j < params.length; j++) {
- if (!evaldArguments[j] && name === params[j].name) {
- evaldArguments[j] = arg.value.eval(context);
- frame.prependRule(new Declaration(name, arg.value.eval(context)));
- isNamedFound = true;
- break;
- }
- }
-
- if (isNamedFound) {
- args.splice(i, 1);
- i--;
- continue;
- } else {
- throw {
- type: 'Runtime',
- message: `Named argument for ${this.name} ${args[i].name} not found`
- };
- }
- }
- }
- }
-
- argIndex = 0;
-
- for (i = 0; i < params.length; i++) {
- if (evaldArguments[i]) {
- continue;
- }
-
- arg = args && args[argIndex];
-
- if (name = params[i].name) {
- if (params[i].variadic) {
- varargs = [];
-
- for (j = argIndex; j < argsLength; j++) {
- varargs.push(args[j].value.eval(context));
- }
-
- frame.prependRule(new Declaration(name, new Expression(varargs).eval(context)));
- } else {
- val = arg && arg.value;
-
- if (val) {
- // This was a mixin call, pass in a detached ruleset of it's eval'd rules
- if (Array.isArray(val)) {
- val = new DetachedRuleset(new Ruleset('', val));
- } else {
- val = val.eval(context);
- }
- } else if (params[i].value) {
- val = params[i].value.eval(mixinEnv);
- frame.resetCache();
- } else {
- throw {
- type: 'Runtime',
- message: `wrong number of arguments for ${this.name} (${argsLength} for ${this.arity})`
- };
- }
-
- frame.prependRule(new Declaration(name, val));
- evaldArguments[i] = val;
- }
- }
-
- if (params[i].variadic && args) {
- for (j = argIndex; j < argsLength; j++) {
- evaldArguments[j] = args[j].value.eval(context);
- }
- }
-
- argIndex++;
- }
-
- return frame;
- }
- }, {
- key: "makeImportant",
- value: function makeImportant() {
- var rules = !this.rules ? this.rules : this.rules.map(function (r) {
- if (r.makeImportant) {
- return r.makeImportant(true);
- } else {
- return r;
- }
- });
- var result = new Definition(this.name, this.params, rules, this.condition, this.variadic, this.frames);
- return result;
- }
- }, {
- key: "eval",
- value: function _eval(context) {
- return new Definition(this.name, this.params, this.rules, this.condition, this.variadic, this.frames || copyArray(context.frames));
- }
- }, {
- key: "evalCall",
- value: function evalCall(context, args, important) {
- var _arguments = [];
- var mixinFrames = this.frames ? this.frames.concat(context.frames) : context.frames;
- var frame = this.evalParams(context, new contexts.Eval(context, mixinFrames), args, _arguments);
- var rules;
- var ruleset;
- frame.prependRule(new Declaration('@arguments', new Expression(_arguments).eval(context)));
- rules = copyArray(this.rules);
- ruleset = new Ruleset(null, rules);
- ruleset.originalRuleset = this;
- ruleset = ruleset.eval(new contexts.Eval(context, [this, frame].concat(mixinFrames)));
-
- if (important) {
- ruleset = ruleset.makeImportant();
- }
-
- return ruleset;
- }
- }, {
- key: "matchCondition",
- value: function matchCondition(args, context) {
- if (this.condition && !this.condition.eval(new contexts.Eval(context, [this.evalParams(context,
- /* the parameter variables */
- new contexts.Eval(context, this.frames ? this.frames.concat(context.frames) : context.frames), args, [])].concat(this.frames || []) // the parent namespace/mixin frames
- .concat(context.frames)))) {
- // the current environment frames
- return false;
- }
-
- return true;
- }
- }, {
- key: "matchArgs",
- value: function matchArgs(args, context) {
- var allArgsCnt = args && args.length || 0;
- var len;
- var optionalParameters = this.optionalParameters;
- var requiredArgsCnt = !args ? 0 : args.reduce(function (count, p) {
- if (optionalParameters.indexOf(p.name) < 0) {
- return count + 1;
- } else {
- return count;
- }
- }, 0);
-
- if (!this.variadic) {
- if (requiredArgsCnt < this.required) {
- return false;
- }
-
- if (allArgsCnt > this.params.length) {
- return false;
- }
- } else {
- if (requiredArgsCnt < this.required - 1) {
- return false;
- }
- } // check patterns
-
-
- len = Math.min(requiredArgsCnt, this.arity);
-
- for (var i = 0; i < len; i++) {
- if (!this.params[i].name && !this.params[i].variadic) {
- if (args[i].value.eval(context).toCSS() != this.params[i].value.eval(context).toCSS()) {
- return false;
- }
- }
- }
-
- return true;
- }
- }]);
-
- return Definition;
-}(Ruleset);
-
-Definition.prototype.type = 'MixinDefinition';
-Definition.prototype.evalFirst = true;
-
-var MixinCall =
-/*#__PURE__*/
-function (_Node) {
- _inherits(MixinCall, _Node);
-
- function MixinCall(elements, args, index, currentFileInfo, important) {
- var _this;
-
- _classCallCheck(this, MixinCall);
-
- _this = _possibleConstructorReturn(this, _getPrototypeOf(MixinCall).call(this));
- _this.selector = new Selector(elements);
- _this.arguments = args || [];
- _this._index = index;
- _this._fileInfo = currentFileInfo;
- _this.important = important;
- _this.allowRoot = true;
-
- _this.setParent(_this.selector, _assertThisInitialized(_this));
-
- return _this;
- }
-
- _createClass(MixinCall, [{
- key: "accept",
- value: function accept(visitor) {
- if (this.selector) {
- this.selector = visitor.visit(this.selector);
- }
-
- if (this.arguments.length) {
- this.arguments = visitor.visitArray(this.arguments);
- }
- }
- }, {
- key: "eval",
- value: function _eval(context) {
- var mixins;
- var mixin;
- var mixinPath;
- var args = [];
- var arg;
- var argValue;
- var rules = [];
- var match = false;
- var i;
- var m;
- var f;
- var isRecursive;
- var isOneFound;
- var candidates = [];
- var candidate;
- var conditionResult = [];
- var defaultResult;
- var defFalseEitherCase = -1;
- var defNone = 0;
- var defTrue = 1;
- var defFalse = 2;
- var count;
- var originalRuleset;
- var noArgumentsFilter;
- this.selector = this.selector.eval(context);
-
- function calcDefGroup(mixin, mixinPath) {
- var f;
- var p;
- var namespace;
-
- for (f = 0; f < 2; f++) {
- conditionResult[f] = true;
- defaultFunc.value(f);
-
- for (p = 0; p < mixinPath.length && conditionResult[f]; p++) {
- namespace = mixinPath[p];
-
- if (namespace.matchCondition) {
- conditionResult[f] = conditionResult[f] && namespace.matchCondition(null, context);
- }
- }
-
- if (mixin.matchCondition) {
- conditionResult[f] = conditionResult[f] && mixin.matchCondition(args, context);
- }
- }
-
- if (conditionResult[0] || conditionResult[1]) {
- if (conditionResult[0] != conditionResult[1]) {
- return conditionResult[1] ? defTrue : defFalse;
- }
-
- return defNone;
- }
-
- return defFalseEitherCase;
- }
-
- for (i = 0; i < this.arguments.length; i++) {
- arg = this.arguments[i];
- argValue = arg.value.eval(context);
-
- if (arg.expand && Array.isArray(argValue.value)) {
- argValue = argValue.value;
-
- for (m = 0; m < argValue.length; m++) {
- args.push({
- value: argValue[m]
- });
- }
- } else {
- args.push({
- name: arg.name,
- value: argValue
- });
- }
- }
-
- noArgumentsFilter = function noArgumentsFilter(rule) {
- return rule.matchArgs(null, context);
- };
-
- for (i = 0; i < context.frames.length; i++) {
- if ((mixins = context.frames[i].find(this.selector, null, noArgumentsFilter)).length > 0) {
- isOneFound = true; // To make `default()` function independent of definition order we have two "subpasses" here.
- // At first we evaluate each guard *twice* (with `default() == true` and `default() == false`),
- // and build candidate list with corresponding flags. Then, when we know all possible matches,
- // we make a final decision.
-
- for (m = 0; m < mixins.length; m++) {
- mixin = mixins[m].rule;
- mixinPath = mixins[m].path;
- isRecursive = false;
-
- for (f = 0; f < context.frames.length; f++) {
- if (!(mixin instanceof Definition) && mixin === (context.frames[f].originalRuleset || context.frames[f])) {
- isRecursive = true;
- break;
- }
- }
-
- if (isRecursive) {
- continue;
- }
-
- if (mixin.matchArgs(args, context)) {
- candidate = {
- mixin,
- group: calcDefGroup(mixin, mixinPath)
- };
-
- if (candidate.group !== defFalseEitherCase) {
- candidates.push(candidate);
- }
-
- match = true;
- }
- }
-
- defaultFunc.reset();
- count = [0, 0, 0];
-
- for (m = 0; m < candidates.length; m++) {
- count[candidates[m].group]++;
- }
-
- if (count[defNone] > 0) {
- defaultResult = defFalse;
- } else {
- defaultResult = defTrue;
-
- if (count[defTrue] + count[defFalse] > 1) {
- throw {
- type: 'Runtime',
- message: `Ambiguous use of \`default()\` found when matching for \`${this.format(args)}\``,
- index: this.getIndex(),
- filename: this.fileInfo().filename
- };
- }
- }
-
- for (m = 0; m < candidates.length; m++) {
- candidate = candidates[m].group;
-
- if (candidate === defNone || candidate === defaultResult) {
- try {
- mixin = candidates[m].mixin;
-
- if (!(mixin instanceof Definition)) {
- originalRuleset = mixin.originalRuleset || mixin;
- mixin = new Definition('', [], mixin.rules, null, false, null, originalRuleset.visibilityInfo());
- mixin.originalRuleset = originalRuleset;
- }
-
- var newRules = mixin.evalCall(context, args, this.important).rules;
-
- this._setVisibilityToReplacement(newRules);
-
- Array.prototype.push.apply(rules, newRules);
- } catch (e) {
- throw {
- message: e.message,
- index: this.getIndex(),
- filename: this.fileInfo().filename,
- stack: e.stack
- };
- }
- }
- }
-
- if (match) {
- return rules;
- }
- }
- }
-
- if (isOneFound) {
- throw {
- type: 'Runtime',
- message: `No matching definition was found for \`${this.format(args)}\``,
- index: this.getIndex(),
- filename: this.fileInfo().filename
- };
- } else {
- throw {
- type: 'Name',
- message: `${this.selector.toCSS().trim()} is undefined`,
- index: this.getIndex(),
- filename: this.fileInfo().filename
- };
- }
- }
- }, {
- key: "_setVisibilityToReplacement",
- value: function _setVisibilityToReplacement(replacement) {
- var i;
- var rule;
-
- if (this.blocksVisibility()) {
- for (i = 0; i < replacement.length; i++) {
- rule = replacement[i];
- rule.addVisibilityBlock();
- }
- }
- }
- }, {
- key: "format",
- value: function format(args) {
- return `${this.selector.toCSS().trim()}(${args ? args.map(function (a) {
- var argValue = '';
-
- if (a.name) {
- argValue += `${a.name}:`;
- }
-
- if (a.value.toCSS) {
- argValue += a.value.toCSS();
- } else {
- argValue += '???';
- }
-
- return argValue;
- }).join(', ') : ''})`;
- }
- }]);
-
- return MixinCall;
-}(Node);
-
-MixinCall.prototype.type = 'MixinCall';
-
-var tree = {
- Node,
- Color,
- AtRule,
- DetachedRuleset,
- Operation,
- Dimension,
- Unit,
- Keyword,
- Variable,
- Property,
- Ruleset,
- Element,
- Attribute,
- Combinator,
- Selector,
- Quoted,
- Expression,
- Declaration,
- Call,
- URL,
- Import,
- Comment,
- Anonymous,
- Value,
- JavaScript,
- Assignment,
- Condition,
- Paren,
- Media,
- UnicodeDescriptor,
- Negative,
- Extend,
- VariableCall,
- NamespaceValue,
- mixin: {
- Call: MixinCall,
- Definition: Definition
- }
-};
-
-var environment$1 =
-/*#__PURE__*/
-function () {
- function environment(externalEnvironment, fileManagers) {
- _classCallCheck(this, environment);
-
- this.fileManagers = fileManagers || [];
- externalEnvironment = externalEnvironment || {};
- var optionalFunctions = ['encodeBase64', 'mimeLookup', 'charsetLookup', 'getSourceMapGenerator'];
- var requiredFunctions = [];
- var functions = requiredFunctions.concat(optionalFunctions);
-
- for (var i = 0; i < functions.length; i++) {
- var propName = functions[i];
- var environmentFunc = externalEnvironment[propName];
-
- if (environmentFunc) {
- this[propName] = environmentFunc.bind(externalEnvironment);
- } else if (i < requiredFunctions.length) {
- this.warn(`missing required function in environment - ${propName}`);
- }
- }
- }
-
- _createClass(environment, [{
- key: "getFileManager",
- value: function getFileManager(filename, currentDirectory, options, environment, isSync) {
- if (!filename) {
- logger.warn('getFileManager called with no filename.. Please report this issue. continuing.');
- }
-
- if (currentDirectory == null) {
- logger.warn('getFileManager called with null directory.. Please report this issue. continuing.');
- }
-
- var fileManagers = this.fileManagers;
-
- if (options.pluginManager) {
- fileManagers = [].concat(fileManagers).concat(options.pluginManager.getFileManagers());
- }
-
- for (var i = fileManagers.length - 1; i >= 0; i--) {
- var fileManager = fileManagers[i];
-
- if (fileManager[isSync ? 'supportsSync' : 'supports'](filename, currentDirectory, options, environment)) {
- return fileManager;
- }
- }
-
- return null;
- }
- }, {
- key: "addFileManager",
- value: function addFileManager(fileManager) {
- this.fileManagers.push(fileManager);
- }
- }, {
- key: "clearFileManagers",
- value: function clearFileManagers() {
- this.fileManagers = [];
- }
- }]);
-
- return environment;
-}();
-
-var AbstractPluginLoader =
-/*#__PURE__*/
-function () {
- function AbstractPluginLoader() {
- _classCallCheck(this, AbstractPluginLoader);
-
- // Implemented by Node.js plugin loader
- this.require = function () {
- return null;
- };
- }
-
- _createClass(AbstractPluginLoader, [{
- key: "evalPlugin",
- value: function evalPlugin(contents, context, imports, pluginOptions, fileInfo) {
- var loader;
- var registry;
- var pluginObj;
- var localModule;
- var pluginManager;
- var filename;
- var result;
- pluginManager = context.pluginManager;
-
- if (fileInfo) {
- if (typeof fileInfo === 'string') {
- filename = fileInfo;
- } else {
- filename = fileInfo.filename;
- }
- }
-
- var shortname = new this.less.FileManager().extractUrlParts(filename).filename;
-
- if (filename) {
- pluginObj = pluginManager.get(filename);
-
- if (pluginObj) {
- result = this.trySetOptions(pluginObj, filename, shortname, pluginOptions);
-
- if (result) {
- return result;
- }
-
- try {
- if (pluginObj.use) {
- pluginObj.use.call(this.context, pluginObj);
- }
- } catch (e) {
- e.message = e.message || 'Error during @plugin call';
- return new LessError(e, imports, filename);
- }
-
- return pluginObj;
- }
- }
-
- localModule = {
- exports: {},
- pluginManager,
- fileInfo
- };
- registry = functionRegistry.create();
-
- var registerPlugin = function registerPlugin(obj) {
- pluginObj = obj;
- };
-
- try {
- loader = new Function('module', 'require', 'registerPlugin', 'functions', 'tree', 'less', 'fileInfo', contents);
- loader(localModule, this.require(filename), registerPlugin, registry, this.less.tree, this.less, fileInfo);
- } catch (e) {
- return new LessError(e, imports, filename);
- }
-
- if (!pluginObj) {
- pluginObj = localModule.exports;
- }
-
- pluginObj = this.validatePlugin(pluginObj, filename, shortname);
-
- if (pluginObj instanceof LessError) {
- return pluginObj;
- }
-
- if (pluginObj) {
- pluginObj.imports = imports;
- pluginObj.filename = filename; // For < 3.x (or unspecified minVersion) - setOptions() before install()
-
- if (!pluginObj.minVersion || this.compareVersion('3.0.0', pluginObj.minVersion) < 0) {
- result = this.trySetOptions(pluginObj, filename, shortname, pluginOptions);
-
- if (result) {
- return result;
- }
- } // Run on first load
-
-
- pluginManager.addPlugin(pluginObj, fileInfo.filename, registry);
- pluginObj.functions = registry.getLocalFunctions(); // Need to call setOptions again because the pluginObj might have functions
-
- result = this.trySetOptions(pluginObj, filename, shortname, pluginOptions);
-
- if (result) {
- return result;
- } // Run every @plugin call
-
-
- try {
- if (pluginObj.use) {
- pluginObj.use.call(this.context, pluginObj);
- }
- } catch (e) {
- e.message = e.message || 'Error during @plugin call';
- return new LessError(e, imports, filename);
- }
- } else {
- return new LessError({
- message: 'Not a valid plugin'
- }, imports, filename);
- }
-
- return pluginObj;
- }
- }, {
- key: "trySetOptions",
- value: function trySetOptions(plugin, filename, name, options) {
- if (options && !plugin.setOptions) {
- return new LessError({
- message: `Options have been provided but the plugin ${name} does not support any options.`
- });
- }
-
- try {
- plugin.setOptions && plugin.setOptions(options);
- } catch (e) {
- return new LessError(e);
- }
- }
- }, {
- key: "validatePlugin",
- value: function validatePlugin(plugin, filename, name) {
- if (plugin) {
- // support plugins being a function
- // so that the plugin can be more usable programmatically
- if (typeof plugin === 'function') {
- plugin = new plugin();
- }
-
- if (plugin.minVersion) {
- if (this.compareVersion(plugin.minVersion, this.less.version) < 0) {
- return new LessError({
- message: `Plugin ${name} requires version ${this.versionToString(plugin.minVersion)}`
- });
- }
- }
-
- return plugin;
- }
-
- return null;
- }
- }, {
- key: "compareVersion",
- value: function compareVersion(aVersion, bVersion) {
- if (typeof aVersion === 'string') {
- aVersion = aVersion.match(/^(\d+)\.?(\d+)?\.?(\d+)?/);
- aVersion.shift();
- }
-
- for (var i = 0; i < aVersion.length; i++) {
- if (aVersion[i] !== bVersion[i]) {
- return parseInt(aVersion[i]) > parseInt(bVersion[i]) ? -1 : 1;
- }
- }
-
- return 0;
- }
- }, {
- key: "versionToString",
- value: function versionToString(version) {
- var versionString = '';
-
- for (var i = 0; i < version.length; i++) {
- versionString += (versionString ? '.' : '') + version[i];
- }
-
- return versionString;
- }
- }, {
- key: "printUsage",
- value: function printUsage(plugins) {
- for (var i = 0; i < plugins.length; i++) {
- var plugin = plugins[i];
-
- if (plugin.printUsage) {
- plugin.printUsage();
- }
- }
- }
- }]);
-
- return AbstractPluginLoader;
-}();
-
-var _visitArgs = {
- visitDeeper: true
-};
-var _hasIndexed = false;
-
-function _noop(node) {
- return node;
-}
-
-function indexNodeTypes(parent, ticker) {
- // add .typeIndex to tree node types for lookup table
- var key;
- var child;
-
- for (key in parent) {
- /* eslint guard-for-in: 0 */
- child = parent[key];
-
- switch (typeof child) {
- case 'function':
- // ignore bound functions directly on tree which do not have a prototype
- // or aren't nodes
- if (child.prototype && child.prototype.type) {
- child.prototype.typeIndex = ticker++;
- }
-
- break;
-
- case 'object':
- ticker = indexNodeTypes(child, ticker);
- break;
- }
- }
-
- return ticker;
-}
-
-var Visitor =
-/*#__PURE__*/
-function () {
- function Visitor(implementation) {
- _classCallCheck(this, Visitor);
-
- this._implementation = implementation;
- this._visitInCache = {};
- this._visitOutCache = {};
-
- if (!_hasIndexed) {
- indexNodeTypes(tree, 1);
- _hasIndexed = true;
- }
- }
-
- _createClass(Visitor, [{
- key: "visit",
- value: function visit(node) {
- if (!node) {
- return node;
- }
-
- var nodeTypeIndex = node.typeIndex;
-
- if (!nodeTypeIndex) {
- // MixinCall args aren't a node type?
- if (node.value && node.value.typeIndex) {
- this.visit(node.value);
- }
-
- return node;
- }
-
- var impl = this._implementation;
- var func = this._visitInCache[nodeTypeIndex];
- var funcOut = this._visitOutCache[nodeTypeIndex];
- var visitArgs = _visitArgs;
- var fnName;
- visitArgs.visitDeeper = true;
-
- if (!func) {
- fnName = `visit${node.type}`;
- func = impl[fnName] || _noop;
- funcOut = impl[`${fnName}Out`] || _noop;
- this._visitInCache[nodeTypeIndex] = func;
- this._visitOutCache[nodeTypeIndex] = funcOut;
- }
-
- if (func !== _noop) {
- var newNode = func.call(impl, node, visitArgs);
-
- if (node && impl.isReplacing) {
- node = newNode;
- }
- }
-
- if (visitArgs.visitDeeper && node && node.accept) {
- node.accept(this);
- }
-
- if (funcOut != _noop) {
- funcOut.call(impl, node);
- }
-
- return node;
- }
- }, {
- key: "visitArray",
- value: function visitArray(nodes, nonReplacing) {
- if (!nodes) {
- return nodes;
- }
-
- var cnt = nodes.length;
- var i; // Non-replacing
-
- if (nonReplacing || !this._implementation.isReplacing) {
- for (i = 0; i < cnt; i++) {
- this.visit(nodes[i]);
- }
-
- return nodes;
- } // Replacing
-
-
- var out = [];
-
- for (i = 0; i < cnt; i++) {
- var evald = this.visit(nodes[i]);
-
- if (evald === undefined) {
- continue;
- }
-
- if (!evald.splice) {
- out.push(evald);
- } else if (evald.length) {
- this.flatten(evald, out);
- }
- }
-
- return out;
- }
- }, {
- key: "flatten",
- value: function flatten(arr, out) {
- if (!out) {
- out = [];
- }
-
- var cnt;
- var i;
- var item;
- var nestedCnt;
- var j;
- var nestedItem;
-
- for (i = 0, cnt = arr.length; i < cnt; i++) {
- item = arr[i];
-
- if (item === undefined) {
- continue;
- }
-
- if (!item.splice) {
- out.push(item);
- continue;
- }
-
- for (j = 0, nestedCnt = item.length; j < nestedCnt; j++) {
- nestedItem = item[j];
-
- if (nestedItem === undefined) {
- continue;
- }
-
- if (!nestedItem.splice) {
- out.push(nestedItem);
- } else if (nestedItem.length) {
- this.flatten(nestedItem, out);
- }
- }
- }
-
- return out;
- }
- }]);
-
- return Visitor;
-}();
-
-var ImportSequencer =
-/*#__PURE__*/
-function () {
- function ImportSequencer(onSequencerEmpty) {
- _classCallCheck(this, ImportSequencer);
-
- this.imports = [];
- this.variableImports = [];
- this._onSequencerEmpty = onSequencerEmpty;
- this._currentDepth = 0;
- }
-
- _createClass(ImportSequencer, [{
- key: "addImport",
- value: function addImport(callback) {
- var importSequencer = this;
- var importItem = {
- callback,
- args: null,
- isReady: false
- };
- this.imports.push(importItem);
- return function () {
- for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
- args[_key] = arguments[_key];
- }
-
- importItem.args = Array.prototype.slice.call(args, 0);
- importItem.isReady = true;
- importSequencer.tryRun();
- };
- }
- }, {
- key: "addVariableImport",
- value: function addVariableImport(callback) {
- this.variableImports.push(callback);
- }
- }, {
- key: "tryRun",
- value: function tryRun() {
- this._currentDepth++;
-
- try {
- while (true) {
- while (this.imports.length > 0) {
- var importItem = this.imports[0];
-
- if (!importItem.isReady) {
- return;
- }
-
- this.imports = this.imports.slice(1);
- importItem.callback.apply(null, importItem.args);
- }
-
- if (this.variableImports.length === 0) {
- break;
- }
-
- var variableImport = this.variableImports[0];
- this.variableImports = this.variableImports.slice(1);
- variableImport();
- }
- } finally {
- this._currentDepth--;
- }
-
- if (this._currentDepth === 0 && this._onSequencerEmpty) {
- this._onSequencerEmpty();
- }
- }
- }]);
-
- return ImportSequencer;
-}();
-
-var ImportVisitor = function ImportVisitor(importer, finish) {
- this._visitor = new Visitor(this);
- this._importer = importer;
- this._finish = finish;
- this.context = new contexts.Eval();
- this.importCount = 0;
- this.onceFileDetectionMap = {};
- this.recursionDetector = {};
- this._sequencer = new ImportSequencer(this._onSequencerEmpty.bind(this));
-};
-
-ImportVisitor.prototype = {
- isReplacing: false,
- run: function run(root) {
- try {
- // process the contents
- this._visitor.visit(root);
- } catch (e) {
- this.error = e;
- }
-
- this.isFinished = true;
-
- this._sequencer.tryRun();
- },
- _onSequencerEmpty: function _onSequencerEmpty() {
- if (!this.isFinished) {
- return;
- }
-
- this._finish(this.error);
- },
- visitImport: function visitImport(importNode, visitArgs) {
- var inlineCSS = importNode.options.inline;
-
- if (!importNode.css || inlineCSS) {
- var context = new contexts.Eval(this.context, copyArray(this.context.frames));
- var importParent = context.frames[0];
- this.importCount++;
-
- if (importNode.isVariableImport()) {
- this._sequencer.addVariableImport(this.processImportNode.bind(this, importNode, context, importParent));
- } else {
- this.processImportNode(importNode, context, importParent);
- }
- }
-
- visitArgs.visitDeeper = false;
- },
- processImportNode: function processImportNode(importNode, context, importParent) {
- var evaldImportNode;
- var inlineCSS = importNode.options.inline;
-
- try {
- evaldImportNode = importNode.evalForImport(context);
- } catch (e) {
- if (!e.filename) {
- e.index = importNode.getIndex();
- e.filename = importNode.fileInfo().filename;
- } // attempt to eval properly and treat as css
-
-
- importNode.css = true; // if that fails, this error will be thrown
-
- importNode.error = e;
- }
-
- if (evaldImportNode && (!evaldImportNode.css || inlineCSS)) {
- if (evaldImportNode.options.multiple) {
- context.importMultiple = true;
- } // try appending if we haven't determined if it is css or not
-
-
- var tryAppendLessExtension = evaldImportNode.css === undefined;
-
- for (var i = 0; i < importParent.rules.length; i++) {
- if (importParent.rules[i] === importNode) {
- importParent.rules[i] = evaldImportNode;
- break;
- }
- }
-
- var onImported = this.onImported.bind(this, evaldImportNode, context);
-
- var sequencedOnImported = this._sequencer.addImport(onImported);
-
- this._importer.push(evaldImportNode.getPath(), tryAppendLessExtension, evaldImportNode.fileInfo(), evaldImportNode.options, sequencedOnImported);
- } else {
- this.importCount--;
-
- if (this.isFinished) {
- this._sequencer.tryRun();
- }
- }
- },
- onImported: function onImported(importNode, context, e, root, importedAtRoot, fullPath) {
- if (e) {
- if (!e.filename) {
- e.index = importNode.getIndex();
- e.filename = importNode.fileInfo().filename;
- }
-
- this.error = e;
- }
-
- var importVisitor = this;
- var inlineCSS = importNode.options.inline;
- var isPlugin = importNode.options.isPlugin;
- var isOptional = importNode.options.optional;
- var duplicateImport = importedAtRoot || fullPath in importVisitor.recursionDetector;
-
- if (!context.importMultiple) {
- if (duplicateImport) {
- importNode.skip = true;
- } else {
- importNode.skip = function () {
- if (fullPath in importVisitor.onceFileDetectionMap) {
- return true;
- }
-
- importVisitor.onceFileDetectionMap[fullPath] = true;
- return false;
- };
- }
- }
-
- if (!fullPath && isOptional) {
- importNode.skip = true;
- }
-
- if (root) {
- importNode.root = root;
- importNode.importedFilename = fullPath;
-
- if (!inlineCSS && !isPlugin && (context.importMultiple || !duplicateImport)) {
- importVisitor.recursionDetector[fullPath] = true;
- var oldContext = this.context;
- this.context = context;
-
- try {
- this._visitor.visit(root);
- } catch (e) {
- this.error = e;
- }
-
- this.context = oldContext;
- }
- }
-
- importVisitor.importCount--;
-
- if (importVisitor.isFinished) {
- importVisitor._sequencer.tryRun();
- }
- },
- visitDeclaration: function visitDeclaration(declNode, visitArgs) {
- if (declNode.value.type === 'DetachedRuleset') {
- this.context.frames.unshift(declNode);
- } else {
- visitArgs.visitDeeper = false;
- }
- },
- visitDeclarationOut: function visitDeclarationOut(declNode) {
- if (declNode.value.type === 'DetachedRuleset') {
- this.context.frames.shift();
- }
- },
- visitAtRule: function visitAtRule(atRuleNode, visitArgs) {
- this.context.frames.unshift(atRuleNode);
- },
- visitAtRuleOut: function visitAtRuleOut(atRuleNode) {
- this.context.frames.shift();
- },
- visitMixinDefinition: function visitMixinDefinition(mixinDefinitionNode, visitArgs) {
- this.context.frames.unshift(mixinDefinitionNode);
- },
- visitMixinDefinitionOut: function visitMixinDefinitionOut(mixinDefinitionNode) {
- this.context.frames.shift();
- },
- visitRuleset: function visitRuleset(rulesetNode, visitArgs) {
- this.context.frames.unshift(rulesetNode);
- },
- visitRulesetOut: function visitRulesetOut(rulesetNode) {
- this.context.frames.shift();
- },
- visitMedia: function visitMedia(mediaNode, visitArgs) {
- this.context.frames.unshift(mediaNode.rules[0]);
- },
- visitMediaOut: function visitMediaOut(mediaNode) {
- this.context.frames.shift();
- }
-};
-
-var SetTreeVisibilityVisitor =
-/*#__PURE__*/
-function () {
- function SetTreeVisibilityVisitor(visible) {
- _classCallCheck(this, SetTreeVisibilityVisitor);
-
- this.visible = visible;
- }
-
- _createClass(SetTreeVisibilityVisitor, [{
- key: "run",
- value: function run(root) {
- this.visit(root);
- }
- }, {
- key: "visitArray",
- value: function visitArray(nodes) {
- if (!nodes) {
- return nodes;
- }
-
- var cnt = nodes.length;
- var i;
-
- for (i = 0; i < cnt; i++) {
- this.visit(nodes[i]);
- }
-
- return nodes;
- }
- }, {
- key: "visit",
- value: function visit(node) {
- if (!node) {
- return node;
- }
-
- if (node.constructor === Array) {
- return this.visitArray(node);
- }
-
- if (!node.blocksVisibility || node.blocksVisibility()) {
- return node;
- }
-
- if (this.visible) {
- node.ensureVisibility();
- } else {
- node.ensureInvisibility();
- }
-
- node.accept(this);
- return node;
- }
- }]);
-
- return SetTreeVisibilityVisitor;
-}();
-
-/* jshint loopfunc:true */
-
-var ExtendFinderVisitor =
-/*#__PURE__*/
-function () {
- function ExtendFinderVisitor() {
- _classCallCheck(this, ExtendFinderVisitor);
-
- this._visitor = new Visitor(this);
- this.contexts = [];
- this.allExtendsStack = [[]];
- }
-
- _createClass(ExtendFinderVisitor, [{
- key: "run",
- value: function run(root) {
- root = this._visitor.visit(root);
- root.allExtends = this.allExtendsStack[0];
- return root;
- }
- }, {
- key: "visitDeclaration",
- value: function visitDeclaration(declNode, visitArgs) {
- visitArgs.visitDeeper = false;
- }
- }, {
- key: "visitMixinDefinition",
- value: function visitMixinDefinition(mixinDefinitionNode, visitArgs) {
- visitArgs.visitDeeper = false;
- }
- }, {
- key: "visitRuleset",
- value: function visitRuleset(rulesetNode, visitArgs) {
- if (rulesetNode.root) {
- return;
- }
-
- var i;
- var j;
- var extend;
- var allSelectorsExtendList = [];
- var extendList; // get &:extend(.a); rules which apply to all selectors in this ruleset
-
- var rules = rulesetNode.rules;
- var ruleCnt = rules ? rules.length : 0;
-
- for (i = 0; i < ruleCnt; i++) {
- if (rulesetNode.rules[i] instanceof tree.Extend) {
- allSelectorsExtendList.push(rules[i]);
- rulesetNode.extendOnEveryPath = true;
- }
- } // now find every selector and apply the extends that apply to all extends
- // and the ones which apply to an individual extend
-
-
- var paths = rulesetNode.paths;
-
- for (i = 0; i < paths.length; i++) {
- var selectorPath = paths[i];
- var selector = selectorPath[selectorPath.length - 1];
- var selExtendList = selector.extendList;
- extendList = selExtendList ? copyArray(selExtendList).concat(allSelectorsExtendList) : allSelectorsExtendList;
-
- if (extendList) {
- extendList = extendList.map(function (allSelectorsExtend) {
- return allSelectorsExtend.clone();
- });
- }
-
- for (j = 0; j < extendList.length; j++) {
- this.foundExtends = true;
- extend = extendList[j];
- extend.findSelfSelectors(selectorPath);
- extend.ruleset = rulesetNode;
-
- if (j === 0) {
- extend.firstExtendOnThisSelectorPath = true;
- }
-
- this.allExtendsStack[this.allExtendsStack.length - 1].push(extend);
- }
- }
-
- this.contexts.push(rulesetNode.selectors);
- }
- }, {
- key: "visitRulesetOut",
- value: function visitRulesetOut(rulesetNode) {
- if (!rulesetNode.root) {
- this.contexts.length = this.contexts.length - 1;
- }
- }
- }, {
- key: "visitMedia",
- value: function visitMedia(mediaNode, visitArgs) {
- mediaNode.allExtends = [];
- this.allExtendsStack.push(mediaNode.allExtends);
- }
- }, {
- key: "visitMediaOut",
- value: function visitMediaOut(mediaNode) {
- this.allExtendsStack.length = this.allExtendsStack.length - 1;
- }
- }, {
- key: "visitAtRule",
- value: function visitAtRule(atRuleNode, visitArgs) {
- atRuleNode.allExtends = [];
- this.allExtendsStack.push(atRuleNode.allExtends);
- }
- }, {
- key: "visitAtRuleOut",
- value: function visitAtRuleOut(atRuleNode) {
- this.allExtendsStack.length = this.allExtendsStack.length - 1;
- }
- }]);
-
- return ExtendFinderVisitor;
-}();
-
-var ProcessExtendsVisitor =
-/*#__PURE__*/
-function () {
- function ProcessExtendsVisitor() {
- _classCallCheck(this, ProcessExtendsVisitor);
-
- this._visitor = new Visitor(this);
- }
-
- _createClass(ProcessExtendsVisitor, [{
- key: "run",
- value: function run(root) {
- var extendFinder = new ExtendFinderVisitor();
- this.extendIndices = {};
- extendFinder.run(root);
-
- if (!extendFinder.foundExtends) {
- return root;
- }
-
- root.allExtends = root.allExtends.concat(this.doExtendChaining(root.allExtends, root.allExtends));
- this.allExtendsStack = [root.allExtends];
-
- var newRoot = this._visitor.visit(root);
-
- this.checkExtendsForNonMatched(root.allExtends);
- return newRoot;
- }
- }, {
- key: "checkExtendsForNonMatched",
- value: function checkExtendsForNonMatched(extendList) {
- var indices = this.extendIndices;
- extendList.filter(function (extend) {
- return !extend.hasFoundMatches && extend.parent_ids.length == 1;
- }).forEach(function (extend) {
- var selector = '_unknown_';
-
- try {
- selector = extend.selector.toCSS({});
- } catch (_) {}
-
- if (!indices[`${extend.index} ${selector}`]) {
- indices[`${extend.index} ${selector}`] = true;
- logger.warn(`extend '${selector}' has no matches`);
- }
- });
- }
- }, {
- key: "doExtendChaining",
- value: function doExtendChaining(extendsList, extendsListTarget, iterationCount) {
- //
- // chaining is different from normal extension.. if we extend an extend then we are not just copying, altering
- // and pasting the selector we would do normally, but we are also adding an extend with the same target selector
- // this means this new extend can then go and alter other extends
- //
- // this method deals with all the chaining work - without it, extend is flat and doesn't work on other extend selectors
- // this is also the most expensive.. and a match on one selector can cause an extension of a selector we had already
- // processed if we look at each selector at a time, as is done in visitRuleset
- var extendIndex;
- var targetExtendIndex;
- var matches;
- var extendsToAdd = [];
- var newSelector;
- var extendVisitor = this;
- var selectorPath;
- var extend;
- var targetExtend;
- var newExtend;
- iterationCount = iterationCount || 0; // loop through comparing every extend with every target extend.
- // a target extend is the one on the ruleset we are looking at copy/edit/pasting in place
- // e.g. .a:extend(.b) {} and .b:extend(.c) {} then the first extend extends the second one
- // and the second is the target.
- // the separation into two lists allows us to process a subset of chains with a bigger set, as is the
- // case when processing media queries
-
- for (extendIndex = 0; extendIndex < extendsList.length; extendIndex++) {
- for (targetExtendIndex = 0; targetExtendIndex < extendsListTarget.length; targetExtendIndex++) {
- extend = extendsList[extendIndex];
- targetExtend = extendsListTarget[targetExtendIndex]; // look for circular references
-
- if (extend.parent_ids.indexOf(targetExtend.object_id) >= 0) {
- continue;
- } // find a match in the target extends self selector (the bit before :extend)
-
-
- selectorPath = [targetExtend.selfSelectors[0]];
- matches = extendVisitor.findMatch(extend, selectorPath);
-
- if (matches.length) {
- extend.hasFoundMatches = true; // we found a match, so for each self selector..
-
- extend.selfSelectors.forEach(function (selfSelector) {
- var info = targetExtend.visibilityInfo(); // process the extend as usual
-
- newSelector = extendVisitor.extendSelector(matches, selectorPath, selfSelector, extend.isVisible()); // but now we create a new extend from it
-
- newExtend = new tree.Extend(targetExtend.selector, targetExtend.option, 0, targetExtend.fileInfo(), info);
- newExtend.selfSelectors = newSelector; // add the extend onto the list of extends for that selector
-
- newSelector[newSelector.length - 1].extendList = [newExtend]; // record that we need to add it.
-
- extendsToAdd.push(newExtend);
- newExtend.ruleset = targetExtend.ruleset; // remember its parents for circular references
-
- newExtend.parent_ids = newExtend.parent_ids.concat(targetExtend.parent_ids, extend.parent_ids); // only process the selector once.. if we have :extend(.a,.b) then multiple
- // extends will look at the same selector path, so when extending
- // we know that any others will be duplicates in terms of what is added to the css
-
- if (targetExtend.firstExtendOnThisSelectorPath) {
- newExtend.firstExtendOnThisSelectorPath = true;
- targetExtend.ruleset.paths.push(newSelector);
- }
- });
- }
- }
- }
-
- if (extendsToAdd.length) {
- // try to detect circular references to stop a stack overflow.
- // may no longer be needed.
- this.extendChainCount++;
-
- if (iterationCount > 100) {
- var selectorOne = '{unable to calculate}';
- var selectorTwo = '{unable to calculate}';
-
- try {
- selectorOne = extendsToAdd[0].selfSelectors[0].toCSS();
- selectorTwo = extendsToAdd[0].selector.toCSS();
- } catch (e) {}
-
- throw {
- message: `extend circular reference detected. One of the circular extends is currently:${selectorOne}:extend(${selectorTwo})`
- };
- } // now process the new extends on the existing rules so that we can handle a extending b extending c extending
- // d extending e...
-
-
- return extendsToAdd.concat(extendVisitor.doExtendChaining(extendsToAdd, extendsListTarget, iterationCount + 1));
- } else {
- return extendsToAdd;
- }
- }
- }, {
- key: "visitDeclaration",
- value: function visitDeclaration(ruleNode, visitArgs) {
- visitArgs.visitDeeper = false;
- }
- }, {
- key: "visitMixinDefinition",
- value: function visitMixinDefinition(mixinDefinitionNode, visitArgs) {
- visitArgs.visitDeeper = false;
- }
- }, {
- key: "visitSelector",
- value: function visitSelector(selectorNode, visitArgs) {
- visitArgs.visitDeeper = false;
- }
- }, {
- key: "visitRuleset",
- value: function visitRuleset(rulesetNode, visitArgs) {
- if (rulesetNode.root) {
- return;
- }
-
- var matches;
- var pathIndex;
- var extendIndex;
- var allExtends = this.allExtendsStack[this.allExtendsStack.length - 1];
- var selectorsToAdd = [];
- var extendVisitor = this;
- var selectorPath; // look at each selector path in the ruleset, find any extend matches and then copy, find and replace
-
- for (extendIndex = 0; extendIndex < allExtends.length; extendIndex++) {
- for (pathIndex = 0; pathIndex < rulesetNode.paths.length; pathIndex++) {
- selectorPath = rulesetNode.paths[pathIndex]; // extending extends happens initially, before the main pass
-
- if (rulesetNode.extendOnEveryPath) {
- continue;
- }
-
- var extendList = selectorPath[selectorPath.length - 1].extendList;
-
- if (extendList && extendList.length) {
- continue;
- }
-
- matches = this.findMatch(allExtends[extendIndex], selectorPath);
-
- if (matches.length) {
- allExtends[extendIndex].hasFoundMatches = true;
- allExtends[extendIndex].selfSelectors.forEach(function (selfSelector) {
- var extendedSelectors;
- extendedSelectors = extendVisitor.extendSelector(matches, selectorPath, selfSelector, allExtends[extendIndex].isVisible());
- selectorsToAdd.push(extendedSelectors);
- });
- }
- }
- }
-
- rulesetNode.paths = rulesetNode.paths.concat(selectorsToAdd);
- }
- }, {
- key: "findMatch",
- value: function findMatch(extend, haystackSelectorPath) {
- //
- // look through the haystack selector path to try and find the needle - extend.selector
- // returns an array of selector matches that can then be replaced
- //
- var haystackSelectorIndex;
- var hackstackSelector;
- var hackstackElementIndex;
- var haystackElement;
- var targetCombinator;
- var i;
- var extendVisitor = this;
- var needleElements = extend.selector.elements;
- var potentialMatches = [];
- var potentialMatch;
- var matches = []; // loop through the haystack elements
-
- for (haystackSelectorIndex = 0; haystackSelectorIndex < haystackSelectorPath.length; haystackSelectorIndex++) {
- hackstackSelector = haystackSelectorPath[haystackSelectorIndex];
-
- for (hackstackElementIndex = 0; hackstackElementIndex < hackstackSelector.elements.length; hackstackElementIndex++) {
- haystackElement = hackstackSelector.elements[hackstackElementIndex]; // if we allow elements before our match we can add a potential match every time. otherwise only at the first element.
-
- if (extend.allowBefore || haystackSelectorIndex === 0 && hackstackElementIndex === 0) {
- potentialMatches.push({
- pathIndex: haystackSelectorIndex,
- index: hackstackElementIndex,
- matched: 0,
- initialCombinator: haystackElement.combinator
- });
- }
-
- for (i = 0; i < potentialMatches.length; i++) {
- potentialMatch = potentialMatches[i]; // selectors add " " onto the first element. When we use & it joins the selectors together, but if we don't
- // then each selector in haystackSelectorPath has a space before it added in the toCSS phase. so we need to
- // work out what the resulting combinator will be
-
- targetCombinator = haystackElement.combinator.value;
-
- if (targetCombinator === '' && hackstackElementIndex === 0) {
- targetCombinator = ' ';
- } // if we don't match, null our match to indicate failure
-
-
- if (!extendVisitor.isElementValuesEqual(needleElements[potentialMatch.matched].value, haystackElement.value) || potentialMatch.matched > 0 && needleElements[potentialMatch.matched].combinator.value !== targetCombinator) {
- potentialMatch = null;
- } else {
- potentialMatch.matched++;
- } // if we are still valid and have finished, test whether we have elements after and whether these are allowed
-
-
- if (potentialMatch) {
- potentialMatch.finished = potentialMatch.matched === needleElements.length;
-
- if (potentialMatch.finished && !extend.allowAfter && (hackstackElementIndex + 1 < hackstackSelector.elements.length || haystackSelectorIndex + 1 < haystackSelectorPath.length)) {
- potentialMatch = null;
- }
- } // if null we remove, if not, we are still valid, so either push as a valid match or continue
-
-
- if (potentialMatch) {
- if (potentialMatch.finished) {
- potentialMatch.length = needleElements.length;
- potentialMatch.endPathIndex = haystackSelectorIndex;
- potentialMatch.endPathElementIndex = hackstackElementIndex + 1; // index after end of match
-
- potentialMatches.length = 0; // we don't allow matches to overlap, so start matching again
-
- matches.push(potentialMatch);
- }
- } else {
- potentialMatches.splice(i, 1);
- i--;
- }
- }
- }
- }
-
- return matches;
- }
- }, {
- key: "isElementValuesEqual",
- value: function isElementValuesEqual(elementValue1, elementValue2) {
- if (typeof elementValue1 === 'string' || typeof elementValue2 === 'string') {
- return elementValue1 === elementValue2;
- }
-
- if (elementValue1 instanceof tree.Attribute) {
- if (elementValue1.op !== elementValue2.op || elementValue1.key !== elementValue2.key) {
- return false;
- }
-
- if (!elementValue1.value || !elementValue2.value) {
- if (elementValue1.value || elementValue2.value) {
- return false;
- }
-
- return true;
- }
-
- elementValue1 = elementValue1.value.value || elementValue1.value;
- elementValue2 = elementValue2.value.value || elementValue2.value;
- return elementValue1 === elementValue2;
- }
-
- elementValue1 = elementValue1.value;
- elementValue2 = elementValue2.value;
-
- if (elementValue1 instanceof tree.Selector) {
- if (!(elementValue2 instanceof tree.Selector) || elementValue1.elements.length !== elementValue2.elements.length) {
- return false;
- }
-
- for (var i = 0; i < elementValue1.elements.length; i++) {
- if (elementValue1.elements[i].combinator.value !== elementValue2.elements[i].combinator.value) {
- if (i !== 0 || (elementValue1.elements[i].combinator.value || ' ') !== (elementValue2.elements[i].combinator.value || ' ')) {
- return false;
- }
- }
-
- if (!this.isElementValuesEqual(elementValue1.elements[i].value, elementValue2.elements[i].value)) {
- return false;
- }
- }
-
- return true;
- }
-
- return false;
- }
- }, {
- key: "extendSelector",
- value: function extendSelector(matches, selectorPath, replacementSelector, isVisible) {
- // for a set of matches, replace each match with the replacement selector
- var currentSelectorPathIndex = 0;
- var currentSelectorPathElementIndex = 0;
- var path = [];
- var matchIndex;
- var selector;
- var firstElement;
- var match;
- var newElements;
-
- for (matchIndex = 0; matchIndex < matches.length; matchIndex++) {
- match = matches[matchIndex];
- selector = selectorPath[match.pathIndex];
- firstElement = new tree.Element(match.initialCombinator, replacementSelector.elements[0].value, replacementSelector.elements[0].isVariable, replacementSelector.elements[0].getIndex(), replacementSelector.elements[0].fileInfo());
-
- if (match.pathIndex > currentSelectorPathIndex && currentSelectorPathElementIndex > 0) {
- path[path.length - 1].elements = path[path.length - 1].elements.concat(selectorPath[currentSelectorPathIndex].elements.slice(currentSelectorPathElementIndex));
- currentSelectorPathElementIndex = 0;
- currentSelectorPathIndex++;
- }
-
- newElements = selector.elements.slice(currentSelectorPathElementIndex, match.index).concat([firstElement]).concat(replacementSelector.elements.slice(1));
-
- if (currentSelectorPathIndex === match.pathIndex && matchIndex > 0) {
- path[path.length - 1].elements = path[path.length - 1].elements.concat(newElements);
- } else {
- path = path.concat(selectorPath.slice(currentSelectorPathIndex, match.pathIndex));
- path.push(new tree.Selector(newElements));
- }
-
- currentSelectorPathIndex = match.endPathIndex;
- currentSelectorPathElementIndex = match.endPathElementIndex;
-
- if (currentSelectorPathElementIndex >= selectorPath[currentSelectorPathIndex].elements.length) {
- currentSelectorPathElementIndex = 0;
- currentSelectorPathIndex++;
- }
- }
-
- if (currentSelectorPathIndex < selectorPath.length && currentSelectorPathElementIndex > 0) {
- path[path.length - 1].elements = path[path.length - 1].elements.concat(selectorPath[currentSelectorPathIndex].elements.slice(currentSelectorPathElementIndex));
- currentSelectorPathIndex++;
- }
-
- path = path.concat(selectorPath.slice(currentSelectorPathIndex, selectorPath.length));
- path = path.map(function (currentValue) {
- // we can re-use elements here, because the visibility property matters only for selectors
- var derived = currentValue.createDerived(currentValue.elements);
-
- if (isVisible) {
- derived.ensureVisibility();
- } else {
- derived.ensureInvisibility();
- }
-
- return derived;
- });
- return path;
- }
- }, {
- key: "visitMedia",
- value: function visitMedia(mediaNode, visitArgs) {
- var newAllExtends = mediaNode.allExtends.concat(this.allExtendsStack[this.allExtendsStack.length - 1]);
- newAllExtends = newAllExtends.concat(this.doExtendChaining(newAllExtends, mediaNode.allExtends));
- this.allExtendsStack.push(newAllExtends);
- }
- }, {
- key: "visitMediaOut",
- value: function visitMediaOut(mediaNode) {
- var lastIndex = this.allExtendsStack.length - 1;
- this.allExtendsStack.length = lastIndex;
- }
- }, {
- key: "visitAtRule",
- value: function visitAtRule(atRuleNode, visitArgs) {
- var newAllExtends = atRuleNode.allExtends.concat(this.allExtendsStack[this.allExtendsStack.length - 1]);
- newAllExtends = newAllExtends.concat(this.doExtendChaining(newAllExtends, atRuleNode.allExtends));
- this.allExtendsStack.push(newAllExtends);
- }
- }, {
- key: "visitAtRuleOut",
- value: function visitAtRuleOut(atRuleNode) {
- var lastIndex = this.allExtendsStack.length - 1;
- this.allExtendsStack.length = lastIndex;
- }
- }]);
-
- return ProcessExtendsVisitor;
-}();
-
-var JoinSelectorVisitor =
-/*#__PURE__*/
-function () {
- function JoinSelectorVisitor() {
- _classCallCheck(this, JoinSelectorVisitor);
-
- this.contexts = [[]];
- this._visitor = new Visitor(this);
- }
-
- _createClass(JoinSelectorVisitor, [{
- key: "run",
- value: function run(root) {
- return this._visitor.visit(root);
- }
- }, {
- key: "visitDeclaration",
- value: function visitDeclaration(declNode, visitArgs) {
- visitArgs.visitDeeper = false;
- }
- }, {
- key: "visitMixinDefinition",
- value: function visitMixinDefinition(mixinDefinitionNode, visitArgs) {
- visitArgs.visitDeeper = false;
- }
- }, {
- key: "visitRuleset",
- value: function visitRuleset(rulesetNode, visitArgs) {
- var context = this.contexts[this.contexts.length - 1];
- var paths = [];
- var selectors;
- this.contexts.push(paths);
-
- if (!rulesetNode.root) {
- selectors = rulesetNode.selectors;
-
- if (selectors) {
- selectors = selectors.filter(function (selector) {
- return selector.getIsOutput();
- });
- rulesetNode.selectors = selectors.length ? selectors : selectors = null;
-
- if (selectors) {
- rulesetNode.joinSelectors(paths, context, selectors);
- }
- }
-
- if (!selectors) {
- rulesetNode.rules = null;
- }
-
- rulesetNode.paths = paths;
- }
- }
- }, {
- key: "visitRulesetOut",
- value: function visitRulesetOut(rulesetNode) {
- this.contexts.length = this.contexts.length - 1;
- }
- }, {
- key: "visitMedia",
- value: function visitMedia(mediaNode, visitArgs) {
- var context = this.contexts[this.contexts.length - 1];
- mediaNode.rules[0].root = context.length === 0 || context[0].multiMedia;
- }
- }, {
- key: "visitAtRule",
- value: function visitAtRule(atRuleNode, visitArgs) {
- var context = this.contexts[this.contexts.length - 1];
-
- if (atRuleNode.rules && atRuleNode.rules.length) {
- atRuleNode.rules[0].root = atRuleNode.isRooted || context.length === 0 || null;
- }
- }
- }]);
-
- return JoinSelectorVisitor;
-}();
-
-var CSSVisitorUtils =
-/*#__PURE__*/
-function () {
- function CSSVisitorUtils(context) {
- _classCallCheck(this, CSSVisitorUtils);
-
- this._visitor = new Visitor(this);
- this._context = context;
- }
-
- _createClass(CSSVisitorUtils, [{
- key: "containsSilentNonBlockedChild",
- value: function containsSilentNonBlockedChild(bodyRules) {
- var rule;
-
- if (!bodyRules) {
- return false;
- }
-
- for (var r = 0; r < bodyRules.length; r++) {
- rule = bodyRules[r];
-
- if (rule.isSilent && rule.isSilent(this._context) && !rule.blocksVisibility()) {
- // the atrule contains something that was referenced (likely by extend)
- // therefore it needs to be shown in output too
- return true;
- }
- }
-
- return false;
- }
- }, {
- key: "keepOnlyVisibleChilds",
- value: function keepOnlyVisibleChilds(owner) {
- if (owner && owner.rules) {
- owner.rules = owner.rules.filter(function (thing) {
- return thing.isVisible();
- });
- }
- }
- }, {
- key: "isEmpty",
- value: function isEmpty(owner) {
- return owner && owner.rules ? owner.rules.length === 0 : true;
- }
- }, {
- key: "hasVisibleSelector",
- value: function hasVisibleSelector(rulesetNode) {
- return rulesetNode && rulesetNode.paths ? rulesetNode.paths.length > 0 : false;
- }
- }, {
- key: "resolveVisibility",
- value: function resolveVisibility(node, originalRules) {
- if (!node.blocksVisibility()) {
- if (this.isEmpty(node) && !this.containsSilentNonBlockedChild(originalRules)) {
- return;
- }
-
- return node;
- }
-
- var compiledRulesBody = node.rules[0];
- this.keepOnlyVisibleChilds(compiledRulesBody);
-
- if (this.isEmpty(compiledRulesBody)) {
- return;
- }
-
- node.ensureVisibility();
- node.removeVisibilityBlock();
- return node;
- }
- }, {
- key: "isVisibleRuleset",
- value: function isVisibleRuleset(rulesetNode) {
- if (rulesetNode.firstRoot) {
- return true;
- }
-
- if (this.isEmpty(rulesetNode)) {
- return false;
- }
-
- if (!rulesetNode.root && !this.hasVisibleSelector(rulesetNode)) {
- return false;
- }
-
- return true;
- }
- }]);
-
- return CSSVisitorUtils;
-}();
-
-var ToCSSVisitor = function ToCSSVisitor(context) {
- this._visitor = new Visitor(this);
- this._context = context;
- this.utils = new CSSVisitorUtils(context);
-};
-
-ToCSSVisitor.prototype = {
- isReplacing: true,
- run: function run(root) {
- return this._visitor.visit(root);
- },
- visitDeclaration: function visitDeclaration(declNode, visitArgs) {
- if (declNode.blocksVisibility() || declNode.variable) {
- return;
- }
-
- return declNode;
- },
- visitMixinDefinition: function visitMixinDefinition(mixinNode, visitArgs) {
- // mixin definitions do not get eval'd - this means they keep state
- // so we have to clear that state here so it isn't used if toCSS is called twice
- mixinNode.frames = [];
- },
- visitExtend: function visitExtend(extendNode, visitArgs) {},
- visitComment: function visitComment(commentNode, visitArgs) {
- if (commentNode.blocksVisibility() || commentNode.isSilent(this._context)) {
- return;
- }
-
- return commentNode;
- },
- visitMedia: function visitMedia(mediaNode, visitArgs) {
- var originalRules = mediaNode.rules[0].rules;
- mediaNode.accept(this._visitor);
- visitArgs.visitDeeper = false;
- return this.utils.resolveVisibility(mediaNode, originalRules);
- },
- visitImport: function visitImport(importNode, visitArgs) {
- if (importNode.blocksVisibility()) {
- return;
- }
-
- return importNode;
- },
- visitAtRule: function visitAtRule(atRuleNode, visitArgs) {
- if (atRuleNode.rules && atRuleNode.rules.length) {
- return this.visitAtRuleWithBody(atRuleNode, visitArgs);
- } else {
- return this.visitAtRuleWithoutBody(atRuleNode, visitArgs);
- }
- },
- visitAnonymous: function visitAnonymous(anonymousNode, visitArgs) {
- if (!anonymousNode.blocksVisibility()) {
- anonymousNode.accept(this._visitor);
- return anonymousNode;
- }
- },
- visitAtRuleWithBody: function visitAtRuleWithBody(atRuleNode, visitArgs) {
- // if there is only one nested ruleset and that one has no path, then it is
- // just fake ruleset
- function hasFakeRuleset(atRuleNode) {
- var bodyRules = atRuleNode.rules;
- return bodyRules.length === 1 && (!bodyRules[0].paths || bodyRules[0].paths.length === 0);
- }
-
- function getBodyRules(atRuleNode) {
- var nodeRules = atRuleNode.rules;
-
- if (hasFakeRuleset(atRuleNode)) {
- return nodeRules[0].rules;
- }
-
- return nodeRules;
- } // it is still true that it is only one ruleset in array
- // this is last such moment
- // process childs
-
-
- var originalRules = getBodyRules(atRuleNode);
- atRuleNode.accept(this._visitor);
- visitArgs.visitDeeper = false;
-
- if (!this.utils.isEmpty(atRuleNode)) {
- this._mergeRules(atRuleNode.rules[0].rules);
- }
-
- return this.utils.resolveVisibility(atRuleNode, originalRules);
- },
- visitAtRuleWithoutBody: function visitAtRuleWithoutBody(atRuleNode, visitArgs) {
- if (atRuleNode.blocksVisibility()) {
- return;
- }
-
- if (atRuleNode.name === '@charset') {
- // Only output the debug info together with subsequent @charset definitions
- // a comment (or @media statement) before the actual @charset atrule would
- // be considered illegal css as it has to be on the first line
- if (this.charset) {
- if (atRuleNode.debugInfo) {
- var comment = new tree.Comment(`/* ${atRuleNode.toCSS(this._context).replace(/\n/g, '')} */\n`);
- comment.debugInfo = atRuleNode.debugInfo;
- return this._visitor.visit(comment);
- }
-
- return;
- }
-
- this.charset = true;
- }
-
- return atRuleNode;
- },
- checkValidNodes: function checkValidNodes(rules, isRoot) {
- if (!rules) {
- return;
- }
-
- for (var i = 0; i < rules.length; i++) {
- var ruleNode = rules[i];
-
- if (isRoot && ruleNode instanceof tree.Declaration && !ruleNode.variable) {
- throw {
- message: 'Properties must be inside selector blocks. They cannot be in the root',
- index: ruleNode.getIndex(),
- filename: ruleNode.fileInfo() && ruleNode.fileInfo().filename
- };
- }
-
- if (ruleNode instanceof tree.Call) {
- throw {
- message: `Function '${ruleNode.name}' is undefined`,
- index: ruleNode.getIndex(),
- filename: ruleNode.fileInfo() && ruleNode.fileInfo().filename
- };
- }
-
- if (ruleNode.type && !ruleNode.allowRoot) {
- throw {
- message: `${ruleNode.type} node returned by a function is not valid here`,
- index: ruleNode.getIndex(),
- filename: ruleNode.fileInfo() && ruleNode.fileInfo().filename
- };
- }
- }
- },
- visitRuleset: function visitRuleset(rulesetNode, visitArgs) {
- // at this point rulesets are nested into each other
- var rule;
- var rulesets = [];
- this.checkValidNodes(rulesetNode.rules, rulesetNode.firstRoot);
-
- if (!rulesetNode.root) {
- // remove invisible paths
- this._compileRulesetPaths(rulesetNode); // remove rulesets from this ruleset body and compile them separately
-
-
- var nodeRules = rulesetNode.rules;
- var nodeRuleCnt = nodeRules ? nodeRules.length : 0;
-
- for (var i = 0; i < nodeRuleCnt;) {
- rule = nodeRules[i];
-
- if (rule && rule.rules) {
- // visit because we are moving them out from being a child
- rulesets.push(this._visitor.visit(rule));
- nodeRules.splice(i, 1);
- nodeRuleCnt--;
- continue;
- }
-
- i++;
- } // accept the visitor to remove rules and refactor itself
- // then we can decide nogw whether we want it or not
- // compile body
-
-
- if (nodeRuleCnt > 0) {
- rulesetNode.accept(this._visitor);
- } else {
- rulesetNode.rules = null;
- }
-
- visitArgs.visitDeeper = false;
- } else {
- // if (! rulesetNode.root) {
- rulesetNode.accept(this._visitor);
- visitArgs.visitDeeper = false;
- }
-
- if (rulesetNode.rules) {
- this._mergeRules(rulesetNode.rules);
-
- this._removeDuplicateRules(rulesetNode.rules);
- } // now decide whether we keep the ruleset
-
-
- if (this.utils.isVisibleRuleset(rulesetNode)) {
- rulesetNode.ensureVisibility();
- rulesets.splice(0, 0, rulesetNode);
- }
-
- if (rulesets.length === 1) {
- return rulesets[0];
- }
-
- return rulesets;
- },
- _compileRulesetPaths: function _compileRulesetPaths(rulesetNode) {
- if (rulesetNode.paths) {
- rulesetNode.paths = rulesetNode.paths.filter(function (p) {
- var i;
-
- if (p[0].elements[0].combinator.value === ' ') {
- p[0].elements[0].combinator = new tree.Combinator('');
- }
-
- for (i = 0; i < p.length; i++) {
- if (p[i].isVisible() && p[i].getIsOutput()) {
- return true;
- }
- }
-
- return false;
- });
- }
- },
- _removeDuplicateRules: function _removeDuplicateRules(rules) {
- if (!rules) {
- return;
- } // remove duplicates
-
-
- var ruleCache = {};
- var ruleList;
- var rule;
- var i;
-
- for (i = rules.length - 1; i >= 0; i--) {
- rule = rules[i];
-
- if (rule instanceof tree.Declaration) {
- if (!ruleCache[rule.name]) {
- ruleCache[rule.name] = rule;
- } else {
- ruleList = ruleCache[rule.name];
-
- if (ruleList instanceof tree.Declaration) {
- ruleList = ruleCache[rule.name] = [ruleCache[rule.name].toCSS(this._context)];
- }
-
- var ruleCSS = rule.toCSS(this._context);
-
- if (ruleList.indexOf(ruleCSS) !== -1) {
- rules.splice(i, 1);
- } else {
- ruleList.push(ruleCSS);
- }
- }
- }
- }
- },
- _mergeRules: function _mergeRules(rules) {
- if (!rules) {
- return;
- }
-
- var groups = {};
- var groupsArr = [];
-
- for (var i = 0; i < rules.length; i++) {
- var rule = rules[i];
-
- if (rule.merge) {
- var key = rule.name;
- groups[key] ? rules.splice(i--, 1) : groupsArr.push(groups[key] = []);
- groups[key].push(rule);
- }
- }
-
- groupsArr.forEach(function (group) {
- if (group.length > 0) {
- var result = group[0];
- var space = [];
- var comma = [new tree.Expression(space)];
- group.forEach(function (rule) {
- if (rule.merge === '+' && space.length > 0) {
- comma.push(new tree.Expression(space = []));
- }
-
- space.push(rule.value);
- result.important = result.important || rule.important;
- });
- result.value = new tree.Value(comma);
- }
- });
- }
-};
-
-var visitors = {
- Visitor,
- ImportVisitor,
- MarkVisibleSelectorsVisitor: SetTreeVisibilityVisitor,
- ExtendVisitor: ProcessExtendsVisitor,
- JoinSelectorVisitor,
- ToCSSVisitor
-};
-
-// Split the input into chunks.
-var chunker = (function (input, fail) {
- var len = input.length;
- var level = 0;
- var parenLevel = 0;
- var lastOpening;
- var lastOpeningParen;
- var lastMultiComment;
- var lastMultiCommentEndBrace;
- var chunks = [];
- var emitFrom = 0;
- var chunkerCurrentIndex;
- var currentChunkStartIndex;
- var cc;
- var cc2;
- var matched;
-
- function emitChunk(force) {
- var len = chunkerCurrentIndex - emitFrom;
-
- if (len < 512 && !force || !len) {
- return;
- }
-
- chunks.push(input.slice(emitFrom, chunkerCurrentIndex + 1));
- emitFrom = chunkerCurrentIndex + 1;
- }
-
- for (chunkerCurrentIndex = 0; chunkerCurrentIndex < len; chunkerCurrentIndex++) {
- cc = input.charCodeAt(chunkerCurrentIndex);
-
- if (cc >= 97 && cc <= 122 || cc < 34) {
- // a-z or whitespace
- continue;
- }
-
- switch (cc) {
- case 40:
- // (
- parenLevel++;
- lastOpeningParen = chunkerCurrentIndex;
- continue;
-
- case 41:
- // )
- if (--parenLevel < 0) {
- return fail('missing opening `(`', chunkerCurrentIndex);
- }
-
- continue;
-
- case 59:
- // ;
- if (!parenLevel) {
- emitChunk();
- }
-
- continue;
-
- case 123:
- // {
- level++;
- lastOpening = chunkerCurrentIndex;
- continue;
-
- case 125:
- // }
- if (--level < 0) {
- return fail('missing opening `{`', chunkerCurrentIndex);
- }
-
- if (!level && !parenLevel) {
- emitChunk();
- }
-
- continue;
-
- case 92:
- // \
- if (chunkerCurrentIndex < len - 1) {
- chunkerCurrentIndex++;
- continue;
- }
-
- return fail('unescaped `\\`', chunkerCurrentIndex);
-
- case 34:
- case 39:
- case 96:
- // ", ' and `
- matched = 0;
- currentChunkStartIndex = chunkerCurrentIndex;
-
- for (chunkerCurrentIndex = chunkerCurrentIndex + 1; chunkerCurrentIndex < len; chunkerCurrentIndex++) {
- cc2 = input.charCodeAt(chunkerCurrentIndex);
-
- if (cc2 > 96) {
- continue;
- }
-
- if (cc2 == cc) {
- matched = 1;
- break;
- }
-
- if (cc2 == 92) {
- // \
- if (chunkerCurrentIndex == len - 1) {
- return fail('unescaped `\\`', chunkerCurrentIndex);
- }
-
- chunkerCurrentIndex++;
- }
- }
-
- if (matched) {
- continue;
- }
-
- return fail(`unmatched \`${String.fromCharCode(cc)}\``, currentChunkStartIndex);
-
- case 47:
- // /, check for comment
- if (parenLevel || chunkerCurrentIndex == len - 1) {
- continue;
- }
-
- cc2 = input.charCodeAt(chunkerCurrentIndex + 1);
-
- if (cc2 == 47) {
- // //, find lnfeed
- for (chunkerCurrentIndex = chunkerCurrentIndex + 2; chunkerCurrentIndex < len; chunkerCurrentIndex++) {
- cc2 = input.charCodeAt(chunkerCurrentIndex);
-
- if (cc2 <= 13 && (cc2 == 10 || cc2 == 13)) {
- break;
- }
- }
- } else if (cc2 == 42) {
- // /*, find */
- lastMultiComment = currentChunkStartIndex = chunkerCurrentIndex;
-
- for (chunkerCurrentIndex = chunkerCurrentIndex + 2; chunkerCurrentIndex < len - 1; chunkerCurrentIndex++) {
- cc2 = input.charCodeAt(chunkerCurrentIndex);
-
- if (cc2 == 125) {
- lastMultiCommentEndBrace = chunkerCurrentIndex;
- }
-
- if (cc2 != 42) {
- continue;
- }
-
- if (input.charCodeAt(chunkerCurrentIndex + 1) == 47) {
- break;
- }
- }
-
- if (chunkerCurrentIndex == len - 1) {
- return fail('missing closing `*/`', currentChunkStartIndex);
- }
-
- chunkerCurrentIndex++;
- }
-
- continue;
-
- case 42:
- // *, check for unmatched */
- if (chunkerCurrentIndex < len - 1 && input.charCodeAt(chunkerCurrentIndex + 1) == 47) {
- return fail('unmatched `/*`', chunkerCurrentIndex);
- }
-
- continue;
- }
- }
-
- if (level !== 0) {
- if (lastMultiComment > lastOpening && lastMultiCommentEndBrace > lastMultiComment) {
- return fail('missing closing `}` or `*/`', lastOpening);
- } else {
- return fail('missing closing `}`', lastOpening);
- }
- } else if (parenLevel !== 0) {
- return fail('missing closing `)`', lastOpeningParen);
- }
-
- emitChunk(true);
- return chunks;
-});
-
-var getParserInput = (function () {
- var // Less input string
- input;
- var // current chunk
- j;
- var // holds state for backtracking
- saveStack = [];
- var // furthest index the parser has gone to
- furthest;
- var // if this is furthest we got to, this is the probably cause
- furthestPossibleErrorMessage;
- var // chunkified input
- chunks;
- var // current chunk
- current;
- var // index of current chunk, in `input`
- currentPos;
- var parserInput = {};
- var CHARCODE_SPACE = 32;
- var CHARCODE_TAB = 9;
- var CHARCODE_LF = 10;
- var CHARCODE_CR = 13;
- var CHARCODE_PLUS = 43;
- var CHARCODE_COMMA = 44;
- var CHARCODE_FORWARD_SLASH = 47;
- var CHARCODE_9 = 57;
-
- function skipWhitespace(length) {
- var oldi = parserInput.i;
- var oldj = j;
- var curr = parserInput.i - currentPos;
- var endIndex = parserInput.i + current.length - curr;
- var mem = parserInput.i += length;
- var inp = input;
- var c;
- var nextChar;
- var comment;
-
- for (; parserInput.i < endIndex; parserInput.i++) {
- c = inp.charCodeAt(parserInput.i);
-
- if (parserInput.autoCommentAbsorb && c === CHARCODE_FORWARD_SLASH) {
- nextChar = inp.charAt(parserInput.i + 1);
-
- if (nextChar === '/') {
- comment = {
- index: parserInput.i,
- isLineComment: true
- };
- var nextNewLine = inp.indexOf('\n', parserInput.i + 2);
-
- if (nextNewLine < 0) {
- nextNewLine = endIndex;
- }
-
- parserInput.i = nextNewLine;
- comment.text = inp.substr(comment.index, parserInput.i - comment.index);
- parserInput.commentStore.push(comment);
- continue;
- } else if (nextChar === '*') {
- var nextStarSlash = inp.indexOf('*/', parserInput.i + 2);
-
- if (nextStarSlash >= 0) {
- comment = {
- index: parserInput.i,
- text: inp.substr(parserInput.i, nextStarSlash + 2 - parserInput.i),
- isLineComment: false
- };
- parserInput.i += comment.text.length - 1;
- parserInput.commentStore.push(comment);
- continue;
- }
- }
-
- break;
- }
-
- if (c !== CHARCODE_SPACE && c !== CHARCODE_LF && c !== CHARCODE_TAB && c !== CHARCODE_CR) {
- break;
- }
- }
-
- current = current.slice(length + parserInput.i - mem + curr);
- currentPos = parserInput.i;
-
- if (!current.length) {
- if (j < chunks.length - 1) {
- current = chunks[++j];
- skipWhitespace(0); // skip space at the beginning of a chunk
-
- return true; // things changed
- }
-
- parserInput.finished = true;
- }
-
- return oldi !== parserInput.i || oldj !== j;
- }
-
- parserInput.save = function () {
- currentPos = parserInput.i;
- saveStack.push({
- current,
- i: parserInput.i,
- j
- });
- };
-
- parserInput.restore = function (possibleErrorMessage) {
- if (parserInput.i > furthest || parserInput.i === furthest && possibleErrorMessage && !furthestPossibleErrorMessage) {
- furthest = parserInput.i;
- furthestPossibleErrorMessage = possibleErrorMessage;
- }
-
- var state = saveStack.pop();
- current = state.current;
- currentPos = parserInput.i = state.i;
- j = state.j;
- };
-
- parserInput.forget = function () {
- saveStack.pop();
- };
-
- parserInput.isWhitespace = function (offset) {
- var pos = parserInput.i + (offset || 0);
- var code = input.charCodeAt(pos);
- return code === CHARCODE_SPACE || code === CHARCODE_CR || code === CHARCODE_TAB || code === CHARCODE_LF;
- }; // Specialization of $(tok)
-
-
- parserInput.$re = function (tok) {
- if (parserInput.i > currentPos) {
- current = current.slice(parserInput.i - currentPos);
- currentPos = parserInput.i;
- }
-
- var m = tok.exec(current);
-
- if (!m) {
- return null;
- }
-
- skipWhitespace(m[0].length);
-
- if (typeof m === 'string') {
- return m;
- }
-
- return m.length === 1 ? m[0] : m;
- };
-
- parserInput.$char = function (tok) {
- if (input.charAt(parserInput.i) !== tok) {
- return null;
- }
-
- skipWhitespace(1);
- return tok;
- };
-
- parserInput.$str = function (tok) {
- var tokLength = tok.length; // https://jsperf.com/string-startswith/21
-
- for (var i = 0; i < tokLength; i++) {
- if (input.charAt(parserInput.i + i) !== tok.charAt(i)) {
- return null;
- }
- }
-
- skipWhitespace(tokLength);
- return tok;
- };
-
- parserInput.$quoted = function (loc) {
- var pos = loc || parserInput.i;
- var startChar = input.charAt(pos);
-
- if (startChar !== '\'' && startChar !== '"') {
- return;
- }
-
- var length = input.length;
- var currentPosition = pos;
-
- for (var i = 1; i + currentPosition < length; i++) {
- var nextChar = input.charAt(i + currentPosition);
-
- switch (nextChar) {
- case '\\':
- i++;
- continue;
-
- case '\r':
- case '\n':
- break;
-
- case startChar:
- var str = input.substr(currentPosition, i + 1);
-
- if (!loc && loc !== 0) {
- skipWhitespace(i + 1);
- return str;
- }
-
- return [startChar, str];
-
- default:
- }
- }
-
- return null;
- };
- /**
- * Permissive parsing. Ignores everything except matching {} [] () and quotes
- * until matching token (outside of blocks)
- */
-
-
- parserInput.$parseUntil = function (tok) {
- var quote = '';
- var returnVal = null;
- var inComment = false;
- var blockDepth = 0;
- var blockStack = [];
- var parseGroups = [];
- var length = input.length;
- var startPos = parserInput.i;
- var lastPos = parserInput.i;
- var i = parserInput.i;
- var loop = true;
- var testChar;
-
- if (typeof tok === 'string') {
- testChar = function testChar(char) {
- return char === tok;
- };
- } else {
- testChar = function testChar(char) {
- return tok.test(char);
- };
- }
-
- do {
- var nextChar = input.charAt(i);
-
- if (blockDepth === 0 && testChar(nextChar)) {
- returnVal = input.substr(lastPos, i - lastPos);
-
- if (returnVal) {
- parseGroups.push(returnVal);
- } else {
- parseGroups.push(' ');
- }
-
- returnVal = parseGroups;
- skipWhitespace(i - startPos);
- loop = false;
- } else {
- if (inComment) {
- if (nextChar === '*' && input.charAt(i + 1) === '/') {
- i++;
- blockDepth--;
- inComment = false;
- }
-
- i++;
- continue;
- }
-
- switch (nextChar) {
- case '\\':
- i++;
- nextChar = input.charAt(i);
- parseGroups.push(input.substr(lastPos, i - lastPos + 1));
- lastPos = i + 1;
- break;
-
- case '/':
- if (input.charAt(i + 1) === '*') {
- i++;
- inComment = true;
- blockDepth++;
- }
-
- break;
-
- case '\'':
- case '"':
- quote = parserInput.$quoted(i);
-
- if (quote) {
- parseGroups.push(input.substr(lastPos, i - lastPos), quote);
- i += quote[1].length - 1;
- lastPos = i + 1;
- } else {
- skipWhitespace(i - startPos);
- returnVal = nextChar;
- loop = false;
- }
-
- break;
-
- case '{':
- blockStack.push('}');
- blockDepth++;
- break;
-
- case '(':
- blockStack.push(')');
- blockDepth++;
- break;
-
- case '[':
- blockStack.push(']');
- blockDepth++;
- break;
-
- case '}':
- case ')':
- case ']':
- var expected = blockStack.pop();
-
- if (nextChar === expected) {
- blockDepth--;
- } else {
- // move the parser to the error and return expected
- skipWhitespace(i - startPos);
- returnVal = expected;
- loop = false;
- }
-
- }
-
- i++;
-
- if (i > length) {
- loop = false;
- }
- }
- } while (loop);
-
- return returnVal ? returnVal : null;
- };
-
- parserInput.autoCommentAbsorb = true;
- parserInput.commentStore = [];
- parserInput.finished = false; // Same as $(), but don't change the state of the parser,
- // just return the match.
-
- parserInput.peek = function (tok) {
- if (typeof tok === 'string') {
- // https://jsperf.com/string-startswith/21
- for (var i = 0; i < tok.length; i++) {
- if (input.charAt(parserInput.i + i) !== tok.charAt(i)) {
- return false;
- }
- }
-
- return true;
- } else {
- return tok.test(current);
- }
- }; // Specialization of peek()
- // TODO remove or change some currentChar calls to peekChar
-
-
- parserInput.peekChar = function (tok) {
- return input.charAt(parserInput.i) === tok;
- };
-
- parserInput.currentChar = function () {
- return input.charAt(parserInput.i);
- };
-
- parserInput.prevChar = function () {
- return input.charAt(parserInput.i - 1);
- };
-
- parserInput.getInput = function () {
- return input;
- };
-
- parserInput.peekNotNumeric = function () {
- var c = input.charCodeAt(parserInput.i); // Is the first char of the dimension 0-9, '.', '+' or '-'
-
- return c > CHARCODE_9 || c < CHARCODE_PLUS || c === CHARCODE_FORWARD_SLASH || c === CHARCODE_COMMA;
- };
-
- parserInput.start = function (str, chunkInput, failFunction) {
- input = str;
- parserInput.i = j = currentPos = furthest = 0; // chunking apparently makes things quicker (but my tests indicate
- // it might actually make things slower in node at least)
- // and it is a non-perfect parse - it can't recognise
- // unquoted urls, meaning it can't distinguish comments
- // meaning comments with quotes or {}() in them get 'counted'
- // and then lead to parse errors.
- // In addition if the chunking chunks in the wrong place we might
- // not be able to parse a parser statement in one go
- // this is officially deprecated but can be switched on via an option
- // in the case it causes too much performance issues.
-
- if (chunkInput) {
- chunks = chunker(str, failFunction);
- } else {
- chunks = [str];
- }
-
- current = chunks[0];
- skipWhitespace(0);
- };
-
- parserInput.end = function () {
- var message;
- var isFinished = parserInput.i >= input.length;
-
- if (parserInput.i < furthest) {
- message = furthestPossibleErrorMessage;
- parserInput.i = furthest;
- }
-
- return {
- isFinished,
- furthest: parserInput.i,
- furthestPossibleErrorMessage: message,
- furthestReachedEnd: parserInput.i >= input.length - 1,
- furthestChar: input[parserInput.i]
- };
- };
-
- return parserInput;
-});
-
-// less.js - parser
-//
-// A relatively straight-forward predictive parser.
-// There is no tokenization/lexing stage, the input is parsed
-// in one sweep.
-//
-// To make the parser fast enough to run in the browser, several
-// optimization had to be made:
-//
-// - Matching and slicing on a huge input is often cause of slowdowns.
-// The solution is to chunkify the input into smaller strings.
-// The chunks are stored in the `chunks` var,
-// `j` holds the current chunk index, and `currentPos` holds
-// the index of the current chunk in relation to `input`.
-// This gives us an almost 4x speed-up.
-//
-// - In many cases, we don't need to match individual tokens;
-// for example, if a value doesn't hold any variables, operations
-// or dynamic references, the parser can effectively 'skip' it,
-// treating it as a literal.
-// An example would be '1px solid #000' - which evaluates to itself,
-// we don't need to know what the individual components are.
-// The drawback, of course is that you don't get the benefits of
-// syntax-checking on the CSS. This gives us a 50% speed-up in the parser,
-// and a smaller speed-up in the code-gen.
-//
-//
-// Token matching is done with the `$` function, which either takes
-// a terminal string or regexp, or a non-terminal function to call.
-// It also takes care of moving all the indices forwards.
-//
-
-var Parser = function Parser(context, imports, fileInfo) {
- var parsers;
- var parserInput = getParserInput();
-
- function error(msg, type) {
- throw new LessError({
- index: parserInput.i,
- filename: fileInfo.filename,
- type: type || 'Syntax',
- message: msg
- }, imports);
- }
-
- function expect(arg, msg) {
- // some older browsers return typeof 'function' for RegExp
- var result = arg instanceof Function ? arg.call(parsers) : parserInput.$re(arg);
-
- if (result) {
- return result;
- }
-
- error(msg || (typeof arg === 'string' ? `expected '${arg}' got '${parserInput.currentChar()}'` : 'unexpected token'));
- } // Specialization of expect()
-
-
- function expectChar(arg, msg) {
- if (parserInput.$char(arg)) {
- return arg;
- }
-
- error(msg || `expected '${arg}' got '${parserInput.currentChar()}'`);
- }
-
- function getDebugInfo(index) {
- var filename = fileInfo.filename;
- return {
- lineNumber: getLocation(index, parserInput.getInput()).line + 1,
- fileName: filename
- };
- }
- /**
- * Used after initial parsing to create nodes on the fly
- *
- * @param {String} str - string to parse
- * @param {Array} parseList - array of parsers to run input through e.g. ["value", "important"]
- * @param {Number} currentIndex - start number to begin indexing
- * @param {Object} fileInfo - fileInfo to attach to created nodes
- */
-
-
- function parseNode(str, parseList, currentIndex, fileInfo, callback) {
- var result;
- var returnNodes = [];
- var parser = parserInput;
-
- try {
- parser.start(str, false, function fail(msg, index) {
- callback({
- message: msg,
- index: index + currentIndex
- });
- });
-
- for (var x = 0, p, i; p = parseList[x]; x++) {
- i = parser.i;
- result = parsers[p]();
-
- if (result) {
- try {
- result._index = i + currentIndex;
- result._fileInfo = fileInfo;
- } catch (e) {}
-
- returnNodes.push(result);
- } else {
- returnNodes.push(null);
- }
- }
-
- var endInfo = parser.end();
-
- if (endInfo.isFinished) {
- callback(null, returnNodes);
- } else {
- callback(true, null);
- }
- } catch (e) {
- throw new LessError({
- index: e.index + currentIndex,
- message: e.message
- }, imports, fileInfo.filename);
- }
- } //
- // The Parser
- //
-
-
- return {
- parserInput,
- imports,
- fileInfo,
- parseNode,
- //
- // Parse an input string into an abstract syntax tree,
- // @param str A string containing 'less' markup
- // @param callback call `callback` when done.
- // @param [additionalData] An optional map which can contains vars - a map (key, value) of variables to apply
- //
- parse: function parse(str, callback, additionalData) {
- var root;
- var error = null;
- var globalVars;
- var modifyVars;
- var ignored;
- var preText = '';
- globalVars = additionalData && additionalData.globalVars ? `${Parser.serializeVars(additionalData.globalVars)}\n` : '';
- modifyVars = additionalData && additionalData.modifyVars ? `\n${Parser.serializeVars(additionalData.modifyVars)}` : '';
-
- if (context.pluginManager) {
- var preProcessors = context.pluginManager.getPreProcessors();
-
- for (var i = 0; i < preProcessors.length; i++) {
- str = preProcessors[i].process(str, {
- context,
- imports,
- fileInfo
- });
- }
- }
-
- if (globalVars || additionalData && additionalData.banner) {
- preText = (additionalData && additionalData.banner ? additionalData.banner : '') + globalVars;
- ignored = imports.contentsIgnoredChars;
- ignored[fileInfo.filename] = ignored[fileInfo.filename] || 0;
- ignored[fileInfo.filename] += preText.length;
- }
-
- str = str.replace(/\r\n?/g, '\n'); // Remove potential UTF Byte Order Mark
-
- str = preText + str.replace(/^\uFEFF/, '') + modifyVars;
- imports.contents[fileInfo.filename] = str; // Start with the primary rule.
- // The whole syntax tree is held under a Ruleset node,
- // with the `root` property set to true, so no `{}` are
- // output. The callback is called when the input is parsed.
-
- try {
- parserInput.start(str, context.chunkInput, function fail(msg, index) {
- throw new LessError({
- index,
- type: 'Parse',
- message: msg,
- filename: fileInfo.filename
- }, imports);
- });
- tree.Node.prototype.parse = this;
- root = new tree.Ruleset(null, this.parsers.primary());
- tree.Node.prototype.rootNode = root;
- root.root = true;
- root.firstRoot = true;
- root.functionRegistry = functionRegistry.inherit();
- } catch (e) {
- return callback(new LessError(e, imports, fileInfo.filename));
- } // If `i` is smaller than the `input.length - 1`,
- // it means the parser wasn't able to parse the whole
- // string, so we've got a parsing error.
- //
- // We try to extract a \n delimited string,
- // showing the line where the parse error occurred.
- // We split it up into two parts (the part which parsed,
- // and the part which didn't), so we can color them differently.
-
-
- var endInfo = parserInput.end();
-
- if (!endInfo.isFinished) {
- var message = endInfo.furthestPossibleErrorMessage;
-
- if (!message) {
- message = 'Unrecognised input';
-
- if (endInfo.furthestChar === '}') {
- message += '. Possibly missing opening \'{\'';
- } else if (endInfo.furthestChar === ')') {
- message += '. Possibly missing opening \'(\'';
- } else if (endInfo.furthestReachedEnd) {
- message += '. Possibly missing something';
- }
- }
-
- error = new LessError({
- type: 'Parse',
- message,
- index: endInfo.furthest,
- filename: fileInfo.filename
- }, imports);
- }
-
- var finish = function finish(e) {
- e = error || e || imports.error;
-
- if (e) {
- if (!(e instanceof LessError)) {
- e = new LessError(e, imports, fileInfo.filename);
- }
-
- return callback(e);
- } else {
- return callback(null, root);
- }
- };
-
- if (context.processImports !== false) {
- new visitors.ImportVisitor(imports, finish).run(root);
- } else {
- return finish();
- }
- },
- //
- // Here in, the parsing rules/functions
- //
- // The basic structure of the syntax tree generated is as follows:
- //
- // Ruleset -> Declaration -> Value -> Expression -> Entity
- //
- // Here's some Less code:
- //
- // .class {
- // color: #fff;
- // border: 1px solid #000;
- // width: @w + 4px;
- // > .child {...}
- // }
- //
- // And here's what the parse tree might look like:
- //
- // Ruleset (Selector '.class', [
- // Declaration ("color", Value ([Expression [Color #fff]]))
- // Declaration ("border", Value ([Expression [Dimension 1px][Keyword "solid"][Color #000]]))
- // Declaration ("width", Value ([Expression [Operation " + " [Variable "@w"][Dimension 4px]]]))
- // Ruleset (Selector [Element '>', '.child'], [...])
- // ])
- //
- // In general, most rules will try to parse a token with the `$re()` function, and if the return
- // value is truly, will return a new node, of the relevant type. Sometimes, we need to check
- // first, before parsing, that's when we use `peek()`.
- //
- parsers: parsers = {
- //
- // The `primary` rule is the *entry* and *exit* point of the parser.
- // The rules here can appear at any level of the parse tree.
- //
- // The recursive nature of the grammar is an interplay between the `block`
- // rule, which represents `{ ... }`, the `ruleset` rule, and this `primary` rule,
- // as represented by this simplified grammar:
- //
- // primary → (ruleset | declaration)+
- // ruleset → selector+ block
- // block → '{' primary '}'
- //
- // Only at one point is the primary rule not called from the
- // block rule: at the root level.
- //
- primary: function primary() {
- var mixin = this.mixin;
- var root = [];
- var node;
-
- while (true) {
- while (true) {
- node = this.comment();
-
- if (!node) {
- break;
- }
-
- root.push(node);
- } // always process comments before deciding if finished
-
-
- if (parserInput.finished) {
- break;
- }
-
- if (parserInput.peek('}')) {
- break;
- }
-
- node = this.extendRule();
-
- if (node) {
- root = root.concat(node);
- continue;
- }
-
- node = mixin.definition() || this.declaration() || this.ruleset() || mixin.call(false, false) || this.variableCall() || this.entities.call() || this.atrule();
-
- if (node) {
- root.push(node);
- } else {
- var foundSemiColon = false;
-
- while (parserInput.$char(';')) {
- foundSemiColon = true;
- }
-
- if (!foundSemiColon) {
- break;
- }
- }
- }
-
- return root;
- },
- // comments are collected by the main parsing mechanism and then assigned to nodes
- // where the current structure allows it
- comment: function comment() {
- if (parserInput.commentStore.length) {
- var comment = parserInput.commentStore.shift();
- return new tree.Comment(comment.text, comment.isLineComment, comment.index, fileInfo);
- }
- },
- //
- // Entities are tokens which can be found inside an Expression
- //
- entities: {
- mixinLookup: function mixinLookup() {
- return parsers.mixin.call(true, true);
- },
- //
- // A string, which supports escaping " and '
- //
- // "milky way" 'he\'s the one!'
- //
- quoted: function quoted(forceEscaped) {
- var str;
- var index = parserInput.i;
- var isEscaped = false;
- parserInput.save();
-
- if (parserInput.$char('~')) {
- isEscaped = true;
- } else if (forceEscaped) {
- parserInput.restore();
- return;
- }
-
- str = parserInput.$quoted();
-
- if (!str) {
- parserInput.restore();
- return;
- }
-
- parserInput.forget();
- return new tree.Quoted(str.charAt(0), str.substr(1, str.length - 2), isEscaped, index, fileInfo);
- },
- //
- // A catch-all word, such as:
- //
- // black border-collapse
- //
- keyword: function keyword() {
- var k = parserInput.$char('%') || parserInput.$re(/^\[?(?:[\w-]|\\(?:[A-Fa-f0-9]{1,6} ?|[^A-Fa-f0-9]))+\]?/);
-
- if (k) {
- return tree.Color.fromKeyword(k) || new tree.Keyword(k);
- }
- },
- //
- // A function call
- //
- // rgb(255, 0, 255)
- //
- // The arguments are parsed with the `entities.arguments` parser.
- //
- call: function call() {
- var name;
- var args;
- var func;
- var index = parserInput.i; // http://jsperf.com/case-insensitive-regex-vs-strtolower-then-regex/18
-
- if (parserInput.peek(/^url\(/i)) {
- return;
- }
-
- parserInput.save();
- name = parserInput.$re(/^([\w-]+|%|progid:[\w\.]+)\(/);
-
- if (!name) {
- parserInput.forget();
- return;
- }
-
- name = name[1];
- func = this.customFuncCall(name);
-
- if (func) {
- args = func.parse();
-
- if (args && func.stop) {
- parserInput.forget();
- return args;
- }
- }
-
- args = this.arguments(args);
-
- if (!parserInput.$char(')')) {
- parserInput.restore('Could not parse call arguments or missing \')\'');
- return;
- }
-
- parserInput.forget();
- return new tree.Call(name, args, index, fileInfo);
- },
- //
- // Parsing rules for functions with non-standard args, e.g.:
- //
- // boolean(not(2 > 1))
- //
- // This is a quick prototype, to be modified/improved when
- // more custom-parsed funcs come (e.g. `selector(...)`)
- //
- customFuncCall: function customFuncCall(name) {
- /* Ideally the table is to be moved out of here for faster perf.,
- but it's quite tricky since it relies on all these `parsers`
- and `expect` available only here */
- return {
- alpha: f(parsers.ieAlpha, true),
- boolean: f(condition),
- 'if': f(condition)
- }[name.toLowerCase()];
-
- function f(parse, stop) {
- return {
- parse,
- // parsing function
- stop // when true - stop after parse() and return its result,
- // otherwise continue for plain args
-
- };
- }
-
- function condition() {
- return [expect(parsers.condition, 'expected condition')];
- }
- },
- arguments: function _arguments(prevArgs) {
- var argsComma = prevArgs || [];
- var argsSemiColon = [];
- var isSemiColonSeparated;
- var value;
- parserInput.save();
-
- while (true) {
- if (prevArgs) {
- prevArgs = false;
- } else {
- value = parsers.detachedRuleset() || this.assignment() || parsers.expression();
-
- if (!value) {
- break;
- }
-
- if (value.value && value.value.length == 1) {
- value = value.value[0];
- }
-
- argsComma.push(value);
- }
-
- if (parserInput.$char(',')) {
- continue;
- }
-
- if (parserInput.$char(';') || isSemiColonSeparated) {
- isSemiColonSeparated = true;
- value = argsComma.length < 1 ? argsComma[0] : new tree.Value(argsComma);
- argsSemiColon.push(value);
- argsComma = [];
- }
- }
-
- parserInput.forget();
- return isSemiColonSeparated ? argsSemiColon : argsComma;
- },
- literal: function literal() {
- return this.dimension() || this.color() || this.quoted() || this.unicodeDescriptor();
- },
- // Assignments are argument entities for calls.
- // They are present in ie filter properties as shown below.
- //
- // filter: progid:DXImageTransform.Microsoft.Alpha( *opacity=50* )
- //
- assignment: function assignment() {
- var key;
- var value;
- parserInput.save();
- key = parserInput.$re(/^\w+(?=\s?=)/i);
-
- if (!key) {
- parserInput.restore();
- return;
- }
-
- if (!parserInput.$char('=')) {
- parserInput.restore();
- return;
- }
-
- value = parsers.entity();
-
- if (value) {
- parserInput.forget();
- return new tree.Assignment(key, value);
- } else {
- parserInput.restore();
- }
- },
- //
- // Parse url() tokens
- //
- // We use a specific rule for urls, because they don't really behave like
- // standard function calls. The difference is that the argument doesn't have
- // to be enclosed within a string, so it can't be parsed as an Expression.
- //
- url: function url() {
- var value;
- var index = parserInput.i;
- parserInput.autoCommentAbsorb = false;
-
- if (!parserInput.$str('url(')) {
- parserInput.autoCommentAbsorb = true;
- return;
- }
-
- value = this.quoted() || this.variable() || this.property() || parserInput.$re(/^(?:(?:\\[\(\)'"])|[^\(\)'"])+/) || '';
- parserInput.autoCommentAbsorb = true;
- expectChar(')');
- return new tree.URL(value.value != null || value instanceof tree.Variable || value instanceof tree.Property ? value : new tree.Anonymous(value, index), index, fileInfo);
- },
- //
- // A Variable entity, such as `@fink`, in
- //
- // width: @fink + 2px
- //
- // We use a different parser for variable definitions,
- // see `parsers.variable`.
- //
- variable: function variable() {
- var ch;
- var name;
- var index = parserInput.i;
- parserInput.save();
-
- if (parserInput.currentChar() === '@' && (name = parserInput.$re(/^@@?[\w-]+/))) {
- ch = parserInput.currentChar();
-
- if (ch === '(' || ch === '[' && !parserInput.prevChar().match(/^\s/)) {
- // this may be a VariableCall lookup
- var result = parsers.variableCall(name);
-
- if (result) {
- parserInput.forget();
- return result;
- }
- }
-
- parserInput.forget();
- return new tree.Variable(name, index, fileInfo);
- }
-
- parserInput.restore();
- },
- // A variable entity using the protective {} e.g. @{var}
- variableCurly: function variableCurly() {
- var curly;
- var index = parserInput.i;
-
- if (parserInput.currentChar() === '@' && (curly = parserInput.$re(/^@\{([\w-]+)\}/))) {
- return new tree.Variable(`@${curly[1]}`, index, fileInfo);
- }
- },
- //
- // A Property accessor, such as `$color`, in
- //
- // background-color: $color
- //
- property: function property() {
- var name;
- var index = parserInput.i;
-
- if (parserInput.currentChar() === '$' && (name = parserInput.$re(/^\$[\w-]+/))) {
- return new tree.Property(name, index, fileInfo);
- }
- },
- // A property entity useing the protective {} e.g. ${prop}
- propertyCurly: function propertyCurly() {
- var curly;
- var index = parserInput.i;
-
- if (parserInput.currentChar() === '$' && (curly = parserInput.$re(/^\$\{([\w-]+)\}/))) {
- return new tree.Property(`$${curly[1]}`, index, fileInfo);
- }
- },
- //
- // A Hexadecimal color
- //
- // #4F3C2F
- //
- // `rgb` and `hsl` colors are parsed through the `entities.call` parser.
- //
- color: function color() {
- var rgb;
- parserInput.save();
-
- if (parserInput.currentChar() === '#' && (rgb = parserInput.$re(/^#([A-Fa-f0-9]{8}|[A-Fa-f0-9]{6}|[A-Fa-f0-9]{3,4})([\w.#\[])?/))) {
- if (!rgb[2]) {
- parserInput.forget();
- return new tree.Color(rgb[1], undefined, rgb[0]);
- }
- }
-
- parserInput.restore();
- },
- colorKeyword: function colorKeyword() {
- parserInput.save();
- var autoCommentAbsorb = parserInput.autoCommentAbsorb;
- parserInput.autoCommentAbsorb = false;
- var k = parserInput.$re(/^[_A-Za-z-][_A-Za-z0-9-]+/);
- parserInput.autoCommentAbsorb = autoCommentAbsorb;
-
- if (!k) {
- parserInput.forget();
- return;
- }
-
- parserInput.restore();
- var color = tree.Color.fromKeyword(k);
-
- if (color) {
- parserInput.$str(k);
- return color;
- }
- },
- //
- // A Dimension, that is, a number and a unit
- //
- // 0.5em 95%
- //
- dimension: function dimension() {
- if (parserInput.peekNotNumeric()) {
- return;
- }
-
- var value = parserInput.$re(/^([+-]?\d*\.?\d+)(%|[a-z_]+)?/i);
-
- if (value) {
- return new tree.Dimension(value[1], value[2]);
- }
- },
- //
- // A unicode descriptor, as is used in unicode-range
- //
- // U+0?? or U+00A1-00A9
- //
- unicodeDescriptor: function unicodeDescriptor() {
- var ud;
- ud = parserInput.$re(/^U\+[0-9a-fA-F?]+(\-[0-9a-fA-F?]+)?/);
-
- if (ud) {
- return new tree.UnicodeDescriptor(ud[0]);
- }
- },
- //
- // JavaScript code to be evaluated
- //
- // `window.location.href`
- //
- javascript: function javascript() {
- var js;
- var index = parserInput.i;
- parserInput.save();
- var escape = parserInput.$char('~');
- var jsQuote = parserInput.$char('`');
-
- if (!jsQuote) {
- parserInput.restore();
- return;
- }
-
- js = parserInput.$re(/^[^`]*`/);
-
- if (js) {
- parserInput.forget();
- return new tree.JavaScript(js.substr(0, js.length - 1), Boolean(escape), index, fileInfo);
- }
-
- parserInput.restore('invalid javascript definition');
- }
- },
- //
- // The variable part of a variable definition. Used in the `rule` parser
- //
- // @fink:
- //
- variable: function variable() {
- var name;
-
- if (parserInput.currentChar() === '@' && (name = parserInput.$re(/^(@[\w-]+)\s*:/))) {
- return name[1];
- }
- },
- //
- // Call a variable value to retrieve a detached ruleset
- // or a value from a detached ruleset's rules.
- //
- // @fink();
- // @fink;
- // color: @fink[@color];
- //
- variableCall: function variableCall(parsedName) {
- var lookups;
- var important;
- var i = parserInput.i;
- var inValue = !!parsedName;
- var name = parsedName;
- parserInput.save();
-
- if (name || parserInput.currentChar() === '@' && (name = parserInput.$re(/^(@[\w-]+)(\(\s*\))?/))) {
- lookups = this.mixin.ruleLookups();
-
- if (!lookups && (inValue && parserInput.$str('()') !== '()' || name[2] !== '()')) {
- parserInput.restore('Missing \'[...]\' lookup in variable call');
- return;
- }
-
- if (!inValue) {
- name = name[1];
- }
-
- if (lookups && parsers.important()) {
- important = true;
- }
-
- var call = new tree.VariableCall(name, i, fileInfo);
-
- if (!inValue && parsers.end()) {
- parserInput.forget();
- return call;
- } else {
- parserInput.forget();
- return new tree.NamespaceValue(call, lookups, important, i, fileInfo);
- }
- }
-
- parserInput.restore();
- },
- //
- // extend syntax - used to extend selectors
- //
- extend: function extend(isRule) {
- var elements;
- var e;
- var index = parserInput.i;
- var option;
- var extendList;
- var extend;
-
- if (!parserInput.$str(isRule ? '&:extend(' : ':extend(')) {
- return;
- }
-
- do {
- option = null;
- elements = null;
-
- while (!(option = parserInput.$re(/^(all)(?=\s*(\)|,))/))) {
- e = this.element();
-
- if (!e) {
- break;
- }
-
- if (elements) {
- elements.push(e);
- } else {
- elements = [e];
- }
- }
-
- option = option && option[1];
-
- if (!elements) {
- error('Missing target selector for :extend().');
- }
-
- extend = new tree.Extend(new tree.Selector(elements), option, index, fileInfo);
-
- if (extendList) {
- extendList.push(extend);
- } else {
- extendList = [extend];
- }
- } while (parserInput.$char(','));
-
- expect(/^\)/);
-
- if (isRule) {
- expect(/^;/);
- }
-
- return extendList;
- },
- //
- // extendRule - used in a rule to extend all the parent selectors
- //
- extendRule: function extendRule() {
- return this.extend(true);
- },
- //
- // Mixins
- //
- mixin: {
- //
- // A Mixin call, with an optional argument list
- //
- // #mixins > .square(#fff);
- // #mixins.square(#fff);
- // .rounded(4px, black);
- // .button;
- //
- // We can lookup / return a value using the lookup syntax:
- //
- // color: #mixin.square(#fff)[@color];
- //
- // The `while` loop is there because mixins can be
- // namespaced, but we only support the child and descendant
- // selector for now.
- //
- call: function call(inValue, getLookup) {
- var s = parserInput.currentChar();
- var important = false;
- var lookups;
- var index = parserInput.i;
- var elements;
- var args;
- var hasParens;
-
- if (s !== '.' && s !== '#') {
- return;
- }
-
- parserInput.save(); // stop us absorbing part of an invalid selector
-
- elements = this.elements();
-
- if (elements) {
- if (parserInput.$char('(')) {
- args = this.args(true).args;
- expectChar(')');
- hasParens = true;
- }
-
- if (getLookup !== false) {
- lookups = this.ruleLookups();
- }
-
- if (getLookup === true && !lookups) {
- parserInput.restore();
- return;
- }
-
- if (inValue && !lookups && !hasParens) {
- // This isn't a valid in-value mixin call
- parserInput.restore();
- return;
- }
-
- if (!inValue && parsers.important()) {
- important = true;
- }
-
- if (inValue || parsers.end()) {
- parserInput.forget();
- var mixin = new tree.mixin.Call(elements, args, index, fileInfo, !lookups && important);
-
- if (lookups) {
- return new tree.NamespaceValue(mixin, lookups, important);
- } else {
- return mixin;
- }
- }
- }
-
- parserInput.restore();
- },
-
- /**
- * Matching elements for mixins
- * (Start with . or # and can have > )
- */
- elements: function elements() {
- var elements;
- var e;
- var c;
- var elem;
- var elemIndex;
- var re = /^[#.](?:[\w-]|\\(?:[A-Fa-f0-9]{1,6} ?|[^A-Fa-f0-9]))+/;
-
- while (true) {
- elemIndex = parserInput.i;
- e = parserInput.$re(re);
-
- if (!e) {
- break;
- }
-
- elem = new tree.Element(c, e, false, elemIndex, fileInfo);
-
- if (elements) {
- elements.push(elem);
- } else {
- elements = [elem];
- }
-
- c = parserInput.$char('>');
- }
-
- return elements;
- },
- args: function args(isCall) {
- var entities = parsers.entities;
- var returner = {
- args: null,
- variadic: false
- };
- var expressions = [];
- var argsSemiColon = [];
- var argsComma = [];
- var isSemiColonSeparated;
- var expressionContainsNamed;
- var name;
- var nameLoop;
- var value;
- var arg;
- var expand;
- var hasSep = true;
- parserInput.save();
-
- while (true) {
- if (isCall) {
- arg = parsers.detachedRuleset() || parsers.expression();
- } else {
- parserInput.commentStore.length = 0;
-
- if (parserInput.$str('...')) {
- returner.variadic = true;
-
- if (parserInput.$char(';') && !isSemiColonSeparated) {
- isSemiColonSeparated = true;
- }
-
- (isSemiColonSeparated ? argsSemiColon : argsComma).push({
- variadic: true
- });
- break;
- }
-
- arg = entities.variable() || entities.property() || entities.literal() || entities.keyword() || this.call(true);
- }
-
- if (!arg || !hasSep) {
- break;
- }
-
- nameLoop = null;
-
- if (arg.throwAwayComments) {
- arg.throwAwayComments();
- }
-
- value = arg;
- var val = null;
-
- if (isCall) {
- // Variable
- if (arg.value && arg.value.length == 1) {
- val = arg.value[0];
- }
- } else {
- val = arg;
- }
-
- if (val && (val instanceof tree.Variable || val instanceof tree.Property)) {
- if (parserInput.$char(':')) {
- if (expressions.length > 0) {
- if (isSemiColonSeparated) {
- error('Cannot mix ; and , as delimiter types');
- }
-
- expressionContainsNamed = true;
- }
-
- value = parsers.detachedRuleset() || parsers.expression();
-
- if (!value) {
- if (isCall) {
- error('could not understand value for named argument');
- } else {
- parserInput.restore();
- returner.args = [];
- return returner;
- }
- }
-
- nameLoop = name = val.name;
- } else if (parserInput.$str('...')) {
- if (!isCall) {
- returner.variadic = true;
-
- if (parserInput.$char(';') && !isSemiColonSeparated) {
- isSemiColonSeparated = true;
- }
-
- (isSemiColonSeparated ? argsSemiColon : argsComma).push({
- name: arg.name,
- variadic: true
- });
- break;
- } else {
- expand = true;
- }
- } else if (!isCall) {
- name = nameLoop = val.name;
- value = null;
- }
- }
-
- if (value) {
- expressions.push(value);
- }
-
- argsComma.push({
- name: nameLoop,
- value,
- expand
- });
-
- if (parserInput.$char(',')) {
- hasSep = true;
- continue;
- }
-
- hasSep = parserInput.$char(';') === ';';
-
- if (hasSep || isSemiColonSeparated) {
- if (expressionContainsNamed) {
- error('Cannot mix ; and , as delimiter types');
- }
-
- isSemiColonSeparated = true;
-
- if (expressions.length > 1) {
- value = new tree.Value(expressions);
- }
-
- argsSemiColon.push({
- name,
- value,
- expand
- });
- name = null;
- expressions = [];
- expressionContainsNamed = false;
- }
- }
-
- parserInput.forget();
- returner.args = isSemiColonSeparated ? argsSemiColon : argsComma;
- return returner;
- },
- //
- // A Mixin definition, with a list of parameters
- //
- // .rounded (@radius: 2px, @color) {
- // ...
- // }
- //
- // Until we have a finer grained state-machine, we have to
- // do a look-ahead, to make sure we don't have a mixin call.
- // See the `rule` function for more information.
- //
- // We start by matching `.rounded (`, and then proceed on to
- // the argument list, which has optional default values.
- // We store the parameters in `params`, with a `value` key,
- // if there is a value, such as in the case of `@radius`.
- //
- // Once we've got our params list, and a closing `)`, we parse
- // the `{...}` block.
- //
- definition: function definition() {
- var name;
- var params = [];
- var match;
- var ruleset;
- var cond;
- var variadic = false;
-
- if (parserInput.currentChar() !== '.' && parserInput.currentChar() !== '#' || parserInput.peek(/^[^{]*\}/)) {
- return;
- }
-
- parserInput.save();
- match = parserInput.$re(/^([#.](?:[\w-]|\\(?:[A-Fa-f0-9]{1,6} ?|[^A-Fa-f0-9]))+)\s*\(/);
-
- if (match) {
- name = match[1];
- var argInfo = this.args(false);
- params = argInfo.args;
- variadic = argInfo.variadic; // .mixincall("@{a}");
- // looks a bit like a mixin definition..
- // also
- // .mixincall(@a: {rule: set;});
- // so we have to be nice and restore
-
- if (!parserInput.$char(')')) {
- parserInput.restore('Missing closing \')\'');
- return;
- }
-
- parserInput.commentStore.length = 0;
-
- if (parserInput.$str('when')) {
- // Guard
- cond = expect(parsers.conditions, 'expected condition');
- }
-
- ruleset = parsers.block();
-
- if (ruleset) {
- parserInput.forget();
- return new tree.mixin.Definition(name, params, ruleset, cond, variadic);
- } else {
- parserInput.restore();
- }
- } else {
- parserInput.forget();
- }
- },
- ruleLookups: function ruleLookups() {
- var rule;
- var lookups = [];
-
- if (parserInput.currentChar() !== '[') {
- return;
- }
-
- while (true) {
- parserInput.save();
- rule = this.lookupValue();
-
- if (!rule && rule !== '') {
- parserInput.restore();
- break;
- }
-
- lookups.push(rule);
- parserInput.forget();
- }
-
- if (lookups.length > 0) {
- return lookups;
- }
- },
- lookupValue: function lookupValue() {
- parserInput.save();
-
- if (!parserInput.$char('[')) {
- parserInput.restore();
- return;
- }
-
- var name = parserInput.$re(/^(?:[@$]{0,2})[_a-zA-Z0-9-]*/);
-
- if (!parserInput.$char(']')) {
- parserInput.restore();
- return;
- }
-
- if (name || name === '') {
- parserInput.forget();
- return name;
- }
-
- parserInput.restore();
- }
- },
- //
- // Entities are the smallest recognized token,
- // and can be found inside a rule's value.
- //
- entity: function entity() {
- var entities = this.entities;
- return this.comment() || entities.literal() || entities.variable() || entities.url() || entities.property() || entities.call() || entities.keyword() || this.mixin.call(true) || entities.javascript();
- },
- //
- // A Declaration terminator. Note that we use `peek()` to check for '}',
- // because the `block` rule will be expecting it, but we still need to make sure
- // it's there, if ';' was omitted.
- //
- end: function end() {
- return parserInput.$char(';') || parserInput.peek('}');
- },
- //
- // IE's alpha function
- //
- // alpha(opacity=88)
- //
- ieAlpha: function ieAlpha() {
- var value; // http://jsperf.com/case-insensitive-regex-vs-strtolower-then-regex/18
-
- if (!parserInput.$re(/^opacity=/i)) {
- return;
- }
-
- value = parserInput.$re(/^\d+/);
-
- if (!value) {
- value = expect(parsers.entities.variable, 'Could not parse alpha');
- value = `@{${value.name.slice(1)}}`;
- }
-
- expectChar(')');
- return new tree.Quoted('', `alpha(opacity=${value})`);
- },
- //
- // A Selector Element
- //
- // div
- // + h1
- // #socks
- // input[type="text"]
- //
- // Elements are the building blocks for Selectors,
- // they are made out of a `Combinator` (see combinator rule),
- // and an element name, such as a tag a class, or `*`.
- //
- element: function element() {
- var e;
- var c;
- var v;
- var index = parserInput.i;
- c = this.combinator();
- e = parserInput.$re(/^(?:\d+\.\d+|\d+)%/) || parserInput.$re(/^(?:[.#]?|:*)(?:[\w-]|[^\x00-\x9f]|\\(?:[A-Fa-f0-9]{1,6} ?|[^A-Fa-f0-9]))+/) || parserInput.$char('*') || parserInput.$char('&') || this.attribute() || parserInput.$re(/^\([^&()@]+\)/) || parserInput.$re(/^[\.#:](?=@)/) || this.entities.variableCurly();
-
- if (!e) {
- parserInput.save();
-
- if (parserInput.$char('(')) {
- if ((v = this.selector(false)) && parserInput.$char(')')) {
- e = new tree.Paren(v);
- parserInput.forget();
- } else {
- parserInput.restore('Missing closing \')\'');
- }
- } else {
- parserInput.forget();
- }
- }
-
- if (e) {
- return new tree.Element(c, e, e instanceof tree.Variable, index, fileInfo);
- }
- },
- //
- // Combinators combine elements together, in a Selector.
- //
- // Because our parser isn't white-space sensitive, special care
- // has to be taken, when parsing the descendant combinator, ` `,
- // as it's an empty space. We have to check the previous character
- // in the input, to see if it's a ` ` character. More info on how
- // we deal with this in *combinator.js*.
- //
- combinator: function combinator() {
- var c = parserInput.currentChar();
-
- if (c === '/') {
- parserInput.save();
- var slashedCombinator = parserInput.$re(/^\/[a-z]+\//i);
-
- if (slashedCombinator) {
- parserInput.forget();
- return new tree.Combinator(slashedCombinator);
- }
-
- parserInput.restore();
- }
-
- if (c === '>' || c === '+' || c === '~' || c === '|' || c === '^') {
- parserInput.i++;
-
- if (c === '^' && parserInput.currentChar() === '^') {
- c = '^^';
- parserInput.i++;
- }
-
- while (parserInput.isWhitespace()) {
- parserInput.i++;
- }
-
- return new tree.Combinator(c);
- } else if (parserInput.isWhitespace(-1)) {
- return new tree.Combinator(' ');
- } else {
- return new tree.Combinator(null);
- }
- },
- //
- // A CSS Selector
- // with less extensions e.g. the ability to extend and guard
- //
- // .class > div + h1
- // li a:hover
- //
- // Selectors are made out of one or more Elements, see above.
- //
- selector: function selector(isLess) {
- var index = parserInput.i;
- var elements;
- var extendList;
- var c;
- var e;
- var allExtends;
- var when;
- var condition;
- isLess = isLess !== false;
-
- while (isLess && (extendList = this.extend()) || isLess && (when = parserInput.$str('when')) || (e = this.element())) {
- if (when) {
- condition = expect(this.conditions, 'expected condition');
- } else if (condition) {
- error('CSS guard can only be used at the end of selector');
- } else if (extendList) {
- if (allExtends) {
- allExtends = allExtends.concat(extendList);
- } else {
- allExtends = extendList;
- }
- } else {
- if (allExtends) {
- error('Extend can only be used at the end of selector');
- }
-
- c = parserInput.currentChar();
-
- if (elements) {
- elements.push(e);
- } else {
- elements = [e];
- }
-
- e = null;
- }
-
- if (c === '{' || c === '}' || c === ';' || c === ',' || c === ')') {
- break;
- }
- }
-
- if (elements) {
- return new tree.Selector(elements, allExtends, condition, index, fileInfo);
- }
-
- if (allExtends) {
- error('Extend must be used to extend a selector, it cannot be used on its own');
- }
- },
- selectors: function selectors() {
- var s;
- var selectors;
-
- while (true) {
- s = this.selector();
-
- if (!s) {
- break;
- }
-
- if (selectors) {
- selectors.push(s);
- } else {
- selectors = [s];
- }
-
- parserInput.commentStore.length = 0;
-
- if (s.condition && selectors.length > 1) {
- error("Guards are only currently allowed on a single selector.");
- }
-
- if (!parserInput.$char(',')) {
- break;
- }
-
- if (s.condition) {
- error("Guards are only currently allowed on a single selector.");
- }
-
- parserInput.commentStore.length = 0;
- }
-
- return selectors;
- },
- attribute: function attribute() {
- if (!parserInput.$char('[')) {
- return;
- }
-
- var entities = this.entities;
- var key;
- var val;
- var op;
-
- if (!(key = entities.variableCurly())) {
- key = expect(/^(?:[_A-Za-z0-9-\*]*\|)?(?:[_A-Za-z0-9-]|\\.)+/);
- }
-
- op = parserInput.$re(/^[|~*$^]?=/);
-
- if (op) {
- val = entities.quoted() || parserInput.$re(/^[0-9]+%/) || parserInput.$re(/^[\w-]+/) || entities.variableCurly();
- }
-
- expectChar(']');
- return new tree.Attribute(key, op, val);
- },
- //
- // The `block` rule is used by `ruleset` and `mixin.definition`.
- // It's a wrapper around the `primary` rule, with added `{}`.
- //
- block: function block() {
- var content;
-
- if (parserInput.$char('{') && (content = this.primary()) && parserInput.$char('}')) {
- return content;
- }
- },
- blockRuleset: function blockRuleset() {
- var block = this.block();
-
- if (block) {
- block = new tree.Ruleset(null, block);
- }
-
- return block;
- },
- detachedRuleset: function detachedRuleset() {
- var argInfo;
- var params;
- var variadic;
- parserInput.save();
-
- if (parserInput.$re(/^[.#]\(/)) {
- /**
- * DR args currently only implemented for each() function, and not
- * yet settable as `@dr: #(@arg) {}`
- * This should be done when DRs are merged with mixins.
- * See: https://github.com/less/less-meta/issues/16
- */
- argInfo = this.mixin.args(false);
- params = argInfo.args;
- variadic = argInfo.variadic;
-
- if (!parserInput.$char(')')) {
- parserInput.restore();
- return;
- }
- }
-
- var blockRuleset = this.blockRuleset();
-
- if (blockRuleset) {
- parserInput.forget();
-
- if (params) {
- return new tree.mixin.Definition(null, params, blockRuleset, null, variadic);
- }
-
- return new tree.DetachedRuleset(blockRuleset);
- }
-
- parserInput.restore();
- },
- //
- // div, .class, body > p {...}
- //
- ruleset: function ruleset() {
- var selectors;
- var rules;
- var debugInfo;
- parserInput.save();
-
- if (context.dumpLineNumbers) {
- debugInfo = getDebugInfo(parserInput.i);
- }
-
- selectors = this.selectors();
-
- if (selectors && (rules = this.block())) {
- parserInput.forget();
- var ruleset = new tree.Ruleset(selectors, rules, context.strictImports);
-
- if (context.dumpLineNumbers) {
- ruleset.debugInfo = debugInfo;
- }
-
- return ruleset;
- } else {
- parserInput.restore();
- }
- },
- declaration: function declaration() {
- var name;
- var value;
- var index = parserInput.i;
- var hasDR;
- var c = parserInput.currentChar();
- var important;
- var merge;
- var isVariable;
-
- if (c === '.' || c === '#' || c === '&' || c === ':') {
- return;
- }
-
- parserInput.save();
- name = this.variable() || this.ruleProperty();
-
- if (name) {
- isVariable = typeof name === 'string';
-
- if (isVariable) {
- value = this.detachedRuleset();
-
- if (value) {
- hasDR = true;
- }
- }
-
- parserInput.commentStore.length = 0;
-
- if (!value) {
- // a name returned by this.ruleProperty() is always an array of the form:
- // [string-1, ..., string-n, ""] or [string-1, ..., string-n, "+"]
- // where each item is a tree.Keyword or tree.Variable
- merge = !isVariable && name.length > 1 && name.pop().value; // Custom property values get permissive parsing
-
- if (name[0].value && name[0].value.slice(0, 2) === '--') {
- value = this.permissiveValue();
- } // Try to store values as anonymous
- // If we need the value later we'll re-parse it in ruleset.parseValue
- else {
- value = this.anonymousValue();
- }
-
- if (value) {
- parserInput.forget(); // anonymous values absorb the end ';' which is required for them to work
-
- return new tree.Declaration(name, value, false, merge, index, fileInfo);
- }
-
- if (!value) {
- value = this.value();
- }
-
- if (value) {
- important = this.important();
- } else if (isVariable) {
- // As a last resort, try permissiveValue
- value = this.permissiveValue();
- }
- }
-
- if (value && (this.end() || hasDR)) {
- parserInput.forget();
- return new tree.Declaration(name, value, important, merge, index, fileInfo);
- } else {
- parserInput.restore();
- }
- } else {
- parserInput.restore();
- }
- },
- anonymousValue: function anonymousValue() {
- var index = parserInput.i;
- var match = parserInput.$re(/^([^.#@\$+\/'"*`(;{}-]*);/);
-
- if (match) {
- return new tree.Anonymous(match[1], index);
- }
- },
-
- /**
- * Used for custom properties, at-rules, and variables (as fallback)
- * Parses almost anything inside of {} [] () "" blocks
- * until it reaches outer-most tokens.
- *
- * First, it will try to parse comments and entities to reach
- * the end. This is mostly like the Expression parser except no
- * math is allowed.
- */
- permissiveValue: function permissiveValue(untilTokens) {
- var i;
- var e;
- var done;
- var value;
- var tok = untilTokens || ';';
- var index = parserInput.i;
- var result = [];
-
- function testCurrentChar() {
- var char = parserInput.currentChar();
-
- if (typeof tok === 'string') {
- return char === tok;
- } else {
- return tok.test(char);
- }
- }
-
- if (testCurrentChar()) {
- return;
- }
-
- value = [];
-
- do {
- e = this.comment();
-
- if (e) {
- value.push(e);
- continue;
- }
-
- e = this.entity();
-
- if (e) {
- value.push(e);
- }
- } while (e);
-
- done = testCurrentChar();
-
- if (value.length > 0) {
- value = new tree.Expression(value);
-
- if (done) {
- return value;
- } else {
- result.push(value);
- } // Preserve space before $parseUntil as it will not
-
-
- if (parserInput.prevChar() === ' ') {
- result.push(new tree.Anonymous(' ', index));
- }
- }
-
- parserInput.save();
- value = parserInput.$parseUntil(tok);
-
- if (value) {
- if (typeof value === 'string') {
- error(`Expected '${value}'`, 'Parse');
- }
-
- if (value.length === 1 && value[0] === ' ') {
- parserInput.forget();
- return new tree.Anonymous('', index);
- }
-
- var item;
-
- for (i = 0; i < value.length; i++) {
- item = value[i];
-
- if (Array.isArray(item)) {
- // Treat actual quotes as normal quoted values
- result.push(new tree.Quoted(item[0], item[1], true, index, fileInfo));
- } else {
- if (i === value.length - 1) {
- item = item.trim();
- } // Treat like quoted values, but replace vars like unquoted expressions
-
-
- var quote = new tree.Quoted('\'', item, true, index, fileInfo);
- quote.variableRegex = /@([\w-]+)/g;
- quote.propRegex = /\$([\w-]+)/g;
- result.push(quote);
- }
- }
-
- parserInput.forget();
- return new tree.Expression(result, true);
- }
-
- parserInput.restore();
- },
- //
- // An @import atrule
- //
- // @import "lib";
- //
- // Depending on our environment, importing is done differently:
- // In the browser, it's an XHR request, in Node, it would be a
- // file-system operation. The function used for importing is
- // stored in `import`, which we pass to the Import constructor.
- //
- 'import': function _import() {
- var path;
- var features;
- var index = parserInput.i;
- var dir = parserInput.$re(/^@import?\s+/);
-
- if (dir) {
- var options = (dir ? this.importOptions() : null) || {};
-
- if (path = this.entities.quoted() || this.entities.url()) {
- features = this.mediaFeatures();
-
- if (!parserInput.$char(';')) {
- parserInput.i = index;
- error('missing semi-colon or unrecognised media features on import');
- }
-
- features = features && new tree.Value(features);
- return new tree.Import(path, features, options, index, fileInfo);
- } else {
- parserInput.i = index;
- error('malformed import statement');
- }
- }
- },
- importOptions: function importOptions() {
- var o;
- var options = {};
- var optionName;
- var value; // list of options, surrounded by parens
-
- if (!parserInput.$char('(')) {
- return null;
- }
-
- do {
- o = this.importOption();
-
- if (o) {
- optionName = o;
- value = true;
-
- switch (optionName) {
- case 'css':
- optionName = 'less';
- value = false;
- break;
-
- case 'once':
- optionName = 'multiple';
- value = false;
- break;
- }
-
- options[optionName] = value;
-
- if (!parserInput.$char(',')) {
- break;
- }
- }
- } while (o);
-
- expectChar(')');
- return options;
- },
- importOption: function importOption() {
- var opt = parserInput.$re(/^(less|css|multiple|once|inline|reference|optional)/);
-
- if (opt) {
- return opt[1];
- }
- },
- mediaFeature: function mediaFeature() {
- var entities = this.entities;
- var nodes = [];
- var e;
- var p;
- parserInput.save();
-
- do {
- e = entities.keyword() || entities.variable() || entities.mixinLookup();
-
- if (e) {
- nodes.push(e);
- } else if (parserInput.$char('(')) {
- p = this.property();
- e = this.value();
-
- if (parserInput.$char(')')) {
- if (p && e) {
- nodes.push(new tree.Paren(new tree.Declaration(p, e, null, null, parserInput.i, fileInfo, true)));
- } else if (e) {
- nodes.push(new tree.Paren(e));
- } else {
- error('badly formed media feature definition');
- }
- } else {
- error('Missing closing \')\'', 'Parse');
- }
- }
- } while (e);
-
- parserInput.forget();
-
- if (nodes.length > 0) {
- return new tree.Expression(nodes);
- }
- },
- mediaFeatures: function mediaFeatures() {
- var entities = this.entities;
- var features = [];
- var e;
-
- do {
- e = this.mediaFeature();
-
- if (e) {
- features.push(e);
-
- if (!parserInput.$char(',')) {
- break;
- }
- } else {
- e = entities.variable() || entities.mixinLookup();
-
- if (e) {
- features.push(e);
-
- if (!parserInput.$char(',')) {
- break;
- }
- }
- }
- } while (e);
-
- return features.length > 0 ? features : null;
- },
- media: function media() {
- var features;
- var rules;
- var media;
- var debugInfo;
- var index = parserInput.i;
-
- if (context.dumpLineNumbers) {
- debugInfo = getDebugInfo(index);
- }
-
- parserInput.save();
-
- if (parserInput.$str('@media')) {
- features = this.mediaFeatures();
- rules = this.block();
-
- if (!rules) {
- error('media definitions require block statements after any features');
- }
-
- parserInput.forget();
- media = new tree.Media(rules, features, index, fileInfo);
-
- if (context.dumpLineNumbers) {
- media.debugInfo = debugInfo;
- }
-
- return media;
- }
-
- parserInput.restore();
- },
- //
- // A @plugin directive, used to import plugins dynamically.
- //
- // @plugin (args) "lib";
- //
- plugin: function plugin() {
- var path;
- var args;
- var options;
- var index = parserInput.i;
- var dir = parserInput.$re(/^@plugin?\s+/);
-
- if (dir) {
- args = this.pluginArgs();
-
- if (args) {
- options = {
- pluginArgs: args,
- isPlugin: true
- };
- } else {
- options = {
- isPlugin: true
- };
- }
-
- if (path = this.entities.quoted() || this.entities.url()) {
- if (!parserInput.$char(';')) {
- parserInput.i = index;
- error('missing semi-colon on @plugin');
- }
-
- return new tree.Import(path, null, options, index, fileInfo);
- } else {
- parserInput.i = index;
- error('malformed @plugin statement');
- }
- }
- },
- pluginArgs: function pluginArgs() {
- // list of options, surrounded by parens
- parserInput.save();
-
- if (!parserInput.$char('(')) {
- parserInput.restore();
- return null;
- }
-
- var args = parserInput.$re(/^\s*([^\);]+)\)\s*/);
-
- if (args[1]) {
- parserInput.forget();
- return args[1].trim();
- } else {
- parserInput.restore();
- return null;
- }
- },
- //
- // A CSS AtRule
- //
- // @charset "utf-8";
- //
- atrule: function atrule() {
- var index = parserInput.i;
- var name;
- var value;
- var rules;
- var nonVendorSpecificName;
- var hasIdentifier;
- var hasExpression;
- var hasUnknown;
- var hasBlock = true;
- var isRooted = true;
-
- if (parserInput.currentChar() !== '@') {
- return;
- }
-
- value = this['import']() || this.plugin() || this.media();
-
- if (value) {
- return value;
- }
-
- parserInput.save();
- name = parserInput.$re(/^@[a-z-]+/);
-
- if (!name) {
- return;
- }
-
- nonVendorSpecificName = name;
-
- if (name.charAt(1) == '-' && name.indexOf('-', 2) > 0) {
- nonVendorSpecificName = `@${name.slice(name.indexOf('-', 2) + 1)}`;
- }
-
- switch (nonVendorSpecificName) {
- case '@charset':
- hasIdentifier = true;
- hasBlock = false;
- break;
-
- case '@namespace':
- hasExpression = true;
- hasBlock = false;
- break;
-
- case '@keyframes':
- case '@counter-style':
- hasIdentifier = true;
- break;
-
- case '@document':
- case '@supports':
- hasUnknown = true;
- isRooted = false;
- break;
-
- default:
- hasUnknown = true;
- break;
- }
-
- parserInput.commentStore.length = 0;
-
- if (hasIdentifier) {
- value = this.entity();
-
- if (!value) {
- error(`expected ${name} identifier`);
- }
- } else if (hasExpression) {
- value = this.expression();
-
- if (!value) {
- error(`expected ${name} expression`);
- }
- } else if (hasUnknown) {
- value = this.permissiveValue(/^[{;]/);
- hasBlock = parserInput.currentChar() === '{';
-
- if (!value) {
- if (!hasBlock && parserInput.currentChar() !== ';') {
- error(`${name} rule is missing block or ending semi-colon`);
- }
- } else if (!value.value) {
- value = null;
- }
- }
-
- if (hasBlock) {
- rules = this.blockRuleset();
- }
-
- if (rules || !hasBlock && value && parserInput.$char(';')) {
- parserInput.forget();
- return new tree.AtRule(name, value, rules, index, fileInfo, context.dumpLineNumbers ? getDebugInfo(index) : null, isRooted);
- }
-
- parserInput.restore('at-rule options not recognised');
- },
- //
- // A Value is a comma-delimited list of Expressions
- //
- // font-family: Baskerville, Georgia, serif;
- //
- // In a Rule, a Value represents everything after the `:`,
- // and before the `;`.
- //
- value: function value() {
- var e;
- var expressions = [];
- var index = parserInput.i;
-
- do {
- e = this.expression();
-
- if (e) {
- expressions.push(e);
-
- if (!parserInput.$char(',')) {
- break;
- }
- }
- } while (e);
-
- if (expressions.length > 0) {
- return new tree.Value(expressions, index);
- }
- },
- important: function important() {
- if (parserInput.currentChar() === '!') {
- return parserInput.$re(/^! *important/);
- }
- },
- sub: function sub() {
- var a;
- var e;
- parserInput.save();
-
- if (parserInput.$char('(')) {
- a = this.addition();
-
- if (a && parserInput.$char(')')) {
- parserInput.forget();
- e = new tree.Expression([a]);
- e.parens = true;
- return e;
- }
-
- parserInput.restore('Expected \')\'');
- return;
- }
-
- parserInput.restore();
- },
- multiplication: function multiplication() {
- var m;
- var a;
- var op;
- var operation;
- var isSpaced;
- m = this.operand();
-
- if (m) {
- isSpaced = parserInput.isWhitespace(-1);
-
- while (true) {
- if (parserInput.peek(/^\/[*\/]/)) {
- break;
- }
-
- parserInput.save();
- op = parserInput.$char('/') || parserInput.$char('*') || parserInput.$str('./');
-
- if (!op) {
- parserInput.forget();
- break;
- }
-
- a = this.operand();
-
- if (!a) {
- parserInput.restore();
- break;
- }
-
- parserInput.forget();
- m.parensInOp = true;
- a.parensInOp = true;
- operation = new tree.Operation(op, [operation || m, a], isSpaced);
- isSpaced = parserInput.isWhitespace(-1);
- }
-
- return operation || m;
- }
- },
- addition: function addition() {
- var m;
- var a;
- var op;
- var operation;
- var isSpaced;
- m = this.multiplication();
-
- if (m) {
- isSpaced = parserInput.isWhitespace(-1);
-
- while (true) {
- op = parserInput.$re(/^[-+]\s+/) || !isSpaced && (parserInput.$char('+') || parserInput.$char('-'));
-
- if (!op) {
- break;
- }
-
- a = this.multiplication();
-
- if (!a) {
- break;
- }
-
- m.parensInOp = true;
- a.parensInOp = true;
- operation = new tree.Operation(op, [operation || m, a], isSpaced);
- isSpaced = parserInput.isWhitespace(-1);
- }
-
- return operation || m;
- }
- },
- conditions: function conditions() {
- var a;
- var b;
- var index = parserInput.i;
- var condition;
- a = this.condition(true);
-
- if (a) {
- while (true) {
- if (!parserInput.peek(/^,\s*(not\s*)?\(/) || !parserInput.$char(',')) {
- break;
- }
-
- b = this.condition(true);
-
- if (!b) {
- break;
- }
-
- condition = new tree.Condition('or', condition || a, b, index);
- }
-
- return condition || a;
- }
- },
- condition: function condition(needsParens) {
- var result;
- var logical;
- var next;
-
- function or() {
- return parserInput.$str('or');
- }
-
- result = this.conditionAnd(needsParens);
-
- if (!result) {
- return;
- }
-
- logical = or();
-
- if (logical) {
- next = this.condition(needsParens);
-
- if (next) {
- result = new tree.Condition(logical, result, next);
- } else {
- return;
- }
- }
-
- return result;
- },
- conditionAnd: function conditionAnd(needsParens) {
- var result;
- var logical;
- var next;
- var self = this;
-
- function insideCondition() {
- var cond = self.negatedCondition(needsParens) || self.parenthesisCondition(needsParens);
-
- if (!cond && !needsParens) {
- return self.atomicCondition(needsParens);
- }
-
- return cond;
- }
-
- function and() {
- return parserInput.$str('and');
- }
-
- result = insideCondition();
-
- if (!result) {
- return;
- }
-
- logical = and();
-
- if (logical) {
- next = this.conditionAnd(needsParens);
-
- if (next) {
- result = new tree.Condition(logical, result, next);
- } else {
- return;
- }
- }
-
- return result;
- },
- negatedCondition: function negatedCondition(needsParens) {
- if (parserInput.$str('not')) {
- var result = this.parenthesisCondition(needsParens);
-
- if (result) {
- result.negate = !result.negate;
- }
-
- return result;
- }
- },
- parenthesisCondition: function parenthesisCondition(needsParens) {
- function tryConditionFollowedByParenthesis(me) {
- var body;
- parserInput.save();
- body = me.condition(needsParens);
-
- if (!body) {
- parserInput.restore();
- return;
- }
-
- if (!parserInput.$char(')')) {
- parserInput.restore();
- return;
- }
-
- parserInput.forget();
- return body;
- }
-
- var body;
- parserInput.save();
-
- if (!parserInput.$str('(')) {
- parserInput.restore();
- return;
- }
-
- body = tryConditionFollowedByParenthesis(this);
-
- if (body) {
- parserInput.forget();
- return body;
- }
-
- body = this.atomicCondition(needsParens);
-
- if (!body) {
- parserInput.restore();
- return;
- }
-
- if (!parserInput.$char(')')) {
- parserInput.restore(`expected ')' got '${parserInput.currentChar()}'`);
- return;
- }
-
- parserInput.forget();
- return body;
- },
- atomicCondition: function atomicCondition(needsParens) {
- var entities = this.entities;
- var index = parserInput.i;
- var a;
- var b;
- var c;
- var op;
-
- function cond() {
- return this.addition() || entities.keyword() || entities.quoted() || entities.mixinLookup();
- }
-
- cond = cond.bind(this);
- a = cond();
-
- if (a) {
- if (parserInput.$char('>')) {
- if (parserInput.$char('=')) {
- op = '>=';
- } else {
- op = '>';
- }
- } else if (parserInput.$char('<')) {
- if (parserInput.$char('=')) {
- op = '<=';
- } else {
- op = '<';
- }
- } else if (parserInput.$char('=')) {
- if (parserInput.$char('>')) {
- op = '=>';
- } else if (parserInput.$char('<')) {
- op = '=<';
- } else {
- op = '=';
- }
- }
-
- if (op) {
- b = cond();
-
- if (b) {
- c = new tree.Condition(op, a, b, index, false);
- } else {
- error('expected expression');
- }
- } else {
- c = new tree.Condition('=', a, new tree.Keyword('true'), index, false);
- }
-
- return c;
- }
- },
- //
- // An operand is anything that can be part of an operation,
- // such as a Color, or a Variable
- //
- operand: function operand() {
- var entities = this.entities;
- var negate;
-
- if (parserInput.peek(/^-[@\$\(]/)) {
- negate = parserInput.$char('-');
- }
-
- var o = this.sub() || entities.dimension() || entities.color() || entities.variable() || entities.property() || entities.call() || entities.quoted(true) || entities.colorKeyword() || entities.mixinLookup();
-
- if (negate) {
- o.parensInOp = true;
- o = new tree.Negative(o);
- }
-
- return o;
- },
- //
- // Expressions either represent mathematical operations,
- // or white-space delimited Entities.
- //
- // 1px solid black
- // @var * 2
- //
- expression: function expression() {
- var entities = [];
- var e;
- var delim;
- var index = parserInput.i;
-
- do {
- e = this.comment();
-
- if (e) {
- entities.push(e);
- continue;
- }
-
- e = this.addition() || this.entity();
-
- if (e) {
- entities.push(e); // operations do not allow keyword "/" dimension (e.g. small/20px) so we support that here
-
- if (!parserInput.peek(/^\/[\/*]/)) {
- delim = parserInput.$char('/');
-
- if (delim) {
- entities.push(new tree.Anonymous(delim, index));
- }
- }
- }
- } while (e);
-
- if (entities.length > 0) {
- return new tree.Expression(entities);
- }
- },
- property: function property() {
- var name = parserInput.$re(/^(\*?-?[_a-zA-Z0-9-]+)\s*:/);
-
- if (name) {
- return name[1];
- }
- },
- ruleProperty: function ruleProperty() {
- var name = [];
- var index = [];
- var s;
- var k;
- parserInput.save();
- var simpleProperty = parserInput.$re(/^([_a-zA-Z0-9-]+)\s*:/);
-
- if (simpleProperty) {
- name = [new tree.Keyword(simpleProperty[1])];
- parserInput.forget();
- return name;
- }
-
- function match(re) {
- var i = parserInput.i;
- var chunk = parserInput.$re(re);
-
- if (chunk) {
- index.push(i);
- return name.push(chunk[1]);
- }
- }
-
- match(/^(\*?)/);
-
- while (true) {
- if (!match(/^((?:[\w-]+)|(?:[@\$]\{[\w-]+\}))/)) {
- break;
- }
- }
-
- if (name.length > 1 && match(/^((?:\+_|\+)?)\s*:/)) {
- parserInput.forget(); // at last, we have the complete match now. move forward,
- // convert name particles to tree objects and return:
-
- if (name[0] === '') {
- name.shift();
- index.shift();
- }
-
- for (k = 0; k < name.length; k++) {
- s = name[k];
- name[k] = s.charAt(0) !== '@' && s.charAt(0) !== '$' ? new tree.Keyword(s) : s.charAt(0) === '@' ? new tree.Variable(`@${s.slice(2, -1)}`, index[k], fileInfo) : new tree.Property(`$${s.slice(2, -1)}`, index[k], fileInfo);
- }
-
- return name;
- }
-
- parserInput.restore();
- }
- }
- };
-};
-
-Parser.serializeVars = function (vars) {
- var s = '';
-
- for (var name in vars) {
- if (Object.hasOwnProperty.call(vars, name)) {
- var value = vars[name];
- s += `${(name[0] === '@' ? '' : '@') + name}: ${value}${String(value).slice(-1) === ';' ? '' : ';'}`;
- }
- }
-
- return s;
-};
-
-function boolean(condition) {
- return condition ? Keyword.True : Keyword.False;
-}
-
-function If(condition, trueValue, falseValue) {
- return condition ? trueValue : falseValue || new Anonymous();
-}
-
-var boolean$1 = {
- boolean,
- 'if': If
-};
-
-var colorFunctions;
-
-function clamp$1(val) {
- return Math.min(1, Math.max(0, val));
-}
-
-function hsla(origColor, hsl) {
- var color = colorFunctions.hsla(hsl.h, hsl.s, hsl.l, hsl.a);
-
- if (color) {
- if (origColor.value && /^(rgb|hsl)/.test(origColor.value)) {
- color.value = origColor.value;
- } else {
- color.value = 'rgb';
- }
-
- return color;
- }
-}
-
-function toHSL(color) {
- if (color.toHSL) {
- return color.toHSL();
- } else {
- throw new Error('Argument cannot be evaluated to a color');
- }
-}
-
-function toHSV(color) {
- if (color.toHSV) {
- return color.toHSV();
- } else {
- throw new Error('Argument cannot be evaluated to a color');
- }
-}
-
-function number(n) {
- if (n instanceof Dimension) {
- return parseFloat(n.unit.is('%') ? n.value / 100 : n.value);
- } else if (typeof n === 'number') {
- return n;
- } else {
- throw {
- type: 'Argument',
- message: 'color functions take numbers as parameters'
- };
- }
-}
-
-function scaled(n, size) {
- if (n instanceof Dimension && n.unit.is('%')) {
- return parseFloat(n.value * size / 100);
- } else {
- return number(n);
- }
-}
-
-colorFunctions = {
- rgb: function rgb(r, g, b) {
- var color = colorFunctions.rgba(r, g, b, 1.0);
-
- if (color) {
- color.value = 'rgb';
- return color;
- }
- },
- rgba: function rgba(r, g, b, a) {
- try {
- if (r instanceof Color) {
- if (g) {
- a = number(g);
- } else {
- a = r.alpha;
- }
-
- return new Color(r.rgb, a, 'rgba');
- }
-
- var rgb = [r, g, b].map(function (c) {
- return scaled(c, 255);
- });
- a = number(a);
- return new Color(rgb, a, 'rgba');
- } catch (e) {}
- },
- hsl: function hsl(h, s, l) {
- var color = colorFunctions.hsla(h, s, l, 1.0);
-
- if (color) {
- color.value = 'hsl';
- return color;
- }
- },
- hsla: function hsla(h, s, l, a) {
- try {
- if (h instanceof Color) {
- if (s) {
- a = number(s);
- } else {
- a = h.alpha;
- }
-
- return new Color(h.rgb, a, 'hsla');
- }
-
- var m1;
- var m2;
-
- function hue(h) {
- h = h < 0 ? h + 1 : h > 1 ? h - 1 : h;
-
- if (h * 6 < 1) {
- return m1 + (m2 - m1) * h * 6;
- } else if (h * 2 < 1) {
- return m2;
- } else if (h * 3 < 2) {
- return m1 + (m2 - m1) * (2 / 3 - h) * 6;
- } else {
- return m1;
- }
- }
-
- h = number(h) % 360 / 360;
- s = clamp$1(number(s));
- l = clamp$1(number(l));
- a = clamp$1(number(a));
- m2 = l <= 0.5 ? l * (s + 1) : l + s - l * s;
- m1 = l * 2 - m2;
- var rgb = [hue(h + 1 / 3) * 255, hue(h) * 255, hue(h - 1 / 3) * 255];
- a = number(a);
- return new Color(rgb, a, 'hsla');
- } catch (e) {}
- },
- hsv: function hsv(h, s, v) {
- return colorFunctions.hsva(h, s, v, 1.0);
- },
- hsva: function hsva(h, s, v, a) {
- h = number(h) % 360 / 360 * 360;
- s = number(s);
- v = number(v);
- a = number(a);
- var i;
- var f;
- i = Math.floor(h / 60 % 6);
- f = h / 60 - i;
- var vs = [v, v * (1 - s), v * (1 - f * s), v * (1 - (1 - f) * s)];
- var perm = [[0, 3, 1], [2, 0, 1], [1, 0, 3], [1, 2, 0], [3, 1, 0], [0, 1, 2]];
- return colorFunctions.rgba(vs[perm[i][0]] * 255, vs[perm[i][1]] * 255, vs[perm[i][2]] * 255, a);
- },
- hue: function hue(color) {
- return new Dimension(toHSL(color).h);
- },
- saturation: function saturation(color) {
- return new Dimension(toHSL(color).s * 100, '%');
- },
- lightness: function lightness(color) {
- return new Dimension(toHSL(color).l * 100, '%');
- },
- hsvhue: function hsvhue(color) {
- return new Dimension(toHSV(color).h);
- },
- hsvsaturation: function hsvsaturation(color) {
- return new Dimension(toHSV(color).s * 100, '%');
- },
- hsvvalue: function hsvvalue(color) {
- return new Dimension(toHSV(color).v * 100, '%');
- },
- red: function red(color) {
- return new Dimension(color.rgb[0]);
- },
- green: function green(color) {
- return new Dimension(color.rgb[1]);
- },
- blue: function blue(color) {
- return new Dimension(color.rgb[2]);
- },
- alpha: function alpha(color) {
- return new Dimension(toHSL(color).a);
- },
- luma: function luma(color) {
- return new Dimension(color.luma() * color.alpha * 100, '%');
- },
- luminance: function luminance(color) {
- var luminance = 0.2126 * color.rgb[0] / 255 + 0.7152 * color.rgb[1] / 255 + 0.0722 * color.rgb[2] / 255;
- return new Dimension(luminance * color.alpha * 100, '%');
- },
- saturate: function saturate(color, amount, method) {
- // filter: saturate(3.2);
- // should be kept as is, so check for color
- if (!color.rgb) {
- return null;
- }
-
- var hsl = toHSL(color);
-
- if (typeof method !== 'undefined' && method.value === 'relative') {
- hsl.s += hsl.s * amount.value / 100;
- } else {
- hsl.s += amount.value / 100;
- }
-
- hsl.s = clamp$1(hsl.s);
- return hsla(color, hsl);
- },
- desaturate: function desaturate(color, amount, method) {
- var hsl = toHSL(color);
-
- if (typeof method !== 'undefined' && method.value === 'relative') {
- hsl.s -= hsl.s * amount.value / 100;
- } else {
- hsl.s -= amount.value / 100;
- }
-
- hsl.s = clamp$1(hsl.s);
- return hsla(color, hsl);
- },
- lighten: function lighten(color, amount, method) {
- var hsl = toHSL(color);
-
- if (typeof method !== 'undefined' && method.value === 'relative') {
- hsl.l += hsl.l * amount.value / 100;
- } else {
- hsl.l += amount.value / 100;
- }
-
- hsl.l = clamp$1(hsl.l);
- return hsla(color, hsl);
- },
- darken: function darken(color, amount, method) {
- var hsl = toHSL(color);
-
- if (typeof method !== 'undefined' && method.value === 'relative') {
- hsl.l -= hsl.l * amount.value / 100;
- } else {
- hsl.l -= amount.value / 100;
- }
-
- hsl.l = clamp$1(hsl.l);
- return hsla(color, hsl);
- },
- fadein: function fadein(color, amount, method) {
- var hsl = toHSL(color);
-
- if (typeof method !== 'undefined' && method.value === 'relative') {
- hsl.a += hsl.a * amount.value / 100;
- } else {
- hsl.a += amount.value / 100;
- }
-
- hsl.a = clamp$1(hsl.a);
- return hsla(color, hsl);
- },
- fadeout: function fadeout(color, amount, method) {
- var hsl = toHSL(color);
-
- if (typeof method !== 'undefined' && method.value === 'relative') {
- hsl.a -= hsl.a * amount.value / 100;
- } else {
- hsl.a -= amount.value / 100;
- }
-
- hsl.a = clamp$1(hsl.a);
- return hsla(color, hsl);
- },
- fade: function fade(color, amount) {
- var hsl = toHSL(color);
- hsl.a = amount.value / 100;
- hsl.a = clamp$1(hsl.a);
- return hsla(color, hsl);
- },
- spin: function spin(color, amount) {
- var hsl = toHSL(color);
- var hue = (hsl.h + amount.value) % 360;
- hsl.h = hue < 0 ? 360 + hue : hue;
- return hsla(color, hsl);
- },
- //
- // Copyright (c) 2006-2009 Hampton Catlin, Natalie Weizenbaum, and Chris Eppstein
- // http://sass-lang.com
- //
- mix: function mix(color1, color2, weight) {
- if (!weight) {
- weight = new Dimension(50);
- }
-
- var p = weight.value / 100.0;
- var w = p * 2 - 1;
- var a = toHSL(color1).a - toHSL(color2).a;
- var w1 = ((w * a == -1 ? w : (w + a) / (1 + w * a)) + 1) / 2.0;
- var w2 = 1 - w1;
- var rgb = [color1.rgb[0] * w1 + color2.rgb[0] * w2, color1.rgb[1] * w1 + color2.rgb[1] * w2, color1.rgb[2] * w1 + color2.rgb[2] * w2];
- var alpha = color1.alpha * p + color2.alpha * (1 - p);
- return new Color(rgb, alpha);
- },
- greyscale: function greyscale(color) {
- return colorFunctions.desaturate(color, new Dimension(100));
- },
- contrast: function contrast(color, dark, light, threshold) {
- // filter: contrast(3.2);
- // should be kept as is, so check for color
- if (!color.rgb) {
- return null;
- }
-
- if (typeof light === 'undefined') {
- light = colorFunctions.rgba(255, 255, 255, 1.0);
- }
-
- if (typeof dark === 'undefined') {
- dark = colorFunctions.rgba(0, 0, 0, 1.0);
- } // Figure out which is actually light and dark:
-
-
- if (dark.luma() > light.luma()) {
- var t = light;
- light = dark;
- dark = t;
- }
-
- if (typeof threshold === 'undefined') {
- threshold = 0.43;
- } else {
- threshold = number(threshold);
- }
-
- if (color.luma() < threshold) {
- return light;
- } else {
- return dark;
- }
- },
- // Changes made in 2.7.0 - Reverted in 3.0.0
- // contrast: function (color, color1, color2, threshold) {
- // // Return which of `color1` and `color2` has the greatest contrast with `color`
- // // according to the standard WCAG contrast ratio calculation.
- // // http://www.w3.org/TR/WCAG20/#contrast-ratiodef
- // // The threshold param is no longer used, in line with SASS.
- // // filter: contrast(3.2);
- // // should be kept as is, so check for color
- // if (!color.rgb) {
- // return null;
- // }
- // if (typeof color1 === 'undefined') {
- // color1 = colorFunctions.rgba(0, 0, 0, 1.0);
- // }
- // if (typeof color2 === 'undefined') {
- // color2 = colorFunctions.rgba(255, 255, 255, 1.0);
- // }
- // var contrast1, contrast2;
- // var luma = color.luma();
- // var luma1 = color1.luma();
- // var luma2 = color2.luma();
- // // Calculate contrast ratios for each color
- // if (luma > luma1) {
- // contrast1 = (luma + 0.05) / (luma1 + 0.05);
- // } else {
- // contrast1 = (luma1 + 0.05) / (luma + 0.05);
- // }
- // if (luma > luma2) {
- // contrast2 = (luma + 0.05) / (luma2 + 0.05);
- // } else {
- // contrast2 = (luma2 + 0.05) / (luma + 0.05);
- // }
- // if (contrast1 > contrast2) {
- // return color1;
- // } else {
- // return color2;
- // }
- // },
- argb: function argb(color) {
- return new Anonymous(color.toARGB());
- },
- color: function color(c) {
- if (c instanceof Quoted && /^#([A-Fa-f0-9]{8}|[A-Fa-f0-9]{6}|[A-Fa-f0-9]{3,4})$/i.test(c.value)) {
- var val = c.value.slice(1);
- return new Color(val, undefined, `#${val}`);
- }
-
- if (c instanceof Color || (c = Color.fromKeyword(c.value))) {
- c.value = undefined;
- return c;
- }
-
- throw {
- type: 'Argument',
- message: 'argument must be a color keyword or 3|4|6|8 digit hex e.g. #FFF'
- };
- },
- tint: function tint(color, amount) {
- return colorFunctions.mix(colorFunctions.rgb(255, 255, 255), color, amount);
- },
- shade: function shade(color, amount) {
- return colorFunctions.mix(colorFunctions.rgb(0, 0, 0), color, amount);
- }
-};
-var color = colorFunctions;
-
-// ref: http://www.w3.org/TR/compositing-1
-
-function colorBlend(mode, color1, color2) {
- var ab = color1.alpha; // result
-
- var // backdrop
- cb;
- var as = color2.alpha;
- var // source
- cs;
- var ar;
- var cr;
- var r = [];
- ar = as + ab * (1 - as);
-
- for (var i = 0; i < 3; i++) {
- cb = color1.rgb[i] / 255;
- cs = color2.rgb[i] / 255;
- cr = mode(cb, cs);
-
- if (ar) {
- cr = (as * cs + ab * (cb - as * (cb + cs - cr))) / ar;
- }
-
- r[i] = cr * 255;
- }
-
- return new Color(r, ar);
-}
-
-var colorBlendModeFunctions = {
- multiply: function multiply(cb, cs) {
- return cb * cs;
- },
- screen: function screen(cb, cs) {
- return cb + cs - cb * cs;
- },
- overlay: function overlay(cb, cs) {
- cb *= 2;
- return cb <= 1 ? colorBlendModeFunctions.multiply(cb, cs) : colorBlendModeFunctions.screen(cb - 1, cs);
- },
- softlight: function softlight(cb, cs) {
- var d = 1;
- var e = cb;
-
- if (cs > 0.5) {
- e = 1;
- d = cb > 0.25 ? Math.sqrt(cb) : ((16 * cb - 12) * cb + 4) * cb;
- }
-
- return cb - (1 - 2 * cs) * e * (d - cb);
- },
- hardlight: function hardlight(cb, cs) {
- return colorBlendModeFunctions.overlay(cs, cb);
- },
- difference: function difference(cb, cs) {
- return Math.abs(cb - cs);
- },
- exclusion: function exclusion(cb, cs) {
- return cb + cs - 2 * cb * cs;
- },
- // non-w3c functions:
- average: function average(cb, cs) {
- return (cb + cs) / 2;
- },
- negation: function negation(cb, cs) {
- return 1 - Math.abs(cb + cs - 1);
- }
-};
-
-for (var f in colorBlendModeFunctions) {
- if (colorBlendModeFunctions.hasOwnProperty(f)) {
- colorBlend[f] = colorBlend.bind(null, colorBlendModeFunctions[f]);
- }
-}
-
-var dataUri = (function (environment) {
- var fallback = function fallback(functionThis, node) {
- return new URL(node, functionThis.index, functionThis.currentFileInfo).eval(functionThis.context);
- };
-
- return {
- 'data-uri': function dataUri(mimetypeNode, filePathNode) {
- if (!filePathNode) {
- filePathNode = mimetypeNode;
- mimetypeNode = null;
- }
-
- var mimetype = mimetypeNode && mimetypeNode.value;
- var filePath = filePathNode.value;
- var currentFileInfo = this.currentFileInfo;
- var currentDirectory = currentFileInfo.rewriteUrls ? currentFileInfo.currentDirectory : currentFileInfo.entryPath;
- var fragmentStart = filePath.indexOf('#');
- var fragment = '';
-
- if (fragmentStart !== -1) {
- fragment = filePath.slice(fragmentStart);
- filePath = filePath.slice(0, fragmentStart);
- }
-
- var context = clone(this.context);
- context.rawBuffer = true;
- var fileManager = environment.getFileManager(filePath, currentDirectory, context, environment, true);
-
- if (!fileManager) {
- return fallback(this, filePathNode);
- }
-
- var useBase64 = false; // detect the mimetype if not given
-
- if (!mimetypeNode) {
- mimetype = environment.mimeLookup(filePath);
-
- if (mimetype === 'image/svg+xml') {
- useBase64 = false;
- } else {
- // use base 64 unless it's an ASCII or UTF-8 format
- var charset = environment.charsetLookup(mimetype);
- useBase64 = ['US-ASCII', 'UTF-8'].indexOf(charset) < 0;
- }
-
- if (useBase64) {
- mimetype += ';base64';
- }
- } else {
- useBase64 = /;base64$/.test(mimetype);
- }
-
- var fileSync = fileManager.loadFileSync(filePath, currentDirectory, context, environment);
-
- if (!fileSync.contents) {
- logger.warn(`Skipped data-uri embedding of ${filePath} because file not found`);
- return fallback(this, filePathNode || mimetypeNode);
- }
-
- var buf = fileSync.contents;
-
- if (useBase64 && !environment.encodeBase64) {
- return fallback(this, filePathNode);
- }
-
- buf = useBase64 ? environment.encodeBase64(buf) : encodeURIComponent(buf);
- var uri = `data:${mimetype},${buf}${fragment}`;
- return new URL(new Quoted(`"${uri}"`, uri, false, this.index, this.currentFileInfo), this.index, this.currentFileInfo);
- }
- };
-});
-
-var getItemsFromNode = function getItemsFromNode(node) {
- // handle non-array values as an array of length 1
- // return 'undefined' if index is invalid
- var items = Array.isArray(node.value) ? node.value : Array(node);
- return items;
-};
-
-var list = {
- _SELF: function _SELF(n) {
- return n;
- },
- extract: function extract(values, index) {
- // (1-based index)
- index = index.value - 1;
- return getItemsFromNode(values)[index];
- },
- length: function length(values) {
- return new Dimension(getItemsFromNode(values).length);
- },
-
- /**
- * Creates a Less list of incremental values.
- * Modeled after Lodash's range function, also exists natively in PHP
- *
- * @param {Dimension} [start=1]
- * @param {Dimension} end - e.g. 10 or 10px - unit is added to output
- * @param {Dimension} [step=1]
- */
- range: function range(start, end, step) {
- var from;
- var to;
- var stepValue = 1;
- var list = [];
-
- if (end) {
- to = end;
- from = start.value;
-
- if (step) {
- stepValue = step.value;
- }
- } else {
- from = 1;
- to = start;
- }
-
- for (var i = from; i <= to.value; i += stepValue) {
- list.push(new Dimension(i, to.unit));
- }
-
- return new Expression(list);
- },
- each: function each(list, rs) {
- var rules = [];
- var newRules;
- var iterator;
-
- if (list.value && !(list instanceof Quoted)) {
- if (Array.isArray(list.value)) {
- iterator = list.value;
- } else {
- iterator = [list.value];
- }
- } else if (list.ruleset) {
- iterator = list.ruleset.rules;
- } else if (list.rules) {
- iterator = list.rules;
- } else if (Array.isArray(list)) {
- iterator = list;
- } else {
- iterator = [list];
- }
-
- var valueName = '@value';
- var keyName = '@key';
- var indexName = '@index';
-
- if (rs.params) {
- valueName = rs.params[0] && rs.params[0].name;
- keyName = rs.params[1] && rs.params[1].name;
- indexName = rs.params[2] && rs.params[2].name;
- rs = rs.rules;
- } else {
- rs = rs.ruleset;
- }
-
- for (var i = 0; i < iterator.length; i++) {
- var key = void 0;
- var value = void 0;
- var item = iterator[i];
-
- if (item instanceof Declaration) {
- key = typeof item.name === 'string' ? item.name : item.name[0].value;
- value = item.value;
- } else {
- key = new Dimension(i + 1);
- value = item;
- }
-
- if (item instanceof Comment) {
- continue;
- }
-
- newRules = rs.rules.slice(0);
-
- if (valueName) {
- newRules.push(new Declaration(valueName, value, false, false, this.index, this.currentFileInfo));
- }
-
- if (indexName) {
- newRules.push(new Declaration(indexName, new Dimension(i + 1), false, false, this.index, this.currentFileInfo));
- }
-
- if (keyName) {
- newRules.push(new Declaration(keyName, key, false, false, this.index, this.currentFileInfo));
- }
-
- rules.push(new Ruleset([new Selector([new Element("", '&')])], newRules, rs.strictImports, rs.visibilityInfo()));
- }
-
- return new Ruleset([new Selector([new Element("", '&')])], rules, rs.strictImports, rs.visibilityInfo()).eval(this.context);
- }
-};
-
-var MathHelper = function MathHelper(fn, unit, n) {
- if (!(n instanceof Dimension)) {
- throw {
- type: 'Argument',
- message: 'argument must be a number'
- };
- }
-
- if (unit == null) {
- unit = n.unit;
- } else {
- n = n.unify();
- }
-
- return new Dimension(fn(parseFloat(n.value)), unit);
-};
-
-var mathFunctions = {
- // name, unit
- ceil: null,
- floor: null,
- sqrt: null,
- abs: null,
- tan: '',
- sin: '',
- cos: '',
- atan: 'rad',
- asin: 'rad',
- acos: 'rad'
-};
-
-for (var f$1 in mathFunctions) {
- if (mathFunctions.hasOwnProperty(f$1)) {
- mathFunctions[f$1] = MathHelper.bind(null, Math[f$1], mathFunctions[f$1]);
- }
-}
-
-mathFunctions.round = function (n, f) {
- var fraction = typeof f === 'undefined' ? 0 : f.value;
- return MathHelper(function (num) {
- return num.toFixed(fraction);
- }, null, n);
-};
-
-var minMax = function minMax(isMin, args) {
- args = Array.prototype.slice.call(args);
-
- switch (args.length) {
- case 0:
- throw {
- type: 'Argument',
- message: 'one or more arguments required'
- };
- }
-
- var i; // key is the unit.toString() for unified Dimension values,
-
- var j;
- var current;
- var currentUnified;
- var referenceUnified;
- var unit;
- var unitStatic;
- var unitClone;
- var // elems only contains original argument values.
- order = [];
- var values = {}; // value is the index into the order array.
-
- for (i = 0; i < args.length; i++) {
- current = args[i];
-
- if (!(current instanceof Dimension)) {
- if (Array.isArray(args[i].value)) {
- Array.prototype.push.apply(args, Array.prototype.slice.call(args[i].value));
- }
-
- continue;
- }
-
- currentUnified = current.unit.toString() === '' && unitClone !== undefined ? new Dimension(current.value, unitClone).unify() : current.unify();
- unit = currentUnified.unit.toString() === '' && unitStatic !== undefined ? unitStatic : currentUnified.unit.toString();
- unitStatic = unit !== '' && unitStatic === undefined || unit !== '' && order[0].unify().unit.toString() === '' ? unit : unitStatic;
- unitClone = unit !== '' && unitClone === undefined ? current.unit.toString() : unitClone;
- j = values[''] !== undefined && unit !== '' && unit === unitStatic ? values[''] : values[unit];
-
- if (j === undefined) {
- if (unitStatic !== undefined && unit !== unitStatic) {
- throw {
- type: 'Argument',
- message: 'incompatible types'
- };
- }
-
- values[unit] = order.length;
- order.push(current);
- continue;
- }
-
- referenceUnified = order[j].unit.toString() === '' && unitClone !== undefined ? new Dimension(order[j].value, unitClone).unify() : order[j].unify();
-
- if (isMin && currentUnified.value < referenceUnified.value || !isMin && currentUnified.value > referenceUnified.value) {
- order[j] = current;
- }
- }
-
- if (order.length == 1) {
- return order[0];
- }
-
- args = order.map(function (a) {
- return a.toCSS(this.context);
- }).join(this.context.compress ? ',' : ', ');
- return new Anonymous(`${isMin ? 'min' : 'max'}(${args})`);
-};
-
-var number$1 = {
- min: function min() {
- for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
- args[_key] = arguments[_key];
- }
-
- return minMax(true, args);
- },
- max: function max() {
- for (var _len2 = arguments.length, args = new Array(_len2), _key2 = 0; _key2 < _len2; _key2++) {
- args[_key2] = arguments[_key2];
- }
-
- return minMax(false, args);
- },
- convert: function convert(val, unit) {
- return val.convertTo(unit.value);
- },
- pi: function pi() {
- return new Dimension(Math.PI);
- },
- mod: function mod(a, b) {
- return new Dimension(a.value % b.value, a.unit);
- },
- pow: function pow(x, y) {
- if (typeof x === 'number' && typeof y === 'number') {
- x = new Dimension(x);
- y = new Dimension(y);
- } else if (!(x instanceof Dimension) || !(y instanceof Dimension)) {
- throw {
- type: 'Argument',
- message: 'arguments must be numbers'
- };
- }
-
- return new Dimension(Math.pow(x.value, y.value), x.unit);
- },
- percentage: function percentage(n) {
- var result = MathHelper(function (num) {
- return num * 100;
- }, '%', n);
- return result;
- }
-};
-
-var string = {
- e: function e(str) {
- return new Quoted('"', str instanceof JavaScript ? str.evaluated : str.value, true);
- },
- escape: function escape(str) {
- return new Anonymous(encodeURI(str.value).replace(/=/g, '%3D').replace(/:/g, '%3A').replace(/#/g, '%23').replace(/;/g, '%3B').replace(/\(/g, '%28').replace(/\)/g, '%29'));
- },
- replace: function replace(string, pattern, replacement, flags) {
- var result = string.value;
- replacement = replacement.type === 'Quoted' ? replacement.value : replacement.toCSS();
- result = result.replace(new RegExp(pattern.value, flags ? flags.value : ''), replacement);
- return new Quoted(string.quote || '', result, string.escaped);
- },
- '%': function _(string
- /* arg, arg, ... */
- ) {
- var args = Array.prototype.slice.call(arguments, 1);
- var result = string.value;
-
- var _loop = function _loop(i) {
- /* jshint loopfunc:true */
- result = result.replace(/%[sda]/i, function (token) {
- var value = args[i].type === 'Quoted' && token.match(/s/i) ? args[i].value : args[i].toCSS();
- return token.match(/[A-Z]$/) ? encodeURIComponent(value) : value;
- });
- };
-
- for (var i = 0; i < args.length; i++) {
- _loop(i);
- }
-
- result = result.replace(/%%/g, '%');
- return new Quoted(string.quote || '', result, string.escaped);
- }
-};
-
-var svg = (function (environment) {
- return {
- 'svg-gradient': function svgGradient(direction) {
- var stops;
- var gradientDirectionSvg;
- var gradientType = 'linear';
- var rectangleDimension = 'x="0" y="0" width="1" height="1"';
- var renderEnv = {
- compress: false
- };
- var returner;
- var directionValue = direction.toCSS(renderEnv);
- var i;
- var color;
- var position;
- var positionValue;
- var alpha;
-
- function throwArgumentDescriptor() {
- throw {
- type: 'Argument',
- message: 'svg-gradient expects direction, start_color [start_position], [color position,]...,' + ' end_color [end_position] or direction, color list'
- };
- }
-
- if (arguments.length == 2) {
- if (arguments[1].value.length < 2) {
- throwArgumentDescriptor();
- }
-
- stops = arguments[1].value;
- } else if (arguments.length < 3) {
- throwArgumentDescriptor();
- } else {
- stops = Array.prototype.slice.call(arguments, 1);
- }
-
- switch (directionValue) {
- case 'to bottom':
- gradientDirectionSvg = 'x1="0%" y1="0%" x2="0%" y2="100%"';
- break;
-
- case 'to right':
- gradientDirectionSvg = 'x1="0%" y1="0%" x2="100%" y2="0%"';
- break;
-
- case 'to bottom right':
- gradientDirectionSvg = 'x1="0%" y1="0%" x2="100%" y2="100%"';
- break;
-
- case 'to top right':
- gradientDirectionSvg = 'x1="0%" y1="100%" x2="100%" y2="0%"';
- break;
-
- case 'ellipse':
- case 'ellipse at center':
- gradientType = 'radial';
- gradientDirectionSvg = 'cx="50%" cy="50%" r="75%"';
- rectangleDimension = 'x="-50" y="-50" width="101" height="101"';
- break;
-
- default:
- throw {
- type: 'Argument',
- message: 'svg-gradient direction must be \'to bottom\', \'to right\',' + ' \'to bottom right\', \'to top right\' or \'ellipse at center\''
- };
- }
-
- returner = ``;
- returner = encodeURIComponent(returner);
- returner = `data:image/svg+xml,${returner}`;
- return new URL(new Quoted(`'${returner}'`, returner, false, this.index, this.currentFileInfo), this.index, this.currentFileInfo);
- }
- };
-});
-
-var isa = function isa(n, Type) {
- return n instanceof Type ? Keyword.True : Keyword.False;
-};
-
-var isunit = function isunit(n, unit) {
- if (unit === undefined) {
- throw {
- type: 'Argument',
- message: 'missing the required second argument to isunit.'
- };
- }
-
- unit = typeof unit.value === 'string' ? unit.value : unit;
-
- if (typeof unit !== 'string') {
- throw {
- type: 'Argument',
- message: 'Second argument to isunit should be a unit or a string.'
- };
- }
-
- return n instanceof Dimension && n.unit.is(unit) ? Keyword.True : Keyword.False;
-};
-
-var types = {
- isruleset: function isruleset(n) {
- return isa(n, DetachedRuleset);
- },
- iscolor: function iscolor(n) {
- return isa(n, Color);
- },
- isnumber: function isnumber(n) {
- return isa(n, Dimension);
- },
- isstring: function isstring(n) {
- return isa(n, Quoted);
- },
- iskeyword: function iskeyword(n) {
- return isa(n, Keyword);
- },
- isurl: function isurl(n) {
- return isa(n, URL);
- },
- ispixel: function ispixel(n) {
- return isunit(n, 'px');
- },
- ispercentage: function ispercentage(n) {
- return isunit(n, '%');
- },
- isem: function isem(n) {
- return isunit(n, 'em');
- },
- isunit,
- unit: function unit(val, _unit) {
- if (!(val instanceof Dimension)) {
- throw {
- type: 'Argument',
- message: `the first argument to unit must be a number${val instanceof Operation ? '. Have you forgotten parenthesis?' : ''}`
- };
- }
-
- if (_unit) {
- if (_unit instanceof Keyword) {
- _unit = _unit.value;
- } else {
- _unit = _unit.toCSS();
- }
- } else {
- _unit = '';
- }
-
- return new Dimension(val.value, _unit);
- },
- 'get-unit': function getUnit(n) {
- return new Anonymous(n.unit);
- }
-};
-
-var Functions = (function (environment) {
- var functions = {
- functionRegistry,
- functionCaller
- }; // register functions
-
- functionRegistry.addMultiple(boolean$1);
- functionRegistry.add('default', defaultFunc.eval.bind(defaultFunc));
- functionRegistry.addMultiple(color);
- functionRegistry.addMultiple(colorBlend);
- functionRegistry.addMultiple(dataUri(environment));
- functionRegistry.addMultiple(list);
- functionRegistry.addMultiple(mathFunctions);
- functionRegistry.addMultiple(number$1);
- functionRegistry.addMultiple(string);
- functionRegistry.addMultiple(svg());
- functionRegistry.addMultiple(types);
- return functions;
-});
-
-var sourceMapOutput = (function (environment) {
- var SourceMapOutput =
- /*#__PURE__*/
- function () {
- function SourceMapOutput(options) {
- _classCallCheck(this, SourceMapOutput);
-
- this._css = [];
- this._rootNode = options.rootNode;
- this._contentsMap = options.contentsMap;
- this._contentsIgnoredCharsMap = options.contentsIgnoredCharsMap;
-
- if (options.sourceMapFilename) {
- this._sourceMapFilename = options.sourceMapFilename.replace(/\\/g, '/');
- }
-
- this._outputFilename = options.outputFilename;
- this.sourceMapURL = options.sourceMapURL;
-
- if (options.sourceMapBasepath) {
- this._sourceMapBasepath = options.sourceMapBasepath.replace(/\\/g, '/');
- }
-
- if (options.sourceMapRootpath) {
- this._sourceMapRootpath = options.sourceMapRootpath.replace(/\\/g, '/');
-
- if (this._sourceMapRootpath.charAt(this._sourceMapRootpath.length - 1) !== '/') {
- this._sourceMapRootpath += '/';
- }
- } else {
- this._sourceMapRootpath = '';
- }
-
- this._outputSourceFiles = options.outputSourceFiles;
- this._sourceMapGeneratorConstructor = environment.getSourceMapGenerator();
- this._lineNumber = 0;
- this._column = 0;
- }
-
- _createClass(SourceMapOutput, [{
- key: "removeBasepath",
- value: function removeBasepath(path) {
- if (this._sourceMapBasepath && path.indexOf(this._sourceMapBasepath) === 0) {
- path = path.substring(this._sourceMapBasepath.length);
-
- if (path.charAt(0) === '\\' || path.charAt(0) === '/') {
- path = path.substring(1);
- }
- }
-
- return path;
- }
- }, {
- key: "normalizeFilename",
- value: function normalizeFilename(filename) {
- filename = filename.replace(/\\/g, '/');
- filename = this.removeBasepath(filename);
- return (this._sourceMapRootpath || '') + filename;
- }
- }, {
- key: "add",
- value: function add(chunk, fileInfo, index, mapLines) {
- // ignore adding empty strings
- if (!chunk) {
- return;
- }
-
- var lines;
- var sourceLines;
- var columns;
- var sourceColumns;
- var i;
-
- if (fileInfo && fileInfo.filename) {
- var inputSource = this._contentsMap[fileInfo.filename]; // remove vars/banner added to the top of the file
-
- if (this._contentsIgnoredCharsMap[fileInfo.filename]) {
- // adjust the index
- index -= this._contentsIgnoredCharsMap[fileInfo.filename];
-
- if (index < 0) {
- index = 0;
- } // adjust the source
-
-
- inputSource = inputSource.slice(this._contentsIgnoredCharsMap[fileInfo.filename]);
- } // ignore empty content
-
-
- if (inputSource === undefined) {
- return;
- }
-
- inputSource = inputSource.substring(0, index);
- sourceLines = inputSource.split('\n');
- sourceColumns = sourceLines[sourceLines.length - 1];
- }
-
- lines = chunk.split('\n');
- columns = lines[lines.length - 1];
-
- if (fileInfo && fileInfo.filename) {
- if (!mapLines) {
- this._sourceMapGenerator.addMapping({
- generated: {
- line: this._lineNumber + 1,
- column: this._column
- },
- original: {
- line: sourceLines.length,
- column: sourceColumns.length
- },
- source: this.normalizeFilename(fileInfo.filename)
- });
- } else {
- for (i = 0; i < lines.length; i++) {
- this._sourceMapGenerator.addMapping({
- generated: {
- line: this._lineNumber + i + 1,
- column: i === 0 ? this._column : 0
- },
- original: {
- line: sourceLines.length + i,
- column: i === 0 ? sourceColumns.length : 0
- },
- source: this.normalizeFilename(fileInfo.filename)
- });
- }
- }
- }
-
- if (lines.length === 1) {
- this._column += columns.length;
- } else {
- this._lineNumber += lines.length - 1;
- this._column = columns.length;
- }
-
- this._css.push(chunk);
- }
- }, {
- key: "isEmpty",
- value: function isEmpty() {
- return this._css.length === 0;
- }
- }, {
- key: "toCSS",
- value: function toCSS(context) {
- this._sourceMapGenerator = new this._sourceMapGeneratorConstructor({
- file: this._outputFilename,
- sourceRoot: null
- });
-
- if (this._outputSourceFiles) {
- for (var filename in this._contentsMap) {
- if (this._contentsMap.hasOwnProperty(filename)) {
- var source = this._contentsMap[filename];
-
- if (this._contentsIgnoredCharsMap[filename]) {
- source = source.slice(this._contentsIgnoredCharsMap[filename]);
- }
-
- this._sourceMapGenerator.setSourceContent(this.normalizeFilename(filename), source);
- }
- }
- }
-
- this._rootNode.genCSS(context, this);
-
- if (this._css.length > 0) {
- var sourceMapURL;
- var sourceMapContent = JSON.stringify(this._sourceMapGenerator.toJSON());
-
- if (this.sourceMapURL) {
- sourceMapURL = this.sourceMapURL;
- } else if (this._sourceMapFilename) {
- sourceMapURL = this._sourceMapFilename;
- }
-
- this.sourceMapURL = sourceMapURL;
- this.sourceMap = sourceMapContent;
- }
-
- return this._css.join('');
- }
- }]);
-
- return SourceMapOutput;
- }();
-
- return SourceMapOutput;
-});
-
-var sourceMapBuilder = (function (SourceMapOutput, environment) {
- var SourceMapBuilder =
- /*#__PURE__*/
- function () {
- function SourceMapBuilder(options) {
- _classCallCheck(this, SourceMapBuilder);
-
- this.options = options;
- }
-
- _createClass(SourceMapBuilder, [{
- key: "toCSS",
- value: function toCSS(rootNode, options, imports) {
- var sourceMapOutput = new SourceMapOutput({
- contentsIgnoredCharsMap: imports.contentsIgnoredChars,
- rootNode,
- contentsMap: imports.contents,
- sourceMapFilename: this.options.sourceMapFilename,
- sourceMapURL: this.options.sourceMapURL,
- outputFilename: this.options.sourceMapOutputFilename,
- sourceMapBasepath: this.options.sourceMapBasepath,
- sourceMapRootpath: this.options.sourceMapRootpath,
- outputSourceFiles: this.options.outputSourceFiles,
- sourceMapGenerator: this.options.sourceMapGenerator,
- sourceMapFileInline: this.options.sourceMapFileInline
- });
- var css = sourceMapOutput.toCSS(options);
- this.sourceMap = sourceMapOutput.sourceMap;
- this.sourceMapURL = sourceMapOutput.sourceMapURL;
-
- if (this.options.sourceMapInputFilename) {
- this.sourceMapInputFilename = sourceMapOutput.normalizeFilename(this.options.sourceMapInputFilename);
- }
-
- if (this.options.sourceMapBasepath !== undefined && this.sourceMapURL !== undefined) {
- this.sourceMapURL = sourceMapOutput.removeBasepath(this.sourceMapURL);
- }
-
- return css + this.getCSSAppendage();
- }
- }, {
- key: "getCSSAppendage",
- value: function getCSSAppendage() {
- var sourceMapURL = this.sourceMapURL;
-
- if (this.options.sourceMapFileInline) {
- if (this.sourceMap === undefined) {
- return '';
- }
-
- sourceMapURL = `data:application/json;base64,${environment.encodeBase64(this.sourceMap)}`;
- }
-
- if (sourceMapURL) {
- return `/*# sourceMappingURL=${sourceMapURL} */`;
- }
-
- return '';
- }
- }, {
- key: "getExternalSourceMap",
- value: function getExternalSourceMap() {
- return this.sourceMap;
- }
- }, {
- key: "setExternalSourceMap",
- value: function setExternalSourceMap(sourceMap) {
- this.sourceMap = sourceMap;
- }
- }, {
- key: "isInline",
- value: function isInline() {
- return this.options.sourceMapFileInline;
- }
- }, {
- key: "getSourceMapURL",
- value: function getSourceMapURL() {
- return this.sourceMapURL;
- }
- }, {
- key: "getOutputFilename",
- value: function getOutputFilename() {
- return this.options.sourceMapOutputFilename;
- }
- }, {
- key: "getInputFilename",
- value: function getInputFilename() {
- return this.sourceMapInputFilename;
- }
- }]);
-
- return SourceMapBuilder;
- }();
-
- return SourceMapBuilder;
-});
-
-var transformTree = (function (root) {
- var options = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};
- var evaldRoot;
- var variables = options.variables;
- var evalEnv = new contexts.Eval(options); //
- // Allows setting variables with a hash, so:
- //
- // `{ color: new tree.Color('#f01') }` will become:
- //
- // new tree.Declaration('@color',
- // new tree.Value([
- // new tree.Expression([
- // new tree.Color('#f01')
- // ])
- // ])
- // )
- //
-
- if (typeof variables === 'object' && !Array.isArray(variables)) {
- variables = Object.keys(variables).map(function (k) {
- var value = variables[k];
-
- if (!(value instanceof tree.Value)) {
- if (!(value instanceof tree.Expression)) {
- value = new tree.Expression([value]);
- }
-
- value = new tree.Value([value]);
- }
-
- return new tree.Declaration(`@${k}`, value, false, null, 0);
- });
- evalEnv.frames = [new tree.Ruleset(null, variables)];
- }
-
- var visitors$1 = [new visitors.JoinSelectorVisitor(), new visitors.MarkVisibleSelectorsVisitor(true), new visitors.ExtendVisitor(), new visitors.ToCSSVisitor({
- compress: Boolean(options.compress)
- })];
- var preEvalVisitors = [];
- var v;
- var visitorIterator;
- /**
- * first() / get() allows visitors to be added while visiting
- *
- * @todo Add scoping for visitors just like functions for @plugin; right now they're global
- */
-
- if (options.pluginManager) {
- visitorIterator = options.pluginManager.visitor();
-
- for (var i = 0; i < 2; i++) {
- visitorIterator.first();
-
- while (v = visitorIterator.get()) {
- if (v.isPreEvalVisitor) {
- if (i === 0 || preEvalVisitors.indexOf(v) === -1) {
- preEvalVisitors.push(v);
- v.run(root);
- }
- } else {
- if (i === 0 || visitors$1.indexOf(v) === -1) {
- if (v.isPreVisitor) {
- visitors$1.unshift(v);
- } else {
- visitors$1.push(v);
- }
- }
- }
- }
- }
- }
-
- evaldRoot = root.eval(evalEnv);
-
- for (var i = 0; i < visitors$1.length; i++) {
- visitors$1[i].run(evaldRoot);
- } // Run any remaining visitors added after eval pass
-
-
- if (options.pluginManager) {
- visitorIterator.first();
-
- while (v = visitorIterator.get()) {
- if (visitors$1.indexOf(v) === -1 && preEvalVisitors.indexOf(v) === -1) {
- v.run(evaldRoot);
- }
- }
- }
-
- return evaldRoot;
-});
-
-var parseTree = (function (SourceMapBuilder) {
- var ParseTree =
- /*#__PURE__*/
- function () {
- function ParseTree(root, imports) {
- _classCallCheck(this, ParseTree);
-
- this.root = root;
- this.imports = imports;
- }
-
- _createClass(ParseTree, [{
- key: "toCSS",
- value: function toCSS(options) {
- var evaldRoot;
- var result = {};
- var sourceMapBuilder;
-
- try {
- evaldRoot = transformTree(this.root, options);
- } catch (e) {
- throw new LessError(e, this.imports);
- }
-
- try {
- var compress = Boolean(options.compress);
-
- if (compress) {
- logger.warn('The compress option has been deprecated. ' + 'We recommend you use a dedicated css minifier, for instance see less-plugin-clean-css.');
- }
-
- var toCSSOptions = {
- compress,
- dumpLineNumbers: options.dumpLineNumbers,
- strictUnits: Boolean(options.strictUnits),
- numPrecision: 8
- };
-
- if (options.sourceMap) {
- sourceMapBuilder = new SourceMapBuilder(options.sourceMap);
- result.css = sourceMapBuilder.toCSS(evaldRoot, toCSSOptions, this.imports);
- } else {
- result.css = evaldRoot.toCSS(toCSSOptions);
- }
- } catch (e) {
- throw new LessError(e, this.imports);
- }
-
- if (options.pluginManager) {
- var postProcessors = options.pluginManager.getPostProcessors();
-
- for (var i = 0; i < postProcessors.length; i++) {
- result.css = postProcessors[i].process(result.css, {
- sourceMap: sourceMapBuilder,
- options,
- imports: this.imports
- });
- }
- }
-
- if (options.sourceMap) {
- result.map = sourceMapBuilder.getExternalSourceMap();
- }
-
- result.imports = [];
-
- for (var file in this.imports.files) {
- if (this.imports.files.hasOwnProperty(file) && file !== this.imports.rootFilename) {
- result.imports.push(file);
- }
- }
-
- return result;
- }
- }]);
-
- return ParseTree;
- }();
-
- return ParseTree;
-});
-
-var importManager = (function (environment) {
- // FileInfo = {
- // 'rewriteUrls' - option - whether to adjust URL's to be relative
- // 'filename' - full resolved filename of current file
- // 'rootpath' - path to append to normal URLs for this node
- // 'currentDirectory' - path to the current file, absolute
- // 'rootFilename' - filename of the base file
- // 'entryPath' - absolute path to the entry file
- // 'reference' - whether the file should not be output and only output parts that are referenced
- var ImportManager =
- /*#__PURE__*/
- function () {
- function ImportManager(less, context, rootFileInfo) {
- _classCallCheck(this, ImportManager);
-
- this.less = less;
- this.rootFilename = rootFileInfo.filename;
- this.paths = context.paths || []; // Search paths, when importing
-
- this.contents = {}; // map - filename to contents of all the files
-
- this.contentsIgnoredChars = {}; // map - filename to lines at the beginning of each file to ignore
-
- this.mime = context.mime;
- this.error = null;
- this.context = context; // Deprecated? Unused outside of here, could be useful.
-
- this.queue = []; // Files which haven't been imported yet
-
- this.files = {}; // Holds the imported parse trees.
- }
- /**
- * Add an import to be imported
- * @param path - the raw path
- * @param tryAppendExtension - whether to try appending a file extension (.less or .js if the path has no extension)
- * @param currentFileInfo - the current file info (used for instance to work out relative paths)
- * @param importOptions - import options
- * @param callback - callback for when it is imported
- */
-
-
- _createClass(ImportManager, [{
- key: "push",
- value: function push(path, tryAppendExtension, currentFileInfo, importOptions, callback) {
- var importManager = this;
- var pluginLoader = this.context.pluginManager.Loader;
- this.queue.push(path);
-
- var fileParsedFunc = function fileParsedFunc(e, root, fullPath) {
- importManager.queue.splice(importManager.queue.indexOf(path), 1); // Remove the path from the queue
-
- var importedEqualsRoot = fullPath === importManager.rootFilename;
-
- if (importOptions.optional && e) {
- callback(null, {
- rules: []
- }, false, null);
- logger.info(`The file ${fullPath} was skipped because it was not found and the import was marked optional.`);
- } else {
- // Inline imports aren't cached here.
- // If we start to cache them, please make sure they won't conflict with non-inline imports of the
- // same name as they used to do before this comment and the condition below have been added.
- if (!importManager.files[fullPath] && !importOptions.inline) {
- importManager.files[fullPath] = {
- root,
- options: importOptions
- };
- }
-
- if (e && !importManager.error) {
- importManager.error = e;
- }
-
- callback(e, root, importedEqualsRoot, fullPath);
- }
- };
-
- var newFileInfo = {
- rewriteUrls: this.context.rewriteUrls,
- entryPath: currentFileInfo.entryPath,
- rootpath: currentFileInfo.rootpath,
- rootFilename: currentFileInfo.rootFilename
- };
- var fileManager = environment.getFileManager(path, currentFileInfo.currentDirectory, this.context, environment);
-
- if (!fileManager) {
- fileParsedFunc({
- message: `Could not find a file-manager for ${path}`
- });
- return;
- }
-
- var loadFileCallback = function loadFileCallback(loadedFile) {
- var plugin;
- var resolvedFilename = loadedFile.filename;
- var contents = loadedFile.contents.replace(/^\uFEFF/, ''); // Pass on an updated rootpath if path of imported file is relative and file
- // is in a (sub|sup) directory
- //
- // Examples:
- // - If path of imported file is 'module/nav/nav.less' and rootpath is 'less/',
- // then rootpath should become 'less/module/nav/'
- // - If path of imported file is '../mixins.less' and rootpath is 'less/',
- // then rootpath should become 'less/../'
-
- newFileInfo.currentDirectory = fileManager.getPath(resolvedFilename);
-
- if (newFileInfo.rewriteUrls) {
- newFileInfo.rootpath = fileManager.join(importManager.context.rootpath || '', fileManager.pathDiff(newFileInfo.currentDirectory, newFileInfo.entryPath));
-
- if (!fileManager.isPathAbsolute(newFileInfo.rootpath) && fileManager.alwaysMakePathsAbsolute()) {
- newFileInfo.rootpath = fileManager.join(newFileInfo.entryPath, newFileInfo.rootpath);
- }
- }
-
- newFileInfo.filename = resolvedFilename;
- var newEnv = new contexts.Parse(importManager.context);
- newEnv.processImports = false;
- importManager.contents[resolvedFilename] = contents;
-
- if (currentFileInfo.reference || importOptions.reference) {
- newFileInfo.reference = true;
- }
-
- if (importOptions.isPlugin) {
- plugin = pluginLoader.evalPlugin(contents, newEnv, importManager, importOptions.pluginArgs, newFileInfo);
-
- if (plugin instanceof LessError) {
- fileParsedFunc(plugin, null, resolvedFilename);
- } else {
- fileParsedFunc(null, plugin, resolvedFilename);
- }
- } else if (importOptions.inline) {
- fileParsedFunc(null, contents, resolvedFilename);
- } else {
- // import (multiple) parse trees apparently get altered and can't be cached.
- // TODO: investigate why this is
- if (importManager.files[resolvedFilename] && !importManager.files[resolvedFilename].options.multiple && !importOptions.multiple) {
- fileParsedFunc(null, importManager.files[resolvedFilename].root, resolvedFilename);
- } else {
- new Parser(newEnv, importManager, newFileInfo).parse(contents, function (e, root) {
- fileParsedFunc(e, root, resolvedFilename);
- });
- }
- }
- };
-
- var promise;
- var context = clone(this.context);
-
- if (tryAppendExtension) {
- context.ext = importOptions.isPlugin ? '.js' : '.less';
- }
-
- if (importOptions.isPlugin) {
- context.mime = 'application/javascript';
- promise = pluginLoader.loadPlugin(path, currentFileInfo.currentDirectory, context, environment, fileManager);
- } else {
- promise = fileManager.loadFile(path, currentFileInfo.currentDirectory, context, environment, function (err, loadedFile) {
- if (err) {
- fileParsedFunc(err);
- } else {
- loadFileCallback(loadedFile);
- }
- });
- }
-
- if (promise) {
- promise.then(loadFileCallback, fileParsedFunc);
- }
- }
- }]);
-
- return ImportManager;
- }();
-
- return ImportManager;
-});
-
-var Render = (function (environment, ParseTree, ImportManager) {
- var render = function render(input, options, callback) {
- if (typeof options === 'function') {
- callback = options;
- options = copyOptions(this.options, {});
- } else {
- options = copyOptions(this.options, options || {});
- }
-
- if (!callback) {
- var self = this;
- return new Promise(function (resolve, reject) {
- render.call(self, input, options, function (err, output) {
- if (err) {
- reject(err);
- } else {
- resolve(output);
- }
- });
- });
- } else {
- this.parse(input, options, function (err, root, imports, options) {
- if (err) {
- return callback(err);
- }
-
- var result;
-
- try {
- var parseTree = new ParseTree(root, imports);
- result = parseTree.toCSS(options);
- } catch (err) {
- return callback(err);
- }
-
- callback(null, result);
- });
- }
- };
-
- return render;
-});
-
-/**
- * Plugin Manager
- */
-var PluginManager =
-/*#__PURE__*/
-function () {
- function PluginManager(less) {
- _classCallCheck(this, PluginManager);
-
- this.less = less;
- this.visitors = [];
- this.preProcessors = [];
- this.postProcessors = [];
- this.installedPlugins = [];
- this.fileManagers = [];
- this.iterator = -1;
- this.pluginCache = {};
- this.Loader = new less.PluginLoader(less);
- }
- /**
- * Adds all the plugins in the array
- * @param {Array} plugins
- */
-
-
- _createClass(PluginManager, [{
- key: "addPlugins",
- value: function addPlugins(plugins) {
- if (plugins) {
- for (var i = 0; i < plugins.length; i++) {
- this.addPlugin(plugins[i]);
- }
- }
- }
- /**
- *
- * @param plugin
- * @param {String} filename
- */
-
- }, {
- key: "addPlugin",
- value: function addPlugin(plugin, filename, functionRegistry) {
- this.installedPlugins.push(plugin);
-
- if (filename) {
- this.pluginCache[filename] = plugin;
- }
-
- if (plugin.install) {
- plugin.install(this.less, this, functionRegistry || this.less.functions.functionRegistry);
- }
- }
- /**
- *
- * @param filename
- */
-
- }, {
- key: "get",
- value: function get(filename) {
- return this.pluginCache[filename];
- }
- /**
- * Adds a visitor. The visitor object has options on itself to determine
- * when it should run.
- * @param visitor
- */
-
- }, {
- key: "addVisitor",
- value: function addVisitor(visitor) {
- this.visitors.push(visitor);
- }
- /**
- * Adds a pre processor object
- * @param {object} preProcessor
- * @param {number} priority - guidelines 1 = before import, 1000 = import, 2000 = after import
- */
-
- }, {
- key: "addPreProcessor",
- value: function addPreProcessor(preProcessor, priority) {
- var indexToInsertAt;
-
- for (indexToInsertAt = 0; indexToInsertAt < this.preProcessors.length; indexToInsertAt++) {
- if (this.preProcessors[indexToInsertAt].priority >= priority) {
- break;
- }
- }
-
- this.preProcessors.splice(indexToInsertAt, 0, {
- preProcessor,
- priority
- });
- }
- /**
- * Adds a post processor object
- * @param {object} postProcessor
- * @param {number} priority - guidelines 1 = before compression, 1000 = compression, 2000 = after compression
- */
-
- }, {
- key: "addPostProcessor",
- value: function addPostProcessor(postProcessor, priority) {
- var indexToInsertAt;
-
- for (indexToInsertAt = 0; indexToInsertAt < this.postProcessors.length; indexToInsertAt++) {
- if (this.postProcessors[indexToInsertAt].priority >= priority) {
- break;
- }
- }
-
- this.postProcessors.splice(indexToInsertAt, 0, {
- postProcessor,
- priority
- });
- }
- /**
- *
- * @param manager
- */
-
- }, {
- key: "addFileManager",
- value: function addFileManager(manager) {
- this.fileManagers.push(manager);
- }
- /**
- *
- * @returns {Array}
- * @private
- */
-
- }, {
- key: "getPreProcessors",
- value: function getPreProcessors() {
- var preProcessors = [];
-
- for (var i = 0; i < this.preProcessors.length; i++) {
- preProcessors.push(this.preProcessors[i].preProcessor);
- }
-
- return preProcessors;
- }
- /**
- *
- * @returns {Array}
- * @private
- */
-
- }, {
- key: "getPostProcessors",
- value: function getPostProcessors() {
- var postProcessors = [];
-
- for (var i = 0; i < this.postProcessors.length; i++) {
- postProcessors.push(this.postProcessors[i].postProcessor);
- }
-
- return postProcessors;
- }
- /**
- *
- * @returns {Array}
- * @private
- */
-
- }, {
- key: "getVisitors",
- value: function getVisitors() {
- return this.visitors;
- }
- }, {
- key: "visitor",
- value: function visitor() {
- var self = this;
- return {
- first: function first() {
- self.iterator = -1;
- return self.visitors[self.iterator];
- },
- get: function get() {
- self.iterator += 1;
- return self.visitors[self.iterator];
- }
- };
- }
- /**
- *
- * @returns {Array}
- * @private
- */
-
- }, {
- key: "getFileManagers",
- value: function getFileManagers() {
- return this.fileManagers;
- }
- }]);
-
- return PluginManager;
-}();
-
-var pm;
-
-function PluginManagerFactory(less, newFactory) {
- if (newFactory || !pm) {
- pm = new PluginManager(less);
- }
-
- return pm;
-}
-
-var Parse = (function (environment, ParseTree, ImportManager) {
- var parse = function parse(input, options, callback) {
- if (typeof options === 'function') {
- callback = options;
- options = copyOptions(this.options, {});
- } else {
- options = copyOptions(this.options, options || {});
- }
-
- if (!callback) {
- var self = this;
- return new Promise(function (resolve, reject) {
- parse.call(self, input, options, function (err, output) {
- if (err) {
- reject(err);
- } else {
- resolve(output);
- }
- });
- });
- } else {
- var context;
- var rootFileInfo;
- var pluginManager = new PluginManagerFactory(this, !options.reUsePluginManager);
- options.pluginManager = pluginManager;
- context = new contexts.Parse(options);
-
- if (options.rootFileInfo) {
- rootFileInfo = options.rootFileInfo;
- } else {
- var filename = options.filename || 'input';
- var entryPath = filename.replace(/[^\/\\]*$/, '');
- rootFileInfo = {
- filename,
- rewriteUrls: context.rewriteUrls,
- rootpath: context.rootpath || '',
- currentDirectory: entryPath,
- entryPath,
- rootFilename: filename
- }; // add in a missing trailing slash
-
- if (rootFileInfo.rootpath && rootFileInfo.rootpath.slice(-1) !== '/') {
- rootFileInfo.rootpath += '/';
- }
- }
-
- var imports = new ImportManager(this, context, rootFileInfo);
- this.importManager = imports; // TODO: allow the plugins to be just a list of paths or names
- // Do an async plugin queue like lessc
-
- if (options.plugins) {
- options.plugins.forEach(function (plugin) {
- var evalResult;
- var contents;
-
- if (plugin.fileContent) {
- contents = plugin.fileContent.replace(/^\uFEFF/, '');
- evalResult = pluginManager.Loader.evalPlugin(contents, context, imports, plugin.options, plugin.filename);
-
- if (evalResult instanceof LessError) {
- return callback(evalResult);
- }
- } else {
- pluginManager.addPlugin(plugin);
- }
- });
- }
-
- new Parser(context, imports, rootFileInfo).parse(input, function (e, root) {
- if (e) {
- return callback(e);
- }
-
- callback(null, root, imports, options);
- }, options);
- }
- };
-
- return parse;
-});
-
-var createFromEnvironment = (function (environment, fileManagers) {
- /**
- * @todo
- * This original code could be improved quite a bit.
- * Many classes / modules currently add side-effects / mutations to passed in objects,
- * which makes it hard to refactor and reason about.
- */
- environment = new environment$1(environment, fileManagers);
- var SourceMapOutput = sourceMapOutput(environment);
- var SourceMapBuilder = sourceMapBuilder(SourceMapOutput, environment);
- var ParseTree = parseTree(SourceMapBuilder);
- var ImportManager = importManager(environment);
- var render = Render(environment, ParseTree);
- var parse = Parse(environment, ParseTree, ImportManager);
- var functions = Functions(environment);
- /**
- * @todo
- * This root properties / methods need to be organized.
- * It's not clear what should / must be public and why.
- */
-
- var initial = {
- version: [3, 10, 3],
- data,
- tree,
- Environment: environment$1,
- AbstractFileManager,
- AbstractPluginLoader,
- environment,
- visitors,
- Parser,
- functions,
- contexts,
- SourceMapOutput,
- SourceMapBuilder,
- ParseTree,
- ImportManager,
- render,
- parse,
- LessError,
- transformTree,
- utils,
- PluginManager: PluginManagerFactory,
- logger
- }; // Create a public API
-
- var ctor = function ctor(t) {
- return function () {
- for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
- args[_key] = arguments[_key];
- }
-
- return _construct(t, args);
- };
- };
-
- var t;
- var api = Object.create(initial);
-
- for (var n in initial.tree) {
- /* eslint guard-for-in: 0 */
- t = initial.tree[n];
-
- if (typeof t === 'function') {
- api[n.toLowerCase()] = ctor(t);
- } else {
- api[n] = Object.create(null);
-
- for (var o in t) {
- /* eslint guard-for-in: 0 */
- api[n][o.toLowerCase()] = ctor(t[o]);
- }
- }
- }
-
- return api;
-});
-
-function createCommonjsModule(fn, module) {
- return module = { exports: {} }, fn(module, module.exports), module.exports;
-}
-
-var lesscHelper = createCommonjsModule(function (module, exports) {
- // lessc_helper.js
- //
- // helper functions for lessc
- var lessc_helper = {
- // Stylize a string
- stylize: function stylize(str, style) {
- var styles = {
- 'reset': [0, 0],
- 'bold': [1, 22],
- 'inverse': [7, 27],
- 'underline': [4, 24],
- 'yellow': [33, 39],
- 'green': [32, 39],
- 'red': [31, 39],
- 'grey': [90, 39]
- };
- return `\x1b[${styles[style][0]}m${str}\x1b[${styles[style][1]}m`;
- },
- // Print command line options
- printUsage: function printUsage() {
- console.log('usage: lessc [option option=parameter ...] [destination]');
- console.log('');
- console.log('If source is set to `-\' (dash or hyphen-minus), input is read from stdin.');
- console.log('');
- console.log('options:');
- console.log(' -h, --help Prints help (this message) and exit.');
- console.log(' --include-path=PATHS Sets include paths. Separated by `:\'. `;\' also supported on windows.');
- console.log(' -M, --depends Outputs a makefile import dependency list to stdout.');
- console.log(' --no-color Disables colorized output.');
- console.log(' --ie-compat Enables IE8 compatibility checks.');
- console.log(' --js Enables inline JavaScript in less files');
- console.log(' -l, --lint Syntax check only (lint).');
- console.log(' -s, --silent Suppresses output of error messages.');
- console.log(' --strict-imports Forces evaluation of imports.');
- console.log(' --insecure Allows imports from insecure https hosts.');
- console.log(' -v, --version Prints version number and exit.');
- console.log(' --verbose Be verbose.');
- console.log(' --source-map[=FILENAME] Outputs a v3 sourcemap to the filename (or output filename.map).');
- console.log(' --source-map-rootpath=X Adds this path onto the sourcemap filename and less file paths.');
- console.log(' --source-map-basepath=X Sets sourcemap base path, defaults to current working directory.');
- console.log(' --source-map-include-source Puts the less files into the map instead of referencing them.');
- console.log(' --source-map-inline Puts the map (and any less files) as a base64 data uri into the output css file.');
- console.log(' --source-map-url=URL Sets a custom URL to map file, for sourceMappingURL comment');
- console.log(' in generated CSS file.');
- console.log(' -rp, --rootpath=URL Sets rootpath for url rewriting in relative imports and urls');
- console.log(' Works with or without the relative-urls option.');
- console.log(' -ru=, --rewrite-urls= Rewrites URLs to make them relative to the base less file.');
- console.log(' all|local|off \'all\' rewrites all URLs, \'local\' just those starting with a \'.\'');
- console.log('');
- console.log(' -m=, --math=');
- console.log(' always Less will eagerly perform math operations always.');
- console.log(' parens-division Math performed except for division (/) operator');
- console.log(' parens | strict Math only performed inside parentheses');
- console.log(' strict-legacy Parens required in very strict terms (legacy --strict-math)');
- console.log('');
- console.log(' -su=on|off Allows mixed units, e.g. 1px+1em or 1px*1px which have units');
- console.log(' --strict-units=on|off that cannot be represented.');
- console.log(' --global-var=\'VAR=VALUE\' Defines a variable that can be referenced by the file.');
- console.log(' --modify-var=\'VAR=VALUE\' Modifies a variable already declared in the file.');
- console.log(' --url-args=\'QUERYSTRING\' Adds params into url tokens (e.g. 42, cb=42 or \'a=1&b=2\')');
- console.log(' --plugin=PLUGIN=OPTIONS Loads a plugin. You can also omit the --plugin= if the plugin begins');
- console.log(' less-plugin. E.g. the clean css plugin is called less-plugin-clean-css');
- console.log(' once installed (npm install less-plugin-clean-css), use either with');
- console.log(' --plugin=less-plugin-clean-css or just --clean-css');
- console.log(' specify options afterwards e.g. --plugin=less-plugin-clean-css="advanced"');
- console.log(' or --clean-css="advanced"');
- console.log('');
- console.log('-------------------------- Deprecated ----------------');
- console.log(' -sm=on|off Legacy parens-only math. Use --math');
- console.log(' --strict-math=on|off ');
- console.log('');
- console.log(' --line-numbers=TYPE Outputs filename and line numbers.');
- console.log(' TYPE can be either \'comments\', which will output');
- console.log(' the debug info within comments, \'mediaquery\'');
- console.log(' that will output the information within a fake');
- console.log(' media query which is compatible with the SASS');
- console.log(' format, and \'all\' which will do both.');
- console.log(' -x, --compress Compresses output by removing some whitespaces.');
- console.log(' We recommend you use a dedicated minifer like less-plugin-clean-css');
- console.log('');
- console.log('Report bugs to: http://github.com/less/less.js/issues');
- console.log('Home page: ');
- }
- }; // Exports helper functions
-
- for (var h in lessc_helper) {
- if (lessc_helper.hasOwnProperty(h)) {
- exports[h] = lessc_helper[h];
- }
- }
-});
-
-/**
- * Node Plugin Loader
- */
-
-var PluginLoader =
-/*#__PURE__*/
-function (_AbstractPluginLoader) {
- _inherits(PluginLoader, _AbstractPluginLoader);
-
- function PluginLoader(less) {
- var _this;
-
- _classCallCheck(this, PluginLoader);
-
- _this = _possibleConstructorReturn(this, _getPrototypeOf(PluginLoader).call(this));
- _this.less = less;
-
- _this.require = function (prefix) {
- prefix = path.dirname(prefix);
- return function (id) {
- var str = id.substr(0, 2);
-
- if (str === '..' || str === './') {
- return require(path.join(prefix, id));
- } else {
- return require(id);
- }
- };
- };
-
- return _this;
- }
-
- _createClass(PluginLoader, [{
- key: "loadPlugin",
- value: function loadPlugin(filename, basePath, context, environment, fileManager) {
- var prefix = filename.slice(0, 1);
- var explicit = prefix === '.' || prefix === '/' || filename.slice(-3).toLowerCase() === '.js';
-
- if (!explicit) {
- context.prefixes = ['less-plugin-', ''];
- }
-
- return new Promise(function (fulfill, reject) {
- fileManager.loadFile(filename, basePath, context, environment).then(function (data) {
- try {
- fulfill(data);
- } catch (e) {
- console.log(e);
- reject(e);
- }
- }).catch(function (err) {
- reject(err);
- });
- });
- }
- }]);
-
- return PluginLoader;
-}(AbstractPluginLoader);
-
-// Export a new default each time
-var defaultOptions = (function () {
- return {
- /* Inline Javascript - @plugin still allowed */
- javascriptEnabled: false,
-
- /* Outputs a makefile import dependency list to stdout. */
- depends: false,
-
- /* (DEPRECATED) Compress using less built-in compression.
- * This does an okay job but does not utilise all the tricks of
- * dedicated css compression. */
- compress: false,
-
- /* Runs the less parser and just reports errors without any output. */
- lint: false,
-
- /* Sets available include paths.
- * If the file in an @import rule does not exist at that exact location,
- * less will look for it at the location(s) passed to this option.
- * You might use this for instance to specify a path to a library which
- * you want to be referenced simply and relatively in the less files. */
- paths: [],
-
- /* color output in the terminal */
- color: true,
-
- /* The strictImports controls whether the compiler will allow an @import inside of either
- * @media blocks or (a later addition) other selector blocks.
- * See: https://github.com/less/less.js/issues/656 */
- strictImports: false,
-
- /* Allow Imports from Insecure HTTPS Hosts */
- insecure: false,
-
- /* Allows you to add a path to every generated import and url in your css.
- * This does not affect less import statements that are processed, just ones
- * that are left in the output css. */
- rootpath: '',
-
- /* By default URLs are kept as-is, so if you import a file in a sub-directory
- * that references an image, exactly the same URL will be output in the css.
- * This option allows you to re-write URL's in imported files so that the
- * URL is always relative to the base imported file */
- rewriteUrls: false,
-
- /* How to process math
- * 0 always - eagerly try to solve all operations
- * 1 parens-division - require parens for division "/"
- * 2 parens | strict - require parens for all operations
- * 3 strict-legacy - legacy strict behavior (super-strict)
- */
- math: 0,
-
- /* Without this option, less attempts to guess at the output unit when it does maths. */
- strictUnits: false,
-
- /* Effectively the declaration is put at the top of your base Less file,
- * meaning it can be used but it also can be overridden if this variable
- * is defined in the file. */
- globalVars: null,
-
- /* As opposed to the global variable option, this puts the declaration at the
- * end of your base file, meaning it will override anything defined in your Less file. */
- modifyVars: null,
-
- /* This option allows you to specify a argument to go on to every URL. */
- urlArgs: ''
- };
-});
-
-var imageSize = (function (environment) {
- function _imageSize(functionContext, filePathNode) {
- var filePath = filePathNode.value;
- var currentFileInfo = functionContext.currentFileInfo;
- var currentDirectory = currentFileInfo.rewriteUrls ? currentFileInfo.currentDirectory : currentFileInfo.entryPath;
- var fragmentStart = filePath.indexOf('#');
- var fragment = '';
-
- if (fragmentStart !== -1) {
- fragment = filePath.slice(fragmentStart);
- filePath = filePath.slice(0, fragmentStart);
- }
-
- var fileManager = environment.getFileManager(filePath, currentDirectory, functionContext.context, environment, true);
-
- if (!fileManager) {
- throw {
- type: 'File',
- message: `Can not set up FileManager for ${filePathNode}`
- };
- }
-
- var fileSync = fileManager.loadFileSync(filePath, currentDirectory, functionContext.context, environment);
-
- if (fileSync.error) {
- throw fileSync.error;
- }
-
- var sizeOf = require('image-size');
-
- return sizeOf(fileSync.filename);
- }
-
- var imageFunctions = {
- 'image-size': function imageSize(filePathNode) {
- var size = _imageSize(this, filePathNode);
-
- return new Expression([new Dimension(size.width, 'px'), new Dimension(size.height, 'px')]);
- },
- 'image-width': function imageWidth(filePathNode) {
- var size = _imageSize(this, filePathNode);
-
- return new Dimension(size.width, 'px');
- },
- 'image-height': function imageHeight(filePathNode) {
- var size = _imageSize(this, filePathNode);
-
- return new Dimension(size.height, 'px');
- }
- };
- functionRegistry.addMultiple(imageFunctions);
-});
-
-var less = createFromEnvironment(environment, [new FileManager(), new UrlFileManager()]); // allow people to create less with their own environment
-
-less.createFromEnvironment = createFromEnvironment;
-less.lesscHelper = lesscHelper;
-less.PluginLoader = PluginLoader;
-less.fs = fs$1;
-less.FileManager = FileManager;
-less.UrlFileManager = UrlFileManager; // Set up options
-
-less.options = defaultOptions(); // provide image-size functionality
-
-imageSize(less.environment);
-
-module.exports = less;
diff --git a/vendor/less/dist/less.js b/vendor/less/dist/less.js
index 8219629d3..9731e83dc 100644
--- a/vendor/less/dist/less.js
+++ b/vendor/less/dist/less.js
@@ -1,14331 +1,11339 @@
/**
- * Less - Leaner CSS v3.10.3
+ * Less - Leaner CSS v4.1.2
* http://lesscss.org
*
- * Copyright (c) 2009-2019, Alexis Sellier
+ * Copyright (c) 2009-2021, Alexis Sellier
* Licensed under the Apache-2.0 License.
*
* @license Apache-2.0
*/
(function (global, factory) {
- typeof exports === 'object' && typeof module !== 'undefined' ? module.exports = factory() :
- typeof define === 'function' && define.amd ? define(factory) :
- (global = global || self, global.less = factory());
-}(this, function () { 'use strict';
+ typeof exports === 'object' && typeof module !== 'undefined' ? module.exports = factory() :
+ typeof define === 'function' && define.amd ? define(factory) :
+ (global = typeof globalThis !== 'undefined' ? globalThis : global || self, global.less = factory());
+}(this, (function () { 'use strict';
- // Export a new default each time
- var defaultOptions = (function () {
- return {
- /* Inline Javascript - @plugin still allowed */
- javascriptEnabled: false,
+ // Export a new default each time
+ function defaultOptions () {
+ return {
+ /* Inline Javascript - @plugin still allowed */
+ javascriptEnabled: false,
+ /* Outputs a makefile import dependency list to stdout. */
+ depends: false,
+ /* (DEPRECATED) Compress using less built-in compression.
+ * This does an okay job but does not utilise all the tricks of
+ * dedicated css compression. */
+ compress: false,
+ /* Runs the less parser and just reports errors without any output. */
+ lint: false,
+ /* Sets available include paths.
+ * If the file in an @import rule does not exist at that exact location,
+ * less will look for it at the location(s) passed to this option.
+ * You might use this for instance to specify a path to a library which
+ * you want to be referenced simply and relatively in the less files. */
+ paths: [],
+ /* color output in the terminal */
+ color: true,
+ /* The strictImports controls whether the compiler will allow an @import inside of either
+ * @media blocks or (a later addition) other selector blocks.
+ * See: https://github.com/less/less.js/issues/656 */
+ strictImports: false,
+ /* Allow Imports from Insecure HTTPS Hosts */
+ insecure: false,
+ /* Allows you to add a path to every generated import and url in your css.
+ * This does not affect less import statements that are processed, just ones
+ * that are left in the output css. */
+ rootpath: '',
+ /* By default URLs are kept as-is, so if you import a file in a sub-directory
+ * that references an image, exactly the same URL will be output in the css.
+ * This option allows you to re-write URL's in imported files so that the
+ * URL is always relative to the base imported file */
+ rewriteUrls: false,
+ /* How to process math
+ * 0 always - eagerly try to solve all operations
+ * 1 parens-division - require parens for division "/"
+ * 2 parens | strict - require parens for all operations
+ * 3 strict-legacy - legacy strict behavior (super-strict)
+ */
+ math: 1,
+ /* Without this option, less attempts to guess at the output unit when it does maths. */
+ strictUnits: false,
+ /* Effectively the declaration is put at the top of your base Less file,
+ * meaning it can be used but it also can be overridden if this variable
+ * is defined in the file. */
+ globalVars: null,
+ /* As opposed to the global variable option, this puts the declaration at the
+ * end of your base file, meaning it will override anything defined in your Less file. */
+ modifyVars: null,
+ /* This option allows you to specify a argument to go on to every URL. */
+ urlArgs: ''
+ };
+ }
- /* Outputs a makefile import dependency list to stdout. */
- depends: false,
+ function extractId(href) {
+ return href.replace(/^[a-z-]+:\/+?[^\/]+/, '') // Remove protocol & domain
+ .replace(/[\?\&]livereload=\w+/, '') // Remove LiveReload cachebuster
+ .replace(/^\//, '') // Remove root /
+ .replace(/\.[a-zA-Z]+$/, '') // Remove simple extension
+ .replace(/[^\.\w-]+/g, '-') // Replace illegal characters
+ .replace(/\./g, ':'); // Replace dots with colons(for valid id)
+ }
+ function addDataAttr(options, tag) {
+ for (var opt in tag.dataset) {
+ if (tag.dataset.hasOwnProperty(opt)) {
+ if (opt === 'env' || opt === 'dumpLineNumbers' || opt === 'rootpath' || opt === 'errorReporting') {
+ options[opt] = tag.dataset[opt];
+ }
+ else {
+ try {
+ options[opt] = JSON.parse(tag.dataset[opt]);
+ }
+ catch (_) { }
+ }
+ }
+ }
+ }
- /* (DEPRECATED) Compress using less built-in compression.
- * This does an okay job but does not utilise all the tricks of
- * dedicated css compression. */
- compress: false,
-
- /* Runs the less parser and just reports errors without any output. */
- lint: false,
-
- /* Sets available include paths.
- * If the file in an @import rule does not exist at that exact location,
- * less will look for it at the location(s) passed to this option.
- * You might use this for instance to specify a path to a library which
- * you want to be referenced simply and relatively in the less files. */
- paths: [],
-
- /* color output in the terminal */
- color: true,
-
- /* The strictImports controls whether the compiler will allow an @import inside of either
- * @media blocks or (a later addition) other selector blocks.
- * See: https://github.com/less/less.js/issues/656 */
- strictImports: false,
-
- /* Allow Imports from Insecure HTTPS Hosts */
- insecure: false,
-
- /* Allows you to add a path to every generated import and url in your css.
- * This does not affect less import statements that are processed, just ones
- * that are left in the output css. */
- rootpath: '',
-
- /* By default URLs are kept as-is, so if you import a file in a sub-directory
- * that references an image, exactly the same URL will be output in the css.
- * This option allows you to re-write URL's in imported files so that the
- * URL is always relative to the base imported file */
- rewriteUrls: false,
-
- /* How to process math
- * 0 always - eagerly try to solve all operations
- * 1 parens-division - require parens for division "/"
- * 2 parens | strict - require parens for all operations
- * 3 strict-legacy - legacy strict behavior (super-strict)
- */
- math: 0,
-
- /* Without this option, less attempts to guess at the output unit when it does maths. */
- strictUnits: false,
-
- /* Effectively the declaration is put at the top of your base Less file,
- * meaning it can be used but it also can be overridden if this variable
- * is defined in the file. */
- globalVars: null,
-
- /* As opposed to the global variable option, this puts the declaration at the
- * end of your base file, meaning it will override anything defined in your Less file. */
- modifyVars: null,
-
- /* This option allows you to specify a argument to go on to every URL. */
- urlArgs: ''
+ var browser = {
+ createCSS: function (document, styles, sheet) {
+ // Strip the query-string
+ var href = sheet.href || '';
+ // If there is no title set, use the filename, minus the extension
+ var id = "less:" + (sheet.title || extractId(href));
+ // If this has already been inserted into the DOM, we may need to replace it
+ var oldStyleNode = document.getElementById(id);
+ var keepOldStyleNode = false;
+ // Create a new stylesheet node for insertion or (if necessary) replacement
+ var styleNode = document.createElement('style');
+ styleNode.setAttribute('type', 'text/css');
+ if (sheet.media) {
+ styleNode.setAttribute('media', sheet.media);
+ }
+ styleNode.id = id;
+ if (!styleNode.styleSheet) {
+ styleNode.appendChild(document.createTextNode(styles));
+ // If new contents match contents of oldStyleNode, don't replace oldStyleNode
+ keepOldStyleNode = (oldStyleNode !== null && oldStyleNode.childNodes.length > 0 && styleNode.childNodes.length > 0 &&
+ oldStyleNode.firstChild.nodeValue === styleNode.firstChild.nodeValue);
+ }
+ var head = document.getElementsByTagName('head')[0];
+ // If there is no oldStyleNode, just append; otherwise, only append if we need
+ // to replace oldStyleNode with an updated stylesheet
+ if (oldStyleNode === null || keepOldStyleNode === false) {
+ var nextEl = sheet && sheet.nextSibling || null;
+ if (nextEl) {
+ nextEl.parentNode.insertBefore(styleNode, nextEl);
+ }
+ else {
+ head.appendChild(styleNode);
+ }
+ }
+ if (oldStyleNode && keepOldStyleNode === false) {
+ oldStyleNode.parentNode.removeChild(oldStyleNode);
+ }
+ // For IE.
+ // This needs to happen *after* the style element is added to the DOM, otherwise IE 7 and 8 may crash.
+ // See http://social.msdn.microsoft.com/Forums/en-US/7e081b65-878a-4c22-8e68-c10d39c2ed32/internet-explorer-crashes-appending-style-element-to-head
+ if (styleNode.styleSheet) {
+ try {
+ styleNode.styleSheet.cssText = styles;
+ }
+ catch (e) {
+ throw new Error('Couldn\'t reassign styleSheet.cssText.');
+ }
+ }
+ },
+ currentScript: function (window) {
+ var document = window.document;
+ return document.currentScript || (function () {
+ var scripts = document.getElementsByTagName('script');
+ return scripts[scripts.length - 1];
+ })();
+ }
};
- });
- function extractId(href) {
- return href.replace(/^[a-z-]+:\/+?[^\/]+/, '') // Remove protocol & domain
- .replace(/[\?\&]livereload=\w+/, '') // Remove LiveReload cachebuster
- .replace(/^\//, '') // Remove root /
- .replace(/\.[a-zA-Z]+$/, '') // Remove simple extension
- .replace(/[^\.\w-]+/g, '-') // Replace illegal characters
- .replace(/\./g, ':'); // Replace dots with colons(for valid id)
- }
- function addDataAttr(options, tag) {
- for (var opt in tag.dataset) {
- if (tag.dataset.hasOwnProperty(opt)) {
- if (opt === 'env' || opt === 'dumpLineNumbers' || opt === 'rootpath' || opt === 'errorReporting') {
- options[opt] = tag.dataset[opt];
- } else {
- try {
- options[opt] = JSON.parse(tag.dataset[opt]);
- } catch (_) {}
+ var addDefaultOptions = (function (window, options) {
+ // use options from the current script tag data attribues
+ addDataAttr(options, browser.currentScript(window));
+ if (options.isFileProtocol === undefined) {
+ options.isFileProtocol = /^(file|(chrome|safari)(-extension)?|resource|qrc|app):/.test(window.location.protocol);
}
- }
- }
- }
-
- var browser = {
- createCSS: function createCSS(document, styles, sheet) {
- // Strip the query-string
- var href = sheet.href || ''; // If there is no title set, use the filename, minus the extension
-
- var id = "less:".concat(sheet.title || extractId(href)); // If this has already been inserted into the DOM, we may need to replace it
-
- var oldStyleNode = document.getElementById(id);
- var keepOldStyleNode = false; // Create a new stylesheet node for insertion or (if necessary) replacement
-
- var styleNode = document.createElement('style');
- styleNode.setAttribute('type', 'text/css');
-
- if (sheet.media) {
- styleNode.setAttribute('media', sheet.media);
- }
-
- styleNode.id = id;
-
- if (!styleNode.styleSheet) {
- styleNode.appendChild(document.createTextNode(styles)); // If new contents match contents of oldStyleNode, don't replace oldStyleNode
-
- keepOldStyleNode = oldStyleNode !== null && oldStyleNode.childNodes.length > 0 && styleNode.childNodes.length > 0 && oldStyleNode.firstChild.nodeValue === styleNode.firstChild.nodeValue;
- }
-
- var head = document.getElementsByTagName('head')[0]; // If there is no oldStyleNode, just append; otherwise, only append if we need
- // to replace oldStyleNode with an updated stylesheet
-
- if (oldStyleNode === null || keepOldStyleNode === false) {
- var nextEl = sheet && sheet.nextSibling || null;
-
- if (nextEl) {
- nextEl.parentNode.insertBefore(styleNode, nextEl);
- } else {
- head.appendChild(styleNode);
+ // Load styles asynchronously (default: false)
+ //
+ // This is set to `false` by default, so that the body
+ // doesn't start loading before the stylesheets are parsed.
+ // Setting this to `true` can result in flickering.
+ //
+ options.async = options.async || false;
+ options.fileAsync = options.fileAsync || false;
+ // Interval between watch polls
+ options.poll = options.poll || (options.isFileProtocol ? 1000 : 1500);
+ options.env = options.env || (window.location.hostname == '127.0.0.1' ||
+ window.location.hostname == '0.0.0.0' ||
+ window.location.hostname == 'localhost' ||
+ (window.location.port &&
+ window.location.port.length > 0) ||
+ options.isFileProtocol ? 'development'
+ : 'production');
+ var dumpLineNumbers = /!dumpLineNumbers:(comments|mediaquery|all)/.exec(window.location.hash);
+ if (dumpLineNumbers) {
+ options.dumpLineNumbers = dumpLineNumbers[1];
}
- }
-
- if (oldStyleNode && keepOldStyleNode === false) {
- oldStyleNode.parentNode.removeChild(oldStyleNode);
- } // For IE.
- // This needs to happen *after* the style element is added to the DOM, otherwise IE 7 and 8 may crash.
- // See http://social.msdn.microsoft.com/Forums/en-US/7e081b65-878a-4c22-8e68-c10d39c2ed32/internet-explorer-crashes-appending-style-element-to-head
-
-
- if (styleNode.styleSheet) {
- try {
- styleNode.styleSheet.cssText = styles;
- } catch (e) {
- throw new Error('Couldn\'t reassign styleSheet.cssText.');
+ if (options.useFileCache === undefined) {
+ options.useFileCache = true;
+ }
+ if (options.onReady === undefined) {
+ options.onReady = true;
+ }
+ if (options.relativeUrls) {
+ options.rewriteUrls = 'all';
}
- }
- },
- currentScript: function currentScript(window) {
- var document = window.document;
- return document.currentScript || function () {
- var scripts = document.getElementsByTagName('script');
- return scripts[scripts.length - 1];
- }();
- }
- };
-
- var addDefaultOptions = (function (window, options) {
- // use options from the current script tag data attribues
- addDataAttr(options, browser.currentScript(window));
-
- if (options.isFileProtocol === undefined) {
- options.isFileProtocol = /^(file|(chrome|safari)(-extension)?|resource|qrc|app):/.test(window.location.protocol);
- } // Load styles asynchronously (default: false)
- //
- // This is set to `false` by default, so that the body
- // doesn't start loading before the stylesheets are parsed.
- // Setting this to `true` can result in flickering.
- //
-
-
- options.async = options.async || false;
- options.fileAsync = options.fileAsync || false; // Interval between watch polls
-
- options.poll = options.poll || (options.isFileProtocol ? 1000 : 1500);
- options.env = options.env || (window.location.hostname == '127.0.0.1' || window.location.hostname == '0.0.0.0' || window.location.hostname == 'localhost' || window.location.port && window.location.port.length > 0 || options.isFileProtocol ? 'development' : 'production');
- var dumpLineNumbers = /!dumpLineNumbers:(comments|mediaquery|all)/.exec(window.location.hash);
-
- if (dumpLineNumbers) {
- options.dumpLineNumbers = dumpLineNumbers[1];
- }
-
- if (options.useFileCache === undefined) {
- options.useFileCache = true;
- }
-
- if (options.onReady === undefined) {
- options.onReady = true;
- }
-
- if (options.relativeUrls) {
- options.rewriteUrls = 'all';
- }
- });
-
- function _typeof(obj) {
- if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") {
- _typeof = function (obj) {
- return typeof obj;
- };
- } else {
- _typeof = function (obj) {
- return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj;
- };
- }
-
- return _typeof(obj);
- }
-
- function _classCallCheck(instance, Constructor) {
- if (!(instance instanceof Constructor)) {
- throw new TypeError("Cannot call a class as a function");
- }
- }
-
- function _defineProperties(target, props) {
- for (var i = 0; i < props.length; i++) {
- var descriptor = props[i];
- descriptor.enumerable = descriptor.enumerable || false;
- descriptor.configurable = true;
- if ("value" in descriptor) descriptor.writable = true;
- Object.defineProperty(target, descriptor.key, descriptor);
- }
- }
-
- function _createClass(Constructor, protoProps, staticProps) {
- if (protoProps) _defineProperties(Constructor.prototype, protoProps);
- if (staticProps) _defineProperties(Constructor, staticProps);
- return Constructor;
- }
-
- function _inherits(subClass, superClass) {
- if (typeof superClass !== "function" && superClass !== null) {
- throw new TypeError("Super expression must either be null or a function");
- }
-
- subClass.prototype = Object.create(superClass && superClass.prototype, {
- constructor: {
- value: subClass,
- writable: true,
- configurable: true
- }
});
- if (superClass) _setPrototypeOf(subClass, superClass);
- }
- function _getPrototypeOf(o) {
- _getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf : function _getPrototypeOf(o) {
- return o.__proto__ || Object.getPrototypeOf(o);
- };
- return _getPrototypeOf(o);
- }
-
- function _setPrototypeOf(o, p) {
- _setPrototypeOf = Object.setPrototypeOf || function _setPrototypeOf(o, p) {
- o.__proto__ = p;
- return o;
+ var logger$1 = {
+ error: function (msg) {
+ this._fireEvent('error', msg);
+ },
+ warn: function (msg) {
+ this._fireEvent('warn', msg);
+ },
+ info: function (msg) {
+ this._fireEvent('info', msg);
+ },
+ debug: function (msg) {
+ this._fireEvent('debug', msg);
+ },
+ addListener: function (listener) {
+ this._listeners.push(listener);
+ },
+ removeListener: function (listener) {
+ for (var i = 0; i < this._listeners.length; i++) {
+ if (this._listeners[i] === listener) {
+ this._listeners.splice(i, 1);
+ return;
+ }
+ }
+ },
+ _fireEvent: function (type, msg) {
+ for (var i = 0; i < this._listeners.length; i++) {
+ var logFunction = this._listeners[i][type];
+ if (logFunction) {
+ logFunction(msg);
+ }
+ }
+ },
+ _listeners: []
};
- return _setPrototypeOf(o, p);
- }
-
- function isNativeReflectConstruct() {
- if (typeof Reflect === "undefined" || !Reflect.construct) return false;
- if (Reflect.construct.sham) return false;
- if (typeof Proxy === "function") return true;
-
- try {
- Date.prototype.toString.call(Reflect.construct(Date, [], function () {}));
- return true;
- } catch (e) {
- return false;
- }
- }
-
- function _construct(Parent, args, Class) {
- if (isNativeReflectConstruct()) {
- _construct = Reflect.construct;
- } else {
- _construct = function _construct(Parent, args, Class) {
- var a = [null];
- a.push.apply(a, args);
- var Constructor = Function.bind.apply(Parent, a);
- var instance = new Constructor();
- if (Class) _setPrototypeOf(instance, Class.prototype);
- return instance;
- };
- }
-
- return _construct.apply(null, arguments);
- }
-
- function _assertThisInitialized(self) {
- if (self === void 0) {
- throw new ReferenceError("this hasn't been initialised - super() hasn't been called");
- }
-
- return self;
- }
-
- function _possibleConstructorReturn(self, call) {
- if (call && (typeof call === "object" || typeof call === "function")) {
- return call;
- }
-
- return _assertThisInitialized(self);
- }
-
- function _toConsumableArray(arr) {
- return _arrayWithoutHoles(arr) || _iterableToArray(arr) || _nonIterableSpread();
- }
-
- function _arrayWithoutHoles(arr) {
- if (Array.isArray(arr)) {
- for (var i = 0, arr2 = new Array(arr.length); i < arr.length; i++) arr2[i] = arr[i];
-
- return arr2;
- }
- }
-
- function _iterableToArray(iter) {
- if (Symbol.iterator in Object(iter) || Object.prototype.toString.call(iter) === "[object Arguments]") return Array.from(iter);
- }
-
- function _nonIterableSpread() {
- throw new TypeError("Invalid attempt to spread non-iterable instance");
- }
-
- var colors = {
- 'aliceblue': '#f0f8ff',
- 'antiquewhite': '#faebd7',
- 'aqua': '#00ffff',
- 'aquamarine': '#7fffd4',
- 'azure': '#f0ffff',
- 'beige': '#f5f5dc',
- 'bisque': '#ffe4c4',
- 'black': '#000000',
- 'blanchedalmond': '#ffebcd',
- 'blue': '#0000ff',
- 'blueviolet': '#8a2be2',
- 'brown': '#a52a2a',
- 'burlywood': '#deb887',
- 'cadetblue': '#5f9ea0',
- 'chartreuse': '#7fff00',
- 'chocolate': '#d2691e',
- 'coral': '#ff7f50',
- 'cornflowerblue': '#6495ed',
- 'cornsilk': '#fff8dc',
- 'crimson': '#dc143c',
- 'cyan': '#00ffff',
- 'darkblue': '#00008b',
- 'darkcyan': '#008b8b',
- 'darkgoldenrod': '#b8860b',
- 'darkgray': '#a9a9a9',
- 'darkgrey': '#a9a9a9',
- 'darkgreen': '#006400',
- 'darkkhaki': '#bdb76b',
- 'darkmagenta': '#8b008b',
- 'darkolivegreen': '#556b2f',
- 'darkorange': '#ff8c00',
- 'darkorchid': '#9932cc',
- 'darkred': '#8b0000',
- 'darksalmon': '#e9967a',
- 'darkseagreen': '#8fbc8f',
- 'darkslateblue': '#483d8b',
- 'darkslategray': '#2f4f4f',
- 'darkslategrey': '#2f4f4f',
- 'darkturquoise': '#00ced1',
- 'darkviolet': '#9400d3',
- 'deeppink': '#ff1493',
- 'deepskyblue': '#00bfff',
- 'dimgray': '#696969',
- 'dimgrey': '#696969',
- 'dodgerblue': '#1e90ff',
- 'firebrick': '#b22222',
- 'floralwhite': '#fffaf0',
- 'forestgreen': '#228b22',
- 'fuchsia': '#ff00ff',
- 'gainsboro': '#dcdcdc',
- 'ghostwhite': '#f8f8ff',
- 'gold': '#ffd700',
- 'goldenrod': '#daa520',
- 'gray': '#808080',
- 'grey': '#808080',
- 'green': '#008000',
- 'greenyellow': '#adff2f',
- 'honeydew': '#f0fff0',
- 'hotpink': '#ff69b4',
- 'indianred': '#cd5c5c',
- 'indigo': '#4b0082',
- 'ivory': '#fffff0',
- 'khaki': '#f0e68c',
- 'lavender': '#e6e6fa',
- 'lavenderblush': '#fff0f5',
- 'lawngreen': '#7cfc00',
- 'lemonchiffon': '#fffacd',
- 'lightblue': '#add8e6',
- 'lightcoral': '#f08080',
- 'lightcyan': '#e0ffff',
- 'lightgoldenrodyellow': '#fafad2',
- 'lightgray': '#d3d3d3',
- 'lightgrey': '#d3d3d3',
- 'lightgreen': '#90ee90',
- 'lightpink': '#ffb6c1',
- 'lightsalmon': '#ffa07a',
- 'lightseagreen': '#20b2aa',
- 'lightskyblue': '#87cefa',
- 'lightslategray': '#778899',
- 'lightslategrey': '#778899',
- 'lightsteelblue': '#b0c4de',
- 'lightyellow': '#ffffe0',
- 'lime': '#00ff00',
- 'limegreen': '#32cd32',
- 'linen': '#faf0e6',
- 'magenta': '#ff00ff',
- 'maroon': '#800000',
- 'mediumaquamarine': '#66cdaa',
- 'mediumblue': '#0000cd',
- 'mediumorchid': '#ba55d3',
- 'mediumpurple': '#9370d8',
- 'mediumseagreen': '#3cb371',
- 'mediumslateblue': '#7b68ee',
- 'mediumspringgreen': '#00fa9a',
- 'mediumturquoise': '#48d1cc',
- 'mediumvioletred': '#c71585',
- 'midnightblue': '#191970',
- 'mintcream': '#f5fffa',
- 'mistyrose': '#ffe4e1',
- 'moccasin': '#ffe4b5',
- 'navajowhite': '#ffdead',
- 'navy': '#000080',
- 'oldlace': '#fdf5e6',
- 'olive': '#808000',
- 'olivedrab': '#6b8e23',
- 'orange': '#ffa500',
- 'orangered': '#ff4500',
- 'orchid': '#da70d6',
- 'palegoldenrod': '#eee8aa',
- 'palegreen': '#98fb98',
- 'paleturquoise': '#afeeee',
- 'palevioletred': '#d87093',
- 'papayawhip': '#ffefd5',
- 'peachpuff': '#ffdab9',
- 'peru': '#cd853f',
- 'pink': '#ffc0cb',
- 'plum': '#dda0dd',
- 'powderblue': '#b0e0e6',
- 'purple': '#800080',
- 'rebeccapurple': '#663399',
- 'red': '#ff0000',
- 'rosybrown': '#bc8f8f',
- 'royalblue': '#4169e1',
- 'saddlebrown': '#8b4513',
- 'salmon': '#fa8072',
- 'sandybrown': '#f4a460',
- 'seagreen': '#2e8b57',
- 'seashell': '#fff5ee',
- 'sienna': '#a0522d',
- 'silver': '#c0c0c0',
- 'skyblue': '#87ceeb',
- 'slateblue': '#6a5acd',
- 'slategray': '#708090',
- 'slategrey': '#708090',
- 'snow': '#fffafa',
- 'springgreen': '#00ff7f',
- 'steelblue': '#4682b4',
- 'tan': '#d2b48c',
- 'teal': '#008080',
- 'thistle': '#d8bfd8',
- 'tomato': '#ff6347',
- 'turquoise': '#40e0d0',
- 'violet': '#ee82ee',
- 'wheat': '#f5deb3',
- 'white': '#ffffff',
- 'whitesmoke': '#f5f5f5',
- 'yellow': '#ffff00',
- 'yellowgreen': '#9acd32'
- };
-
- var unitConversions = {
- length: {
- 'm': 1,
- 'cm': 0.01,
- 'mm': 0.001,
- 'in': 0.0254,
- 'px': 0.0254 / 96,
- 'pt': 0.0254 / 72,
- 'pc': 0.0254 / 72 * 12
- },
- duration: {
- 's': 1,
- 'ms': 0.001
- },
- angle: {
- 'rad': 1 / (2 * Math.PI),
- 'deg': 1 / 360,
- 'grad': 1 / 400,
- 'turn': 1
- }
- };
-
- var data = {
- colors: colors,
- unitConversions: unitConversions
- };
-
- var Node =
- /*#__PURE__*/
- function () {
- function Node() {
- _classCallCheck(this, Node);
-
- this.parent = null;
- this.visibilityBlocks = undefined;
- this.nodeVisible = undefined;
- this.rootNode = null;
- this.parsed = null;
- var self = this;
- Object.defineProperty(this, 'currentFileInfo', {
- get: function get() {
- return self.fileInfo();
- }
- });
- Object.defineProperty(this, 'index', {
- get: function get() {
- return self.getIndex();
- }
- });
- }
-
- _createClass(Node, [{
- key: "setParent",
- value: function setParent(nodes, parent) {
- function set(node) {
- if (node && node instanceof Node) {
- node.parent = parent;
- }
- }
-
- if (Array.isArray(nodes)) {
- nodes.forEach(set);
- } else {
- set(nodes);
- }
- }
- }, {
- key: "getIndex",
- value: function getIndex() {
- return this._index || this.parent && this.parent.getIndex() || 0;
- }
- }, {
- key: "fileInfo",
- value: function fileInfo() {
- return this._fileInfo || this.parent && this.parent.fileInfo() || {};
- }
- }, {
- key: "isRulesetLike",
- value: function isRulesetLike() {
- return false;
- }
- }, {
- key: "toCSS",
- value: function toCSS(context) {
- var strs = [];
- this.genCSS(context, {
- add: function add(chunk, fileInfo, index) {
- strs.push(chunk);
- },
- isEmpty: function isEmpty() {
- return strs.length === 0;
- }
- });
- return strs.join('');
- }
- }, {
- key: "genCSS",
- value: function genCSS(context, output) {
- output.add(this.value);
- }
- }, {
- key: "accept",
- value: function accept(visitor) {
- this.value = visitor.visit(this.value);
- }
- }, {
- key: "eval",
- value: function _eval() {
- return this;
- }
- }, {
- key: "_operate",
- value: function _operate(context, op, a, b) {
- switch (op) {
- case '+':
- return a + b;
-
- case '-':
- return a - b;
-
- case '*':
- return a * b;
-
- case '/':
- return a / b;
- }
- }
- }, {
- key: "fround",
- value: function fround(context, value) {
- var precision = context && context.numPrecision; // add "epsilon" to ensure numbers like 1.000000005 (represented as 1.000000004999...) are properly rounded:
-
- return precision ? Number((value + 2e-16).toFixed(precision)) : value;
- } // Returns true if this node represents root of ast imported by reference
-
- }, {
- key: "blocksVisibility",
- value: function blocksVisibility() {
- if (this.visibilityBlocks == null) {
- this.visibilityBlocks = 0;
- }
-
- return this.visibilityBlocks !== 0;
- }
- }, {
- key: "addVisibilityBlock",
- value: function addVisibilityBlock() {
- if (this.visibilityBlocks == null) {
- this.visibilityBlocks = 0;
- }
-
- this.visibilityBlocks = this.visibilityBlocks + 1;
- }
- }, {
- key: "removeVisibilityBlock",
- value: function removeVisibilityBlock() {
- if (this.visibilityBlocks == null) {
- this.visibilityBlocks = 0;
- }
-
- this.visibilityBlocks = this.visibilityBlocks - 1;
- } // Turns on node visibility - if called node will be shown in output regardless
- // of whether it comes from import by reference or not
-
- }, {
- key: "ensureVisibility",
- value: function ensureVisibility() {
- this.nodeVisible = true;
- } // Turns off node visibility - if called node will NOT be shown in output regardless
- // of whether it comes from import by reference or not
-
- }, {
- key: "ensureInvisibility",
- value: function ensureInvisibility() {
- this.nodeVisible = false;
- } // return values:
- // false - the node must not be visible
- // true - the node must be visible
- // undefined or null - the node has the same visibility as its parent
-
- }, {
- key: "isVisible",
- value: function isVisible() {
- return this.nodeVisible;
- }
- }, {
- key: "visibilityInfo",
- value: function visibilityInfo() {
- return {
- visibilityBlocks: this.visibilityBlocks,
- nodeVisible: this.nodeVisible
- };
- }
- }, {
- key: "copyVisibilityInfo",
- value: function copyVisibilityInfo(info) {
- if (!info) {
- return;
- }
-
- this.visibilityBlocks = info.visibilityBlocks;
- this.nodeVisible = info.nodeVisible;
- }
- }]);
-
- return Node;
- }();
-
- Node.compare = function (a, b) {
- /* returns:
- -1: a < b
- 0: a = b
- 1: a > b
- and *any* other value for a != b (e.g. undefined, NaN, -2 etc.) */
- if (a.compare && // for "symmetric results" force toCSS-based comparison
- // of Quoted or Anonymous if either value is one of those
- !(b.type === 'Quoted' || b.type === 'Anonymous')) {
- return a.compare(b);
- } else if (b.compare) {
- return -b.compare(a);
- } else if (a.type !== b.type) {
- return undefined;
- }
-
- a = a.value;
- b = b.value;
-
- if (!Array.isArray(a)) {
- return a === b ? 0 : undefined;
- }
-
- if (a.length !== b.length) {
- return undefined;
- }
-
- for (var i = 0; i < a.length; i++) {
- if (Node.compare(a[i], b[i]) !== 0) {
- return undefined;
- }
- }
-
- return 0;
- };
-
- Node.numericCompare = function (a, b) {
- return a < b ? -1 : a === b ? 0 : a > b ? 1 : undefined;
- };
-
- // RGB Colors - #ff0014, #eee
- //
-
- var Color =
- /*#__PURE__*/
- function (_Node) {
- _inherits(Color, _Node);
-
- function Color(rgb, a, originalForm) {
- var _this;
-
- _classCallCheck(this, Color);
-
- _this = _possibleConstructorReturn(this, _getPrototypeOf(Color).call(this));
-
- var self = _assertThisInitialized(_this); //
- // The end goal here, is to parse the arguments
- // into an integer triplet, such as `128, 255, 0`
- //
- // This facilitates operations and conversions.
- //
-
-
- if (Array.isArray(rgb)) {
- _this.rgb = rgb;
- } else if (rgb.length >= 6) {
- _this.rgb = [];
- rgb.match(/.{2}/g).map(function (c, i) {
- if (i < 3) {
- self.rgb.push(parseInt(c, 16));
- } else {
- self.alpha = parseInt(c, 16) / 255;
- }
- });
- } else {
- _this.rgb = [];
- rgb.split('').map(function (c, i) {
- if (i < 3) {
- self.rgb.push(parseInt(c + c, 16));
- } else {
- self.alpha = parseInt(c + c, 16) / 255;
- }
- });
- }
-
- _this.alpha = _this.alpha || (typeof a === 'number' ? a : 1);
-
- if (typeof originalForm !== 'undefined') {
- _this.value = originalForm;
- }
-
- return _this;
- }
-
- _createClass(Color, [{
- key: "luma",
- value: function luma() {
- var r = this.rgb[0] / 255;
- var g = this.rgb[1] / 255;
- var b = this.rgb[2] / 255;
- r = r <= 0.03928 ? r / 12.92 : Math.pow((r + 0.055) / 1.055, 2.4);
- g = g <= 0.03928 ? g / 12.92 : Math.pow((g + 0.055) / 1.055, 2.4);
- b = b <= 0.03928 ? b / 12.92 : Math.pow((b + 0.055) / 1.055, 2.4);
- return 0.2126 * r + 0.7152 * g + 0.0722 * b;
- }
- }, {
- key: "genCSS",
- value: function genCSS(context, output) {
- output.add(this.toCSS(context));
- }
- }, {
- key: "toCSS",
- value: function toCSS(context, doNotCompress) {
- var compress = context && context.compress && !doNotCompress;
- var color;
- var alpha;
- var colorFunction;
- var args = []; // `value` is set if this color was originally
- // converted from a named color string so we need
- // to respect this and try to output named color too.
-
- alpha = this.fround(context, this.alpha);
-
- if (this.value) {
- if (this.value.indexOf('rgb') === 0) {
- if (alpha < 1) {
- colorFunction = 'rgba';
+ /**
+ * @todo Document why this abstraction exists, and the relationship between
+ * environment, file managers, and plugin manager
+ */
+ var Environment = /** @class */ (function () {
+ function Environment(externalEnvironment, fileManagers) {
+ this.fileManagers = fileManagers || [];
+ externalEnvironment = externalEnvironment || {};
+ var optionalFunctions = ['encodeBase64', 'mimeLookup', 'charsetLookup', 'getSourceMapGenerator'];
+ var requiredFunctions = [];
+ var functions = requiredFunctions.concat(optionalFunctions);
+ for (var i = 0; i < functions.length; i++) {
+ var propName = functions[i];
+ var environmentFunc = externalEnvironment[propName];
+ if (environmentFunc) {
+ this[propName] = environmentFunc.bind(externalEnvironment);
+ }
+ else if (i < requiredFunctions.length) {
+ this.warn("missing required function in environment - " + propName);
+ }
}
- } else if (this.value.indexOf('hsl') === 0) {
- if (alpha < 1) {
- colorFunction = 'hsla';
- } else {
- colorFunction = 'hsl';
+ }
+ Environment.prototype.getFileManager = function (filename, currentDirectory, options, environment, isSync) {
+ if (!filename) {
+ logger$1.warn('getFileManager called with no filename.. Please report this issue. continuing.');
}
- } else {
- return this.value;
- }
- } else {
- if (alpha < 1) {
- colorFunction = 'rgba';
- }
- }
-
- switch (colorFunction) {
- case 'rgba':
- args = this.rgb.map(function (c) {
- return clamp(Math.round(c), 255);
- }).concat(clamp(alpha, 1));
- break;
-
- case 'hsla':
- args.push(clamp(alpha, 1));
-
- case 'hsl':
- color = this.toHSL();
- args = [this.fround(context, color.h), "".concat(this.fround(context, color.s * 100), "%"), "".concat(this.fround(context, color.l * 100), "%")].concat(args);
- }
-
- if (colorFunction) {
- // Values are capped between `0` and `255`, rounded and zero-padded.
- return "".concat(colorFunction, "(").concat(args.join(",".concat(compress ? '' : ' ')), ")");
- }
-
- color = this.toRGB();
-
- if (compress) {
- var splitcolor = color.split(''); // Convert color to short format
-
- if (splitcolor[1] === splitcolor[2] && splitcolor[3] === splitcolor[4] && splitcolor[5] === splitcolor[6]) {
- color = "#".concat(splitcolor[1]).concat(splitcolor[3]).concat(splitcolor[5]);
- }
- }
-
- return color;
- } //
- // Operations have to be done per-channel, if not,
- // channels will spill onto each other. Once we have
- // our result, in the form of an integer triplet,
- // we create a new Color node to hold the result.
- //
-
- }, {
- key: "operate",
- value: function operate(context, op, other) {
- var rgb = new Array(3);
- var alpha = this.alpha * (1 - other.alpha) + other.alpha;
-
- for (var c = 0; c < 3; c++) {
- rgb[c] = this._operate(context, op, this.rgb[c], other.rgb[c]);
- }
-
- return new Color(rgb, alpha);
- }
- }, {
- key: "toRGB",
- value: function toRGB() {
- return toHex(this.rgb);
- }
- }, {
- key: "toHSL",
- value: function toHSL() {
- var r = this.rgb[0] / 255;
- var g = this.rgb[1] / 255;
- var b = this.rgb[2] / 255;
- var a = this.alpha;
- var max = Math.max(r, g, b);
- var min = Math.min(r, g, b);
- var h;
- var s;
- var l = (max + min) / 2;
- var d = max - min;
-
- if (max === min) {
- h = s = 0;
- } else {
- s = l > 0.5 ? d / (2 - max - min) : d / (max + min);
-
- switch (max) {
- case r:
- h = (g - b) / d + (g < b ? 6 : 0);
- break;
-
- case g:
- h = (b - r) / d + 2;
- break;
-
- case b:
- h = (r - g) / d + 4;
- break;
- }
-
- h /= 6;
- }
-
- return {
- h: h * 360,
- s: s,
- l: l,
- a: a
+ if (currentDirectory == null) {
+ logger$1.warn('getFileManager called with null directory.. Please report this issue. continuing.');
+ }
+ var fileManagers = this.fileManagers;
+ if (options.pluginManager) {
+ fileManagers = [].concat(fileManagers).concat(options.pluginManager.getFileManagers());
+ }
+ for (var i = fileManagers.length - 1; i >= 0; i--) {
+ var fileManager = fileManagers[i];
+ if (fileManager[isSync ? 'supportsSync' : 'supports'](filename, currentDirectory, options, environment)) {
+ return fileManager;
+ }
+ }
+ return null;
};
- } // Adapted from http://mjijackson.com/2008/02/rgb-to-hsl-and-rgb-to-hsv-color-model-conversion-algorithms-in-javascript
-
- }, {
- key: "toHSV",
- value: function toHSV() {
- var r = this.rgb[0] / 255;
- var g = this.rgb[1] / 255;
- var b = this.rgb[2] / 255;
- var a = this.alpha;
- var max = Math.max(r, g, b);
- var min = Math.min(r, g, b);
- var h;
- var s;
- var v = max;
- var d = max - min;
-
- if (max === 0) {
- s = 0;
- } else {
- s = d / max;
- }
-
- if (max === min) {
- h = 0;
- } else {
- switch (max) {
- case r:
- h = (g - b) / d + (g < b ? 6 : 0);
- break;
-
- case g:
- h = (b - r) / d + 2;
- break;
-
- case b:
- h = (r - g) / d + 4;
- break;
- }
-
- h /= 6;
- }
-
- return {
- h: h * 360,
- s: s,
- v: v,
- a: a
+ Environment.prototype.addFileManager = function (fileManager) {
+ this.fileManagers.push(fileManager);
};
- }
- }, {
- key: "toARGB",
- value: function toARGB() {
- return toHex([this.alpha * 255].concat(this.rgb));
- }
- }, {
- key: "compare",
- value: function compare(x) {
- return x.rgb && x.rgb[0] === this.rgb[0] && x.rgb[1] === this.rgb[1] && x.rgb[2] === this.rgb[2] && x.alpha === this.alpha ? 0 : undefined;
- }
- }]);
+ Environment.prototype.clearFileManagers = function () {
+ this.fileManagers = [];
+ };
+ return Environment;
+ }());
- return Color;
- }(Node);
+ var colors = {
+ 'aliceblue': '#f0f8ff',
+ 'antiquewhite': '#faebd7',
+ 'aqua': '#00ffff',
+ 'aquamarine': '#7fffd4',
+ 'azure': '#f0ffff',
+ 'beige': '#f5f5dc',
+ 'bisque': '#ffe4c4',
+ 'black': '#000000',
+ 'blanchedalmond': '#ffebcd',
+ 'blue': '#0000ff',
+ 'blueviolet': '#8a2be2',
+ 'brown': '#a52a2a',
+ 'burlywood': '#deb887',
+ 'cadetblue': '#5f9ea0',
+ 'chartreuse': '#7fff00',
+ 'chocolate': '#d2691e',
+ 'coral': '#ff7f50',
+ 'cornflowerblue': '#6495ed',
+ 'cornsilk': '#fff8dc',
+ 'crimson': '#dc143c',
+ 'cyan': '#00ffff',
+ 'darkblue': '#00008b',
+ 'darkcyan': '#008b8b',
+ 'darkgoldenrod': '#b8860b',
+ 'darkgray': '#a9a9a9',
+ 'darkgrey': '#a9a9a9',
+ 'darkgreen': '#006400',
+ 'darkkhaki': '#bdb76b',
+ 'darkmagenta': '#8b008b',
+ 'darkolivegreen': '#556b2f',
+ 'darkorange': '#ff8c00',
+ 'darkorchid': '#9932cc',
+ 'darkred': '#8b0000',
+ 'darksalmon': '#e9967a',
+ 'darkseagreen': '#8fbc8f',
+ 'darkslateblue': '#483d8b',
+ 'darkslategray': '#2f4f4f',
+ 'darkslategrey': '#2f4f4f',
+ 'darkturquoise': '#00ced1',
+ 'darkviolet': '#9400d3',
+ 'deeppink': '#ff1493',
+ 'deepskyblue': '#00bfff',
+ 'dimgray': '#696969',
+ 'dimgrey': '#696969',
+ 'dodgerblue': '#1e90ff',
+ 'firebrick': '#b22222',
+ 'floralwhite': '#fffaf0',
+ 'forestgreen': '#228b22',
+ 'fuchsia': '#ff00ff',
+ 'gainsboro': '#dcdcdc',
+ 'ghostwhite': '#f8f8ff',
+ 'gold': '#ffd700',
+ 'goldenrod': '#daa520',
+ 'gray': '#808080',
+ 'grey': '#808080',
+ 'green': '#008000',
+ 'greenyellow': '#adff2f',
+ 'honeydew': '#f0fff0',
+ 'hotpink': '#ff69b4',
+ 'indianred': '#cd5c5c',
+ 'indigo': '#4b0082',
+ 'ivory': '#fffff0',
+ 'khaki': '#f0e68c',
+ 'lavender': '#e6e6fa',
+ 'lavenderblush': '#fff0f5',
+ 'lawngreen': '#7cfc00',
+ 'lemonchiffon': '#fffacd',
+ 'lightblue': '#add8e6',
+ 'lightcoral': '#f08080',
+ 'lightcyan': '#e0ffff',
+ 'lightgoldenrodyellow': '#fafad2',
+ 'lightgray': '#d3d3d3',
+ 'lightgrey': '#d3d3d3',
+ 'lightgreen': '#90ee90',
+ 'lightpink': '#ffb6c1',
+ 'lightsalmon': '#ffa07a',
+ 'lightseagreen': '#20b2aa',
+ 'lightskyblue': '#87cefa',
+ 'lightslategray': '#778899',
+ 'lightslategrey': '#778899',
+ 'lightsteelblue': '#b0c4de',
+ 'lightyellow': '#ffffe0',
+ 'lime': '#00ff00',
+ 'limegreen': '#32cd32',
+ 'linen': '#faf0e6',
+ 'magenta': '#ff00ff',
+ 'maroon': '#800000',
+ 'mediumaquamarine': '#66cdaa',
+ 'mediumblue': '#0000cd',
+ 'mediumorchid': '#ba55d3',
+ 'mediumpurple': '#9370d8',
+ 'mediumseagreen': '#3cb371',
+ 'mediumslateblue': '#7b68ee',
+ 'mediumspringgreen': '#00fa9a',
+ 'mediumturquoise': '#48d1cc',
+ 'mediumvioletred': '#c71585',
+ 'midnightblue': '#191970',
+ 'mintcream': '#f5fffa',
+ 'mistyrose': '#ffe4e1',
+ 'moccasin': '#ffe4b5',
+ 'navajowhite': '#ffdead',
+ 'navy': '#000080',
+ 'oldlace': '#fdf5e6',
+ 'olive': '#808000',
+ 'olivedrab': '#6b8e23',
+ 'orange': '#ffa500',
+ 'orangered': '#ff4500',
+ 'orchid': '#da70d6',
+ 'palegoldenrod': '#eee8aa',
+ 'palegreen': '#98fb98',
+ 'paleturquoise': '#afeeee',
+ 'palevioletred': '#d87093',
+ 'papayawhip': '#ffefd5',
+ 'peachpuff': '#ffdab9',
+ 'peru': '#cd853f',
+ 'pink': '#ffc0cb',
+ 'plum': '#dda0dd',
+ 'powderblue': '#b0e0e6',
+ 'purple': '#800080',
+ 'rebeccapurple': '#663399',
+ 'red': '#ff0000',
+ 'rosybrown': '#bc8f8f',
+ 'royalblue': '#4169e1',
+ 'saddlebrown': '#8b4513',
+ 'salmon': '#fa8072',
+ 'sandybrown': '#f4a460',
+ 'seagreen': '#2e8b57',
+ 'seashell': '#fff5ee',
+ 'sienna': '#a0522d',
+ 'silver': '#c0c0c0',
+ 'skyblue': '#87ceeb',
+ 'slateblue': '#6a5acd',
+ 'slategray': '#708090',
+ 'slategrey': '#708090',
+ 'snow': '#fffafa',
+ 'springgreen': '#00ff7f',
+ 'steelblue': '#4682b4',
+ 'tan': '#d2b48c',
+ 'teal': '#008080',
+ 'thistle': '#d8bfd8',
+ 'tomato': '#ff6347',
+ 'turquoise': '#40e0d0',
+ 'violet': '#ee82ee',
+ 'wheat': '#f5deb3',
+ 'white': '#ffffff',
+ 'whitesmoke': '#f5f5f5',
+ 'yellow': '#ffff00',
+ 'yellowgreen': '#9acd32'
+ };
- Color.prototype.type = 'Color';
-
- function clamp(v, max) {
- return Math.min(Math.max(v, 0), max);
- }
-
- function toHex(v) {
- return "#".concat(v.map(function (c) {
- c = clamp(Math.round(c), 255);
- return (c < 16 ? '0' : '') + c.toString(16);
- }).join(''));
- }
-
- Color.fromKeyword = function (keyword) {
- var c;
- var key = keyword.toLowerCase();
-
- if (colors.hasOwnProperty(key)) {
- c = new Color(colors[key].slice(1));
- } else if (key === 'transparent') {
- c = new Color([0, 0, 0], 0);
- }
-
- if (c) {
- c.value = keyword;
- return c;
- }
- };
-
- var Paren =
- /*#__PURE__*/
- function (_Node) {
- _inherits(Paren, _Node);
-
- function Paren(node) {
- var _this;
-
- _classCallCheck(this, Paren);
-
- _this = _possibleConstructorReturn(this, _getPrototypeOf(Paren).call(this));
- _this.value = node;
- return _this;
- }
-
- _createClass(Paren, [{
- key: "genCSS",
- value: function genCSS(context, output) {
- output.add('(');
- this.value.genCSS(context, output);
- output.add(')');
- }
- }, {
- key: "eval",
- value: function _eval(context) {
- return new Paren(this.value.eval(context));
- }
- }]);
-
- return Paren;
- }(Node);
-
- Paren.prototype.type = 'Paren';
-
- var _noSpaceCombinators = {
- '': true,
- ' ': true,
- '|': true
- };
-
- var Combinator =
- /*#__PURE__*/
- function (_Node) {
- _inherits(Combinator, _Node);
-
- function Combinator(value) {
- var _this;
-
- _classCallCheck(this, Combinator);
-
- _this = _possibleConstructorReturn(this, _getPrototypeOf(Combinator).call(this));
-
- if (value === ' ') {
- _this.value = ' ';
- _this.emptyOrWhitespace = true;
- } else {
- _this.value = value ? value.trim() : '';
- _this.emptyOrWhitespace = _this.value === '';
- }
-
- return _this;
- }
-
- _createClass(Combinator, [{
- key: "genCSS",
- value: function genCSS(context, output) {
- var spaceOrEmpty = context.compress || _noSpaceCombinators[this.value] ? '' : ' ';
- output.add(spaceOrEmpty + this.value + spaceOrEmpty);
- }
- }]);
-
- return Combinator;
- }(Node);
-
- Combinator.prototype.type = 'Combinator';
-
- var Element =
- /*#__PURE__*/
- function (_Node) {
- _inherits(Element, _Node);
-
- function Element(combinator, value, isVariable, index, currentFileInfo, visibilityInfo) {
- var _this;
-
- _classCallCheck(this, Element);
-
- _this = _possibleConstructorReturn(this, _getPrototypeOf(Element).call(this));
- _this.combinator = combinator instanceof Combinator ? combinator : new Combinator(combinator);
-
- if (typeof value === 'string') {
- _this.value = value.trim();
- } else if (value) {
- _this.value = value;
- } else {
- _this.value = '';
- }
-
- _this.isVariable = isVariable;
- _this._index = index;
- _this._fileInfo = currentFileInfo;
-
- _this.copyVisibilityInfo(visibilityInfo);
-
- _this.setParent(_this.combinator, _assertThisInitialized(_this));
-
- return _this;
- }
-
- _createClass(Element, [{
- key: "accept",
- value: function accept(visitor) {
- var value = this.value;
- this.combinator = visitor.visit(this.combinator);
-
- if (_typeof(value) === 'object') {
- this.value = visitor.visit(value);
+ var unitConversions = {
+ length: {
+ 'm': 1,
+ 'cm': 0.01,
+ 'mm': 0.001,
+ 'in': 0.0254,
+ 'px': 0.0254 / 96,
+ 'pt': 0.0254 / 72,
+ 'pc': 0.0254 / 72 * 12
+ },
+ duration: {
+ 's': 1,
+ 'ms': 0.001
+ },
+ angle: {
+ 'rad': 1 / (2 * Math.PI),
+ 'deg': 1 / 360,
+ 'grad': 1 / 400,
+ 'turn': 1
}
- }
- }, {
- key: "eval",
- value: function _eval(context) {
- return new Element(this.combinator, this.value.eval ? this.value.eval(context) : this.value, this.isVariable, this.getIndex(), this.fileInfo(), this.visibilityInfo());
- }
- }, {
- key: "clone",
- value: function clone() {
- return new Element(this.combinator, this.value, this.isVariable, this.getIndex(), this.fileInfo(), this.visibilityInfo());
- }
- }, {
- key: "genCSS",
- value: function genCSS(context, output) {
- output.add(this.toCSS(context), this.fileInfo(), this.getIndex());
- }
- }, {
- key: "toCSS",
- value: function toCSS() {
- var context = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};
- var value = this.value;
- var firstSelector = context.firstSelector;
+ };
- if (value instanceof Paren) {
- // selector in parens should not be affected by outer selector
- // flags (breaks only interpolated selectors - see #1973)
- context.firstSelector = true;
+ var data = { colors: colors, unitConversions: unitConversions };
+
+ /**
+ * The reason why Node is a class and other nodes simply do not extend
+ * from Node (since we're transpiling) is due to this issue:
+ *
+ * https://github.com/less/less.js/issues/3434
+ */
+ var Node = /** @class */ (function () {
+ function Node() {
+ this.parent = null;
+ this.visibilityBlocks = undefined;
+ this.nodeVisible = undefined;
+ this.rootNode = null;
+ this.parsed = null;
}
-
- value = value.toCSS ? value.toCSS(context) : value;
- context.firstSelector = firstSelector;
-
- if (value === '' && this.combinator.value.charAt(0) === '&') {
- return '';
- } else {
- return this.combinator.toCSS(context) + value;
- }
- }
- }]);
-
- return Element;
- }(Node);
-
- Element.prototype.type = 'Element';
-
- var Math$1 = {
- ALWAYS: 0,
- PARENS_DIVISION: 1,
- PARENS: 2,
- STRICT_LEGACY: 3
- };
- var RewriteUrls = {
- OFF: 0,
- LOCAL: 1,
- ALL: 2
- };
-
- function createCommonjsModule(fn, module) {
- return module = { exports: {} }, fn(module, module.exports), module.exports;
- }
-
- var clone_1 = createCommonjsModule(function (module) {
- var clone = (function() {
-
- function _instanceof(obj, type) {
- return type != null && obj instanceof type;
- }
-
- var nativeMap;
- try {
- nativeMap = Map;
- } catch(_) {
- // maybe a reference error because no `Map`. Give it a dummy value that no
- // value will ever be an instanceof.
- nativeMap = function() {};
- }
-
- var nativeSet;
- try {
- nativeSet = Set;
- } catch(_) {
- nativeSet = function() {};
- }
-
- var nativePromise;
- try {
- nativePromise = Promise;
- } catch(_) {
- nativePromise = function() {};
- }
-
- /**
- * Clones (copies) an Object using deep copying.
- *
- * This function supports circular references by default, but if you are certain
- * there are no circular references in your object, you can save some CPU time
- * by calling clone(obj, false).
- *
- * Caution: if `circular` is false and `parent` contains circular references,
- * your program may enter an infinite loop and crash.
- *
- * @param `parent` - the object to be cloned
- * @param `circular` - set to true if the object to be cloned may contain
- * circular references. (optional - true by default)
- * @param `depth` - set to a number if the object is only to be cloned to
- * a particular depth. (optional - defaults to Infinity)
- * @param `prototype` - sets the prototype to be used when cloning an object.
- * (optional - defaults to parent prototype).
- * @param `includeNonEnumerable` - set to true if the non-enumerable properties
- * should be cloned as well. Non-enumerable properties on the prototype
- * chain will be ignored. (optional - false by default)
- */
- function clone(parent, circular, depth, prototype, includeNonEnumerable) {
- if (typeof circular === 'object') {
- depth = circular.depth;
- prototype = circular.prototype;
- includeNonEnumerable = circular.includeNonEnumerable;
- circular = circular.circular;
- }
- // maintain two arrays for circular references, where corresponding parents
- // and children have the same index
- var allParents = [];
- var allChildren = [];
-
- var useBuffer = typeof Buffer != 'undefined';
-
- if (typeof circular == 'undefined')
- circular = true;
-
- if (typeof depth == 'undefined')
- depth = Infinity;
-
- // recurse this function so we don't reset allParents and allChildren
- function _clone(parent, depth) {
- // cloning null always returns null
- if (parent === null)
- return null;
-
- if (depth === 0)
- return parent;
-
- var child;
- var proto;
- if (typeof parent != 'object') {
- return parent;
- }
-
- if (_instanceof(parent, nativeMap)) {
- child = new nativeMap();
- } else if (_instanceof(parent, nativeSet)) {
- child = new nativeSet();
- } else if (_instanceof(parent, nativePromise)) {
- child = new nativePromise(function (resolve, reject) {
- parent.then(function(value) {
- resolve(_clone(value, depth - 1));
- }, function(err) {
- reject(_clone(err, depth - 1));
- });
+ Object.defineProperty(Node.prototype, "currentFileInfo", {
+ get: function () {
+ return this.fileInfo();
+ },
+ enumerable: false,
+ configurable: true
});
- } else if (clone.__isArray(parent)) {
- child = [];
- } else if (clone.__isRegExp(parent)) {
- child = new RegExp(parent.source, __getRegExpFlags(parent));
- if (parent.lastIndex) child.lastIndex = parent.lastIndex;
- } else if (clone.__isDate(parent)) {
- child = new Date(parent.getTime());
- } else if (useBuffer && Buffer.isBuffer(parent)) {
- if (Buffer.allocUnsafe) {
- // Node.js >= 4.5.0
- child = Buffer.allocUnsafe(parent.length);
- } else {
- // Older Node.js versions
- child = new Buffer(parent.length);
+ Object.defineProperty(Node.prototype, "index", {
+ get: function () {
+ return this.getIndex();
+ },
+ enumerable: false,
+ configurable: true
+ });
+ Node.prototype.setParent = function (nodes, parent) {
+ function set(node) {
+ if (node && node instanceof Node) {
+ node.parent = parent;
+ }
+ }
+ if (Array.isArray(nodes)) {
+ nodes.forEach(set);
+ }
+ else {
+ set(nodes);
+ }
+ };
+ Node.prototype.getIndex = function () {
+ return this._index || (this.parent && this.parent.getIndex()) || 0;
+ };
+ Node.prototype.fileInfo = function () {
+ return this._fileInfo || (this.parent && this.parent.fileInfo()) || {};
+ };
+ Node.prototype.isRulesetLike = function () { return false; };
+ Node.prototype.toCSS = function (context) {
+ var strs = [];
+ this.genCSS(context, {
+ add: function (chunk, fileInfo, index) {
+ strs.push(chunk);
+ },
+ isEmpty: function () {
+ return strs.length === 0;
+ }
+ });
+ return strs.join('');
+ };
+ Node.prototype.genCSS = function (context, output) {
+ output.add(this.value);
+ };
+ Node.prototype.accept = function (visitor) {
+ this.value = visitor.visit(this.value);
+ };
+ Node.prototype.eval = function () { return this; };
+ Node.prototype._operate = function (context, op, a, b) {
+ switch (op) {
+ case '+': return a + b;
+ case '-': return a - b;
+ case '*': return a * b;
+ case '/': return a / b;
+ }
+ };
+ Node.prototype.fround = function (context, value) {
+ var precision = context && context.numPrecision;
+ // add "epsilon" to ensure numbers like 1.000000005 (represented as 1.000000004999...) are properly rounded:
+ return (precision) ? Number((value + 2e-16).toFixed(precision)) : value;
+ };
+ Node.compare = function (a, b) {
+ /* returns:
+ -1: a < b
+ 0: a = b
+ 1: a > b
+ and *any* other value for a != b (e.g. undefined, NaN, -2 etc.) */
+ if ((a.compare) &&
+ // for "symmetric results" force toCSS-based comparison
+ // of Quoted or Anonymous if either value is one of those
+ !(b.type === 'Quoted' || b.type === 'Anonymous')) {
+ return a.compare(b);
+ }
+ else if (b.compare) {
+ return -b.compare(a);
+ }
+ else if (a.type !== b.type) {
+ return undefined;
+ }
+ a = a.value;
+ b = b.value;
+ if (!Array.isArray(a)) {
+ return a === b ? 0 : undefined;
+ }
+ if (a.length !== b.length) {
+ return undefined;
+ }
+ for (var i = 0; i < a.length; i++) {
+ if (Node.compare(a[i], b[i]) !== 0) {
+ return undefined;
+ }
+ }
+ return 0;
+ };
+ Node.numericCompare = function (a, b) {
+ return a < b ? -1
+ : a === b ? 0
+ : a > b ? 1 : undefined;
+ };
+ // Returns true if this node represents root of ast imported by reference
+ Node.prototype.blocksVisibility = function () {
+ if (this.visibilityBlocks == null) {
+ this.visibilityBlocks = 0;
+ }
+ return this.visibilityBlocks !== 0;
+ };
+ Node.prototype.addVisibilityBlock = function () {
+ if (this.visibilityBlocks == null) {
+ this.visibilityBlocks = 0;
+ }
+ this.visibilityBlocks = this.visibilityBlocks + 1;
+ };
+ Node.prototype.removeVisibilityBlock = function () {
+ if (this.visibilityBlocks == null) {
+ this.visibilityBlocks = 0;
+ }
+ this.visibilityBlocks = this.visibilityBlocks - 1;
+ };
+ // Turns on node visibility - if called node will be shown in output regardless
+ // of whether it comes from import by reference or not
+ Node.prototype.ensureVisibility = function () {
+ this.nodeVisible = true;
+ };
+ // Turns off node visibility - if called node will NOT be shown in output regardless
+ // of whether it comes from import by reference or not
+ Node.prototype.ensureInvisibility = function () {
+ this.nodeVisible = false;
+ };
+ // return values:
+ // false - the node must not be visible
+ // true - the node must be visible
+ // undefined or null - the node has the same visibility as its parent
+ Node.prototype.isVisible = function () {
+ return this.nodeVisible;
+ };
+ Node.prototype.visibilityInfo = function () {
+ return {
+ visibilityBlocks: this.visibilityBlocks,
+ nodeVisible: this.nodeVisible
+ };
+ };
+ Node.prototype.copyVisibilityInfo = function (info) {
+ if (!info) {
+ return;
+ }
+ this.visibilityBlocks = info.visibilityBlocks;
+ this.nodeVisible = info.nodeVisible;
+ };
+ return Node;
+ }());
+
+ //
+ // RGB Colors - #ff0014, #eee
+ //
+ var Color = function (rgb, a, originalForm) {
+ var self = this;
+ //
+ // The end goal here, is to parse the arguments
+ // into an integer triplet, such as `128, 255, 0`
+ //
+ // This facilitates operations and conversions.
+ //
+ if (Array.isArray(rgb)) {
+ this.rgb = rgb;
}
- parent.copy(child);
- return child;
- } else if (_instanceof(parent, Error)) {
- child = Object.create(parent);
- } else {
- if (typeof prototype == 'undefined') {
- proto = Object.getPrototypeOf(parent);
- child = Object.create(proto);
+ else if (rgb.length >= 6) {
+ this.rgb = [];
+ rgb.match(/.{2}/g).map(function (c, i) {
+ if (i < 3) {
+ self.rgb.push(parseInt(c, 16));
+ }
+ else {
+ self.alpha = (parseInt(c, 16)) / 255;
+ }
+ });
}
else {
- child = Object.create(prototype);
- proto = prototype;
- }
- }
-
- if (circular) {
- var index = allParents.indexOf(parent);
-
- if (index != -1) {
- return allChildren[index];
- }
- allParents.push(parent);
- allChildren.push(child);
- }
-
- if (_instanceof(parent, nativeMap)) {
- parent.forEach(function(value, key) {
- var keyChild = _clone(key, depth - 1);
- var valueChild = _clone(value, depth - 1);
- child.set(keyChild, valueChild);
- });
- }
- if (_instanceof(parent, nativeSet)) {
- parent.forEach(function(value) {
- var entryChild = _clone(value, depth - 1);
- child.add(entryChild);
- });
- }
-
- for (var i in parent) {
- var attrs;
- if (proto) {
- attrs = Object.getOwnPropertyDescriptor(proto, i);
- }
-
- if (attrs && attrs.set == null) {
- continue;
- }
- child[i] = _clone(parent[i], depth - 1);
- }
-
- if (Object.getOwnPropertySymbols) {
- var symbols = Object.getOwnPropertySymbols(parent);
- for (var i = 0; i < symbols.length; i++) {
- // Don't need to worry about cloning a symbol because it is a primitive,
- // like a number or string.
- var symbol = symbols[i];
- var descriptor = Object.getOwnPropertyDescriptor(parent, symbol);
- if (descriptor && !descriptor.enumerable && !includeNonEnumerable) {
- continue;
- }
- child[symbol] = _clone(parent[symbol], depth - 1);
- if (!descriptor.enumerable) {
- Object.defineProperty(child, symbol, {
- enumerable: false
+ this.rgb = [];
+ rgb.split('').map(function (c, i) {
+ if (i < 3) {
+ self.rgb.push(parseInt(c + c, 16));
+ }
+ else {
+ self.alpha = (parseInt(c + c, 16)) / 255;
+ }
});
- }
}
- }
-
- if (includeNonEnumerable) {
- var allPropertyNames = Object.getOwnPropertyNames(parent);
- for (var i = 0; i < allPropertyNames.length; i++) {
- var propertyName = allPropertyNames[i];
- var descriptor = Object.getOwnPropertyDescriptor(parent, propertyName);
- if (descriptor && descriptor.enumerable) {
- continue;
- }
- child[propertyName] = _clone(parent[propertyName], depth - 1);
- Object.defineProperty(child, propertyName, {
- enumerable: false
- });
+ this.alpha = this.alpha || (typeof a === 'number' ? a : 1);
+ if (typeof originalForm !== 'undefined') {
+ this.value = originalForm;
}
- }
-
- return child;
- }
-
- return _clone(parent, depth);
- }
-
- /**
- * Simple flat clone using prototype, accepts only objects, usefull for property
- * override on FLAT configuration object (no nested props).
- *
- * USE WITH CAUTION! This may not behave as you wish if you do not know how this
- * works.
- */
- clone.clonePrototype = function clonePrototype(parent) {
- if (parent === null)
- return null;
-
- var c = function () {};
- c.prototype = parent;
- return new c();
- };
-
- // private utility functions
-
- function __objToStr(o) {
- return Object.prototype.toString.call(o);
- }
- clone.__objToStr = __objToStr;
-
- function __isDate(o) {
- return typeof o === 'object' && __objToStr(o) === '[object Date]';
- }
- clone.__isDate = __isDate;
-
- function __isArray(o) {
- return typeof o === 'object' && __objToStr(o) === '[object Array]';
- }
- clone.__isArray = __isArray;
-
- function __isRegExp(o) {
- return typeof o === 'object' && __objToStr(o) === '[object RegExp]';
- }
- clone.__isRegExp = __isRegExp;
-
- function __getRegExpFlags(re) {
- var flags = '';
- if (re.global) flags += 'g';
- if (re.ignoreCase) flags += 'i';
- if (re.multiline) flags += 'm';
- return flags;
- }
- clone.__getRegExpFlags = __getRegExpFlags;
-
- return clone;
- })();
-
- if ( module.exports) {
- module.exports = clone;
- }
- });
-
- /* jshint proto: true */
- function getLocation(index, inputStream) {
- var n = index + 1;
- var line = null;
- var column = -1;
-
- while (--n >= 0 && inputStream.charAt(n) !== '\n') {
- column++;
- }
-
- if (typeof index === 'number') {
- line = (inputStream.slice(0, index).match(/\n/g) || '').length;
- }
-
- return {
- line: line,
- column: column
};
- }
- function copyArray(arr) {
- var i;
- var length = arr.length;
- var copy = new Array(length);
-
- for (i = 0; i < length; i++) {
- copy[i] = arr[i];
- }
-
- return copy;
- }
- function clone(obj) {
- var cloned = {};
-
- for (var prop in obj) {
- if (obj.hasOwnProperty(prop)) {
- cloned[prop] = obj[prop];
- }
- }
-
- return cloned;
- }
- function defaults(obj1, obj2) {
- var newObj = obj2 || {};
-
- if (!obj2._defaults) {
- newObj = {};
-
- var _defaults = clone_1(obj1);
-
- newObj._defaults = _defaults;
- var cloned = obj2 ? clone_1(obj2) : {};
- Object.assign(newObj, _defaults, cloned);
- }
-
- return newObj;
- }
- function copyOptions(obj1, obj2) {
- if (obj2 && obj2._defaults) {
- return obj2;
- }
-
- var opts = defaults(obj1, obj2);
-
- if (opts.strictMath) {
- opts.math = Math$1.STRICT_LEGACY;
- } // Back compat with changed relativeUrls option
-
-
- if (opts.relativeUrls) {
- opts.rewriteUrls = RewriteUrls.ALL;
- }
-
- if (typeof opts.math === 'string') {
- switch (opts.math.toLowerCase()) {
- case 'always':
- opts.math = Math$1.ALWAYS;
- break;
-
- case 'parens-division':
- opts.math = Math$1.PARENS_DIVISION;
- break;
-
- case 'strict':
- case 'parens':
- opts.math = Math$1.PARENS;
- break;
-
- case 'strict-legacy':
- opts.math = Math$1.STRICT_LEGACY;
- }
- }
-
- if (typeof opts.rewriteUrls === 'string') {
- switch (opts.rewriteUrls.toLowerCase()) {
- case 'off':
- opts.rewriteUrls = RewriteUrls.OFF;
- break;
-
- case 'local':
- opts.rewriteUrls = RewriteUrls.LOCAL;
- break;
-
- case 'all':
- opts.rewriteUrls = RewriteUrls.ALL;
- break;
- }
- }
-
- return opts;
- }
- function merge(obj1, obj2) {
- for (var prop in obj2) {
- if (obj2.hasOwnProperty(prop)) {
- obj1[prop] = obj2[prop];
- }
- }
-
- return obj1;
- }
- function flattenArray(arr) {
- var result = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : [];
-
- for (var i = 0, length = arr.length; i < length; i++) {
- var value = arr[i];
-
- if (Array.isArray(value)) {
- flattenArray(value, result);
- } else {
- if (value !== undefined) {
- result.push(value);
- }
- }
- }
-
- return result;
- }
-
- var utils = /*#__PURE__*/Object.freeze({
- getLocation: getLocation,
- copyArray: copyArray,
- clone: clone,
- defaults: defaults,
- copyOptions: copyOptions,
- merge: merge,
- flattenArray: flattenArray
- });
-
- /**
- * This is a centralized class of any error that could be thrown internally (mostly by the parser).
- * Besides standard .message it keeps some additional data like a path to the file where the error
- * occurred along with line and column numbers.
- *
- * @class
- * @extends Error
- * @type {module.LessError}
- *
- * @prop {string} type
- * @prop {string} filename
- * @prop {number} index
- * @prop {number} line
- * @prop {number} column
- * @prop {number} callLine
- * @prop {number} callExtract
- * @prop {string[]} extract
- *
- * @param {Object} e - An error object to wrap around or just a descriptive object
- * @param {Object} fileContentMap - An object with file contents in 'contents' property (like importManager) @todo - move to fileManager?
- * @param {string} [currentFilename]
- */
-
- var LessError = function LessError(e, fileContentMap, currentFilename) {
- Error.call(this);
- var filename = e.filename || currentFilename;
- this.message = e.message;
- this.stack = e.stack;
-
- if (fileContentMap && filename) {
- var input = fileContentMap.contents[filename];
- var loc = getLocation(e.index, input);
- var line = loc.line;
- var col = loc.column;
- var callLine = e.call && getLocation(e.call, input).line;
- var lines = input ? input.split('\n') : '';
- this.type = e.type || 'Syntax';
- this.filename = filename;
- this.index = e.index;
- this.line = typeof line === 'number' ? line + 1 : null;
- this.column = col;
-
- if (!this.line && this.stack) {
- var found = this.stack.match(/(|Function):(\d+):(\d+)/);
-
- if (found) {
- if (found[2]) {
- this.line = parseInt(found[2]) - 2;
- }
-
- if (found[3]) {
- this.column = parseInt(found[3]);
- }
- }
- }
-
- this.callLine = callLine + 1;
- this.callExtract = lines[callLine];
- this.extract = [lines[this.line - 2], lines[this.line - 1], lines[this.line]];
- }
- };
-
- if (typeof Object.create === 'undefined') {
- var F = function F() {};
-
- F.prototype = Error.prototype;
- LessError.prototype = new F();
- } else {
- LessError.prototype = Object.create(Error.prototype);
- }
-
- LessError.prototype.constructor = LessError;
- /**
- * An overridden version of the default Object.prototype.toString
- * which uses additional information to create a helpful message.
- *
- * @param {Object} options
- * @returns {string}
- */
-
- LessError.prototype.toString = function () {
- var options = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};
- var message = '';
- var extract = this.extract || [];
- var error = [];
-
- var stylize = function stylize(str) {
- return str;
- };
-
- if (options.stylize) {
- var type = _typeof(options.stylize);
-
- if (type !== 'function') {
- throw Error("options.stylize should be a function, got a ".concat(type, "!"));
- }
-
- stylize = options.stylize;
- }
-
- if (this.line !== null) {
- if (typeof extract[0] === 'string') {
- error.push(stylize("".concat(this.line - 1, " ").concat(extract[0]), 'grey'));
- }
-
- if (typeof extract[1] === 'string') {
- var errorTxt = "".concat(this.line, " ");
-
- if (extract[1]) {
- errorTxt += extract[1].slice(0, this.column) + stylize(stylize(stylize(extract[1].substr(this.column, 1), 'bold') + extract[1].slice(this.column + 1), 'red'), 'inverse');
- }
-
- error.push(errorTxt);
- }
-
- if (typeof extract[2] === 'string') {
- error.push(stylize("".concat(this.line + 1, " ").concat(extract[2]), 'grey'));
- }
-
- error = "".concat(error.join('\n') + stylize('', 'reset'), "\n");
- }
-
- message += stylize("".concat(this.type, "Error: ").concat(this.message), 'red');
-
- if (this.filename) {
- message += stylize(' in ', 'red') + this.filename;
- }
-
- if (this.line) {
- message += stylize(" on line ".concat(this.line, ", column ").concat(this.column + 1, ":"), 'grey');
- }
-
- message += "\n".concat(error);
-
- if (this.callLine) {
- message += "".concat(stylize('from ', 'red') + (this.filename || ''), "/n");
- message += "".concat(stylize(this.callLine, 'grey'), " ").concat(this.callExtract, "/n");
- }
-
- return message;
- };
-
- var Selector =
- /*#__PURE__*/
- function (_Node) {
- _inherits(Selector, _Node);
-
- function Selector(elements, extendList, condition, index, currentFileInfo, visibilityInfo) {
- var _this;
-
- _classCallCheck(this, Selector);
-
- _this = _possibleConstructorReturn(this, _getPrototypeOf(Selector).call(this));
- _this.extendList = extendList;
- _this.condition = condition;
- _this.evaldCondition = !condition;
- _this._index = index;
- _this._fileInfo = currentFileInfo;
- _this.elements = _this.getElements(elements);
- _this.mixinElements_ = undefined;
-
- _this.copyVisibilityInfo(visibilityInfo);
-
- _this.setParent(_this.elements, _assertThisInitialized(_this));
-
- return _this;
- }
-
- _createClass(Selector, [{
- key: "accept",
- value: function accept(visitor) {
- if (this.elements) {
- this.elements = visitor.visitArray(this.elements);
- }
-
- if (this.extendList) {
- this.extendList = visitor.visitArray(this.extendList);
- }
-
- if (this.condition) {
- this.condition = visitor.visit(this.condition);
- }
- }
- }, {
- key: "createDerived",
- value: function createDerived(elements, extendList, evaldCondition) {
- elements = this.getElements(elements);
- var newSelector = new Selector(elements, extendList || this.extendList, null, this.getIndex(), this.fileInfo(), this.visibilityInfo());
- newSelector.evaldCondition = evaldCondition != null ? evaldCondition : this.evaldCondition;
- newSelector.mediaEmpty = this.mediaEmpty;
- return newSelector;
- }
- }, {
- key: "getElements",
- value: function getElements(els) {
- if (!els) {
- return [new Element('', '&', false, this._index, this._fileInfo)];
- }
-
- if (typeof els === 'string') {
- this.parse.parseNode(els, ['selector'], this._index, this._fileInfo, function (err, result) {
- if (err) {
- throw new LessError({
- index: err.index,
- message: err.message
- }, this.parse.imports, this._fileInfo.filename);
+ Color.prototype = Object.assign(new Node(), {
+ type: 'Color',
+ luma: function () {
+ var r = this.rgb[0] / 255, g = this.rgb[1] / 255, b = this.rgb[2] / 255;
+ r = (r <= 0.03928) ? r / 12.92 : Math.pow(((r + 0.055) / 1.055), 2.4);
+ g = (g <= 0.03928) ? g / 12.92 : Math.pow(((g + 0.055) / 1.055), 2.4);
+ b = (b <= 0.03928) ? b / 12.92 : Math.pow(((b + 0.055) / 1.055), 2.4);
+ return 0.2126 * r + 0.7152 * g + 0.0722 * b;
+ },
+ genCSS: function (context, output) {
+ output.add(this.toCSS(context));
+ },
+ toCSS: function (context, doNotCompress) {
+ var compress = context && context.compress && !doNotCompress;
+ var color;
+ var alpha;
+ var colorFunction;
+ var args = [];
+ // `value` is set if this color was originally
+ // converted from a named color string so we need
+ // to respect this and try to output named color too.
+ alpha = this.fround(context, this.alpha);
+ if (this.value) {
+ if (this.value.indexOf('rgb') === 0) {
+ if (alpha < 1) {
+ colorFunction = 'rgba';
+ }
+ }
+ else if (this.value.indexOf('hsl') === 0) {
+ if (alpha < 1) {
+ colorFunction = 'hsla';
+ }
+ else {
+ colorFunction = 'hsl';
+ }
+ }
+ else {
+ return this.value;
+ }
}
-
- els = result[0].elements;
- });
- }
-
- return els;
- }
- }, {
- key: "createEmptySelectors",
- value: function createEmptySelectors() {
- var el = new Element('', '&', false, this._index, this._fileInfo);
- var sels = [new Selector([el], null, null, this._index, this._fileInfo)];
- sels[0].mediaEmpty = true;
- return sels;
- }
- }, {
- key: "match",
- value: function match(other) {
- var elements = this.elements;
- var len = elements.length;
- var olen;
- var i;
- other = other.mixinElements();
- olen = other.length;
-
- if (olen === 0 || len < olen) {
- return 0;
- } else {
- for (i = 0; i < olen; i++) {
- if (elements[i].value !== other[i]) {
- return 0;
+ else {
+ if (alpha < 1) {
+ colorFunction = 'rgba';
+ }
}
- }
+ switch (colorFunction) {
+ case 'rgba':
+ args = this.rgb.map(function (c) {
+ return clamp$1(Math.round(c), 255);
+ }).concat(clamp$1(alpha, 1));
+ break;
+ case 'hsla':
+ args.push(clamp$1(alpha, 1));
+ case 'hsl':
+ color = this.toHSL();
+ args = [
+ this.fround(context, color.h),
+ this.fround(context, color.s * 100) + "%",
+ this.fround(context, color.l * 100) + "%"
+ ].concat(args);
+ }
+ if (colorFunction) {
+ // Values are capped between `0` and `255`, rounded and zero-padded.
+ return colorFunction + "(" + args.join("," + (compress ? '' : ' ')) + ")";
+ }
+ color = this.toRGB();
+ if (compress) {
+ var splitcolor = color.split('');
+ // Convert color to short format
+ if (splitcolor[1] === splitcolor[2] && splitcolor[3] === splitcolor[4] && splitcolor[5] === splitcolor[6]) {
+ color = "#" + splitcolor[1] + splitcolor[3] + splitcolor[5];
+ }
+ }
+ return color;
+ },
+ //
+ // Operations have to be done per-channel, if not,
+ // channels will spill onto each other. Once we have
+ // our result, in the form of an integer triplet,
+ // we create a new Color node to hold the result.
+ //
+ operate: function (context, op, other) {
+ var rgb = new Array(3);
+ var alpha = this.alpha * (1 - other.alpha) + other.alpha;
+ for (var c = 0; c < 3; c++) {
+ rgb[c] = this._operate(context, op, this.rgb[c], other.rgb[c]);
+ }
+ return new Color(rgb, alpha);
+ },
+ toRGB: function () {
+ return toHex(this.rgb);
+ },
+ toHSL: function () {
+ var r = this.rgb[0] / 255, g = this.rgb[1] / 255, b = this.rgb[2] / 255, a = this.alpha;
+ var max = Math.max(r, g, b), min = Math.min(r, g, b);
+ var h;
+ var s;
+ var l = (max + min) / 2;
+ var d = max - min;
+ if (max === min) {
+ h = s = 0;
+ }
+ else {
+ s = l > 0.5 ? d / (2 - max - min) : d / (max + min);
+ switch (max) {
+ case r:
+ h = (g - b) / d + (g < b ? 6 : 0);
+ break;
+ case g:
+ h = (b - r) / d + 2;
+ break;
+ case b:
+ h = (r - g) / d + 4;
+ break;
+ }
+ h /= 6;
+ }
+ return { h: h * 360, s: s, l: l, a: a };
+ },
+ // Adapted from http://mjijackson.com/2008/02/rgb-to-hsl-and-rgb-to-hsv-color-model-conversion-algorithms-in-javascript
+ toHSV: function () {
+ var r = this.rgb[0] / 255, g = this.rgb[1] / 255, b = this.rgb[2] / 255, a = this.alpha;
+ var max = Math.max(r, g, b), min = Math.min(r, g, b);
+ var h;
+ var s;
+ var v = max;
+ var d = max - min;
+ if (max === 0) {
+ s = 0;
+ }
+ else {
+ s = d / max;
+ }
+ if (max === min) {
+ h = 0;
+ }
+ else {
+ switch (max) {
+ case r:
+ h = (g - b) / d + (g < b ? 6 : 0);
+ break;
+ case g:
+ h = (b - r) / d + 2;
+ break;
+ case b:
+ h = (r - g) / d + 4;
+ break;
+ }
+ h /= 6;
+ }
+ return { h: h * 360, s: s, v: v, a: a };
+ },
+ toARGB: function () {
+ return toHex([this.alpha * 255].concat(this.rgb));
+ },
+ compare: function (x) {
+ return (x.rgb &&
+ x.rgb[0] === this.rgb[0] &&
+ x.rgb[1] === this.rgb[1] &&
+ x.rgb[2] === this.rgb[2] &&
+ x.alpha === this.alpha) ? 0 : undefined;
}
-
- return olen; // return number of matched elements
- }
- }, {
- key: "mixinElements",
- value: function mixinElements() {
- if (this.mixinElements_) {
- return this.mixinElements_;
+ });
+ Color.fromKeyword = function (keyword) {
+ var c;
+ var key = keyword.toLowerCase();
+ if (colors.hasOwnProperty(key)) {
+ c = new Color(colors[key].slice(1));
}
-
- var elements = this.elements.map(function (v) {
- return v.combinator.value + (v.value.value || v.value);
- }).join('').match(/[,\*\.\w-]([\w-]|(\\.))*/g);
-
- if (elements) {
- if (elements[0] === '&') {
- elements.shift();
- }
- } else {
- elements = [];
+ else if (key === 'transparent') {
+ c = new Color([0, 0, 0], 0);
}
-
- return this.mixinElements_ = elements;
- }
- }, {
- key: "isJustParentSelector",
- value: function isJustParentSelector() {
- return !this.mediaEmpty && this.elements.length === 1 && this.elements[0].value === '&' && (this.elements[0].combinator.value === ' ' || this.elements[0].combinator.value === '');
- }
- }, {
- key: "eval",
- value: function _eval(context) {
- var evaldCondition = this.condition && this.condition.eval(context);
- var elements = this.elements;
- var extendList = this.extendList;
- elements = elements && elements.map(function (e) {
- return e.eval(context);
- });
- extendList = extendList && extendList.map(function (extend) {
- return extend.eval(context);
- });
- return this.createDerived(elements, extendList, evaldCondition);
- }
- }, {
- key: "genCSS",
- value: function genCSS(context, output) {
- var i;
- var element;
-
- if ((!context || !context.firstSelector) && this.elements[0].combinator.value === '') {
- output.add(' ', this.fileInfo(), this.getIndex());
+ if (c) {
+ c.value = keyword;
+ return c;
}
-
- for (i = 0; i < this.elements.length; i++) {
- element = this.elements[i];
- element.genCSS(context, output);
- }
- }
- }, {
- key: "getIsOutput",
- value: function getIsOutput() {
- return this.evaldCondition;
- }
- }]);
-
- return Selector;
- }(Node);
-
- Selector.prototype.type = 'Selector';
-
- var Value =
- /*#__PURE__*/
- function (_Node) {
- _inherits(Value, _Node);
-
- function Value(value) {
- var _this;
-
- _classCallCheck(this, Value);
-
- _this = _possibleConstructorReturn(this, _getPrototypeOf(Value).call(this));
-
- if (!value) {
- throw new Error('Value requires an array argument');
- }
-
- if (!Array.isArray(value)) {
- _this.value = [value];
- } else {
- _this.value = value;
- }
-
- return _this;
+ };
+ function clamp$1(v, max) {
+ return Math.min(Math.max(v, 0), max);
+ }
+ function toHex(v) {
+ return "#" + v.map(function (c) {
+ c = clamp$1(Math.round(c), 255);
+ return (c < 16 ? '0' : '') + c.toString(16);
+ }).join('');
}
- _createClass(Value, [{
- key: "accept",
- value: function accept(visitor) {
- if (this.value) {
- this.value = visitor.visitArray(this.value);
+ var Paren = function (node) {
+ this.value = node;
+ };
+ Paren.prototype = Object.assign(new Node(), {
+ type: 'Paren',
+ genCSS: function (context, output) {
+ output.add('(');
+ this.value.genCSS(context, output);
+ output.add(')');
+ },
+ eval: function (context) {
+ return new Paren(this.value.eval(context));
}
- }
- }, {
- key: "eval",
- value: function _eval(context) {
- if (this.value.length === 1) {
- return this.value[0].eval(context);
- } else {
- return new Value(this.value.map(function (v) {
- return v.eval(context);
- }));
+ });
+
+ var _noSpaceCombinators = {
+ '': true,
+ ' ': true,
+ '|': true
+ };
+ var Combinator = function (value) {
+ if (value === ' ') {
+ this.value = ' ';
+ this.emptyOrWhitespace = true;
}
- }
- }, {
- key: "genCSS",
- value: function genCSS(context, output) {
- var i;
-
- for (i = 0; i < this.value.length; i++) {
- this.value[i].genCSS(context, output);
-
- if (i + 1 < this.value.length) {
- output.add(context && context.compress ? ',' : ', ');
- }
+ else {
+ this.value = value ? value.trim() : '';
+ this.emptyOrWhitespace = this.value === '';
}
- }
- }]);
-
- return Value;
- }(Node);
-
- Value.prototype.type = 'Value';
-
- var Keyword =
- /*#__PURE__*/
- function (_Node) {
- _inherits(Keyword, _Node);
-
- function Keyword(value) {
- var _this;
-
- _classCallCheck(this, Keyword);
-
- _this = _possibleConstructorReturn(this, _getPrototypeOf(Keyword).call(this));
- _this.value = value;
- return _this;
- }
-
- _createClass(Keyword, [{
- key: "genCSS",
- value: function genCSS(context, output) {
- if (this.value === '%') {
- throw {
- type: 'Syntax',
- message: 'Invalid % without number'
- };
+ };
+ Combinator.prototype = Object.assign(new Node(), {
+ type: 'Combinator',
+ genCSS: function (context, output) {
+ var spaceOrEmpty = (context.compress || _noSpaceCombinators[this.value]) ? '' : ' ';
+ output.add(spaceOrEmpty + this.value + spaceOrEmpty);
}
+ });
- output.add(this.value);
- }
- }]);
-
- return Keyword;
- }(Node);
-
- Keyword.prototype.type = 'Keyword';
- Keyword.True = new Keyword('true');
- Keyword.False = new Keyword('false');
-
- var Anonymous =
- /*#__PURE__*/
- function (_Node) {
- _inherits(Anonymous, _Node);
-
- function Anonymous(value, index, currentFileInfo, mapLines, rulesetLike, visibilityInfo) {
- var _this;
-
- _classCallCheck(this, Anonymous);
-
- _this = _possibleConstructorReturn(this, _getPrototypeOf(Anonymous).call(this));
- _this.value = value;
- _this._index = index;
- _this._fileInfo = currentFileInfo;
- _this.mapLines = mapLines;
- _this.rulesetLike = typeof rulesetLike === 'undefined' ? false : rulesetLike;
- _this.allowRoot = true;
-
- _this.copyVisibilityInfo(visibilityInfo);
-
- return _this;
- }
-
- _createClass(Anonymous, [{
- key: "eval",
- value: function _eval() {
- return new Anonymous(this.value, this._index, this._fileInfo, this.mapLines, this.rulesetLike, this.visibilityInfo());
- }
- }, {
- key: "compare",
- value: function compare(other) {
- return other.toCSS && this.toCSS() === other.toCSS() ? 0 : undefined;
- }
- }, {
- key: "isRulesetLike",
- value: function isRulesetLike() {
- return this.rulesetLike;
- }
- }, {
- key: "genCSS",
- value: function genCSS(context, output) {
- this.nodeVisible = Boolean(this.value);
-
- if (this.nodeVisible) {
- output.add(this.value, this._fileInfo, this._index, this.mapLines);
+ var Element = function (combinator, value, isVariable, index, currentFileInfo, visibilityInfo) {
+ this.combinator = combinator instanceof Combinator ?
+ combinator : new Combinator(combinator);
+ if (typeof value === 'string') {
+ this.value = value.trim();
}
- }
- }]);
-
- return Anonymous;
- }(Node);
-
- Anonymous.prototype.type = 'Anonymous';
-
- var MATH = Math$1;
-
- var Declaration =
- /*#__PURE__*/
- function (_Node) {
- _inherits(Declaration, _Node);
-
- function Declaration(name, value, important, merge, index, currentFileInfo, inline, variable) {
- var _this;
-
- _classCallCheck(this, Declaration);
-
- _this = _possibleConstructorReturn(this, _getPrototypeOf(Declaration).call(this));
- _this.name = name;
- _this.value = value instanceof Node ? value : new Value([value ? new Anonymous(value) : null]);
- _this.important = important ? " ".concat(important.trim()) : '';
- _this.merge = merge;
- _this._index = index;
- _this._fileInfo = currentFileInfo;
- _this.inline = inline || false;
- _this.variable = variable !== undefined ? variable : name.charAt && name.charAt(0) === '@';
- _this.allowRoot = true;
-
- _this.setParent(_this.value, _assertThisInitialized(_this));
-
- return _this;
- }
-
- _createClass(Declaration, [{
- key: "genCSS",
- value: function genCSS(context, output) {
- output.add(this.name + (context.compress ? ':' : ': '), this.fileInfo(), this.getIndex());
-
- try {
- this.value.genCSS(context, output);
- } catch (e) {
- e.index = this._index;
- e.filename = this._fileInfo.filename;
- throw e;
+ else if (value) {
+ this.value = value;
}
-
- output.add(this.important + (this.inline || context.lastRule && context.compress ? '' : ';'), this._fileInfo, this._index);
- }
- }, {
- key: "eval",
- value: function _eval(context) {
- var mathBypass = false;
- var prevMath;
- var name = this.name;
- var evaldValue;
- var variable = this.variable;
-
- if (typeof name !== 'string') {
- // expand 'primitive' name directly to get
- // things faster (~10% for benchmark.less):
- name = name.length === 1 && name[0] instanceof Keyword ? name[0].value : evalName(context, name);
- variable = false; // never treat expanded interpolation as new variable name
- } // @todo remove when parens-division is default
-
-
- if (name === 'font' && context.math === MATH.ALWAYS) {
- mathBypass = true;
- prevMath = context.math;
- context.math = MATH.PARENS_DIVISION;
+ else {
+ this.value = '';
}
-
- try {
- context.importantScope.push({});
- evaldValue = this.value.eval(context);
-
- if (!this.variable && evaldValue.type === 'DetachedRuleset') {
- throw {
- message: 'Rulesets cannot be evaluated on a property.',
- index: this.getIndex(),
- filename: this.fileInfo().filename
- };
- }
-
- var important = this.important;
- var importantResult = context.importantScope.pop();
-
- if (!important && importantResult.important) {
- important = importantResult.important;
- }
-
- return new Declaration(name, evaldValue, important, this.merge, this.getIndex(), this.fileInfo(), this.inline, variable);
- } catch (e) {
- if (typeof e.index !== 'number') {
- e.index = this.getIndex();
- e.filename = this.fileInfo().filename;
- }
-
- throw e;
- } finally {
- if (mathBypass) {
- context.math = prevMath;
- }
+ this.isVariable = isVariable;
+ this._index = index;
+ this._fileInfo = currentFileInfo;
+ this.copyVisibilityInfo(visibilityInfo);
+ this.setParent(this.combinator, this);
+ };
+ Element.prototype = Object.assign(new Node(), {
+ type: 'Element',
+ accept: function (visitor) {
+ var value = this.value;
+ this.combinator = visitor.visit(this.combinator);
+ if (typeof value === 'object') {
+ this.value = visitor.visit(value);
+ }
+ },
+ eval: function (context) {
+ return new Element(this.combinator, this.value.eval ? this.value.eval(context) : this.value, this.isVariable, this.getIndex(), this.fileInfo(), this.visibilityInfo());
+ },
+ clone: function () {
+ return new Element(this.combinator, this.value, this.isVariable, this.getIndex(), this.fileInfo(), this.visibilityInfo());
+ },
+ genCSS: function (context, output) {
+ output.add(this.toCSS(context), this.fileInfo(), this.getIndex());
+ },
+ toCSS: function (context) {
+ context = context || {};
+ var value = this.value;
+ var firstSelector = context.firstSelector;
+ if (value instanceof Paren) {
+ // selector in parens should not be affected by outer selector
+ // flags (breaks only interpolated selectors - see #1973)
+ context.firstSelector = true;
+ }
+ value = value.toCSS ? value.toCSS(context) : value;
+ context.firstSelector = firstSelector;
+ if (value === '' && this.combinator.value.charAt(0) === '&') {
+ return '';
+ }
+ else {
+ return this.combinator.toCSS(context) + value;
+ }
}
- }
- }, {
- key: "makeImportant",
- value: function makeImportant() {
- return new Declaration(this.name, this.value, '!important', this.merge, this.getIndex(), this.fileInfo(), this.inline);
- }
- }]);
+ });
- return Declaration;
- }(Node);
-
- function evalName(context, name) {
- var value = '';
- var i;
- var n = name.length;
- var output = {
- add: function add(s) {
- value += s;
- }
+ var Math$1 = {
+ ALWAYS: 0,
+ PARENS_DIVISION: 1,
+ PARENS: 2
+ // removed - STRICT_LEGACY: 3
+ };
+ var RewriteUrls = {
+ OFF: 0,
+ LOCAL: 1,
+ ALL: 2
};
- for (i = 0; i < n; i++) {
- name[i].eval(context).genCSS(context, output);
+ /**
+ * Returns the object type of the given payload
+ *
+ * @param {*} payload
+ * @returns {string}
+ */
+ function getType(payload) {
+ return Object.prototype.toString.call(payload).slice(8, -1);
+ }
+ /**
+ * Returns whether the payload is a plain JavaScript object (excluding special classes or objects with other prototypes)
+ *
+ * @param {*} payload
+ * @returns {payload is Record}
+ */
+ function isPlainObject(payload) {
+ if (getType(payload) !== 'Object')
+ return false;
+ return payload.constructor === Object && Object.getPrototypeOf(payload) === Object.prototype;
+ }
+ /**
+ * Returns whether the payload is an array
+ *
+ * @param {any} payload
+ * @returns {payload is any[]}
+ */
+ function isArray(payload) {
+ return getType(payload) === 'Array';
}
- return value;
- }
+ /*! *****************************************************************************
+ Copyright (c) Microsoft Corporation. All rights reserved.
+ Licensed under the Apache License, Version 2.0 (the "License"); you may not use
+ this file except in compliance with the License. You may obtain a copy of the
+ License at http://www.apache.org/licenses/LICENSE-2.0
- Declaration.prototype.type = 'Declaration';
+ THIS CODE IS PROVIDED ON AN *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY IMPLIED
+ WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE,
+ MERCHANTABLITY OR NON-INFRINGEMENT.
- var debugInfo = function debugInfo(context, ctx, lineSeparator) {
- var result = '';
+ See the Apache Version 2.0 License for specific language governing permissions
+ and limitations under the License.
+ ***************************************************************************** */
- if (context.dumpLineNumbers && !context.compress) {
- switch (context.dumpLineNumbers) {
- case 'comments':
- result = debugInfo.asComment(ctx);
- break;
-
- case 'mediaquery':
- result = debugInfo.asMediaQuery(ctx);
- break;
-
- case 'all':
- result = debugInfo.asComment(ctx) + (lineSeparator || '') + debugInfo.asMediaQuery(ctx);
- break;
- }
+ function __spreadArrays() {
+ for (var s = 0, i = 0, il = arguments.length; i < il; i++) s += arguments[i].length;
+ for (var r = Array(s), k = 0, i = 0; i < il; i++)
+ for (var a = arguments[i], j = 0, jl = a.length; j < jl; j++, k++)
+ r[k] = a[j];
+ return r;
}
- return result;
- };
-
- debugInfo.asComment = function (ctx) {
- return "/* line ".concat(ctx.debugInfo.lineNumber, ", ").concat(ctx.debugInfo.fileName, " */\n");
- };
-
- debugInfo.asMediaQuery = function (ctx) {
- var filenameWithProtocol = ctx.debugInfo.fileName;
-
- if (!/^[a-z]+:\/\//i.test(filenameWithProtocol)) {
- filenameWithProtocol = "file://".concat(filenameWithProtocol);
- }
-
- return "@media -sass-debug-info{filename{font-family:".concat(filenameWithProtocol.replace(/([.:\/\\])/g, function (a) {
- if (a == '\\') {
- a = '\/';
- }
-
- return "\\".concat(a);
- }), "}line{font-family:\\00003").concat(ctx.debugInfo.lineNumber, "}}\n");
- };
-
- var Comment =
- /*#__PURE__*/
- function (_Node) {
- _inherits(Comment, _Node);
-
- function Comment(value, isLineComment, index, currentFileInfo) {
- var _this;
-
- _classCallCheck(this, Comment);
-
- _this = _possibleConstructorReturn(this, _getPrototypeOf(Comment).call(this));
- _this.value = value;
- _this.isLineComment = isLineComment;
- _this._index = index;
- _this._fileInfo = currentFileInfo;
- _this.allowRoot = true;
- return _this;
- }
-
- _createClass(Comment, [{
- key: "genCSS",
- value: function genCSS(context, output) {
- if (this.debugInfo) {
- output.add(debugInfo(context, this), this.fileInfo(), this.getIndex());
+ function assignProp(carry, key, newVal, originalObject, includeNonenumerable) {
+ var propType = {}.propertyIsEnumerable.call(originalObject, key)
+ ? 'enumerable'
+ : 'nonenumerable';
+ if (propType === 'enumerable')
+ carry[key] = newVal;
+ if (includeNonenumerable && propType === 'nonenumerable') {
+ Object.defineProperty(carry, key, {
+ value: newVal,
+ enumerable: false,
+ writable: true,
+ configurable: true,
+ });
}
-
- output.add(this.value);
- }
- }, {
- key: "isSilent",
- value: function isSilent(context) {
- var isCompressed = context.compress && this.value[2] !== '!';
- return this.isLineComment || isCompressed;
- }
- }]);
-
- return Comment;
- }(Node);
-
- Comment.prototype.type = 'Comment';
-
- var contexts = {};
-
- var copyFromOriginal = function copyFromOriginal(original, destination, propertiesToCopy) {
- if (!original) {
- return;
+ }
+ /**
+ * Copy (clone) an object and all its props recursively to get rid of any prop referenced of the original object. Arrays are also cloned, however objects inside arrays are still linked.
+ *
+ * @export
+ * @template T
+ * @param {T} target Target can be anything
+ * @param {Options} [options={}] Options can be `props` or `nonenumerable`
+ * @returns {T} the target with replaced values
+ * @export
+ */
+ function copy(target, options) {
+ if (options === void 0) { options = {}; }
+ if (isArray(target))
+ return target.map(function (i) { return copy(i, options); });
+ if (!isPlainObject(target))
+ return target;
+ var props = Object.getOwnPropertyNames(target);
+ var symbols = Object.getOwnPropertySymbols(target);
+ return __spreadArrays(props, symbols).reduce(function (carry, key) {
+ if (isArray(options.props) && !options.props.includes(key)) {
+ return carry;
+ }
+ var val = target[key];
+ var newVal = copy(val, options);
+ assignProp(carry, key, newVal, target, options.nonenumerable);
+ return carry;
+ }, {});
}
- for (var i = 0; i < propertiesToCopy.length; i++) {
- if (original.hasOwnProperty(propertiesToCopy[i])) {
- destination[propertiesToCopy[i]] = original[propertiesToCopy[i]];
- }
+ /* jshint proto: true */
+ function getLocation(index, inputStream) {
+ var n = index + 1;
+ var line = null;
+ var column = -1;
+ while (--n >= 0 && inputStream.charAt(n) !== '\n') {
+ column++;
+ }
+ if (typeof index === 'number') {
+ line = (inputStream.slice(0, index).match(/\n/g) || '').length;
+ }
+ return {
+ line: line,
+ column: column
+ };
}
- };
- /*
- parse is used whilst parsing
- */
-
-
- var parseCopyProperties = [// options
- 'paths', // option - unmodified - paths to search for imports on
- 'rewriteUrls', // option - whether to adjust URL's to be relative
- 'rootpath', // option - rootpath to append to URL's
- 'strictImports', // option -
- 'insecure', // option - whether to allow imports from insecure ssl hosts
- 'dumpLineNumbers', // option - whether to dump line numbers
- 'compress', // option - whether to compress
- 'syncImport', // option - whether to import synchronously
- 'chunkInput', // option - whether to chunk input. more performant but causes parse issues.
- 'mime', // browser only - mime type for sheet import
- 'useFileCache', // browser only - whether to use the per file session cache
- // context
- 'processImports', // option & context - whether to process imports. if false then imports will not be imported.
- // Used by the import manager to stop multiple import visitors being created.
- 'pluginManager' // Used as the plugin manager for the session
- ];
-
- contexts.Parse = function (options) {
- copyFromOriginal(options, this, parseCopyProperties);
-
- if (typeof this.paths === 'string') {
- this.paths = [this.paths];
+ function copyArray(arr) {
+ var i;
+ var length = arr.length;
+ var copy = new Array(length);
+ for (i = 0; i < length; i++) {
+ copy[i] = arr[i];
+ }
+ return copy;
}
- };
-
- var evalCopyProperties = ['paths', // additional include paths
- 'compress', // whether to compress
- 'math', // whether math has to be within parenthesis
- 'strictUnits', // whether units need to evaluate correctly
- 'sourceMap', // whether to output a source map
- 'importMultiple', // whether we are currently importing multiple copies
- 'urlArgs', // whether to add args into url tokens
- 'javascriptEnabled', // option - whether Inline JavaScript is enabled. if undefined, defaults to false
- 'pluginManager', // Used as the plugin manager for the session
- 'importantScope', // used to bubble up !important statements
- 'rewriteUrls' // option - whether to adjust URL's to be relative
- ];
-
- function isPathRelative(path) {
- return !/^(?:[a-z-]+:|\/|#)/i.test(path);
- }
-
- function isPathLocalRelative(path) {
- return path.charAt(0) === '.';
- }
-
- contexts.Eval =
- /*#__PURE__*/
- function () {
- function _class(options, frames) {
- _classCallCheck(this, _class);
-
- copyFromOriginal(options, this, evalCopyProperties);
-
- if (typeof this.paths === 'string') {
- this.paths = [this.paths];
- }
-
- this.frames = frames || [];
- this.importantScope = this.importantScope || [];
- this.inCalc = false;
- this.mathOn = true;
+ function clone(obj) {
+ var cloned = {};
+ for (var prop in obj) {
+ if (obj.hasOwnProperty(prop)) {
+ cloned[prop] = obj[prop];
+ }
+ }
+ return cloned;
+ }
+ function defaults(obj1, obj2) {
+ var newObj = obj2 || {};
+ if (!obj2._defaults) {
+ newObj = {};
+ var defaults_1 = copy(obj1);
+ newObj._defaults = defaults_1;
+ var cloned = obj2 ? copy(obj2) : {};
+ Object.assign(newObj, defaults_1, cloned);
+ }
+ return newObj;
+ }
+ function copyOptions(obj1, obj2) {
+ if (obj2 && obj2._defaults) {
+ return obj2;
+ }
+ var opts = defaults(obj1, obj2);
+ if (opts.strictMath) {
+ opts.math = Math$1.PARENS;
+ }
+ // Back compat with changed relativeUrls option
+ if (opts.relativeUrls) {
+ opts.rewriteUrls = RewriteUrls.ALL;
+ }
+ if (typeof opts.math === 'string') {
+ switch (opts.math.toLowerCase()) {
+ case 'always':
+ opts.math = Math$1.ALWAYS;
+ break;
+ case 'parens-division':
+ opts.math = Math$1.PARENS_DIVISION;
+ break;
+ case 'strict':
+ case 'parens':
+ opts.math = Math$1.PARENS;
+ break;
+ default:
+ opts.math = Math$1.PARENS;
+ }
+ }
+ if (typeof opts.rewriteUrls === 'string') {
+ switch (opts.rewriteUrls.toLowerCase()) {
+ case 'off':
+ opts.rewriteUrls = RewriteUrls.OFF;
+ break;
+ case 'local':
+ opts.rewriteUrls = RewriteUrls.LOCAL;
+ break;
+ case 'all':
+ opts.rewriteUrls = RewriteUrls.ALL;
+ break;
+ }
+ }
+ return opts;
+ }
+ function merge(obj1, obj2) {
+ for (var prop in obj2) {
+ if (obj2.hasOwnProperty(prop)) {
+ obj1[prop] = obj2[prop];
+ }
+ }
+ return obj1;
+ }
+ function flattenArray(arr, result) {
+ if (result === void 0) { result = []; }
+ for (var i = 0, length_1 = arr.length; i < length_1; i++) {
+ var value = arr[i];
+ if (Array.isArray(value)) {
+ flattenArray(value, result);
+ }
+ else {
+ if (value !== undefined) {
+ result.push(value);
+ }
+ }
+ }
+ return result;
}
- _createClass(_class, [{
- key: "enterCalc",
- value: function enterCalc() {
+ var utils = /*#__PURE__*/Object.freeze({
+ __proto__: null,
+ getLocation: getLocation,
+ copyArray: copyArray,
+ clone: clone,
+ defaults: defaults,
+ copyOptions: copyOptions,
+ merge: merge,
+ flattenArray: flattenArray
+ });
+
+ var anonymousFunc = /(|Function):(\d+):(\d+)/;
+ /**
+ * This is a centralized class of any error that could be thrown internally (mostly by the parser).
+ * Besides standard .message it keeps some additional data like a path to the file where the error
+ * occurred along with line and column numbers.
+ *
+ * @class
+ * @extends Error
+ * @type {module.LessError}
+ *
+ * @prop {string} type
+ * @prop {string} filename
+ * @prop {number} index
+ * @prop {number} line
+ * @prop {number} column
+ * @prop {number} callLine
+ * @prop {number} callExtract
+ * @prop {string[]} extract
+ *
+ * @param {Object} e - An error object to wrap around or just a descriptive object
+ * @param {Object} fileContentMap - An object with file contents in 'contents' property (like importManager) @todo - move to fileManager?
+ * @param {string} [currentFilename]
+ */
+ var LessError = function (e, fileContentMap, currentFilename) {
+ Error.call(this);
+ var filename = e.filename || currentFilename;
+ this.message = e.message;
+ this.stack = e.stack;
+ if (fileContentMap && filename) {
+ var input = fileContentMap.contents[filename];
+ var loc = getLocation(e.index, input);
+ var line = loc.line;
+ var col = loc.column;
+ var callLine = e.call && getLocation(e.call, input).line;
+ var lines = input ? input.split('\n') : '';
+ this.type = e.type || 'Syntax';
+ this.filename = filename;
+ this.index = e.index;
+ this.line = typeof line === 'number' ? line + 1 : null;
+ this.column = col;
+ if (!this.line && this.stack) {
+ var found = this.stack.match(anonymousFunc);
+ /**
+ * We have to figure out how this environment stringifies anonymous functions
+ * so we can correctly map plugin errors.
+ *
+ * Note, in Node 8, the output of anonymous funcs varied based on parameters
+ * being present or not, so we inject dummy params.
+ */
+ var func = new Function('a', 'throw new Error()');
+ var lineAdjust = 0;
+ try {
+ func();
+ }
+ catch (e) {
+ var match = e.stack.match(anonymousFunc);
+ var line = parseInt(match[2]);
+ lineAdjust = 1 - line;
+ }
+ if (found) {
+ if (found[2]) {
+ this.line = parseInt(found[2]) + lineAdjust;
+ }
+ if (found[3]) {
+ this.column = parseInt(found[3]);
+ }
+ }
+ }
+ this.callLine = callLine + 1;
+ this.callExtract = lines[callLine];
+ this.extract = [
+ lines[this.line - 2],
+ lines[this.line - 1],
+ lines[this.line]
+ ];
+ }
+ };
+ if (typeof Object.create === 'undefined') {
+ var F = function () { };
+ F.prototype = Error.prototype;
+ LessError.prototype = new F();
+ }
+ else {
+ LessError.prototype = Object.create(Error.prototype);
+ }
+ LessError.prototype.constructor = LessError;
+ /**
+ * An overridden version of the default Object.prototype.toString
+ * which uses additional information to create a helpful message.
+ *
+ * @param {Object} options
+ * @returns {string}
+ */
+ LessError.prototype.toString = function (options) {
+ options = options || {};
+ var message = '';
+ var extract = this.extract || [];
+ var error = [];
+ var stylize = function (str) { return str; };
+ if (options.stylize) {
+ var type = typeof options.stylize;
+ if (type !== 'function') {
+ throw Error("options.stylize should be a function, got a " + type + "!");
+ }
+ stylize = options.stylize;
+ }
+ if (this.line !== null) {
+ if (typeof extract[0] === 'string') {
+ error.push(stylize(this.line - 1 + " " + extract[0], 'grey'));
+ }
+ if (typeof extract[1] === 'string') {
+ var errorTxt = this.line + " ";
+ if (extract[1]) {
+ errorTxt += extract[1].slice(0, this.column) +
+ stylize(stylize(stylize(extract[1].substr(this.column, 1), 'bold') +
+ extract[1].slice(this.column + 1), 'red'), 'inverse');
+ }
+ error.push(errorTxt);
+ }
+ if (typeof extract[2] === 'string') {
+ error.push(stylize(this.line + 1 + " " + extract[2], 'grey'));
+ }
+ error = error.join('\n') + stylize('', 'reset') + "\n";
+ }
+ message += stylize(this.type + "Error: " + this.message, 'red');
+ if (this.filename) {
+ message += stylize(' in ', 'red') + this.filename;
+ }
+ if (this.line) {
+ message += stylize(" on line " + this.line + ", column " + (this.column + 1) + ":", 'grey');
+ }
+ message += "\n" + error;
+ if (this.callLine) {
+ message += stylize('from ', 'red') + (this.filename || '') + "/n";
+ message += stylize(this.callLine, 'grey') + " " + this.callExtract + "/n";
+ }
+ return message;
+ };
+
+ var Selector = function (elements, extendList, condition, index, currentFileInfo, visibilityInfo) {
+ this.extendList = extendList;
+ this.condition = condition;
+ this.evaldCondition = !condition;
+ this._index = index;
+ this._fileInfo = currentFileInfo;
+ this.elements = this.getElements(elements);
+ this.mixinElements_ = undefined;
+ this.copyVisibilityInfo(visibilityInfo);
+ this.setParent(this.elements, this);
+ };
+ Selector.prototype = Object.assign(new Node(), {
+ type: 'Selector',
+ accept: function (visitor) {
+ if (this.elements) {
+ this.elements = visitor.visitArray(this.elements);
+ }
+ if (this.extendList) {
+ this.extendList = visitor.visitArray(this.extendList);
+ }
+ if (this.condition) {
+ this.condition = visitor.visit(this.condition);
+ }
+ },
+ createDerived: function (elements, extendList, evaldCondition) {
+ elements = this.getElements(elements);
+ var newSelector = new Selector(elements, extendList || this.extendList, null, this.getIndex(), this.fileInfo(), this.visibilityInfo());
+ newSelector.evaldCondition = (evaldCondition != null) ? evaldCondition : this.evaldCondition;
+ newSelector.mediaEmpty = this.mediaEmpty;
+ return newSelector;
+ },
+ getElements: function (els) {
+ if (!els) {
+ return [new Element('', '&', false, this._index, this._fileInfo)];
+ }
+ if (typeof els === 'string') {
+ this.parse.parseNode(els, ['selector'], this._index, this._fileInfo, function (err, result) {
+ if (err) {
+ throw new LessError({
+ index: err.index,
+ message: err.message
+ }, this.parse.imports, this._fileInfo.filename);
+ }
+ els = result[0].elements;
+ });
+ }
+ return els;
+ },
+ createEmptySelectors: function () {
+ var el = new Element('', '&', false, this._index, this._fileInfo), sels = [new Selector([el], null, null, this._index, this._fileInfo)];
+ sels[0].mediaEmpty = true;
+ return sels;
+ },
+ match: function (other) {
+ var elements = this.elements;
+ var len = elements.length;
+ var olen;
+ var i;
+ other = other.mixinElements();
+ olen = other.length;
+ if (olen === 0 || len < olen) {
+ return 0;
+ }
+ else {
+ for (i = 0; i < olen; i++) {
+ if (elements[i].value !== other[i]) {
+ return 0;
+ }
+ }
+ }
+ return olen; // return number of matched elements
+ },
+ mixinElements: function () {
+ if (this.mixinElements_) {
+ return this.mixinElements_;
+ }
+ var elements = this.elements.map(function (v) {
+ return v.combinator.value + (v.value.value || v.value);
+ }).join('').match(/[,\*\.\w-]([\w-]|(\\.))*/g);
+ if (elements) {
+ if (elements[0] === '&') {
+ elements.shift();
+ }
+ }
+ else {
+ elements = [];
+ }
+ return (this.mixinElements_ = elements);
+ },
+ isJustParentSelector: function () {
+ return !this.mediaEmpty &&
+ this.elements.length === 1 &&
+ this.elements[0].value === '&' &&
+ (this.elements[0].combinator.value === ' ' || this.elements[0].combinator.value === '');
+ },
+ eval: function (context) {
+ var evaldCondition = this.condition && this.condition.eval(context);
+ var elements = this.elements;
+ var extendList = this.extendList;
+ elements = elements && elements.map(function (e) { return e.eval(context); });
+ extendList = extendList && extendList.map(function (extend) { return extend.eval(context); });
+ return this.createDerived(elements, extendList, evaldCondition);
+ },
+ genCSS: function (context, output) {
+ var i, element;
+ if ((!context || !context.firstSelector) && this.elements[0].combinator.value === '') {
+ output.add(' ', this.fileInfo(), this.getIndex());
+ }
+ for (i = 0; i < this.elements.length; i++) {
+ element = this.elements[i];
+ element.genCSS(context, output);
+ }
+ },
+ getIsOutput: function () {
+ return this.evaldCondition;
+ }
+ });
+
+ var Value = function (value) {
+ if (!value) {
+ throw new Error('Value requires an array argument');
+ }
+ if (!Array.isArray(value)) {
+ this.value = [value];
+ }
+ else {
+ this.value = value;
+ }
+ };
+ Value.prototype = Object.assign(new Node(), {
+ type: 'Value',
+ accept: function (visitor) {
+ if (this.value) {
+ this.value = visitor.visitArray(this.value);
+ }
+ },
+ eval: function (context) {
+ if (this.value.length === 1) {
+ return this.value[0].eval(context);
+ }
+ else {
+ return new Value(this.value.map(function (v) {
+ return v.eval(context);
+ }));
+ }
+ },
+ genCSS: function (context, output) {
+ var i;
+ for (i = 0; i < this.value.length; i++) {
+ this.value[i].genCSS(context, output);
+ if (i + 1 < this.value.length) {
+ output.add((context && context.compress) ? ',' : ', ');
+ }
+ }
+ }
+ });
+
+ var Keyword = function (value) {
+ this.value = value;
+ };
+ Keyword.prototype = Object.assign(new Node(), {
+ type: 'Keyword',
+ genCSS: function (context, output) {
+ if (this.value === '%') {
+ throw { type: 'Syntax', message: 'Invalid % without number' };
+ }
+ output.add(this.value);
+ }
+ });
+ Keyword.True = new Keyword('true');
+ Keyword.False = new Keyword('false');
+
+ var Anonymous = function (value, index, currentFileInfo, mapLines, rulesetLike, visibilityInfo) {
+ this.value = value;
+ this._index = index;
+ this._fileInfo = currentFileInfo;
+ this.mapLines = mapLines;
+ this.rulesetLike = (typeof rulesetLike === 'undefined') ? false : rulesetLike;
+ this.allowRoot = true;
+ this.copyVisibilityInfo(visibilityInfo);
+ };
+ Anonymous.prototype = Object.assign(new Node(), {
+ type: 'Anonymous',
+ eval: function () {
+ return new Anonymous(this.value, this._index, this._fileInfo, this.mapLines, this.rulesetLike, this.visibilityInfo());
+ },
+ compare: function (other) {
+ return other.toCSS && this.toCSS() === other.toCSS() ? 0 : undefined;
+ },
+ isRulesetLike: function () {
+ return this.rulesetLike;
+ },
+ genCSS: function (context, output) {
+ this.nodeVisible = Boolean(this.value);
+ if (this.nodeVisible) {
+ output.add(this.value, this._fileInfo, this._index, this.mapLines);
+ }
+ }
+ });
+
+ var MATH$1 = Math$1;
+ function evalName(context, name) {
+ var value = '';
+ var i;
+ var n = name.length;
+ var output = { add: function (s) { value += s; } };
+ for (i = 0; i < n; i++) {
+ name[i].eval(context).genCSS(context, output);
+ }
+ return value;
+ }
+ var Declaration = function (name, value, important, merge, index, currentFileInfo, inline, variable) {
+ this.name = name;
+ this.value = (value instanceof Node) ? value : new Value([value ? new Anonymous(value) : null]);
+ this.important = important ? " " + important.trim() : '';
+ this.merge = merge;
+ this._index = index;
+ this._fileInfo = currentFileInfo;
+ this.inline = inline || false;
+ this.variable = (variable !== undefined) ? variable
+ : (name.charAt && (name.charAt(0) === '@'));
+ this.allowRoot = true;
+ this.setParent(this.value, this);
+ };
+ Declaration.prototype = Object.assign(new Node(), {
+ type: 'Declaration',
+ genCSS: function (context, output) {
+ output.add(this.name + (context.compress ? ':' : ': '), this.fileInfo(), this.getIndex());
+ try {
+ this.value.genCSS(context, output);
+ }
+ catch (e) {
+ e.index = this._index;
+ e.filename = this._fileInfo.filename;
+ throw e;
+ }
+ output.add(this.important + ((this.inline || (context.lastRule && context.compress)) ? '' : ';'), this._fileInfo, this._index);
+ },
+ eval: function (context) {
+ var mathBypass = false, prevMath, name = this.name, evaldValue, variable = this.variable;
+ if (typeof name !== 'string') {
+ // expand 'primitive' name directly to get
+ // things faster (~10% for benchmark.less):
+ name = (name.length === 1) && (name[0] instanceof Keyword) ?
+ name[0].value : evalName(context, name);
+ variable = false; // never treat expanded interpolation as new variable name
+ }
+ // @todo remove when parens-division is default
+ if (name === 'font' && context.math === MATH$1.ALWAYS) {
+ mathBypass = true;
+ prevMath = context.math;
+ context.math = MATH$1.PARENS_DIVISION;
+ }
+ try {
+ context.importantScope.push({});
+ evaldValue = this.value.eval(context);
+ if (!this.variable && evaldValue.type === 'DetachedRuleset') {
+ throw { message: 'Rulesets cannot be evaluated on a property.',
+ index: this.getIndex(), filename: this.fileInfo().filename };
+ }
+ var important = this.important;
+ var importantResult = context.importantScope.pop();
+ if (!important && importantResult.important) {
+ important = importantResult.important;
+ }
+ return new Declaration(name, evaldValue, important, this.merge, this.getIndex(), this.fileInfo(), this.inline, variable);
+ }
+ catch (e) {
+ if (typeof e.index !== 'number') {
+ e.index = this.getIndex();
+ e.filename = this.fileInfo().filename;
+ }
+ throw e;
+ }
+ finally {
+ if (mathBypass) {
+ context.math = prevMath;
+ }
+ }
+ },
+ makeImportant: function () {
+ return new Declaration(this.name, this.value, '!important', this.merge, this.getIndex(), this.fileInfo(), this.inline);
+ }
+ });
+
+ var debugInfo = /** @class */ (function () {
+ function debugInfo(context, ctx, lineSeparator) {
+ var result = '';
+ if (context.dumpLineNumbers && !context.compress) {
+ switch (context.dumpLineNumbers) {
+ case 'comments':
+ result = debugInfo.asComment(ctx);
+ break;
+ case 'mediaquery':
+ result = debugInfo.asMediaQuery(ctx);
+ break;
+ case 'all':
+ result = debugInfo.asComment(ctx) + (lineSeparator || '') + debugInfo.asMediaQuery(ctx);
+ break;
+ }
+ }
+ return result;
+ }
+ debugInfo.asComment = function (ctx) {
+ return "/* line " + ctx.debugInfo.lineNumber + ", " + ctx.debugInfo.fileName + " */\n";
+ };
+ debugInfo.asMediaQuery = function (ctx) {
+ var filenameWithProtocol = ctx.debugInfo.fileName;
+ if (!/^[a-z]+:\/\//i.test(filenameWithProtocol)) {
+ filenameWithProtocol = "file://" + filenameWithProtocol;
+ }
+ return "@media -sass-debug-info{filename{font-family:" + filenameWithProtocol.replace(/([.:\/\\])/g, function (a) {
+ if (a == '\\') {
+ a = '\/';
+ }
+ return "\\" + a;
+ }) + "}line{font-family:\\00003" + ctx.debugInfo.lineNumber + "}}\n";
+ };
+ return debugInfo;
+ }());
+
+ var Comment = function (value, isLineComment, index, currentFileInfo) {
+ this.value = value;
+ this.isLineComment = isLineComment;
+ this._index = index;
+ this._fileInfo = currentFileInfo;
+ this.allowRoot = true;
+ };
+ Comment.prototype = Object.assign(new Node(), {
+ type: 'Comment',
+ genCSS: function (context, output) {
+ if (this.debugInfo) {
+ output.add(debugInfo(context, this), this.fileInfo(), this.getIndex());
+ }
+ output.add(this.value);
+ },
+ isSilent: function (context) {
+ var isCompressed = context.compress && this.value[2] !== '!';
+ return this.isLineComment || isCompressed;
+ }
+ });
+
+ var contexts = {};
+ var copyFromOriginal = function copyFromOriginal(original, destination, propertiesToCopy) {
+ if (!original) {
+ return;
+ }
+ for (var i = 0; i < propertiesToCopy.length; i++) {
+ if (original.hasOwnProperty(propertiesToCopy[i])) {
+ destination[propertiesToCopy[i]] = original[propertiesToCopy[i]];
+ }
+ }
+ };
+ /*
+ parse is used whilst parsing
+ */
+ var parseCopyProperties = [
+ // options
+ 'paths',
+ 'rewriteUrls',
+ 'rootpath',
+ 'strictImports',
+ 'insecure',
+ 'dumpLineNumbers',
+ 'compress',
+ 'syncImport',
+ 'chunkInput',
+ 'mime',
+ 'useFileCache',
+ // context
+ 'processImports',
+ // Used by the import manager to stop multiple import visitors being created.
+ 'pluginManager' // Used as the plugin manager for the session
+ ];
+ contexts.Parse = function (options) {
+ copyFromOriginal(options, this, parseCopyProperties);
+ if (typeof this.paths === 'string') {
+ this.paths = [this.paths];
+ }
+ };
+ var evalCopyProperties = [
+ 'paths',
+ 'compress',
+ 'math',
+ 'strictUnits',
+ 'sourceMap',
+ 'importMultiple',
+ 'urlArgs',
+ 'javascriptEnabled',
+ 'pluginManager',
+ 'importantScope',
+ 'rewriteUrls' // option - whether to adjust URL's to be relative
+ ];
+ contexts.Eval = function (options, frames) {
+ copyFromOriginal(options, this, evalCopyProperties);
+ if (typeof this.paths === 'string') {
+ this.paths = [this.paths];
+ }
+ this.frames = frames || [];
+ this.importantScope = this.importantScope || [];
+ };
+ contexts.Eval.prototype.enterCalc = function () {
if (!this.calcStack) {
- this.calcStack = [];
+ this.calcStack = [];
}
-
this.calcStack.push(true);
this.inCalc = true;
- }
- }, {
- key: "exitCalc",
- value: function exitCalc() {
+ };
+ contexts.Eval.prototype.exitCalc = function () {
this.calcStack.pop();
-
- if (!this.calcStack) {
- this.inCalc = false;
+ if (!this.calcStack.length) {
+ this.inCalc = false;
}
- }
- }, {
- key: "inParenthesis",
- value: function inParenthesis() {
+ };
+ contexts.Eval.prototype.inParenthesis = function () {
if (!this.parensStack) {
- this.parensStack = [];
+ this.parensStack = [];
}
-
this.parensStack.push(true);
- }
- }, {
- key: "outOfParenthesis",
- value: function outOfParenthesis() {
+ };
+ contexts.Eval.prototype.outOfParenthesis = function () {
this.parensStack.pop();
- }
- }, {
- key: "isMathOn",
- value: function isMathOn(op) {
+ };
+ contexts.Eval.prototype.inCalc = false;
+ contexts.Eval.prototype.mathOn = true;
+ contexts.Eval.prototype.isMathOn = function (op) {
if (!this.mathOn) {
- return false;
+ return false;
}
-
if (op === '/' && this.math !== Math$1.ALWAYS && (!this.parensStack || !this.parensStack.length)) {
- return false;
+ return false;
}
-
if (this.math > Math$1.PARENS_DIVISION) {
- return this.parensStack && this.parensStack.length;
+ return this.parensStack && this.parensStack.length;
}
-
return true;
- }
- }, {
- key: "pathRequiresRewrite",
- value: function pathRequiresRewrite(path) {
+ };
+ contexts.Eval.prototype.pathRequiresRewrite = function (path) {
var isRelative = this.rewriteUrls === RewriteUrls.LOCAL ? isPathLocalRelative : isPathRelative;
return isRelative(path);
- }
- }, {
- key: "rewritePath",
- value: function rewritePath(path, rootpath) {
+ };
+ contexts.Eval.prototype.rewritePath = function (path, rootpath) {
var newPath;
rootpath = rootpath || '';
- newPath = this.normalizePath(rootpath + path); // If a path was explicit relative and the rootpath was not an absolute path
+ newPath = this.normalizePath(rootpath + path);
+ // If a path was explicit relative and the rootpath was not an absolute path
// we must ensure that the new path is also explicit relative.
-
- if (isPathLocalRelative(path) && isPathRelative(rootpath) && isPathLocalRelative(newPath) === false) {
- newPath = "./".concat(newPath);
+ if (isPathLocalRelative(path) &&
+ isPathRelative(rootpath) &&
+ isPathLocalRelative(newPath) === false) {
+ newPath = "./" + newPath;
}
-
return newPath;
- }
- }, {
- key: "normalizePath",
- value: function normalizePath(path) {
+ };
+ contexts.Eval.prototype.normalizePath = function (path) {
var segments = path.split('/').reverse();
var segment;
path = [];
-
while (segments.length !== 0) {
- segment = segments.pop();
-
- switch (segment) {
- case '.':
- break;
-
- case '..':
- if (path.length === 0 || path[path.length - 1] === '..') {
- path.push(segment);
- } else {
- path.pop();
- }
-
- break;
-
- default:
- path.push(segment);
- break;
- }
+ segment = segments.pop();
+ switch (segment) {
+ case '.':
+ break;
+ case '..':
+ if ((path.length === 0) || (path[path.length - 1] === '..')) {
+ path.push(segment);
+ }
+ else {
+ path.pop();
+ }
+ break;
+ default:
+ path.push(segment);
+ break;
+ }
}
-
return path.join('/');
- }
- }]);
-
- return _class;
- }();
-
- function makeRegistry(base) {
- return {
- _data: {},
- add: function add(name, func) {
- // precautionary case conversion, as later querying of
- // the registry by function-caller uses lower case as well.
- name = name.toLowerCase();
-
- if (this._data.hasOwnProperty(name)) ;
-
- this._data[name] = func;
- },
- addMultiple: function addMultiple(functions) {
- var _this = this;
-
- Object.keys(functions).forEach(function (name) {
- _this.add(name, functions[name]);
- });
- },
- get: function get(name) {
- return this._data[name] || base && base.get(name);
- },
- getLocalFunctions: function getLocalFunctions() {
- return this._data;
- },
- inherit: function inherit() {
- return makeRegistry(this);
- },
- create: function create(base) {
- return makeRegistry(base);
- }
};
- }
-
- var functionRegistry = makeRegistry(null);
-
- var defaultFunc = {
- eval: function _eval() {
- var v = this.value_;
- var e = this.error_;
-
- if (e) {
- throw e;
- }
-
- if (v != null) {
- return v ? Keyword.True : Keyword.False;
- }
- },
- value: function value(v) {
- this.value_ = v;
- },
- error: function error(e) {
- this.error_ = e;
- },
- reset: function reset() {
- this.value_ = this.error_ = null;
+ function isPathRelative(path) {
+ return !/^(?:[a-z-]+:|\/|#)/i.test(path);
}
- };
-
- var Ruleset =
- /*#__PURE__*/
- function (_Node) {
- _inherits(Ruleset, _Node);
-
- function Ruleset(selectors, rules, strictImports, visibilityInfo) {
- var _this;
-
- _classCallCheck(this, Ruleset);
-
- _this = _possibleConstructorReturn(this, _getPrototypeOf(Ruleset).call(this));
- _this.selectors = selectors;
- _this.rules = rules;
- _this._lookups = {};
- _this._variables = null;
- _this._properties = null;
- _this.strictImports = strictImports;
-
- _this.copyVisibilityInfo(visibilityInfo);
-
- _this.allowRoot = true;
-
- _this.setParent(_this.selectors, _assertThisInitialized(_this));
-
- _this.setParent(_this.rules, _assertThisInitialized(_this));
-
- return _this;
+ function isPathLocalRelative(path) {
+ return path.charAt(0) === '.';
}
+ // todo - do the same for the toCSS ?
- _createClass(Ruleset, [{
- key: "isRulesetLike",
- value: function isRulesetLike() {
- return true;
- }
- }, {
- key: "accept",
- value: function accept(visitor) {
- if (this.paths) {
- this.paths = visitor.visitArray(this.paths, true);
- } else if (this.selectors) {
- this.selectors = visitor.visitArray(this.selectors);
- }
-
- if (this.rules && this.rules.length) {
- this.rules = visitor.visitArray(this.rules);
- }
- }
- }, {
- key: "eval",
- value: function _eval(context) {
- var selectors;
- var selCnt;
- var selector;
- var i;
- var hasVariable;
- var hasOnePassingSelector = false;
-
- if (this.selectors && (selCnt = this.selectors.length)) {
- selectors = new Array(selCnt);
- defaultFunc.error({
- type: 'Syntax',
- message: 'it is currently only allowed in parametric mixin guards,'
- });
-
- for (i = 0; i < selCnt; i++) {
- selector = this.selectors[i].eval(context);
-
- for (var j = 0; j < selector.elements.length; j++) {
- if (selector.elements[j].isVariable) {
- hasVariable = true;
- break;
- }
+ function makeRegistry(base) {
+ return {
+ _data: {},
+ add: function (name, func) {
+ // precautionary case conversion, as later querying of
+ // the registry by function-caller uses lower case as well.
+ name = name.toLowerCase();
+ if (this._data.hasOwnProperty(name)) ;
+ this._data[name] = func;
+ },
+ addMultiple: function (functions) {
+ var _this = this;
+ Object.keys(functions).forEach(function (name) {
+ _this.add(name, functions[name]);
+ });
+ },
+ get: function (name) {
+ return this._data[name] || (base && base.get(name));
+ },
+ getLocalFunctions: function () {
+ return this._data;
+ },
+ inherit: function () {
+ return makeRegistry(this);
+ },
+ create: function (base) {
+ return makeRegistry(base);
}
+ };
+ }
+ var functionRegistry = makeRegistry(null);
- selectors[i] = selector;
-
- if (selector.evaldCondition) {
- hasOnePassingSelector = true;
+ var defaultFunc = {
+ eval: function () {
+ var v = this.value_;
+ var e = this.error_;
+ if (e) {
+ throw e;
}
- }
-
- if (hasVariable) {
- var toParseSelectors = new Array(selCnt);
-
- for (i = 0; i < selCnt; i++) {
- selector = selectors[i];
- toParseSelectors[i] = selector.toCSS(context);
+ if (v != null) {
+ return v ? Keyword.True : Keyword.False;
}
-
- this.parse.parseNode(toParseSelectors.join(','), ["selectors"], selectors[0].getIndex(), selectors[0].fileInfo(), function (err, result) {
- if (result) {
- selectors = flattenArray(result);
- }
- });
- }
-
- defaultFunc.reset();
- } else {
- hasOnePassingSelector = true;
+ },
+ value: function (v) {
+ this.value_ = v;
+ },
+ error: function (e) {
+ this.error_ = e;
+ },
+ reset: function () {
+ this.value_ = this.error_ = null;
}
+ };
- var rules = this.rules ? copyArray(this.rules) : null;
- var ruleset = new Ruleset(selectors, rules, this.strictImports, this.visibilityInfo());
- var rule;
- var subRule;
- ruleset.originalRuleset = this;
- ruleset.root = this.root;
- ruleset.firstRoot = this.firstRoot;
- ruleset.allowImports = this.allowImports;
-
- if (this.debugInfo) {
- ruleset.debugInfo = this.debugInfo;
- }
-
- if (!hasOnePassingSelector) {
- rules.length = 0;
- } // inherit a function registry from the frames stack when possible;
- // otherwise from the global registry
-
-
- ruleset.functionRegistry = function (frames) {
- var i = 0;
- var n = frames.length;
- var found;
-
- for (; i !== n; ++i) {
- found = frames[i].functionRegistry;
-
- if (found) {
- return found;
- }
- }
-
- return functionRegistry;
- }(context.frames).inherit(); // push the current ruleset to the frames stack
-
-
- var ctxFrames = context.frames;
- ctxFrames.unshift(ruleset); // currrent selectors
-
- var ctxSelectors = context.selectors;
-
- if (!ctxSelectors) {
- context.selectors = ctxSelectors = [];
- }
-
- ctxSelectors.unshift(this.selectors); // Evaluate imports
-
- if (ruleset.root || ruleset.allowImports || !ruleset.strictImports) {
- ruleset.evalImports(context);
- } // Store the frames around mixin definitions,
- // so they can be evaluated like closures when the time comes.
-
-
- var rsRules = ruleset.rules;
-
- for (i = 0; rule = rsRules[i]; i++) {
- if (rule.evalFirst) {
- rsRules[i] = rule.eval(context);
- }
- }
-
- var mediaBlockCount = context.mediaBlocks && context.mediaBlocks.length || 0; // Evaluate mixin calls.
-
- for (i = 0; rule = rsRules[i]; i++) {
- if (rule.type === 'MixinCall') {
- /* jshint loopfunc:true */
- rules = rule.eval(context).filter(function (r) {
- if (r instanceof Declaration && r.variable) {
- // do not pollute the scope if the variable is
- // already there. consider returning false here
- // but we need a way to "return" variable from mixins
- return !ruleset.variable(r.name);
- }
-
- return true;
- });
- rsRules.splice.apply(rsRules, _toConsumableArray([i, 1].concat(rules)));
- i += rules.length - 1;
- ruleset.resetCache();
- } else if (rule.type === 'VariableCall') {
- /* jshint loopfunc:true */
- rules = rule.eval(context).rules.filter(function (r) {
- if (r instanceof Declaration && r.variable) {
- // do not pollute the scope at all
- return false;
- }
-
- return true;
- });
- rsRules.splice.apply(rsRules, _toConsumableArray([i, 1].concat(rules)));
- i += rules.length - 1;
- ruleset.resetCache();
- }
- } // Evaluate everything else
-
-
- for (i = 0; rule = rsRules[i]; i++) {
- if (!rule.evalFirst) {
- rsRules[i] = rule = rule.eval ? rule.eval(context) : rule;
- }
- } // Evaluate everything else
-
-
- for (i = 0; rule = rsRules[i]; i++) {
- // for rulesets, check if it is a css guard and can be removed
- if (rule instanceof Ruleset && rule.selectors && rule.selectors.length === 1) {
- // check if it can be folded in (e.g. & where)
- if (rule.selectors[0] && rule.selectors[0].isJustParentSelector()) {
- rsRules.splice(i--, 1);
-
- for (var j = 0; subRule = rule.rules[j]; j++) {
- if (subRule instanceof Node) {
- subRule.copyVisibilityInfo(rule.visibilityInfo());
-
- if (!(subRule instanceof Declaration) || !subRule.variable) {
- rsRules.splice(++i, 0, subRule);
- }
- }
- }
- }
- }
- } // Pop the stack
-
-
- ctxFrames.shift();
- ctxSelectors.shift();
-
- if (context.mediaBlocks) {
- for (i = mediaBlockCount; i < context.mediaBlocks.length; i++) {
- context.mediaBlocks[i].bubbleSelectors(selectors);
- }
- }
-
- return ruleset;
- }
- }, {
- key: "evalImports",
- value: function evalImports(context) {
- var rules = this.rules;
- var i;
- var importRules;
-
- if (!rules) {
- return;
- }
-
- for (i = 0; i < rules.length; i++) {
- if (rules[i].type === 'Import') {
- importRules = rules[i].eval(context);
-
- if (importRules && (importRules.length || importRules.length === 0)) {
- rules.splice.apply(rules, _toConsumableArray([i, 1].concat(importRules)));
- i += importRules.length - 1;
- } else {
- rules.splice(i, 1, importRules);
- }
-
- this.resetCache();
- }
- }
- }
- }, {
- key: "makeImportant",
- value: function makeImportant() {
- var result = new Ruleset(this.selectors, this.rules.map(function (r) {
- if (r.makeImportant) {
- return r.makeImportant();
- } else {
- return r;
- }
- }), this.strictImports, this.visibilityInfo());
- return result;
- }
- }, {
- key: "matchArgs",
- value: function matchArgs(args) {
- return !args || args.length === 0;
- } // lets you call a css selector with a guard
-
- }, {
- key: "matchCondition",
- value: function matchCondition(args, context) {
- var lastSelector = this.selectors[this.selectors.length - 1];
-
- if (!lastSelector.evaldCondition) {
- return false;
- }
-
- if (lastSelector.condition && !lastSelector.condition.eval(new contexts.Eval(context, context.frames))) {
- return false;
- }
-
- return true;
- }
- }, {
- key: "resetCache",
- value: function resetCache() {
- this._rulesets = null;
+ var Ruleset = function (selectors, rules, strictImports, visibilityInfo) {
+ this.selectors = selectors;
+ this.rules = rules;
+ this._lookups = {};
this._variables = null;
this._properties = null;
- this._lookups = {};
- }
- }, {
- key: "variables",
- value: function variables() {
- if (!this._variables) {
- this._variables = !this.rules ? {} : this.rules.reduce(function (hash, r) {
- if (r instanceof Declaration && r.variable === true) {
- hash[r.name] = r;
- } // when evaluating variables in an import statement, imports have not been eval'd
- // so we need to go inside import statements.
- // guard against root being a string (in the case of inlined less)
-
-
- if (r.type === 'Import' && r.root && r.root.variables) {
- var vars = r.root.variables();
-
- for (var name in vars) {
- if (vars.hasOwnProperty(name)) {
- hash[name] = r.root.variable(name);
- }
- }
- }
-
- return hash;
- }, {});
- }
-
- return this._variables;
- }
- }, {
- key: "properties",
- value: function properties() {
- if (!this._properties) {
- this._properties = !this.rules ? {} : this.rules.reduce(function (hash, r) {
- if (r instanceof Declaration && r.variable !== true) {
- var name = r.name.length === 1 && r.name[0] instanceof Keyword ? r.name[0].value : r.name; // Properties don't overwrite as they can merge
-
- if (!hash["$".concat(name)]) {
- hash["$".concat(name)] = [r];
- } else {
- hash["$".concat(name)].push(r);
- }
- }
-
- return hash;
- }, {});
- }
-
- return this._properties;
- }
- }, {
- key: "variable",
- value: function variable(name) {
- var decl = this.variables()[name];
-
- if (decl) {
- return this.parseValue(decl);
- }
- }
- }, {
- key: "property",
- value: function property(name) {
- var decl = this.properties()[name];
-
- if (decl) {
- return this.parseValue(decl);
- }
- }
- }, {
- key: "lastDeclaration",
- value: function lastDeclaration() {
- for (var i = this.rules.length; i > 0; i--) {
- var decl = this.rules[i - 1];
-
- if (decl instanceof Declaration) {
- return this.parseValue(decl);
- }
- }
- }
- }, {
- key: "parseValue",
- value: function parseValue(toParse) {
- var self = this;
-
- function transformDeclaration(decl) {
- if (decl.value instanceof Anonymous && !decl.parsed) {
- if (typeof decl.value.value === 'string') {
- this.parse.parseNode(decl.value.value, ['value', 'important'], decl.value.getIndex(), decl.fileInfo(), function (err, result) {
- if (err) {
- decl.parsed = true;
- }
-
- if (result) {
- decl.value = result[0];
- decl.important = result[1] || '';
- decl.parsed = true;
- }
- });
- } else {
- decl.parsed = true;
- }
-
- return decl;
- } else {
- return decl;
- }
- }
-
- if (!Array.isArray(toParse)) {
- return transformDeclaration.call(self, toParse);
- } else {
- var nodes = [];
- toParse.forEach(function (n) {
- nodes.push(transformDeclaration.call(self, n));
- });
- return nodes;
- }
- }
- }, {
- key: "rulesets",
- value: function rulesets() {
- if (!this.rules) {
- return [];
- }
-
- var filtRules = [];
- var rules = this.rules;
- var i;
- var rule;
-
- for (i = 0; rule = rules[i]; i++) {
- if (rule.isRuleset) {
- filtRules.push(rule);
- }
- }
-
- return filtRules;
- }
- }, {
- key: "prependRule",
- value: function prependRule(rule) {
- var rules = this.rules;
-
- if (rules) {
- rules.unshift(rule);
- } else {
- this.rules = [rule];
- }
-
- this.setParent(rule, this);
- }
- }, {
- key: "find",
- value: function find(selector) {
- var self = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : this;
- var filter = arguments.length > 2 ? arguments[2] : undefined;
- var rules = [];
- var match;
- var foundMixins;
- var key = selector.toCSS();
-
- if (key in this._lookups) {
- return this._lookups[key];
- }
-
- this.rulesets().forEach(function (rule) {
- if (rule !== self) {
- for (var j = 0; j < rule.selectors.length; j++) {
- match = selector.match(rule.selectors[j]);
-
- if (match) {
- if (selector.elements.length > match) {
- if (!filter || filter(rule)) {
- foundMixins = rule.find(new Selector(selector.elements.slice(match)), self, filter);
-
- for (var i = 0; i < foundMixins.length; ++i) {
- foundMixins[i].path.push(rule);
- }
-
- Array.prototype.push.apply(rules, foundMixins);
- }
- } else {
- rules.push({
- rule: rule,
- path: []
- });
- }
-
- break;
- }
- }
- }
- });
- this._lookups[key] = rules;
- return rules;
- }
- }, {
- key: "genCSS",
- value: function genCSS(context, output) {
- var i;
- var j;
- var charsetRuleNodes = [];
- var ruleNodes = [];
- var // Line number debugging
- debugInfo$1;
- var rule;
- var path;
- context.tabLevel = context.tabLevel || 0;
-
- if (!this.root) {
- context.tabLevel++;
- }
-
- var tabRuleStr = context.compress ? '' : Array(context.tabLevel + 1).join(' ');
- var tabSetStr = context.compress ? '' : Array(context.tabLevel).join(' ');
- var sep;
- var charsetNodeIndex = 0;
- var importNodeIndex = 0;
-
- for (i = 0; rule = this.rules[i]; i++) {
- if (rule instanceof Comment) {
- if (importNodeIndex === i) {
- importNodeIndex++;
- }
-
- ruleNodes.push(rule);
- } else if (rule.isCharset && rule.isCharset()) {
- ruleNodes.splice(charsetNodeIndex, 0, rule);
- charsetNodeIndex++;
- importNodeIndex++;
- } else if (rule.type === 'Import') {
- ruleNodes.splice(importNodeIndex, 0, rule);
- importNodeIndex++;
- } else {
- ruleNodes.push(rule);
- }
- }
-
- ruleNodes = charsetRuleNodes.concat(ruleNodes); // If this is the root node, we don't render
- // a selector, or {}.
-
- if (!this.root) {
- debugInfo$1 = debugInfo(context, this, tabSetStr);
-
- if (debugInfo$1) {
- output.add(debugInfo$1);
- output.add(tabSetStr);
- }
-
- var paths = this.paths;
- var pathCnt = paths.length;
- var pathSubCnt;
- sep = context.compress ? ',' : ",\n".concat(tabSetStr);
-
- for (i = 0; i < pathCnt; i++) {
- path = paths[i];
-
- if (!(pathSubCnt = path.length)) {
- continue;
- }
-
- if (i > 0) {
- output.add(sep);
- }
-
- context.firstSelector = true;
- path[0].genCSS(context, output);
- context.firstSelector = false;
-
- for (j = 1; j < pathSubCnt; j++) {
- path[j].genCSS(context, output);
- }
- }
-
- output.add((context.compress ? '{' : ' {\n') + tabRuleStr);
- } // Compile rules and rulesets
-
-
- for (i = 0; rule = ruleNodes[i]; i++) {
- if (i + 1 === ruleNodes.length) {
- context.lastRule = true;
- }
-
- var currentLastRule = context.lastRule;
-
- if (rule.isRulesetLike(rule)) {
- context.lastRule = false;
- }
-
- if (rule.genCSS) {
- rule.genCSS(context, output);
- } else if (rule.value) {
- output.add(rule.value.toString());
- }
-
- context.lastRule = currentLastRule;
-
- if (!context.lastRule && rule.isVisible()) {
- output.add(context.compress ? '' : "\n".concat(tabRuleStr));
- } else {
- context.lastRule = false;
- }
- }
-
- if (!this.root) {
- output.add(context.compress ? '}' : "\n".concat(tabSetStr, "}"));
- context.tabLevel--;
- }
-
- if (!output.isEmpty() && !context.compress && this.firstRoot) {
- output.add('\n');
- }
- }
- }, {
- key: "joinSelectors",
- value: function joinSelectors(paths, context, selectors) {
- for (var s = 0; s < selectors.length; s++) {
- this.joinSelector(paths, context, selectors[s]);
- }
- }
- }, {
- key: "joinSelector",
- value: function joinSelector(paths, context, selector) {
- function createParenthesis(elementsToPak, originalElement) {
- var replacementParen;
- var j;
-
- if (elementsToPak.length === 0) {
- replacementParen = new Paren(elementsToPak[0]);
- } else {
- var insideParent = new Array(elementsToPak.length);
-
- for (j = 0; j < elementsToPak.length; j++) {
- insideParent[j] = new Element(null, elementsToPak[j], originalElement.isVariable, originalElement._index, originalElement._fileInfo);
- }
-
- replacementParen = new Paren(new Selector(insideParent));
- }
-
- return replacementParen;
- }
-
- function createSelector(containedElement, originalElement) {
- var element;
- var selector;
- element = new Element(null, containedElement, originalElement.isVariable, originalElement._index, originalElement._fileInfo);
- selector = new Selector([element]);
- return selector;
- } // joins selector path from `beginningPath` with selector path in `addPath`
- // `replacedElement` contains element that is being replaced by `addPath`
- // returns concatenated path
-
-
- function addReplacementIntoPath(beginningPath, addPath, replacedElement, originalSelector) {
- var newSelectorPath;
- var lastSelector;
- var newJoinedSelector; // our new selector path
-
- newSelectorPath = []; // construct the joined selector - if & is the first thing this will be empty,
- // if not newJoinedSelector will be the last set of elements in the selector
-
- if (beginningPath.length > 0) {
- newSelectorPath = copyArray(beginningPath);
- lastSelector = newSelectorPath.pop();
- newJoinedSelector = originalSelector.createDerived(copyArray(lastSelector.elements));
- } else {
- newJoinedSelector = originalSelector.createDerived([]);
- }
-
- if (addPath.length > 0) {
- // /deep/ is a CSS4 selector - (removed, so should deprecate)
- // that is valid without anything in front of it
- // so if the & does not have a combinator that is "" or " " then
- // and there is a combinator on the parent, then grab that.
- // this also allows + a { & .b { .a & { ... though not sure why you would want to do that
- var combinator = replacedElement.combinator;
- var parentEl = addPath[0].elements[0];
-
- if (combinator.emptyOrWhitespace && !parentEl.combinator.emptyOrWhitespace) {
- combinator = parentEl.combinator;
- } // join the elements so far with the first part of the parent
-
-
- newJoinedSelector.elements.push(new Element(combinator, parentEl.value, replacedElement.isVariable, replacedElement._index, replacedElement._fileInfo));
- newJoinedSelector.elements = newJoinedSelector.elements.concat(addPath[0].elements.slice(1));
- } // now add the joined selector - but only if it is not empty
-
-
- if (newJoinedSelector.elements.length !== 0) {
- newSelectorPath.push(newJoinedSelector);
- } // put together the parent selectors after the join (e.g. the rest of the parent)
-
-
- if (addPath.length > 1) {
- var restOfPath = addPath.slice(1);
- restOfPath = restOfPath.map(function (selector) {
- return selector.createDerived(selector.elements, []);
- });
- newSelectorPath = newSelectorPath.concat(restOfPath);
- }
-
- return newSelectorPath;
- } // joins selector path from `beginningPath` with every selector path in `addPaths` array
- // `replacedElement` contains element that is being replaced by `addPath`
- // returns array with all concatenated paths
-
-
- function addAllReplacementsIntoPath(beginningPath, addPaths, replacedElement, originalSelector, result) {
- var j;
-
- for (j = 0; j < beginningPath.length; j++) {
- var newSelectorPath = addReplacementIntoPath(beginningPath[j], addPaths, replacedElement, originalSelector);
- result.push(newSelectorPath);
- }
-
- return result;
- }
-
- function mergeElementsOnToSelectors(elements, selectors) {
- var i;
- var sel;
-
- if (elements.length === 0) {
- return;
- }
-
- if (selectors.length === 0) {
- selectors.push([new Selector(elements)]);
- return;
- }
-
- for (i = 0; sel = selectors[i]; i++) {
- // if the previous thing in sel is a parent this needs to join on to it
- if (sel.length > 0) {
- sel[sel.length - 1] = sel[sel.length - 1].createDerived(sel[sel.length - 1].elements.concat(elements));
- } else {
- sel.push(new Selector(elements));
- }
- }
- } // replace all parent selectors inside `inSelector` by content of `context` array
- // resulting selectors are returned inside `paths` array
- // returns true if `inSelector` contained at least one parent selector
-
-
- function replaceParentSelector(paths, context, inSelector) {
- // The paths are [[Selector]]
- // The first list is a list of comma separated selectors
- // The inner list is a list of inheritance separated selectors
- // e.g.
- // .a, .b {
- // .c {
- // }
- // }
- // == [[.a] [.c]] [[.b] [.c]]
- //
- var i;
- var j;
- var k;
- var currentElements;
- var newSelectors;
- var selectorsMultiplied;
- var sel;
- var el;
- var hadParentSelector = false;
- var length;
- var lastSelector;
-
- function findNestedSelector(element) {
- var maybeSelector;
-
- if (!(element.value instanceof Paren)) {
- return null;
- }
-
- maybeSelector = element.value.value;
-
- if (!(maybeSelector instanceof Selector)) {
- return null;
- }
-
- return maybeSelector;
- } // the elements from the current selector so far
-
-
- currentElements = []; // the current list of new selectors to add to the path.
- // We will build it up. We initiate it with one empty selector as we "multiply" the new selectors
- // by the parents
-
- newSelectors = [[]];
-
- for (i = 0; el = inSelector.elements[i]; i++) {
- // non parent reference elements just get added
- if (el.value !== '&') {
- var nestedSelector = findNestedSelector(el);
-
- if (nestedSelector != null) {
- // merge the current list of non parent selector elements
- // on to the current list of selectors to add
- mergeElementsOnToSelectors(currentElements, newSelectors);
- var nestedPaths = [];
- var replaced = void 0;
- var replacedNewSelectors = [];
- replaced = replaceParentSelector(nestedPaths, context, nestedSelector);
- hadParentSelector = hadParentSelector || replaced; // the nestedPaths array should have only one member - replaceParentSelector does not multiply selectors
-
- for (k = 0; k < nestedPaths.length; k++) {
- var replacementSelector = createSelector(createParenthesis(nestedPaths[k], el), el);
- addAllReplacementsIntoPath(newSelectors, [replacementSelector], el, inSelector, replacedNewSelectors);
- }
-
- newSelectors = replacedNewSelectors;
- currentElements = [];
- } else {
- currentElements.push(el);
- }
- } else {
- hadParentSelector = true; // the new list of selectors to add
-
- selectorsMultiplied = []; // merge the current list of non parent selector elements
- // on to the current list of selectors to add
-
- mergeElementsOnToSelectors(currentElements, newSelectors); // loop through our current selectors
-
- for (j = 0; j < newSelectors.length; j++) {
- sel = newSelectors[j]; // if we don't have any parent paths, the & might be in a mixin so that it can be used
- // whether there are parents or not
-
- if (context.length === 0) {
- // the combinator used on el should now be applied to the next element instead so that
- // it is not lost
- if (sel.length > 0) {
- sel[0].elements.push(new Element(el.combinator, '', el.isVariable, el._index, el._fileInfo));
- }
-
- selectorsMultiplied.push(sel);
- } else {
- // and the parent selectors
- for (k = 0; k < context.length; k++) {
- // We need to put the current selectors
- // then join the last selector's elements on to the parents selectors
- var newSelectorPath = addReplacementIntoPath(sel, context[k], el, inSelector); // add that to our new set of selectors
-
- selectorsMultiplied.push(newSelectorPath);
- }
- }
- } // our new selectors has been multiplied, so reset the state
-
-
- newSelectors = selectorsMultiplied;
- currentElements = [];
- }
- } // if we have any elements left over (e.g. .a& .b == .b)
- // add them on to all the current selectors
-
-
- mergeElementsOnToSelectors(currentElements, newSelectors);
-
- for (i = 0; i < newSelectors.length; i++) {
- length = newSelectors[i].length;
-
- if (length > 0) {
- paths.push(newSelectors[i]);
- lastSelector = newSelectors[i][length - 1];
- newSelectors[i][length - 1] = lastSelector.createDerived(lastSelector.elements, inSelector.extendList);
- }
- }
-
- return hadParentSelector;
- }
-
- function deriveSelector(visibilityInfo, deriveFrom) {
- var newSelector = deriveFrom.createDerived(deriveFrom.elements, deriveFrom.extendList, deriveFrom.evaldCondition);
- newSelector.copyVisibilityInfo(visibilityInfo);
- return newSelector;
- } // joinSelector code follows
-
-
- var i;
- var newPaths;
- var hadParentSelector;
- newPaths = [];
- hadParentSelector = replaceParentSelector(newPaths, context, selector);
-
- if (!hadParentSelector) {
- if (context.length > 0) {
- newPaths = [];
-
- for (i = 0; i < context.length; i++) {
- var concatenated = context[i].map(deriveSelector.bind(this, selector.visibilityInfo()));
- concatenated.push(selector);
- newPaths.push(concatenated);
- }
- } else {
- newPaths = [[selector]];
- }
- }
-
- for (i = 0; i < newPaths.length; i++) {
- paths.push(newPaths[i]);
- }
- }
- }]);
-
- return Ruleset;
- }(Node);
-
- Ruleset.prototype.type = 'Ruleset';
- Ruleset.prototype.isRuleset = true;
-
- var AtRule =
- /*#__PURE__*/
- function (_Node) {
- _inherits(AtRule, _Node);
-
- function AtRule(name, value, rules, index, currentFileInfo, debugInfo, isRooted, visibilityInfo) {
- var _this;
-
- _classCallCheck(this, AtRule);
-
- _this = _possibleConstructorReturn(this, _getPrototypeOf(AtRule).call(this));
- var i;
- _this.name = name;
- _this.value = value instanceof Node ? value : value ? new Anonymous(value) : value;
-
- if (rules) {
- if (Array.isArray(rules)) {
- _this.rules = rules;
- } else {
- _this.rules = [rules];
- _this.rules[0].selectors = new Selector([], null, null, index, currentFileInfo).createEmptySelectors();
- }
-
- for (i = 0; i < _this.rules.length; i++) {
- _this.rules[i].allowImports = true;
- }
-
- _this.setParent(_this.rules, _assertThisInitialized(_this));
- }
-
- _this._index = index;
- _this._fileInfo = currentFileInfo;
- _this.debugInfo = debugInfo;
- _this.isRooted = isRooted || false;
-
- _this.copyVisibilityInfo(visibilityInfo);
-
- _this.allowRoot = true;
- return _this;
- }
-
- _createClass(AtRule, [{
- key: "accept",
- value: function accept(visitor) {
- var value = this.value;
- var rules = this.rules;
-
- if (rules) {
- this.rules = visitor.visitArray(rules);
- }
-
- if (value) {
- this.value = visitor.visit(value);
- }
- }
- }, {
- key: "isRulesetLike",
- value: function isRulesetLike() {
- return this.rules || !this.isCharset();
- }
- }, {
- key: "isCharset",
- value: function isCharset() {
- return '@charset' === this.name;
- }
- }, {
- key: "genCSS",
- value: function genCSS(context, output) {
- var value = this.value;
- var rules = this.rules;
- output.add(this.name, this.fileInfo(), this.getIndex());
-
- if (value) {
- output.add(' ');
- value.genCSS(context, output);
- }
-
- if (rules) {
- this.outputRuleset(context, output, rules);
- } else {
- output.add(';');
- }
- }
- }, {
- key: "eval",
- value: function _eval(context) {
- var mediaPathBackup;
- var mediaBlocksBackup;
- var value = this.value;
- var rules = this.rules; // media stored inside other atrule should not bubble over it
- // backpup media bubbling information
-
- mediaPathBackup = context.mediaPath;
- mediaBlocksBackup = context.mediaBlocks; // deleted media bubbling information
-
- context.mediaPath = [];
- context.mediaBlocks = [];
-
- if (value) {
- value = value.eval(context);
- }
-
- if (rules) {
- // assuming that there is only one rule at this point - that is how parser constructs the rule
- rules = [rules[0].eval(context)];
- rules[0].root = true;
- } // restore media bubbling information
-
-
- context.mediaPath = mediaPathBackup;
- context.mediaBlocks = mediaBlocksBackup;
- return new AtRule(this.name, value, rules, this.getIndex(), this.fileInfo(), this.debugInfo, this.isRooted, this.visibilityInfo());
- }
- }, {
- key: "variable",
- value: function variable(name) {
- if (this.rules) {
- // assuming that there is only one rule at this point - that is how parser constructs the rule
- return Ruleset.prototype.variable.call(this.rules[0], name);
- }
- }
- }, {
- key: "find",
- value: function find() {
- if (this.rules) {
- for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
- args[_key] = arguments[_key];
- }
-
- // assuming that there is only one rule at this point - that is how parser constructs the rule
- return Ruleset.prototype.find.apply(this.rules[0], args);
- }
- }
- }, {
- key: "rulesets",
- value: function rulesets() {
- if (this.rules) {
- // assuming that there is only one rule at this point - that is how parser constructs the rule
- return Ruleset.prototype.rulesets.apply(this.rules[0]);
- }
- }
- }, {
- key: "outputRuleset",
- value: function outputRuleset(context, output, rules) {
- var ruleCnt = rules.length;
- var i;
- context.tabLevel = (context.tabLevel | 0) + 1; // Compressed
-
- if (context.compress) {
- output.add('{');
-
- for (i = 0; i < ruleCnt; i++) {
- rules[i].genCSS(context, output);
- }
-
- output.add('}');
- context.tabLevel--;
- return;
- } // Non-compressed
-
-
- var tabSetStr = "\n".concat(Array(context.tabLevel).join(' '));
- var tabRuleStr = "".concat(tabSetStr, " ");
-
- if (!ruleCnt) {
- output.add(" {".concat(tabSetStr, "}"));
- } else {
- output.add(" {".concat(tabRuleStr));
- rules[0].genCSS(context, output);
-
- for (i = 1; i < ruleCnt; i++) {
- output.add(tabRuleStr);
- rules[i].genCSS(context, output);
- }
-
- output.add("".concat(tabSetStr, "}"));
- }
-
- context.tabLevel--;
- }
- }]);
-
- return AtRule;
- }(Node);
-
- AtRule.prototype.type = 'AtRule';
-
- var DetachedRuleset =
- /*#__PURE__*/
- function (_Node) {
- _inherits(DetachedRuleset, _Node);
-
- function DetachedRuleset(ruleset, frames) {
- var _this;
-
- _classCallCheck(this, DetachedRuleset);
-
- _this = _possibleConstructorReturn(this, _getPrototypeOf(DetachedRuleset).call(this));
- _this.ruleset = ruleset;
- _this.frames = frames;
-
- _this.setParent(_this.ruleset, _assertThisInitialized(_this));
-
- return _this;
- }
-
- _createClass(DetachedRuleset, [{
- key: "accept",
- value: function accept(visitor) {
- this.ruleset = visitor.visit(this.ruleset);
- }
- }, {
- key: "eval",
- value: function _eval(context) {
- var frames = this.frames || copyArray(context.frames);
- return new DetachedRuleset(this.ruleset, frames);
- }
- }, {
- key: "callEval",
- value: function callEval(context) {
- return this.ruleset.eval(this.frames ? new contexts.Eval(context, this.frames.concat(context.frames)) : context);
- }
- }]);
-
- return DetachedRuleset;
- }(Node);
-
- DetachedRuleset.prototype.type = 'DetachedRuleset';
- DetachedRuleset.prototype.evalFirst = true;
-
- var Unit =
- /*#__PURE__*/
- function (_Node) {
- _inherits(Unit, _Node);
-
- function Unit(numerator, denominator, backupUnit) {
- var _this;
-
- _classCallCheck(this, Unit);
-
- _this = _possibleConstructorReturn(this, _getPrototypeOf(Unit).call(this));
- _this.numerator = numerator ? copyArray(numerator).sort() : [];
- _this.denominator = denominator ? copyArray(denominator).sort() : [];
-
- if (backupUnit) {
- _this.backupUnit = backupUnit;
- } else if (numerator && numerator.length) {
- _this.backupUnit = numerator[0];
- }
-
- return _this;
- }
-
- _createClass(Unit, [{
- key: "clone",
- value: function clone() {
- return new Unit(copyArray(this.numerator), copyArray(this.denominator), this.backupUnit);
- }
- }, {
- key: "genCSS",
- value: function genCSS(context, output) {
- // Dimension checks the unit is singular and throws an error if in strict math mode.
- var strictUnits = context && context.strictUnits;
-
- if (this.numerator.length === 1) {
- output.add(this.numerator[0]); // the ideal situation
- } else if (!strictUnits && this.backupUnit) {
- output.add(this.backupUnit);
- } else if (!strictUnits && this.denominator.length) {
- output.add(this.denominator[0]);
- }
- }
- }, {
- key: "toString",
- value: function toString() {
- var i;
- var returnStr = this.numerator.join('*');
-
- for (i = 0; i < this.denominator.length; i++) {
- returnStr += "/".concat(this.denominator[i]);
- }
-
- return returnStr;
- }
- }, {
- key: "compare",
- value: function compare(other) {
- return this.is(other.toString()) ? 0 : undefined;
- }
- }, {
- key: "is",
- value: function is(unitString) {
- return this.toString().toUpperCase() === unitString.toUpperCase();
- }
- }, {
- key: "isLength",
- value: function isLength() {
- return RegExp('^(px|em|ex|ch|rem|in|cm|mm|pc|pt|ex|vw|vh|vmin|vmax)$', 'gi').test(this.toCSS());
- }
- }, {
- key: "isEmpty",
- value: function isEmpty() {
- return this.numerator.length === 0 && this.denominator.length === 0;
- }
- }, {
- key: "isSingular",
- value: function isSingular() {
- return this.numerator.length <= 1 && this.denominator.length === 0;
- }
- }, {
- key: "map",
- value: function map(callback) {
- var i;
-
- for (i = 0; i < this.numerator.length; i++) {
- this.numerator[i] = callback(this.numerator[i], false);
- }
-
- for (i = 0; i < this.denominator.length; i++) {
- this.denominator[i] = callback(this.denominator[i], true);
- }
- }
- }, {
- key: "usedUnits",
- value: function usedUnits() {
- var group;
- var result = {};
- var mapUnit;
- var groupName;
-
- mapUnit = function mapUnit(atomicUnit) {
- /* jshint loopfunc:true */
- if (group.hasOwnProperty(atomicUnit) && !result[groupName]) {
- result[groupName] = atomicUnit;
- }
-
- return atomicUnit;
- };
-
- for (groupName in unitConversions) {
- if (unitConversions.hasOwnProperty(groupName)) {
- group = unitConversions[groupName];
- this.map(mapUnit);
- }
- }
-
- return result;
- }
- }, {
- key: "cancel",
- value: function cancel() {
- var counter = {};
- var atomicUnit;
- var i;
-
- for (i = 0; i < this.numerator.length; i++) {
- atomicUnit = this.numerator[i];
- counter[atomicUnit] = (counter[atomicUnit] || 0) + 1;
- }
-
- for (i = 0; i < this.denominator.length; i++) {
- atomicUnit = this.denominator[i];
- counter[atomicUnit] = (counter[atomicUnit] || 0) - 1;
- }
-
- this.numerator = [];
- this.denominator = [];
-
- for (atomicUnit in counter) {
- if (counter.hasOwnProperty(atomicUnit)) {
- var count = counter[atomicUnit];
-
- if (count > 0) {
- for (i = 0; i < count; i++) {
- this.numerator.push(atomicUnit);
- }
- } else if (count < 0) {
- for (i = 0; i < -count; i++) {
- this.denominator.push(atomicUnit);
- }
- }
- }
- }
-
- this.numerator.sort();
- this.denominator.sort();
- }
- }]);
-
- return Unit;
- }(Node);
-
- Unit.prototype.type = 'Unit';
-
- // A number with a unit
- //
-
- var Dimension =
- /*#__PURE__*/
- function (_Node) {
- _inherits(Dimension, _Node);
-
- function Dimension(value, unit) {
- var _this;
-
- _classCallCheck(this, Dimension);
-
- _this = _possibleConstructorReturn(this, _getPrototypeOf(Dimension).call(this));
- _this.value = parseFloat(value);
-
- if (isNaN(_this.value)) {
- throw new Error('Dimension is not a number.');
- }
-
- _this.unit = unit && unit instanceof Unit ? unit : new Unit(unit ? [unit] : undefined);
-
- _this.setParent(_this.unit, _assertThisInitialized(_this));
-
- return _this;
- }
-
- _createClass(Dimension, [{
- key: "accept",
- value: function accept(visitor) {
- this.unit = visitor.visit(this.unit);
- }
- }, {
- key: "eval",
- value: function _eval(context) {
- return this;
- }
- }, {
- key: "toColor",
- value: function toColor() {
- return new Color([this.value, this.value, this.value]);
- }
- }, {
- key: "genCSS",
- value: function genCSS(context, output) {
- if (context && context.strictUnits && !this.unit.isSingular()) {
- throw new Error("Multiple units in dimension. Correct the units or use the unit function. Bad unit: ".concat(this.unit.toString()));
- }
-
- var value = this.fround(context, this.value);
- var strValue = String(value);
-
- if (value !== 0 && value < 0.000001 && value > -0.000001) {
- // would be output 1e-6 etc.
- strValue = value.toFixed(20).replace(/0+$/, '');
- }
-
- if (context && context.compress) {
- // Zero values doesn't need a unit
- if (value === 0 && this.unit.isLength()) {
- output.add(strValue);
- return;
- } // Float values doesn't need a leading zero
-
-
- if (value > 0 && value < 1) {
- strValue = strValue.substr(1);
- }
- }
-
- output.add(strValue);
- this.unit.genCSS(context, output);
- } // In an operation between two Dimensions,
- // we default to the first Dimension's unit,
- // so `1px + 2` will yield `3px`.
-
- }, {
- key: "operate",
- value: function operate(context, op, other) {
- /* jshint noempty:false */
- var value = this._operate(context, op, this.value, other.value);
-
- var unit = this.unit.clone();
-
- if (op === '+' || op === '-') {
- if (unit.numerator.length === 0 && unit.denominator.length === 0) {
- unit = other.unit.clone();
-
- if (this.unit.backupUnit) {
- unit.backupUnit = this.unit.backupUnit;
- }
- } else if (other.unit.numerator.length === 0 && unit.denominator.length === 0) ; else {
- other = other.convertTo(this.unit.usedUnits());
-
- if (context.strictUnits && other.unit.toString() !== unit.toString()) {
- throw new Error("Incompatible units. Change the units or use the unit function. " + "Bad units: '".concat(unit.toString(), "' and '").concat(other.unit.toString(), "'."));
- }
-
- value = this._operate(context, op, this.value, other.value);
- }
- } else if (op === '*') {
- unit.numerator = unit.numerator.concat(other.unit.numerator).sort();
- unit.denominator = unit.denominator.concat(other.unit.denominator).sort();
- unit.cancel();
- } else if (op === '/') {
- unit.numerator = unit.numerator.concat(other.unit.denominator).sort();
- unit.denominator = unit.denominator.concat(other.unit.numerator).sort();
- unit.cancel();
- }
-
- return new Dimension(value, unit);
- }
- }, {
- key: "compare",
- value: function compare(other) {
- var a;
- var b;
-
- if (!(other instanceof Dimension)) {
- return undefined;
- }
-
- if (this.unit.isEmpty() || other.unit.isEmpty()) {
- a = this;
- b = other;
- } else {
- a = this.unify();
- b = other.unify();
-
- if (a.unit.compare(b.unit) !== 0) {
- return undefined;
- }
- }
-
- return Node.numericCompare(a.value, b.value);
- }
- }, {
- key: "unify",
- value: function unify() {
- return this.convertTo({
- length: 'px',
- duration: 's',
- angle: 'rad'
- });
- }
- }, {
- key: "convertTo",
- value: function convertTo(conversions) {
- var value = this.value;
- var unit = this.unit.clone();
- var i;
- var groupName;
- var group;
- var targetUnit;
- var derivedConversions = {};
- var applyUnit;
-
- if (typeof conversions === 'string') {
- for (i in unitConversions) {
- if (unitConversions[i].hasOwnProperty(conversions)) {
- derivedConversions = {};
- derivedConversions[i] = conversions;
- }
- }
-
- conversions = derivedConversions;
- }
-
- applyUnit = function applyUnit(atomicUnit, denominator) {
- /* jshint loopfunc:true */
- if (group.hasOwnProperty(atomicUnit)) {
- if (denominator) {
- value = value / (group[atomicUnit] / group[targetUnit]);
- } else {
- value = value * (group[atomicUnit] / group[targetUnit]);
- }
-
- return targetUnit;
- }
-
- return atomicUnit;
- };
-
- for (groupName in conversions) {
- if (conversions.hasOwnProperty(groupName)) {
- targetUnit = conversions[groupName];
- group = unitConversions[groupName];
- unit.map(applyUnit);
- }
- }
-
- unit.cancel();
- return new Dimension(value, unit);
- }
- }]);
-
- return Dimension;
- }(Node);
-
- Dimension.prototype.type = 'Dimension';
-
- var MATH$1 = Math$1;
-
- var Operation =
- /*#__PURE__*/
- function (_Node) {
- _inherits(Operation, _Node);
-
- function Operation(op, operands, isSpaced) {
- var _this;
-
- _classCallCheck(this, Operation);
-
- _this = _possibleConstructorReturn(this, _getPrototypeOf(Operation).call(this));
- _this.op = op.trim();
- _this.operands = operands;
- _this.isSpaced = isSpaced;
- return _this;
- }
-
- _createClass(Operation, [{
- key: "accept",
- value: function accept(visitor) {
- this.operands = visitor.visitArray(this.operands);
- }
- }, {
- key: "eval",
- value: function _eval(context) {
- var a = this.operands[0].eval(context);
- var b = this.operands[1].eval(context);
- var op;
-
- if (context.isMathOn(this.op)) {
- op = this.op === './' ? '/' : this.op;
-
- if (a instanceof Dimension && b instanceof Color) {
- a = a.toColor();
- }
-
- if (b instanceof Dimension && a instanceof Color) {
- b = b.toColor();
- }
-
- if (!a.operate) {
- if (a instanceof Operation && a.op === '/' && context.math === MATH$1.PARENS_DIVISION) {
- return new Operation(this.op, [a, b], this.isSpaced);
- }
-
- throw {
- type: 'Operation',
- message: 'Operation on an invalid type'
- };
- }
-
- return a.operate(context, op, b);
- } else {
- return new Operation(this.op, [a, b], this.isSpaced);
- }
- }
- }, {
- key: "genCSS",
- value: function genCSS(context, output) {
- this.operands[0].genCSS(context, output);
-
- if (this.isSpaced) {
- output.add(' ');
- }
-
- output.add(this.op);
-
- if (this.isSpaced) {
- output.add(' ');
- }
-
- this.operands[1].genCSS(context, output);
- }
- }]);
-
- return Operation;
- }(Node);
-
- Operation.prototype.type = 'Operation';
-
- var MATH$2 = Math$1;
-
- var Expression =
- /*#__PURE__*/
- function (_Node) {
- _inherits(Expression, _Node);
-
- function Expression(value, noSpacing) {
- var _this;
-
- _classCallCheck(this, Expression);
-
- _this = _possibleConstructorReturn(this, _getPrototypeOf(Expression).call(this));
- _this.value = value;
- _this.noSpacing = noSpacing;
-
- if (!value) {
- throw new Error('Expression requires an array parameter');
- }
-
- return _this;
- }
-
- _createClass(Expression, [{
- key: "accept",
- value: function accept(visitor) {
- this.value = visitor.visitArray(this.value);
- }
- }, {
- key: "eval",
- value: function _eval(context) {
- var returnValue;
- var mathOn = context.isMathOn();
- var inParenthesis = this.parens && (context.math !== MATH$2.STRICT_LEGACY || !this.parensInOp);
- var doubleParen = false;
-
- if (inParenthesis) {
- context.inParenthesis();
- }
-
- if (this.value.length > 1) {
- returnValue = new Expression(this.value.map(function (e) {
- if (!e.eval) {
- return e;
- }
-
- return e.eval(context);
- }), this.noSpacing);
- } else if (this.value.length === 1) {
- if (this.value[0].parens && !this.value[0].parensInOp && !context.inCalc) {
- doubleParen = true;
- }
-
- returnValue = this.value[0].eval(context);
- } else {
- returnValue = this;
- }
-
- if (inParenthesis) {
- context.outOfParenthesis();
- }
-
- if (this.parens && this.parensInOp && !mathOn && !doubleParen && !(returnValue instanceof Dimension)) {
- returnValue = new Paren(returnValue);
- }
-
- return returnValue;
- }
- }, {
- key: "genCSS",
- value: function genCSS(context, output) {
- for (var i = 0; i < this.value.length; i++) {
- this.value[i].genCSS(context, output);
-
- if (!this.noSpacing && i + 1 < this.value.length) {
- output.add(' ');
- }
- }
- }
- }, {
- key: "throwAwayComments",
- value: function throwAwayComments() {
- this.value = this.value.filter(function (v) {
- return !(v instanceof Comment);
- });
- }
- }]);
-
- return Expression;
- }(Node);
-
- Expression.prototype.type = 'Expression';
-
- var functionCaller =
- /*#__PURE__*/
- function () {
- function functionCaller(name, context, index, currentFileInfo) {
- _classCallCheck(this, functionCaller);
-
- this.name = name.toLowerCase();
- this.index = index;
- this.context = context;
- this.currentFileInfo = currentFileInfo;
- this.func = context.frames[0].functionRegistry.get(this.name);
- }
-
- _createClass(functionCaller, [{
- key: "isValid",
- value: function isValid() {
- return Boolean(this.func);
- }
- }, {
- key: "call",
- value: function call(args) {
- // This code is terrible and should be replaced as per this issue...
- // https://github.com/less/less.js/issues/2477
- if (Array.isArray(args)) {
- args = args.filter(function (item) {
- if (item.type === 'Comment') {
- return false;
- }
-
- return true;
- }).map(function (item) {
- if (item.type === 'Expression') {
- var subNodes = item.value.filter(function (item) {
- if (item.type === 'Comment') {
- return false;
- }
-
- return true;
- });
-
- if (subNodes.length === 1) {
- return subNodes[0];
- } else {
- return new Expression(subNodes);
- }
- }
-
- return item;
- });
- }
-
- return this.func.apply(this, _toConsumableArray(args));
- }
- }]);
-
- return functionCaller;
- }();
-
- // A function call node.
- //
-
- var Call =
- /*#__PURE__*/
- function (_Node) {
- _inherits(Call, _Node);
-
- function Call(name, args, index, currentFileInfo) {
- var _this;
-
- _classCallCheck(this, Call);
-
- _this = _possibleConstructorReturn(this, _getPrototypeOf(Call).call(this));
- _this.name = name;
- _this.args = args;
- _this.calc = name === 'calc';
- _this._index = index;
- _this._fileInfo = currentFileInfo;
- return _this;
- }
-
- _createClass(Call, [{
- key: "accept",
- value: function accept(visitor) {
- if (this.args) {
- this.args = visitor.visitArray(this.args);
- }
- } //
- // When evaluating a function call,
- // we either find the function in the functionRegistry,
- // in which case we call it, passing the evaluated arguments,
- // if this returns null or we cannot find the function, we
- // simply print it out as it appeared originally [2].
- //
- // The reason why we evaluate the arguments, is in the case where
- // we try to pass a variable to a function, like: `saturate(@color)`.
- // The function should receive the value, not the variable.
- //
-
- }, {
- key: "eval",
- value: function _eval(context) {
- /**
- * Turn off math for calc(), and switch back on for evaluating nested functions
- */
- var currentMathContext = context.mathOn;
- context.mathOn = !this.calc;
-
- if (this.calc || context.inCalc) {
- context.enterCalc();
- }
-
- var args = this.args.map(function (a) {
- return a.eval(context);
- });
-
- if (this.calc || context.inCalc) {
- context.exitCalc();
- }
-
- context.mathOn = currentMathContext;
- var result;
- var funcCaller = new functionCaller(this.name, context, this.getIndex(), this.fileInfo());
-
- if (funcCaller.isValid()) {
- try {
- result = funcCaller.call(args);
- } catch (e) {
- throw {
- type: e.type || 'Runtime',
- message: "error evaluating function `".concat(this.name, "`").concat(e.message ? ": ".concat(e.message) : ''),
- index: this.getIndex(),
- filename: this.fileInfo().filename,
- line: e.lineNumber,
- column: e.columnNumber
- };
- }
-
- if (result !== null && result !== undefined) {
- // Results that that are not nodes are cast as Anonymous nodes
- // Falsy values or booleans are returned as empty nodes
- if (!(result instanceof Node)) {
- if (!result || result === true) {
- result = new Anonymous(null);
- } else {
- result = new Anonymous(result.toString());
- }
- }
-
- result._index = this._index;
- result._fileInfo = this._fileInfo;
- return result;
- }
- }
-
- return new Call(this.name, args, this.getIndex(), this.fileInfo());
- }
- }, {
- key: "genCSS",
- value: function genCSS(context, output) {
- output.add("".concat(this.name, "("), this.fileInfo(), this.getIndex());
-
- for (var i = 0; i < this.args.length; i++) {
- this.args[i].genCSS(context, output);
-
- if (i + 1 < this.args.length) {
- output.add(', ');
- }
- }
-
- output.add(')');
- }
- }]);
-
- return Call;
- }(Node);
-
- Call.prototype.type = 'Call';
-
- var Variable =
- /*#__PURE__*/
- function (_Node) {
- _inherits(Variable, _Node);
-
- function Variable(name, index, currentFileInfo) {
- var _this;
-
- _classCallCheck(this, Variable);
-
- _this = _possibleConstructorReturn(this, _getPrototypeOf(Variable).call(this));
- _this.name = name;
- _this._index = index;
- _this._fileInfo = currentFileInfo;
- return _this;
- }
-
- _createClass(Variable, [{
- key: "eval",
- value: function _eval(context) {
- var variable;
- var name = this.name;
-
- if (name.indexOf('@@') === 0) {
- name = "@".concat(new Variable(name.slice(1), this.getIndex(), this.fileInfo()).eval(context).value);
- }
-
- if (this.evaluating) {
- throw {
- type: 'Name',
- message: "Recursive variable definition for ".concat(name),
- filename: this.fileInfo().filename,
- index: this.getIndex()
- };
- }
-
- this.evaluating = true;
- variable = this.find(context.frames, function (frame) {
- var v = frame.variable(name);
-
- if (v) {
- if (v.important) {
- var importantScope = context.importantScope[context.importantScope.length - 1];
- importantScope.important = v.important;
- } // If in calc, wrap vars in a function call to cascade evaluate args first
-
-
- if (context.inCalc) {
- return new Call('_SELF', [v.value]).eval(context);
- } else {
- return v.value.eval(context);
- }
- }
- });
-
- if (variable) {
- this.evaluating = false;
- return variable;
- } else {
- throw {
- type: 'Name',
- message: "variable ".concat(name, " is undefined"),
- filename: this.fileInfo().filename,
- index: this.getIndex()
- };
- }
- }
- }, {
- key: "find",
- value: function find(obj, fun) {
- for (var i = 0, r; i < obj.length; i++) {
- r = fun.call(obj, obj[i]);
-
- if (r) {
- return r;
- }
- }
-
- return null;
- }
- }]);
-
- return Variable;
- }(Node);
-
- Variable.prototype.type = 'Variable';
-
- var Property =
- /*#__PURE__*/
- function (_Node) {
- _inherits(Property, _Node);
-
- function Property(name, index, currentFileInfo) {
- var _this;
-
- _classCallCheck(this, Property);
-
- _this = _possibleConstructorReturn(this, _getPrototypeOf(Property).call(this));
- _this.name = name;
- _this._index = index;
- _this._fileInfo = currentFileInfo;
- return _this;
- }
-
- _createClass(Property, [{
- key: "eval",
- value: function _eval(context) {
- var property;
- var name = this.name; // TODO: shorten this reference
-
- var mergeRules = context.pluginManager.less.visitors.ToCSSVisitor.prototype._mergeRules;
-
- if (this.evaluating) {
- throw {
- type: 'Name',
- message: "Recursive property reference for ".concat(name),
- filename: this.fileInfo().filename,
- index: this.getIndex()
- };
- }
-
- this.evaluating = true;
- property = this.find(context.frames, function (frame) {
- var v;
- var vArr = frame.property(name);
-
- if (vArr) {
- for (var i = 0; i < vArr.length; i++) {
- v = vArr[i];
- vArr[i] = new Declaration(v.name, v.value, v.important, v.merge, v.index, v.currentFileInfo, v.inline, v.variable);
- }
-
- mergeRules(vArr);
- v = vArr[vArr.length - 1];
-
- if (v.important) {
- var importantScope = context.importantScope[context.importantScope.length - 1];
- importantScope.important = v.important;
- }
-
- v = v.value.eval(context);
- return v;
- }
- });
-
- if (property) {
- this.evaluating = false;
- return property;
- } else {
- throw {
- type: 'Name',
- message: "Property '".concat(name, "' is undefined"),
- filename: this.currentFileInfo.filename,
- index: this.index
- };
- }
- }
- }, {
- key: "find",
- value: function find(obj, fun) {
- for (var i = 0, r; i < obj.length; i++) {
- r = fun.call(obj, obj[i]);
-
- if (r) {
- return r;
- }
- }
-
- return null;
- }
- }]);
-
- return Property;
- }(Node);
-
- Property.prototype.type = 'Property';
-
- var Attribute =
- /*#__PURE__*/
- function (_Node) {
- _inherits(Attribute, _Node);
-
- function Attribute(key, op, value) {
- var _this;
-
- _classCallCheck(this, Attribute);
-
- _this = _possibleConstructorReturn(this, _getPrototypeOf(Attribute).call(this));
- _this.key = key;
- _this.op = op;
- _this.value = value;
- return _this;
- }
-
- _createClass(Attribute, [{
- key: "eval",
- value: function _eval(context) {
- return new Attribute(this.key.eval ? this.key.eval(context) : this.key, this.op, this.value && this.value.eval ? this.value.eval(context) : this.value);
- }
- }, {
- key: "genCSS",
- value: function genCSS(context, output) {
- output.add(this.toCSS(context));
- }
- }, {
- key: "toCSS",
- value: function toCSS(context) {
- var value = this.key.toCSS ? this.key.toCSS(context) : this.key;
-
- if (this.op) {
- value += this.op;
- value += this.value.toCSS ? this.value.toCSS(context) : this.value;
- }
-
- return "[".concat(value, "]");
- }
- }]);
-
- return Attribute;
- }(Node);
-
- Attribute.prototype.type = 'Attribute';
-
- var Quoted =
- /*#__PURE__*/
- function (_Node) {
- _inherits(Quoted, _Node);
-
- function Quoted(str, content, escaped, index, currentFileInfo) {
- var _this;
-
- _classCallCheck(this, Quoted);
-
- _this = _possibleConstructorReturn(this, _getPrototypeOf(Quoted).call(this));
- _this.escaped = escaped == null ? true : escaped;
- _this.value = content || '';
- _this.quote = str.charAt(0);
- _this._index = index;
- _this._fileInfo = currentFileInfo;
- _this.variableRegex = /@\{([\w-]+)\}/g;
- _this.propRegex = /\$\{([\w-]+)\}/g;
- _this.allowRoot = escaped;
- return _this;
- }
-
- _createClass(Quoted, [{
- key: "genCSS",
- value: function genCSS(context, output) {
- if (!this.escaped) {
- output.add(this.quote, this.fileInfo(), this.getIndex());
- }
-
- output.add(this.value);
-
- if (!this.escaped) {
- output.add(this.quote);
- }
- }
- }, {
- key: "containsVariables",
- value: function containsVariables() {
- return this.value.match(this.variableRegex);
- }
- }, {
- key: "eval",
- value: function _eval(context) {
- var that = this;
- var value = this.value;
-
- var variableReplacement = function variableReplacement(_, name) {
- var v = new Variable("@".concat(name), that.getIndex(), that.fileInfo()).eval(context, true);
- return v instanceof Quoted ? v.value : v.toCSS();
- };
-
- var propertyReplacement = function propertyReplacement(_, name) {
- var v = new Property("$".concat(name), that.getIndex(), that.fileInfo()).eval(context, true);
- return v instanceof Quoted ? v.value : v.toCSS();
- };
-
- function iterativeReplace(value, regexp, replacementFnc) {
- var evaluatedValue = value;
-
- do {
- value = evaluatedValue.toString();
- evaluatedValue = value.replace(regexp, replacementFnc);
- } while (value !== evaluatedValue);
-
- return evaluatedValue;
- }
-
- value = iterativeReplace(value, this.variableRegex, variableReplacement);
- value = iterativeReplace(value, this.propRegex, propertyReplacement);
- return new Quoted(this.quote + value + this.quote, value, this.escaped, this.getIndex(), this.fileInfo());
- }
- }, {
- key: "compare",
- value: function compare(other) {
- // when comparing quoted strings allow the quote to differ
- if (other.type === 'Quoted' && !this.escaped && !other.escaped) {
- return Node.numericCompare(this.value, other.value);
- } else {
- return other.toCSS && this.toCSS() === other.toCSS() ? 0 : undefined;
- }
- }
- }]);
-
- return Quoted;
- }(Node);
-
- Quoted.prototype.type = 'Quoted';
-
- var URL =
- /*#__PURE__*/
- function (_Node) {
- _inherits(URL, _Node);
-
- function URL(val, index, currentFileInfo, isEvald) {
- var _this;
-
- _classCallCheck(this, URL);
-
- _this = _possibleConstructorReturn(this, _getPrototypeOf(URL).call(this));
- _this.value = val;
- _this._index = index;
- _this._fileInfo = currentFileInfo;
- _this.isEvald = isEvald;
- return _this;
- }
-
- _createClass(URL, [{
- key: "accept",
- value: function accept(visitor) {
- this.value = visitor.visit(this.value);
- }
- }, {
- key: "genCSS",
- value: function genCSS(context, output) {
- output.add('url(');
- this.value.genCSS(context, output);
- output.add(')');
- }
- }, {
- key: "eval",
- value: function _eval(context) {
- var val = this.value.eval(context);
- var rootpath;
-
- if (!this.isEvald) {
- // Add the rootpath if the URL requires a rewrite
- rootpath = this.fileInfo() && this.fileInfo().rootpath;
-
- if (typeof rootpath === 'string' && typeof val.value === 'string' && context.pathRequiresRewrite(val.value)) {
- if (!val.quote) {
- rootpath = escapePath(rootpath);
- }
-
- val.value = context.rewritePath(val.value, rootpath);
- } else {
- val.value = context.normalizePath(val.value);
- } // Add url args if enabled
-
-
- if (context.urlArgs) {
- if (!val.value.match(/^\s*data:/)) {
- var delimiter = val.value.indexOf('?') === -1 ? '?' : '&';
- var urlArgs = delimiter + context.urlArgs;
-
- if (val.value.indexOf('#') !== -1) {
- val.value = val.value.replace('#', "".concat(urlArgs, "#"));
- } else {
- val.value += urlArgs;
- }
- }
- }
- }
-
- return new URL(val, this.getIndex(), this.fileInfo(), true);
- }
- }]);
-
- return URL;
- }(Node);
-
- URL.prototype.type = 'Url';
-
- function escapePath(path) {
- return path.replace(/[\(\)'"\s]/g, function (match) {
- return "\\".concat(match);
- });
- }
-
- var Media =
- /*#__PURE__*/
- function (_AtRule) {
- _inherits(Media, _AtRule);
-
- function Media(value, features, index, currentFileInfo, visibilityInfo) {
- var _this;
-
- _classCallCheck(this, Media);
-
- _this = _possibleConstructorReturn(this, _getPrototypeOf(Media).call(this));
- _this._index = index;
- _this._fileInfo = currentFileInfo;
- var selectors = new Selector([], null, null, _this._index, _this._fileInfo).createEmptySelectors();
- _this.features = new Value(features);
- _this.rules = [new Ruleset(selectors, value)];
- _this.rules[0].allowImports = true;
-
- _this.copyVisibilityInfo(visibilityInfo);
-
- _this.allowRoot = true;
-
- _this.setParent(selectors, _assertThisInitialized(_this));
-
- _this.setParent(_this.features, _assertThisInitialized(_this));
-
- _this.setParent(_this.rules, _assertThisInitialized(_this));
-
- return _this;
- }
-
- _createClass(Media, [{
- key: "isRulesetLike",
- value: function isRulesetLike() {
- return true;
- }
- }, {
- key: "accept",
- value: function accept(visitor) {
- if (this.features) {
- this.features = visitor.visit(this.features);
- }
-
- if (this.rules) {
- this.rules = visitor.visitArray(this.rules);
- }
- }
- }, {
- key: "genCSS",
- value: function genCSS(context, output) {
- output.add('@media ', this._fileInfo, this._index);
- this.features.genCSS(context, output);
- this.outputRuleset(context, output, this.rules);
- }
- }, {
- key: "eval",
- value: function _eval(context) {
- if (!context.mediaBlocks) {
- context.mediaBlocks = [];
- context.mediaPath = [];
- }
-
- var media = new Media(null, [], this._index, this._fileInfo, this.visibilityInfo());
-
- if (this.debugInfo) {
- this.rules[0].debugInfo = this.debugInfo;
- media.debugInfo = this.debugInfo;
- }
-
- media.features = this.features.eval(context);
- context.mediaPath.push(media);
- context.mediaBlocks.push(media);
- this.rules[0].functionRegistry = context.frames[0].functionRegistry.inherit();
- context.frames.unshift(this.rules[0]);
- media.rules = [this.rules[0].eval(context)];
- context.frames.shift();
- context.mediaPath.pop();
- return context.mediaPath.length === 0 ? media.evalTop(context) : media.evalNested(context);
- }
- }, {
- key: "evalTop",
- value: function evalTop(context) {
- var result = this; // Render all dependent Media blocks.
-
- if (context.mediaBlocks.length > 1) {
- var selectors = new Selector([], null, null, this.getIndex(), this.fileInfo()).createEmptySelectors();
- result = new Ruleset(selectors, context.mediaBlocks);
- result.multiMedia = true;
- result.copyVisibilityInfo(this.visibilityInfo());
- this.setParent(result, this);
- }
-
- delete context.mediaBlocks;
- delete context.mediaPath;
- return result;
- }
- }, {
- key: "evalNested",
- value: function evalNested(context) {
- var i;
- var value;
- var path = context.mediaPath.concat([this]); // Extract the media-query conditions separated with `,` (OR).
-
- for (i = 0; i < path.length; i++) {
- value = path[i].features instanceof Value ? path[i].features.value : path[i].features;
- path[i] = Array.isArray(value) ? value : [value];
- } // Trace all permutations to generate the resulting media-query.
- //
- // (a, b and c) with nested (d, e) ->
- // a and d
- // a and e
- // b and c and d
- // b and c and e
-
-
- this.features = new Value(this.permute(path).map(function (path) {
- path = path.map(function (fragment) {
- return fragment.toCSS ? fragment : new Anonymous(fragment);
- });
-
- for (i = path.length - 1; i > 0; i--) {
- path.splice(i, 0, new Anonymous('and'));
- }
-
- return new Expression(path);
- }));
- this.setParent(this.features, this); // Fake a tree-node that doesn't output anything.
-
- return new Ruleset([], []);
- }
- }, {
- key: "permute",
- value: function permute(arr) {
- if (arr.length === 0) {
- return [];
- } else if (arr.length === 1) {
- return arr[0];
- } else {
- var result = [];
- var rest = this.permute(arr.slice(1));
-
- for (var i = 0; i < rest.length; i++) {
- for (var j = 0; j < arr[0].length; j++) {
- result.push([arr[0][j]].concat(rest[i]));
- }
- }
-
- return result;
- }
- }
- }, {
- key: "bubbleSelectors",
- value: function bubbleSelectors(selectors) {
- if (!selectors) {
- return;
- }
-
- this.rules = [new Ruleset(copyArray(selectors), [this.rules[0]])];
+ this.strictImports = strictImports;
+ this.copyVisibilityInfo(visibilityInfo);
+ this.allowRoot = true;
+ this.setParent(this.selectors, this);
this.setParent(this.rules, this);
- }
- }]);
-
- return Media;
- }(AtRule);
-
- Media.prototype.type = 'Media';
-
- // CSS @import node
- //
- // The general strategy here is that we don't want to wait
- // for the parsing to be completed, before we start importing
- // the file. That's because in the context of a browser,
- // most of the time will be spent waiting for the server to respond.
- //
- // On creation, we push the import path to our import queue, though
- // `import,push`, we also pass it a callback, which it'll call once
- // the file has been fetched, and parsed.
- //
-
- var Import =
- /*#__PURE__*/
- function (_Node) {
- _inherits(Import, _Node);
-
- function Import(path, features, options, index, currentFileInfo, visibilityInfo) {
- var _this;
-
- _classCallCheck(this, Import);
-
- _this = _possibleConstructorReturn(this, _getPrototypeOf(Import).call(this));
- _this.options = options;
- _this._index = index;
- _this._fileInfo = currentFileInfo;
- _this.path = path;
- _this.features = features;
- _this.allowRoot = true;
-
- if (_this.options.less !== undefined || _this.options.inline) {
- _this.css = !_this.options.less || _this.options.inline;
- } else {
- var pathValue = _this.getPath();
-
- if (pathValue && /[#\.\&\?]css([\?;].*)?$/.test(pathValue)) {
- _this.css = true;
- }
- }
-
- _this.copyVisibilityInfo(visibilityInfo);
-
- _this.setParent(_this.features, _assertThisInitialized(_this));
-
- _this.setParent(_this.path, _assertThisInitialized(_this));
-
- return _this;
- }
-
- _createClass(Import, [{
- key: "accept",
- value: function accept(visitor) {
- if (this.features) {
- this.features = visitor.visit(this.features);
- }
-
- this.path = visitor.visit(this.path);
-
- if (!this.options.isPlugin && !this.options.inline && this.root) {
- this.root = visitor.visit(this.root);
- }
- }
- }, {
- key: "genCSS",
- value: function genCSS(context, output) {
- if (this.css && this.path._fileInfo.reference === undefined) {
- output.add('@import ', this._fileInfo, this._index);
- this.path.genCSS(context, output);
-
- if (this.features) {
- output.add(' ');
- this.features.genCSS(context, output);
- }
-
- output.add(';');
- }
- }
- }, {
- key: "getPath",
- value: function getPath() {
- return this.path instanceof URL ? this.path.value.value : this.path.value;
- }
- }, {
- key: "isVariableImport",
- value: function isVariableImport() {
- var path = this.path;
-
- if (path instanceof URL) {
- path = path.value;
- }
-
- if (path instanceof Quoted) {
- return path.containsVariables();
- }
-
- return true;
- }
- }, {
- key: "evalForImport",
- value: function evalForImport(context) {
- var path = this.path;
-
- if (path instanceof URL) {
- path = path.value;
- }
-
- return new Import(path.eval(context), this.features, this.options, this._index, this._fileInfo, this.visibilityInfo());
- }
- }, {
- key: "evalPath",
- value: function evalPath(context) {
- var path = this.path.eval(context);
- var fileInfo = this._fileInfo;
-
- if (!(path instanceof URL)) {
- // Add the rootpath if the URL requires a rewrite
- var pathValue = path.value;
-
- if (fileInfo && pathValue && context.pathRequiresRewrite(pathValue)) {
- path.value = context.rewritePath(pathValue, fileInfo.rootpath);
- } else {
- path.value = context.normalizePath(path.value);
- }
- }
-
- return path;
- }
- }, {
- key: "eval",
- value: function _eval(context) {
- var result = this.doEval(context);
-
- if (this.options.reference || this.blocksVisibility()) {
- if (result.length || result.length === 0) {
- result.forEach(function (node) {
- node.addVisibilityBlock();
- });
- } else {
- result.addVisibilityBlock();
- }
- }
-
- return result;
- }
- }, {
- key: "doEval",
- value: function doEval(context) {
- var ruleset;
- var registry;
- var features = this.features && this.features.eval(context);
-
- if (this.options.isPlugin) {
- if (this.root && this.root.eval) {
- try {
- this.root.eval(context);
- } catch (e) {
- e.message = 'Plugin error during evaluation';
- throw new LessError(e, this.root.imports, this.root.filename);
- }
- }
-
- registry = context.frames[0] && context.frames[0].functionRegistry;
-
- if (registry && this.root && this.root.functions) {
- registry.addMultiple(this.root.functions);
- }
-
- return [];
- }
-
- if (this.skip) {
- if (typeof this.skip === 'function') {
- this.skip = this.skip();
- }
-
- if (this.skip) {
- return [];
- }
- }
-
- if (this.options.inline) {
- var contents = new Anonymous(this.root, 0, {
- filename: this.importedFilename,
- reference: this.path._fileInfo && this.path._fileInfo.reference
- }, true, true);
- return this.features ? new Media([contents], this.features.value) : [contents];
- } else if (this.css) {
- var newImport = new Import(this.evalPath(context), features, this.options, this._index);
-
- if (!newImport.css && this.error) {
- throw this.error;
- }
-
- return newImport;
- } else {
- ruleset = new Ruleset(null, copyArray(this.root.rules));
- ruleset.evalImports(context);
- return this.features ? new Media(ruleset.rules, this.features.value) : ruleset.rules;
- }
- }
- }]);
-
- return Import;
- }(Node);
-
- Import.prototype.type = 'Import';
-
- var JsEvalNode =
- /*#__PURE__*/
- function (_Node) {
- _inherits(JsEvalNode, _Node);
-
- function JsEvalNode() {
- _classCallCheck(this, JsEvalNode);
-
- return _possibleConstructorReturn(this, _getPrototypeOf(JsEvalNode).apply(this, arguments));
- }
-
- _createClass(JsEvalNode, [{
- key: "evaluateJavaScript",
- value: function evaluateJavaScript(expression, context) {
- var result;
- var that = this;
- var evalContext = {};
-
- if (!context.javascriptEnabled) {
- throw {
- message: 'Inline JavaScript is not enabled. Is it set in your options?',
- filename: this.fileInfo().filename,
- index: this.getIndex()
- };
- }
-
- expression = expression.replace(/@\{([\w-]+)\}/g, function (_, name) {
- return that.jsify(new Variable("@".concat(name), that.getIndex(), that.fileInfo()).eval(context));
- });
-
- try {
- expression = new Function("return (".concat(expression, ")"));
- } catch (e) {
- throw {
- message: "JavaScript evaluation error: ".concat(e.message, " from `").concat(expression, "`"),
- filename: this.fileInfo().filename,
- index: this.getIndex()
- };
- }
-
- var variables = context.frames[0].variables();
-
- for (var k in variables) {
- if (variables.hasOwnProperty(k)) {
- /* jshint loopfunc:true */
- evalContext[k.slice(1)] = {
- value: variables[k].value,
- toJS: function toJS() {
- return this.value.eval(context).toCSS();
- }
- };
- }
- }
-
- try {
- result = expression.call(evalContext);
- } catch (e) {
- throw {
- message: "JavaScript evaluation error: '".concat(e.name, ": ").concat(e.message.replace(/["]/g, '\''), "'"),
- filename: this.fileInfo().filename,
- index: this.getIndex()
- };
- }
-
- return result;
- }
- }, {
- key: "jsify",
- value: function jsify(obj) {
- if (Array.isArray(obj.value) && obj.value.length > 1) {
- return "[".concat(obj.value.map(function (v) {
- return v.toCSS();
- }).join(', '), "]");
- } else {
- return obj.toCSS();
- }
- }
- }]);
-
- return JsEvalNode;
- }(Node);
-
- var JavaScript =
- /*#__PURE__*/
- function (_JsEvalNode) {
- _inherits(JavaScript, _JsEvalNode);
-
- function JavaScript(string, escaped, index, currentFileInfo) {
- var _this;
-
- _classCallCheck(this, JavaScript);
-
- _this = _possibleConstructorReturn(this, _getPrototypeOf(JavaScript).call(this));
- _this.escaped = escaped;
- _this.expression = string;
- _this._index = index;
- _this._fileInfo = currentFileInfo;
- return _this;
- }
-
- _createClass(JavaScript, [{
- key: "eval",
- value: function _eval(context) {
- var result = this.evaluateJavaScript(this.expression, context);
-
- var type = _typeof(result);
-
- if (type === 'number' && !isNaN(result)) {
- return new Dimension(result);
- } else if (type === 'string') {
- return new Quoted("\"".concat(result, "\""), result, this.escaped, this._index);
- } else if (Array.isArray(result)) {
- return new Anonymous(result.join(', '));
- } else {
- return new Anonymous(result);
- }
- }
- }]);
-
- return JavaScript;
- }(JsEvalNode);
-
- JavaScript.prototype.type = 'JavaScript';
-
- var Assignment =
- /*#__PURE__*/
- function (_Node) {
- _inherits(Assignment, _Node);
-
- function Assignment(key, val) {
- var _this;
-
- _classCallCheck(this, Assignment);
-
- _this = _possibleConstructorReturn(this, _getPrototypeOf(Assignment).call(this));
- _this.key = key;
- _this.value = val;
- return _this;
- }
-
- _createClass(Assignment, [{
- key: "accept",
- value: function accept(visitor) {
- this.value = visitor.visit(this.value);
- }
- }, {
- key: "eval",
- value: function _eval(context) {
- if (this.value.eval) {
- return new Assignment(this.key, this.value.eval(context));
- }
-
- return this;
- }
- }, {
- key: "genCSS",
- value: function genCSS(context, output) {
- output.add("".concat(this.key, "="));
-
- if (this.value.genCSS) {
- this.value.genCSS(context, output);
- } else {
- output.add(this.value);
- }
- }
- }]);
-
- return Assignment;
- }(Node);
-
- Assignment.prototype.type = 'Assignment';
-
- var Condition =
- /*#__PURE__*/
- function (_Node) {
- _inherits(Condition, _Node);
-
- function Condition(op, l, r, i, negate) {
- var _this;
-
- _classCallCheck(this, Condition);
-
- _this = _possibleConstructorReturn(this, _getPrototypeOf(Condition).call(this));
- _this.op = op.trim();
- _this.lvalue = l;
- _this.rvalue = r;
- _this._index = i;
- _this.negate = negate;
- return _this;
- }
-
- _createClass(Condition, [{
- key: "accept",
- value: function accept(visitor) {
- this.lvalue = visitor.visit(this.lvalue);
- this.rvalue = visitor.visit(this.rvalue);
- }
- }, {
- key: "eval",
- value: function _eval(context) {
- var result = function (op, a, b) {
- switch (op) {
- case 'and':
- return a && b;
-
- case 'or':
- return a || b;
-
- default:
- switch (Node.compare(a, b)) {
- case -1:
- return op === '<' || op === '=<' || op === '<=';
-
- case 0:
- return op === '=' || op === '>=' || op === '=<' || op === '<=';
-
- case 1:
- return op === '>' || op === '>=';
-
- default:
- return false;
- }
-
- }
- }(this.op, this.lvalue.eval(context), this.rvalue.eval(context));
-
- return this.negate ? !result : result;
- }
- }]);
-
- return Condition;
- }(Node);
-
- Condition.prototype.type = 'Condition';
-
- var UnicodeDescriptor =
- /*#__PURE__*/
- function (_Node) {
- _inherits(UnicodeDescriptor, _Node);
-
- function UnicodeDescriptor(value) {
- var _this;
-
- _classCallCheck(this, UnicodeDescriptor);
-
- _this = _possibleConstructorReturn(this, _getPrototypeOf(UnicodeDescriptor).call(this));
- _this.value = value;
- return _this;
- }
-
- return UnicodeDescriptor;
- }(Node);
-
- UnicodeDescriptor.prototype.type = 'UnicodeDescriptor';
-
- var Negative =
- /*#__PURE__*/
- function (_Node) {
- _inherits(Negative, _Node);
-
- function Negative(node) {
- var _this;
-
- _classCallCheck(this, Negative);
-
- _this = _possibleConstructorReturn(this, _getPrototypeOf(Negative).call(this));
- _this.value = node;
- return _this;
- }
-
- _createClass(Negative, [{
- key: "genCSS",
- value: function genCSS(context, output) {
- output.add('-');
- this.value.genCSS(context, output);
- }
- }, {
- key: "eval",
- value: function _eval(context) {
- if (context.isMathOn()) {
- return new Operation('*', [new Dimension(-1), this.value]).eval(context);
- }
-
- return new Negative(this.value.eval(context));
- }
- }]);
-
- return Negative;
- }(Node);
-
- Negative.prototype.type = 'Negative';
-
- var Extend =
- /*#__PURE__*/
- function (_Node) {
- _inherits(Extend, _Node);
-
- function Extend(selector, option, index, currentFileInfo, visibilityInfo) {
- var _this;
-
- _classCallCheck(this, Extend);
-
- _this = _possibleConstructorReturn(this, _getPrototypeOf(Extend).call(this));
- _this.selector = selector;
- _this.option = option;
- _this.object_id = Extend.next_id++;
- _this.parent_ids = [_this.object_id];
- _this._index = index;
- _this._fileInfo = currentFileInfo;
-
- _this.copyVisibilityInfo(visibilityInfo);
-
- _this.allowRoot = true;
-
- switch (option) {
- case 'all':
- _this.allowBefore = true;
- _this.allowAfter = true;
- break;
-
- default:
- _this.allowBefore = false;
- _this.allowAfter = false;
- break;
- }
-
- _this.setParent(_this.selector, _assertThisInitialized(_this));
-
- return _this;
- }
-
- _createClass(Extend, [{
- key: "accept",
- value: function accept(visitor) {
- this.selector = visitor.visit(this.selector);
- }
- }, {
- key: "eval",
- value: function _eval(context) {
- return new Extend(this.selector.eval(context), this.option, this.getIndex(), this.fileInfo(), this.visibilityInfo());
- }
- }, {
- key: "clone",
- value: function clone(context) {
- return new Extend(this.selector, this.option, this.getIndex(), this.fileInfo(), this.visibilityInfo());
- } // it concatenates (joins) all selectors in selector array
-
- }, {
- key: "findSelfSelectors",
- value: function findSelfSelectors(selectors) {
- var selfElements = [];
- var i;
- var selectorElements;
-
- for (i = 0; i < selectors.length; i++) {
- selectorElements = selectors[i].elements; // duplicate the logic in genCSS function inside the selector node.
- // future TODO - move both logics into the selector joiner visitor
-
- if (i > 0 && selectorElements.length && selectorElements[0].combinator.value === '') {
- selectorElements[0].combinator.value = ' ';
- }
-
- selfElements = selfElements.concat(selectors[i].elements);
- }
-
- this.selfSelectors = [new Selector(selfElements)];
- this.selfSelectors[0].copyVisibilityInfo(this.visibilityInfo());
- }
- }]);
-
- return Extend;
- }(Node);
-
- Extend.next_id = 0;
- Extend.prototype.type = 'Extend';
-
- var VariableCall =
- /*#__PURE__*/
- function (_Node) {
- _inherits(VariableCall, _Node);
-
- function VariableCall(variable, index, currentFileInfo) {
- var _this;
-
- _classCallCheck(this, VariableCall);
-
- _this = _possibleConstructorReturn(this, _getPrototypeOf(VariableCall).call(this));
- _this.variable = variable;
- _this._index = index;
- _this._fileInfo = currentFileInfo;
- _this.allowRoot = true;
- return _this;
- }
-
- _createClass(VariableCall, [{
- key: "eval",
- value: function _eval(context) {
- var rules;
- var detachedRuleset = new Variable(this.variable, this.getIndex(), this.fileInfo()).eval(context);
- var error = new LessError({
- message: "Could not evaluate variable call ".concat(this.variable)
- });
-
- if (!detachedRuleset.ruleset) {
- if (detachedRuleset.rules) {
- rules = detachedRuleset;
- } else if (Array.isArray(detachedRuleset)) {
- rules = new Ruleset('', detachedRuleset);
- } else if (Array.isArray(detachedRuleset.value)) {
- rules = new Ruleset('', detachedRuleset.value);
- } else {
- throw error;
- }
-
- detachedRuleset = new DetachedRuleset(rules);
- }
-
- if (detachedRuleset.ruleset) {
- return detachedRuleset.callEval(context);
- }
-
- throw error;
- }
- }]);
-
- return VariableCall;
- }(Node);
-
- VariableCall.prototype.type = 'VariableCall';
-
- var NamespaceValue =
- /*#__PURE__*/
- function (_Node) {
- _inherits(NamespaceValue, _Node);
-
- function NamespaceValue(ruleCall, lookups, important, index, fileInfo) {
- var _this;
-
- _classCallCheck(this, NamespaceValue);
-
- _this = _possibleConstructorReturn(this, _getPrototypeOf(NamespaceValue).call(this));
- _this.value = ruleCall;
- _this.lookups = lookups;
- _this.important = important;
- _this._index = index;
- _this._fileInfo = fileInfo;
- return _this;
- }
-
- _createClass(NamespaceValue, [{
- key: "eval",
- value: function _eval(context) {
- var i;
- var name;
- var rules = this.value.eval(context);
-
- for (i = 0; i < this.lookups.length; i++) {
- name = this.lookups[i];
- /**
- * Eval'd DRs return rulesets.
- * Eval'd mixins return rules, so let's make a ruleset if we need it.
- * We need to do this because of late parsing of values
- */
-
- if (Array.isArray(rules)) {
- rules = new Ruleset([new Selector()], rules);
- }
-
- if (name === '') {
- rules = rules.lastDeclaration();
- } else if (name.charAt(0) === '@') {
- if (name.charAt(1) === '@') {
- name = "@".concat(new Variable(name.substr(1)).eval(context).value);
- }
-
- if (rules.variables) {
- rules = rules.variable(name);
- }
-
- if (!rules) {
- throw {
- type: 'Name',
- message: "variable ".concat(name, " not found"),
- filename: this.fileInfo().filename,
- index: this.getIndex()
- };
- }
- } else {
- if (name.substring(0, 2) === '$@') {
- name = "$".concat(new Variable(name.substr(1)).eval(context).value);
- } else {
- name = name.charAt(0) === '$' ? name : "$".concat(name);
- }
-
- if (rules.properties) {
- rules = rules.property(name);
- }
-
- if (!rules) {
- throw {
- type: 'Name',
- message: "property \"".concat(name.substr(1), "\" not found"),
- filename: this.fileInfo().filename,
- index: this.getIndex()
- };
- } // Properties are an array of values, since a ruleset can have multiple props.
- // We pick the last one (the "cascaded" value)
-
-
- rules = rules[rules.length - 1];
- }
-
- if (rules.value) {
- rules = rules.eval(context).value;
- }
-
- if (rules.ruleset) {
- rules = rules.ruleset.eval(context);
- }
- }
-
- return rules;
- }
- }]);
-
- return NamespaceValue;
- }(Node);
-
- NamespaceValue.prototype.type = 'NamespaceValue';
-
- var Definition =
- /*#__PURE__*/
- function (_Ruleset) {
- _inherits(Definition, _Ruleset);
-
- function Definition(name, params, rules, condition, variadic, frames, visibilityInfo) {
- var _this;
-
- _classCallCheck(this, Definition);
-
- _this = _possibleConstructorReturn(this, _getPrototypeOf(Definition).call(this));
- _this.name = name || 'anonymous mixin';
- _this.selectors = [new Selector([new Element(null, name, false, _this._index, _this._fileInfo)])];
- _this.params = params;
- _this.condition = condition;
- _this.variadic = variadic;
- _this.arity = params.length;
- _this.rules = rules;
- _this._lookups = {};
- var optionalParameters = [];
- _this.required = params.reduce(function (count, p) {
- if (!p.name || p.name && !p.value) {
- return count + 1;
- } else {
- optionalParameters.push(p.name);
- return count;
- }
- }, 0);
- _this.optionalParameters = optionalParameters;
- _this.frames = frames;
-
- _this.copyVisibilityInfo(visibilityInfo);
-
- _this.allowRoot = true;
- return _this;
- }
-
- _createClass(Definition, [{
- key: "accept",
- value: function accept(visitor) {
- if (this.params && this.params.length) {
- this.params = visitor.visitArray(this.params);
- }
-
- this.rules = visitor.visitArray(this.rules);
-
- if (this.condition) {
- this.condition = visitor.visit(this.condition);
- }
- }
- }, {
- key: "evalParams",
- value: function evalParams(context, mixinEnv, args, evaldArguments) {
- /* jshint boss:true */
- var frame = new Ruleset(null, null);
- var varargs;
- var arg;
- var params = copyArray(this.params);
- var i;
- var j;
- var val;
- var name;
- var isNamedFound;
- var argIndex;
- var argsLength = 0;
-
- if (mixinEnv.frames && mixinEnv.frames[0] && mixinEnv.frames[0].functionRegistry) {
- frame.functionRegistry = mixinEnv.frames[0].functionRegistry.inherit();
- }
-
- mixinEnv = new contexts.Eval(mixinEnv, [frame].concat(mixinEnv.frames));
-
- if (args) {
- args = copyArray(args);
- argsLength = args.length;
-
- for (i = 0; i < argsLength; i++) {
- arg = args[i];
-
- if (name = arg && arg.name) {
- isNamedFound = false;
-
- for (j = 0; j < params.length; j++) {
- if (!evaldArguments[j] && name === params[j].name) {
- evaldArguments[j] = arg.value.eval(context);
- frame.prependRule(new Declaration(name, arg.value.eval(context)));
- isNamedFound = true;
- break;
- }
- }
-
- if (isNamedFound) {
- args.splice(i, 1);
- i--;
- continue;
- } else {
- throw {
- type: 'Runtime',
- message: "Named argument for ".concat(this.name, " ").concat(args[i].name, " not found")
- };
- }
- }
- }
- }
-
- argIndex = 0;
-
- for (i = 0; i < params.length; i++) {
- if (evaldArguments[i]) {
- continue;
- }
-
- arg = args && args[argIndex];
-
- if (name = params[i].name) {
- if (params[i].variadic) {
- varargs = [];
-
- for (j = argIndex; j < argsLength; j++) {
- varargs.push(args[j].value.eval(context));
- }
-
- frame.prependRule(new Declaration(name, new Expression(varargs).eval(context)));
- } else {
- val = arg && arg.value;
-
- if (val) {
- // This was a mixin call, pass in a detached ruleset of it's eval'd rules
- if (Array.isArray(val)) {
- val = new DetachedRuleset(new Ruleset('', val));
- } else {
- val = val.eval(context);
- }
- } else if (params[i].value) {
- val = params[i].value.eval(mixinEnv);
- frame.resetCache();
- } else {
- throw {
- type: 'Runtime',
- message: "wrong number of arguments for ".concat(this.name, " (").concat(argsLength, " for ").concat(this.arity, ")")
- };
- }
-
- frame.prependRule(new Declaration(name, val));
- evaldArguments[i] = val;
- }
- }
-
- if (params[i].variadic && args) {
- for (j = argIndex; j < argsLength; j++) {
- evaldArguments[j] = args[j].value.eval(context);
- }
- }
-
- argIndex++;
- }
-
- return frame;
- }
- }, {
- key: "makeImportant",
- value: function makeImportant() {
- var rules = !this.rules ? this.rules : this.rules.map(function (r) {
- if (r.makeImportant) {
- return r.makeImportant(true);
- } else {
- return r;
- }
- });
- var result = new Definition(this.name, this.params, rules, this.condition, this.variadic, this.frames);
- return result;
- }
- }, {
- key: "eval",
- value: function _eval(context) {
- return new Definition(this.name, this.params, this.rules, this.condition, this.variadic, this.frames || copyArray(context.frames));
- }
- }, {
- key: "evalCall",
- value: function evalCall(context, args, important) {
- var _arguments = [];
- var mixinFrames = this.frames ? this.frames.concat(context.frames) : context.frames;
- var frame = this.evalParams(context, new contexts.Eval(context, mixinFrames), args, _arguments);
- var rules;
- var ruleset;
- frame.prependRule(new Declaration('@arguments', new Expression(_arguments).eval(context)));
- rules = copyArray(this.rules);
- ruleset = new Ruleset(null, rules);
- ruleset.originalRuleset = this;
- ruleset = ruleset.eval(new contexts.Eval(context, [this, frame].concat(mixinFrames)));
-
- if (important) {
- ruleset = ruleset.makeImportant();
- }
-
- return ruleset;
- }
- }, {
- key: "matchCondition",
- value: function matchCondition(args, context) {
- if (this.condition && !this.condition.eval(new contexts.Eval(context, [this.evalParams(context,
- /* the parameter variables */
- new contexts.Eval(context, this.frames ? this.frames.concat(context.frames) : context.frames), args, [])].concat(this.frames || []) // the parent namespace/mixin frames
- .concat(context.frames)))) {
- // the current environment frames
- return false;
- }
-
- return true;
- }
- }, {
- key: "matchArgs",
- value: function matchArgs(args, context) {
- var allArgsCnt = args && args.length || 0;
- var len;
- var optionalParameters = this.optionalParameters;
- var requiredArgsCnt = !args ? 0 : args.reduce(function (count, p) {
- if (optionalParameters.indexOf(p.name) < 0) {
- return count + 1;
- } else {
- return count;
- }
- }, 0);
-
- if (!this.variadic) {
- if (requiredArgsCnt < this.required) {
- return false;
- }
-
- if (allArgsCnt > this.params.length) {
- return false;
- }
- } else {
- if (requiredArgsCnt < this.required - 1) {
- return false;
- }
- } // check patterns
-
-
- len = Math.min(requiredArgsCnt, this.arity);
-
- for (var i = 0; i < len; i++) {
- if (!this.params[i].name && !this.params[i].variadic) {
- if (args[i].value.eval(context).toCSS() != this.params[i].value.eval(context).toCSS()) {
- return false;
- }
- }
- }
-
- return true;
- }
- }]);
-
- return Definition;
- }(Ruleset);
-
- Definition.prototype.type = 'MixinDefinition';
- Definition.prototype.evalFirst = true;
-
- var MixinCall =
- /*#__PURE__*/
- function (_Node) {
- _inherits(MixinCall, _Node);
-
- function MixinCall(elements, args, index, currentFileInfo, important) {
- var _this;
-
- _classCallCheck(this, MixinCall);
-
- _this = _possibleConstructorReturn(this, _getPrototypeOf(MixinCall).call(this));
- _this.selector = new Selector(elements);
- _this.arguments = args || [];
- _this._index = index;
- _this._fileInfo = currentFileInfo;
- _this.important = important;
- _this.allowRoot = true;
-
- _this.setParent(_this.selector, _assertThisInitialized(_this));
-
- return _this;
- }
-
- _createClass(MixinCall, [{
- key: "accept",
- value: function accept(visitor) {
- if (this.selector) {
- this.selector = visitor.visit(this.selector);
- }
-
- if (this.arguments.length) {
- this.arguments = visitor.visitArray(this.arguments);
- }
- }
- }, {
- key: "eval",
- value: function _eval(context) {
- var mixins;
- var mixin;
- var mixinPath;
- var args = [];
- var arg;
- var argValue;
- var rules = [];
- var match = false;
- var i;
- var m;
- var f;
- var isRecursive;
- var isOneFound;
- var candidates = [];
- var candidate;
- var conditionResult = [];
- var defaultResult;
- var defFalseEitherCase = -1;
- var defNone = 0;
- var defTrue = 1;
- var defFalse = 2;
- var count;
- var originalRuleset;
- var noArgumentsFilter;
- this.selector = this.selector.eval(context);
-
- function calcDefGroup(mixin, mixinPath) {
- var f;
- var p;
- var namespace;
-
- for (f = 0; f < 2; f++) {
- conditionResult[f] = true;
- defaultFunc.value(f);
-
- for (p = 0; p < mixinPath.length && conditionResult[f]; p++) {
- namespace = mixinPath[p];
-
- if (namespace.matchCondition) {
- conditionResult[f] = conditionResult[f] && namespace.matchCondition(null, context);
- }
- }
-
- if (mixin.matchCondition) {
- conditionResult[f] = conditionResult[f] && mixin.matchCondition(args, context);
- }
- }
-
- if (conditionResult[0] || conditionResult[1]) {
- if (conditionResult[0] != conditionResult[1]) {
- return conditionResult[1] ? defTrue : defFalse;
- }
-
- return defNone;
- }
-
- return defFalseEitherCase;
- }
-
- for (i = 0; i < this.arguments.length; i++) {
- arg = this.arguments[i];
- argValue = arg.value.eval(context);
-
- if (arg.expand && Array.isArray(argValue.value)) {
- argValue = argValue.value;
-
- for (m = 0; m < argValue.length; m++) {
- args.push({
- value: argValue[m]
- });
- }
- } else {
- args.push({
- name: arg.name,
- value: argValue
- });
- }
- }
-
- noArgumentsFilter = function noArgumentsFilter(rule) {
- return rule.matchArgs(null, context);
- };
-
- for (i = 0; i < context.frames.length; i++) {
- if ((mixins = context.frames[i].find(this.selector, null, noArgumentsFilter)).length > 0) {
- isOneFound = true; // To make `default()` function independent of definition order we have two "subpasses" here.
- // At first we evaluate each guard *twice* (with `default() == true` and `default() == false`),
- // and build candidate list with corresponding flags. Then, when we know all possible matches,
- // we make a final decision.
-
- for (m = 0; m < mixins.length; m++) {
- mixin = mixins[m].rule;
- mixinPath = mixins[m].path;
- isRecursive = false;
-
- for (f = 0; f < context.frames.length; f++) {
- if (!(mixin instanceof Definition) && mixin === (context.frames[f].originalRuleset || context.frames[f])) {
- isRecursive = true;
- break;
- }
- }
-
- if (isRecursive) {
- continue;
- }
-
- if (mixin.matchArgs(args, context)) {
- candidate = {
- mixin: mixin,
- group: calcDefGroup(mixin, mixinPath)
- };
-
- if (candidate.group !== defFalseEitherCase) {
- candidates.push(candidate);
- }
-
- match = true;
- }
- }
-
- defaultFunc.reset();
- count = [0, 0, 0];
-
- for (m = 0; m < candidates.length; m++) {
- count[candidates[m].group]++;
- }
-
- if (count[defNone] > 0) {
- defaultResult = defFalse;
- } else {
- defaultResult = defTrue;
-
- if (count[defTrue] + count[defFalse] > 1) {
- throw {
- type: 'Runtime',
- message: "Ambiguous use of `default()` found when matching for `".concat(this.format(args), "`"),
- index: this.getIndex(),
- filename: this.fileInfo().filename
- };
- }
- }
-
- for (m = 0; m < candidates.length; m++) {
- candidate = candidates[m].group;
-
- if (candidate === defNone || candidate === defaultResult) {
- try {
- mixin = candidates[m].mixin;
-
- if (!(mixin instanceof Definition)) {
- originalRuleset = mixin.originalRuleset || mixin;
- mixin = new Definition('', [], mixin.rules, null, false, null, originalRuleset.visibilityInfo());
- mixin.originalRuleset = originalRuleset;
- }
-
- var newRules = mixin.evalCall(context, args, this.important).rules;
-
- this._setVisibilityToReplacement(newRules);
-
- Array.prototype.push.apply(rules, newRules);
- } catch (e) {
- throw {
- message: e.message,
- index: this.getIndex(),
- filename: this.fileInfo().filename,
- stack: e.stack
- };
- }
- }
- }
-
- if (match) {
- return rules;
- }
- }
- }
-
- if (isOneFound) {
- throw {
- type: 'Runtime',
- message: "No matching definition was found for `".concat(this.format(args), "`"),
- index: this.getIndex(),
- filename: this.fileInfo().filename
- };
- } else {
- throw {
- type: 'Name',
- message: "".concat(this.selector.toCSS().trim(), " is undefined"),
- index: this.getIndex(),
- filename: this.fileInfo().filename
- };
- }
- }
- }, {
- key: "_setVisibilityToReplacement",
- value: function _setVisibilityToReplacement(replacement) {
- var i;
- var rule;
-
- if (this.blocksVisibility()) {
- for (i = 0; i < replacement.length; i++) {
- rule = replacement[i];
- rule.addVisibilityBlock();
- }
- }
- }
- }, {
- key: "format",
- value: function format(args) {
- return "".concat(this.selector.toCSS().trim(), "(").concat(args ? args.map(function (a) {
- var argValue = '';
-
- if (a.name) {
- argValue += "".concat(a.name, ":");
- }
-
- if (a.value.toCSS) {
- argValue += a.value.toCSS();
- } else {
- argValue += '???';
- }
-
- return argValue;
- }).join(', ') : '', ")");
- }
- }]);
-
- return MixinCall;
- }(Node);
-
- MixinCall.prototype.type = 'MixinCall';
-
- var tree = {
- Node: Node,
- Color: Color,
- AtRule: AtRule,
- DetachedRuleset: DetachedRuleset,
- Operation: Operation,
- Dimension: Dimension,
- Unit: Unit,
- Keyword: Keyword,
- Variable: Variable,
- Property: Property,
- Ruleset: Ruleset,
- Element: Element,
- Attribute: Attribute,
- Combinator: Combinator,
- Selector: Selector,
- Quoted: Quoted,
- Expression: Expression,
- Declaration: Declaration,
- Call: Call,
- URL: URL,
- Import: Import,
- Comment: Comment,
- Anonymous: Anonymous,
- Value: Value,
- JavaScript: JavaScript,
- Assignment: Assignment,
- Condition: Condition,
- Paren: Paren,
- Media: Media,
- UnicodeDescriptor: UnicodeDescriptor,
- Negative: Negative,
- Extend: Extend,
- VariableCall: VariableCall,
- NamespaceValue: NamespaceValue,
- mixin: {
- Call: MixinCall,
- Definition: Definition
- }
- };
-
- var logger = {
- error: function error(msg) {
- this._fireEvent('error', msg);
- },
- warn: function warn(msg) {
- this._fireEvent('warn', msg);
- },
- info: function info(msg) {
- this._fireEvent('info', msg);
- },
- debug: function debug(msg) {
- this._fireEvent('debug', msg);
- },
- addListener: function addListener(listener) {
- this._listeners.push(listener);
- },
- removeListener: function removeListener(listener) {
- for (var i = 0; i < this._listeners.length; i++) {
- if (this._listeners[i] === listener) {
- this._listeners.splice(i, 1);
-
- return;
- }
- }
- },
- _fireEvent: function _fireEvent(type, msg) {
- for (var i = 0; i < this._listeners.length; i++) {
- var logFunction = this._listeners[i][type];
-
- if (logFunction) {
- logFunction(msg);
- }
- }
- },
- _listeners: []
- };
-
- var environment =
- /*#__PURE__*/
- function () {
- function environment(externalEnvironment, fileManagers) {
- _classCallCheck(this, environment);
-
- this.fileManagers = fileManagers || [];
- externalEnvironment = externalEnvironment || {};
- var optionalFunctions = ['encodeBase64', 'mimeLookup', 'charsetLookup', 'getSourceMapGenerator'];
- var requiredFunctions = [];
- var functions = requiredFunctions.concat(optionalFunctions);
-
- for (var i = 0; i < functions.length; i++) {
- var propName = functions[i];
- var environmentFunc = externalEnvironment[propName];
-
- if (environmentFunc) {
- this[propName] = environmentFunc.bind(externalEnvironment);
- } else if (i < requiredFunctions.length) {
- this.warn("missing required function in environment - ".concat(propName));
- }
- }
- }
-
- _createClass(environment, [{
- key: "getFileManager",
- value: function getFileManager(filename, currentDirectory, options, environment, isSync) {
- if (!filename) {
- logger.warn('getFileManager called with no filename.. Please report this issue. continuing.');
- }
-
- if (currentDirectory == null) {
- logger.warn('getFileManager called with null directory.. Please report this issue. continuing.');
- }
-
- var fileManagers = this.fileManagers;
-
- if (options.pluginManager) {
- fileManagers = [].concat(fileManagers).concat(options.pluginManager.getFileManagers());
- }
-
- for (var i = fileManagers.length - 1; i >= 0; i--) {
- var fileManager = fileManagers[i];
-
- if (fileManager[isSync ? 'supportsSync' : 'supports'](filename, currentDirectory, options, environment)) {
- return fileManager;
- }
- }
-
- return null;
- }
- }, {
- key: "addFileManager",
- value: function addFileManager(fileManager) {
- this.fileManagers.push(fileManager);
- }
- }, {
- key: "clearFileManagers",
- value: function clearFileManagers() {
- this.fileManagers = [];
- }
- }]);
-
- return environment;
- }();
-
- var AbstractFileManager =
- /*#__PURE__*/
- function () {
- function AbstractFileManager() {
- _classCallCheck(this, AbstractFileManager);
- }
-
- _createClass(AbstractFileManager, [{
- key: "getPath",
- value: function getPath(filename) {
- var j = filename.lastIndexOf('?');
-
- if (j > 0) {
- filename = filename.slice(0, j);
- }
-
- j = filename.lastIndexOf('/');
-
- if (j < 0) {
- j = filename.lastIndexOf('\\');
- }
-
- if (j < 0) {
- return '';
- }
-
- return filename.slice(0, j + 1);
- }
- }, {
- key: "tryAppendExtension",
- value: function tryAppendExtension(path, ext) {
- return /(\.[a-z]*$)|([\?;].*)$/.test(path) ? path : path + ext;
- }
- }, {
- key: "tryAppendLessExtension",
- value: function tryAppendLessExtension(path) {
- return this.tryAppendExtension(path, '.less');
- }
- }, {
- key: "supportsSync",
- value: function supportsSync() {
- return false;
- }
- }, {
- key: "alwaysMakePathsAbsolute",
- value: function alwaysMakePathsAbsolute() {
- return false;
- }
- }, {
- key: "isPathAbsolute",
- value: function isPathAbsolute(filename) {
- return /^(?:[a-z-]+:|\/|\\|#)/i.test(filename);
- } // TODO: pull out / replace?
-
- }, {
- key: "join",
- value: function join(basePath, laterPath) {
- if (!basePath) {
- return laterPath;
- }
-
- return basePath + laterPath;
- }
- }, {
- key: "pathDiff",
- value: function pathDiff(url, baseUrl) {
- // diff between two paths to create a relative path
- var urlParts = this.extractUrlParts(url);
- var baseUrlParts = this.extractUrlParts(baseUrl);
- var i;
- var max;
- var urlDirectories;
- var baseUrlDirectories;
- var diff = '';
-
- if (urlParts.hostPart !== baseUrlParts.hostPart) {
- return '';
- }
-
- max = Math.max(baseUrlParts.directories.length, urlParts.directories.length);
-
- for (i = 0; i < max; i++) {
- if (baseUrlParts.directories[i] !== urlParts.directories[i]) {
- break;
- }
- }
-
- baseUrlDirectories = baseUrlParts.directories.slice(i);
- urlDirectories = urlParts.directories.slice(i);
-
- for (i = 0; i < baseUrlDirectories.length - 1; i++) {
- diff += '../';
- }
-
- for (i = 0; i < urlDirectories.length - 1; i++) {
- diff += "".concat(urlDirectories[i], "/");
- }
-
- return diff;
- }
- }, {
- key: "extractUrlParts",
- // helper function, not part of API
- value: function extractUrlParts(url, baseUrl) {
- // urlParts[1] = protocol://hostname/ OR /
- // urlParts[2] = / if path relative to host base
- // urlParts[3] = directories
- // urlParts[4] = filename
- // urlParts[5] = parameters
- var urlPartsRegex = /^((?:[a-z-]+:)?\/{2}(?:[^\/\?#]*\/)|([\/\\]))?((?:[^\/\\\?#]*[\/\\])*)([^\/\\\?#]*)([#\?].*)?$/i;
- var urlParts = url.match(urlPartsRegex);
- var returner = {};
- var rawDirectories = [];
- var directories = [];
- var i;
- var baseUrlParts;
-
- if (!urlParts) {
- throw new Error("Could not parse sheet href - '".concat(url, "'"));
- } // Stylesheets in IE don't always return the full path
-
-
- if (baseUrl && (!urlParts[1] || urlParts[2])) {
- baseUrlParts = baseUrl.match(urlPartsRegex);
-
- if (!baseUrlParts) {
- throw new Error("Could not parse page url - '".concat(baseUrl, "'"));
- }
-
- urlParts[1] = urlParts[1] || baseUrlParts[1] || '';
-
- if (!urlParts[2]) {
- urlParts[3] = baseUrlParts[3] + urlParts[3];
- }
- }
-
- if (urlParts[3]) {
- rawDirectories = urlParts[3].replace(/\\/g, '/').split('/'); // collapse '..' and skip '.'
-
- for (i = 0; i < rawDirectories.length; i++) {
- if (rawDirectories[i] === '..') {
- directories.pop();
- } else if (rawDirectories[i] !== '.') {
- directories.push(rawDirectories[i]);
- }
- }
- }
-
- returner.hostPart = urlParts[1];
- returner.directories = directories;
- returner.rawPath = (urlParts[1] || '') + rawDirectories.join('/');
- returner.path = (urlParts[1] || '') + directories.join('/');
- returner.filename = urlParts[4];
- returner.fileUrl = returner.path + (urlParts[4] || '');
- returner.url = returner.fileUrl + (urlParts[5] || '');
- return returner;
- }
- }]);
-
- return AbstractFileManager;
- }();
-
- var AbstractPluginLoader =
- /*#__PURE__*/
- function () {
- function AbstractPluginLoader() {
- _classCallCheck(this, AbstractPluginLoader);
-
- // Implemented by Node.js plugin loader
- this.require = function () {
- return null;
- };
- }
-
- _createClass(AbstractPluginLoader, [{
- key: "evalPlugin",
- value: function evalPlugin(contents, context, imports, pluginOptions, fileInfo) {
- var loader;
- var registry;
- var pluginObj;
- var localModule;
- var pluginManager;
- var filename;
- var result;
- pluginManager = context.pluginManager;
-
- if (fileInfo) {
- if (typeof fileInfo === 'string') {
- filename = fileInfo;
- } else {
- filename = fileInfo.filename;
- }
- }
-
- var shortname = new this.less.FileManager().extractUrlParts(filename).filename;
-
- if (filename) {
- pluginObj = pluginManager.get(filename);
-
- if (pluginObj) {
- result = this.trySetOptions(pluginObj, filename, shortname, pluginOptions);
-
- if (result) {
- return result;
- }
-
- try {
- if (pluginObj.use) {
- pluginObj.use.call(this.context, pluginObj);
- }
- } catch (e) {
- e.message = e.message || 'Error during @plugin call';
- return new LessError(e, imports, filename);
- }
-
- return pluginObj;
- }
- }
-
- localModule = {
- exports: {},
- pluginManager: pluginManager,
- fileInfo: fileInfo
- };
- registry = functionRegistry.create();
-
- var registerPlugin = function registerPlugin(obj) {
- pluginObj = obj;
- };
-
- try {
- loader = new Function('module', 'require', 'registerPlugin', 'functions', 'tree', 'less', 'fileInfo', contents);
- loader(localModule, this.require(filename), registerPlugin, registry, this.less.tree, this.less, fileInfo);
- } catch (e) {
- return new LessError(e, imports, filename);
- }
-
- if (!pluginObj) {
- pluginObj = localModule.exports;
- }
-
- pluginObj = this.validatePlugin(pluginObj, filename, shortname);
-
- if (pluginObj instanceof LessError) {
- return pluginObj;
- }
-
- if (pluginObj) {
- pluginObj.imports = imports;
- pluginObj.filename = filename; // For < 3.x (or unspecified minVersion) - setOptions() before install()
-
- if (!pluginObj.minVersion || this.compareVersion('3.0.0', pluginObj.minVersion) < 0) {
- result = this.trySetOptions(pluginObj, filename, shortname, pluginOptions);
-
- if (result) {
- return result;
- }
- } // Run on first load
-
-
- pluginManager.addPlugin(pluginObj, fileInfo.filename, registry);
- pluginObj.functions = registry.getLocalFunctions(); // Need to call setOptions again because the pluginObj might have functions
-
- result = this.trySetOptions(pluginObj, filename, shortname, pluginOptions);
-
- if (result) {
- return result;
- } // Run every @plugin call
-
-
- try {
- if (pluginObj.use) {
- pluginObj.use.call(this.context, pluginObj);
- }
- } catch (e) {
- e.message = e.message || 'Error during @plugin call';
- return new LessError(e, imports, filename);
- }
- } else {
- return new LessError({
- message: 'Not a valid plugin'
- }, imports, filename);
- }
-
- return pluginObj;
- }
- }, {
- key: "trySetOptions",
- value: function trySetOptions(plugin, filename, name, options) {
- if (options && !plugin.setOptions) {
- return new LessError({
- message: "Options have been provided but the plugin ".concat(name, " does not support any options.")
- });
- }
-
- try {
- plugin.setOptions && plugin.setOptions(options);
- } catch (e) {
- return new LessError(e);
- }
- }
- }, {
- key: "validatePlugin",
- value: function validatePlugin(plugin, filename, name) {
- if (plugin) {
- // support plugins being a function
- // so that the plugin can be more usable programmatically
- if (typeof plugin === 'function') {
- plugin = new plugin();
- }
-
- if (plugin.minVersion) {
- if (this.compareVersion(plugin.minVersion, this.less.version) < 0) {
- return new LessError({
- message: "Plugin ".concat(name, " requires version ").concat(this.versionToString(plugin.minVersion))
- });
- }
- }
-
- return plugin;
- }
-
- return null;
- }
- }, {
- key: "compareVersion",
- value: function compareVersion(aVersion, bVersion) {
- if (typeof aVersion === 'string') {
- aVersion = aVersion.match(/^(\d+)\.?(\d+)?\.?(\d+)?/);
- aVersion.shift();
- }
-
- for (var i = 0; i < aVersion.length; i++) {
- if (aVersion[i] !== bVersion[i]) {
- return parseInt(aVersion[i]) > parseInt(bVersion[i]) ? -1 : 1;
- }
- }
-
- return 0;
- }
- }, {
- key: "versionToString",
- value: function versionToString(version) {
- var versionString = '';
-
- for (var i = 0; i < version.length; i++) {
- versionString += (versionString ? '.' : '') + version[i];
- }
-
- return versionString;
- }
- }, {
- key: "printUsage",
- value: function printUsage(plugins) {
- for (var i = 0; i < plugins.length; i++) {
- var plugin = plugins[i];
-
- if (plugin.printUsage) {
- plugin.printUsage();
- }
- }
- }
- }]);
-
- return AbstractPluginLoader;
- }();
-
- var _visitArgs = {
- visitDeeper: true
- };
- var _hasIndexed = false;
-
- function _noop(node) {
- return node;
- }
-
- function indexNodeTypes(parent, ticker) {
- // add .typeIndex to tree node types for lookup table
- var key;
- var child;
-
- for (key in parent) {
- /* eslint guard-for-in: 0 */
- child = parent[key];
-
- switch (_typeof(child)) {
- case 'function':
- // ignore bound functions directly on tree which do not have a prototype
- // or aren't nodes
- if (child.prototype && child.prototype.type) {
- child.prototype.typeIndex = ticker++;
- }
-
- break;
-
- case 'object':
- ticker = indexNodeTypes(child, ticker);
- break;
- }
- }
-
- return ticker;
- }
-
- var Visitor =
- /*#__PURE__*/
- function () {
- function Visitor(implementation) {
- _classCallCheck(this, Visitor);
-
- this._implementation = implementation;
- this._visitInCache = {};
- this._visitOutCache = {};
-
- if (!_hasIndexed) {
- indexNodeTypes(tree, 1);
- _hasIndexed = true;
- }
- }
-
- _createClass(Visitor, [{
- key: "visit",
- value: function visit(node) {
- if (!node) {
- return node;
- }
-
- var nodeTypeIndex = node.typeIndex;
-
- if (!nodeTypeIndex) {
- // MixinCall args aren't a node type?
- if (node.value && node.value.typeIndex) {
- this.visit(node.value);
- }
-
- return node;
- }
-
- var impl = this._implementation;
- var func = this._visitInCache[nodeTypeIndex];
- var funcOut = this._visitOutCache[nodeTypeIndex];
- var visitArgs = _visitArgs;
- var fnName;
- visitArgs.visitDeeper = true;
-
- if (!func) {
- fnName = "visit".concat(node.type);
- func = impl[fnName] || _noop;
- funcOut = impl["".concat(fnName, "Out")] || _noop;
- this._visitInCache[nodeTypeIndex] = func;
- this._visitOutCache[nodeTypeIndex] = funcOut;
- }
-
- if (func !== _noop) {
- var newNode = func.call(impl, node, visitArgs);
-
- if (node && impl.isReplacing) {
- node = newNode;
- }
- }
-
- if (visitArgs.visitDeeper && node && node.accept) {
- node.accept(this);
- }
-
- if (funcOut != _noop) {
- funcOut.call(impl, node);
- }
-
- return node;
- }
- }, {
- key: "visitArray",
- value: function visitArray(nodes, nonReplacing) {
- if (!nodes) {
- return nodes;
- }
-
- var cnt = nodes.length;
- var i; // Non-replacing
-
- if (nonReplacing || !this._implementation.isReplacing) {
- for (i = 0; i < cnt; i++) {
- this.visit(nodes[i]);
- }
-
- return nodes;
- } // Replacing
-
-
- var out = [];
-
- for (i = 0; i < cnt; i++) {
- var evald = this.visit(nodes[i]);
-
- if (evald === undefined) {
- continue;
- }
-
- if (!evald.splice) {
- out.push(evald);
- } else if (evald.length) {
- this.flatten(evald, out);
- }
- }
-
- return out;
- }
- }, {
- key: "flatten",
- value: function flatten(arr, out) {
- if (!out) {
- out = [];
- }
-
- var cnt;
- var i;
- var item;
- var nestedCnt;
- var j;
- var nestedItem;
-
- for (i = 0, cnt = arr.length; i < cnt; i++) {
- item = arr[i];
-
- if (item === undefined) {
- continue;
- }
-
- if (!item.splice) {
- out.push(item);
- continue;
- }
-
- for (j = 0, nestedCnt = item.length; j < nestedCnt; j++) {
- nestedItem = item[j];
-
- if (nestedItem === undefined) {
- continue;
- }
-
- if (!nestedItem.splice) {
- out.push(nestedItem);
- } else if (nestedItem.length) {
- this.flatten(nestedItem, out);
- }
- }
- }
-
- return out;
- }
- }]);
-
- return Visitor;
- }();
-
- var ImportSequencer =
- /*#__PURE__*/
- function () {
- function ImportSequencer(onSequencerEmpty) {
- _classCallCheck(this, ImportSequencer);
-
- this.imports = [];
- this.variableImports = [];
- this._onSequencerEmpty = onSequencerEmpty;
- this._currentDepth = 0;
- }
-
- _createClass(ImportSequencer, [{
- key: "addImport",
- value: function addImport(callback) {
- var importSequencer = this;
- var importItem = {
- callback: callback,
- args: null,
- isReady: false
- };
- this.imports.push(importItem);
- return function () {
- for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
- args[_key] = arguments[_key];
- }
-
- importItem.args = Array.prototype.slice.call(args, 0);
- importItem.isReady = true;
- importSequencer.tryRun();
- };
- }
- }, {
- key: "addVariableImport",
- value: function addVariableImport(callback) {
- this.variableImports.push(callback);
- }
- }, {
- key: "tryRun",
- value: function tryRun() {
- this._currentDepth++;
-
- try {
- while (true) {
- while (this.imports.length > 0) {
- var importItem = this.imports[0];
-
- if (!importItem.isReady) {
- return;
- }
-
- this.imports = this.imports.slice(1);
- importItem.callback.apply(null, importItem.args);
- }
-
- if (this.variableImports.length === 0) {
- break;
- }
-
- var variableImport = this.variableImports[0];
- this.variableImports = this.variableImports.slice(1);
- variableImport();
- }
- } finally {
- this._currentDepth--;
- }
-
- if (this._currentDepth === 0 && this._onSequencerEmpty) {
- this._onSequencerEmpty();
- }
- }
- }]);
-
- return ImportSequencer;
- }();
-
- var ImportVisitor = function ImportVisitor(importer, finish) {
- this._visitor = new Visitor(this);
- this._importer = importer;
- this._finish = finish;
- this.context = new contexts.Eval();
- this.importCount = 0;
- this.onceFileDetectionMap = {};
- this.recursionDetector = {};
- this._sequencer = new ImportSequencer(this._onSequencerEmpty.bind(this));
- };
-
- ImportVisitor.prototype = {
- isReplacing: false,
- run: function run(root) {
- try {
- // process the contents
- this._visitor.visit(root);
- } catch (e) {
- this.error = e;
- }
-
- this.isFinished = true;
-
- this._sequencer.tryRun();
- },
- _onSequencerEmpty: function _onSequencerEmpty() {
- if (!this.isFinished) {
- return;
- }
-
- this._finish(this.error);
- },
- visitImport: function visitImport(importNode, visitArgs) {
- var inlineCSS = importNode.options.inline;
-
- if (!importNode.css || inlineCSS) {
- var context = new contexts.Eval(this.context, copyArray(this.context.frames));
- var importParent = context.frames[0];
- this.importCount++;
-
- if (importNode.isVariableImport()) {
- this._sequencer.addVariableImport(this.processImportNode.bind(this, importNode, context, importParent));
- } else {
- this.processImportNode(importNode, context, importParent);
- }
- }
-
- visitArgs.visitDeeper = false;
- },
- processImportNode: function processImportNode(importNode, context, importParent) {
- var evaldImportNode;
- var inlineCSS = importNode.options.inline;
-
- try {
- evaldImportNode = importNode.evalForImport(context);
- } catch (e) {
- if (!e.filename) {
- e.index = importNode.getIndex();
- e.filename = importNode.fileInfo().filename;
- } // attempt to eval properly and treat as css
-
-
- importNode.css = true; // if that fails, this error will be thrown
-
- importNode.error = e;
- }
-
- if (evaldImportNode && (!evaldImportNode.css || inlineCSS)) {
- if (evaldImportNode.options.multiple) {
- context.importMultiple = true;
- } // try appending if we haven't determined if it is css or not
-
-
- var tryAppendLessExtension = evaldImportNode.css === undefined;
-
- for (var i = 0; i < importParent.rules.length; i++) {
- if (importParent.rules[i] === importNode) {
- importParent.rules[i] = evaldImportNode;
- break;
- }
- }
-
- var onImported = this.onImported.bind(this, evaldImportNode, context);
-
- var sequencedOnImported = this._sequencer.addImport(onImported);
-
- this._importer.push(evaldImportNode.getPath(), tryAppendLessExtension, evaldImportNode.fileInfo(), evaldImportNode.options, sequencedOnImported);
- } else {
- this.importCount--;
-
- if (this.isFinished) {
- this._sequencer.tryRun();
- }
- }
- },
- onImported: function onImported(importNode, context, e, root, importedAtRoot, fullPath) {
- if (e) {
- if (!e.filename) {
- e.index = importNode.getIndex();
- e.filename = importNode.fileInfo().filename;
- }
-
- this.error = e;
- }
-
- var importVisitor = this;
- var inlineCSS = importNode.options.inline;
- var isPlugin = importNode.options.isPlugin;
- var isOptional = importNode.options.optional;
- var duplicateImport = importedAtRoot || fullPath in importVisitor.recursionDetector;
-
- if (!context.importMultiple) {
- if (duplicateImport) {
- importNode.skip = true;
- } else {
- importNode.skip = function () {
- if (fullPath in importVisitor.onceFileDetectionMap) {
- return true;
- }
-
- importVisitor.onceFileDetectionMap[fullPath] = true;
- return false;
- };
- }
- }
-
- if (!fullPath && isOptional) {
- importNode.skip = true;
- }
-
- if (root) {
- importNode.root = root;
- importNode.importedFilename = fullPath;
-
- if (!inlineCSS && !isPlugin && (context.importMultiple || !duplicateImport)) {
- importVisitor.recursionDetector[fullPath] = true;
- var oldContext = this.context;
- this.context = context;
-
- try {
- this._visitor.visit(root);
- } catch (e) {
- this.error = e;
- }
-
- this.context = oldContext;
- }
- }
-
- importVisitor.importCount--;
-
- if (importVisitor.isFinished) {
- importVisitor._sequencer.tryRun();
- }
- },
- visitDeclaration: function visitDeclaration(declNode, visitArgs) {
- if (declNode.value.type === 'DetachedRuleset') {
- this.context.frames.unshift(declNode);
- } else {
- visitArgs.visitDeeper = false;
- }
- },
- visitDeclarationOut: function visitDeclarationOut(declNode) {
- if (declNode.value.type === 'DetachedRuleset') {
- this.context.frames.shift();
- }
- },
- visitAtRule: function visitAtRule(atRuleNode, visitArgs) {
- this.context.frames.unshift(atRuleNode);
- },
- visitAtRuleOut: function visitAtRuleOut(atRuleNode) {
- this.context.frames.shift();
- },
- visitMixinDefinition: function visitMixinDefinition(mixinDefinitionNode, visitArgs) {
- this.context.frames.unshift(mixinDefinitionNode);
- },
- visitMixinDefinitionOut: function visitMixinDefinitionOut(mixinDefinitionNode) {
- this.context.frames.shift();
- },
- visitRuleset: function visitRuleset(rulesetNode, visitArgs) {
- this.context.frames.unshift(rulesetNode);
- },
- visitRulesetOut: function visitRulesetOut(rulesetNode) {
- this.context.frames.shift();
- },
- visitMedia: function visitMedia(mediaNode, visitArgs) {
- this.context.frames.unshift(mediaNode.rules[0]);
- },
- visitMediaOut: function visitMediaOut(mediaNode) {
- this.context.frames.shift();
- }
- };
-
- var SetTreeVisibilityVisitor =
- /*#__PURE__*/
- function () {
- function SetTreeVisibilityVisitor(visible) {
- _classCallCheck(this, SetTreeVisibilityVisitor);
-
- this.visible = visible;
- }
-
- _createClass(SetTreeVisibilityVisitor, [{
- key: "run",
- value: function run(root) {
- this.visit(root);
- }
- }, {
- key: "visitArray",
- value: function visitArray(nodes) {
- if (!nodes) {
- return nodes;
- }
-
- var cnt = nodes.length;
- var i;
-
- for (i = 0; i < cnt; i++) {
- this.visit(nodes[i]);
- }
-
- return nodes;
- }
- }, {
- key: "visit",
- value: function visit(node) {
- if (!node) {
- return node;
- }
-
- if (node.constructor === Array) {
- return this.visitArray(node);
- }
-
- if (!node.blocksVisibility || node.blocksVisibility()) {
- return node;
- }
-
- if (this.visible) {
- node.ensureVisibility();
- } else {
- node.ensureInvisibility();
- }
-
- node.accept(this);
- return node;
- }
- }]);
-
- return SetTreeVisibilityVisitor;
- }();
-
- /* jshint loopfunc:true */
-
- var ExtendFinderVisitor =
- /*#__PURE__*/
- function () {
- function ExtendFinderVisitor() {
- _classCallCheck(this, ExtendFinderVisitor);
-
- this._visitor = new Visitor(this);
- this.contexts = [];
- this.allExtendsStack = [[]];
- }
-
- _createClass(ExtendFinderVisitor, [{
- key: "run",
- value: function run(root) {
- root = this._visitor.visit(root);
- root.allExtends = this.allExtendsStack[0];
- return root;
- }
- }, {
- key: "visitDeclaration",
- value: function visitDeclaration(declNode, visitArgs) {
- visitArgs.visitDeeper = false;
- }
- }, {
- key: "visitMixinDefinition",
- value: function visitMixinDefinition(mixinDefinitionNode, visitArgs) {
- visitArgs.visitDeeper = false;
- }
- }, {
- key: "visitRuleset",
- value: function visitRuleset(rulesetNode, visitArgs) {
- if (rulesetNode.root) {
- return;
- }
-
- var i;
- var j;
- var extend;
- var allSelectorsExtendList = [];
- var extendList; // get &:extend(.a); rules which apply to all selectors in this ruleset
-
- var rules = rulesetNode.rules;
- var ruleCnt = rules ? rules.length : 0;
-
- for (i = 0; i < ruleCnt; i++) {
- if (rulesetNode.rules[i] instanceof tree.Extend) {
- allSelectorsExtendList.push(rules[i]);
- rulesetNode.extendOnEveryPath = true;
- }
- } // now find every selector and apply the extends that apply to all extends
- // and the ones which apply to an individual extend
-
-
- var paths = rulesetNode.paths;
-
- for (i = 0; i < paths.length; i++) {
- var selectorPath = paths[i];
- var selector = selectorPath[selectorPath.length - 1];
- var selExtendList = selector.extendList;
- extendList = selExtendList ? copyArray(selExtendList).concat(allSelectorsExtendList) : allSelectorsExtendList;
-
- if (extendList) {
- extendList = extendList.map(function (allSelectorsExtend) {
- return allSelectorsExtend.clone();
- });
- }
-
- for (j = 0; j < extendList.length; j++) {
- this.foundExtends = true;
- extend = extendList[j];
- extend.findSelfSelectors(selectorPath);
- extend.ruleset = rulesetNode;
-
- if (j === 0) {
- extend.firstExtendOnThisSelectorPath = true;
- }
-
- this.allExtendsStack[this.allExtendsStack.length - 1].push(extend);
- }
- }
-
- this.contexts.push(rulesetNode.selectors);
- }
- }, {
- key: "visitRulesetOut",
- value: function visitRulesetOut(rulesetNode) {
- if (!rulesetNode.root) {
- this.contexts.length = this.contexts.length - 1;
- }
- }
- }, {
- key: "visitMedia",
- value: function visitMedia(mediaNode, visitArgs) {
- mediaNode.allExtends = [];
- this.allExtendsStack.push(mediaNode.allExtends);
- }
- }, {
- key: "visitMediaOut",
- value: function visitMediaOut(mediaNode) {
- this.allExtendsStack.length = this.allExtendsStack.length - 1;
- }
- }, {
- key: "visitAtRule",
- value: function visitAtRule(atRuleNode, visitArgs) {
- atRuleNode.allExtends = [];
- this.allExtendsStack.push(atRuleNode.allExtends);
- }
- }, {
- key: "visitAtRuleOut",
- value: function visitAtRuleOut(atRuleNode) {
- this.allExtendsStack.length = this.allExtendsStack.length - 1;
- }
- }]);
-
- return ExtendFinderVisitor;
- }();
-
- var ProcessExtendsVisitor =
- /*#__PURE__*/
- function () {
- function ProcessExtendsVisitor() {
- _classCallCheck(this, ProcessExtendsVisitor);
-
- this._visitor = new Visitor(this);
- }
-
- _createClass(ProcessExtendsVisitor, [{
- key: "run",
- value: function run(root) {
- var extendFinder = new ExtendFinderVisitor();
- this.extendIndices = {};
- extendFinder.run(root);
-
- if (!extendFinder.foundExtends) {
- return root;
- }
-
- root.allExtends = root.allExtends.concat(this.doExtendChaining(root.allExtends, root.allExtends));
- this.allExtendsStack = [root.allExtends];
-
- var newRoot = this._visitor.visit(root);
-
- this.checkExtendsForNonMatched(root.allExtends);
- return newRoot;
- }
- }, {
- key: "checkExtendsForNonMatched",
- value: function checkExtendsForNonMatched(extendList) {
- var indices = this.extendIndices;
- extendList.filter(function (extend) {
- return !extend.hasFoundMatches && extend.parent_ids.length == 1;
- }).forEach(function (extend) {
- var selector = '_unknown_';
-
- try {
- selector = extend.selector.toCSS({});
- } catch (_) {}
-
- if (!indices["".concat(extend.index, " ").concat(selector)]) {
- indices["".concat(extend.index, " ").concat(selector)] = true;
- logger.warn("extend '".concat(selector, "' has no matches"));
- }
- });
- }
- }, {
- key: "doExtendChaining",
- value: function doExtendChaining(extendsList, extendsListTarget, iterationCount) {
- //
- // chaining is different from normal extension.. if we extend an extend then we are not just copying, altering
- // and pasting the selector we would do normally, but we are also adding an extend with the same target selector
- // this means this new extend can then go and alter other extends
- //
- // this method deals with all the chaining work - without it, extend is flat and doesn't work on other extend selectors
- // this is also the most expensive.. and a match on one selector can cause an extension of a selector we had already
- // processed if we look at each selector at a time, as is done in visitRuleset
- var extendIndex;
- var targetExtendIndex;
- var matches;
- var extendsToAdd = [];
- var newSelector;
- var extendVisitor = this;
- var selectorPath;
- var extend;
- var targetExtend;
- var newExtend;
- iterationCount = iterationCount || 0; // loop through comparing every extend with every target extend.
- // a target extend is the one on the ruleset we are looking at copy/edit/pasting in place
- // e.g. .a:extend(.b) {} and .b:extend(.c) {} then the first extend extends the second one
- // and the second is the target.
- // the separation into two lists allows us to process a subset of chains with a bigger set, as is the
- // case when processing media queries
-
- for (extendIndex = 0; extendIndex < extendsList.length; extendIndex++) {
- for (targetExtendIndex = 0; targetExtendIndex < extendsListTarget.length; targetExtendIndex++) {
- extend = extendsList[extendIndex];
- targetExtend = extendsListTarget[targetExtendIndex]; // look for circular references
-
- if (extend.parent_ids.indexOf(targetExtend.object_id) >= 0) {
- continue;
- } // find a match in the target extends self selector (the bit before :extend)
-
-
- selectorPath = [targetExtend.selfSelectors[0]];
- matches = extendVisitor.findMatch(extend, selectorPath);
-
- if (matches.length) {
- extend.hasFoundMatches = true; // we found a match, so for each self selector..
-
- extend.selfSelectors.forEach(function (selfSelector) {
- var info = targetExtend.visibilityInfo(); // process the extend as usual
-
- newSelector = extendVisitor.extendSelector(matches, selectorPath, selfSelector, extend.isVisible()); // but now we create a new extend from it
-
- newExtend = new tree.Extend(targetExtend.selector, targetExtend.option, 0, targetExtend.fileInfo(), info);
- newExtend.selfSelectors = newSelector; // add the extend onto the list of extends for that selector
-
- newSelector[newSelector.length - 1].extendList = [newExtend]; // record that we need to add it.
-
- extendsToAdd.push(newExtend);
- newExtend.ruleset = targetExtend.ruleset; // remember its parents for circular references
-
- newExtend.parent_ids = newExtend.parent_ids.concat(targetExtend.parent_ids, extend.parent_ids); // only process the selector once.. if we have :extend(.a,.b) then multiple
- // extends will look at the same selector path, so when extending
- // we know that any others will be duplicates in terms of what is added to the css
-
- if (targetExtend.firstExtendOnThisSelectorPath) {
- newExtend.firstExtendOnThisSelectorPath = true;
- targetExtend.ruleset.paths.push(newSelector);
- }
- });
- }
- }
- }
-
- if (extendsToAdd.length) {
- // try to detect circular references to stop a stack overflow.
- // may no longer be needed.
- this.extendChainCount++;
-
- if (iterationCount > 100) {
- var selectorOne = '{unable to calculate}';
- var selectorTwo = '{unable to calculate}';
-
- try {
- selectorOne = extendsToAdd[0].selfSelectors[0].toCSS();
- selectorTwo = extendsToAdd[0].selector.toCSS();
- } catch (e) {}
-
- throw {
- message: "extend circular reference detected. One of the circular extends is currently:".concat(selectorOne, ":extend(").concat(selectorTwo, ")")
- };
- } // now process the new extends on the existing rules so that we can handle a extending b extending c extending
- // d extending e...
-
-
- return extendsToAdd.concat(extendVisitor.doExtendChaining(extendsToAdd, extendsListTarget, iterationCount + 1));
- } else {
- return extendsToAdd;
- }
- }
- }, {
- key: "visitDeclaration",
- value: function visitDeclaration(ruleNode, visitArgs) {
- visitArgs.visitDeeper = false;
- }
- }, {
- key: "visitMixinDefinition",
- value: function visitMixinDefinition(mixinDefinitionNode, visitArgs) {
- visitArgs.visitDeeper = false;
- }
- }, {
- key: "visitSelector",
- value: function visitSelector(selectorNode, visitArgs) {
- visitArgs.visitDeeper = false;
- }
- }, {
- key: "visitRuleset",
- value: function visitRuleset(rulesetNode, visitArgs) {
- if (rulesetNode.root) {
- return;
- }
-
- var matches;
- var pathIndex;
- var extendIndex;
- var allExtends = this.allExtendsStack[this.allExtendsStack.length - 1];
- var selectorsToAdd = [];
- var extendVisitor = this;
- var selectorPath; // look at each selector path in the ruleset, find any extend matches and then copy, find and replace
-
- for (extendIndex = 0; extendIndex < allExtends.length; extendIndex++) {
- for (pathIndex = 0; pathIndex < rulesetNode.paths.length; pathIndex++) {
- selectorPath = rulesetNode.paths[pathIndex]; // extending extends happens initially, before the main pass
-
- if (rulesetNode.extendOnEveryPath) {
- continue;
- }
-
- var extendList = selectorPath[selectorPath.length - 1].extendList;
-
- if (extendList && extendList.length) {
- continue;
- }
-
- matches = this.findMatch(allExtends[extendIndex], selectorPath);
-
- if (matches.length) {
- allExtends[extendIndex].hasFoundMatches = true;
- allExtends[extendIndex].selfSelectors.forEach(function (selfSelector) {
- var extendedSelectors;
- extendedSelectors = extendVisitor.extendSelector(matches, selectorPath, selfSelector, allExtends[extendIndex].isVisible());
- selectorsToAdd.push(extendedSelectors);
- });
- }
- }
- }
-
- rulesetNode.paths = rulesetNode.paths.concat(selectorsToAdd);
- }
- }, {
- key: "findMatch",
- value: function findMatch(extend, haystackSelectorPath) {
- //
- // look through the haystack selector path to try and find the needle - extend.selector
- // returns an array of selector matches that can then be replaced
- //
- var haystackSelectorIndex;
- var hackstackSelector;
- var hackstackElementIndex;
- var haystackElement;
- var targetCombinator;
- var i;
- var extendVisitor = this;
- var needleElements = extend.selector.elements;
- var potentialMatches = [];
- var potentialMatch;
- var matches = []; // loop through the haystack elements
-
- for (haystackSelectorIndex = 0; haystackSelectorIndex < haystackSelectorPath.length; haystackSelectorIndex++) {
- hackstackSelector = haystackSelectorPath[haystackSelectorIndex];
-
- for (hackstackElementIndex = 0; hackstackElementIndex < hackstackSelector.elements.length; hackstackElementIndex++) {
- haystackElement = hackstackSelector.elements[hackstackElementIndex]; // if we allow elements before our match we can add a potential match every time. otherwise only at the first element.
-
- if (extend.allowBefore || haystackSelectorIndex === 0 && hackstackElementIndex === 0) {
- potentialMatches.push({
- pathIndex: haystackSelectorIndex,
- index: hackstackElementIndex,
- matched: 0,
- initialCombinator: haystackElement.combinator
- });
- }
-
- for (i = 0; i < potentialMatches.length; i++) {
- potentialMatch = potentialMatches[i]; // selectors add " " onto the first element. When we use & it joins the selectors together, but if we don't
- // then each selector in haystackSelectorPath has a space before it added in the toCSS phase. so we need to
- // work out what the resulting combinator will be
-
- targetCombinator = haystackElement.combinator.value;
-
- if (targetCombinator === '' && hackstackElementIndex === 0) {
- targetCombinator = ' ';
- } // if we don't match, null our match to indicate failure
-
-
- if (!extendVisitor.isElementValuesEqual(needleElements[potentialMatch.matched].value, haystackElement.value) || potentialMatch.matched > 0 && needleElements[potentialMatch.matched].combinator.value !== targetCombinator) {
- potentialMatch = null;
- } else {
- potentialMatch.matched++;
- } // if we are still valid and have finished, test whether we have elements after and whether these are allowed
-
-
- if (potentialMatch) {
- potentialMatch.finished = potentialMatch.matched === needleElements.length;
-
- if (potentialMatch.finished && !extend.allowAfter && (hackstackElementIndex + 1 < hackstackSelector.elements.length || haystackSelectorIndex + 1 < haystackSelectorPath.length)) {
- potentialMatch = null;
- }
- } // if null we remove, if not, we are still valid, so either push as a valid match or continue
-
-
- if (potentialMatch) {
- if (potentialMatch.finished) {
- potentialMatch.length = needleElements.length;
- potentialMatch.endPathIndex = haystackSelectorIndex;
- potentialMatch.endPathElementIndex = hackstackElementIndex + 1; // index after end of match
-
- potentialMatches.length = 0; // we don't allow matches to overlap, so start matching again
-
- matches.push(potentialMatch);
- }
- } else {
- potentialMatches.splice(i, 1);
- i--;
- }
- }
- }
- }
-
- return matches;
- }
- }, {
- key: "isElementValuesEqual",
- value: function isElementValuesEqual(elementValue1, elementValue2) {
- if (typeof elementValue1 === 'string' || typeof elementValue2 === 'string') {
- return elementValue1 === elementValue2;
- }
-
- if (elementValue1 instanceof tree.Attribute) {
- if (elementValue1.op !== elementValue2.op || elementValue1.key !== elementValue2.key) {
- return false;
- }
-
- if (!elementValue1.value || !elementValue2.value) {
- if (elementValue1.value || elementValue2.value) {
- return false;
- }
-
- return true;
- }
-
- elementValue1 = elementValue1.value.value || elementValue1.value;
- elementValue2 = elementValue2.value.value || elementValue2.value;
- return elementValue1 === elementValue2;
- }
-
- elementValue1 = elementValue1.value;
- elementValue2 = elementValue2.value;
-
- if (elementValue1 instanceof tree.Selector) {
- if (!(elementValue2 instanceof tree.Selector) || elementValue1.elements.length !== elementValue2.elements.length) {
- return false;
- }
-
- for (var i = 0; i < elementValue1.elements.length; i++) {
- if (elementValue1.elements[i].combinator.value !== elementValue2.elements[i].combinator.value) {
- if (i !== 0 || (elementValue1.elements[i].combinator.value || ' ') !== (elementValue2.elements[i].combinator.value || ' ')) {
- return false;
- }
- }
-
- if (!this.isElementValuesEqual(elementValue1.elements[i].value, elementValue2.elements[i].value)) {
- return false;
- }
- }
-
- return true;
- }
-
- return false;
- }
- }, {
- key: "extendSelector",
- value: function extendSelector(matches, selectorPath, replacementSelector, isVisible) {
- // for a set of matches, replace each match with the replacement selector
- var currentSelectorPathIndex = 0;
- var currentSelectorPathElementIndex = 0;
- var path = [];
- var matchIndex;
- var selector;
- var firstElement;
- var match;
- var newElements;
-
- for (matchIndex = 0; matchIndex < matches.length; matchIndex++) {
- match = matches[matchIndex];
- selector = selectorPath[match.pathIndex];
- firstElement = new tree.Element(match.initialCombinator, replacementSelector.elements[0].value, replacementSelector.elements[0].isVariable, replacementSelector.elements[0].getIndex(), replacementSelector.elements[0].fileInfo());
-
- if (match.pathIndex > currentSelectorPathIndex && currentSelectorPathElementIndex > 0) {
- path[path.length - 1].elements = path[path.length - 1].elements.concat(selectorPath[currentSelectorPathIndex].elements.slice(currentSelectorPathElementIndex));
- currentSelectorPathElementIndex = 0;
- currentSelectorPathIndex++;
- }
-
- newElements = selector.elements.slice(currentSelectorPathElementIndex, match.index).concat([firstElement]).concat(replacementSelector.elements.slice(1));
-
- if (currentSelectorPathIndex === match.pathIndex && matchIndex > 0) {
- path[path.length - 1].elements = path[path.length - 1].elements.concat(newElements);
- } else {
- path = path.concat(selectorPath.slice(currentSelectorPathIndex, match.pathIndex));
- path.push(new tree.Selector(newElements));
- }
-
- currentSelectorPathIndex = match.endPathIndex;
- currentSelectorPathElementIndex = match.endPathElementIndex;
-
- if (currentSelectorPathElementIndex >= selectorPath[currentSelectorPathIndex].elements.length) {
- currentSelectorPathElementIndex = 0;
- currentSelectorPathIndex++;
- }
- }
-
- if (currentSelectorPathIndex < selectorPath.length && currentSelectorPathElementIndex > 0) {
- path[path.length - 1].elements = path[path.length - 1].elements.concat(selectorPath[currentSelectorPathIndex].elements.slice(currentSelectorPathElementIndex));
- currentSelectorPathIndex++;
- }
-
- path = path.concat(selectorPath.slice(currentSelectorPathIndex, selectorPath.length));
- path = path.map(function (currentValue) {
- // we can re-use elements here, because the visibility property matters only for selectors
- var derived = currentValue.createDerived(currentValue.elements);
-
- if (isVisible) {
- derived.ensureVisibility();
- } else {
- derived.ensureInvisibility();
- }
-
- return derived;
- });
- return path;
- }
- }, {
- key: "visitMedia",
- value: function visitMedia(mediaNode, visitArgs) {
- var newAllExtends = mediaNode.allExtends.concat(this.allExtendsStack[this.allExtendsStack.length - 1]);
- newAllExtends = newAllExtends.concat(this.doExtendChaining(newAllExtends, mediaNode.allExtends));
- this.allExtendsStack.push(newAllExtends);
- }
- }, {
- key: "visitMediaOut",
- value: function visitMediaOut(mediaNode) {
- var lastIndex = this.allExtendsStack.length - 1;
- this.allExtendsStack.length = lastIndex;
- }
- }, {
- key: "visitAtRule",
- value: function visitAtRule(atRuleNode, visitArgs) {
- var newAllExtends = atRuleNode.allExtends.concat(this.allExtendsStack[this.allExtendsStack.length - 1]);
- newAllExtends = newAllExtends.concat(this.doExtendChaining(newAllExtends, atRuleNode.allExtends));
- this.allExtendsStack.push(newAllExtends);
- }
- }, {
- key: "visitAtRuleOut",
- value: function visitAtRuleOut(atRuleNode) {
- var lastIndex = this.allExtendsStack.length - 1;
- this.allExtendsStack.length = lastIndex;
- }
- }]);
-
- return ProcessExtendsVisitor;
- }();
-
- var JoinSelectorVisitor =
- /*#__PURE__*/
- function () {
- function JoinSelectorVisitor() {
- _classCallCheck(this, JoinSelectorVisitor);
-
- this.contexts = [[]];
- this._visitor = new Visitor(this);
- }
-
- _createClass(JoinSelectorVisitor, [{
- key: "run",
- value: function run(root) {
- return this._visitor.visit(root);
- }
- }, {
- key: "visitDeclaration",
- value: function visitDeclaration(declNode, visitArgs) {
- visitArgs.visitDeeper = false;
- }
- }, {
- key: "visitMixinDefinition",
- value: function visitMixinDefinition(mixinDefinitionNode, visitArgs) {
- visitArgs.visitDeeper = false;
- }
- }, {
- key: "visitRuleset",
- value: function visitRuleset(rulesetNode, visitArgs) {
- var context = this.contexts[this.contexts.length - 1];
- var paths = [];
- var selectors;
- this.contexts.push(paths);
-
- if (!rulesetNode.root) {
- selectors = rulesetNode.selectors;
-
- if (selectors) {
- selectors = selectors.filter(function (selector) {
- return selector.getIsOutput();
- });
- rulesetNode.selectors = selectors.length ? selectors : selectors = null;
-
- if (selectors) {
- rulesetNode.joinSelectors(paths, context, selectors);
- }
- }
-
- if (!selectors) {
- rulesetNode.rules = null;
- }
-
- rulesetNode.paths = paths;
- }
- }
- }, {
- key: "visitRulesetOut",
- value: function visitRulesetOut(rulesetNode) {
- this.contexts.length = this.contexts.length - 1;
- }
- }, {
- key: "visitMedia",
- value: function visitMedia(mediaNode, visitArgs) {
- var context = this.contexts[this.contexts.length - 1];
- mediaNode.rules[0].root = context.length === 0 || context[0].multiMedia;
- }
- }, {
- key: "visitAtRule",
- value: function visitAtRule(atRuleNode, visitArgs) {
- var context = this.contexts[this.contexts.length - 1];
-
- if (atRuleNode.rules && atRuleNode.rules.length) {
- atRuleNode.rules[0].root = atRuleNode.isRooted || context.length === 0 || null;
- }
- }
- }]);
-
- return JoinSelectorVisitor;
- }();
-
- var CSSVisitorUtils =
- /*#__PURE__*/
- function () {
- function CSSVisitorUtils(context) {
- _classCallCheck(this, CSSVisitorUtils);
-
- this._visitor = new Visitor(this);
- this._context = context;
- }
-
- _createClass(CSSVisitorUtils, [{
- key: "containsSilentNonBlockedChild",
- value: function containsSilentNonBlockedChild(bodyRules) {
- var rule;
-
- if (!bodyRules) {
- return false;
- }
-
- for (var r = 0; r < bodyRules.length; r++) {
- rule = bodyRules[r];
-
- if (rule.isSilent && rule.isSilent(this._context) && !rule.blocksVisibility()) {
- // the atrule contains something that was referenced (likely by extend)
- // therefore it needs to be shown in output too
- return true;
- }
- }
-
- return false;
- }
- }, {
- key: "keepOnlyVisibleChilds",
- value: function keepOnlyVisibleChilds(owner) {
- if (owner && owner.rules) {
- owner.rules = owner.rules.filter(function (thing) {
- return thing.isVisible();
- });
- }
- }
- }, {
- key: "isEmpty",
- value: function isEmpty(owner) {
- return owner && owner.rules ? owner.rules.length === 0 : true;
- }
- }, {
- key: "hasVisibleSelector",
- value: function hasVisibleSelector(rulesetNode) {
- return rulesetNode && rulesetNode.paths ? rulesetNode.paths.length > 0 : false;
- }
- }, {
- key: "resolveVisibility",
- value: function resolveVisibility(node, originalRules) {
- if (!node.blocksVisibility()) {
- if (this.isEmpty(node) && !this.containsSilentNonBlockedChild(originalRules)) {
- return;
- }
-
- return node;
- }
-
- var compiledRulesBody = node.rules[0];
- this.keepOnlyVisibleChilds(compiledRulesBody);
-
- if (this.isEmpty(compiledRulesBody)) {
- return;
- }
-
- node.ensureVisibility();
- node.removeVisibilityBlock();
- return node;
- }
- }, {
- key: "isVisibleRuleset",
- value: function isVisibleRuleset(rulesetNode) {
- if (rulesetNode.firstRoot) {
- return true;
- }
-
- if (this.isEmpty(rulesetNode)) {
- return false;
- }
-
- if (!rulesetNode.root && !this.hasVisibleSelector(rulesetNode)) {
- return false;
- }
-
- return true;
- }
- }]);
-
- return CSSVisitorUtils;
- }();
-
- var ToCSSVisitor = function ToCSSVisitor(context) {
- this._visitor = new Visitor(this);
- this._context = context;
- this.utils = new CSSVisitorUtils(context);
- };
-
- ToCSSVisitor.prototype = {
- isReplacing: true,
- run: function run(root) {
- return this._visitor.visit(root);
- },
- visitDeclaration: function visitDeclaration(declNode, visitArgs) {
- if (declNode.blocksVisibility() || declNode.variable) {
- return;
- }
-
- return declNode;
- },
- visitMixinDefinition: function visitMixinDefinition(mixinNode, visitArgs) {
- // mixin definitions do not get eval'd - this means they keep state
- // so we have to clear that state here so it isn't used if toCSS is called twice
- mixinNode.frames = [];
- },
- visitExtend: function visitExtend(extendNode, visitArgs) {},
- visitComment: function visitComment(commentNode, visitArgs) {
- if (commentNode.blocksVisibility() || commentNode.isSilent(this._context)) {
- return;
- }
-
- return commentNode;
- },
- visitMedia: function visitMedia(mediaNode, visitArgs) {
- var originalRules = mediaNode.rules[0].rules;
- mediaNode.accept(this._visitor);
- visitArgs.visitDeeper = false;
- return this.utils.resolveVisibility(mediaNode, originalRules);
- },
- visitImport: function visitImport(importNode, visitArgs) {
- if (importNode.blocksVisibility()) {
- return;
- }
-
- return importNode;
- },
- visitAtRule: function visitAtRule(atRuleNode, visitArgs) {
- if (atRuleNode.rules && atRuleNode.rules.length) {
- return this.visitAtRuleWithBody(atRuleNode, visitArgs);
- } else {
- return this.visitAtRuleWithoutBody(atRuleNode, visitArgs);
- }
- },
- visitAnonymous: function visitAnonymous(anonymousNode, visitArgs) {
- if (!anonymousNode.blocksVisibility()) {
- anonymousNode.accept(this._visitor);
- return anonymousNode;
- }
- },
- visitAtRuleWithBody: function visitAtRuleWithBody(atRuleNode, visitArgs) {
- // if there is only one nested ruleset and that one has no path, then it is
- // just fake ruleset
- function hasFakeRuleset(atRuleNode) {
- var bodyRules = atRuleNode.rules;
- return bodyRules.length === 1 && (!bodyRules[0].paths || bodyRules[0].paths.length === 0);
- }
-
- function getBodyRules(atRuleNode) {
- var nodeRules = atRuleNode.rules;
-
- if (hasFakeRuleset(atRuleNode)) {
- return nodeRules[0].rules;
- }
-
- return nodeRules;
- } // it is still true that it is only one ruleset in array
- // this is last such moment
- // process childs
-
-
- var originalRules = getBodyRules(atRuleNode);
- atRuleNode.accept(this._visitor);
- visitArgs.visitDeeper = false;
-
- if (!this.utils.isEmpty(atRuleNode)) {
- this._mergeRules(atRuleNode.rules[0].rules);
- }
-
- return this.utils.resolveVisibility(atRuleNode, originalRules);
- },
- visitAtRuleWithoutBody: function visitAtRuleWithoutBody(atRuleNode, visitArgs) {
- if (atRuleNode.blocksVisibility()) {
- return;
- }
-
- if (atRuleNode.name === '@charset') {
- // Only output the debug info together with subsequent @charset definitions
- // a comment (or @media statement) before the actual @charset atrule would
- // be considered illegal css as it has to be on the first line
- if (this.charset) {
- if (atRuleNode.debugInfo) {
- var comment = new tree.Comment("/* ".concat(atRuleNode.toCSS(this._context).replace(/\n/g, ''), " */\n"));
- comment.debugInfo = atRuleNode.debugInfo;
- return this._visitor.visit(comment);
- }
-
- return;
- }
-
- this.charset = true;
- }
-
- return atRuleNode;
- },
- checkValidNodes: function checkValidNodes(rules, isRoot) {
- if (!rules) {
- return;
- }
-
- for (var i = 0; i < rules.length; i++) {
- var ruleNode = rules[i];
-
- if (isRoot && ruleNode instanceof tree.Declaration && !ruleNode.variable) {
- throw {
- message: 'Properties must be inside selector blocks. They cannot be in the root',
- index: ruleNode.getIndex(),
- filename: ruleNode.fileInfo() && ruleNode.fileInfo().filename
- };
- }
-
- if (ruleNode instanceof tree.Call) {
- throw {
- message: "Function '".concat(ruleNode.name, "' is undefined"),
- index: ruleNode.getIndex(),
- filename: ruleNode.fileInfo() && ruleNode.fileInfo().filename
- };
- }
-
- if (ruleNode.type && !ruleNode.allowRoot) {
- throw {
- message: "".concat(ruleNode.type, " node returned by a function is not valid here"),
- index: ruleNode.getIndex(),
- filename: ruleNode.fileInfo() && ruleNode.fileInfo().filename
- };
- }
- }
- },
- visitRuleset: function visitRuleset(rulesetNode, visitArgs) {
- // at this point rulesets are nested into each other
- var rule;
- var rulesets = [];
- this.checkValidNodes(rulesetNode.rules, rulesetNode.firstRoot);
-
- if (!rulesetNode.root) {
- // remove invisible paths
- this._compileRulesetPaths(rulesetNode); // remove rulesets from this ruleset body and compile them separately
-
-
- var nodeRules = rulesetNode.rules;
- var nodeRuleCnt = nodeRules ? nodeRules.length : 0;
-
- for (var i = 0; i < nodeRuleCnt;) {
- rule = nodeRules[i];
-
- if (rule && rule.rules) {
- // visit because we are moving them out from being a child
- rulesets.push(this._visitor.visit(rule));
- nodeRules.splice(i, 1);
- nodeRuleCnt--;
- continue;
- }
-
- i++;
- } // accept the visitor to remove rules and refactor itself
- // then we can decide nogw whether we want it or not
- // compile body
-
-
- if (nodeRuleCnt > 0) {
- rulesetNode.accept(this._visitor);
- } else {
- rulesetNode.rules = null;
- }
-
- visitArgs.visitDeeper = false;
- } else {
- // if (! rulesetNode.root) {
- rulesetNode.accept(this._visitor);
- visitArgs.visitDeeper = false;
- }
-
- if (rulesetNode.rules) {
- this._mergeRules(rulesetNode.rules);
-
- this._removeDuplicateRules(rulesetNode.rules);
- } // now decide whether we keep the ruleset
-
-
- if (this.utils.isVisibleRuleset(rulesetNode)) {
- rulesetNode.ensureVisibility();
- rulesets.splice(0, 0, rulesetNode);
- }
-
- if (rulesets.length === 1) {
- return rulesets[0];
- }
-
- return rulesets;
- },
- _compileRulesetPaths: function _compileRulesetPaths(rulesetNode) {
- if (rulesetNode.paths) {
- rulesetNode.paths = rulesetNode.paths.filter(function (p) {
- var i;
-
- if (p[0].elements[0].combinator.value === ' ') {
- p[0].elements[0].combinator = new tree.Combinator('');
- }
-
- for (i = 0; i < p.length; i++) {
- if (p[i].isVisible() && p[i].getIsOutput()) {
- return true;
- }
- }
-
- return false;
- });
- }
- },
- _removeDuplicateRules: function _removeDuplicateRules(rules) {
- if (!rules) {
- return;
- } // remove duplicates
-
-
- var ruleCache = {};
- var ruleList;
- var rule;
- var i;
-
- for (i = rules.length - 1; i >= 0; i--) {
- rule = rules[i];
-
- if (rule instanceof tree.Declaration) {
- if (!ruleCache[rule.name]) {
- ruleCache[rule.name] = rule;
- } else {
- ruleList = ruleCache[rule.name];
-
- if (ruleList instanceof tree.Declaration) {
- ruleList = ruleCache[rule.name] = [ruleCache[rule.name].toCSS(this._context)];
- }
-
- var ruleCSS = rule.toCSS(this._context);
-
- if (ruleList.indexOf(ruleCSS) !== -1) {
- rules.splice(i, 1);
- } else {
- ruleList.push(ruleCSS);
- }
- }
- }
- }
- },
- _mergeRules: function _mergeRules(rules) {
- if (!rules) {
- return;
- }
-
- var groups = {};
- var groupsArr = [];
-
- for (var i = 0; i < rules.length; i++) {
- var rule = rules[i];
-
- if (rule.merge) {
- var key = rule.name;
- groups[key] ? rules.splice(i--, 1) : groupsArr.push(groups[key] = []);
- groups[key].push(rule);
- }
- }
-
- groupsArr.forEach(function (group) {
- if (group.length > 0) {
- var result = group[0];
- var space = [];
- var comma = [new tree.Expression(space)];
- group.forEach(function (rule) {
- if (rule.merge === '+' && space.length > 0) {
- comma.push(new tree.Expression(space = []));
- }
-
- space.push(rule.value);
- result.important = result.important || rule.important;
- });
- result.value = new tree.Value(comma);
- }
- });
- }
- };
-
- var visitors = {
- Visitor: Visitor,
- ImportVisitor: ImportVisitor,
- MarkVisibleSelectorsVisitor: SetTreeVisibilityVisitor,
- ExtendVisitor: ProcessExtendsVisitor,
- JoinSelectorVisitor: JoinSelectorVisitor,
- ToCSSVisitor: ToCSSVisitor
- };
-
- // Split the input into chunks.
- var chunker = (function (input, fail) {
- var len = input.length;
- var level = 0;
- var parenLevel = 0;
- var lastOpening;
- var lastOpeningParen;
- var lastMultiComment;
- var lastMultiCommentEndBrace;
- var chunks = [];
- var emitFrom = 0;
- var chunkerCurrentIndex;
- var currentChunkStartIndex;
- var cc;
- var cc2;
- var matched;
-
- function emitChunk(force) {
- var len = chunkerCurrentIndex - emitFrom;
-
- if (len < 512 && !force || !len) {
- return;
- }
-
- chunks.push(input.slice(emitFrom, chunkerCurrentIndex + 1));
- emitFrom = chunkerCurrentIndex + 1;
- }
-
- for (chunkerCurrentIndex = 0; chunkerCurrentIndex < len; chunkerCurrentIndex++) {
- cc = input.charCodeAt(chunkerCurrentIndex);
-
- if (cc >= 97 && cc <= 122 || cc < 34) {
- // a-z or whitespace
- continue;
- }
-
- switch (cc) {
- case 40:
- // (
- parenLevel++;
- lastOpeningParen = chunkerCurrentIndex;
- continue;
-
- case 41:
- // )
- if (--parenLevel < 0) {
- return fail('missing opening `(`', chunkerCurrentIndex);
- }
-
- continue;
-
- case 59:
- // ;
- if (!parenLevel) {
- emitChunk();
- }
-
- continue;
-
- case 123:
- // {
- level++;
- lastOpening = chunkerCurrentIndex;
- continue;
-
- case 125:
- // }
- if (--level < 0) {
- return fail('missing opening `{`', chunkerCurrentIndex);
- }
-
- if (!level && !parenLevel) {
- emitChunk();
- }
-
- continue;
-
- case 92:
- // \
- if (chunkerCurrentIndex < len - 1) {
- chunkerCurrentIndex++;
- continue;
- }
-
- return fail('unescaped `\\`', chunkerCurrentIndex);
-
- case 34:
- case 39:
- case 96:
- // ", ' and `
- matched = 0;
- currentChunkStartIndex = chunkerCurrentIndex;
-
- for (chunkerCurrentIndex = chunkerCurrentIndex + 1; chunkerCurrentIndex < len; chunkerCurrentIndex++) {
- cc2 = input.charCodeAt(chunkerCurrentIndex);
-
- if (cc2 > 96) {
- continue;
- }
-
- if (cc2 == cc) {
- matched = 1;
- break;
- }
-
- if (cc2 == 92) {
- // \
- if (chunkerCurrentIndex == len - 1) {
- return fail('unescaped `\\`', chunkerCurrentIndex);
- }
-
- chunkerCurrentIndex++;
- }
- }
-
- if (matched) {
- continue;
- }
-
- return fail("unmatched `".concat(String.fromCharCode(cc), "`"), currentChunkStartIndex);
-
- case 47:
- // /, check for comment
- if (parenLevel || chunkerCurrentIndex == len - 1) {
- continue;
- }
-
- cc2 = input.charCodeAt(chunkerCurrentIndex + 1);
-
- if (cc2 == 47) {
- // //, find lnfeed
- for (chunkerCurrentIndex = chunkerCurrentIndex + 2; chunkerCurrentIndex < len; chunkerCurrentIndex++) {
- cc2 = input.charCodeAt(chunkerCurrentIndex);
-
- if (cc2 <= 13 && (cc2 == 10 || cc2 == 13)) {
- break;
- }
- }
- } else if (cc2 == 42) {
- // /*, find */
- lastMultiComment = currentChunkStartIndex = chunkerCurrentIndex;
-
- for (chunkerCurrentIndex = chunkerCurrentIndex + 2; chunkerCurrentIndex < len - 1; chunkerCurrentIndex++) {
- cc2 = input.charCodeAt(chunkerCurrentIndex);
-
- if (cc2 == 125) {
- lastMultiCommentEndBrace = chunkerCurrentIndex;
- }
-
- if (cc2 != 42) {
- continue;
- }
-
- if (input.charCodeAt(chunkerCurrentIndex + 1) == 47) {
- break;
- }
- }
-
- if (chunkerCurrentIndex == len - 1) {
- return fail('missing closing `*/`', currentChunkStartIndex);
- }
-
- chunkerCurrentIndex++;
- }
-
- continue;
-
- case 42:
- // *, check for unmatched */
- if (chunkerCurrentIndex < len - 1 && input.charCodeAt(chunkerCurrentIndex + 1) == 47) {
- return fail('unmatched `/*`', chunkerCurrentIndex);
- }
-
- continue;
- }
- }
-
- if (level !== 0) {
- if (lastMultiComment > lastOpening && lastMultiCommentEndBrace > lastMultiComment) {
- return fail('missing closing `}` or `*/`', lastOpening);
- } else {
- return fail('missing closing `}`', lastOpening);
- }
- } else if (parenLevel !== 0) {
- return fail('missing closing `)`', lastOpeningParen);
- }
-
- emitChunk(true);
- return chunks;
- });
-
- var getParserInput = (function () {
- var // Less input string
- input;
- var // current chunk
- j;
- var // holds state for backtracking
- saveStack = [];
- var // furthest index the parser has gone to
- furthest;
- var // if this is furthest we got to, this is the probably cause
- furthestPossibleErrorMessage;
- var // chunkified input
- chunks;
- var // current chunk
- current;
- var // index of current chunk, in `input`
- currentPos;
- var parserInput = {};
- var CHARCODE_SPACE = 32;
- var CHARCODE_TAB = 9;
- var CHARCODE_LF = 10;
- var CHARCODE_CR = 13;
- var CHARCODE_PLUS = 43;
- var CHARCODE_COMMA = 44;
- var CHARCODE_FORWARD_SLASH = 47;
- var CHARCODE_9 = 57;
-
- function skipWhitespace(length) {
- var oldi = parserInput.i;
- var oldj = j;
- var curr = parserInput.i - currentPos;
- var endIndex = parserInput.i + current.length - curr;
- var mem = parserInput.i += length;
- var inp = input;
- var c;
- var nextChar;
- var comment;
-
- for (; parserInput.i < endIndex; parserInput.i++) {
- c = inp.charCodeAt(parserInput.i);
-
- if (parserInput.autoCommentAbsorb && c === CHARCODE_FORWARD_SLASH) {
- nextChar = inp.charAt(parserInput.i + 1);
-
- if (nextChar === '/') {
- comment = {
- index: parserInput.i,
- isLineComment: true
- };
- var nextNewLine = inp.indexOf('\n', parserInput.i + 2);
-
- if (nextNewLine < 0) {
- nextNewLine = endIndex;
- }
-
- parserInput.i = nextNewLine;
- comment.text = inp.substr(comment.index, parserInput.i - comment.index);
- parserInput.commentStore.push(comment);
- continue;
- } else if (nextChar === '*') {
- var nextStarSlash = inp.indexOf('*/', parserInput.i + 2);
-
- if (nextStarSlash >= 0) {
- comment = {
- index: parserInput.i,
- text: inp.substr(parserInput.i, nextStarSlash + 2 - parserInput.i),
- isLineComment: false
- };
- parserInput.i += comment.text.length - 1;
- parserInput.commentStore.push(comment);
- continue;
- }
- }
-
- break;
- }
-
- if (c !== CHARCODE_SPACE && c !== CHARCODE_LF && c !== CHARCODE_TAB && c !== CHARCODE_CR) {
- break;
- }
- }
-
- current = current.slice(length + parserInput.i - mem + curr);
- currentPos = parserInput.i;
-
- if (!current.length) {
- if (j < chunks.length - 1) {
- current = chunks[++j];
- skipWhitespace(0); // skip space at the beginning of a chunk
-
- return true; // things changed
- }
-
- parserInput.finished = true;
- }
-
- return oldi !== parserInput.i || oldj !== j;
- }
-
- parserInput.save = function () {
- currentPos = parserInput.i;
- saveStack.push({
- current: current,
- i: parserInput.i,
- j: j
- });
};
-
- parserInput.restore = function (possibleErrorMessage) {
- if (parserInput.i > furthest || parserInput.i === furthest && possibleErrorMessage && !furthestPossibleErrorMessage) {
- furthest = parserInput.i;
- furthestPossibleErrorMessage = possibleErrorMessage;
- }
-
- var state = saveStack.pop();
- current = state.current;
- currentPos = parserInput.i = state.i;
- j = state.j;
- };
-
- parserInput.forget = function () {
- saveStack.pop();
- };
-
- parserInput.isWhitespace = function (offset) {
- var pos = parserInput.i + (offset || 0);
- var code = input.charCodeAt(pos);
- return code === CHARCODE_SPACE || code === CHARCODE_CR || code === CHARCODE_TAB || code === CHARCODE_LF;
- }; // Specialization of $(tok)
-
-
- parserInput.$re = function (tok) {
- if (parserInput.i > currentPos) {
- current = current.slice(parserInput.i - currentPos);
- currentPos = parserInput.i;
- }
-
- var m = tok.exec(current);
-
- if (!m) {
- return null;
- }
-
- skipWhitespace(m[0].length);
-
- if (typeof m === 'string') {
- return m;
- }
-
- return m.length === 1 ? m[0] : m;
- };
-
- parserInput.$char = function (tok) {
- if (input.charAt(parserInput.i) !== tok) {
- return null;
- }
-
- skipWhitespace(1);
- return tok;
- };
-
- parserInput.$str = function (tok) {
- var tokLength = tok.length; // https://jsperf.com/string-startswith/21
-
- for (var i = 0; i < tokLength; i++) {
- if (input.charAt(parserInput.i + i) !== tok.charAt(i)) {
- return null;
- }
- }
-
- skipWhitespace(tokLength);
- return tok;
- };
-
- parserInput.$quoted = function (loc) {
- var pos = loc || parserInput.i;
- var startChar = input.charAt(pos);
-
- if (startChar !== '\'' && startChar !== '"') {
- return;
- }
-
- var length = input.length;
- var currentPosition = pos;
-
- for (var i = 1; i + currentPosition < length; i++) {
- var nextChar = input.charAt(i + currentPosition);
-
- switch (nextChar) {
- case '\\':
- i++;
- continue;
-
- case '\r':
- case '\n':
- break;
-
- case startChar:
- var str = input.substr(currentPosition, i + 1);
-
- if (!loc && loc !== 0) {
- skipWhitespace(i + 1);
- return str;
+ Ruleset.prototype = Object.assign(new Node(), {
+ type: 'Ruleset',
+ isRuleset: true,
+ isRulesetLike: function () { return true; },
+ accept: function (visitor) {
+ if (this.paths) {
+ this.paths = visitor.visitArray(this.paths, true);
}
-
- return [startChar, str];
-
- default:
- }
- }
-
- return null;
- };
- /**
- * Permissive parsing. Ignores everything except matching {} [] () and quotes
- * until matching token (outside of blocks)
- */
-
-
- parserInput.$parseUntil = function (tok) {
- var quote = '';
- var returnVal = null;
- var inComment = false;
- var blockDepth = 0;
- var blockStack = [];
- var parseGroups = [];
- var length = input.length;
- var startPos = parserInput.i;
- var lastPos = parserInput.i;
- var i = parserInput.i;
- var loop = true;
- var testChar;
-
- if (typeof tok === 'string') {
- testChar = function testChar(char) {
- return char === tok;
- };
- } else {
- testChar = function testChar(char) {
- return tok.test(char);
- };
- }
-
- do {
- var nextChar = input.charAt(i);
-
- if (blockDepth === 0 && testChar(nextChar)) {
- returnVal = input.substr(lastPos, i - lastPos);
-
- if (returnVal) {
- parseGroups.push(returnVal);
- } else {
- parseGroups.push(' ');
- }
-
- returnVal = parseGroups;
- skipWhitespace(i - startPos);
- loop = false;
- } else {
- if (inComment) {
- if (nextChar === '*' && input.charAt(i + 1) === '/') {
- i++;
- blockDepth--;
- inComment = false;
+ else if (this.selectors) {
+ this.selectors = visitor.visitArray(this.selectors);
}
-
- i++;
- continue;
- }
-
- switch (nextChar) {
- case '\\':
- i++;
- nextChar = input.charAt(i);
- parseGroups.push(input.substr(lastPos, i - lastPos + 1));
- lastPos = i + 1;
- break;
-
- case '/':
- if (input.charAt(i + 1) === '*') {
- i++;
- inComment = true;
- blockDepth++;
- }
-
- break;
-
- case '\'':
- case '"':
- quote = parserInput.$quoted(i);
-
- if (quote) {
- parseGroups.push(input.substr(lastPos, i - lastPos), quote);
- i += quote[1].length - 1;
- lastPos = i + 1;
- } else {
- skipWhitespace(i - startPos);
- returnVal = nextChar;
- loop = false;
- }
-
- break;
-
- case '{':
- blockStack.push('}');
- blockDepth++;
- break;
-
- case '(':
- blockStack.push(')');
- blockDepth++;
- break;
-
- case '[':
- blockStack.push(']');
- blockDepth++;
- break;
-
- case '}':
- case ')':
- case ']':
- var expected = blockStack.pop();
-
- if (nextChar === expected) {
- blockDepth--;
- } else {
- // move the parser to the error and return expected
- skipWhitespace(i - startPos);
- returnVal = expected;
- loop = false;
- }
-
- }
-
- i++;
-
- if (i > length) {
- loop = false;
- }
- }
- } while (loop);
-
- return returnVal ? returnVal : null;
- };
-
- parserInput.autoCommentAbsorb = true;
- parserInput.commentStore = [];
- parserInput.finished = false; // Same as $(), but don't change the state of the parser,
- // just return the match.
-
- parserInput.peek = function (tok) {
- if (typeof tok === 'string') {
- // https://jsperf.com/string-startswith/21
- for (var i = 0; i < tok.length; i++) {
- if (input.charAt(parserInput.i + i) !== tok.charAt(i)) {
- return false;
- }
- }
-
- return true;
- } else {
- return tok.test(current);
- }
- }; // Specialization of peek()
- // TODO remove or change some currentChar calls to peekChar
-
-
- parserInput.peekChar = function (tok) {
- return input.charAt(parserInput.i) === tok;
- };
-
- parserInput.currentChar = function () {
- return input.charAt(parserInput.i);
- };
-
- parserInput.prevChar = function () {
- return input.charAt(parserInput.i - 1);
- };
-
- parserInput.getInput = function () {
- return input;
- };
-
- parserInput.peekNotNumeric = function () {
- var c = input.charCodeAt(parserInput.i); // Is the first char of the dimension 0-9, '.', '+' or '-'
-
- return c > CHARCODE_9 || c < CHARCODE_PLUS || c === CHARCODE_FORWARD_SLASH || c === CHARCODE_COMMA;
- };
-
- parserInput.start = function (str, chunkInput, failFunction) {
- input = str;
- parserInput.i = j = currentPos = furthest = 0; // chunking apparently makes things quicker (but my tests indicate
- // it might actually make things slower in node at least)
- // and it is a non-perfect parse - it can't recognise
- // unquoted urls, meaning it can't distinguish comments
- // meaning comments with quotes or {}() in them get 'counted'
- // and then lead to parse errors.
- // In addition if the chunking chunks in the wrong place we might
- // not be able to parse a parser statement in one go
- // this is officially deprecated but can be switched on via an option
- // in the case it causes too much performance issues.
-
- if (chunkInput) {
- chunks = chunker(str, failFunction);
- } else {
- chunks = [str];
- }
-
- current = chunks[0];
- skipWhitespace(0);
- };
-
- parserInput.end = function () {
- var message;
- var isFinished = parserInput.i >= input.length;
-
- if (parserInput.i < furthest) {
- message = furthestPossibleErrorMessage;
- parserInput.i = furthest;
- }
-
- return {
- isFinished: isFinished,
- furthest: parserInput.i,
- furthestPossibleErrorMessage: message,
- furthestReachedEnd: parserInput.i >= input.length - 1,
- furthestChar: input[parserInput.i]
- };
- };
-
- return parserInput;
- });
-
- // less.js - parser
- //
- // A relatively straight-forward predictive parser.
- // There is no tokenization/lexing stage, the input is parsed
- // in one sweep.
- //
- // To make the parser fast enough to run in the browser, several
- // optimization had to be made:
- //
- // - Matching and slicing on a huge input is often cause of slowdowns.
- // The solution is to chunkify the input into smaller strings.
- // The chunks are stored in the `chunks` var,
- // `j` holds the current chunk index, and `currentPos` holds
- // the index of the current chunk in relation to `input`.
- // This gives us an almost 4x speed-up.
- //
- // - In many cases, we don't need to match individual tokens;
- // for example, if a value doesn't hold any variables, operations
- // or dynamic references, the parser can effectively 'skip' it,
- // treating it as a literal.
- // An example would be '1px solid #000' - which evaluates to itself,
- // we don't need to know what the individual components are.
- // The drawback, of course is that you don't get the benefits of
- // syntax-checking on the CSS. This gives us a 50% speed-up in the parser,
- // and a smaller speed-up in the code-gen.
- //
- //
- // Token matching is done with the `$` function, which either takes
- // a terminal string or regexp, or a non-terminal function to call.
- // It also takes care of moving all the indices forwards.
- //
-
- var Parser = function Parser(context, imports, fileInfo) {
- var parsers;
- var parserInput = getParserInput();
-
- function error(msg, type) {
- throw new LessError({
- index: parserInput.i,
- filename: fileInfo.filename,
- type: type || 'Syntax',
- message: msg
- }, imports);
- }
-
- function expect(arg, msg) {
- // some older browsers return typeof 'function' for RegExp
- var result = arg instanceof Function ? arg.call(parsers) : parserInput.$re(arg);
-
- if (result) {
- return result;
- }
-
- error(msg || (typeof arg === 'string' ? "expected '".concat(arg, "' got '").concat(parserInput.currentChar(), "'") : 'unexpected token'));
- } // Specialization of expect()
-
-
- function expectChar(arg, msg) {
- if (parserInput.$char(arg)) {
- return arg;
- }
-
- error(msg || "expected '".concat(arg, "' got '").concat(parserInput.currentChar(), "'"));
- }
-
- function getDebugInfo(index) {
- var filename = fileInfo.filename;
- return {
- lineNumber: getLocation(index, parserInput.getInput()).line + 1,
- fileName: filename
- };
- }
- /**
- * Used after initial parsing to create nodes on the fly
- *
- * @param {String} str - string to parse
- * @param {Array} parseList - array of parsers to run input through e.g. ["value", "important"]
- * @param {Number} currentIndex - start number to begin indexing
- * @param {Object} fileInfo - fileInfo to attach to created nodes
- */
-
-
- function parseNode(str, parseList, currentIndex, fileInfo, callback) {
- var result;
- var returnNodes = [];
- var parser = parserInput;
-
- try {
- parser.start(str, false, function fail(msg, index) {
- callback({
- message: msg,
- index: index + currentIndex
- });
- });
-
- for (var x = 0, p, i; p = parseList[x]; x++) {
- i = parser.i;
- result = parsers[p]();
-
- if (result) {
- try {
- result._index = i + currentIndex;
- result._fileInfo = fileInfo;
- } catch (e) {}
-
- returnNodes.push(result);
- } else {
- returnNodes.push(null);
- }
- }
-
- var endInfo = parser.end();
-
- if (endInfo.isFinished) {
- callback(null, returnNodes);
- } else {
- callback(true, null);
- }
- } catch (e) {
- throw new LessError({
- index: e.index + currentIndex,
- message: e.message
- }, imports, fileInfo.filename);
- }
- } //
- // The Parser
- //
-
-
- return {
- parserInput: parserInput,
- imports: imports,
- fileInfo: fileInfo,
- parseNode: parseNode,
- //
- // Parse an input string into an abstract syntax tree,
- // @param str A string containing 'less' markup
- // @param callback call `callback` when done.
- // @param [additionalData] An optional map which can contains vars - a map (key, value) of variables to apply
- //
- parse: function parse(str, callback, additionalData) {
- var root;
- var error = null;
- var globalVars;
- var modifyVars;
- var ignored;
- var preText = '';
- globalVars = additionalData && additionalData.globalVars ? "".concat(Parser.serializeVars(additionalData.globalVars), "\n") : '';
- modifyVars = additionalData && additionalData.modifyVars ? "\n".concat(Parser.serializeVars(additionalData.modifyVars)) : '';
-
- if (context.pluginManager) {
- var preProcessors = context.pluginManager.getPreProcessors();
-
- for (var i = 0; i < preProcessors.length; i++) {
- str = preProcessors[i].process(str, {
- context: context,
- imports: imports,
- fileInfo: fileInfo
- });
- }
- }
-
- if (globalVars || additionalData && additionalData.banner) {
- preText = (additionalData && additionalData.banner ? additionalData.banner : '') + globalVars;
- ignored = imports.contentsIgnoredChars;
- ignored[fileInfo.filename] = ignored[fileInfo.filename] || 0;
- ignored[fileInfo.filename] += preText.length;
- }
-
- str = str.replace(/\r\n?/g, '\n'); // Remove potential UTF Byte Order Mark
-
- str = preText + str.replace(/^\uFEFF/, '') + modifyVars;
- imports.contents[fileInfo.filename] = str; // Start with the primary rule.
- // The whole syntax tree is held under a Ruleset node,
- // with the `root` property set to true, so no `{}` are
- // output. The callback is called when the input is parsed.
-
- try {
- parserInput.start(str, context.chunkInput, function fail(msg, index) {
- throw new LessError({
- index: index,
- type: 'Parse',
- message: msg,
- filename: fileInfo.filename
- }, imports);
- });
- tree.Node.prototype.parse = this;
- root = new tree.Ruleset(null, this.parsers.primary());
- tree.Node.prototype.rootNode = root;
- root.root = true;
- root.firstRoot = true;
- root.functionRegistry = functionRegistry.inherit();
- } catch (e) {
- return callback(new LessError(e, imports, fileInfo.filename));
- } // If `i` is smaller than the `input.length - 1`,
- // it means the parser wasn't able to parse the whole
- // string, so we've got a parsing error.
- //
- // We try to extract a \n delimited string,
- // showing the line where the parse error occurred.
- // We split it up into two parts (the part which parsed,
- // and the part which didn't), so we can color them differently.
-
-
- var endInfo = parserInput.end();
-
- if (!endInfo.isFinished) {
- var message = endInfo.furthestPossibleErrorMessage;
-
- if (!message) {
- message = 'Unrecognised input';
-
- if (endInfo.furthestChar === '}') {
- message += '. Possibly missing opening \'{\'';
- } else if (endInfo.furthestChar === ')') {
- message += '. Possibly missing opening \'(\'';
- } else if (endInfo.furthestReachedEnd) {
- message += '. Possibly missing something';
+ if (this.rules && this.rules.length) {
+ this.rules = visitor.visitArray(this.rules);
}
- }
-
- error = new LessError({
- type: 'Parse',
- message: message,
- index: endInfo.furthest,
- filename: fileInfo.filename
- }, imports);
- }
-
- var finish = function finish(e) {
- e = error || e || imports.error;
-
- if (e) {
- if (!(e instanceof LessError)) {
- e = new LessError(e, imports, fileInfo.filename);
- }
-
- return callback(e);
- } else {
- return callback(null, root);
- }
- };
-
- if (context.processImports !== false) {
- new visitors.ImportVisitor(imports, finish).run(root);
- } else {
- return finish();
- }
- },
- //
- // Here in, the parsing rules/functions
- //
- // The basic structure of the syntax tree generated is as follows:
- //
- // Ruleset -> Declaration -> Value -> Expression -> Entity
- //
- // Here's some Less code:
- //
- // .class {
- // color: #fff;
- // border: 1px solid #000;
- // width: @w + 4px;
- // > .child {...}
- // }
- //
- // And here's what the parse tree might look like:
- //
- // Ruleset (Selector '.class', [
- // Declaration ("color", Value ([Expression [Color #fff]]))
- // Declaration ("border", Value ([Expression [Dimension 1px][Keyword "solid"][Color #000]]))
- // Declaration ("width", Value ([Expression [Operation " + " [Variable "@w"][Dimension 4px]]]))
- // Ruleset (Selector [Element '>', '.child'], [...])
- // ])
- //
- // In general, most rules will try to parse a token with the `$re()` function, and if the return
- // value is truly, will return a new node, of the relevant type. Sometimes, we need to check
- // first, before parsing, that's when we use `peek()`.
- //
- parsers: parsers = {
- //
- // The `primary` rule is the *entry* and *exit* point of the parser.
- // The rules here can appear at any level of the parse tree.
- //
- // The recursive nature of the grammar is an interplay between the `block`
- // rule, which represents `{ ... }`, the `ruleset` rule, and this `primary` rule,
- // as represented by this simplified grammar:
- //
- // primary → (ruleset | declaration)+
- // ruleset → selector+ block
- // block → '{' primary '}'
- //
- // Only at one point is the primary rule not called from the
- // block rule: at the root level.
- //
- primary: function primary() {
- var mixin = this.mixin;
- var root = [];
- var node;
-
- while (true) {
- while (true) {
- node = this.comment();
-
- if (!node) {
- break;
- }
-
- root.push(node);
- } // always process comments before deciding if finished
-
-
- if (parserInput.finished) {
- break;
- }
-
- if (parserInput.peek('}')) {
- break;
- }
-
- node = this.extendRule();
-
- if (node) {
- root = root.concat(node);
- continue;
- }
-
- node = mixin.definition() || this.declaration() || this.ruleset() || mixin.call(false, false) || this.variableCall() || this.entities.call() || this.atrule();
-
- if (node) {
- root.push(node);
- } else {
- var foundSemiColon = false;
-
- while (parserInput.$char(';')) {
- foundSemiColon = true;
- }
-
- if (!foundSemiColon) {
- break;
- }
- }
- }
-
- return root;
},
- // comments are collected by the main parsing mechanism and then assigned to nodes
- // where the current structure allows it
- comment: function comment() {
- if (parserInput.commentStore.length) {
- var comment = parserInput.commentStore.shift();
- return new tree.Comment(comment.text, comment.isLineComment, comment.index, fileInfo);
- }
- },
- //
- // Entities are tokens which can be found inside an Expression
- //
- entities: {
- mixinLookup: function mixinLookup() {
- return parsers.mixin.call(true, true);
- },
- //
- // A string, which supports escaping " and '
- //
- // "milky way" 'he\'s the one!'
- //
- quoted: function quoted(forceEscaped) {
- var str;
- var index = parserInput.i;
- var isEscaped = false;
- parserInput.save();
-
- if (parserInput.$char('~')) {
- isEscaped = true;
- } else if (forceEscaped) {
- parserInput.restore();
- return;
- }
-
- str = parserInput.$quoted();
-
- if (!str) {
- parserInput.restore();
- return;
- }
-
- parserInput.forget();
- return new tree.Quoted(str.charAt(0), str.substr(1, str.length - 2), isEscaped, index, fileInfo);
- },
- //
- // A catch-all word, such as:
- //
- // black border-collapse
- //
- keyword: function keyword() {
- var k = parserInput.$char('%') || parserInput.$re(/^\[?(?:[\w-]|\\(?:[A-Fa-f0-9]{1,6} ?|[^A-Fa-f0-9]))+\]?/);
-
- if (k) {
- return tree.Color.fromKeyword(k) || new tree.Keyword(k);
- }
- },
- //
- // A function call
- //
- // rgb(255, 0, 255)
- //
- // The arguments are parsed with the `entities.arguments` parser.
- //
- call: function call() {
- var name;
- var args;
- var func;
- var index = parserInput.i; // http://jsperf.com/case-insensitive-regex-vs-strtolower-then-regex/18
-
- if (parserInput.peek(/^url\(/i)) {
- return;
- }
-
- parserInput.save();
- name = parserInput.$re(/^([\w-]+|%|progid:[\w\.]+)\(/);
-
- if (!name) {
- parserInput.forget();
- return;
- }
-
- name = name[1];
- func = this.customFuncCall(name);
-
- if (func) {
- args = func.parse();
-
- if (args && func.stop) {
- parserInput.forget();
- return args;
- }
- }
-
- args = this.arguments(args);
-
- if (!parserInput.$char(')')) {
- parserInput.restore('Could not parse call arguments or missing \')\'');
- return;
- }
-
- parserInput.forget();
- return new tree.Call(name, args, index, fileInfo);
- },
- //
- // Parsing rules for functions with non-standard args, e.g.:
- //
- // boolean(not(2 > 1))
- //
- // This is a quick prototype, to be modified/improved when
- // more custom-parsed funcs come (e.g. `selector(...)`)
- //
- customFuncCall: function customFuncCall(name) {
- /* Ideally the table is to be moved out of here for faster perf.,
- but it's quite tricky since it relies on all these `parsers`
- and `expect` available only here */
- return {
- alpha: f(parsers.ieAlpha, true),
- boolean: f(condition),
- 'if': f(condition)
- }[name.toLowerCase()];
-
- function f(parse, stop) {
- return {
- parse: parse,
- // parsing function
- stop: stop // when true - stop after parse() and return its result,
- // otherwise continue for plain args
-
- };
- }
-
- function condition() {
- return [expect(parsers.condition, 'expected condition')];
- }
- },
- arguments: function _arguments(prevArgs) {
- var argsComma = prevArgs || [];
- var argsSemiColon = [];
- var isSemiColonSeparated;
- var value;
- parserInput.save();
-
- while (true) {
- if (prevArgs) {
- prevArgs = false;
- } else {
- value = parsers.detachedRuleset() || this.assignment() || parsers.expression();
-
- if (!value) {
- break;
- }
-
- if (value.value && value.value.length == 1) {
- value = value.value[0];
- }
-
- argsComma.push(value);
- }
-
- if (parserInput.$char(',')) {
- continue;
- }
-
- if (parserInput.$char(';') || isSemiColonSeparated) {
- isSemiColonSeparated = true;
- value = argsComma.length < 1 ? argsComma[0] : new tree.Value(argsComma);
- argsSemiColon.push(value);
- argsComma = [];
- }
- }
-
- parserInput.forget();
- return isSemiColonSeparated ? argsSemiColon : argsComma;
- },
- literal: function literal() {
- return this.dimension() || this.color() || this.quoted() || this.unicodeDescriptor();
- },
- // Assignments are argument entities for calls.
- // They are present in ie filter properties as shown below.
- //
- // filter: progid:DXImageTransform.Microsoft.Alpha( *opacity=50* )
- //
- assignment: function assignment() {
- var key;
- var value;
- parserInput.save();
- key = parserInput.$re(/^\w+(?=\s?=)/i);
-
- if (!key) {
- parserInput.restore();
- return;
- }
-
- if (!parserInput.$char('=')) {
- parserInput.restore();
- return;
- }
-
- value = parsers.entity();
-
- if (value) {
- parserInput.forget();
- return new tree.Assignment(key, value);
- } else {
- parserInput.restore();
- }
- },
- //
- // Parse url() tokens
- //
- // We use a specific rule for urls, because they don't really behave like
- // standard function calls. The difference is that the argument doesn't have
- // to be enclosed within a string, so it can't be parsed as an Expression.
- //
- url: function url() {
- var value;
- var index = parserInput.i;
- parserInput.autoCommentAbsorb = false;
-
- if (!parserInput.$str('url(')) {
- parserInput.autoCommentAbsorb = true;
- return;
- }
-
- value = this.quoted() || this.variable() || this.property() || parserInput.$re(/^(?:(?:\\[\(\)'"])|[^\(\)'"])+/) || '';
- parserInput.autoCommentAbsorb = true;
- expectChar(')');
- return new tree.URL(value.value != null || value instanceof tree.Variable || value instanceof tree.Property ? value : new tree.Anonymous(value, index), index, fileInfo);
- },
- //
- // A Variable entity, such as `@fink`, in
- //
- // width: @fink + 2px
- //
- // We use a different parser for variable definitions,
- // see `parsers.variable`.
- //
- variable: function variable() {
- var ch;
- var name;
- var index = parserInput.i;
- parserInput.save();
-
- if (parserInput.currentChar() === '@' && (name = parserInput.$re(/^@@?[\w-]+/))) {
- ch = parserInput.currentChar();
-
- if (ch === '(' || ch === '[' && !parserInput.prevChar().match(/^\s/)) {
- // this may be a VariableCall lookup
- var result = parsers.variableCall(name);
-
- if (result) {
- parserInput.forget();
- return result;
- }
- }
-
- parserInput.forget();
- return new tree.Variable(name, index, fileInfo);
- }
-
- parserInput.restore();
- },
- // A variable entity using the protective {} e.g. @{var}
- variableCurly: function variableCurly() {
- var curly;
- var index = parserInput.i;
-
- if (parserInput.currentChar() === '@' && (curly = parserInput.$re(/^@\{([\w-]+)\}/))) {
- return new tree.Variable("@".concat(curly[1]), index, fileInfo);
- }
- },
- //
- // A Property accessor, such as `$color`, in
- //
- // background-color: $color
- //
- property: function property() {
- var name;
- var index = parserInput.i;
-
- if (parserInput.currentChar() === '$' && (name = parserInput.$re(/^\$[\w-]+/))) {
- return new tree.Property(name, index, fileInfo);
- }
- },
- // A property entity useing the protective {} e.g. ${prop}
- propertyCurly: function propertyCurly() {
- var curly;
- var index = parserInput.i;
-
- if (parserInput.currentChar() === '$' && (curly = parserInput.$re(/^\$\{([\w-]+)\}/))) {
- return new tree.Property("$".concat(curly[1]), index, fileInfo);
- }
- },
- //
- // A Hexadecimal color
- //
- // #4F3C2F
- //
- // `rgb` and `hsl` colors are parsed through the `entities.call` parser.
- //
- color: function color() {
- var rgb;
- parserInput.save();
-
- if (parserInput.currentChar() === '#' && (rgb = parserInput.$re(/^#([A-Fa-f0-9]{8}|[A-Fa-f0-9]{6}|[A-Fa-f0-9]{3,4})([\w.#\[])?/))) {
- if (!rgb[2]) {
- parserInput.forget();
- return new tree.Color(rgb[1], undefined, rgb[0]);
- }
- }
-
- parserInput.restore();
- },
- colorKeyword: function colorKeyword() {
- parserInput.save();
- var autoCommentAbsorb = parserInput.autoCommentAbsorb;
- parserInput.autoCommentAbsorb = false;
- var k = parserInput.$re(/^[_A-Za-z-][_A-Za-z0-9-]+/);
- parserInput.autoCommentAbsorb = autoCommentAbsorb;
-
- if (!k) {
- parserInput.forget();
- return;
- }
-
- parserInput.restore();
- var color = tree.Color.fromKeyword(k);
-
- if (color) {
- parserInput.$str(k);
- return color;
- }
- },
- //
- // A Dimension, that is, a number and a unit
- //
- // 0.5em 95%
- //
- dimension: function dimension() {
- if (parserInput.peekNotNumeric()) {
- return;
- }
-
- var value = parserInput.$re(/^([+-]?\d*\.?\d+)(%|[a-z_]+)?/i);
-
- if (value) {
- return new tree.Dimension(value[1], value[2]);
- }
- },
- //
- // A unicode descriptor, as is used in unicode-range
- //
- // U+0?? or U+00A1-00A9
- //
- unicodeDescriptor: function unicodeDescriptor() {
- var ud;
- ud = parserInput.$re(/^U\+[0-9a-fA-F?]+(\-[0-9a-fA-F?]+)?/);
-
- if (ud) {
- return new tree.UnicodeDescriptor(ud[0]);
- }
- },
- //
- // JavaScript code to be evaluated
- //
- // `window.location.href`
- //
- javascript: function javascript() {
- var js;
- var index = parserInput.i;
- parserInput.save();
- var escape = parserInput.$char('~');
- var jsQuote = parserInput.$char('`');
-
- if (!jsQuote) {
- parserInput.restore();
- return;
- }
-
- js = parserInput.$re(/^[^`]*`/);
-
- if (js) {
- parserInput.forget();
- return new tree.JavaScript(js.substr(0, js.length - 1), Boolean(escape), index, fileInfo);
- }
-
- parserInput.restore('invalid javascript definition');
- }
- },
- //
- // The variable part of a variable definition. Used in the `rule` parser
- //
- // @fink:
- //
- variable: function variable() {
- var name;
-
- if (parserInput.currentChar() === '@' && (name = parserInput.$re(/^(@[\w-]+)\s*:/))) {
- return name[1];
- }
- },
- //
- // Call a variable value to retrieve a detached ruleset
- // or a value from a detached ruleset's rules.
- //
- // @fink();
- // @fink;
- // color: @fink[@color];
- //
- variableCall: function variableCall(parsedName) {
- var lookups;
- var important;
- var i = parserInput.i;
- var inValue = !!parsedName;
- var name = parsedName;
- parserInput.save();
-
- if (name || parserInput.currentChar() === '@' && (name = parserInput.$re(/^(@[\w-]+)(\(\s*\))?/))) {
- lookups = this.mixin.ruleLookups();
-
- if (!lookups && (inValue && parserInput.$str('()') !== '()' || name[2] !== '()')) {
- parserInput.restore('Missing \'[...]\' lookup in variable call');
- return;
- }
-
- if (!inValue) {
- name = name[1];
- }
-
- if (lookups && parsers.important()) {
- important = true;
- }
-
- var call = new tree.VariableCall(name, i, fileInfo);
-
- if (!inValue && parsers.end()) {
- parserInput.forget();
- return call;
- } else {
- parserInput.forget();
- return new tree.NamespaceValue(call, lookups, important, i, fileInfo);
- }
- }
-
- parserInput.restore();
- },
- //
- // extend syntax - used to extend selectors
- //
- extend: function extend(isRule) {
- var elements;
- var e;
- var index = parserInput.i;
- var option;
- var extendList;
- var extend;
-
- if (!parserInput.$str(isRule ? '&:extend(' : ':extend(')) {
- return;
- }
-
- do {
- option = null;
- elements = null;
-
- while (!(option = parserInput.$re(/^(all)(?=\s*(\)|,))/))) {
- e = this.element();
-
- if (!e) {
- break;
- }
-
- if (elements) {
- elements.push(e);
- } else {
- elements = [e];
- }
- }
-
- option = option && option[1];
-
- if (!elements) {
- error('Missing target selector for :extend().');
- }
-
- extend = new tree.Extend(new tree.Selector(elements), option, index, fileInfo);
-
- if (extendList) {
- extendList.push(extend);
- } else {
- extendList = [extend];
- }
- } while (parserInput.$char(','));
-
- expect(/^\)/);
-
- if (isRule) {
- expect(/^;/);
- }
-
- return extendList;
- },
- //
- // extendRule - used in a rule to extend all the parent selectors
- //
- extendRule: function extendRule() {
- return this.extend(true);
- },
- //
- // Mixins
- //
- mixin: {
- //
- // A Mixin call, with an optional argument list
- //
- // #mixins > .square(#fff);
- // #mixins.square(#fff);
- // .rounded(4px, black);
- // .button;
- //
- // We can lookup / return a value using the lookup syntax:
- //
- // color: #mixin.square(#fff)[@color];
- //
- // The `while` loop is there because mixins can be
- // namespaced, but we only support the child and descendant
- // selector for now.
- //
- call: function call(inValue, getLookup) {
- var s = parserInput.currentChar();
- var important = false;
- var lookups;
- var index = parserInput.i;
- var elements;
- var args;
- var hasParens;
-
- if (s !== '.' && s !== '#') {
- return;
- }
-
- parserInput.save(); // stop us absorbing part of an invalid selector
-
- elements = this.elements();
-
- if (elements) {
- if (parserInput.$char('(')) {
- args = this.args(true).args;
- expectChar(')');
- hasParens = true;
- }
-
- if (getLookup !== false) {
- lookups = this.ruleLookups();
- }
-
- if (getLookup === true && !lookups) {
- parserInput.restore();
- return;
- }
-
- if (inValue && !lookups && !hasParens) {
- // This isn't a valid in-value mixin call
- parserInput.restore();
- return;
- }
-
- if (!inValue && parsers.important()) {
- important = true;
- }
-
- if (inValue || parsers.end()) {
- parserInput.forget();
- var mixin = new tree.mixin.Call(elements, args, index, fileInfo, !lookups && important);
-
- if (lookups) {
- return new tree.NamespaceValue(mixin, lookups, important);
- } else {
- return mixin;
- }
- }
- }
-
- parserInput.restore();
- },
-
- /**
- * Matching elements for mixins
- * (Start with . or # and can have > )
- */
- elements: function elements() {
- var elements;
- var e;
- var c;
- var elem;
- var elemIndex;
- var re = /^[#.](?:[\w-]|\\(?:[A-Fa-f0-9]{1,6} ?|[^A-Fa-f0-9]))+/;
-
- while (true) {
- elemIndex = parserInput.i;
- e = parserInput.$re(re);
-
- if (!e) {
- break;
- }
-
- elem = new tree.Element(c, e, false, elemIndex, fileInfo);
-
- if (elements) {
- elements.push(elem);
- } else {
- elements = [elem];
- }
-
- c = parserInput.$char('>');
- }
-
- return elements;
- },
- args: function args(isCall) {
- var entities = parsers.entities;
- var returner = {
- args: null,
- variadic: false
- };
- var expressions = [];
- var argsSemiColon = [];
- var argsComma = [];
- var isSemiColonSeparated;
- var expressionContainsNamed;
- var name;
- var nameLoop;
- var value;
- var arg;
- var expand;
- var hasSep = true;
- parserInput.save();
-
- while (true) {
- if (isCall) {
- arg = parsers.detachedRuleset() || parsers.expression();
- } else {
- parserInput.commentStore.length = 0;
-
- if (parserInput.$str('...')) {
- returner.variadic = true;
-
- if (parserInput.$char(';') && !isSemiColonSeparated) {
- isSemiColonSeparated = true;
- }
-
- (isSemiColonSeparated ? argsSemiColon : argsComma).push({
- variadic: true
- });
- break;
- }
-
- arg = entities.variable() || entities.property() || entities.literal() || entities.keyword() || this.call(true);
- }
-
- if (!arg || !hasSep) {
- break;
- }
-
- nameLoop = null;
-
- if (arg.throwAwayComments) {
- arg.throwAwayComments();
- }
-
- value = arg;
- var val = null;
-
- if (isCall) {
- // Variable
- if (arg.value && arg.value.length == 1) {
- val = arg.value[0];
- }
- } else {
- val = arg;
- }
-
- if (val && (val instanceof tree.Variable || val instanceof tree.Property)) {
- if (parserInput.$char(':')) {
- if (expressions.length > 0) {
- if (isSemiColonSeparated) {
- error('Cannot mix ; and , as delimiter types');
+ eval: function (context) {
+ var selectors;
+ var selCnt;
+ var selector;
+ var i;
+ var hasVariable;
+ var hasOnePassingSelector = false;
+ if (this.selectors && (selCnt = this.selectors.length)) {
+ selectors = new Array(selCnt);
+ defaultFunc.error({
+ type: 'Syntax',
+ message: 'it is currently only allowed in parametric mixin guards,'
+ });
+ for (i = 0; i < selCnt; i++) {
+ selector = this.selectors[i].eval(context);
+ for (var j = 0; j < selector.elements.length; j++) {
+ if (selector.elements[j].isVariable) {
+ hasVariable = true;
+ break;
+ }
}
-
- expressionContainsNamed = true;
- }
-
- value = parsers.detachedRuleset() || parsers.expression();
-
- if (!value) {
- if (isCall) {
- error('could not understand value for named argument');
- } else {
- parserInput.restore();
- returner.args = [];
- return returner;
+ selectors[i] = selector;
+ if (selector.evaldCondition) {
+ hasOnePassingSelector = true;
}
- }
-
- nameLoop = name = val.name;
- } else if (parserInput.$str('...')) {
- if (!isCall) {
- returner.variadic = true;
-
- if (parserInput.$char(';') && !isSemiColonSeparated) {
- isSemiColonSeparated = true;
+ }
+ if (hasVariable) {
+ var toParseSelectors = new Array(selCnt);
+ for (i = 0; i < selCnt; i++) {
+ selector = selectors[i];
+ toParseSelectors[i] = selector.toCSS(context);
}
-
- (isSemiColonSeparated ? argsSemiColon : argsComma).push({
- name: arg.name,
- variadic: true
+ this.parse.parseNode(toParseSelectors.join(','), ["selectors"], selectors[0].getIndex(), selectors[0].fileInfo(), function (err, result) {
+ if (result) {
+ selectors = flattenArray(result);
+ }
});
- break;
- } else {
- expand = true;
- }
- } else if (!isCall) {
- name = nameLoop = val.name;
- value = null;
}
- }
-
- if (value) {
- expressions.push(value);
- }
-
- argsComma.push({
- name: nameLoop,
- value: value,
- expand: expand
- });
-
- if (parserInput.$char(',')) {
- hasSep = true;
- continue;
- }
-
- hasSep = parserInput.$char(';') === ';';
-
- if (hasSep || isSemiColonSeparated) {
- if (expressionContainsNamed) {
- error('Cannot mix ; and , as delimiter types');
- }
-
- isSemiColonSeparated = true;
-
- if (expressions.length > 1) {
- value = new tree.Value(expressions);
- }
-
- argsSemiColon.push({
- name: name,
- value: value,
- expand: expand
- });
- name = null;
- expressions = [];
- expressionContainsNamed = false;
- }
+ defaultFunc.reset();
}
-
- parserInput.forget();
- returner.args = isSemiColonSeparated ? argsSemiColon : argsComma;
- return returner;
- },
- //
- // A Mixin definition, with a list of parameters
- //
- // .rounded (@radius: 2px, @color) {
- // ...
- // }
- //
- // Until we have a finer grained state-machine, we have to
- // do a look-ahead, to make sure we don't have a mixin call.
- // See the `rule` function for more information.
- //
- // We start by matching `.rounded (`, and then proceed on to
- // the argument list, which has optional default values.
- // We store the parameters in `params`, with a `value` key,
- // if there is a value, such as in the case of `@radius`.
- //
- // Once we've got our params list, and a closing `)`, we parse
- // the `{...}` block.
- //
- definition: function definition() {
- var name;
- var params = [];
- var match;
- var ruleset;
- var cond;
- var variadic = false;
-
- if (parserInput.currentChar() !== '.' && parserInput.currentChar() !== '#' || parserInput.peek(/^[^{]*\}/)) {
- return;
+ else {
+ hasOnePassingSelector = true;
}
-
- parserInput.save();
- match = parserInput.$re(/^([#.](?:[\w-]|\\(?:[A-Fa-f0-9]{1,6} ?|[^A-Fa-f0-9]))+)\s*\(/);
-
- if (match) {
- name = match[1];
- var argInfo = this.args(false);
- params = argInfo.args;
- variadic = argInfo.variadic; // .mixincall("@{a}");
- // looks a bit like a mixin definition..
- // also
- // .mixincall(@a: {rule: set;});
- // so we have to be nice and restore
-
- if (!parserInput.$char(')')) {
- parserInput.restore('Missing closing \')\'');
- return;
- }
-
- parserInput.commentStore.length = 0;
-
- if (parserInput.$str('when')) {
- // Guard
- cond = expect(parsers.conditions, 'expected condition');
- }
-
- ruleset = parsers.block();
-
- if (ruleset) {
- parserInput.forget();
- return new tree.mixin.Definition(name, params, ruleset, cond, variadic);
- } else {
- parserInput.restore();
- }
- } else {
- parserInput.forget();
- }
- },
- ruleLookups: function ruleLookups() {
+ var rules = this.rules ? copyArray(this.rules) : null;
+ var ruleset = new Ruleset(selectors, rules, this.strictImports, this.visibilityInfo());
var rule;
- var lookups = [];
-
- if (parserInput.currentChar() !== '[') {
- return;
+ var subRule;
+ ruleset.originalRuleset = this;
+ ruleset.root = this.root;
+ ruleset.firstRoot = this.firstRoot;
+ ruleset.allowImports = this.allowImports;
+ if (this.debugInfo) {
+ ruleset.debugInfo = this.debugInfo;
}
-
- while (true) {
- parserInput.save();
- rule = this.lookupValue();
-
- if (!rule && rule !== '') {
- parserInput.restore();
- break;
- }
-
- lookups.push(rule);
- parserInput.forget();
+ if (!hasOnePassingSelector) {
+ rules.length = 0;
}
-
- if (lookups.length > 0) {
- return lookups;
+ // inherit a function registry from the frames stack when possible;
+ // otherwise from the global registry
+ ruleset.functionRegistry = (function (frames) {
+ var i = 0;
+ var n = frames.length;
+ var found;
+ for (; i !== n; ++i) {
+ found = frames[i].functionRegistry;
+ if (found) {
+ return found;
+ }
+ }
+ return functionRegistry;
+ }(context.frames)).inherit();
+ // push the current ruleset to the frames stack
+ var ctxFrames = context.frames;
+ ctxFrames.unshift(ruleset);
+ // currrent selectors
+ var ctxSelectors = context.selectors;
+ if (!ctxSelectors) {
+ context.selectors = ctxSelectors = [];
}
- },
- lookupValue: function lookupValue() {
- parserInput.save();
-
- if (!parserInput.$char('[')) {
- parserInput.restore();
- return;
+ ctxSelectors.unshift(this.selectors);
+ // Evaluate imports
+ if (ruleset.root || ruleset.allowImports || !ruleset.strictImports) {
+ ruleset.evalImports(context);
}
-
- var name = parserInput.$re(/^(?:[@$]{0,2})[_a-zA-Z0-9-]*/);
-
- if (!parserInput.$char(']')) {
- parserInput.restore();
- return;
+ // Store the frames around mixin definitions,
+ // so they can be evaluated like closures when the time comes.
+ var rsRules = ruleset.rules;
+ for (i = 0; (rule = rsRules[i]); i++) {
+ if (rule.evalFirst) {
+ rsRules[i] = rule.eval(context);
+ }
}
-
- if (name || name === '') {
- parserInput.forget();
- return name;
+ var mediaBlockCount = (context.mediaBlocks && context.mediaBlocks.length) || 0;
+ // Evaluate mixin calls.
+ for (i = 0; (rule = rsRules[i]); i++) {
+ if (rule.type === 'MixinCall') {
+ /* jshint loopfunc:true */
+ rules = rule.eval(context).filter(function (r) {
+ if ((r instanceof Declaration) && r.variable) {
+ // do not pollute the scope if the variable is
+ // already there. consider returning false here
+ // but we need a way to "return" variable from mixins
+ return !(ruleset.variable(r.name));
+ }
+ return true;
+ });
+ rsRules.splice.apply(rsRules, [i, 1].concat(rules));
+ i += rules.length - 1;
+ ruleset.resetCache();
+ }
+ else if (rule.type === 'VariableCall') {
+ /* jshint loopfunc:true */
+ rules = rule.eval(context).rules.filter(function (r) {
+ if ((r instanceof Declaration) && r.variable) {
+ // do not pollute the scope at all
+ return false;
+ }
+ return true;
+ });
+ rsRules.splice.apply(rsRules, [i, 1].concat(rules));
+ i += rules.length - 1;
+ ruleset.resetCache();
+ }
}
-
- parserInput.restore();
- }
- },
- //
- // Entities are the smallest recognized token,
- // and can be found inside a rule's value.
- //
- entity: function entity() {
- var entities = this.entities;
- return this.comment() || entities.literal() || entities.variable() || entities.url() || entities.property() || entities.call() || entities.keyword() || this.mixin.call(true) || entities.javascript();
- },
- //
- // A Declaration terminator. Note that we use `peek()` to check for '}',
- // because the `block` rule will be expecting it, but we still need to make sure
- // it's there, if ';' was omitted.
- //
- end: function end() {
- return parserInput.$char(';') || parserInput.peek('}');
- },
- //
- // IE's alpha function
- //
- // alpha(opacity=88)
- //
- ieAlpha: function ieAlpha() {
- var value; // http://jsperf.com/case-insensitive-regex-vs-strtolower-then-regex/18
-
- if (!parserInput.$re(/^opacity=/i)) {
- return;
- }
-
- value = parserInput.$re(/^\d+/);
-
- if (!value) {
- value = expect(parsers.entities.variable, 'Could not parse alpha');
- value = "@{".concat(value.name.slice(1), "}");
- }
-
- expectChar(')');
- return new tree.Quoted('', "alpha(opacity=".concat(value, ")"));
- },
- //
- // A Selector Element
- //
- // div
- // + h1
- // #socks
- // input[type="text"]
- //
- // Elements are the building blocks for Selectors,
- // they are made out of a `Combinator` (see combinator rule),
- // and an element name, such as a tag a class, or `*`.
- //
- element: function element() {
- var e;
- var c;
- var v;
- var index = parserInput.i;
- c = this.combinator();
- e = parserInput.$re(/^(?:\d+\.\d+|\d+)%/) || parserInput.$re(/^(?:[.#]?|:*)(?:[\w-]|[^\x00-\x9f]|\\(?:[A-Fa-f0-9]{1,6} ?|[^A-Fa-f0-9]))+/) || parserInput.$char('*') || parserInput.$char('&') || this.attribute() || parserInput.$re(/^\([^&()@]+\)/) || parserInput.$re(/^[\.#:](?=@)/) || this.entities.variableCurly();
-
- if (!e) {
- parserInput.save();
-
- if (parserInput.$char('(')) {
- if ((v = this.selector(false)) && parserInput.$char(')')) {
- e = new tree.Paren(v);
- parserInput.forget();
- } else {
- parserInput.restore('Missing closing \')\'');
- }
- } else {
- parserInput.forget();
+ // Evaluate everything else
+ for (i = 0; (rule = rsRules[i]); i++) {
+ if (!rule.evalFirst) {
+ rsRules[i] = rule = rule.eval ? rule.eval(context) : rule;
+ }
}
- }
-
- if (e) {
- return new tree.Element(c, e, e instanceof tree.Variable, index, fileInfo);
- }
- },
- //
- // Combinators combine elements together, in a Selector.
- //
- // Because our parser isn't white-space sensitive, special care
- // has to be taken, when parsing the descendant combinator, ` `,
- // as it's an empty space. We have to check the previous character
- // in the input, to see if it's a ` ` character. More info on how
- // we deal with this in *combinator.js*.
- //
- combinator: function combinator() {
- var c = parserInput.currentChar();
-
- if (c === '/') {
- parserInput.save();
- var slashedCombinator = parserInput.$re(/^\/[a-z]+\//i);
-
- if (slashedCombinator) {
- parserInput.forget();
- return new tree.Combinator(slashedCombinator);
+ // Evaluate everything else
+ for (i = 0; (rule = rsRules[i]); i++) {
+ // for rulesets, check if it is a css guard and can be removed
+ if (rule instanceof Ruleset && rule.selectors && rule.selectors.length === 1) {
+ // check if it can be folded in (e.g. & where)
+ if (rule.selectors[0] && rule.selectors[0].isJustParentSelector()) {
+ rsRules.splice(i--, 1);
+ for (var j = 0; (subRule = rule.rules[j]); j++) {
+ if (subRule instanceof Node) {
+ subRule.copyVisibilityInfo(rule.visibilityInfo());
+ if (!(subRule instanceof Declaration) || !subRule.variable) {
+ rsRules.splice(++i, 0, subRule);
+ }
+ }
+ }
+ }
+ }
}
-
- parserInput.restore();
- }
-
- if (c === '>' || c === '+' || c === '~' || c === '|' || c === '^') {
- parserInput.i++;
-
- if (c === '^' && parserInput.currentChar() === '^') {
- c = '^^';
- parserInput.i++;
+ // Pop the stack
+ ctxFrames.shift();
+ ctxSelectors.shift();
+ if (context.mediaBlocks) {
+ for (i = mediaBlockCount; i < context.mediaBlocks.length; i++) {
+ context.mediaBlocks[i].bubbleSelectors(selectors);
+ }
}
-
- while (parserInput.isWhitespace()) {
- parserInput.i++;
- }
-
- return new tree.Combinator(c);
- } else if (parserInput.isWhitespace(-1)) {
- return new tree.Combinator(' ');
- } else {
- return new tree.Combinator(null);
- }
- },
- //
- // A CSS Selector
- // with less extensions e.g. the ability to extend and guard
- //
- // .class > div + h1
- // li a:hover
- //
- // Selectors are made out of one or more Elements, see above.
- //
- selector: function selector(isLess) {
- var index = parserInput.i;
- var elements;
- var extendList;
- var c;
- var e;
- var allExtends;
- var when;
- var condition;
- isLess = isLess !== false;
-
- while (isLess && (extendList = this.extend()) || isLess && (when = parserInput.$str('when')) || (e = this.element())) {
- if (when) {
- condition = expect(this.conditions, 'expected condition');
- } else if (condition) {
- error('CSS guard can only be used at the end of selector');
- } else if (extendList) {
- if (allExtends) {
- allExtends = allExtends.concat(extendList);
- } else {
- allExtends = extendList;
- }
- } else {
- if (allExtends) {
- error('Extend can only be used at the end of selector');
- }
-
- c = parserInput.currentChar();
-
- if (elements) {
- elements.push(e);
- } else {
- elements = [e];
- }
-
- e = null;
- }
-
- if (c === '{' || c === '}' || c === ';' || c === ',' || c === ')') {
- break;
- }
- }
-
- if (elements) {
- return new tree.Selector(elements, allExtends, condition, index, fileInfo);
- }
-
- if (allExtends) {
- error('Extend must be used to extend a selector, it cannot be used on its own');
- }
- },
- selectors: function selectors() {
- var s;
- var selectors;
-
- while (true) {
- s = this.selector();
-
- if (!s) {
- break;
- }
-
- if (selectors) {
- selectors.push(s);
- } else {
- selectors = [s];
- }
-
- parserInput.commentStore.length = 0;
-
- if (s.condition && selectors.length > 1) {
- error("Guards are only currently allowed on a single selector.");
- }
-
- if (!parserInput.$char(',')) {
- break;
- }
-
- if (s.condition) {
- error("Guards are only currently allowed on a single selector.");
- }
-
- parserInput.commentStore.length = 0;
- }
-
- return selectors;
- },
- attribute: function attribute() {
- if (!parserInput.$char('[')) {
- return;
- }
-
- var entities = this.entities;
- var key;
- var val;
- var op;
-
- if (!(key = entities.variableCurly())) {
- key = expect(/^(?:[_A-Za-z0-9-\*]*\|)?(?:[_A-Za-z0-9-]|\\.)+/);
- }
-
- op = parserInput.$re(/^[|~*$^]?=/);
-
- if (op) {
- val = entities.quoted() || parserInput.$re(/^[0-9]+%/) || parserInput.$re(/^[\w-]+/) || entities.variableCurly();
- }
-
- expectChar(']');
- return new tree.Attribute(key, op, val);
- },
- //
- // The `block` rule is used by `ruleset` and `mixin.definition`.
- // It's a wrapper around the `primary` rule, with added `{}`.
- //
- block: function block() {
- var content;
-
- if (parserInput.$char('{') && (content = this.primary()) && parserInput.$char('}')) {
- return content;
- }
- },
- blockRuleset: function blockRuleset() {
- var block = this.block();
-
- if (block) {
- block = new tree.Ruleset(null, block);
- }
-
- return block;
- },
- detachedRuleset: function detachedRuleset() {
- var argInfo;
- var params;
- var variadic;
- parserInput.save();
-
- if (parserInput.$re(/^[.#]\(/)) {
- /**
- * DR args currently only implemented for each() function, and not
- * yet settable as `@dr: #(@arg) {}`
- * This should be done when DRs are merged with mixins.
- * See: https://github.com/less/less-meta/issues/16
- */
- argInfo = this.mixin.args(false);
- params = argInfo.args;
- variadic = argInfo.variadic;
-
- if (!parserInput.$char(')')) {
- parserInput.restore();
- return;
- }
- }
-
- var blockRuleset = this.blockRuleset();
-
- if (blockRuleset) {
- parserInput.forget();
-
- if (params) {
- return new tree.mixin.Definition(null, params, blockRuleset, null, variadic);
- }
-
- return new tree.DetachedRuleset(blockRuleset);
- }
-
- parserInput.restore();
- },
- //
- // div, .class, body > p {...}
- //
- ruleset: function ruleset() {
- var selectors;
- var rules;
- var debugInfo;
- parserInput.save();
-
- if (context.dumpLineNumbers) {
- debugInfo = getDebugInfo(parserInput.i);
- }
-
- selectors = this.selectors();
-
- if (selectors && (rules = this.block())) {
- parserInput.forget();
- var ruleset = new tree.Ruleset(selectors, rules, context.strictImports);
-
- if (context.dumpLineNumbers) {
- ruleset.debugInfo = debugInfo;
- }
-
return ruleset;
- } else {
- parserInput.restore();
- }
},
- declaration: function declaration() {
- var name;
- var value;
- var index = parserInput.i;
- var hasDR;
- var c = parserInput.currentChar();
- var important;
- var merge;
- var isVariable;
-
- if (c === '.' || c === '#' || c === '&' || c === ':') {
- return;
- }
-
- parserInput.save();
- name = this.variable() || this.ruleProperty();
-
- if (name) {
- isVariable = typeof name === 'string';
-
- if (isVariable) {
- value = this.detachedRuleset();
-
- if (value) {
- hasDR = true;
- }
- }
-
- parserInput.commentStore.length = 0;
-
- if (!value) {
- // a name returned by this.ruleProperty() is always an array of the form:
- // [string-1, ..., string-n, ""] or [string-1, ..., string-n, "+"]
- // where each item is a tree.Keyword or tree.Variable
- merge = !isVariable && name.length > 1 && name.pop().value; // Custom property values get permissive parsing
-
- if (name[0].value && name[0].value.slice(0, 2) === '--') {
- value = this.permissiveValue();
- } // Try to store values as anonymous
- // If we need the value later we'll re-parse it in ruleset.parseValue
- else {
- value = this.anonymousValue();
- }
-
- if (value) {
- parserInput.forget(); // anonymous values absorb the end ';' which is required for them to work
-
- return new tree.Declaration(name, value, false, merge, index, fileInfo);
- }
-
- if (!value) {
- value = this.value();
- }
-
- if (value) {
- important = this.important();
- } else if (isVariable) {
- // As a last resort, try permissiveValue
- value = this.permissiveValue();
- }
- }
-
- if (value && (this.end() || hasDR)) {
- parserInput.forget();
- return new tree.Declaration(name, value, important, merge, index, fileInfo);
- } else {
- parserInput.restore();
- }
- } else {
- parserInput.restore();
- }
- },
- anonymousValue: function anonymousValue() {
- var index = parserInput.i;
- var match = parserInput.$re(/^([^.#@\$+\/'"*`(;{}-]*);/);
-
- if (match) {
- return new tree.Anonymous(match[1], index);
- }
- },
-
- /**
- * Used for custom properties, at-rules, and variables (as fallback)
- * Parses almost anything inside of {} [] () "" blocks
- * until it reaches outer-most tokens.
- *
- * First, it will try to parse comments and entities to reach
- * the end. This is mostly like the Expression parser except no
- * math is allowed.
- */
- permissiveValue: function permissiveValue(untilTokens) {
- var i;
- var e;
- var done;
- var value;
- var tok = untilTokens || ';';
- var index = parserInput.i;
- var result = [];
-
- function testCurrentChar() {
- var char = parserInput.currentChar();
-
- if (typeof tok === 'string') {
- return char === tok;
- } else {
- return tok.test(char);
- }
- }
-
- if (testCurrentChar()) {
- return;
- }
-
- value = [];
-
- do {
- e = this.comment();
-
- if (e) {
- value.push(e);
- continue;
- }
-
- e = this.entity();
-
- if (e) {
- value.push(e);
- }
- } while (e);
-
- done = testCurrentChar();
-
- if (value.length > 0) {
- value = new tree.Expression(value);
-
- if (done) {
- return value;
- } else {
- result.push(value);
- } // Preserve space before $parseUntil as it will not
-
-
- if (parserInput.prevChar() === ' ') {
- result.push(new tree.Anonymous(' ', index));
- }
- }
-
- parserInput.save();
- value = parserInput.$parseUntil(tok);
-
- if (value) {
- if (typeof value === 'string') {
- error("Expected '".concat(value, "'"), 'Parse');
- }
-
- if (value.length === 1 && value[0] === ' ') {
- parserInput.forget();
- return new tree.Anonymous('', index);
- }
-
- var item;
-
- for (i = 0; i < value.length; i++) {
- item = value[i];
-
- if (Array.isArray(item)) {
- // Treat actual quotes as normal quoted values
- result.push(new tree.Quoted(item[0], item[1], true, index, fileInfo));
- } else {
- if (i === value.length - 1) {
- item = item.trim();
- } // Treat like quoted values, but replace vars like unquoted expressions
-
-
- var quote = new tree.Quoted('\'', item, true, index, fileInfo);
- quote.variableRegex = /@([\w-]+)/g;
- quote.propRegex = /\$([\w-]+)/g;
- result.push(quote);
- }
- }
-
- parserInput.forget();
- return new tree.Expression(result, true);
- }
-
- parserInput.restore();
- },
- //
- // An @import atrule
- //
- // @import "lib";
- //
- // Depending on our environment, importing is done differently:
- // In the browser, it's an XHR request, in Node, it would be a
- // file-system operation. The function used for importing is
- // stored in `import`, which we pass to the Import constructor.
- //
- 'import': function _import() {
- var path;
- var features;
- var index = parserInput.i;
- var dir = parserInput.$re(/^@import?\s+/);
-
- if (dir) {
- var options = (dir ? this.importOptions() : null) || {};
-
- if (path = this.entities.quoted() || this.entities.url()) {
- features = this.mediaFeatures();
-
- if (!parserInput.$char(';')) {
- parserInput.i = index;
- error('missing semi-colon or unrecognised media features on import');
- }
-
- features = features && new tree.Value(features);
- return new tree.Import(path, features, options, index, fileInfo);
- } else {
- parserInput.i = index;
- error('malformed import statement');
- }
- }
- },
- importOptions: function importOptions() {
- var o;
- var options = {};
- var optionName;
- var value; // list of options, surrounded by parens
-
- if (!parserInput.$char('(')) {
- return null;
- }
-
- do {
- o = this.importOption();
-
- if (o) {
- optionName = o;
- value = true;
-
- switch (optionName) {
- case 'css':
- optionName = 'less';
- value = false;
- break;
-
- case 'once':
- optionName = 'multiple';
- value = false;
- break;
- }
-
- options[optionName] = value;
-
- if (!parserInput.$char(',')) {
- break;
- }
- }
- } while (o);
-
- expectChar(')');
- return options;
- },
- importOption: function importOption() {
- var opt = parserInput.$re(/^(less|css|multiple|once|inline|reference|optional)/);
-
- if (opt) {
- return opt[1];
- }
- },
- mediaFeature: function mediaFeature() {
- var entities = this.entities;
- var nodes = [];
- var e;
- var p;
- parserInput.save();
-
- do {
- e = entities.keyword() || entities.variable() || entities.mixinLookup();
-
- if (e) {
- nodes.push(e);
- } else if (parserInput.$char('(')) {
- p = this.property();
- e = this.value();
-
- if (parserInput.$char(')')) {
- if (p && e) {
- nodes.push(new tree.Paren(new tree.Declaration(p, e, null, null, parserInput.i, fileInfo, true)));
- } else if (e) {
- nodes.push(new tree.Paren(e));
- } else {
- error('badly formed media feature definition');
- }
- } else {
- error('Missing closing \')\'', 'Parse');
- }
- }
- } while (e);
-
- parserInput.forget();
-
- if (nodes.length > 0) {
- return new tree.Expression(nodes);
- }
- },
- mediaFeatures: function mediaFeatures() {
- var entities = this.entities;
- var features = [];
- var e;
-
- do {
- e = this.mediaFeature();
-
- if (e) {
- features.push(e);
-
- if (!parserInput.$char(',')) {
- break;
- }
- } else {
- e = entities.variable() || entities.mixinLookup();
-
- if (e) {
- features.push(e);
-
- if (!parserInput.$char(',')) {
- break;
- }
- }
- }
- } while (e);
-
- return features.length > 0 ? features : null;
- },
- media: function media() {
- var features;
- var rules;
- var media;
- var debugInfo;
- var index = parserInput.i;
-
- if (context.dumpLineNumbers) {
- debugInfo = getDebugInfo(index);
- }
-
- parserInput.save();
-
- if (parserInput.$str('@media')) {
- features = this.mediaFeatures();
- rules = this.block();
-
+ evalImports: function (context) {
+ var rules = this.rules;
+ var i;
+ var importRules;
if (!rules) {
- error('media definitions require block statements after any features');
+ return;
}
-
- parserInput.forget();
- media = new tree.Media(rules, features, index, fileInfo);
-
- if (context.dumpLineNumbers) {
- media.debugInfo = debugInfo;
+ for (i = 0; i < rules.length; i++) {
+ if (rules[i].type === 'Import') {
+ importRules = rules[i].eval(context);
+ if (importRules && (importRules.length || importRules.length === 0)) {
+ rules.splice.apply(rules, [i, 1].concat(importRules));
+ i += importRules.length - 1;
+ }
+ else {
+ rules.splice(i, 1, importRules);
+ }
+ this.resetCache();
+ }
}
-
- return media;
- }
-
- parserInput.restore();
},
- //
- // A @plugin directive, used to import plugins dynamically.
- //
- // @plugin (args) "lib";
- //
- plugin: function plugin() {
- var path;
- var args;
- var options;
- var index = parserInput.i;
- var dir = parserInput.$re(/^@plugin?\s+/);
-
- if (dir) {
- args = this.pluginArgs();
-
- if (args) {
- options = {
- pluginArgs: args,
- isPlugin: true
- };
- } else {
- options = {
- isPlugin: true
- };
- }
-
- if (path = this.entities.quoted() || this.entities.url()) {
- if (!parserInput.$char(';')) {
- parserInput.i = index;
- error('missing semi-colon on @plugin');
- }
-
- return new tree.Import(path, null, options, index, fileInfo);
- } else {
- parserInput.i = index;
- error('malformed @plugin statement');
- }
- }
- },
- pluginArgs: function pluginArgs() {
- // list of options, surrounded by parens
- parserInput.save();
-
- if (!parserInput.$char('(')) {
- parserInput.restore();
- return null;
- }
-
- var args = parserInput.$re(/^\s*([^\);]+)\)\s*/);
-
- if (args[1]) {
- parserInput.forget();
- return args[1].trim();
- } else {
- parserInput.restore();
- return null;
- }
- },
- //
- // A CSS AtRule
- //
- // @charset "utf-8";
- //
- atrule: function atrule() {
- var index = parserInput.i;
- var name;
- var value;
- var rules;
- var nonVendorSpecificName;
- var hasIdentifier;
- var hasExpression;
- var hasUnknown;
- var hasBlock = true;
- var isRooted = true;
-
- if (parserInput.currentChar() !== '@') {
- return;
- }
-
- value = this['import']() || this.plugin() || this.media();
-
- if (value) {
- return value;
- }
-
- parserInput.save();
- name = parserInput.$re(/^@[a-z-]+/);
-
- if (!name) {
- return;
- }
-
- nonVendorSpecificName = name;
-
- if (name.charAt(1) == '-' && name.indexOf('-', 2) > 0) {
- nonVendorSpecificName = "@".concat(name.slice(name.indexOf('-', 2) + 1));
- }
-
- switch (nonVendorSpecificName) {
- case '@charset':
- hasIdentifier = true;
- hasBlock = false;
- break;
-
- case '@namespace':
- hasExpression = true;
- hasBlock = false;
- break;
-
- case '@keyframes':
- case '@counter-style':
- hasIdentifier = true;
- break;
-
- case '@document':
- case '@supports':
- hasUnknown = true;
- isRooted = false;
- break;
-
- default:
- hasUnknown = true;
- break;
- }
-
- parserInput.commentStore.length = 0;
-
- if (hasIdentifier) {
- value = this.entity();
-
- if (!value) {
- error("expected ".concat(name, " identifier"));
- }
- } else if (hasExpression) {
- value = this.expression();
-
- if (!value) {
- error("expected ".concat(name, " expression"));
- }
- } else if (hasUnknown) {
- value = this.permissiveValue(/^[{;]/);
- hasBlock = parserInput.currentChar() === '{';
-
- if (!value) {
- if (!hasBlock && parserInput.currentChar() !== ';') {
- error("".concat(name, " rule is missing block or ending semi-colon"));
- }
- } else if (!value.value) {
- value = null;
- }
- }
-
- if (hasBlock) {
- rules = this.blockRuleset();
- }
-
- if (rules || !hasBlock && value && parserInput.$char(';')) {
- parserInput.forget();
- return new tree.AtRule(name, value, rules, index, fileInfo, context.dumpLineNumbers ? getDebugInfo(index) : null, isRooted);
- }
-
- parserInput.restore('at-rule options not recognised');
- },
- //
- // A Value is a comma-delimited list of Expressions
- //
- // font-family: Baskerville, Georgia, serif;
- //
- // In a Rule, a Value represents everything after the `:`,
- // and before the `;`.
- //
- value: function value() {
- var e;
- var expressions = [];
- var index = parserInput.i;
-
- do {
- e = this.expression();
-
- if (e) {
- expressions.push(e);
-
- if (!parserInput.$char(',')) {
- break;
- }
- }
- } while (e);
-
- if (expressions.length > 0) {
- return new tree.Value(expressions, index);
- }
- },
- important: function important() {
- if (parserInput.currentChar() === '!') {
- return parserInput.$re(/^! *important/);
- }
- },
- sub: function sub() {
- var a;
- var e;
- parserInput.save();
-
- if (parserInput.$char('(')) {
- a = this.addition();
-
- if (a && parserInput.$char(')')) {
- parserInput.forget();
- e = new tree.Expression([a]);
- e.parens = true;
- return e;
- }
-
- parserInput.restore('Expected \')\'');
- return;
- }
-
- parserInput.restore();
- },
- multiplication: function multiplication() {
- var m;
- var a;
- var op;
- var operation;
- var isSpaced;
- m = this.operand();
-
- if (m) {
- isSpaced = parserInput.isWhitespace(-1);
-
- while (true) {
- if (parserInput.peek(/^\/[*\/]/)) {
- break;
- }
-
- parserInput.save();
- op = parserInput.$char('/') || parserInput.$char('*') || parserInput.$str('./');
-
- if (!op) {
- parserInput.forget();
- break;
- }
-
- a = this.operand();
-
- if (!a) {
- parserInput.restore();
- break;
- }
-
- parserInput.forget();
- m.parensInOp = true;
- a.parensInOp = true;
- operation = new tree.Operation(op, [operation || m, a], isSpaced);
- isSpaced = parserInput.isWhitespace(-1);
- }
-
- return operation || m;
- }
- },
- addition: function addition() {
- var m;
- var a;
- var op;
- var operation;
- var isSpaced;
- m = this.multiplication();
-
- if (m) {
- isSpaced = parserInput.isWhitespace(-1);
-
- while (true) {
- op = parserInput.$re(/^[-+]\s+/) || !isSpaced && (parserInput.$char('+') || parserInput.$char('-'));
-
- if (!op) {
- break;
- }
-
- a = this.multiplication();
-
- if (!a) {
- break;
- }
-
- m.parensInOp = true;
- a.parensInOp = true;
- operation = new tree.Operation(op, [operation || m, a], isSpaced);
- isSpaced = parserInput.isWhitespace(-1);
- }
-
- return operation || m;
- }
- },
- conditions: function conditions() {
- var a;
- var b;
- var index = parserInput.i;
- var condition;
- a = this.condition(true);
-
- if (a) {
- while (true) {
- if (!parserInput.peek(/^,\s*(not\s*)?\(/) || !parserInput.$char(',')) {
- break;
- }
-
- b = this.condition(true);
-
- if (!b) {
- break;
- }
-
- condition = new tree.Condition('or', condition || a, b, index);
- }
-
- return condition || a;
- }
- },
- condition: function condition(needsParens) {
- var result;
- var logical;
- var next;
-
- function or() {
- return parserInput.$str('or');
- }
-
- result = this.conditionAnd(needsParens);
-
- if (!result) {
- return;
- }
-
- logical = or();
-
- if (logical) {
- next = this.condition(needsParens);
-
- if (next) {
- result = new tree.Condition(logical, result, next);
- } else {
- return;
- }
- }
-
- return result;
- },
- conditionAnd: function conditionAnd(needsParens) {
- var result;
- var logical;
- var next;
- var self = this;
-
- function insideCondition() {
- var cond = self.negatedCondition(needsParens) || self.parenthesisCondition(needsParens);
-
- if (!cond && !needsParens) {
- return self.atomicCondition(needsParens);
- }
-
- return cond;
- }
-
- function and() {
- return parserInput.$str('and');
- }
-
- result = insideCondition();
-
- if (!result) {
- return;
- }
-
- logical = and();
-
- if (logical) {
- next = this.conditionAnd(needsParens);
-
- if (next) {
- result = new tree.Condition(logical, result, next);
- } else {
- return;
- }
- }
-
- return result;
- },
- negatedCondition: function negatedCondition(needsParens) {
- if (parserInput.$str('not')) {
- var result = this.parenthesisCondition(needsParens);
-
- if (result) {
- result.negate = !result.negate;
- }
-
+ makeImportant: function () {
+ var result = new Ruleset(this.selectors, this.rules.map(function (r) {
+ if (r.makeImportant) {
+ return r.makeImportant();
+ }
+ else {
+ return r;
+ }
+ }), this.strictImports, this.visibilityInfo());
return result;
- }
},
- parenthesisCondition: function parenthesisCondition(needsParens) {
- function tryConditionFollowedByParenthesis(me) {
- var body;
- parserInput.save();
- body = me.condition(needsParens);
-
- if (!body) {
- parserInput.restore();
- return;
- }
-
- if (!parserInput.$char(')')) {
- parserInput.restore();
- return;
- }
-
- parserInput.forget();
- return body;
- }
-
- var body;
- parserInput.save();
-
- if (!parserInput.$str('(')) {
- parserInput.restore();
- return;
- }
-
- body = tryConditionFollowedByParenthesis(this);
-
- if (body) {
- parserInput.forget();
- return body;
- }
-
- body = this.atomicCondition(needsParens);
-
- if (!body) {
- parserInput.restore();
- return;
- }
-
- if (!parserInput.$char(')')) {
- parserInput.restore("expected ')' got '".concat(parserInput.currentChar(), "'"));
- return;
- }
-
- parserInput.forget();
- return body;
+ matchArgs: function (args) {
+ return !args || args.length === 0;
},
- atomicCondition: function atomicCondition(needsParens) {
- var entities = this.entities;
- var index = parserInput.i;
- var a;
- var b;
- var c;
- var op;
-
- function cond() {
- return this.addition() || entities.keyword() || entities.quoted() || entities.mixinLookup();
- }
-
- cond = cond.bind(this);
- a = cond();
-
- if (a) {
- if (parserInput.$char('>')) {
- if (parserInput.$char('=')) {
- op = '>=';
- } else {
- op = '>';
- }
- } else if (parserInput.$char('<')) {
- if (parserInput.$char('=')) {
- op = '<=';
- } else {
- op = '<';
- }
- } else if (parserInput.$char('=')) {
- if (parserInput.$char('>')) {
- op = '=>';
- } else if (parserInput.$char('<')) {
- op = '=<';
- } else {
- op = '=';
- }
+ // lets you call a css selector with a guard
+ matchCondition: function (args, context) {
+ var lastSelector = this.selectors[this.selectors.length - 1];
+ if (!lastSelector.evaldCondition) {
+ return false;
}
-
- if (op) {
- b = cond();
-
- if (b) {
- c = new tree.Condition(op, a, b, index, false);
- } else {
- error('expected expression');
- }
- } else {
- c = new tree.Condition('=', a, new tree.Keyword('true'), index, false);
+ if (lastSelector.condition &&
+ !lastSelector.condition.eval(new contexts.Eval(context, context.frames))) {
+ return false;
}
-
- return c;
- }
+ return true;
},
- //
- // An operand is anything that can be part of an operation,
- // such as a Color, or a Variable
- //
- operand: function operand() {
- var entities = this.entities;
- var negate;
-
- if (parserInput.peek(/^-[@\$\(]/)) {
- negate = parserInput.$char('-');
- }
-
- var o = this.sub() || entities.dimension() || entities.color() || entities.variable() || entities.property() || entities.call() || entities.quoted(true) || entities.colorKeyword() || entities.mixinLookup();
-
- if (negate) {
- o.parensInOp = true;
- o = new tree.Negative(o);
- }
-
- return o;
+ resetCache: function () {
+ this._rulesets = null;
+ this._variables = null;
+ this._properties = null;
+ this._lookups = {};
},
- //
- // Expressions either represent mathematical operations,
- // or white-space delimited Entities.
- //
- // 1px solid black
- // @var * 2
- //
- expression: function expression() {
- var entities = [];
- var e;
- var delim;
- var index = parserInput.i;
-
- do {
- e = this.comment();
-
- if (e) {
- entities.push(e);
- continue;
+ variables: function () {
+ if (!this._variables) {
+ this._variables = !this.rules ? {} : this.rules.reduce(function (hash, r) {
+ if (r instanceof Declaration && r.variable === true) {
+ hash[r.name] = r;
+ }
+ // when evaluating variables in an import statement, imports have not been eval'd
+ // so we need to go inside import statements.
+ // guard against root being a string (in the case of inlined less)
+ if (r.type === 'Import' && r.root && r.root.variables) {
+ var vars = r.root.variables();
+ for (var name_1 in vars) {
+ if (vars.hasOwnProperty(name_1)) {
+ hash[name_1] = r.root.variable(name_1);
+ }
+ }
+ }
+ return hash;
+ }, {});
}
-
- e = this.addition() || this.entity();
-
- if (e) {
- entities.push(e); // operations do not allow keyword "/" dimension (e.g. small/20px) so we support that here
-
- if (!parserInput.peek(/^\/[\/*]/)) {
- delim = parserInput.$char('/');
-
- if (delim) {
- entities.push(new tree.Anonymous(delim, index));
+ return this._variables;
+ },
+ properties: function () {
+ if (!this._properties) {
+ this._properties = !this.rules ? {} : this.rules.reduce(function (hash, r) {
+ if (r instanceof Declaration && r.variable !== true) {
+ var name_2 = (r.name.length === 1) && (r.name[0] instanceof Keyword) ?
+ r.name[0].value : r.name;
+ // Properties don't overwrite as they can merge
+ if (!hash["$" + name_2]) {
+ hash["$" + name_2] = [r];
+ }
+ else {
+ hash["$" + name_2].push(r);
+ }
+ }
+ return hash;
+ }, {});
+ }
+ return this._properties;
+ },
+ variable: function (name) {
+ var decl = this.variables()[name];
+ if (decl) {
+ return this.parseValue(decl);
+ }
+ },
+ property: function (name) {
+ var decl = this.properties()[name];
+ if (decl) {
+ return this.parseValue(decl);
+ }
+ },
+ lastDeclaration: function () {
+ for (var i = this.rules.length; i > 0; i--) {
+ var decl = this.rules[i - 1];
+ if (decl instanceof Declaration) {
+ return this.parseValue(decl);
}
- }
}
- } while (e);
-
- if (entities.length > 0) {
- return new tree.Expression(entities);
- }
},
- property: function property() {
- var name = parserInput.$re(/^(\*?-?[_a-zA-Z0-9-]+)\s*:/);
-
- if (name) {
- return name[1];
- }
+ parseValue: function (toParse) {
+ var self = this;
+ function transformDeclaration(decl) {
+ if (decl.value instanceof Anonymous && !decl.parsed) {
+ if (typeof decl.value.value === 'string') {
+ this.parse.parseNode(decl.value.value, ['value', 'important'], decl.value.getIndex(), decl.fileInfo(), function (err, result) {
+ if (err) {
+ decl.parsed = true;
+ }
+ if (result) {
+ decl.value = result[0];
+ decl.important = result[1] || '';
+ decl.parsed = true;
+ }
+ });
+ }
+ else {
+ decl.parsed = true;
+ }
+ return decl;
+ }
+ else {
+ return decl;
+ }
+ }
+ if (!Array.isArray(toParse)) {
+ return transformDeclaration.call(self, toParse);
+ }
+ else {
+ var nodes_1 = [];
+ toParse.forEach(function (n) {
+ nodes_1.push(transformDeclaration.call(self, n));
+ });
+ return nodes_1;
+ }
},
- ruleProperty: function ruleProperty() {
- var name = [];
- var index = [];
- var s;
- var k;
- parserInput.save();
- var simpleProperty = parserInput.$re(/^([_a-zA-Z0-9-]+)\s*:/);
-
- if (simpleProperty) {
- name = [new tree.Keyword(simpleProperty[1])];
- parserInput.forget();
- return name;
- }
-
- function match(re) {
- var i = parserInput.i;
- var chunk = parserInput.$re(re);
-
- if (chunk) {
- index.push(i);
- return name.push(chunk[1]);
+ rulesets: function () {
+ if (!this.rules) {
+ return [];
}
- }
-
- match(/^(\*?)/);
-
- while (true) {
- if (!match(/^((?:[\w-]+)|(?:[@\$]\{[\w-]+\}))/)) {
- break;
+ var filtRules = [];
+ var rules = this.rules;
+ var i;
+ var rule;
+ for (i = 0; (rule = rules[i]); i++) {
+ if (rule.isRuleset) {
+ filtRules.push(rule);
+ }
}
- }
-
- if (name.length > 1 && match(/^((?:\+_|\+)?)\s*:/)) {
- parserInput.forget(); // at last, we have the complete match now. move forward,
- // convert name particles to tree objects and return:
-
- if (name[0] === '') {
- name.shift();
- index.shift();
+ return filtRules;
+ },
+ prependRule: function (rule) {
+ var rules = this.rules;
+ if (rules) {
+ rules.unshift(rule);
}
-
- for (k = 0; k < name.length; k++) {
- s = name[k];
- name[k] = s.charAt(0) !== '@' && s.charAt(0) !== '$' ? new tree.Keyword(s) : s.charAt(0) === '@' ? new tree.Variable("@".concat(s.slice(2, -1)), index[k], fileInfo) : new tree.Property("$".concat(s.slice(2, -1)), index[k], fileInfo);
+ else {
+ this.rules = [rule];
+ }
+ this.setParent(rule, this);
+ },
+ find: function (selector, self, filter) {
+ self = self || this;
+ var rules = [];
+ var match;
+ var foundMixins;
+ var key = selector.toCSS();
+ if (key in this._lookups) {
+ return this._lookups[key];
+ }
+ this.rulesets().forEach(function (rule) {
+ if (rule !== self) {
+ for (var j = 0; j < rule.selectors.length; j++) {
+ match = selector.match(rule.selectors[j]);
+ if (match) {
+ if (selector.elements.length > match) {
+ if (!filter || filter(rule)) {
+ foundMixins = rule.find(new Selector(selector.elements.slice(match)), self, filter);
+ for (var i = 0; i < foundMixins.length; ++i) {
+ foundMixins[i].path.push(rule);
+ }
+ Array.prototype.push.apply(rules, foundMixins);
+ }
+ }
+ else {
+ rules.push({ rule: rule, path: [] });
+ }
+ break;
+ }
+ }
+ }
+ });
+ this._lookups[key] = rules;
+ return rules;
+ },
+ genCSS: function (context, output) {
+ var i;
+ var j;
+ var charsetRuleNodes = [];
+ var ruleNodes = [];
+ var // Line number debugging
+ debugInfo$1;
+ var rule;
+ var path;
+ context.tabLevel = (context.tabLevel || 0);
+ if (!this.root) {
+ context.tabLevel++;
+ }
+ var tabRuleStr = context.compress ? '' : Array(context.tabLevel + 1).join(' ');
+ var tabSetStr = context.compress ? '' : Array(context.tabLevel).join(' ');
+ var sep;
+ var charsetNodeIndex = 0;
+ var importNodeIndex = 0;
+ for (i = 0; (rule = this.rules[i]); i++) {
+ if (rule instanceof Comment) {
+ if (importNodeIndex === i) {
+ importNodeIndex++;
+ }
+ ruleNodes.push(rule);
+ }
+ else if (rule.isCharset && rule.isCharset()) {
+ ruleNodes.splice(charsetNodeIndex, 0, rule);
+ charsetNodeIndex++;
+ importNodeIndex++;
+ }
+ else if (rule.type === 'Import') {
+ ruleNodes.splice(importNodeIndex, 0, rule);
+ importNodeIndex++;
+ }
+ else {
+ ruleNodes.push(rule);
+ }
+ }
+ ruleNodes = charsetRuleNodes.concat(ruleNodes);
+ // If this is the root node, we don't render
+ // a selector, or {}.
+ if (!this.root) {
+ debugInfo$1 = debugInfo(context, this, tabSetStr);
+ if (debugInfo$1) {
+ output.add(debugInfo$1);
+ output.add(tabSetStr);
+ }
+ var paths = this.paths;
+ var pathCnt = paths.length;
+ var pathSubCnt = void 0;
+ sep = context.compress ? ',' : (",\n" + tabSetStr);
+ for (i = 0; i < pathCnt; i++) {
+ path = paths[i];
+ if (!(pathSubCnt = path.length)) {
+ continue;
+ }
+ if (i > 0) {
+ output.add(sep);
+ }
+ context.firstSelector = true;
+ path[0].genCSS(context, output);
+ context.firstSelector = false;
+ for (j = 1; j < pathSubCnt; j++) {
+ path[j].genCSS(context, output);
+ }
+ }
+ output.add((context.compress ? '{' : ' {\n') + tabRuleStr);
+ }
+ // Compile rules and rulesets
+ for (i = 0; (rule = ruleNodes[i]); i++) {
+ if (i + 1 === ruleNodes.length) {
+ context.lastRule = true;
+ }
+ var currentLastRule = context.lastRule;
+ if (rule.isRulesetLike(rule)) {
+ context.lastRule = false;
+ }
+ if (rule.genCSS) {
+ rule.genCSS(context, output);
+ }
+ else if (rule.value) {
+ output.add(rule.value.toString());
+ }
+ context.lastRule = currentLastRule;
+ if (!context.lastRule && rule.isVisible()) {
+ output.add(context.compress ? '' : ("\n" + tabRuleStr));
+ }
+ else {
+ context.lastRule = false;
+ }
+ }
+ if (!this.root) {
+ output.add((context.compress ? '}' : "\n" + tabSetStr + "}"));
+ context.tabLevel--;
+ }
+ if (!output.isEmpty() && !context.compress && this.firstRoot) {
+ output.add('\n');
+ }
+ },
+ joinSelectors: function (paths, context, selectors) {
+ for (var s = 0; s < selectors.length; s++) {
+ this.joinSelector(paths, context, selectors[s]);
+ }
+ },
+ joinSelector: function (paths, context, selector) {
+ function createParenthesis(elementsToPak, originalElement) {
+ var replacementParen, j;
+ if (elementsToPak.length === 0) {
+ replacementParen = new Paren(elementsToPak[0]);
+ }
+ else {
+ var insideParent = new Array(elementsToPak.length);
+ for (j = 0; j < elementsToPak.length; j++) {
+ insideParent[j] = new Element(null, elementsToPak[j], originalElement.isVariable, originalElement._index, originalElement._fileInfo);
+ }
+ replacementParen = new Paren(new Selector(insideParent));
+ }
+ return replacementParen;
+ }
+ function createSelector(containedElement, originalElement) {
+ var element, selector;
+ element = new Element(null, containedElement, originalElement.isVariable, originalElement._index, originalElement._fileInfo);
+ selector = new Selector([element]);
+ return selector;
+ }
+ // joins selector path from `beginningPath` with selector path in `addPath`
+ // `replacedElement` contains element that is being replaced by `addPath`
+ // returns concatenated path
+ function addReplacementIntoPath(beginningPath, addPath, replacedElement, originalSelector) {
+ var newSelectorPath, lastSelector, newJoinedSelector;
+ // our new selector path
+ newSelectorPath = [];
+ // construct the joined selector - if & is the first thing this will be empty,
+ // if not newJoinedSelector will be the last set of elements in the selector
+ if (beginningPath.length > 0) {
+ newSelectorPath = copyArray(beginningPath);
+ lastSelector = newSelectorPath.pop();
+ newJoinedSelector = originalSelector.createDerived(copyArray(lastSelector.elements));
+ }
+ else {
+ newJoinedSelector = originalSelector.createDerived([]);
+ }
+ if (addPath.length > 0) {
+ // /deep/ is a CSS4 selector - (removed, so should deprecate)
+ // that is valid without anything in front of it
+ // so if the & does not have a combinator that is "" or " " then
+ // and there is a combinator on the parent, then grab that.
+ // this also allows + a { & .b { .a & { ... though not sure why you would want to do that
+ var combinator = replacedElement.combinator;
+ var parentEl = addPath[0].elements[0];
+ if (combinator.emptyOrWhitespace && !parentEl.combinator.emptyOrWhitespace) {
+ combinator = parentEl.combinator;
+ }
+ // join the elements so far with the first part of the parent
+ newJoinedSelector.elements.push(new Element(combinator, parentEl.value, replacedElement.isVariable, replacedElement._index, replacedElement._fileInfo));
+ newJoinedSelector.elements = newJoinedSelector.elements.concat(addPath[0].elements.slice(1));
+ }
+ // now add the joined selector - but only if it is not empty
+ if (newJoinedSelector.elements.length !== 0) {
+ newSelectorPath.push(newJoinedSelector);
+ }
+ // put together the parent selectors after the join (e.g. the rest of the parent)
+ if (addPath.length > 1) {
+ var restOfPath = addPath.slice(1);
+ restOfPath = restOfPath.map(function (selector) {
+ return selector.createDerived(selector.elements, []);
+ });
+ newSelectorPath = newSelectorPath.concat(restOfPath);
+ }
+ return newSelectorPath;
+ }
+ // joins selector path from `beginningPath` with every selector path in `addPaths` array
+ // `replacedElement` contains element that is being replaced by `addPath`
+ // returns array with all concatenated paths
+ function addAllReplacementsIntoPath(beginningPath, addPaths, replacedElement, originalSelector, result) {
+ var j;
+ for (j = 0; j < beginningPath.length; j++) {
+ var newSelectorPath = addReplacementIntoPath(beginningPath[j], addPaths, replacedElement, originalSelector);
+ result.push(newSelectorPath);
+ }
+ return result;
+ }
+ function mergeElementsOnToSelectors(elements, selectors) {
+ var i, sel;
+ if (elements.length === 0) {
+ return;
+ }
+ if (selectors.length === 0) {
+ selectors.push([new Selector(elements)]);
+ return;
+ }
+ for (i = 0; (sel = selectors[i]); i++) {
+ // if the previous thing in sel is a parent this needs to join on to it
+ if (sel.length > 0) {
+ sel[sel.length - 1] = sel[sel.length - 1].createDerived(sel[sel.length - 1].elements.concat(elements));
+ }
+ else {
+ sel.push(new Selector(elements));
+ }
+ }
+ }
+ // replace all parent selectors inside `inSelector` by content of `context` array
+ // resulting selectors are returned inside `paths` array
+ // returns true if `inSelector` contained at least one parent selector
+ function replaceParentSelector(paths, context, inSelector) {
+ // The paths are [[Selector]]
+ // The first list is a list of comma separated selectors
+ // The inner list is a list of inheritance separated selectors
+ // e.g.
+ // .a, .b {
+ // .c {
+ // }
+ // }
+ // == [[.a] [.c]] [[.b] [.c]]
+ //
+ var i, j, k, currentElements, newSelectors, selectorsMultiplied, sel, el, hadParentSelector = false, length, lastSelector;
+ function findNestedSelector(element) {
+ var maybeSelector;
+ if (!(element.value instanceof Paren)) {
+ return null;
+ }
+ maybeSelector = element.value.value;
+ if (!(maybeSelector instanceof Selector)) {
+ return null;
+ }
+ return maybeSelector;
+ }
+ // the elements from the current selector so far
+ currentElements = [];
+ // the current list of new selectors to add to the path.
+ // We will build it up. We initiate it with one empty selector as we "multiply" the new selectors
+ // by the parents
+ newSelectors = [
+ []
+ ];
+ for (i = 0; (el = inSelector.elements[i]); i++) {
+ // non parent reference elements just get added
+ if (el.value !== '&') {
+ var nestedSelector = findNestedSelector(el);
+ if (nestedSelector != null) {
+ // merge the current list of non parent selector elements
+ // on to the current list of selectors to add
+ mergeElementsOnToSelectors(currentElements, newSelectors);
+ var nestedPaths = [];
+ var replaced = void 0;
+ var replacedNewSelectors = [];
+ replaced = replaceParentSelector(nestedPaths, context, nestedSelector);
+ hadParentSelector = hadParentSelector || replaced;
+ // the nestedPaths array should have only one member - replaceParentSelector does not multiply selectors
+ for (k = 0; k < nestedPaths.length; k++) {
+ var replacementSelector = createSelector(createParenthesis(nestedPaths[k], el), el);
+ addAllReplacementsIntoPath(newSelectors, [replacementSelector], el, inSelector, replacedNewSelectors);
+ }
+ newSelectors = replacedNewSelectors;
+ currentElements = [];
+ }
+ else {
+ currentElements.push(el);
+ }
+ }
+ else {
+ hadParentSelector = true;
+ // the new list of selectors to add
+ selectorsMultiplied = [];
+ // merge the current list of non parent selector elements
+ // on to the current list of selectors to add
+ mergeElementsOnToSelectors(currentElements, newSelectors);
+ // loop through our current selectors
+ for (j = 0; j < newSelectors.length; j++) {
+ sel = newSelectors[j];
+ // if we don't have any parent paths, the & might be in a mixin so that it can be used
+ // whether there are parents or not
+ if (context.length === 0) {
+ // the combinator used on el should now be applied to the next element instead so that
+ // it is not lost
+ if (sel.length > 0) {
+ sel[0].elements.push(new Element(el.combinator, '', el.isVariable, el._index, el._fileInfo));
+ }
+ selectorsMultiplied.push(sel);
+ }
+ else {
+ // and the parent selectors
+ for (k = 0; k < context.length; k++) {
+ // We need to put the current selectors
+ // then join the last selector's elements on to the parents selectors
+ var newSelectorPath = addReplacementIntoPath(sel, context[k], el, inSelector);
+ // add that to our new set of selectors
+ selectorsMultiplied.push(newSelectorPath);
+ }
+ }
+ }
+ // our new selectors has been multiplied, so reset the state
+ newSelectors = selectorsMultiplied;
+ currentElements = [];
+ }
+ }
+ // if we have any elements left over (e.g. .a& .b == .b)
+ // add them on to all the current selectors
+ mergeElementsOnToSelectors(currentElements, newSelectors);
+ for (i = 0; i < newSelectors.length; i++) {
+ length = newSelectors[i].length;
+ if (length > 0) {
+ paths.push(newSelectors[i]);
+ lastSelector = newSelectors[i][length - 1];
+ newSelectors[i][length - 1] = lastSelector.createDerived(lastSelector.elements, inSelector.extendList);
+ }
+ }
+ return hadParentSelector;
+ }
+ function deriveSelector(visibilityInfo, deriveFrom) {
+ var newSelector = deriveFrom.createDerived(deriveFrom.elements, deriveFrom.extendList, deriveFrom.evaldCondition);
+ newSelector.copyVisibilityInfo(visibilityInfo);
+ return newSelector;
+ }
+ // joinSelector code follows
+ var i, newPaths, hadParentSelector;
+ newPaths = [];
+ hadParentSelector = replaceParentSelector(newPaths, context, selector);
+ if (!hadParentSelector) {
+ if (context.length > 0) {
+ newPaths = [];
+ for (i = 0; i < context.length; i++) {
+ var concatenated = context[i].map(deriveSelector.bind(this, selector.visibilityInfo()));
+ concatenated.push(selector);
+ newPaths.push(concatenated);
+ }
+ }
+ else {
+ newPaths = [[selector]];
+ }
+ }
+ for (i = 0; i < newPaths.length; i++) {
+ paths.push(newPaths[i]);
}
-
- return name;
- }
-
- parserInput.restore();
}
- }
- };
- };
+ });
- Parser.serializeVars = function (vars) {
- var s = '';
-
- for (var name in vars) {
- if (Object.hasOwnProperty.call(vars, name)) {
- var value = vars[name];
- s += "".concat((name[0] === '@' ? '' : '@') + name, ": ").concat(value).concat(String(value).slice(-1) === ';' ? '' : ';');
- }
- }
-
- return s;
- };
-
- function boolean(condition) {
- return condition ? Keyword.True : Keyword.False;
- }
-
- function If(condition, trueValue, falseValue) {
- return condition ? trueValue : falseValue || new Anonymous();
- }
-
- var boolean$1 = {
- boolean: boolean,
- 'if': If
- };
-
- var colorFunctions;
-
- function clamp$1(val) {
- return Math.min(1, Math.max(0, val));
- }
-
- function hsla(origColor, hsl) {
- var color = colorFunctions.hsla(hsl.h, hsl.s, hsl.l, hsl.a);
-
- if (color) {
- if (origColor.value && /^(rgb|hsl)/.test(origColor.value)) {
- color.value = origColor.value;
- } else {
- color.value = 'rgb';
- }
-
- return color;
- }
- }
-
- function toHSL(color) {
- if (color.toHSL) {
- return color.toHSL();
- } else {
- throw new Error('Argument cannot be evaluated to a color');
- }
- }
-
- function toHSV(color) {
- if (color.toHSV) {
- return color.toHSV();
- } else {
- throw new Error('Argument cannot be evaluated to a color');
- }
- }
-
- function number(n) {
- if (n instanceof Dimension) {
- return parseFloat(n.unit.is('%') ? n.value / 100 : n.value);
- } else if (typeof n === 'number') {
- return n;
- } else {
- throw {
- type: 'Argument',
- message: 'color functions take numbers as parameters'
- };
- }
- }
-
- function scaled(n, size) {
- if (n instanceof Dimension && n.unit.is('%')) {
- return parseFloat(n.value * size / 100);
- } else {
- return number(n);
- }
- }
-
- colorFunctions = {
- rgb: function rgb(r, g, b) {
- var color = colorFunctions.rgba(r, g, b, 1.0);
-
- if (color) {
- color.value = 'rgb';
- return color;
- }
- },
- rgba: function rgba(r, g, b, a) {
- try {
- if (r instanceof Color) {
- if (g) {
- a = number(g);
- } else {
- a = r.alpha;
- }
-
- return new Color(r.rgb, a, 'rgba');
- }
-
- var rgb = [r, g, b].map(function (c) {
- return scaled(c, 255);
- });
- a = number(a);
- return new Color(rgb, a, 'rgba');
- } catch (e) {}
- },
- hsl: function hsl(h, s, l) {
- var color = colorFunctions.hsla(h, s, l, 1.0);
-
- if (color) {
- color.value = 'hsl';
- return color;
- }
- },
- hsla: function hsla(h, s, l, a) {
- try {
- var hue = function hue(h) {
- h = h < 0 ? h + 1 : h > 1 ? h - 1 : h;
-
- if (h * 6 < 1) {
- return m1 + (m2 - m1) * h * 6;
- } else if (h * 2 < 1) {
- return m2;
- } else if (h * 3 < 2) {
- return m1 + (m2 - m1) * (2 / 3 - h) * 6;
- } else {
- return m1;
- }
- };
-
- if (h instanceof Color) {
- if (s) {
- a = number(s);
- } else {
- a = h.alpha;
- }
-
- return new Color(h.rgb, a, 'hsla');
- }
-
- var m1;
- var m2;
- h = number(h) % 360 / 360;
- s = clamp$1(number(s));
- l = clamp$1(number(l));
- a = clamp$1(number(a));
- m2 = l <= 0.5 ? l * (s + 1) : l + s - l * s;
- m1 = l * 2 - m2;
- var rgb = [hue(h + 1 / 3) * 255, hue(h) * 255, hue(h - 1 / 3) * 255];
- a = number(a);
- return new Color(rgb, a, 'hsla');
- } catch (e) {}
- },
- hsv: function hsv(h, s, v) {
- return colorFunctions.hsva(h, s, v, 1.0);
- },
- hsva: function hsva(h, s, v, a) {
- h = number(h) % 360 / 360 * 360;
- s = number(s);
- v = number(v);
- a = number(a);
- var i;
- var f;
- i = Math.floor(h / 60 % 6);
- f = h / 60 - i;
- var vs = [v, v * (1 - s), v * (1 - f * s), v * (1 - (1 - f) * s)];
- var perm = [[0, 3, 1], [2, 0, 1], [1, 0, 3], [1, 2, 0], [3, 1, 0], [0, 1, 2]];
- return colorFunctions.rgba(vs[perm[i][0]] * 255, vs[perm[i][1]] * 255, vs[perm[i][2]] * 255, a);
- },
- hue: function hue(color) {
- return new Dimension(toHSL(color).h);
- },
- saturation: function saturation(color) {
- return new Dimension(toHSL(color).s * 100, '%');
- },
- lightness: function lightness(color) {
- return new Dimension(toHSL(color).l * 100, '%');
- },
- hsvhue: function hsvhue(color) {
- return new Dimension(toHSV(color).h);
- },
- hsvsaturation: function hsvsaturation(color) {
- return new Dimension(toHSV(color).s * 100, '%');
- },
- hsvvalue: function hsvvalue(color) {
- return new Dimension(toHSV(color).v * 100, '%');
- },
- red: function red(color) {
- return new Dimension(color.rgb[0]);
- },
- green: function green(color) {
- return new Dimension(color.rgb[1]);
- },
- blue: function blue(color) {
- return new Dimension(color.rgb[2]);
- },
- alpha: function alpha(color) {
- return new Dimension(toHSL(color).a);
- },
- luma: function luma(color) {
- return new Dimension(color.luma() * color.alpha * 100, '%');
- },
- luminance: function luminance(color) {
- var luminance = 0.2126 * color.rgb[0] / 255 + 0.7152 * color.rgb[1] / 255 + 0.0722 * color.rgb[2] / 255;
- return new Dimension(luminance * color.alpha * 100, '%');
- },
- saturate: function saturate(color, amount, method) {
- // filter: saturate(3.2);
- // should be kept as is, so check for color
- if (!color.rgb) {
- return null;
- }
-
- var hsl = toHSL(color);
-
- if (typeof method !== 'undefined' && method.value === 'relative') {
- hsl.s += hsl.s * amount.value / 100;
- } else {
- hsl.s += amount.value / 100;
- }
-
- hsl.s = clamp$1(hsl.s);
- return hsla(color, hsl);
- },
- desaturate: function desaturate(color, amount, method) {
- var hsl = toHSL(color);
-
- if (typeof method !== 'undefined' && method.value === 'relative') {
- hsl.s -= hsl.s * amount.value / 100;
- } else {
- hsl.s -= amount.value / 100;
- }
-
- hsl.s = clamp$1(hsl.s);
- return hsla(color, hsl);
- },
- lighten: function lighten(color, amount, method) {
- var hsl = toHSL(color);
-
- if (typeof method !== 'undefined' && method.value === 'relative') {
- hsl.l += hsl.l * amount.value / 100;
- } else {
- hsl.l += amount.value / 100;
- }
-
- hsl.l = clamp$1(hsl.l);
- return hsla(color, hsl);
- },
- darken: function darken(color, amount, method) {
- var hsl = toHSL(color);
-
- if (typeof method !== 'undefined' && method.value === 'relative') {
- hsl.l -= hsl.l * amount.value / 100;
- } else {
- hsl.l -= amount.value / 100;
- }
-
- hsl.l = clamp$1(hsl.l);
- return hsla(color, hsl);
- },
- fadein: function fadein(color, amount, method) {
- var hsl = toHSL(color);
-
- if (typeof method !== 'undefined' && method.value === 'relative') {
- hsl.a += hsl.a * amount.value / 100;
- } else {
- hsl.a += amount.value / 100;
- }
-
- hsl.a = clamp$1(hsl.a);
- return hsla(color, hsl);
- },
- fadeout: function fadeout(color, amount, method) {
- var hsl = toHSL(color);
-
- if (typeof method !== 'undefined' && method.value === 'relative') {
- hsl.a -= hsl.a * amount.value / 100;
- } else {
- hsl.a -= amount.value / 100;
- }
-
- hsl.a = clamp$1(hsl.a);
- return hsla(color, hsl);
- },
- fade: function fade(color, amount) {
- var hsl = toHSL(color);
- hsl.a = amount.value / 100;
- hsl.a = clamp$1(hsl.a);
- return hsla(color, hsl);
- },
- spin: function spin(color, amount) {
- var hsl = toHSL(color);
- var hue = (hsl.h + amount.value) % 360;
- hsl.h = hue < 0 ? 360 + hue : hue;
- return hsla(color, hsl);
- },
- //
- // Copyright (c) 2006-2009 Hampton Catlin, Natalie Weizenbaum, and Chris Eppstein
- // http://sass-lang.com
- //
- mix: function mix(color1, color2, weight) {
- if (!weight) {
- weight = new Dimension(50);
- }
-
- var p = weight.value / 100.0;
- var w = p * 2 - 1;
- var a = toHSL(color1).a - toHSL(color2).a;
- var w1 = ((w * a == -1 ? w : (w + a) / (1 + w * a)) + 1) / 2.0;
- var w2 = 1 - w1;
- var rgb = [color1.rgb[0] * w1 + color2.rgb[0] * w2, color1.rgb[1] * w1 + color2.rgb[1] * w2, color1.rgb[2] * w1 + color2.rgb[2] * w2];
- var alpha = color1.alpha * p + color2.alpha * (1 - p);
- return new Color(rgb, alpha);
- },
- greyscale: function greyscale(color) {
- return colorFunctions.desaturate(color, new Dimension(100));
- },
- contrast: function contrast(color, dark, light, threshold) {
- // filter: contrast(3.2);
- // should be kept as is, so check for color
- if (!color.rgb) {
- return null;
- }
-
- if (typeof light === 'undefined') {
- light = colorFunctions.rgba(255, 255, 255, 1.0);
- }
-
- if (typeof dark === 'undefined') {
- dark = colorFunctions.rgba(0, 0, 0, 1.0);
- } // Figure out which is actually light and dark:
-
-
- if (dark.luma() > light.luma()) {
- var t = light;
- light = dark;
- dark = t;
- }
-
- if (typeof threshold === 'undefined') {
- threshold = 0.43;
- } else {
- threshold = number(threshold);
- }
-
- if (color.luma() < threshold) {
- return light;
- } else {
- return dark;
- }
- },
- // Changes made in 2.7.0 - Reverted in 3.0.0
- // contrast: function (color, color1, color2, threshold) {
- // // Return which of `color1` and `color2` has the greatest contrast with `color`
- // // according to the standard WCAG contrast ratio calculation.
- // // http://www.w3.org/TR/WCAG20/#contrast-ratiodef
- // // The threshold param is no longer used, in line with SASS.
- // // filter: contrast(3.2);
- // // should be kept as is, so check for color
- // if (!color.rgb) {
- // return null;
- // }
- // if (typeof color1 === 'undefined') {
- // color1 = colorFunctions.rgba(0, 0, 0, 1.0);
- // }
- // if (typeof color2 === 'undefined') {
- // color2 = colorFunctions.rgba(255, 255, 255, 1.0);
- // }
- // var contrast1, contrast2;
- // var luma = color.luma();
- // var luma1 = color1.luma();
- // var luma2 = color2.luma();
- // // Calculate contrast ratios for each color
- // if (luma > luma1) {
- // contrast1 = (luma + 0.05) / (luma1 + 0.05);
- // } else {
- // contrast1 = (luma1 + 0.05) / (luma + 0.05);
- // }
- // if (luma > luma2) {
- // contrast2 = (luma + 0.05) / (luma2 + 0.05);
- // } else {
- // contrast2 = (luma2 + 0.05) / (luma + 0.05);
- // }
- // if (contrast1 > contrast2) {
- // return color1;
- // } else {
- // return color2;
- // }
- // },
- argb: function argb(color) {
- return new Anonymous(color.toARGB());
- },
- color: function color(c) {
- if (c instanceof Quoted && /^#([A-Fa-f0-9]{8}|[A-Fa-f0-9]{6}|[A-Fa-f0-9]{3,4})$/i.test(c.value)) {
- var val = c.value.slice(1);
- return new Color(val, undefined, "#".concat(val));
- }
-
- if (c instanceof Color || (c = Color.fromKeyword(c.value))) {
- c.value = undefined;
- return c;
- }
-
- throw {
- type: 'Argument',
- message: 'argument must be a color keyword or 3|4|6|8 digit hex e.g. #FFF'
- };
- },
- tint: function tint(color, amount) {
- return colorFunctions.mix(colorFunctions.rgb(255, 255, 255), color, amount);
- },
- shade: function shade(color, amount) {
- return colorFunctions.mix(colorFunctions.rgb(0, 0, 0), color, amount);
- }
- };
- var color = colorFunctions;
-
- // ref: http://www.w3.org/TR/compositing-1
-
- function colorBlend(mode, color1, color2) {
- var ab = color1.alpha; // result
-
- var // backdrop
- cb;
- var as = color2.alpha;
- var // source
- cs;
- var ar;
- var cr;
- var r = [];
- ar = as + ab * (1 - as);
-
- for (var i = 0; i < 3; i++) {
- cb = color1.rgb[i] / 255;
- cs = color2.rgb[i] / 255;
- cr = mode(cb, cs);
-
- if (ar) {
- cr = (as * cs + ab * (cb - as * (cb + cs - cr))) / ar;
- }
-
- r[i] = cr * 255;
- }
-
- return new Color(r, ar);
- }
-
- var colorBlendModeFunctions = {
- multiply: function multiply(cb, cs) {
- return cb * cs;
- },
- screen: function screen(cb, cs) {
- return cb + cs - cb * cs;
- },
- overlay: function overlay(cb, cs) {
- cb *= 2;
- return cb <= 1 ? colorBlendModeFunctions.multiply(cb, cs) : colorBlendModeFunctions.screen(cb - 1, cs);
- },
- softlight: function softlight(cb, cs) {
- var d = 1;
- var e = cb;
-
- if (cs > 0.5) {
- e = 1;
- d = cb > 0.25 ? Math.sqrt(cb) : ((16 * cb - 12) * cb + 4) * cb;
- }
-
- return cb - (1 - 2 * cs) * e * (d - cb);
- },
- hardlight: function hardlight(cb, cs) {
- return colorBlendModeFunctions.overlay(cs, cb);
- },
- difference: function difference(cb, cs) {
- return Math.abs(cb - cs);
- },
- exclusion: function exclusion(cb, cs) {
- return cb + cs - 2 * cb * cs;
- },
- // non-w3c functions:
- average: function average(cb, cs) {
- return (cb + cs) / 2;
- },
- negation: function negation(cb, cs) {
- return 1 - Math.abs(cb + cs - 1);
- }
- };
-
- for (var f in colorBlendModeFunctions) {
- if (colorBlendModeFunctions.hasOwnProperty(f)) {
- colorBlend[f] = colorBlend.bind(null, colorBlendModeFunctions[f]);
- }
- }
-
- var dataUri = (function (environment) {
- var fallback = function fallback(functionThis, node) {
- return new URL(node, functionThis.index, functionThis.currentFileInfo).eval(functionThis.context);
- };
-
- return {
- 'data-uri': function dataUri(mimetypeNode, filePathNode) {
- if (!filePathNode) {
- filePathNode = mimetypeNode;
- mimetypeNode = null;
- }
-
- var mimetype = mimetypeNode && mimetypeNode.value;
- var filePath = filePathNode.value;
- var currentFileInfo = this.currentFileInfo;
- var currentDirectory = currentFileInfo.rewriteUrls ? currentFileInfo.currentDirectory : currentFileInfo.entryPath;
- var fragmentStart = filePath.indexOf('#');
- var fragment = '';
-
- if (fragmentStart !== -1) {
- fragment = filePath.slice(fragmentStart);
- filePath = filePath.slice(0, fragmentStart);
- }
-
- var context = clone(this.context);
- context.rawBuffer = true;
- var fileManager = environment.getFileManager(filePath, currentDirectory, context, environment, true);
-
- if (!fileManager) {
- return fallback(this, filePathNode);
- }
-
- var useBase64 = false; // detect the mimetype if not given
-
- if (!mimetypeNode) {
- mimetype = environment.mimeLookup(filePath);
-
- if (mimetype === 'image/svg+xml') {
- useBase64 = false;
- } else {
- // use base 64 unless it's an ASCII or UTF-8 format
- var charset = environment.charsetLookup(mimetype);
- useBase64 = ['US-ASCII', 'UTF-8'].indexOf(charset) < 0;
- }
-
- if (useBase64) {
- mimetype += ';base64';
- }
- } else {
- useBase64 = /;base64$/.test(mimetype);
- }
-
- var fileSync = fileManager.loadFileSync(filePath, currentDirectory, context, environment);
-
- if (!fileSync.contents) {
- logger.warn("Skipped data-uri embedding of ".concat(filePath, " because file not found"));
- return fallback(this, filePathNode || mimetypeNode);
- }
-
- var buf = fileSync.contents;
-
- if (useBase64 && !environment.encodeBase64) {
- return fallback(this, filePathNode);
- }
-
- buf = useBase64 ? environment.encodeBase64(buf) : encodeURIComponent(buf);
- var uri = "data:".concat(mimetype, ",").concat(buf).concat(fragment);
- return new URL(new Quoted("\"".concat(uri, "\""), uri, false, this.index, this.currentFileInfo), this.index, this.currentFileInfo);
- }
- };
- });
-
- var getItemsFromNode = function getItemsFromNode(node) {
- // handle non-array values as an array of length 1
- // return 'undefined' if index is invalid
- var items = Array.isArray(node.value) ? node.value : Array(node);
- return items;
- };
-
- var list = {
- _SELF: function _SELF(n) {
- return n;
- },
- extract: function extract(values, index) {
- // (1-based index)
- index = index.value - 1;
- return getItemsFromNode(values)[index];
- },
- length: function length(values) {
- return new Dimension(getItemsFromNode(values).length);
- },
-
- /**
- * Creates a Less list of incremental values.
- * Modeled after Lodash's range function, also exists natively in PHP
- *
- * @param {Dimension} [start=1]
- * @param {Dimension} end - e.g. 10 or 10px - unit is added to output
- * @param {Dimension} [step=1]
- */
- range: function range(start, end, step) {
- var from;
- var to;
- var stepValue = 1;
- var list = [];
-
- if (end) {
- to = end;
- from = start.value;
-
- if (step) {
- stepValue = step.value;
- }
- } else {
- from = 1;
- to = start;
- }
-
- for (var i = from; i <= to.value; i += stepValue) {
- list.push(new Dimension(i, to.unit));
- }
-
- return new Expression(list);
- },
- each: function each(list, rs) {
- var rules = [];
- var newRules;
- var iterator;
-
- if (list.value && !(list instanceof Quoted)) {
- if (Array.isArray(list.value)) {
- iterator = list.value;
- } else {
- iterator = [list.value];
- }
- } else if (list.ruleset) {
- iterator = list.ruleset.rules;
- } else if (list.rules) {
- iterator = list.rules;
- } else if (Array.isArray(list)) {
- iterator = list;
- } else {
- iterator = [list];
- }
-
- var valueName = '@value';
- var keyName = '@key';
- var indexName = '@index';
-
- if (rs.params) {
- valueName = rs.params[0] && rs.params[0].name;
- keyName = rs.params[1] && rs.params[1].name;
- indexName = rs.params[2] && rs.params[2].name;
- rs = rs.rules;
- } else {
- rs = rs.ruleset;
- }
-
- for (var i = 0; i < iterator.length; i++) {
- var key = void 0;
- var value = void 0;
- var item = iterator[i];
-
- if (item instanceof Declaration) {
- key = typeof item.name === 'string' ? item.name : item.name[0].value;
- value = item.value;
- } else {
- key = new Dimension(i + 1);
- value = item;
- }
-
- if (item instanceof Comment) {
- continue;
- }
-
- newRules = rs.rules.slice(0);
-
- if (valueName) {
- newRules.push(new Declaration(valueName, value, false, false, this.index, this.currentFileInfo));
- }
-
- if (indexName) {
- newRules.push(new Declaration(indexName, new Dimension(i + 1), false, false, this.index, this.currentFileInfo));
- }
-
- if (keyName) {
- newRules.push(new Declaration(keyName, key, false, false, this.index, this.currentFileInfo));
- }
-
- rules.push(new Ruleset([new Selector([new Element("", '&')])], newRules, rs.strictImports, rs.visibilityInfo()));
- }
-
- return new Ruleset([new Selector([new Element("", '&')])], rules, rs.strictImports, rs.visibilityInfo()).eval(this.context);
- }
- };
-
- var MathHelper = function MathHelper(fn, unit, n) {
- if (!(n instanceof Dimension)) {
- throw {
- type: 'Argument',
- message: 'argument must be a number'
- };
- }
-
- if (unit == null) {
- unit = n.unit;
- } else {
- n = n.unify();
- }
-
- return new Dimension(fn(parseFloat(n.value)), unit);
- };
-
- var mathFunctions = {
- // name, unit
- ceil: null,
- floor: null,
- sqrt: null,
- abs: null,
- tan: '',
- sin: '',
- cos: '',
- atan: 'rad',
- asin: 'rad',
- acos: 'rad'
- };
-
- for (var f$1 in mathFunctions) {
- if (mathFunctions.hasOwnProperty(f$1)) {
- mathFunctions[f$1] = MathHelper.bind(null, Math[f$1], mathFunctions[f$1]);
- }
- }
-
- mathFunctions.round = function (n, f) {
- var fraction = typeof f === 'undefined' ? 0 : f.value;
- return MathHelper(function (num) {
- return num.toFixed(fraction);
- }, null, n);
- };
-
- var minMax = function minMax(isMin, args) {
- args = Array.prototype.slice.call(args);
-
- switch (args.length) {
- case 0:
- throw {
- type: 'Argument',
- message: 'one or more arguments required'
- };
- }
-
- var i; // key is the unit.toString() for unified Dimension values,
-
- var j;
- var current;
- var currentUnified;
- var referenceUnified;
- var unit;
- var unitStatic;
- var unitClone;
- var // elems only contains original argument values.
- order = [];
- var values = {}; // value is the index into the order array.
-
- for (i = 0; i < args.length; i++) {
- current = args[i];
-
- if (!(current instanceof Dimension)) {
- if (Array.isArray(args[i].value)) {
- Array.prototype.push.apply(args, Array.prototype.slice.call(args[i].value));
- }
-
- continue;
- }
-
- currentUnified = current.unit.toString() === '' && unitClone !== undefined ? new Dimension(current.value, unitClone).unify() : current.unify();
- unit = currentUnified.unit.toString() === '' && unitStatic !== undefined ? unitStatic : currentUnified.unit.toString();
- unitStatic = unit !== '' && unitStatic === undefined || unit !== '' && order[0].unify().unit.toString() === '' ? unit : unitStatic;
- unitClone = unit !== '' && unitClone === undefined ? current.unit.toString() : unitClone;
- j = values[''] !== undefined && unit !== '' && unit === unitStatic ? values[''] : values[unit];
-
- if (j === undefined) {
- if (unitStatic !== undefined && unit !== unitStatic) {
- throw {
- type: 'Argument',
- message: 'incompatible types'
- };
- }
-
- values[unit] = order.length;
- order.push(current);
- continue;
- }
-
- referenceUnified = order[j].unit.toString() === '' && unitClone !== undefined ? new Dimension(order[j].value, unitClone).unify() : order[j].unify();
-
- if (isMin && currentUnified.value < referenceUnified.value || !isMin && currentUnified.value > referenceUnified.value) {
- order[j] = current;
- }
- }
-
- if (order.length == 1) {
- return order[0];
- }
-
- args = order.map(function (a) {
- return a.toCSS(this.context);
- }).join(this.context.compress ? ',' : ', ');
- return new Anonymous("".concat(isMin ? 'min' : 'max', "(").concat(args, ")"));
- };
-
- var number$1 = {
- min: function min() {
- for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
- args[_key] = arguments[_key];
- }
-
- return minMax(true, args);
- },
- max: function max() {
- for (var _len2 = arguments.length, args = new Array(_len2), _key2 = 0; _key2 < _len2; _key2++) {
- args[_key2] = arguments[_key2];
- }
-
- return minMax(false, args);
- },
- convert: function convert(val, unit) {
- return val.convertTo(unit.value);
- },
- pi: function pi() {
- return new Dimension(Math.PI);
- },
- mod: function mod(a, b) {
- return new Dimension(a.value % b.value, a.unit);
- },
- pow: function pow(x, y) {
- if (typeof x === 'number' && typeof y === 'number') {
- x = new Dimension(x);
- y = new Dimension(y);
- } else if (!(x instanceof Dimension) || !(y instanceof Dimension)) {
- throw {
- type: 'Argument',
- message: 'arguments must be numbers'
- };
- }
-
- return new Dimension(Math.pow(x.value, y.value), x.unit);
- },
- percentage: function percentage(n) {
- var result = MathHelper(function (num) {
- return num * 100;
- }, '%', n);
- return result;
- }
- };
-
- var string = {
- e: function e(str) {
- return new Quoted('"', str instanceof JavaScript ? str.evaluated : str.value, true);
- },
- escape: function escape(str) {
- return new Anonymous(encodeURI(str.value).replace(/=/g, '%3D').replace(/:/g, '%3A').replace(/#/g, '%23').replace(/;/g, '%3B').replace(/\(/g, '%28').replace(/\)/g, '%29'));
- },
- replace: function replace(string, pattern, replacement, flags) {
- var result = string.value;
- replacement = replacement.type === 'Quoted' ? replacement.value : replacement.toCSS();
- result = result.replace(new RegExp(pattern.value, flags ? flags.value : ''), replacement);
- return new Quoted(string.quote || '', result, string.escaped);
- },
- '%': function _(string
- /* arg, arg, ... */
- ) {
- var args = Array.prototype.slice.call(arguments, 1);
- var result = string.value;
-
- var _loop = function _loop(i) {
- /* jshint loopfunc:true */
- result = result.replace(/%[sda]/i, function (token) {
- var value = args[i].type === 'Quoted' && token.match(/s/i) ? args[i].value : args[i].toCSS();
- return token.match(/[A-Z]$/) ? encodeURIComponent(value) : value;
- });
- };
-
- for (var i = 0; i < args.length; i++) {
- _loop(i);
- }
-
- result = result.replace(/%%/g, '%');
- return new Quoted(string.quote || '', result, string.escaped);
- }
- };
-
- var svg = (function (environment) {
- return {
- 'svg-gradient': function svgGradient(direction) {
- var stops;
- var gradientDirectionSvg;
- var gradientType = 'linear';
- var rectangleDimension = 'x="0" y="0" width="1" height="1"';
- var renderEnv = {
- compress: false
- };
- var returner;
- var directionValue = direction.toCSS(renderEnv);
+ var AtRule = function (name, value, rules, index, currentFileInfo, debugInfo, isRooted, visibilityInfo) {
var i;
- var color;
- var position;
- var positionValue;
- var alpha;
-
- function throwArgumentDescriptor() {
- throw {
- type: 'Argument',
- message: 'svg-gradient expects direction, start_color [start_position], [color position,]...,' + ' end_color [end_position] or direction, color list'
- };
+ this.name = name;
+ this.value = (value instanceof Node) ? value : (value ? new Anonymous(value) : value);
+ if (rules) {
+ if (Array.isArray(rules)) {
+ this.rules = rules;
+ }
+ else {
+ this.rules = [rules];
+ this.rules[0].selectors = (new Selector([], null, null, index, currentFileInfo)).createEmptySelectors();
+ }
+ for (i = 0; i < this.rules.length; i++) {
+ this.rules[i].allowImports = true;
+ }
+ this.setParent(this.rules, this);
}
-
- if (arguments.length == 2) {
- if (arguments[1].value.length < 2) {
- throwArgumentDescriptor();
- }
-
- stops = arguments[1].value;
- } else if (arguments.length < 3) {
- throwArgumentDescriptor();
- } else {
- stops = Array.prototype.slice.call(arguments, 1);
- }
-
- switch (directionValue) {
- case 'to bottom':
- gradientDirectionSvg = 'x1="0%" y1="0%" x2="0%" y2="100%"';
- break;
-
- case 'to right':
- gradientDirectionSvg = 'x1="0%" y1="0%" x2="100%" y2="0%"';
- break;
-
- case 'to bottom right':
- gradientDirectionSvg = 'x1="0%" y1="0%" x2="100%" y2="100%"';
- break;
-
- case 'to top right':
- gradientDirectionSvg = 'x1="0%" y1="100%" x2="100%" y2="0%"';
- break;
-
- case 'ellipse':
- case 'ellipse at center':
- gradientType = 'radial';
- gradientDirectionSvg = 'cx="50%" cy="50%" r="75%"';
- rectangleDimension = 'x="-50" y="-50" width="101" height="101"';
- break;
-
- default:
- throw {
- type: 'Argument',
- message: 'svg-gradient direction must be \'to bottom\', \'to right\',' + ' \'to bottom right\', \'to top right\' or \'ellipse at center\''
- };
- }
-
- returner = "");
- returner = encodeURIComponent(returner);
- returner = "data:image/svg+xml,".concat(returner);
- return new URL(new Quoted("'".concat(returner, "'"), returner, false, this.index, this.currentFileInfo), this.index, this.currentFileInfo);
- }
+ this._index = index;
+ this._fileInfo = currentFileInfo;
+ this.debugInfo = debugInfo;
+ this.isRooted = isRooted || false;
+ this.copyVisibilityInfo(visibilityInfo);
+ this.allowRoot = true;
};
- });
-
- var isa = function isa(n, Type) {
- return n instanceof Type ? Keyword.True : Keyword.False;
- };
-
- var isunit = function isunit(n, unit) {
- if (unit === undefined) {
- throw {
- type: 'Argument',
- message: 'missing the required second argument to isunit.'
- };
- }
-
- unit = typeof unit.value === 'string' ? unit.value : unit;
-
- if (typeof unit !== 'string') {
- throw {
- type: 'Argument',
- message: 'Second argument to isunit should be a unit or a string.'
- };
- }
-
- return n instanceof Dimension && n.unit.is(unit) ? Keyword.True : Keyword.False;
- };
-
- var types = {
- isruleset: function isruleset(n) {
- return isa(n, DetachedRuleset);
- },
- iscolor: function iscolor(n) {
- return isa(n, Color);
- },
- isnumber: function isnumber(n) {
- return isa(n, Dimension);
- },
- isstring: function isstring(n) {
- return isa(n, Quoted);
- },
- iskeyword: function iskeyword(n) {
- return isa(n, Keyword);
- },
- isurl: function isurl(n) {
- return isa(n, URL);
- },
- ispixel: function ispixel(n) {
- return isunit(n, 'px');
- },
- ispercentage: function ispercentage(n) {
- return isunit(n, '%');
- },
- isem: function isem(n) {
- return isunit(n, 'em');
- },
- isunit: isunit,
- unit: function unit(val, _unit) {
- if (!(val instanceof Dimension)) {
- throw {
- type: 'Argument',
- message: "the first argument to unit must be a number".concat(val instanceof Operation ? '. Have you forgotten parenthesis?' : '')
- };
- }
-
- if (_unit) {
- if (_unit instanceof Keyword) {
- _unit = _unit.value;
- } else {
- _unit = _unit.toCSS();
- }
- } else {
- _unit = '';
- }
-
- return new Dimension(val.value, _unit);
- },
- 'get-unit': function getUnit(n) {
- return new Anonymous(n.unit);
- }
- };
-
- var Functions = (function (environment) {
- var functions = {
- functionRegistry: functionRegistry,
- functionCaller: functionCaller
- }; // register functions
-
- functionRegistry.addMultiple(boolean$1);
- functionRegistry.add('default', defaultFunc.eval.bind(defaultFunc));
- functionRegistry.addMultiple(color);
- functionRegistry.addMultiple(colorBlend);
- functionRegistry.addMultiple(dataUri(environment));
- functionRegistry.addMultiple(list);
- functionRegistry.addMultiple(mathFunctions);
- functionRegistry.addMultiple(number$1);
- functionRegistry.addMultiple(string);
- functionRegistry.addMultiple(svg());
- functionRegistry.addMultiple(types);
- return functions;
- });
-
- var sourceMapOutput = (function (environment) {
- var SourceMapOutput =
- /*#__PURE__*/
- function () {
- function SourceMapOutput(options) {
- _classCallCheck(this, SourceMapOutput);
-
- this._css = [];
- this._rootNode = options.rootNode;
- this._contentsMap = options.contentsMap;
- this._contentsIgnoredCharsMap = options.contentsIgnoredCharsMap;
-
- if (options.sourceMapFilename) {
- this._sourceMapFilename = options.sourceMapFilename.replace(/\\/g, '/');
- }
-
- this._outputFilename = options.outputFilename;
- this.sourceMapURL = options.sourceMapURL;
-
- if (options.sourceMapBasepath) {
- this._sourceMapBasepath = options.sourceMapBasepath.replace(/\\/g, '/');
- }
-
- if (options.sourceMapRootpath) {
- this._sourceMapRootpath = options.sourceMapRootpath.replace(/\\/g, '/');
-
- if (this._sourceMapRootpath.charAt(this._sourceMapRootpath.length - 1) !== '/') {
- this._sourceMapRootpath += '/';
- }
- } else {
- this._sourceMapRootpath = '';
- }
-
- this._outputSourceFiles = options.outputSourceFiles;
- this._sourceMapGeneratorConstructor = environment.getSourceMapGenerator();
- this._lineNumber = 0;
- this._column = 0;
- }
-
- _createClass(SourceMapOutput, [{
- key: "removeBasepath",
- value: function removeBasepath(path) {
- if (this._sourceMapBasepath && path.indexOf(this._sourceMapBasepath) === 0) {
- path = path.substring(this._sourceMapBasepath.length);
-
- if (path.charAt(0) === '\\' || path.charAt(0) === '/') {
- path = path.substring(1);
+ AtRule.prototype = Object.assign(new Node(), {
+ type: 'AtRule',
+ accept: function (visitor) {
+ var value = this.value, rules = this.rules;
+ if (rules) {
+ this.rules = visitor.visitArray(rules);
}
- }
-
- return path;
- }
- }, {
- key: "normalizeFilename",
- value: function normalizeFilename(filename) {
- filename = filename.replace(/\\/g, '/');
- filename = this.removeBasepath(filename);
- return (this._sourceMapRootpath || '') + filename;
- }
- }, {
- key: "add",
- value: function add(chunk, fileInfo, index, mapLines) {
- // ignore adding empty strings
- if (!chunk) {
- return;
- }
-
- var lines;
- var sourceLines;
- var columns;
- var sourceColumns;
- var i;
-
- if (fileInfo && fileInfo.filename) {
- var inputSource = this._contentsMap[fileInfo.filename]; // remove vars/banner added to the top of the file
-
- if (this._contentsIgnoredCharsMap[fileInfo.filename]) {
- // adjust the index
- index -= this._contentsIgnoredCharsMap[fileInfo.filename];
-
- if (index < 0) {
- index = 0;
- } // adjust the source
-
-
- inputSource = inputSource.slice(this._contentsIgnoredCharsMap[fileInfo.filename]);
- } // ignore empty content
-
-
- if (inputSource === undefined) {
- return;
+ if (value) {
+ this.value = visitor.visit(value);
}
-
- inputSource = inputSource.substring(0, index);
- sourceLines = inputSource.split('\n');
- sourceColumns = sourceLines[sourceLines.length - 1];
- }
-
- lines = chunk.split('\n');
- columns = lines[lines.length - 1];
-
- if (fileInfo && fileInfo.filename) {
- if (!mapLines) {
- this._sourceMapGenerator.addMapping({
- generated: {
- line: this._lineNumber + 1,
- column: this._column
- },
- original: {
- line: sourceLines.length,
- column: sourceColumns.length
- },
- source: this.normalizeFilename(fileInfo.filename)
- });
- } else {
- for (i = 0; i < lines.length; i++) {
- this._sourceMapGenerator.addMapping({
- generated: {
- line: this._lineNumber + i + 1,
- column: i === 0 ? this._column : 0
- },
- original: {
- line: sourceLines.length + i,
- column: i === 0 ? sourceColumns.length : 0
- },
- source: this.normalizeFilename(fileInfo.filename)
- });
- }
+ },
+ isRulesetLike: function () {
+ return this.rules || !this.isCharset();
+ },
+ isCharset: function () {
+ return '@charset' === this.name;
+ },
+ genCSS: function (context, output) {
+ var value = this.value, rules = this.rules;
+ output.add(this.name, this.fileInfo(), this.getIndex());
+ if (value) {
+ output.add(' ');
+ value.genCSS(context, output);
}
- }
-
- if (lines.length === 1) {
- this._column += columns.length;
- } else {
- this._lineNumber += lines.length - 1;
- this._column = columns.length;
- }
-
- this._css.push(chunk);
- }
- }, {
- key: "isEmpty",
- value: function isEmpty() {
- return this._css.length === 0;
- }
- }, {
- key: "toCSS",
- value: function toCSS(context) {
- this._sourceMapGenerator = new this._sourceMapGeneratorConstructor({
- file: this._outputFilename,
- sourceRoot: null
- });
-
- if (this._outputSourceFiles) {
- for (var filename in this._contentsMap) {
- if (this._contentsMap.hasOwnProperty(filename)) {
- var source = this._contentsMap[filename];
-
- if (this._contentsIgnoredCharsMap[filename]) {
- source = source.slice(this._contentsIgnoredCharsMap[filename]);
+ if (rules) {
+ this.outputRuleset(context, output, rules);
+ }
+ else {
+ output.add(';');
+ }
+ },
+ eval: function (context) {
+ var mediaPathBackup, mediaBlocksBackup, value = this.value, rules = this.rules;
+ // media stored inside other atrule should not bubble over it
+ // backpup media bubbling information
+ mediaPathBackup = context.mediaPath;
+ mediaBlocksBackup = context.mediaBlocks;
+ // deleted media bubbling information
+ context.mediaPath = [];
+ context.mediaBlocks = [];
+ if (value) {
+ value = value.eval(context);
+ }
+ if (rules) {
+ // assuming that there is only one rule at this point - that is how parser constructs the rule
+ rules = [rules[0].eval(context)];
+ rules[0].root = true;
+ }
+ // restore media bubbling information
+ context.mediaPath = mediaPathBackup;
+ context.mediaBlocks = mediaBlocksBackup;
+ return new AtRule(this.name, value, rules, this.getIndex(), this.fileInfo(), this.debugInfo, this.isRooted, this.visibilityInfo());
+ },
+ variable: function (name) {
+ if (this.rules) {
+ // assuming that there is only one rule at this point - that is how parser constructs the rule
+ return Ruleset.prototype.variable.call(this.rules[0], name);
+ }
+ },
+ find: function () {
+ if (this.rules) {
+ // assuming that there is only one rule at this point - that is how parser constructs the rule
+ return Ruleset.prototype.find.apply(this.rules[0], arguments);
+ }
+ },
+ rulesets: function () {
+ if (this.rules) {
+ // assuming that there is only one rule at this point - that is how parser constructs the rule
+ return Ruleset.prototype.rulesets.apply(this.rules[0]);
+ }
+ },
+ outputRuleset: function (context, output, rules) {
+ var ruleCnt = rules.length;
+ var i;
+ context.tabLevel = (context.tabLevel | 0) + 1;
+ // Compressed
+ if (context.compress) {
+ output.add('{');
+ for (i = 0; i < ruleCnt; i++) {
+ rules[i].genCSS(context, output);
}
-
- this._sourceMapGenerator.setSourceContent(this.normalizeFilename(filename), source);
- }
+ output.add('}');
+ context.tabLevel--;
+ return;
}
- }
-
- this._rootNode.genCSS(context, this);
-
- if (this._css.length > 0) {
- var sourceMapURL;
- var sourceMapContent = JSON.stringify(this._sourceMapGenerator.toJSON());
-
- if (this.sourceMapURL) {
- sourceMapURL = this.sourceMapURL;
- } else if (this._sourceMapFilename) {
- sourceMapURL = this._sourceMapFilename;
+ // Non-compressed
+ var tabSetStr = "\n" + Array(context.tabLevel).join(' '), tabRuleStr = tabSetStr + " ";
+ if (!ruleCnt) {
+ output.add(" {" + tabSetStr + "}");
}
-
- this.sourceMapURL = sourceMapURL;
- this.sourceMap = sourceMapContent;
- }
-
- return this._css.join('');
- }
- }]);
-
- return SourceMapOutput;
- }();
-
- return SourceMapOutput;
- });
-
- var sourceMapBuilder = (function (SourceMapOutput, environment) {
- var SourceMapBuilder =
- /*#__PURE__*/
- function () {
- function SourceMapBuilder(options) {
- _classCallCheck(this, SourceMapBuilder);
-
- this.options = options;
- }
-
- _createClass(SourceMapBuilder, [{
- key: "toCSS",
- value: function toCSS(rootNode, options, imports) {
- var sourceMapOutput = new SourceMapOutput({
- contentsIgnoredCharsMap: imports.contentsIgnoredChars,
- rootNode: rootNode,
- contentsMap: imports.contents,
- sourceMapFilename: this.options.sourceMapFilename,
- sourceMapURL: this.options.sourceMapURL,
- outputFilename: this.options.sourceMapOutputFilename,
- sourceMapBasepath: this.options.sourceMapBasepath,
- sourceMapRootpath: this.options.sourceMapRootpath,
- outputSourceFiles: this.options.outputSourceFiles,
- sourceMapGenerator: this.options.sourceMapGenerator,
- sourceMapFileInline: this.options.sourceMapFileInline
- });
- var css = sourceMapOutput.toCSS(options);
- this.sourceMap = sourceMapOutput.sourceMap;
- this.sourceMapURL = sourceMapOutput.sourceMapURL;
-
- if (this.options.sourceMapInputFilename) {
- this.sourceMapInputFilename = sourceMapOutput.normalizeFilename(this.options.sourceMapInputFilename);
- }
-
- if (this.options.sourceMapBasepath !== undefined && this.sourceMapURL !== undefined) {
- this.sourceMapURL = sourceMapOutput.removeBasepath(this.sourceMapURL);
- }
-
- return css + this.getCSSAppendage();
- }
- }, {
- key: "getCSSAppendage",
- value: function getCSSAppendage() {
- var sourceMapURL = this.sourceMapURL;
-
- if (this.options.sourceMapFileInline) {
- if (this.sourceMap === undefined) {
- return '';
+ else {
+ output.add(" {" + tabRuleStr);
+ rules[0].genCSS(context, output);
+ for (i = 1; i < ruleCnt; i++) {
+ output.add(tabRuleStr);
+ rules[i].genCSS(context, output);
+ }
+ output.add(tabSetStr + "}");
}
-
- sourceMapURL = "data:application/json;base64,".concat(environment.encodeBase64(this.sourceMap));
- }
-
- if (sourceMapURL) {
- return "/*# sourceMappingURL=".concat(sourceMapURL, " */");
- }
-
- return '';
+ context.tabLevel--;
}
- }, {
- key: "getExternalSourceMap",
- value: function getExternalSourceMap() {
- return this.sourceMap;
+ });
+
+ var DetachedRuleset = function (ruleset, frames) {
+ this.ruleset = ruleset;
+ this.frames = frames;
+ this.setParent(this.ruleset, this);
+ };
+ DetachedRuleset.prototype = Object.assign(new Node(), {
+ type: 'DetachedRuleset',
+ evalFirst: true,
+ accept: function (visitor) {
+ this.ruleset = visitor.visit(this.ruleset);
+ },
+ eval: function (context) {
+ var frames = this.frames || copyArray(context.frames);
+ return new DetachedRuleset(this.ruleset, frames);
+ },
+ callEval: function (context) {
+ return this.ruleset.eval(this.frames ? new contexts.Eval(context, this.frames.concat(context.frames)) : context);
}
- }, {
- key: "setExternalSourceMap",
- value: function setExternalSourceMap(sourceMap) {
- this.sourceMap = sourceMap;
+ });
+
+ var Unit = function (numerator, denominator, backupUnit) {
+ this.numerator = numerator ? copyArray(numerator).sort() : [];
+ this.denominator = denominator ? copyArray(denominator).sort() : [];
+ if (backupUnit) {
+ this.backupUnit = backupUnit;
}
- }, {
- key: "isInline",
- value: function isInline() {
- return this.options.sourceMapFileInline;
+ else if (numerator && numerator.length) {
+ this.backupUnit = numerator[0];
}
- }, {
- key: "getSourceMapURL",
- value: function getSourceMapURL() {
- return this.sourceMapURL;
- }
- }, {
- key: "getOutputFilename",
- value: function getOutputFilename() {
- return this.options.sourceMapOutputFilename;
- }
- }, {
- key: "getInputFilename",
- value: function getInputFilename() {
- return this.sourceMapInputFilename;
- }
- }]);
-
- return SourceMapBuilder;
- }();
-
- return SourceMapBuilder;
- });
-
- var transformTree = (function (root) {
- var options = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};
- var evaldRoot;
- var variables = options.variables;
- var evalEnv = new contexts.Eval(options); //
- // Allows setting variables with a hash, so:
- //
- // `{ color: new tree.Color('#f01') }` will become:
- //
- // new tree.Declaration('@color',
- // new tree.Value([
- // new tree.Expression([
- // new tree.Color('#f01')
- // ])
- // ])
- // )
- //
-
- if (_typeof(variables) === 'object' && !Array.isArray(variables)) {
- variables = Object.keys(variables).map(function (k) {
- var value = variables[k];
-
- if (!(value instanceof tree.Value)) {
- if (!(value instanceof tree.Expression)) {
- value = new tree.Expression([value]);
- }
-
- value = new tree.Value([value]);
- }
-
- return new tree.Declaration("@".concat(k), value, false, null, 0);
- });
- evalEnv.frames = [new tree.Ruleset(null, variables)];
- }
-
- var visitors$1 = [new visitors.JoinSelectorVisitor(), new visitors.MarkVisibleSelectorsVisitor(true), new visitors.ExtendVisitor(), new visitors.ToCSSVisitor({
- compress: Boolean(options.compress)
- })];
- var preEvalVisitors = [];
- var v;
- var visitorIterator;
- /**
- * first() / get() allows visitors to be added while visiting
- *
- * @todo Add scoping for visitors just like functions for @plugin; right now they're global
- */
-
- if (options.pluginManager) {
- visitorIterator = options.pluginManager.visitor();
-
- for (var i = 0; i < 2; i++) {
- visitorIterator.first();
-
- while (v = visitorIterator.get()) {
- if (v.isPreEvalVisitor) {
- if (i === 0 || preEvalVisitors.indexOf(v) === -1) {
- preEvalVisitors.push(v);
- v.run(root);
+ };
+ Unit.prototype = Object.assign(new Node(), {
+ type: 'Unit',
+ clone: function () {
+ return new Unit(copyArray(this.numerator), copyArray(this.denominator), this.backupUnit);
+ },
+ genCSS: function (context, output) {
+ // Dimension checks the unit is singular and throws an error if in strict math mode.
+ var strictUnits = context && context.strictUnits;
+ if (this.numerator.length === 1) {
+ output.add(this.numerator[0]); // the ideal situation
}
- } else {
- if (i === 0 || visitors$1.indexOf(v) === -1) {
- if (v.isPreVisitor) {
- visitors$1.unshift(v);
- } else {
- visitors$1.push(v);
- }
+ else if (!strictUnits && this.backupUnit) {
+ output.add(this.backupUnit);
}
- }
- }
- }
- }
-
- evaldRoot = root.eval(evalEnv);
-
- for (var i = 0; i < visitors$1.length; i++) {
- visitors$1[i].run(evaldRoot);
- } // Run any remaining visitors added after eval pass
-
-
- if (options.pluginManager) {
- visitorIterator.first();
-
- while (v = visitorIterator.get()) {
- if (visitors$1.indexOf(v) === -1 && preEvalVisitors.indexOf(v) === -1) {
- v.run(evaldRoot);
- }
- }
- }
-
- return evaldRoot;
- });
-
- var parseTree = (function (SourceMapBuilder) {
- var ParseTree =
- /*#__PURE__*/
- function () {
- function ParseTree(root, imports) {
- _classCallCheck(this, ParseTree);
-
- this.root = root;
- this.imports = imports;
- }
-
- _createClass(ParseTree, [{
- key: "toCSS",
- value: function toCSS(options) {
- var evaldRoot;
- var result = {};
- var sourceMapBuilder;
-
- try {
- evaldRoot = transformTree(this.root, options);
- } catch (e) {
- throw new LessError(e, this.imports);
- }
-
- try {
- var compress = Boolean(options.compress);
-
- if (compress) {
- logger.warn('The compress option has been deprecated. ' + 'We recommend you use a dedicated css minifier, for instance see less-plugin-clean-css.');
+ else if (!strictUnits && this.denominator.length) {
+ output.add(this.denominator[0]);
}
-
- var toCSSOptions = {
- compress: compress,
- dumpLineNumbers: options.dumpLineNumbers,
- strictUnits: Boolean(options.strictUnits),
- numPrecision: 8
+ },
+ toString: function () {
+ var i, returnStr = this.numerator.join('*');
+ for (i = 0; i < this.denominator.length; i++) {
+ returnStr += "/" + this.denominator[i];
+ }
+ return returnStr;
+ },
+ compare: function (other) {
+ return this.is(other.toString()) ? 0 : undefined;
+ },
+ is: function (unitString) {
+ return this.toString().toUpperCase() === unitString.toUpperCase();
+ },
+ isLength: function () {
+ return RegExp('^(px|em|ex|ch|rem|in|cm|mm|pc|pt|ex|vw|vh|vmin|vmax)$', 'gi').test(this.toCSS());
+ },
+ isEmpty: function () {
+ return this.numerator.length === 0 && this.denominator.length === 0;
+ },
+ isSingular: function () {
+ return this.numerator.length <= 1 && this.denominator.length === 0;
+ },
+ map: function (callback) {
+ var i;
+ for (i = 0; i < this.numerator.length; i++) {
+ this.numerator[i] = callback(this.numerator[i], false);
+ }
+ for (i = 0; i < this.denominator.length; i++) {
+ this.denominator[i] = callback(this.denominator[i], true);
+ }
+ },
+ usedUnits: function () {
+ var group;
+ var result = {};
+ var mapUnit;
+ var groupName;
+ mapUnit = function (atomicUnit) {
+ /* jshint loopfunc:true */
+ if (group.hasOwnProperty(atomicUnit) && !result[groupName]) {
+ result[groupName] = atomicUnit;
+ }
+ return atomicUnit;
};
-
- if (options.sourceMap) {
- sourceMapBuilder = new SourceMapBuilder(options.sourceMap);
- result.css = sourceMapBuilder.toCSS(evaldRoot, toCSSOptions, this.imports);
- } else {
- result.css = evaldRoot.toCSS(toCSSOptions);
+ for (groupName in unitConversions) {
+ if (unitConversions.hasOwnProperty(groupName)) {
+ group = unitConversions[groupName];
+ this.map(mapUnit);
+ }
}
- } catch (e) {
- throw new LessError(e, this.imports);
- }
-
- if (options.pluginManager) {
- var postProcessors = options.pluginManager.getPostProcessors();
-
- for (var i = 0; i < postProcessors.length; i++) {
- result.css = postProcessors[i].process(result.css, {
- sourceMap: sourceMapBuilder,
- options: options,
- imports: this.imports
- });
+ return result;
+ },
+ cancel: function () {
+ var counter = {};
+ var atomicUnit;
+ var i;
+ for (i = 0; i < this.numerator.length; i++) {
+ atomicUnit = this.numerator[i];
+ counter[atomicUnit] = (counter[atomicUnit] || 0) + 1;
}
- }
-
- if (options.sourceMap) {
- result.map = sourceMapBuilder.getExternalSourceMap();
- }
-
- result.imports = [];
-
- for (var file in this.imports.files) {
- if (this.imports.files.hasOwnProperty(file) && file !== this.imports.rootFilename) {
- result.imports.push(file);
+ for (i = 0; i < this.denominator.length; i++) {
+ atomicUnit = this.denominator[i];
+ counter[atomicUnit] = (counter[atomicUnit] || 0) - 1;
}
- }
-
- return result;
+ this.numerator = [];
+ this.denominator = [];
+ for (atomicUnit in counter) {
+ if (counter.hasOwnProperty(atomicUnit)) {
+ var count = counter[atomicUnit];
+ if (count > 0) {
+ for (i = 0; i < count; i++) {
+ this.numerator.push(atomicUnit);
+ }
+ }
+ else if (count < 0) {
+ for (i = 0; i < -count; i++) {
+ this.denominator.push(atomicUnit);
+ }
+ }
+ }
+ }
+ this.numerator.sort();
+ this.denominator.sort();
}
- }]);
+ });
- return ParseTree;
- }();
-
- return ParseTree;
- });
-
- var importManager = (function (environment) {
- // FileInfo = {
- // 'rewriteUrls' - option - whether to adjust URL's to be relative
- // 'filename' - full resolved filename of current file
- // 'rootpath' - path to append to normal URLs for this node
- // 'currentDirectory' - path to the current file, absolute
- // 'rootFilename' - filename of the base file
- // 'entryPath' - absolute path to the entry file
- // 'reference' - whether the file should not be output and only output parts that are referenced
- var ImportManager =
- /*#__PURE__*/
- function () {
- function ImportManager(less, context, rootFileInfo) {
- _classCallCheck(this, ImportManager);
-
- this.less = less;
- this.rootFilename = rootFileInfo.filename;
- this.paths = context.paths || []; // Search paths, when importing
-
- this.contents = {}; // map - filename to contents of all the files
-
- this.contentsIgnoredChars = {}; // map - filename to lines at the beginning of each file to ignore
-
- this.mime = context.mime;
- this.error = null;
- this.context = context; // Deprecated? Unused outside of here, could be useful.
-
- this.queue = []; // Files which haven't been imported yet
-
- this.files = {}; // Holds the imported parse trees.
- }
- /**
- * Add an import to be imported
- * @param path - the raw path
- * @param tryAppendExtension - whether to try appending a file extension (.less or .js if the path has no extension)
- * @param currentFileInfo - the current file info (used for instance to work out relative paths)
- * @param importOptions - import options
- * @param callback - callback for when it is imported
- */
-
-
- _createClass(ImportManager, [{
- key: "push",
- value: function push(path, tryAppendExtension, currentFileInfo, importOptions, callback) {
- var importManager = this;
- var pluginLoader = this.context.pluginManager.Loader;
- this.queue.push(path);
-
- var fileParsedFunc = function fileParsedFunc(e, root, fullPath) {
- importManager.queue.splice(importManager.queue.indexOf(path), 1); // Remove the path from the queue
-
- var importedEqualsRoot = fullPath === importManager.rootFilename;
-
- if (importOptions.optional && e) {
- callback(null, {
- rules: []
- }, false, null);
- logger.info("The file ".concat(fullPath, " was skipped because it was not found and the import was marked optional."));
- } else {
- // Inline imports aren't cached here.
- // If we start to cache them, please make sure they won't conflict with non-inline imports of the
- // same name as they used to do before this comment and the condition below have been added.
- if (!importManager.files[fullPath] && !importOptions.inline) {
- importManager.files[fullPath] = {
- root: root,
- options: importOptions
- };
- }
-
- if (e && !importManager.error) {
- importManager.error = e;
- }
-
- callback(e, root, importedEqualsRoot, fullPath);
+ //
+ // A number with a unit
+ //
+ var Dimension = function (value, unit) {
+ this.value = parseFloat(value);
+ if (isNaN(this.value)) {
+ throw new Error('Dimension is not a number.');
+ }
+ this.unit = (unit && unit instanceof Unit) ? unit :
+ new Unit(unit ? [unit] : undefined);
+ this.setParent(this.unit, this);
+ };
+ Dimension.prototype = Object.assign(new Node(), {
+ type: 'Dimension',
+ accept: function (visitor) {
+ this.unit = visitor.visit(this.unit);
+ },
+ eval: function (context) {
+ return this;
+ },
+ toColor: function () {
+ return new Color([this.value, this.value, this.value]);
+ },
+ genCSS: function (context, output) {
+ if ((context && context.strictUnits) && !this.unit.isSingular()) {
+ throw new Error("Multiple units in dimension. Correct the units or use the unit function. Bad unit: " + this.unit.toString());
}
- };
+ var value = this.fround(context, this.value);
+ var strValue = String(value);
+ if (value !== 0 && value < 0.000001 && value > -0.000001) {
+ // would be output 1e-6 etc.
+ strValue = value.toFixed(20).replace(/0+$/, '');
+ }
+ if (context && context.compress) {
+ // Zero values doesn't need a unit
+ if (value === 0 && this.unit.isLength()) {
+ output.add(strValue);
+ return;
+ }
+ // Float values doesn't need a leading zero
+ if (value > 0 && value < 1) {
+ strValue = (strValue).substr(1);
+ }
+ }
+ output.add(strValue);
+ this.unit.genCSS(context, output);
+ },
+ // In an operation between two Dimensions,
+ // we default to the first Dimension's unit,
+ // so `1px + 2` will yield `3px`.
+ operate: function (context, op, other) {
+ /* jshint noempty:false */
+ var value = this._operate(context, op, this.value, other.value);
+ var unit = this.unit.clone();
+ if (op === '+' || op === '-') {
+ if (unit.numerator.length === 0 && unit.denominator.length === 0) {
+ unit = other.unit.clone();
+ if (this.unit.backupUnit) {
+ unit.backupUnit = this.unit.backupUnit;
+ }
+ }
+ else if (other.unit.numerator.length === 0 && unit.denominator.length === 0) ;
+ else {
+ other = other.convertTo(this.unit.usedUnits());
+ if (context.strictUnits && other.unit.toString() !== unit.toString()) {
+ throw new Error("Incompatible units. Change the units or use the unit function. "
+ + ("Bad units: '" + unit.toString() + "' and '" + other.unit.toString() + "'."));
+ }
+ value = this._operate(context, op, this.value, other.value);
+ }
+ }
+ else if (op === '*') {
+ unit.numerator = unit.numerator.concat(other.unit.numerator).sort();
+ unit.denominator = unit.denominator.concat(other.unit.denominator).sort();
+ unit.cancel();
+ }
+ else if (op === '/') {
+ unit.numerator = unit.numerator.concat(other.unit.denominator).sort();
+ unit.denominator = unit.denominator.concat(other.unit.numerator).sort();
+ unit.cancel();
+ }
+ return new Dimension(value, unit);
+ },
+ compare: function (other) {
+ var a, b;
+ if (!(other instanceof Dimension)) {
+ return undefined;
+ }
+ if (this.unit.isEmpty() || other.unit.isEmpty()) {
+ a = this;
+ b = other;
+ }
+ else {
+ a = this.unify();
+ b = other.unify();
+ if (a.unit.compare(b.unit) !== 0) {
+ return undefined;
+ }
+ }
+ return Node.numericCompare(a.value, b.value);
+ },
+ unify: function () {
+ return this.convertTo({ length: 'px', duration: 's', angle: 'rad' });
+ },
+ convertTo: function (conversions) {
+ var value = this.value;
+ var unit = this.unit.clone();
+ var i;
+ var groupName;
+ var group;
+ var targetUnit;
+ var derivedConversions = {};
+ var applyUnit;
+ if (typeof conversions === 'string') {
+ for (i in unitConversions) {
+ if (unitConversions[i].hasOwnProperty(conversions)) {
+ derivedConversions = {};
+ derivedConversions[i] = conversions;
+ }
+ }
+ conversions = derivedConversions;
+ }
+ applyUnit = function (atomicUnit, denominator) {
+ /* jshint loopfunc:true */
+ if (group.hasOwnProperty(atomicUnit)) {
+ if (denominator) {
+ value = value / (group[atomicUnit] / group[targetUnit]);
+ }
+ else {
+ value = value * (group[atomicUnit] / group[targetUnit]);
+ }
+ return targetUnit;
+ }
+ return atomicUnit;
+ };
+ for (groupName in conversions) {
+ if (conversions.hasOwnProperty(groupName)) {
+ targetUnit = conversions[groupName];
+ group = unitConversions[groupName];
+ unit.map(applyUnit);
+ }
+ }
+ unit.cancel();
+ return new Dimension(value, unit);
+ }
+ });
- var newFileInfo = {
- rewriteUrls: this.context.rewriteUrls,
- entryPath: currentFileInfo.entryPath,
- rootpath: currentFileInfo.rootpath,
- rootFilename: currentFileInfo.rootFilename
- };
- var fileManager = environment.getFileManager(path, currentFileInfo.currentDirectory, this.context, environment);
+ var MATH = Math$1;
+ var Operation = function (op, operands, isSpaced) {
+ this.op = op.trim();
+ this.operands = operands;
+ this.isSpaced = isSpaced;
+ };
+ Operation.prototype = Object.assign(new Node(), {
+ type: 'Operation',
+ accept: function (visitor) {
+ this.operands = visitor.visitArray(this.operands);
+ },
+ eval: function (context) {
+ var a = this.operands[0].eval(context), b = this.operands[1].eval(context), op;
+ if (context.isMathOn(this.op)) {
+ op = this.op === './' ? '/' : this.op;
+ if (a instanceof Dimension && b instanceof Color) {
+ a = a.toColor();
+ }
+ if (b instanceof Dimension && a instanceof Color) {
+ b = b.toColor();
+ }
+ if (!a.operate || !b.operate) {
+ if ((a instanceof Operation || b instanceof Operation)
+ && a.op === '/' && context.math === MATH.PARENS_DIVISION) {
+ return new Operation(this.op, [a, b], this.isSpaced);
+ }
+ throw { type: 'Operation',
+ message: 'Operation on an invalid type' };
+ }
+ return a.operate(context, op, b);
+ }
+ else {
+ return new Operation(this.op, [a, b], this.isSpaced);
+ }
+ },
+ genCSS: function (context, output) {
+ this.operands[0].genCSS(context, output);
+ if (this.isSpaced) {
+ output.add(' ');
+ }
+ output.add(this.op);
+ if (this.isSpaced) {
+ output.add(' ');
+ }
+ this.operands[1].genCSS(context, output);
+ }
+ });
- if (!fileManager) {
- fileParsedFunc({
- message: "Could not find a file-manager for ".concat(path)
+ /*! *****************************************************************************
+ Copyright (c) Microsoft Corporation.
+
+ Permission to use, copy, modify, and/or distribute this software for any
+ purpose with or without fee is hereby granted.
+
+ THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH
+ REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY
+ AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,
+ INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM
+ LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR
+ OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
+ PERFORMANCE OF THIS SOFTWARE.
+ ***************************************************************************** */
+
+ function __spreadArray(to, from, pack) {
+ if (pack || arguments.length === 2) for (var i = 0, l = from.length, ar; i < l; i++) {
+ if (ar || !(i in from)) {
+ if (!ar) ar = Array.prototype.slice.call(from, 0, i);
+ ar[i] = from[i];
+ }
+ }
+ return to.concat(ar || from);
+ }
+
+ var Expression = function (value, noSpacing) {
+ this.value = value;
+ this.noSpacing = noSpacing;
+ if (!value) {
+ throw new Error('Expression requires an array parameter');
+ }
+ };
+ Expression.prototype = Object.assign(new Node(), {
+ type: 'Expression',
+ accept: function (visitor) {
+ this.value = visitor.visitArray(this.value);
+ },
+ eval: function (context) {
+ var returnValue;
+ var mathOn = context.isMathOn();
+ var inParenthesis = this.parens;
+ var doubleParen = false;
+ if (inParenthesis) {
+ context.inParenthesis();
+ }
+ if (this.value.length > 1) {
+ returnValue = new Expression(this.value.map(function (e) {
+ if (!e.eval) {
+ return e;
+ }
+ return e.eval(context);
+ }), this.noSpacing);
+ }
+ else if (this.value.length === 1) {
+ if (this.value[0].parens && !this.value[0].parensInOp && !context.inCalc) {
+ doubleParen = true;
+ }
+ returnValue = this.value[0].eval(context);
+ }
+ else {
+ returnValue = this;
+ }
+ if (inParenthesis) {
+ context.outOfParenthesis();
+ }
+ if (this.parens && this.parensInOp && !mathOn && !doubleParen
+ && (!(returnValue instanceof Dimension))) {
+ returnValue = new Paren(returnValue);
+ }
+ return returnValue;
+ },
+ genCSS: function (context, output) {
+ for (var i = 0; i < this.value.length; i++) {
+ this.value[i].genCSS(context, output);
+ if (!this.noSpacing && i + 1 < this.value.length) {
+ output.add(' ');
+ }
+ }
+ },
+ throwAwayComments: function () {
+ this.value = this.value.filter(function (v) {
+ return !(v instanceof Comment);
});
- return;
- }
+ }
+ });
- var loadFileCallback = function loadFileCallback(loadedFile) {
- var plugin;
- var resolvedFilename = loadedFile.filename;
- var contents = loadedFile.contents.replace(/^\uFEFF/, ''); // Pass on an updated rootpath if path of imported file is relative and file
- // is in a (sub|sup) directory
+ var functionCaller = /** @class */ (function () {
+ function functionCaller(name, context, index, currentFileInfo) {
+ this.name = name.toLowerCase();
+ this.index = index;
+ this.context = context;
+ this.currentFileInfo = currentFileInfo;
+ this.func = context.frames[0].functionRegistry.get(this.name);
+ }
+ functionCaller.prototype.isValid = function () {
+ return Boolean(this.func);
+ };
+ functionCaller.prototype.call = function (args) {
+ var _this = this;
+ if (!(Array.isArray(args))) {
+ args = [args];
+ }
+ var evalArgs = this.func.evalArgs;
+ if (evalArgs !== false) {
+ args = args.map(function (a) { return a.eval(_this.context); });
+ }
+ var commentFilter = function (item) { return !(item.type === 'Comment'); };
+ // This code is terrible and should be replaced as per this issue...
+ // https://github.com/less/less.js/issues/2477
+ args = args
+ .filter(commentFilter)
+ .map(function (item) {
+ if (item.type === 'Expression') {
+ var subNodes = item.value.filter(commentFilter);
+ if (subNodes.length === 1) {
+ // https://github.com/less/less.js/issues/3616
+ if (item.parens && subNodes[0].op === '/') {
+ return item;
+ }
+ return subNodes[0];
+ }
+ else {
+ return new Expression(subNodes);
+ }
+ }
+ return item;
+ });
+ if (evalArgs === false) {
+ return this.func.apply(this, __spreadArray([this.context], args));
+ }
+ return this.func.apply(this, args);
+ };
+ return functionCaller;
+ }());
+
+ //
+ // A function call node.
+ //
+ var Call = function (name, args, index, currentFileInfo) {
+ this.name = name;
+ this.args = args;
+ this.calc = name === 'calc';
+ this._index = index;
+ this._fileInfo = currentFileInfo;
+ };
+ Call.prototype = Object.assign(new Node(), {
+ type: 'Call',
+ accept: function (visitor) {
+ if (this.args) {
+ this.args = visitor.visitArray(this.args);
+ }
+ },
+ //
+ // When evaluating a function call,
+ // we either find the function in the functionRegistry,
+ // in which case we call it, passing the evaluated arguments,
+ // if this returns null or we cannot find the function, we
+ // simply print it out as it appeared originally [2].
+ //
+ // The reason why we evaluate the arguments, is in the case where
+ // we try to pass a variable to a function, like: `saturate(@color)`.
+ // The function should receive the value, not the variable.
+ //
+ eval: function (context) {
+ var _this = this;
+ /**
+ * Turn off math for calc(), and switch back on for evaluating nested functions
+ */
+ var currentMathContext = context.mathOn;
+ context.mathOn = !this.calc;
+ if (this.calc || context.inCalc) {
+ context.enterCalc();
+ }
+ var exitCalc = function () {
+ if (_this.calc || context.inCalc) {
+ context.exitCalc();
+ }
+ context.mathOn = currentMathContext;
+ };
+ var result;
+ var funcCaller = new functionCaller(this.name, context, this.getIndex(), this.fileInfo());
+ if (funcCaller.isValid()) {
+ try {
+ result = funcCaller.call(this.args);
+ exitCalc();
+ }
+ catch (e) {
+ if (e.hasOwnProperty('line') && e.hasOwnProperty('column')) {
+ throw e;
+ }
+ throw {
+ type: e.type || 'Runtime',
+ message: "Error evaluating function `" + this.name + "`" + (e.message ? ": " + e.message : ''),
+ index: this.getIndex(),
+ filename: this.fileInfo().filename,
+ line: e.lineNumber,
+ column: e.columnNumber
+ };
+ }
+ }
+ if (result !== null && result !== undefined) {
+ // Results that that are not nodes are cast as Anonymous nodes
+ // Falsy values or booleans are returned as empty nodes
+ if (!(result instanceof Node)) {
+ if (!result || result === true) {
+ result = new Anonymous(null);
+ }
+ else {
+ result = new Anonymous(result.toString());
+ }
+ }
+ result._index = this._index;
+ result._fileInfo = this._fileInfo;
+ return result;
+ }
+ var args = this.args.map(function (a) { return a.eval(context); });
+ exitCalc();
+ return new Call(this.name, args, this.getIndex(), this.fileInfo());
+ },
+ genCSS: function (context, output) {
+ output.add(this.name + "(", this.fileInfo(), this.getIndex());
+ for (var i = 0; i < this.args.length; i++) {
+ this.args[i].genCSS(context, output);
+ if (i + 1 < this.args.length) {
+ output.add(', ');
+ }
+ }
+ output.add(')');
+ }
+ });
+
+ var Variable = function (name, index, currentFileInfo) {
+ this.name = name;
+ this._index = index;
+ this._fileInfo = currentFileInfo;
+ };
+ Variable.prototype = Object.assign(new Node(), {
+ type: 'Variable',
+ eval: function (context) {
+ var variable, name = this.name;
+ if (name.indexOf('@@') === 0) {
+ name = "@" + new Variable(name.slice(1), this.getIndex(), this.fileInfo()).eval(context).value;
+ }
+ if (this.evaluating) {
+ throw { type: 'Name',
+ message: "Recursive variable definition for " + name,
+ filename: this.fileInfo().filename,
+ index: this.getIndex() };
+ }
+ this.evaluating = true;
+ variable = this.find(context.frames, function (frame) {
+ var v = frame.variable(name);
+ if (v) {
+ if (v.important) {
+ var importantScope = context.importantScope[context.importantScope.length - 1];
+ importantScope.important = v.important;
+ }
+ // If in calc, wrap vars in a function call to cascade evaluate args first
+ if (context.inCalc) {
+ return (new Call('_SELF', [v.value])).eval(context);
+ }
+ else {
+ return v.value.eval(context);
+ }
+ }
+ });
+ if (variable) {
+ this.evaluating = false;
+ return variable;
+ }
+ else {
+ throw { type: 'Name',
+ message: "variable " + name + " is undefined",
+ filename: this.fileInfo().filename,
+ index: this.getIndex() };
+ }
+ },
+ find: function (obj, fun) {
+ for (var i = 0, r = void 0; i < obj.length; i++) {
+ r = fun.call(obj, obj[i]);
+ if (r) {
+ return r;
+ }
+ }
+ return null;
+ }
+ });
+
+ var Property = function (name, index, currentFileInfo) {
+ this.name = name;
+ this._index = index;
+ this._fileInfo = currentFileInfo;
+ };
+ Property.prototype = Object.assign(new Node(), {
+ type: 'Property',
+ eval: function (context) {
+ var property;
+ var name = this.name;
+ // TODO: shorten this reference
+ var mergeRules = context.pluginManager.less.visitors.ToCSSVisitor.prototype._mergeRules;
+ if (this.evaluating) {
+ throw { type: 'Name',
+ message: "Recursive property reference for " + name,
+ filename: this.fileInfo().filename,
+ index: this.getIndex() };
+ }
+ this.evaluating = true;
+ property = this.find(context.frames, function (frame) {
+ var v;
+ var vArr = frame.property(name);
+ if (vArr) {
+ for (var i = 0; i < vArr.length; i++) {
+ v = vArr[i];
+ vArr[i] = new Declaration(v.name, v.value, v.important, v.merge, v.index, v.currentFileInfo, v.inline, v.variable);
+ }
+ mergeRules(vArr);
+ v = vArr[vArr.length - 1];
+ if (v.important) {
+ var importantScope = context.importantScope[context.importantScope.length - 1];
+ importantScope.important = v.important;
+ }
+ v = v.value.eval(context);
+ return v;
+ }
+ });
+ if (property) {
+ this.evaluating = false;
+ return property;
+ }
+ else {
+ throw { type: 'Name',
+ message: "Property '" + name + "' is undefined",
+ filename: this.currentFileInfo.filename,
+ index: this.index };
+ }
+ },
+ find: function (obj, fun) {
+ for (var i = 0, r = void 0; i < obj.length; i++) {
+ r = fun.call(obj, obj[i]);
+ if (r) {
+ return r;
+ }
+ }
+ return null;
+ }
+ });
+
+ var Attribute = function (key, op, value) {
+ this.key = key;
+ this.op = op;
+ this.value = value;
+ };
+ Attribute.prototype = Object.assign(new Node(), {
+ type: 'Attribute',
+ eval: function (context) {
+ return new Attribute(this.key.eval ? this.key.eval(context) : this.key, this.op, (this.value && this.value.eval) ? this.value.eval(context) : this.value);
+ },
+ genCSS: function (context, output) {
+ output.add(this.toCSS(context));
+ },
+ toCSS: function (context) {
+ var value = this.key.toCSS ? this.key.toCSS(context) : this.key;
+ if (this.op) {
+ value += this.op;
+ value += (this.value.toCSS ? this.value.toCSS(context) : this.value);
+ }
+ return "[" + value + "]";
+ }
+ });
+
+ var Quoted = function (str, content, escaped, index, currentFileInfo) {
+ this.escaped = (escaped == null) ? true : escaped;
+ this.value = content || '';
+ this.quote = str.charAt(0);
+ this._index = index;
+ this._fileInfo = currentFileInfo;
+ this.variableRegex = /@\{([\w-]+)\}/g;
+ this.propRegex = /\$\{([\w-]+)\}/g;
+ this.allowRoot = escaped;
+ };
+ Quoted.prototype = Object.assign(new Node(), {
+ type: 'Quoted',
+ genCSS: function (context, output) {
+ if (!this.escaped) {
+ output.add(this.quote, this.fileInfo(), this.getIndex());
+ }
+ output.add(this.value);
+ if (!this.escaped) {
+ output.add(this.quote);
+ }
+ },
+ containsVariables: function () {
+ return this.value.match(this.variableRegex);
+ },
+ eval: function (context) {
+ var that = this;
+ var value = this.value;
+ var variableReplacement = function (_, name) {
+ var v = new Variable("@" + name, that.getIndex(), that.fileInfo()).eval(context, true);
+ return (v instanceof Quoted) ? v.value : v.toCSS();
+ };
+ var propertyReplacement = function (_, name) {
+ var v = new Property("$" + name, that.getIndex(), that.fileInfo()).eval(context, true);
+ return (v instanceof Quoted) ? v.value : v.toCSS();
+ };
+ function iterativeReplace(value, regexp, replacementFnc) {
+ var evaluatedValue = value;
+ do {
+ value = evaluatedValue.toString();
+ evaluatedValue = value.replace(regexp, replacementFnc);
+ } while (value !== evaluatedValue);
+ return evaluatedValue;
+ }
+ value = iterativeReplace(value, this.variableRegex, variableReplacement);
+ value = iterativeReplace(value, this.propRegex, propertyReplacement);
+ return new Quoted(this.quote + value + this.quote, value, this.escaped, this.getIndex(), this.fileInfo());
+ },
+ compare: function (other) {
+ // when comparing quoted strings allow the quote to differ
+ if (other.type === 'Quoted' && !this.escaped && !other.escaped) {
+ return Node.numericCompare(this.value, other.value);
+ }
+ else {
+ return other.toCSS && this.toCSS() === other.toCSS() ? 0 : undefined;
+ }
+ }
+ });
+
+ function escapePath(path) {
+ return path.replace(/[\(\)'"\s]/g, function (match) { return "\\" + match; });
+ }
+ var URL = function (val, index, currentFileInfo, isEvald) {
+ this.value = val;
+ this._index = index;
+ this._fileInfo = currentFileInfo;
+ this.isEvald = isEvald;
+ };
+ URL.prototype = Object.assign(new Node(), {
+ type: 'Url',
+ accept: function (visitor) {
+ this.value = visitor.visit(this.value);
+ },
+ genCSS: function (context, output) {
+ output.add('url(');
+ this.value.genCSS(context, output);
+ output.add(')');
+ },
+ eval: function (context) {
+ var val = this.value.eval(context);
+ var rootpath;
+ if (!this.isEvald) {
+ // Add the rootpath if the URL requires a rewrite
+ rootpath = this.fileInfo() && this.fileInfo().rootpath;
+ if (typeof rootpath === 'string' &&
+ typeof val.value === 'string' &&
+ context.pathRequiresRewrite(val.value)) {
+ if (!val.quote) {
+ rootpath = escapePath(rootpath);
+ }
+ val.value = context.rewritePath(val.value, rootpath);
+ }
+ else {
+ val.value = context.normalizePath(val.value);
+ }
+ // Add url args if enabled
+ if (context.urlArgs) {
+ if (!val.value.match(/^\s*data:/)) {
+ var delimiter = val.value.indexOf('?') === -1 ? '?' : '&';
+ var urlArgs = delimiter + context.urlArgs;
+ if (val.value.indexOf('#') !== -1) {
+ val.value = val.value.replace('#', urlArgs + "#");
+ }
+ else {
+ val.value += urlArgs;
+ }
+ }
+ }
+ }
+ return new URL(val, this.getIndex(), this.fileInfo(), true);
+ }
+ });
+
+ var Media = function (value, features, index, currentFileInfo, visibilityInfo) {
+ this._index = index;
+ this._fileInfo = currentFileInfo;
+ var selectors = (new Selector([], null, null, this._index, this._fileInfo)).createEmptySelectors();
+ this.features = new Value(features);
+ this.rules = [new Ruleset(selectors, value)];
+ this.rules[0].allowImports = true;
+ this.copyVisibilityInfo(visibilityInfo);
+ this.allowRoot = true;
+ this.setParent(selectors, this);
+ this.setParent(this.features, this);
+ this.setParent(this.rules, this);
+ };
+ Media.prototype = Object.assign(new AtRule(), {
+ type: 'Media',
+ isRulesetLike: function () {
+ return true;
+ },
+ accept: function (visitor) {
+ if (this.features) {
+ this.features = visitor.visit(this.features);
+ }
+ if (this.rules) {
+ this.rules = visitor.visitArray(this.rules);
+ }
+ },
+ genCSS: function (context, output) {
+ output.add('@media ', this._fileInfo, this._index);
+ this.features.genCSS(context, output);
+ this.outputRuleset(context, output, this.rules);
+ },
+ eval: function (context) {
+ if (!context.mediaBlocks) {
+ context.mediaBlocks = [];
+ context.mediaPath = [];
+ }
+ var media = new Media(null, [], this._index, this._fileInfo, this.visibilityInfo());
+ if (this.debugInfo) {
+ this.rules[0].debugInfo = this.debugInfo;
+ media.debugInfo = this.debugInfo;
+ }
+ media.features = this.features.eval(context);
+ context.mediaPath.push(media);
+ context.mediaBlocks.push(media);
+ this.rules[0].functionRegistry = context.frames[0].functionRegistry.inherit();
+ context.frames.unshift(this.rules[0]);
+ media.rules = [this.rules[0].eval(context)];
+ context.frames.shift();
+ context.mediaPath.pop();
+ return context.mediaPath.length === 0 ? media.evalTop(context) :
+ media.evalNested(context);
+ },
+ evalTop: function (context) {
+ var result = this;
+ // Render all dependent Media blocks.
+ if (context.mediaBlocks.length > 1) {
+ var selectors = (new Selector([], null, null, this.getIndex(), this.fileInfo())).createEmptySelectors();
+ result = new Ruleset(selectors, context.mediaBlocks);
+ result.multiMedia = true;
+ result.copyVisibilityInfo(this.visibilityInfo());
+ this.setParent(result, this);
+ }
+ delete context.mediaBlocks;
+ delete context.mediaPath;
+ return result;
+ },
+ evalNested: function (context) {
+ var i;
+ var value;
+ var path = context.mediaPath.concat([this]);
+ // Extract the media-query conditions separated with `,` (OR).
+ for (i = 0; i < path.length; i++) {
+ value = path[i].features instanceof Value ?
+ path[i].features.value : path[i].features;
+ path[i] = Array.isArray(value) ? value : [value];
+ }
+ // Trace all permutations to generate the resulting media-query.
//
- // Examples:
- // - If path of imported file is 'module/nav/nav.less' and rootpath is 'less/',
- // then rootpath should become 'less/module/nav/'
- // - If path of imported file is '../mixins.less' and rootpath is 'less/',
- // then rootpath should become 'less/../'
-
- newFileInfo.currentDirectory = fileManager.getPath(resolvedFilename);
-
- if (newFileInfo.rewriteUrls) {
- newFileInfo.rootpath = fileManager.join(importManager.context.rootpath || '', fileManager.pathDiff(newFileInfo.currentDirectory, newFileInfo.entryPath));
-
- if (!fileManager.isPathAbsolute(newFileInfo.rootpath) && fileManager.alwaysMakePathsAbsolute()) {
- newFileInfo.rootpath = fileManager.join(newFileInfo.entryPath, newFileInfo.rootpath);
- }
- }
-
- newFileInfo.filename = resolvedFilename;
- var newEnv = new contexts.Parse(importManager.context);
- newEnv.processImports = false;
- importManager.contents[resolvedFilename] = contents;
-
- if (currentFileInfo.reference || importOptions.reference) {
- newFileInfo.reference = true;
- }
-
- if (importOptions.isPlugin) {
- plugin = pluginLoader.evalPlugin(contents, newEnv, importManager, importOptions.pluginArgs, newFileInfo);
-
- if (plugin instanceof LessError) {
- fileParsedFunc(plugin, null, resolvedFilename);
- } else {
- fileParsedFunc(null, plugin, resolvedFilename);
- }
- } else if (importOptions.inline) {
- fileParsedFunc(null, contents, resolvedFilename);
- } else {
- // import (multiple) parse trees apparently get altered and can't be cached.
- // TODO: investigate why this is
- if (importManager.files[resolvedFilename] && !importManager.files[resolvedFilename].options.multiple && !importOptions.multiple) {
- fileParsedFunc(null, importManager.files[resolvedFilename].root, resolvedFilename);
- } else {
- new Parser(newEnv, importManager, newFileInfo).parse(contents, function (e, root) {
- fileParsedFunc(e, root, resolvedFilename);
- });
- }
- }
- };
-
- var promise;
- var context = clone(this.context);
-
- if (tryAppendExtension) {
- context.ext = importOptions.isPlugin ? '.js' : '.less';
- }
-
- if (importOptions.isPlugin) {
- context.mime = 'application/javascript';
- promise = pluginLoader.loadPlugin(path, currentFileInfo.currentDirectory, context, environment, fileManager);
- } else {
- promise = fileManager.loadFile(path, currentFileInfo.currentDirectory, context, environment, function (err, loadedFile) {
- if (err) {
- fileParsedFunc(err);
- } else {
- loadFileCallback(loadedFile);
- }
- });
- }
-
- if (promise) {
- promise.then(loadFileCallback, fileParsedFunc);
- }
- }
- }]);
-
- return ImportManager;
- }();
-
- return ImportManager;
- });
-
- var Render = (function (environment, ParseTree, ImportManager) {
- var render = function render(input, options, callback) {
- if (typeof options === 'function') {
- callback = options;
- options = copyOptions(this.options, {});
- } else {
- options = copyOptions(this.options, options || {});
- }
-
- if (!callback) {
- var self = this;
- return new Promise(function (resolve, reject) {
- render.call(self, input, options, function (err, output) {
- if (err) {
- reject(err);
- } else {
- resolve(output);
- }
- });
- });
- } else {
- this.parse(input, options, function (err, root, imports, options) {
- if (err) {
- return callback(err);
- }
-
- var result;
-
- try {
- var parseTree = new ParseTree(root, imports);
- result = parseTree.toCSS(options);
- } catch (err) {
- return callback(err);
- }
-
- callback(null, result);
- });
- }
- };
-
- return render;
- });
-
- /**
- * Plugin Manager
- */
- var PluginManager =
- /*#__PURE__*/
- function () {
- function PluginManager(less) {
- _classCallCheck(this, PluginManager);
-
- this.less = less;
- this.visitors = [];
- this.preProcessors = [];
- this.postProcessors = [];
- this.installedPlugins = [];
- this.fileManagers = [];
- this.iterator = -1;
- this.pluginCache = {};
- this.Loader = new less.PluginLoader(less);
- }
- /**
- * Adds all the plugins in the array
- * @param {Array} plugins
- */
-
-
- _createClass(PluginManager, [{
- key: "addPlugins",
- value: function addPlugins(plugins) {
- if (plugins) {
- for (var i = 0; i < plugins.length; i++) {
- this.addPlugin(plugins[i]);
- }
- }
- }
- /**
- *
- * @param plugin
- * @param {String} filename
- */
-
- }, {
- key: "addPlugin",
- value: function addPlugin(plugin, filename, functionRegistry) {
- this.installedPlugins.push(plugin);
-
- if (filename) {
- this.pluginCache[filename] = plugin;
- }
-
- if (plugin.install) {
- plugin.install(this.less, this, functionRegistry || this.less.functions.functionRegistry);
- }
- }
- /**
- *
- * @param filename
- */
-
- }, {
- key: "get",
- value: function get(filename) {
- return this.pluginCache[filename];
- }
- /**
- * Adds a visitor. The visitor object has options on itself to determine
- * when it should run.
- * @param visitor
- */
-
- }, {
- key: "addVisitor",
- value: function addVisitor(visitor) {
- this.visitors.push(visitor);
- }
- /**
- * Adds a pre processor object
- * @param {object} preProcessor
- * @param {number} priority - guidelines 1 = before import, 1000 = import, 2000 = after import
- */
-
- }, {
- key: "addPreProcessor",
- value: function addPreProcessor(preProcessor, priority) {
- var indexToInsertAt;
-
- for (indexToInsertAt = 0; indexToInsertAt < this.preProcessors.length; indexToInsertAt++) {
- if (this.preProcessors[indexToInsertAt].priority >= priority) {
- break;
- }
- }
-
- this.preProcessors.splice(indexToInsertAt, 0, {
- preProcessor: preProcessor,
- priority: priority
- });
- }
- /**
- * Adds a post processor object
- * @param {object} postProcessor
- * @param {number} priority - guidelines 1 = before compression, 1000 = compression, 2000 = after compression
- */
-
- }, {
- key: "addPostProcessor",
- value: function addPostProcessor(postProcessor, priority) {
- var indexToInsertAt;
-
- for (indexToInsertAt = 0; indexToInsertAt < this.postProcessors.length; indexToInsertAt++) {
- if (this.postProcessors[indexToInsertAt].priority >= priority) {
- break;
- }
- }
-
- this.postProcessors.splice(indexToInsertAt, 0, {
- postProcessor: postProcessor,
- priority: priority
- });
- }
- /**
- *
- * @param manager
- */
-
- }, {
- key: "addFileManager",
- value: function addFileManager(manager) {
- this.fileManagers.push(manager);
- }
- /**
- *
- * @returns {Array}
- * @private
- */
-
- }, {
- key: "getPreProcessors",
- value: function getPreProcessors() {
- var preProcessors = [];
-
- for (var i = 0; i < this.preProcessors.length; i++) {
- preProcessors.push(this.preProcessors[i].preProcessor);
- }
-
- return preProcessors;
- }
- /**
- *
- * @returns {Array}
- * @private
- */
-
- }, {
- key: "getPostProcessors",
- value: function getPostProcessors() {
- var postProcessors = [];
-
- for (var i = 0; i < this.postProcessors.length; i++) {
- postProcessors.push(this.postProcessors[i].postProcessor);
- }
-
- return postProcessors;
- }
- /**
- *
- * @returns {Array}
- * @private
- */
-
- }, {
- key: "getVisitors",
- value: function getVisitors() {
- return this.visitors;
- }
- }, {
- key: "visitor",
- value: function visitor() {
- var self = this;
- return {
- first: function first() {
- self.iterator = -1;
- return self.visitors[self.iterator];
- },
- get: function get() {
- self.iterator += 1;
- return self.visitors[self.iterator];
- }
- };
- }
- /**
- *
- * @returns {Array}
- * @private
- */
-
- }, {
- key: "getFileManagers",
- value: function getFileManagers() {
- return this.fileManagers;
- }
- }]);
-
- return PluginManager;
- }();
-
- var pm;
-
- function PluginManagerFactory(less, newFactory) {
- if (newFactory || !pm) {
- pm = new PluginManager(less);
- }
-
- return pm;
- }
-
- var Parse = (function (environment, ParseTree, ImportManager) {
- var parse = function parse(input, options, callback) {
- if (typeof options === 'function') {
- callback = options;
- options = copyOptions(this.options, {});
- } else {
- options = copyOptions(this.options, options || {});
- }
-
- if (!callback) {
- var self = this;
- return new Promise(function (resolve, reject) {
- parse.call(self, input, options, function (err, output) {
- if (err) {
- reject(err);
- } else {
- resolve(output);
- }
- });
- });
- } else {
- var context;
- var rootFileInfo;
- var pluginManager = new PluginManagerFactory(this, !options.reUsePluginManager);
- options.pluginManager = pluginManager;
- context = new contexts.Parse(options);
-
- if (options.rootFileInfo) {
- rootFileInfo = options.rootFileInfo;
- } else {
- var filename = options.filename || 'input';
- var entryPath = filename.replace(/[^\/\\]*$/, '');
- rootFileInfo = {
- filename: filename,
- rewriteUrls: context.rewriteUrls,
- rootpath: context.rootpath || '',
- currentDirectory: entryPath,
- entryPath: entryPath,
- rootFilename: filename
- }; // add in a missing trailing slash
-
- if (rootFileInfo.rootpath && rootFileInfo.rootpath.slice(-1) !== '/') {
- rootFileInfo.rootpath += '/';
- }
- }
-
- var imports = new ImportManager(this, context, rootFileInfo);
- this.importManager = imports; // TODO: allow the plugins to be just a list of paths or names
- // Do an async plugin queue like lessc
-
- if (options.plugins) {
- options.plugins.forEach(function (plugin) {
- var evalResult;
- var contents;
-
- if (plugin.fileContent) {
- contents = plugin.fileContent.replace(/^\uFEFF/, '');
- evalResult = pluginManager.Loader.evalPlugin(contents, context, imports, plugin.options, plugin.filename);
-
- if (evalResult instanceof LessError) {
- return callback(evalResult);
- }
- } else {
- pluginManager.addPlugin(plugin);
- }
- });
- }
-
- new Parser(context, imports, rootFileInfo).parse(input, function (e, root) {
- if (e) {
- return callback(e);
- }
-
- callback(null, root, imports, options);
- }, options);
- }
- };
-
- return parse;
- });
-
- var lessRoot = (function (environment$1, fileManagers) {
- /**
- * @todo
- * This original code could be improved quite a bit.
- * Many classes / modules currently add side-effects / mutations to passed in objects,
- * which makes it hard to refactor and reason about.
- */
- environment$1 = new environment(environment$1, fileManagers);
- var SourceMapOutput = sourceMapOutput(environment$1);
- var SourceMapBuilder = sourceMapBuilder(SourceMapOutput, environment$1);
- var ParseTree = parseTree(SourceMapBuilder);
- var ImportManager = importManager(environment$1);
- var render = Render(environment$1, ParseTree);
- var parse = Parse(environment$1, ParseTree, ImportManager);
- var functions = Functions(environment$1);
- /**
- * @todo
- * This root properties / methods need to be organized.
- * It's not clear what should / must be public and why.
- */
-
- var initial = {
- version: [3, 10, 3],
- data: data,
- tree: tree,
- Environment: environment,
- AbstractFileManager: AbstractFileManager,
- AbstractPluginLoader: AbstractPluginLoader,
- environment: environment$1,
- visitors: visitors,
- Parser: Parser,
- functions: functions,
- contexts: contexts,
- SourceMapOutput: SourceMapOutput,
- SourceMapBuilder: SourceMapBuilder,
- ParseTree: ParseTree,
- ImportManager: ImportManager,
- render: render,
- parse: parse,
- LessError: LessError,
- transformTree: transformTree,
- utils: utils,
- PluginManager: PluginManagerFactory,
- logger: logger
- }; // Create a public API
-
- var ctor = function ctor(t) {
- return function () {
- for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
- args[_key] = arguments[_key];
- }
-
- return _construct(t, args);
- };
- };
-
- var t;
- var api = Object.create(initial);
-
- for (var n in initial.tree) {
- /* eslint guard-for-in: 0 */
- t = initial.tree[n];
-
- if (typeof t === 'function') {
- api[n.toLowerCase()] = ctor(t);
- } else {
- api[n] = Object.create(null);
-
- for (var o in t) {
- /* eslint guard-for-in: 0 */
- api[n][o.toLowerCase()] = ctor(t[o]);
- }
- }
- }
-
- return api;
- });
-
- var options;
- var logger$1;
- var fileCache = {}; // TODOS - move log somewhere. pathDiff and doing something similar in node. use pathDiff in the other browser file for the initial load
-
- var FileManager =
- /*#__PURE__*/
- function (_AbstractFileManager) {
- _inherits(FileManager, _AbstractFileManager);
-
- function FileManager() {
- _classCallCheck(this, FileManager);
-
- return _possibleConstructorReturn(this, _getPrototypeOf(FileManager).apply(this, arguments));
- }
-
- _createClass(FileManager, [{
- key: "alwaysMakePathsAbsolute",
- value: function alwaysMakePathsAbsolute() {
- return true;
- }
- }, {
- key: "join",
- value: function join(basePath, laterPath) {
- if (!basePath) {
- return laterPath;
- }
-
- return this.extractUrlParts(laterPath, basePath).path;
- }
- }, {
- key: "doXHR",
- value: function doXHR(url, type, callback, errback) {
- var xhr = new XMLHttpRequest();
- var async = options.isFileProtocol ? options.fileAsync : true;
-
- if (typeof xhr.overrideMimeType === 'function') {
- xhr.overrideMimeType('text/css');
- }
-
- logger$1.debug("XHR: Getting '".concat(url, "'"));
- xhr.open('GET', url, async);
- xhr.setRequestHeader('Accept', type || 'text/x-less, text/css; q=0.9, */*; q=0.5');
- xhr.send(null);
-
- function handleResponse(xhr, callback, errback) {
- if (xhr.status >= 200 && xhr.status < 300) {
- callback(xhr.responseText, xhr.getResponseHeader('Last-Modified'));
- } else if (typeof errback === 'function') {
- errback(xhr.status, url);
- }
- }
-
- if (options.isFileProtocol && !options.fileAsync) {
- if (xhr.status === 0 || xhr.status >= 200 && xhr.status < 300) {
- callback(xhr.responseText);
- } else {
- errback(xhr.status, url);
- }
- } else if (async) {
- xhr.onreadystatechange = function () {
- if (xhr.readyState == 4) {
- handleResponse(xhr, callback, errback);
- }
- };
- } else {
- handleResponse(xhr, callback, errback);
- }
- }
- }, {
- key: "supports",
- value: function supports() {
- return true;
- }
- }, {
- key: "clearFileCache",
- value: function clearFileCache() {
- fileCache = {};
- }
- }, {
- key: "loadFile",
- value: function loadFile(filename, currentDirectory, options, environment) {
- // TODO: Add prefix support like less-node?
- // What about multiple paths?
- if (currentDirectory && !this.isPathAbsolute(filename)) {
- filename = currentDirectory + filename;
- }
-
- filename = options.ext ? this.tryAppendExtension(filename, options.ext) : filename;
- options = options || {}; // sheet may be set to the stylesheet for the initial load or a collection of properties including
- // some context variables for imports
-
- var hrefParts = this.extractUrlParts(filename, window.location.href);
- var href = hrefParts.url;
- var self = this;
- return new Promise(function (resolve, reject) {
- if (options.useFileCache && fileCache[href]) {
- try {
- var lessText = fileCache[href];
- return resolve({
- contents: lessText,
- filename: href,
- webInfo: {
- lastModified: new Date()
+ // (a, b and c) with nested (d, e) ->
+ // a and d
+ // a and e
+ // b and c and d
+ // b and c and e
+ this.features = new Value(this.permute(path).map(function (path) {
+ path = path.map(function (fragment) { return fragment.toCSS ? fragment : new Anonymous(fragment); });
+ for (i = path.length - 1; i > 0; i--) {
+ path.splice(i, 0, new Anonymous('and'));
}
- });
- } catch (e) {
- return reject({
- filename: href,
- message: "Error loading file ".concat(href, " error was ").concat(e.message)
- });
+ return new Expression(path);
+ }));
+ this.setParent(this.features, this);
+ // Fake a tree-node that doesn't output anything.
+ return new Ruleset([], []);
+ },
+ permute: function (arr) {
+ if (arr.length === 0) {
+ return [];
}
- }
+ else if (arr.length === 1) {
+ return arr[0];
+ }
+ else {
+ var result = [];
+ var rest = this.permute(arr.slice(1));
+ for (var i = 0; i < rest.length; i++) {
+ for (var j = 0; j < arr[0].length; j++) {
+ result.push([arr[0][j]].concat(rest[i]));
+ }
+ }
+ return result;
+ }
+ },
+ bubbleSelectors: function (selectors) {
+ if (!selectors) {
+ return;
+ }
+ this.rules = [new Ruleset(copyArray(selectors), [this.rules[0]])];
+ this.setParent(this.rules, this);
+ }
+ });
- self.doXHR(href, options.mime, function doXHRCallback(data, lastModified) {
- // per file cache
- fileCache[href] = data; // Use remote copy (re-parse)
+ //
+ // CSS @import node
+ //
+ // The general strategy here is that we don't want to wait
+ // for the parsing to be completed, before we start importing
+ // the file. That's because in the context of a browser,
+ // most of the time will be spent waiting for the server to respond.
+ //
+ // On creation, we push the import path to our import queue, though
+ // `import,push`, we also pass it a callback, which it'll call once
+ // the file has been fetched, and parsed.
+ //
+ var Import = function (path, features, options, index, currentFileInfo, visibilityInfo) {
+ this.options = options;
+ this._index = index;
+ this._fileInfo = currentFileInfo;
+ this.path = path;
+ this.features = features;
+ this.allowRoot = true;
+ if (this.options.less !== undefined || this.options.inline) {
+ this.css = !this.options.less || this.options.inline;
+ }
+ else {
+ var pathValue = this.getPath();
+ if (pathValue && /[#\.\&\?]css([\?;].*)?$/.test(pathValue)) {
+ this.css = true;
+ }
+ }
+ this.copyVisibilityInfo(visibilityInfo);
+ this.setParent(this.features, this);
+ this.setParent(this.path, this);
+ };
+ Import.prototype = Object.assign(new Node(), {
+ type: 'Import',
+ accept: function (visitor) {
+ if (this.features) {
+ this.features = visitor.visit(this.features);
+ }
+ this.path = visitor.visit(this.path);
+ if (!this.options.isPlugin && !this.options.inline && this.root) {
+ this.root = visitor.visit(this.root);
+ }
+ },
+ genCSS: function (context, output) {
+ if (this.css && this.path._fileInfo.reference === undefined) {
+ output.add('@import ', this._fileInfo, this._index);
+ this.path.genCSS(context, output);
+ if (this.features) {
+ output.add(' ');
+ this.features.genCSS(context, output);
+ }
+ output.add(';');
+ }
+ },
+ getPath: function () {
+ return (this.path instanceof URL) ?
+ this.path.value.value : this.path.value;
+ },
+ isVariableImport: function () {
+ var path = this.path;
+ if (path instanceof URL) {
+ path = path.value;
+ }
+ if (path instanceof Quoted) {
+ return path.containsVariables();
+ }
+ return true;
+ },
+ evalForImport: function (context) {
+ var path = this.path;
+ if (path instanceof URL) {
+ path = path.value;
+ }
+ return new Import(path.eval(context), this.features, this.options, this._index, this._fileInfo, this.visibilityInfo());
+ },
+ evalPath: function (context) {
+ var path = this.path.eval(context);
+ var fileInfo = this._fileInfo;
+ if (!(path instanceof URL)) {
+ // Add the rootpath if the URL requires a rewrite
+ var pathValue = path.value;
+ if (fileInfo &&
+ pathValue &&
+ context.pathRequiresRewrite(pathValue)) {
+ path.value = context.rewritePath(pathValue, fileInfo.rootpath);
+ }
+ else {
+ path.value = context.normalizePath(path.value);
+ }
+ }
+ return path;
+ },
+ eval: function (context) {
+ var result = this.doEval(context);
+ if (this.options.reference || this.blocksVisibility()) {
+ if (result.length || result.length === 0) {
+ result.forEach(function (node) {
+ node.addVisibilityBlock();
+ });
+ }
+ else {
+ result.addVisibilityBlock();
+ }
+ }
+ return result;
+ },
+ doEval: function (context) {
+ var ruleset;
+ var registry;
+ var features = this.features && this.features.eval(context);
+ if (this.options.isPlugin) {
+ if (this.root && this.root.eval) {
+ try {
+ this.root.eval(context);
+ }
+ catch (e) {
+ e.message = 'Plugin error during evaluation';
+ throw new LessError(e, this.root.imports, this.root.filename);
+ }
+ }
+ registry = context.frames[0] && context.frames[0].functionRegistry;
+ if (registry && this.root && this.root.functions) {
+ registry.addMultiple(this.root.functions);
+ }
+ return [];
+ }
+ if (this.skip) {
+ if (typeof this.skip === 'function') {
+ this.skip = this.skip();
+ }
+ if (this.skip) {
+ return [];
+ }
+ }
+ if (this.options.inline) {
+ var contents = new Anonymous(this.root, 0, {
+ filename: this.importedFilename,
+ reference: this.path._fileInfo && this.path._fileInfo.reference
+ }, true, true);
+ return this.features ? new Media([contents], this.features.value) : [contents];
+ }
+ else if (this.css) {
+ var newImport = new Import(this.evalPath(context), features, this.options, this._index);
+ if (!newImport.css && this.error) {
+ throw this.error;
+ }
+ return newImport;
+ }
+ else if (this.root) {
+ ruleset = new Ruleset(null, copyArray(this.root.rules));
+ ruleset.evalImports(context);
+ return this.features ? new Media(ruleset.rules, this.features.value) : ruleset.rules;
+ }
+ else {
+ return [];
+ }
+ }
+ });
- resolve({
- contents: data,
- filename: href,
- webInfo: {
- lastModified: lastModified
- }
+ var JsEvalNode = function () { };
+ JsEvalNode.prototype = Object.assign(new Node(), {
+ evaluateJavaScript: function (expression, context) {
+ var result;
+ var that = this;
+ var evalContext = {};
+ if (!context.javascriptEnabled) {
+ throw { message: 'Inline JavaScript is not enabled. Is it set in your options?',
+ filename: this.fileInfo().filename,
+ index: this.getIndex() };
+ }
+ expression = expression.replace(/@\{([\w-]+)\}/g, function (_, name) {
+ return that.jsify(new Variable("@" + name, that.getIndex(), that.fileInfo()).eval(context));
});
- }, function doXHRError(status, url) {
- reject({
- type: 'File',
- message: "'".concat(url, "' wasn't found (").concat(status, ")"),
- href: href
+ try {
+ expression = new Function("return (" + expression + ")");
+ }
+ catch (e) {
+ throw { message: "JavaScript evaluation error: " + e.message + " from `" + expression + "`",
+ filename: this.fileInfo().filename,
+ index: this.getIndex() };
+ }
+ var variables = context.frames[0].variables();
+ for (var k in variables) {
+ if (variables.hasOwnProperty(k)) {
+ /* jshint loopfunc:true */
+ evalContext[k.slice(1)] = {
+ value: variables[k].value,
+ toJS: function () {
+ return this.value.eval(context).toCSS();
+ }
+ };
+ }
+ }
+ try {
+ result = expression.call(evalContext);
+ }
+ catch (e) {
+ throw { message: "JavaScript evaluation error: '" + e.name + ": " + e.message.replace(/["]/g, '\'') + "'",
+ filename: this.fileInfo().filename,
+ index: this.getIndex() };
+ }
+ return result;
+ },
+ jsify: function (obj) {
+ if (Array.isArray(obj.value) && (obj.value.length > 1)) {
+ return "[" + obj.value.map(function (v) { return v.toCSS(); }).join(', ') + "]";
+ }
+ else {
+ return obj.toCSS();
+ }
+ }
+ });
+
+ var JavaScript = function (string, escaped, index, currentFileInfo) {
+ this.escaped = escaped;
+ this.expression = string;
+ this._index = index;
+ this._fileInfo = currentFileInfo;
+ };
+ JavaScript.prototype = Object.assign(new JsEvalNode(), {
+ type: 'JavaScript',
+ eval: function (context) {
+ var result = this.evaluateJavaScript(this.expression, context);
+ var type = typeof result;
+ if (type === 'number' && !isNaN(result)) {
+ return new Dimension(result);
+ }
+ else if (type === 'string') {
+ return new Quoted("\"" + result + "\"", result, this.escaped, this._index);
+ }
+ else if (Array.isArray(result)) {
+ return new Anonymous(result.join(', '));
+ }
+ else {
+ return new Anonymous(result);
+ }
+ }
+ });
+
+ var Assignment = function (key, val) {
+ this.key = key;
+ this.value = val;
+ };
+ Assignment.prototype = Object.assign(new Node(), {
+ type: 'Assignment',
+ accept: function (visitor) {
+ this.value = visitor.visit(this.value);
+ },
+ eval: function (context) {
+ if (this.value.eval) {
+ return new Assignment(this.key, this.value.eval(context));
+ }
+ return this;
+ },
+ genCSS: function (context, output) {
+ output.add(this.key + "=");
+ if (this.value.genCSS) {
+ this.value.genCSS(context, output);
+ }
+ else {
+ output.add(this.value);
+ }
+ }
+ });
+
+ var Condition = function (op, l, r, i, negate) {
+ this.op = op.trim();
+ this.lvalue = l;
+ this.rvalue = r;
+ this._index = i;
+ this.negate = negate;
+ };
+ Condition.prototype = Object.assign(new Node(), {
+ type: 'Condition',
+ accept: function (visitor) {
+ this.lvalue = visitor.visit(this.lvalue);
+ this.rvalue = visitor.visit(this.rvalue);
+ },
+ eval: function (context) {
+ var result = (function (op, a, b) {
+ switch (op) {
+ case 'and': return a && b;
+ case 'or': return a || b;
+ default:
+ switch (Node.compare(a, b)) {
+ case -1:
+ return op === '<' || op === '=<' || op === '<=';
+ case 0:
+ return op === '=' || op === '>=' || op === '=<' || op === '<=';
+ case 1:
+ return op === '>' || op === '>=';
+ default:
+ return false;
+ }
+ }
+ })(this.op, this.lvalue.eval(context), this.rvalue.eval(context));
+ return this.negate ? !result : result;
+ }
+ });
+
+ var UnicodeDescriptor = function (value) {
+ this.value = value;
+ };
+ UnicodeDescriptor.prototype = Object.assign(new Node(), {
+ type: 'UnicodeDescriptor'
+ });
+
+ var Negative = function (node) {
+ this.value = node;
+ };
+ Negative.prototype = Object.assign(new Node(), {
+ type: 'Negative',
+ genCSS: function (context, output) {
+ output.add('-');
+ this.value.genCSS(context, output);
+ },
+ eval: function (context) {
+ if (context.isMathOn()) {
+ return (new Operation('*', [new Dimension(-1), this.value])).eval(context);
+ }
+ return new Negative(this.value.eval(context));
+ }
+ });
+
+ var Extend = function (selector, option, index, currentFileInfo, visibilityInfo) {
+ this.selector = selector;
+ this.option = option;
+ this.object_id = Extend.next_id++;
+ this.parent_ids = [this.object_id];
+ this._index = index;
+ this._fileInfo = currentFileInfo;
+ this.copyVisibilityInfo(visibilityInfo);
+ this.allowRoot = true;
+ switch (option) {
+ case 'all':
+ this.allowBefore = true;
+ this.allowAfter = true;
+ break;
+ default:
+ this.allowBefore = false;
+ this.allowAfter = false;
+ break;
+ }
+ this.setParent(this.selector, this);
+ };
+ Extend.prototype = Object.assign(new Node(), {
+ type: 'Extend',
+ accept: function (visitor) {
+ this.selector = visitor.visit(this.selector);
+ },
+ eval: function (context) {
+ return new Extend(this.selector.eval(context), this.option, this.getIndex(), this.fileInfo(), this.visibilityInfo());
+ },
+ clone: function (context) {
+ return new Extend(this.selector, this.option, this.getIndex(), this.fileInfo(), this.visibilityInfo());
+ },
+ // it concatenates (joins) all selectors in selector array
+ findSelfSelectors: function (selectors) {
+ var selfElements = [], i, selectorElements;
+ for (i = 0; i < selectors.length; i++) {
+ selectorElements = selectors[i].elements;
+ // duplicate the logic in genCSS function inside the selector node.
+ // future TODO - move both logics into the selector joiner visitor
+ if (i > 0 && selectorElements.length && selectorElements[0].combinator.value === '') {
+ selectorElements[0].combinator.value = ' ';
+ }
+ selfElements = selfElements.concat(selectors[i].elements);
+ }
+ this.selfSelectors = [new Selector(selfElements)];
+ this.selfSelectors[0].copyVisibilityInfo(this.visibilityInfo());
+ }
+ });
+ Extend.next_id = 0;
+
+ var VariableCall = function (variable, index, currentFileInfo) {
+ this.variable = variable;
+ this._index = index;
+ this._fileInfo = currentFileInfo;
+ this.allowRoot = true;
+ };
+ VariableCall.prototype = Object.assign(new Node(), {
+ type: 'VariableCall',
+ eval: function (context) {
+ var rules;
+ var detachedRuleset = new Variable(this.variable, this.getIndex(), this.fileInfo()).eval(context);
+ var error = new LessError({ message: "Could not evaluate variable call " + this.variable });
+ if (!detachedRuleset.ruleset) {
+ if (detachedRuleset.rules) {
+ rules = detachedRuleset;
+ }
+ else if (Array.isArray(detachedRuleset)) {
+ rules = new Ruleset('', detachedRuleset);
+ }
+ else if (Array.isArray(detachedRuleset.value)) {
+ rules = new Ruleset('', detachedRuleset.value);
+ }
+ else {
+ throw error;
+ }
+ detachedRuleset = new DetachedRuleset(rules);
+ }
+ if (detachedRuleset.ruleset) {
+ return detachedRuleset.callEval(context);
+ }
+ throw error;
+ }
+ });
+
+ var NamespaceValue = function (ruleCall, lookups, index, fileInfo) {
+ this.value = ruleCall;
+ this.lookups = lookups;
+ this._index = index;
+ this._fileInfo = fileInfo;
+ };
+ NamespaceValue.prototype = Object.assign(new Node(), {
+ type: 'NamespaceValue',
+ eval: function (context) {
+ var i, name, rules = this.value.eval(context);
+ for (i = 0; i < this.lookups.length; i++) {
+ name = this.lookups[i];
+ /**
+ * Eval'd DRs return rulesets.
+ * Eval'd mixins return rules, so let's make a ruleset if we need it.
+ * We need to do this because of late parsing of values
+ */
+ if (Array.isArray(rules)) {
+ rules = new Ruleset([new Selector()], rules);
+ }
+ if (name === '') {
+ rules = rules.lastDeclaration();
+ }
+ else if (name.charAt(0) === '@') {
+ if (name.charAt(1) === '@') {
+ name = "@" + new Variable(name.substr(1)).eval(context).value;
+ }
+ if (rules.variables) {
+ rules = rules.variable(name);
+ }
+ if (!rules) {
+ throw { type: 'Name',
+ message: "variable " + name + " not found",
+ filename: this.fileInfo().filename,
+ index: this.getIndex() };
+ }
+ }
+ else {
+ if (name.substring(0, 2) === '$@') {
+ name = "$" + new Variable(name.substr(1)).eval(context).value;
+ }
+ else {
+ name = name.charAt(0) === '$' ? name : "$" + name;
+ }
+ if (rules.properties) {
+ rules = rules.property(name);
+ }
+ if (!rules) {
+ throw { type: 'Name',
+ message: "property \"" + name.substr(1) + "\" not found",
+ filename: this.fileInfo().filename,
+ index: this.getIndex() };
+ }
+ // Properties are an array of values, since a ruleset can have multiple props.
+ // We pick the last one (the "cascaded" value)
+ rules = rules[rules.length - 1];
+ }
+ if (rules.value) {
+ rules = rules.eval(context).value;
+ }
+ if (rules.ruleset) {
+ rules = rules.ruleset.eval(context);
+ }
+ }
+ return rules;
+ }
+ });
+
+ var Definition = function (name, params, rules, condition, variadic, frames, visibilityInfo) {
+ this.name = name || 'anonymous mixin';
+ this.selectors = [new Selector([new Element(null, name, false, this._index, this._fileInfo)])];
+ this.params = params;
+ this.condition = condition;
+ this.variadic = variadic;
+ this.arity = params.length;
+ this.rules = rules;
+ this._lookups = {};
+ var optionalParameters = [];
+ this.required = params.reduce(function (count, p) {
+ if (!p.name || (p.name && !p.value)) {
+ return count + 1;
+ }
+ else {
+ optionalParameters.push(p.name);
+ return count;
+ }
+ }, 0);
+ this.optionalParameters = optionalParameters;
+ this.frames = frames;
+ this.copyVisibilityInfo(visibilityInfo);
+ this.allowRoot = true;
+ };
+ Definition.prototype = Object.assign(new Ruleset(), {
+ type: 'MixinDefinition',
+ evalFirst: true,
+ accept: function (visitor) {
+ if (this.params && this.params.length) {
+ this.params = visitor.visitArray(this.params);
+ }
+ this.rules = visitor.visitArray(this.rules);
+ if (this.condition) {
+ this.condition = visitor.visit(this.condition);
+ }
+ },
+ evalParams: function (context, mixinEnv, args, evaldArguments) {
+ /* jshint boss:true */
+ var frame = new Ruleset(null, null);
+ var varargs;
+ var arg;
+ var params = copyArray(this.params);
+ var i;
+ var j;
+ var val;
+ var name;
+ var isNamedFound;
+ var argIndex;
+ var argsLength = 0;
+ if (mixinEnv.frames && mixinEnv.frames[0] && mixinEnv.frames[0].functionRegistry) {
+ frame.functionRegistry = mixinEnv.frames[0].functionRegistry.inherit();
+ }
+ mixinEnv = new contexts.Eval(mixinEnv, [frame].concat(mixinEnv.frames));
+ if (args) {
+ args = copyArray(args);
+ argsLength = args.length;
+ for (i = 0; i < argsLength; i++) {
+ arg = args[i];
+ if (name = (arg && arg.name)) {
+ isNamedFound = false;
+ for (j = 0; j < params.length; j++) {
+ if (!evaldArguments[j] && name === params[j].name) {
+ evaldArguments[j] = arg.value.eval(context);
+ frame.prependRule(new Declaration(name, arg.value.eval(context)));
+ isNamedFound = true;
+ break;
+ }
+ }
+ if (isNamedFound) {
+ args.splice(i, 1);
+ i--;
+ continue;
+ }
+ else {
+ throw { type: 'Runtime', message: "Named argument for " + this.name + " " + args[i].name + " not found" };
+ }
+ }
+ }
+ }
+ argIndex = 0;
+ for (i = 0; i < params.length; i++) {
+ if (evaldArguments[i]) {
+ continue;
+ }
+ arg = args && args[argIndex];
+ if (name = params[i].name) {
+ if (params[i].variadic) {
+ varargs = [];
+ for (j = argIndex; j < argsLength; j++) {
+ varargs.push(args[j].value.eval(context));
+ }
+ frame.prependRule(new Declaration(name, new Expression(varargs).eval(context)));
+ }
+ else {
+ val = arg && arg.value;
+ if (val) {
+ // This was a mixin call, pass in a detached ruleset of it's eval'd rules
+ if (Array.isArray(val)) {
+ val = new DetachedRuleset(new Ruleset('', val));
+ }
+ else {
+ val = val.eval(context);
+ }
+ }
+ else if (params[i].value) {
+ val = params[i].value.eval(mixinEnv);
+ frame.resetCache();
+ }
+ else {
+ throw { type: 'Runtime', message: "wrong number of arguments for " + this.name + " (" + argsLength + " for " + this.arity + ")" };
+ }
+ frame.prependRule(new Declaration(name, val));
+ evaldArguments[i] = val;
+ }
+ }
+ if (params[i].variadic && args) {
+ for (j = argIndex; j < argsLength; j++) {
+ evaldArguments[j] = args[j].value.eval(context);
+ }
+ }
+ argIndex++;
+ }
+ return frame;
+ },
+ makeImportant: function () {
+ var rules = !this.rules ? this.rules : this.rules.map(function (r) {
+ if (r.makeImportant) {
+ return r.makeImportant(true);
+ }
+ else {
+ return r;
+ }
});
- });
- });
- }
- }]);
-
- return FileManager;
- }(AbstractFileManager);
-
- var FM = (function (opts, log) {
- options = opts;
- logger$1 = log;
- return FileManager;
- });
-
- /**
- * Browser Plugin Loader
- */
-
- var PluginLoader =
- /*#__PURE__*/
- function (_AbstractPluginLoader) {
- _inherits(PluginLoader, _AbstractPluginLoader);
-
- function PluginLoader(less) {
- var _this;
-
- _classCallCheck(this, PluginLoader);
-
- _this = _possibleConstructorReturn(this, _getPrototypeOf(PluginLoader).call(this));
- _this.less = less; // Should we shim this.require for browser? Probably not?
-
- return _this;
- }
-
- _createClass(PluginLoader, [{
- key: "loadPlugin",
- value: function loadPlugin(filename, basePath, context, environment, fileManager) {
- return new Promise(function (fulfill, reject) {
- fileManager.loadFile(filename, basePath, context, environment).then(fulfill).catch(reject);
- });
- }
- }]);
-
- return PluginLoader;
- }(AbstractPluginLoader);
-
- var LogListener = (function (less, options) {
- var logLevel_debug = 4;
- var logLevel_info = 3;
- var logLevel_warn = 2;
- var logLevel_error = 1; // The amount of logging in the javascript console.
- // 3 - Debug, information and errors
- // 2 - Information and errors
- // 1 - Errors
- // 0 - None
- // Defaults to 2
-
- options.logLevel = typeof options.logLevel !== 'undefined' ? options.logLevel : options.env === 'development' ? logLevel_info : logLevel_error;
-
- if (!options.loggers) {
- options.loggers = [{
- debug: function debug(msg) {
- if (options.logLevel >= logLevel_debug) {
- console.log(msg);
- }
+ var result = new Definition(this.name, this.params, rules, this.condition, this.variadic, this.frames);
+ return result;
},
- info: function info(msg) {
- if (options.logLevel >= logLevel_info) {
- console.log(msg);
- }
+ eval: function (context) {
+ return new Definition(this.name, this.params, this.rules, this.condition, this.variadic, this.frames || copyArray(context.frames));
},
- warn: function warn(msg) {
- if (options.logLevel >= logLevel_warn) {
- console.warn(msg);
- }
+ evalCall: function (context, args, important) {
+ var _arguments = [];
+ var mixinFrames = this.frames ? this.frames.concat(context.frames) : context.frames;
+ var frame = this.evalParams(context, new contexts.Eval(context, mixinFrames), args, _arguments);
+ var rules;
+ var ruleset;
+ frame.prependRule(new Declaration('@arguments', new Expression(_arguments).eval(context)));
+ rules = copyArray(this.rules);
+ ruleset = new Ruleset(null, rules);
+ ruleset.originalRuleset = this;
+ ruleset = ruleset.eval(new contexts.Eval(context, [this, frame].concat(mixinFrames)));
+ if (important) {
+ ruleset = ruleset.makeImportant();
+ }
+ return ruleset;
},
- error: function error(msg) {
- if (options.logLevel >= logLevel_error) {
- console.error(msg);
- }
- }
- }];
- }
-
- for (var i = 0; i < options.loggers.length; i++) {
- less.logger.addListener(options.loggers[i]);
- }
- });
-
- var ErrorReporting = (function (window, less, options) {
- function errorHTML(e, rootHref) {
- var id = "less-error-message:".concat(extractId(rootHref || ''));
- var template = '
{content}
';
- var elem = window.document.createElement('div');
- var timer;
- var content;
- var errors = [];
- var filename = e.filename || rootHref;
- var filenameNoPath = filename.match(/([^\/]+(\?.*)?)$/)[1];
- elem.id = id;
- elem.className = 'less-error-message';
- content = "
".concat(e.type || 'Syntax', "Error: ").concat(e.message || 'There is an error in your .less file') + "
in ").concat(filenameNoPath, " ");
-
- var errorline = function errorline(e, i, classname) {
- if (e.extract[i] !== undefined) {
- errors.push(template.replace(/\{line\}/, (parseInt(e.line, 10) || 0) + (i - 1)).replace(/\{class\}/, classname).replace(/\{content\}/, e.extract[i]));
- }
- };
-
- if (e.line) {
- errorline(e, 0, '');
- errorline(e, 1, 'line');
- errorline(e, 2, '');
- content += "on line ".concat(e.line, ", column ").concat(e.column + 1, ":
").concat(errors.join(''), "
");
- }
-
- if (e.stack && (e.extract || options.logLevel >= 4)) {
- content += " Stack Trace".concat(e.stack.split('\n').slice(1).join(' '));
- }
-
- elem.innerHTML = content; // CSS for error messages
-
- browser.createCSS(window.document, ['.less-error-message ul, .less-error-message li {', 'list-style-type: none;', 'margin-right: 15px;', 'padding: 4px 0;', 'margin: 0;', '}', '.less-error-message label {', 'font-size: 12px;', 'margin-right: 15px;', 'padding: 4px 0;', 'color: #cc7777;', '}', '.less-error-message pre {', 'color: #dd6666;', 'padding: 4px 0;', 'margin: 0;', 'display: inline-block;', '}', '.less-error-message pre.line {', 'color: #ff0000;', '}', '.less-error-message h3 {', 'font-size: 20px;', 'font-weight: bold;', 'padding: 15px 0 5px 0;', 'margin: 0;', '}', '.less-error-message a {', 'color: #10a', '}', '.less-error-message .error {', 'color: red;', 'font-weight: bold;', 'padding-bottom: 2px;', 'border-bottom: 1px dashed red;', '}'].join('\n'), {
- title: 'error-message'
- });
- elem.style.cssText = ['font-family: Arial, sans-serif', 'border: 1px solid #e00', 'background-color: #eee', 'border-radius: 5px', '-webkit-border-radius: 5px', '-moz-border-radius: 5px', 'color: #e00', 'padding: 15px', 'margin-bottom: 15px'].join(';');
-
- if (options.env === 'development') {
- timer = setInterval(function () {
- var document = window.document;
- var body = document.body;
-
- if (body) {
- if (document.getElementById(id)) {
- body.replaceChild(elem, document.getElementById(id));
- } else {
- body.insertBefore(elem, body.firstChild);
+ matchCondition: function (args, context) {
+ if (this.condition && !this.condition.eval(new contexts.Eval(context, [this.evalParams(context, /* the parameter variables */ new contexts.Eval(context, this.frames ? this.frames.concat(context.frames) : context.frames), args, [])]
+ .concat(this.frames || []) // the parent namespace/mixin frames
+ .concat(context.frames)))) { // the current environment frames
+ return false;
}
-
- clearInterval(timer);
- }
- }, 10);
- }
- }
-
- function removeErrorHTML(path) {
- var node = window.document.getElementById("less-error-message:".concat(extractId(path)));
-
- if (node) {
- node.parentNode.removeChild(node);
- }
- }
-
- function removeError(path) {
- if (!options.errorReporting || options.errorReporting === 'html') {
- removeErrorHTML(path);
- } else if (options.errorReporting === 'console') ; else if (typeof options.errorReporting === 'function') {
- options.errorReporting('remove', path);
- }
- }
-
- function errorConsole(e, rootHref) {
- var template = '{line} {content}';
- var filename = e.filename || rootHref;
- var errors = [];
- var content = "".concat(e.type || 'Syntax', "Error: ").concat(e.message || 'There is an error in your .less file', " in ").concat(filename);
-
- var errorline = function errorline(e, i, classname) {
- if (e.extract[i] !== undefined) {
- errors.push(template.replace(/\{line\}/, (parseInt(e.line, 10) || 0) + (i - 1)).replace(/\{class\}/, classname).replace(/\{content\}/, e.extract[i]));
- }
- };
-
- if (e.line) {
- errorline(e, 0, '');
- errorline(e, 1, 'line');
- errorline(e, 2, '');
- content += " on line ".concat(e.line, ", column ").concat(e.column + 1, ":\n").concat(errors.join('\n'));
- }
-
- if (e.stack && (e.extract || options.logLevel >= 4)) {
- content += "\nStack Trace\n".concat(e.stack);
- }
-
- less.logger.error(content);
- }
-
- function error(e, rootHref) {
- if (!options.errorReporting || options.errorReporting === 'html') {
- errorHTML(e, rootHref);
- } else if (options.errorReporting === 'console') {
- errorConsole(e, rootHref);
- } else if (typeof options.errorReporting === 'function') {
- options.errorReporting('add', e, rootHref);
- }
- }
-
- return {
- add: error,
- remove: removeError
- };
- });
-
- // Cache system is a bit outdated and could do with work
- var Cache = (function (window, options, logger) {
- var cache = null;
-
- if (options.env !== 'development') {
- try {
- cache = typeof window.localStorage === 'undefined' ? null : window.localStorage;
- } catch (_) {}
- }
-
- return {
- setCSS: function setCSS(path, lastModified, modifyVars, styles) {
- if (cache) {
- logger.info("saving ".concat(path, " to cache."));
-
- try {
- cache.setItem(path, styles);
- cache.setItem("".concat(path, ":timestamp"), lastModified);
-
- if (modifyVars) {
- cache.setItem("".concat(path, ":vars"), JSON.stringify(modifyVars));
+ return true;
+ },
+ matchArgs: function (args, context) {
+ var allArgsCnt = (args && args.length) || 0;
+ var len;
+ var optionalParameters = this.optionalParameters;
+ var requiredArgsCnt = !args ? 0 : args.reduce(function (count, p) {
+ if (optionalParameters.indexOf(p.name) < 0) {
+ return count + 1;
+ }
+ else {
+ return count;
+ }
+ }, 0);
+ if (!this.variadic) {
+ if (requiredArgsCnt < this.required) {
+ return false;
+ }
+ if (allArgsCnt > this.params.length) {
+ return false;
+ }
}
- } catch (e) {
- // TODO - could do with adding more robust error handling
- logger.error("failed to save \"".concat(path, "\" to local storage for caching."));
- }
- }
- },
- getCSS: function getCSS(path, webInfo, modifyVars) {
- var css = cache && cache.getItem(path);
- var timestamp = cache && cache.getItem("".concat(path, ":timestamp"));
- var vars = cache && cache.getItem("".concat(path, ":vars"));
- modifyVars = modifyVars || {};
- vars = vars || "{}"; // if not set, treat as the JSON representation of an empty object
-
- if (timestamp && webInfo.lastModified && new Date(webInfo.lastModified).valueOf() === new Date(timestamp).valueOf() && JSON.stringify(modifyVars) === vars) {
- // Use local copy
- return css;
- }
- }
- };
- });
-
- var ImageSize = (function () {
- function _imageSize() {
- throw {
- type: 'Runtime',
- message: 'Image size functions are not supported in browser version of less'
- };
- }
-
- var imageFunctions = {
- 'image-size': function imageSize(filePathNode) {
- _imageSize();
-
- return -1;
- },
- 'image-width': function imageWidth(filePathNode) {
- _imageSize();
-
- return -1;
- },
- 'image-height': function imageHeight(filePathNode) {
- _imageSize();
-
- return -1;
- }
- };
- functionRegistry.addMultiple(imageFunctions);
- });
-
- //
- var root = (function (window, options) {
- var document = window.document;
- var less = lessRoot();
- less.options = options;
- var environment = less.environment;
- var FileManager = FM(options, less.logger);
- var fileManager = new FileManager();
- environment.addFileManager(fileManager);
- less.FileManager = FileManager;
- less.PluginLoader = PluginLoader;
- LogListener(less, options);
- var errors = ErrorReporting(window, less, options);
- var cache = less.cache = options.cache || Cache(window, options, less.logger);
- ImageSize(less.environment); // Setup user functions - Deprecate?
-
- if (options.functions) {
- less.functions.functionRegistry.addMultiple(options.functions);
- }
-
- var typePattern = /^text\/(x-)?less$/;
-
- function clone(obj) {
- var cloned = {};
-
- for (var prop in obj) {
- if (obj.hasOwnProperty(prop)) {
- cloned[prop] = obj[prop];
- }
- }
-
- return cloned;
- } // only really needed for phantom
-
-
- function bind(func, thisArg) {
- var curryArgs = Array.prototype.slice.call(arguments, 2);
- return function () {
- var args = curryArgs.concat(Array.prototype.slice.call(arguments, 0));
- return func.apply(thisArg, args);
- };
- }
-
- function loadStyles(modifyVars) {
- var styles = document.getElementsByTagName('style');
- var style;
-
- for (var i = 0; i < styles.length; i++) {
- style = styles[i];
-
- if (style.type.match(typePattern)) {
- var instanceOptions = clone(options);
- instanceOptions.modifyVars = modifyVars;
- var lessText = style.innerHTML || '';
- instanceOptions.filename = document.location.href.replace(/#.*$/, '');
- /* jshint loopfunc:true */
- // use closure to store current style
-
- less.render(lessText, instanceOptions, bind(function (style, e, result) {
- if (e) {
- errors.add(e, 'inline');
- } else {
- style.type = 'text/css';
-
- if (style.styleSheet) {
- style.styleSheet.cssText = result.css;
- } else {
- style.innerHTML = result.css;
- }
+ else {
+ if (requiredArgsCnt < (this.required - 1)) {
+ return false;
+ }
}
- }, null, style));
+ // check patterns
+ len = Math.min(requiredArgsCnt, this.arity);
+ for (var i = 0; i < len; i++) {
+ if (!this.params[i].name && !this.params[i].variadic) {
+ if (args[i].value.eval(context).toCSS() != this.params[i].value.eval(context).toCSS()) {
+ return false;
+ }
+ }
+ }
+ return true;
}
- }
- }
+ });
- function loadStyleSheet(sheet, callback, reload, remaining, modifyVars) {
- var instanceOptions = clone(options);
- addDataAttr(instanceOptions, sheet);
- instanceOptions.mime = sheet.type;
+ var MixinCall = function (elements, args, index, currentFileInfo, important) {
+ this.selector = new Selector(elements);
+ this.arguments = args || [];
+ this._index = index;
+ this._fileInfo = currentFileInfo;
+ this.important = important;
+ this.allowRoot = true;
+ this.setParent(this.selector, this);
+ };
+ MixinCall.prototype = Object.assign(new Node(), {
+ type: 'MixinCall',
+ accept: function (visitor) {
+ if (this.selector) {
+ this.selector = visitor.visit(this.selector);
+ }
+ if (this.arguments.length) {
+ this.arguments = visitor.visitArray(this.arguments);
+ }
+ },
+ eval: function (context) {
+ var mixins;
+ var mixin;
+ var mixinPath;
+ var args = [];
+ var arg;
+ var argValue;
+ var rules = [];
+ var match = false;
+ var i;
+ var m;
+ var f;
+ var isRecursive;
+ var isOneFound;
+ var candidates = [];
+ var candidate;
+ var conditionResult = [];
+ var defaultResult;
+ var defFalseEitherCase = -1;
+ var defNone = 0;
+ var defTrue = 1;
+ var defFalse = 2;
+ var count;
+ var originalRuleset;
+ var noArgumentsFilter;
+ this.selector = this.selector.eval(context);
+ function calcDefGroup(mixin, mixinPath) {
+ var f, p, namespace;
+ for (f = 0; f < 2; f++) {
+ conditionResult[f] = true;
+ defaultFunc.value(f);
+ for (p = 0; p < mixinPath.length && conditionResult[f]; p++) {
+ namespace = mixinPath[p];
+ if (namespace.matchCondition) {
+ conditionResult[f] = conditionResult[f] && namespace.matchCondition(null, context);
+ }
+ }
+ if (mixin.matchCondition) {
+ conditionResult[f] = conditionResult[f] && mixin.matchCondition(args, context);
+ }
+ }
+ if (conditionResult[0] || conditionResult[1]) {
+ if (conditionResult[0] != conditionResult[1]) {
+ return conditionResult[1] ?
+ defTrue : defFalse;
+ }
+ return defNone;
+ }
+ return defFalseEitherCase;
+ }
+ for (i = 0; i < this.arguments.length; i++) {
+ arg = this.arguments[i];
+ argValue = arg.value.eval(context);
+ if (arg.expand && Array.isArray(argValue.value)) {
+ argValue = argValue.value;
+ for (m = 0; m < argValue.length; m++) {
+ args.push({ value: argValue[m] });
+ }
+ }
+ else {
+ args.push({ name: arg.name, value: argValue });
+ }
+ }
+ noArgumentsFilter = function (rule) { return rule.matchArgs(null, context); };
+ for (i = 0; i < context.frames.length; i++) {
+ if ((mixins = context.frames[i].find(this.selector, null, noArgumentsFilter)).length > 0) {
+ isOneFound = true;
+ // To make `default()` function independent of definition order we have two "subpasses" here.
+ // At first we evaluate each guard *twice* (with `default() == true` and `default() == false`),
+ // and build candidate list with corresponding flags. Then, when we know all possible matches,
+ // we make a final decision.
+ for (m = 0; m < mixins.length; m++) {
+ mixin = mixins[m].rule;
+ mixinPath = mixins[m].path;
+ isRecursive = false;
+ for (f = 0; f < context.frames.length; f++) {
+ if ((!(mixin instanceof Definition)) && mixin === (context.frames[f].originalRuleset || context.frames[f])) {
+ isRecursive = true;
+ break;
+ }
+ }
+ if (isRecursive) {
+ continue;
+ }
+ if (mixin.matchArgs(args, context)) {
+ candidate = { mixin: mixin, group: calcDefGroup(mixin, mixinPath) };
+ if (candidate.group !== defFalseEitherCase) {
+ candidates.push(candidate);
+ }
+ match = true;
+ }
+ }
+ defaultFunc.reset();
+ count = [0, 0, 0];
+ for (m = 0; m < candidates.length; m++) {
+ count[candidates[m].group]++;
+ }
+ if (count[defNone] > 0) {
+ defaultResult = defFalse;
+ }
+ else {
+ defaultResult = defTrue;
+ if ((count[defTrue] + count[defFalse]) > 1) {
+ throw { type: 'Runtime',
+ message: "Ambiguous use of `default()` found when matching for `" + this.format(args) + "`",
+ index: this.getIndex(), filename: this.fileInfo().filename };
+ }
+ }
+ for (m = 0; m < candidates.length; m++) {
+ candidate = candidates[m].group;
+ if ((candidate === defNone) || (candidate === defaultResult)) {
+ try {
+ mixin = candidates[m].mixin;
+ if (!(mixin instanceof Definition)) {
+ originalRuleset = mixin.originalRuleset || mixin;
+ mixin = new Definition('', [], mixin.rules, null, false, null, originalRuleset.visibilityInfo());
+ mixin.originalRuleset = originalRuleset;
+ }
+ var newRules = mixin.evalCall(context, args, this.important).rules;
+ this._setVisibilityToReplacement(newRules);
+ Array.prototype.push.apply(rules, newRules);
+ }
+ catch (e) {
+ throw { message: e.message, index: this.getIndex(), filename: this.fileInfo().filename, stack: e.stack };
+ }
+ }
+ }
+ if (match) {
+ return rules;
+ }
+ }
+ }
+ if (isOneFound) {
+ throw { type: 'Runtime',
+ message: "No matching definition was found for `" + this.format(args) + "`",
+ index: this.getIndex(), filename: this.fileInfo().filename };
+ }
+ else {
+ throw { type: 'Name',
+ message: this.selector.toCSS().trim() + " is undefined",
+ index: this.getIndex(), filename: this.fileInfo().filename };
+ }
+ },
+ _setVisibilityToReplacement: function (replacement) {
+ var i, rule;
+ if (this.blocksVisibility()) {
+ for (i = 0; i < replacement.length; i++) {
+ rule = replacement[i];
+ rule.addVisibilityBlock();
+ }
+ }
+ },
+ format: function (args) {
+ return this.selector.toCSS().trim() + "(" + (args ? args.map(function (a) {
+ var argValue = '';
+ if (a.name) {
+ argValue += a.name + ":";
+ }
+ if (a.value.toCSS) {
+ argValue += a.value.toCSS();
+ }
+ else {
+ argValue += '???';
+ }
+ return argValue;
+ }).join(', ') : '') + ")";
+ }
+ });
- if (modifyVars) {
- instanceOptions.modifyVars = modifyVars;
- }
+ var tree = {
+ Node: Node,
+ Color: Color,
+ AtRule: AtRule,
+ DetachedRuleset: DetachedRuleset,
+ Operation: Operation,
+ Dimension: Dimension,
+ Unit: Unit,
+ Keyword: Keyword,
+ Variable: Variable,
+ Property: Property,
+ Ruleset: Ruleset,
+ Element: Element,
+ Attribute: Attribute,
+ Combinator: Combinator,
+ Selector: Selector,
+ Quoted: Quoted,
+ Expression: Expression,
+ Declaration: Declaration,
+ Call: Call,
+ URL: URL,
+ Import: Import,
+ Comment: Comment,
+ Anonymous: Anonymous,
+ Value: Value,
+ JavaScript: JavaScript,
+ Assignment: Assignment,
+ Condition: Condition,
+ Paren: Paren,
+ Media: Media,
+ UnicodeDescriptor: UnicodeDescriptor,
+ Negative: Negative,
+ Extend: Extend,
+ VariableCall: VariableCall,
+ NamespaceValue: NamespaceValue,
+ mixin: {
+ Call: MixinCall,
+ Definition: Definition
+ }
+ };
- function loadInitialFileCallback(loadedFile) {
- var data = loadedFile.contents;
- var path = loadedFile.filename;
- var webInfo = loadedFile.webInfo;
- var newFileInfo = {
- currentDirectory: fileManager.getPath(path),
- filename: path,
- rootFilename: path,
- rewriteUrls: instanceOptions.rewriteUrls
+ var AbstractFileManager = /** @class */ (function () {
+ function AbstractFileManager() {
+ }
+ AbstractFileManager.prototype.getPath = function (filename) {
+ var j = filename.lastIndexOf('?');
+ if (j > 0) {
+ filename = filename.slice(0, j);
+ }
+ j = filename.lastIndexOf('/');
+ if (j < 0) {
+ j = filename.lastIndexOf('\\');
+ }
+ if (j < 0) {
+ return '';
+ }
+ return filename.slice(0, j + 1);
};
- newFileInfo.entryPath = newFileInfo.currentDirectory;
- newFileInfo.rootpath = instanceOptions.rootpath || newFileInfo.currentDirectory;
+ AbstractFileManager.prototype.tryAppendExtension = function (path, ext) {
+ return /(\.[a-z]*$)|([\?;].*)$/.test(path) ? path : path + ext;
+ };
+ AbstractFileManager.prototype.tryAppendLessExtension = function (path) {
+ return this.tryAppendExtension(path, '.less');
+ };
+ AbstractFileManager.prototype.supportsSync = function () {
+ return false;
+ };
+ AbstractFileManager.prototype.alwaysMakePathsAbsolute = function () {
+ return false;
+ };
+ AbstractFileManager.prototype.isPathAbsolute = function (filename) {
+ return (/^(?:[a-z-]+:|\/|\\|#)/i).test(filename);
+ };
+ // TODO: pull out / replace?
+ AbstractFileManager.prototype.join = function (basePath, laterPath) {
+ if (!basePath) {
+ return laterPath;
+ }
+ return basePath + laterPath;
+ };
+ AbstractFileManager.prototype.pathDiff = function (url, baseUrl) {
+ // diff between two paths to create a relative path
+ var urlParts = this.extractUrlParts(url);
+ var baseUrlParts = this.extractUrlParts(baseUrl);
+ var i;
+ var max;
+ var urlDirectories;
+ var baseUrlDirectories;
+ var diff = '';
+ if (urlParts.hostPart !== baseUrlParts.hostPart) {
+ return '';
+ }
+ max = Math.max(baseUrlParts.directories.length, urlParts.directories.length);
+ for (i = 0; i < max; i++) {
+ if (baseUrlParts.directories[i] !== urlParts.directories[i]) {
+ break;
+ }
+ }
+ baseUrlDirectories = baseUrlParts.directories.slice(i);
+ urlDirectories = urlParts.directories.slice(i);
+ for (i = 0; i < baseUrlDirectories.length - 1; i++) {
+ diff += '../';
+ }
+ for (i = 0; i < urlDirectories.length - 1; i++) {
+ diff += urlDirectories[i] + "/";
+ }
+ return diff;
+ };
+ // helper function, not part of API
+ AbstractFileManager.prototype.extractUrlParts = function (url, baseUrl) {
+ // urlParts[1] = protocol://hostname/ OR /
+ // urlParts[2] = / if path relative to host base
+ // urlParts[3] = directories
+ // urlParts[4] = filename
+ // urlParts[5] = parameters
+ var urlPartsRegex = /^((?:[a-z-]+:)?\/{2}(?:[^\/\?#]*\/)|([\/\\]))?((?:[^\/\\\?#]*[\/\\])*)([^\/\\\?#]*)([#\?].*)?$/i;
+ var urlParts = url.match(urlPartsRegex);
+ var returner = {};
+ var rawDirectories = [];
+ var directories = [];
+ var i;
+ var baseUrlParts;
+ if (!urlParts) {
+ throw new Error("Could not parse sheet href - '" + url + "'");
+ }
+ // Stylesheets in IE don't always return the full path
+ if (baseUrl && (!urlParts[1] || urlParts[2])) {
+ baseUrlParts = baseUrl.match(urlPartsRegex);
+ if (!baseUrlParts) {
+ throw new Error("Could not parse page url - '" + baseUrl + "'");
+ }
+ urlParts[1] = urlParts[1] || baseUrlParts[1] || '';
+ if (!urlParts[2]) {
+ urlParts[3] = baseUrlParts[3] + urlParts[3];
+ }
+ }
+ if (urlParts[3]) {
+ rawDirectories = urlParts[3].replace(/\\/g, '/').split('/');
+ // collapse '..' and skip '.'
+ for (i = 0; i < rawDirectories.length; i++) {
+ if (rawDirectories[i] === '..') {
+ directories.pop();
+ }
+ else if (rawDirectories[i] !== '.') {
+ directories.push(rawDirectories[i]);
+ }
+ }
+ }
+ returner.hostPart = urlParts[1];
+ returner.directories = directories;
+ returner.rawPath = (urlParts[1] || '') + rawDirectories.join('/');
+ returner.path = (urlParts[1] || '') + directories.join('/');
+ returner.filename = urlParts[4];
+ returner.fileUrl = returner.path + (urlParts[4] || '');
+ returner.url = returner.fileUrl + (urlParts[5] || '');
+ return returner;
+ };
+ return AbstractFileManager;
+ }());
- if (webInfo) {
- webInfo.remaining = remaining;
- var css = cache.getCSS(path, webInfo, instanceOptions.modifyVars);
-
- if (!reload && css) {
- webInfo.local = true;
- callback(null, css, data, sheet, webInfo, path);
- return;
- }
- } // TODO add tests around how this behaves when reloading
-
-
- errors.remove(path);
- instanceOptions.rootFileInfo = newFileInfo;
- less.render(data, instanceOptions, function (e, result) {
- if (e) {
- e.href = path;
- callback(e);
- } else {
- cache.setCSS(sheet.href, webInfo.lastModified, instanceOptions.modifyVars, result.css);
- callback(null, result.css, data, sheet, webInfo, path);
- }
- });
- }
-
- fileManager.loadFile(sheet.href, null, instanceOptions, environment).then(function (loadedFile) {
- loadInitialFileCallback(loadedFile);
- }).catch(function (err) {
- console.log(err);
- callback(err);
- });
- }
-
- function loadStyleSheets(callback, reload, modifyVars) {
- for (var i = 0; i < less.sheets.length; i++) {
- loadStyleSheet(less.sheets[i], callback, reload, less.sheets.length - (i + 1), modifyVars);
- }
- }
-
- function initRunningMode() {
- if (less.env === 'development') {
- less.watchTimer = setInterval(function () {
- if (less.watchMode) {
- fileManager.clearFileCache();
- loadStyleSheets(function (e, css, _, sheet, webInfo) {
- if (e) {
- errors.add(e, e.href || sheet.href);
- } else if (css) {
- browser.createCSS(window.document, css, sheet);
- }
- });
- }
- }, options.poll);
- }
- } //
- // Watch mode
- //
-
-
- less.watch = function () {
- if (!less.watchMode) {
- less.env = 'development';
- initRunningMode();
- }
-
- this.watchMode = true;
- return true;
- };
-
- less.unwatch = function () {
- clearInterval(less.watchTimer);
- this.watchMode = false;
- return false;
- }; //
- // Synchronously get all tags with the 'rel' attribute set to
- // "stylesheet/less".
- //
-
-
- less.registerStylesheetsImmediately = function () {
- var links = document.getElementsByTagName('link');
- less.sheets = [];
-
- for (var i = 0; i < links.length; i++) {
- if (links[i].rel === 'stylesheet/less' || links[i].rel.match(/stylesheet/) && links[i].type.match(typePattern)) {
- less.sheets.push(links[i]);
+ var AbstractPluginLoader = /** @class */ (function () {
+ function AbstractPluginLoader() {
+ // Implemented by Node.js plugin loader
+ this.require = function () {
+ return null;
+ };
}
- }
- }; //
- // Asynchronously get all tags with the 'rel' attribute set to
- // "stylesheet/less", returning a Promise.
- //
+ AbstractPluginLoader.prototype.evalPlugin = function (contents, context, imports, pluginOptions, fileInfo) {
+ var loader, registry, pluginObj, localModule, pluginManager, filename, result;
+ pluginManager = context.pluginManager;
+ if (fileInfo) {
+ if (typeof fileInfo === 'string') {
+ filename = fileInfo;
+ }
+ else {
+ filename = fileInfo.filename;
+ }
+ }
+ var shortname = (new this.less.FileManager()).extractUrlParts(filename).filename;
+ if (filename) {
+ pluginObj = pluginManager.get(filename);
+ if (pluginObj) {
+ result = this.trySetOptions(pluginObj, filename, shortname, pluginOptions);
+ if (result) {
+ return result;
+ }
+ try {
+ if (pluginObj.use) {
+ pluginObj.use.call(this.context, pluginObj);
+ }
+ }
+ catch (e) {
+ e.message = e.message || 'Error during @plugin call';
+ return new LessError(e, imports, filename);
+ }
+ return pluginObj;
+ }
+ }
+ localModule = {
+ exports: {},
+ pluginManager: pluginManager,
+ fileInfo: fileInfo
+ };
+ registry = functionRegistry.create();
+ var registerPlugin = function (obj) {
+ pluginObj = obj;
+ };
+ try {
+ loader = new Function('module', 'require', 'registerPlugin', 'functions', 'tree', 'less', 'fileInfo', contents);
+ loader(localModule, this.require(filename), registerPlugin, registry, this.less.tree, this.less, fileInfo);
+ }
+ catch (e) {
+ return new LessError(e, imports, filename);
+ }
+ if (!pluginObj) {
+ pluginObj = localModule.exports;
+ }
+ pluginObj = this.validatePlugin(pluginObj, filename, shortname);
+ if (pluginObj instanceof LessError) {
+ return pluginObj;
+ }
+ if (pluginObj) {
+ pluginObj.imports = imports;
+ pluginObj.filename = filename;
+ // For < 3.x (or unspecified minVersion) - setOptions() before install()
+ if (!pluginObj.minVersion || this.compareVersion('3.0.0', pluginObj.minVersion) < 0) {
+ result = this.trySetOptions(pluginObj, filename, shortname, pluginOptions);
+ if (result) {
+ return result;
+ }
+ }
+ // Run on first load
+ pluginManager.addPlugin(pluginObj, fileInfo.filename, registry);
+ pluginObj.functions = registry.getLocalFunctions();
+ // Need to call setOptions again because the pluginObj might have functions
+ result = this.trySetOptions(pluginObj, filename, shortname, pluginOptions);
+ if (result) {
+ return result;
+ }
+ // Run every @plugin call
+ try {
+ if (pluginObj.use) {
+ pluginObj.use.call(this.context, pluginObj);
+ }
+ }
+ catch (e) {
+ e.message = e.message || 'Error during @plugin call';
+ return new LessError(e, imports, filename);
+ }
+ }
+ else {
+ return new LessError({ message: 'Not a valid plugin' }, imports, filename);
+ }
+ return pluginObj;
+ };
+ AbstractPluginLoader.prototype.trySetOptions = function (plugin, filename, name, options) {
+ if (options && !plugin.setOptions) {
+ return new LessError({
+ message: "Options have been provided but the plugin " + name + " does not support any options."
+ });
+ }
+ try {
+ plugin.setOptions && plugin.setOptions(options);
+ }
+ catch (e) {
+ return new LessError(e);
+ }
+ };
+ AbstractPluginLoader.prototype.validatePlugin = function (plugin, filename, name) {
+ if (plugin) {
+ // support plugins being a function
+ // so that the plugin can be more usable programmatically
+ if (typeof plugin === 'function') {
+ plugin = new plugin();
+ }
+ if (plugin.minVersion) {
+ if (this.compareVersion(plugin.minVersion, this.less.version) < 0) {
+ return new LessError({
+ message: "Plugin " + name + " requires version " + this.versionToString(plugin.minVersion)
+ });
+ }
+ }
+ return plugin;
+ }
+ return null;
+ };
+ AbstractPluginLoader.prototype.compareVersion = function (aVersion, bVersion) {
+ if (typeof aVersion === 'string') {
+ aVersion = aVersion.match(/^(\d+)\.?(\d+)?\.?(\d+)?/);
+ aVersion.shift();
+ }
+ for (var i = 0; i < aVersion.length; i++) {
+ if (aVersion[i] !== bVersion[i]) {
+ return parseInt(aVersion[i]) > parseInt(bVersion[i]) ? -1 : 1;
+ }
+ }
+ return 0;
+ };
+ AbstractPluginLoader.prototype.versionToString = function (version) {
+ var versionString = '';
+ for (var i = 0; i < version.length; i++) {
+ versionString += (versionString ? '.' : '') + version[i];
+ }
+ return versionString;
+ };
+ AbstractPluginLoader.prototype.printUsage = function (plugins) {
+ for (var i = 0; i < plugins.length; i++) {
+ var plugin = plugins[i];
+ if (plugin.printUsage) {
+ plugin.printUsage();
+ }
+ }
+ };
+ return AbstractPluginLoader;
+ }());
+ var _visitArgs = { visitDeeper: true };
+ var _hasIndexed = false;
+ function _noop(node) {
+ return node;
+ }
+ function indexNodeTypes(parent, ticker) {
+ // add .typeIndex to tree node types for lookup table
+ var key, child;
+ for (key in parent) {
+ /* eslint guard-for-in: 0 */
+ child = parent[key];
+ switch (typeof child) {
+ case 'function':
+ // ignore bound functions directly on tree which do not have a prototype
+ // or aren't nodes
+ if (child.prototype && child.prototype.type) {
+ child.prototype.typeIndex = ticker++;
+ }
+ break;
+ case 'object':
+ ticker = indexNodeTypes(child, ticker);
+ break;
+ }
+ }
+ return ticker;
+ }
+ var Visitor = /** @class */ (function () {
+ function Visitor(implementation) {
+ this._implementation = implementation;
+ this._visitInCache = {};
+ this._visitOutCache = {};
+ if (!_hasIndexed) {
+ indexNodeTypes(tree, 1);
+ _hasIndexed = true;
+ }
+ }
+ Visitor.prototype.visit = function (node) {
+ if (!node) {
+ return node;
+ }
+ var nodeTypeIndex = node.typeIndex;
+ if (!nodeTypeIndex) {
+ // MixinCall args aren't a node type?
+ if (node.value && node.value.typeIndex) {
+ this.visit(node.value);
+ }
+ return node;
+ }
+ var impl = this._implementation;
+ var func = this._visitInCache[nodeTypeIndex];
+ var funcOut = this._visitOutCache[nodeTypeIndex];
+ var visitArgs = _visitArgs;
+ var fnName;
+ visitArgs.visitDeeper = true;
+ if (!func) {
+ fnName = "visit" + node.type;
+ func = impl[fnName] || _noop;
+ funcOut = impl[fnName + "Out"] || _noop;
+ this._visitInCache[nodeTypeIndex] = func;
+ this._visitOutCache[nodeTypeIndex] = funcOut;
+ }
+ if (func !== _noop) {
+ var newNode = func.call(impl, node, visitArgs);
+ if (node && impl.isReplacing) {
+ node = newNode;
+ }
+ }
+ if (visitArgs.visitDeeper && node) {
+ if (node.length) {
+ for (var i = 0, cnt = node.length; i < cnt; i++) {
+ if (node[i].accept) {
+ node[i].accept(this);
+ }
+ }
+ }
+ else if (node.accept) {
+ node.accept(this);
+ }
+ }
+ if (funcOut != _noop) {
+ funcOut.call(impl, node);
+ }
+ return node;
+ };
+ Visitor.prototype.visitArray = function (nodes, nonReplacing) {
+ if (!nodes) {
+ return nodes;
+ }
+ var cnt = nodes.length;
+ var i;
+ // Non-replacing
+ if (nonReplacing || !this._implementation.isReplacing) {
+ for (i = 0; i < cnt; i++) {
+ this.visit(nodes[i]);
+ }
+ return nodes;
+ }
+ // Replacing
+ var out = [];
+ for (i = 0; i < cnt; i++) {
+ var evald = this.visit(nodes[i]);
+ if (evald === undefined) {
+ continue;
+ }
+ if (!evald.splice) {
+ out.push(evald);
+ }
+ else if (evald.length) {
+ this.flatten(evald, out);
+ }
+ }
+ return out;
+ };
+ Visitor.prototype.flatten = function (arr, out) {
+ if (!out) {
+ out = [];
+ }
+ var cnt, i, item, nestedCnt, j, nestedItem;
+ for (i = 0, cnt = arr.length; i < cnt; i++) {
+ item = arr[i];
+ if (item === undefined) {
+ continue;
+ }
+ if (!item.splice) {
+ out.push(item);
+ continue;
+ }
+ for (j = 0, nestedCnt = item.length; j < nestedCnt; j++) {
+ nestedItem = item[j];
+ if (nestedItem === undefined) {
+ continue;
+ }
+ if (!nestedItem.splice) {
+ out.push(nestedItem);
+ }
+ else if (nestedItem.length) {
+ this.flatten(nestedItem, out);
+ }
+ }
+ }
+ return out;
+ };
+ return Visitor;
+ }());
- less.registerStylesheets = function () {
- return new Promise(function (resolve, reject) {
- less.registerStylesheetsImmediately();
- resolve();
- });
- }; //
- // With this function, it's possible to alter variables and re-render
- // CSS without reloading less-files
- //
+ var ImportSequencer = /** @class */ (function () {
+ function ImportSequencer(onSequencerEmpty) {
+ this.imports = [];
+ this.variableImports = [];
+ this._onSequencerEmpty = onSequencerEmpty;
+ this._currentDepth = 0;
+ }
+ ImportSequencer.prototype.addImport = function (callback) {
+ var importSequencer = this, importItem = {
+ callback: callback,
+ args: null,
+ isReady: false
+ };
+ this.imports.push(importItem);
+ return function () {
+ importItem.args = Array.prototype.slice.call(arguments, 0);
+ importItem.isReady = true;
+ importSequencer.tryRun();
+ };
+ };
+ ImportSequencer.prototype.addVariableImport = function (callback) {
+ this.variableImports.push(callback);
+ };
+ ImportSequencer.prototype.tryRun = function () {
+ this._currentDepth++;
+ try {
+ while (true) {
+ while (this.imports.length > 0) {
+ var importItem = this.imports[0];
+ if (!importItem.isReady) {
+ return;
+ }
+ this.imports = this.imports.slice(1);
+ importItem.callback.apply(null, importItem.args);
+ }
+ if (this.variableImports.length === 0) {
+ break;
+ }
+ var variableImport = this.variableImports[0];
+ this.variableImports = this.variableImports.slice(1);
+ variableImport();
+ }
+ }
+ finally {
+ this._currentDepth--;
+ }
+ if (this._currentDepth === 0 && this._onSequencerEmpty) {
+ this._onSequencerEmpty();
+ }
+ };
+ return ImportSequencer;
+ }());
-
- less.modifyVars = function (record) {
- return less.refresh(true, record, false);
+ var ImportVisitor = function (importer, finish) {
+ this._visitor = new Visitor(this);
+ this._importer = importer;
+ this._finish = finish;
+ this.context = new contexts.Eval();
+ this.importCount = 0;
+ this.onceFileDetectionMap = {};
+ this.recursionDetector = {};
+ this._sequencer = new ImportSequencer(this._onSequencerEmpty.bind(this));
};
-
- less.refresh = function (reload, modifyVars, clearFileCache) {
- if ((reload || clearFileCache) && clearFileCache !== false) {
- fileManager.clearFileCache();
- }
-
- return new Promise(function (resolve, reject) {
- var startTime;
- var endTime;
- var totalMilliseconds;
- var remainingSheets;
- startTime = endTime = new Date(); // Set counter for remaining unprocessed sheets
-
- remainingSheets = less.sheets.length;
-
- if (remainingSheets === 0) {
- endTime = new Date();
- totalMilliseconds = endTime - startTime;
- less.logger.info('Less has finished and no sheets were loaded.');
- resolve({
- startTime: startTime,
- endTime: endTime,
- totalMilliseconds: totalMilliseconds,
- sheets: less.sheets.length
- });
- } else {
- // Relies on less.sheets array, callback seems to be guaranteed to be called for every element of the array
- loadStyleSheets(function (e, css, _, sheet, webInfo) {
+ ImportVisitor.prototype = {
+ isReplacing: false,
+ run: function (root) {
+ try {
+ // process the contents
+ this._visitor.visit(root);
+ }
+ catch (e) {
+ this.error = e;
+ }
+ this.isFinished = true;
+ this._sequencer.tryRun();
+ },
+ _onSequencerEmpty: function () {
+ if (!this.isFinished) {
+ return;
+ }
+ this._finish(this.error);
+ },
+ visitImport: function (importNode, visitArgs) {
+ var inlineCSS = importNode.options.inline;
+ if (!importNode.css || inlineCSS) {
+ var context = new contexts.Eval(this.context, copyArray(this.context.frames));
+ var importParent = context.frames[0];
+ this.importCount++;
+ if (importNode.isVariableImport()) {
+ this._sequencer.addVariableImport(this.processImportNode.bind(this, importNode, context, importParent));
+ }
+ else {
+ this.processImportNode(importNode, context, importParent);
+ }
+ }
+ visitArgs.visitDeeper = false;
+ },
+ processImportNode: function (importNode, context, importParent) {
+ var evaldImportNode;
+ var inlineCSS = importNode.options.inline;
+ try {
+ evaldImportNode = importNode.evalForImport(context);
+ }
+ catch (e) {
+ if (!e.filename) {
+ e.index = importNode.getIndex();
+ e.filename = importNode.fileInfo().filename;
+ }
+ // attempt to eval properly and treat as css
+ importNode.css = true;
+ // if that fails, this error will be thrown
+ importNode.error = e;
+ }
+ if (evaldImportNode && (!evaldImportNode.css || inlineCSS)) {
+ if (evaldImportNode.options.multiple) {
+ context.importMultiple = true;
+ }
+ // try appending if we haven't determined if it is css or not
+ var tryAppendLessExtension = evaldImportNode.css === undefined;
+ for (var i = 0; i < importParent.rules.length; i++) {
+ if (importParent.rules[i] === importNode) {
+ importParent.rules[i] = evaldImportNode;
+ break;
+ }
+ }
+ var onImported = this.onImported.bind(this, evaldImportNode, context), sequencedOnImported = this._sequencer.addImport(onImported);
+ this._importer.push(evaldImportNode.getPath(), tryAppendLessExtension, evaldImportNode.fileInfo(), evaldImportNode.options, sequencedOnImported);
+ }
+ else {
+ this.importCount--;
+ if (this.isFinished) {
+ this._sequencer.tryRun();
+ }
+ }
+ },
+ onImported: function (importNode, context, e, root, importedAtRoot, fullPath) {
if (e) {
- errors.add(e, e.href || sheet.href);
- reject(e);
- return;
+ if (!e.filename) {
+ e.index = importNode.getIndex();
+ e.filename = importNode.fileInfo().filename;
+ }
+ this.error = e;
}
-
- if (webInfo.local) {
- less.logger.info("Loading ".concat(sheet.href, " from cache."));
- } else {
- less.logger.info("Rendered ".concat(sheet.href, " successfully."));
+ var importVisitor = this, inlineCSS = importNode.options.inline, isPlugin = importNode.options.isPlugin, isOptional = importNode.options.optional, duplicateImport = importedAtRoot || fullPath in importVisitor.recursionDetector;
+ if (!context.importMultiple) {
+ if (duplicateImport) {
+ importNode.skip = true;
+ }
+ else {
+ importNode.skip = function () {
+ if (fullPath in importVisitor.onceFileDetectionMap) {
+ return true;
+ }
+ importVisitor.onceFileDetectionMap[fullPath] = true;
+ return false;
+ };
+ }
}
-
- browser.createCSS(window.document, css, sheet);
- less.logger.info("CSS for ".concat(sheet.href, " generated in ").concat(new Date() - endTime, "ms")); // Count completed sheet
-
- remainingSheets--; // Check if the last remaining sheet was processed and then call the promise
-
- if (remainingSheets === 0) {
- totalMilliseconds = new Date() - startTime;
- less.logger.info("Less has finished. CSS generated in ".concat(totalMilliseconds, "ms"));
- resolve({
- startTime: startTime,
- endTime: endTime,
- totalMilliseconds: totalMilliseconds,
- sheets: less.sheets.length
- });
+ if (!fullPath && isOptional) {
+ importNode.skip = true;
}
-
- endTime = new Date();
- }, reload, modifyVars);
+ if (root) {
+ importNode.root = root;
+ importNode.importedFilename = fullPath;
+ if (!inlineCSS && !isPlugin && (context.importMultiple || !duplicateImport)) {
+ importVisitor.recursionDetector[fullPath] = true;
+ var oldContext = this.context;
+ this.context = context;
+ try {
+ this._visitor.visit(root);
+ }
+ catch (e) {
+ this.error = e;
+ }
+ this.context = oldContext;
+ }
+ }
+ importVisitor.importCount--;
+ if (importVisitor.isFinished) {
+ importVisitor._sequencer.tryRun();
+ }
+ },
+ visitDeclaration: function (declNode, visitArgs) {
+ if (declNode.value.type === 'DetachedRuleset') {
+ this.context.frames.unshift(declNode);
+ }
+ else {
+ visitArgs.visitDeeper = false;
+ }
+ },
+ visitDeclarationOut: function (declNode) {
+ if (declNode.value.type === 'DetachedRuleset') {
+ this.context.frames.shift();
+ }
+ },
+ visitAtRule: function (atRuleNode, visitArgs) {
+ this.context.frames.unshift(atRuleNode);
+ },
+ visitAtRuleOut: function (atRuleNode) {
+ this.context.frames.shift();
+ },
+ visitMixinDefinition: function (mixinDefinitionNode, visitArgs) {
+ this.context.frames.unshift(mixinDefinitionNode);
+ },
+ visitMixinDefinitionOut: function (mixinDefinitionNode) {
+ this.context.frames.shift();
+ },
+ visitRuleset: function (rulesetNode, visitArgs) {
+ this.context.frames.unshift(rulesetNode);
+ },
+ visitRulesetOut: function (rulesetNode) {
+ this.context.frames.shift();
+ },
+ visitMedia: function (mediaNode, visitArgs) {
+ this.context.frames.unshift(mediaNode.rules[0]);
+ },
+ visitMediaOut: function (mediaNode) {
+ this.context.frames.shift();
}
-
- loadStyles(modifyVars);
- });
};
- less.refreshStyles = loadStyles;
+ var SetTreeVisibilityVisitor = /** @class */ (function () {
+ function SetTreeVisibilityVisitor(visible) {
+ this.visible = visible;
+ }
+ SetTreeVisibilityVisitor.prototype.run = function (root) {
+ this.visit(root);
+ };
+ SetTreeVisibilityVisitor.prototype.visitArray = function (nodes) {
+ if (!nodes) {
+ return nodes;
+ }
+ var cnt = nodes.length;
+ var i;
+ for (i = 0; i < cnt; i++) {
+ this.visit(nodes[i]);
+ }
+ return nodes;
+ };
+ SetTreeVisibilityVisitor.prototype.visit = function (node) {
+ if (!node) {
+ return node;
+ }
+ if (node.constructor === Array) {
+ return this.visitArray(node);
+ }
+ if (!node.blocksVisibility || node.blocksVisibility()) {
+ return node;
+ }
+ if (this.visible) {
+ node.ensureVisibility();
+ }
+ else {
+ node.ensureInvisibility();
+ }
+ node.accept(this);
+ return node;
+ };
+ return SetTreeVisibilityVisitor;
+ }());
+
+ /* jshint loopfunc:true */
+ var ExtendFinderVisitor = /** @class */ (function () {
+ function ExtendFinderVisitor() {
+ this._visitor = new Visitor(this);
+ this.contexts = [];
+ this.allExtendsStack = [[]];
+ }
+ ExtendFinderVisitor.prototype.run = function (root) {
+ root = this._visitor.visit(root);
+ root.allExtends = this.allExtendsStack[0];
+ return root;
+ };
+ ExtendFinderVisitor.prototype.visitDeclaration = function (declNode, visitArgs) {
+ visitArgs.visitDeeper = false;
+ };
+ ExtendFinderVisitor.prototype.visitMixinDefinition = function (mixinDefinitionNode, visitArgs) {
+ visitArgs.visitDeeper = false;
+ };
+ ExtendFinderVisitor.prototype.visitRuleset = function (rulesetNode, visitArgs) {
+ if (rulesetNode.root) {
+ return;
+ }
+ var i;
+ var j;
+ var extend;
+ var allSelectorsExtendList = [];
+ var extendList;
+ // get &:extend(.a); rules which apply to all selectors in this ruleset
+ var rules = rulesetNode.rules, ruleCnt = rules ? rules.length : 0;
+ for (i = 0; i < ruleCnt; i++) {
+ if (rulesetNode.rules[i] instanceof tree.Extend) {
+ allSelectorsExtendList.push(rules[i]);
+ rulesetNode.extendOnEveryPath = true;
+ }
+ }
+ // now find every selector and apply the extends that apply to all extends
+ // and the ones which apply to an individual extend
+ var paths = rulesetNode.paths;
+ for (i = 0; i < paths.length; i++) {
+ var selectorPath = paths[i], selector = selectorPath[selectorPath.length - 1], selExtendList = selector.extendList;
+ extendList = selExtendList ? copyArray(selExtendList).concat(allSelectorsExtendList)
+ : allSelectorsExtendList;
+ if (extendList) {
+ extendList = extendList.map(function (allSelectorsExtend) {
+ return allSelectorsExtend.clone();
+ });
+ }
+ for (j = 0; j < extendList.length; j++) {
+ this.foundExtends = true;
+ extend = extendList[j];
+ extend.findSelfSelectors(selectorPath);
+ extend.ruleset = rulesetNode;
+ if (j === 0) {
+ extend.firstExtendOnThisSelectorPath = true;
+ }
+ this.allExtendsStack[this.allExtendsStack.length - 1].push(extend);
+ }
+ }
+ this.contexts.push(rulesetNode.selectors);
+ };
+ ExtendFinderVisitor.prototype.visitRulesetOut = function (rulesetNode) {
+ if (!rulesetNode.root) {
+ this.contexts.length = this.contexts.length - 1;
+ }
+ };
+ ExtendFinderVisitor.prototype.visitMedia = function (mediaNode, visitArgs) {
+ mediaNode.allExtends = [];
+ this.allExtendsStack.push(mediaNode.allExtends);
+ };
+ ExtendFinderVisitor.prototype.visitMediaOut = function (mediaNode) {
+ this.allExtendsStack.length = this.allExtendsStack.length - 1;
+ };
+ ExtendFinderVisitor.prototype.visitAtRule = function (atRuleNode, visitArgs) {
+ atRuleNode.allExtends = [];
+ this.allExtendsStack.push(atRuleNode.allExtends);
+ };
+ ExtendFinderVisitor.prototype.visitAtRuleOut = function (atRuleNode) {
+ this.allExtendsStack.length = this.allExtendsStack.length - 1;
+ };
+ return ExtendFinderVisitor;
+ }());
+ var ProcessExtendsVisitor = /** @class */ (function () {
+ function ProcessExtendsVisitor() {
+ this._visitor = new Visitor(this);
+ }
+ ProcessExtendsVisitor.prototype.run = function (root) {
+ var extendFinder = new ExtendFinderVisitor();
+ this.extendIndices = {};
+ extendFinder.run(root);
+ if (!extendFinder.foundExtends) {
+ return root;
+ }
+ root.allExtends = root.allExtends.concat(this.doExtendChaining(root.allExtends, root.allExtends));
+ this.allExtendsStack = [root.allExtends];
+ var newRoot = this._visitor.visit(root);
+ this.checkExtendsForNonMatched(root.allExtends);
+ return newRoot;
+ };
+ ProcessExtendsVisitor.prototype.checkExtendsForNonMatched = function (extendList) {
+ var indices = this.extendIndices;
+ extendList.filter(function (extend) {
+ return !extend.hasFoundMatches && extend.parent_ids.length == 1;
+ }).forEach(function (extend) {
+ var selector = '_unknown_';
+ try {
+ selector = extend.selector.toCSS({});
+ }
+ catch (_) { }
+ if (!indices[extend.index + " " + selector]) {
+ indices[extend.index + " " + selector] = true;
+ logger$1.warn("extend '" + selector + "' has no matches");
+ }
+ });
+ };
+ ProcessExtendsVisitor.prototype.doExtendChaining = function (extendsList, extendsListTarget, iterationCount) {
+ //
+ // chaining is different from normal extension.. if we extend an extend then we are not just copying, altering
+ // and pasting the selector we would do normally, but we are also adding an extend with the same target selector
+ // this means this new extend can then go and alter other extends
+ //
+ // this method deals with all the chaining work - without it, extend is flat and doesn't work on other extend selectors
+ // this is also the most expensive.. and a match on one selector can cause an extension of a selector we had already
+ // processed if we look at each selector at a time, as is done in visitRuleset
+ var extendIndex;
+ var targetExtendIndex;
+ var matches;
+ var extendsToAdd = [];
+ var newSelector;
+ var extendVisitor = this;
+ var selectorPath;
+ var extend;
+ var targetExtend;
+ var newExtend;
+ iterationCount = iterationCount || 0;
+ // loop through comparing every extend with every target extend.
+ // a target extend is the one on the ruleset we are looking at copy/edit/pasting in place
+ // e.g. .a:extend(.b) {} and .b:extend(.c) {} then the first extend extends the second one
+ // and the second is the target.
+ // the separation into two lists allows us to process a subset of chains with a bigger set, as is the
+ // case when processing media queries
+ for (extendIndex = 0; extendIndex < extendsList.length; extendIndex++) {
+ for (targetExtendIndex = 0; targetExtendIndex < extendsListTarget.length; targetExtendIndex++) {
+ extend = extendsList[extendIndex];
+ targetExtend = extendsListTarget[targetExtendIndex];
+ // look for circular references
+ if (extend.parent_ids.indexOf(targetExtend.object_id) >= 0) {
+ continue;
+ }
+ // find a match in the target extends self selector (the bit before :extend)
+ selectorPath = [targetExtend.selfSelectors[0]];
+ matches = extendVisitor.findMatch(extend, selectorPath);
+ if (matches.length) {
+ extend.hasFoundMatches = true;
+ // we found a match, so for each self selector..
+ extend.selfSelectors.forEach(function (selfSelector) {
+ var info = targetExtend.visibilityInfo();
+ // process the extend as usual
+ newSelector = extendVisitor.extendSelector(matches, selectorPath, selfSelector, extend.isVisible());
+ // but now we create a new extend from it
+ newExtend = new (tree.Extend)(targetExtend.selector, targetExtend.option, 0, targetExtend.fileInfo(), info);
+ newExtend.selfSelectors = newSelector;
+ // add the extend onto the list of extends for that selector
+ newSelector[newSelector.length - 1].extendList = [newExtend];
+ // record that we need to add it.
+ extendsToAdd.push(newExtend);
+ newExtend.ruleset = targetExtend.ruleset;
+ // remember its parents for circular references
+ newExtend.parent_ids = newExtend.parent_ids.concat(targetExtend.parent_ids, extend.parent_ids);
+ // only process the selector once.. if we have :extend(.a,.b) then multiple
+ // extends will look at the same selector path, so when extending
+ // we know that any others will be duplicates in terms of what is added to the css
+ if (targetExtend.firstExtendOnThisSelectorPath) {
+ newExtend.firstExtendOnThisSelectorPath = true;
+ targetExtend.ruleset.paths.push(newSelector);
+ }
+ });
+ }
+ }
+ }
+ if (extendsToAdd.length) {
+ // try to detect circular references to stop a stack overflow.
+ // may no longer be needed.
+ this.extendChainCount++;
+ if (iterationCount > 100) {
+ var selectorOne = '{unable to calculate}';
+ var selectorTwo = '{unable to calculate}';
+ try {
+ selectorOne = extendsToAdd[0].selfSelectors[0].toCSS();
+ selectorTwo = extendsToAdd[0].selector.toCSS();
+ }
+ catch (e) { }
+ throw { message: "extend circular reference detected. One of the circular extends is currently:" + selectorOne + ":extend(" + selectorTwo + ")" };
+ }
+ // now process the new extends on the existing rules so that we can handle a extending b extending c extending
+ // d extending e...
+ return extendsToAdd.concat(extendVisitor.doExtendChaining(extendsToAdd, extendsListTarget, iterationCount + 1));
+ }
+ else {
+ return extendsToAdd;
+ }
+ };
+ ProcessExtendsVisitor.prototype.visitDeclaration = function (ruleNode, visitArgs) {
+ visitArgs.visitDeeper = false;
+ };
+ ProcessExtendsVisitor.prototype.visitMixinDefinition = function (mixinDefinitionNode, visitArgs) {
+ visitArgs.visitDeeper = false;
+ };
+ ProcessExtendsVisitor.prototype.visitSelector = function (selectorNode, visitArgs) {
+ visitArgs.visitDeeper = false;
+ };
+ ProcessExtendsVisitor.prototype.visitRuleset = function (rulesetNode, visitArgs) {
+ if (rulesetNode.root) {
+ return;
+ }
+ var matches;
+ var pathIndex;
+ var extendIndex;
+ var allExtends = this.allExtendsStack[this.allExtendsStack.length - 1];
+ var selectorsToAdd = [];
+ var extendVisitor = this;
+ var selectorPath;
+ // look at each selector path in the ruleset, find any extend matches and then copy, find and replace
+ for (extendIndex = 0; extendIndex < allExtends.length; extendIndex++) {
+ for (pathIndex = 0; pathIndex < rulesetNode.paths.length; pathIndex++) {
+ selectorPath = rulesetNode.paths[pathIndex];
+ // extending extends happens initially, before the main pass
+ if (rulesetNode.extendOnEveryPath) {
+ continue;
+ }
+ var extendList = selectorPath[selectorPath.length - 1].extendList;
+ if (extendList && extendList.length) {
+ continue;
+ }
+ matches = this.findMatch(allExtends[extendIndex], selectorPath);
+ if (matches.length) {
+ allExtends[extendIndex].hasFoundMatches = true;
+ allExtends[extendIndex].selfSelectors.forEach(function (selfSelector) {
+ var extendedSelectors;
+ extendedSelectors = extendVisitor.extendSelector(matches, selectorPath, selfSelector, allExtends[extendIndex].isVisible());
+ selectorsToAdd.push(extendedSelectors);
+ });
+ }
+ }
+ }
+ rulesetNode.paths = rulesetNode.paths.concat(selectorsToAdd);
+ };
+ ProcessExtendsVisitor.prototype.findMatch = function (extend, haystackSelectorPath) {
+ //
+ // look through the haystack selector path to try and find the needle - extend.selector
+ // returns an array of selector matches that can then be replaced
+ //
+ var haystackSelectorIndex;
+ var hackstackSelector;
+ var hackstackElementIndex;
+ var haystackElement;
+ var targetCombinator;
+ var i;
+ var extendVisitor = this;
+ var needleElements = extend.selector.elements;
+ var potentialMatches = [];
+ var potentialMatch;
+ var matches = [];
+ // loop through the haystack elements
+ for (haystackSelectorIndex = 0; haystackSelectorIndex < haystackSelectorPath.length; haystackSelectorIndex++) {
+ hackstackSelector = haystackSelectorPath[haystackSelectorIndex];
+ for (hackstackElementIndex = 0; hackstackElementIndex < hackstackSelector.elements.length; hackstackElementIndex++) {
+ haystackElement = hackstackSelector.elements[hackstackElementIndex];
+ // if we allow elements before our match we can add a potential match every time. otherwise only at the first element.
+ if (extend.allowBefore || (haystackSelectorIndex === 0 && hackstackElementIndex === 0)) {
+ potentialMatches.push({ pathIndex: haystackSelectorIndex, index: hackstackElementIndex, matched: 0,
+ initialCombinator: haystackElement.combinator });
+ }
+ for (i = 0; i < potentialMatches.length; i++) {
+ potentialMatch = potentialMatches[i];
+ // selectors add " " onto the first element. When we use & it joins the selectors together, but if we don't
+ // then each selector in haystackSelectorPath has a space before it added in the toCSS phase. so we need to
+ // work out what the resulting combinator will be
+ targetCombinator = haystackElement.combinator.value;
+ if (targetCombinator === '' && hackstackElementIndex === 0) {
+ targetCombinator = ' ';
+ }
+ // if we don't match, null our match to indicate failure
+ if (!extendVisitor.isElementValuesEqual(needleElements[potentialMatch.matched].value, haystackElement.value) ||
+ (potentialMatch.matched > 0 && needleElements[potentialMatch.matched].combinator.value !== targetCombinator)) {
+ potentialMatch = null;
+ }
+ else {
+ potentialMatch.matched++;
+ }
+ // if we are still valid and have finished, test whether we have elements after and whether these are allowed
+ if (potentialMatch) {
+ potentialMatch.finished = potentialMatch.matched === needleElements.length;
+ if (potentialMatch.finished &&
+ (!extend.allowAfter &&
+ (hackstackElementIndex + 1 < hackstackSelector.elements.length || haystackSelectorIndex + 1 < haystackSelectorPath.length))) {
+ potentialMatch = null;
+ }
+ }
+ // if null we remove, if not, we are still valid, so either push as a valid match or continue
+ if (potentialMatch) {
+ if (potentialMatch.finished) {
+ potentialMatch.length = needleElements.length;
+ potentialMatch.endPathIndex = haystackSelectorIndex;
+ potentialMatch.endPathElementIndex = hackstackElementIndex + 1; // index after end of match
+ potentialMatches.length = 0; // we don't allow matches to overlap, so start matching again
+ matches.push(potentialMatch);
+ }
+ }
+ else {
+ potentialMatches.splice(i, 1);
+ i--;
+ }
+ }
+ }
+ }
+ return matches;
+ };
+ ProcessExtendsVisitor.prototype.isElementValuesEqual = function (elementValue1, elementValue2) {
+ if (typeof elementValue1 === 'string' || typeof elementValue2 === 'string') {
+ return elementValue1 === elementValue2;
+ }
+ if (elementValue1 instanceof tree.Attribute) {
+ if (elementValue1.op !== elementValue2.op || elementValue1.key !== elementValue2.key) {
+ return false;
+ }
+ if (!elementValue1.value || !elementValue2.value) {
+ if (elementValue1.value || elementValue2.value) {
+ return false;
+ }
+ return true;
+ }
+ elementValue1 = elementValue1.value.value || elementValue1.value;
+ elementValue2 = elementValue2.value.value || elementValue2.value;
+ return elementValue1 === elementValue2;
+ }
+ elementValue1 = elementValue1.value;
+ elementValue2 = elementValue2.value;
+ if (elementValue1 instanceof tree.Selector) {
+ if (!(elementValue2 instanceof tree.Selector) || elementValue1.elements.length !== elementValue2.elements.length) {
+ return false;
+ }
+ for (var i = 0; i < elementValue1.elements.length; i++) {
+ if (elementValue1.elements[i].combinator.value !== elementValue2.elements[i].combinator.value) {
+ if (i !== 0 || (elementValue1.elements[i].combinator.value || ' ') !== (elementValue2.elements[i].combinator.value || ' ')) {
+ return false;
+ }
+ }
+ if (!this.isElementValuesEqual(elementValue1.elements[i].value, elementValue2.elements[i].value)) {
+ return false;
+ }
+ }
+ return true;
+ }
+ return false;
+ };
+ ProcessExtendsVisitor.prototype.extendSelector = function (matches, selectorPath, replacementSelector, isVisible) {
+ // for a set of matches, replace each match with the replacement selector
+ var currentSelectorPathIndex = 0, currentSelectorPathElementIndex = 0, path = [], matchIndex, selector, firstElement, match, newElements;
+ for (matchIndex = 0; matchIndex < matches.length; matchIndex++) {
+ match = matches[matchIndex];
+ selector = selectorPath[match.pathIndex];
+ firstElement = new tree.Element(match.initialCombinator, replacementSelector.elements[0].value, replacementSelector.elements[0].isVariable, replacementSelector.elements[0].getIndex(), replacementSelector.elements[0].fileInfo());
+ if (match.pathIndex > currentSelectorPathIndex && currentSelectorPathElementIndex > 0) {
+ path[path.length - 1].elements = path[path.length - 1]
+ .elements.concat(selectorPath[currentSelectorPathIndex].elements.slice(currentSelectorPathElementIndex));
+ currentSelectorPathElementIndex = 0;
+ currentSelectorPathIndex++;
+ }
+ newElements = selector.elements
+ .slice(currentSelectorPathElementIndex, match.index)
+ .concat([firstElement])
+ .concat(replacementSelector.elements.slice(1));
+ if (currentSelectorPathIndex === match.pathIndex && matchIndex > 0) {
+ path[path.length - 1].elements =
+ path[path.length - 1].elements.concat(newElements);
+ }
+ else {
+ path = path.concat(selectorPath.slice(currentSelectorPathIndex, match.pathIndex));
+ path.push(new tree.Selector(newElements));
+ }
+ currentSelectorPathIndex = match.endPathIndex;
+ currentSelectorPathElementIndex = match.endPathElementIndex;
+ if (currentSelectorPathElementIndex >= selectorPath[currentSelectorPathIndex].elements.length) {
+ currentSelectorPathElementIndex = 0;
+ currentSelectorPathIndex++;
+ }
+ }
+ if (currentSelectorPathIndex < selectorPath.length && currentSelectorPathElementIndex > 0) {
+ path[path.length - 1].elements = path[path.length - 1]
+ .elements.concat(selectorPath[currentSelectorPathIndex].elements.slice(currentSelectorPathElementIndex));
+ currentSelectorPathIndex++;
+ }
+ path = path.concat(selectorPath.slice(currentSelectorPathIndex, selectorPath.length));
+ path = path.map(function (currentValue) {
+ // we can re-use elements here, because the visibility property matters only for selectors
+ var derived = currentValue.createDerived(currentValue.elements);
+ if (isVisible) {
+ derived.ensureVisibility();
+ }
+ else {
+ derived.ensureInvisibility();
+ }
+ return derived;
+ });
+ return path;
+ };
+ ProcessExtendsVisitor.prototype.visitMedia = function (mediaNode, visitArgs) {
+ var newAllExtends = mediaNode.allExtends.concat(this.allExtendsStack[this.allExtendsStack.length - 1]);
+ newAllExtends = newAllExtends.concat(this.doExtendChaining(newAllExtends, mediaNode.allExtends));
+ this.allExtendsStack.push(newAllExtends);
+ };
+ ProcessExtendsVisitor.prototype.visitMediaOut = function (mediaNode) {
+ var lastIndex = this.allExtendsStack.length - 1;
+ this.allExtendsStack.length = lastIndex;
+ };
+ ProcessExtendsVisitor.prototype.visitAtRule = function (atRuleNode, visitArgs) {
+ var newAllExtends = atRuleNode.allExtends.concat(this.allExtendsStack[this.allExtendsStack.length - 1]);
+ newAllExtends = newAllExtends.concat(this.doExtendChaining(newAllExtends, atRuleNode.allExtends));
+ this.allExtendsStack.push(newAllExtends);
+ };
+ ProcessExtendsVisitor.prototype.visitAtRuleOut = function (atRuleNode) {
+ var lastIndex = this.allExtendsStack.length - 1;
+ this.allExtendsStack.length = lastIndex;
+ };
+ return ProcessExtendsVisitor;
+ }());
+
+ var JoinSelectorVisitor = /** @class */ (function () {
+ function JoinSelectorVisitor() {
+ this.contexts = [[]];
+ this._visitor = new Visitor(this);
+ }
+ JoinSelectorVisitor.prototype.run = function (root) {
+ return this._visitor.visit(root);
+ };
+ JoinSelectorVisitor.prototype.visitDeclaration = function (declNode, visitArgs) {
+ visitArgs.visitDeeper = false;
+ };
+ JoinSelectorVisitor.prototype.visitMixinDefinition = function (mixinDefinitionNode, visitArgs) {
+ visitArgs.visitDeeper = false;
+ };
+ JoinSelectorVisitor.prototype.visitRuleset = function (rulesetNode, visitArgs) {
+ var context = this.contexts[this.contexts.length - 1];
+ var paths = [];
+ var selectors;
+ this.contexts.push(paths);
+ if (!rulesetNode.root) {
+ selectors = rulesetNode.selectors;
+ if (selectors) {
+ selectors = selectors.filter(function (selector) { return selector.getIsOutput(); });
+ rulesetNode.selectors = selectors.length ? selectors : (selectors = null);
+ if (selectors) {
+ rulesetNode.joinSelectors(paths, context, selectors);
+ }
+ }
+ if (!selectors) {
+ rulesetNode.rules = null;
+ }
+ rulesetNode.paths = paths;
+ }
+ };
+ JoinSelectorVisitor.prototype.visitRulesetOut = function (rulesetNode) {
+ this.contexts.length = this.contexts.length - 1;
+ };
+ JoinSelectorVisitor.prototype.visitMedia = function (mediaNode, visitArgs) {
+ var context = this.contexts[this.contexts.length - 1];
+ mediaNode.rules[0].root = (context.length === 0 || context[0].multiMedia);
+ };
+ JoinSelectorVisitor.prototype.visitAtRule = function (atRuleNode, visitArgs) {
+ var context = this.contexts[this.contexts.length - 1];
+ if (atRuleNode.rules && atRuleNode.rules.length) {
+ atRuleNode.rules[0].root = (atRuleNode.isRooted || context.length === 0 || null);
+ }
+ };
+ return JoinSelectorVisitor;
+ }());
+
+ var CSSVisitorUtils = /** @class */ (function () {
+ function CSSVisitorUtils(context) {
+ this._visitor = new Visitor(this);
+ this._context = context;
+ }
+ CSSVisitorUtils.prototype.containsSilentNonBlockedChild = function (bodyRules) {
+ var rule;
+ if (!bodyRules) {
+ return false;
+ }
+ for (var r = 0; r < bodyRules.length; r++) {
+ rule = bodyRules[r];
+ if (rule.isSilent && rule.isSilent(this._context) && !rule.blocksVisibility()) {
+ // the atrule contains something that was referenced (likely by extend)
+ // therefore it needs to be shown in output too
+ return true;
+ }
+ }
+ return false;
+ };
+ CSSVisitorUtils.prototype.keepOnlyVisibleChilds = function (owner) {
+ if (owner && owner.rules) {
+ owner.rules = owner.rules.filter(function (thing) { return thing.isVisible(); });
+ }
+ };
+ CSSVisitorUtils.prototype.isEmpty = function (owner) {
+ return (owner && owner.rules)
+ ? (owner.rules.length === 0) : true;
+ };
+ CSSVisitorUtils.prototype.hasVisibleSelector = function (rulesetNode) {
+ return (rulesetNode && rulesetNode.paths)
+ ? (rulesetNode.paths.length > 0) : false;
+ };
+ CSSVisitorUtils.prototype.resolveVisibility = function (node, originalRules) {
+ if (!node.blocksVisibility()) {
+ if (this.isEmpty(node) && !this.containsSilentNonBlockedChild(originalRules)) {
+ return;
+ }
+ return node;
+ }
+ var compiledRulesBody = node.rules[0];
+ this.keepOnlyVisibleChilds(compiledRulesBody);
+ if (this.isEmpty(compiledRulesBody)) {
+ return;
+ }
+ node.ensureVisibility();
+ node.removeVisibilityBlock();
+ return node;
+ };
+ CSSVisitorUtils.prototype.isVisibleRuleset = function (rulesetNode) {
+ if (rulesetNode.firstRoot) {
+ return true;
+ }
+ if (this.isEmpty(rulesetNode)) {
+ return false;
+ }
+ if (!rulesetNode.root && !this.hasVisibleSelector(rulesetNode)) {
+ return false;
+ }
+ return true;
+ };
+ return CSSVisitorUtils;
+ }());
+ var ToCSSVisitor = function (context) {
+ this._visitor = new Visitor(this);
+ this._context = context;
+ this.utils = new CSSVisitorUtils(context);
+ };
+ ToCSSVisitor.prototype = {
+ isReplacing: true,
+ run: function (root) {
+ return this._visitor.visit(root);
+ },
+ visitDeclaration: function (declNode, visitArgs) {
+ if (declNode.blocksVisibility() || declNode.variable) {
+ return;
+ }
+ return declNode;
+ },
+ visitMixinDefinition: function (mixinNode, visitArgs) {
+ // mixin definitions do not get eval'd - this means they keep state
+ // so we have to clear that state here so it isn't used if toCSS is called twice
+ mixinNode.frames = [];
+ },
+ visitExtend: function (extendNode, visitArgs) {
+ },
+ visitComment: function (commentNode, visitArgs) {
+ if (commentNode.blocksVisibility() || commentNode.isSilent(this._context)) {
+ return;
+ }
+ return commentNode;
+ },
+ visitMedia: function (mediaNode, visitArgs) {
+ var originalRules = mediaNode.rules[0].rules;
+ mediaNode.accept(this._visitor);
+ visitArgs.visitDeeper = false;
+ return this.utils.resolveVisibility(mediaNode, originalRules);
+ },
+ visitImport: function (importNode, visitArgs) {
+ if (importNode.blocksVisibility()) {
+ return;
+ }
+ return importNode;
+ },
+ visitAtRule: function (atRuleNode, visitArgs) {
+ if (atRuleNode.rules && atRuleNode.rules.length) {
+ return this.visitAtRuleWithBody(atRuleNode, visitArgs);
+ }
+ else {
+ return this.visitAtRuleWithoutBody(atRuleNode, visitArgs);
+ }
+ },
+ visitAnonymous: function (anonymousNode, visitArgs) {
+ if (!anonymousNode.blocksVisibility()) {
+ anonymousNode.accept(this._visitor);
+ return anonymousNode;
+ }
+ },
+ visitAtRuleWithBody: function (atRuleNode, visitArgs) {
+ // if there is only one nested ruleset and that one has no path, then it is
+ // just fake ruleset
+ function hasFakeRuleset(atRuleNode) {
+ var bodyRules = atRuleNode.rules;
+ return bodyRules.length === 1 && (!bodyRules[0].paths || bodyRules[0].paths.length === 0);
+ }
+ function getBodyRules(atRuleNode) {
+ var nodeRules = atRuleNode.rules;
+ if (hasFakeRuleset(atRuleNode)) {
+ return nodeRules[0].rules;
+ }
+ return nodeRules;
+ }
+ // it is still true that it is only one ruleset in array
+ // this is last such moment
+ // process childs
+ var originalRules = getBodyRules(atRuleNode);
+ atRuleNode.accept(this._visitor);
+ visitArgs.visitDeeper = false;
+ if (!this.utils.isEmpty(atRuleNode)) {
+ this._mergeRules(atRuleNode.rules[0].rules);
+ }
+ return this.utils.resolveVisibility(atRuleNode, originalRules);
+ },
+ visitAtRuleWithoutBody: function (atRuleNode, visitArgs) {
+ if (atRuleNode.blocksVisibility()) {
+ return;
+ }
+ if (atRuleNode.name === '@charset') {
+ // Only output the debug info together with subsequent @charset definitions
+ // a comment (or @media statement) before the actual @charset atrule would
+ // be considered illegal css as it has to be on the first line
+ if (this.charset) {
+ if (atRuleNode.debugInfo) {
+ var comment = new tree.Comment("/* " + atRuleNode.toCSS(this._context).replace(/\n/g, '') + " */\n");
+ comment.debugInfo = atRuleNode.debugInfo;
+ return this._visitor.visit(comment);
+ }
+ return;
+ }
+ this.charset = true;
+ }
+ return atRuleNode;
+ },
+ checkValidNodes: function (rules, isRoot) {
+ if (!rules) {
+ return;
+ }
+ for (var i = 0; i < rules.length; i++) {
+ var ruleNode = rules[i];
+ if (isRoot && ruleNode instanceof tree.Declaration && !ruleNode.variable) {
+ throw { message: 'Properties must be inside selector blocks. They cannot be in the root',
+ index: ruleNode.getIndex(), filename: ruleNode.fileInfo() && ruleNode.fileInfo().filename };
+ }
+ if (ruleNode instanceof tree.Call) {
+ throw { message: "Function '" + ruleNode.name + "' did not return a root node",
+ index: ruleNode.getIndex(), filename: ruleNode.fileInfo() && ruleNode.fileInfo().filename };
+ }
+ if (ruleNode.type && !ruleNode.allowRoot) {
+ throw { message: ruleNode.type + " node returned by a function is not valid here",
+ index: ruleNode.getIndex(), filename: ruleNode.fileInfo() && ruleNode.fileInfo().filename };
+ }
+ }
+ },
+ visitRuleset: function (rulesetNode, visitArgs) {
+ // at this point rulesets are nested into each other
+ var rule;
+ var rulesets = [];
+ this.checkValidNodes(rulesetNode.rules, rulesetNode.firstRoot);
+ if (!rulesetNode.root) {
+ // remove invisible paths
+ this._compileRulesetPaths(rulesetNode);
+ // remove rulesets from this ruleset body and compile them separately
+ var nodeRules = rulesetNode.rules;
+ var nodeRuleCnt = nodeRules ? nodeRules.length : 0;
+ for (var i = 0; i < nodeRuleCnt;) {
+ rule = nodeRules[i];
+ if (rule && rule.rules) {
+ // visit because we are moving them out from being a child
+ rulesets.push(this._visitor.visit(rule));
+ nodeRules.splice(i, 1);
+ nodeRuleCnt--;
+ continue;
+ }
+ i++;
+ }
+ // accept the visitor to remove rules and refactor itself
+ // then we can decide nogw whether we want it or not
+ // compile body
+ if (nodeRuleCnt > 0) {
+ rulesetNode.accept(this._visitor);
+ }
+ else {
+ rulesetNode.rules = null;
+ }
+ visitArgs.visitDeeper = false;
+ }
+ else { // if (! rulesetNode.root) {
+ rulesetNode.accept(this._visitor);
+ visitArgs.visitDeeper = false;
+ }
+ if (rulesetNode.rules) {
+ this._mergeRules(rulesetNode.rules);
+ this._removeDuplicateRules(rulesetNode.rules);
+ }
+ // now decide whether we keep the ruleset
+ if (this.utils.isVisibleRuleset(rulesetNode)) {
+ rulesetNode.ensureVisibility();
+ rulesets.splice(0, 0, rulesetNode);
+ }
+ if (rulesets.length === 1) {
+ return rulesets[0];
+ }
+ return rulesets;
+ },
+ _compileRulesetPaths: function (rulesetNode) {
+ if (rulesetNode.paths) {
+ rulesetNode.paths = rulesetNode.paths
+ .filter(function (p) {
+ var i;
+ if (p[0].elements[0].combinator.value === ' ') {
+ p[0].elements[0].combinator = new (tree.Combinator)('');
+ }
+ for (i = 0; i < p.length; i++) {
+ if (p[i].isVisible() && p[i].getIsOutput()) {
+ return true;
+ }
+ }
+ return false;
+ });
+ }
+ },
+ _removeDuplicateRules: function (rules) {
+ if (!rules) {
+ return;
+ }
+ // remove duplicates
+ var ruleCache = {};
+ var ruleList;
+ var rule;
+ var i;
+ for (i = rules.length - 1; i >= 0; i--) {
+ rule = rules[i];
+ if (rule instanceof tree.Declaration) {
+ if (!ruleCache[rule.name]) {
+ ruleCache[rule.name] = rule;
+ }
+ else {
+ ruleList = ruleCache[rule.name];
+ if (ruleList instanceof tree.Declaration) {
+ ruleList = ruleCache[rule.name] = [ruleCache[rule.name].toCSS(this._context)];
+ }
+ var ruleCSS = rule.toCSS(this._context);
+ if (ruleList.indexOf(ruleCSS) !== -1) {
+ rules.splice(i, 1);
+ }
+ else {
+ ruleList.push(ruleCSS);
+ }
+ }
+ }
+ }
+ },
+ _mergeRules: function (rules) {
+ if (!rules) {
+ return;
+ }
+ var groups = {};
+ var groupsArr = [];
+ for (var i = 0; i < rules.length; i++) {
+ var rule = rules[i];
+ if (rule.merge) {
+ var key = rule.name;
+ groups[key] ? rules.splice(i--, 1) :
+ groupsArr.push(groups[key] = []);
+ groups[key].push(rule);
+ }
+ }
+ groupsArr.forEach(function (group) {
+ if (group.length > 0) {
+ var result_1 = group[0];
+ var space_1 = [];
+ var comma_1 = [new tree.Expression(space_1)];
+ group.forEach(function (rule) {
+ if ((rule.merge === '+') && (space_1.length > 0)) {
+ comma_1.push(new tree.Expression(space_1 = []));
+ }
+ space_1.push(rule.value);
+ result_1.important = result_1.important || rule.important;
+ });
+ result_1.value = new tree.Value(comma_1);
+ }
+ });
+ }
+ };
+
+ var visitors = {
+ Visitor: Visitor,
+ ImportVisitor: ImportVisitor,
+ MarkVisibleSelectorsVisitor: SetTreeVisibilityVisitor,
+ ExtendVisitor: ProcessExtendsVisitor,
+ JoinSelectorVisitor: JoinSelectorVisitor,
+ ToCSSVisitor: ToCSSVisitor
+ };
+
+ // Split the input into chunks.
+ function chunker (input, fail) {
+ var len = input.length;
+ var level = 0;
+ var parenLevel = 0;
+ var lastOpening;
+ var lastOpeningParen;
+ var lastMultiComment;
+ var lastMultiCommentEndBrace;
+ var chunks = [];
+ var emitFrom = 0;
+ var chunkerCurrentIndex;
+ var currentChunkStartIndex;
+ var cc;
+ var cc2;
+ var matched;
+ function emitChunk(force) {
+ var len = chunkerCurrentIndex - emitFrom;
+ if (((len < 512) && !force) || !len) {
+ return;
+ }
+ chunks.push(input.slice(emitFrom, chunkerCurrentIndex + 1));
+ emitFrom = chunkerCurrentIndex + 1;
+ }
+ for (chunkerCurrentIndex = 0; chunkerCurrentIndex < len; chunkerCurrentIndex++) {
+ cc = input.charCodeAt(chunkerCurrentIndex);
+ if (((cc >= 97) && (cc <= 122)) || (cc < 34)) {
+ // a-z or whitespace
+ continue;
+ }
+ switch (cc) {
+ case 40: // (
+ parenLevel++;
+ lastOpeningParen = chunkerCurrentIndex;
+ continue;
+ case 41: // )
+ if (--parenLevel < 0) {
+ return fail('missing opening `(`', chunkerCurrentIndex);
+ }
+ continue;
+ case 59: // ;
+ if (!parenLevel) {
+ emitChunk();
+ }
+ continue;
+ case 123: // {
+ level++;
+ lastOpening = chunkerCurrentIndex;
+ continue;
+ case 125: // }
+ if (--level < 0) {
+ return fail('missing opening `{`', chunkerCurrentIndex);
+ }
+ if (!level && !parenLevel) {
+ emitChunk();
+ }
+ continue;
+ case 92: // \
+ if (chunkerCurrentIndex < len - 1) {
+ chunkerCurrentIndex++;
+ continue;
+ }
+ return fail('unescaped `\\`', chunkerCurrentIndex);
+ case 34:
+ case 39:
+ case 96: // ", ' and `
+ matched = 0;
+ currentChunkStartIndex = chunkerCurrentIndex;
+ for (chunkerCurrentIndex = chunkerCurrentIndex + 1; chunkerCurrentIndex < len; chunkerCurrentIndex++) {
+ cc2 = input.charCodeAt(chunkerCurrentIndex);
+ if (cc2 > 96) {
+ continue;
+ }
+ if (cc2 == cc) {
+ matched = 1;
+ break;
+ }
+ if (cc2 == 92) { // \
+ if (chunkerCurrentIndex == len - 1) {
+ return fail('unescaped `\\`', chunkerCurrentIndex);
+ }
+ chunkerCurrentIndex++;
+ }
+ }
+ if (matched) {
+ continue;
+ }
+ return fail("unmatched `" + String.fromCharCode(cc) + "`", currentChunkStartIndex);
+ case 47: // /, check for comment
+ if (parenLevel || (chunkerCurrentIndex == len - 1)) {
+ continue;
+ }
+ cc2 = input.charCodeAt(chunkerCurrentIndex + 1);
+ if (cc2 == 47) {
+ // //, find lnfeed
+ for (chunkerCurrentIndex = chunkerCurrentIndex + 2; chunkerCurrentIndex < len; chunkerCurrentIndex++) {
+ cc2 = input.charCodeAt(chunkerCurrentIndex);
+ if ((cc2 <= 13) && ((cc2 == 10) || (cc2 == 13))) {
+ break;
+ }
+ }
+ }
+ else if (cc2 == 42) {
+ // /*, find */
+ lastMultiComment = currentChunkStartIndex = chunkerCurrentIndex;
+ for (chunkerCurrentIndex = chunkerCurrentIndex + 2; chunkerCurrentIndex < len - 1; chunkerCurrentIndex++) {
+ cc2 = input.charCodeAt(chunkerCurrentIndex);
+ if (cc2 == 125) {
+ lastMultiCommentEndBrace = chunkerCurrentIndex;
+ }
+ if (cc2 != 42) {
+ continue;
+ }
+ if (input.charCodeAt(chunkerCurrentIndex + 1) == 47) {
+ break;
+ }
+ }
+ if (chunkerCurrentIndex == len - 1) {
+ return fail('missing closing `*/`', currentChunkStartIndex);
+ }
+ chunkerCurrentIndex++;
+ }
+ continue;
+ case 42: // *, check for unmatched */
+ if ((chunkerCurrentIndex < len - 1) && (input.charCodeAt(chunkerCurrentIndex + 1) == 47)) {
+ return fail('unmatched `/*`', chunkerCurrentIndex);
+ }
+ continue;
+ }
+ }
+ if (level !== 0) {
+ if ((lastMultiComment > lastOpening) && (lastMultiCommentEndBrace > lastMultiComment)) {
+ return fail('missing closing `}` or `*/`', lastOpening);
+ }
+ else {
+ return fail('missing closing `}`', lastOpening);
+ }
+ }
+ else if (parenLevel !== 0) {
+ return fail('missing closing `)`', lastOpeningParen);
+ }
+ emitChunk(true);
+ return chunks;
+ }
+
+ var getParserInput = (function () {
+ var // Less input string
+ input;
+ var // current chunk
+ j;
+ var // holds state for backtracking
+ saveStack = [];
+ var // furthest index the parser has gone to
+ furthest;
+ var // if this is furthest we got to, this is the probably cause
+ furthestPossibleErrorMessage;
+ var // chunkified input
+ chunks;
+ var // current chunk
+ current;
+ var // index of current chunk, in `input`
+ currentPos;
+ var parserInput = {};
+ var CHARCODE_SPACE = 32;
+ var CHARCODE_TAB = 9;
+ var CHARCODE_LF = 10;
+ var CHARCODE_CR = 13;
+ var CHARCODE_PLUS = 43;
+ var CHARCODE_COMMA = 44;
+ var CHARCODE_FORWARD_SLASH = 47;
+ var CHARCODE_9 = 57;
+ function skipWhitespace(length) {
+ var oldi = parserInput.i;
+ var oldj = j;
+ var curr = parserInput.i - currentPos;
+ var endIndex = parserInput.i + current.length - curr;
+ var mem = (parserInput.i += length);
+ var inp = input;
+ var c;
+ var nextChar;
+ var comment;
+ for (; parserInput.i < endIndex; parserInput.i++) {
+ c = inp.charCodeAt(parserInput.i);
+ if (parserInput.autoCommentAbsorb && c === CHARCODE_FORWARD_SLASH) {
+ nextChar = inp.charAt(parserInput.i + 1);
+ if (nextChar === '/') {
+ comment = { index: parserInput.i, isLineComment: true };
+ var nextNewLine = inp.indexOf('\n', parserInput.i + 2);
+ if (nextNewLine < 0) {
+ nextNewLine = endIndex;
+ }
+ parserInput.i = nextNewLine;
+ comment.text = inp.substr(comment.index, parserInput.i - comment.index);
+ parserInput.commentStore.push(comment);
+ continue;
+ }
+ else if (nextChar === '*') {
+ var nextStarSlash = inp.indexOf('*/', parserInput.i + 2);
+ if (nextStarSlash >= 0) {
+ comment = {
+ index: parserInput.i,
+ text: inp.substr(parserInput.i, nextStarSlash + 2 - parserInput.i),
+ isLineComment: false
+ };
+ parserInput.i += comment.text.length - 1;
+ parserInput.commentStore.push(comment);
+ continue;
+ }
+ }
+ break;
+ }
+ if ((c !== CHARCODE_SPACE) && (c !== CHARCODE_LF) && (c !== CHARCODE_TAB) && (c !== CHARCODE_CR)) {
+ break;
+ }
+ }
+ current = current.slice(length + parserInput.i - mem + curr);
+ currentPos = parserInput.i;
+ if (!current.length) {
+ if (j < chunks.length - 1) {
+ current = chunks[++j];
+ skipWhitespace(0); // skip space at the beginning of a chunk
+ return true; // things changed
+ }
+ parserInput.finished = true;
+ }
+ return oldi !== parserInput.i || oldj !== j;
+ }
+ parserInput.save = function () {
+ currentPos = parserInput.i;
+ saveStack.push({ current: current, i: parserInput.i, j: j });
+ };
+ parserInput.restore = function (possibleErrorMessage) {
+ if (parserInput.i > furthest || (parserInput.i === furthest && possibleErrorMessage && !furthestPossibleErrorMessage)) {
+ furthest = parserInput.i;
+ furthestPossibleErrorMessage = possibleErrorMessage;
+ }
+ var state = saveStack.pop();
+ current = state.current;
+ currentPos = parserInput.i = state.i;
+ j = state.j;
+ };
+ parserInput.forget = function () {
+ saveStack.pop();
+ };
+ parserInput.isWhitespace = function (offset) {
+ var pos = parserInput.i + (offset || 0);
+ var code = input.charCodeAt(pos);
+ return (code === CHARCODE_SPACE || code === CHARCODE_CR || code === CHARCODE_TAB || code === CHARCODE_LF);
+ };
+ // Specialization of $(tok)
+ parserInput.$re = function (tok) {
+ if (parserInput.i > currentPos) {
+ current = current.slice(parserInput.i - currentPos);
+ currentPos = parserInput.i;
+ }
+ var m = tok.exec(current);
+ if (!m) {
+ return null;
+ }
+ skipWhitespace(m[0].length);
+ if (typeof m === 'string') {
+ return m;
+ }
+ return m.length === 1 ? m[0] : m;
+ };
+ parserInput.$char = function (tok) {
+ if (input.charAt(parserInput.i) !== tok) {
+ return null;
+ }
+ skipWhitespace(1);
+ return tok;
+ };
+ parserInput.$str = function (tok) {
+ var tokLength = tok.length;
+ // https://jsperf.com/string-startswith/21
+ for (var i = 0; i < tokLength; i++) {
+ if (input.charAt(parserInput.i + i) !== tok.charAt(i)) {
+ return null;
+ }
+ }
+ skipWhitespace(tokLength);
+ return tok;
+ };
+ parserInput.$quoted = function (loc) {
+ var pos = loc || parserInput.i;
+ var startChar = input.charAt(pos);
+ if (startChar !== '\'' && startChar !== '"') {
+ return;
+ }
+ var length = input.length;
+ var currentPosition = pos;
+ for (var i = 1; i + currentPosition < length; i++) {
+ var nextChar = input.charAt(i + currentPosition);
+ switch (nextChar) {
+ case '\\':
+ i++;
+ continue;
+ case '\r':
+ case '\n':
+ break;
+ case startChar:
+ var str = input.substr(currentPosition, i + 1);
+ if (!loc && loc !== 0) {
+ skipWhitespace(i + 1);
+ return str;
+ }
+ return [startChar, str];
+ }
+ }
+ return null;
+ };
+ /**
+ * Permissive parsing. Ignores everything except matching {} [] () and quotes
+ * until matching token (outside of blocks)
+ */
+ parserInput.$parseUntil = function (tok) {
+ var quote = '';
+ var returnVal = null;
+ var inComment = false;
+ var blockDepth = 0;
+ var blockStack = [];
+ var parseGroups = [];
+ var length = input.length;
+ var startPos = parserInput.i;
+ var lastPos = parserInput.i;
+ var i = parserInput.i;
+ var loop = true;
+ var testChar;
+ if (typeof tok === 'string') {
+ testChar = function (char) { return char === tok; };
+ }
+ else {
+ testChar = function (char) { return tok.test(char); };
+ }
+ do {
+ var nextChar = input.charAt(i);
+ if (blockDepth === 0 && testChar(nextChar)) {
+ returnVal = input.substr(lastPos, i - lastPos);
+ if (returnVal) {
+ parseGroups.push(returnVal);
+ }
+ else {
+ parseGroups.push(' ');
+ }
+ returnVal = parseGroups;
+ skipWhitespace(i - startPos);
+ loop = false;
+ }
+ else {
+ if (inComment) {
+ if (nextChar === '*' &&
+ input.charAt(i + 1) === '/') {
+ i++;
+ blockDepth--;
+ inComment = false;
+ }
+ i++;
+ continue;
+ }
+ switch (nextChar) {
+ case '\\':
+ i++;
+ nextChar = input.charAt(i);
+ parseGroups.push(input.substr(lastPos, i - lastPos + 1));
+ lastPos = i + 1;
+ break;
+ case '/':
+ if (input.charAt(i + 1) === '*') {
+ i++;
+ inComment = true;
+ blockDepth++;
+ }
+ break;
+ case '\'':
+ case '"':
+ quote = parserInput.$quoted(i);
+ if (quote) {
+ parseGroups.push(input.substr(lastPos, i - lastPos), quote);
+ i += quote[1].length - 1;
+ lastPos = i + 1;
+ }
+ else {
+ skipWhitespace(i - startPos);
+ returnVal = nextChar;
+ loop = false;
+ }
+ break;
+ case '{':
+ blockStack.push('}');
+ blockDepth++;
+ break;
+ case '(':
+ blockStack.push(')');
+ blockDepth++;
+ break;
+ case '[':
+ blockStack.push(']');
+ blockDepth++;
+ break;
+ case '}':
+ case ')':
+ case ']':
+ var expected = blockStack.pop();
+ if (nextChar === expected) {
+ blockDepth--;
+ }
+ else {
+ // move the parser to the error and return expected
+ skipWhitespace(i - startPos);
+ returnVal = expected;
+ loop = false;
+ }
+ }
+ i++;
+ if (i > length) {
+ loop = false;
+ }
+ }
+ } while (loop);
+ return returnVal ? returnVal : null;
+ };
+ parserInput.autoCommentAbsorb = true;
+ parserInput.commentStore = [];
+ parserInput.finished = false;
+ // Same as $(), but don't change the state of the parser,
+ // just return the match.
+ parserInput.peek = function (tok) {
+ if (typeof tok === 'string') {
+ // https://jsperf.com/string-startswith/21
+ for (var i = 0; i < tok.length; i++) {
+ if (input.charAt(parserInput.i + i) !== tok.charAt(i)) {
+ return false;
+ }
+ }
+ return true;
+ }
+ else {
+ return tok.test(current);
+ }
+ };
+ // Specialization of peek()
+ // TODO remove or change some currentChar calls to peekChar
+ parserInput.peekChar = function (tok) { return input.charAt(parserInput.i) === tok; };
+ parserInput.currentChar = function () { return input.charAt(parserInput.i); };
+ parserInput.prevChar = function () { return input.charAt(parserInput.i - 1); };
+ parserInput.getInput = function () { return input; };
+ parserInput.peekNotNumeric = function () {
+ var c = input.charCodeAt(parserInput.i);
+ // Is the first char of the dimension 0-9, '.', '+' or '-'
+ return (c > CHARCODE_9 || c < CHARCODE_PLUS) || c === CHARCODE_FORWARD_SLASH || c === CHARCODE_COMMA;
+ };
+ parserInput.start = function (str, chunkInput, failFunction) {
+ input = str;
+ parserInput.i = j = currentPos = furthest = 0;
+ // chunking apparently makes things quicker (but my tests indicate
+ // it might actually make things slower in node at least)
+ // and it is a non-perfect parse - it can't recognise
+ // unquoted urls, meaning it can't distinguish comments
+ // meaning comments with quotes or {}() in them get 'counted'
+ // and then lead to parse errors.
+ // In addition if the chunking chunks in the wrong place we might
+ // not be able to parse a parser statement in one go
+ // this is officially deprecated but can be switched on via an option
+ // in the case it causes too much performance issues.
+ if (chunkInput) {
+ chunks = chunker(str, failFunction);
+ }
+ else {
+ chunks = [str];
+ }
+ current = chunks[0];
+ skipWhitespace(0);
+ };
+ parserInput.end = function () {
+ var message;
+ var isFinished = parserInput.i >= input.length;
+ if (parserInput.i < furthest) {
+ message = furthestPossibleErrorMessage;
+ parserInput.i = furthest;
+ }
+ return {
+ isFinished: isFinished,
+ furthest: parserInput.i,
+ furthestPossibleErrorMessage: message,
+ furthestReachedEnd: parserInput.i >= input.length - 1,
+ furthestChar: input[parserInput.i]
+ };
+ };
+ return parserInput;
+ });
+
+ //
+ // less.js - parser
+ //
+ // A relatively straight-forward predictive parser.
+ // There is no tokenization/lexing stage, the input is parsed
+ // in one sweep.
+ //
+ // To make the parser fast enough to run in the browser, several
+ // optimization had to be made:
+ //
+ // - Matching and slicing on a huge input is often cause of slowdowns.
+ // The solution is to chunkify the input into smaller strings.
+ // The chunks are stored in the `chunks` var,
+ // `j` holds the current chunk index, and `currentPos` holds
+ // the index of the current chunk in relation to `input`.
+ // This gives us an almost 4x speed-up.
+ //
+ // - In many cases, we don't need to match individual tokens;
+ // for example, if a value doesn't hold any variables, operations
+ // or dynamic references, the parser can effectively 'skip' it,
+ // treating it as a literal.
+ // An example would be '1px solid #000' - which evaluates to itself,
+ // we don't need to know what the individual components are.
+ // The drawback, of course is that you don't get the benefits of
+ // syntax-checking on the CSS. This gives us a 50% speed-up in the parser,
+ // and a smaller speed-up in the code-gen.
+ //
+ //
+ // Token matching is done with the `$` function, which either takes
+ // a terminal string or regexp, or a non-terminal function to call.
+ // It also takes care of moving all the indices forwards.
+ //
+ var Parser = function Parser(context, imports, fileInfo) {
+ var parsers;
+ var parserInput = getParserInput();
+ function error(msg, type) {
+ throw new LessError({
+ index: parserInput.i,
+ filename: fileInfo.filename,
+ type: type || 'Syntax',
+ message: msg
+ }, imports);
+ }
+ function expect(arg, msg) {
+ // some older browsers return typeof 'function' for RegExp
+ var result = (arg instanceof Function) ? arg.call(parsers) : parserInput.$re(arg);
+ if (result) {
+ return result;
+ }
+ error(msg || (typeof arg === 'string'
+ ? "expected '" + arg + "' got '" + parserInput.currentChar() + "'"
+ : 'unexpected token'));
+ }
+ // Specialization of expect()
+ function expectChar(arg, msg) {
+ if (parserInput.$char(arg)) {
+ return arg;
+ }
+ error(msg || "expected '" + arg + "' got '" + parserInput.currentChar() + "'");
+ }
+ function getDebugInfo(index) {
+ var filename = fileInfo.filename;
+ return {
+ lineNumber: getLocation(index, parserInput.getInput()).line + 1,
+ fileName: filename
+ };
+ }
+ /**
+ * Used after initial parsing to create nodes on the fly
+ *
+ * @param {String} str - string to parse
+ * @param {Array} parseList - array of parsers to run input through e.g. ["value", "important"]
+ * @param {Number} currentIndex - start number to begin indexing
+ * @param {Object} fileInfo - fileInfo to attach to created nodes
+ */
+ function parseNode(str, parseList, currentIndex, fileInfo, callback) {
+ var result;
+ var returnNodes = [];
+ var parser = parserInput;
+ try {
+ parser.start(str, false, function fail(msg, index) {
+ callback({
+ message: msg,
+ index: index + currentIndex
+ });
+ });
+ for (var x = 0, p = void 0, i = void 0; (p = parseList[x]); x++) {
+ i = parser.i;
+ result = parsers[p]();
+ if (result) {
+ try {
+ result._index = i + currentIndex;
+ result._fileInfo = fileInfo;
+ }
+ catch (e) { }
+ returnNodes.push(result);
+ }
+ else {
+ returnNodes.push(null);
+ }
+ }
+ var endInfo = parser.end();
+ if (endInfo.isFinished) {
+ callback(null, returnNodes);
+ }
+ else {
+ callback(true, null);
+ }
+ }
+ catch (e) {
+ throw new LessError({
+ index: e.index + currentIndex,
+ message: e.message
+ }, imports, fileInfo.filename);
+ }
+ }
+ //
+ // The Parser
+ //
+ return {
+ parserInput: parserInput,
+ imports: imports,
+ fileInfo: fileInfo,
+ parseNode: parseNode,
+ //
+ // Parse an input string into an abstract syntax tree,
+ // @param str A string containing 'less' markup
+ // @param callback call `callback` when done.
+ // @param [additionalData] An optional map which can contains vars - a map (key, value) of variables to apply
+ //
+ parse: function (str, callback, additionalData) {
+ var root;
+ var error = null;
+ var globalVars;
+ var modifyVars;
+ var ignored;
+ var preText = '';
+ globalVars = (additionalData && additionalData.globalVars) ? Parser.serializeVars(additionalData.globalVars) + "\n" : '';
+ modifyVars = (additionalData && additionalData.modifyVars) ? "\n" + Parser.serializeVars(additionalData.modifyVars) : '';
+ if (context.pluginManager) {
+ var preProcessors = context.pluginManager.getPreProcessors();
+ for (var i = 0; i < preProcessors.length; i++) {
+ str = preProcessors[i].process(str, { context: context, imports: imports, fileInfo: fileInfo });
+ }
+ }
+ if (globalVars || (additionalData && additionalData.banner)) {
+ preText = ((additionalData && additionalData.banner) ? additionalData.banner : '') + globalVars;
+ ignored = imports.contentsIgnoredChars;
+ ignored[fileInfo.filename] = ignored[fileInfo.filename] || 0;
+ ignored[fileInfo.filename] += preText.length;
+ }
+ str = str.replace(/\r\n?/g, '\n');
+ // Remove potential UTF Byte Order Mark
+ str = preText + str.replace(/^\uFEFF/, '') + modifyVars;
+ imports.contents[fileInfo.filename] = str;
+ // Start with the primary rule.
+ // The whole syntax tree is held under a Ruleset node,
+ // with the `root` property set to true, so no `{}` are
+ // output. The callback is called when the input is parsed.
+ try {
+ parserInput.start(str, context.chunkInput, function fail(msg, index) {
+ throw new LessError({
+ index: index,
+ type: 'Parse',
+ message: msg,
+ filename: fileInfo.filename
+ }, imports);
+ });
+ tree.Node.prototype.parse = this;
+ root = new tree.Ruleset(null, this.parsers.primary());
+ tree.Node.prototype.rootNode = root;
+ root.root = true;
+ root.firstRoot = true;
+ root.functionRegistry = functionRegistry.inherit();
+ }
+ catch (e) {
+ return callback(new LessError(e, imports, fileInfo.filename));
+ }
+ // If `i` is smaller than the `input.length - 1`,
+ // it means the parser wasn't able to parse the whole
+ // string, so we've got a parsing error.
+ //
+ // We try to extract a \n delimited string,
+ // showing the line where the parse error occurred.
+ // We split it up into two parts (the part which parsed,
+ // and the part which didn't), so we can color them differently.
+ var endInfo = parserInput.end();
+ if (!endInfo.isFinished) {
+ var message = endInfo.furthestPossibleErrorMessage;
+ if (!message) {
+ message = 'Unrecognised input';
+ if (endInfo.furthestChar === '}') {
+ message += '. Possibly missing opening \'{\'';
+ }
+ else if (endInfo.furthestChar === ')') {
+ message += '. Possibly missing opening \'(\'';
+ }
+ else if (endInfo.furthestReachedEnd) {
+ message += '. Possibly missing something';
+ }
+ }
+ error = new LessError({
+ type: 'Parse',
+ message: message,
+ index: endInfo.furthest,
+ filename: fileInfo.filename
+ }, imports);
+ }
+ var finish = function (e) {
+ e = error || e || imports.error;
+ if (e) {
+ if (!(e instanceof LessError)) {
+ e = new LessError(e, imports, fileInfo.filename);
+ }
+ return callback(e);
+ }
+ else {
+ return callback(null, root);
+ }
+ };
+ if (context.processImports !== false) {
+ new visitors.ImportVisitor(imports, finish)
+ .run(root);
+ }
+ else {
+ return finish();
+ }
+ },
+ //
+ // Here in, the parsing rules/functions
+ //
+ // The basic structure of the syntax tree generated is as follows:
+ //
+ // Ruleset -> Declaration -> Value -> Expression -> Entity
+ //
+ // Here's some Less code:
+ //
+ // .class {
+ // color: #fff;
+ // border: 1px solid #000;
+ // width: @w + 4px;
+ // > .child {...}
+ // }
+ //
+ // And here's what the parse tree might look like:
+ //
+ // Ruleset (Selector '.class', [
+ // Declaration ("color", Value ([Expression [Color #fff]]))
+ // Declaration ("border", Value ([Expression [Dimension 1px][Keyword "solid"][Color #000]]))
+ // Declaration ("width", Value ([Expression [Operation " + " [Variable "@w"][Dimension 4px]]]))
+ // Ruleset (Selector [Element '>', '.child'], [...])
+ // ])
+ //
+ // In general, most rules will try to parse a token with the `$re()` function, and if the return
+ // value is truly, will return a new node, of the relevant type. Sometimes, we need to check
+ // first, before parsing, that's when we use `peek()`.
+ //
+ parsers: parsers = {
+ //
+ // The `primary` rule is the *entry* and *exit* point of the parser.
+ // The rules here can appear at any level of the parse tree.
+ //
+ // The recursive nature of the grammar is an interplay between the `block`
+ // rule, which represents `{ ... }`, the `ruleset` rule, and this `primary` rule,
+ // as represented by this simplified grammar:
+ //
+ // primary → (ruleset | declaration)+
+ // ruleset → selector+ block
+ // block → '{' primary '}'
+ //
+ // Only at one point is the primary rule not called from the
+ // block rule: at the root level.
+ //
+ primary: function () {
+ var mixin = this.mixin;
+ var root = [];
+ var node;
+ while (true) {
+ while (true) {
+ node = this.comment();
+ if (!node) {
+ break;
+ }
+ root.push(node);
+ }
+ // always process comments before deciding if finished
+ if (parserInput.finished) {
+ break;
+ }
+ if (parserInput.peek('}')) {
+ break;
+ }
+ node = this.extendRule();
+ if (node) {
+ root = root.concat(node);
+ continue;
+ }
+ node = mixin.definition() || this.declaration() || mixin.call(false, false) ||
+ this.ruleset() || this.variableCall() || this.entities.call() || this.atrule();
+ if (node) {
+ root.push(node);
+ }
+ else {
+ var foundSemiColon = false;
+ while (parserInput.$char(';')) {
+ foundSemiColon = true;
+ }
+ if (!foundSemiColon) {
+ break;
+ }
+ }
+ }
+ return root;
+ },
+ // comments are collected by the main parsing mechanism and then assigned to nodes
+ // where the current structure allows it
+ comment: function () {
+ if (parserInput.commentStore.length) {
+ var comment = parserInput.commentStore.shift();
+ return new (tree.Comment)(comment.text, comment.isLineComment, comment.index, fileInfo);
+ }
+ },
+ //
+ // Entities are tokens which can be found inside an Expression
+ //
+ entities: {
+ mixinLookup: function () {
+ return parsers.mixin.call(true, true);
+ },
+ //
+ // A string, which supports escaping " and '
+ //
+ // "milky way" 'he\'s the one!'
+ //
+ quoted: function (forceEscaped) {
+ var str;
+ var index = parserInput.i;
+ var isEscaped = false;
+ parserInput.save();
+ if (parserInput.$char('~')) {
+ isEscaped = true;
+ }
+ else if (forceEscaped) {
+ parserInput.restore();
+ return;
+ }
+ str = parserInput.$quoted();
+ if (!str) {
+ parserInput.restore();
+ return;
+ }
+ parserInput.forget();
+ return new (tree.Quoted)(str.charAt(0), str.substr(1, str.length - 2), isEscaped, index, fileInfo);
+ },
+ //
+ // A catch-all word, such as:
+ //
+ // black border-collapse
+ //
+ keyword: function () {
+ var k = parserInput.$char('%') || parserInput.$re(/^\[?(?:[\w-]|\\(?:[A-Fa-f0-9]{1,6} ?|[^A-Fa-f0-9]))+\]?/);
+ if (k) {
+ return tree.Color.fromKeyword(k) || new (tree.Keyword)(k);
+ }
+ },
+ //
+ // A function call
+ //
+ // rgb(255, 0, 255)
+ //
+ // The arguments are parsed with the `entities.arguments` parser.
+ //
+ call: function () {
+ var name;
+ var args;
+ var func;
+ var index = parserInput.i;
+ // http://jsperf.com/case-insensitive-regex-vs-strtolower-then-regex/18
+ if (parserInput.peek(/^url\(/i)) {
+ return;
+ }
+ parserInput.save();
+ name = parserInput.$re(/^([\w-]+|%|~|progid:[\w\.]+)\(/);
+ if (!name) {
+ parserInput.forget();
+ return;
+ }
+ name = name[1];
+ func = this.customFuncCall(name);
+ if (func) {
+ args = func.parse();
+ if (args && func.stop) {
+ parserInput.forget();
+ return args;
+ }
+ }
+ args = this.arguments(args);
+ if (!parserInput.$char(')')) {
+ parserInput.restore('Could not parse call arguments or missing \')\'');
+ return;
+ }
+ parserInput.forget();
+ return new (tree.Call)(name, args, index, fileInfo);
+ },
+ //
+ // Parsing rules for functions with non-standard args, e.g.:
+ //
+ // boolean(not(2 > 1))
+ //
+ // This is a quick prototype, to be modified/improved when
+ // more custom-parsed funcs come (e.g. `selector(...)`)
+ //
+ customFuncCall: function (name) {
+ /* Ideally the table is to be moved out of here for faster perf.,
+ but it's quite tricky since it relies on all these `parsers`
+ and `expect` available only here */
+ return {
+ alpha: f(parsers.ieAlpha, true),
+ boolean: f(condition),
+ 'if': f(condition)
+ }[name.toLowerCase()];
+ function f(parse, stop) {
+ return {
+ parse: parse,
+ stop: stop // when true - stop after parse() and return its result,
+ // otherwise continue for plain args
+ };
+ }
+ function condition() {
+ return [expect(parsers.condition, 'expected condition')];
+ }
+ },
+ arguments: function (prevArgs) {
+ var argsComma = prevArgs || [];
+ var argsSemiColon = [];
+ var isSemiColonSeparated;
+ var value;
+ parserInput.save();
+ while (true) {
+ if (prevArgs) {
+ prevArgs = false;
+ }
+ else {
+ value = parsers.detachedRuleset() || this.assignment() || parsers.expression();
+ if (!value) {
+ break;
+ }
+ if (value.value && value.value.length == 1) {
+ value = value.value[0];
+ }
+ argsComma.push(value);
+ }
+ if (parserInput.$char(',')) {
+ continue;
+ }
+ if (parserInput.$char(';') || isSemiColonSeparated) {
+ isSemiColonSeparated = true;
+ value = (argsComma.length < 1) ? argsComma[0]
+ : new tree.Value(argsComma);
+ argsSemiColon.push(value);
+ argsComma = [];
+ }
+ }
+ parserInput.forget();
+ return isSemiColonSeparated ? argsSemiColon : argsComma;
+ },
+ literal: function () {
+ return this.dimension() ||
+ this.color() ||
+ this.quoted() ||
+ this.unicodeDescriptor();
+ },
+ // Assignments are argument entities for calls.
+ // They are present in ie filter properties as shown below.
+ //
+ // filter: progid:DXImageTransform.Microsoft.Alpha( *opacity=50* )
+ //
+ assignment: function () {
+ var key;
+ var value;
+ parserInput.save();
+ key = parserInput.$re(/^\w+(?=\s?=)/i);
+ if (!key) {
+ parserInput.restore();
+ return;
+ }
+ if (!parserInput.$char('=')) {
+ parserInput.restore();
+ return;
+ }
+ value = parsers.entity();
+ if (value) {
+ parserInput.forget();
+ return new (tree.Assignment)(key, value);
+ }
+ else {
+ parserInput.restore();
+ }
+ },
+ //
+ // Parse url() tokens
+ //
+ // We use a specific rule for urls, because they don't really behave like
+ // standard function calls. The difference is that the argument doesn't have
+ // to be enclosed within a string, so it can't be parsed as an Expression.
+ //
+ url: function () {
+ var value;
+ var index = parserInput.i;
+ parserInput.autoCommentAbsorb = false;
+ if (!parserInput.$str('url(')) {
+ parserInput.autoCommentAbsorb = true;
+ return;
+ }
+ value = this.quoted() || this.variable() || this.property() ||
+ parserInput.$re(/^(?:(?:\\[\(\)'"])|[^\(\)'"])+/) || '';
+ parserInput.autoCommentAbsorb = true;
+ expectChar(')');
+ return new (tree.URL)((value.value != null ||
+ value instanceof tree.Variable ||
+ value instanceof tree.Property) ?
+ value : new (tree.Anonymous)(value, index), index, fileInfo);
+ },
+ //
+ // A Variable entity, such as `@fink`, in
+ //
+ // width: @fink + 2px
+ //
+ // We use a different parser for variable definitions,
+ // see `parsers.variable`.
+ //
+ variable: function () {
+ var ch;
+ var name;
+ var index = parserInput.i;
+ parserInput.save();
+ if (parserInput.currentChar() === '@' && (name = parserInput.$re(/^@@?[\w-]+/))) {
+ ch = parserInput.currentChar();
+ if (ch === '(' || ch === '[' && !parserInput.prevChar().match(/^\s/)) {
+ // this may be a VariableCall lookup
+ var result = parsers.variableCall(name);
+ if (result) {
+ parserInput.forget();
+ return result;
+ }
+ }
+ parserInput.forget();
+ return new (tree.Variable)(name, index, fileInfo);
+ }
+ parserInput.restore();
+ },
+ // A variable entity using the protective {} e.g. @{var}
+ variableCurly: function () {
+ var curly;
+ var index = parserInput.i;
+ if (parserInput.currentChar() === '@' && (curly = parserInput.$re(/^@\{([\w-]+)\}/))) {
+ return new (tree.Variable)("@" + curly[1], index, fileInfo);
+ }
+ },
+ //
+ // A Property accessor, such as `$color`, in
+ //
+ // background-color: $color
+ //
+ property: function () {
+ var name;
+ var index = parserInput.i;
+ if (parserInput.currentChar() === '$' && (name = parserInput.$re(/^\$[\w-]+/))) {
+ return new (tree.Property)(name, index, fileInfo);
+ }
+ },
+ // A property entity useing the protective {} e.g. ${prop}
+ propertyCurly: function () {
+ var curly;
+ var index = parserInput.i;
+ if (parserInput.currentChar() === '$' && (curly = parserInput.$re(/^\$\{([\w-]+)\}/))) {
+ return new (tree.Property)("$" + curly[1], index, fileInfo);
+ }
+ },
+ //
+ // A Hexadecimal color
+ //
+ // #4F3C2F
+ //
+ // `rgb` and `hsl` colors are parsed through the `entities.call` parser.
+ //
+ color: function () {
+ var rgb;
+ parserInput.save();
+ if (parserInput.currentChar() === '#' && (rgb = parserInput.$re(/^#([A-Fa-f0-9]{8}|[A-Fa-f0-9]{6}|[A-Fa-f0-9]{3,4})([\w.#\[])?/))) {
+ if (!rgb[2]) {
+ parserInput.forget();
+ return new (tree.Color)(rgb[1], undefined, rgb[0]);
+ }
+ }
+ parserInput.restore();
+ },
+ colorKeyword: function () {
+ parserInput.save();
+ var autoCommentAbsorb = parserInput.autoCommentAbsorb;
+ parserInput.autoCommentAbsorb = false;
+ var k = parserInput.$re(/^[_A-Za-z-][_A-Za-z0-9-]+/);
+ parserInput.autoCommentAbsorb = autoCommentAbsorb;
+ if (!k) {
+ parserInput.forget();
+ return;
+ }
+ parserInput.restore();
+ var color = tree.Color.fromKeyword(k);
+ if (color) {
+ parserInput.$str(k);
+ return color;
+ }
+ },
+ //
+ // A Dimension, that is, a number and a unit
+ //
+ // 0.5em 95%
+ //
+ dimension: function () {
+ if (parserInput.peekNotNumeric()) {
+ return;
+ }
+ var value = parserInput.$re(/^([+-]?\d*\.?\d+)(%|[a-z_]+)?/i);
+ if (value) {
+ return new (tree.Dimension)(value[1], value[2]);
+ }
+ },
+ //
+ // A unicode descriptor, as is used in unicode-range
+ //
+ // U+0?? or U+00A1-00A9
+ //
+ unicodeDescriptor: function () {
+ var ud;
+ ud = parserInput.$re(/^U\+[0-9a-fA-F?]+(\-[0-9a-fA-F?]+)?/);
+ if (ud) {
+ return new (tree.UnicodeDescriptor)(ud[0]);
+ }
+ },
+ //
+ // JavaScript code to be evaluated
+ //
+ // `window.location.href`
+ //
+ javascript: function () {
+ var js;
+ var index = parserInput.i;
+ parserInput.save();
+ var escape = parserInput.$char('~');
+ var jsQuote = parserInput.$char('`');
+ if (!jsQuote) {
+ parserInput.restore();
+ return;
+ }
+ js = parserInput.$re(/^[^`]*`/);
+ if (js) {
+ parserInput.forget();
+ return new (tree.JavaScript)(js.substr(0, js.length - 1), Boolean(escape), index, fileInfo);
+ }
+ parserInput.restore('invalid javascript definition');
+ }
+ },
+ //
+ // The variable part of a variable definition. Used in the `rule` parser
+ //
+ // @fink:
+ //
+ variable: function () {
+ var name;
+ if (parserInput.currentChar() === '@' && (name = parserInput.$re(/^(@[\w-]+)\s*:/))) {
+ return name[1];
+ }
+ },
+ //
+ // Call a variable value to retrieve a detached ruleset
+ // or a value from a detached ruleset's rules.
+ //
+ // @fink();
+ // @fink;
+ // color: @fink[@color];
+ //
+ variableCall: function (parsedName) {
+ var lookups;
+ var i = parserInput.i;
+ var inValue = !!parsedName;
+ var name = parsedName;
+ parserInput.save();
+ if (name || (parserInput.currentChar() === '@'
+ && (name = parserInput.$re(/^(@[\w-]+)(\(\s*\))?/)))) {
+ lookups = this.mixin.ruleLookups();
+ if (!lookups && ((inValue && parserInput.$str('()') !== '()') || (name[2] !== '()'))) {
+ parserInput.restore('Missing \'[...]\' lookup in variable call');
+ return;
+ }
+ if (!inValue) {
+ name = name[1];
+ }
+ var call = new tree.VariableCall(name, i, fileInfo);
+ if (!inValue && parsers.end()) {
+ parserInput.forget();
+ return call;
+ }
+ else {
+ parserInput.forget();
+ return new tree.NamespaceValue(call, lookups, i, fileInfo);
+ }
+ }
+ parserInput.restore();
+ },
+ //
+ // extend syntax - used to extend selectors
+ //
+ extend: function (isRule) {
+ var elements;
+ var e;
+ var index = parserInput.i;
+ var option;
+ var extendList;
+ var extend;
+ if (!parserInput.$str(isRule ? '&:extend(' : ':extend(')) {
+ return;
+ }
+ do {
+ option = null;
+ elements = null;
+ while (!(option = parserInput.$re(/^(all)(?=\s*(\)|,))/))) {
+ e = this.element();
+ if (!e) {
+ break;
+ }
+ if (elements) {
+ elements.push(e);
+ }
+ else {
+ elements = [e];
+ }
+ }
+ option = option && option[1];
+ if (!elements) {
+ error('Missing target selector for :extend().');
+ }
+ extend = new (tree.Extend)(new (tree.Selector)(elements), option, index, fileInfo);
+ if (extendList) {
+ extendList.push(extend);
+ }
+ else {
+ extendList = [extend];
+ }
+ } while (parserInput.$char(','));
+ expect(/^\)/);
+ if (isRule) {
+ expect(/^;/);
+ }
+ return extendList;
+ },
+ //
+ // extendRule - used in a rule to extend all the parent selectors
+ //
+ extendRule: function () {
+ return this.extend(true);
+ },
+ //
+ // Mixins
+ //
+ mixin: {
+ //
+ // A Mixin call, with an optional argument list
+ //
+ // #mixins > .square(#fff);
+ // #mixins.square(#fff);
+ // .rounded(4px, black);
+ // .button;
+ //
+ // We can lookup / return a value using the lookup syntax:
+ //
+ // color: #mixin.square(#fff)[@color];
+ //
+ // The `while` loop is there because mixins can be
+ // namespaced, but we only support the child and descendant
+ // selector for now.
+ //
+ call: function (inValue, getLookup) {
+ var s = parserInput.currentChar();
+ var important = false;
+ var lookups;
+ var index = parserInput.i;
+ var elements;
+ var args;
+ var hasParens;
+ if (s !== '.' && s !== '#') {
+ return;
+ }
+ parserInput.save(); // stop us absorbing part of an invalid selector
+ elements = this.elements();
+ if (elements) {
+ if (parserInput.$char('(')) {
+ args = this.args(true).args;
+ expectChar(')');
+ hasParens = true;
+ }
+ if (getLookup !== false) {
+ lookups = this.ruleLookups();
+ }
+ if (getLookup === true && !lookups) {
+ parserInput.restore();
+ return;
+ }
+ if (inValue && !lookups && !hasParens) {
+ // This isn't a valid in-value mixin call
+ parserInput.restore();
+ return;
+ }
+ if (!inValue && parsers.important()) {
+ important = true;
+ }
+ if (inValue || parsers.end()) {
+ parserInput.forget();
+ var mixin = new (tree.mixin.Call)(elements, args, index, fileInfo, !lookups && important);
+ if (lookups) {
+ return new tree.NamespaceValue(mixin, lookups);
+ }
+ else {
+ return mixin;
+ }
+ }
+ }
+ parserInput.restore();
+ },
+ /**
+ * Matching elements for mixins
+ * (Start with . or # and can have > )
+ */
+ elements: function () {
+ var elements;
+ var e;
+ var c;
+ var elem;
+ var elemIndex;
+ var re = /^[#.](?:[\w-]|\\(?:[A-Fa-f0-9]{1,6} ?|[^A-Fa-f0-9]))+/;
+ while (true) {
+ elemIndex = parserInput.i;
+ e = parserInput.$re(re);
+ if (!e) {
+ break;
+ }
+ elem = new (tree.Element)(c, e, false, elemIndex, fileInfo);
+ if (elements) {
+ elements.push(elem);
+ }
+ else {
+ elements = [elem];
+ }
+ c = parserInput.$char('>');
+ }
+ return elements;
+ },
+ args: function (isCall) {
+ var entities = parsers.entities;
+ var returner = { args: null, variadic: false };
+ var expressions = [];
+ var argsSemiColon = [];
+ var argsComma = [];
+ var isSemiColonSeparated;
+ var expressionContainsNamed;
+ var name;
+ var nameLoop;
+ var value;
+ var arg;
+ var expand;
+ var hasSep = true;
+ parserInput.save();
+ while (true) {
+ if (isCall) {
+ arg = parsers.detachedRuleset() || parsers.expression();
+ }
+ else {
+ parserInput.commentStore.length = 0;
+ if (parserInput.$str('...')) {
+ returner.variadic = true;
+ if (parserInput.$char(';') && !isSemiColonSeparated) {
+ isSemiColonSeparated = true;
+ }
+ (isSemiColonSeparated ? argsSemiColon : argsComma)
+ .push({ variadic: true });
+ break;
+ }
+ arg = entities.variable() || entities.property() || entities.literal() || entities.keyword() || this.call(true);
+ }
+ if (!arg || !hasSep) {
+ break;
+ }
+ nameLoop = null;
+ if (arg.throwAwayComments) {
+ arg.throwAwayComments();
+ }
+ value = arg;
+ var val = null;
+ if (isCall) {
+ // Variable
+ if (arg.value && arg.value.length == 1) {
+ val = arg.value[0];
+ }
+ }
+ else {
+ val = arg;
+ }
+ if (val && (val instanceof tree.Variable || val instanceof tree.Property)) {
+ if (parserInput.$char(':')) {
+ if (expressions.length > 0) {
+ if (isSemiColonSeparated) {
+ error('Cannot mix ; and , as delimiter types');
+ }
+ expressionContainsNamed = true;
+ }
+ value = parsers.detachedRuleset() || parsers.expression();
+ if (!value) {
+ if (isCall) {
+ error('could not understand value for named argument');
+ }
+ else {
+ parserInput.restore();
+ returner.args = [];
+ return returner;
+ }
+ }
+ nameLoop = (name = val.name);
+ }
+ else if (parserInput.$str('...')) {
+ if (!isCall) {
+ returner.variadic = true;
+ if (parserInput.$char(';') && !isSemiColonSeparated) {
+ isSemiColonSeparated = true;
+ }
+ (isSemiColonSeparated ? argsSemiColon : argsComma)
+ .push({ name: arg.name, variadic: true });
+ break;
+ }
+ else {
+ expand = true;
+ }
+ }
+ else if (!isCall) {
+ name = nameLoop = val.name;
+ value = null;
+ }
+ }
+ if (value) {
+ expressions.push(value);
+ }
+ argsComma.push({ name: nameLoop, value: value, expand: expand });
+ if (parserInput.$char(',')) {
+ hasSep = true;
+ continue;
+ }
+ hasSep = parserInput.$char(';') === ';';
+ if (hasSep || isSemiColonSeparated) {
+ if (expressionContainsNamed) {
+ error('Cannot mix ; and , as delimiter types');
+ }
+ isSemiColonSeparated = true;
+ if (expressions.length > 1) {
+ value = new (tree.Value)(expressions);
+ }
+ argsSemiColon.push({ name: name, value: value, expand: expand });
+ name = null;
+ expressions = [];
+ expressionContainsNamed = false;
+ }
+ }
+ parserInput.forget();
+ returner.args = isSemiColonSeparated ? argsSemiColon : argsComma;
+ return returner;
+ },
+ //
+ // A Mixin definition, with a list of parameters
+ //
+ // .rounded (@radius: 2px, @color) {
+ // ...
+ // }
+ //
+ // Until we have a finer grained state-machine, we have to
+ // do a look-ahead, to make sure we don't have a mixin call.
+ // See the `rule` function for more information.
+ //
+ // We start by matching `.rounded (`, and then proceed on to
+ // the argument list, which has optional default values.
+ // We store the parameters in `params`, with a `value` key,
+ // if there is a value, such as in the case of `@radius`.
+ //
+ // Once we've got our params list, and a closing `)`, we parse
+ // the `{...}` block.
+ //
+ definition: function () {
+ var name;
+ var params = [];
+ var match;
+ var ruleset;
+ var cond;
+ var variadic = false;
+ if ((parserInput.currentChar() !== '.' && parserInput.currentChar() !== '#') ||
+ parserInput.peek(/^[^{]*\}/)) {
+ return;
+ }
+ parserInput.save();
+ match = parserInput.$re(/^([#.](?:[\w-]|\\(?:[A-Fa-f0-9]{1,6} ?|[^A-Fa-f0-9]))+)\s*\(/);
+ if (match) {
+ name = match[1];
+ var argInfo = this.args(false);
+ params = argInfo.args;
+ variadic = argInfo.variadic;
+ // .mixincall("@{a}");
+ // looks a bit like a mixin definition..
+ // also
+ // .mixincall(@a: {rule: set;});
+ // so we have to be nice and restore
+ if (!parserInput.$char(')')) {
+ parserInput.restore('Missing closing \')\'');
+ return;
+ }
+ parserInput.commentStore.length = 0;
+ if (parserInput.$str('when')) { // Guard
+ cond = expect(parsers.conditions, 'expected condition');
+ }
+ ruleset = parsers.block();
+ if (ruleset) {
+ parserInput.forget();
+ return new (tree.mixin.Definition)(name, params, ruleset, cond, variadic);
+ }
+ else {
+ parserInput.restore();
+ }
+ }
+ else {
+ parserInput.restore();
+ }
+ },
+ ruleLookups: function () {
+ var rule;
+ var lookups = [];
+ if (parserInput.currentChar() !== '[') {
+ return;
+ }
+ while (true) {
+ parserInput.save();
+ rule = this.lookupValue();
+ if (!rule && rule !== '') {
+ parserInput.restore();
+ break;
+ }
+ lookups.push(rule);
+ parserInput.forget();
+ }
+ if (lookups.length > 0) {
+ return lookups;
+ }
+ },
+ lookupValue: function () {
+ parserInput.save();
+ if (!parserInput.$char('[')) {
+ parserInput.restore();
+ return;
+ }
+ var name = parserInput.$re(/^(?:[@$]{0,2})[_a-zA-Z0-9-]*/);
+ if (!parserInput.$char(']')) {
+ parserInput.restore();
+ return;
+ }
+ if (name || name === '') {
+ parserInput.forget();
+ return name;
+ }
+ parserInput.restore();
+ }
+ },
+ //
+ // Entities are the smallest recognized token,
+ // and can be found inside a rule's value.
+ //
+ entity: function () {
+ var entities = this.entities;
+ return this.comment() || entities.literal() || entities.variable() || entities.url() ||
+ entities.property() || entities.call() || entities.keyword() || this.mixin.call(true) ||
+ entities.javascript();
+ },
+ //
+ // A Declaration terminator. Note that we use `peek()` to check for '}',
+ // because the `block` rule will be expecting it, but we still need to make sure
+ // it's there, if ';' was omitted.
+ //
+ end: function () {
+ return parserInput.$char(';') || parserInput.peek('}');
+ },
+ //
+ // IE's alpha function
+ //
+ // alpha(opacity=88)
+ //
+ ieAlpha: function () {
+ var value;
+ // http://jsperf.com/case-insensitive-regex-vs-strtolower-then-regex/18
+ if (!parserInput.$re(/^opacity=/i)) {
+ return;
+ }
+ value = parserInput.$re(/^\d+/);
+ if (!value) {
+ value = expect(parsers.entities.variable, 'Could not parse alpha');
+ value = "@{" + value.name.slice(1) + "}";
+ }
+ expectChar(')');
+ return new tree.Quoted('', "alpha(opacity=" + value + ")");
+ },
+ //
+ // A Selector Element
+ //
+ // div
+ // + h1
+ // #socks
+ // input[type="text"]
+ //
+ // Elements are the building blocks for Selectors,
+ // they are made out of a `Combinator` (see combinator rule),
+ // and an element name, such as a tag a class, or `*`.
+ //
+ element: function () {
+ var e;
+ var c;
+ var v;
+ var index = parserInput.i;
+ c = this.combinator();
+ e = parserInput.$re(/^(?:\d+\.\d+|\d+)%/) ||
+ parserInput.$re(/^(?:[.#]?|:*)(?:[\w-]|[^\x00-\x9f]|\\(?:[A-Fa-f0-9]{1,6} ?|[^A-Fa-f0-9]))+/) ||
+ parserInput.$char('*') || parserInput.$char('&') || this.attribute() ||
+ parserInput.$re(/^\([^&()@]+\)/) || parserInput.$re(/^[\.#:](?=@)/) ||
+ this.entities.variableCurly();
+ if (!e) {
+ parserInput.save();
+ if (parserInput.$char('(')) {
+ if ((v = this.selector(false)) && parserInput.$char(')')) {
+ e = new (tree.Paren)(v);
+ parserInput.forget();
+ }
+ else {
+ parserInput.restore('Missing closing \')\'');
+ }
+ }
+ else {
+ parserInput.forget();
+ }
+ }
+ if (e) {
+ return new (tree.Element)(c, e, e instanceof tree.Variable, index, fileInfo);
+ }
+ },
+ //
+ // Combinators combine elements together, in a Selector.
+ //
+ // Because our parser isn't white-space sensitive, special care
+ // has to be taken, when parsing the descendant combinator, ` `,
+ // as it's an empty space. We have to check the previous character
+ // in the input, to see if it's a ` ` character. More info on how
+ // we deal with this in *combinator.js*.
+ //
+ combinator: function () {
+ var c = parserInput.currentChar();
+ if (c === '/') {
+ parserInput.save();
+ var slashedCombinator = parserInput.$re(/^\/[a-z]+\//i);
+ if (slashedCombinator) {
+ parserInput.forget();
+ return new (tree.Combinator)(slashedCombinator);
+ }
+ parserInput.restore();
+ }
+ if (c === '>' || c === '+' || c === '~' || c === '|' || c === '^') {
+ parserInput.i++;
+ if (c === '^' && parserInput.currentChar() === '^') {
+ c = '^^';
+ parserInput.i++;
+ }
+ while (parserInput.isWhitespace()) {
+ parserInput.i++;
+ }
+ return new (tree.Combinator)(c);
+ }
+ else if (parserInput.isWhitespace(-1)) {
+ return new (tree.Combinator)(' ');
+ }
+ else {
+ return new (tree.Combinator)(null);
+ }
+ },
+ //
+ // A CSS Selector
+ // with less extensions e.g. the ability to extend and guard
+ //
+ // .class > div + h1
+ // li a:hover
+ //
+ // Selectors are made out of one or more Elements, see above.
+ //
+ selector: function (isLess) {
+ var index = parserInput.i;
+ var elements;
+ var extendList;
+ var c;
+ var e;
+ var allExtends;
+ var when;
+ var condition;
+ isLess = isLess !== false;
+ while ((isLess && (extendList = this.extend())) || (isLess && (when = parserInput.$str('when'))) || (e = this.element())) {
+ if (when) {
+ condition = expect(this.conditions, 'expected condition');
+ }
+ else if (condition) {
+ error('CSS guard can only be used at the end of selector');
+ }
+ else if (extendList) {
+ if (allExtends) {
+ allExtends = allExtends.concat(extendList);
+ }
+ else {
+ allExtends = extendList;
+ }
+ }
+ else {
+ if (allExtends) {
+ error('Extend can only be used at the end of selector');
+ }
+ c = parserInput.currentChar();
+ if (elements) {
+ elements.push(e);
+ }
+ else {
+ elements = [e];
+ }
+ e = null;
+ }
+ if (c === '{' || c === '}' || c === ';' || c === ',' || c === ')') {
+ break;
+ }
+ }
+ if (elements) {
+ return new (tree.Selector)(elements, allExtends, condition, index, fileInfo);
+ }
+ if (allExtends) {
+ error('Extend must be used to extend a selector, it cannot be used on its own');
+ }
+ },
+ selectors: function () {
+ var s;
+ var selectors;
+ while (true) {
+ s = this.selector();
+ if (!s) {
+ break;
+ }
+ if (selectors) {
+ selectors.push(s);
+ }
+ else {
+ selectors = [s];
+ }
+ parserInput.commentStore.length = 0;
+ if (s.condition && selectors.length > 1) {
+ error("Guards are only currently allowed on a single selector.");
+ }
+ if (!parserInput.$char(',')) {
+ break;
+ }
+ if (s.condition) {
+ error("Guards are only currently allowed on a single selector.");
+ }
+ parserInput.commentStore.length = 0;
+ }
+ return selectors;
+ },
+ attribute: function () {
+ if (!parserInput.$char('[')) {
+ return;
+ }
+ var entities = this.entities;
+ var key;
+ var val;
+ var op;
+ if (!(key = entities.variableCurly())) {
+ key = expect(/^(?:[_A-Za-z0-9-\*]*\|)?(?:[_A-Za-z0-9-]|\\.)+/);
+ }
+ op = parserInput.$re(/^[|~*$^]?=/);
+ if (op) {
+ val = entities.quoted() || parserInput.$re(/^[0-9]+%/) || parserInput.$re(/^[\w-]+/) || entities.variableCurly();
+ }
+ expectChar(']');
+ return new (tree.Attribute)(key, op, val);
+ },
+ //
+ // The `block` rule is used by `ruleset` and `mixin.definition`.
+ // It's a wrapper around the `primary` rule, with added `{}`.
+ //
+ block: function () {
+ var content;
+ if (parserInput.$char('{') && (content = this.primary()) && parserInput.$char('}')) {
+ return content;
+ }
+ },
+ blockRuleset: function () {
+ var block = this.block();
+ if (block) {
+ block = new tree.Ruleset(null, block);
+ }
+ return block;
+ },
+ detachedRuleset: function () {
+ var argInfo;
+ var params;
+ var variadic;
+ parserInput.save();
+ if (parserInput.$re(/^[.#]\(/)) {
+ /**
+ * DR args currently only implemented for each() function, and not
+ * yet settable as `@dr: #(@arg) {}`
+ * This should be done when DRs are merged with mixins.
+ * See: https://github.com/less/less-meta/issues/16
+ */
+ argInfo = this.mixin.args(false);
+ params = argInfo.args;
+ variadic = argInfo.variadic;
+ if (!parserInput.$char(')')) {
+ parserInput.restore();
+ return;
+ }
+ }
+ var blockRuleset = this.blockRuleset();
+ if (blockRuleset) {
+ parserInput.forget();
+ if (params) {
+ return new tree.mixin.Definition(null, params, blockRuleset, null, variadic);
+ }
+ return new tree.DetachedRuleset(blockRuleset);
+ }
+ parserInput.restore();
+ },
+ //
+ // div, .class, body > p {...}
+ //
+ ruleset: function () {
+ var selectors;
+ var rules;
+ var debugInfo;
+ parserInput.save();
+ if (context.dumpLineNumbers) {
+ debugInfo = getDebugInfo(parserInput.i);
+ }
+ selectors = this.selectors();
+ if (selectors && (rules = this.block())) {
+ parserInput.forget();
+ var ruleset = new (tree.Ruleset)(selectors, rules, context.strictImports);
+ if (context.dumpLineNumbers) {
+ ruleset.debugInfo = debugInfo;
+ }
+ return ruleset;
+ }
+ else {
+ parserInput.restore();
+ }
+ },
+ declaration: function () {
+ var name;
+ var value;
+ var index = parserInput.i;
+ var hasDR;
+ var c = parserInput.currentChar();
+ var important;
+ var merge;
+ var isVariable;
+ if (c === '.' || c === '#' || c === '&' || c === ':') {
+ return;
+ }
+ parserInput.save();
+ name = this.variable() || this.ruleProperty();
+ if (name) {
+ isVariable = typeof name === 'string';
+ if (isVariable) {
+ value = this.detachedRuleset();
+ if (value) {
+ hasDR = true;
+ }
+ }
+ parserInput.commentStore.length = 0;
+ if (!value) {
+ // a name returned by this.ruleProperty() is always an array of the form:
+ // [string-1, ..., string-n, ""] or [string-1, ..., string-n, "+"]
+ // where each item is a tree.Keyword or tree.Variable
+ merge = !isVariable && name.length > 1 && name.pop().value;
+ // Custom property values get permissive parsing
+ if (name[0].value && name[0].value.slice(0, 2) === '--') {
+ value = this.permissiveValue();
+ }
+ // Try to store values as anonymous
+ // If we need the value later we'll re-parse it in ruleset.parseValue
+ else {
+ value = this.anonymousValue();
+ }
+ if (value) {
+ parserInput.forget();
+ // anonymous values absorb the end ';' which is required for them to work
+ return new (tree.Declaration)(name, value, false, merge, index, fileInfo);
+ }
+ if (!value) {
+ value = this.value();
+ }
+ if (value) {
+ important = this.important();
+ }
+ else if (isVariable) {
+ // As a last resort, try permissiveValue
+ value = this.permissiveValue();
+ }
+ }
+ if (value && (this.end() || hasDR)) {
+ parserInput.forget();
+ return new (tree.Declaration)(name, value, important, merge, index, fileInfo);
+ }
+ else {
+ parserInput.restore();
+ }
+ }
+ else {
+ parserInput.restore();
+ }
+ },
+ anonymousValue: function () {
+ var index = parserInput.i;
+ var match = parserInput.$re(/^([^.#@\$+\/'"*`(;{}-]*);/);
+ if (match) {
+ return new (tree.Anonymous)(match[1], index);
+ }
+ },
+ /**
+ * Used for custom properties, at-rules, and variables (as fallback)
+ * Parses almost anything inside of {} [] () "" blocks
+ * until it reaches outer-most tokens.
+ *
+ * First, it will try to parse comments and entities to reach
+ * the end. This is mostly like the Expression parser except no
+ * math is allowed.
+ */
+ permissiveValue: function (untilTokens) {
+ var i;
+ var e;
+ var done;
+ var value;
+ var tok = untilTokens || ';';
+ var index = parserInput.i;
+ var result = [];
+ function testCurrentChar() {
+ var char = parserInput.currentChar();
+ if (typeof tok === 'string') {
+ return char === tok;
+ }
+ else {
+ return tok.test(char);
+ }
+ }
+ if (testCurrentChar()) {
+ return;
+ }
+ value = [];
+ do {
+ e = this.comment();
+ if (e) {
+ value.push(e);
+ continue;
+ }
+ e = this.entity();
+ if (e) {
+ value.push(e);
+ }
+ } while (e);
+ done = testCurrentChar();
+ if (value.length > 0) {
+ value = new (tree.Expression)(value);
+ if (done) {
+ return value;
+ }
+ else {
+ result.push(value);
+ }
+ // Preserve space before $parseUntil as it will not
+ if (parserInput.prevChar() === ' ') {
+ result.push(new tree.Anonymous(' ', index));
+ }
+ }
+ parserInput.save();
+ value = parserInput.$parseUntil(tok);
+ if (value) {
+ if (typeof value === 'string') {
+ error("Expected '" + value + "'", 'Parse');
+ }
+ if (value.length === 1 && value[0] === ' ') {
+ parserInput.forget();
+ return new tree.Anonymous('', index);
+ }
+ var item = void 0;
+ for (i = 0; i < value.length; i++) {
+ item = value[i];
+ if (Array.isArray(item)) {
+ // Treat actual quotes as normal quoted values
+ result.push(new tree.Quoted(item[0], item[1], true, index, fileInfo));
+ }
+ else {
+ if (i === value.length - 1) {
+ item = item.trim();
+ }
+ // Treat like quoted values, but replace vars like unquoted expressions
+ var quote = new tree.Quoted('\'', item, true, index, fileInfo);
+ quote.variableRegex = /@([\w-]+)/g;
+ quote.propRegex = /\$([\w-]+)/g;
+ result.push(quote);
+ }
+ }
+ parserInput.forget();
+ return new tree.Expression(result, true);
+ }
+ parserInput.restore();
+ },
+ //
+ // An @import atrule
+ //
+ // @import "lib";
+ //
+ // Depending on our environment, importing is done differently:
+ // In the browser, it's an XHR request, in Node, it would be a
+ // file-system operation. The function used for importing is
+ // stored in `import`, which we pass to the Import constructor.
+ //
+ 'import': function () {
+ var path;
+ var features;
+ var index = parserInput.i;
+ var dir = parserInput.$re(/^@import?\s+/);
+ if (dir) {
+ var options = (dir ? this.importOptions() : null) || {};
+ if ((path = this.entities.quoted() || this.entities.url())) {
+ features = this.mediaFeatures();
+ if (!parserInput.$char(';')) {
+ parserInput.i = index;
+ error('missing semi-colon or unrecognised media features on import');
+ }
+ features = features && new (tree.Value)(features);
+ return new (tree.Import)(path, features, options, index, fileInfo);
+ }
+ else {
+ parserInput.i = index;
+ error('malformed import statement');
+ }
+ }
+ },
+ importOptions: function () {
+ var o;
+ var options = {};
+ var optionName;
+ var value;
+ // list of options, surrounded by parens
+ if (!parserInput.$char('(')) {
+ return null;
+ }
+ do {
+ o = this.importOption();
+ if (o) {
+ optionName = o;
+ value = true;
+ switch (optionName) {
+ case 'css':
+ optionName = 'less';
+ value = false;
+ break;
+ case 'once':
+ optionName = 'multiple';
+ value = false;
+ break;
+ }
+ options[optionName] = value;
+ if (!parserInput.$char(',')) {
+ break;
+ }
+ }
+ } while (o);
+ expectChar(')');
+ return options;
+ },
+ importOption: function () {
+ var opt = parserInput.$re(/^(less|css|multiple|once|inline|reference|optional)/);
+ if (opt) {
+ return opt[1];
+ }
+ },
+ mediaFeature: function () {
+ var entities = this.entities;
+ var nodes = [];
+ var e;
+ var p;
+ parserInput.save();
+ do {
+ e = entities.keyword() || entities.variable() || entities.mixinLookup();
+ if (e) {
+ nodes.push(e);
+ }
+ else if (parserInput.$char('(')) {
+ p = this.property();
+ e = this.value();
+ if (parserInput.$char(')')) {
+ if (p && e) {
+ nodes.push(new (tree.Paren)(new (tree.Declaration)(p, e, null, null, parserInput.i, fileInfo, true)));
+ }
+ else if (e) {
+ nodes.push(new (tree.Paren)(e));
+ }
+ else {
+ error('badly formed media feature definition');
+ }
+ }
+ else {
+ error('Missing closing \')\'', 'Parse');
+ }
+ }
+ } while (e);
+ parserInput.forget();
+ if (nodes.length > 0) {
+ return new (tree.Expression)(nodes);
+ }
+ },
+ mediaFeatures: function () {
+ var entities = this.entities;
+ var features = [];
+ var e;
+ do {
+ e = this.mediaFeature();
+ if (e) {
+ features.push(e);
+ if (!parserInput.$char(',')) {
+ break;
+ }
+ }
+ else {
+ e = entities.variable() || entities.mixinLookup();
+ if (e) {
+ features.push(e);
+ if (!parserInput.$char(',')) {
+ break;
+ }
+ }
+ }
+ } while (e);
+ return features.length > 0 ? features : null;
+ },
+ media: function () {
+ var features;
+ var rules;
+ var media;
+ var debugInfo;
+ var index = parserInput.i;
+ if (context.dumpLineNumbers) {
+ debugInfo = getDebugInfo(index);
+ }
+ parserInput.save();
+ if (parserInput.$str('@media')) {
+ features = this.mediaFeatures();
+ rules = this.block();
+ if (!rules) {
+ error('media definitions require block statements after any features');
+ }
+ parserInput.forget();
+ media = new (tree.Media)(rules, features, index, fileInfo);
+ if (context.dumpLineNumbers) {
+ media.debugInfo = debugInfo;
+ }
+ return media;
+ }
+ parserInput.restore();
+ },
+ //
+ // A @plugin directive, used to import plugins dynamically.
+ //
+ // @plugin (args) "lib";
+ //
+ plugin: function () {
+ var path;
+ var args;
+ var options;
+ var index = parserInput.i;
+ var dir = parserInput.$re(/^@plugin?\s+/);
+ if (dir) {
+ args = this.pluginArgs();
+ if (args) {
+ options = {
+ pluginArgs: args,
+ isPlugin: true
+ };
+ }
+ else {
+ options = { isPlugin: true };
+ }
+ if ((path = this.entities.quoted() || this.entities.url())) {
+ if (!parserInput.$char(';')) {
+ parserInput.i = index;
+ error('missing semi-colon on @plugin');
+ }
+ return new (tree.Import)(path, null, options, index, fileInfo);
+ }
+ else {
+ parserInput.i = index;
+ error('malformed @plugin statement');
+ }
+ }
+ },
+ pluginArgs: function () {
+ // list of options, surrounded by parens
+ parserInput.save();
+ if (!parserInput.$char('(')) {
+ parserInput.restore();
+ return null;
+ }
+ var args = parserInput.$re(/^\s*([^\);]+)\)\s*/);
+ if (args[1]) {
+ parserInput.forget();
+ return args[1].trim();
+ }
+ else {
+ parserInput.restore();
+ return null;
+ }
+ },
+ //
+ // A CSS AtRule
+ //
+ // @charset "utf-8";
+ //
+ atrule: function () {
+ var index = parserInput.i;
+ var name;
+ var value;
+ var rules;
+ var nonVendorSpecificName;
+ var hasIdentifier;
+ var hasExpression;
+ var hasUnknown;
+ var hasBlock = true;
+ var isRooted = true;
+ if (parserInput.currentChar() !== '@') {
+ return;
+ }
+ value = this['import']() || this.plugin() || this.media();
+ if (value) {
+ return value;
+ }
+ parserInput.save();
+ name = parserInput.$re(/^@[a-z-]+/);
+ if (!name) {
+ return;
+ }
+ nonVendorSpecificName = name;
+ if (name.charAt(1) == '-' && name.indexOf('-', 2) > 0) {
+ nonVendorSpecificName = "@" + name.slice(name.indexOf('-', 2) + 1);
+ }
+ switch (nonVendorSpecificName) {
+ case '@charset':
+ hasIdentifier = true;
+ hasBlock = false;
+ break;
+ case '@namespace':
+ hasExpression = true;
+ hasBlock = false;
+ break;
+ case '@keyframes':
+ case '@counter-style':
+ hasIdentifier = true;
+ break;
+ case '@document':
+ case '@supports':
+ hasUnknown = true;
+ isRooted = false;
+ break;
+ default:
+ hasUnknown = true;
+ break;
+ }
+ parserInput.commentStore.length = 0;
+ if (hasIdentifier) {
+ value = this.entity();
+ if (!value) {
+ error("expected " + name + " identifier");
+ }
+ }
+ else if (hasExpression) {
+ value = this.expression();
+ if (!value) {
+ error("expected " + name + " expression");
+ }
+ }
+ else if (hasUnknown) {
+ value = this.permissiveValue(/^[{;]/);
+ hasBlock = (parserInput.currentChar() === '{');
+ if (!value) {
+ if (!hasBlock && parserInput.currentChar() !== ';') {
+ error(name + " rule is missing block or ending semi-colon");
+ }
+ }
+ else if (!value.value) {
+ value = null;
+ }
+ }
+ if (hasBlock) {
+ rules = this.blockRuleset();
+ }
+ if (rules || (!hasBlock && value && parserInput.$char(';'))) {
+ parserInput.forget();
+ return new (tree.AtRule)(name, value, rules, index, fileInfo, context.dumpLineNumbers ? getDebugInfo(index) : null, isRooted);
+ }
+ parserInput.restore('at-rule options not recognised');
+ },
+ //
+ // A Value is a comma-delimited list of Expressions
+ //
+ // font-family: Baskerville, Georgia, serif;
+ //
+ // In a Rule, a Value represents everything after the `:`,
+ // and before the `;`.
+ //
+ value: function () {
+ var e;
+ var expressions = [];
+ var index = parserInput.i;
+ do {
+ e = this.expression();
+ if (e) {
+ expressions.push(e);
+ if (!parserInput.$char(',')) {
+ break;
+ }
+ }
+ } while (e);
+ if (expressions.length > 0) {
+ return new (tree.Value)(expressions, index);
+ }
+ },
+ important: function () {
+ if (parserInput.currentChar() === '!') {
+ return parserInput.$re(/^! *important/);
+ }
+ },
+ sub: function () {
+ var a;
+ var e;
+ parserInput.save();
+ if (parserInput.$char('(')) {
+ a = this.addition();
+ if (a && parserInput.$char(')')) {
+ parserInput.forget();
+ e = new (tree.Expression)([a]);
+ e.parens = true;
+ return e;
+ }
+ parserInput.restore('Expected \')\'');
+ return;
+ }
+ parserInput.restore();
+ },
+ multiplication: function () {
+ var m;
+ var a;
+ var op;
+ var operation;
+ var isSpaced;
+ m = this.operand();
+ if (m) {
+ isSpaced = parserInput.isWhitespace(-1);
+ while (true) {
+ if (parserInput.peek(/^\/[*\/]/)) {
+ break;
+ }
+ parserInput.save();
+ op = parserInput.$char('/') || parserInput.$char('*') || parserInput.$str('./');
+ if (!op) {
+ parserInput.forget();
+ break;
+ }
+ a = this.operand();
+ if (!a) {
+ parserInput.restore();
+ break;
+ }
+ parserInput.forget();
+ m.parensInOp = true;
+ a.parensInOp = true;
+ operation = new (tree.Operation)(op, [operation || m, a], isSpaced);
+ isSpaced = parserInput.isWhitespace(-1);
+ }
+ return operation || m;
+ }
+ },
+ addition: function () {
+ var m;
+ var a;
+ var op;
+ var operation;
+ var isSpaced;
+ m = this.multiplication();
+ if (m) {
+ isSpaced = parserInput.isWhitespace(-1);
+ while (true) {
+ op = parserInput.$re(/^[-+]\s+/) || (!isSpaced && (parserInput.$char('+') || parserInput.$char('-')));
+ if (!op) {
+ break;
+ }
+ a = this.multiplication();
+ if (!a) {
+ break;
+ }
+ m.parensInOp = true;
+ a.parensInOp = true;
+ operation = new (tree.Operation)(op, [operation || m, a], isSpaced);
+ isSpaced = parserInput.isWhitespace(-1);
+ }
+ return operation || m;
+ }
+ },
+ conditions: function () {
+ var a;
+ var b;
+ var index = parserInput.i;
+ var condition;
+ a = this.condition(true);
+ if (a) {
+ while (true) {
+ if (!parserInput.peek(/^,\s*(not\s*)?\(/) || !parserInput.$char(',')) {
+ break;
+ }
+ b = this.condition(true);
+ if (!b) {
+ break;
+ }
+ condition = new (tree.Condition)('or', condition || a, b, index);
+ }
+ return condition || a;
+ }
+ },
+ condition: function (needsParens) {
+ var result;
+ var logical;
+ var next;
+ function or() {
+ return parserInput.$str('or');
+ }
+ result = this.conditionAnd(needsParens);
+ if (!result) {
+ return;
+ }
+ logical = or();
+ if (logical) {
+ next = this.condition(needsParens);
+ if (next) {
+ result = new (tree.Condition)(logical, result, next);
+ }
+ else {
+ return;
+ }
+ }
+ return result;
+ },
+ conditionAnd: function (needsParens) {
+ var result;
+ var logical;
+ var next;
+ var self = this;
+ function insideCondition() {
+ var cond = self.negatedCondition(needsParens) || self.parenthesisCondition(needsParens);
+ if (!cond && !needsParens) {
+ return self.atomicCondition(needsParens);
+ }
+ return cond;
+ }
+ function and() {
+ return parserInput.$str('and');
+ }
+ result = insideCondition();
+ if (!result) {
+ return;
+ }
+ logical = and();
+ if (logical) {
+ next = this.conditionAnd(needsParens);
+ if (next) {
+ result = new (tree.Condition)(logical, result, next);
+ }
+ else {
+ return;
+ }
+ }
+ return result;
+ },
+ negatedCondition: function (needsParens) {
+ if (parserInput.$str('not')) {
+ var result = this.parenthesisCondition(needsParens);
+ if (result) {
+ result.negate = !result.negate;
+ }
+ return result;
+ }
+ },
+ parenthesisCondition: function (needsParens) {
+ function tryConditionFollowedByParenthesis(me) {
+ var body;
+ parserInput.save();
+ body = me.condition(needsParens);
+ if (!body) {
+ parserInput.restore();
+ return;
+ }
+ if (!parserInput.$char(')')) {
+ parserInput.restore();
+ return;
+ }
+ parserInput.forget();
+ return body;
+ }
+ var body;
+ parserInput.save();
+ if (!parserInput.$str('(')) {
+ parserInput.restore();
+ return;
+ }
+ body = tryConditionFollowedByParenthesis(this);
+ if (body) {
+ parserInput.forget();
+ return body;
+ }
+ body = this.atomicCondition(needsParens);
+ if (!body) {
+ parserInput.restore();
+ return;
+ }
+ if (!parserInput.$char(')')) {
+ parserInput.restore("expected ')' got '" + parserInput.currentChar() + "'");
+ return;
+ }
+ parserInput.forget();
+ return body;
+ },
+ atomicCondition: function (needsParens) {
+ var entities = this.entities;
+ var index = parserInput.i;
+ var a;
+ var b;
+ var c;
+ var op;
+ function cond() {
+ return this.addition() || entities.keyword() || entities.quoted() || entities.mixinLookup();
+ }
+ cond = cond.bind(this);
+ a = cond();
+ if (a) {
+ if (parserInput.$char('>')) {
+ if (parserInput.$char('=')) {
+ op = '>=';
+ }
+ else {
+ op = '>';
+ }
+ }
+ else if (parserInput.$char('<')) {
+ if (parserInput.$char('=')) {
+ op = '<=';
+ }
+ else {
+ op = '<';
+ }
+ }
+ else if (parserInput.$char('=')) {
+ if (parserInput.$char('>')) {
+ op = '=>';
+ }
+ else if (parserInput.$char('<')) {
+ op = '=<';
+ }
+ else {
+ op = '=';
+ }
+ }
+ if (op) {
+ b = cond();
+ if (b) {
+ c = new (tree.Condition)(op, a, b, index, false);
+ }
+ else {
+ error('expected expression');
+ }
+ }
+ else {
+ c = new (tree.Condition)('=', a, new (tree.Keyword)('true'), index, false);
+ }
+ return c;
+ }
+ },
+ //
+ // An operand is anything that can be part of an operation,
+ // such as a Color, or a Variable
+ //
+ operand: function () {
+ var entities = this.entities;
+ var negate;
+ if (parserInput.peek(/^-[@\$\(]/)) {
+ negate = parserInput.$char('-');
+ }
+ var o = this.sub() || entities.dimension() ||
+ entities.color() || entities.variable() ||
+ entities.property() || entities.call() ||
+ entities.quoted(true) || entities.colorKeyword() ||
+ entities.mixinLookup();
+ if (negate) {
+ o.parensInOp = true;
+ o = new (tree.Negative)(o);
+ }
+ return o;
+ },
+ //
+ // Expressions either represent mathematical operations,
+ // or white-space delimited Entities.
+ //
+ // 1px solid black
+ // @var * 2
+ //
+ expression: function () {
+ var entities = [];
+ var e;
+ var delim;
+ var index = parserInput.i;
+ do {
+ e = this.comment();
+ if (e) {
+ entities.push(e);
+ continue;
+ }
+ e = this.addition() || this.entity();
+ if (e instanceof tree.Comment) {
+ e = null;
+ }
+ if (e) {
+ entities.push(e);
+ // operations do not allow keyword "/" dimension (e.g. small/20px) so we support that here
+ if (!parserInput.peek(/^\/[\/*]/)) {
+ delim = parserInput.$char('/');
+ if (delim) {
+ entities.push(new (tree.Anonymous)(delim, index));
+ }
+ }
+ }
+ } while (e);
+ if (entities.length > 0) {
+ return new (tree.Expression)(entities);
+ }
+ },
+ property: function () {
+ var name = parserInput.$re(/^(\*?-?[_a-zA-Z0-9-]+)\s*:/);
+ if (name) {
+ return name[1];
+ }
+ },
+ ruleProperty: function () {
+ var name = [];
+ var index = [];
+ var s;
+ var k;
+ parserInput.save();
+ var simpleProperty = parserInput.$re(/^([_a-zA-Z0-9-]+)\s*:/);
+ if (simpleProperty) {
+ name = [new (tree.Keyword)(simpleProperty[1])];
+ parserInput.forget();
+ return name;
+ }
+ function match(re) {
+ var i = parserInput.i;
+ var chunk = parserInput.$re(re);
+ if (chunk) {
+ index.push(i);
+ return name.push(chunk[1]);
+ }
+ }
+ match(/^(\*?)/);
+ while (true) {
+ if (!match(/^((?:[\w-]+)|(?:[@\$]\{[\w-]+\}))/)) {
+ break;
+ }
+ }
+ if ((name.length > 1) && match(/^((?:\+_|\+)?)\s*:/)) {
+ parserInput.forget();
+ // at last, we have the complete match now. move forward,
+ // convert name particles to tree objects and return:
+ if (name[0] === '') {
+ name.shift();
+ index.shift();
+ }
+ for (k = 0; k < name.length; k++) {
+ s = name[k];
+ name[k] = (s.charAt(0) !== '@' && s.charAt(0) !== '$') ?
+ new (tree.Keyword)(s) :
+ (s.charAt(0) === '@' ?
+ new (tree.Variable)("@" + s.slice(2, -1), index[k], fileInfo) :
+ new (tree.Property)("$" + s.slice(2, -1), index[k], fileInfo));
+ }
+ return name;
+ }
+ parserInput.restore();
+ }
+ }
+ };
+ };
+ Parser.serializeVars = function (vars) {
+ var s = '';
+ for (var name_1 in vars) {
+ if (Object.hasOwnProperty.call(vars, name_1)) {
+ var value = vars[name_1];
+ s += ((name_1[0] === '@') ? '' : '@') + name_1 + ": " + value + ((String(value).slice(-1) === ';') ? '' : ';');
+ }
+ }
+ return s;
+ };
+
+ function boolean(condition) {
+ return condition ? Keyword.True : Keyword.False;
+ }
+ /**
+ * Functions with evalArgs set to false are sent context
+ * as the first argument.
+ */
+ function If(context, condition, trueValue, falseValue) {
+ return condition.eval(context) ? trueValue.eval(context)
+ : (falseValue ? falseValue.eval(context) : new Anonymous);
+ }
+ If.evalArgs = false;
+ function isdefined(context, variable) {
+ try {
+ variable.eval(context);
+ return Keyword.True;
+ }
+ catch (e) {
+ return Keyword.False;
+ }
+ }
+ isdefined.evalArgs = false;
+ var boolean$1 = { isdefined: isdefined, boolean: boolean, 'if': If };
+
+ var colorFunctions;
+ function clamp(val) {
+ return Math.min(1, Math.max(0, val));
+ }
+ function hsla(origColor, hsl) {
+ var color = colorFunctions.hsla(hsl.h, hsl.s, hsl.l, hsl.a);
+ if (color) {
+ if (origColor.value &&
+ /^(rgb|hsl)/.test(origColor.value)) {
+ color.value = origColor.value;
+ }
+ else {
+ color.value = 'rgb';
+ }
+ return color;
+ }
+ }
+ function toHSL(color) {
+ if (color.toHSL) {
+ return color.toHSL();
+ }
+ else {
+ throw new Error('Argument cannot be evaluated to a color');
+ }
+ }
+ function toHSV(color) {
+ if (color.toHSV) {
+ return color.toHSV();
+ }
+ else {
+ throw new Error('Argument cannot be evaluated to a color');
+ }
+ }
+ function number$1(n) {
+ if (n instanceof Dimension) {
+ return parseFloat(n.unit.is('%') ? n.value / 100 : n.value);
+ }
+ else if (typeof n === 'number') {
+ return n;
+ }
+ else {
+ throw {
+ type: 'Argument',
+ message: 'color functions take numbers as parameters'
+ };
+ }
+ }
+ function scaled(n, size) {
+ if (n instanceof Dimension && n.unit.is('%')) {
+ return parseFloat(n.value * size / 100);
+ }
+ else {
+ return number$1(n);
+ }
+ }
+ colorFunctions = {
+ rgb: function (r, g, b) {
+ var a = 1;
+ /**
+ * Comma-less syntax
+ * e.g. rgb(0 128 255 / 50%)
+ */
+ if (r instanceof Expression) {
+ var val = r.value;
+ r = val[0];
+ g = val[1];
+ b = val[2];
+ /**
+ * @todo - should this be normalized in
+ * function caller? Or parsed differently?
+ */
+ if (b instanceof Operation) {
+ var op = b;
+ b = op.operands[0];
+ a = op.operands[1];
+ }
+ }
+ var color = colorFunctions.rgba(r, g, b, a);
+ if (color) {
+ color.value = 'rgb';
+ return color;
+ }
+ },
+ rgba: function (r, g, b, a) {
+ try {
+ if (r instanceof Color) {
+ if (g) {
+ a = number$1(g);
+ }
+ else {
+ a = r.alpha;
+ }
+ return new Color(r.rgb, a, 'rgba');
+ }
+ var rgb = [r, g, b].map(function (c) { return scaled(c, 255); });
+ a = number$1(a);
+ return new Color(rgb, a, 'rgba');
+ }
+ catch (e) { }
+ },
+ hsl: function (h, s, l) {
+ var a = 1;
+ if (h instanceof Expression) {
+ var val = h.value;
+ h = val[0];
+ s = val[1];
+ l = val[2];
+ if (l instanceof Operation) {
+ var op = l;
+ l = op.operands[0];
+ a = op.operands[1];
+ }
+ }
+ var color = colorFunctions.hsla(h, s, l, a);
+ if (color) {
+ color.value = 'hsl';
+ return color;
+ }
+ },
+ hsla: function (h, s, l, a) {
+ try {
+ if (h instanceof Color) {
+ if (s) {
+ a = number$1(s);
+ }
+ else {
+ a = h.alpha;
+ }
+ return new Color(h.rgb, a, 'hsla');
+ }
+ var m1_1;
+ var m2_1;
+ function hue(h) {
+ h = h < 0 ? h + 1 : (h > 1 ? h - 1 : h);
+ if (h * 6 < 1) {
+ return m1_1 + (m2_1 - m1_1) * h * 6;
+ }
+ else if (h * 2 < 1) {
+ return m2_1;
+ }
+ else if (h * 3 < 2) {
+ return m1_1 + (m2_1 - m1_1) * (2 / 3 - h) * 6;
+ }
+ else {
+ return m1_1;
+ }
+ }
+ h = (number$1(h) % 360) / 360;
+ s = clamp(number$1(s));
+ l = clamp(number$1(l));
+ a = clamp(number$1(a));
+ m2_1 = l <= 0.5 ? l * (s + 1) : l + s - l * s;
+ m1_1 = l * 2 - m2_1;
+ var rgb = [
+ hue(h + 1 / 3) * 255,
+ hue(h) * 255,
+ hue(h - 1 / 3) * 255
+ ];
+ a = number$1(a);
+ return new Color(rgb, a, 'hsla');
+ }
+ catch (e) { }
+ },
+ hsv: function (h, s, v) {
+ return colorFunctions.hsva(h, s, v, 1.0);
+ },
+ hsva: function (h, s, v, a) {
+ h = ((number$1(h) % 360) / 360) * 360;
+ s = number$1(s);
+ v = number$1(v);
+ a = number$1(a);
+ var i;
+ var f;
+ i = Math.floor((h / 60) % 6);
+ f = (h / 60) - i;
+ var vs = [v,
+ v * (1 - s),
+ v * (1 - f * s),
+ v * (1 - (1 - f) * s)];
+ var perm = [[0, 3, 1],
+ [2, 0, 1],
+ [1, 0, 3],
+ [1, 2, 0],
+ [3, 1, 0],
+ [0, 1, 2]];
+ return colorFunctions.rgba(vs[perm[i][0]] * 255, vs[perm[i][1]] * 255, vs[perm[i][2]] * 255, a);
+ },
+ hue: function (color) {
+ return new Dimension(toHSL(color).h);
+ },
+ saturation: function (color) {
+ return new Dimension(toHSL(color).s * 100, '%');
+ },
+ lightness: function (color) {
+ return new Dimension(toHSL(color).l * 100, '%');
+ },
+ hsvhue: function (color) {
+ return new Dimension(toHSV(color).h);
+ },
+ hsvsaturation: function (color) {
+ return new Dimension(toHSV(color).s * 100, '%');
+ },
+ hsvvalue: function (color) {
+ return new Dimension(toHSV(color).v * 100, '%');
+ },
+ red: function (color) {
+ return new Dimension(color.rgb[0]);
+ },
+ green: function (color) {
+ return new Dimension(color.rgb[1]);
+ },
+ blue: function (color) {
+ return new Dimension(color.rgb[2]);
+ },
+ alpha: function (color) {
+ return new Dimension(toHSL(color).a);
+ },
+ luma: function (color) {
+ return new Dimension(color.luma() * color.alpha * 100, '%');
+ },
+ luminance: function (color) {
+ var luminance = (0.2126 * color.rgb[0] / 255) +
+ (0.7152 * color.rgb[1] / 255) +
+ (0.0722 * color.rgb[2] / 255);
+ return new Dimension(luminance * color.alpha * 100, '%');
+ },
+ saturate: function (color, amount, method) {
+ // filter: saturate(3.2);
+ // should be kept as is, so check for color
+ if (!color.rgb) {
+ return null;
+ }
+ var hsl = toHSL(color);
+ if (typeof method !== 'undefined' && method.value === 'relative') {
+ hsl.s += hsl.s * amount.value / 100;
+ }
+ else {
+ hsl.s += amount.value / 100;
+ }
+ hsl.s = clamp(hsl.s);
+ return hsla(color, hsl);
+ },
+ desaturate: function (color, amount, method) {
+ var hsl = toHSL(color);
+ if (typeof method !== 'undefined' && method.value === 'relative') {
+ hsl.s -= hsl.s * amount.value / 100;
+ }
+ else {
+ hsl.s -= amount.value / 100;
+ }
+ hsl.s = clamp(hsl.s);
+ return hsla(color, hsl);
+ },
+ lighten: function (color, amount, method) {
+ var hsl = toHSL(color);
+ if (typeof method !== 'undefined' && method.value === 'relative') {
+ hsl.l += hsl.l * amount.value / 100;
+ }
+ else {
+ hsl.l += amount.value / 100;
+ }
+ hsl.l = clamp(hsl.l);
+ return hsla(color, hsl);
+ },
+ darken: function (color, amount, method) {
+ var hsl = toHSL(color);
+ if (typeof method !== 'undefined' && method.value === 'relative') {
+ hsl.l -= hsl.l * amount.value / 100;
+ }
+ else {
+ hsl.l -= amount.value / 100;
+ }
+ hsl.l = clamp(hsl.l);
+ return hsla(color, hsl);
+ },
+ fadein: function (color, amount, method) {
+ var hsl = toHSL(color);
+ if (typeof method !== 'undefined' && method.value === 'relative') {
+ hsl.a += hsl.a * amount.value / 100;
+ }
+ else {
+ hsl.a += amount.value / 100;
+ }
+ hsl.a = clamp(hsl.a);
+ return hsla(color, hsl);
+ },
+ fadeout: function (color, amount, method) {
+ var hsl = toHSL(color);
+ if (typeof method !== 'undefined' && method.value === 'relative') {
+ hsl.a -= hsl.a * amount.value / 100;
+ }
+ else {
+ hsl.a -= amount.value / 100;
+ }
+ hsl.a = clamp(hsl.a);
+ return hsla(color, hsl);
+ },
+ fade: function (color, amount) {
+ var hsl = toHSL(color);
+ hsl.a = amount.value / 100;
+ hsl.a = clamp(hsl.a);
+ return hsla(color, hsl);
+ },
+ spin: function (color, amount) {
+ var hsl = toHSL(color);
+ var hue = (hsl.h + amount.value) % 360;
+ hsl.h = hue < 0 ? 360 + hue : hue;
+ return hsla(color, hsl);
+ },
+ //
+ // Copyright (c) 2006-2009 Hampton Catlin, Natalie Weizenbaum, and Chris Eppstein
+ // http://sass-lang.com
+ //
+ mix: function (color1, color2, weight) {
+ if (!weight) {
+ weight = new Dimension(50);
+ }
+ var p = weight.value / 100.0;
+ var w = p * 2 - 1;
+ var a = toHSL(color1).a - toHSL(color2).a;
+ var w1 = (((w * a == -1) ? w : (w + a) / (1 + w * a)) + 1) / 2.0;
+ var w2 = 1 - w1;
+ var rgb = [color1.rgb[0] * w1 + color2.rgb[0] * w2,
+ color1.rgb[1] * w1 + color2.rgb[1] * w2,
+ color1.rgb[2] * w1 + color2.rgb[2] * w2];
+ var alpha = color1.alpha * p + color2.alpha * (1 - p);
+ return new Color(rgb, alpha);
+ },
+ greyscale: function (color) {
+ return colorFunctions.desaturate(color, new Dimension(100));
+ },
+ contrast: function (color, dark, light, threshold) {
+ // filter: contrast(3.2);
+ // should be kept as is, so check for color
+ if (!color.rgb) {
+ return null;
+ }
+ if (typeof light === 'undefined') {
+ light = colorFunctions.rgba(255, 255, 255, 1.0);
+ }
+ if (typeof dark === 'undefined') {
+ dark = colorFunctions.rgba(0, 0, 0, 1.0);
+ }
+ // Figure out which is actually light and dark:
+ if (dark.luma() > light.luma()) {
+ var t = light;
+ light = dark;
+ dark = t;
+ }
+ if (typeof threshold === 'undefined') {
+ threshold = 0.43;
+ }
+ else {
+ threshold = number$1(threshold);
+ }
+ if (color.luma() < threshold) {
+ return light;
+ }
+ else {
+ return dark;
+ }
+ },
+ // Changes made in 2.7.0 - Reverted in 3.0.0
+ // contrast: function (color, color1, color2, threshold) {
+ // // Return which of `color1` and `color2` has the greatest contrast with `color`
+ // // according to the standard WCAG contrast ratio calculation.
+ // // http://www.w3.org/TR/WCAG20/#contrast-ratiodef
+ // // The threshold param is no longer used, in line with SASS.
+ // // filter: contrast(3.2);
+ // // should be kept as is, so check for color
+ // if (!color.rgb) {
+ // return null;
+ // }
+ // if (typeof color1 === 'undefined') {
+ // color1 = colorFunctions.rgba(0, 0, 0, 1.0);
+ // }
+ // if (typeof color2 === 'undefined') {
+ // color2 = colorFunctions.rgba(255, 255, 255, 1.0);
+ // }
+ // var contrast1, contrast2;
+ // var luma = color.luma();
+ // var luma1 = color1.luma();
+ // var luma2 = color2.luma();
+ // // Calculate contrast ratios for each color
+ // if (luma > luma1) {
+ // contrast1 = (luma + 0.05) / (luma1 + 0.05);
+ // } else {
+ // contrast1 = (luma1 + 0.05) / (luma + 0.05);
+ // }
+ // if (luma > luma2) {
+ // contrast2 = (luma + 0.05) / (luma2 + 0.05);
+ // } else {
+ // contrast2 = (luma2 + 0.05) / (luma + 0.05);
+ // }
+ // if (contrast1 > contrast2) {
+ // return color1;
+ // } else {
+ // return color2;
+ // }
+ // },
+ argb: function (color) {
+ return new Anonymous(color.toARGB());
+ },
+ color: function (c) {
+ if ((c instanceof Quoted) &&
+ (/^#([A-Fa-f0-9]{8}|[A-Fa-f0-9]{6}|[A-Fa-f0-9]{3,4})$/i.test(c.value))) {
+ var val = c.value.slice(1);
+ return new Color(val, undefined, "#" + val);
+ }
+ if ((c instanceof Color) || (c = Color.fromKeyword(c.value))) {
+ c.value = undefined;
+ return c;
+ }
+ throw {
+ type: 'Argument',
+ message: 'argument must be a color keyword or 3|4|6|8 digit hex e.g. #FFF'
+ };
+ },
+ tint: function (color, amount) {
+ return colorFunctions.mix(colorFunctions.rgb(255, 255, 255), color, amount);
+ },
+ shade: function (color, amount) {
+ return colorFunctions.mix(colorFunctions.rgb(0, 0, 0), color, amount);
+ }
+ };
+ var color = colorFunctions;
+
+ // Color Blending
+ // ref: http://www.w3.org/TR/compositing-1
+ function colorBlend(mode, color1, color2) {
+ var ab = color1.alpha; // result
+ var // backdrop
+ cb;
+ var as = color2.alpha;
+ var // source
+ cs;
+ var ar;
+ var cr;
+ var r = [];
+ ar = as + ab * (1 - as);
+ for (var i = 0; i < 3; i++) {
+ cb = color1.rgb[i] / 255;
+ cs = color2.rgb[i] / 255;
+ cr = mode(cb, cs);
+ if (ar) {
+ cr = (as * cs + ab * (cb -
+ as * (cb + cs - cr))) / ar;
+ }
+ r[i] = cr * 255;
+ }
+ return new Color(r, ar);
+ }
+ var colorBlendModeFunctions = {
+ multiply: function (cb, cs) {
+ return cb * cs;
+ },
+ screen: function (cb, cs) {
+ return cb + cs - cb * cs;
+ },
+ overlay: function (cb, cs) {
+ cb *= 2;
+ return (cb <= 1) ?
+ colorBlendModeFunctions.multiply(cb, cs) :
+ colorBlendModeFunctions.screen(cb - 1, cs);
+ },
+ softlight: function (cb, cs) {
+ var d = 1;
+ var e = cb;
+ if (cs > 0.5) {
+ e = 1;
+ d = (cb > 0.25) ? Math.sqrt(cb)
+ : ((16 * cb - 12) * cb + 4) * cb;
+ }
+ return cb - (1 - 2 * cs) * e * (d - cb);
+ },
+ hardlight: function (cb, cs) {
+ return colorBlendModeFunctions.overlay(cs, cb);
+ },
+ difference: function (cb, cs) {
+ return Math.abs(cb - cs);
+ },
+ exclusion: function (cb, cs) {
+ return cb + cs - 2 * cb * cs;
+ },
+ // non-w3c functions:
+ average: function (cb, cs) {
+ return (cb + cs) / 2;
+ },
+ negation: function (cb, cs) {
+ return 1 - Math.abs(cb + cs - 1);
+ }
+ };
+ for (var f$1 in colorBlendModeFunctions) {
+ if (colorBlendModeFunctions.hasOwnProperty(f$1)) {
+ colorBlend[f$1] = colorBlend.bind(null, colorBlendModeFunctions[f$1]);
+ }
+ }
+
+ var dataUri = (function (environment) {
+ var fallback = function (functionThis, node) { return new URL(node, functionThis.index, functionThis.currentFileInfo).eval(functionThis.context); };
+ return { 'data-uri': function (mimetypeNode, filePathNode) {
+ if (!filePathNode) {
+ filePathNode = mimetypeNode;
+ mimetypeNode = null;
+ }
+ var mimetype = mimetypeNode && mimetypeNode.value;
+ var filePath = filePathNode.value;
+ var currentFileInfo = this.currentFileInfo;
+ var currentDirectory = currentFileInfo.rewriteUrls ?
+ currentFileInfo.currentDirectory : currentFileInfo.entryPath;
+ var fragmentStart = filePath.indexOf('#');
+ var fragment = '';
+ if (fragmentStart !== -1) {
+ fragment = filePath.slice(fragmentStart);
+ filePath = filePath.slice(0, fragmentStart);
+ }
+ var context = clone(this.context);
+ context.rawBuffer = true;
+ var fileManager = environment.getFileManager(filePath, currentDirectory, context, environment, true);
+ if (!fileManager) {
+ return fallback(this, filePathNode);
+ }
+ var useBase64 = false;
+ // detect the mimetype if not given
+ if (!mimetypeNode) {
+ mimetype = environment.mimeLookup(filePath);
+ if (mimetype === 'image/svg+xml') {
+ useBase64 = false;
+ }
+ else {
+ // use base 64 unless it's an ASCII or UTF-8 format
+ var charset = environment.charsetLookup(mimetype);
+ useBase64 = ['US-ASCII', 'UTF-8'].indexOf(charset) < 0;
+ }
+ if (useBase64) {
+ mimetype += ';base64';
+ }
+ }
+ else {
+ useBase64 = /;base64$/.test(mimetype);
+ }
+ var fileSync = fileManager.loadFileSync(filePath, currentDirectory, context, environment);
+ if (!fileSync.contents) {
+ logger$1.warn("Skipped data-uri embedding of " + filePath + " because file not found");
+ return fallback(this, filePathNode || mimetypeNode);
+ }
+ var buf = fileSync.contents;
+ if (useBase64 && !environment.encodeBase64) {
+ return fallback(this, filePathNode);
+ }
+ buf = useBase64 ? environment.encodeBase64(buf) : encodeURIComponent(buf);
+ var uri = "data:" + mimetype + "," + buf + fragment;
+ return new URL(new Quoted("\"" + uri + "\"", uri, false, this.index, this.currentFileInfo), this.index, this.currentFileInfo);
+ } };
+ });
+
+ var getItemsFromNode = function (node) {
+ // handle non-array values as an array of length 1
+ // return 'undefined' if index is invalid
+ var items = Array.isArray(node.value) ?
+ node.value : Array(node);
+ return items;
+ };
+ var list = {
+ _SELF: function (n) {
+ return n;
+ },
+ '~': function () {
+ var expr = [];
+ for (var _i = 0; _i < arguments.length; _i++) {
+ expr[_i] = arguments[_i];
+ }
+ if (expr.length === 1) {
+ return expr[0];
+ }
+ return new Value(expr);
+ },
+ extract: function (values, index) {
+ // (1-based index)
+ index = index.value - 1;
+ return getItemsFromNode(values)[index];
+ },
+ length: function (values) {
+ return new Dimension(getItemsFromNode(values).length);
+ },
+ /**
+ * Creates a Less list of incremental values.
+ * Modeled after Lodash's range function, also exists natively in PHP
+ *
+ * @param {Dimension} [start=1]
+ * @param {Dimension} end - e.g. 10 or 10px - unit is added to output
+ * @param {Dimension} [step=1]
+ */
+ range: function (start, end, step) {
+ var from;
+ var to;
+ var stepValue = 1;
+ var list = [];
+ if (end) {
+ to = end;
+ from = start.value;
+ if (step) {
+ stepValue = step.value;
+ }
+ }
+ else {
+ from = 1;
+ to = start;
+ }
+ for (var i = from; i <= to.value; i += stepValue) {
+ list.push(new Dimension(i, to.unit));
+ }
+ return new Expression(list);
+ },
+ each: function (list, rs) {
+ var _this = this;
+ var rules = [];
+ var newRules;
+ var iterator;
+ var tryEval = function (val) {
+ if (val instanceof Node) {
+ return val.eval(_this.context);
+ }
+ return val;
+ };
+ if (list.value && !(list instanceof Quoted)) {
+ if (Array.isArray(list.value)) {
+ iterator = list.value.map(tryEval);
+ }
+ else {
+ iterator = [tryEval(list.value)];
+ }
+ }
+ else if (list.ruleset) {
+ iterator = tryEval(list.ruleset).rules;
+ }
+ else if (list.rules) {
+ iterator = list.rules.map(tryEval);
+ }
+ else if (Array.isArray(list)) {
+ iterator = list.map(tryEval);
+ }
+ else {
+ iterator = [tryEval(list)];
+ }
+ var valueName = '@value';
+ var keyName = '@key';
+ var indexName = '@index';
+ if (rs.params) {
+ valueName = rs.params[0] && rs.params[0].name;
+ keyName = rs.params[1] && rs.params[1].name;
+ indexName = rs.params[2] && rs.params[2].name;
+ rs = rs.rules;
+ }
+ else {
+ rs = rs.ruleset;
+ }
+ for (var i = 0; i < iterator.length; i++) {
+ var key = void 0;
+ var value = void 0;
+ var item = iterator[i];
+ if (item instanceof Declaration) {
+ key = typeof item.name === 'string' ? item.name : item.name[0].value;
+ value = item.value;
+ }
+ else {
+ key = new Dimension(i + 1);
+ value = item;
+ }
+ if (item instanceof Comment) {
+ continue;
+ }
+ newRules = rs.rules.slice(0);
+ if (valueName) {
+ newRules.push(new Declaration(valueName, value, false, false, this.index, this.currentFileInfo));
+ }
+ if (indexName) {
+ newRules.push(new Declaration(indexName, new Dimension(i + 1), false, false, this.index, this.currentFileInfo));
+ }
+ if (keyName) {
+ newRules.push(new Declaration(keyName, key, false, false, this.index, this.currentFileInfo));
+ }
+ rules.push(new Ruleset([new (Selector)([new Element("", '&')])], newRules, rs.strictImports, rs.visibilityInfo()));
+ }
+ return new Ruleset([new (Selector)([new Element("", '&')])], rules, rs.strictImports, rs.visibilityInfo()).eval(this.context);
+ }
+ };
+
+ var MathHelper = function (fn, unit, n) {
+ if (!(n instanceof Dimension)) {
+ throw { type: 'Argument', message: 'argument must be a number' };
+ }
+ if (unit == null) {
+ unit = n.unit;
+ }
+ else {
+ n = n.unify();
+ }
+ return new Dimension(fn(parseFloat(n.value)), unit);
+ };
+
+ var mathFunctions = {
+ // name, unit
+ ceil: null,
+ floor: null,
+ sqrt: null,
+ abs: null,
+ tan: '',
+ sin: '',
+ cos: '',
+ atan: 'rad',
+ asin: 'rad',
+ acos: 'rad'
+ };
+ for (var f in mathFunctions) {
+ if (mathFunctions.hasOwnProperty(f)) {
+ mathFunctions[f] = MathHelper.bind(null, Math[f], mathFunctions[f]);
+ }
+ }
+ mathFunctions.round = function (n, f) {
+ var fraction = typeof f === 'undefined' ? 0 : f.value;
+ return MathHelper(function (num) { return num.toFixed(fraction); }, null, n);
+ };
+
+ var minMax = function (isMin, args) {
+ args = Array.prototype.slice.call(args);
+ switch (args.length) {
+ case 0: throw { type: 'Argument', message: 'one or more arguments required' };
+ }
+ var i; // key is the unit.toString() for unified Dimension values,
+ var j;
+ var current;
+ var currentUnified;
+ var referenceUnified;
+ var unit;
+ var unitStatic;
+ var unitClone;
+ var // elems only contains original argument values.
+ order = [];
+ var values = {};
+ // value is the index into the order array.
+ for (i = 0; i < args.length; i++) {
+ current = args[i];
+ if (!(current instanceof Dimension)) {
+ if (Array.isArray(args[i].value)) {
+ Array.prototype.push.apply(args, Array.prototype.slice.call(args[i].value));
+ }
+ continue;
+ }
+ currentUnified = current.unit.toString() === '' && unitClone !== undefined ? new Dimension(current.value, unitClone).unify() : current.unify();
+ unit = currentUnified.unit.toString() === '' && unitStatic !== undefined ? unitStatic : currentUnified.unit.toString();
+ unitStatic = unit !== '' && unitStatic === undefined || unit !== '' && order[0].unify().unit.toString() === '' ? unit : unitStatic;
+ unitClone = unit !== '' && unitClone === undefined ? current.unit.toString() : unitClone;
+ j = values[''] !== undefined && unit !== '' && unit === unitStatic ? values[''] : values[unit];
+ if (j === undefined) {
+ if (unitStatic !== undefined && unit !== unitStatic) {
+ throw { type: 'Argument', message: 'incompatible types' };
+ }
+ values[unit] = order.length;
+ order.push(current);
+ continue;
+ }
+ referenceUnified = order[j].unit.toString() === '' && unitClone !== undefined ? new Dimension(order[j].value, unitClone).unify() : order[j].unify();
+ if (isMin && currentUnified.value < referenceUnified.value ||
+ !isMin && currentUnified.value > referenceUnified.value) {
+ order[j] = current;
+ }
+ }
+ if (order.length == 1) {
+ return order[0];
+ }
+ args = order.map(function (a) { return a.toCSS(this.context); }).join(this.context.compress ? ',' : ', ');
+ return new Anonymous((isMin ? 'min' : 'max') + "(" + args + ")");
+ };
+ var number = {
+ min: function () {
+ var args = [];
+ for (var _i = 0; _i < arguments.length; _i++) {
+ args[_i] = arguments[_i];
+ }
+ try {
+ return minMax(true, args);
+ }
+ catch (e) { }
+ },
+ max: function () {
+ var args = [];
+ for (var _i = 0; _i < arguments.length; _i++) {
+ args[_i] = arguments[_i];
+ }
+ try {
+ return minMax(false, args);
+ }
+ catch (e) { }
+ },
+ convert: function (val, unit) {
+ return val.convertTo(unit.value);
+ },
+ pi: function () {
+ return new Dimension(Math.PI);
+ },
+ mod: function (a, b) {
+ return new Dimension(a.value % b.value, a.unit);
+ },
+ pow: function (x, y) {
+ if (typeof x === 'number' && typeof y === 'number') {
+ x = new Dimension(x);
+ y = new Dimension(y);
+ }
+ else if (!(x instanceof Dimension) || !(y instanceof Dimension)) {
+ throw { type: 'Argument', message: 'arguments must be numbers' };
+ }
+ return new Dimension(Math.pow(x.value, y.value), x.unit);
+ },
+ percentage: function (n) {
+ var result = MathHelper(function (num) { return num * 100; }, '%', n);
+ return result;
+ }
+ };
+
+ var string = {
+ e: function (str) {
+ return new Quoted('"', str instanceof JavaScript ? str.evaluated : str.value, true);
+ },
+ escape: function (str) {
+ return new Anonymous(encodeURI(str.value).replace(/=/g, '%3D').replace(/:/g, '%3A').replace(/#/g, '%23').replace(/;/g, '%3B')
+ .replace(/\(/g, '%28').replace(/\)/g, '%29'));
+ },
+ replace: function (string, pattern, replacement, flags) {
+ var result = string.value;
+ replacement = (replacement.type === 'Quoted') ?
+ replacement.value : replacement.toCSS();
+ result = result.replace(new RegExp(pattern.value, flags ? flags.value : ''), replacement);
+ return new Quoted(string.quote || '', result, string.escaped);
+ },
+ '%': function (string /* arg, arg, ... */) {
+ var args = Array.prototype.slice.call(arguments, 1);
+ var result = string.value;
+ var _loop_1 = function (i) {
+ /* jshint loopfunc:true */
+ result = result.replace(/%[sda]/i, function (token) {
+ var value = ((args[i].type === 'Quoted') &&
+ token.match(/s/i)) ? args[i].value : args[i].toCSS();
+ return token.match(/[A-Z]$/) ? encodeURIComponent(value) : value;
+ });
+ };
+ for (var i = 0; i < args.length; i++) {
+ _loop_1(i);
+ }
+ result = result.replace(/%%/g, '%');
+ return new Quoted(string.quote || '', result, string.escaped);
+ }
+ };
+
+ var svg = (function (environment) {
+ return { 'svg-gradient': function (direction) {
+ var stops;
+ var gradientDirectionSvg;
+ var gradientType = 'linear';
+ var rectangleDimension = 'x="0" y="0" width="1" height="1"';
+ var renderEnv = { compress: false };
+ var returner;
+ var directionValue = direction.toCSS(renderEnv);
+ var i;
+ var color;
+ var position;
+ var positionValue;
+ var alpha;
+ function throwArgumentDescriptor() {
+ throw { type: 'Argument',
+ message: 'svg-gradient expects direction, start_color [start_position], [color position,]...,' +
+ ' end_color [end_position] or direction, color list' };
+ }
+ if (arguments.length == 2) {
+ if (arguments[1].value.length < 2) {
+ throwArgumentDescriptor();
+ }
+ stops = arguments[1].value;
+ }
+ else if (arguments.length < 3) {
+ throwArgumentDescriptor();
+ }
+ else {
+ stops = Array.prototype.slice.call(arguments, 1);
+ }
+ switch (directionValue) {
+ case 'to bottom':
+ gradientDirectionSvg = 'x1="0%" y1="0%" x2="0%" y2="100%"';
+ break;
+ case 'to right':
+ gradientDirectionSvg = 'x1="0%" y1="0%" x2="100%" y2="0%"';
+ break;
+ case 'to bottom right':
+ gradientDirectionSvg = 'x1="0%" y1="0%" x2="100%" y2="100%"';
+ break;
+ case 'to top right':
+ gradientDirectionSvg = 'x1="0%" y1="100%" x2="100%" y2="0%"';
+ break;
+ case 'ellipse':
+ case 'ellipse at center':
+ gradientType = 'radial';
+ gradientDirectionSvg = 'cx="50%" cy="50%" r="75%"';
+ rectangleDimension = 'x="-50" y="-50" width="101" height="101"';
+ break;
+ default:
+ throw { type: 'Argument', message: 'svg-gradient direction must be \'to bottom\', \'to right\',' +
+ ' \'to bottom right\', \'to top right\' or \'ellipse at center\'' };
+ }
+ returner = "";
+ returner = encodeURIComponent(returner);
+ returner = "data:image/svg+xml," + returner;
+ return new URL(new Quoted("'" + returner + "'", returner, false, this.index, this.currentFileInfo), this.index, this.currentFileInfo);
+ } };
+ });
+
+ var isa = function (n, Type) { return (n instanceof Type) ? Keyword.True : Keyword.False; };
+ var isunit = function (n, unit) {
+ if (unit === undefined) {
+ throw { type: 'Argument', message: 'missing the required second argument to isunit.' };
+ }
+ unit = typeof unit.value === 'string' ? unit.value : unit;
+ if (typeof unit !== 'string') {
+ throw { type: 'Argument', message: 'Second argument to isunit should be a unit or a string.' };
+ }
+ return (n instanceof Dimension) && n.unit.is(unit) ? Keyword.True : Keyword.False;
+ };
+ var types = {
+ isruleset: function (n) {
+ return isa(n, DetachedRuleset);
+ },
+ iscolor: function (n) {
+ return isa(n, Color);
+ },
+ isnumber: function (n) {
+ return isa(n, Dimension);
+ },
+ isstring: function (n) {
+ return isa(n, Quoted);
+ },
+ iskeyword: function (n) {
+ return isa(n, Keyword);
+ },
+ isurl: function (n) {
+ return isa(n, URL);
+ },
+ ispixel: function (n) {
+ return isunit(n, 'px');
+ },
+ ispercentage: function (n) {
+ return isunit(n, '%');
+ },
+ isem: function (n) {
+ return isunit(n, 'em');
+ },
+ isunit: isunit,
+ unit: function (val, unit) {
+ if (!(val instanceof Dimension)) {
+ throw { type: 'Argument',
+ message: "the first argument to unit must be a number" + (val instanceof Operation ? '. Have you forgotten parenthesis?' : '') };
+ }
+ if (unit) {
+ if (unit instanceof Keyword) {
+ unit = unit.value;
+ }
+ else {
+ unit = unit.toCSS();
+ }
+ }
+ else {
+ unit = '';
+ }
+ return new Dimension(val.value, unit);
+ },
+ 'get-unit': function (n) {
+ return new Anonymous(n.unit);
+ }
+ };
+
+ var functions = (function (environment) {
+ var functions = { functionRegistry: functionRegistry, functionCaller: functionCaller };
+ // register functions
+ functionRegistry.addMultiple(boolean$1);
+ functionRegistry.add('default', defaultFunc.eval.bind(defaultFunc));
+ functionRegistry.addMultiple(color);
+ functionRegistry.addMultiple(colorBlend);
+ functionRegistry.addMultiple(dataUri(environment));
+ functionRegistry.addMultiple(list);
+ functionRegistry.addMultiple(mathFunctions);
+ functionRegistry.addMultiple(number);
+ functionRegistry.addMultiple(string);
+ functionRegistry.addMultiple(svg());
+ functionRegistry.addMultiple(types);
+ return functions;
+ });
+
+ function transformTree (root, options) {
+ options = options || {};
+ var evaldRoot;
+ var variables = options.variables;
+ var evalEnv = new contexts.Eval(options);
+ //
+ // Allows setting variables with a hash, so:
+ //
+ // `{ color: new tree.Color('#f01') }` will become:
+ //
+ // new tree.Declaration('@color',
+ // new tree.Value([
+ // new tree.Expression([
+ // new tree.Color('#f01')
+ // ])
+ // ])
+ // )
+ //
+ if (typeof variables === 'object' && !Array.isArray(variables)) {
+ variables = Object.keys(variables).map(function (k) {
+ var value = variables[k];
+ if (!(value instanceof tree.Value)) {
+ if (!(value instanceof tree.Expression)) {
+ value = new tree.Expression([value]);
+ }
+ value = new tree.Value([value]);
+ }
+ return new tree.Declaration("@" + k, value, false, null, 0);
+ });
+ evalEnv.frames = [new tree.Ruleset(null, variables)];
+ }
+ var visitors$1 = [
+ new visitors.JoinSelectorVisitor(),
+ new visitors.MarkVisibleSelectorsVisitor(true),
+ new visitors.ExtendVisitor(),
+ new visitors.ToCSSVisitor({ compress: Boolean(options.compress) })
+ ];
+ var preEvalVisitors = [];
+ var v;
+ var visitorIterator;
+ /**
+ * first() / get() allows visitors to be added while visiting
+ *
+ * @todo Add scoping for visitors just like functions for @plugin; right now they're global
+ */
+ if (options.pluginManager) {
+ visitorIterator = options.pluginManager.visitor();
+ for (var i = 0; i < 2; i++) {
+ visitorIterator.first();
+ while ((v = visitorIterator.get())) {
+ if (v.isPreEvalVisitor) {
+ if (i === 0 || preEvalVisitors.indexOf(v) === -1) {
+ preEvalVisitors.push(v);
+ v.run(root);
+ }
+ }
+ else {
+ if (i === 0 || visitors$1.indexOf(v) === -1) {
+ if (v.isPreVisitor) {
+ visitors$1.unshift(v);
+ }
+ else {
+ visitors$1.push(v);
+ }
+ }
+ }
+ }
+ }
+ }
+ evaldRoot = root.eval(evalEnv);
+ for (var i = 0; i < visitors$1.length; i++) {
+ visitors$1[i].run(evaldRoot);
+ }
+ // Run any remaining visitors added after eval pass
+ if (options.pluginManager) {
+ visitorIterator.first();
+ while ((v = visitorIterator.get())) {
+ if (visitors$1.indexOf(v) === -1 && preEvalVisitors.indexOf(v) === -1) {
+ v.run(evaldRoot);
+ }
+ }
+ }
+ return evaldRoot;
+ }
+
+ /**
+ * Plugin Manager
+ */
+ var PluginManager = /** @class */ (function () {
+ function PluginManager(less) {
+ this.less = less;
+ this.visitors = [];
+ this.preProcessors = [];
+ this.postProcessors = [];
+ this.installedPlugins = [];
+ this.fileManagers = [];
+ this.iterator = -1;
+ this.pluginCache = {};
+ this.Loader = new less.PluginLoader(less);
+ }
+ /**
+ * Adds all the plugins in the array
+ * @param {Array} plugins
+ */
+ PluginManager.prototype.addPlugins = function (plugins) {
+ if (plugins) {
+ for (var i = 0; i < plugins.length; i++) {
+ this.addPlugin(plugins[i]);
+ }
+ }
+ };
+ /**
+ *
+ * @param plugin
+ * @param {String} filename
+ */
+ PluginManager.prototype.addPlugin = function (plugin, filename, functionRegistry) {
+ this.installedPlugins.push(plugin);
+ if (filename) {
+ this.pluginCache[filename] = plugin;
+ }
+ if (plugin.install) {
+ plugin.install(this.less, this, functionRegistry || this.less.functions.functionRegistry);
+ }
+ };
+ /**
+ *
+ * @param filename
+ */
+ PluginManager.prototype.get = function (filename) {
+ return this.pluginCache[filename];
+ };
+ /**
+ * Adds a visitor. The visitor object has options on itself to determine
+ * when it should run.
+ * @param visitor
+ */
+ PluginManager.prototype.addVisitor = function (visitor) {
+ this.visitors.push(visitor);
+ };
+ /**
+ * Adds a pre processor object
+ * @param {object} preProcessor
+ * @param {number} priority - guidelines 1 = before import, 1000 = import, 2000 = after import
+ */
+ PluginManager.prototype.addPreProcessor = function (preProcessor, priority) {
+ var indexToInsertAt;
+ for (indexToInsertAt = 0; indexToInsertAt < this.preProcessors.length; indexToInsertAt++) {
+ if (this.preProcessors[indexToInsertAt].priority >= priority) {
+ break;
+ }
+ }
+ this.preProcessors.splice(indexToInsertAt, 0, { preProcessor: preProcessor, priority: priority });
+ };
+ /**
+ * Adds a post processor object
+ * @param {object} postProcessor
+ * @param {number} priority - guidelines 1 = before compression, 1000 = compression, 2000 = after compression
+ */
+ PluginManager.prototype.addPostProcessor = function (postProcessor, priority) {
+ var indexToInsertAt;
+ for (indexToInsertAt = 0; indexToInsertAt < this.postProcessors.length; indexToInsertAt++) {
+ if (this.postProcessors[indexToInsertAt].priority >= priority) {
+ break;
+ }
+ }
+ this.postProcessors.splice(indexToInsertAt, 0, { postProcessor: postProcessor, priority: priority });
+ };
+ /**
+ *
+ * @param manager
+ */
+ PluginManager.prototype.addFileManager = function (manager) {
+ this.fileManagers.push(manager);
+ };
+ /**
+ *
+ * @returns {Array}
+ * @private
+ */
+ PluginManager.prototype.getPreProcessors = function () {
+ var preProcessors = [];
+ for (var i = 0; i < this.preProcessors.length; i++) {
+ preProcessors.push(this.preProcessors[i].preProcessor);
+ }
+ return preProcessors;
+ };
+ /**
+ *
+ * @returns {Array}
+ * @private
+ */
+ PluginManager.prototype.getPostProcessors = function () {
+ var postProcessors = [];
+ for (var i = 0; i < this.postProcessors.length; i++) {
+ postProcessors.push(this.postProcessors[i].postProcessor);
+ }
+ return postProcessors;
+ };
+ /**
+ *
+ * @returns {Array}
+ * @private
+ */
+ PluginManager.prototype.getVisitors = function () {
+ return this.visitors;
+ };
+ PluginManager.prototype.visitor = function () {
+ var self = this;
+ return {
+ first: function () {
+ self.iterator = -1;
+ return self.visitors[self.iterator];
+ },
+ get: function () {
+ self.iterator += 1;
+ return self.visitors[self.iterator];
+ }
+ };
+ };
+ /**
+ *
+ * @returns {Array}
+ * @private
+ */
+ PluginManager.prototype.getFileManagers = function () {
+ return this.fileManagers;
+ };
+ return PluginManager;
+ }());
+ var pm;
+ var PluginManagerFactory = function (less, newFactory) {
+ if (newFactory || !pm) {
+ pm = new PluginManager(less);
+ }
+ return pm;
+ };
+
+ function SourceMapOutput (environment) {
+ var SourceMapOutput = /** @class */ (function () {
+ function SourceMapOutput(options) {
+ this._css = [];
+ this._rootNode = options.rootNode;
+ this._contentsMap = options.contentsMap;
+ this._contentsIgnoredCharsMap = options.contentsIgnoredCharsMap;
+ if (options.sourceMapFilename) {
+ this._sourceMapFilename = options.sourceMapFilename.replace(/\\/g, '/');
+ }
+ this._outputFilename = options.outputFilename;
+ this.sourceMapURL = options.sourceMapURL;
+ if (options.sourceMapBasepath) {
+ this._sourceMapBasepath = options.sourceMapBasepath.replace(/\\/g, '/');
+ }
+ if (options.sourceMapRootpath) {
+ this._sourceMapRootpath = options.sourceMapRootpath.replace(/\\/g, '/');
+ if (this._sourceMapRootpath.charAt(this._sourceMapRootpath.length - 1) !== '/') {
+ this._sourceMapRootpath += '/';
+ }
+ }
+ else {
+ this._sourceMapRootpath = '';
+ }
+ this._outputSourceFiles = options.outputSourceFiles;
+ this._sourceMapGeneratorConstructor = environment.getSourceMapGenerator();
+ this._lineNumber = 0;
+ this._column = 0;
+ }
+ SourceMapOutput.prototype.removeBasepath = function (path) {
+ if (this._sourceMapBasepath && path.indexOf(this._sourceMapBasepath) === 0) {
+ path = path.substring(this._sourceMapBasepath.length);
+ if (path.charAt(0) === '\\' || path.charAt(0) === '/') {
+ path = path.substring(1);
+ }
+ }
+ return path;
+ };
+ SourceMapOutput.prototype.normalizeFilename = function (filename) {
+ filename = filename.replace(/\\/g, '/');
+ filename = this.removeBasepath(filename);
+ return (this._sourceMapRootpath || '') + filename;
+ };
+ SourceMapOutput.prototype.add = function (chunk, fileInfo, index, mapLines) {
+ // ignore adding empty strings
+ if (!chunk) {
+ return;
+ }
+ var lines, sourceLines, columns, sourceColumns, i;
+ if (fileInfo && fileInfo.filename) {
+ var inputSource = this._contentsMap[fileInfo.filename];
+ // remove vars/banner added to the top of the file
+ if (this._contentsIgnoredCharsMap[fileInfo.filename]) {
+ // adjust the index
+ index -= this._contentsIgnoredCharsMap[fileInfo.filename];
+ if (index < 0) {
+ index = 0;
+ }
+ // adjust the source
+ inputSource = inputSource.slice(this._contentsIgnoredCharsMap[fileInfo.filename]);
+ }
+ /**
+ * ignore empty content, or failsafe
+ * if contents map is incorrect
+ */
+ if (inputSource === undefined) {
+ this._css.push(chunk);
+ return;
+ }
+ inputSource = inputSource.substring(0, index);
+ sourceLines = inputSource.split('\n');
+ sourceColumns = sourceLines[sourceLines.length - 1];
+ }
+ lines = chunk.split('\n');
+ columns = lines[lines.length - 1];
+ if (fileInfo && fileInfo.filename) {
+ if (!mapLines) {
+ this._sourceMapGenerator.addMapping({ generated: { line: this._lineNumber + 1, column: this._column },
+ original: { line: sourceLines.length, column: sourceColumns.length },
+ source: this.normalizeFilename(fileInfo.filename) });
+ }
+ else {
+ for (i = 0; i < lines.length; i++) {
+ this._sourceMapGenerator.addMapping({ generated: { line: this._lineNumber + i + 1, column: i === 0 ? this._column : 0 },
+ original: { line: sourceLines.length + i, column: i === 0 ? sourceColumns.length : 0 },
+ source: this.normalizeFilename(fileInfo.filename) });
+ }
+ }
+ }
+ if (lines.length === 1) {
+ this._column += columns.length;
+ }
+ else {
+ this._lineNumber += lines.length - 1;
+ this._column = columns.length;
+ }
+ this._css.push(chunk);
+ };
+ SourceMapOutput.prototype.isEmpty = function () {
+ return this._css.length === 0;
+ };
+ SourceMapOutput.prototype.toCSS = function (context) {
+ this._sourceMapGenerator = new this._sourceMapGeneratorConstructor({ file: this._outputFilename, sourceRoot: null });
+ if (this._outputSourceFiles) {
+ for (var filename in this._contentsMap) {
+ if (this._contentsMap.hasOwnProperty(filename)) {
+ var source = this._contentsMap[filename];
+ if (this._contentsIgnoredCharsMap[filename]) {
+ source = source.slice(this._contentsIgnoredCharsMap[filename]);
+ }
+ this._sourceMapGenerator.setSourceContent(this.normalizeFilename(filename), source);
+ }
+ }
+ }
+ this._rootNode.genCSS(context, this);
+ if (this._css.length > 0) {
+ var sourceMapURL = void 0;
+ var sourceMapContent = JSON.stringify(this._sourceMapGenerator.toJSON());
+ if (this.sourceMapURL) {
+ sourceMapURL = this.sourceMapURL;
+ }
+ else if (this._sourceMapFilename) {
+ sourceMapURL = this._sourceMapFilename;
+ }
+ this.sourceMapURL = sourceMapURL;
+ this.sourceMap = sourceMapContent;
+ }
+ return this._css.join('');
+ };
+ return SourceMapOutput;
+ }());
+ return SourceMapOutput;
+ }
+
+ function SourceMapBuilder (SourceMapOutput, environment) {
+ var SourceMapBuilder = /** @class */ (function () {
+ function SourceMapBuilder(options) {
+ this.options = options;
+ }
+ SourceMapBuilder.prototype.toCSS = function (rootNode, options, imports) {
+ var sourceMapOutput = new SourceMapOutput({
+ contentsIgnoredCharsMap: imports.contentsIgnoredChars,
+ rootNode: rootNode,
+ contentsMap: imports.contents,
+ sourceMapFilename: this.options.sourceMapFilename,
+ sourceMapURL: this.options.sourceMapURL,
+ outputFilename: this.options.sourceMapOutputFilename,
+ sourceMapBasepath: this.options.sourceMapBasepath,
+ sourceMapRootpath: this.options.sourceMapRootpath,
+ outputSourceFiles: this.options.outputSourceFiles,
+ sourceMapGenerator: this.options.sourceMapGenerator,
+ sourceMapFileInline: this.options.sourceMapFileInline,
+ disableSourcemapAnnotation: this.options.disableSourcemapAnnotation
+ });
+ var css = sourceMapOutput.toCSS(options);
+ this.sourceMap = sourceMapOutput.sourceMap;
+ this.sourceMapURL = sourceMapOutput.sourceMapURL;
+ if (this.options.sourceMapInputFilename) {
+ this.sourceMapInputFilename = sourceMapOutput.normalizeFilename(this.options.sourceMapInputFilename);
+ }
+ if (this.options.sourceMapBasepath !== undefined && this.sourceMapURL !== undefined) {
+ this.sourceMapURL = sourceMapOutput.removeBasepath(this.sourceMapURL);
+ }
+ return css + this.getCSSAppendage();
+ };
+ SourceMapBuilder.prototype.getCSSAppendage = function () {
+ var sourceMapURL = this.sourceMapURL;
+ if (this.options.sourceMapFileInline) {
+ if (this.sourceMap === undefined) {
+ return '';
+ }
+ sourceMapURL = "data:application/json;base64," + environment.encodeBase64(this.sourceMap);
+ }
+ if (this.options.disableSourcemapAnnotation) {
+ return '';
+ }
+ if (sourceMapURL) {
+ return "/*# sourceMappingURL=" + sourceMapURL + " */";
+ }
+ return '';
+ };
+ SourceMapBuilder.prototype.getExternalSourceMap = function () {
+ return this.sourceMap;
+ };
+ SourceMapBuilder.prototype.setExternalSourceMap = function (sourceMap) {
+ this.sourceMap = sourceMap;
+ };
+ SourceMapBuilder.prototype.isInline = function () {
+ return this.options.sourceMapFileInline;
+ };
+ SourceMapBuilder.prototype.getSourceMapURL = function () {
+ return this.sourceMapURL;
+ };
+ SourceMapBuilder.prototype.getOutputFilename = function () {
+ return this.options.sourceMapOutputFilename;
+ };
+ SourceMapBuilder.prototype.getInputFilename = function () {
+ return this.sourceMapInputFilename;
+ };
+ return SourceMapBuilder;
+ }());
+ return SourceMapBuilder;
+ }
+
+ function ParseTree (SourceMapBuilder) {
+ var ParseTree = /** @class */ (function () {
+ function ParseTree(root, imports) {
+ this.root = root;
+ this.imports = imports;
+ }
+ ParseTree.prototype.toCSS = function (options) {
+ var evaldRoot;
+ var result = {};
+ var sourceMapBuilder;
+ try {
+ evaldRoot = transformTree(this.root, options);
+ }
+ catch (e) {
+ throw new LessError(e, this.imports);
+ }
+ try {
+ var compress = Boolean(options.compress);
+ if (compress) {
+ logger$1.warn('The compress option has been deprecated. ' +
+ 'We recommend you use a dedicated css minifier, for instance see less-plugin-clean-css.');
+ }
+ var toCSSOptions = {
+ compress: compress,
+ dumpLineNumbers: options.dumpLineNumbers,
+ strictUnits: Boolean(options.strictUnits),
+ numPrecision: 8
+ };
+ if (options.sourceMap) {
+ sourceMapBuilder = new SourceMapBuilder(options.sourceMap);
+ result.css = sourceMapBuilder.toCSS(evaldRoot, toCSSOptions, this.imports);
+ }
+ else {
+ result.css = evaldRoot.toCSS(toCSSOptions);
+ }
+ }
+ catch (e) {
+ throw new LessError(e, this.imports);
+ }
+ if (options.pluginManager) {
+ var postProcessors = options.pluginManager.getPostProcessors();
+ for (var i = 0; i < postProcessors.length; i++) {
+ result.css = postProcessors[i].process(result.css, { sourceMap: sourceMapBuilder, options: options, imports: this.imports });
+ }
+ }
+ if (options.sourceMap) {
+ result.map = sourceMapBuilder.getExternalSourceMap();
+ }
+ result.imports = [];
+ for (var file in this.imports.files) {
+ if (this.imports.files.hasOwnProperty(file) && file !== this.imports.rootFilename) {
+ result.imports.push(file);
+ }
+ }
+ return result;
+ };
+ return ParseTree;
+ }());
+ return ParseTree;
+ }
+
+ function ImportManager (environment) {
+ // FileInfo = {
+ // 'rewriteUrls' - option - whether to adjust URL's to be relative
+ // 'filename' - full resolved filename of current file
+ // 'rootpath' - path to append to normal URLs for this node
+ // 'currentDirectory' - path to the current file, absolute
+ // 'rootFilename' - filename of the base file
+ // 'entryPath' - absolute path to the entry file
+ // 'reference' - whether the file should not be output and only output parts that are referenced
+ var ImportManager = /** @class */ (function () {
+ function ImportManager(less, context, rootFileInfo) {
+ this.less = less;
+ this.rootFilename = rootFileInfo.filename;
+ this.paths = context.paths || []; // Search paths, when importing
+ this.contents = {}; // map - filename to contents of all the files
+ this.contentsIgnoredChars = {}; // map - filename to lines at the beginning of each file to ignore
+ this.mime = context.mime;
+ this.error = null;
+ this.context = context;
+ // Deprecated? Unused outside of here, could be useful.
+ this.queue = []; // Files which haven't been imported yet
+ this.files = {}; // Holds the imported parse trees.
+ }
+ /**
+ * Add an import to be imported
+ * @param path - the raw path
+ * @param tryAppendExtension - whether to try appending a file extension (.less or .js if the path has no extension)
+ * @param currentFileInfo - the current file info (used for instance to work out relative paths)
+ * @param importOptions - import options
+ * @param callback - callback for when it is imported
+ */
+ ImportManager.prototype.push = function (path, tryAppendExtension, currentFileInfo, importOptions, callback) {
+ var importManager = this, pluginLoader = this.context.pluginManager.Loader;
+ this.queue.push(path);
+ var fileParsedFunc = function (e, root, fullPath) {
+ importManager.queue.splice(importManager.queue.indexOf(path), 1); // Remove the path from the queue
+ var importedEqualsRoot = fullPath === importManager.rootFilename;
+ if (importOptions.optional && e) {
+ callback(null, { rules: [] }, false, null);
+ logger$1.info("The file " + fullPath + " was skipped because it was not found and the import was marked optional.");
+ }
+ else {
+ // Inline imports aren't cached here.
+ // If we start to cache them, please make sure they won't conflict with non-inline imports of the
+ // same name as they used to do before this comment and the condition below have been added.
+ if (!importManager.files[fullPath] && !importOptions.inline) {
+ importManager.files[fullPath] = { root: root, options: importOptions };
+ }
+ if (e && !importManager.error) {
+ importManager.error = e;
+ }
+ callback(e, root, importedEqualsRoot, fullPath);
+ }
+ };
+ var newFileInfo = {
+ rewriteUrls: this.context.rewriteUrls,
+ entryPath: currentFileInfo.entryPath,
+ rootpath: currentFileInfo.rootpath,
+ rootFilename: currentFileInfo.rootFilename
+ };
+ var fileManager = environment.getFileManager(path, currentFileInfo.currentDirectory, this.context, environment);
+ if (!fileManager) {
+ fileParsedFunc({ message: "Could not find a file-manager for " + path });
+ return;
+ }
+ var loadFileCallback = function (loadedFile) {
+ var plugin;
+ var resolvedFilename = loadedFile.filename;
+ var contents = loadedFile.contents.replace(/^\uFEFF/, '');
+ // Pass on an updated rootpath if path of imported file is relative and file
+ // is in a (sub|sup) directory
+ //
+ // Examples:
+ // - If path of imported file is 'module/nav/nav.less' and rootpath is 'less/',
+ // then rootpath should become 'less/module/nav/'
+ // - If path of imported file is '../mixins.less' and rootpath is 'less/',
+ // then rootpath should become 'less/../'
+ newFileInfo.currentDirectory = fileManager.getPath(resolvedFilename);
+ if (newFileInfo.rewriteUrls) {
+ newFileInfo.rootpath = fileManager.join((importManager.context.rootpath || ''), fileManager.pathDiff(newFileInfo.currentDirectory, newFileInfo.entryPath));
+ if (!fileManager.isPathAbsolute(newFileInfo.rootpath) && fileManager.alwaysMakePathsAbsolute()) {
+ newFileInfo.rootpath = fileManager.join(newFileInfo.entryPath, newFileInfo.rootpath);
+ }
+ }
+ newFileInfo.filename = resolvedFilename;
+ var newEnv = new contexts.Parse(importManager.context);
+ newEnv.processImports = false;
+ importManager.contents[resolvedFilename] = contents;
+ if (currentFileInfo.reference || importOptions.reference) {
+ newFileInfo.reference = true;
+ }
+ if (importOptions.isPlugin) {
+ plugin = pluginLoader.evalPlugin(contents, newEnv, importManager, importOptions.pluginArgs, newFileInfo);
+ if (plugin instanceof LessError) {
+ fileParsedFunc(plugin, null, resolvedFilename);
+ }
+ else {
+ fileParsedFunc(null, plugin, resolvedFilename);
+ }
+ }
+ else if (importOptions.inline) {
+ fileParsedFunc(null, contents, resolvedFilename);
+ }
+ else {
+ // import (multiple) parse trees apparently get altered and can't be cached.
+ // TODO: investigate why this is
+ if (importManager.files[resolvedFilename]
+ && !importManager.files[resolvedFilename].options.multiple
+ && !importOptions.multiple) {
+ fileParsedFunc(null, importManager.files[resolvedFilename].root, resolvedFilename);
+ }
+ else {
+ new Parser(newEnv, importManager, newFileInfo).parse(contents, function (e, root) {
+ fileParsedFunc(e, root, resolvedFilename);
+ });
+ }
+ }
+ };
+ var loadedFile;
+ var promise;
+ var context = clone(this.context);
+ if (tryAppendExtension) {
+ context.ext = importOptions.isPlugin ? '.js' : '.less';
+ }
+ if (importOptions.isPlugin) {
+ context.mime = 'application/javascript';
+ if (context.syncImport) {
+ loadedFile = pluginLoader.loadPluginSync(path, currentFileInfo.currentDirectory, context, environment, fileManager);
+ }
+ else {
+ promise = pluginLoader.loadPlugin(path, currentFileInfo.currentDirectory, context, environment, fileManager);
+ }
+ }
+ else {
+ if (context.syncImport) {
+ loadedFile = fileManager.loadFileSync(path, currentFileInfo.currentDirectory, context, environment);
+ }
+ else {
+ promise = fileManager.loadFile(path, currentFileInfo.currentDirectory, context, environment, function (err, loadedFile) {
+ if (err) {
+ fileParsedFunc(err);
+ }
+ else {
+ loadFileCallback(loadedFile);
+ }
+ });
+ }
+ }
+ if (loadedFile) {
+ if (!loadedFile.filename) {
+ fileParsedFunc(loadedFile);
+ }
+ else {
+ loadFileCallback(loadedFile);
+ }
+ }
+ else if (promise) {
+ promise.then(loadFileCallback, fileParsedFunc);
+ }
+ };
+ return ImportManager;
+ }());
+ return ImportManager;
+ }
+
+ function Parse (environment, ParseTree, ImportManager) {
+ var parse = function (input, options, callback) {
+ if (typeof options === 'function') {
+ callback = options;
+ options = copyOptions(this.options, {});
+ }
+ else {
+ options = copyOptions(this.options, options || {});
+ }
+ if (!callback) {
+ var self_1 = this;
+ return new Promise(function (resolve, reject) {
+ parse.call(self_1, input, options, function (err, output) {
+ if (err) {
+ reject(err);
+ }
+ else {
+ resolve(output);
+ }
+ });
+ });
+ }
+ else {
+ var context_1;
+ var rootFileInfo = void 0;
+ var pluginManager_1 = new PluginManagerFactory(this, !options.reUsePluginManager);
+ options.pluginManager = pluginManager_1;
+ context_1 = new contexts.Parse(options);
+ if (options.rootFileInfo) {
+ rootFileInfo = options.rootFileInfo;
+ }
+ else {
+ var filename = options.filename || 'input';
+ var entryPath = filename.replace(/[^\/\\]*$/, '');
+ rootFileInfo = {
+ filename: filename,
+ rewriteUrls: context_1.rewriteUrls,
+ rootpath: context_1.rootpath || '',
+ currentDirectory: entryPath,
+ entryPath: entryPath,
+ rootFilename: filename
+ };
+ // add in a missing trailing slash
+ if (rootFileInfo.rootpath && rootFileInfo.rootpath.slice(-1) !== '/') {
+ rootFileInfo.rootpath += '/';
+ }
+ }
+ var imports_1 = new ImportManager(this, context_1, rootFileInfo);
+ this.importManager = imports_1;
+ // TODO: allow the plugins to be just a list of paths or names
+ // Do an async plugin queue like lessc
+ if (options.plugins) {
+ options.plugins.forEach(function (plugin) {
+ var evalResult, contents;
+ if (plugin.fileContent) {
+ contents = plugin.fileContent.replace(/^\uFEFF/, '');
+ evalResult = pluginManager_1.Loader.evalPlugin(contents, context_1, imports_1, plugin.options, plugin.filename);
+ if (evalResult instanceof LessError) {
+ return callback(evalResult);
+ }
+ }
+ else {
+ pluginManager_1.addPlugin(plugin);
+ }
+ });
+ }
+ new Parser(context_1, imports_1, rootFileInfo)
+ .parse(input, function (e, root) {
+ if (e) {
+ return callback(e);
+ }
+ callback(null, root, imports_1, options);
+ }, options);
+ }
+ };
+ return parse;
+ }
+
+ function Render (environment, ParseTree, ImportManager) {
+ var render = function (input, options, callback) {
+ if (typeof options === 'function') {
+ callback = options;
+ options = copyOptions(this.options, {});
+ }
+ else {
+ options = copyOptions(this.options, options || {});
+ }
+ if (!callback) {
+ var self_1 = this;
+ return new Promise(function (resolve, reject) {
+ render.call(self_1, input, options, function (err, output) {
+ if (err) {
+ reject(err);
+ }
+ else {
+ resolve(output);
+ }
+ });
+ });
+ }
+ else {
+ this.parse(input, options, function (err, root, imports, options) {
+ if (err) {
+ return callback(err);
+ }
+ var result;
+ try {
+ var parseTree = new ParseTree(root, imports);
+ result = parseTree.toCSS(options);
+ }
+ catch (err) {
+ return callback(err);
+ }
+ callback(null, result);
+ });
+ }
+ };
+ return render;
+ }
+
+ var version = "4.1.2";
+
+ function parseNodeVersion(version) {
+ var match = version.match(/^v(\d{1,2})\.(\d{1,2})\.(\d{1,2})(?:-([0-9A-Za-z-.]+))?(?:\+([0-9A-Za-z-.]+))?$/); // eslint-disable-line max-len
+ if (!match) {
+ throw new Error('Unable to parse: ' + version);
+ }
+
+ var res = {
+ major: parseInt(match[1], 10),
+ minor: parseInt(match[2], 10),
+ patch: parseInt(match[3], 10),
+ pre: match[4] || '',
+ build: match[5] || '',
+ };
+
+ return res;
+ }
+
+ var parseNodeVersion_1 = parseNodeVersion;
+
+ function lessRoot (environment, fileManagers) {
+ var sourceMapOutput, sourceMapBuilder, parseTree, importManager;
+ environment = new Environment(environment, fileManagers);
+ sourceMapOutput = SourceMapOutput(environment);
+ sourceMapBuilder = SourceMapBuilder(sourceMapOutput, environment);
+ parseTree = ParseTree(sourceMapBuilder);
+ importManager = ImportManager(environment);
+ var render = Render(environment, parseTree);
+ var parse = Parse(environment, parseTree, importManager);
+ var v = parseNodeVersion_1("v" + version);
+ var initial = {
+ version: [v.major, v.minor, v.patch],
+ data: data,
+ tree: tree,
+ Environment: Environment,
+ AbstractFileManager: AbstractFileManager,
+ AbstractPluginLoader: AbstractPluginLoader,
+ environment: environment,
+ visitors: visitors,
+ Parser: Parser,
+ functions: functions(environment),
+ contexts: contexts,
+ SourceMapOutput: sourceMapOutput,
+ SourceMapBuilder: sourceMapBuilder,
+ ParseTree: parseTree,
+ ImportManager: importManager,
+ render: render,
+ parse: parse,
+ LessError: LessError,
+ transformTree: transformTree,
+ utils: utils,
+ PluginManager: PluginManagerFactory,
+ logger: logger$1
+ };
+ // Create a public API
+ var ctor = function (t) {
+ return function () {
+ var obj = Object.create(t.prototype);
+ t.apply(obj, Array.prototype.slice.call(arguments, 0));
+ return obj;
+ };
+ };
+ var t;
+ var api = Object.create(initial);
+ for (var n in initial.tree) {
+ /* eslint guard-for-in: 0 */
+ t = initial.tree[n];
+ if (typeof t === 'function') {
+ api[n.toLowerCase()] = ctor(t);
+ }
+ else {
+ api[n] = Object.create(null);
+ for (var o in t) {
+ /* eslint guard-for-in: 0 */
+ api[n][o.toLowerCase()] = ctor(t[o]);
+ }
+ }
+ }
+ /**
+ * Some of the functions assume a `this` context of the API object,
+ * which causes it to fail when wrapped for ES6 imports.
+ *
+ * An assumed `this` should be removed in the future.
+ */
+ initial.parse = initial.parse.bind(api);
+ initial.render = initial.render.bind(api);
+ return api;
+ }
+
+ /* global window, XMLHttpRequest */
+ var options$1;
+ var logger;
+ var fileCache = {};
+ // TODOS - move log somewhere. pathDiff and doing something similar in node. use pathDiff in the other browser file for the initial load
+ var FileManager = function () { };
+ FileManager.prototype = Object.assign(new AbstractFileManager(), {
+ alwaysMakePathsAbsolute: function () {
+ return true;
+ },
+ join: function (basePath, laterPath) {
+ if (!basePath) {
+ return laterPath;
+ }
+ return this.extractUrlParts(laterPath, basePath).path;
+ },
+ doXHR: function (url, type, callback, errback) {
+ var xhr = new XMLHttpRequest();
+ var async = options$1.isFileProtocol ? options$1.fileAsync : true;
+ if (typeof xhr.overrideMimeType === 'function') {
+ xhr.overrideMimeType('text/css');
+ }
+ logger.debug("XHR: Getting '" + url + "'");
+ xhr.open('GET', url, async);
+ xhr.setRequestHeader('Accept', type || 'text/x-less, text/css; q=0.9, */*; q=0.5');
+ xhr.send(null);
+ function handleResponse(xhr, callback, errback) {
+ if (xhr.status >= 200 && xhr.status < 300) {
+ callback(xhr.responseText, xhr.getResponseHeader('Last-Modified'));
+ }
+ else if (typeof errback === 'function') {
+ errback(xhr.status, url);
+ }
+ }
+ if (options$1.isFileProtocol && !options$1.fileAsync) {
+ if (xhr.status === 0 || (xhr.status >= 200 && xhr.status < 300)) {
+ callback(xhr.responseText);
+ }
+ else {
+ errback(xhr.status, url);
+ }
+ }
+ else if (async) {
+ xhr.onreadystatechange = function () {
+ if (xhr.readyState == 4) {
+ handleResponse(xhr, callback, errback);
+ }
+ };
+ }
+ else {
+ handleResponse(xhr, callback, errback);
+ }
+ },
+ supports: function () {
+ return true;
+ },
+ clearFileCache: function () {
+ fileCache = {};
+ },
+ loadFile: function (filename, currentDirectory, options, environment) {
+ // TODO: Add prefix support like less-node?
+ // What about multiple paths?
+ if (currentDirectory && !this.isPathAbsolute(filename)) {
+ filename = currentDirectory + filename;
+ }
+ filename = options.ext ? this.tryAppendExtension(filename, options.ext) : filename;
+ options = options || {};
+ // sheet may be set to the stylesheet for the initial load or a collection of properties including
+ // some context variables for imports
+ var hrefParts = this.extractUrlParts(filename, window.location.href);
+ var href = hrefParts.url;
+ var self = this;
+ return new Promise(function (resolve, reject) {
+ if (options.useFileCache && fileCache[href]) {
+ try {
+ var lessText = fileCache[href];
+ return resolve({ contents: lessText, filename: href, webInfo: { lastModified: new Date() } });
+ }
+ catch (e) {
+ return reject({ filename: href, message: "Error loading file " + href + " error was " + e.message });
+ }
+ }
+ self.doXHR(href, options.mime, function doXHRCallback(data, lastModified) {
+ // per file cache
+ fileCache[href] = data;
+ // Use remote copy (re-parse)
+ resolve({ contents: data, filename: href, webInfo: { lastModified: lastModified } });
+ }, function doXHRError(status, url) {
+ reject({ type: 'File', message: "'" + url + "' wasn't found (" + status + ")", href: href });
+ });
+ });
+ }
+ });
+ var FM = (function (opts, log) {
+ options$1 = opts;
+ logger = log;
+ return FileManager;
+ });
+
+ // TODO: Add tests for browser @plugin
+ /**
+ * Browser Plugin Loader
+ */
+ var PluginLoader = function (less) {
+ this.less = less;
+ // Should we shim this.require for browser? Probably not?
+ };
+ PluginLoader.prototype = Object.assign(new AbstractPluginLoader(), {
+ loadPlugin: function (filename, basePath, context, environment, fileManager) {
+ return new Promise(function (fulfill, reject) {
+ fileManager.loadFile(filename, basePath, context, environment)
+ .then(fulfill).catch(reject);
+ });
+ }
+ });
+
+ var LogListener = (function (less, options) {
+ var logLevel_debug = 4;
+ var logLevel_info = 3;
+ var logLevel_warn = 2;
+ var logLevel_error = 1;
+ // The amount of logging in the javascript console.
+ // 3 - Debug, information and errors
+ // 2 - Information and errors
+ // 1 - Errors
+ // 0 - None
+ // Defaults to 2
+ options.logLevel = typeof options.logLevel !== 'undefined' ? options.logLevel : (options.env === 'development' ? logLevel_info : logLevel_error);
+ if (!options.loggers) {
+ options.loggers = [{
+ debug: function (msg) {
+ if (options.logLevel >= logLevel_debug) {
+ console.log(msg);
+ }
+ },
+ info: function (msg) {
+ if (options.logLevel >= logLevel_info) {
+ console.log(msg);
+ }
+ },
+ warn: function (msg) {
+ if (options.logLevel >= logLevel_warn) {
+ console.warn(msg);
+ }
+ },
+ error: function (msg) {
+ if (options.logLevel >= logLevel_error) {
+ console.error(msg);
+ }
+ }
+ }];
+ }
+ for (var i = 0; i < options.loggers.length; i++) {
+ less.logger.addListener(options.loggers[i]);
+ }
+ });
+
+ var ErrorReporting = (function (window, less, options) {
+ function errorHTML(e, rootHref) {
+ var id = "less-error-message:" + extractId(rootHref || '');
+ var template = '
{content}
';
+ var elem = window.document.createElement('div');
+ var timer;
+ var content;
+ var errors = [];
+ var filename = e.filename || rootHref;
+ var filenameNoPath = filename.match(/([^\/]+(\?.*)?)$/)[1];
+ elem.id = id;
+ elem.className = 'less-error-message';
+ content = "
" + (e.type || 'Syntax') + "Error: " + (e.message || 'There is an error in your .less file') +
+ ("
in " + filenameNoPath + " ");
+ var errorline = function (e, i, classname) {
+ if (e.extract[i] !== undefined) {
+ errors.push(template.replace(/\{line\}/, (parseInt(e.line, 10) || 0) + (i - 1))
+ .replace(/\{class\}/, classname)
+ .replace(/\{content\}/, e.extract[i]));
+ }
+ };
+ if (e.line) {
+ errorline(e, 0, '');
+ errorline(e, 1, 'line');
+ errorline(e, 2, '');
+ content += "on line " + e.line + ", column " + (e.column + 1) + ":
" + errors.join('') + "
";
+ }
+ if (e.stack && (e.extract || options.logLevel >= 4)) {
+ content += " Stack Trace" + e.stack.split('\n').slice(1).join(' ');
+ }
+ elem.innerHTML = content;
+ // CSS for error messages
+ browser.createCSS(window.document, [
+ '.less-error-message ul, .less-error-message li {',
+ 'list-style-type: none;',
+ 'margin-right: 15px;',
+ 'padding: 4px 0;',
+ 'margin: 0;',
+ '}',
+ '.less-error-message label {',
+ 'font-size: 12px;',
+ 'margin-right: 15px;',
+ 'padding: 4px 0;',
+ 'color: #cc7777;',
+ '}',
+ '.less-error-message pre {',
+ 'color: #dd6666;',
+ 'padding: 4px 0;',
+ 'margin: 0;',
+ 'display: inline-block;',
+ '}',
+ '.less-error-message pre.line {',
+ 'color: #ff0000;',
+ '}',
+ '.less-error-message h3 {',
+ 'font-size: 20px;',
+ 'font-weight: bold;',
+ 'padding: 15px 0 5px 0;',
+ 'margin: 0;',
+ '}',
+ '.less-error-message a {',
+ 'color: #10a',
+ '}',
+ '.less-error-message .error {',
+ 'color: red;',
+ 'font-weight: bold;',
+ 'padding-bottom: 2px;',
+ 'border-bottom: 1px dashed red;',
+ '}'
+ ].join('\n'), { title: 'error-message' });
+ elem.style.cssText = [
+ 'font-family: Arial, sans-serif',
+ 'border: 1px solid #e00',
+ 'background-color: #eee',
+ 'border-radius: 5px',
+ '-webkit-border-radius: 5px',
+ '-moz-border-radius: 5px',
+ 'color: #e00',
+ 'padding: 15px',
+ 'margin-bottom: 15px'
+ ].join(';');
+ if (options.env === 'development') {
+ timer = setInterval(function () {
+ var document = window.document;
+ var body = document.body;
+ if (body) {
+ if (document.getElementById(id)) {
+ body.replaceChild(elem, document.getElementById(id));
+ }
+ else {
+ body.insertBefore(elem, body.firstChild);
+ }
+ clearInterval(timer);
+ }
+ }, 10);
+ }
+ }
+ function removeErrorHTML(path) {
+ var node = window.document.getElementById("less-error-message:" + extractId(path));
+ if (node) {
+ node.parentNode.removeChild(node);
+ }
+ }
+ function removeError(path) {
+ if (!options.errorReporting || options.errorReporting === 'html') {
+ removeErrorHTML(path);
+ }
+ else if (options.errorReporting === 'console') ;
+ else if (typeof options.errorReporting === 'function') {
+ options.errorReporting('remove', path);
+ }
+ }
+ function errorConsole(e, rootHref) {
+ var template = '{line} {content}';
+ var filename = e.filename || rootHref;
+ var errors = [];
+ var content = (e.type || 'Syntax') + "Error: " + (e.message || 'There is an error in your .less file') + " in " + filename;
+ var errorline = function (e, i, classname) {
+ if (e.extract[i] !== undefined) {
+ errors.push(template.replace(/\{line\}/, (parseInt(e.line, 10) || 0) + (i - 1))
+ .replace(/\{class\}/, classname)
+ .replace(/\{content\}/, e.extract[i]));
+ }
+ };
+ if (e.line) {
+ errorline(e, 0, '');
+ errorline(e, 1, 'line');
+ errorline(e, 2, '');
+ content += " on line " + e.line + ", column " + (e.column + 1) + ":\n" + errors.join('\n');
+ }
+ if (e.stack && (e.extract || options.logLevel >= 4)) {
+ content += "\nStack Trace\n" + e.stack;
+ }
+ less.logger.error(content);
+ }
+ function error(e, rootHref) {
+ if (!options.errorReporting || options.errorReporting === 'html') {
+ errorHTML(e, rootHref);
+ }
+ else if (options.errorReporting === 'console') {
+ errorConsole(e, rootHref);
+ }
+ else if (typeof options.errorReporting === 'function') {
+ options.errorReporting('add', e, rootHref);
+ }
+ }
+ return {
+ add: error,
+ remove: removeError
+ };
+ });
+
+ // Cache system is a bit outdated and could do with work
+ var Cache = (function (window, options, logger) {
+ var cache = null;
+ if (options.env !== 'development') {
+ try {
+ cache = (typeof window.localStorage === 'undefined') ? null : window.localStorage;
+ }
+ catch (_) { }
+ }
+ return {
+ setCSS: function (path, lastModified, modifyVars, styles) {
+ if (cache) {
+ logger.info("saving " + path + " to cache.");
+ try {
+ cache.setItem(path, styles);
+ cache.setItem(path + ":timestamp", lastModified);
+ if (modifyVars) {
+ cache.setItem(path + ":vars", JSON.stringify(modifyVars));
+ }
+ }
+ catch (e) {
+ // TODO - could do with adding more robust error handling
+ logger.error("failed to save \"" + path + "\" to local storage for caching.");
+ }
+ }
+ },
+ getCSS: function (path, webInfo, modifyVars) {
+ var css = cache && cache.getItem(path);
+ var timestamp = cache && cache.getItem(path + ":timestamp");
+ var vars = cache && cache.getItem(path + ":vars");
+ modifyVars = modifyVars || {};
+ vars = vars || "{}"; // if not set, treat as the JSON representation of an empty object
+ if (timestamp && webInfo.lastModified &&
+ (new Date(webInfo.lastModified).valueOf() ===
+ new Date(timestamp).valueOf()) &&
+ JSON.stringify(modifyVars) === vars) {
+ // Use local copy
+ return css;
+ }
+ }
+ };
+ });
+
+ var ImageSize = (function () {
+ function imageSize() {
+ throw {
+ type: 'Runtime',
+ message: 'Image size functions are not supported in browser version of less'
+ };
+ }
+ var imageFunctions = {
+ 'image-size': function (filePathNode) {
+ imageSize();
+ return -1;
+ },
+ 'image-width': function (filePathNode) {
+ imageSize();
+ return -1;
+ },
+ 'image-height': function (filePathNode) {
+ imageSize();
+ return -1;
+ }
+ };
+ functionRegistry.addMultiple(imageFunctions);
+ });
+
+ //
+ var root = (function (window, options) {
+ var document = window.document;
+ var less = lessRoot();
+ less.options = options;
+ var environment = less.environment;
+ var FileManager = FM(options, less.logger);
+ var fileManager = new FileManager();
+ environment.addFileManager(fileManager);
+ less.FileManager = FileManager;
+ less.PluginLoader = PluginLoader;
+ LogListener(less, options);
+ var errors = ErrorReporting(window, less, options);
+ var cache = less.cache = options.cache || Cache(window, options, less.logger);
+ ImageSize(less.environment);
+ // Setup user functions - Deprecate?
+ if (options.functions) {
+ less.functions.functionRegistry.addMultiple(options.functions);
+ }
+ var typePattern = /^text\/(x-)?less$/;
+ function clone(obj) {
+ var cloned = {};
+ for (var prop in obj) {
+ if (obj.hasOwnProperty(prop)) {
+ cloned[prop] = obj[prop];
+ }
+ }
+ return cloned;
+ }
+ // only really needed for phantom
+ function bind(func, thisArg) {
+ var curryArgs = Array.prototype.slice.call(arguments, 2);
+ return function () {
+ var args = curryArgs.concat(Array.prototype.slice.call(arguments, 0));
+ return func.apply(thisArg, args);
+ };
+ }
+ function loadStyles(modifyVars) {
+ var styles = document.getElementsByTagName('style');
+ var style;
+ for (var i = 0; i < styles.length; i++) {
+ style = styles[i];
+ if (style.type.match(typePattern)) {
+ var instanceOptions = clone(options);
+ instanceOptions.modifyVars = modifyVars;
+ var lessText = style.innerHTML || '';
+ instanceOptions.filename = document.location.href.replace(/#.*$/, '');
+ /* jshint loopfunc:true */
+ // use closure to store current style
+ less.render(lessText, instanceOptions, bind(function (style, e, result) {
+ if (e) {
+ errors.add(e, 'inline');
+ }
+ else {
+ style.type = 'text/css';
+ if (style.styleSheet) {
+ style.styleSheet.cssText = result.css;
+ }
+ else {
+ style.innerHTML = result.css;
+ }
+ }
+ }, null, style));
+ }
+ }
+ }
+ function loadStyleSheet(sheet, callback, reload, remaining, modifyVars) {
+ var instanceOptions = clone(options);
+ addDataAttr(instanceOptions, sheet);
+ instanceOptions.mime = sheet.type;
+ if (modifyVars) {
+ instanceOptions.modifyVars = modifyVars;
+ }
+ function loadInitialFileCallback(loadedFile) {
+ var data = loadedFile.contents;
+ var path = loadedFile.filename;
+ var webInfo = loadedFile.webInfo;
+ var newFileInfo = {
+ currentDirectory: fileManager.getPath(path),
+ filename: path,
+ rootFilename: path,
+ rewriteUrls: instanceOptions.rewriteUrls
+ };
+ newFileInfo.entryPath = newFileInfo.currentDirectory;
+ newFileInfo.rootpath = instanceOptions.rootpath || newFileInfo.currentDirectory;
+ if (webInfo) {
+ webInfo.remaining = remaining;
+ var css = cache.getCSS(path, webInfo, instanceOptions.modifyVars);
+ if (!reload && css) {
+ webInfo.local = true;
+ callback(null, css, data, sheet, webInfo, path);
+ return;
+ }
+ }
+ // TODO add tests around how this behaves when reloading
+ errors.remove(path);
+ instanceOptions.rootFileInfo = newFileInfo;
+ less.render(data, instanceOptions, function (e, result) {
+ if (e) {
+ e.href = path;
+ callback(e);
+ }
+ else {
+ cache.setCSS(sheet.href, webInfo.lastModified, instanceOptions.modifyVars, result.css);
+ callback(null, result.css, data, sheet, webInfo, path);
+ }
+ });
+ }
+ fileManager.loadFile(sheet.href, null, instanceOptions, environment)
+ .then(function (loadedFile) {
+ loadInitialFileCallback(loadedFile);
+ }).catch(function (err) {
+ console.log(err);
+ callback(err);
+ });
+ }
+ function loadStyleSheets(callback, reload, modifyVars) {
+ for (var i = 0; i < less.sheets.length; i++) {
+ loadStyleSheet(less.sheets[i], callback, reload, less.sheets.length - (i + 1), modifyVars);
+ }
+ }
+ function initRunningMode() {
+ if (less.env === 'development') {
+ less.watchTimer = setInterval(function () {
+ if (less.watchMode) {
+ fileManager.clearFileCache();
+ loadStyleSheets(function (e, css, _, sheet, webInfo) {
+ if (e) {
+ errors.add(e, e.href || sheet.href);
+ }
+ else if (css) {
+ browser.createCSS(window.document, css, sheet);
+ }
+ });
+ }
+ }, options.poll);
+ }
+ }
+ //
+ // Watch mode
+ //
+ less.watch = function () {
+ if (!less.watchMode) {
+ less.env = 'development';
+ initRunningMode();
+ }
+ this.watchMode = true;
+ return true;
+ };
+ less.unwatch = function () { clearInterval(less.watchTimer); this.watchMode = false; return false; };
+ //
+ // Synchronously get all tags with the 'rel' attribute set to
+ // "stylesheet/less".
+ //
+ less.registerStylesheetsImmediately = function () {
+ var links = document.getElementsByTagName('link');
+ less.sheets = [];
+ for (var i = 0; i < links.length; i++) {
+ if (links[i].rel === 'stylesheet/less' || (links[i].rel.match(/stylesheet/) &&
+ (links[i].type.match(typePattern)))) {
+ less.sheets.push(links[i]);
+ }
+ }
+ };
+ //
+ // Asynchronously get all tags with the 'rel' attribute set to
+ // "stylesheet/less", returning a Promise.
+ //
+ less.registerStylesheets = function () { return new Promise(function (resolve, reject) {
+ less.registerStylesheetsImmediately();
+ resolve();
+ }); };
+ //
+ // With this function, it's possible to alter variables and re-render
+ // CSS without reloading less-files
+ //
+ less.modifyVars = function (record) { return less.refresh(true, record, false); };
+ less.refresh = function (reload, modifyVars, clearFileCache) {
+ if ((reload || clearFileCache) && clearFileCache !== false) {
+ fileManager.clearFileCache();
+ }
+ return new Promise(function (resolve, reject) {
+ var startTime;
+ var endTime;
+ var totalMilliseconds;
+ var remainingSheets;
+ startTime = endTime = new Date();
+ // Set counter for remaining unprocessed sheets
+ remainingSheets = less.sheets.length;
+ if (remainingSheets === 0) {
+ endTime = new Date();
+ totalMilliseconds = endTime - startTime;
+ less.logger.info('Less has finished and no sheets were loaded.');
+ resolve({
+ startTime: startTime,
+ endTime: endTime,
+ totalMilliseconds: totalMilliseconds,
+ sheets: less.sheets.length
+ });
+ }
+ else {
+ // Relies on less.sheets array, callback seems to be guaranteed to be called for every element of the array
+ loadStyleSheets(function (e, css, _, sheet, webInfo) {
+ if (e) {
+ errors.add(e, e.href || sheet.href);
+ reject(e);
+ return;
+ }
+ if (webInfo.local) {
+ less.logger.info("Loading " + sheet.href + " from cache.");
+ }
+ else {
+ less.logger.info("Rendered " + sheet.href + " successfully.");
+ }
+ browser.createCSS(window.document, css, sheet);
+ less.logger.info("CSS for " + sheet.href + " generated in " + (new Date() - endTime) + "ms");
+ // Count completed sheet
+ remainingSheets--;
+ // Check if the last remaining sheet was processed and then call the promise
+ if (remainingSheets === 0) {
+ totalMilliseconds = new Date() - startTime;
+ less.logger.info("Less has finished. CSS generated in " + totalMilliseconds + "ms");
+ resolve({
+ startTime: startTime,
+ endTime: endTime,
+ totalMilliseconds: totalMilliseconds,
+ sheets: less.sheets.length
+ });
+ }
+ endTime = new Date();
+ }, reload, modifyVars);
+ }
+ loadStyles(modifyVars);
+ });
+ };
+ less.refreshStyles = loadStyles;
+ return less;
+ });
+
+ /**
+ * Kicks off less and compiles any stylesheets
+ * used in the browser distributed version of less
+ * to kick-start less using the browser api
+ */
+ var options = defaultOptions();
+ if (window.less) {
+ for (var key in window.less) {
+ if (window.less.hasOwnProperty(key)) {
+ options[key] = window.less[key];
+ }
+ }
+ }
+ addDefaultOptions(window, options);
+ options.plugins = options.plugins || [];
+ if (window.LESS_PLUGINS) {
+ options.plugins = options.plugins.concat(window.LESS_PLUGINS);
+ }
+ var less = root(window, options);
+ window.less = less;
+ var css;
+ var head;
+ var style;
+ // Always restore page visibility
+ function resolveOrReject(data) {
+ if (data.filename) {
+ console.warn(data);
+ }
+ if (!options.async) {
+ head.removeChild(style);
+ }
+ }
+ if (options.onReady) {
+ if (/!watch/.test(window.location.hash)) {
+ less.watch();
+ }
+ // Simulate synchronous stylesheet loading by hiding page rendering
+ if (!options.async) {
+ css = 'body { display: none !important }';
+ head = document.head || document.getElementsByTagName('head')[0];
+ style = document.createElement('style');
+ style.type = 'text/css';
+ if (style.styleSheet) {
+ style.styleSheet.cssText = css;
+ }
+ else {
+ style.appendChild(document.createTextNode(css));
+ }
+ head.appendChild(style);
+ }
+ less.registerStylesheetsImmediately();
+ less.pageLoadFinished = less.refresh(less.env === 'development').then(resolveOrReject, resolveOrReject);
+ }
+
return less;
- });
- /**
- * Kicks off less and compiles any stylesheets
- * used in the browser distributed version of less
- * to kick-start less using the browser api
- */
- var options$1 = defaultOptions();
-
- if (window.less) {
- for (var key in window.less) {
- if (window.less.hasOwnProperty(key)) {
- options$1[key] = window.less[key];
- }
- }
- }
-
- addDefaultOptions(window, options$1);
- options$1.plugins = options$1.plugins || [];
-
- if (window.LESS_PLUGINS) {
- options$1.plugins = options$1.plugins.concat(window.LESS_PLUGINS);
- }
-
- var less = root(window, options$1);
- window.less = less;
- var css;
- var head;
- var style; // Always restore page visibility
-
- function resolveOrReject(data) {
- if (data.filename) {
- console.warn(data);
- }
-
- if (!options$1.async) {
- head.removeChild(style);
- }
- }
-
- if (options$1.onReady) {
- if (/!watch/.test(window.location.hash)) {
- less.watch();
- } // Simulate synchronous stylesheet loading by hiding page rendering
-
-
- if (!options$1.async) {
- css = 'body { display: none !important }';
- head = document.head || document.getElementsByTagName('head')[0];
- style = document.createElement('style');
- style.type = 'text/css';
-
- if (style.styleSheet) {
- style.styleSheet.cssText = css;
- } else {
- style.appendChild(document.createTextNode(css));
- }
-
- head.appendChild(style);
- }
-
- less.registerStylesheetsImmediately();
- less.pageLoadFinished = less.refresh(less.env === 'development').then(resolveOrReject, resolveOrReject);
- }
-
- return less;
-
-}));
+})));
diff --git a/vendor/less/dist/less.min.js b/vendor/less/dist/less.min.js
index 5472db1a0..ce4c4aa7d 100644
--- a/vendor/less/dist/less.min.js
+++ b/vendor/less/dist/less.min.js
@@ -1,11 +1,11 @@
/**
- * Less - Leaner CSS v3.10.3
+ * Less - Leaner CSS v4.1.2
* http://lesscss.org
*
- * Copyright (c) 2009-2019, Alexis Sellier
+ * Copyright (c) 2009-2021, Alexis Sellier
* Licensed under the Apache-2.0 License.
*
* @license Apache-2.0
*/
-!function(e,t){"object"==typeof exports&&"undefined"!=typeof module?module.exports=t():"function"==typeof define&&define.amd?define(t):(e=e||self).less=t()}(this,function(){"use strict";function e(e){return e.replace(/^[a-z-]+:\/+?[^\/]+/,"").replace(/[\?\&]livereload=\w+/,"").replace(/^\//,"").replace(/\.[a-zA-Z]+$/,"").replace(/[^\.\w-]+/g,"-").replace(/\./g,":")}function t(e,t){for(var n in t.dataset)if(t.dataset.hasOwnProperty(n))if("env"===n||"dumpLineNumbers"===n||"rootpath"===n||"errorReporting"===n)e[n]=t.dataset[n];else try{e[n]=JSON.parse(t.dataset[n])}catch(e){}}var n={createCSS:function(t,n,i){var r=i.href||"",a="less:".concat(i.title||e(r)),s=t.getElementById(a),o=!1,l=t.createElement("style");l.setAttribute("type","text/css"),i.media&&l.setAttribute("media",i.media),l.id=a,l.styleSheet||(l.appendChild(t.createTextNode(n)),o=null!==s&&s.childNodes.length>0&&l.childNodes.length>0&&s.firstChild.nodeValue===l.firstChild.nodeValue);var u=t.getElementsByTagName("head")[0];if(null===s||!1===o){var c=i&&i.nextSibling||null;c?c.parentNode.insertBefore(l,c):u.appendChild(l)}if(s&&!1===o&&s.parentNode.removeChild(s),l.styleSheet)try{l.styleSheet.cssText=n}catch(e){throw new Error("Couldn't reassign styleSheet.cssText.")}},currentScript:function(e){var t,n=e.document;return n.currentScript||(t=n.getElementsByTagName("script"))[t.length-1]}};function i(e){return(i="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(e){return typeof e}:function(e){return e&&"function"==typeof Symbol&&e.constructor===Symbol&&e!==Symbol.prototype?"symbol":typeof e})(e)}function r(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}function a(e,t){for(var n=0;nt?1:void 0};var y=function(e){function t(e,n,i){var a;r(this,t);var s=h(a=f(this,l(t).call(this)));return Array.isArray(e)?a.rgb=e:e.length>=6?(a.rgb=[],e.match(/.{2}/g).map(function(e,t){t<3?s.rgb.push(parseInt(e,16)):s.alpha=parseInt(e,16)/255})):(a.rgb=[],e.split("").map(function(e,t){t<3?s.rgb.push(parseInt(e+e,16)):s.alpha=parseInt(e+e,16)/255})),a.alpha=a.alpha||("number"==typeof n?n:1),void 0!==i&&(a.value=i),a}return o(t,g),s(t,[{key:"luma",value:function(){var e=this.rgb[0]/255,t=this.rgb[1]/255,n=this.rgb[2]/255;return.2126*(e=e<=.03928?e/12.92:Math.pow((e+.055)/1.055,2.4))+.7152*(t=t<=.03928?t/12.92:Math.pow((t+.055)/1.055,2.4))+.0722*(n=n<=.03928?n/12.92:Math.pow((n+.055)/1.055,2.4))}},{key:"genCSS",value:function(e,t){t.add(this.toCSS(e))}},{key:"toCSS",value:function(e,t){var n,i,r,a=e&&e.compress&&!t,s=[];if(i=this.fround(e,this.alpha),this.value)if(0===this.value.indexOf("rgb"))i<1&&(r="rgba");else{if(0!==this.value.indexOf("hsl"))return this.value;r=i<1?"hsla":"hsl"}else i<1&&(r="rgba");switch(r){case"rgba":s=this.rgb.map(function(e){return b(Math.round(e),255)}).concat(b(i,1));break;case"hsla":s.push(b(i,1));case"hsl":n=this.toHSL(),s=[this.fround(e,n.h),"".concat(this.fround(e,100*n.s),"%"),"".concat(this.fround(e,100*n.l),"%")].concat(s)}if(r)return"".concat(r,"(").concat(s.join(",".concat(a?"":" ")),")");if(n=this.toRGB(),a){var o=n.split("");o[1]===o[2]&&o[3]===o[4]&&o[5]===o[6]&&(n="#".concat(o[1]).concat(o[3]).concat(o[5]))}return n}},{key:"operate",value:function(e,n,i){for(var r=new Array(3),a=this.alpha*(1-i.alpha)+i.alpha,s=0;s<3;s++)r[s]=this._operate(e,n,this.rgb[s],i.rgb[s]);return new t(r,a)}},{key:"toRGB",value:function(){return w(this.rgb)}},{key:"toHSL",value:function(){var e,t,n=this.rgb[0]/255,i=this.rgb[1]/255,r=this.rgb[2]/255,a=this.alpha,s=Math.max(n,i,r),o=Math.min(n,i,r),l=(s+o)/2,u=s-o;if(s===o)e=t=0;else{switch(t=l>.5?u/(2-s-o):u/(s+o),s){case n:e=(i-r)/u+(i0&&void 0!==arguments[0]?arguments[0]:{},t=this.value,n=e.firstSelector;return t instanceof k&&(e.firstSelector=!0),t=t.toCSS?t.toCSS(e):t,e.firstSelector=n,""===t&&"&"===this.combinator.value.charAt(0)?"":this.combinator.toCSS(e)+t}}]),t}();I.prototype.type="Element";var C={ALWAYS:0,PARENS_DIVISION:1,PARENS:2,STRICT_LEGACY:3},_={OFF:0,LOCAL:1,ALL:2};var A=function(e,t){return e(t={exports:{}},t.exports),t.exports}(function(e){var t=function(){function e(e,t){return null!=t&&e instanceof t}var t,n,i;try{t=Map}catch(e){t=function(){}}try{n=Set}catch(e){n=function(){}}try{i=Promise}catch(e){i=function(){}}function r(a,o,l,u,c){"object"==typeof o&&(l=o.depth,u=o.prototype,c=o.includeNonEnumerable,o=o.circular);var h=[],f=[],p="undefined"!=typeof Buffer;return void 0===o&&(o=!0),void 0===l&&(l=1/0),function a(l,v){if(null===l)return null;if(0===v)return l;var d,m;if("object"!=typeof l)return l;if(e(l,t))d=new t;else if(e(l,n))d=new n;else if(e(l,i))d=new i(function(e,t){l.then(function(t){e(a(t,v-1))},function(e){t(a(e,v-1))})});else if(r.__isArray(l))d=[];else if(r.__isRegExp(l))d=new RegExp(l.source,s(l)),l.lastIndex&&(d.lastIndex=l.lastIndex);else if(r.__isDate(l))d=new Date(l.getTime());else{if(p&&Buffer.isBuffer(l))return d=Buffer.allocUnsafe?Buffer.allocUnsafe(l.length):new Buffer(l.length),l.copy(d),d;e(l,Error)?d=Object.create(l):void 0===u?(m=Object.getPrototypeOf(l),d=Object.create(m)):(d=Object.create(u),m=u)}if(o){var g=h.indexOf(l);if(-1!=g)return f[g];h.push(l),f.push(d)}for(var y in e(l,t)&&l.forEach(function(e,t){var n=a(t,v-1),i=a(e,v-1);d.set(n,i)}),e(l,n)&&l.forEach(function(e){var t=a(e,v-1);d.add(t)}),l){var b;m&&(b=Object.getOwnPropertyDescriptor(m,y)),b&&null==b.set||(d[y]=a(l[y],v-1))}if(Object.getOwnPropertySymbols){var w=Object.getOwnPropertySymbols(l);for(y=0;y=0&&"\n"!==t.charAt(n);)r++;return"number"==typeof e&&(i=(t.slice(0,e).match(/\n/g)||"").length),{line:i,column:r}}function P(e){var t,n=e.length,i=new Array(n);for(t=0;t1&&void 0!==arguments[1]?arguments[1]:[],n=0,i=e.length;n|Function):(\d+):(\d+)/);c&&(c[2]&&(this.line=parseInt(c[2])-2),c[3]&&(this.column=parseInt(c[3])))}this.callLine=l+1,this.callExtract=u[l],this.extract=[u[this.line-2],u[this.line-1],u[this.line]]}};if(void 0===Object.create){var L=function(){};L.prototype=Error.prototype,$.prototype=new L}else $.prototype=Object.create(Error.prototype);$.prototype.constructor=$,$.prototype.toString=function(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{},t="",n=this.extract||[],r=[],a=function(e){return e};if(e.stylize){var s=i(e.stylize);if("function"!==s)throw Error("options.stylize should be a function, got a ".concat(s,"!"));a=e.stylize}if(null!==this.line){if("string"==typeof n[0]&&r.push(a("".concat(this.line-1," ").concat(n[0]),"grey")),"string"==typeof n[1]){var o="".concat(this.line," ");n[1]&&(o+=n[1].slice(0,this.column)+a(a(a(n[1].substr(this.column,1),"bold")+n[1].slice(this.column+1),"red"),"inverse")),r.push(o)}"string"==typeof n[2]&&r.push(a("".concat(this.line+1," ").concat(n[2]),"grey")),r="".concat(r.join("\n")+a("","reset"),"\n")}return t+=a("".concat(this.type,"Error: ").concat(this.message),"red"),this.filename&&(t+=a(" in ","red")+this.filename),this.line&&(t+=a(" on line ".concat(this.line,", column ").concat(this.column+1,":"),"grey")),t+="\n".concat(r),this.callLine&&(t+="".concat(a("from ","red")+(this.filename||""),"/n"),t+="".concat(a(this.callLine,"grey")," ").concat(this.callExtract,"/n")),t};var D=function(e){function t(e,n,i,a,s,o){var u;return r(this,t),(u=f(this,l(t).call(this))).extendList=n,u.condition=i,u.evaldCondition=!i,u._index=a,u._fileInfo=s,u.elements=u.getElements(e),u.mixinElements_=void 0,u.copyVisibilityInfo(o),u.setParent(u.elements,h(u)),u}return o(t,g),s(t,[{key:"accept",value:function(e){this.elements&&(this.elements=e.visitArray(this.elements)),this.extendList&&(this.extendList=e.visitArray(this.extendList)),this.condition&&(this.condition=e.visit(this.condition))}},{key:"createDerived",value:function(e,n,i){var r=new t(e=this.getElements(e),n||this.extendList,null,this.getIndex(),this.fileInfo(),this.visibilityInfo());return r.evaldCondition=null!=i?i:this.evaldCondition,r.mediaEmpty=this.mediaEmpty,r}},{key:"getElements",value:function(e){return e?("string"==typeof e&&this.parse.parseNode(e,["selector"],this._index,this._fileInfo,function(t,n){if(t)throw new $({index:t.index,message:t.message},this.parse.imports,this._fileInfo.filename);e=n[0].elements}),e):[new I("","&",!1,this._index,this._fileInfo)]}},{key:"createEmptySelectors",value:function(){var e=[new t([new I("","&",!1,this._index,this._fileInfo)],null,null,this._index,this._fileInfo)];return e[0].mediaEmpty=!0,e}},{key:"match",value:function(e){var t,n,i=this.elements,r=i.length;if(0===(t=(e=e.mixinElements()).length)||rC.PARENS_DIVISION)||this.parensStack&&this.parensStack.length))}},{key:"pathRequiresRewrite",value:function(e){return(this.rewriteUrls===_.LOCAL?K:Q)(e)}},{key:"rewritePath",value:function(e,t){var n;return t=t||"",n=this.normalizePath(t+e),K(e)&&Q(t)&&!1===K(n)&&(n="./".concat(n)),n}},{key:"normalizePath",value:function(e){var t,n=e.split("/").reverse();for(e=[];0!==n.length;)switch(t=n.pop()){case".":break;case"..":0===e.length||".."===e[e.length-1]?e.push(t):e.pop();break;default:e.push(t)}return e.join("/")}}]),e}();var Z=function e(t){return{_data:{},add:function(e,t){e=e.toLowerCase(),this._data.hasOwnProperty(e),this._data[e]=t},addMultiple:function(e){var t=this;Object.keys(e).forEach(function(n){t.add(n,e[n])})},get:function(e){return this._data[e]||t&&t.get(e)},getLocalFunctions:function(){return this._data},inherit:function(){return e(this)},create:function(t){return e(t)}}}(null),Y={eval:function(){var e=this.value_,t=this.error_;if(t)throw t;if(null!=e)return e?j.True:j.False},value:function(e){this.value_=e},error:function(e){this.error_=e},reset:function(){this.value_=this.error_=null}},X=function(e){function t(e,n,i,a){var s;return r(this,t),(s=f(this,l(t).call(this))).selectors=e,s.rules=n,s._lookups={},s._variables=null,s._properties=null,s.strictImports=i,s.copyVisibilityInfo(a),s.allowRoot=!0,s.setParent(s.selectors,h(s)),s.setParent(s.rules,h(s)),s}return o(t,g),s(t,[{key:"isRulesetLike",value:function(){return!0}},{key:"accept",value:function(e){this.paths?this.paths=e.visitArray(this.paths,!0):this.selectors&&(this.selectors=e.visitArray(this.selectors)),this.rules&&this.rules.length&&(this.rules=e.visitArray(this.rules))}},{key:"eval",value:function(e){var n,i,r,a,s,o=!1;if(this.selectors&&(i=this.selectors.length)){for(n=new Array(i),Y.error({type:"Syntax",message:"it is currently only allowed in parametric mixin guards,"}),a=0;a0;e--){var t=this.rules[e-1];if(t instanceof q)return this.parseValue(t)}}},{key:"parseValue",value:function(e){var t=this;function n(e){return e.value instanceof B&&!e.parsed?("string"==typeof e.value.value?this.parse.parseNode(e.value.value,["value","important"],e.value.getIndex(),e.fileInfo(),function(t,n){t&&(e.parsed=!0),n&&(e.value=n[0],e.important=n[1]||"",e.parsed=!0)}):e.parsed=!0,e):e}if(Array.isArray(e)){var i=[];return e.forEach(function(e){i.push(n.call(t,e))}),i}return n.call(t,e)}},{key:"rulesets",value:function(){if(!this.rules)return[];var e,t,n=[],i=this.rules;for(e=0;t=i[e];e++)t.isRuleset&&n.push(t);return n}},{key:"prependRule",value:function(e){var t=this.rules;t?t.unshift(e):this.rules=[e],this.setParent(e,this)}},{key:"find",value:function(e){var t,n,i=arguments.length>1&&void 0!==arguments[1]?arguments[1]:this,r=arguments.length>2?arguments[2]:void 0,a=[],s=e.toCSS();return s in this._lookups?this._lookups[s]:(this.rulesets().forEach(function(s){if(s!==i)for(var o=0;ot){if(!r||r(s)){n=s.find(new D(e.elements.slice(t)),i,r);for(var l=0;l0&&t.add(l),e.firstSelector=!0,s[0].genCSS(e,t),e.firstSelector=!1,i=1;i