| 1 |
'use strict' |
| 2 |
|
| 3 |
const convertSourceMap = require('convert-source-map') |
| 4 |
const libCoverage = require('istanbul-lib-coverage') |
| 5 |
const libSourceMaps = require('istanbul-lib-source-maps') |
| 6 |
const fs = require('./fs-promises') |
| 7 |
const os = require('os') |
| 8 |
const path = require('path') |
| 9 |
const pMap = require('p-map') |
| 10 |
|
| 11 |
class SourceMaps { |
| 12 |
constructor (opts) { |
| 13 |
this.cache = opts.cache |
| 14 |
this.cacheDirectory = opts.cacheDirectory |
| 15 |
this.loadedMaps = {} |
| 16 |
this._sourceMapCache = libSourceMaps.createSourceMapStore() |
| 17 |
} |
| 18 |
|
| 19 |
cachedPath (source, hash) { |
| 20 |
return path.join( |
| 21 |
this.cacheDirectory, |
| 22 |
`${path.parse(source).name}-${hash}.map` |
| 23 |
) |
| 24 |
} |
| 25 |
|
| 26 |
purgeCache () { |
| 27 |
this._sourceMapCache = libSourceMaps.createSourceMapStore() |
| 28 |
this.loadedMaps = {} |
| 29 |
} |
| 30 |
|
| 31 |
extract (code, filename) { |
| 32 |
const sourceMap = convertSourceMap.fromSource(code) || convertSourceMap.fromMapFileSource(code, (f) => require('fs').readFileSync(path.resolve(path.dirname(filename), f), 'utf8')) |
| 33 |
return sourceMap ? sourceMap.toObject() : undefined |
| 34 |
} |
| 35 |
|
| 36 |
registerMap (filename, hash, sourceMap) { |
| 37 |
if (!sourceMap) { |
| 38 |
return |
| 39 |
} |
| 40 |
|
| 41 |
if (this.cache && hash) { |
| 42 |
const mapPath = this.cachedPath(filename, hash) |
| 43 |
fs.writeFileSync(mapPath, JSON.stringify(sourceMap)) |
| 44 |
} else { |
| 45 |
this._sourceMapCache.registerMap(filename, sourceMap) |
| 46 |
} |
| 47 |
} |
| 48 |
|
| 49 |
async remapCoverage (obj) { |
| 50 |
const transformed = await this._sourceMapCache.transformCoverage( |
| 51 |
libCoverage.createCoverageMap(obj) |
| 52 |
) |
| 53 |
return transformed.data |
| 54 |
} |
| 55 |
|
| 56 |
async reloadCachedSourceMaps (report) { |
| 57 |
await pMap( |
| 58 |
Object.entries(report), |
| 59 |
async ([absFile, fileReport]) => { |
| 60 |
if (!fileReport || !fileReport.contentHash) { |
| 61 |
return |
| 62 |
} |
| 63 |
|
| 64 |
const hash = fileReport.contentHash |
| 65 |
if (!(hash in this.loadedMaps)) { |
| 66 |
try { |
| 67 |
const mapPath = this.cachedPath(absFile, hash) |
| 68 |
this.loadedMaps[hash] = JSON.parse(await fs.readFile(mapPath, 'utf8')) |
| 69 |
} catch (e) { |
| 70 |
// set to false to avoid repeatedly trying to load the map |
| 71 |
this.loadedMaps[hash] = false |
| 72 |
} |
| 73 |
} |
| 74 |
|
| 75 |
if (this.loadedMaps[hash]) { |
| 76 |
this._sourceMapCache.registerMap(absFile, this.loadedMaps[hash]) |
| 77 |
} |
| 78 |
}, |
| 79 |
{ concurrency: os.cpus().length } |
| 80 |
) |
| 81 |
} |
| 82 |
} |
| 83 |
|
| 84 |
module.exports = SourceMaps |