-
Notifications
You must be signed in to change notification settings - Fork 20
/
options.js
247 lines (206 loc) · 8.18 KB
/
options.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
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
import { Meteor } from 'meteor/meteor';
import R from 'ramda';
import checkNpmPackage from './check-npm-package';
import { createReplacer } from './text-replacer';
import sha1 from './sha1';
import cjson from 'cjson';
import ImportPathHelpers from './helpers/import-path-helpers';
import jsonToRegex from 'json-to-regex';
import path from 'path';
import fs from 'fs';
import appModulePath from 'app-module-path';
appModulePath.addPath(ImportPathHelpers.basePath + '/node_modules/');
const optionsFilePath = path.join(ImportPathHelpers.basePath || '', 'package.json');
const pluginOptions = {};
loadOptions();
export { loadOptions as reloadOptions };
export default pluginOptions;
function getDefaultOptions() {
return {
cache: {
enableCache: true,
},
cssClassNamingConvention: {
replacements: []
},
defaultIgnorePath: 'node_modules/.*/(examples|docs|test|tests)/',
enableDebugLog: false,
enableProfiling: false,
enableSassCompilation: ['scss', 'sass'],
enableLessCompilation: ['less'],
enableStylusCompilation: ['styl', 'm.styl'],
explicitIncludes: [],
extensions: ['css', 'm.css', 'mss'],
filenames: [],
globalVariablesText: '',
ignorePaths: [],
includePaths: [],
jsClassNamingConvention: {
camelCase: false
},
missingClassErrorLevel: 'warn',
missingClassIgnoreList: [],
outputJsFilePath: '{dirname}/{basename}{extname}',
outputCssFilePath: '{dirname}/{basename}{extname}',
passthroughPaths: [],
specificArchitecture: 'web',
hash: null
};
}
export function getHash() {
return pluginOptions.options.hash;
}
function loadOptions() {
let options = null;
if (fs.existsSync(optionsFilePath)) {
options = cjson.load(optionsFilePath).cssModules;
}
options = options || {};
options = processGlobalVariables(options);
options = R.merge(getDefaultOptions(), options || {});
processPluginOptions(options.postcssPlugins);
if (!Meteor.isDevelopment) {
options.missingClassErrorLevel = false;
}
options.hash = sha1(JSON.stringify(options));
if (options.hash === pluginOptions.hash) {
return pluginOptions.options;
}
processCssClassNamingConventionReplacements(options);
options.passthroughPaths = options.passthroughPaths.map(jsonToRegex);
options.includePaths = options.includePaths.map(jsonToRegex);
options.ignorePaths = [options.defaultIgnorePath, ...options.ignorePaths].map(jsonToRegex);
checkSassCompilation(options);
checkLessCompilation(options);
checkStylusCompilation(options);
return pluginOptions.options = options;
}
function processCssClassNamingConventionReplacements(options) {
if (!options.cssClassNamingConvention || !options.cssClassNamingConvention.replacements) return;
const replacements = options.cssClassNamingConvention.replacements;
options.cssClassNamingConvention.replacements = replacements.map(createReplacer);
}
function checkSassCompilation(options) {
if (!options.enableSassCompilation) {
return;
}
if (options.enableSassCompilation === true ||
(Array.isArray(options.enableSassCompilation) && R.intersection(options.enableSassCompilation, options.extensions).length)) {
const result = checkNpmPackage('node-sass@>=3.x <=4.x');
if (result === true) return;
}
options.enableSassCompilation = false;
}
function checkLessCompilation(options) {
if (!options.enableLessCompilation) return;
if (options.enableLessCompilation === true ||
(Array.isArray(options.enableLessCompilation) && R.intersection(options.enableLessCompilation, options.extensions).length)) {
const result = checkNpmPackage('[email protected]');
if (result === true) return;
}
options.enableLessCompilation = false;
}
function checkStylusCompilation(options) {
if (!options.enableStylusCompilation) return;
if (options.enableStylusCompilation === true ||
(Array.isArray(options.enableStylusCompilation) && R.intersection(options.enableStylusCompilation, options.extensions).length)) {
const result = checkNpmPackage('[email protected]');
if (result === true) return;
}
options.enableStylusCompilation = false;
}
function processGlobalVariables(options) {
if (!options.globalVariables) return options;
const globalVariablesText = [];
const globalVariablesJs = [];
options.globalVariables.forEach(entry => {
switch (R.type(entry)) {
case 'Object':
globalVariablesJs.push(entry);
globalVariablesText.push(convertJsonVariablesToScssVariables(entry));
break;
case 'String':
const fileContents = fs.readFileSync(entry, 'utf-8');
if (path.extname(entry) === '.json') {
const jsonVariables = cjson.parse(fileContents);
globalVariablesJs.push(jsonVariables);
globalVariablesText.push(convertJsonVariablesToScssVariables(jsonVariables));
} else {
globalVariablesJs.push(convertScssVariablesToJsonVariables(fileContents));
globalVariablesText.push(fileContents);
}
break;
}
});
options.globalVariablesJs = R.mergeAll(globalVariablesJs);
options.globalVariablesText = R.join('\n', globalVariablesText);
options.globalVariablesTextLineCount = options.globalVariablesText.split(/\r\n|\r|\n/).length;
return options;
function convertJsonVariablesToScssVariables(variables) {
const convertObjectToKeyValueArray = R.toPairs;
const convertVariablesToScss = R.reduce((variables, pair) => variables + `$${pair[0]}: ${pair[1]};\n`, '');
const processVariables = R.pipe(convertObjectToKeyValueArray, convertVariablesToScss);
return processVariables(variables);
}
function convertScssVariablesToJsonVariables(text) {
const extractVariables = R.match(/^\$.*/gm);
const convertVariableToJson = R.pipe(R.replace(/"/g, '\\"'), R.replace(/\$(.*):\s*(.*);/g, '"$1":"$2"'));
const surroundWithBraces = (str) => `{${str}}`;
const processText = R.pipe(extractVariables, R.map(convertVariableToJson), R.join(',\n'), surroundWithBraces, cjson.parse);
return processText(text);
}
}
function processPluginOptions(plugins) {
if (!plugins) return;
const keys = Object.keys(plugins);
keys.forEach(key => {
plugins[key] = getPluginOptions(plugins[key]);
});
}
function getPluginOptions(pluginEntry) {
let combinedOptions = pluginEntry.inlineOptions !== undefined ? pluginEntry.inlineOptions : undefined;
let fileOptions;
if (R.type(pluginEntry.fileOptions) === 'Array') {
const getFilesAsJson = R.compose(R.reduce(deepExtend, {}), R.map(R.compose(loadJsonOrMssFile, decodeFilePath)));
fileOptions = getFilesAsJson(pluginEntry.fileOptions);
if (Object.keys(fileOptions).length) {
combinedOptions = deepExtend(combinedOptions || {}, fileOptions || {});
}
}
return combinedOptions;
}
function loadJsonOrMssFile(filePath) {
const removeLastOccurrence = (character, str) => {
const index = str.lastIndexOf(character);
return str.substring(0, index) + str.substring(index + 1);
};
const loadMssFile = R.compose(variables => ({ variables: variables }), cjson.parse, str => `{${str}}`, R.curry(removeLastOccurrence)(','), R.replace(/\$(.*):\s*(.*),/g, '"$1":"$2",'), R.replace(/;/g, ','), R.partialRight(fs.readFileSync, ['utf-8']));
return filePath.endsWith('.json') ? cjson.load(filePath) : loadMssFile(filePath);
}
function decodeFilePath(filePath) {
const match = filePath.match(/{(.*)}\/(.*)$/);
if (!match) return filePath;
if (match[1] === '') return match[2];
const paths = [];
paths[1] = paths[0] = `packages/${match[1].replace(':', '_')}/${match[2]}`;
if (!fs.existsSync(paths[0])) {
paths[2] = paths[0] = 'packages/' + match[1].replace(/.*:/, '') + '/' + match[2];
}
if (!fs.existsSync(paths[0])) {
throw new Error(`Path not exist: ${filePath}\nTested path 1: ${paths[1]}\nTest path 2: ${paths[2]}`);
}
return paths[0];
}
function deepExtend(destination, source) {
for (let property in source) {
if (source[property] && source[property].constructor &&
source[property].constructor === Object) {
destination[property] = destination[property] || {};
// eslint-disable-next-line no-caller
arguments.callee(destination[property], source[property]);
} else {
destination[property] = source[property];
}
}
return destination;
}