1 | var sourceMap = require('source-map')
|
---|
2 | var SourceMapConsumer = sourceMap.SourceMapConsumer
|
---|
3 | var SourceMapGenerator = sourceMap.SourceMapGenerator
|
---|
4 |
|
---|
5 | module.exports = merge
|
---|
6 |
|
---|
7 | /**
|
---|
8 | * Merge old source map and new source map and return merged.
|
---|
9 | * If old or new source map value is falsy, return another one as it is.
|
---|
10 | *
|
---|
11 | * @param {object|string} [oldMap] old source map object
|
---|
12 | * @param {object|string} [newmap] new source map object
|
---|
13 | * @return {object|undefined} merged source map object, or undefined when both old and new source map are undefined
|
---|
14 | */
|
---|
15 | function merge(oldMap, newMap) {
|
---|
16 | if (!oldMap) return newMap
|
---|
17 | if (!newMap) return oldMap
|
---|
18 |
|
---|
19 | var oldMapConsumer = new SourceMapConsumer(oldMap)
|
---|
20 | var newMapConsumer = new SourceMapConsumer(newMap)
|
---|
21 | var mergedMapGenerator = new SourceMapGenerator()
|
---|
22 |
|
---|
23 | // iterate on new map and overwrite original position of new map with one of old map
|
---|
24 | newMapConsumer.eachMapping(function(m) {
|
---|
25 | // pass when `originalLine` is null.
|
---|
26 | // It occurs in case that the node does not have origin in original code.
|
---|
27 | if (m.originalLine == null) return
|
---|
28 |
|
---|
29 | var origPosInOldMap = oldMapConsumer.originalPositionFor({
|
---|
30 | line: m.originalLine,
|
---|
31 | column: m.originalColumn
|
---|
32 | })
|
---|
33 |
|
---|
34 | if (origPosInOldMap.source == null) return
|
---|
35 |
|
---|
36 | mergedMapGenerator.addMapping({
|
---|
37 | original: {
|
---|
38 | line: origPosInOldMap.line,
|
---|
39 | column: origPosInOldMap.column
|
---|
40 | },
|
---|
41 | generated: {
|
---|
42 | line: m.generatedLine,
|
---|
43 | column: m.generatedColumn
|
---|
44 | },
|
---|
45 | source: origPosInOldMap.source,
|
---|
46 | name: origPosInOldMap.name
|
---|
47 | })
|
---|
48 | })
|
---|
49 |
|
---|
50 | var consumers = [oldMapConsumer, newMapConsumer]
|
---|
51 | consumers.forEach(function(consumer) {
|
---|
52 | consumer.sources.forEach(function(sourceFile) {
|
---|
53 | mergedMapGenerator._sources.add(sourceFile)
|
---|
54 | var sourceContent = consumer.sourceContentFor(sourceFile)
|
---|
55 | if (sourceContent != null) {
|
---|
56 | mergedMapGenerator.setSourceContent(sourceFile, sourceContent)
|
---|
57 | }
|
---|
58 | })
|
---|
59 | })
|
---|
60 |
|
---|
61 | mergedMapGenerator._sourceRoot = oldMap.sourceRoot
|
---|
62 | mergedMapGenerator._file = oldMap.file
|
---|
63 |
|
---|
64 | return JSON.parse(mergedMapGenerator.toString())
|
---|
65 | }
|
---|