import { z } from "zod"; import { WEB_SOURCE_MAP_LIMITS, sourceMapLimitRecovery, type SourceMapLimitSelection, type SourceMapLimits, } from "./sourceMapLimits.js"; import { malformedInput, ParseFailureError, type ParseFailureKind, unsupportedInput, } from "./parseFailure.js"; import { classifySourceMapSection, classifySourceMapSections, sourceMapJsonText, sourceMapMappingsSchema, } from "./sourceMapEnvelope.js"; import type { SourceMapSection } from "./sourceMapEnvelope.js"; import type { EncodedSourceMapXInput } from "@jridgewell/trace-mapping"; const leafSchema = z.object({ version: z.literal(3), file: z.string().nullable().optional(), sourceRoot: z.string().nullable().optional(), sources: z.array(z.string().nullable()), sourcesContent: z.array(z.string().nullable()).nullable().optional(), names: z.array(z.string()).default([]), mappings: sourceMapMappingsSchema.regex(/^[A-Za-z0-9+/,;]*$/u), ignoreList: z.array(z.int().min(0)).optional(), x_google_ignoreList: z.array(z.int().min(0)).optional(), }); const mapHeaderSchema = z.object({ version: z.literal(3), file: z.string().nullable().optional(), sections: z.unknown().optional(), }); const sectionSchema = z.object({ offset: z.object({ line: z.int().min(0).max(Number.MAX_SAFE_INTEGER), column: z.int().min(0).max(Number.MAX_SAFE_INTEGER), }), map: z.unknown().optional(), url: z.unknown().optional(), }); type Offset = { readonly line: number; readonly column: number }; interface PendingMap { readonly value: unknown; readonly path: readonly number[]; readonly offset: Offset; readonly stop: Offset | null; } /** Aggregate structural work shared by maps in one selected inspection. */ export interface SourceMapStructureBudget { records: number; } export interface SourceMapStructureOptions { readonly profile?: "browser-collection"; readonly limits?: SourceMapLimits; readonly budget?: SourceMapStructureBudget; readonly check?: () => void; } /** 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: Schema, value: unknown, ): z.output => { const parsed = schema.safeParse(value); if (parsed.success) return parsed.data; throw malformedInput(SOURCE_MAP_FORMAT, parsed.error.message); }; /** Raw declaration identity, separate from flattened engine URL identity. */ export interface SourceMapSourceDeclaration { readonly sectionPath: readonly number[]; readonly sourceIndex: number; readonly source: string | null; readonly root: string | null; readonly content: string | null; readonly ignored: boolean; } /** Validated leaf with absolute first-line offsets and its enclosing section boundary. */ export interface SourceMapLeaf { readonly map: z.output; readonly codecMap: EncodedSourceMapXInput; readonly offset: Offset; readonly stop: Offset | null; } const codecLeaf = ( map: z.output, ): EncodedSourceMapXInput => ({ version: 3, ...(map.file === undefined ? {} : { file: map.file }), ...(typeof map.sourceRoot === "string" ? { sourceRoot: map.sourceRoot } : {}), sources: map.sources, ...(map.sourcesContent == null ? {} : { sourcesContent: map.sourcesContent }), names: map.names, mappings: map.mappings, ...(map.ignoreList === undefined ? {} : { ignoreList: map.ignoreList }), ...(map.x_google_ignoreList === undefined ? {} : { x_google_ignoreList: map.x_google_ignoreList }), }); const compare = (a: Offset, b: Offset): number => a.line - b.line || a.column - b.column; const addOffset = ( base: Offset, offset: Offset, limits: SourceMapLimits, ): Offset => { const result = { line: base.line + offset.line, column: offset.column + (offset.line === 0 ? base.column : 0), }; if ( !Number.isSafeInteger(result.line) || !Number.isSafeInteger(result.column) || result.line >= limits.decodedRows ) throw sourceMapLimitFailure( `Indexed offset exceeds the generated-row decoder budget.`, "decoded_rows", limits.decodedRows, ); return result; }; const consumeRecords = ( budget: { records: number }, limits: SourceMapLimits, count: number, ): void => { if (count > limits.decodedRecords - budget.records) throw sourceMapLimitFailure( `Source-map structure exceeds the decoder budget.`, "decoded_records", limits.decodedRecords, ); budget.records += count; }; const addSections = ({ node, pending, rawSections, budget, options, }: { readonly node: PendingMap; readonly pending: PendingMap[]; readonly rawSections: readonly unknown[]; readonly budget: { records: number }; readonly options: SourceMapStructureOptions; }): void => { const limits = options.limits ?? WEB_SOURCE_MAP_LIMITS; options.check?.(); consumeRecords(budget, limits, rawSections.length); const sections = parseStructure(z.array(sectionSchema), rawSections); const embeddedMaps: Extract< SourceMapSection, { readonly kind: "embedded" } >["map"][] = []; for (const [index, section] of sections.entries()) { if ((index & 255) === 0) options.check?.(); const previous = sections[index - 1]; if (previous !== undefined && compare(section.offset, previous.offset) < 0) throw malformedInput( SOURCE_MAP_FORMAT, "Indexed section offsets must be in nondecreasing order.", ); const classification = classifySourceMapSection(section); if (classification.kind === "external") throw unsupportedInput( SOURCE_MAP_FORMAT, `External source-map section URL is not fetched: ${classification.url}`, ); if (classification.kind === "invalid") throw malformedInput( SOURCE_MAP_FORMAT, `${classification.reason} Section path: ${JSON.stringify([...node.path, index])}.`, ); embeddedMaps.push(classification.map); } for (let index = sections.length - 1; index >= 0; index -= 1) { const section = sections[index]; if (section === undefined) continue; const map = embeddedMaps[index]; if (map === undefined) throw malformedInput( SOURCE_MAP_FORMAT, "Validated indexed section map is unavailable.", ); const next = sections[index + 1]; const nextOffset = next === undefined ? null : addOffset(node.offset, next.offset, limits); const stop = nextOffset === null ? node.stop : node.stop === null || compare(nextOffset, node.stop) < 0 ? nextOffset : node.stop; const offset = addOffset(node.offset, section.offset, limits); pending.push({ value: map, path: [...node.path, index], offset, stop, }); } }; const inspectMappingLayout = ( mappings: string, limits: SourceMapLimits, check?: () => void, ): { lines: number; segments: number } => { let lines = 1; let segments = 0; let components = 0; let inSegment = false; let continued = false; let digits = 0; const finish = (): void => { if (continued) throw malformedInput( SOURCE_MAP_FORMAT, "Source-map VLQ ends with an unfinished continuation.", ); if (inSegment && ![1, 4, 5].includes(components)) throw malformedInput( SOURCE_MAP_FORMAT, "Source-map segment requires one, four or five VLQ components.", ); }; let index = 0; for (const character of mappings) { if ((index++ & 0x3fff) === 0) check?.(); if (character === "," || character === ";") { finish(); inSegment = false; components = 0; if (character === ";") lines += 1; } else { digits += 1; if ( (digits === 7 && !/[A-Dg-j]/u.test(character)) || (digits > 7 && character !== "A" && character !== "g") ) throw malformedInput( SOURCE_MAP_FORMAT, "Source-map VLQ exceeds the format's 32-bit quantity representation.", ); if (!inSegment) segments += 1; inSegment = true; continued = /[g-z0-9+/]/u.test(character); if (!continued) { components += 1; digits = 0; } } if (segments > limits.decodedSegments || lines > 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(); return { lines, segments }; }; const inspectLeaf = ( node: PendingMap, budget: { records: number }, options: SourceMapStructureOptions, ): z.output => { const limits = options.limits ?? WEB_SOURCE_MAP_LIMITS; options.check?.(); consumeRecords(budget, limits, 1); if ( typeof node.value !== "object" || node.value === null || Array.isArray(node.value) ) return parseStructure(leafSchema, node.value); const rawMap = node.value as Readonly>; const rawSources = rawMap.sources; const rawNames = rawMap.names; const rawContents = rawMap.sourcesContent; consumeRecords( budget, limits, Array.isArray(rawSources) ? rawSources.length : 0, ); consumeRecords(budget, limits, Array.isArray(rawNames) ? rawNames.length : 0); consumeRecords( budget, limits, Array.isArray(rawContents) ? rawContents.length : 0, ); options.check?.(); const leaf = parseStructure(leafSchema, node.value); const layout = inspectMappingLayout(leaf.mappings, limits, options.check); consumeRecords(budget, limits, layout.segments + layout.lines); if ( layout.segments > limits.decodedSegments || node.offset.line + layout.lines > 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; }; /** Validate structure before allocation, retaining raw declarations and section boundaries. */ export const inspectSourceMap = ( text: string, options: SourceMapStructureOptions = {}, ): ReturnType => { const jsonText = sourceMapJsonText(text); const value: unknown = JSON.parse(jsonText); return inspectSourceMapValue(value, options); }; /** Return validated leaves when a consumer needs decoded rows after preflight. */ export const inspectSourceMapValue = ( value: unknown, options: SourceMapStructureOptions = {}, ): { readonly format: "regular" | "indexed"; readonly reportedFile: string | null; readonly declarations: readonly SourceMapSourceDeclaration[]; readonly leaves: readonly SourceMapLeaf[]; } => { const limits = options.limits ?? WEB_SOURCE_MAP_LIMITS; options.check?.(); const root = parseStructure(mapHeaderSchema, value); const declarations: SourceMapSourceDeclaration[] = []; const leaves: SourceMapLeaf[] = []; const pending: PendingMap[] = [ { value, path: [], offset: { line: 0, column: 0 }, stop: null }, ]; const budget = options.budget ?? { records: 0 }; while (pending.length > 0) { options.check?.(); const node = pending.pop(); if (node === undefined) break; if (node.path.length > 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 malformedInput(SOURCE_MAP_FORMAT, sections.reason); if (sections.kind === "indexed") { addSections({ node, pending, rawSections: sections.sections, budget, options, }); continue; } const leaf = inspectLeaf(node, budget, options); leaves.push({ map: leaf, codecMap: codecLeaf(leaf), offset: node.offset, stop: node.stop, }); if (options.profile !== "browser-collection") { const ignoredSources = new Set( leaf.ignoreList ?? leaf.x_google_ignoreList ?? [], ); for (const [sourceIndex, source] of leaf.sources.entries()) declarations.push({ sectionPath: node.path, sourceIndex, source, root: leaf.sourceRoot ?? null, content: leaf.sourcesContent?.[sourceIndex] ?? null, ignored: ignoredSources.has(sourceIndex), }); } } return { format: root.sections === undefined ? "regular" : "indexed", reportedFile: root.file ?? null, declarations, leaves, }; }; /** * Leaf maps reachable within the decoder's section depth and record budgets. * Deeper or excess sections are dropped rather than expanded, so a map the * decoder refused for its limits cannot allocate past them here. */ const boundedSourceMapLeaves = ( root: unknown, options: Pick, ): Record[] => { const limits = options.limits ?? WEB_SOURCE_MAP_LIMITS; const leaves: Record[] = []; if ( typeof root !== "object" || root === null || Array.isArray(root) || (root as { version?: unknown }).version !== 3 ) return leaves; const pending: { map: unknown; depth: number }[] = [{ map: root, depth: 0 }]; let records = 0; while (pending.length > 0) { options.check?.(); const current = pending.pop(); if (current === undefined) break; const sections = classifySourceMapSections(current.map); if (sections.kind === "invalid") continue; if (sections.kind === "regular") { leaves.push(current.map as Record); continue; } if (current.depth >= limits.sectionDepth) continue; records += sections.sections.length; if (records > limits.decodedRecords) break; for (let index = sections.sections.length - 1; index >= 0; index -= 1) { const section = classifySourceMapSection(sections.sections[index]); if (section.kind === "embedded") pending.push({ map: section.map, depth: current.depth + 1 }); } } return leaves; }; /** Recover observed source content without treating incomplete maps as absent. */ export const inspectSourceMapSourceContent = ( text: string, options: Pick = {}, ): | { readonly embedded: boolean; readonly complete: true } | { readonly embedded: boolean; readonly complete: false; readonly failure: ParseFailureError; } => { options.check?.(); let value: unknown; try { value = JSON.parse(sourceMapJsonText(text)); } catch (cause) { if (!(cause instanceof SyntaxError)) throw cause; return { embedded: false, complete: false, failure: new ParseFailureError({ kind: "malformed", format: SOURCE_MAP_FORMAT, detail: cause.message, }), }; } const hasContent = ( inspection: ReturnType, ): boolean => inspection.declarations.some( (declaration) => declaration.content !== null && declaration.content.length > 0, ); try { return { embedded: hasContent(inspectSourceMapValue(value, options)), complete: true, }; } catch (failure) { if (!isSourceMapFailure(failure)) throw failure; const budget = { records: 0 }; let embedded = false; for (const leaf of boundedSourceMapLeaves(value, options)) { try { const inspected = inspectSourceMapValue(leaf, { ...options, budget }); embedded ||= hasContent(inspected); } catch (cause) { if (!isSourceMapFailure(cause)) throw cause; // An unresolved leaf cannot discard content observed in valid siblings. } } return { embedded, complete: false, failure }; } };