sourcemap-parse.js
2.08 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
const sourceMap = require('source-map');
const lru = require('lru-cache');
const rp = require('request-promise');
const url = require('url');
const logger = global.yoho.logger;
const config = global.yoho.config;
const cache = lru({
max: 500
});
const loadFileSourceMap = (fileUrl) => {
const cacheItem = cache.get(fileUrl);
if (cacheItem) {
logger.info('cache');
return Promise.resolve(cacheItem);
} else {
if (!/\.js(\?.*?)?$/.test(fileUrl)) {
return Promise.resolve();
}
const urlPath = url.parse(fileUrl).pathname;
try {
return rp(`${config.sourceMap.domain}/api/sourcemap/load?path=${urlPath}`, {
json: true,
resolveWithFullResponse: true
}).then(res => {
const data = res.toJSON();
if (data.headers.sourcemap) {
cache.set(fileUrl, data.body);
return data.body;
}
return void 0;
}, () => {
logger.error(`${fileUrl}.map file request failure!`);
});
} catch (e) {
logger.error(`${fileUrl}.map file request failure!`, e);
return Promise.resolve();
}
}
};
const parse = ({fileUrl, line, column}) => {
if (!/\.js(\?[^\?]*)?$/.test(fileUrl) || !line) {
return Promise.resolve({
source: fileUrl,
line,
column
});
}
return loadFileSourceMap(fileUrl).then(source => {
if (!source || !line) {
return void 0;
}
try {
const consumer = new sourceMap.SourceMapConsumer(source);
const origin = consumer.originalPositionFor({
line: line,
column: column
});
return origin;
} catch (e) {
if (cache.get(fileUrl)) {
cache.del(fileUrl);
}
logger.error(e);
}
return void 0;
}, err => {
logger.error(err);
});
};
module.exports = {
parse
};