first commit

This commit is contained in:
2026-03-10 16:18:05 +00:00
commit 11f9c069b5
31635 changed files with 3187747 additions and 0 deletions

5
node_modules/metro-source-map/README.md generated vendored Normal file
View File

@@ -0,0 +1,5 @@
# Metro
🚇 The source map generator for [Metro](https://metrobundler.dev/).
(TODO)

40
node_modules/metro-source-map/package.json generated vendored Normal file
View File

@@ -0,0 +1,40 @@
{
"name": "metro-source-map",
"version": "0.83.3",
"description": "🚇 Source map generator for Metro.",
"main": "src/source-map.js",
"exports": {
".": "./src/source-map.js",
"./package.json": "./package.json",
"./private/*": "./src/*.js"
},
"repository": {
"type": "git",
"url": "git@github.com:facebook/metro.git"
},
"scripts": {
"prepare-release": "test -d build && rm -rf src.real && mv src src.real && mv build src",
"cleanup-release": "test ! -e build && mv src build && mv src.real src"
},
"dependencies": {
"@babel/traverse": "^7.25.3",
"@babel/traverse--for-generate-function-map": "npm:@babel/traverse@^7.25.3",
"@babel/types": "^7.25.2",
"flow-enums-runtime": "^0.0.6",
"invariant": "^2.2.4",
"metro-symbolicate": "0.83.3",
"nullthrows": "^1.1.1",
"ob1": "0.83.3",
"source-map": "^0.5.6",
"vlq": "^1.0.0"
},
"license": "MIT",
"devDependencies": {
"@babel/core": "^7.25.2",
"@babel/parser": "^7.25.3",
"terser": "^5.15.0"
},
"engines": {
"node": ">=20.19.4"
}
}

47
node_modules/metro-source-map/src/B64Builder.d.ts generated vendored Normal file
View File

@@ -0,0 +1,47 @@
/**
* 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.
*
* @format
* @oncall react_native
*/
/**
* Efficient builder for base64 VLQ mappings strings.
*
* This class uses a buffer that is preallocated with one megabyte and is
* reallocated dynamically as needed, doubling its size.
*
* Encoding never creates any complex value types (strings, objects), and only
* writes character values to the buffer.
*
* For details about source map terminology and specification, check
* https://docs.google.com/document/d/1U1RGAehQwRypUTovF1KRlpiOFze0b-_2gc6fAH0KY0k/edit
*/
declare class B64Builder {
buffer: Buffer;
pos: number;
hasSegment: boolean;
constructor();
/**
* Adds `n` markers for generated lines to the mappings.
*/
markLines(n: number): this;
/**
* Starts a segment at the specified column offset in the current line.
*/
startSegment(column: number): this;
/**
* Appends a single number to the mappings.
*/
append(value: number): this;
/**
* Returns the string representation of the mappings.
*/
toString(): string;
_writeByte(byte: number): void;
_realloc(): void;
}
export default B64Builder;

65
node_modules/metro-source-map/src/B64Builder.js generated vendored Normal file
View File

@@ -0,0 +1,65 @@
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true,
});
exports.default = void 0;
var _encode = _interopRequireDefault(require("./encode"));
function _interopRequireDefault(e) {
return e && e.__esModule ? e : { default: e };
}
const MAX_SEGMENT_LENGTH = 7;
const ONE_MEG = 1024 * 1024;
const COMMA = 0x2c;
const SEMICOLON = 0x3b;
class B64Builder {
constructor() {
this.buffer = Buffer.alloc(ONE_MEG);
this.pos = 0;
this.hasSegment = false;
}
markLines(n) {
if (n < 1) {
return this;
}
this.hasSegment = false;
if (this.pos + n >= this.buffer.length) {
this._realloc();
}
while (n--) {
this.buffer[this.pos++] = SEMICOLON;
}
return this;
}
startSegment(column) {
if (this.hasSegment) {
this._writeByte(COMMA);
} else {
this.hasSegment = true;
}
this.append(column);
return this;
}
append(value) {
if (this.pos + MAX_SEGMENT_LENGTH >= this.buffer.length) {
this._realloc();
}
this.pos = (0, _encode.default)(value, this.buffer, this.pos);
return this;
}
toString() {
return this.buffer.toString("ascii", 0, this.pos);
}
_writeByte(byte) {
if (this.pos === this.buffer.length) {
this._realloc();
}
this.buffer[this.pos++] = byte;
}
_realloc() {
const { buffer } = this;
this.buffer = Buffer.alloc(buffer.length * 2);
buffer.copy(this.buffer);
}
}
exports.default = B64Builder;

104
node_modules/metro-source-map/src/B64Builder.js.flow generated vendored Normal file
View File

@@ -0,0 +1,104 @@
/**
* 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
* @format
* @oncall react_native
*/
import encode from './encode';
const MAX_SEGMENT_LENGTH = 7;
const ONE_MEG = 1024 * 1024;
const COMMA = 0x2c;
const SEMICOLON = 0x3b;
/**
* Efficient builder for base64 VLQ mappings strings.
*
* This class uses a buffer that is preallocated with one megabyte and is
* reallocated dynamically as needed, doubling its size.
*
* Encoding never creates any complex value types (strings, objects), and only
* writes character values to the buffer.
*
* For details about source map terminology and specification, check
* https://docs.google.com/document/d/1U1RGAehQwRypUTovF1KRlpiOFze0b-_2gc6fAH0KY0k/edit
*/
export default class B64Builder {
buffer: Buffer;
pos: number;
hasSegment: boolean;
constructor() {
this.buffer = Buffer.alloc(ONE_MEG);
this.pos = 0;
this.hasSegment = false;
}
/**
* Adds `n` markers for generated lines to the mappings.
*/
markLines(n: number): this {
if (n < 1) {
return this;
}
this.hasSegment = false;
if (this.pos + n >= this.buffer.length) {
this._realloc();
}
while (n--) {
this.buffer[this.pos++] = SEMICOLON;
}
return this;
}
/**
* Starts a segment at the specified column offset in the current line.
*/
startSegment(column: number): this {
if (this.hasSegment) {
this._writeByte(COMMA);
} else {
this.hasSegment = true;
}
this.append(column);
return this;
}
/**
* Appends a single number to the mappings.
*/
append(value: number): this {
if (this.pos + MAX_SEGMENT_LENGTH >= this.buffer.length) {
this._realloc();
}
this.pos = encode(value, this.buffer, this.pos);
return this;
}
/**
* Returns the string representation of the mappings.
*/
toString(): string {
return this.buffer.toString('ascii', 0, this.pos);
}
_writeByte(byte: number) {
if (this.pos === this.buffer.length) {
this._realloc();
}
this.buffer[this.pos++] = byte;
}
_realloc() {
const {buffer} = this;
this.buffer = Buffer.alloc(buffer.length * 2);
buffer.copy(this.buffer);
}
}

43
node_modules/metro-source-map/src/BundleBuilder.d.ts generated vendored Normal file
View File

@@ -0,0 +1,43 @@
/**
* 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.
*
* @format
* @oncall react_native
*/
import type {IndexMap, IndexMapSection, MixedSourceMap} from './source-map';
/**
* Builds a source-mapped bundle by concatenating strings and their
* corresponding source maps (if any).
*
* Usage:
*
* const builder = new BundleBuilder('bundle.js');
* builder
* .append('foo\n', fooMap)
* .append('bar\n')
* // ...
* const code = builder.getCode();
* const map = builder.getMap();
*/
export declare class BundleBuilder {
_file: string;
_sections: Array<IndexMapSection>;
_line: number;
_column: number;
_code: string;
_afterMappedContent: boolean;
constructor(file: string);
_pushMapSection(map: MixedSourceMap): void;
_endMappedContent(): void;
append(code: string, map: null | undefined | MixedSourceMap): this;
getMap(): MixedSourceMap;
getCode(): string;
}
export declare function createIndexMap(
file: string,
sections: Array<IndexMapSection>,
): IndexMap;

89
node_modules/metro-source-map/src/BundleBuilder.js generated vendored Normal file
View File

@@ -0,0 +1,89 @@
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true,
});
exports.BundleBuilder = void 0;
exports.createIndexMap = createIndexMap;
const EMPTY_MAP = {
version: 3,
sources: [],
names: [],
mappings: "A",
};
class BundleBuilder {
constructor(file) {
this._file = file;
this._sections = [];
this._line = 0;
this._column = 0;
this._code = "";
this._afterMappedContent = false;
}
_pushMapSection(map) {
this._sections.push({
map,
offset: {
column: this._column,
line: this._line,
},
});
}
_endMappedContent() {
if (this._afterMappedContent) {
this._pushMapSection(EMPTY_MAP);
this._afterMappedContent = false;
}
}
append(code, map) {
if (!code.length) {
return this;
}
const { lineBreaks, lastLineColumns } = measureString(code);
if (map) {
this._pushMapSection(map);
this._afterMappedContent = true;
} else {
this._endMappedContent();
}
this._afterMappedContent = !!map;
this._line = this._line + lineBreaks;
if (lineBreaks > 0) {
this._column = lastLineColumns;
} else {
this._column = this._column + lastLineColumns;
}
this._code = this._code + code;
return this;
}
getMap() {
this._endMappedContent();
return createIndexMap(this._file, this._sections);
}
getCode() {
return this._code;
}
}
exports.BundleBuilder = BundleBuilder;
const reLineBreak = /\r\n|\r|\n/g;
function measureString(str) {
let lineBreaks = 0;
let match;
let lastLineStart = 0;
while ((match = reLineBreak.exec(str))) {
++lineBreaks;
lastLineStart = match.index + match[0].length;
}
const lastLineColumns = str.length - lastLineStart;
return {
lineBreaks,
lastLineColumns,
};
}
function createIndexMap(file, sections) {
return {
version: 3,
file,
sections,
};
}

124
node_modules/metro-source-map/src/BundleBuilder.js.flow generated vendored Normal file
View File

@@ -0,0 +1,124 @@
/**
* 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 {IndexMap, IndexMapSection, MixedSourceMap} from './source-map';
const EMPTY_MAP = {
version: 3,
sources: ([]: Array<string>),
names: ([]: Array<string>),
mappings: 'A',
};
/**
* Builds a source-mapped bundle by concatenating strings and their
* corresponding source maps (if any).
*
* Usage:
*
* const builder = new BundleBuilder('bundle.js');
* builder
* .append('foo\n', fooMap)
* .append('bar\n')
* // ...
* const code = builder.getCode();
* const map = builder.getMap();
*/
export class BundleBuilder {
_file: string;
_sections: Array<IndexMapSection>;
_line: number;
_column: number;
_code: string;
_afterMappedContent: boolean;
constructor(file: string) {
this._file = file;
this._sections = [];
this._line = 0;
this._column = 0;
this._code = '';
this._afterMappedContent = false;
}
_pushMapSection(map: MixedSourceMap) {
this._sections.push({
map,
offset: {column: this._column, line: this._line},
});
}
_endMappedContent() {
if (this._afterMappedContent) {
this._pushMapSection(EMPTY_MAP);
this._afterMappedContent = false;
}
}
append(code: string, map: ?MixedSourceMap): this {
if (!code.length) {
return this;
}
const {lineBreaks, lastLineColumns} = measureString(code);
if (map) {
this._pushMapSection(map);
this._afterMappedContent = true;
} else {
this._endMappedContent();
}
this._afterMappedContent = !!map;
this._line = this._line + lineBreaks;
if (lineBreaks > 0) {
this._column = lastLineColumns;
} else {
this._column = this._column + lastLineColumns;
}
this._code = this._code + code;
return this;
}
getMap(): MixedSourceMap {
this._endMappedContent();
return createIndexMap(this._file, this._sections);
}
getCode(): string {
return this._code;
}
}
const reLineBreak = /\r\n|\r|\n/g;
function measureString(str: string): {
lineBreaks: number,
lastLineColumns: number,
} {
let lineBreaks = 0;
let match;
let lastLineStart = 0;
while ((match = reLineBreak.exec(str))) {
++lineBreaks;
lastLineStart = match.index + match[0].length;
}
const lastLineColumns = str.length - lastLineStart;
return {lineBreaks, lastLineColumns};
}
export function createIndexMap(
file: string,
sections: Array<IndexMapSection>,
): IndexMap {
return {
version: 3,
file,
sections,
};
}

View File

@@ -0,0 +1,37 @@
/**
* 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.
*
* @format
* @oncall react_native
*/
import type {
GeneratedPositionLookup,
IConsumer,
IterationOrder,
Mapping,
SourcePosition,
} from './types';
declare class AbstractConsumer implements IConsumer {
_sourceMap: {readonly file?: string};
constructor(sourceMap: {readonly file?: string});
originalPositionFor(
generatedPosition: GeneratedPositionLookup,
): SourcePosition;
generatedMappings(): Iterable<Mapping>;
eachMapping(
callback: (mapping: Mapping) => unknown,
context?: unknown,
order?: IterationOrder,
): void;
get file(): null | undefined | string;
sourceContentFor(
source: string,
nullOnMissing: true,
): null | undefined | string;
}
export default AbstractConsumer;

View File

@@ -0,0 +1,38 @@
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true,
});
exports.default = void 0;
var _constants = require("./constants");
var _invariant = _interopRequireDefault(require("invariant"));
function _interopRequireDefault(e) {
return e && e.__esModule ? e : { default: e };
}
class AbstractConsumer {
constructor(sourceMap) {
this._sourceMap = sourceMap;
}
originalPositionFor(generatedPosition) {
(0, _invariant.default)(false, "Not implemented");
}
generatedMappings() {
(0, _invariant.default)(false, "Not implemented");
}
eachMapping(callback, context = null, order = _constants.GENERATED_ORDER) {
(0, _invariant.default)(
order === _constants.GENERATED_ORDER,
`Iteration order not implemented: ${(0, _constants.iterationOrderToString)(order)}`,
);
for (const mapping of this.generatedMappings()) {
callback.call(context, mapping);
}
}
get file() {
return this._sourceMap.file;
}
sourceContentFor(source, nullOnMissing) {
(0, _invariant.default)(false, "Not implemented");
}
}
exports.default = AbstractConsumer;

View File

