forked from princed/postcss-modules-values-replace
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.js
201 lines (160 loc) · 6.24 KB
/
index.js
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
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
const postcss = require('postcss');
const path = require('path');
const promisify = require('es6-promisify');
const { CachedInputFileSystem, NodeJsInputFileSystem, ResolverFactory } = require('enhanced-resolve');
const valuesParser = require('postcss-values-parser');
const { urlToRequest } = require('loader-utils');
const ICSSUtils = require('icss-utils');
const matchImports = /^(.+?|\([\s\S]+?\))\s+from\s+("[^"]*"|'[^']*'|[\w-]+)$/;
const matchValueDefinition = /(?:\s+|^)([\w-]+)(:?\s+)(.+?)(\s*)$/g;
const matchImport = /^([\w-]+)(?:\s+as\s+([\w-]+))?/;
const matchPath = /"[^"]*"|'[^']*'/;
const PLUGIN = 'postcss-modules-values-replace';
const INNER_PLUGIN = 'postcss-modules-values-replace-bind';
// Borrowed from enhanced-resolve
const nodeFs = new CachedInputFileSystem(new NodeJsInputFileSystem(), 4000);
const concordContext = {};
const replaceValueSymbols = (valueString, replacements) => {
const value = valuesParser(valueString, { loose: true }).parse();
value.walk((node) => {
if (node.type !== 'word') return;
const replacement = replacements[node.value];
if (replacement != null) {
// eslint-disable-next-line no-param-reassign
node.value = replacement;
}
});
return value.toString();
};
const getDefinition = (atRule, existingDefinitions, requiredDefinitions) => {
let matches;
const definition = {};
// eslint-disable-next-line no-cond-assign
while (matches = matchValueDefinition.exec(atRule.params)) {
const [/* match */, requiredName, middle, value, end] = matches;
// Add to the definitions, knowing that values can refer to each other
definition[requiredName] = replaceValueSymbols(value, existingDefinitions);
if (!requiredDefinitions) {
// eslint-disable-next-line no-param-reassign
atRule.params = requiredName + middle + definition[requiredName] + end;
}
}
return definition;
};
const getImports = (aliases) => {
const imports = {};
aliases.replace(/^\(\s*([\s\S]+)\s*\)$/, '$1').split(/\s*,\s*/).forEach((alias) => {
const tokens = matchImport.exec(alias);
if (tokens) {
const [/* match */, theirName, myName = theirName] = tokens;
imports[theirName] = myName;
} else {
throw new Error(`@value statement "${alias}" is invalid!`);
}
});
return imports;
};
const walk = async (requiredDefinitions, walkFile, root, result) => {
const rules = [];
const fromDir = result.opts.from && path.dirname(result.opts.from);
root.walkAtRules('value', (atRule) => {
rules.push(atRule);
});
const reduceRules = async (definitionsPromise, atRule) => {
const existingDefinitions = await definitionsPromise;
const matches = matchImports.exec(atRule.params);
if (matches) {
// eslint-disable-next-line prefer-const
let [/* match */, aliases, pathString] = matches;
// We can use constants for path names
if (existingDefinitions[pathString]) {
// eslint-disable-next-line prefer-destructuring
pathString = existingDefinitions[pathString];
}
// Do nothing if path is not found
if (!pathString.match(matchPath)) {
return {};
}
const exportsPath = pathString.replace(/['"]/g, '');
const imports = getImports(aliases);
const definitions = await walkFile(exportsPath, fromDir, imports);
return Object.assign(existingDefinitions, definitions);
}
if (atRule.params.indexOf('@value') !== -1) {
result.warn(`Invalid value definition: ${atRule.params}`);
}
const newDefinitions = getDefinition(atRule, existingDefinitions, requiredDefinitions);
return Object.assign(existingDefinitions, newDefinitions);
};
const definitions = await rules.reduce(reduceRules, Promise.resolve({}));
if (requiredDefinitions) {
const validDefinitions = {};
Object.keys(requiredDefinitions).forEach((key) => {
validDefinitions[requiredDefinitions[key]] = definitions[key];
});
result.messages.push({
type: INNER_PLUGIN,
value: validDefinitions,
});
return undefined;
}
return definitions;
};
const walkerPlugin = postcss.plugin(INNER_PLUGIN, (fn, ...args) => fn.bind(null, ...args));
const factory = ({
fs = nodeFs,
noEmitExports = false,
resolve: resolveOptions = {},
preprocessValues = false,
importsAsModuleRequests = false,
replaceInSelectors = false,
} = {}) => async (root, rootResult) => {
const resolver = ResolverFactory.createResolver(Object.assign(
{ fileSystem: fs },
resolveOptions,
));
const resolve = promisify(resolver.resolve, resolver);
const readFile = promisify(fs.readFile, fs);
let preprocessPlugins = [];
if (preprocessValues) {
const rootPlugins = rootResult.processor.plugins;
const oursPluginIndex = rootPlugins
.findIndex(plugin => plugin.postcssPlugin === PLUGIN);
preprocessPlugins = rootPlugins.slice(0, oursPluginIndex);
}
async function walkFile(from, dir, requiredDefinitions) {
const request = importsAsModuleRequests ? urlToRequest(from) : from;
const resolvedFrom = await resolve(concordContext, dir, request);
const content = await readFile(resolvedFrom);
const plugins = [
...preprocessPlugins,
walkerPlugin(walk, requiredDefinitions, walkFile),
];
const result = await postcss(plugins)
.process(content, { from: resolvedFrom });
return result.messages[0].value;
}
const definitions = await walk(null, walkFile, root, rootResult);
rootResult.messages.push({
plugin: PLUGIN,
type: 'values',
values: definitions,
});
root.walk((node) => {
if (node.type === 'decl') {
// eslint-disable-next-line no-param-reassign
node.value = replaceValueSymbols(node.value, definitions);
} else if (node.type === 'atrule' && node.name === 'media') {
// eslint-disable-next-line no-param-reassign
node.params = replaceValueSymbols(node.params, definitions);
} else if (replaceInSelectors && node.type === 'rule') {
// eslint-disable-next-line no-param-reassign
node.selector = ICSSUtils.replaceValueSymbols(node.selector, definitions);
} else if (noEmitExports && node.type === 'atrule' && node.name === 'value') {
node.remove();
}
});
};
const plugin = postcss.plugin(PLUGIN, factory);
module.exports = plugin;
exports.default = plugin;