metro-source-map 0.52.0 → 0.54.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/package.json CHANGED
@@ -1,5 +1,5 @@
1
1
  {
2
- "version": "0.52.0",
2
+ "version": "0.54.1",
3
3
  "name": "metro-source-map",
4
4
  "description": "🚇 Source map generator for Metro.",
5
5
  "main": "src/source-map.js",
@@ -12,7 +12,13 @@
12
12
  "cleanup-release": "test ! -e build && mv src build && mv src.real src"
13
13
  },
14
14
  "dependencies": {
15
+ "@babel/traverse": "^7.0.0",
16
+ "@babel/types": "^7.0.0",
15
17
  "source-map": "^0.5.6"
16
18
  },
17
- "license": "MIT"
19
+ "license": "MIT",
20
+ "devDependencies": {
21
+ "@babel/parser": "^7.0.0",
22
+ "metro-symbolicate": "0.54.1"
23
+ }
18
24
  }
@@ -0,0 +1,132 @@
1
+ /**
2
+ * Copyright (c) Facebook, Inc. and its affiliates.
3
+ *
4
+ * This source code is licensed under the MIT license found in the
5
+ * LICENSE file in the root directory of this source tree.
6
+ *
7
+ *
8
+ * @format
9
+ */
10
+ "use strict";
11
+
12
+ const EMPTY_MAP = {
13
+ version: 3,
14
+ sources: [],
15
+ names: [],
16
+ mappings: "A"
17
+ };
18
+ /**
19
+ * Builds a source-mapped bundle by concatenating strings and their
20
+ * corresponding source maps (if any).
21
+ *
22
+ * Usage:
23
+ *
24
+ * const builder = new BundleBuilder('bundle.js');
25
+ * builder
26
+ * .append('foo\n', fooMap)
27
+ * .append('bar\n')
28
+ * // ...
29
+ * const code = builder.getCode();
30
+ * const map = builder.getMap();
31
+ */
32
+
33
+ class BundleBuilder {
34
+ constructor(file) {
35
+ this._file = file;
36
+ this._sections = [];
37
+ this._line = 0;
38
+ this._column = 0;
39
+ this._code = "";
40
+ this._afterMappedContent = false;
41
+ }
42
+
43
+ _pushMapSection(map) {
44
+ this._sections.push({
45
+ map,
46
+ offset: {
47
+ column: this._column,
48
+ line: this._line
49
+ }
50
+ });
51
+ }
52
+
53
+ _endMappedContent() {
54
+ if (this._afterMappedContent) {
55
+ this._pushMapSection(EMPTY_MAP);
56
+
57
+ this._afterMappedContent = false;
58
+ }
59
+ }
60
+
61
+ append(code, map) {
62
+ if (!code.length) {
63
+ return this;
64
+ }
65
+
66
+ const _measureString = measureString(code),
67
+ lineBreaks = _measureString.lineBreaks,
68
+ lastLineColumns = _measureString.lastLineColumns;
69
+
70
+ if (map) {
71
+ this._pushMapSection(map);
72
+
73
+ this._afterMappedContent = true;
74
+ } else {
75
+ this._endMappedContent();
76
+ }
77
+
78
+ this._afterMappedContent = !!map;
79
+ this._line = this._line + lineBreaks;
80
+
81
+ if (lineBreaks > 0) {
82
+ this._column = lastLineColumns;
83
+ } else {
84
+ this._column = this._column + lastLineColumns;
85
+ }
86
+
87
+ this._code = this._code + code;
88
+ return this;
89
+ }
90
+
91
+ getMap() {
92
+ this._endMappedContent();
93
+
94
+ return createIndexMap(this._file, this._sections);
95
+ }
96
+
97
+ getCode() {
98
+ return this._code;
99
+ }
100
+ }
101
+
102
+ const reLineBreak = /\r\n|\r|\n/g;
103
+
104
+ function measureString(str) {
105
+ let lineBreaks = 0;
106
+ let match;
107
+ let lastLineStart = 0;
108
+
109
+ while ((match = reLineBreak.exec(str))) {
110
+ ++lineBreaks;
111
+ lastLineStart = match.index + match[0].length;
112
+ }
113
+
114
+ const lastLineColumns = str.length - lastLineStart;
115
+ return {
116
+ lineBreaks,
117
+ lastLineColumns
118
+ };
119
+ }
120
+
121
+ function createIndexMap(file, sections) {
122
+ return {
123
+ version: 3,
124
+ file,
125
+ sections
126
+ };
127
+ }
128
+
129
+ module.exports = {
130
+ BundleBuilder,
131
+ createIndexMap
132
+ };
@@ -0,0 +1,126 @@
1
+ /**
2
+ * Copyright (c) Facebook, Inc. and its affiliates.
3
+ *
4
+ * This source code is licensed under the MIT license found in the
5
+ * LICENSE file in the root directory of this source tree.
6
+ *
7
+ * @flow
8
+ * @format
9
+ */
10
+
11
+ 'use strict';
12
+
13
+ import type {IndexMap, IndexMapSection, MetroSourceMap} from './source-map';
14
+
15
+ const EMPTY_MAP = {
16
+ version: 3,
17
+ sources: [],
18
+ names: [],
19
+ mappings: 'A',
20
+ };
21
+
22
+ /**
23
+ * Builds a source-mapped bundle by concatenating strings and their
24
+ * corresponding source maps (if any).
25
+ *
26
+ * Usage:
27
+ *
28
+ * const builder = new BundleBuilder('bundle.js');
29
+ * builder
30
+ * .append('foo\n', fooMap)
31
+ * .append('bar\n')
32
+ * // ...
33
+ * const code = builder.getCode();
34
+ * const map = builder.getMap();
35
+ */
36
+ class BundleBuilder {
37
+ _file: string;
38
+ _sections: Array<IndexMapSection>;
39
+ _line: number;
40
+ _column: number;
41
+ _code: string;
42
+ _afterMappedContent: boolean;
43
+
44
+ constructor(file: string) {
45
+ this._file = file;
46
+ this._sections = [];
47
+ this._line = 0;
48
+ this._column = 0;
49
+ this._code = '';
50
+ this._afterMappedContent = false;
51
+ }
52
+
53
+ _pushMapSection(map: MetroSourceMap) {
54
+ this._sections.push({
55
+ map,
56
+ offset: {column: this._column, line: this._line},
57
+ });
58
+ }
59
+
60
+ _endMappedContent() {
61
+ if (this._afterMappedContent) {
62
+ this._pushMapSection(EMPTY_MAP);
63
+ this._afterMappedContent = false;
64
+ }
65
+ }
66
+
67
+ append(code: string, map: ?MetroSourceMap): this {
68
+ if (!code.length) {
69
+ return this;
70
+ }
71
+ const {lineBreaks, lastLineColumns} = measureString(code);
72
+ if (map) {
73
+ this._pushMapSection(map);
74
+ this._afterMappedContent = true;
75
+ } else {
76
+ this._endMappedContent();
77
+ }
78
+ this._afterMappedContent = !!map;
79
+ this._line = this._line + lineBreaks;
80
+ if (lineBreaks > 0) {
81
+ this._column = lastLineColumns;
82
+ } else {
83
+ this._column = this._column + lastLineColumns;
84
+ }
85
+ this._code = this._code + code;
86
+ return this;
87
+ }
88
+
89
+ getMap(): MetroSourceMap {
90
+ this._endMappedContent();
91
+ return createIndexMap(this._file, this._sections);
92
+ }
93
+
94
+ getCode(): string {
95
+ return this._code;
96
+ }
97
+ }
98
+
99
+ const reLineBreak = /\r\n|\r|\n/g;
100
+
101
+ function measureString(
102
+ str: string,
103
+ ): {|lineBreaks: number, lastLineColumns: number|} {
104
+ let lineBreaks = 0;
105
+ let match;
106
+ let lastLineStart = 0;
107
+ while ((match = reLineBreak.exec(str))) {
108
+ ++lineBreaks;
109
+ lastLineStart = match.index + match[0].length;
110
+ }
111
+ const lastLineColumns = str.length - lastLineStart;
112
+ return {lineBreaks, lastLineColumns};
113
+ }
114
+
115
+ function createIndexMap(
116
+ file: string,
117
+ sections: Array<IndexMapSection>,
118
+ ): IndexMap {
119
+ return {
120
+ version: 3,
121
+ file,
122
+ sections,
123
+ };
124
+ }
125
+
126
+ module.exports = {BundleBuilder, createIndexMap};
package/src/Generator.js CHANGED
@@ -226,6 +226,9 @@ class IndexedSet {
226
226
  }
