urls-processor.js
2.11 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
var EscapeStore = require('./escape-store');
var reduceUrls = require('../urls/reduce');
var lineBreak = require('os').EOL;
function UrlsProcessor(context, saveWaypoints, keepUrlQuotes) {
this.urls = new EscapeStore('URL');
this.context = context;
this.saveWaypoints = saveWaypoints;
this.keepUrlQuotes = keepUrlQuotes;
}
// Strip urls by replacing them by a special
// marker for further restoring. It's done via string scanning
// instead of regexps to speed up the process.
UrlsProcessor.prototype.escape = function (data) {
var breaksCount;
var lastBreakAt;
var indent;
var saveWaypoints = this.saveWaypoints;
var self = this;
return reduceUrls(data, this.context, function (url, tempData) {
if (saveWaypoints) {
breaksCount = url.split(lineBreak).length - 1;
lastBreakAt = url.lastIndexOf(lineBreak);
indent = lastBreakAt > 0 ?
url.substring(lastBreakAt + lineBreak.length).length :
url.length;
}
var placeholder = self.urls.store(url, saveWaypoints ? [breaksCount, indent] : null);
tempData.push(placeholder);
});
};
function normalize(url, keepUrlQuotes) {
url = url
.replace(/^url/gi, 'url')
.replace(/\\?\n|\\?\r\n/g, '')
.replace(/(\s{2,}|\s)/g, ' ')
.replace(/^url\((['"])? /, 'url($1')
.replace(/ (['"])?\)$/, '$1)');
if (/url\(".*'.*"\)/.test(url) || /url\('.*".*'\)/.test(url))
return url;
if (!keepUrlQuotes && !/^['"].+['"]$/.test(url) && !/url\(.*[\s\(\)].*\)/.test(url) && !/url\(['"]data:[^;]+;charset/.test(url))
url = url.replace(/["']/g, '');
return url;
}
UrlsProcessor.prototype.restore = function (data) {
var tempData = [];
var cursor = 0;
for (; cursor < data.length;) {
var nextMatch = this.urls.nextMatch(data, cursor);
if (nextMatch.start < 0)
break;
tempData.push(data.substring(cursor, nextMatch.start));
var url = normalize(this.urls.restore(nextMatch.match), this.keepUrlQuotes);
tempData.push(url);
cursor = nextMatch.end;
}
return tempData.length > 0 ?
tempData.join('') + data.substring(cursor, data.length) :
data;
};
module.exports = UrlsProcessor;