sourcemap-parse.js 1.51 KB
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;

        return rp(`${config.sourceMap.domain}/api/sourcemap/load?path=${urlPath}`, {json: true}).then(res => {
            cache.set(fileUrl, res);
            return res;
        }, () => {
            logger.error(`${fileUrl}.map file request failure!`);
        });
    }
};

const parse = ({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
};