Spaces:
Running
Running
File size: 2,717 Bytes
a5f860b |
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 |
var path = require('path');
var url = require('url');
var isDataUriResource = require('../utils/is-data-uri-resource');
var DOUBLE_QUOTE = '"';
var SINGLE_QUOTE = '\'';
var URL_PREFIX = 'url(';
var URL_SUFFIX = ')';
var PROTOCOL_LESS_PREFIX_PATTERN = /^[^\w\d]*\/\//;
var QUOTE_PREFIX_PATTERN = /^["']/;
var QUOTE_SUFFIX_PATTERN = /["']$/;
var ROUND_BRACKETS_PATTERN = /[()]/;
var URL_PREFIX_PATTERN = /^url\(/i;
var URL_SUFFIX_PATTERN = /\)$/;
var WHITESPACE_PATTERN = /\s/;
var isWindows = process.platform == 'win32';
function rebase(uri, rebaseConfig) {
if (!rebaseConfig) {
return uri;
}
if (isAbsolute(uri) && !isRemote(rebaseConfig.toBase)) {
return uri;
}
if (isRemote(uri) || isSVGMarker(uri) || isInternal(uri) || isDataUriResource(uri)) {
return uri;
}
if (isRemote(rebaseConfig.toBase)) {
return url.resolve(rebaseConfig.toBase, uri);
}
return rebaseConfig.absolute
? normalize(absolute(uri, rebaseConfig))
: normalize(relative(uri, rebaseConfig));
}
function isAbsolute(uri) {
return path.isAbsolute(uri);
}
function isSVGMarker(uri) {
return uri[0] == '#';
}
function isInternal(uri) {
return /^\w+:\w+/.test(uri);
}
function isRemote(uri) {
return /^[^:]+?:\/\//.test(uri) || PROTOCOL_LESS_PREFIX_PATTERN.test(uri);
}
function absolute(uri, rebaseConfig) {
return path
.resolve(path.join(rebaseConfig.fromBase || '', uri))
.replace(rebaseConfig.toBase, '');
}
function relative(uri, rebaseConfig) {
return path.relative(rebaseConfig.toBase, path.join(rebaseConfig.fromBase || '', uri));
}
function normalize(uri) {
return isWindows ? uri.replace(/\\/g, '/') : uri;
}
function quoteFor(unquotedUrl) {
if (unquotedUrl.indexOf(SINGLE_QUOTE) > -1) {
return DOUBLE_QUOTE;
} if (unquotedUrl.indexOf(DOUBLE_QUOTE) > -1) {
return SINGLE_QUOTE;
} if (hasWhitespace(unquotedUrl) || hasRoundBrackets(unquotedUrl)) {
return SINGLE_QUOTE;
}
return '';
}
function hasWhitespace(url) {
return WHITESPACE_PATTERN.test(url);
}
function hasRoundBrackets(url) {
return ROUND_BRACKETS_PATTERN.test(url);
}
function rewriteUrl(originalUrl, rebaseConfig, pathOnly) {
var strippedUrl = originalUrl
.replace(URL_PREFIX_PATTERN, '')
.replace(URL_SUFFIX_PATTERN, '')
.trim();
var unquotedUrl = strippedUrl
.replace(QUOTE_PREFIX_PATTERN, '')
.replace(QUOTE_SUFFIX_PATTERN, '')
.trim();
var quote = strippedUrl[0] == SINGLE_QUOTE || strippedUrl[0] == DOUBLE_QUOTE
? strippedUrl[0]
: quoteFor(unquotedUrl);
return pathOnly
? rebase(unquotedUrl, rebaseConfig)
: URL_PREFIX + quote + rebase(unquotedUrl, rebaseConfig) + quote + URL_SUFFIX;
}
module.exports = rewriteUrl;
|