forked from codesandbox/codesandbox-client
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathparser.js
More file actions
62 lines (59 loc) · 1.64 KB
/
parser.js
File metadata and controls
62 lines (59 loc) · 1.64 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
/* eslint-disable */
const compiler = require('vue-template-compiler');
const cache = require('lru-cache')(100);
const hash = require('hash-sum');
const SourceMapGenerator = require('source-map').SourceMapGenerator;
const splitRE = /\r?\n/g;
const emptyRE = /^(?:\/\/)?\s*$/;
module.exports = function(content, filename, needMap, sourceRoot) {
const cacheKey = hash(filename + content);
// source-map cache busting for hot-reloadded modules
const filenameWithHash = filename + '?' + cacheKey;
let output = cache.get(cacheKey);
if (output) return output;
output = compiler.parseComponent(content, { pad: 'line' });
if (needMap) {
if (output.script && !output.script.src) {
output.script.map = generateSourceMap(
filenameWithHash,
content,
output.script.content,
sourceRoot
);
}
if (output.styles) {
output.styles.forEach(style => {
if (!style.src) {
style.map = generateSourceMap(
filenameWithHash,
content,
style.content,
sourceRoot
);
}
});
}
}
cache.set(cacheKey, output);
return output;
};
function generateSourceMap(filename, source, generated, sourceRoot) {
const map = new SourceMapGenerator({ sourceRoot });
map.setSourceContent(filename, source);
generated.split(splitRE).forEach((line, index) => {
if (!emptyRE.test(line)) {
map.addMapping({
source: filename,
original: {
line: index + 1,
column: 0,
},
generated: {
line: index + 1,
column: 0,
},
});
}
});
return map.toJSON();
}