This repository has been archived by the owner on Jan 28, 2020. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 4
/
Copy pathindex.js
97 lines (80 loc) · 2.7 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
const mediaQueryText = require('mediaquery-text');
const cheerio = require('cheerio');
const extend = require('extend');
const pick = require('object.pick');
function replaceCodeBlock(html, re, block) {
return html.replace(re, () => block);
}
module.exports = (html, options, callback) => {
const results = {};
const codeBlocks = {
EJS: { start: '<%', end: '%>' },
HBS: { start: '{{', end: '}}' }
};
const codeBlockLookup = [];
const encodeCodeBlocks = _html => {
let __html = _html;
const blocks = extend(codeBlocks, options.codeBlocks);
Object.keys(blocks).forEach(key => {
const re = new RegExp(`${blocks[key].start}([\\S\\s]*?)${blocks[key].end}`, 'g');
__html = __html.replace(re, match => {
codeBlockLookup.push(match);
return `EXCS_CODE_BLOCK_${codeBlockLookup.length - 1}_`;
});
});
return __html;
};
const decodeCodeBlocks = _html => {
let index;
let re;
let __html = _html;
for (index = 0; index < codeBlockLookup.length; index++) {
re = new RegExp(`EXCS_CODE_BLOCK_${index}_(="")?`, 'gi');
__html = replaceCodeBlock(__html, re, codeBlockLookup[index]);
}
return __html;
};
const encodeEntities = _html => encodeCodeBlocks(_html);
const decodeEntities = _html => decodeCodeBlocks(_html);
let $;
let styleDataList;
let styleData;
$ = cheerio.load(encodeEntities(html), extend({
decodeEntities: false
}, pick(options, [
'xmlMode',
'decodeEntities',
'lowerCaseTags',
'lowerCaseAttributeNames',
'recognizeCDATA',
'recognizeSelfClosing'
])));
results.css = [];
$('style').each((index, element) => {
let mediaQueries;
// if data-embed property exists, skip inlining and removing
if (typeof $(element).data('embed') !== 'undefined') {
return;
}
styleDataList = element.childNodes;
if (styleDataList.length !== 1) {
callback(new Error('empty style element'));
return;
}
styleData = styleDataList[0].data;
if (options.applyStyleTags) {
results.css.push(styleData);
}
if (options.removeStyleTags) {
if (options.preserveMediaQueries) {
mediaQueries = mediaQueryText(element.childNodes[0].nodeValue);
element.childNodes[0].nodeValue = mediaQueries;
}
if (!mediaQueries) {
$(element).remove();
}
}
});
results.html = decodeEntities($.html());
callback(null, results);
};