sourcemap-parse.js 1.48 KB
// 查找sourcemap

const sourceMap = require('source-map');
const config = require('../../../config/config');
const url = require('url');
const path = require('path');
const fs = require('fs');

const sourcesPathMap = {};

async function readFile(url) {
    const filePath = path.join(config.sourceMap, url + '.map');

    return new Promise(function(resolve, reject) {
        fs.readFile(filePath, function(err, data) {
            if (err) {
                reject(err);
                return;
            }

            resolve(data);
        })

    });
}

function fixPath(filepath) {
    return filepath.replace(/\.[\.\/]+/g, "");
}

async function lookupSourceMap(fileUrl, line, column) {
    if (!/\.js(\?.*?)?$/.test(fileUrl)) {
        return;
    }

    const urlPath = url.parse(fileUrl).pathname;
    const content = await readFile(urlPath);
    const fileContent = content.toString();
    const fileObj = JSON.parse(fileContent);
    const sources = fileObj.sources;

    sources.map(item => {
        sourcesPathMap[fixPath(item)] = item;
    });

    var consumer = new sourceMap.SourceMapConsumer(fileContent);
    var lookup = {
        line: parseInt(line),
        column: parseInt(column)
    };
    var result = consumer.originalPositionFor(lookup);

    var originSource = sourcesPathMap[result.source],
        sourcesContent = fileObj.sourcesContent[sources.indexOf(originSource)];

    result.sourcesContent = sourcesContent;

    return result;
}

module.exports = lookupSourceMap;