@@ -0,0 +1,63 @@
/**
* 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 {
GeneratedPositionLookup,
IConsumer,
IterationOrder,
Mapping,
SourcePosition,
} from './types';
import {GENERATED_ORDER, iterationOrderToString} from './constants';
import invariant from 'invariant';
// Implementation details shared between MappingsConsumer and SectionsConsumer
export default class AbstractConsumer implements IConsumer {
_sourceMap: {+file?: string, ...};
constructor(sourceMap: {+file?: string, ...}) {
this._sourceMap = sourceMap;
}
originalPositionFor(
generatedPosition: GeneratedPositionLookup,
): SourcePosition {
invariant(false, 'Not implemented');
}
generatedMappings(): Iterable<Mapping> {
invariant(false, 'Not implemented');
}
eachMapping(
callback: (mapping: Mapping) => mixed,
context?: mixed = null,
order?: IterationOrder = GENERATED_ORDER,
): void {
invariant(
order === GENERATED_ORDER,
`Iteration order not implemented: ${iterationOrderToString(order)}`,
);
for (const mapping of this.generatedMappings()) {
callback.call(context, mapping);
}
}
// flowlint-next-line unsafe-getters-setters:off
get file(): ?string {
return this._sourceMap.file;
}
sourceContentFor(source: string, nullOnMissing: true): ?string {
invariant(false, 'Not implemented');
}
}

View File

@@ -0,0 +1,47 @@
/**
* 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.
*
* @format
* @oncall react_native
*/
import type {MixedSourceMap} from '../source-map';
import type {LookupBias} from './constants.js';
import type {
GeneratedPositionLookup,
IConsumer,
IterationOrder,
Mapping,
SourcePosition,
} from './types';
/**
* A source map consumer that supports both "basic" and "indexed" source maps.
* Uses `MappingsConsumer` and `SectionsConsumer` under the hood (via
* `createConsumer`).
*/
declare class DelegatingConsumer implements IConsumer {
static readonly GENERATED_ORDER: IterationOrder;
static readonly ORIGINAL_ORDER: IterationOrder;
static readonly GREATEST_LOWER_BOUND: LookupBias;
static readonly LEAST_UPPER_BOUND: LookupBias;
_rootConsumer: IConsumer;
constructor(sourceMap: MixedSourceMap);
originalPositionFor(
generatedPosition: GeneratedPositionLookup,
): SourcePosition;
generatedMappings(): Iterable<Mapping>;
eachMapping(
callback: (mapping: Mapping) => unknown,
context?: unknown,
order?: IterationOrder,
): void;
get file(): null | undefined | string;
sourceContentFor(
source: string,
nullOnMissing: true,
): null | undefined | string;
}
export default DelegatingConsumer;

View File

@@ -0,0 +1,37 @@
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true,
});
exports.default = void 0;
var _constants = require("./constants");
var _createConsumer = _interopRequireDefault(require("./createConsumer"));
function _interopRequireDefault(e) {
return e && e.__esModule ? e : { default: e };
}
class DelegatingConsumer {
static GENERATED_ORDER = _constants.GENERATED_ORDER;
static ORIGINAL_ORDER = _constants.ORIGINAL_ORDER;
static GREATEST_LOWER_BOUND = _constants.GREATEST_LOWER_BOUND;
static LEAST_UPPER_BOUND = _constants.LEAST_UPPER_BOUND;
constructor(sourceMap) {
this._rootConsumer = (0, _createConsumer.default)(sourceMap);
return this._rootConsumer;
}
originalPositionFor(generatedPosition) {
return this._rootConsumer.originalPositionFor(generatedPosition);
}
generatedMappings() {
return this._rootConsumer.generatedMappings();
}
eachMapping(callback, context, order) {
return this._rootConsumer.eachMapping(callback, context, order);
}
get file() {
return this._rootConsumer.file;
}
sourceContentFor(source, nullOnMissing) {
return this._rootConsumer.sourceContentFor(source, nullOnMissing);
}
}
exports.default = DelegatingConsumer;

View File

@@ -0,0 +1,75 @@
/**
* 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 {MixedSourceMap} from '../source-map';
import type {LookupBias} from './constants.js';
import type {
GeneratedPositionLookup,
IConsumer,
IterationOrder,
Mapping,
SourcePosition,
} from './types';
import {
GENERATED_ORDER,
GREATEST_LOWER_BOUND,
LEAST_UPPER_BOUND,
ORIGINAL_ORDER,
} from './constants';
import createConsumer from './createConsumer';
/**
* A source map consumer that supports both "basic" and "indexed" source maps.
* Uses `MappingsConsumer` and `SectionsConsumer` under the hood (via
* `createConsumer`).
*/
export default class DelegatingConsumer implements IConsumer {
static +GENERATED_ORDER: IterationOrder = GENERATED_ORDER;
static +ORIGINAL_ORDER: IterationOrder = ORIGINAL_ORDER;
static +GREATEST_LOWER_BOUND: LookupBias = GREATEST_LOWER_BOUND;
static +LEAST_UPPER_BOUND: LookupBias = LEAST_UPPER_BOUND;
_rootConsumer: IConsumer;
// $FlowFixMe[incompatible-type]
constructor(sourceMap: MixedSourceMap): IConsumer {
this._rootConsumer = createConsumer(sourceMap);
return this._rootConsumer;
}
originalPositionFor(
generatedPosition: GeneratedPositionLookup,
): SourcePosition {
return this._rootConsumer.originalPositionFor(generatedPosition);
}
generatedMappings(): Iterable<Mapping> {
return this._rootConsumer.generatedMappings();
}
eachMapping(
callback: (mapping: Mapping) => mixed,
context?: mixed,
order?: IterationOrder,
): void {
return this._rootConsumer.eachMapping(callback, context, order);
}
// flowlint-next-line unsafe-getters-setters:off
get file(): ?string {
return this._rootConsumer.file;
}
sourceContentFor(source: string, nullOnMissing: true): ?string {
return this._rootConsumer.sourceContentFor(source, nullOnMissing);
}
}

View File

@@ -0,0 +1,43 @@
/**
* 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.
*
* @format
* @oncall react_native
*/
import type {BasicSourceMap} from '../source-map';
import type {
GeneratedPositionLookup,
IConsumer,
Mapping,
SourcePosition,
} from './types';
import type {Number0} from 'ob1';
import AbstractConsumer from './AbstractConsumer';
/**
* A source map consumer that supports "basic" source maps (that have a
* `mappings` field and no sections).
*/
declare class MappingsConsumer extends AbstractConsumer implements IConsumer {
_sourceMap: BasicSourceMap;
_decodedMappings: null | undefined | ReadonlyArray<Mapping>;
_normalizedSources: null | undefined | ReadonlyArray<string>;
constructor(sourceMap: BasicSourceMap);
originalPositionFor(
generatedPosition: GeneratedPositionLookup,
): SourcePosition;
_decodeMappings(): Generator<Mapping, void, void>;
_normalizeAndCacheSources(): ReadonlyArray<string>;
_decodeAndCacheMappings(): ReadonlyArray<Mapping>;
generatedMappings(): Iterable<Mapping>;
_indexOfSource(source: string): null | undefined | Number0;
sourceContentFor(
source: string,
nullOnMissing: true,
): null | undefined | string;
}
export default MappingsConsumer;

View File

@@ -0,0 +1,194 @@
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true,
});
exports.default = void 0;
var _AbstractConsumer = _interopRequireDefault(require("./AbstractConsumer"));
var _constants = require("./constants");
var _normalizeSourcePath = _interopRequireDefault(
require("./normalizeSourcePath"),
);
var _search = require("./search");
var _invariant = _interopRequireDefault(require("invariant"));
var _ob = require("ob1");
var _vlq = require("vlq");
function _interopRequireDefault(e) {
return e && e.__esModule ? e : { default: e };
}
class MappingsConsumer extends _AbstractConsumer.default {
constructor(sourceMap) {
super(sourceMap);
this._sourceMap = sourceMap;
this._decodedMappings = null;
this._normalizedSources = null;
}
originalPositionFor(generatedPosition) {
const { line, column } = generatedPosition;
if (line == null || column == null) {
return {
..._constants.EMPTY_POSITION,
};
}
if (generatedPosition.bias != null) {
(0, _invariant.default)(
generatedPosition.bias === _constants.GREATEST_LOWER_BOUND,
`Unimplemented lookup bias: ${(0, _constants.lookupBiasToString)(generatedPosition.bias)}`,
);
}
const mappings = this._decodeAndCacheMappings();
const index = (0, _search.greatestLowerBound)(
mappings,
{
line,
column,
},
(position, mapping) => {
if (position.line === mapping.generatedLine) {
return (0, _ob.get0)(
(0, _ob.sub)(position.column, mapping.generatedColumn),
);
}
return (0, _ob.get0)(
(0, _ob.sub)(position.line, mapping.generatedLine),
);
},
);
if (
index != null &&
mappings[index].generatedLine === generatedPosition.line
) {
const mapping = mappings[index];
return {
source: mapping.source,
name: mapping.name,
line: mapping.originalLine,
column: mapping.originalColumn,
};
}
return {
..._constants.EMPTY_POSITION,
};
}
*_decodeMappings() {
let generatedLine = _constants.FIRST_LINE;
let generatedColumn = _constants.FIRST_COLUMN;
let originalLine = _constants.FIRST_LINE;
let originalColumn = _constants.FIRST_COLUMN;
let nameIndex = (0, _ob.add0)(0);
let sourceIndex = (0, _ob.add0)(0);
const normalizedSources = this._normalizeAndCacheSources();
const { mappings: mappingsRaw, names } = this._sourceMap;
let next;
const vlqCache = new Map();
for (let i = 0; i < mappingsRaw.length; i = next) {
switch (mappingsRaw[i]) {
case ";":
generatedLine = (0, _ob.inc)(generatedLine);
generatedColumn = _constants.FIRST_COLUMN;
case ",":
next = i + 1;
continue;
}
findNext: for (next = i + 1; next < mappingsRaw.length; ++next) {
switch (mappingsRaw[next]) {
case ";":
case ",":
break findNext;
}
}
const mappingRaw = mappingsRaw.slice(i, next);
let decodedVlqValues;
if (vlqCache.has(mappingRaw)) {
decodedVlqValues = vlqCache.get(mappingRaw);
} else {
decodedVlqValues = (0, _vlq.decode)(mappingRaw);
vlqCache.set(mappingRaw, decodedVlqValues);
}
(0, _invariant.default)(
Array.isArray(decodedVlqValues),
"Decoding VLQ tuple failed",
);
const [
generatedColumnDelta,
sourceIndexDelta,
originalLineDelta,
originalColumnDelta,
nameIndexDelta,
] = decodedVlqValues;
(0, _vlq.decode)(mappingRaw);
(0, _invariant.default)(
generatedColumnDelta != null,
"Invalid generated column delta",
);
generatedColumn = (0, _ob.add)(generatedColumn, generatedColumnDelta);
const mapping = {
generatedLine,
generatedColumn,
source: null,
name: null,
originalLine: null,
originalColumn: null,
};
if (sourceIndexDelta != null) {
sourceIndex = (0, _ob.add)(sourceIndex, sourceIndexDelta);
mapping.source = normalizedSources[(0, _ob.get0)(sourceIndex)];
(0, _invariant.default)(
originalLineDelta != null,
"Invalid original line delta",
);
(0, _invariant.default)(
originalColumnDelta != null,
"Invalid original column delta",
);
originalLine = (0, _ob.add)(originalLine, originalLineDelta);
originalColumn = (0, _ob.add)(originalColumn, originalColumnDelta);
mapping.originalLine = originalLine;
mapping.originalColumn = originalColumn;
if (nameIndexDelta != null) {
nameIndex = (0, _ob.add)(nameIndex, nameIndexDelta);
mapping.name = names[(0, _ob.get0)(nameIndex)];
}
}
yield mapping;
}
}
_normalizeAndCacheSources() {
if (!this._normalizedSources) {
this._normalizedSources = this._sourceMap.sources.map((source) =>
(0, _normalizeSourcePath.default)(source, this._sourceMap),
);
}
return this._normalizedSources;
}
_decodeAndCacheMappings() {
if (!this._decodedMappings) {
this._decodedMappings = [...this._decodeMappings()];
}
return this._decodedMappings;
}
generatedMappings() {
return this._decodeAndCacheMappings();
}
_indexOfSource(source) {
const idx = this._normalizeAndCacheSources().indexOf(
(0, _normalizeSourcePath.default)(source, this._sourceMap),
);
if (idx === -1) {
return null;
}
return (0, _ob.add0)(idx);
}
sourceContentFor(source, nullOnMissing) {
const { sourcesContent } = this._sourceMap;
if (!sourcesContent) {
return null;
}
const idx = this._indexOfSource(source);
if (idx == null) {
return null;
}
return sourcesContent[(0, _ob.get0)(idx)] ?? null;
}
}
exports.default = MappingsConsumer;

View File

@@ -0,0 +1,219 @@
/**
* 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
* @format
* @oncall react_native
*/
import type {BasicSourceMap} from '../source-map';
import type {
GeneratedPositionLookup,
IConsumer,
Mapping,
SourcePosition,
} from './types';
import type {Number0} from 'ob1';
import AbstractConsumer from './AbstractConsumer';
import {
EMPTY_POSITION,
FIRST_COLUMN,
FIRST_LINE,
GREATEST_LOWER_BOUND,
lookupBiasToString,
} from './constants';
import normalizeSourcePath from './normalizeSourcePath';
import {greatestLowerBound} from './search';
import invariant from 'invariant';
import {add, add0, get0, inc, sub} from 'ob1';
import {decode as decodeVlq} from 'vlq';
/**
* A source map consumer that supports "basic" source maps (that have a
* `mappings` field and no sections).
*/
export default class MappingsConsumer
extends AbstractConsumer
implements IConsumer
{
_sourceMap: BasicSourceMap;
_decodedMappings: ?$ReadOnlyArray<Mapping>;
_normalizedSources: ?$ReadOnlyArray<string>;
constructor(sourceMap: BasicSourceMap) {
super(sourceMap);
this._sourceMap = sourceMap;
this._decodedMappings = null;
this._normalizedSources = null;
}
originalPositionFor(
generatedPosition: GeneratedPositionLookup,
): SourcePosition {
const {line, column} = generatedPosition;
if (line == null || column == null) {
return {...EMPTY_POSITION};
}
if (generatedPosition.bias != null) {
invariant(
generatedPosition.bias === GREATEST_LOWER_BOUND,
`Unimplemented lookup bias: ${lookupBiasToString(
// $FlowFixMe[incompatible-type]
generatedPosition.bias,
)}`,
);
}
const mappings = this._decodeAndCacheMappings();
const index = greatestLowerBound(
mappings,
{line, column},
(position, mapping) => {
if (position.line === mapping.generatedLine) {
return get0(sub(position.column, mapping.generatedColumn));
}
return get0(sub(position.line, mapping.generatedLine));
},
);
if (
index != null &&
mappings[index].generatedLine === generatedPosition.line
) {
const mapping = mappings[index];
return {
source: mapping.source,
name: mapping.name,
line: mapping.originalLine,
column: mapping.originalColumn,
};
}
return {...EMPTY_POSITION};
}
*_decodeMappings(): Generator<Mapping, void, void> {
let generatedLine = FIRST_LINE;
let generatedColumn = FIRST_COLUMN;
let originalLine = FIRST_LINE;
let originalColumn = FIRST_COLUMN;
let nameIndex = add0(0);
let sourceIndex = add0(0);
const normalizedSources = this._normalizeAndCacheSources();
const {mappings: mappingsRaw, names} = this._sourceMap;
let next;
const vlqCache = new Map<string, any>();
for (let i = 0; i < mappingsRaw.length; i = next) {
switch (mappingsRaw[i]) {
case ';':
generatedLine = inc(generatedLine);
generatedColumn = FIRST_COLUMN;
/* falls through */
case ',':
next = i + 1;
continue;
}
findNext: for (next = i + 1; next < mappingsRaw.length; ++next) {
switch (mappingsRaw[next]) {
case ';':
/* falls through */
case ',':
break findNext;
}
}
const mappingRaw = mappingsRaw.slice(i, next);
let decodedVlqValues;
if (vlqCache.has(mappingRaw)) {
decodedVlqValues = vlqCache.get(mappingRaw);
} else {
decodedVlqValues = decodeVlq(mappingRaw);
vlqCache.set(mappingRaw, decodedVlqValues);
}
invariant(Array.isArray(decodedVlqValues), 'Decoding VLQ tuple failed');
const [
generatedColumnDelta,
sourceIndexDelta,
originalLineDelta,
originalColumnDelta,
nameIndexDelta,
] = decodedVlqValues;
decodeVlq(mappingRaw);
invariant(generatedColumnDelta != null, 'Invalid generated column delta');
generatedColumn = add(generatedColumn, generatedColumnDelta);
const mapping: {...Mapping, ...} = {
generatedLine,
generatedColumn,
source: null,
name: null,
originalLine: null,
originalColumn: null,
};
if (sourceIndexDelta != null) {
sourceIndex = add(sourceIndex, sourceIndexDelta);
mapping.source = normalizedSources[get0(sourceIndex)];
invariant(originalLineDelta != null, 'Invalid original line delta');
invariant(originalColumnDelta != null, 'Invalid original column delta');
originalLine = add(originalLine, originalLineDelta);
originalColumn = add(originalColumn, originalColumnDelta);
mapping.originalLine = originalLine;
mapping.originalColumn = originalColumn;
if (nameIndexDelta != null) {
nameIndex = add(nameIndex, nameIndexDelta);
mapping.name = names[get0(nameIndex)];
}
}
yield mapping;
}
}
_normalizeAndCacheSources(): $ReadOnlyArray<string> {
if (!this._normalizedSources) {
this._normalizedSources = this._sourceMap.sources.map(source =>
normalizeSourcePath(source, this._sourceMap),
);
}
return this._normalizedSources;
}
_decodeAndCacheMappings(): $ReadOnlyArray<Mapping> {
if (!this._decodedMappings) {
this._decodedMappings = [...this._decodeMappings()];
}
return this._decodedMappings;
}
generatedMappings(): Iterable<Mapping> {
return this._decodeAndCacheMappings();
}
_indexOfSource(source: string): ?Number0 {
const idx = this._normalizeAndCacheSources().indexOf(
normalizeSourcePath(source, this._sourceMap),
);
if (idx === -1) {
return null;
}
return add0(idx);
}
sourceContentFor(source: string, nullOnMissing: true): ?string {
const {sourcesContent} = this._sourceMap;
if (!sourcesContent) {
return null;
}
const idx = this._indexOfSource(source);
if (idx == null) {
return null;
}
return sourcesContent[get0(idx)] ?? null;
}
}

