-
Notifications
You must be signed in to change notification settings - Fork 250
/
Copy pathSourceMapper.ts
254 lines (225 loc) · 9.01 KB
/
SourceMapper.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
import * as path from 'path';
import { File, Location, Position, StrykerOptions } from '@stryker-mutator/api/core';
import { StrykerError } from '@stryker-mutator/util';
import { getLogger } from 'log4js';
import { RawSourceMap, SourceMapConsumer } from 'source-map';
import { base64Decode } from '../utils/objectUtils';
const SOURCE_MAP_URL_REGEX = /\/\/\s*#\s*sourceMappingURL=(.*)/g;
// This file contains source mapping logic.
// It reads transpiled output files (*.js) and scans it for comments like these: sourceMappingURL=*.js.map
// If it finds it, it will use mozilla's source-map to implement the `transpiledLocationFor` method.
export interface MappedLocation {
fileName: string;
location: Location;
}
export class SourceMapError extends StrykerError {
constructor(message: string, innerError?: Error) {
super(
`${message}. Cannot analyse code coverage. Setting \`coverageAnalysis: "off"\` in your config will prevent this error, but forces Stryker to run each test for each mutant.`,
innerError
);
Error.captureStackTrace(this, SourceMapError);
// TS recommendation: https://github.com/Microsoft/TypeScript/wiki/Breaking-Changes#extending-built-ins-like-error-array-and-map-may-no-longer-work
Object.setPrototypeOf(this, SourceMapError.prototype);
}
}
/**
* Represents an object that can calculated a transpiled location for a given original location
* It is implemented with the [composite pattern](https://en.wikipedia.org/wiki/Composite_pattern)
* Use the `create` method to retrieve a specific `SourceMapper` implementation
*/
export default abstract class SourceMapper {
/**
* Calculated a transpiled location for a given original location
* @param originalLocation The original location to be converted to a transpiled location
*/
public abstract async transpiledLocationFor(originalLocation: MappedLocation): Promise<MappedLocation>;
public abstract transpiledFileNameFor(originalFileName: string): string;
public static create(transpiledFiles: readonly File[], options: StrykerOptions): SourceMapper {
if (options.transpilers.length && options.coverageAnalysis !== 'off') {
return new TranspiledSourceMapper(transpiledFiles);
} else {
return new PassThroughSourceMapper();
}
}
}
export class TranspiledSourceMapper extends SourceMapper {
private sourceMaps: SourceMapBySource;
private readonly log = getLogger(SourceMapper.name);
constructor(private readonly transpiledFiles: readonly File[]) {
super();
}
/**
* @inheritDoc
*/
public transpiledFileNameFor(originalFileName: string) {
const sourceMap = this.getSourceMap(originalFileName);
return sourceMap.transpiledFile.name;
}
/**
* @inheritdoc
*/
public async transpiledLocationFor(originalLocation: MappedLocation): Promise<MappedLocation> {
const sourceMap = this.getSourceMap(originalLocation.fileName);
const relativeSource = this.getRelativeSource(sourceMap, originalLocation);
const start = await sourceMap.generatedPositionFor(originalLocation.location.start, relativeSource);
const end = await sourceMap.generatedPositionFor(originalLocation.location.end, relativeSource);
return {
fileName: sourceMap.transpiledFile.name,
location: {
end,
start
}
};
}
private getRelativeSource(from: SourceMap, to: MappedLocation) {
return path.relative(path.dirname(from.sourceMapFileName), to.fileName).replace(/\\/g, '/');
}
/**
* Gets the source map for given file
*/
private getSourceMap(sourceFileName: string): SourceMap {
if (!this.sourceMaps) {
this.sourceMaps = this.createSourceMaps();
}
const sourceMap: SourceMap | undefined = this.sourceMaps[path.resolve(sourceFileName)];
if (sourceMap) {
return sourceMap;
} else {
throw new SourceMapError(`Source map not found for "${sourceFileName}"`);
}
}
/**
* Creates all source maps for lazy loading purposes
*/
private createSourceMaps(): SourceMapBySource {
const sourceMaps: SourceMapBySource = Object.create(null);
this.transpiledFiles.forEach(transpiledFile => {
const sourceMapFile = this.getSourceMapForFile(transpiledFile);
if (sourceMapFile) {
const rawSourceMap = this.getRawSourceMap(sourceMapFile);
const sourceMap = new SourceMap(transpiledFile, sourceMapFile.name, rawSourceMap);
rawSourceMap.sources.forEach(source => {
const sourceFileName = path.resolve(path.dirname(sourceMapFile.name), source);
sourceMaps[sourceFileName] = sourceMap;
});
}
});
return sourceMaps;
}
private getRawSourceMap(sourceMapFile: File): RawSourceMap {
try {
return JSON.parse(sourceMapFile.textContent);
} catch (error) {
throw new SourceMapError(`Source map file "${sourceMapFile.name}" could not be parsed as json`, error);
}
}
private getSourceMapForFile(transpiledFile: File): File | null {
const sourceMappingUrl = this.getSourceMapUrl(transpiledFile);
if (sourceMappingUrl) {
return this.getSourceMapFileFromUrl(sourceMappingUrl, transpiledFile);
} else {
return null;
}
}
/**
* Gets the source map file from a url.
* @param sourceMapUrl The source map url. Can be a data url (data:application/json;base64,ABC...), or an actual file url
* @param transpiledFile The transpiled file for which the data url is
*/
private getSourceMapFileFromUrl(sourceMapUrl: string, transpiledFile: File): File {
const sourceMapFile = this.isInlineUrl(sourceMapUrl)
? this.getInlineSourceMap(sourceMapUrl, transpiledFile)
: this.getExternalSourceMap(sourceMapUrl, transpiledFile);
return sourceMapFile;
}
private isInlineUrl(sourceMapUrl: string) {
return sourceMapUrl.startsWith('data:');
}
/**
* Gets the source map from a data url
*/
private getInlineSourceMap(sourceMapUrl: string, transpiledFile: File): File {
const supportedDataPrefix = 'data:application/json;base64,';
if (sourceMapUrl.startsWith(supportedDataPrefix)) {
const content = base64Decode(sourceMapUrl.substr(supportedDataPrefix.length));
return new File(transpiledFile.name, content);
} else {
throw new SourceMapError(
`Source map file for "${transpiledFile.name}" cannot be read. Data url "${sourceMapUrl.substr(
0,
sourceMapUrl.lastIndexOf(',')
)}" found, where "${supportedDataPrefix.substr(0, supportedDataPrefix.length - 1)}" was expected`
);
}
}
/**
* Gets the source map from a file
*/
private getExternalSourceMap(sourceMapUrl: string, transpiledFile: File) {
const sourceMapFileName = path.resolve(path.dirname(transpiledFile.name), sourceMapUrl);
const sourceMapFile = this.transpiledFiles.find(file => path.resolve(file.name) === sourceMapFileName);
if (sourceMapFile) {
return sourceMapFile;
} else {
throw new SourceMapError(
`Source map file "${sourceMapUrl}" (referenced by "${transpiledFile.name}") cannot be found in list of transpiled files`
);
}
}
/**
* Gets the source map url from a transpiled file (the last comment with sourceMappingURL= ...)
*/
private getSourceMapUrl(transpiledFile: File): string | null {
SOURCE_MAP_URL_REGEX.lastIndex = 0;
let currentMatch: RegExpExecArray | null;
let lastMatch: RegExpExecArray | null = null;
// Retrieve the final sourceMappingURL comment in the file
while ((currentMatch = SOURCE_MAP_URL_REGEX.exec(transpiledFile.textContent))) {
lastMatch = currentMatch;
}
if (lastMatch) {
this.log.debug('Source map url found in transpiled file "%s"', transpiledFile.name);
return lastMatch[1];
} else {
this.log.debug('No source map url found in transpiled file "%s"', transpiledFile.name);
return null;
}
}
}
export class PassThroughSourceMapper extends SourceMapper {
/**
* @inheritdoc
*/
public transpiledFileNameFor(originalFileName: string): string {
return originalFileName;
}
/**
* @inheritdoc
*/
public async transpiledLocationFor(originalLocation: MappedLocation): Promise<MappedLocation> {
return Promise.resolve(originalLocation);
}
}
class SourceMap {
private sourceMap: SourceMapConsumer | undefined;
constructor(public transpiledFile: File, public sourceMapFileName: string, private readonly rawSourceMap: RawSourceMap) {}
public async generatedPositionFor(originalPosition: Position, relativeSource: string): Promise<Position> {
if (!this.sourceMap) {
this.sourceMap = await new SourceMapConsumer(this.rawSourceMap);
}
const transpiledPosition = await this.sourceMap.generatedPositionFor({
bias: SourceMapConsumer.LEAST_UPPER_BOUND,
column: originalPosition.column,
line: originalPosition.line + 1, // SourceMapConsumer works 1-based
source: relativeSource
});
return Promise.resolve({
column: transpiledPosition.column || 0,
line: (transpiledPosition.line || 1) - 1 // Stryker works 0-based
});
}
}
interface SourceMapBySource {
[sourceFileName: string]: SourceMap;
}