| 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
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404 |
75x
3x
73x
47x
3x
3x
3x
3x
2x
1x
73x
71x
62x
61x
2x
59x
2x
57x
2x
55x
2x
53x
51x
2x
49x
2x
36x
36x
36x
36x
35x
35x
35x
35x
35x
35x
35x
34x
34x
1x
34x
34x
34x
34x
34x
32x
32x
32x
32x
34x
34x
2x
2x
2x
32x
2x
32x
32x
32x
2x
2x
2x
1x
32x
32x
35x
35x
1x
1x
35x
36x
36x
35x
35x
34x
1x
35x
34x
34x
34x
35x
41x
25x
17x
16x
28x
16x
35x
35x
35x
1x
34x
492x
34x
34x
34x
34x
124x
124x
122x
122x
380x
380x
152x
2x
150x
226x
226x
161x
65x
23x
150x
150x
43x
122x
122x
122x
34x
124x
4x
120x
122x
2x
120x
150x
161x
54x
54x
54x
91x
63x
38x
54x
27x
13x
107x
107x
90x
30x
80x
61x
43x
16x
| // @flow
import fs from 'fs'
import path from 'path'
import glob from 'glob'
import defaultOptions from './constants/defaultOptions'
import postcss from 'postcss'
import selectorParser from 'postcss-selector-parser'
import {
CONFIG_FILENAME,
ERROR_CONFIG_FILE_LOADING,
ERROR_MISSING_CONTENT,
ERROR_MISSING_CSS,
ERROR_EXTRACTER_FAILED,
ERROR_OPTIONS_TYPE,
ERROR_OUTPUT_TYPE,
ERROR_EXTRACTERS_TYPE,
ERROR_WHITELIST_TYPE,
ERROR_STDOUT_TYPE,
ERROR_INFO_TYPE,
ERROR_REJECTED_TYPE,
ERROR_WHITELIST_PATTERNS_TYPE,
IGNORE_ANNOTATION
} from './constants/constants'
import CSS_WHITELIST from './constants/cssWhitelist'
import SELECTOR_STANDARD_TYPES from './constants/selectorTypes'
import DefaultExtractor from './Extractors/DefaultExtractor'
import LegacyExtractor from './Extractors/LegacyExtractor'
class Purgecss {
options: Options
constructor(options: Options | string) {
if (typeof options === 'string' || typeof options === 'undefined')
options = this.loadConfigFile(options)
this.checkOptions(options)
this.options = Object.assign(defaultOptions, options)
}
/**
* Load the configuration file from the path
* @param {string} configFile Path of the config file
*/
loadConfigFile(configFile: string): Options {
const pathConfig = typeof configFile === 'undefined' ? CONFIG_FILENAME : configFile
let options
try {
const t = path.resolve(process.cwd(), pathConfig)
options = require(t)
} catch (e) {
throw new Error(ERROR_CONFIG_FILE_LOADING + e.message)
}
return options
}
/**
* Verify that the purgecss options provided are valid
* @param {object} options Purgecss options
*/
checkOptions(options: Options) {
if (typeof options !== 'object') throw new TypeError(ERROR_OPTIONS_TYPE)
if (!options.content || !options.content.length) throw new Error(ERROR_MISSING_CONTENT)
if (!options.css || !options.css.length) throw new Error(ERROR_MISSING_CSS)
if (options.output && typeof options.output !== 'string')
throw new TypeError(ERROR_OUTPUT_TYPE)
if (options.extractors && !Array.isArray(options.extractors))
throw new TypeError(ERROR_EXTRACTERS_TYPE)
if (options.whitelist && !Array.isArray(options.whitelist))
throw new TypeError(ERROR_WHITELIST_TYPE)
if (options.stdout && typeof options.stdout !== 'boolean')
throw new TypeError(ERROR_STDOUT_TYPE)
if (options.info && typeof options.info !== 'boolean') throw new TypeError(ERROR_INFO_TYPE)
if (options.rejected && typeof options.rejected !== 'boolean')
throw new TypeError(ERROR_REJECTED_TYPE)
if (options.whitelistPatterns && !Array.isArray(options.whitelistPatterns))
throw new TypeError(ERROR_WHITELIST_PATTERNS_TYPE)
}
/**
* Main function that purge the css file
*/
purge(): Array<ResultPurge> {
// Get selectors from content files
const { content, extractors, css } = this.options
const fileFormatContents = ((content.filter(o => typeof o === 'string'): Array<any>): Array<
string
>)
const rawFormatContents = ((content.filter(o => typeof o === 'object'): Array<any>): Array<
RawContent
>)
const cssFileSelectors = this.extractFileSelector(fileFormatContents, extractors)
const cssRawSelectors = this.extractRawSelector(rawFormatContents, extractors)
// Get css selectors and remove unused ones
return this.getCssContents(css, new Set([...cssFileSelectors, ...cssRawSelectors]))
}
/**
* Get the content of the css files, or return the raw content
* @param {array} cssOptions Array of css options, files and raw
* @param {Set} cssSelectors Set of all extracted css selectors
*/
getCssContents(cssOptions: Array<any>, cssSelectors: Set<string>): Array<ResultPurge> {
const sources = []
for (let option of cssOptions) {
let file = null
let cssContent = ''
if (typeof option === 'string') {
file = option
cssContent = this.options.stdin ? file : fs.readFileSync(file, 'utf8')
} else {
cssContent = option.raw
}
let { cleanCss, keyframes } = this.options.keyframes
? this.cutKeyframes(cssContent)
: { cleanCss: cssContent, keyframes: {} }
cleanCss = this.getSelectorsCss(cleanCss, cssSelectors)
if (this.options.keyframes) cleanCss = this.insertUsedKeyframes(cleanCss, keyframes)
sources.push({
file,
css: cleanCss
})
}
return sources
}
/**
* Removes all `@ keyframes` statements and repalces them with a placeholder
* @param {string} css css before it was purged
*/
cutKeyframes(css: string): Object {
// regex copied from https://github.com/scottjehl/Respond/commit/653786df3a54e05ab1f167b7148e8b3ded1db97c
const keyframesRegExp = /@[^@]*keyframes([^{]+)\{(?:[^{}]*\{[^}{]*\})+[^}]+\}/gi
const keyframes = {}
let cleanCss = css
let match
do {
match = keyframesRegExp.exec(cleanCss)
if (match) {
const full = match[0]
const name = match[1].replace(/^(?=\n)$|^\s*|\s*$|\n\n+/gm, '') // removes whitespaces and linebreaks
keyframes[name] = full
}
} while (match)
// replace @keyframes with placeholders
for (let kf in keyframes) {
cleanCss = cleanCss.replace(keyframes[kf], `/* keyframe "${kf}" */`)
}
return {
cleanCss,
keyframes
}
}
/**
* Inserts used `@ keyframes` statements at placeholders
* and removes unused ones
* you must run cutKeyframes before this.
* @param {string} css css after it was purged
* @param {array} keyframes the `keyframes` array that is returned from cutKeyframes
*/
insertUsedKeyframes(css: string, keyframes: Object): string {
let cleanCss = css
for (let kf in keyframes) {
const kfRegExp = new RegExp(`animation.*(${kf})`, 'g')
const placeholderRegExp = new RegExp(`.. keyframe "${kf}" ..`, 'g')
// insert used keyframes
if (kfRegExp.test(cleanCss) && placeholderRegExp.test(cleanCss)) {
cleanCss = cleanCss.replace(placeholderRegExp, keyframes[kf])
}
}
// remove unused keyframe placeholders
cleanCss = cleanCss.replace(/.. keyframe "\S+" ../g, '')
return cleanCss
}
/**
* Extract the selectors present in the passed string using a purgecss extractor
* @param {array} content Array of content
* @param {array} extractors Array of extractors
*/
extractRawSelector(content: Array<RawContent>, extractors?: Array<ExtractorsObj>): Set<string> {
let selectors = new Set()
for (const { raw, extension } of content) {
const extractor = this.getFileExtractor(`.${extension}`, extractors)
selectors = new Set([...selectors, ...this.extractSelectors(raw, extractor)])
}
return selectors
}
/**
* Extract the selectors present in the files using a purgecss extractor
* @param {array} files Array of files path or glob pattern
* @param {array} extractors Array of extractors
*/
extractFileSelector(files: Array<string>, extractors?: Array<ExtractorsObj>): Set<string> {
let selectors = new Set()
for (let globfile of files) {
let filesnames = []
if (fs.existsSync(globfile)) {
filesnames.push(globfile)
} else {
filesnames = glob.sync(globfile)
}
for (let file of filesnames) {
const content = fs.readFileSync(file, 'utf8')
const extractor = this.getFileExtractor(file, extractors)
selectors = new Set([...selectors, ...this.extractSelectors(content, extractor)])
}
}
return selectors
}
/**
* Get the extractor corresponding to the extension file
* @param {string} filename Name of the file
* @param {array} extractors Array of extractors definition objects
*/
getFileExtractor(filename: string, extractors: Array<ExtractorsObj> = []) {
if (!extractors.length) {
if (this.options.legacy === true) return LegacyExtractor
return DefaultExtractor
}
const extractorObj: any = extractors.find(extractor =>
extractor.extensions.find(ext => filename.endsWith(ext))
)
return extractorObj.extractor
}
/**
* Use the extract function of the extractor to get the list of selectors
* @param {string} content Content (e.g: html file)
* @param {object} extractor Purgecss extractor use to extract the selector
*/
extractSelectors(content: string, extractor: Object): Set<string> {
let selectors = new Set()
const arraySelector = extractor.extract(content)
if (arraySelector === null) {
throw new Error(ERROR_EXTRACTER_FAILED)
}
arraySelector.forEach(selector => {
selectors.add(selector)
})
// Remove empty string
selectors.delete('')
return selectors
}
/**
* Use postcss to walk through the css ast and remove unused css
* @param {string} css css to remove selectors from
* @param {*} selectors selectors used in content files
*/
getSelectorsCss(css: string, selectors: Set<string>): string {
const root = postcss.parse(css)
root.walkRules(node => {
const annotation = node.prev()
if (this.isIgnoreAnnotation(annotation)) return
node.selector = selectorParser(selectorsParsed => {
selectorsParsed.walk(selector => {
let selectorsInRule = []
if (selector.type === 'selector') {
// if inside :not pseudo class, ignore
if (
selector.parent &&
selector.parent.value === ':not' &&
selector.parent.type === 'pseudo'
) {
return
}
for (let nodeSelector of selector.nodes) {
const { type, value } = nodeSelector
if (
SELECTOR_STANDARD_TYPES.includes(type) &&
typeof value !== 'undefined'
) {
selectorsInRule.push(value)
} else if (
type === 'tag' &&
!/[+]|(even)|(odd)|^from$|^to$|^\d/.test(value)
) {
// test if we do not have a pseudo class parameter (e.g. 2n in :nth-child(2n))
selectorsInRule.push(value)
}
}
let keepSelector = this.shouldKeepSelector(selectors, selectorsInRule)
if (!keepSelector) {
selector.remove()
}
}
})
}).processSync(node.selector)
const parent = node.parent
// // Remove empty rules
if (!node.selector) node.remove()
if (this.isRuleEmpty(parent)) parent.remove()
})
return root.toString()
}
/**
* Check if the node is a css comment to ignore the selector rule
* @param {object} node Node of postcss abstract syntax tree
*/
isIgnoreAnnotation(node: Object): boolean {
if (node && node.type === 'comment') {
return node.text.includes(IGNORE_ANNOTATION)
}
return false
}
/**
* Check if the node correspond to an empty css rule
* @param {object} node Node of postcss abstract syntax tree
*/
isRuleEmpty(node: Object): boolean {
if (
(node.type === 'decl' && !node.value) ||
((node.type === 'rule' && !node.selector) || (node.nodes && !node.nodes.length)) ||
(node.type === 'atrule' &&
((!node.nodes && !node.params) || (!node.params && !node.nodes.length)))
) {
return true
}
return false
}
/**
* Determine if the selector should be kept, based on the selectors found in the files
* @param {Set} selectorsInContent Set of css selectors found in the content files
* @param {Array} selectorsInRule Array of selectors
*/
shouldKeepSelector(selectorsInContent: Set<string>, selectorsInRule: Array<string>): boolean {
for (let selector of selectorsInRule) {
// legacy
if (this.options.legacy) {
const sels = selector.split(/[^a-z]/g)
let keepSelector = false
for (let sel of sels) {
if (!sel) continue
if (!selectorsInContent.has(sel)) break
keepSelector = true
}
if (keepSelector) return true
if (
selectorsInContent.has(selector) ||
CSS_WHITELIST.includes(selector) ||
this.isSelectorWhitelisted(selector)
)
return true
} else {
// non legacy extractors
// pseudo class
const unescapedSelector = selector.replace(/\\/g, '')
if (unescapedSelector.startsWith(':')) continue
if (
!(
selectorsInContent.has(unescapedSelector) ||
CSS_WHITELIST.includes(unescapedSelector) ||
this.isSelectorWhitelisted(unescapedSelector)
)
) {
return false
}
}
}
return this.options.legacy ? false : true
}
/**
* Check if the selector is whitelisted by the options whitelist or whitelistPatterns
* @param {string} selector css selector
*/
isSelectorWhitelisted(selector: string): boolean {
return !!(
CSS_WHITELIST.includes(selector) ||
(this.options.whitelist &&
this.options.whitelist.some((v: string) => v === selector)) ||
(this.options.whitelistPatterns &&
this.options.whitelistPatterns.some((v: RegExp) => v.test(selector)))
)
}
}
export default Purgecss
|