View File

@@ -0,0 +1,40 @@
/**
* 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.
*
* @format
* @oncall react_native
*/
import type {IndexMap} from '../source-map';
import type {
GeneratedOffset,
GeneratedPositionLookup,
IConsumer,
Mapping,
SourcePosition,
} from './types';
import AbstractConsumer from './AbstractConsumer';
/**
* A source map consumer that supports "indexed" source maps (that have a
* `sections` field and no top-level mappings).
*/
declare class SectionsConsumer extends AbstractConsumer implements IConsumer {
_consumers: ReadonlyArray<[GeneratedOffset, IConsumer]>;
constructor(sourceMap: IndexMap);
originalPositionFor(
generatedPosition: GeneratedPositionLookup,
): SourcePosition;
generatedMappings(): Iterable<Mapping>;
_consumerForPosition(
generatedPosition: GeneratedPositionLookup,
): null | undefined | [GeneratedOffset, IConsumer];
sourceContentFor(
source: string,
nullOnMissing: true,
): null | undefined | string;
}
export default SectionsConsumer;

View File

@@ -0,0 +1,105 @@
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true,
});
exports.default = void 0;
var _AbstractConsumer = _interopRequireDefault(require("./AbstractConsumer"));
var _constants = require("./constants");
var _createConsumer = _interopRequireDefault(require("./createConsumer"));
var _positionMath = require("./positionMath");
var _search = require("./search");
var _ob = require("ob1");
function _interopRequireDefault(e) {
return e && e.__esModule ? e : { default: e };
}
class SectionsConsumer extends _AbstractConsumer.default {
constructor(sourceMap) {
super(sourceMap);
this._consumers = sourceMap.sections.map((section, index) => {
const generatedOffset = {
lines: (0, _ob.add0)(section.offset.line),
columns: (0, _ob.add0)(section.offset.column),
};
const consumer = (0, _createConsumer.default)(section.map);
return [generatedOffset, consumer];
});
}
originalPositionFor(generatedPosition) {
const [generatedOffset, consumer] =
this._consumerForPosition(generatedPosition) || [];
if (!consumer) {
return {
..._constants.EMPTY_POSITION,
};
}
return consumer.originalPositionFor(
(0, _positionMath.subtractOffsetFromPosition)(
generatedPosition,
generatedOffset,
),
);
}
*generatedMappings() {
for (const [generatedOffset, consumer] of this._consumers) {
let first = true;
for (const mapping of consumer.generatedMappings()) {
if (
first &&
((0, _ob.get1)(mapping.generatedLine) > 1 ||
(0, _ob.get0)(mapping.generatedColumn) > 0)
) {
yield {
generatedLine: _constants.FIRST_LINE,
generatedColumn: _constants.FIRST_COLUMN,
source: null,
name: null,
originalLine: null,
originalColumn: null,
};
}
first = false;
yield {
...mapping,
generatedLine: (0, _ob.add)(
mapping.generatedLine,
generatedOffset.lines,
),
generatedColumn: (0, _ob.add)(
mapping.generatedColumn,
generatedOffset.columns,
),
};
}
}
}
_consumerForPosition(generatedPosition) {
const { line, column } = generatedPosition;
if (line == null || column == null) {
return null;
}
const index = (0, _search.greatestLowerBound)(
this._consumers,
generatedPosition,
(position, [offset]) => {
const line0 = (0, _ob.sub1)(line);
const column0 = column;
if (line0 === offset.lines) {
return (0, _ob.get0)((0, _ob.sub)(column0, offset.columns));
}
return (0, _ob.get0)((0, _ob.sub)(line0, offset.lines));
},
);
return index != null ? this._consumers[index] : null;
}
sourceContentFor(source, nullOnMissing) {
for (const [_, consumer] of this._consumers) {
const content = consumer.sourceContentFor(source, nullOnMissing);
if (content != null) {
return content;
}
}
return null;
}
}
exports.default = SectionsConsumer;

View File

@@ -0,0 +1,124 @@
/**
* 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 {IndexMap} from '../source-map';
import type {
GeneratedOffset,
GeneratedPositionLookup,
IConsumer,
Mapping,
SourcePosition,
} from './types';
import AbstractConsumer from './AbstractConsumer';
import {EMPTY_POSITION, FIRST_COLUMN, FIRST_LINE} from './constants';
import createConsumer from './createConsumer';
import {subtractOffsetFromPosition} from './positionMath';
import {greatestLowerBound} from './search';
import {add, add0, get0, get1, sub, sub1} from 'ob1';
/**
* A source map consumer that supports "indexed" source maps (that have a
* `sections` field and no top-level mappings).
*/
export default class SectionsConsumer
extends AbstractConsumer
implements IConsumer
{
_consumers: $ReadOnlyArray<[GeneratedOffset, IConsumer]>;
constructor(sourceMap: IndexMap) {
super(sourceMap);
this._consumers = sourceMap.sections.map((section, index) => {
const generatedOffset = {
lines: add0(section.offset.line),
columns: add0(section.offset.column),
};
const consumer = createConsumer(section.map);
return [generatedOffset, consumer];
});
}
originalPositionFor(
generatedPosition: GeneratedPositionLookup,
): SourcePosition {
const [generatedOffset, consumer] =
this._consumerForPosition(generatedPosition) || [];
if (!consumer) {
return {...EMPTY_POSITION};
}
return consumer.originalPositionFor(
subtractOffsetFromPosition(generatedPosition, generatedOffset),
);
}
*generatedMappings(): Iterable<Mapping> {
for (const [generatedOffset, consumer] of this._consumers) {
let first = true;
for (const mapping of consumer.generatedMappings()) {
if (
first &&
(get1(mapping.generatedLine) > 1 || get0(mapping.generatedColumn) > 0)
) {
yield {
generatedLine: FIRST_LINE,
generatedColumn: FIRST_COLUMN,
source: null,
name: null,
originalLine: null,
originalColumn: null,
};
}
first = false;
yield {
...mapping,
generatedLine: add(mapping.generatedLine, generatedOffset.lines),
generatedColumn: add(
mapping.generatedColumn,
generatedOffset.columns,
),
};
}
}
}
_consumerForPosition(
generatedPosition: GeneratedPositionLookup,
): ?[GeneratedOffset, IConsumer] {
const {line, column} = generatedPosition;
if (line == null || column == null) {
return null;
}
const index = greatestLowerBound(
this._consumers,
generatedPosition,
(position, [offset]) => {
const line0 = sub1(line);
const column0 = column;
if (line0 === offset.lines) {
return get0(sub(column0, offset.columns));
}
return get0(sub(line0, offset.lines));
},
);
return index != null ? this._consumers[index] : null;
}
sourceContentFor(source: string, nullOnMissing: true): ?string {
for (const [_, consumer] of this._consumers) {
const content = consumer.sourceContentFor(source, nullOnMissing);
if (content != null) {
return content;
}
}
return null;
}
}

View File

@@ -0,0 +1,39 @@
/**
* 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.
*
* @format
* @oncall react_native
*/
import type {Number0, Number1} from 'ob1';
declare const FIRST_COLUMN: Number0;
declare const FIRST_LINE: Number1;
export declare type IterationOrder = symbol & {__IterationOrder__: string};
declare const GENERATED_ORDER: IterationOrder;
declare const ORIGINAL_ORDER: IterationOrder;
export declare type LookupBias = symbol & {__LookupBias__: string};
declare const GREATEST_LOWER_BOUND: LookupBias;
declare const LEAST_UPPER_BOUND: LookupBias;
declare const EMPTY_POSITION: Readonly<{
source: null;
name: null;
line: null;
column: null;
}>;
declare function iterationOrderToString(x: IterationOrder): string;
declare function lookupBiasToString(x: LookupBias): string;
export {
FIRST_COLUMN,
FIRST_LINE,
GENERATED_ORDER,
ORIGINAL_ORDER,
GREATEST_LOWER_BOUND,
LEAST_UPPER_BOUND,
EMPTY_POSITION,
iterationOrderToString,
lookupBiasToString,
};

View File

@@ -0,0 +1,35 @@
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true,
});
exports.ORIGINAL_ORDER =
exports.LEAST_UPPER_BOUND =
exports.GREATEST_LOWER_BOUND =
exports.GENERATED_ORDER =
exports.FIRST_LINE =
exports.FIRST_COLUMN =
exports.EMPTY_POSITION =
void 0;
exports.iterationOrderToString = iterationOrderToString;
exports.lookupBiasToString = lookupBiasToString;
var _ob = require("ob1");
const FIRST_COLUMN = (exports.FIRST_COLUMN = (0, _ob.add0)(0));
const FIRST_LINE = (exports.FIRST_LINE = (0, _ob.add1)(0));
const GENERATED_ORDER = (exports.GENERATED_ORDER = "GENERATED_ORDER");
const ORIGINAL_ORDER = (exports.ORIGINAL_ORDER = "ORIGINAL_ORDER");
const GREATEST_LOWER_BOUND = (exports.GREATEST_LOWER_BOUND =
"GREATEST_LOWER_BOUND");
const LEAST_UPPER_BOUND = (exports.LEAST_UPPER_BOUND = "LEAST_UPPER_BOUND");
const EMPTY_POSITION = (exports.EMPTY_POSITION = Object.freeze({
source: null,
name: null,
line: null,
column: null,
}));
function iterationOrderToString(x) {
return x;
}
function lookupBiasToString(x) {
return x;
}

View File

@@ -0,0 +1,57 @@
/**
* 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 {Number0, Number1} from 'ob1';
import {add0, add1} from 'ob1';
const FIRST_COLUMN: Number0 = add0(0);
const FIRST_LINE: Number1 = add1(0);
export opaque type IterationOrder = 'GENERATED_ORDER' | 'ORIGINAL_ORDER';
const GENERATED_ORDER: IterationOrder = 'GENERATED_ORDER';
const ORIGINAL_ORDER: IterationOrder = 'ORIGINAL_ORDER';
export opaque type LookupBias = 'GREATEST_LOWER_BOUND' | 'LEAST_UPPER_BOUND';
const GREATEST_LOWER_BOUND: LookupBias = 'GREATEST_LOWER_BOUND';
const LEAST_UPPER_BOUND: LookupBias = 'LEAST_UPPER_BOUND';
const EMPTY_POSITION: $ReadOnly<{
source: null,
name: null,
line: null,
column: null,
}> = Object.freeze({
source: null,
name: null,
line: null,
column: null,
});
function iterationOrderToString(x: IterationOrder): string {
return x;
}
function lookupBiasToString(x: LookupBias): string {
return x;
}
export {
FIRST_COLUMN,
FIRST_LINE,
GENERATED_ORDER,
ORIGINAL_ORDER,
GREATEST_LOWER_BOUND,
LEAST_UPPER_BOUND,
EMPTY_POSITION,
iterationOrderToString,
lookupBiasToString,
};

View File

@@ -0,0 +1,15 @@
/**
* 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.
*
* @format
* @oncall react_native
*/
import type {MixedSourceMap} from '../source-map';
import type {IConsumer} from './types';
declare function createConsumer(sourceMap: MixedSourceMap): IConsumer;
export default createConsumer;

View File

@@ -0,0 +1,22 @@
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true,
});
exports.default = createConsumer;
var _MappingsConsumer = _interopRequireDefault(require("./MappingsConsumer"));
var _SectionsConsumer = _interopRequireDefault(require("./SectionsConsumer"));
var _invariant = _interopRequireDefault(require("invariant"));
function _interopRequireDefault(e) {
return e && e.__esModule ? e : { default: e };
}
function createConsumer(sourceMap) {
(0, _invariant.default)(
sourceMap.version === "3" || sourceMap.version === 3,
`Unrecognized source map format version: ${sourceMap.version}`,
);
if (sourceMap.mappings === undefined) {
return new _SectionsConsumer.default(sourceMap);
}
return new _MappingsConsumer.default(sourceMap);
}

View File

@@ -0,0 +1,30 @@
/**
* 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 {MixedSourceMap} from '../source-map';
import type {IConsumer} from './types';
import MappingsConsumer from './MappingsConsumer';
import SectionsConsumer from './SectionsConsumer';
import invariant from 'invariant';
export default function createConsumer(sourceMap: MixedSourceMap): IConsumer {
invariant(
(sourceMap.version: mixed) === '3' || sourceMap.version === 3,
`Unrecognized source map format version: ${sourceMap.version}`,
);
// eslint-disable-next-line lint/strictly-null
if (sourceMap.mappings === undefined) {
return new SectionsConsumer(sourceMap);
}
return new MappingsConsumer(sourceMap);
}

16
node_modules/metro-source-map/src/Consumer/index.d.ts generated vendored Normal file
View File

@@ -0,0 +1,16 @@
/**
* 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.
*
* @format
* @oncall react_native
*/
import DelegatingConsumer from './DelegatingConsumer';
declare const $$EXPORT_DEFAULT_DECLARATION$$: typeof DelegatingConsumer;
declare type $$EXPORT_DEFAULT_DECLARATION$$ =
typeof $$EXPORT_DEFAULT_DECLARATION$$;
export default $$EXPORT_DEFAULT_DECLARATION$$;

