This repository was archived by the owner on May 30, 2018. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 4
Expand file tree
/
Copy pathhtmllint-loader.js
More file actions
443 lines (363 loc) · 11.3 KB
/
htmllint-loader.js
File metadata and controls
443 lines (363 loc) · 11.3 KB
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
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
const assign = require('object-assign');
const chalk = require('chalk');
const deasync = require('deasync');
const fs = require('fs');
const htmllint = require('htmllint');
const stripAnsi = require('strip-ansi');
const table = require('text-table');
const htmlAttributes = require('./html-attributes');
const severities = require('./html-severities');
const isFile = filePath => {
try {
return fs.lstatSync(filePath) // eslint-disable-line no-sync
.isFile();
} catch (e) {
return false;
}
};
const getRandomInt = (min, max) => {
const minCeil = Math.ceil(min);
const maxFloor = Math.floor(max);
return Math.floor(Math.random() * (maxFloor - minCeil)) + minCeil;
};
const randomKey = key => `${key}-${getRandomInt(1, 10000)}`;
const matchReplace = match => {
let output = match;
while (output.search(/{{{.*?}}}/) >= 0) {
output = output.replace(/{{{.*?}}}/, randomKey('handlebars'));
}
while (output.search(/{{.*?}}/) >= 0) {
output = output.replace(/{{.*?}}/, randomKey('handlebars'));
}
while (output.search(/<%=.*?%>/) >= 0) {
output = output.replace(/<%=.*?%>/, randomKey('ejs'));
}
while (output.search(/<%-.*?%>/) >= 0) {
output = output.replace(/<%-.*?%>/, randomKey('ejs'));
}
while (output.search(/<%.*?%>/) >= 0) {
output = output.replace(/<%.*?%>/, randomKey('ejs'));
}
while (output.search(/<\?php.*?\?>/) >= 0) {
output = output.replace(/<\?php.*?\?>/, randomKey('php'));
}
while (output.search(/<\?=.*?\?>/) >= 0) {
output = output.replace(/<\?=.*?\?>/, randomKey('php'));
}
while (output.search(/<\?.*?\?>/) >= 0) {
output = output.replace(/<\?.*?\?>/, randomKey('php'));
}
return output;
};
const cleanAttributes = content => {
let output = content;
for (const key in htmlAttributes) {
if (Object.prototype.hasOwnProperty.call(htmlAttributes, key)) {
const attr = htmlAttributes[key];
// if the content has the attribute within it then go ahead and clean it for handlebars and php
if (output.indexOf(attr) > -1) {
// regex to catch attributes with quotes
const regex = new RegExp(`${attr}=".*?"`, 'g');
// every valid html attr that is not quoted
const hbsRegex = new RegExp(`${attr}={{{.*?}}}`);
const hbsRegex2 = new RegExp(`${attr}={{.*?}}`);
const ejsRegex = new RegExp(`${attr}=<%=.*?%>`);
const ejsRegex2 = new RegExp(`${attr}=<%-.*?%>`);
const ejsRegex3 = new RegExp(`${attr}=<%.*?%>`);
const phpRegex = new RegExp(`${attr}=<\\?php.*?\\?>`);
const phpRegex2 = new RegExp(`${attr}=<\\?=.*?\\?>`);
const phpRegex3 = new RegExp(`${attr}=<\\?.*?\\?>`);
output = output.replace(regex, matchReplace);
output = output.replace(hbsRegex, `${attr}=${randomKey('handlebars')}`);
output = output.replace(hbsRegex2, `${attr}=${randomKey('handlebars')}`);
output = output.replace(ejsRegex, `${attr}=${randomKey('ejs')}`);
output = output.replace(ejsRegex2, `${attr}=${randomKey('ejs')}`);
output = output.replace(ejsRegex3, `${attr}=${randomKey('ejs')}`);
output = output.replace(phpRegex, `${attr}=${randomKey('php')}`);
output = output.replace(phpRegex2, `${attr}=${randomKey('php')}`);
output = output.replace(phpRegex3, `${attr}=${randomKey('php')}`);
}
}
}
return output;
};
const cleanHandlebars = content => {
let output = content;
// clean multiple intances of handlebars text in 1 line
while (output.search(/{{{.*?}}}/) >= 0) {
output = output.replace(/{{{.*?}}}/, '');
}
// clean multiple intances of handlebars text in 1 line
while (output.search(/{{.*?}}/) >= 0) {
output = output.replace(/{{.*?}}/, '');
}
return output;
};
const cleanEjs = content => {
let output = content;
// clean multiple intances of EJS escaped text in 1 line
while (output.search(/<%=.*?%>/) >= 0) {
output = output.replace(/<%=.*?%>/, '');
}
// clean multiple intances of EJS unescaped text in 1 line
while (output.search(/<%-.*?%>/) >= 0) {
output = output.replace(/<%-.*?%>/, '');
}
// clean multiple intances of EJS all other text in 1 line
while (output.search(/<%.*?%>/) >= 0) {
output = output.replace(/<%.*?%>/, '');
}
return output;
};
const cleanPHP = content => {
let output = content;
// clean multiple intances of php tag text in 1 line
while (output.search(/<\?php.*?\?>/) >= 0) {
output = output.replace(/<\?php.*?\?>/, '');
}
// clean multiple intances of php short tag text in 1 line
while (output.search(/<\?=.*?\?>/) >= 0) {
output = output.replace(/<\?=.*?\?>/, '');
}
// clean multiple intances of php shortest tag text in 1 line
while (output.search(/<\?.*?\?>/) >= 0) {
output = output.replace(/<\?.*?\?>/, '');
}
return output;
};
const cleanContent = content => {
const lines = content.split('\n');
let disabled = false;
/* eslint-disable no-div-regex */
for (let [i, line] of lines.entries()) { // eslint-disable-line prefer-const
if (line.indexOf('htmllint:disable-line') > -1) {
lines[i] = '';
continue; // eslint-disable-line no-continue
}
if (line.indexOf('htmllint:disable') > -1) {
disabled = true;
}
if (line.indexOf('htmllint:enable') > -1) {
disabled = false;
}
if (disabled) {
line = '';
} else {
line = cleanAttributes(line);
line = cleanHandlebars(line);
line = cleanEjs(line);
line = cleanPHP(line);
line = line
.replace(/="\s\s\s/, '="')
.replace(/="\s\s/, '="')
.replace(/="\s/, '="')
.replace(/\s\s\s"/, '"')
.replace(/\s\s"/, '"')
.replace(/\s"/, '"')
.replace(/<>/, '')
.replace(/<\/>/, '')
.replace('<?php', '')
.replace('<?=', '')
.replace('<?', '')
.replace('<%', '')
.replace('%>', '')
.replace('?>', '');
}
/* eslint-enable no-div-regex */
lines[i] = line;
}
return lines.join('\n');
};
const pluralize = (_word, count) => {
let word = _word;
if (count > 1) {
word = `${word}s`;
}
return word;
};
const stylish = results => {
let errors = 0;
let warnings = 0;
let output = '';
let total = 0;
let summaryColor = 'yellow';
let messages = null;
let filename = null;
let tableOptions = null;
let fileOutput = null;
let styledOutput = null;
let tableLayout = null;
let format = null;
results.forEach(file => {
messages = file.messages;
filename = chalk.underline(file.filePath);
tableOptions = {
align: ['', ' ', 'r', 'l'],
stringLength: function stringLength(str) {
return stripAnsi(str).length;
},
};
fileOutput = '\n';
if (messages.length === 0) {
return;
}
total = total + messages.length;
styledOutput = messages.map(message => {
let messageType = 'unknown';
if (message.severity === 'error') {
messageType = chalk.red('error');
errors = errors + 1;
} else {
messageType = chalk.yellow('warning');
warnings = warnings + 1;
}
return [
'',
chalk.dim(`${message.line}:${message.column}`),
messageType,
chalk.dim(message.linter || ''),
message.reason.replace(/\.$/, ''),
];
});
tableLayout = table(styledOutput, tableOptions);
format = tableLayout.split('\n');
format = `${format.join('\n')}\n\n`;
fileOutput = `${fileOutput}${filename}\n`;
fileOutput = fileOutput + format;
output = output + fileOutput;
});
if (total > 0) {
const bold = [
'\u2716 ',
total,
pluralize(' problem', total),
' (',
errors,
pluralize(' error', errors),
', ',
warnings,
pluralize(' warning', warnings),
')\n',
];
if (errors > 0) {
summaryColor = 'red';
}
output = output + chalk[summaryColor].bold(bold.join(''));
}
const message = total > 0 ? new Error(output) : '';
delete message.stack;
return {
message,
warnings,
errors,
};
};
const lint = (source, options, webpack) => {
const messages = [];
let done = false;
let content = fs.readFileSync(options.resourcePath, 'utf8'); // eslint-disable-line no-sync
// take care of fragmented title tags
content = content.replace(/<title>[\s\S]*?<\/title>/, match => {
const parts = match.split('\n');
const last = parts.length - 1;
if (last === 0) {
return '<title>has title</title>';
}
for (const [i, part] of parts.entries()) { // eslint-disable-line no-unused-vars
if (i === 0) {
parts[i] = '<title>';
} else if (i === last) {
parts[i] = '</title>';
} else {
parts[i] = `${i}`;
}
}
return parts.join('\n');
});
content = cleanContent(content);
// fragmented handlebars
while (content.search(/{{{[\s\S]*?}}}/) >= 0) {
content = content.replace(/{{{[\s\S]*?}}}/, match => '\n'.repeat(match.split('\n').length - 1));
}
// fragmented handlebars
while (content.search(/{{[\s\S]*?}}/) >= 0) {
content = content.replace(/{{[\s\S]*?}}/, match => '\n'.repeat(match.split('\n').length - 1));
}
htmllint(content, options.lintOptions).then(issues => {
for (const issue of issues) {
let rule = issue.rule;
switch (issue.code) { // eslint-disable-line default-case
case 'E018':
rule = 'tag-self-close';
break;
case 'E025':
rule = 'html-req-lang';
break;
}
messages.push({
line: issue.line,
column: issue.column,
length: 0,
severity: severities[rule] || 'warning',
reason: htmllint.messages.renderIssue(issue),
linter: rule,
});
}
done = true;
}, err => {
messages.push({
line: 0,
column: 0,
length: 0,
severity: 'warning',
reason: err.message,
linter: 'unknown',
});
done = true;
});
deasync.loopWhile(() => !done);
if (messages.length > 0) {
// formatted.message is returned from stylish();
const formatted = stylish([{
filePath: options.resourcePath,
messages,
}]);
if (formatted.errors > 0) {
if (options.failOnError) {
webpack.emitError(formatted.message);
if (process.env.NODE_ENV === 'production') {
throw new Error(`Module failed because of a htmllint errors.\n ${formatted.message}`);
}
} else {
webpack.emitWarning(formatted.message);
}
} else if (formatted.warnings > 0) {
if (options.failOnWarning) {
webpack.emitError(formatted.message);
if (process.env.NODE_ENV === 'production') {
throw new Error(`Module failed because of a htmllint warnings.\n ${formatted.message}`);
}
} else {
webpack.emitWarning(formatted.message);
}
}
}
};
module.exports = function htmlLint(source) {
const cwd = process.cwd();
const config = (isFile('.htmllintrc')) ? '.htmllintrc' : 'node_modules/htmllint-loader/.htmllintrc';
const options = assign(
{
config,
failOnError: true,
failWarning: false,
},
this.query
);
options.lintOptions = JSON.parse(fs.readFileSync(options.config)); // eslint-disable-line no-sync
if (this.resourcePath.indexOf(cwd) === 0) {
options.resourcePath = this.resourcePath.substr(cwd.length + 1);
}
lint(source, options, this);
return source;
};