From 8634dfd30d43d1daf57c60c1ccbc65fcc3282ee0 Mon Sep 17 00:00:00 2001 From: miripiruni Date: Wed, 17 May 2017 15:54:10 +0300 Subject: [PATCH] File: support prev map (issue #16) --- lib/file.js | 61 +++++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 61 insertions(+) diff --git a/lib/file.js b/lib/file.js index 98b4cac..598441c 100644 --- a/lib/file.js +++ b/lib/file.js @@ -1,6 +1,7 @@ var os = require('os'), path = require('path'), url = require('url'), + fs = require('fs'), mozilla = require('source-map'), SourceMapGenerator = mozilla.SourceMapGenerator, utils = require('./utils'); @@ -37,6 +38,60 @@ File.prototype = { return this; }, + writeFileFromPrevMap: function (file, prev) { + if (prev === false) { + return this.writeFileContent(file); + } + + if (prev) { + if (typeof prev === 'string') { + return prev; + } + + if (typeof prev === 'function') { + var prevPath = prev(file); + + if (prevPath && fs.existsSync && fs.existsSync(prevPath)) { + return fs.readFileSync(prevPath, 'utf-8').toString().trim(); + } else { + throw new Error('Unable to load previous source map: ' + prevPath.toString()); + } + } + + if (prev instanceof mozilla.SourceMapConsumer) { + return mozilla.SourceMapGenerator.fromSourceMap(prev).toString(); + } + + if (prev instanceof mozilla.SourceMapGenerator) { + return prev.toString(); + } + + if (isMap(prev)) { + return JSON.stringify(prev); + } + + throw new Error('Unsupported previous source map format: ' + prev.toString()); + + } + + if (this.inline) { + return this.decodeInline(this.annotation); + } + + if (this.annotation) { + var map = this.annotation; + if (file) { + map = path.join(path.dirname(file), map); + } + + this.root = path.dirname(map); + + return (fs.existsSync && fs.existsSync(map)) ? + fs.readFileSync(map, 'utf-8').toString().trim() : + false; + } + }, + writeLine: function (line) { this.write(line + '\n'); @@ -131,6 +186,12 @@ File.prototype = { } }; + +function isMap(map) { + if (typeof map !== 'object') return false; + return typeof map.mappings === 'string' || typeof map._mappings === 'string'; +} + function getLines(text) { return text.split(/\r\n|\r|\n/); }