227
227
 
228
228
  items() {
229
+ /* $FlowFixMe(>=0.98.0 site=react_native_fb) This comment suppresses an
230
+ * error found when Flow v0.98 was deployed. To see the error delete this
231
+ * comment and run Flow. */
229
232
  return Array.from(this.map.keys());
230
233
  }
231
234
  }
@@ -212,6 +212,9 @@ class IndexedSet {
212
212
  }
213
213
 
214
214
  items() {
215
+ /* $FlowFixMe(>=0.98.0 site=react_native_fb) This comment suppresses an
216
+ * error found when Flow v0.98 was deployed. To see the error delete this
217
+ * comment and run Flow. */
215
218
  return Array.from(this.map.keys());
216
219
  }
217
220
  }
@@ -0,0 +1,531 @@
1
+ /**
2
+ * Copyright (c) Facebook, Inc. and its affiliates.
3
+ *
4
+ * This source code is licensed under the MIT license found in the
5
+ * LICENSE file in the root directory of this source tree.
6
+ *
7
+ *
8
+ * @format
9
+ *
10
+ */
11
+ "use strict";
12
+
13
+ var _traverse = _interopRequireDefault(require("@babel/traverse"));
14
+
15
+ function _interopRequireDefault(obj) {
16
+ return obj && obj.__esModule ? obj : { default: obj };
17
+ }
18
+
19
+ function _slicedToArray(arr, i) {
20
+ return (
21
+ _arrayWithHoles(arr) || _iterableToArrayLimit(arr, i) || _nonIterableRest()
22
+ );
23
+ }
24
+
25
+ function _nonIterableRest() {
26
+ throw new TypeError("Invalid attempt to destructure non-iterable instance");
27
+ }
28
+
29
+ function _iterableToArrayLimit(arr, i) {
30
+ var _arr = [];
31
+ var _n = true;
32
+ var _d = false;
33
+ var _e = undefined;
34
+ try {
35
+ for (
36
+ var _i = arr[Symbol.iterator](), _s;
37
+ !(_n = (_s = _i.next()).done);
38
+ _n = true
39
+ ) {
40
+ _arr.push(_s.value);
41
+ if (i && _arr.length === i) break;
42
+ }
43
+ } catch (err) {
44
+ _d = true;
45
+ _e = err;
46
+ } finally {
47
+ try {
48
+ if (!_n && _i["return"] != null) _i["return"]();
49
+ } finally {
50
+ if (_d) throw _e;
51
+ }
52
+ }
53
+ return _arr;
54
+ }
55
+
56
+ function _arrayWithHoles(arr) {
57
+ if (Array.isArray(arr)) return arr;
58
+ }
59
+
60
+ function _toConsumableArray(arr) {
61
+ return (
62
+ _arrayWithoutHoles(arr) || _iterableToArray(arr) || _nonIterableSpread()
63
+ );
64
+ }
65
+
66
+ function _nonIterableSpread() {
67
+ throw new TypeError("Invalid attempt to spread non-iterable instance");
68
+ }
69
+
70
+ function _iterableToArray(iter) {
71
+ if (
72
+ Symbol.iterator in Object(iter) ||
73
+ Object.prototype.toString.call(iter) === "[object Arguments]"
74
+ )
75
+ return Array.from(iter);
76
+ }
77
+
78
+ function _arrayWithoutHoles(arr) {
79
+ if (Array.isArray(arr)) {
80
+ for (var i = 0, arr2 = new Array(arr.length); i < arr.length; i++)
81
+ arr2[i] = arr[i];
82
+ return arr2;
83
+ }
84
+ }
85
+
86
+ const B64Builder = require("./B64Builder");
87
+
88
+ const fsPath = require("path");
89
+
90
+ const t = require("@babel/types");
91
+
92
+ /**
93
+ * Generate a map of source positions to function names. The names are meant to
94
+ * describe the stack frame in an error trace and may contain more contextual
95
+ * information than just the actual name of the function.
96
+ *
97
+ * The output is encoded for use in a source map. For details about the format,
98
+ * see MappingEncoder below.
99
+ */
100
+ function generateFunctionMap(ast, context) {
101
+ const encoder = new MappingEncoder();
102
+ forEachMapping(ast, context, mapping => encoder.push(mapping));
103
+ return encoder.getResult();
104
+ }
105
+ /**
106
+ * Same as generateFunctionMap, but returns the raw array of mappings instead
107
+ * of encoding it for use in a source map.
108
+ *
109
+ * Lines are 1-based and columns are 0-based.
110
+ */
111
+
112
+ function generateFunctionMappingsArray(ast, context) {
113
+ const mappings = [];
114
+ forEachMapping(ast, context, mapping => {
115
+ mappings.push(mapping);
116
+ });
117
+ return mappings;
118
+ }
119
+ /**
120
+ * Traverses a Babel AST and calls the supplied callback with function name
121
+ * mappings, one at a time.
122
+ */
123
+
124
+ function forEachMapping(ast, context, pushMapping) {
125
+ const nameStack = [];
126
+ let tailPos = {
127
+ line: 1,
128
+ column: 0
129
+ };
130
+ let tailName = null;
131
+
132
+ function advanceToPos(pos) {
133
+ if (tailPos && positionGreater(pos, tailPos)) {
134
+ const name = nameStack[0].name; // We always have at least Program
135
+
136
+ if (name !== tailName) {
137
+ pushMapping({
138
+ name,
139
+ start: {
140
+ line: tailPos.line,
141
+ column: tailPos.column
142
+ }
143
+ });
144
+ tailName = name;
145
+ }
146
+ }
147
+
148
+ tailPos = pos;
149
+ }
150
+
151
+ function pushFrame(name, loc) {
152
+ advanceToPos(loc.start);
153
+ nameStack.unshift({
154
+ name,
155
+ loc
156
+ });
157
+ }
158
+
159
+ function popFrame() {
160
+ const top = nameStack[0];
161
+
162
+ if (top) {
163
+ const loc = top.loc;
164
+ advanceToPos(loc.end);
165
+ nameStack.shift();
166
+ }
167
+ }
168
+
169
+ if (!context) {
170
+ context = {};
171
+ }
172
+
173
+ const basename = context.filename
174
+ ? fsPath.basename(context.filename).replace(/\..+$/, "")
175
+ : null;
176
+ (0, _traverse.default)(ast, {
177
+ "Function|Program": {
178
+ enter(path) {
179
+ let name = getNameForPath(path);
180
+
181
+ if (basename) {
182
+ name = removeNamePrefix(name, basename);
183
+ }
184
+
185
+ pushFrame(name, path.node.loc);
186
+ },
187
+
188
+ exit(path) {
189
+ popFrame();
190
+ }
191
+ }
192
+ });
193
+ }
194
+
195
+ const ANONYMOUS_NAME = "<anonymous>";
196
+ const CALLEES_TO_SKIP = ["Object.freeze"];
197
+ /**
198
+ * Derive a contextual name for the given AST node (Function, Program, Class or
199
+ * ObjectExpression).
200
+ */
201
+
202
+ function getNameForPath(path) {
203
+ const node = path.node,
204
+ parent = path.parent,
205
+ parentPath = path.parentPath;
206
+
207
+ if (t.isProgram(node)) {
208
+ return "<global>";
209
+ }
210
+
211
+ let id = path.id; // has an `id` so we don't need to infer one
212
+
213
+ if (node.id) {
214
+ return node.id.name;
215
+ }
216
+
217
+ let propertyPath;
218
+ let kind = "";
219
+
220
+ if (t.isObjectMethod(node) || t.isClassMethod(node)) {
221
+ id = node.key;
222
+
223
+ if (node.kind !== "method" && node.kind !== "constructor") {
224
+ kind = node.kind;
225
+ }
226
+
227
+ propertyPath = path;
228
+ } else if (t.isObjectProperty(parent) || t.isClassProperty(parent)) {
229
+ // { foo() {} };
230
+ id = parent.key;
231
+ propertyPath = parentPath;
232
+ } else if (t.isVariableDeclarator(parent)) {
233
+ // let foo = function () {};
234
+ id = parent.id;
235
+ } else if (t.isAssignmentExpression(parent)) {
236
+ // foo = function () {};
237
+ id = parent.left;
238
+ } else if (t.isJSXExpressionContainer(parent)) {
239
+ if (t.isJSXElement(parentPath.parentPath.node)) {
240
+ // <foo>{function () {}}</foo>
241
+ const openingElement = parentPath.parentPath.node.openingElement;
242
+ id = t.JSXMemberExpression(
243
+ t.JSXMemberExpression(openingElement.name, t.JSXIdentifier("props")),
244
+ t.JSXIdentifier("children")
245
+ );
246
+ } else if (t.isJSXAttribute(parentPath.parentPath.node)) {
247
+ // <foo bar={function () {}} />
248
+ const openingElement = parentPath.parentPath.parentPath.node;
249
+ const prop = parentPath.parentPath.node;
250
+ id = t.JSXMemberExpression(
251
+ t.JSXMemberExpression(openingElement.name, t.JSXIdentifier("props")),
252
+ prop.name
253
+ );
254
+ }
255
+ }
256
+
257
+ let name = getNameFromId(id);
258
+
259
+ if (name == null) {
260
+ if (t.isCallExpression(parent) || t.isNewExpression(parent)) {
261
+ // foo(function () {})
262
+ const argIndex = parent.arguments.indexOf(node);
263
+
264
+ if (argIndex !== -1) {
265
+ const calleeName = getNameFromId(parent.callee); // var f = Object.freeze(function () {})
266
+
267
+ if (CALLEES_TO_SKIP.indexOf(calleeName) !== -1) {
268
+ return getNameForPath(parentPath);
269
+ }
270
+
271
+ if (calleeName) {
272
+ return `${calleeName}$argument_${argIndex}`;
273
+ }
274
+ }
275
+ }
276
+
277
+ return ANONYMOUS_NAME;
278
+ }
279
+
280
+ if (kind) {
281
+ name = kind + "__" + name;
282
+ }
283
+
284
+ if (propertyPath) {
285
+ if (t.isClassBody(propertyPath.parent)) {
286
+ const className = getNameForPath(propertyPath.parentPath.parentPath);
287
+
288
+ if (className !== ANONYMOUS_NAME) {
289
+ const separator = propertyPath.node.static ? "." : "#";
290
+ name = className + separator + name;
291
+ }
292
+ } else if (t.isObjectExpression(propertyPath.parent)) {
293
+ const objectName = getNameForPath(propertyPath.parentPath);
294
+
295
+ if (objectName !== ANONYMOUS_NAME) {
296
+ name = objectName + "." + name;
297
+ }
298
+ }
299
+ }
300
+
301
+ return name;
302
+ }
303
+
304
+ function isAnyMemberExpression(node) {
305
+ return t.isMemberExpression(node) || t.isJSXMemberExpression(node);
306
+ }
307
+
308
+ function isAnyIdentifier(node) {
309
+ return t.isIdentifier(node) || t.isJSXIdentifier(node);
310
+ }
311
+
312
+ function getNameFromId(id) {
313
+ const parts = getNamePartsFromId(id);
314
+
315
+ if (!parts.length) {
316
+ return null;
317
+ }
318
+
319
+ if (parts.length > 5) {
320
+ return (
321
+ parts[0] +
322
+ "." +
323
+ parts[1] +
324
+ "..." +
325
+ parts[parts.length - 2] +
326
+ "." +
327
+ parts[parts.length - 1]
328
+ );
329
+ }
330
+
331
+ return parts.join(".");
332
+ }
333
+
334
+ function getNamePartsFromId(id) {
335
+ if (!id) {
336
+ return [];
337
+ }
338
+
339
+ if (t.isCallExpression(id) || t.isNewExpression(id)) {
340
+ return getNamePartsFromId(id.callee);
341
+ }
342
+
343
+ if (t.isTypeCastExpression(id)) {
344
+ return getNamePartsFromId(id.expression);
345
+ }
346
+
347
+ let name;
348
+
349
+ if (isAnyIdentifier(id)) {
350
+ name = id.name;
351
+ } else if (t.isNullLiteral(id)) {
352
+ name = "null";
353
+ } else if (t.isRegExpLiteral(id)) {
354
+ name = `_${id.pattern}_${id.flags}`;
355
+ } else if (t.isTemplateLiteral(id)) {
356
+ name = id.quasis.map(quasi => quasi.value.raw).join("");
357
+ } else if (t.isLiteral(id) && id.value != null) {
358
+ name = id.value + "";
359
+ }
360
+
361
+ if (name != null) {
362
+ return [t.toBindingIdentifierName(name)];
363
+ }
364
+
365
+ if (t.isImport(id)) {
366
+ name = "import";
367
+ }
368
+
369
+ if (name != null) {
370
+ return [name];
371
+ }
372
+
373
+ if (isAnyMemberExpression(id)) {
374
+ if (
375
+ isAnyIdentifier(id.object) &&
376
+ id.object.name === "Symbol" &&
377
+ (isAnyIdentifier(id.property) || t.isLiteral(id.property))
378
+ ) {
379
+ const propertyName = getNameFromId(id.property);
380
+
381
+ if (propertyName) {
382
+ name = "@@" + propertyName;
383
+ }
384
+ } else {
385
+ const propertyName = getNamePartsFromId(id.property);
386
+
387
+ if (propertyName.length) {
388
+ const objectName = getNamePartsFromId(id.object);
389
+
390
+ if (objectName.length) {
391
+ return _toConsumableArray(objectName).concat(
392
+ _toConsumableArray(propertyName)
393
+ );
394
+ } else {
395
+ return propertyName;
396
+ }
397
+ }
398
+ }
399
+ }
400
+
401
+ return name ? [name] : [];
402
+ }
403
+
404
+ const DELIMITER_START_RE = /^[^A-Za-z0-9_$@]+/;
405
+ /**
406
+ * Strip the given prefix from `name`, if it occurs there, plus any delimiter
407
+ * characters that follow (of which at least one is required). If an empty
408
+ * string would be returned, return the original name instead.
409
+ */
410
+
411
+ function removeNamePrefix(name, namePrefix) {
412
+ if (!namePrefix.length || !name.startsWith(namePrefix)) {
413
+ return name;
414
+ }
415
+
416
+ const shortenedName = name.substr(namePrefix.length);
417
+
418
+ const _ref = shortenedName.match(DELIMITER_START_RE) || [],
419
+ _ref2 = _slicedToArray(_ref, 1),
420
+ delimiterMatch = _ref2[0];
421
+
422
+ if (delimiterMatch) {
423
+ return shortenedName.substr(delimiterMatch.length) || name;
424
+ }
425
+
426
+ return name;
427
+ }
428
+ /**
429
+ * Encodes function name mappings as deltas in a Base64 VLQ format inspired by
430
+ * the standard source map format.
431
+ *
432
+ * Mappings on different lines are separated with a single `;` (even if there
433
+ * are multiple intervening lines).
434
+ * Mappings on the same line are separated with `,`.
435
+ *
436
+ * The first mapping of a line has the fields:
437
+ * [column delta, name delta, line delta]
438
+ *
439
+ * where the column delta is relative to the beginning of the line, the name
440
+ * delta is relative to the previously occurring name, and the line delta is
441
+ * relative to the previously occurring line.
442
+ *
443
+ * The 2...nth other mappings of a line have the fields:
444
+ * [column delta, name delta]
445
+ *
446
+ * where both fields are relative to their previous running values. The line
447
+ * delta is omitted since it is always 0 by definition.
448
+ *
449
+ * Lines and columns are both 0-based in the serialised format. In memory,
450
+ * lines are 1-based while columns are 0-based.
451
+ */
452
+
453
+ class MappingEncoder {
454
+ constructor() {
455
+ this._namesMap = new Map();
456
+ this._names = [];
457
+ this._line = new RelativeValue(1);
458
+ this._column = new RelativeValue(0);
459
+ this._nameIndex = new RelativeValue(0);
460
+ this._mappings = new B64Builder();
461
+ }
462
+
463
+ getResult() {
464
+ return {
465
+ names: this._names,
466
+ mappings: this._mappings.toString()
467
+ };
468
+ }
469
+
470
+ push(_ref3) {
471
+ let name = _ref3.name,
472
+ start = _ref3.start;
473
+
474
+ let nameIndex = this._namesMap.get(name);
475
+
476
+ if (typeof nameIndex !== "number") {
477
+ nameIndex = this._names.length;
478
+ this._names[nameIndex] = name;
479
+
480
+ this._namesMap.set(name, nameIndex);
481
+ }
482
+
483
+ const lineDelta = this._line.next(start.line);
484
+
485
+ const firstOfLine = this._mappings.pos === 0 || lineDelta > 0;
486
+
487
+ if (lineDelta > 0) {
488
+ // The next entry will have the line offset, so emit just one semicolon.
489
+ this._mappings.markLines(1);
490
+
491
+ this._column.reset(0);
492
+ }
493
+
494
+ this._mappings.startSegment(this._column.next(start.column));
495
+
496
+ this._mappings.append(this._nameIndex.next(nameIndex));
497
+
498
+ if (firstOfLine) {
499
+ this._mappings.append(lineDelta);
500
+ }
501
+ }
502
+ }
503
+
504
+ class RelativeValue {
505
+ constructor() {
506
+ let value =
507
+ arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : 0;
508
+ this.reset(value);
509
+ }
510
+
511
+ next(absoluteValue) {
512
+ const delta = absoluteValue - this._value;
513
+ this._value = absoluteValue;
514
+ return delta;
515
+ }
516
+
517
+ reset() {
518
+ let value =
519
+ arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : 0;
520
+ this._value = value;
521
+ }
522
+ }
523
+
524
+ function positionGreater(x, y) {
525
+ return x.line > y.line || (x.line === y.line && x.column > y.column);
526
+ }
527
+
528
+ module.exports = {
529
+ generateFunctionMap,
530
+ generateFunctionMappingsArray
531
+ };
@@ -0,0 +1,421 @@
1
+ /**
2
+ * Copyright (c) Facebook, Inc. and its affiliates.
3
+ *
4
+ * This source code is licensed under the MIT license found in the
5
+ * LICENSE file in the root directory of this source tree.
6
+ *
7
+ * @flow
8
+ * @format
9
+ *
10
+ */
11
+ 'use strict';
12
+
13
+ const B64Builder = require('./B64Builder');
14
+
15
+ const fsPath = require('path');
16
+ const t = require('@babel/types');
17
+
18
+ import type {FBSourceFunctionMap} from './source-map';
19
+ import type {Ast} from '@babel/core';
20
+ import traverse from '@babel/traverse';
21
+ import type {Path} from '@babel/traverse';
22
+ type Position = {line: number, column: number};
23
+ type RangeMapping = {name: string, start: Position};
24
+ type Context = {filename?: string};
25
+
26
+ /**
27
+ * Generate a map of source positions to function names. The names are meant to
28
+ * describe the stack frame in an error trace and may contain more contextual
29
+ * information than just the actual name of the function.
30
+ *
31
+ * The output is encoded for use in a source map. For details about the format,
32
+ * see MappingEncoder below.
33
+ */
34
+ function generateFunctionMap(ast: Ast, context?: Context): FBSourceFunctionMap {
35
+ const encoder = new MappingEncoder();
36
+ forEachMapping(ast, context, mapping => encoder.push(mapping));
37
+ return encoder.getResult();
38
+ }
39
+
40
+ /**
41
+ * Same as generateFunctionMap, but returns the raw array of mappings instead
42
+ * of encoding it for use in a source map.
43
+ *
44
+ * Lines are 1-based and columns are 0-based.
45
+ */
46
+ function generateFunctionMappingsArray(
47
+ ast: Ast,
48
+ context?: Context,
49
+ ): $ReadOnlyArray<RangeMapping> {
50
+ const mappings = [];
51
+ forEachMapping(ast, context, mapping => {
52
+ mappings.push(mapping);
53
+ });
54
+ return mappings;
55
+ }
56
+
57
+ /**
58
+ * Traverses a Babel AST and calls the supplied callback with function name
59
+ * mappings, one at a time.
60
+ */
61
+ function forEachMapping(
62
+ ast: Ast,
63
+ context: ?Context,
64
+ pushMapping: RangeMapping => void,
65
+ ) {
66
+ const nameStack = [];
67
+ let tailPos = {line: 1, column: 0};
68
+ let tailName = null;
69
+
70
+ function advanceToPos(pos) {
71
+ if (tailPos && positionGreater(pos, tailPos)) {
72
+ const name = nameStack[0].name; // We always have at least Program
73
+ if (name !== tailName) {
74
+ pushMapping({
75
+ name,
76
+ start: {line: tailPos.line, column: tailPos.column},
77
+ });
78
+ tailName = name;
79
+ }
80
+ }
81
+ tailPos = pos;
82
+ }
83
+
84
+ function pushFrame(name, loc) {
85
+ advanceToPos(loc.start);
86
+ nameStack.unshift({name, loc});
87
+ }
88
+
89
+ function popFrame() {
90
+ const top = nameStack[0];
91
+ if (top) {
92
+ const {loc} = top;
93
+ advanceToPos(loc.end);
94
+ nameStack.shift();
95
+ }
96
+ }
97
+
98
+ if (!context) {
99
+ context = {};
100
+ }
101
+
102
+ const basename = context.filename
103
+ ? fsPath.basename(context.filename).replace(/\..+$/, '')
104
+ : null;
105
+
106
+ traverse(ast, {
107
+ 'Function|Program': {
108
+ enter(path) {
109
+ let name = getNameForPath(path);
110
+ if (basename) {
111
+ name = removeNamePrefix(name, basename);
112
+ }
113
+ pushFrame(name, path.node.loc);
114
+ },
115
+ exit(path) {
116
+ popFrame();
117
+ },
118
+ },
119
+ });
120
+ }
121
+
122
+ const ANONYMOUS_NAME = '<anonymous>';
123
+ const CALLEES_TO_SKIP = ['Object.freeze'];
124
+
125
+ /**
126
+ * Derive a contextual name for the given AST node (Function, Program, Class or
127
+ * ObjectExpression).
128
+ */
129
+ function getNameForPath(path: Path): string {
130
+ const {node, parent, parentPath} = path;
131
+ if (t.isProgram(node)) {
132
+ return '<global>';
133
+ }
134
+ let {id} = path;
135
+ // has an `id` so we don't need to infer one
136
+ if (node.id) {
137
+ return node.id.name;
138
+ }
139
+ let propertyPath;
140
+ let kind = '';
141
+ if (t.isObjectMethod(node) || t.isClassMethod(node)) {
142
+ id = node.key;
143
+ if (node.kind !== 'method' && node.kind !== 'constructor') {
144
+ kind = node.kind;
145
+ }
146
+ propertyPath = path;
147
+ } else if (t.isObjectProperty(parent) || t.isClassProperty(parent)) {
148
+ // { foo() {} };
149
+ id = parent.key;
150
+ propertyPath = parentPath;
151
+ } else if (t.isVariableDeclarator(parent)) {
152
+ // let foo = function () {};
153
+ id = parent.id;
154
+ } else if (t.isAssignmentExpression(parent)) {
155
+ // foo = function () {};
156
+ id = parent.left;
157
+ } else if (t.isJSXExpressionContainer(parent)) {
158
+ if (t.isJSXElement(parentPath.parentPath.node)) {
159
+ // <foo>{function () {}}</foo>
160
+ const openingElement = parentPath.parentPath.node.openingElement;
161
+ id = t.JSXMemberExpression(
162
+ t.JSXMemberExpression(openingElement.name, t.JSXIdentifier('props')),
163
+ t.JSXIdentifier('children'),
164
+ );
165
+ } else if (t.isJSXAttribute(parentPath.parentPath.node)) {
166
+ // <foo bar={function () {}} />
167
+ const openingElement = parentPath.parentPath.parentPath.node;
168
+ const prop = parentPath.parentPath.node;
169
+ id = t.JSXMemberExpression(
170
+ t.JSXMemberExpression(openingElement.name, t.JSXIdentifier('props')),
171
+ prop.name,
172
+ );
173
+ }
174
+ }
175
+
176
+ let name = getNameFromId(id);
177
+
178
+ if (name == null) {
179
+ if (t.isCallExpression(parent) || t.isNewExpression(parent)) {
180
+ // foo(function () {})
181
+ const argIndex = parent.arguments.indexOf(node);
182
+ if (argIndex !== -1) {
183
+ const calleeName = getNameFromId(parent.callee);
184
+ // var f = Object.freeze(function () {})
185
+ if (CALLEES_TO_SKIP.indexOf(calleeName) !== -1) {
186
+ return getNameForPath(parentPath);
187
+ }
188
+ if (calleeName) {
189
+ return `${calleeName}$argument_${argIndex}`;
190
+ }
191
+ }
192
+ }
193
+ return ANONYMOUS_NAME;
194
+ }
195
+
196
+ if (kind) {
197
+ name = kind + '__' + name;
198
+ }
199
+
200
+ if (propertyPath) {
201
+ if (t.isClassBody(propertyPath.parent)) {
202
+ const className = getNameForPath(propertyPath.parentPath.parentPath);
203
+ if (className !== ANONYMOUS_NAME) {
204
+ const separator = propertyPath.node.static ? '.' : '#';
205
+ name = className + separator + name;
206
+ }
207
+ } else if (t.isObjectExpression(propertyPath.parent)) {
208
+ const objectName = getNameForPath(propertyPath.parentPath);
209
+ if (objectName !== ANONYMOUS_NAME) {
210
+ name = objectName + '.' + name;
211
+ }
212
+ }
213
+ }
214
+
215
+ return name;
216
+ }
217
+
218
+ function isAnyMemberExpression(node: Ast): boolean {
219
+ return t.isMemberExpression(node) || t.isJSXMemberExpression(node);
220
+ }
221
+
222
+ function isAnyIdentifier(node: Ast): boolean {
223
+ return t.isIdentifier(node) || t.isJSXIdentifier(node);
224
+ }
225
+
226
+ function getNameFromId(id: Ast): ?string {
227
+ const parts = getNamePartsFromId(id);
228
+
229
+ if (!parts.length) {
230
+ return null;
231
+ }
232
+ if (parts.length > 5) {
233
+ return (
234
+ parts[0] +
235
+ '.' +
236
+ parts[1] +
237
+ '...' +
238
+ parts[parts.length - 2] +
239
+ '.' +
240
+ parts[parts.length - 1]
241
+ );
242
+ }
243
+ return parts.join('.');
244
+ }
245
+
246
+ function getNamePartsFromId(id: Ast): $ReadOnlyArray<string> {
247
+ if (!id) {
248
+ return [];
249
+ }
250
+
251
+ if (t.isCallExpression(id) || t.isNewExpression(id)) {
252
+ return getNamePartsFromId(id.callee);
253
+ }
254
+
255
+ if (t.isTypeCastExpression(id)) {
256
+ return getNamePartsFromId(id.expression);
257
+ }
258
+
259
+ let name;
260
+
261
+ if (isAnyIdentifier(id)) {
262
+ name = id.name;
263
+ } else if (t.isNullLiteral(id)) {
264
+ name = 'null';
265
+ } else if (t.isRegExpLiteral(id)) {
266
+ name = `_${id.pattern}_${id.flags}`;
267
+ } else if (t.isTemplateLiteral(id)) {
268
+ name = id.quasis.map(quasi => quasi.value.raw).join('');
269
+ } else if (t.isLiteral(id) && id.value != null) {
270
+ name = id.value + '';
271
+ }
272
+
273
+ if (name != null) {
274
+ return [t.toBindingIdentifierName(name)];
275
+ }
276
+
277
+ if (t.isImport(id)) {
278
+ name = 'import';
279
+ }
280
+
281
+ if (name != null) {
282
+ return [name];
283
+ }
284
+
285
+ if (isAnyMemberExpression(id)) {
286
+ if (
287
+ isAnyIdentifier(id.object) &&
288
+ id.object.name === 'Symbol' &&
289
+ (isAnyIdentifier(id.property) || t.isLiteral(id.property))
290
+ ) {
291
+ const propertyName = getNameFromId(id.property);
292
+ if (propertyName) {
293
+ name = '@@' + propertyName;
294
+ }
295
+ } else {
296
+ const propertyName = getNamePartsFromId(id.property);
297
+ if (propertyName.length) {
298
+ const objectName = getNamePartsFromId(id.object);
299
+ if (objectName.length) {
300
+ return [...objectName, ...propertyName];
301
+ } else {
302
+ return propertyName;
303
+ }
304
+ }
305
+ }
306
+ }
307
+
308
+ return name ? [name] : [];
309
+ }
310
+
311
+ const DELIMITER_START_RE = /^[^A-Za-z0-9_$@]+/;
312
+
313
+ /**
314
+ * Strip the given prefix from `name`, if it occurs there, plus any delimiter
315
+ * characters that follow (of which at least one is required). If an empty
316
+ * string would be returned, return the original name instead.
317
+ */
318
+ function removeNamePrefix(name: string, namePrefix: string): string {
319
+ if (!namePrefix.length || !name.startsWith(namePrefix)) {
320
+ return name;
321
+ }
322
+
323
+ const shortenedName = name.substr(namePrefix.length);
324
+ const [delimiterMatch] = shortenedName.match(DELIMITER_START_RE) || [];
325
+ if (delimiterMatch) {
326
+ return shortenedName.substr(delimiterMatch.length) || name;
327
+ }
328
+
329
+ return name;
330
+ }
331
+
332
+ /**
333
+ * Encodes function name mappings as deltas in a Base64 VLQ format inspired by
334
+ * the standard source map format.
335
+ *
336
+ * Mappings on different lines are separated with a single `;` (even if there
337
+ * are multiple intervening lines).
338
+ * Mappings on the same line are separated with `,`.
339
+ *
340
+ * The first mapping of a line has the fields:
341
+ * [column delta, name delta, line delta]
342
+ *
343
+ * where the column delta is relative to the beginning of the line, the name
344
+ * delta is relative to the previously occurring name, and the line delta is
345
+ * relative to the previously occurring line.
346
+ *
347
+ * The 2...nth other mappings of a line have the fields:
348
+ * [column delta, name delta]
349
+ *
350
+ * where both fields are relative to their previous running values. The line
351
+ * delta is omitted since it is always 0 by definition.
352
+ *
353
+ * Lines and columns are both 0-based in the serialised format. In memory,
354
+ * lines are 1-based while columns are 0-based.
355
+ */
356
+ class MappingEncoder {
357
+ _namesMap: Map<string, number>;
358
+ _names: Array<string>;
359
+ _line: RelativeValue;
360
+ _column: RelativeValue;
361
+ _nameIndex: RelativeValue;
362
+ _mappings: B64Builder;
363
+
364
+ constructor() {
365
+ this._namesMap = new Map();
366
+ this._names = [];
367
+ this._line = new RelativeValue(1);
368
+ this._column = new RelativeValue(0);
369
+ this._nameIndex = new RelativeValue(0);
370
+ this._mappings = new B64Builder();
371
+ }
372
+
373
+ getResult(): FBSourceFunctionMap {
374
+ return {names: this._names, mappings: this._mappings.toString()};
375
+ }
376
+
377
+ push({name, start}: RangeMapping) {
378
+ let nameIndex = this._namesMap.get(name);
379
+ if (typeof nameIndex !== 'number') {
380
+ nameIndex = this._names.length;
381
+ this._names[nameIndex] = name;
382
+ this._namesMap.set(name, nameIndex);
383
+ }
384
+ const lineDelta = this._line.next(start.line);
385
+ const firstOfLine = this._mappings.pos === 0 || lineDelta > 0;
386
+ if (lineDelta > 0) {
387
+ // The next entry will have the line offset, so emit just one semicolon.
388
+ this._mappings.markLines(1);
389
+ this._column.reset(0);
390
+ }
391
+ this._mappings.startSegment(this._column.next(start.column));
392
+ this._mappings.append(this._nameIndex.next(nameIndex));
393
+ if (firstOfLine) {
394
+ this._mappings.append(lineDelta);
395
+ }
396
+ }
397
+ }
398
+
399
+ class RelativeValue {
400
+ _value: number;
401
+
402
+ constructor(value: number = 0) {
403
+ this.reset(value);
404
+ }
405
+
406
+ next(absoluteValue: number): number {
407
+ const delta = absoluteValue - this._value;
408
+ this._value = absoluteValue;
409
+ return delta;
410
+ }
411
+
412
+ reset(value: number = 0) {
413
+ this._value = value;
414
+ }
415
+ }
416
+
417
+ function positionGreater(x, y) {
418
+ return x.line > y.line || (x.line === y.line && x.column > y.column);
419
+ }
420
+
421
+ module.exports = {generateFunctionMap, generateFunctionMappingsArray};
package/src/source-map.js CHANGED
@@ -13,6 +13,13 @@ const Generator = require("./Generator");
13
13
 
