rewrite.js
2.45 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
var path = require('path');
var url = require('url');
var reduceUrls = require('./reduce');
var isWindows = process.platform == 'win32';
function isAbsolute(uri) {
return uri[0] == '/';
}
function isSVGMarker(uri) {
return uri[0] == '#';
}
function isEscaped(uri) {
return uri.indexOf('__ESCAPED_URL_CLEAN_CSS__') === 0;
}
function isInternal(uri) {
return /^\w+:\w+/.test(uri);
}
function isRemote(uri) {
return /^[^:]+?:\/\//.test(uri) || uri.indexOf('//') === 0;
}
function isSameOrigin(uri1, uri2) {
return url.parse(uri1).protocol == url.parse(uri2).protocol &&
url.parse(uri1).host == url.parse(uri2).host;
}
function isImport(uri) {
return uri.lastIndexOf('.css') === uri.length - 4;
}
function isData(uri) {
return uri.indexOf('data:') === 0;
}
function absolute(uri, options) {
return path
.resolve(path.join(options.fromBase || '', uri))
.replace(options.toBase, '');
}
function relative(uri, options) {
return path.relative(options.toBase, path.join(options.fromBase || '', uri));
}
function normalize(uri) {
return isWindows ? uri.replace(/\\/g, '/') : uri;
}
function rebase(uri, options) {
if (isAbsolute(uri) || isSVGMarker(uri) || isEscaped(uri) || isInternal(uri))
return uri;
if (options.rebase === false && !isImport(uri))
return uri;
if (!options.imports && isImport(uri))
return uri;
if (isData(uri))
return '\'' + uri + '\'';
if (isRemote(uri) && !isRemote(options.toBase))
return uri;
if (isRemote(uri) && !isSameOrigin(uri, options.toBase))
return uri;
if (!isRemote(uri) && isRemote(options.toBase))
return url.resolve(options.toBase, uri);
return options.absolute ?
normalize(absolute(uri, options)) :
normalize(relative(uri, options));
}
function quoteFor(url) {
if (url.indexOf('\'') > -1)
return '"';
else if (url.indexOf('"') > -1)
return '\'';
else if (/\s/.test(url) || /[\(\)]/.test(url))
return '\'';
else
return '';
}
function rewriteUrls(data, options, context) {
return reduceUrls(data, context, function (originUrl, tempData) {
var url = originUrl.replace(/^(url\()?\s*['"]?|['"]?\s*\)?$/g, '');
var match = originUrl.match(/^(url\()?\s*(['"]).*?(['"])\s*\)?$/);
var quote;
if (!!options.urlQuotes && match && match[2] === match[3]) {
quote = match[2];
} else {
quote = quoteFor(url);
}
tempData.push('url(' + quote + rebase(url, options) + quote + ')');
});
}
module.exports = rewriteUrls;