13
node_modules/metro-source-map/src/Consumer/index.js generated vendored Normal file
View File

@@ -0,0 +1,13 @@
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true,
});
exports.default = void 0;
var _DelegatingConsumer = _interopRequireDefault(
require("./DelegatingConsumer"),
);
function _interopRequireDefault(e) {
return e && e.__esModule ? e : { default: e };
}
var _default = (exports.default = _DelegatingConsumer.default);

View File

@@ -0,0 +1,15 @@
/**
* 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
*/
// Implements an API-compatible subset of source-map's `SourceMapConsumer`.
import DelegatingConsumer from './DelegatingConsumer';
export default DelegatingConsumer;

View File

@@ -0,0 +1,15 @@
/**
* 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.
*
* @format
* @oncall react_native
*/
declare function normalizeSourcePath(
sourceInput: string,
map: {readonly sourceRoot?: null | undefined | string},
): string;
export default normalizeSourcePath;

View File

@@ -0,0 +1,23 @@
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true,
});
exports.default = normalizeSourcePath;
var _util = _interopRequireDefault(require("source-map/lib/util"));
function _interopRequireDefault(e) {
return e && e.__esModule ? e : { default: e };
}
function normalizeSourcePath(sourceInput, map) {
const { sourceRoot } = map;
let source = sourceInput;
source = String(source);
source = _util.default.normalize(source);
source =
sourceRoot != null &&
_util.default.isAbsolute(sourceRoot) &&
_util.default.isAbsolute(source)
? _util.default.relative(sourceRoot, source)
: source;
return source;
}

View File

@@ -0,0 +1,38 @@
/**
* 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
*/
// flowlint-next-line untyped-import:off
import util from 'source-map/lib/util';
// Extracted from source-map@0.5.6's SourceMapConsumer
export default function normalizeSourcePath(
sourceInput: string,
map: {+sourceRoot?: ?string, ...},
): string {
const {sourceRoot} = map;
let source = sourceInput;
source = String(source);
// Some source maps produce relative source paths like "./foo.js" instead of
// "foo.js". Normalize these first so that future comparisons will succeed.
// See bugzil.la/1090768.
source = util.normalize(source);
// Always ensure that absolute sources are internally stored relative to
// the source root, if the source root is absolute. Not doing this would
// be particularly problematic when the source root is a prefix of the
// source (valid, but why??). See github issue #199 and bugzil.la/1188982.
source =
sourceRoot != null && util.isAbsolute(sourceRoot) && util.isAbsolute(source)
? util.relative(sourceRoot, source)
: source;
return source;
}

View File

@@ -0,0 +1,25 @@
/**
* 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.
*
* @format
* @oncall react_native
*/
import type {GeneratedOffset} from './types';
import type {Number0, Number1} from 'ob1';
export declare function shiftPositionByOffset<
T extends {
readonly line: null | undefined | Number1;
readonly column: null | undefined | Number0;
},
>(pos: T, offset: GeneratedOffset): T;
export declare function subtractOffsetFromPosition<
T extends {
readonly line: null | undefined | Number1;
readonly column: null | undefined | Number0;
},
>(pos: T, offset: GeneratedOffset): T;

View File

@@ -0,0 +1,28 @@
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true,
});
exports.shiftPositionByOffset = shiftPositionByOffset;
exports.subtractOffsetFromPosition = subtractOffsetFromPosition;
var _ob = require("ob1");
function shiftPositionByOffset(pos, offset) {
return {
...pos,
line: pos.line != null ? (0, _ob.add)(pos.line, offset.lines) : null,
column:
pos.column != null ? (0, _ob.add)(pos.column, offset.columns) : null,
};
}
function subtractOffsetFromPosition(pos, offset) {
if (pos.line === (0, _ob.add1)(offset.lines)) {
return shiftPositionByOffset(pos, {
lines: (0, _ob.neg)(offset.lines),
columns: (0, _ob.neg)(offset.columns),
});
}
return shiftPositionByOffset(pos, {
lines: (0, _ob.neg)(offset.lines),
columns: (0, _ob.add0)(0),
});
}

View File

@@ -0,0 +1,48 @@
/**
* 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 {GeneratedOffset} from './types';
import type {Number0, Number1} from 'ob1';
import {add, add0, add1, neg} from 'ob1';
export function shiftPositionByOffset<
T: {
+line: ?Number1,
+column: ?Number0,
...
},
>(pos: T, offset: GeneratedOffset): T {
return {
...pos,
line: pos.line != null ? add(pos.line, offset.lines) : null,
column: pos.column != null ? add(pos.column, offset.columns) : null,
};
}
export function subtractOffsetFromPosition<
T: {
+line: ?Number1,
+column: ?Number0,
...
},
>(pos: T, offset: GeneratedOffset): T {
if (pos.line === add1(offset.lines)) {
return shiftPositionByOffset(pos, {
lines: neg(offset.lines),
columns: neg(offset.columns),
});
}
return shiftPositionByOffset(pos, {
lines: neg(offset.lines),
columns: add0(0),
});
}

15
node_modules/metro-source-map/src/Consumer/search.d.ts generated vendored Normal file
View File

@@ -0,0 +1,15 @@
/**
* 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.
*
* @format
* @oncall react_native
*/
export declare function greatestLowerBound<T, U>(
elements: ReadonlyArray<T>,
target: U,
comparator: ($$PARAM_0$$: U, $$PARAM_1$$: T) => number,
): null | undefined | number;

24
node_modules/metro-source-map/src/Consumer/search.js generated vendored Normal file
View File

@@ -0,0 +1,24 @@
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true,
});
exports.greatestLowerBound = greatestLowerBound;
function greatestLowerBound(elements, target, comparator) {
let first = 0;
let it = 0;
let count = elements.length;
let step;
while (count > 0) {
it = first;
step = Math.floor(count / 2);
it = it + step;
if (comparator(target, elements[it]) >= 0) {
first = ++it;
count = count - (step + 1);
} else {
count = step;
}
}
return first ? first - 1 : null;
}

View File

@@ -0,0 +1,33 @@
/**
* 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
*/
export function greatestLowerBound<T, U>(
elements: $ReadOnlyArray<T>,
target: U,
comparator: (U, T) => number,
): ?number {
let first = 0;
let it = 0;
let count = elements.length;
let step;
while (count > 0) {
it = first;
step = Math.floor(count / 2);
it = it + step;
if (comparator(target, elements[it]) >= 0) {
first = ++it;
count = count - (step + 1);
} else {
count = step;
}
}
return first ? first - 1 : null;
}

57
node_modules/metro-source-map/src/Consumer/types.d.ts generated vendored Normal file
View File

@@ -0,0 +1,57 @@
/**
* 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.
*
* @format
* @oncall react_native
*/
import type {IterationOrder, LookupBias} from './constants';
import type {Number0, Number1} from 'ob1';
export type {IterationOrder, LookupBias};
export type GeneratedOffset = {
readonly lines: Number0;
readonly columns: Number0;
};
export type SourcePosition = {
source: null | undefined | string;
line: null | undefined | Number1;
column: null | undefined | Number0;
name: null | undefined | string;
};
export type GeneratedPosition = {
readonly line: Number1;
readonly column: Number0;
};
export type GeneratedPositionLookup = {
readonly line: null | undefined | Number1;
readonly column: null | undefined | Number0;
readonly bias?: LookupBias;
};
export type Mapping = Readonly<{
source: null | undefined | string;
generatedLine: Number1;
generatedColumn: Number0;
originalLine: null | undefined | Number1;
originalColumn: null | undefined | Number0;
name: null | undefined | string;
}>;
export interface IConsumer {
originalPositionFor(
generatedPosition: GeneratedPositionLookup,
): SourcePosition;
generatedMappings(): Iterable<Mapping>;
eachMapping(
callback: (mapping: Mapping) => unknown,
context?: unknown,
order?: IterationOrder,
): void;
get file(): null | undefined | string;
sourceContentFor(
source: string,
nullOnMissing: true,
): null | undefined | string;
}

1
node_modules/metro-source-map/src/Consumer/types.js generated vendored Normal file
View File

@@ -0,0 +1 @@
"use strict";

View File

@@ -0,0 +1,67 @@
/**
* 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 {IterationOrder, LookupBias} from './constants';
import type {Number0, Number1} from 'ob1';
export type {IterationOrder, LookupBias};
export type GeneratedOffset = {+lines: Number0, +columns: Number0};
export type SourcePosition = {
source: ?string,
line: ?Number1,
column: ?Number0,
name: ?string,
...
};
export type GeneratedPosition = {
+line: Number1,
+column: Number0,
...
};
export type GeneratedPositionLookup = {
+line: ?Number1,
+column: ?Number0,
+bias?: LookupBias,
...
};
export type Mapping = $ReadOnly<{
source: ?string,
generatedLine: Number1,
generatedColumn: Number0,
originalLine: ?Number1,
originalColumn: ?Number0,
name: ?string,
...
}>;
export interface IConsumer {
originalPositionFor(
generatedPosition: GeneratedPositionLookup,
): SourcePosition;
generatedMappings(): Iterable<Mapping>;
eachMapping(
callback: (mapping: Mapping) => mixed,
context?: mixed,
order?: IterationOrder,
): void;
// flowlint-next-line unsafe-getters-setters:off
get file(): ?string;
sourceContentFor(
source: string,
/* nullOnMissing = false behaves inconsistently upstream, so we don't support it */
nullOnMissing: true,
): ?string;
}

107
node_modules/metro-source-map/src/Generator.d.ts generated vendored Normal file
View File

@@ -0,0 +1,107 @@
/**
* 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.
*
* @format
* @oncall react_native
*/
import type {
BasicSourceMap,
FBSourceFunctionMap,
FBSourceMetadata,
} from './source-map';
import B64Builder from './B64Builder';
type FileFlags = Readonly<{addToIgnoreList?: boolean}>;
/**
* Generates a source map from raw mappings.
*
* Raw mappings are a set of 2, 4, or five elements:
*
* - line and column number in the generated source
* - line and column number in the original source
* - symbol name in the original source
*
* Mappings have to be passed in the order appearance in the generated source.
*/
declare class Generator {
builder: B64Builder;
last: {
generatedColumn: number;
generatedLine: number;
name: number;
source: number;
sourceColumn: number;
sourceLine: number;
};
names: IndexedSet;
source: number;
sources: Array<string>;
sourcesContent: Array<null | undefined | string>;
x_facebook_sources: Array<null | undefined | FBSourceMetadata>;
x_google_ignoreList: Array<number>;
constructor();
/**
* Mark the beginning of a new source file.
*/
startFile(
file: string,
code: string,
functionMap: null | undefined | FBSourceFunctionMap,
flags?: FileFlags,
): void;
/**
* Mark the end of the current source file
*/
endFile(): void;
/**
* Adds a mapping for generated code without a corresponding source location.
*/
addSimpleMapping(generatedLine: number, generatedColumn: number): void;
/**
* Adds a mapping for generated code with a corresponding source location.
*/
addSourceMapping(
generatedLine: number,
generatedColumn: number,
sourceLine: number,
sourceColumn: number,
): void;
/**
* Adds a mapping for code with a corresponding source location + symbol name.
*/
addNamedSourceMapping(
generatedLine: number,
generatedColumn: number,
sourceLine: number,
sourceColumn: number,
name: string,
): void;
/**
* Return the source map as object.
*/
toMap(file?: string, options?: {excludeSource?: boolean}): BasicSourceMap;
/**
* Return the source map as string.
*
* This is ~2.5x faster than calling `JSON.stringify(generator.toMap())`
*/
toString(file?: string, options?: {excludeSource?: boolean}): string;
/**
* Determine whether we need to write the `x_facebook_sources` field.
* If the metadata is all `null`s, we can omit the field entirely.
*/
hasSourcesMetadata(): boolean;
}
export default Generator;
declare class IndexedSet {
map: Map<string, number>;
nextIndex: number;
constructor();
indexFor(x: string): number;
items(): Array<string>;
}

178
node_modules/metro-source-map/src/Generator.js generated vendored Normal file
View File

@@ -0,0 +1,178 @@
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true,
});
exports.default = void 0;
var _B64Builder = _interopRequireDefault(require("./B64Builder"));
function _interopRequireDefault(e) {
return e && e.__esModule ? e : { default: e };
}
class Generator {
constructor() {
this.builder = new _B64Builder.default();
this.last = {
generatedColumn: 0,
generatedLine: 1,
name: 0,
source: 0,
sourceColumn: 0,
sourceLine: 1,
};
this.names = new IndexedSet();
this.source = -1;
this.sources = [];
this.sourcesContent = [];
this.x_facebook_sources = [];
this.x_google_ignoreList = [];
}
startFile(file, code, functionMap, flags) {
const { addToIgnoreList = false } = flags ?? {};
const sourceIndex = this.sources.push(file) - 1;
this.source = sourceIndex;
this.sourcesContent.push(code);
this.x_facebook_sources.push(functionMap ? [functionMap] : null);
if (addToIgnoreList) {
this.x_google_ignoreList.push(sourceIndex);
}
}
endFile() {
this.source = -1;
}
addSimpleMapping(generatedLine, generatedColumn) {
const last = this.last;
if (
this.source === -1 ||
(generatedLine === last.generatedLine &&
generatedColumn < last.generatedColumn) ||
generatedLine < last.generatedLine
) {
const msg =
this.source === -1
? "Cannot add mapping before starting a file with `addFile()`"
: "Mapping is for a position preceding an earlier mapping";
throw new Error(msg);
}
if (generatedLine > last.generatedLine) {
this.builder.markLines(generatedLine - last.generatedLine);
last.generatedLine = generatedLine;
last.generatedColumn = 0;
}
this.builder.startSegment(generatedColumn - last.generatedColumn);
last.generatedColumn = generatedColumn;
}
addSourceMapping(generatedLine, generatedColumn, sourceLine, sourceColumn) {
this.addSimpleMapping(generatedLine, generatedColumn);
const last = this.last;
this.builder
.append(this.source - last.source)
.append(sourceLine - last.sourceLine)
.append(sourceColumn - last.sourceColumn);
last.source = this.source;
last.sourceColumn = sourceColumn;
last.sourceLine = sourceLine;
}
addNamedSourceMapping(
generatedLine,
generatedColumn,
sourceLine,
sourceColumn,
name,
) {
this.addSourceMapping(
generatedLine,
generatedColumn,
sourceLine,
sourceColumn,
);
const last = this.last;
const nameIndex = this.names.indexFor(name);
this.builder.append(nameIndex - last.name);
last.name = nameIndex;
}
toMap(file, options) {
const content =
options && options.excludeSource === true
? {}
: {
sourcesContent: this.sourcesContent.slice(),
};
const sourcesMetadata = this.hasSourcesMetadata()
? {
x_facebook_sources: JSON.parse(
JSON.stringify(this.x_facebook_sources),
),
}
: {};
const ignoreList = this.x_google_ignoreList.length
? {
x_google_ignoreList: this.x_google_ignoreList,
}
: {};
return {
version: 3,
file,
sources: this.sources.slice(),
...content,
...sourcesMetadata,
...ignoreList,
names: this.names.items(),
mappings: this.builder.toString(),
};
}
toString(file, options) {
let content;
if (options && options.excludeSource === true) {
content = "";
} else {
content = `"sourcesContent":${JSON.stringify(this.sourcesContent)},`;
}
let sourcesMetadata;
if (this.hasSourcesMetadata()) {
sourcesMetadata = `"x_facebook_sources":${JSON.stringify(this.x_facebook_sources)},`;
} else {
sourcesMetadata = "";
}
let ignoreList;
if (this.x_google_ignoreList.length) {
ignoreList = `"x_google_ignoreList":${JSON.stringify(this.x_google_ignoreList)},`;
} else {
ignoreList = "";
}
return (
"{" +
'"version":3,' +
(file != null ? `"file":${JSON.stringify(file)},` : "") +
`"sources":${JSON.stringify(this.sources)},` +
content +
sourcesMetadata +
ignoreList +
`"names":${JSON.stringify(this.names.items())},` +
`"mappings":"${this.builder.toString()}"` +
"}"
);
}
hasSourcesMetadata() {
return this.x_facebook_sources.some(
(metadata) => metadata != null && metadata.some((value) => value != null),
);
}
}
exports.default = Generator;
class IndexedSet {
constructor() {
this.map = new Map();
this.nextIndex = 0;
}
indexFor(x) {
let index = this.map.get(x);
if (index == null) {
index = this.nextIndex++;
this.map.set(x, index);
}
return index;
}
items() {
return Array.from(this.map.keys());
}
}

