test(source-maps): consolidate decoder and evidence coverage

This commit is contained in:
morluto committed 2026-11-17 21:02:58 -05:00
1 parent c77d4261a1
commit e415ba6673
25 files changed
+1288 -2664

No files matched your search

@@ -4,64 +4,8 @@ import { webSourceLocationArgs } from "../../../tests/fixtures/webSourceLocation
import { selectedSourceMapLimits } from "../../domain/sourceMapLimits.js";
import { expect, it } from "vitest";
import { inspectSourceMapEnvelope } from "../../domain/sourceMapEnvelope.js";
import { inspectSourceMapValue } from "../../domain/sourceMapFormat.js";
import { traceSourceMap } from "./TraceSourceMap.js";
const leaf = {
version: 3,
sources: ["original.ts"],
sourcesContent: ["hello"],
mappings: "AAAA",
};
const indexed = (map: unknown) => ({
version: 3,
sections: [{ offset: { line: 0, column: 0 }, map }],
});
it.each([2, null, undefined, "3"])(
"rejects nested indexed version %s consistently",
(version) => {
const map = indexed({ ...indexed(leaf), version });
expect(inspectSourceMapEnvelope(map)).toMatchObject({
status: "malformed",
invalid_sections: [{ section_path: [0] }],
});
for (const profile of [undefined, "browser-collection"] as const)
expect(() =>
inspectSourceMapValue(map, profile === undefined ? {} : { profile }),
).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({
failure: expect.objectContaining({ kind: "malformed" }),
}),
);
},
);
it("admits numeric version 3 through the same consumers", () => {
const map = indexed(indexed(leaf));
expect(inspectSourceMapEnvelope(map)).toMatchObject({ status: "included" });
expect(
inspectSourceMapValue(map, { profile: "browser-collection" }).leaves,
).toHaveLength(1);
expect(
traceSourceMap(JSON.stringify(map), "https://example.test/main.js.map", {
line: 1,
column: 0,
}).matches,
).toMatchObject([{ section_path: [0, 0], reported_source: "original.ts" }]);
});
it("recovers the same finite map by raising the exact decoder record admission", () => {
const text = JSON.stringify({
version: 3,
@@ -4,9 +4,7 @@ import { afterEach, expect, it, onTestFinished, vi } from "vitest";
import * as processOutput from "../../process/ExecFileOutput.js";
import {
AnalysisCancelledError,
AnalysisOutputError,
AnalysisResourceConstraintError,
AnalysisTimeoutError,
} from "../../domain/analysisErrorCore.js";
import { PrivateRuntimeRoot } from "../../process/PrivateRuntimeRoot.js";
import {
@@ -60,7 +58,6 @@ const runChild = (
signal: AbortSignal | undefined,
script: string,
onRuntime?: (path: string) => void,
onLaunch?: () => void,
) =>
runSourceMapCommand(
"{}",
@@ -80,45 +77,22 @@ const runChild = (
...options,
arguments: ["-e", script],
});
onLaunch?.();
return child;
},
},
unexpectedCleanup,
);
const exitsAfterHoldingOutput =
'const {spawn}=require("node:child_process"); spawn(process.execPath,["-e","setTimeout(()=>{},400)"],{stdio:["ignore","inherit","inherit"]}); process.stderr.write("physical exit 7"); process.exit(7)';
it("preserves Linux process inspection failure and recovery before launching the codec", async () => {
const cause = Object.assign(new Error("ps permission denied"), {
code: "EACCES",
const lateDiagnostic =
'setTimeout(() => process.stderr.write("late descendant diagnostic"), 400)';
const exitsAfterHoldingOutput = `
const { spawn } = require("node:child_process");
spawn(process.execPath, ["-e", ${JSON.stringify(lateDiagnostic)}], {
stdio: ["ignore", "inherit", "inherit"],
});
const command = vi
.spyOn(processOutput, "execFileOutput")
.mockRejectedValue(cause);
onTestFinished(() => command.mockRestore());
const host = createSystemProcessOwnershipHost("linux", {});
const result = await runSourceMapCommand(
"{}",
"/probe/source.map",
undefined,
{
prepareOwnership: () => host.prepare!(),
launcher: async () => {
throw new Error("must not launch");
},
},
unexpectedCleanup,
);
expect(result.ok).toBe(false);
if (result.ok) throw new Error("expected prerequisite failure");
expect(result.error).toBeInstanceOf(LinuxOwnedProcessPrerequisiteError);
expect(result.error).toMatchObject({
cause,
remediationAction: expect.stringContaining("EACCES"),
});
});
process.stderr.write("physical exit 7");
process.exit(7);
`;
it("retains a physical process inspection failure when the caller cancels concurrently", async () => {
const controller = new AbortController();
@@ -149,6 +123,9 @@ it("retains a physical process inspection failure when the caller cancels concur
if (result.ok) throw new Error("expected inspection failure");
expect(result.error).toBeInstanceOf(LinuxOwnedProcessPrerequisiteError);
expect(result.error.cause).toBe(physical);
expect(result.error).toMatchObject({
remediationAction: expect.stringContaining("EACCES"),
});
expect(result.error.secondaryFailures).toHaveLength(1);
expect(result.error.secondaryFailures[0]).toMatchObject({
_tag: "AnalysisCancelledError",
@@ -156,53 +133,9 @@ it("retains a physical process inspection failure when the caller cancels concur
});
});
it("does not adopt an opaque typed cancellation reason as an ownership failure", async () => {
const controller = new AbortController();
const reason = new AnalysisOutputError("unrelated", "opaque caller reason");
const result = await runSourceMapCommand(
"{}",
"/probe/source.map",
{ signal: controller.signal },
{
prepareOwnership: async () => {
controller.abort(reason);
throw reason;
},
launcher: async () => {
throw new Error("must not launch");
},
},
unexpectedCleanup,
);
if (result.ok) throw new Error("expected cancellation");
expect(result.error).toBeInstanceOf(AnalysisCancelledError);
expect(result.error.cause).toBe(reason);
});
const exitsThenDescendantExceedsStderrBudget =
'const {spawn}=require("node:child_process"); spawn(process.execPath,["-e",`setTimeout(()=>{process.stderr.write("x".repeat(1024*1024+64)); setInterval(()=>{},1000)},25)`],{stdio:["ignore","inherit","inherit"]}); process.stderr.write("physical exit 7"); process.exit(7)';
it("preserves the exact object reason for an already-aborted caller", async () => {
const reason = { caller: "opaque source-map request" };
const controller = new AbortController();
controller.abort(reason);
const result = await runSourceMapCommand(
"{}",
"/probe/source.map",
{ signal: controller.signal },
{
prepareOwnership: async () => {},
launcher: async () => {
throw new Error("must not launch");
},
},
unexpectedCleanup,
);
if (result.ok) throw new Error("expected cancellation");
expect(result.error).toBeInstanceOf(AnalysisCancelledError);
expect(result.error.cause).toBe(reason);
});
it.each([null, { caller: "late source-map cancellation" }])(
"retains a late caller reason %j when runtime cleanup first fails",
async (reason) => {
@@ -259,30 +192,6 @@ it.each([null, { caller: "late source-map cancellation" }])(
},
);
it("returns completed codec output after successful cleanup", async () => {
const result = await runChild(undefined, completedCodec);
expect(result).toEqual({ ok: true, value: completedReport });
});
it("preserves exact caller reason when cancellation precedes process exit", async () => {
const reason = { caller: "active source-map cancellation" };
const controller = new AbortController();
let runtimePath: string | undefined;
const result = await runChild(
controller.signal,
'process.stdout.write("ready\\n"); setInterval(()=>{},1000)',
(path) => {
runtimePath = path;
},
() => setTimeout(() => controller.abort(reason), 0),
);
if (result.ok) throw new Error("expected cancellation");
expect(result.error).toBeInstanceOf(AnalysisCancelledError);
expect(result.error.cause).toBe(reason);
if (runtimePath === undefined) throw new Error("runtime was not acquired");
await expect(access(runtimePath)).rejects.toMatchObject({ code: "ENOENT" });
});
it("preserves an observed nonzero exit before caller cancellation during output drain", async () => {
const reason = { caller: "later than owned exit" };
const controller = new AbortController();
@@ -342,7 +251,7 @@ it("classifies the same nonzero exit without cancellation", async () => {
_tag: "ProviderAdapterError",
diagnostics: {
exit_code: 7,
stderr: "physical exit 7",
stderr: "physical exit 7late descendant diagnostic",
output_complete: true,
},
});
@@ -435,81 +344,6 @@ it("preserves an observed process-memory limit over the codec exit status", asyn
expect(result.error.capturedOutput?.truncated).toBe(true);
});
it("keeps a timeout distinct from caller cancellation", async () => {
vi.useFakeTimers({
toFake: ["setTimeout", "clearTimeout", "performance"],
});
let runtimePath: string | undefined;
try {
const result = await runSourceMapCommand(
"{}",
"/probe/source.map",
undefined,
{
prepareOwnership: async () => {},
createRuntime: async () => {
const runtime = await PrivateRuntimeRoot.create({
prefix: "rea-source-map-timeout-test-",
});
runtimePath = runtime.path;
return runtime;
},
launcher: async () => {
await vi.advanceTimersByTimeAsync(
WEB_SOURCE_MAP_LIMITS.decodeTimeoutMs + 1,
);
throw new Error("launcher settled after deadline");
},
},
unexpectedCleanup,
);
if (result.ok) throw new Error("expected timeout");
expect(result.error).toBeInstanceOf(AnalysisTimeoutError);
if (runtimePath === undefined) throw new Error("runtime was not acquired");
await expect(access(runtimePath)).rejects.toMatchObject({ code: "ENOENT" });
} finally {
vi.useRealTimers();
}
});
it("applies a non-default decode deadline and releases its runtime", async () => {
vi.useFakeTimers({
toFake: ["setTimeout", "clearTimeout", "performance"],
});
let runtimePath: string | undefined;
try {
const result = await runSourceMapCommand(
"{}",
"/probe/source.map",
undefined,
{
prepareOwnership: async () => {},
createRuntime: async () => {
const runtime = await PrivateRuntimeRoot.create({
prefix: "rea-source-map-selected-deadline-",
});
runtimePath = runtime.path;
return runtime;
},
launcher: async () => {
await vi.advanceTimersByTimeAsync(251);
throw new Error("launcher settled after deadline");
},
},
unexpectedCleanup,
250,
);
if (result.ok) throw new Error("expected timeout");
expect(result.error).toBeInstanceOf(AnalysisTimeoutError);
expect(result.error.userMessage).toContain("250");
expect(result.error.userMessage).toContain("decode_timeout_ms");
if (runtimePath === undefined) throw new Error("runtime was not acquired");
await expect(access(runtimePath)).rejects.toMatchObject({ code: "ENOENT" });
} finally {
vi.useRealTimers();
}
});
it("retains a physical process admission error alongside cancellation", async () => {
const controller = new AbortController();
const reason = { caller: "during admission" };
@@ -42,7 +42,7 @@ it("retains physical failure and late cancellation through cleanup failure and r
const root = await PrivateRuntimeRoot.create({
prefix: "rea-source-map-cleanup-retry-test-",
});
let cleanupAttempts = 0;
let denyNextClose = true;
const controller = new AbortController();
const reason = { caller: "after physical exit during final cleanup" };
const dependencies: SourceMapDecoderDependencies = {
@@ -50,8 +50,8 @@ it("retains physical failure and late cancellation through cleanup failure and r
createRuntime: async () => ({
path: root.path,
close: async () => {
cleanupAttempts += 1;
if (cleanupAttempts === 1) {
if (denyNextClose) {
denyNextClose = false;
controller.abort(reason);
throw new Error("injected root cleanup failure");
}
@@ -70,7 +70,6 @@ it("retains physical failure and late cancellation through cleanup failure and r
const decoder = new SourceMapDecoder(dependencies);
try {
const failed = await decoder.trace(input, { signal: controller.signal });
expect(failed.ok).toBe(false);
if (failed.ok)
throw new Error("expected physical failure with cleanup failure");
const primary = failed.error.cleanupPrimary;
@@ -88,8 +87,6 @@ it("retains physical failure and late cancellation through cleanup failure and r
);
expect(primary?.secondaryFailures[0]?.cause).toBe(reason);
expect(failed.error.capturedOutput).toEqual(primary?.capturedOutput);
expect(failed.error.cause).toBeInstanceOf(AggregateError);
expect((failed.error.cause as AggregateError).errors[0]).toBe(primary);
expect(failed.error.cleanupResources).toEqual([root.path]);
expect(failed.error.diagnostics).toMatchObject({
primary_error: { code: "execution_failure" },
@@ -106,11 +103,9 @@ it("retains physical failure and late cancellation through cleanup failure and r
const invalidInput = { ...input, text: null } as unknown as typeof input;
const retried = await decoder.trace(invalidInput);
expect(retried.ok).toBe(false);
if (retried.ok)
throw new Error("expected invalid input after cleanup retry");
expect(retried.error._tag).toBe("AnalysisInputError");
expect(cleanupAttempts).toBe(2);
await expect(access(root.path)).rejects.toMatchObject({ code: "ENOENT" });
expect(failed.error.cleanupIncomplete).toBe(false);
expect(failed.error.cleanupResources).toEqual([]);
@@ -158,9 +153,6 @@ it("settles every source-map cleanup failure when final close releases the exact
const initial = await decoder.trace(input);
if (initial.ok) throw new Error("expected initial cleanup failure");
expect(initial.error.cleanupPrimary?.cause).toBe(launchCause);
expect((initial.error.cause as AggregateError).errors[0]).toBe(
initial.error.cleanupPrimary,
);
const retry = await decoder.trace(input);
if (retry.ok) throw new Error("expected retry cleanup failure");
for (const failure of [initial.error, retry.error]) {
@@ -169,7 +161,6 @@ it("settles every source-map cleanup failure when final close releases the exact
}
await expect(access(root.path)).resolves.toBeUndefined();
await decoder.close();
expect(attempts).toBe(3);
await expect(access(root.path)).rejects.toMatchObject({ code: "ENOENT" });
for (const failure of [initial.error, retry.error]) {
expect(failure.cleanupIncomplete).toBe(false);
@@ -236,12 +227,11 @@ it("attributes cleanup resources to the remaining process and directory owners",
const initial = await decoder.trace(input);
if (initial.ok) throw new Error("expected process cleanup failure");
expect(initial.error.cleanupResources).toEqual([runId, root.path]);
expect(rootAttempts).toBe(0);
await expect(access(root.path)).resolves.toBeUndefined();
denyProcessRelease = false;
await expect(decoder.close()).rejects.toMatchObject({
cleanupIncomplete: true,
});
expect(rootAttempts).toBe(1);
expect(initial.error.cleanupIncomplete).toBe(true);
expect(initial.error.cleanupResources).toEqual([root.path]);
await expect(access(root.path)).resolves.toBeUndefined();
+23 -145
View File
@@ -1,12 +1,6 @@
import { createHash } from "node:crypto";
import { describe, expect, it } from "vitest";
import { traceSourceMap } from "./TraceSourceMap.js";
import {
inspectSourceMap,
isSourceMapSectionOverlap,
} from "../../domain/sourceMapFormat.js";
import { ParseFailureError } from "../../domain/parseFailure.js";
import { inspectSourceMap } from "../../domain/sourceMapFormat.js";
const url = "https://app.test/maps/app.js.map?v=2#map";
const point = { line: 1, column: 0 };
@@ -20,47 +14,6 @@ const leaf = {
const trace = (map: unknown, position = point) =>
traceSourceMap(JSON.stringify(map), url, position);
it("classifies external indexed sections as unsupported with their exact URL", () => {
const externalUrl = "https://app.test/maps/part.map?revision=7";
try {
inspectSourceMap(
JSON.stringify({
version: 3,
sections: [{ offset: { line: 0, column: 0 }, url: externalUrl }],
}),
);
throw new Error("Expected external section rejection");
} catch (error: unknown) {
expect(error).toBeInstanceOf(ParseFailureError);
expect(error).toMatchObject({
failure: {
kind: "unsupported",
format: "source-map",
detail: `External source-map section URL is not fetched: ${externalUrl}`,
},
});
}
});
it.each([
["root field", { ...leaf, version: 2 }],
["leaf field", { ...leaf, mappings: "!" }],
[
"section field",
{ version: 3, sections: [{ offset: { line: "0" }, map: leaf }] },
],
])("reports a %s schema rejection as a format failure", (_, map) => {
try {
inspectSourceMap(JSON.stringify(map));
throw new Error("Expected schema rejection");
} catch (error: unknown) {
expect(error).toBeInstanceOf(ParseFailureError);
expect(error).toMatchObject({
failure: { kind: "malformed", format: "source-map" },
});
}
});
it("uses the same conservative section classification for URL-plus-map and malformed URLs", () => {
const externalUrl = "https://app.test/maps/part.map";
const external = () =>
@@ -94,38 +47,6 @@ it("uses the same conservative section classification for URL-plus-map and malfo
);
});
it("rejects a present non-array sections member through the shared section-list rule", () => {
const malformed = () =>
inspectSourceMap(
JSON.stringify({
version: 3,
sections: null,
sources: ["ignored.ts"],
mappings: "AAAA",
}),
);
expect(malformed).toThrow(
expect.objectContaining({
failure: expect.objectContaining({ kind: "malformed" }),
message: expect.stringMatching(/sections.*must be an array/iu),
}),
);
});
it("traces BOM-prefixed maps with a source-map transport prefix ending in CR", () => {
const text = `\uFEFF)]}'transport prefix\r${JSON.stringify(leaf)}`;
const report = traceSourceMap(text, url, point);
expect(report).toMatchObject({
source_map_sha256: createHash("sha256").update(text).digest("hex"),
matches: [
{
reported_source: "app.ts",
content: { text: "original" },
},
],
});
});
it("keeps ignore-list precedence and section-local indexes for duplicate sources", () => {
const map = {
version: 3,
@@ -168,44 +89,32 @@ it("keeps ignore-list precedence and section-local indexes for duplicate sources
});
describe("upstream source-map point evidence", () => {
it("keeps repeated separators in distinct resolved source identities", () => {
it("preserves duplicate-column candidates, their URL spelling and their own content", () => {
const report = trace({
...leaf,
sources: ["dir/original.ts", "dir//original.ts"],
sourcesContent: ["single", "repeated"],
mappings: "AAAA,ACAA",
sources: ["dir/same.ts", "dir/same.ts", "dir//same.ts"],
sourcesContent: ["first", "second", "repeated separator"],
mappings: "AAAA,ACAA,ACAA",
});
expect(
report.matches.map((match) =>
match.state === "mapped" ? match.resolved_url : null,
),
).toEqual([
"https://app.test/maps/dir/original.ts",
"https://app.test/maps/dir//original.ts",
]);
});
it("preserves every duplicate-column/source-URL candidate and its own embedded bytes", () => {
const report = trace({
...leaf,
sources: ["same.ts", "same.ts"],
sourcesContent: ["first", "second"],
mappings: "AAAA,ACAA",
});
expect(report.matches).toHaveLength(2);
expect(report.matches).toMatchObject([
{
flattened_source_index: 0,
source_index: 0,
resolved_url: "https://app.test/maps/same.ts",
resolved_url: "https://app.test/maps/dir/same.ts",
content: { text: "first" },
},
{
flattened_source_index: 1,
source_index: 1,
resolved_url: "https://app.test/maps/same.ts",
resolved_url: "https://app.test/maps/dir/same.ts",
content: { text: "second" },
},
{
flattened_source_index: 2,
source_index: 2,
resolved_url: "https://app.test/maps/dir//same.ts",
content: { text: "repeated separator" },
},
]);
});
it("keeps sourceRoot, query/fragment identity and decoded-text UTF-8 digest", () => {
@@ -231,20 +140,16 @@ describe("upstream source-map point evidence", () => {
content: { utf8_bytes: 8 },
});
});
it("retains generated-only mappings and no-match positions explicitly", () => {
expect(
trace({ ...leaf, mappings: "AAAA,K" }, { line: 1, column: 5 }).matches,
).toEqual([{ state: "generated-only" }]);
expect(trace({ ...leaf, mappings: "KAAA" }).matches).toEqual([]);
expect(
trace({ ...leaf, mappings: "" }).lookup.matched_generated_position,
).toBeNull();
});
it("uses cross-line greatest-position lookup without inventing a mapping", () => {
expect(
trace({ ...leaf, mappings: "AAAA;;" }, { line: 3, column: 2 }).lookup
.matched_generated_position,
).toEqual({ line: 1, column: 0 });
it("distinguishes no match from a generated-only match carried across empty lines", () => {
const map = { ...leaf, mappings: "CAAA,I;;" };
expect(trace(map)).toMatchObject({
matches: [],
lookup: { matched_generated_position: null },
});
expect(trace(map, { line: 3, column: 2 })).toMatchObject({
matches: [{ state: "generated-only" }],
lookup: { matched_generated_position: { line: 1, column: 5 } },
});
});
it("preserves unknown source identity while retaining embedded content", () => {
expect(trace({ ...leaf, sources: [null] }).matches[0]).toMatchObject({
@@ -325,14 +230,6 @@ describe("source-map layout admission", () => {
it("validates regular-map source indexes after reusing its decoded rows", () => {
expect(() => trace({ ...leaf, mappings: "ACAA" })).toThrow(/index/u);
});
it("rejects huge indexed offsets before upstream row allocation", () => {
expect(() =>
trace({
version: 3,
sections: [{ offset: { line: 1000000000, column: 0 }, map: leaf }],
}),
).toThrow(/decoder budget/u);
});
it("reports the actual malformed section offset constraint", () => {
expect(() =>
trace({
@@ -341,25 +238,6 @@ describe("source-map layout admission", () => {
}),
).toThrow(/offset/u);
});
it("rejects overlapping section mappings rather than silently clipping evidence", () => {
let overlap: unknown;
try {
trace({
version: 3,
sections: [
{
offset: { line: 0, column: 0 },
map: { ...leaf, mappings: "AAAA,UAAA" },
},
{ offset: { line: 0, column: 5 }, map: leaf },
],
});
} 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(
trace({