/
HTMLAsset.js
296 lines (266 loc) Β· 7.04 KB
/
HTMLAsset.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
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
const Asset = require('../Asset');
const api = require('posthtml/lib/api');
const urlJoin = require('../utils/urlJoin');
const render = require('posthtml-render');
const posthtmlTransform = require('../transforms/posthtml');
const htmlnanoTransform = require('../transforms/htmlnano');
const isURL = require('../utils/is-url');
// A list of all attributes that may produce a dependency
// Based on https://developer.mozilla.org/en-US/docs/Web/HTML/Attributes
const ATTRS = {
src: [
'script',
'img',
'audio',
'video',
'source',
'track',
'iframe',
'embed'
],
href: ['link', 'a', 'use'],
srcset: ['img', 'source'],
poster: ['video'],
'xlink:href': ['use', 'image'],
content: ['meta'],
data: ['object']
};
// A list of metadata that should produce a dependency
// Based on:
// - http://schema.org/
// - http://ogp.me
// - https://developer.twitter.com/en/docs/tweets/optimize-with-cards/overview/markup
// - https://msdn.microsoft.com/en-us/library/dn255024.aspx
const META = {
property: [
'og:image',
'og:image:url',
'og:image:secure_url',
'og:audio',
'og:audio:secure_url',
'og:video',
'og:video:secure_url'
],
name: [
'twitter:image',
'msapplication-square150x150logo',
'msapplication-square310x310logo',
'msapplication-square70x70logo',
'msapplication-wide310x150logo',
'msapplication-TileImage',
'msapplication-config'
],
itemprop: [
'image',
'logo',
'screenshot',
'thumbnailUrl',
'contentUrl',
'downloadUrl'
]
};
const SCRIPT_TYPES = {
'application/javascript': 'js',
'text/javascript': 'js',
'application/json': false,
'application/ld+json': 'jsonld',
'text/html': false
};
// Options to be passed to `addURLDependency` for certain tags + attributes
const OPTIONS = {
a: {
href: {entry: true}
},
iframe: {
src: {entry: true}
}
};
class HTMLAsset extends Asset {
constructor(name, options) {
super(name, options);
this.type = 'html';
this.isAstDirty = false;
this.hmrPageReload = true;
}
async parse(code) {
let res = await posthtmlTransform.parse(code, this);
res.walk = api.walk;
res.match = api.match;
return res;
}
processSingleDependency(path, opts) {
let assetPath = this.addURLDependency(path, opts);
if (!isURL(assetPath)) {
assetPath = urlJoin(this.options.publicURL, assetPath);
}
return assetPath;
}
collectSrcSetDependencies(srcset, opts) {
const newSources = [];
for (const source of srcset.split(',')) {
const pair = source.trim().split(' ');
if (pair.length === 0) continue;
pair[0] = this.processSingleDependency(pair[0], opts);
newSources.push(pair.join(' '));
}
return newSources.join(',');
}
getAttrDepHandler(attr) {
if (attr === 'srcset') {
return this.collectSrcSetDependencies;
}
return this.processSingleDependency;
}
collectDependencies() {
let {ast} = this;
// Add bundled dependencies from plugins like posthtml-extend or posthtml-include, if any
if (ast.messages) {
ast.messages.forEach(message => {
if (message.type === 'dependency') {
this.addDependency(message.file, {
includedInParent: true
});
}
});
}
ast.walk(node => {
if (node.attrs) {
if (node.tag === 'meta') {
if (
!Object.keys(node.attrs).some(attr => {
let values = META[attr];
return (
values &&
values.includes(node.attrs[attr]) &&
node.attrs.content !== ''
);
})
) {
return node;
}
}
if (
node.tag === 'link' &&
node.attrs.rel === 'manifest' &&
node.attrs.href
) {
node.attrs.href = this.getAttrDepHandler('href').call(
this,
node.attrs.href,
{entry: true}
);
this.isAstDirty = true;
return node;
}
for (let attr in node.attrs) {
let elements = ATTRS[attr];
// Check for virtual paths
if (node.tag === 'a' && node.attrs[attr].lastIndexOf('.') < 1) {
continue;
}
if (elements && elements.includes(node.tag)) {
let depHandler = this.getAttrDepHandler(attr);
let options = OPTIONS[node.tag];
node.attrs[attr] = depHandler.call(
this,
node.attrs[attr],
options && options[attr]
);
this.isAstDirty = true;
}
}
}
return node;
});
}
async pretransform() {
await posthtmlTransform.transform(this);
}
async transform() {
if (this.options.minify) {
await htmlnanoTransform(this);
}
}
async generate() {
// Extract inline <script> and <style> tags for processing.
let parts = [];
this.ast.walk(node => {
if (node.tag === 'script' || node.tag === 'style') {
let value = node.content && node.content.join('').trim();
if (value) {
let type;
if (node.tag === 'style') {
if (node.attrs && node.attrs.type) {
type = node.attrs.type.split('/')[1];
} else {
type = 'css';
}
} else if (node.attrs && node.attrs.type) {
// Skip JSON
if (SCRIPT_TYPES[node.attrs.type] === false) {
return node;
}
if (SCRIPT_TYPES[node.attrs.type]) {
type = SCRIPT_TYPES[node.attrs.type];
} else {
type = node.attrs.type.split('/')[1];
}
} else {
type = 'js';
}
parts.push({
type,
value,
inlineHTML: true,
meta: {
type: 'tag',
node
}
});
}
}
// Process inline style attributes.
if (node.attrs && node.attrs.style) {
parts.push({
type: 'css',
value: node.attrs.style,
meta: {
type: 'attr',
node
}
});
}
return node;
});
return parts;
}
async postProcess(generated) {
// Replace inline scripts and styles with processed results.
for (let rendition of generated) {
let {type, node} = rendition.meta;
if (type === 'attr' && rendition.type === 'css') {
node.attrs.style = rendition.value;
} else if (type === 'tag') {
if (rendition.isMain) {
node.content = rendition.value;
}
// Delete "type" attribute, since CSS and JS are the defaults.
// Unless it's application/ld+json
if (
node.attrs &&
(node.tag === 'style' ||
(node.attrs.type && SCRIPT_TYPES[node.attrs.type] === 'js'))
) {
delete node.attrs.type;
}
}
}
return [
{
type: 'html',
value: render(this.ast)
}
];
}
}
module.exports = HTMLAsset;