UNPKG

@theintern/istanbul-loader

Version:

A webpack loader that adds code coverage instrumentation

96 lines 3.56 kB
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); const istanbul_lib_instrument_1 = require("istanbul-lib-instrument"); const loader_utils_1 = require("loader-utils"); const source_map_1 = require("source-map"); const util_1 = require("intern/lib/node/util"); const loader = function (source, sourceMap) { const callback = this.async(); const options = Object.assign({}, loader_utils_1.getOptions(this)); const _sourceMap = sourceMap; util_1.getConfig(options.config) .then(({ config, file }) => { if (file) { this.addDependency(file); } return config; }) .catch(_error => Object.create(null)) .then(config => { const instrumenterOptions = Object.assign({ produceSourceMap: true }, config.instrumenterOptions); if (config.coverageVariable) { instrumenterOptions.coverageVariable = config.coverageVariable; } const instrumenter = istanbul_lib_instrument_1.createInstrumenter(instrumenterOptions); if (_sourceMap) { _sourceMap.sources = (_sourceMap.sources || []).map(source => { const lastBang = source.lastIndexOf('!'); if (lastBang !== -1) { return source.substr(lastBang + 1); } return source; }); } instrumenter.instrument(String(source), this.resourcePath, (error, instrumentedSource) => { if (error) { callback(error); } else { try { const instrumentedSourceMap = instrumenter.lastSourceMap(); let updatedSourceMap; if (_sourceMap) { updatedSourceMap = mergeSourceMaps(instrumentedSourceMap, _sourceMap); } else { updatedSourceMap = instrumentedSourceMap; } callback(null, instrumentedSource, updatedSourceMap); } catch (err) { callback(err); } } }, _sourceMap); }); }; exports.default = loader; function mergeSourceMaps(...maps) { const consumers = maps.map(map => new source_map_1.SourceMapConsumer(map)); const generator = new source_map_1.SourceMapGenerator({ file: maps[0].file }); consumers[0].eachMapping(mapping => { const original = getOriginalPosition(consumers, mapping); if (original.line !== null) { generator.addMapping({ generated: { line: mapping.generatedLine, column: mapping.generatedColumn }, original: { line: original.line, column: original.column }, source: mapping.source, name: mapping.name }); } }); return JSON.parse(generator.toString()); } function getOriginalPosition(consumers, mapping) { return consumers.reduce((original, consumer) => { if (isMappedPosition(original)) { return consumer.originalPositionFor(original); } return original; }, { line: mapping.generatedLine, column: mapping.generatedColumn }); } function isMappedPosition(position) { return (position.line != null && position.column != null && position.source != null); } //# sourceMappingURL=index.js.map