291
node_modules/metro-source-map/src/Generator.js.flow generated vendored Normal file
View File

@@ -0,0 +1,291 @@
/**
* 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 {
BasicSourceMap,
FBSourceFunctionMap,
FBSourceMetadata,
} from './source-map';
import B64Builder from './B64Builder';
type FileFlags = $ReadOnly<{
addToIgnoreList?: boolean,
}>;
/**
* Generates a source map from raw mappings.
*
* Raw mappings are a set of 2, 4, or five elements:
*
* - line and column number in the generated source
* - line and column number in the original source
* - symbol name in the original source
*
* Mappings have to be passed in the order appearance in the generated source.
*/
export default class Generator {
builder: B64Builder;
last: {
generatedColumn: number,
generatedLine: number,
name: number,
source: number,
sourceColumn: number,
sourceLine: number,
};
names: IndexedSet;
source: number;
sources: Array<string>;
sourcesContent: Array<?string>;
x_facebook_sources: Array<?FBSourceMetadata>;
// https://developer.chrome.com/blog/devtools-better-angular-debugging/#the-x_google_ignorelist-source-map-extension
x_google_ignoreList: Array<number>;
constructor() {
this.builder = new B64Builder();
this.last = {
generatedColumn: 0,
generatedLine: 1, // lines are passed in 1-indexed
name: 0,
source: 0,
sourceColumn: 0,
sourceLine: 1,
};
this.names = new IndexedSet();
this.source = -1;
this.sources = [];
this.sourcesContent = [];
this.x_facebook_sources = [];
this.x_google_ignoreList = [];
}
/**
* Mark the beginning of a new source file.
*/
startFile(
file: string,
code: string,
functionMap: ?FBSourceFunctionMap,
flags?: FileFlags,
) {
const {addToIgnoreList = false} = flags ?? {};
const sourceIndex = this.sources.push(file) - 1;
this.source = sourceIndex;
this.sourcesContent.push(code);
this.x_facebook_sources.push(functionMap ? [functionMap] : null);
if (addToIgnoreList) {
this.x_google_ignoreList.push(sourceIndex);
}
}
/**
* Mark the end of the current source file
*/
endFile() {
this.source = -1;
}
/**
* Adds a mapping for generated code without a corresponding source location.
*/
addSimpleMapping(generatedLine: number, generatedColumn: number): void {
const last = this.last;
if (
this.source === -1 ||
(generatedLine === last.generatedLine &&
generatedColumn < last.generatedColumn) ||
generatedLine < last.generatedLine
) {
const msg =
this.source === -1
? 'Cannot add mapping before starting a file with `addFile()`'
: 'Mapping is for a position preceding an earlier mapping';
throw new Error(msg);
}
if (generatedLine > last.generatedLine) {
this.builder.markLines(generatedLine - last.generatedLine);
last.generatedLine = generatedLine;
last.generatedColumn = 0;
}
this.builder.startSegment(generatedColumn - last.generatedColumn);
last.generatedColumn = generatedColumn;
}
/**
* Adds a mapping for generated code with a corresponding source location.
*/
addSourceMapping(
generatedLine: number,
generatedColumn: number,
sourceLine: number,
sourceColumn: number,
): void {
this.addSimpleMapping(generatedLine, generatedColumn);
const last = this.last;
this.builder
.append(this.source - last.source)
.append(sourceLine - last.sourceLine)
.append(sourceColumn - last.sourceColumn);
last.source = this.source;
last.sourceColumn = sourceColumn;
last.sourceLine = sourceLine;
}
/**
* Adds a mapping for code with a corresponding source location + symbol name.
*/
addNamedSourceMapping(
generatedLine: number,
generatedColumn: number,
sourceLine: number,
sourceColumn: number,
name: string,
): void {
this.addSourceMapping(
generatedLine,
generatedColumn,
sourceLine,
sourceColumn,
);
const last = this.last;
const nameIndex = this.names.indexFor(name);
this.builder.append(nameIndex - last.name);
last.name = nameIndex;
}
/**
* Return the source map as object.
*/
toMap(
file?: string,
options?: {excludeSource?: boolean, ...},
): BasicSourceMap {
const content: {
sourcesContent?: Array<?string>,
} =
options && options.excludeSource === true
? {}
: {sourcesContent: this.sourcesContent.slice()};
const sourcesMetadata: {
x_facebook_sources?: Array<FBSourceMetadata>,
} = this.hasSourcesMetadata()
? {
x_facebook_sources: JSON.parse(
JSON.stringify(this.x_facebook_sources),
),
}
: {};
const ignoreList: {
x_google_ignoreList?: Array<number>,
} = this.x_google_ignoreList.length
? {
x_google_ignoreList: this.x_google_ignoreList,
}
: {};
return ({
version: 3,
file,
sources: this.sources.slice(),
...content,
...sourcesMetadata,
...ignoreList,
names: this.names.items(),
mappings: this.builder.toString(),
}: BasicSourceMap);
}
/**
* Return the source map as string.
*
* This is ~2.5x faster than calling `JSON.stringify(generator.toMap())`
*/
toString(file?: string, options?: {excludeSource?: boolean, ...}): string {
let content;
if (options && options.excludeSource === true) {
content = '';
} else {
content = `"sourcesContent":${JSON.stringify(this.sourcesContent)},`;
}
let sourcesMetadata;
if (this.hasSourcesMetadata()) {
sourcesMetadata = `"x_facebook_sources":${JSON.stringify(
this.x_facebook_sources,
)},`;
} else {
sourcesMetadata = '';
}
let ignoreList;
if (this.x_google_ignoreList.length) {
ignoreList = `"x_google_ignoreList":${JSON.stringify(
this.x_google_ignoreList,
)},`;
} else {
ignoreList = '';
}
return (
'{' +
'"version":3,' +
(file != null ? `"file":${JSON.stringify(file)},` : '') +
`"sources":${JSON.stringify(this.sources)},` +
content +
sourcesMetadata +
ignoreList +
`"names":${JSON.stringify(this.names.items())},` +
`"mappings":"${this.builder.toString()}"` +
'}'
);
}
/**
* Determine whether we need to write the `x_facebook_sources` field.
* If the metadata is all `null`s, we can omit the field entirely.
*/
hasSourcesMetadata(): boolean {
return this.x_facebook_sources.some(
metadata => metadata != null && metadata.some(value => value != null),
);
}
}
class IndexedSet {
map: Map<string, number>;
nextIndex: number;
constructor() {
this.map = new Map();
this.nextIndex = 0;
}
indexFor(x: string): number {
let index = this.map.get(x);
if (index == null) {
index = this.nextIndex++;
this.map.set(x, index);
}
return index;
}
items(): Array<string> {
return Array.from(this.map.keys());
}
}

View File

@@ -0,0 +1,16 @@
/**
* 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.
*
* @format
* @oncall react_native
*/
import type {MixedSourceMap} from './source-map';
declare function composeSourceMaps(
maps: ReadonlyArray<MixedSourceMap>,
): MixedSourceMap;
export default composeSourceMaps;

108
node_modules/metro-source-map/src/composeSourceMaps.js generated vendored Normal file
View File

@@ -0,0 +1,108 @@
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true,
});
exports.default = composeSourceMaps;
var _Consumer = _interopRequireDefault(require("./Consumer"));
var _sourceMap = require("source-map");
function _interopRequireDefault(e) {
return e && e.__esModule ? e : { default: e };
}
_Consumer.default;
function composeSourceMaps(maps) {
const SourceMetadataMapConsumer =
require("metro-symbolicate/private/SourceMetadataMapConsumer").default;
const GoogleIgnoreListConsumer =
require("metro-symbolicate/private/GoogleIgnoreListConsumer").default;
if (maps.length < 1) {
throw new Error("composeSourceMaps: Expected at least one map");
}
const firstMap = maps[0];
const consumers = maps
.map(function (map) {
return new _Consumer.default(map);
})
.reverse();
const generator = new _sourceMap.SourceMapGenerator({
file: consumers[0].file,
});
consumers[0].eachMapping((mapping) => {
const original = findOriginalPosition(
consumers,
mapping.generatedLine,
mapping.generatedColumn,
);
generator.addMapping({
generated: {
line: mapping.generatedLine,
column: mapping.generatedColumn,
},
original:
original.line != null
? {
line: original.line,
column: original.column,
}
: null,
source: original.source,
name: original.name,
});
});
const composedMap = generator.toJSON();
composedMap.sourcesContent = composedMap.sources.map((source) =>
consumers[consumers.length - 1].sourceContentFor(source, true),
);
if (composedMap.sourcesContent.every((content) => content == null)) {
delete composedMap.sourcesContent;
}
const metadataConsumer = new SourceMetadataMapConsumer(firstMap);
composedMap.x_facebook_sources = metadataConsumer.toArray(
composedMap.sources,
);
const function_offsets = maps[maps.length - 1].x_hermes_function_offsets;
if (function_offsets) {
composedMap.x_hermes_function_offsets = function_offsets;
}
const ignoreListConsumer = new GoogleIgnoreListConsumer(firstMap);
const x_google_ignoreList = ignoreListConsumer.toArray(composedMap.sources);
if (x_google_ignoreList.length) {
composedMap.x_google_ignoreList = x_google_ignoreList;
}
return composedMap;
}
function findOriginalPosition(consumers, generatedLine, generatedColumn) {
let currentLine = generatedLine;
let currentColumn = generatedColumn;
let original = {
line: null,
column: null,
source: null,
name: null,
};
for (const consumer of consumers) {
if (currentLine == null || currentColumn == null) {
return {
line: null,
column: null,
source: null,
name: null,
};
}
original = consumer.originalPositionFor({
line: currentLine,
column: currentColumn,
});
currentLine = original.line;
currentColumn = original.column;
if (currentLine == null) {
return {
line: null,
column: null,
source: null,
name: null,
};
}
}
return original;
}

View File

@@ -0,0 +1,138 @@
/**
* 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
* @format
* @oncall react_native
*/
import type {SourcePosition} from './Consumer/types';
import type {IConsumer, MixedSourceMap} from './source-map';
import type {Number0, Number1} from 'ob1';
import Consumer from './Consumer';
import {SourceMapGenerator} from 'source-map';
// TODO(t67648443): Bypass the `sort-requires` rule for this file because of a dependency cycle.
Consumer;
// Originally based on https://github.com/jakobwesthoff/source-map-merger
export default function composeSourceMaps(
maps: $ReadOnlyArray<MixedSourceMap>,
): MixedSourceMap {
// NOTE: require() here to break dependency cycle
const SourceMetadataMapConsumer =
// eslint-disable-next-line import/no-commonjs
require('metro-symbolicate/private/SourceMetadataMapConsumer').default;
const GoogleIgnoreListConsumer =
// eslint-disable-next-line import/no-commonjs
require('metro-symbolicate/private/GoogleIgnoreListConsumer').default;
if (maps.length < 1) {
throw new Error('composeSourceMaps: Expected at least one map');
}
const firstMap = maps[0];
const consumers = maps
.map(function (map) {
return new Consumer(map);
})
.reverse();
const generator = new SourceMapGenerator({
file: consumers[0].file,
});
consumers[0].eachMapping(mapping => {
const original = findOriginalPosition(
consumers,
mapping.generatedLine,
mapping.generatedColumn,
);
generator.addMapping({
generated: {
line: mapping.generatedLine,
column: mapping.generatedColumn,
},
original:
original.line != null
? {
line: original.line,
column: original.column,
}
: null,
source: original.source,
name: original.name,
});
});
const composedMap = generator.toJSON();
composedMap.sourcesContent = composedMap.sources.map(source =>
consumers[consumers.length - 1].sourceContentFor(source, true),
);
if (composedMap.sourcesContent.every(content => content == null)) {
delete composedMap.sourcesContent;
}
const metadataConsumer = new SourceMetadataMapConsumer(firstMap);
composedMap.x_facebook_sources = metadataConsumer.toArray(
composedMap.sources,
);
const function_offsets = maps[maps.length - 1].x_hermes_function_offsets;
if (function_offsets) {
composedMap.x_hermes_function_offsets = function_offsets;
}
const ignoreListConsumer = new GoogleIgnoreListConsumer(firstMap);
const x_google_ignoreList = ignoreListConsumer.toArray(composedMap.sources);
if (x_google_ignoreList.length) {
composedMap.x_google_ignoreList = x_google_ignoreList;
}
return composedMap;
}
function findOriginalPosition(
consumers: $ReadOnlyArray<IConsumer>,
generatedLine: Number1,
generatedColumn: Number0,
): {
line: ?number,
column: ?number,
source: ?string,
name: ?string,
...
} {
let currentLine: ?Number1 = generatedLine;
let currentColumn: ?Number0 = generatedColumn;
let original: SourcePosition = {
line: null,
column: null,
source: null,
name: null,
};
for (const consumer of consumers) {
if (currentLine == null || currentColumn == null) {
return {line: null, column: null, source: null, name: null};
}
original = consumer.originalPositionFor({
line: currentLine,
column: currentColumn,
});
currentLine = original.line;
currentColumn = original.column;
if (currentLine == null) {
return {
line: null,
column: null,
source: null,
name: null,
};
}
}
// $FlowFixMe[incompatible-type] `Number0`, `Number1` is incompatible with number
return original;
}

66
node_modules/metro-source-map/src/encode.d.ts generated vendored Normal file
View File

@@ -0,0 +1,66 @@
/**
* Portions 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.
*
* @format
* @oncall react_native
*/
/**
* Copyright 2011 Mozilla Foundation and contributors
* Licensed under the New BSD license. See LICENSE or:
* http://opensource.org/licenses/BSD-3-Clause
*
* Based on the Base 64 VLQ implementation in Closure Compiler:
* https://git.io/vymuA
*
* Copyright 2011 The Closure Compiler Authors. All rights reserved.
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are
* met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above
* copyright notice, this list of conditions and the following
* disclaimer in the documentation and/or other materials provided
* with the distribution.
* * Neither the name of Google Inc. nor the names of its
* contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
* OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
* @copyright
*
* Associate this with the THIRD_PARTY_LICENCE type to ensure it isn't
* stripped by flow-api-translator.
*/
export type THIRD_PARTY_LICENSE = unknown;
/**
* Encodes a number to base64 VLQ format and appends it to the passed-in buffer
*
* DON'T USE COMPOUND OPERATORS (eg `>>>=`) ON `let`-DECLARED VARIABLES!
* V8 WILL DEOPTIMIZE THIS FUNCTION AND MAP CREATION WILL BE 25% SLOWER!
*
* DON'T ADD MORE COMMENTS TO THIS FUNCTION TO KEEP ITS LENGTH SHORT ENOUGH FOR
* V8 OPTIMIZATION!
*/
declare function encode(
value: number,
buffer: Buffer,
position: number,
): number;
export default encode;

