-
Notifications
You must be signed in to change notification settings - Fork 684
Expand file tree
/
Copy pathsource-map.js
More file actions
638 lines (581 loc) Β· 18.9 KB
/
Copy pathsource-map.js
File metadata and controls
638 lines (581 loc) Β· 18.9 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
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
/**
* Copyright (c) Meta Platforms, Inc. and affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*
* @flow strict-local
* @format
* @oncall react_native
*/
import type {IConsumer} from './Consumer/types';
import {BundleBuilder, createIndexMap} from './BundleBuilder';
import composeSourceMaps from './composeSourceMaps';
import Consumer from './Consumer';
// We need to export this for `metro-symbolicate`
import normalizeSourcePath from './Consumer/normalizeSourcePath';
import {
functionMapBabelPlugin,
generateFunctionMap,
} from './generateFunctionMap';
import Generator from './Generator';
import nullthrows from 'nullthrows';
// $FlowFixMe[untyped-import] - source-map
import SourceMap from 'source-map';
export type {IConsumer};
type GeneratedCodeMapping = [number, number];
type SourceMapping = [number, number, number, number];
type SourceMappingWithName = [number, number, number, number, string];
export type MetroSourceMapSegmentTuple =
| SourceMappingWithName
| SourceMapping
| GeneratedCodeMapping;
// A single segment of a standard "decoded" source map (as produced by
// `@babel/generator`'s `result.decodedMap` / `@jridgewell/gen-mapping`),
// grouped by generated line. All fields are 0-based, including the source line
// (unlike Metro's `MetroSourceMapSegmentTuple`, whose source line is 1-based):
// [generatedColumn]
// [generatedColumn, sourceIndex, sourceLine, sourceColumn]
// [generatedColumn, sourceIndex, sourceLine, sourceColumn, nameIndex]
type BabelDecodedMapSegment =
| [number]
| [number, number, number, number]
| [number, number, number, number, number];
export type BabelDecodedMap = {
readonly mappings: ReadonlyArray<ReadonlyArray<BabelDecodedMapSegment>>,
readonly names: ReadonlyArray<string>,
...
};
export type VlqMap = {
readonly mappings: string,
readonly names: ReadonlyArray<string>,
};
export type HermesFunctionOffsets = {[number]: ReadonlyArray<number>, ...};
export type FBSourcesArray = ReadonlyArray<?FBSourceMetadata>;
export type FBSourceMetadata = [?FBSourceFunctionMap];
export type FBSourceFunctionMap = {
readonly names: ReadonlyArray<string>,
readonly mappings: string,
};
export type BabelSourceMapSegment = Readonly<{
generated: Readonly<{column: number, line: number, ...}>,
original?: Readonly<{column: number, line: number, ...}>,
source?: ?string,
name?: ?string,
...
}>;
export type FBSegmentMap = {[id: string]: MixedSourceMap, ...};
export type BasicSourceMap = {
readonly file?: string,
readonly mappings: string,
readonly names: Array<string>,
readonly sourceRoot?: string,
readonly sources: Array<string>,
readonly sourcesContent?: Array<?string>,
readonly version: number,
readonly x_facebook_offsets?: Array<number>,
readonly x_metro_module_paths?: Array<string>,
readonly x_facebook_sources?: FBSourcesArray,
readonly x_facebook_segments?: FBSegmentMap,
readonly x_hermes_function_offsets?: HermesFunctionOffsets,
readonly x_google_ignoreList?: Array<number>,
};
export type IndexMapSection = {
map: IndexMap | BasicSourceMap,
offset: {
line: number,
column: number,
...
},
...
};
export type IndexMap = {
readonly file?: string,
readonly mappings?: void, // avoids SourceMap being a disjoint union
readonly sourcesContent?: void,
readonly sections: Array<IndexMapSection>,
readonly version: number,
readonly x_facebook_offsets?: Array<number>,
readonly x_metro_module_paths?: Array<string>,
readonly x_facebook_sources?: void,
readonly x_facebook_segments?: FBSegmentMap,
readonly x_hermes_function_offsets?: HermesFunctionOffsets,
readonly x_google_ignoreList?: void,
};
export type MixedSourceMap = IndexMap | BasicSourceMap;
type SourceMapConsumerMapping = {
generatedLine: number,
generatedColumn: number,
originalLine: ?number,
originalColumn: ?number,
source: ?string,
name: ?string,
};
export type RawMappingsModule = {
readonly map: ?ReadonlyArray<MetroSourceMapSegmentTuple> | VlqMap,
readonly functionMap: ?FBSourceFunctionMap,
readonly path: string,
readonly source: string,
readonly code: string,
readonly isIgnored: boolean,
readonly lineCount?: number,
};
// Common shape of the flat `Generator` and the indexed `IndexedSourceMapResult`,
// so serializers can hold either and call `toMap`/`toString` uniformly.
export interface SourceMapGenerator {
toMap(file?: string, options?: {excludeSource?: boolean}): MixedSourceMap;
toString(file?: string, options?: {excludeSource?: boolean}): string;
}
/**
* Result of `fromRawMappingsIndexed`: a sectioned (indexed) source map where
* each module is one section. VLQ-stored modules pass through verbatim, which is
* why building this is cheap compared to flattening into a single map.
*/
class IndexedSourceMapResult implements SourceMapGenerator {
#sections: Array<IndexMapSection>;
constructor(sections: Array<IndexMapSection>) {
this.#sections = sections;
}
toMap(file?: string, options?: {excludeSource?: boolean}): MixedSourceMap {
const sections =
options?.excludeSource === true
? this.#sections.map(section => {
// exclude source
const {sourcesContent: _, ...map} = section.map;
return {
...section,
map,
};
})
: this.#sections;
return createIndexMap(file, sections);
}
toString(file?: string, options?: {excludeSource?: boolean}): string {
return JSON.stringify(this.toMap(file, options));
}
}
function isVlqMap(
map: ?ReadonlyArray<MetroSourceMapSegmentTuple> | VlqMap,
): implies map is VlqMap {
return map != null && !Array.isArray(map) && typeof map.mappings === 'string';
}
function fromRawMappingsImpl(
isBlocking: boolean,
onDone: Generator => void,
modules: ReadonlyArray<RawMappingsModule>,
offsetLines: number,
): void {
const modulesToProcess = modules.slice();
const generator = new Generator();
let carryOver = offsetLines;
function processNextModule() {
if (modulesToProcess.length === 0) {
return true;
}
const mod = nullthrows(modulesToProcess.shift());
const {code, map} = mod;
if (isVlqMap(map)) {
// Modules may store their map compactly as VLQ. Decode it back to tuples
// just-in-time so it can be folded into the flat Generator like any other
// module. Decoding one module at a time keeps the transient tuple arrays
// short-lived, preserving the memory win of VLQ storage.
addMappingsForFile(generator, decodeVlqMap(map), mod, carryOver);
} else if (Array.isArray(map)) {
addMappingsForFile(generator, map, mod, carryOver);
} else if (map != null) {
throw new Error(
`Unexpected module with full source map found: ${mod.path}`,
);
}
carryOver = carryOver + countLines(code);
return false;
}
function workLoop() {
const time = process.hrtime();
while (true) {
const isDone = processNextModule();
if (isDone) {
onDone(generator);
break;
}
if (!isBlocking) {
// Keep the loop running but try to avoid blocking
// for too long because this is not in a worker yet.
const diff = process.hrtime(time);
const NS_IN_MS = 1000000;
if (diff[1] > 50 * NS_IN_MS) {
// We've blocked for more than 50ms.
// This code currently runs on the main thread,
// so let's give Metro an opportunity to handle requests.
setImmediate(workLoop);
break;
}
}
}
}
workLoop();
}
/**
* Creates a source map from modules with "raw mappings", i.e. an array of
* tuples with either 2, 4, or 5 elements:
* generated line, generated column, source line, source line, symbol name.
* Accepts an `offsetLines` argument in case modules' code is to be offset in
* the resulting bundle, e.g. by some prefix code.
*/
function fromRawMappings(
modules: ReadonlyArray<RawMappingsModule>,
offsetLines: number = 0,
): Generator {
let generator: void | Generator;
fromRawMappingsImpl(
true,
g => {
generator = g;
},
modules,
offsetLines,
);
if (generator == null) {
throw new Error('Expected fromRawMappingsImpl() to finish synchronously.');
}
return generator;
}
async function fromRawMappingsNonBlocking(
modules: ReadonlyArray<RawMappingsModule>,
offsetLines: number = 0,
): Promise<Generator> {
return new Promise(resolve => {
fromRawMappingsImpl(false, resolve, modules, offsetLines);
});
}
/**
* Like `fromRawMappings`, but produces an indexed (sectioned) source map with
* one section per module. VLQ-stored modules pass through verbatim β no
* decode/re-encode β which is the whole point: it's much cheaper to serialize
* than the flat path, at the cost of emitting an indexed map that consumers must
* understand. Per-module work is trivial, so this runs synchronously.
*/
function fromRawMappingsIndexed(
modules: ReadonlyArray<RawMappingsModule>,
offsetLines: number = 0,
): IndexedSourceMapResult {
const sections: Array<IndexMapSection> = [];
let carryOver = offsetLines;
for (const mod of modules) {
if (mod.map != null) {
sections.push({
offset: {line: carryOver, column: 0},
map: toIndexMapSection(mod),
});
}
carryOver = carryOver + countLines(mod.code);
}
return new IndexedSourceMapResult(sections);
}
/**
* Builds a single section of an indexed source map. VLQ maps pass through
* verbatim, while tuple maps are encoded with a fresh per-section Generator.
*/
function toIndexMapSection(module: RawMappingsModule): BasicSourceMap {
const {map, path, source, functionMap, isIgnored} = module;
if (isVlqMap(map)) {
let sectionMap: BasicSourceMap = {
version: 3,
sources: [path],
sourcesContent: [source],
names: [...map.names],
mappings: map.mappings,
};
// The Generator bakes these in for tuple maps; for passthrough VLQ maps we
// have to attach them ourselves.
if (functionMap != null) {
sectionMap = {...sectionMap, x_facebook_sources: [[functionMap]]};
}
if (isIgnored) {
sectionMap = {...sectionMap, x_google_ignoreList: [0]};
}
return sectionMap;
}
if (Array.isArray(map)) {
const generator = new Generator();
addMappingsForFile(generator, map, module, 0);
return generator.toMap();
}
throw new Error(`Unexpected module with full source map found: ${path}`);
}
/**
* Transforms a standard source map object into a Raw Mappings object, to be
* used across the bundler.
*/
function toBabelSegments(
sourceMap: BasicSourceMap,
): Array<BabelSourceMapSegment> {
const rawMappings: Array<BabelSourceMapSegment> = [];
new SourceMap.SourceMapConsumer(sourceMap).eachMapping(
(map: SourceMapConsumerMapping) => {
rawMappings.push(
map.originalLine == null || map.originalColumn == null
? {
generated: {
line: map.generatedLine,
column: map.generatedColumn,
},
source: map.source,
name: map.name,
}
: {
generated: {
line: map.generatedLine,
column: map.generatedColumn,
},
original: {
line: map.originalLine,
column: map.originalColumn,
},
source: map.source,
name: map.name,
},
);
},
);
return rawMappings;
}
function toSegmentTuple(
mapping: BabelSourceMapSegment,
): MetroSourceMapSegmentTuple {
const {column, line} = mapping.generated;
const {name, original} = mapping;
if (original == null) {
return [line, column];
}
if (typeof name !== 'string') {
return [line, column, original.line, original.column];
}
return [line, column, original.line, original.column, name];
}
/**
* Converts a Babel/gen-mapping "decoded" source map (`result.decodedMap` from
* `@babel/generator`) into raw mapping tuples, byte-identical to
* `result.rawMappings.map(toSegmentTuple)`.
*
* Preferred over `result.rawMappings` because `decodedMap` is computed eagerly
* during generation, whereas accessing `rawMappings` triggers a second decode
* (`allMappings`) that allocates ~4-5 objects per segment. No terminating
* mapping is appended (callers that need one use `countLinesAndTerminateMap`).
*/
function tuplesFromBabelDecodedMap(
decodedMap: BabelDecodedMap,
): Array<MetroSourceMapSegmentTuple> {
const {mappings, names} = decodedMap;
const tuples: Array<MetroSourceMapSegmentTuple> = [];
for (let line = 0, n = mappings.length; line < n; ++line) {
// Decoded mappings are grouped by generated line (0-based); tuples use
// 1-based generated lines.
const generatedLine = line + 1;
const segments = mappings[line];
for (let i = 0, m = segments.length; i < m; ++i) {
const segment = segments[i];
switch (segment.length) {
case 1:
tuples.push([generatedLine, segment[0]]);
break;
case 4:
// Decoded source lines are 0-based; tuples use 1-based source lines.
tuples.push([generatedLine, segment[0], segment[2] + 1, segment[3]]);
break;
case 5:
tuples.push([
generatedLine,
segment[0],
segment[2] + 1,
segment[3],
names[segment[4]],
]);
break;
}
}
}
return tuples;
}
function addMappingsForFile(
generator: Generator,
mappings: ReadonlyArray<MetroSourceMapSegmentTuple>,
module: RawMappingsModule,
carryOver: number,
) {
generator.startFile(module.path, module.source, module.functionMap, {
addToIgnoreList: module.isIgnored,
});
for (let i = 0, n = mappings.length; i < n; ++i) {
addMapping(generator, mappings[i], carryOver);
}
generator.endFile();
}
function addMapping(
generator: Generator,
mapping: MetroSourceMapSegmentTuple,
carryOver: number,
) {
const line = mapping[0] + carryOver;
// lines start at 1, columns start at 0
const column = mapping[1];
switch (mapping.length) {
case 2:
generator.addSimpleMapping(line, column);
return;
case 4:
generator.addSourceMapping(line, column, mapping[2], mapping[3]);
return;
case 5:
generator.addNamedSourceMapping(
line,
column,
mapping[2],
mapping[3],
mapping[4],
);
return;
}
throw new Error(`Invalid mapping: [${mapping.join(', ')}]`);
}
const newline = /\r\n?|\n|\u2028|\u2029/g;
const countLines = (string: string): number =>
(string.match(newline) || []).length + 1;
/**
* Decodes a compact VLQ map back into raw mapping tuples β the inverse of
* `vlqMapFromTuples`, reusing Metro's existing source-map consumer.
*/
function decodeVlqMap(vlqMap: VlqMap): Array<MetroSourceMapSegmentTuple> {
return toBabelSegments({
version: 3,
sources: [''],
names: [...vlqMap.names],
mappings: vlqMap.mappings,
}).map(toSegmentTuple);
}
/**
* Encodes raw mapping tuples into a compact VLQ `mappings` string + `names`
* table. Decode the inverse via `decodeVlqMap` (or `toBabelSegments` +
* `toSegmentTuple`). Storing maps in this form uses far less memory than the
* equivalent decoded tuple arrays.
*/
function vlqMapFromTuples(
mappings: ReadonlyArray<MetroSourceMapSegmentTuple>,
): VlqMap {
const generator = new Generator();
generator.startFile('', '', null);
for (const mapping of mappings) {
addMapping(generator, mapping, 0);
}
generator.endFile();
const map = generator.toMap();
return {mappings: map.mappings, names: map.names};
}
/**
* Encodes a `VlqMap` directly from a Babel/gen-mapping "decoded" source map
* (`result.decodedMap` from `@babel/generator`), without ever materialising the
* intermediate `Array<MetroSourceMapSegmentTuple>`.
*
* `@babel/generator` computes `decodedMap` eagerly while generating, so reusing
* it avoids the separate, more expensive `result.rawMappings` decode (which
* allocates a flat array of segment objects) plus the per-segment tuple
* allocation that `vlqMapFromTuples` would otherwise consume. The result is
* byte-identical to `vlqMapFromTuples(decoded -> tuples)`.
*
* `terminatingMapping` is a `[generatedLine1Based, generatedColumn0Based]`
* generated-only mapping appended at the end (matching the transform worker's
* `countLinesAndTerminateMap`) unless the last real mapping already sits there.
*/
function vlqMapFromBabelDecodedMap(
decodedMap: BabelDecodedMap,
terminatingMapping: [number, number],
): VlqMap {
const generator = new Generator();
generator.startFile('', '', null);
const {mappings, names} = decodedMap;
let lastGeneratedLine = -1;
let lastGeneratedColumn = -1;
for (let line = 0, n = mappings.length; line < n; ++line) {
// Decoded mappings are grouped by generated line (0-based); Generator
// expects 1-based generated lines.
const generatedLine = line + 1;
const segments = mappings[line];
for (let i = 0, m = segments.length; i < m; ++i) {
const segment = segments[i];
const generatedColumn = segment[0];
switch (segment.length) {
case 1:
generator.addSimpleMapping(generatedLine, generatedColumn);
break;
case 4:
// Decoded source lines are 0-based; Generator expects 1-based.
generator.addSourceMapping(
generatedLine,
generatedColumn,
segment[2] + 1,
segment[3],
);
break;
case 5:
generator.addNamedSourceMapping(
generatedLine,
generatedColumn,
segment[2] + 1,
segment[3],
names[segment[4]],
);
break;
default:
throw new Error(`Invalid mapping: [${segment.join(', ')}]`);
}
lastGeneratedLine = generatedLine;
lastGeneratedColumn = generatedColumn;
}
}
if (
lastGeneratedLine !== terminatingMapping[0] ||
lastGeneratedColumn !== terminatingMapping[1]
) {
generator.addSimpleMapping(terminatingMapping[0], terminatingMapping[1]);
}
generator.endFile();
const map = generator.toMap();
return {mappings: map.mappings, names: map.names};
}
export {
BundleBuilder,
composeSourceMaps,
Consumer,
createIndexMap,
generateFunctionMap,
fromRawMappings,
fromRawMappingsIndexed,
fromRawMappingsNonBlocking,
functionMapBabelPlugin,
isVlqMap,
normalizeSourcePath,
toBabelSegments,
toSegmentTuple,
tuplesFromBabelDecodedMap,
vlqMapFromBabelDecodedMap,
vlqMapFromTuples,
};
/**
* Backwards-compatibility with CommonJS consumers using interopRequireDefault.
* Do not add to this list.
*
* @deprecated Default import from 'metro-source-map' is deprecated, use named exports.
*/
export default {
BundleBuilder,
composeSourceMaps,
Consumer,
createIndexMap,
generateFunctionMap,
fromRawMappings,
fromRawMappingsNonBlocking,
functionMapBabelPlugin,
normalizeSourcePath,
toBabelSegments,
toSegmentTuple,
};