refactor(source-maps): report decoder failures through ParseFailure (#10690)

SourceMapFormatFailure and its format/unsupported/limit/section-overlap reasons are replaced by ParseFailureError with format source-map. Limits carry the selected allowance name and maximum; a section-boundary overlap is a malformed failure on the section-boundary field. The codec reply protocol and every public error are unchanged.
This commit is contained in:
morluto authored and GitHub committed 2026-11-15 09:36:58 +08:00
1 parent 6f19681551
commit 133e7762b6
8 files changed
+203 -114

No files matched your search

@@ -1,6 +1,8 @@
import { malformedInput } from "../../domain/parseFailure.js";
import { TraceMap, decodedMappings } from "@jridgewell/trace-mapping";
import {
SourceMapFormatFailure,
SOURCE_MAP_FORMAT,
sourceMapSectionOverlap,
type SourceMapLeaf,
} from "./SourceMapFormat.js";
@@ -40,8 +42,7 @@ export const decodeValidatedSourceMapLeaves = (
const generatedColumn =
segment[0] + (line === 0 ? leaf.offset.column : 0);
if (!isBeforeSourceMapLeafStop(leaf, line, segment[0]))
throw new SourceMapFormatFailure(
"section-overlap",
throw sourceMapSectionOverlap(
"Embedded source-map mappings overlap the following section boundary.",
);
if (
@@ -52,8 +53,8 @@ export const decodeValidatedSourceMapLeaves = (
(segment.length !== 1 && segment[1] >= leaf.map.sources.length) ||
(segment.length === 5 && segment[4] >= leaf.map.names.length)
)
throw new SourceMapFormatFailure(
"format",
throw malformedInput(
SOURCE_MAP_FORMAT,
"Decoded local or absolute position, source index or name index is invalid.",
);
}
@@ -30,13 +30,21 @@ it.each([2, null, undefined, "3"])(
for (const profile of [undefined, "browser-collection"] as const)
expect(() =>
inspectSourceMapValue(map, profile === undefined ? {} : { profile }),
).toThrow(expect.objectContaining({ reason: "format" }));
).toThrow(
expect.objectContaining({
failure: expect.objectContaining({ kind: "malformed" }),
}),
);
expect(() =>
traceSourceMap(JSON.stringify(map), "https://example.test/main.js.map", {
line: 1,
column: 0,
}),
).toThrow(expect.objectContaining({ reason: "format" }));
).toThrow(
expect.objectContaining({
failure: expect.objectContaining({ kind: "malformed" }),
}),
);
},
);
@@ -72,10 +80,14 @@ it("recovers the same finite map by raising the exact decoder record admission",
),
).toThrow(
expect.objectContaining({
reason: "limit",
message: expect.stringContaining(
"source_map_limits.decoded_records is 4",
),
failure: expect.objectContaining({
kind: "limit",
format: "source-map",
limit: { name: "decoded_records", maximum: 4 },
detail: expect.stringContaining(
"source_map_limits.decoded_records is 4",
),
}),
}),
);
expect(
@@ -5,7 +5,12 @@ import {
sourceMapLimitsSchema,
} from "../../domain/sourceMapLimits.js";
import { traceSourceMap } from "./TraceSourceMap.js";
import { SourceMapFormatFailure } from "./SourceMapFormat.js";
import {
isSourceMapFailure,
SOURCE_MAP_FORMAT,
sourceMapLimitFailure,
} from "./SourceMapFormat.js";
import { malformedInput } from "../../domain/parseFailure.js";
import {
sourceMapCodecInputSchema,
sourceMapCodecReplySchema,
@@ -17,10 +22,7 @@ const execute = async (): Promise<string> => {
try {
const path = process.argv[2];
if (path === undefined)
throw new SourceMapFormatFailure(
"format",
"Codec request path is missing.",
);
throw malformedInput(SOURCE_MAP_FORMAT, "Codec request path is missing.");
const selected = sourceMapLimitsSchema.parse(
JSON.parse(process.argv[3] ?? "{}"),
);
@@ -30,9 +32,10 @@ const execute = async (): Promise<string> => {
const value: unknown = JSON.parse(text);
const input = sourceMapCodecInputSchema.parse(value);
if (Buffer.byteLength(input.text) > limits.mapBytes)
throw new SourceMapFormatFailure(
"limit",
`Source map exceeds codec input admission. ${sourceMapLimitRecovery("map_bytes", limits.mapBytes)}`,
throw sourceMapLimitFailure(
`Source map exceeds codec input admission.`,
"map_bytes",
limits.mapBytes,
);
const report = traceSourceMap(
input.text,
@@ -44,15 +47,16 @@ const execute = async (): Promise<string> => {
sourceMapCodecReplySchema.parse({ state: "success", report }),
);
if (Buffer.byteLength(reply) > limits.outputBytes)
throw new SourceMapFormatFailure(
"limit",
`Complete source-map point evidence exceeds output admission; no partial evidence was returned. ${sourceMapLimitRecovery("output_bytes", limits.outputBytes)}`,
throw sourceMapLimitFailure(
`Complete source-map point evidence exceeds output admission; no partial evidence was returned.`,
"output_bytes",
limits.outputBytes,
);
return reply;
} catch (cause: unknown) {
if (
!(
cause instanceof SourceMapFormatFailure ||
isSourceMapFailure(cause) ||
cause instanceof z.ZodError ||
cause instanceof SyntaxError
)
@@ -61,10 +65,11 @@ const execute = async (): Promise<string> => {
return JSON.stringify({
state: "failure",
reason:
cause instanceof SourceMapFormatFailure &&
cause.reason !== "section-overlap"
? cause.reason
: "format",
!isSourceMapFailure(cause) ||
cause.kind === "malformed" ||
cause.kind === "truncated"
? "format"
: cause.kind,
message: cause.message,
});
}
+99 -44
View File
@@ -2,8 +2,15 @@ import { z } from "zod";
import {
WEB_SOURCE_MAP_LIMITS,
sourceMapLimitRecovery,
type SourceMapLimitSelection,
type SourceMapLimits,
} from "../../domain/sourceMapLimits.js";
import {
malformedInput,
ParseFailureError,
type ParseFailureKind,
unsupportedInput,
} from "../../domain/parseFailure.js";
import {
classifySourceMapSection,
classifySourceMapSections,
@@ -57,15 +64,48 @@ export interface SourceMapStructureOptions {
readonly check?: () => void;
}
/** A decoder-profile failure with an actionable producer constraint. */
export class SourceMapFormatFailure extends Error {
constructor(
readonly reason: "format" | "unsupported" | "limit" | "section-overlap",
message: string,
) {
super(message);
}
}
/** The ParseFailure format of source maps and their indexed sections. */
export const SOURCE_MAP_FORMAT = "source-map";
/** The ParseFailure field of embedded mappings that cross a section boundary. */
const SECTION_BOUNDARY = "section-boundary";
/** A source-map decoder failure; any other cause is not one. */
export const isSourceMapFailure = (
cause: unknown,
): cause is ParseFailureError =>
cause instanceof ParseFailureError &&
cause.failure.format === SOURCE_MAP_FORMAT;
/** A caller-selectable source-map allowance refused the input. */
export const isSourceMapLimit = (
cause: unknown,
): cause is ParseFailureError<"limit"> =>
isSourceMapFailure(cause) && cause.failure.kind === "limit";
/** Embedded mappings overlap the following section; its message is public. */
export const isSourceMapSectionOverlap = (
cause: unknown,
): cause is ParseFailureError<"malformed"> =>
isSourceMapFailure(cause) && cause.failure.field === SECTION_BOUNDARY;
export const sourceMapSectionOverlap = (
detail: string,
): ParseFailureError<"malformed"> =>
malformedInput(SOURCE_MAP_FORMAT, detail, { field: SECTION_BOUNDARY });
/** The selected allowance `name` stopped decoding; the detail names its recovery. */
export const sourceMapLimitFailure = (
summary: string,
name: keyof SourceMapLimitSelection,
maximum: number,
): ParseFailureError<"limit"> =>
new ParseFailureError({
kind: "limit",
format: SOURCE_MAP_FORMAT,
detail: `${summary} ${sourceMapLimitRecovery(name, maximum)}`,
limit: { name, maximum },
});
/** Report schema rejection through the one failure type consumers classify. */
const parseStructure = <Schema extends z.ZodType>(
@@ -74,7 +114,7 @@ const parseStructure = <Schema extends z.ZodType>(
): z.output<Schema> => {
const parsed = schema.safeParse(value);
if (parsed.success) return parsed.data;
throw new SourceMapFormatFailure("format", parsed.error.message);
throw malformedInput(SOURCE_MAP_FORMAT, parsed.error.message);
};
/** Raw declaration identity, separate from flattened engine URL identity. */
@@ -127,9 +167,10 @@ const addOffset = (
!Number.isSafeInteger(result.column) ||
result.line >= limits.decodedRows
)
throw new SourceMapFormatFailure(
"limit",
`Indexed offset exceeds the generated-row decoder budget. ${sourceMapLimitRecovery("decoded_rows", limits.decodedRows)}`,
throw sourceMapLimitFailure(
`Indexed offset exceeds the generated-row decoder budget.`,
"decoded_rows",
limits.decodedRows,
);
return result;
};
@@ -140,9 +181,10 @@ const consumeRecords = (
count: number,
): void => {
if (count > limits.decodedRecords - budget.records)
throw new SourceMapFormatFailure(
"limit",
`Source-map structure exceeds the decoder budget. ${sourceMapLimitRecovery("decoded_records", limits.decodedRecords)}`,
throw sourceMapLimitFailure(
`Source-map structure exceeds the decoder budget.`,
"decoded_records",
limits.decodedRecords,
);
budget.records += count;
};
@@ -172,19 +214,19 @@ const addSections = ({
if ((index & 255) === 0) options.check?.();
const previous = sections[index - 1];
if (previous !== undefined && compare(section.offset, previous.offset) < 0)
throw new SourceMapFormatFailure(
"format",
throw malformedInput(
SOURCE_MAP_FORMAT,
"Indexed section offsets must be in nondecreasing order.",
);
const classification = classifySourceMapSection(section);
if (classification.kind === "external")
throw new SourceMapFormatFailure(
"unsupported",
throw unsupportedInput(
SOURCE_MAP_FORMAT,
`External source-map section URL is not fetched: ${classification.url}`,
);
if (classification.kind === "invalid")
throw new SourceMapFormatFailure(
"format",
throw malformedInput(
SOURCE_MAP_FORMAT,
`${classification.reason} Section path: ${JSON.stringify([...node.path, index])}.`,
);
embeddedMaps.push(classification.map);
@@ -194,8 +236,8 @@ const addSections = ({
if (section === undefined) continue;
const map = embeddedMaps[index];
if (map === undefined)
throw new SourceMapFormatFailure(
"format",
throw malformedInput(
SOURCE_MAP_FORMAT,
"Validated indexed section map is unavailable.",
);
const next = sections[index + 1];
@@ -230,13 +272,13 @@ const inspectMappingLayout = (
let digits = 0;
const finish = (): void => {
if (continued)
throw new SourceMapFormatFailure(
"format",
throw malformedInput(
SOURCE_MAP_FORMAT,
"Source-map VLQ ends with an unfinished continuation.",
);
if (inSegment && ![1, 4, 5].includes(components))
throw new SourceMapFormatFailure(
"format",
throw malformedInput(
SOURCE_MAP_FORMAT,
"Source-map segment requires one, four or five VLQ components.",
);
};
@@ -254,8 +296,8 @@ const inspectMappingLayout = (
(digits === 7 && !/[A-Dg-j]/u.test(character)) ||
(digits > 7 && character !== "A" && character !== "g")
)
throw new SourceMapFormatFailure(
"format",
throw malformedInput(
SOURCE_MAP_FORMAT,
"Source-map VLQ exceeds the format's 32-bit quantity representation.",
);
if (!inSegment) segments += 1;
@@ -267,9 +309,12 @@ const inspectMappingLayout = (
}
}
if (segments > limits.decodedSegments || lines > limits.decodedRows)
throw new SourceMapFormatFailure(
"limit",
`Source-map layout exceeds decoder admission. ${sourceMapLimitRecovery(segments > limits.decodedSegments ? "decoded_segments" : "decoded_rows", segments > limits.decodedSegments ? limits.decodedSegments : limits.decodedRows)}`,
throw sourceMapLimitFailure(
`Source-map layout exceeds decoder admission.`,
segments > limits.decodedSegments ? "decoded_segments" : "decoded_rows",
segments > limits.decodedSegments
? limits.decodedSegments
: limits.decodedRows,
);
}
finish();
@@ -313,9 +358,14 @@ const inspectLeaf = (
layout.segments > limits.decodedSegments ||
node.offset.line + layout.lines > limits.decodedRows
)
throw new SourceMapFormatFailure(
"limit",
`Source-map layout exceeds decoder admission. ${sourceMapLimitRecovery(layout.segments > limits.decodedSegments ? "decoded_segments" : "decoded_rows", layout.segments > limits.decodedSegments ? limits.decodedSegments : limits.decodedRows)}`,
throw sourceMapLimitFailure(
`Source-map layout exceeds decoder admission.`,
layout.segments > limits.decodedSegments
? "decoded_segments"
: "decoded_rows",
layout.segments > limits.decodedSegments
? limits.decodedSegments
: limits.decodedRows,
);
return leaf;
};
@@ -354,13 +404,14 @@ export const inspectSourceMapValue = (
const node = pending.pop();
if (node === undefined) break;
if (node.path.length > limits.sectionDepth)
throw new SourceMapFormatFailure(
"limit",
`Indexed source-map nesting exceeds decoder admission. ${sourceMapLimitRecovery("section_depth", limits.sectionDepth)}`,
throw sourceMapLimitFailure(
`Indexed source-map nesting exceeds decoder admission.`,
"section_depth",
limits.sectionDepth,
);
const sections = classifySourceMapSections(node.value);
if (sections.kind === "invalid")
throw new SourceMapFormatFailure("format", sections.reason);
throw malformedInput(SOURCE_MAP_FORMAT, sections.reason);
if (sections.kind === "indexed") {
addSections({
node,
@@ -452,7 +503,7 @@ export const inspectSourceMapSourceContent = (
| {
readonly embedded: boolean;
readonly complete: false;
readonly failure: SourceMapFormatFailure;
readonly failure: ParseFailureError;
} => {
options.check?.();
let value: unknown;
@@ -463,7 +514,11 @@ export const inspectSourceMapSourceContent = (
return {
embedded: false,
complete: false,
failure: new SourceMapFormatFailure("format", cause.message),
failure: new ParseFailureError<ParseFailureKind>({
kind: "malformed",
format: SOURCE_MAP_FORMAT,
detail: cause.message,
}),
};
}
const hasContent = (
@@ -479,7 +534,7 @@ export const inspectSourceMapSourceContent = (
complete: true,
};
} catch (failure) {
if (!(failure instanceof SourceMapFormatFailure)) throw failure;
if (!isSourceMapFailure(failure)) throw failure;
const budget = { records: 0 };
let embedded = false;
for (const leaf of boundedSourceMapLeaves(value, options)) {
@@ -487,7 +542,7 @@ export const inspectSourceMapSourceContent = (
const inspected = inspectSourceMapValue(leaf, { ...options, budget });
embedded ||= hasContent(inspected);
} catch (cause) {
if (!(cause instanceof SourceMapFormatFailure)) throw cause;
if (!isSourceMapFailure(cause)) throw cause;
// An unresolved leaf cannot discard content observed in valid siblings.
}
}
@@ -2,7 +2,11 @@ import { createHash } from "node:crypto";
import { describe, expect, it } from "vitest";
import { traceSourceMap } from "./TraceSourceMap.js";
import { inspectSourceMap, SourceMapFormatFailure } from "./SourceMapFormat.js";
import {
inspectSourceMap,
isSourceMapSectionOverlap,
} from "./SourceMapFormat.js";
import { ParseFailureError } from "../../domain/parseFailure.js";
const url = "https://app.test/maps/app.js.map?v=2#map";
const point = { line: 1, column: 0 };
@@ -27,10 +31,13 @@ it("classifies external indexed sections as unsupported with their exact URL", (
);
throw new Error("Expected external section rejection");
} catch (error: unknown) {
expect(error).toBeInstanceOf(SourceMapFormatFailure);
expect(error).toBeInstanceOf(ParseFailureError);
expect(error).toMatchObject({
reason: "unsupported",
message: `External source-map section URL is not fetched: ${externalUrl}`,
failure: {
kind: "unsupported",
format: "source-map",
detail: `External source-map section URL is not fetched: ${externalUrl}`,
},
});
}
});
@@ -47,8 +54,10 @@ it.each([
inspectSourceMap(JSON.stringify(map));
throw new Error("Expected schema rejection");
} catch (error: unknown) {
expect(error).toBeInstanceOf(SourceMapFormatFailure);
expect(error).toMatchObject({ reason: "format" });
expect(error).toBeInstanceOf(ParseFailureError);
expect(error).toMatchObject({
failure: { kind: "malformed", format: "source-map" },
});
}
});
@@ -65,7 +74,7 @@ it("uses the same conservative section classification for URL-plus-map and malfo
);
expect(external).toThrow(
expect.objectContaining({
reason: "unsupported",
failure: expect.objectContaining({ kind: "unsupported" }),
message: `External source-map section URL is not fetched: ${externalUrl}`,
}),
);
@@ -79,7 +88,7 @@ it("uses the same conservative section classification for URL-plus-map and malfo
);
expect(malformed).toThrow(
expect.objectContaining({
reason: "format",
failure: expect.objectContaining({ kind: "malformed" }),
message: expect.stringMatching(/section URL.*must be a string.*\[0\]/iu),
}),
);
@@ -97,7 +106,7 @@ it("rejects a present non-array sections member through the shared section-list
);
expect(malformed).toThrow(
expect.objectContaining({
reason: "format",
failure: expect.objectContaining({ kind: "malformed" }),
message: expect.stringMatching(/sections.*must be an array/iu),
}),
);
@@ -333,7 +342,8 @@ describe("source-map layout admission", () => {
).toThrow(/offset/u);
});
it("rejects overlapping section mappings rather than silently clipping evidence", () => {
expect(() =>
let overlap: unknown;
try {
trace({
version: 3,
sections: [
@@ -343,8 +353,12 @@ describe("source-map layout admission", () => {
},
{ offset: { line: 0, column: 5 }, map: leaf },
],
}),
).toThrow(expect.objectContaining({ reason: "section-overlap" }));
});
} catch (cause) {
overlap = cause;
}
expect(isSourceMapSectionOverlap(overlap)).toBe(true);
expect(overlap).toMatchObject({ failure: { kind: "malformed" } });
});
it("accepts absent optional names and null contents without changing reported identity", () => {
expect(
+13 -10
View File
@@ -1,3 +1,4 @@
import { malformedInput } from "../../domain/parseFailure.js";
import {
WEB_SOURCE_MAP_LIMITS,
sourceMapLimitRecovery,
@@ -24,7 +25,8 @@ import {
import type { WebSourcePosition } from "../../domain/webSourcePosition.js";
import {
inspectSourceMap,
SourceMapFormatFailure,
SOURCE_MAP_FORMAT,
sourceMapLimitFailure,
type SourceMapSourceDeclaration,
} from "./SourceMapFormat.js";
import { decodeValidatedSourceMapLeaves } from "./DecodedSourceMap.js";
@@ -42,8 +44,8 @@ export const traceSourceMap = (
if (inspected.format === "regular") {
const decoded = decodedLeaves[0];
if (decoded === undefined)
throw new SourceMapFormatFailure(
"format",
throw malformedInput(
SOURCE_MAP_FORMAT,
"Regular source map has no validated leaf.",
);
map = decoded.map;
@@ -77,9 +79,10 @@ export const traceSourceMap = (
const match = originalMatch(segment, map, url, inspected.declarations);
bytes += Buffer.byteLength(JSON.stringify(match)) + 1;
if (bytes > limits.outputBytes)
throw new SourceMapFormatFailure(
"limit",
`Complete source-map point evidence exceeds output admission; no partial evidence was returned. ${sourceMapLimitRecovery("output_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);
}
@@ -137,8 +140,8 @@ const validateFlattenedRows = (
(segment.length !== 1 && segment[1] >= inspected.declarations.length) ||
(segment.length === 5 && segment[4] >= map.names.length)
)
throw new SourceMapFormatFailure(
"format",
throw malformedInput(
SOURCE_MAP_FORMAT,
"Decoded mapping has invalid component count, position, source index or name index.",
);
}
@@ -170,8 +173,8 @@ const originalMatch = (
if (segment.length === 1) return { state: "generated-only" };
const declaration = declarations[segment[1]];
if (declaration === undefined)
throw new SourceMapFormatFailure(
"format",
throw malformedInput(
SOURCE_MAP_FORMAT,
"Mapping references an absent source declaration.",
);
const original = { line: segment[2] + 1, column: segment[3] };