33
node_modules/metro-source-map/src/encode.js generated vendored Normal file
View File

@@ -0,0 +1,33 @@
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true,
});
exports.default = encode;
const CHAR_MAP = [
0x41, 0x42, 0x43, 0x44, 0x45, 0x46, 0x47, 0x48, 0x49, 0x4a, 0x4b, 0x4c, 0x4d,
0x4e, 0x4f, 0x50, 0x51, 0x52, 0x53, 0x54, 0x55, 0x56, 0x57, 0x58, 0x59, 0x5a,
0x61, 0x62, 0x63, 0x64, 0x65, 0x66, 0x67, 0x68, 0x69, 0x6a, 0x6b, 0x6c, 0x6d,
0x6e, 0x6f, 0x70, 0x71, 0x72, 0x73, 0x74, 0x75, 0x76, 0x77, 0x78, 0x79, 0x7a,
0x30, 0x31, 0x32, 0x33, 0x34, 0x35, 0x36, 0x37, 0x38, 0x39, 0x2b, 0x2f,
];
const VLQ_BASE_SHIFT = 5;
const VLQ_BASE = 1 << VLQ_BASE_SHIFT;
const VLQ_BASE_MASK = VLQ_BASE - 1;
const VLQ_CONTINUATION_BIT = VLQ_BASE;
function toVLQSigned(value) {
return value < 0 ? (-value << 1) + 1 : (value << 1) + 0;
}
function encode(value, buffer, position) {
let vlq = toVLQSigned(value);
let digit;
do {
digit = vlq & VLQ_BASE_MASK;
vlq = vlq >>> VLQ_BASE_SHIFT;
if (vlq > 0) {
digit = digit | VLQ_CONTINUATION_BIT;
}
buffer[position++] = CHAR_MAP[digit];
} while (vlq > 0);
return position;
}

126
node_modules/metro-source-map/src/encode.js.flow generated vendored Normal file
View File

@@ -0,0 +1,126 @@
/**
* Portions 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
* @format
* @oncall react_native
*/
/**
* Copyright 2011 Mozilla Foundation and contributors
* Licensed under the New BSD license. See LICENSE or:
* http://opensource.org/licenses/BSD-3-Clause
*
* Based on the Base 64 VLQ implementation in Closure Compiler:
* https://git.io/vymuA
*
* Copyright 2011 The Closure Compiler Authors. All rights reserved.
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are
* met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above
* copyright notice, this list of conditions and the following
* disclaimer in the documentation and/or other materials provided
* with the distribution.
* * Neither the name of Google Inc. nor the names of its
* contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
* OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
* @copyright
*
* Associate this with the THIRD_PARTY_LICENCE type to ensure it isn't
* stripped by flow-api-translator.
*/
export type THIRD_PARTY_LICENSE = mixed;
/* eslint-disable no-bitwise */
// A map of values to characters for the b64 encoding
const CHAR_MAP = [
0x41, 0x42, 0x43, 0x44, 0x45, 0x46, 0x47, 0x48, 0x49, 0x4a, 0x4b, 0x4c, 0x4d,
0x4e, 0x4f, 0x50, 0x51, 0x52, 0x53, 0x54, 0x55, 0x56, 0x57, 0x58, 0x59, 0x5a,
0x61, 0x62, 0x63, 0x64, 0x65, 0x66, 0x67, 0x68, 0x69, 0x6a, 0x6b, 0x6c, 0x6d,
0x6e, 0x6f, 0x70, 0x71, 0x72, 0x73, 0x74, 0x75, 0x76, 0x77, 0x78, 0x79, 0x7a,
0x30, 0x31, 0x32, 0x33, 0x34, 0x35, 0x36, 0x37, 0x38, 0x39, 0x2b, 0x2f,
];
// A single base 64 digit can contain 6 bits of data. For the base 64 variable
// length quantities we use in the source map spec, the first bit is the sign,
// the next four bits are the actual value, and the 6th bit is the
// continuation bit. The continuation bit tells us whether there are more
// digits in this value following this digit.
//
// Continuation
// | Sign
// | |
// V V
// 101011
const VLQ_BASE_SHIFT = 5;
// binary: 100000
const VLQ_BASE = 1 << VLQ_BASE_SHIFT;
// binary: 011111
const VLQ_BASE_MASK = VLQ_BASE - 1;
// binary: 100000
const VLQ_CONTINUATION_BIT = VLQ_BASE;
/**
* Converts from a two-complement value to a value where the sign bit is
* placed in the least significant bit. For example, as decimals:
* 1 becomes 2 (10 binary), -1 becomes 3 (11 binary)
* 2 becomes 4 (100 binary), -2 becomes 5 (101 binary)
*/
function toVLQSigned(value: number) {
return value < 0 ? (-value << 1) + 1 : (value << 1) + 0;
}
/**
* Encodes a number to base64 VLQ format and appends it to the passed-in buffer
*
* DON'T USE COMPOUND OPERATORS (eg `>>>=`) ON `let`-DECLARED VARIABLES!
* V8 WILL DEOPTIMIZE THIS FUNCTION AND MAP CREATION WILL BE 25% SLOWER!
*
* DON'T ADD MORE COMMENTS TO THIS FUNCTION TO KEEP ITS LENGTH SHORT ENOUGH FOR
* V8 OPTIMIZATION!
*/
export default function encode(
value: number,
buffer: Buffer,
position: number,
): number {
let vlq = toVLQSigned(value);
let digit;
do {
digit = vlq & VLQ_BASE_MASK;
vlq = vlq >>> VLQ_BASE_SHIFT;
if (vlq > 0) {
// There are still more digits in this value, so we must make sure the
// continuation bit is marked.
digit = digit | VLQ_CONTINUATION_BIT;
}
buffer[position++] = CHAR_MAP[digit];
} while (vlq > 0);
return position;
}

View File

@@ -0,0 +1,45 @@
/**
* 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.
*
* @format
* @oncall react_native
*/
import type {FBSourceFunctionMap} from './source-map';
import type {PluginObj} from '@babel/core';
import type {Node as BabelNode} from '@babel/types';
type Position = {line: number; column: number};
type RangeMapping = {name: string; start: Position};
export type Context = {filename?: null | undefined | string};
/**
* Generate a map of source positions to function names. The names are meant to
* describe the stack frame in an error trace and may contain more contextual
* information than just the actual name of the function.
*
* The output is encoded for use in a source map. For details about the format,
* see MappingEncoder below.
*/
declare function generateFunctionMap(
ast: BabelNode,
context?: Context,
): FBSourceFunctionMap;
/**
* Same as generateFunctionMap, but returns the raw array of mappings instead
* of encoding it for use in a source map.
*
* Lines are 1-based and columns are 0-based.
*/
declare function generateFunctionMappingsArray(
ast: BabelNode,
context?: Context,
): ReadonlyArray<RangeMapping>;
declare function functionMapBabelPlugin(): PluginObj;
export {
functionMapBabelPlugin,
generateFunctionMap,
generateFunctionMappingsArray,
};

View File

@@ -0,0 +1,406 @@
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true,
});
exports.functionMapBabelPlugin = functionMapBabelPlugin;
exports.generateFunctionMap = generateFunctionMap;
exports.generateFunctionMappingsArray = generateFunctionMappingsArray;
var _B64Builder = _interopRequireDefault(require("./B64Builder"));
var _traverseForGenerateFunctionMap = _interopRequireDefault(
require("@babel/traverse--for-generate-function-map"),
);
var _types = _interopRequireWildcard(require("@babel/types"));
var t = _types;
var _invariant = _interopRequireDefault(require("invariant"));
var _nullthrows = _interopRequireDefault(require("nullthrows"));
var _path = _interopRequireDefault(require("path"));
function _getRequireWildcardCache(e) {
if ("function" != typeof WeakMap) return null;
var r = new WeakMap(),
t = new WeakMap();
return (_getRequireWildcardCache = function (e) {
return e ? t : r;
})(e);
}
function _interopRequireWildcard(e, r) {
if (!r && e && e.__esModule) return e;
if (null === e || ("object" != typeof e && "function" != typeof e))
return { default: e };
var t = _getRequireWildcardCache(r);
if (t && t.has(e)) return t.get(e);
var n = { __proto__: null },
a = Object.defineProperty && Object.getOwnPropertyDescriptor;
for (var u in e)
if ("default" !== u && {}.hasOwnProperty.call(e, u)) {
var i = a ? Object.getOwnPropertyDescriptor(e, u) : null;
i && (i.get || i.set) ? Object.defineProperty(n, u, i) : (n[u] = e[u]);
}
return ((n.default = e), t && t.set(e, n), n);
}
function _interopRequireDefault(e) {
return e && e.__esModule ? e : { default: e };
}
function generateFunctionMap(ast, context) {
const encoder = new MappingEncoder();
forEachMapping(ast, context, (mapping) => encoder.push(mapping));
return encoder.getResult();
}
function generateFunctionMappingsArray(ast, context) {
const mappings = [];
forEachMapping(ast, context, (mapping) => {
mappings.push(mapping);
});
return mappings;
}
function functionMapBabelPlugin() {
return {
visitor: {},
pre: ({ path, metadata, opts }) => {
const { filename } = (0, _nullthrows.default)(opts);
const encoder = new MappingEncoder();
const visitor = getFunctionMapVisitor(
{
filename,
},
(mapping) => encoder.push(mapping),
);
(0, _invariant.default)(
path && t.isProgram(path.node),
"path missing or not a program node",
);
const programPath = path;
visitor.enter(programPath);
programPath.traverse({
Function: visitor,
Class: visitor,
});
visitor.exit(programPath);
const metroMetadata = metadata;
const functionMap = encoder.getResult();
if (!metroMetadata.metro) {
metroMetadata.metro = {
functionMap,
};
} else {
metroMetadata.metro.functionMap = functionMap;
}
},
};
}
function getFunctionMapVisitor(context, pushMapping) {
const nameStack = [];
let tailPos = {
line: 1,
column: 0,
};
let tailName = null;
function advanceToPos(pos) {
if (tailPos && positionGreater(pos, tailPos)) {
const name = nameStack[0].name;
if (name !== tailName) {
pushMapping({
name,
start: {
line: tailPos.line,
column: tailPos.column,
},
});
tailName = name;
}
}
tailPos = pos;
}
function pushFrame(name, loc) {
advanceToPos(loc.start);
nameStack.unshift({
name,
loc,
});
}
function popFrame() {
const top = nameStack[0];
if (top) {
const { loc } = top;
advanceToPos(loc.end);
nameStack.shift();
}
}
if (!context) {
context = {};
}
const basename = context.filename
? _path.default.basename(context.filename).replace(/\..+$/, "")
: null;
return {
enter(path) {
let name = getNameForPath(path);
if (basename) {
name = removeNamePrefix(name, basename);
}
pushFrame(name, (0, _nullthrows.default)(path.node.loc));
},
exit(path) {
popFrame();
},
};
}
function forEachMapping(ast, context, pushMapping) {
const visitor = getFunctionMapVisitor(context, pushMapping);
(0, _traverseForGenerateFunctionMap.default)(ast, {
noScope: true,
Function: visitor,
Program: visitor,
Class: visitor,
});
}
const ANONYMOUS_NAME = "<anonymous>";
function getNameForPath(path) {
const { node, parent, parentPath } = path;
if ((0, _types.isProgram)(node)) {
return "<global>";
}
let { id } = path;
if (node.id) {
return node.id.name;
}
let propertyPath;
let kind;
if ((0, _types.isObjectMethod)(node) || (0, _types.isClassMethod)(node)) {
id = node.key;
if (node.kind !== "method" && node.kind !== "constructor") {
kind = node.kind;
}
propertyPath = path;
} else if (
(0, _types.isObjectProperty)(parent) ||
(0, _types.isClassProperty)(parent)
) {
id = parent.key;
propertyPath = parentPath;
} else if ((0, _types.isVariableDeclarator)(parent)) {
id = parent.id;
} else if ((0, _types.isAssignmentExpression)(parent)) {
id = parent.left;
} else if ((0, _types.isJSXExpressionContainer)(parent)) {
const grandParentNode = parentPath?.parentPath?.node;
if ((0, _types.isJSXElement)(grandParentNode)) {
const openingElement = grandParentNode.openingElement;
id = t.jsxMemberExpression(
t.jsxMemberExpression(openingElement.name, t.jsxIdentifier("props")),
t.jsxIdentifier("children"),
);
} else if ((0, _types.isJSXAttribute)(grandParentNode)) {
const openingElement = parentPath?.parentPath?.parentPath?.node;
const prop = grandParentNode;
id = t.jsxMemberExpression(
t.jsxMemberExpression(openingElement.name, t.jsxIdentifier("props")),
prop.name,
);
}
}
let name = getNameFromId(id);
if (name == null) {
if (isAnyCallExpression(parent)) {
const argIndex = parent.arguments.indexOf(node);
if (argIndex !== -1) {
const calleeName = getNameFromId(parent.callee);
if (argIndex === 0 && calleeName === "Object.freeze") {
return getNameForPath((0, _nullthrows.default)(parentPath));
}
if (
argIndex === 0 &&
(calleeName === "useCallback" || calleeName === "React.useCallback")
) {
return getNameForPath((0, _nullthrows.default)(parentPath));
}
if (calleeName) {
return `${calleeName}$argument_${argIndex}`;
}
}
}
if (
(0, _types.isTypeCastExpression)(parent) &&
parent.expression === node
) {
return getNameForPath((0, _nullthrows.default)(parentPath));
}
if ((0, _types.isExportDefaultDeclaration)(parent)) {
return "default";
}
return ANONYMOUS_NAME;
}
if (kind != null) {
name = kind + "__" + name;
}
if (propertyPath) {
if ((0, _types.isClassBody)(propertyPath.parent)) {
const className = getNameForPath(propertyPath.parentPath.parentPath);
if (className !== ANONYMOUS_NAME) {
const separator = propertyPath.node.static ? "." : "#";
name = className + separator + name;
}
} else if ((0, _types.isObjectExpression)(propertyPath.parent)) {
const objectName = getNameForPath(
(0, _nullthrows.default)(propertyPath.parentPath),
);
if (objectName !== ANONYMOUS_NAME) {
name = objectName + "." + name;
}
}
}
return name;
}
function isAnyCallExpression(node) {
return (
node.type === "CallExpression" ||
node.type === "NewExpression" ||
node.type === "OptionalCallExpression"
);
}
function isAnyMemberExpression(node) {
return (
node.type === "MemberExpression" ||
node.type === "JSXMemberExpression" ||
node.type === "OptionalMemberExpression"
);
}
function isAnyIdentifier(node) {
return (0, _types.isIdentifier)(node) || (0, _types.isJSXIdentifier)(node);
}
function getNameFromId(id) {
const parts = getNamePartsFromId(id);
if (!parts.length) {
return null;
}
if (parts.length > 5) {
return (
parts[0] +
"." +
parts[1] +
"..." +
parts[parts.length - 2] +
"." +
parts[parts.length - 1]
);
}
return parts.join(".");
}
function getNamePartsFromId(id) {
if (!id) {
return [];
}
if (isAnyCallExpression(id)) {
return getNamePartsFromId(id.callee);
}
if ((0, _types.isTypeCastExpression)(id)) {
return getNamePartsFromId(id.expression);
}
let name;
if (isAnyIdentifier(id)) {
name = id.name;
} else if ((0, _types.isNullLiteral)(id)) {
name = "null";
} else if ((0, _types.isRegExpLiteral)(id)) {
name = `_${id.pattern}_${id.flags ?? ""}`;
} else if ((0, _types.isTemplateLiteral)(id)) {
name = id.quasis.map((quasi) => quasi.value.raw).join("");
} else if ((0, _types.isLiteral)(id) && id.value != null) {
name = String(id.value);
}
if (name != null) {
return [t.toBindingIdentifierName(name)];
}
if ((0, _types.isImport)(id)) {
name = "import";
}
if (name != null) {
return [name];
}
if (isAnyMemberExpression(id)) {
if (
isAnyIdentifier(id.object) &&
id.object.name === "Symbol" &&
(isAnyIdentifier(id.property) || (0, _types.isLiteral)(id.property))
) {
const propertyName = getNameFromId(id.property);
if (propertyName) {
name = "@@" + propertyName;
}
} else {
const propertyName = getNamePartsFromId(id.property);
if (propertyName.length) {
const objectName = getNamePartsFromId(id.object);
if (objectName.length) {
return [...objectName, ...propertyName];
} else {
return propertyName;
}
}
}
}
return name ? [name] : [];
}
const DELIMITER_START_RE = /^[^A-Za-z0-9_$@]+/;
function removeNamePrefix(name, namePrefix) {
if (!namePrefix.length || !name.startsWith(namePrefix)) {
return name;
}
const shortenedName = name.substr(namePrefix.length);
const [delimiterMatch] = shortenedName.match(DELIMITER_START_RE) || [];
if (delimiterMatch) {
return shortenedName.substr(delimiterMatch.length) || name;
}
return name;
}
class MappingEncoder {
constructor() {
this._namesMap = new Map();
this._names = [];
this._line = new RelativeValue(1);
this._column = new RelativeValue(0);
this._nameIndex = new RelativeValue(0);
this._mappings = new _B64Builder.default();
}
getResult() {
return {
names: this._names,
mappings: this._mappings.toString(),
};
}
push({ name, start }) {
let nameIndex = this._namesMap.get(name);
if (typeof nameIndex !== "number") {
nameIndex = this._names.length;
this._names[nameIndex] = name;
this._namesMap.set(name, nameIndex);
}
const lineDelta = this._line.next(start.line);
const firstOfLine = this._mappings.pos === 0 || lineDelta > 0;
if (lineDelta > 0) {
this._mappings.markLines(1);
this._column.reset(0);
}
this._mappings.startSegment(this._column.next(start.column));
this._mappings.append(this._nameIndex.next(nameIndex));
if (firstOfLine) {
this._mappings.append(lineDelta);
}
}
}
class RelativeValue {
constructor(value = 0) {
this.reset(value);
}
next(absoluteValue) {
const delta = absoluteValue - this._value;
this._value = absoluteValue;
return delta;
}
reset(value = 0) {
this._value = value;
}
}
function positionGreater(x, y) {
return x.line > y.line || (x.line === y.line && x.column > y.column);
}

