Generate CSS

@param {Function} done
351512
function generateStylesheets(done) {
			// Convert codepoints to array of strings
			var codepoints = [];
			_.each(o.glyphs, function(name) {
				codepoints.push(o.codepoints[name].toString(16));
			});
			o.codepoints = codepoints;

			// Prepage glyph names to use as CSS classes
			o.glyphs = _.map(o.glyphs, classnameize);

			o.stylesheets.sort(function(a, b) {
				return a === 'css' ? 1 : -1;
			}).forEach(generateStylesheet);

			done();
		}
1058072
function generateTheme({
  stylesDir,
  mainLessFile,
  varFile,
  outputFilePath,
  themeVariables
}) {
  return new Promise((resolve, reject) => {
    /*
      You own custom styles (Change according to your project structure)
      
      - stylesDir - styles directory containing all less files
      - varFile - variable file containing your custom variables
      - mainLessFile - less main file which imports all styles
    */
    let content = '';
    // const hashCode = hash.sha256().update(content).digest('hex');
    // if(hashCode === hashCache){
    //   resolve(cssCache);
    //   return;
    // }
    // hashCache = hashCode;
    let themeCompiledVars = {};
    let themeVars = themeVariables || [];
    const lessPaths = [
      stylesDir
    ];

    return bundle({
      src: varFile
    })
      .then(colorsLess => {
        const mappings = Object.assign(generateColorMap(colorsLess), mainLessFile? generateColorMap(mainLessFile): {});
        return [mappings, colorsLess];
      })
      .then(([mappings, colorsLess]) => {
        let css = "";
        /*
         If not pass in themeVariables, the variables in varFile will be used
         */
        if (!themeVariables) {
            let varJs = lessToJs(fs.readFileSync(varFile, 'utf8'));
            themeVars.forEach(varName => {
                delete varJs[varName];
            });
            themeVars.push(...Object.keys(varJs));
        }
        if (!themeVars.length) {
            themeVars.push("@theme-color");
        }
        themeVars = themeVars.filter(name => name in mappings);
        themeVars.forEach(varName => {
          const color = mappings[varName];
          css = `.${varName.replace("@", "")} { color: ${color}; }\n ${css}`;
        });

        css = `${colorsLess}\n${css}`;
        return render(css, lessPaths).then(({ css }) => [
          css,
          mappings,
          colorsLess
        ]);
      })
      .then(([css, mappings, colorsLess]) => {
        css = css.replace(/(\/.*\/)/g, "");
        const regex = /.(?=\S*['-])([.a-zA-Z0-9'-]+)\ {\n\ \ color:\ (.*);/g;
        themeCompiledVars = getMatches(css, regex);
        content = `${content}\n${colorsLess}`;
        return render(content, lessPaths).then(({ css }) => {
          return getCssModulesStyles(stylesDir).then(customCss => {
            return [
              `${customCss}\n${css}`,
              mappings,
              colorsLess
            ];
          })
          
        });
      })
      .then(([css, mappings, colorsLess]) => {
        return postcss([reducePlugin(themeCompiledVars)])
          .process(css, {
            parser: less.parser,
            from: mainLessFile | varFile
          })
          .then(({ css }) => [css, mappings, colorsLess]);
      })
      .then(([css, mappings, colorsLess]) => {
        Object.keys(themeCompiledVars).forEach(varName => {
          let color;
          if (/(.*)-(\d)/.test(varName)) {
            color = themeCompiledVars[varName];
            varName = getShade(varName);
          } else {
            color = themeCompiledVars[varName];
          }
          color = color.replace('(', '\\(').replace(')', '\\)');
          css = css.replace(new RegExp(`${color}`, "g"), varName);
        });

        css = `${colorsLess}\n${css}`;

        themeVars.reverse().forEach(varName => {
          css = css.replace(new RegExp(`${varName}(\ *):(.*);`, 'g'), '');
          css = `${varName}: ${mappings[varName]};\n${css}\n`;
        });
        css = css.replace(/\n+/g, '\n');

        css = uniqueCss(css);

        if (outputFilePath) {
          fs.writeFileSync(outputFilePath, css);
          console.log(
            `Theme generated successfully. OutputFile: ${outputFilePath}`
          );
        } else {
          console.log(`Theme generated successfully`);
        }
        cssCache = css;
        return resolve(css);
      })
      .catch(err => {
        console.log("Error", err);
        reject(err);
      });
  });
}
756072
function defineDocumentStyles() {
  for (var i = 0; i < document.styleSheets.length; i++) {
    var mysheet = document.styleSheets[i],
      myrules = mysheet.cssRules ? mysheet.cssRules : mysheet.rules;
    config.documentStyles.push(myrules);
  }
}
209881
def generate_css(self, output_file):
        
        if self.CSS_TEMPLATE_NAME is not None:
            template = TEMPLATE_ENV.get_template(self.CSS_TEMPLATE_NAME)
            style = template.render(self._context())

        if isinstance(style, six.string_types):
            style = style.encode('utf-8')

        output_file.write(style)
694965
function compileCSS(style, parser, opts) {
    if (typeof parser === 'object') {
      opts = parser
      parser = ''
    }
    return _compileCSS(style, opts.tagName, parser, opts)
  }
850255
function generateAllThemes($injector, $mdTheming) {
  var head = document.head;
  var firstChild = head ? head.firstElementChild : null;
  var themeCss = !themeConfig.disableTheming && $injector.has('$MD_THEME_CSS') ? $injector.get('$MD_THEME_CSS') : '';

  // Append our custom registered styles to the theme stylesheet.
  themeCss += themeConfig.registeredStyles.join('');

  if (!firstChild) return;
  if (themeCss.length === 0) return; // no rules, so no point in running this expensive task

  // Expose contrast colors for palettes to ensure that text is always readable
  angular.forEach(PALETTES, sanitizePalette);

  // MD_THEME_CSS is a string generated by the build process that includes all the themable
  // components as templates

  // Break the CSS into individual rules
  var rules = themeCss
                  .split(/\}(?!(\}|'|"|;))/)
                  .filter(function(rule) { return rule && rule.trim().length; })
                  .map(function(rule) { return rule.trim() + '}'; });

  THEME_COLOR_TYPES.forEach(function(type) {
    rulesByType[type] = '';
  });

  // Sort the rules based on type, allowing us to do color substitution on a per-type basis
  rules.forEach(function(rule) {
    // First: test that if the rule has '.md-accent', it goes into the accent set of rules
    for (var i = 0, type; type = THEME_COLOR_TYPES[i]; i++) {
      if (rule.indexOf('.md-' + type) > -1) {
        return rulesByType[type] += rule;
      }
    }

    // If no eg 'md-accent' class is found, try to just find 'accent' in the rule and guess from
    // there
    for (i = 0; type = THEME_COLOR_TYPES[i]; i++) {
      if (rule.indexOf(type) > -1) {
        return rulesByType[type] += rule;
      }
    }

    // Default to the primary array
    return rulesByType[DEFAULT_COLOR_TYPE] += rule;
  });

  // If themes are being generated on-demand, quit here. The user will later manually
  // call generateTheme to do this on a theme-by-theme basis.
  if (themeConfig.generateOnDemand) return;

  angular.forEach($mdTheming.THEMES, function(theme) {
    if (!GENERATED[theme.name] && !($mdTheming.defaultTheme() !== 'default' && theme.name === 'default')) {
      generateTheme(theme, theme.name, themeConfig.nonce);
    }
  });


  // *************************
  // Internal functions
  // *************************

  // The user specifies a 'default' contrast color as either light or dark,
  // then explicitly lists which hues are the opposite contrast (eg. A100 has dark, A200 has light)
  function sanitizePalette(palette, name) {
    var defaultContrast = palette.contrastDefaultColor;
    var lightColors = palette.contrastLightColors || [];
    var strongLightColors = palette.contrastStrongLightColors || [];
    var darkColors = palette.contrastDarkColors || [];

    // These colors are provided as space-separated lists
    if (typeof lightColors === 'string') lightColors = lightColors.split(' ');
    if (typeof strongLightColors === 'string') strongLightColors = strongLightColors.split(' ');
    if (typeof darkColors === 'string') darkColors = darkColors.split(' ');

    // Cleanup after ourselves
    delete palette.contrastDefaultColor;
    delete palette.contrastLightColors;
    delete palette.contrastStrongLightColors;
    delete palette.contrastDarkColors;

    // Change { 'A100': '#fffeee' } to { 'A100': { value: '#fffeee', contrast:DARK_CONTRAST_COLOR }
    angular.forEach(palette, function(hueValue, hueName) {
      if (angular.isObject(hueValue)) return; // Already converted
      // Map everything to rgb colors
      var rgbValue = colorToRgbaArray(hueValue);
      if (!rgbValue) {
        throw new Error("Color %1, in palette %2's hue %3, is invalid. Hex or rgb(a) color expected."
                        .replace('%1', hueValue)
                        .replace('%2', palette.name)
                        .replace('%3', hueName));
      }

      palette[hueName] = {
        hex: palette[hueName],
        value: rgbValue,
        contrast: getContrastColor()
      };
      function getContrastColor() {
        if (defaultContrast === 'light') {
          if (darkColors.indexOf(hueName) > -1) {
            return DARK_CONTRAST_COLOR;
          } else {
            return strongLightColors.indexOf(hueName) > -1 ? STRONG_LIGHT_CONTRAST_COLOR
              : LIGHT_CONTRAST_COLOR;
          }
        } else {
          if (lightColors.indexOf(hueName) > -1) {
            return strongLightColors.indexOf(hueName) > -1 ? STRONG_LIGHT_CONTRAST_COLOR
              : LIGHT_CONTRAST_COLOR;
          } else {
            return DARK_CONTRAST_COLOR;
          }
        }
      }
    });
  }
}
408265
function bundleCSS() {
    const glob      = require('glob');
    const srcmap    = require('./srcmap');
    const BUILT_PATH = path.join(__dirname, '..', config.dir.built);

    glob.sync('**/*.css', {
        cwd: BUILT_PATH
    }).forEach((file) => {
        const src = fs.readFileSync(path.join(BUILT_PATH, file)).toString()
            .replace(/^\ufeff/gm, '')
            .replace(/\r\n/gm, '\n')
        ;
        const node = srcmap.getNodeFromCode(src);
        node.prepend(banner('.css', path.basename(file, '.css')));
        const bundleSrc = '\ufeff' + srcmap.getCodeFromNode(node, (srcPath) => {
            const regex_src = new RegExp(`${config.dir.src}\\/${config.dir.stylesheet}\\/`);
            return srcPath
                .replace(/\.\.\//g, '')
                .replace(regex_src, SOURCE_MAP_NAMESPACE)
            ;
        }, { multiline: true });
        fs.writeFileSync(path.join(BUILT_PATH, file), bundleSrc);
        fs.writeFileSync(path.join(DST_PATH, file), bundleSrc);
    });
}
1353019
function completeOutput(outputCSS = '') {


		if (OPTIONS.css_output !== '') {
			// console.log(outputCSS)


			//write output
			try {
				if (OPTIONS.format_4095_rules_legacy_limit) {
					// console.log(summary.stats.after.noRules)
					var noOutputFilesNeeded = Math.ceil(summary.stats.after.noRules / 4095);
					// console.log(noOutputFilesNeeded)
					

					if (noOutputFilesNeeded == 1) {

						outputCSS = trimCSS(outputCSS);
						outputCSS = restoreHacks(outputCSS);
						write(OPTIONS.css_output, outputCSS);
						filesizeKB = getFilesizeInKiloBytes(OPTIONS.css_output);
					} else { //group 4095 rules

						try {
							var ast = css.parse(outputCSS, { source: fileLocation });
						} catch(err) {
							console.log(error("CSS Parser2 Error: probably have something funny in your CSS, change it then please try again."));
							console.log('Reason: ' + err.reason);
							console.log('Line: ' + err.line);
							console.log('Column: ' + err.column);
							console.log('Filename: ' + err.filename);
							process.exit(1);
						}

						var rulesGroups = [];
						var rulesGroupsLen = 0;
						var rules = ast.stylesheet.rules;
						var ruleslen = rules.length;
						var ruleCount = 0;
						var groupCount = 0;

						for (i = 0; i < ruleslen; ++i) {

							if (rulesGroups[groupCount] === undefined) {
								rulesGroups[groupCount] = [];
							}
							rulesGroups[groupCount].push(rules[i]);
							ruleCount += 1;

							if (ruleCount == 4095) {
								groupCount += 1;
							}
						}
						rulesGroupsLen = rulesGroups.length;
						filesizeKB = 0;
						outputFilename = '';
						for (i = 0; i < rulesGroupsLen; i++) {

							outputAST = {
								type: 'stylesheet',
								stylesheet: {
									rules: rulesGroups[i]
								}
							};
							outputCSS = css.stringify(outputAST);

							outputCSS = trimCSS(outputCSS);
							outputCSS = restoreHacks(outputCSS);
							outputFilename = OPTIONS.css_output.substr(0, OPTIONS.css_output.length-4) + '_' + i + '.css';
							write(outputFilename, outputCSS);

							filesizeKB += getFilesizeInKiloBytes(outputFilename);
						}
					}
					
				} else {
					outputCSS = trimCSS(outputCSS);
					outputCSS = restoreHacks(outputCSS);
					if (OPTIONS.css_output === null || OPTIONS.css_output === undefined || OPTIONS.css_output == '') {
						var size = kiloByteLength(outputCSS);
						filesizeKB = size/1000;
					} else {
						write(OPTIONS.css_output, outputCSS);
						filesizeKB = getFilesizeInKiloBytes(OPTIONS.css_output);
					}
				}
				
			} catch(e) {
				console.log(error("Output file error: Something went wrong while writing the file, check your folder permissions, config_css.json and please try again."));
				console.log(e);
				process.exit(1);
			}

		} else {
			outputCSS = trimCSS(outputCSS);
			outputCSS = restoreHacks(outputCSS);
			filesizeKB = kiloByteLength(outputCSS);
		}

		summary.stats.after.totalFileSizeKB += filesizeKB;
		summary.stats.summary.savingsKB = roundTo(summary.stats.before.totalFileSizeKB - summary.stats.after.totalFileSizeKB, 4);
		summary.stats.summary.savingsPercentage = roundTo(summary.stats.summary.savingsKB / summary.stats.before.totalFileSizeKB * 100, 2);

		//write report
		if (OPTIONS.generate_report) {

			try {
				var cssdata = JSON.stringify(summary, null, '\t');
				write(REPORT_DUPLICATE_CSS, JSON.stringify(summary, null, '\t'));
			} catch(e) {
				console.log(error("Report output file error: Something went wrong while writing the file, check your folder permissions, config_css.json and please try again."));
				console.log(e);
				process.exit(1);
			}
		}

		if (OPTIONS.verbose) {

			console.log(cool('Before: ' + summary.stats.before.totalFileSizeKB + 'KB'));
			console.log(cool('After: ' + summary.stats.after.totalFileSizeKB + 'KB'));
			console.log(cool('Saved: ' + summary.stats.summary.savingsKB + 'KB (' + summary.stats.summary.savingsPercentage + '%)'));

			console.timeEnd(logoRed("Purged " + timeLabel + " in "));
		}

		if (OPTIONS.css_output === null || OPTIONS.css_output === undefined || OPTIONS.css_output == '') {
			return outputCSS;
		} else {

			// console.log(OPTIONS.css_output);
			
		}
	}
1324948
function creds(done) {
  var configPath = './config.json';
  try { CONFIG = JSON.parse(fs.readFileSync(configPath)); }
  catch(e) {
    beep();
    console.log('[AWS]'.bold.red + ' Sorry, there was an issue locating your config.json. Please see README.md');
    process.exit();
  }
  done();
}
1279377
function generateStyle( data, type ) {
			var content = "";
			var pattern = outputPattern[ type ];

			function resolveNested( data, parentKey ) {
				var name, key;
				for ( key in data ) {
					if ( data.hasOwnProperty( key ) ) {
						name = parentKey ? format( parentKey + "-" + key, options.cssFormat ) : format( key, options.cssFormat );

						if ( mout.lang.isObject( data[ key ] ) ) {

							resolveNested( data[ key ], name );

						} else {
							var converter = styleConverter[ type ] || getStyleSafeValue;
							var value = converter( data[ key ] );

							content += pattern.replace( "{{key}}", options.namespace + name ).replace( "{{value}}", value );
						}
					}
				}
			}

			resolveNested( data );

			return content;
		}
493178
function(from, to, delay) {
    function step(params, duration, timing) {
      if (params.duration !== undefined) {
        duration = params.duration;
      }
      if (params.timing !== undefined) {
        timing = params.timing;
      }

      return {
        css: params.css || params,
        duration: duration,
        timing: timing
      };
    }

    return this.saveStyle()
      .queue(step(from, 0, this.defaults.timing))
      .wait(delay === undefined ? this.defaults.delay : delay)
      .queue(step(to, this.defaults.duration, this.defaults.timing))
      .restoreStyle();
  }
345450
function handleComplete() {
        const isComplete = cssArray.indexOf(null) === -1;

        if (isComplete) {
            const cssText = cssArray.join('');

            settings.onComplete(cssText, cssArray, sourceNodes);
        }
    }
236327
function(style, url, callback) {
    var text = style.textContent;
    var done = function(text) {
      style.textContent = text;
      callback(style);
    };
    this.resolve(text, url, done);
  }
824236
function done (start, startTime, distance, settings) {
      window.scrollTo(0, start + distance);

      // If it exists, run the callback:
      if (typeof settings.callback === 'function') {
        settings.callback();
      }

      // Reset time for next render:
      startTime = false;
    }
763711
function cleanOutputDir(done) {
			var htmlDemoFileMask = path.join(o.destCss, o.fontBaseName + '*.{css,html}');
			var files = glob.sync(htmlDemoFileMask).concat(wf.generatedFontFiles(o));
			async.forEach(files, function(file, next) {
				fs.unlink(file, next);
			}, done);
		}
1095033
function appendCSS(cssText, element) {
  console.log(element);
  const styleElement = document.createElement('style');
  styleElement.setAttribute('type', 'text/css');
  styleElement.innerHTML = cssText;
  const refNode = element.hasChildNodes() ? element.children[0] : null;
  element.insertBefore(styleElement, refNode);
}
1369536
function init (done) {
    var node = tools.match_ext(filename, 'node')
    var json = tools.match_ext(filename, 'json')

    done(null, {
      content: content,
      json: json,
      node: node,
      // all other files are considered as javascript files.
      js: !node && !json,
    })
  }