fix(sourcemaps)!: preserve nullable source declarations

Accept absent map-level sourcesContent and preserve null source-name slots alongside known originals and aligned content. Represent unnamed local declarations explicitly, retain leaf-local and flattened indices, and preserve declared indexed-section order across consumers.

Account for added indices before browser output allocation. Accept legacy retained rows without indices. Consolidate public CLI/MCP source-map fixtures and update the stale named-source-only assertion.

BREAKING CHANGE: Browser source-map original and mapping rows expose null for unavailable source names instead of inventing an unknown-source string. New index fields are optional when reading older retained evidence.

Refs #2023, #2024
This commit is contained in:
morluto
2026-10-12 11:10:49 +08:00
parent c0904b4c1a
commit ee50ed121e
13 changed files with 361 additions and 70 deletions
@@ -539,6 +539,7 @@ const collectSourceMapOriginals = (
maps: readonly Readonly<Record<string, unknown>>[],
): JavaScriptSourceMapObservation => {
const sources: JavaScriptSourceMapOriginal[] = [];
let declarationIndex = 0;
for (const map of maps) {
const names = map.sources;
if (!Array.isArray(names))
@@ -556,7 +557,7 @@ const collectSourceMapOriginals = (
);
const root = typeof map.sourceRoot === "string" ? map.sourceRoot : null;
for (const [index, raw] of names.entries()) {
if (typeof raw !== "string")
if (raw !== null && typeof raw !== "string")
return invalidSourceMap(
file,
"Source map contains a non-string source name.",
@@ -564,7 +565,12 @@ const collectSourceMapOriginals = (
const rawContent = Array.isArray(contents) ? contents[index] : undefined;
const content = typeof rawContent === "string" ? rawContent : null;
sources.push({
reference: resolveJavaScriptSourceMapReference(raw, root, file.path),
source_index: index,
declaration_index: declarationIndex++,
reference:
typeof raw === "string"
? resolveJavaScriptSourceMapReference(raw, root, file.path)
: null,
content,
content_sha256: content === null ? null : sha256(content),
});
@@ -47,7 +47,11 @@ export interface JavaScriptHtmlScriptObservation {
/** One original source declared by a local source map. */
export interface JavaScriptSourceMapOriginal {
readonly reference: JavaScriptSourceMapReference;
/** Index within the leaf map's sources and sourcesContent arrays. */
readonly source_index: number;
/** Index across the flattened map's leaf declarations. */
readonly declaration_index: number;
readonly reference: JavaScriptSourceMapReference | null;
readonly content: string | null;
readonly content_sha256: string | null;
}
@@ -1,6 +1,7 @@
import {
addArtifactContainsEdge,
addStaticInferenceEdge,
artifactLocalIdentity,
createElectronRoleNode,
linkElectronRoleToAsset,
type JavaScriptArtifactGraphContext,
@@ -118,22 +119,34 @@ export const addJavaScriptSourceMapOriginals = (
if (mapFile === undefined || mapNode === undefined) continue;
const coverage = completeApplicationCoverage();
for (const original of sourceMap.sources) {
const reference = original.reference;
const node = context.accumulator.addNode({
kind: "source-module",
identity: {
strategy: "source-map-original",
stability: "source-map-exact",
source_map_sha256: mapFile.sha256,
original_source: original.reference.source_name,
source_root: original.reference.source_root,
source_sha256: original.content_sha256,
},
kind: reference === null ? "unknown" : "source-module",
identity:
reference === null
? artifactLocalIdentity(
mapFile.sha256,
"source-map-unnamed-declaration",
String(original.declaration_index),
)
: {
strategy: "source-map-original",
stability: "source-map-exact",
source_map_sha256: mapFile.sha256,
original_source: reference.source_name,
source_root: reference.source_root,
source_sha256: original.content_sha256,
},
observations: [
{
label: original.reference.source_name || null,
source_map_reference: original.reference,
label: reference?.source_name || null,
source_map_reference: reference,
properties: {
source_index: original.source_index,
declaration_index: original.declaration_index,
source_name_available: reference !== null,
content_available: original.content !== null,
content_sha256: original.content_sha256,
},
evidence: artifactObservationEvidence({
sha256: mapFile.sha256,
@@ -151,8 +164,10 @@ export const addJavaScriptSourceMapOriginals = (
target_node_id: node.node_id,
relation: "contains",
properties: {
original_source: original.reference.source_name,
source_root: original.reference.source_root,
source_index: original.source_index,
declaration_index: original.declaration_index,
original_source: reference?.source_name ?? null,
source_root: reference?.source_root ?? null,
},
evidence: artifactObservationEvidence({
sha256: mapFile.sha256,
+48 -17
View File
@@ -567,17 +567,21 @@ const normalizeSourceMap = (
const sourceJsonBytes = new Map<string, number>();
const nameJsonBytes = new Map<string, number>();
const originalSources: ParsedSourceMapItem["original_sources"] = [];
let declarationIndex = 0;
for (const { leaf, resolvedSources } of decoded) {
for (const [index, rawSource] of leaf.map.sources.entries()) {
if ((index & 255) === 0) check();
const resolved =
resolvedSources[index] ?? rawSource ?? "[unknown-source]";
const sanitized = cachedSanitized(sourcesByRaw, resolved);
rawSource === null ? null : (resolvedSources[index] ?? null);
const sanitized =
resolved === null ? null : cachedSanitized(sourcesByRaw, resolved);
const content = leaf.map.sourcesContent?.[index] ?? null;
consumeExpandedBytes(
context.budget,
cachedJsonBytes(sourceJsonBytes, sanitized) +
sourceEntryOverheadBytes() +
(sanitized === null
? 4
: cachedJsonBytes(sourceJsonBytes, sanitized)) +
sourceEntryOverheadBytes(index, declarationIndex) +
(originalSources.length === 0 ? 0 : 1) +
(content === null
? 0
@@ -586,6 +590,8 @@ const normalizeSourceMap = (
4),
);
originalSources.push({
source_index: index,
declaration_index: declarationIndex++,
source: sanitized,
artifact:
content === null
@@ -595,16 +601,21 @@ const normalizeSourceMap = (
}
}
const mappings: ParsedSourceMapItem["mappings"] = [];
for (const { leaf, rows, resolvedSources } of decoded)
declarationIndex = 0;
for (const { leaf, rows, resolvedSources } of decoded) {
const declarationBase = declarationIndex;
declarationIndex += leaf.map.sources.length;
for (const [line, row] of rows.entries()) {
if ((line & 255) === 0) check();
for (const segment of row) {
if (!isBeforeSourceMapLeafStop(leaf, line, segment[0])) continue;
if (segment.length === 1) continue;
const rawSource = leaf.map.sources[segment[1]];
if (rawSource === undefined) continue;
const resolved =
resolvedSources[segment[1]] ?? rawSource ?? "[unknown-source]";
const source = cachedSanitized(sourcesByRaw, resolved);
rawSource === null ? null : (resolvedSources[segment[1]] ?? null);
const source =
resolved === null ? null : cachedSanitized(sourcesByRaw, resolved);
const name =
segment.length === 5 ? (leaf.map.names[segment[4]] ?? null) : null;
const generatedLine = leaf.offset.line + line + 1;
@@ -612,9 +623,11 @@ const normalizeSourceMap = (
segment[0] + (line === 0 ? leaf.offset.column : 0);
consumeExpandedBytes(
context.budget,
cachedJsonBytes(sourceJsonBytes, source) +
(source === null ? 4 : cachedJsonBytes(sourceJsonBytes, source)) +
(name === null ? 4 : cachedJsonBytes(nameJsonBytes, name)) +
mappingRowBytes(
segment[1],
declarationBase + segment[1],
generatedLine,
generatedColumn,
segment[2] + 1,
@@ -623,6 +636,8 @@ const normalizeSourceMap = (
(mappings.length === 0 ? 0 : 1),
);
mappings.push({
source_index: segment[1],
declaration_index: declarationBase + segment[1],
generated_line: generatedLine,
generated_column: generatedColumn,
source,
@@ -632,6 +647,7 @@ const normalizeSourceMap = (
});
}
}
}
const modules = originalModuleEdges(originalSources, check, (edge) =>
consumeExpandedBytes(
context.budget,
@@ -705,15 +721,22 @@ const originalModuleEdges = (
for (const source of sources) {
check();
if (source.artifact === null) continue;
const sourceName = source.source;
if (sourceName === null) {
incomplete.push(
`unnamed source at declaration ${String(source.declaration_index)}`,
);
continue;
}
const parsed = parseJavaScriptSource(source.artifact.text);
check();
if (parsed === null) {
incomplete.push(source.source);
incomplete.push(sourceName);
continue;
}
// A recovered program still yields the imports it did parse, but nodes
// after an unrecoverable point are missing, so the edges are a subset.
if (parsed.errors.length > 0) incomplete.push(source.source);
if (parsed.errors.length > 0) incomplete.push(sourceName);
let unboundRequires: ReadonlySet<string> | undefined;
traverseJavaScriptAst(parsed, {
enter: (node) => {
@@ -742,14 +765,14 @@ const originalModuleEdges = (
)
return;
}
const key = `${source.source}\0${kind}\0${specifier}`;
const key = `${sourceName}\0${kind}\0${specifier}`;
if (seen.has(key)) return;
seen.add(key);
const edge = {
from_source: source.source,
from_source: sourceName,
kind,
specifier,
resolved_source: resolveOriginalSource(specifier, source.source),
resolved_source: resolveOriginalSource(specifier, sourceName),
};
beforeEdge(edge);
edges.push(edge);
@@ -840,7 +863,8 @@ const preflightResolvedSourceBytes = (
}
for (const source of map.sources) {
check();
const sourceKey = source ?? "";
if (source === null) continue;
const sourceKey = source;
let resolved = sourcesForRoot.get(sourceKey);
if (resolved === undefined)
resolved = resolveSourceMapSource(source, map.sourceRoot, mapUrl);
@@ -948,8 +972,13 @@ const sourceMapFailureReservation = (
jsonBytes(status) -
jsonBytes("fetch_failed");
const sourceEntryOverheadBytes = (): number =>
Buffer.byteLength('{"source":,"artifact":null}');
const sourceEntryOverheadBytes = (
sourceIndex: number,
declarationIndex: number,
): number =>
Buffer.byteLength(
`{"source_index":${String(sourceIndex)},"declaration_index":${String(declarationIndex)},"source":,"artifact":null}`,
);
const cachedJsonBytes = (cache: Map<string, number>, value: string): number => {
const cached = cache.get(value);
@@ -968,13 +997,15 @@ const cachedSanitized = (cache: Map<string, string>, value: string): string => {
};
const mappingRowBytes = (
sourceIndex: number,
declarationIndex: number,
generatedLine: number,
generatedColumn: number,
originalLine: number,
originalColumn: number,
): number =>
Buffer.byteLength(
`{"generated_line":${String(generatedLine)},"generated_column":${String(generatedColumn)},"source":,"original_line":${String(originalLine)},"original_column":${String(originalColumn)},"name":}`,
`{"source_index":${String(sourceIndex)},"declaration_index":${String(declarationIndex)},"generated_line":${String(generatedLine)},"generated_column":${String(generatedColumn)},"source":,"original_line":${String(originalLine)},"original_column":${String(originalColumn)},"name":}`,
);
const resolveOriginalSource = (
+11
View File
@@ -0,0 +1,11 @@
import { expect, it } from "vitest";
import { hasValidSourceMapContents } from "./sourceMapContents.js";
it("accepts absent map-level source contents and aligned nullable slots", () => {
expect(hasValidSourceMapContents(2, undefined)).toBe(true);
expect(hasValidSourceMapContents(2, null)).toBe(true);
expect(hasValidSourceMapContents(2, [null, "retained source"])).toBe(true);
expect(hasValidSourceMapContents(2, ["retained source"])).toBe(false);
expect(hasValidSourceMapContents(2, [null, 42])).toBe(false);
});
+1
View File
@@ -4,6 +4,7 @@ export const hasValidSourceMapContents = (
contents: unknown,
): boolean =>
contents === undefined ||
contents === null ||
(Array.isArray(contents) &&
contents.length === sourceCount &&
contents.every(
+23 -3
View File
@@ -14,11 +14,31 @@ describe("source-map envelope walk", () => {
const root = {
version: 3,
sections: [
{ offset: { line: 0, column: 0 }, map: leaf },
{ offset: { line: 10, column: 0 }, map: { ...leaf, sources: [] } },
{
offset: { line: 0, column: 0 },
map: {
version: 3,
sections: [
{
offset: { line: 0, column: 0 },
map: { ...leaf, sources: ["b.ts"] },
},
{
offset: { line: 1, column: 0 },
map: { ...leaf, sources: ["c.ts"] },
},
],
},
},
{
offset: { line: 10, column: 0 },
map: { ...leaf, sources: ["d.ts"] },
},
],
};
expect(flattenSourceMapLeaves(root)).toHaveLength(2);
expect(flattenSourceMapLeaves(root)?.map(({ sources }) => sources)).toEqual(
[["b.ts"], ["c.ts"], ["d.ts"]],
);
});
it("rejects sections without embedded maps", () => {
+2 -1
View File
@@ -37,7 +37,8 @@ export const flattenSourceMapLeaves = (
const map = pending.pop();
if (!isVersion3Map(map)) return undefined;
if (Array.isArray(map.sections)) {
for (const section of map.sections) {
for (let index = map.sections.length - 1; index >= 0; index -= 1) {
const section = map.sections[index];
if (!isRecord(section) || !isRecord(section.map)) return undefined;
pending.push(section.map);
}
+6 -2
View File
@@ -32,7 +32,9 @@ const findingSchema = z.object({
});
const originalSourceSchema = z.object({
source: z.string(),
source_index: z.number().int().min(0).optional(),
declaration_index: z.number().int().min(0).optional(),
source: z.string().nullable(),
artifact: webTextArtifactSchema.nullable(),
});
const originalModuleEdgeSchema = z.object({
@@ -42,9 +44,11 @@ const originalModuleEdgeSchema = z.object({
resolved_source: z.string().nullable(),
});
const sourceMapMappingSchema = z.object({
source_index: z.number().int().min(0).optional(),
declaration_index: z.number().int().min(0).optional(),
generated_line: z.number().int().min(1),
generated_column: z.number().int().min(0),
source: z.string(),
source: z.string().nullable(),
original_line: z.number().int().min(1),
original_column: z.number().int().min(0),
name: z.string().nullable(),