View File

@@ -0,0 +1,598 @@
/**
* 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
* @format
* @oncall react_native
*/
import type {FBSourceFunctionMap} from './source-map';
import type {PluginObj} from '@babel/core';
import type {NodePath} from '@babel/traverse';
import type {Node as BabelNode} from '@babel/types';
import type {MetroBabelFileMetadata} from 'metro-babel-transformer';
import B64Builder from './B64Builder';
// $FlowFixMe[cannot-resolve-module] - resolves to @babel/traverse
import traverseForGenerateFunctionMap from '@babel/traverse--for-generate-function-map';
import * as t from '@babel/types';
import {
isAssignmentExpression,
isClassBody,
isClassMethod,
isClassProperty,
isExportDefaultDeclaration,
isIdentifier,
isImport,
isJSXAttribute,
isJSXElement,
isJSXExpressionContainer,
isJSXIdentifier,
isLiteral,
isNullLiteral,
isObjectExpression,
isObjectMethod,
isObjectProperty,
isProgram,
isRegExpLiteral,
isTemplateLiteral,
isTypeCastExpression,
isVariableDeclarator,
} from '@babel/types';
import invariant from 'invariant';
import nullthrows from 'nullthrows';
import fsPath from 'path';
type Position = {
line: number,
column: number,
...
};
type RangeMapping = {
name: string,
start: Position,
...
};
type FunctionMapVisitor = {
enter: (
path:
| NodePath<BabelNodeProgram>
| NodePath<BabelNodeFunction>
| NodePath<BabelNodeClass>,
) => void,
exit: (
path:
| NodePath<BabelNodeProgram>
| NodePath<BabelNodeFunction>
| NodePath<BabelNodeClass>,
) => void,
};
export type Context = {filename?: ?string, ...};
/**
* Generate a map of source positions to function names. The names are meant to
* describe the stack frame in an error trace and may contain more contextual
* information than just the actual name of the function.
*
* The output is encoded for use in a source map. For details about the format,
* see MappingEncoder below.
*/
function generateFunctionMap(
ast: BabelNode,
context?: Context,
): FBSourceFunctionMap {
const encoder = new MappingEncoder();
forEachMapping(ast, context, mapping => encoder.push(mapping));
return encoder.getResult();
}
/**
* Same as generateFunctionMap, but returns the raw array of mappings instead
* of encoding it for use in a source map.
*
* Lines are 1-based and columns are 0-based.
*/
function generateFunctionMappingsArray(
ast: BabelNode,
context?: Context,
): $ReadOnlyArray<RangeMapping> {
const mappings = [];
forEachMapping(ast, context, mapping => {
mappings.push(mapping);
});
return mappings;
}
function functionMapBabelPlugin(): PluginObj<> {
return {
// Eagerly traverse the tree on `pre`, before any visitors have run, so
// that regardless of plugin order we're dealing with the AST before any
// mutations.
visitor: {},
pre: ({path, metadata, opts}) => {
const {filename} = nullthrows(opts);
const encoder = new MappingEncoder();
const visitor = getFunctionMapVisitor({filename}, mapping =>
encoder.push(mapping),
);
invariant(
path && t.isProgram(path.node),
'path missing or not a program node',
);
// $FlowFixMe[prop-missing] checked above
// $FlowFixMe[incompatible-type-arg] checked above
const programPath: NodePath<BabelNodeProgram> = path as $FlowFixMe;
visitor.enter(programPath);
programPath.traverse({
Function: visitor,
Class: visitor,
});
visitor.exit(programPath);
// $FlowFixMe[incompatible-type] Babel `File` is not generically typed
const metroMetadata: MetroBabelFileMetadata = metadata;
const functionMap = encoder.getResult();
// Set the result on a metadata property
if (!metroMetadata.metro) {
metroMetadata.metro = {functionMap};
} else {
metroMetadata.metro.functionMap = functionMap;
}
},
};
}
function getFunctionMapVisitor(
context: ?Context,
pushMapping: RangeMapping => void,
): FunctionMapVisitor {
const nameStack: Array<{loc: BabelNodeSourceLocation, name: string}> = [];
let tailPos = {line: 1, column: 0};
let tailName: null | string = null;
function advanceToPos(pos: {column: number, line: number}) {
if (tailPos && positionGreater(pos, tailPos)) {
const name = nameStack[0].name; // We always have at least Program
if (name !== tailName) {
pushMapping({
name,
start: {line: tailPos.line, column: tailPos.column},
});
tailName = name;
}
}
tailPos = pos;
}
function pushFrame(name: string, loc: BabelNodeSourceLocation) {
advanceToPos(loc.start);
nameStack.unshift({name, loc});
}
function popFrame() {
const top = nameStack[0];
if (top) {
const {loc} = top;
advanceToPos(loc.end);
nameStack.shift();
}
}
if (!context) {
context = {};
}
const basename = context.filename
? fsPath.basename(context.filename).replace(/\..+$/, '')
: null;
return {
enter(path) {
let name = getNameForPath(path);
if (basename) {
name = removeNamePrefix(name, basename);
}
pushFrame(name, nullthrows(path.node.loc));
},
exit(path) {
popFrame();
},
};
}
/**
* Traverses a Babel AST and calls the supplied callback with function name
* mappings, one at a time.
*/
function forEachMapping(
ast: BabelNode,
context: ?Context,
pushMapping: RangeMapping => void,
) {
const visitor = getFunctionMapVisitor(context, pushMapping);
// Traversing populates/pollutes the path cache (`traverse.cache.path`) with
// values missing the `hub` property needed by Babel transformation, so we
// use a separate copy of traverse to populate a separate cache to not pollute
// the main @babel/traverse cache. See: https://github.com/facebook/metro/pull/1340
traverseForGenerateFunctionMap(ast, {
// Our visitor doesn't care about scope
noScope: true,
Function: visitor,
Program: visitor,
Class: visitor,
});
}
const ANONYMOUS_NAME = '<anonymous>';
/**
* Derive a contextual name for the given AST node (Function, Program, Class or
* ObjectExpression).
*/
function getNameForPath(path: NodePath<>): string {
const {node, parent, parentPath} = path;
if (isProgram(node)) {
return '<global>';
}
let {id}: any = path;
// has an `id` so we don't need to infer one
if (node.id) {
// $FlowFixMe[incompatible-type] Flow error uncovered by typing Babel more strictly
return node.id.name;
}
let propertyPath;
let kind: ?string;
// Find or construct an AST node that names the current node.
if (isObjectMethod(node) || isClassMethod(node)) {
// ({ foo() {} });
id = node.key;
if (node.kind !== 'method' && node.kind !== 'constructor') {
// Store the method's kind so we can add it to the final name.
kind = node.kind;
}
// Also store the path to the property so we can find its context
// (object/class) later and add _its_ name to the result.
propertyPath = path;
} else if (isObjectProperty(parent) || isClassProperty(parent)) {
// ({ foo: function() {} });
id = parent.key;
// Also store the path to the property so we can find its context
// (object/class) later and add _its_ name to the result.
propertyPath = parentPath;
} else if (isVariableDeclarator(parent)) {
// let foo = function () {};
id = parent.id;
} else if (isAssignmentExpression(parent)) {
// foo = function () {};
id = parent.left;
} else if (isJSXExpressionContainer(parent)) {
const grandParentNode = parentPath?.parentPath?.node;
if (isJSXElement(grandParentNode)) {
// <foo>{function () {}}</foo>
const openingElement = grandParentNode.openingElement;
id = t.jsxMemberExpression(
// $FlowFixMe[incompatible-type] Flow error uncovered by typing Babel more strictly
t.jsxMemberExpression(openingElement.name, t.jsxIdentifier('props')),
t.jsxIdentifier('children'),
);
} else if (isJSXAttribute(grandParentNode)) {
// <foo bar={function () {}} />
const openingElement = parentPath?.parentPath?.parentPath?.node;
const prop = grandParentNode;
id = t.jsxMemberExpression(
// $FlowFixMe[incompatible-type]
// $FlowFixMe[incompatible-use] Flow error uncovered by typing Babel more strictly
t.jsxMemberExpression(openingElement.name, t.jsxIdentifier('props')),
// $FlowFixMe[incompatible-type] Flow error uncovered by typing Babel more strictly
prop.name,
);
}
}
// Collapse the name AST, if any, into a string.
let name = getNameFromId(id);
if (name == null) {
// We couldn't find a name directly. Try the parent in certain cases.
if (isAnyCallExpression(parent)) {
// foo(function () {})
/* $FlowFixMe[incompatible-type] Error exposed after improved typing of
* Array.{includes,indexOf,lastIndexOf} */
const argIndex = parent.arguments.indexOf(node);
if (argIndex !== -1) {
const calleeName = getNameFromId(parent.callee);
// var f = Object.freeze(function () {})
if (argIndex === 0 && calleeName === 'Object.freeze') {
return getNameForPath(nullthrows(parentPath));
}
// var f = useCallback(function () {})
if (
argIndex === 0 &&
(calleeName === 'useCallback' || calleeName === 'React.useCallback')
) {
return getNameForPath(nullthrows(parentPath));
}
if (calleeName) {
return `${calleeName}$argument_${argIndex}`;
}
}
}
if (isTypeCastExpression(parent) && parent.expression === node) {
return getNameForPath(nullthrows(parentPath));
}
if (isExportDefaultDeclaration(parent)) {
return 'default';
}
// We couldn't infer a name at all.
return ANONYMOUS_NAME;
}
// Annotate getters and setters.
if (kind != null) {
name = kind + '__' + name;
}
// Annotate members with the name of their containing object/class.
if (propertyPath) {
if (isClassBody(propertyPath.parent)) {
// $FlowFixMe[incompatible-type]
// $FlowFixMe[incompatible-use] Discovered when typing babel-traverse
const className = getNameForPath(propertyPath.parentPath.parentPath);
if (className !== ANONYMOUS_NAME) {
const separator = propertyPath.node.static ? '.' : '#';
name = className + separator + name;
}
} else if (isObjectExpression(propertyPath.parent)) {
const objectName = getNameForPath(nullthrows(propertyPath.parentPath));
if (objectName !== ANONYMOUS_NAME) {
name = objectName + '.' + name;
}
}
}
return name;
}
function isAnyCallExpression(
node: BabelNode,
): node is
| BabelNodeNewExpression
| BabelNodeCallExpression
| BabelNodeOptionalCallExpression {
return (
node.type === 'CallExpression' ||
node.type === 'NewExpression' ||
node.type === 'OptionalCallExpression'
);
}
function isAnyMemberExpression(
node: BabelNode,
): node is
| BabelNodeMemberExpression
| BabelNodeJSXMemberExpression
| BabelNodeOptionalMemberExpression {
return (
node.type === 'MemberExpression' ||
node.type === 'JSXMemberExpression' ||
node.type === 'OptionalMemberExpression'
);
}
function isAnyIdentifier(
node: BabelNode,
): node is BabelNodeIdentifier | BabelNodeJSXIdentifier {
return isIdentifier(node) || isJSXIdentifier(node);
}
function getNameFromId(id: BabelNode): ?string {
const parts = getNamePartsFromId(id);
if (!parts.length) {
return null;
}
if (parts.length > 5) {
return (
parts[0] +
'.' +
parts[1] +
'...' +
parts[parts.length - 2] +
'.' +
parts[parts.length - 1]
);
}
return parts.join('.');
}
function getNamePartsFromId(id: BabelNode): $ReadOnlyArray<string> {
if (!id) {
return [];
}
if (isAnyCallExpression(id)) {
return getNamePartsFromId(id.callee);
}
if (isTypeCastExpression(id)) {
return getNamePartsFromId(id.expression);
}
let name;
if (isAnyIdentifier(id)) {
name = id.name;
} else if (isNullLiteral(id)) {
name = 'null';
} else if (isRegExpLiteral(id)) {
name = `_${id.pattern}_${id.flags ?? ''}`;
} else if (isTemplateLiteral(id)) {
name = id.quasis.map(quasi => quasi.value.raw).join('');
} else if (isLiteral(id) && id.value != null) {
name = String(id.value);
}
if (name != null) {
return [t.toBindingIdentifierName(name)];
}
if (isImport(id)) {
name = 'import';
}
if (name != null) {
return [name];
}
if (isAnyMemberExpression(id)) {
if (
isAnyIdentifier(id.object) &&
id.object.name === 'Symbol' &&
(isAnyIdentifier(id.property) || isLiteral(id.property))
) {
const propertyName = getNameFromId(id.property);
if (propertyName) {
name = '@@' + propertyName;
}
} else {
const propertyName = getNamePartsFromId(id.property);
if (propertyName.length) {
const objectName = getNamePartsFromId(id.object);
if (objectName.length) {
return [...objectName, ...propertyName];
} else {
return propertyName;
}
}
}
}
return name ? [name] : [];
}
const DELIMITER_START_RE = /^[^A-Za-z0-9_$@]+/;
/**
* Strip the given prefix from `name`, if it occurs there, plus any delimiter
* characters that follow (of which at least one is required). If an empty
* string would be returned, return the original name instead.
*/
function removeNamePrefix(name: string, namePrefix: string): string {
if (!namePrefix.length || !name.startsWith(namePrefix)) {
return name;
}
const shortenedName = name.substr(namePrefix.length);
const [delimiterMatch] = shortenedName.match(DELIMITER_START_RE) || [];
if (delimiterMatch) {
return shortenedName.substr(delimiterMatch.length) || name;
}
return name;
}
/**
* Encodes function name mappings as deltas in a Base64 VLQ format inspired by
* the standard source map format.
*
* Mappings on different lines are separated with a single `;` (even if there
* are multiple intervening lines).
* Mappings on the same line are separated with `,`.
*
* The first mapping of a line has the fields:
* [column delta, name delta, line delta]
*
* where the column delta is relative to the beginning of the line, the name
* delta is relative to the previously occurring name, and the line delta is
* relative to the previously occurring line.
*
* The 2...nth other mappings of a line have the fields:
* [column delta, name delta]
*
* where both fields are relative to their previous running values. The line
* delta is omitted since it is always 0 by definition.
*
* Lines and columns are both 0-based in the serialised format. In memory,
* lines are 1-based while columns are 0-based.
*/
class MappingEncoder {
_namesMap: Map<string, number>;
_names: Array<string>;
_line: RelativeValue;
_column: RelativeValue;
_nameIndex: RelativeValue;
_mappings: B64Builder;
constructor() {
this._namesMap = new Map();
this._names = [];
this._line = new RelativeValue(1);
this._column = new RelativeValue(0);
this._nameIndex = new RelativeValue(0);
this._mappings = new B64Builder();
}
getResult(): FBSourceFunctionMap {
return {names: this._names, mappings: this._mappings.toString()};
}
push({name, start}: RangeMapping) {
let nameIndex = this._namesMap.get(name);
if (typeof nameIndex !== 'number') {
nameIndex = this._names.length;
this._names[nameIndex] = name;
this._namesMap.set(name, nameIndex);
}
const lineDelta = this._line.next(start.line);
const firstOfLine = this._mappings.pos === 0 || lineDelta > 0;
if (lineDelta > 0) {
// The next entry will have the line offset, so emit just one semicolon.
this._mappings.markLines(1);
this._column.reset(0);
}
this._mappings.startSegment(this._column.next(start.column));
this._mappings.append(this._nameIndex.next(nameIndex));
if (firstOfLine) {
this._mappings.append(lineDelta);
}
}
}
class RelativeValue {
_value: number;
constructor(value: number = 0) {
this.reset(value);
}
next(absoluteValue: number): number {
const delta = absoluteValue - this._value;
this._value = absoluteValue;
return delta;
}
reset(value: number = 0) {
this._value = value;
}
}
function positionGreater(x: Position, y: Position) {
return x.line > y.line || (x.line === y.line && x.column > y.column);
}
export {
functionMapBabelPlugin,
generateFunctionMap,
generateFunctionMappingsArray,
};

