2 var SourceMapGenerator = require('source-map').SourceMapGenerator;
3 var SourceMapConsumer = require('source-map').SourceMapConsumer;
5 module.exports = function applySourceMap(file, sourceMap) {
6 if (typeof sourceMap === 'string' || sourceMap instanceof String) {
7 sourceMap = JSON.parse(sourceMap);
10 if (file.sourceMap && (typeof file.sourceMap === 'string' || file.sourceMap instanceof String)) {
11 file.sourceMap = JSON.parse(file.sourceMap);
14 // check source map properties
15 assertProperty(sourceMap, "file");
16 assertProperty(sourceMap, "mappings");
17 assertProperty(sourceMap, "sources");
19 // fix paths if Windows style paths
20 sourceMap.file = sourceMap.file.replace(/\\/g, '/');
21 sourceMap.sources = sourceMap.sources.map(function(filePath) {
22 return filePath.replace(/\\/g, '/');
25 if (file.sourceMap && file.sourceMap.mappings !== '') {
26 var generator = SourceMapGenerator.fromSourceMap(new SourceMapConsumer(sourceMap));
27 generator.applySourceMap(new SourceMapConsumer(file.sourceMap));
28 file.sourceMap = JSON.parse(generator.toString());
30 file.sourceMap = sourceMap;
34 function assertProperty(sourceMap, propertyName) {
35 if (!sourceMap.hasOwnProperty(propertyName)) {
36 var e = new Error('Source map to be applied is missing the \"' + propertyName + '\" property');