forked from microsoft/TypeScript
-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathsourcemapDecoder.ts
More file actions
377 lines (332 loc) · 16.4 KB
/
sourcemapDecoder.ts
File metadata and controls
377 lines (332 loc) · 16.4 KB
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
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
/* @internal */
namespace ts {
export interface SourceFileLikeCache {
get(path: Path): SourceFileLike | undefined;
}
export function createSourceFileLikeCache(host: { readFile?: (path: string) => string | undefined, fileExists?: (path: string) => boolean }): SourceFileLikeCache {
const cached = createMap<SourceFileLike>();
return {
get(path: Path) {
if (cached.has(path)) {
return cached.get(path);
}
if (!host.fileExists || !host.readFile || !host.fileExists(path)) return;
// And failing that, check the disk
const text = host.readFile(path)!; // TODO: GH#18217
const file = {
text,
lineMap: undefined,
getLineAndCharacterOfPosition(pos: number) {
return computeLineAndCharacterOfPosition(getLineStarts(this), pos);
}
} as SourceFileLike;
cached.set(path, file);
return file;
}
};
}
}
/* @internal */
namespace ts.sourcemaps {
export interface SourceMapData {
version?: number;
file?: string;
sourceRoot?: string;
sources: string[];
sourcesContent?: (string | null)[];
names?: string[];
mappings: string;
}
export interface SourceMappableLocation {
fileName: string;
position: number;
}
export interface SourceMapper {
getOriginalPosition(input: SourceMappableLocation): SourceMappableLocation;
getGeneratedPosition(input: SourceMappableLocation): SourceMappableLocation;
}
export const identitySourceMapper = { getOriginalPosition: identity, getGeneratedPosition: identity };
export interface SourceMapDecodeHost {
readFile(path: string): string | undefined;
fileExists(path: string): boolean;
getCanonicalFileName(path: string): string;
log(text: string): void;
}
export function decode(host: SourceMapDecodeHost, mapPath: string, map: SourceMapData, program?: Program, fallbackCache = createSourceFileLikeCache(host)): SourceMapper {
const currentDirectory = getDirectoryPath(mapPath);
const sourceRoot = map.sourceRoot ? getNormalizedAbsolutePath(map.sourceRoot, currentDirectory) : currentDirectory;
let decodedMappings: ProcessedSourceMapPosition[];
let generatedOrderedMappings: ProcessedSourceMapPosition[];
let sourceOrderedMappings: ProcessedSourceMapPosition[];
return {
getOriginalPosition,
getGeneratedPosition
};
function getGeneratedPosition(loc: SourceMappableLocation): SourceMappableLocation {
const maps = getSourceOrderedMappings();
if (!length(maps)) return loc;
let targetIndex = binarySearch(maps, { sourcePath: loc.fileName, sourcePosition: loc.position }, identity, compareProcessedPositionSourcePositions);
if (targetIndex < 0 && maps.length > 0) {
// if no exact match, closest is 2's compliment of result
targetIndex = ~targetIndex;
}
if (!maps[targetIndex] || comparePaths(loc.fileName, maps[targetIndex].sourcePath, sourceRoot) !== 0) {
return loc;
}
return { fileName: toPath(map.file!, sourceRoot, host.getCanonicalFileName), position: maps[targetIndex].emittedPosition }; // Closest pos
}
function getOriginalPosition(loc: SourceMappableLocation): SourceMappableLocation {
const maps = getGeneratedOrderedMappings();
if (!length(maps)) return loc;
let targetIndex = binarySearch(maps, { emittedPosition: loc.position }, identity, compareProcessedPositionEmittedPositions);
if (targetIndex < 0 && maps.length > 0) {
// if no exact match, closest is 2's compliment of result
targetIndex = ~targetIndex;
}
return { fileName: toPath(maps[targetIndex].sourcePath, sourceRoot, host.getCanonicalFileName), position: maps[targetIndex].sourcePosition }; // Closest pos
}
function getSourceFileLike(fileName: string, location: string): SourceFileLike | undefined {
// Lookup file in program, if provided
const path = toPath(fileName, location, host.getCanonicalFileName);
const file = program && program.getSourceFile(path);
// file returned here could be .d.ts when asked for .ts file if projectReferences and module resolution created this source file
if (!file || file.resolvedPath !== path) {
// Otherwise check the cache (which may hit disk)
return fallbackCache.get(path);
}
return file;
}
function getPositionOfLineAndCharacterUsingName(fileName: string, directory: string, line: number, character: number) {
const file = getSourceFileLike(fileName, directory);
if (!file) {
return -1;
}
return getPositionOfLineAndCharacter(file, line, character);
}
function getDecodedMappings() {
return decodedMappings || (decodedMappings = calculateDecodedMappings(map, processPosition, host));
}
function getSourceOrderedMappings() {
return sourceOrderedMappings || (sourceOrderedMappings = getDecodedMappings().slice().sort(compareProcessedPositionSourcePositions));
}
function getGeneratedOrderedMappings() {
return generatedOrderedMappings || (generatedOrderedMappings = getDecodedMappings().slice().sort(compareProcessedPositionEmittedPositions));
}
function compareProcessedPositionSourcePositions(a: ProcessedSourceMapPosition, b: ProcessedSourceMapPosition) {
return comparePaths(a.sourcePath, b.sourcePath, sourceRoot) ||
compareValues(a.sourcePosition, b.sourcePosition);
}
function compareProcessedPositionEmittedPositions(a: ProcessedSourceMapPosition, b: ProcessedSourceMapPosition) {
return compareValues(a.emittedPosition, b.emittedPosition);
}
function processPosition(position: RawSourceMapPosition): ProcessedSourceMapPosition {
const sourcePath = map.sources[position.sourceIndex];
return {
emittedPosition: getPositionOfLineAndCharacterUsingName(map.file!, currentDirectory, position.emittedLine, position.emittedColumn),
sourcePosition: getPositionOfLineAndCharacterUsingName(sourcePath, sourceRoot, position.sourceLine, position.sourceColumn),
sourcePath,
// TODO: Consider using `name` field to remap the expected identifier to scan for renames to handle another tool renaming oout output
// name: position.nameIndex ? map.names[position.nameIndex] : undefined
};
}
}
/*@internal*/
export interface MappingsDecoder extends Iterator<SourceMapSpan> {
readonly decodingIndex: number;
readonly error: string | undefined;
readonly lastSpan: SourceMapSpan;
}
/*@internal*/
export function decodeMappings(map: SourceMapData): MappingsDecoder {
const state: DecoderState = {
encodedText: map.mappings,
currentNameIndex: undefined,
sourceMapNamesLength: map.names ? map.names.length : undefined,
currentEmittedColumn: 0,
currentEmittedLine: 0,
currentSourceColumn: 0,
currentSourceLine: 0,
currentSourceIndex: 0,
decodingIndex: 0
};
function captureSpan(): SourceMapSpan {
return {
emittedColumn: state.currentEmittedColumn,
emittedLine: state.currentEmittedLine,
sourceColumn: state.currentSourceColumn,
sourceIndex: state.currentSourceIndex,
sourceLine: state.currentSourceLine,
nameIndex: state.currentNameIndex
};
}
return {
get decodingIndex() { return state.decodingIndex; },
get error() { return state.error; },
get lastSpan() { return captureSpan(); },
next() {
if (hasCompletedDecoding(state) || state.error) return { done: true, value: undefined as never };
if (!decodeSinglePosition(state)) return { done: true, value: undefined as never };
return { done: false, value: captureSpan() };
}
};
}
function calculateDecodedMappings<T>(map: SourceMapData, processPosition: (position: RawSourceMapPosition) => T, host?: { log?(s: string): void }): T[] {
const decoder = decodeMappings(map);
const positions = arrayFrom(decoder, processPosition);
if (decoder.error) {
if (host && host.log) {
host.log(`Encountered error while decoding sourcemap: ${decoder.error}`);
}
return [];
}
return positions;
}
interface ProcessedSourceMapPosition {
emittedPosition: number;
sourcePosition: number;
sourcePath: string;
}
interface RawSourceMapPosition {
emittedLine: number;
emittedColumn: number;
sourceLine: number;
sourceColumn: number;
sourceIndex: number;
nameIndex?: number;
}
interface DecoderState {
decodingIndex: number;
currentEmittedLine: number;
currentEmittedColumn: number;
currentSourceLine: number;
currentSourceColumn: number;
currentSourceIndex: number;
currentNameIndex: number | undefined;
encodedText: string;
sourceMapNamesLength?: number;
error?: string;
}
function hasCompletedDecoding(state: DecoderState) {
return state.decodingIndex === state.encodedText.length;
}
function decodeSinglePosition(state: DecoderState): boolean {
while (state.decodingIndex < state.encodedText.length) {
const char = state.encodedText.charCodeAt(state.decodingIndex);
if (char === CharacterCodes.semicolon) {
// New line
state.currentEmittedLine++;
state.currentEmittedColumn = 0;
state.decodingIndex++;
continue;
}
if (char === CharacterCodes.comma) {
// Next entry is on same line - no action needed
state.decodingIndex++;
continue;
}
// Read the current position
// 1. Column offset from prev read jsColumn
state.currentEmittedColumn += base64VLQFormatDecode();
// Incorrect emittedColumn dont support this map
if (createErrorIfCondition(state.currentEmittedColumn < 0, "Invalid emittedColumn found")) {
return false;
}
// Dont support reading mappings that dont have information about original source and its line numbers
if (createErrorIfCondition(isSourceMappingSegmentEnd(state.encodedText, state.decodingIndex), "Unsupported Error Format: No entries after emitted column")) {
return false;
}
// 2. Relative sourceIndex
state.currentSourceIndex += base64VLQFormatDecode();
// Incorrect sourceIndex dont support this map
if (createErrorIfCondition(state.currentSourceIndex < 0, "Invalid sourceIndex found")) {
return false;
}
// Dont support reading mappings that dont have information about original source position
if (createErrorIfCondition(isSourceMappingSegmentEnd(state.encodedText, state.decodingIndex), "Unsupported Error Format: No entries after sourceIndex")) {
return false;
}
// 3. Relative sourceLine 0 based
state.currentSourceLine += base64VLQFormatDecode();
// Incorrect sourceLine dont support this map
if (createErrorIfCondition(state.currentSourceLine < 0, "Invalid sourceLine found")) {
return false;
}
// Dont support reading mappings that dont have information about original source and its line numbers
if (createErrorIfCondition(isSourceMappingSegmentEnd(state.encodedText, state.decodingIndex), "Unsupported Error Format: No entries after emitted Line")) {
return false;
}
// 4. Relative sourceColumn 0 based
state.currentSourceColumn += base64VLQFormatDecode();
// Incorrect sourceColumn dont support this map
if (createErrorIfCondition(state.currentSourceColumn < 0, "Invalid sourceLine found")) {
return false;
}
// 5. Check if there is name:
if (!isSourceMappingSegmentEnd(state.encodedText, state.decodingIndex)) {
if (state.currentNameIndex === undefined) {
state.currentNameIndex = 0;
}
state.currentNameIndex += base64VLQFormatDecode();
// Incorrect nameIndex dont support this map
// TODO: If we start using `name`s, issue errors when they aren't correct in the sourcemap
// if (createErrorIfCondition(state.currentNameIndex < 0 || state.currentNameIndex >= state.sourceMapNamesLength, "Invalid name index for the source map entry")) {
// return;
// }
}
// Dont support reading mappings that dont have information about original source and its line numbers
if (createErrorIfCondition(!isSourceMappingSegmentEnd(state.encodedText, state.decodingIndex), "Unsupported Error Format: There are more entries after " + (state.currentNameIndex === undefined ? "sourceColumn" : "nameIndex"))) {
return false;
}
// Entry should be complete
return true;
}
createErrorIfCondition(/*condition*/ true, "No encoded entry found");
return false;
function createErrorIfCondition(condition: boolean, errormsg: string) {
if (state.error) {
// An error was already reported
return true;
}
if (condition) {
state.error = errormsg;
}
return condition;
}
function base64VLQFormatDecode(): number {
let moreDigits = true;
let shiftCount = 0;
let value = 0;
for (; moreDigits; state.decodingIndex++) {
if (createErrorIfCondition(state.decodingIndex >= state.encodedText.length, "Error in decoding base64VLQFormatDecode, past the mapping string")) {
return undefined!; // TODO: GH#18217
}
// 6 digit number
const currentByte = base64FormatDecode(state.encodedText.charAt(state.decodingIndex));
// If msb is set, we still have more bits to continue
moreDigits = (currentByte & 32) !== 0;
// least significant 5 bits are the next msbs in the final value.
value = value | ((currentByte & 31) << shiftCount);
shiftCount += 5;
}
// Least significant bit if 1 represents negative and rest of the msb is actual absolute value
if ((value & 1) === 0) {
// + number
value = value >> 1;
}
else {
// - number
value = value >> 1;
value = -value;
}
return value;
}
}
function base64FormatDecode(char: string) {
return "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/".indexOf(char);
}
function isSourceMappingSegmentEnd(encodedText: string, pos: number) {
return (pos === encodedText.length ||
encodedText.charCodeAt(pos) === CharacterCodes.comma ||
encodedText.charCodeAt(pos) === CharacterCodes.semicolon);
}
}