155
node_modules/metro-source-map/src/source-map.d.ts generated vendored Normal file
View File

@@ -0,0 +1,155 @@
/**
* 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.
*
* @format
* @oncall react_native
*/
import type {IConsumer} from './Consumer/types';
import {BundleBuilder, createIndexMap} from './BundleBuilder';
import composeSourceMaps from './composeSourceMaps';
import Consumer from './Consumer';
import normalizeSourcePath from './Consumer/normalizeSourcePath';
import {
functionMapBabelPlugin,
generateFunctionMap,
} from './generateFunctionMap';
import Generator from './Generator';
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;
export type HermesFunctionOffsets = {
[$$Key$$: number]: ReadonlyArray<number>;
};
export type FBSourcesArray = ReadonlyArray<null | undefined | FBSourceMetadata>;
export type FBSourceMetadata = [null | undefined | 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?: null | undefined | string;
name?: null | undefined | 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<null | undefined | 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;
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;
/**
* 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.
*/
declare function fromRawMappings(
modules: ReadonlyArray<{
readonly map: null | undefined | ReadonlyArray<MetroSourceMapSegmentTuple>;
readonly functionMap: null | undefined | FBSourceFunctionMap;
readonly path: string;
readonly source: string;
readonly code: string;
readonly isIgnored: boolean;
readonly lineCount?: number;
}>,
offsetLines?: number,
): Generator;
declare function fromRawMappingsNonBlocking(
modules: ReadonlyArray<{
readonly map: null | undefined | ReadonlyArray<MetroSourceMapSegmentTuple>;
readonly functionMap: null | undefined | FBSourceFunctionMap;
readonly path: string;
readonly source: string;
readonly code: string;
readonly isIgnored: boolean;
readonly lineCount?: number;
}>,
offsetLines?: number,
): Promise<Generator>;
/**
* Transforms a standard source map object into a Raw Mappings object, to be
* used across the bundler.
*/
declare function toBabelSegments(
sourceMap: BasicSourceMap,
): Array<BabelSourceMapSegment>;
declare function toSegmentTuple(
mapping: BabelSourceMapSegment,
): MetroSourceMapSegmentTuple;
export {
BundleBuilder,
composeSourceMaps,
Consumer,
createIndexMap,
generateFunctionMap,
fromRawMappings,
fromRawMappingsNonBlocking,
functionMapBabelPlugin,
normalizeSourcePath,
toBabelSegments,
toSegmentTuple,
};
/**
* 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.
*/
declare const $$EXPORT_DEFAULT_DECLARATION$$: {
BundleBuilder: typeof BundleBuilder;
composeSourceMaps: typeof composeSourceMaps;
Consumer: typeof Consumer;
createIndexMap: typeof createIndexMap;
generateFunctionMap: typeof generateFunctionMap;
fromRawMappings: typeof fromRawMappings;
fromRawMappingsNonBlocking: typeof fromRawMappingsNonBlocking;
functionMapBabelPlugin: typeof functionMapBabelPlugin;
normalizeSourcePath: typeof normalizeSourcePath;
toBabelSegments: typeof toBabelSegments;
toSegmentTuple: typeof toSegmentTuple;
};
declare type $$EXPORT_DEFAULT_DECLARATION$$ =
typeof $$EXPORT_DEFAULT_DECLARATION$$;
export default $$EXPORT_DEFAULT_DECLARATION$$;

210
node_modules/metro-source-map/src/source-map.js generated vendored Normal file
View File

@@ -0,0 +1,210 @@
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true,
});
Object.defineProperty(exports, "BundleBuilder", {
enumerable: true,
get: function () {
return _BundleBuilder.BundleBuilder;
},
});
Object.defineProperty(exports, "Consumer", {
enumerable: true,
get: function () {
return _Consumer.default;
},
});
Object.defineProperty(exports, "composeSourceMaps", {
enumerable: true,
get: function () {
return _composeSourceMaps.default;
},
});
Object.defineProperty(exports, "createIndexMap", {
enumerable: true,
get: function () {
return _BundleBuilder.createIndexMap;
},
});
exports.default = void 0;
exports.fromRawMappings = fromRawMappings;
exports.fromRawMappingsNonBlocking = fromRawMappingsNonBlocking;
Object.defineProperty(exports, "functionMapBabelPlugin", {
enumerable: true,
get: function () {
return _generateFunctionMap.functionMapBabelPlugin;
},
});
Object.defineProperty(exports, "generateFunctionMap", {
enumerable: true,
get: function () {
return _generateFunctionMap.generateFunctionMap;
},
});
Object.defineProperty(exports, "normalizeSourcePath", {
enumerable: true,
get: function () {
return _normalizeSourcePath.default;
},
});
exports.toBabelSegments = toBabelSegments;
exports.toSegmentTuple = toSegmentTuple;
var _BundleBuilder = require("./BundleBuilder");
var _composeSourceMaps = _interopRequireDefault(require("./composeSourceMaps"));
var _Consumer = _interopRequireDefault(require("./Consumer"));
var _normalizeSourcePath = _interopRequireDefault(
require("./Consumer/normalizeSourcePath"),
);
var _generateFunctionMap = require("./generateFunctionMap");
var _Generator = _interopRequireDefault(require("./Generator"));
var _sourceMap = _interopRequireDefault(require("source-map"));
function _interopRequireDefault(e) {
return e && e.__esModule ? e : { default: e };
}
function fromRawMappingsImpl(isBlocking, onDone, modules, offsetLines) {
const modulesToProcess = modules.slice();
const generator = new _Generator.default();
let carryOver = offsetLines;
function processNextModule() {
if (modulesToProcess.length === 0) {
return true;
}
const mod = modulesToProcess.shift();
const { code, map } = mod;
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) {
const diff = process.hrtime(time);
const NS_IN_MS = 1000000;
if (diff[1] > 50 * NS_IN_MS) {
setImmediate(workLoop);
break;
}
}
}
}
workLoop();
}
function fromRawMappings(modules, offsetLines = 0) {
let 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, offsetLines = 0) {
return new Promise((resolve) => {
fromRawMappingsImpl(false, resolve, modules, offsetLines);
});
}
function toBabelSegments(sourceMap) {
const rawMappings = [];
new _sourceMap.default.SourceMapConsumer(sourceMap).eachMapping((map) => {
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) {
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];
}
function addMappingsForFile(generator, mappings, module, carryOver) {
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, mapping, carryOver) {
const line = mapping[0] + carryOver;
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.match(newline) || []).length + 1;
var _default = (exports.default = {
BundleBuilder: _BundleBuilder.BundleBuilder,
composeSourceMaps: _composeSourceMaps.default,
Consumer: _Consumer.default,
createIndexMap: _BundleBuilder.createIndexMap,
generateFunctionMap: _generateFunctionMap.generateFunctionMap,
fromRawMappings,
fromRawMappingsNonBlocking,
functionMapBabelPlugin: _generateFunctionMap.functionMapBabelPlugin,
normalizeSourcePath: _normalizeSourcePath.default,
toBabelSegments,
toSegmentTuple,
});

372
node_modules/metro-source-map/src/source-map.js.flow generated vendored Normal file
View File

@@ -0,0 +1,372 @@
/**
* 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';
// $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;
export type HermesFunctionOffsets = {[number]: $ReadOnlyArray<number>, ...};
export type FBSourcesArray = $ReadOnlyArray<?FBSourceMetadata>;
export type FBSourceMetadata = [?FBSourceFunctionMap];
export type FBSourceFunctionMap = {
+names: $ReadOnlyArray<string>,
+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 = {
+file?: string,
+mappings: string,
+names: Array<string>,
+sourceRoot?: string,
+sources: Array<string>,
+sourcesContent?: Array<?string>,
+version: number,
+x_facebook_offsets?: Array<number>,
+x_metro_module_paths?: Array<string>,
+x_facebook_sources?: FBSourcesArray,
+x_facebook_segments?: FBSegmentMap,
+x_hermes_function_offsets?: HermesFunctionOffsets,
+x_google_ignoreList?: Array<number>,
};
export type IndexMapSection = {
map: IndexMap | BasicSourceMap,
offset: {
line: number,
column: number,
...
},
...
};
export type IndexMap = {
+file?: string,
+mappings?: void, // avoids SourceMap being a disjoint union
+sourcesContent?: void,
+sections: Array<IndexMapSection>,
+version: number,
+x_facebook_offsets?: Array<number>,
+x_metro_module_paths?: Array<string>,
+x_facebook_sources?: void,
+x_facebook_segments?: FBSegmentMap,
+x_hermes_function_offsets?: HermesFunctionOffsets,
+x_google_ignoreList?: void,
};
export type MixedSourceMap = IndexMap | BasicSourceMap;
type SourceMapConsumerMapping = {
generatedLine: number,
generatedColumn: number,
originalLine: ?number,
originalColumn: ?number,
source: ?string,
name: ?string,
};
function fromRawMappingsImpl(
isBlocking: boolean,
onDone: Generator => void,
modules: $ReadOnlyArray<{
+map: ?$ReadOnlyArray<MetroSourceMapSegmentTuple>,
+functionMap: ?FBSourceFunctionMap,
+path: string,
+source: string,
+code: string,
+isIgnored: boolean,
+lineCount?: number,
}>,
offsetLines: number,
): void {
const modulesToProcess = modules.slice();
const generator = new Generator();
let carryOver = offsetLines;
function processNextModule() {
if (modulesToProcess.length === 0) {
return true;
}
const mod = modulesToProcess.shift();
// $FlowFixMe[incompatible-use]
const {code, map} = mod;
if (Array.isArray(map)) {
// $FlowFixMe[incompatible-type]
addMappingsForFile(generator, map, mod, carryOver);
} else if (map != null) {
throw new Error(
// $FlowFixMe[incompatible-use]
`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<{
+map: ?$ReadOnlyArray<MetroSourceMapSegmentTuple>,
+functionMap: ?FBSourceFunctionMap,
+path: string,
+source: string,
+code: string,
+isIgnored: boolean,
+lineCount?: number,
}>,
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<{
+map: ?$ReadOnlyArray<MetroSourceMapSegmentTuple>,
+functionMap: ?FBSourceFunctionMap,
+path: string,
+source: string,
+code: string,
+isIgnored: boolean,
+lineCount?: number,
}>,
offsetLines: number = 0,
): Promise<Generator> {
return new Promise(resolve => {
fromRawMappingsImpl(false, resolve, modules, offsetLines);
});
}
/**
* 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];
}
function addMappingsForFile(
generator: Generator,
mappings: Array<MetroSourceMapSegmentTuple>,
module: {
+code: string,
+functionMap: ?FBSourceFunctionMap,
+map: ?Array<MetroSourceMapSegmentTuple>,
+path: string,
+source: string,
+isIgnored: boolean,
+lineCount?: number,
},
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;
export {
BundleBuilder,
composeSourceMaps,
Consumer,
createIndexMap,
generateFunctionMap,
fromRawMappings,
fromRawMappingsNonBlocking,
functionMapBabelPlugin,
normalizeSourcePath,
toBabelSegments,
toSegmentTuple,
};
/**
* 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,
};