source-reader.js
2.69 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
var path = require('path');
var rewriteUrls = require('../urls/rewrite');
var REMOTE_RESOURCE = /^(https?:)?\/\//;
function SourceReader(context, data) {
this.outerContext = context;
this.data = data;
this.sources = {};
}
SourceReader.prototype.sourceAt = function (path) {
return this.sources[path];
};
SourceReader.prototype.trackSource = function (path, source) {
this.sources[path] = {};
this.sources[path][path] = source;
};
SourceReader.prototype.toString = function () {
if (typeof this.data == 'string')
return fromString(this);
if (Buffer.isBuffer(this.data))
return fromBuffer(this);
if (Array.isArray(this.data))
return fromArray(this);
return fromHash(this);
};
function fromString(self) {
var data = self.data;
self.trackSource(undefined, data);
return data;
}
function fromBuffer(self) {
var data = self.data.toString();
self.trackSource(undefined, data);
return data;
}
function fromArray(self) {
return self.data
.map(function (source) {
return self.outerContext.options.processImport === false ?
source + '@shallow' :
source;
})
.map(function (source) {
return !self.outerContext.options.relativeTo || /^https?:\/\//.test(source) ?
source :
path.relative(self.outerContext.options.relativeTo, source);
})
.map(function (source) { return '@import url(' + source + ');'; })
.join('');
}
function fromHash(self) {
var data = [];
var toBase = path.resolve(self.outerContext.options.target || self.outerContext.options.root);
for (var source in self.data) {
var styles = self.data[source].styles;
var inputSourceMap = self.data[source].sourceMap;
var isRemote = REMOTE_RESOURCE.test(source);
var absoluteSource = isRemote ? source : path.resolve(source);
var absoluteSourcePath = path.dirname(absoluteSource);
var rewriteOptions = {
absolute: self.outerContext.options.explicitRoot,
relative: !self.outerContext.options.explicitRoot,
imports: true,
rebase: self.outerContext.options.rebase,
fromBase: absoluteSourcePath,
toBase: isRemote ? absoluteSourcePath : toBase,
urlQuotes: self.outerContext.options.compatibility.properties.urlQuotes
};
styles = rewriteUrls(styles, rewriteOptions, self.outerContext);
self.trackSource(source, styles);
styles = self.outerContext.sourceTracker.store(source, styles);
// here we assume source map lies in the same directory as `source` does
if (self.outerContext.options.sourceMap && inputSourceMap)
self.outerContext.inputSourceMapTracker.trackLoaded(source, source, inputSourceMap);
data.push(styles);
}
return data.join('');
}
module.exports = SourceReader;