UNPKG

2.81 kBJavaScriptView Raw
1const path = require('path');
2const minimatch = require('minimatch');
3
4function fixWebpackFilePath(filePath) {
5 if (filePath.includes('!')) {
6 filePath = filePath.split('!').pop();
7 }
8
9 if (filePath.includes('?')) {
10 filePath = filePath.split('?')[0];
11 }
12
13 return filePath;
14}
15
16function fixPathSeparators(filePath) {
17 const isWin = process.platform.startsWith('win');
18 // Workaround for https://github.com/mattlewis92/karma-coverage-istanbul-reporter/issues/9
19 if (isWin && filePath) {
20 return filePath.replace(/\//g, '\\');
21 }
22
23 return filePath;
24}
25
26function fixWebpackSourcePaths(sourceMap, webpackConfig) {
27 let { sourceRoot } = sourceMap;
28 // As per https://webpack.js.org/configuration/entry-context/#context, if no context is specified, the current
29 // directory that the process is running from should be assumed instead
30 const context = (webpackConfig && webpackConfig.context) || process.cwd();
31 // Fix for https://github.com/mattlewis92/karma-coverage-istanbul-reporter/issues/32
32 // The sourceRoot is relative to the project directory and not an absolute path, so add the webpack context to it if set
33 if (
34 context &&
35 sourceRoot &&
36 !sourceRoot.startsWith(context) &&
37 !path.isAbsolute(sourceRoot)
38 ) {
39 sourceRoot = path.join(context, sourceRoot);
40 }
41
42 sourceRoot = fixPathSeparators(sourceRoot);
43
44 const result = Object.assign({}, sourceMap, {
45 file: fixPathSeparators(sourceMap.file),
46 sources: (sourceMap.sources || []).map((source) => {
47 source = fixWebpackFilePath(source);
48 if (sourceRoot && source.startsWith(sourceRoot)) {
49 source = source.replace(sourceRoot, '');
50 }
51
52 return source;
53 }),
54 });
55
56 if (sourceRoot) {
57 result.sourceRoot = sourceRoot;
58 }
59
60 return result;
61}
62
63function isAbsolute(file) {
64 if (path.isAbsolute) {
65 return path.isAbsolute(file);
66 }
67
68 return path.resolve(file) === path.normalize(file);
69}
70
71function normalize(key, basePath) {
72 // Exclude keys will always be relative, but covObj keys can be absolute or relative
73 let excludeKey = isAbsolute(key) ? path.relative(basePath, key) : key;
74 // Also normalize for files that start with `./`, etc.
75 excludeKey = path.normalize(excludeKey);
76
77 return excludeKey;
78}
79
80function overrideThresholds(key, overrides, basePath) {
81 let thresholds = {};
82
83 // First match wins
84 Object.keys(overrides).some((pattern) => {
85 if (minimatch(normalize(key, basePath), pattern, { dot: true })) {
86 thresholds = overrides[pattern];
87 return true;
88 }
89
90 return false;
91 });
92
93 return thresholds;
94}
95
96module.exports.fixPathSeparators = fixPathSeparators;
97module.exports.fixWebpackSourcePaths = fixWebpackSourcePaths;
98module.exports.fixWebpackFilePath = fixWebpackFilePath;
99module.exports.overrideThresholds = overrideThresholds;