fix(source-maps): retain all candidates at shared section boundaries (#12026)

* fix(source-maps): retain mappings at shared section boundaries

* docs(source-maps): align boundary and decoder guidance

* test(source-maps): type named browser source-map leaves

---------

Co-authored-by: ShuaixinHuang <197200901+ShuaixinHuang@users.noreply.github.com>
This commit is contained in:
ShuaixinHuangandShuaixinHuang authored and GitHub committed 2026-11-18 09:42:28 -05:00
1 parent 0ba3b6049d
commit 919531c7c1
6 files changed
+267 -100

No files matched your search

@@ -220,6 +220,109 @@ describe("upstream source-map point evidence", () => {
});
});
describe("source-map section-boundary candidates", () => {
it.each([
{ mappings: "AAAAA", column: 0, nested: false },
{ mappings: "AAAAA,KAAAA", column: 5, nested: false },
{ mappings: "AAAAA;AAAAA", column: 0, nested: true },
])(
"retains all section-boundary candidates ($mappings, nested=$nested)",
({ mappings, column, nested }) => {
const first = {
...leaf,
sources: ["same.ts"],
sourcesContent: ["first"],
names: ["firstName"],
mappings,
};
const second = {
...leaf,
sources: ["same.ts"],
sourcesContent: ["second"],
names: ["secondName"],
mappings: "AAAAA",
};
const line = nested ? 1 : 0;
const report = trace(
{
version: 3,
sections: [
{ offset: { line: 0, column: 0 }, map: first },
{
offset: { line, column },
map: nested
? {
version: 3,
sections: [
{
offset: { line: 0, column: 0 },
map: second,
},
],
}
: second,
},
],
},
{ line: line + 1, column },
);
expect(report.lookup.matched_generated_position).toEqual({
line: line + 1,
column,
});
expect(report.matches).toMatchObject([
{
flattened_source_index: 0,
section_path: [0],
source_index: 0,
content: { text: "first" },
name: "firstName",
},
{
flattened_source_index: 1,
section_path: nested ? [1, 0] : [1],
source_index: 0,
content: { text: "second" },
name: "secondName",
},
]);
expect(report.matches).toHaveLength(2);
},
);
it.each([false, true])(
"keeps a generated-only section-boundary candidate (first=%s)",
(generatedOnlyFirst) => {
const generated = { version: 3, sources: [], names: [], mappings: "A" };
const first = generatedOnlyFirst ? generated : leaf;
const second = generatedOnlyFirst ? leaf : generated;
const report = trace(
{
version: 3,
sections: [
{
offset: { line: 0, column: 0 },
map: { ...first, mappings: `K${first.mappings.slice(1)}` },
},
{ offset: { line: 0, column: 5 }, map: second },
],
},
{ line: 1, column: 5 },
);
const mapped = {
state: "mapped",
flattened_source_index: 0,
section_path: [generatedOnlyFirst ? 1 : 0],
source_index: 0,
};
const generatedOnly = { state: "generated-only" };
expect(report.matches).toMatchObject(
generatedOnlyFirst ? [generatedOnly, mapped] : [mapped, generatedOnly],
);
expect(report.matches).toHaveLength(2);
},
);
});
describe("source-map layout admission", () => {
it.each(["AAAAC", "g", "!", "AA", "D"])(
"rejects malformed VLQ/components/indexes: %s",
+55 -82
View File
@@ -1,17 +1,11 @@
import { malformedInput } from "../../domain/parseFailure.js";
import {
WEB_SOURCE_MAP_LIMITS,
sourceMapLimitRecovery,
type SourceMapLimits,
} from "../../domain/sourceMapLimits.js";
import { createRequire } from "node:module";
import { getHeapStatistics } from "node:v8";
import {
AnyMap,
TraceMap,
decodedMappings,
type SourceMapSegment,
} from "@jridgewell/trace-mapping";
import type { TraceMap, SourceMapSegment } from "@jridgewell/trace-mapping";
import { z } from "zod";
import { javaScriptRuntime } from "../../domain/runtimeVersion.js";
import { javaScriptWorkerMemoryLimitBytes } from "../../process/JavaScriptWorkerMemoryLimit.js";
@@ -40,51 +34,34 @@ export const traceSourceMap = (
): WebSourceMapReport => {
const inspected = inspectSourceMap(text, { limits });
const decodedLeaves = decodeValidatedSourceMapLeaves(inspected.leaves, url);
let map: TraceMap;
if (inspected.format === "regular") {
const decoded = decodedLeaves[0];
if (decoded === undefined)
throw malformedInput(
SOURCE_MAP_FORMAT,
"Regular source map has no validated leaf.",
);
map = decoded.map;
} else {
map = new AnyMap(
{
version: 3,
sections: decodedLeaves.map(({ leaf, map: sectionMap }) => ({
offset: leaf.offset,
map: sectionMap,
})),
},
url,
);
}
const rows =
inspected.format === "regular"
? (decodedLeaves[0]?.rows ?? [])
: decodedMappings(map);
validateFlattenedRows(inspected, rows, map);
const matched = greatestPosition(rows, position);
const segments =
matched === null
? []
: (rows[matched.line - 1] ?? []).filter(
(segment) => segment[0] === matched.column,
);
const matched = greatestPosition(decodedLeaves, position);
let bytes = 0;
const matches: WebSourceMapReport["matches"] = [];
for (const segment of segments) {
const match = originalMatch(segment, map, url, inspected.declarations);
bytes += Buffer.byteLength(JSON.stringify(match)) + 1;
if (bytes > limits.outputBytes)
throw sourceMapLimitFailure(
`Complete source-map point evidence exceeds output admission; no partial evidence was returned.`,
"output_bytes",
limits.outputBytes,
);
matches.push(match);
let sourceBase = 0;
for (const { leaf, map, rows } of decodedLeaves) {
if (matched !== null) {
const line = matched.line - leaf.offset.line - 1;
const column = matched.column - (line === 0 ? leaf.offset.column : 0);
for (const segment of rows[line] ?? []) {
if (segment[0] !== column) continue;
const match = originalMatch(
segment,
map,
url,
inspected.declarations,
sourceBase,
);
bytes += Buffer.byteLength(JSON.stringify(match)) + 1;
if (bytes > limits.outputBytes)
throw sourceMapLimitFailure(
`Complete source-map point evidence exceeds output admission; no partial evidence was returned.`,
"output_bytes",
limits.outputBytes,
);
matches.push(match);
}
}
sourceBase += leaf.map.sources.length;
}
const metadata: unknown = createRequire(import.meta.url)(
"@jridgewell/trace-mapping/package.json",
@@ -129,49 +106,45 @@ export const traceSourceMap = (
});
};
const validateFlattenedRows = (
inspected: ReturnType<typeof inspectSourceMap>,
rows: ReturnType<typeof decodedMappings>,
map: ReturnType<typeof AnyMap>,
): void => {
for (const row of rows)
for (const segment of row) {
if (
(segment.length !== 1 && segment[1] >= inspected.declarations.length) ||
(segment.length === 5 && segment[4] >= map.names.length)
)
throw malformedInput(
SOURCE_MAP_FORMAT,
"Decoded mapping has invalid component count, position, source index or name index.",
);
}
};
/** Compare validated leaf positions without a second, clipping flatten operation. */
const greatestPosition = (
rows: ReturnType<typeof decodedMappings>,
leaves: ReturnType<typeof decodeValidatedSourceMapLeaves>,
position: WebSourcePosition,
): WebSourcePosition | null => {
for (
let line = Math.min(position.line - 1, rows.length - 1);
line >= 0;
line -= 1
) {
let column: number | undefined;
for (const segment of rows[line] ?? [])
if (line < position.line - 1 || segment[0] <= position.column)
column = segment[0];
if (column !== undefined) return { line: line + 1, column };
let matched: WebSourcePosition | null = null;
for (const { leaf, rows } of leaves) {
const localLine = position.line - leaf.offset.line - 1;
for (let line = Math.min(localLine, rows.length - 1); line >= 0; line--) {
let column: number | undefined;
for (const segment of rows[line] ?? []) {
const absoluteColumn =
segment[0] + (line === 0 ? leaf.offset.column : 0);
if (line < localLine || absoluteColumn <= position.column)
column = absoluteColumn;
}
if (column === undefined) continue;
const absoluteLine = leaf.offset.line + line + 1;
if (
matched === null ||
absoluteLine > matched.line ||
(absoluteLine === matched.line && column > matched.column)
)
matched = { line: absoluteLine, column };
break;
}
}
return null;
return matched;
};
const originalMatch = (
segment: Readonly<SourceMapSegment>,
map: TraceMap,
mapUrl: string,
declarations: readonly SourceMapSourceDeclaration[],
sourceBase: number,
): WebSourceMapReport["matches"][number] => {
if (segment.length === 1) return { state: "generated-only" };
const declaration = declarations[segment[1]];
const sourceIndex = sourceBase + segment[1];
const declaration = declarations[sourceIndex];
if (declaration === undefined)
throw malformedInput(
SOURCE_MAP_FORMAT,
@@ -184,7 +157,7 @@ const originalMatch = (
: webSourceOffset(declaration.content, original);
return {
state: "mapped",
flattened_source_index: segment[1],
flattened_source_index: sourceIndex,
section_path: [...declaration.sectionPath],
source_index: declaration.sourceIndex,
reported_source: declaration.source,