14
14
  const SourceMap = require("source-map");
15
15
 
16
+ const _require = require("./BundleBuilder"),
17
+ createIndexMap = _require.createIndexMap,
18
+ BundleBuilder = _require.BundleBuilder;
19
+
20
+ const _require2 = require("./generateFunctionMap"),
21
+ generateFunctionMap = _require2.generateFunctionMap;
22
+
16
23
  /**
17
24
  * Creates a source map from modules with "raw mappings", i.e. an array of
18
25
  * tuples with either 2, 4, or 5 elements:
@@ -125,16 +132,10 @@ function countLines(string) {
125
132
  return string.split("\n").length;
126
133
  }
127
134
 
128
- function createIndexMap(file, sections) {
129
- return {
130
- version: 3,
131
- file,
132
- sections
133
- };
134
- }
135
-
136
135
  module.exports = {
136
+ BundleBuilder,
137
137
  createIndexMap,
138
+ generateFunctionMap,
138
139
  fromRawMappings,
139
140
  toBabelSegments,
140
141
  toSegmentTuple
@@ -13,6 +13,9 @@
13
13
  const Generator = require('./Generator');
14
14
  const SourceMap = require('source-map');
15
15
 
16
+ const {createIndexMap, BundleBuilder} = require('./BundleBuilder');
17
+ const {generateFunctionMap} = require('./generateFunctionMap');
18
+
16
19
  import type {BabelSourceMap} from '@babel/core';
17
20
  import type {BabelSourceMapSegment} from '@babel/generator';
18
21
 
@@ -31,7 +34,7 @@ type FBExtensions = {
31
34
  x_facebook_sources?: FBSourcesArray,
32
35
  };
33
36
 
34
- export type FBSourcesArray = $ReadOnlyArray<FBSourceMetadata>;
37
+ export type FBSourcesArray = $ReadOnlyArray<?FBSourceMetadata>;
35
38
  export type FBSourceMetadata = [?FBSourceFunctionMap];
36
39
  export type FBSourceFunctionMap = {|
37
40
  +names: $ReadOnlyArray<string>,
@@ -176,19 +179,10 @@ function countLines(string) {
176
179
  return string.split('\n').length;
177
180
  }
178
181
 
179
- function createIndexMap(
180
- file: string,
181
- sections: Array<IndexMapSection>,
182
- ): IndexMap {
183
- return {
184
- version: 3,
185
- file,
186
- sections,
187
- };
188
- }
189
-
190
182
  module.exports = {
183
+ BundleBuilder,
191
184
  createIndexMap,
185
+ generateFunctionMap,
192
186
  fromRawMappings,
193
187
  toBabelSegments,
194
188
  toSegmentTuple,