all files / src/ parser.js

100% Statements 31/31
100% Branches 8/8
100% Functions 8/8
100% Lines 18/18
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39                  25×   38× 38× 38×   38× 15×   15× 15×     38×   38× 34× 51× 51×     34×     38×      
import { plugin } from 'postcss';
import forEach from 'lodash.foreach';
import replaceSymbols from 'icss-replace-symbols';
const importRegexp = /^:import\((.+)\)$/;
const exportRegexp = /^:export$/;
 
/**
 * @param  {function} options.fetch
 * @return {function}
 */
export default plugin('parser', function parser({ fetch } = {}) {
  return css => {
    // https://github.com/postcss/postcss/blob/master/docs/api.md#inputfile
    const file = css.source.input.file;
    const translations = {};
    const exportTokens = {};
 
    css.walkRules(importRegexp, rule => {
      const exports = fetch(RegExp.$1, file);
 
      rule.walkDecls(decl => translations[decl.prop] = exports[decl.value]);
      rule.remove();
    });
 
    replaceSymbols(css, translations);
 
    css.walkRules(exportRegexp, rule => {
      rule.walkDecls(decl => {
        forEach(translations, (value, key) => decl.value = decl.value.replace(key, value));
        exportTokens[decl.prop] = decl.value;
      });
 
      rule.remove();
    });
 
    css.tokens = exportTokens;
  };
});