From 9603ea6647b444b7921d3dcedd2f197d308a4b93 Mon Sep 17 00:00:00 2001 From: "sentry-junior[bot]" <264270552+sentry-junior[bot]@users.noreply.github.com> Date: Thu, 26 Nov 2026 11:11:12 +0000 Subject: [PATCH 1/4] feat(sourcemap): Add wasm sourcemap support for inject and upload Ported from getsentry/cli#1588 by @d2anamaria. `sourcemap inject` and `sourcemap upload` now handle `.wasm` + `.wasm.map` pairs: the map takes the module's `build_id` as its debug ID, and a module without one is stamped first. Rebased onto the refreshed wasm-upload branch as one commit. It folds in the earlier commits on this branch: - feat(sourcemap): Add wasm sourcemap support for inject and upload - fix(sourcemap): Skip unusable wasm pairs instead of failing the run - test(sourcemap): Name wasm-upload companions the way it writes them - fix(sourcemap): Explain wasm pairing when modules and maps don't match Option types now accept explicit `undefined`, and tests use index access on parsed maps, for main's exactOptionalPropertyTypes and noPropertyAccessFromIndexSignature. Refs getsentry/cli#1588 Co-Authored-By: BYK <126780+BYK@users.noreply.github.com> --- packages/cli/src/commands/sourcemap/inject.ts | 52 +- packages/cli/src/commands/sourcemap/upload.ts | 157 ++++-- packages/cli/src/lib/replace-file.ts | 32 ++ packages/cli/src/lib/sourcemap/debug-id.ts | 57 ++ packages/cli/src/lib/sourcemap/inject.ts | 46 +- packages/cli/src/lib/sourcemap/wasm.ts | 386 ++++++++++++++ packages/cli/src/lib/wasm/prepare.ts | 44 +- packages/cli/src/lib/wasm/stamp.ts | 71 +++ .../test/commands/sourcemap/upload.test.ts | 236 +++++++++ packages/cli/test/lib/replace-file.test.ts | 29 + packages/cli/test/lib/sourcemap/wasm.test.ts | 499 ++++++++++++++++++ 11 files changed, 1524 insertions(+), 85 deletions(-) create mode 100644 packages/cli/src/lib/replace-file.ts create mode 100644 packages/cli/src/lib/sourcemap/wasm.ts create mode 100644 packages/cli/src/lib/wasm/stamp.ts create mode 100644 packages/cli/test/lib/replace-file.test.ts create mode 100644 packages/cli/test/lib/sourcemap/wasm.test.ts diff --git a/packages/cli/src/commands/sourcemap/inject.ts b/packages/cli/src/commands/sourcemap/inject.ts index 8e36eb78e5..7c1a764d7f 100644 --- a/packages/cli/src/commands/sourcemap/inject.ts +++ b/packages/cli/src/commands/sourcemap/inject.ts @@ -30,14 +30,27 @@ import { injectDirectory, type InjectResult, } from "../../lib/sourcemap/inject.js"; +import { + addWasmDiscoveryCounts, + discoverWasmPairs, + syncWasmPairs, + type WasmSyncResult, +} from "../../lib/sourcemap/wasm.js"; /** Result type for the inject command output. */ type InjectCommandResult = { modified: number; skipped: number; files: InjectResult[]; + /** Wasm module + sourcemap pairs reconciled onto the module's build id. */ + wasm: WasmSyncResult[]; }; +/** Whether a wasm pair was changed on disk. */ +function wasmChanged(result: WasmSyncResult): boolean { + return result.mapWritten || result.moduleStamped; +} + /** Format human-readable output for inject results. */ function formatInjectResult(data: InjectCommandResult): string { const lines: string[] = []; @@ -58,6 +71,24 @@ function formatInjectResult(data: InjectCommandResult): string { } } + if (data.wasm.length > 0) { + lines.push(""); + for (const pair of data.wasm) { + if (pair.skipped) { + lines.push( + `✗ ${pair.wasmPath} → ${colorTag("muted", `skipped: ${pair.skipped}`)}`, + ); + continue; + } + const status = wasmChanged(pair) ? "✓" : "–"; + // A dry run over an unstamped module cannot know the id it would mint; + // a module whose build_id is too short never gets one. + const debugId = + pair.debugId ?? (pair.moduleStamped ? "(pending)" : "(none)"); + lines.push(`${status} ${pair.wasmPath} → ${colorTag("muted", debugId)}`); + } + } + return renderMarkdown(lines.join("\n")); } @@ -69,6 +100,9 @@ export const injectCommand = buildCommand({ "then injects Sentry debug IDs for reliable sourcemap resolution.\n\n" + "Existing debug IDs are preserved; missing runtime registration snippets are added.\n" + "Files that already register their debug ID at runtime are left unchanged.\n\n" + + "WebAssembly pairs (app.wasm + app.wasm.map) are handled too: the map " + + "takes the module's build_id as its debug ID, and a module without one " + + "is stamped.\n\n" + "Exits with an error if zero JS + sourcemap pairs are discovered " + "(typical cause: bundler not emitting .map files). Pass " + "--allow-empty to suppress this check for directories that may " + @@ -175,8 +209,12 @@ export const injectCommand = buildCommand({ ); const pairs = await discoverFilePairs(dir, extSet, ignoreMatcher); - if (pairs.length === 0 && !flags["allow-empty"]) { - const diag = await diagnoseEmptyDiscovery(dir, { extensions }); + const wasmPairs = await discoverWasmPairs(dir, { ignoreMatcher }); + if (pairs.length === 0 && wasmPairs.length === 0 && !flags["allow-empty"]) { + const diag = await addWasmDiscoveryCounts( + dir, + await diagnoseEmptyDiscovery(dir, { extensions }), + ); throw buildEmptyDiscoveryError(dir, diag); } @@ -185,14 +223,20 @@ export const injectCommand = buildCommand({ ignoreMatcher, dryRun: flags["dry-run"], }); + const wasmResults = await syncWasmPairs(wasmPairs, { + dryRun: flags["dry-run"], + }); - const modified = results.filter((r) => r.injected).length; - const skipped = results.length - modified; + const modified = + results.filter((r) => r.injected).length + + wasmResults.filter(wasmChanged).length; + const skipped = results.length + wasmResults.length - modified; yield new CommandOutput({ modified, skipped, files: results, + wasm: wasmResults, }); if (modified > 0) { diff --git a/packages/cli/src/commands/sourcemap/upload.ts b/packages/cli/src/commands/sourcemap/upload.ts index 9fdf2e9f1e..aea08701bf 100644 --- a/packages/cli/src/commands/sourcemap/upload.ts +++ b/packages/cli/src/commands/sourcemap/upload.ts @@ -39,6 +39,12 @@ import { type InjectResult, resolveUploadTarget, } from "../../lib/sourcemap/inject.js"; +import { + addWasmDiscoveryCounts, + discoverWasmPairs, + syncWasmPairs, + type WasmSyncResult, +} from "../../lib/sourcemap/wasm.js"; import { sentry } from "../../lib/app-identity.js"; /** Result type for the upload command. */ @@ -128,12 +134,44 @@ type ArtifactContext = { noRewrite: boolean; }; -/** Compute a JS file's URL-space relative path (post-strip, forward slashes). */ -function jsRelativePath(jsPath: string, ctx: ArtifactContext): string { - const rel = relative(ctx.resolvedDir, jsPath).replaceAll("\\", "/"); +/** Compute a file's URL-space relative path (post-strip, forward slashes). */ +function urlRelativePath(path: string, ctx: ArtifactContext): string { + const rel = relative(ctx.resolvedDir, path).replaceAll("\\", "/"); return ctx.pathPrefixToStrip ? stripPrefix(rel, ctx.pathPrefixToStrip) : rel; } +/** + * Build the artifact pair for a wasm module and its sourcemap. + * + * Structurally the same as the external-map JS case — the module takes the + * `minified_source` slot — but the debug ID comes off the module's `build_id` + * rather than from hashing content, and the module is uploaded as the bytes on + * disk with no injected snippet. + */ +function buildWasmArtifactPair( + result: WasmSyncResult, + ctx: ArtifactContext, +): ArtifactFile[] { + const wasmRelative = urlRelativePath(result.wasmPath, ctx); + const mapRelative = urlRelativePath(result.mapPath, ctx); + const debugIdField = result.debugId ? { debugId: result.debugId } : {}; + return [ + { + path: result.wasmPath, + ...debugIdField, + type: "minified_source", + url: `${ctx.urlPrefix}${wasmRelative}`, + sourcemapFilename: posixRelative(posixDirname(wasmRelative), mapRelative), + }, + { + path: result.mapPath, + ...debugIdField, + type: "source_map", + url: `${ctx.urlPrefix}${mapRelative}`, + }, + ]; +} + /** * Build the `minified_source` + `source_map` artifact pair for a discovered * file, dispatching on whether the sourcemap is inline or an external file. @@ -143,7 +181,7 @@ function buildArtifactPair( ctx: ArtifactContext, ): ArtifactFile[] { const { jsPath, map, debugId } = result; - const jsRelative = jsRelativePath(jsPath, ctx); + const jsRelative = urlRelativePath(jsPath, ctx); const debugIdField = debugId ? { debugId } : {}; if (map.kind === "inline") { @@ -212,6 +250,47 @@ function buildArtifactPair( ]; } +/** + * Resolve the directory prefix to strip from every uploaded URL. + * + * `--strip-prefix` is taken verbatim, normalized to end at a directory + * boundary; `--strip-common-prefix` derives one from the discovered paths. + * Wasm pairs contribute both of their paths — a wasm-only upload should strip + * its own common directory just as a JS one does. + */ +function resolvePathPrefixToStrip( + discovered: { + resolvedDir: string; + results: InjectResult[]; + wasmResults: WasmSyncResult[]; + }, + flags: { "strip-prefix"?: string; "strip-common-prefix"?: boolean }, +): string { + if (!flags["strip-common-prefix"]) { + // Normalize --strip-prefix to end with "/" so it strips at directory + // boundaries. Without this, "build" would strip from "build/app.js" + // leaving "/app.js" instead of "app.js". + const explicit = flags["strip-prefix"] ?? ""; + if (explicit && !explicit.endsWith("/")) { + return `${explicit}/`; + } + return explicit; + } + const { resolvedDir, results, wasmResults } = discovered; + const toRelative = (path: string) => + relative(resolvedDir, path).replaceAll("\\", "/"); + // Only the JS path participates for inline maps (no standalone .map file). + const allRelative = results.flatMap((r) => + r.mapPath + ? [toRelative(r.jsPath), toRelative(r.mapPath)] + : [toRelative(r.jsPath)], + ); + for (const wasm of wasmResults) { + allRelative.push(toRelative(wasm.wasmPath), toRelative(wasm.mapPath)); + } + return computeCommonPrefix(allRelative); +} + export const uploadCommand = buildCommand({ docs: { brief: "Upload sourcemaps to Sentry", @@ -219,6 +298,8 @@ export const uploadCommand = buildCommand({ "Upload JavaScript sourcemaps and source files to Sentry using " + "debug-ID-based matching.\n\n" + "Automatically injects missing debug IDs and runtime registration snippets, preserving existing IDs.\n" + + "WebAssembly pairs (app.wasm + app.wasm.map) upload alongside, keyed by " + + "the module's build_id.\n" + "Org/project are auto-detected from DSN, env vars, or config defaults.\n\n" + "Exits with an error if zero JS + sourcemap pairs are discovered " + "(typical cause: bundler not emitting .map files). Pass " + @@ -383,13 +464,21 @@ export const uploadCommand = buildCommand({ ignoreMatcher, target.include, ); + const wasmPairs = await discoverWasmPairs(target.dir, { + ignoreMatcher, + include: target.include, + }); - if (pairs.length === 0) { + if (pairs.length === 0 && wasmPairs.length === 0) { if (!flags["allow-empty"]) { - const diag = await diagnoseEmptyDiscovery(target.dir, { - extensions, - include: target.include, - }); + const diag = await addWasmDiscoveryCounts( + target.dir, + await diagnoseEmptyDiscovery(target.dir, { + extensions, + include: target.include, + }), + { include: target.include }, + ); throw buildEmptyDiscoveryError(dir, diag); } // --allow-empty: nothing to upload, so don't require Sentry @@ -437,37 +526,33 @@ export const uploadCommand = buildCommand({ include: target.include, }); + // `--no-rewrite` runs the wasm sync read-only: nothing is stamped and no + // map is rewritten, but a `build_id` already on disk still identifies the + // pair, so it rides along on the manifest entries. + // Skipped pairs were already warned about and are left out of the upload. + const wasmResults = ( + await syncWasmPairs(wasmPairs, { dryRun: flags["no-rewrite"] }) + ).filter((result) => !result.skipped); + const urlPrefix = flags["url-prefix"] ?? "~/"; // Build artifact file list with paths relative to the upload directory const resolvedDir = resolve(target.dir); - // Normalize --strip-prefix to end with "/" so it strips at directory - // boundaries. Without this, "build" would strip from "build/app.js" - // leaving "/app.js" instead of "app.js". - let pathPrefixToStrip = flags["strip-prefix"] ?? ""; - if (pathPrefixToStrip && !pathPrefixToStrip.endsWith("/")) { - pathPrefixToStrip = `${pathPrefixToStrip}/`; - } - if (flags["strip-common-prefix"]) { - // Only the JS path participates for inline maps (no standalone .map file). - const allRelative = results.flatMap((r) => { - const rels = [relative(resolvedDir, r.jsPath).replaceAll("\\", "/")]; - if (r.mapPath) { - rels.push(relative(resolvedDir, r.mapPath).replaceAll("\\", "/")); - } - return rels; - }); - pathPrefixToStrip = computeCommonPrefix(allRelative); - } - - const artifactFiles: ArtifactFile[] = results.flatMap((result) => - buildArtifactPair(result, { - resolvedDir, - urlPrefix, - pathPrefixToStrip, - noRewrite: flags["no-rewrite"] ?? false, - }), - ); + const artifactCtx: ArtifactContext = { + resolvedDir, + urlPrefix, + pathPrefixToStrip: resolvePathPrefixToStrip( + { resolvedDir, results, wasmResults }, + flags, + ), + noRewrite: flags["no-rewrite"] ?? false, + }; + const artifactFiles: ArtifactFile[] = [ + ...results.flatMap((result) => buildArtifactPair(result, artifactCtx)), + ...wasmResults.flatMap((result) => + buildWasmArtifactPair(result, artifactCtx), + ), + ]; await uploadSourcemaps({ org, diff --git a/packages/cli/src/lib/replace-file.ts b/packages/cli/src/lib/replace-file.ts new file mode 100644 index 0000000000..45b6d27c1b --- /dev/null +++ b/packages/cli/src/lib/replace-file.ts @@ -0,0 +1,32 @@ +/** + * Replace a file's contents without ever leaving it half-written. + * + * Used where the CLI rewrites a user's build output in place (wasm modules, + * sourcemaps). A plain `writeFile` truncates first, so a full disk or a kill + * mid-write leaves a corrupt artifact; writing a sibling and renaming it over + * the target is atomic on the same filesystem. The original's mode is kept so + * an executable or read-only-for-others file stays that way. + */ + +import { randomBytes } from "node:crypto"; +import { rename, rm, stat, writeFile } from "node:fs/promises"; + +/** + * Atomically replace `path` with `data`. + * + * @param path - Existing file to replace + * @param data - New contents + */ +export async function replaceFile( + path: string, + data: string | Uint8Array, +): Promise { + const { mode } = await stat(path); + const tmp = `${path}.${process.pid}.${randomBytes(4).toString("hex")}.tmp`; + try { + await writeFile(tmp, data, { mode }); + await rename(tmp, path); + } finally { + await rm(tmp, { force: true }); + } +} diff --git a/packages/cli/src/lib/sourcemap/debug-id.ts b/packages/cli/src/lib/sourcemap/debug-id.ts index 2347caee70..a7105c3b37 100644 --- a/packages/cli/src/lib/sourcemap/debug-id.ts +++ b/packages/cli/src/lib/sourcemap/debug-id.ts @@ -23,6 +23,7 @@ import { createHash } from "node:crypto"; import { readFile, writeFile } from "node:fs/promises"; import { ValidationError } from "../errors.js"; import { logger } from "../logger.js"; +import { replaceFile } from "../replace-file.js"; import { isLikelyBinary } from "../scan/binary.js"; import { type DecodedInlineMap, @@ -138,6 +139,62 @@ export function readSourcemapDebugId(map: unknown): string | undefined { return normalizeDebugId(snake) ?? normalizeDebugId(camel); } +/** Outcome of stamping a debug ID onto a standalone sourcemap. */ +export type SourcemapStampResult = { + /** Whether the map was rewritten on disk (in a dry run: would be). */ + changed: boolean; + /** The debug ID the map carried before, when it carried a different one. */ + replaced?: string | undefined; +}; + +/** + * Read and parse a standalone sourcemap. + * + * Some toolchains save maps with a BOM, which `JSON.parse` rejects. + * + * @throws {SyntaxError} When the file is not JSON + */ +export async function readSourcemapFile( + mapPath: string, +): Promise { + const text = (await readFile(mapPath, "utf-8")).replace(/^\uFEFF/, ""); + return JSON.parse(text) as SourcemapJson; +} + +/** + * Set a debug ID on a sourcemap file, leaving everything else alone. + * + * Unlike {@link injectDebugId} this touches no host file, so it suits maps + * whose companion artifact is not JavaScript — a wasm module carries its own + * id in a custom section and must never be rewritten as text. The map itself is + * edited by {@link mutateSourcemap}, so it gains the id under both field + * spellings exactly as an injected map does, with no `mappings` offset: + * `mappings` only shifts when injection prepends a runtime snippet line. + * + * Idempotent: a map already carrying `debugId` is left byte-identical. + * + * @param mapPath - Path to the `.map` file + * @param debugId - The debug ID to write + * @param options.dryRun - Report what would change without writing + * @returns Whether the map changes, and the id it replaced + */ +export async function setSourcemapDebugId( + mapPath: string, + debugId: string, + options: { dryRun?: boolean | undefined } = {}, +): Promise { + const map = await readSourcemapFile(mapPath); + const existing = readSourcemapDebugId(map); + if (existing === debugId) { + return { changed: false }; + } + if (!options.dryRun) { + mutateSourcemap(map, debugId, {}); + await replaceFile(mapPath, JSON.stringify(map)); + } + return { changed: true, replaced: existing }; +} + /** * Generate a deterministic debug ID (UUID v4 format) from content. * diff --git a/packages/cli/src/lib/sourcemap/inject.ts b/packages/cli/src/lib/sourcemap/inject.ts index ceff236484..18d3e1474c 100644 --- a/packages/cli/src/lib/sourcemap/inject.ts +++ b/packages/cli/src/lib/sourcemap/inject.ts @@ -141,7 +141,7 @@ async function isDirectory(path: string): Promise { } /** POSIX path of `path` relative to `absDir`, for glob and ignore matching. */ -function relativePosix(absDir: string, path: string): string { +export function relativePosix(absDir: string, path: string): string { return relative(absDir, path).replaceAll("\\", "/"); } @@ -594,7 +594,7 @@ async function findCompanionMap( * dropping large JS files would skip debug-ID injection on the * exact bundles users care about most. */ -const SOURCEMAP_SKIP_DIRS: readonly string[] = [NODE_MODULES_DIRNAME]; +export const SOURCEMAP_SKIP_DIRS: readonly string[] = [NODE_MODULES_DIRNAME]; /** * Read-only discovery pass — returns the list of JS + sourcemap pairs @@ -711,6 +711,13 @@ export async function assertDirectoryReadable(dir: string): Promise { export type DiscoveryDiagnostic = { jsFiles: number; mapFiles: number; + /** + * `.wasm` modules found, excluding DWARF companions. Filled in by + * `addWasmDiscoveryCounts`; absent when only JS was scanned. + */ + wasmFiles?: number; + /** `.wasm.map` files found. */ + wasmMaps?: number; }; /** @@ -933,6 +940,41 @@ export function buildEmptyDiscoveryError( diag: DiscoveryDiagnostic, ): ValidationError { const { jsFiles, mapFiles } = diag; + const wasmFiles = diag.wasmFiles ?? 0; + const wasmMaps = diag.wasmMaps ?? 0; + // A wasm-only build directory: the JS advice would send the user to a + // bundler setting that has nothing to do with their toolchain. + if (jsFiles === 0 && mapFiles === 0 && wasmFiles > 0 && wasmMaps === 0) { + return new ValidationError( + `Found ${wasmFiles} .wasm file(s) in '${dir}' but no companion ` + + ".wasm.map files. Your build is not emitting wasm sourcemaps: " + + "compile with `-gsource-map` (Emscripten). Pass --allow-empty " + + "to suppress.", + "directory", + ); + } + // Wasm maps with no module beside them: the debug ID comes from the + // module's `build_id`, so the map alone is not uploadable. + if (jsFiles === 0 && mapFiles === 0 && wasmMaps > 0 && wasmFiles === 0) { + return new ValidationError( + `Found ${wasmMaps} .wasm.map file(s) in '${dir}' but no .wasm ` + + "modules. A wasm sourcemap is matched to its module's build_id, so " + + "the .wasm file must sit beside it — point the command at your " + + "build output. Pass --allow-empty to suppress.", + "directory", + ); + } + // Both sides exist but no filename pairs them, so the pairing rule is the + // fix, not the build flags. + if (jsFiles === 0 && mapFiles === 0 && wasmFiles > 0 && wasmMaps > 0) { + return new ValidationError( + `Found ${wasmFiles} .wasm and ${wasmMaps} .wasm.map file(s) in ` + + `'${dir}' but none pair up. A wasm sourcemap must be named ` + + "`.wasm.map` and sit beside `.wasm`. Pass " + + "--allow-empty to suppress.", + "directory", + ); + } if (jsFiles === 0 && mapFiles === 0) { return new ValidationError( `Directory '${dir}' contains no JS or sourcemap files. ` + diff --git a/packages/cli/src/lib/sourcemap/wasm.ts b/packages/cli/src/lib/sourcemap/wasm.ts new file mode 100644 index 0000000000..2a72f25341 --- /dev/null +++ b/packages/cli/src/lib/sourcemap/wasm.ts @@ -0,0 +1,386 @@ +/** + * Debug IDs for WebAssembly modules and their sourcemaps. + * + * Emscripten's `-gsource-map` emits `app.wasm` next to `app.wasm.map`, a plain + * Source Map v3 file. Sentry identifies a wasm module by the `build_id` custom + * section, which events report as `debug_meta.images[].debug_id`, and matches + * uploaded maps by the `debug_id` field inside the map JSON. This module puts + * the same id on both sides so the two artifacts join up. + * + * The module's `build_id` is the source of truth: it is what the running + * module reports, and unlike the JS path there is nothing to derive from + * content. A map that disagrees is corrected, not adopted. + * + * The wasm path deliberately shares nothing with JS injection beyond + * discovery settings. A module is binary — it gets no `//# debugId=` comment, + * no runtime snippet, and its map needs no `mappings` offset. + */ + +import { readFile, stat } from "node:fs/promises"; +import { resolve as resolvePath } from "node:path"; +import type ignore from "ignore"; +import { logger } from "../logger.js"; +import { walkFiles } from "../scan/index.js"; +import { + BUILD_ID_SECTION, + parseSections, + WasmParseError, +} from "../wasm/binary.js"; +import { + buildIdFromSections, + debugIdFromBuildId, + formatBuildId, +} from "../wasm/build-id.js"; +import { isDebugCompanionPath } from "../wasm/prepare.js"; +import { ensureBuildIdOnDisk } from "../wasm/stamp.js"; +import { readSourcemapFile, setSourcemapDebugId } from "./debug-id.js"; +import { + type DiscoveryDiagnostic, + type PathFilter, + relativePosix, + SOURCEMAP_SKIP_DIRS, +} from "./inject.js"; + +const log = logger.withTag("sourcemap.wasm"); + +/** + * Extensions scanned when looking for wasm modules. Never user-configurable: + * `--ext` selects JavaScript flavours, and a wasm module is always `.wasm`. + */ +const WASM_EXTENSIONS: ReadonlySet = new Set([".wasm"]); + +/** + * Extensions scanned when counting artifacts for the zero-pairs diagnostic. + * Covers `.map` so an orphaned `app.wasm.map` — a map whose module is not in + * the directory — is attributed to wasm instead of being left in the JS tally. + */ +const WASM_DIAGNOSTIC_EXTENSIONS: ReadonlySet = new Set([ + ".wasm", + ".map", +]); + +/** A WebAssembly module and the sourcemap sitting next to it. */ +export type WasmPair = { + /** Absolute path to the `.wasm` module. */ + wasmPath: string; + /** Absolute path to the companion `.wasm.map`. */ + mapPath: string; +}; + +/** Outcome of reconciling one module with its sourcemap. */ +export type WasmSyncResult = { + /** Absolute path to the `.wasm` module. */ + wasmPath: string; + /** Absolute path to the companion `.wasm.map`. */ + mapPath: string; + /** + * The debug ID both files now carry. Absent only when a dry run declined to + * stamp a module that had no `build_id`, so the id is not yet decided. + */ + debugId?: string; + /** Whether the map was rewritten (in a dry run: would be). */ + mapWritten: boolean; + /** + * Whether the module was given a `build_id` it did not have (in a dry run: + * would be). + */ + moduleStamped: boolean; + /** + * Why the pair was left alone, when it was. A skipped pair has no debug ID, + * wrote nothing, and is not uploaded. + */ + skipped?: string; +}; + +/** + * Which modules discovery considers, mirroring the JS discovery settings so + * `--ignore`, `--ignore-file`, and a glob upload target narrow wasm the same + * way they narrow JS. + */ +export type WasmDiscoveryOptions = { + /** Gitignore-style matcher built from `--ignore` / `--ignore-file`. */ + ignoreMatcher?: ReturnType | undefined; + /** Glob filter from a `sourcemap upload` target. */ + include?: PathFilter | undefined; +}; + +/** Whether reconciling a pair is allowed to write. */ +export type WasmSyncOptions = { + /** Report what would change without touching either file. */ + dryRun?: boolean | undefined; +}; + +/** + * Give a wasm module and its sourcemap a shared debug ID. + * + * Reads the module's `build_id`, stamping a fresh one when it has none, then + * writes that id onto the map. Idempotent: a map already carrying the id is + * left byte-identical, and a module that already has a `build_id` is never + * rewritten. A pair that can't be handled (not a module, a map that isn't + * JSON, an unreadable `build_id`, files it can't write) is skipped with a + * warning instead of failing the run. + * + * @param pair - The module and its companion map + * @param options - Stamping options + * @returns What the pair now carries, and what was written + */ +export async function syncWasmSourcemap( + pair: WasmPair, + options: WasmSyncOptions = {}, +): Promise { + try { + return await reconcilePair(pair, options); + } catch (error) { + const reason = skipReason(error); + if (!reason) { + throw error; + } + return skip(pair, reason); + } +} + +/** Errors that mean "this pair can't be handled", not "the CLI is broken". */ +const UNWRITABLE_CODES = new Set(["EACCES", "EPERM", "EROFS"]); + +/** + * Describe an error that should skip one pair rather than abort the run. + * + * A build directory can hold a `.wasm` that isn't one (a saved error page) or + * a map that isn't JSON. The JS path skips such files with a warning, so the + * wasm path does too instead of failing after the JS files were rewritten. + */ +function skipReason(error: unknown): string | undefined { + if (error instanceof WasmParseError) { + return `not a valid wasm module: ${error.message}`; + } + if (error instanceof SyntaxError) { + return `sourcemap is not valid JSON: ${error.message}`; + } + const code = (error as NodeJS.ErrnoException | undefined)?.code; + if (code && UNWRITABLE_CODES.has(code)) { + return `cannot write files (${code})`; + } + return undefined; +} + +/** Warn about a pair and report it as untouched. */ +function skip(pair: WasmPair, reason: string): WasmSyncResult { + log.warn(`Skipping ${pair.wasmPath}: ${reason}`); + return { ...pair, mapWritten: false, moduleStamped: false, skipped: reason }; +} + +async function reconcilePair( + pair: WasmPair, + options: WasmSyncOptions, +): Promise { + const { wasmPath, mapPath } = pair; + + // One read serves both the lookup and the stamp. Reading the id first also + // spares an already-stamped module the full re-encode `stampBuildId` does. + const bytes = await readFile(wasmPath); + const sections = parseSections(bytes); + const existing = buildIdFromSections(sections); + if (!existing && sections.some((s) => s.name === BUILD_ID_SECTION)) { + // Stamping would append a second `build_id`, and readers disagree on + // which one wins (symbolic takes the last, `@sentry/wasm` the first). + return skip(pair, "its build_id section is malformed"); + } + // Fail on a broken map before stamping, so a skipped pair wrote nothing. + await readSourcemapFile(mapPath); + const buildId = await ensureBuildIdOnDisk(wasmPath, bytes, existing, options); + // Reported the same way in a dry run, as `injected` is for JS: the flags + // say what a real run does, so a preview counts the files it would touch. + const moduleStamped = !existing; + + const debugId = buildId + ? debugIdFromBuildId(formatBuildId(buildId)) + : undefined; + if (!debugId) { + if (buildId) { + log.warn( + `${wasmPath} has a ${buildId.length}-byte build_id, too short for a debug ID, so its sourcemap gets none`, + ); + } + // Otherwise a dry run left the module unstamped; a real run would write + // the minted id onto the map. + return { wasmPath, mapPath, mapWritten: moduleStamped, moduleStamped }; + } + + const stamp = await setSourcemapDebugId(mapPath, debugId, { + dryRun: options.dryRun, + }); + if (stamp.replaced) { + log.debug( + `${mapPath} carried debug ID ${stamp.replaced}; replaced with the module's build_id ${debugId}`, + ); + } + + return { + wasmPath, + mapPath, + debugId, + mapWritten: stamp.changed, + moduleStamped, + }; +} + +/** + * Reconcile every discovered pair, in order. + * + * Sequential on purpose: each pair is two small file operations, and a + * bounded-concurrency pool would buy nothing on the handful of modules a wasm + * build emits. + */ +export async function syncWasmPairs( + pairs: WasmPair[], + options: WasmSyncOptions = {}, +): Promise { + const results: WasmSyncResult[] = []; + for (const pair of pairs) { + results.push(await syncWasmSourcemap(pair, options)); + } + return results; +} + +/** + * Find `.wasm` + `.wasm.map` pairs in a build directory. + * + * Pairing is by filename convention only — the wasm `sourceMappingURL` custom + * section is not consulted. Modules with no map beside them are not pairs and + * are dropped silently; `buildEmptyDiscoveryError` explains the whole-directory + * case. + * + * `*.debug.wasm` files are skipped: those are DWARF companions written by + * `debug-files wasm-upload`, uploaded through the debug-file pipeline instead. + * + * @param dir - Directory to scan + * @param options - Ignore matcher and glob filter, as for JS discovery + * @returns One entry per module that has a companion map + */ +export async function discoverWasmPairs( + dir: string, + options: WasmDiscoveryOptions = {}, +): Promise { + const absDir = resolvePath(dir); + const pairs: WasmPair[] = []; + for await (const wasmPath of walkWasmModules(absDir, options)) { + const mapPath = `${wasmPath}.map`; + // A JS pair is kept when either file matches the glob; so is a wasm pair. + const included = + !options.include || + options.include(relativePosix(absDir, wasmPath)) || + options.include(relativePosix(absDir, mapPath)); + if (included && (await hasCompanionMap(mapPath))) { + pairs.push({ wasmPath, mapPath }); + } + } + return pairs; +} + +/** + * Extend a JS discovery diagnostic with wasm counts. + * + * Only called on the zero-pairs error path, so a second walk costs nothing + * that matters. `.wasm.map` files are moved out of the JS `mapFiles` tally — + * the JS walk counts every `.map` — so the JS branches of + * `buildEmptyDiscoveryError` keep describing JS alone. Maps are counted + * independently of modules, so a map left behind by a missing module is still + * recognised as wasm. + * + * Narrowed by the glob target only, exactly as `diagnoseEmptyDiscovery` is: + * the `.wasm.map` count is subtracted from the JS tally, so both walks must + * see the same files. + * + * @param dir - Directory to scan + * @param js - The diagnostic from `diagnoseEmptyDiscovery` + * @param options - The glob filter the JS diagnostic used + * @returns The diagnostic with wasm counts filled in + */ +export async function addWasmDiscoveryCounts( + dir: string, + js: DiscoveryDiagnostic, + options: Pick = {}, +): Promise { + const absDir = resolvePath(dir); + let wasmFiles = 0; + let wasmMaps = 0; + for await (const path of walkWasmModules( + absDir, + options, + WASM_DIAGNOSTIC_EXTENSIONS, + )) { + const rel = relativePosix(absDir, path); + const isMap = path.endsWith(".map"); + if ( + options.include && + !options.include(rel) && + !(isMap && options.include(rel.slice(0, -".map".length))) + ) { + continue; + } + // The widened extension set also yields JS `.map` files; those stay in the + // JS tally. + if (path.endsWith(".wasm.map")) { + wasmMaps += 1; + } else if (path.endsWith(".wasm")) { + wasmFiles += 1; + } + } + return { + jsFiles: js.jsFiles, + mapFiles: Math.max(js.mapFiles - wasmMaps, 0), + wasmFiles, + wasmMaps, + }; +} + +/** + * Yield the deployable `.wasm` modules under `absDir`. + * + * Uses the same traversal settings as JS discovery — build outputs are usually + * gitignored, `dist`/`build` must not be pruned, and a wasm module easily + * exceeds any size cap. + * + * @param extensions - Widened only by the diagnostic walk, which also needs + * `.map` files; callers must then filter the extra extensions themselves. + */ +async function* walkWasmModules( + absDir: string, + { ignoreMatcher, include }: WasmDiscoveryOptions, + extensions: ReadonlySet = WASM_EXTENSIONS, +): AsyncGenerator { + for await (const entry of walkFiles({ + cwd: absDir, + extensions, + alwaysSkipDirs: SOURCEMAP_SKIP_DIRS, + // A glob target can name hidden directories (`.next/static/**`). + hidden: include !== undefined, + respectGitignore: false, + maxFileSize: Number.POSITIVE_INFINITY, + })) { + const wasmPath = entry.absolutePath; + if (isDebugCompanionPath(wasmPath)) { + continue; + } + if (ignoreMatcher?.ignores(relativePosix(absDir, wasmPath))) { + continue; + } + yield wasmPath; + } +} + +/** + * Whether a module's companion sourcemap exists. + * + * An absent map is the common case, not a failure: a module without one is + * simply not a pair, and the whole-directory case is reported by + * `buildEmptyDiscoveryError`. + */ +async function hasCompanionMap(mapPath: string): Promise { + try { + return (await stat(mapPath)).isFile(); + } catch (error) { + log.debug(`no companion sourcemap at ${mapPath}`, error); + return false; + } +} diff --git a/packages/cli/src/lib/wasm/prepare.ts b/packages/cli/src/lib/wasm/prepare.ts index 977a3f6001..835f2c8ce0 100644 --- a/packages/cli/src/lib/wasm/prepare.ts +++ b/packages/cli/src/lib/wasm/prepare.ts @@ -52,6 +52,7 @@ import { randomBuildId, } from "./build-id.js"; import { splitWasm } from "./split.js"; +import { ensureBuildIdOnDisk, stampBuildId } from "./stamp.js"; const log = logger.withTag("wasm.prepare"); @@ -311,49 +312,6 @@ async function readCompanionBuildId(path: string): Promise { } } -/** - * Give a module a build id, writing it back in place when it has none. - * - * `wasm-split` stamps every module it processes regardless of debug quality. - * Sentry matches a stack frame to its debug file by build id, so an unstamped - * module can never be symbolicated — not even from a debug file uploaded - * later. Stamping now keeps that option open. - * - * @param path - Module to stamp. - * @param bytes - The module as read from disk. - * @param existing - Id the module already carries, if any. - * @returns The effective build id, or `null` when a dry run left the module - * untouched. - */ -async function ensureBuildIdOnDisk( - path: string, - bytes: Uint8Array, - existing: Uint8Array | null, - options: PrepareOptions, -): Promise { - // Checked before splitting so an already-stamped module is never re-encoded. - if (existing) { - return existing; - } - if (options.dryRun) { - return null; - } - const stamped = stampBuildId(bytes, options.buildId); - await writeFile(path, stamped.module); - return stamped.buildId; -} - -/** - * Stamp a module with a build id, changing nothing else. - * - * A split with neither `strip` nor `companion` is exactly that, so stamping - * shares one implementation with the real split rather than reassembling the - * section list by hand. - */ -function stampBuildId(bytes: Uint8Array, buildId?: Uint8Array) { - return splitWasm(bytes, buildId ? { buildId } : {}); -} - /** Whether two build ids are byte-identical. */ function buildIdsMatch(a: Uint8Array | null, b: Uint8Array | null): boolean { if (!(a && b) || a.length !== b.length) { diff --git a/packages/cli/src/lib/wasm/stamp.ts b/packages/cli/src/lib/wasm/stamp.ts new file mode 100644 index 0000000000..9244d197ea --- /dev/null +++ b/packages/cli/src/lib/wasm/stamp.ts @@ -0,0 +1,71 @@ +/** + * Writing a build id onto a module already on disk. + * + * Kept apart from `split.ts`, which stays a pure bytes-in/bytes-out port of the + * Rust `wasm-split`. Everything here is the file-level layer above it, shared + * by `debug-files wasm-upload` and the wasm sourcemap path so both stamp under the + * same rule: an id already on the module always wins, and a dry run writes + * nothing. + */ + +import { replaceFile } from "../replace-file.js"; +import { type SplitWasmResult, splitWasm } from "./split.js"; + +/** How to stamp a module that carries no build id yet. */ +export type StampOptions = { + /** Id to use when one must be minted. Defaults to a random v4 UUID. */ + buildId?: Uint8Array | undefined; + /** Report what would change without writing. */ + dryRun?: boolean | undefined; +}; + +/** + * Stamp a module with a build id, changing nothing else. + * + * A split with neither `strip` nor `companion` is exactly that, so stamping + * shares one implementation with the real split rather than reassembling the + * section list by hand. + * + * @param bytes - The module as read from disk + * @param buildId - Id to stamp when the module carries none + * @returns The effective id and the re-encoded module + */ +export function stampBuildId( + bytes: Uint8Array, + buildId?: Uint8Array, +): SplitWasmResult { + return splitWasm(bytes, buildId ? { buildId } : {}); +} + +/** + * Give a module a build id, writing it back in place when it has none. + * + * `wasm-split` stamps every module it processes regardless of debug quality. + * Sentry matches a stack frame to its debug file by build id, so an unstamped + * module can never be symbolicated — not even from a debug file uploaded + * later. Stamping now keeps that option open. + * + * @param path - Module to stamp + * @param bytes - The module as read from disk + * @param existing - Id the module already carries, if any + * @param options - Which id to mint, and whether to write at all + * @returns The effective build id, or `null` when a dry run left the module + * untouched + */ +export async function ensureBuildIdOnDisk( + path: string, + bytes: Uint8Array, + existing: Uint8Array | null, + options: StampOptions = {}, +): Promise { + // Checked before splitting so an already-stamped module is never re-encoded. + if (existing) { + return existing; + } + if (options.dryRun) { + return null; + } + const stamped = stampBuildId(bytes, options.buildId); + await replaceFile(path, stamped.module); + return stamped.buildId; +} diff --git a/packages/cli/test/commands/sourcemap/upload.test.ts b/packages/cli/test/commands/sourcemap/upload.test.ts index 8f0d3f2639..5470b19c1f 100644 --- a/packages/cli/test/commands/sourcemap/upload.test.ts +++ b/packages/cli/test/commands/sourcemap/upload.test.ts @@ -17,6 +17,33 @@ import { ValidationError } from "../../../src/lib/errors.js"; import { getDebugIdSnippet } from "../../../src/lib/sourcemap/debug-id.js"; import { buildEmptyDiscoveryError } from "../../../src/lib/sourcemap/inject.js"; import type { Writer } from "../../../src/types/index.js"; +import { + encodeModule, + makeBuildIdSection, +} from "../../../src/lib/wasm/binary.js"; +import { uuidToBytes } from "../../../src/lib/wasm/build-id.js"; + +/** Deterministic wasm build id, and the debug ID it maps to. */ +const WASM_DEBUG_ID = "00000000-0000-4000-8000-000000000000"; + +/** Write `.wasm` + `.wasm.map` into `dir`. */ +async function writeWasmPair( + dir: string, + stem: string, + buildId?: string, +): Promise<{ wasmPath: string; mapPath: string }> { + const sections = buildId + ? [makeBuildIdSection(uuidToBytes(buildId) as Uint8Array)] + : []; + const wasmPath = join(dir, `${stem}.wasm`); + const mapPath = join(dir, `${stem}.wasm.map`); + await writeFile(wasmPath, encodeModule(sections)); + await writeFile( + mapPath, + JSON.stringify({ version: 3, sources: ["a.c"], names: [], mappings: "" }), + ); + return { wasmPath, mapPath }; +} type InjectFuncArgs = { ext?: string; @@ -243,6 +270,71 @@ describe("sourcemap inject command — --allow-empty behavior", () => { await expect(func.call(ctx, {}, dir)).resolves.toBeUndefined(); }); + test("wasm pair: stamps the map with the module's build_id", async () => { + const { mapPath } = await writeWasmPair(dir, "app", WASM_DEBUG_ID); + const ctx = makeContext(); + + await expect(func.call(ctx, {}, dir)).resolves.toBeUndefined(); + + const map = JSON.parse(await readFile(mapPath, "utf-8")); + expect(map.debug_id).toBe(WASM_DEBUG_ID); + expect(map.debugId).toBe(WASM_DEBUG_ID); + }); + + test("wasm pair alongside a JS pair: both are injected", async () => { + await writeFile(join(dir, "app.js"), "console.log(1)\n"); + await writeFile(join(dir, "app.js.map"), '{"version":3}\n'); + const { mapPath } = await writeWasmPair(dir, "mod", WASM_DEBUG_ID); + const ctx = makeContext(); + + await expect(func.call(ctx, {}, dir)).resolves.toBeUndefined(); + + expect(await readFile(join(dir, "app.js"), "utf-8")).toContain( + "//# debugId=", + ); + expect(JSON.parse(await readFile(mapPath, "utf-8")).debug_id).toBe( + WASM_DEBUG_ID, + ); + }); + + test("wasm-only directory does not trip the missing-.map guard", async () => { + await writeWasmPair(dir, "app", WASM_DEBUG_ID); + const ctx = makeContext(); + + await expect(func.call(ctx, {}, dir)).resolves.toBeUndefined(); + }); + + test(".wasm files without .wasm.map: error recommends -gsource-map", async () => { + await writeFile( + join(dir, "app.wasm"), + encodeModule([ + makeBuildIdSection(uuidToBytes(WASM_DEBUG_ID) as Uint8Array), + ]), + ); + const ctx = makeContext(); + try { + await func.call(ctx, {}, dir); + expect.unreachable("should have thrown"); + } catch (err) { + expect(err).toBeInstanceOf(ValidationError); + const msg = (err as Error).message; + expect(msg).toContain("1 .wasm file(s)"); + expect(msg).toContain("-gsource-map"); + } + }); + + test("--dry-run over a wasm pair: writes nothing", async () => { + const { wasmPath, mapPath } = await writeWasmPair(dir, "app"); + const wasmBefore = await readFile(wasmPath); + const mapBefore = await readFile(mapPath); + const ctx = makeContext(); + + await func.call(ctx, { "dry-run": true }, dir); + + expect(await readFile(wasmPath)).toEqual(wasmBefore); + expect(await readFile(mapPath)).toEqual(mapBefore); + }); + test("sourceMappingURL: invalid inline base64 is skipped (zero pairs)", async () => { await writeFile( join(dir, "bad-inline.js"), @@ -964,6 +1056,150 @@ describe("sourcemap upload command — --allow-empty behavior", () => { } }); + test("wasm pair: uploads module and map under the build_id", async () => { + await writeWasmPair(dir, "app", WASM_DEBUG_ID); + + const uploadSpy = vi + .spyOn(sourcemapsApi, "uploadSourcemaps") + .mockResolvedValue(undefined); + try { + const ctx = makeContext(); + await func.call(ctx, {}, dir); + const files = uploadSpy.mock.calls[0]?.[0]?.files ?? []; + expect(files).toHaveLength(2); + const wasm = files.find((f) => f.type === "minified_source"); + const map = files.find((f) => f.type === "source_map"); + expect(wasm?.url).toBe("~/app.wasm"); + expect(wasm?.sourcemapFilename).toBe("app.wasm.map"); + expect(map?.url).toBe("~/app.wasm.map"); + // Both sides carry the module's build_id as the debug ID. + expect(wasm?.debugId).toBe(WASM_DEBUG_ID); + expect(map?.debugId).toBe(WASM_DEBUG_ID); + } finally { + uploadSpy.mockRestore(); + } + }); + + test("glob target: uploads only the wasm pairs it matches", async () => { + await mkdir(join(dir, "pkg")); + await writeWasmPair(join(dir, "pkg"), "app", WASM_DEBUG_ID); + await writeWasmPair(dir, "other", WASM_DEBUG_ID); + + const uploadSpy = vi + .spyOn(sourcemapsApi, "uploadSourcemaps") + .mockResolvedValue(undefined); + try { + const ctx = makeContext(); + await func.call(ctx, {}, `${dir}/pkg/**`); + const files = uploadSpy.mock.calls[0]?.[0]?.files ?? []; + expect(files.map((f) => f.url).sort()).toEqual([ + "~/app.wasm", + "~/app.wasm.map", + ]); + } finally { + uploadSpy.mockRestore(); + } + }); + + test("wasm pair alongside a JS pair: four artifact entries", async () => { + await writeFile(join(dir, "app.js"), "console.log(1)\n"); + await writeFile( + join(dir, "app.js.map"), + JSON.stringify({ version: 3, sources: [], names: [], mappings: "" }), + ); + await writeWasmPair(dir, "mod", WASM_DEBUG_ID); + + const uploadSpy = vi + .spyOn(sourcemapsApi, "uploadSourcemaps") + .mockResolvedValue(undefined); + try { + const ctx = makeContext(); + await func.call(ctx, {}, dir); + const files = uploadSpy.mock.calls[0]?.[0]?.files ?? []; + expect(files.map((f) => f.url).sort()).toEqual([ + "~/app.js", + "~/app.js.map", + "~/mod.wasm", + "~/mod.wasm.map", + ]); + } finally { + uploadSpy.mockRestore(); + } + }); + + test("a .wasm that is not a module is skipped; the JS pair still uploads", async () => { + await writeFile(join(dir, "app.js"), "console.log(1)\n"); + await writeFile( + join(dir, "app.js.map"), + JSON.stringify({ version: 3, sources: [], names: [], mappings: "" }), + ); + await writeFile(join(dir, "broken.wasm"), "Not Found"); + await writeFile( + join(dir, "broken.wasm.map"), + JSON.stringify({ version: 3, sources: [], names: [], mappings: "" }), + ); + + const uploadSpy = vi + .spyOn(sourcemapsApi, "uploadSourcemaps") + .mockResolvedValue(undefined); + try { + const ctx = makeContext(); + await func.call(ctx, {}, dir); + const files = uploadSpy.mock.calls[0]?.[0]?.files ?? []; + expect(files.map((f) => f.url).sort()).toEqual([ + "~/app.js", + "~/app.js.map", + ]); + } finally { + uploadSpy.mockRestore(); + } + }); + + test("DWARF companions are not uploaded as sourcemap artifacts", async () => { + await writeWasmPair(dir, "app", WASM_DEBUG_ID); + await writeWasmPair( + dir, + "app.00000000000040008000000000000000.debug", + WASM_DEBUG_ID, + ); + + const uploadSpy = vi + .spyOn(sourcemapsApi, "uploadSourcemaps") + .mockResolvedValue(undefined); + try { + const ctx = makeContext(); + await func.call(ctx, {}, dir); + const urls = uploadSpy.mock.calls[0]?.[0]?.files.map((f) => f.url) ?? []; + expect(urls.some((u) => u.includes("debug.wasm"))).toBe(false); + } finally { + uploadSpy.mockRestore(); + } + }); + + test("--no-rewrite + wasm pair: nothing written, id read off the module", async () => { + const { wasmPath, mapPath } = await writeWasmPair( + dir, + "app", + WASM_DEBUG_ID, + ); + const mapBefore = await readFile(mapPath); + const wasmBefore = await readFile(wasmPath); + + const uploadSpy = vi + .spyOn(sourcemapsApi, "uploadSourcemaps") + .mockResolvedValue(undefined); + try { + const ctx = makeContext(); + await func.call(ctx, { "no-rewrite": true }, dir); + expect(await readFile(wasmPath)).toEqual(wasmBefore); + expect(await readFile(mapPath)).toEqual(mapBefore); + const files = uploadSpy.mock.calls[0]?.[0]?.files ?? []; + expect(files.every((f) => f.debugId === WASM_DEBUG_ID)).toBe(true); + } finally { + uploadSpy.mockRestore(); + } + }); + test("pre-existing inline map debug ID: uploaded on both entries", async () => { const pluginId = "aaaaaaaa-bbbb-cccc-dddd-eeeeeeeeeeee"; const jsPath = join(dir, "inline-plugin.js"); diff --git a/packages/cli/test/lib/replace-file.test.ts b/packages/cli/test/lib/replace-file.test.ts new file mode 100644 index 0000000000..9adcc94017 --- /dev/null +++ b/packages/cli/test/lib/replace-file.test.ts @@ -0,0 +1,29 @@ +/** + * Tests for replacing a file's contents in place without a partial write. + */ + +import { + chmod, + mkdtemp, + readdir, + readFile, + stat, + writeFile, +} from "node:fs/promises"; +import { tmpdir } from "node:os"; +import { join } from "node:path"; +import { expect, test } from "vitest"; +import { replaceFile } from "../../src/lib/replace-file.js"; + +test("replaces the contents, keeps the mode, and leaves no temp file", async () => { + const dir = await mkdtemp(join(tmpdir(), "sentry-replace-file-")); + const path = join(dir, "app.wasm"); + await writeFile(path, "old"); + await chmod(path, 0o640); + + await replaceFile(path, new Uint8Array([1, 2, 3])); + + expect(await readFile(path)).toEqual(Buffer.from([1, 2, 3])); + expect(((await stat(path)).mode % 0o1000).toString(8)).toBe("640"); + expect(await readdir(dir)).toEqual(["app.wasm"]); +}); diff --git a/packages/cli/test/lib/sourcemap/wasm.test.ts b/packages/cli/test/lib/sourcemap/wasm.test.ts new file mode 100644 index 0000000000..2023810783 --- /dev/null +++ b/packages/cli/test/lib/sourcemap/wasm.test.ts @@ -0,0 +1,499 @@ +/** + * Tests for pairing WebAssembly modules with their sourcemaps and giving both + * the module's `build_id` as a debug ID. + * + * The single-pair sync is exercised directly — no walker, no upload API — so + * each rule (stamp, adopt, correct, leave alone) is checked in isolation. + */ + +import { mkdir, mkdtemp, readFile, writeFile } from "node:fs/promises"; +import { tmpdir } from "node:os"; +import { join } from "node:path"; +import ignore from "ignore"; +import picomatch from "picomatch"; +import { beforeEach, describe, expect, test } from "vitest"; +import { buildEmptyDiscoveryError } from "../../../src/lib/sourcemap/inject.js"; +import { + addWasmDiscoveryCounts, + discoverWasmPairs, + syncWasmSourcemap, +} from "../../../src/lib/sourcemap/wasm.js"; +import { parseSections } from "../../../src/lib/wasm/binary.js"; +import { + buildIdFromSections, + debugIdFromBuildId, + formatBuildId, + uuidToBytes, +} from "../../../src/lib/wasm/build-id.js"; +import { + byteVector, + customSection, + fromHex, + wasmModule, +} from "../wasm/helpers.js"; + +/** Deterministic build id used wherever the exact debug ID matters. */ +const FIXED_UUID = "00000000-0000-4000-8000-000000000000"; + +/** A second id, for the map-disagrees case. */ +const OTHER_UUID = "11111111-2222-4333-8444-555555555555"; + +let dir: string; + +beforeEach(async () => { + dir = await mkdtemp(join(tmpdir(), "sentry-wasm-sourcemap-")); +}); + +/** Write a wasm module, optionally carrying a `build_id`. */ +async function writeWasm(name: string, buildId?: string): Promise { + const sections = [customSection("name", fromHex("00"))]; + if (buildId) { + sections.push( + customSection("build_id", byteVector(uuidToBytes(buildId) as Uint8Array)), + ); + } + const path = join(dir, name); + await writeFile(path, wasmModule(sections)); + return path; +} + +/** Write a Source Map v3 file, optionally carrying a debug ID. */ +async function writeMap(name: string, debugId?: string): Promise { + const map: Record = { + version: 3, + sources: ["app.c"], + names: [], + mappings: "AAAA", + }; + if (debugId) { + map["debug_id"] = debugId; + } + const path = join(dir, name); + await writeFile(path, JSON.stringify(map)); + return path; +} + +/** Read a map back as a plain object. */ +async function readMap(path: string): Promise> { + return JSON.parse(await readFile(path, "utf-8")); +} + +/** Read the debug ID a module's `build_id` section stands for. */ +async function readModuleDebugId(path: string): Promise { + const buildId = buildIdFromSections(parseSections(await readFile(path))); + return buildId ? debugIdFromBuildId(formatBuildId(buildId)) : undefined; +} + +describe("syncWasmSourcemap", () => { + /** Write a module whose `build_id` section holds exactly `body`. */ + async function writeWasmWithBuildIdBody(name: string, body: string) { + const path = join(dir, name); + await writeFile( + path, + wasmModule([ + customSection("name", fromHex("00")), + customSection("build_id", fromHex(body)), + ]), + ); + return path; + } + + /** Count the `build_id` sections in a module on disk. */ + async function countBuildIdSections(path: string): Promise { + return parseSections(await readFile(path)).filter( + (s) => s.name === "build_id", + ).length; + } + + test("adopts a legacy bare 16-byte build_id instead of stamping a second", async () => { + const wasmPath = await writeWasmWithBuildIdBody( + "legacy.wasm", + "90f5be01270255a18255e7c3e501bc25", + ); + const before = await readFile(wasmPath); + const mapPath = await writeMap("legacy.wasm.map"); + + const result = await syncWasmSourcemap({ wasmPath, mapPath }); + + expect(result.moduleStamped).toBe(false); + expect(result.debugId).toBe("90f5be01-2702-55a1-8255-e7c3e501bc25"); + expect(await readFile(wasmPath)).toEqual(before); + expect(await countBuildIdSections(wasmPath)).toBe(1); + }); + + test("skips a module whose build_id section is malformed", async () => { + // Declares 32 bytes but holds 2: unreadable, yet present. + const wasmPath = await writeWasmWithBuildIdBody("bad-id.wasm", "200102"); + const before = await readFile(wasmPath); + const mapPath = await writeMap("bad-id.wasm.map"); + const mapBefore = await readFile(mapPath); + + const result = await syncWasmSourcemap({ wasmPath, mapPath }); + + expect(result.skipped).toMatch(/build_id section is malformed/); + expect(result.debugId).toBeUndefined(); + expect(await readFile(wasmPath)).toEqual(before); + expect(await readFile(mapPath)).toEqual(mapBefore); + }); + + test("skips a .wasm file that is not a module", async () => { + const wasmPath = join(dir, "404.wasm"); + await writeFile(wasmPath, "Not Found"); + const mapPath = await writeMap("404.wasm.map"); + const mapBefore = await readFile(mapPath); + + const result = await syncWasmSourcemap({ wasmPath, mapPath }); + + expect(result.skipped).toMatch(/not a valid wasm module/); + expect(await readFile(mapPath)).toEqual(mapBefore); + }); + + test("skips a map that is not JSON without stamping the module", async () => { + const wasmPath = await writeWasm("app.wasm"); + const before = await readFile(wasmPath); + const mapPath = join(dir, "app.wasm.map"); + await writeFile(mapPath, "not json"); + + const result = await syncWasmSourcemap({ wasmPath, mapPath }); + + expect(result.skipped).toMatch(/not valid JSON/); + expect(result.moduleStamped).toBe(false); + expect(await readFile(wasmPath)).toEqual(before); + }); + + test("reads a map saved with a BOM", async () => { + const wasmPath = await writeWasm("app.wasm", FIXED_UUID); + const mapPath = join(dir, "app.wasm.map"); + await writeFile( + mapPath, + `\uFEFF${JSON.stringify({ version: 3, mappings: "" })}`, + ); + + const result = await syncWasmSourcemap({ wasmPath, mapPath }); + + expect(result.skipped).toBeUndefined(); + expect((await readMap(mapPath))["debug_id"]).toBe(FIXED_UUID); + }); + + test("leaves the map alone when the build_id is too short for a debug ID", async () => { + const wasmPath = await writeWasmWithBuildIdBody( + "short.wasm", + "080102030405060708", + ); + const mapPath = await writeMap("short.wasm.map"); + const mapBefore = await readFile(mapPath); + + const result = await syncWasmSourcemap({ wasmPath, mapPath }); + + expect(result.debugId).toBeUndefined(); + expect(result.moduleStamped).toBe(false); + expect(result.mapWritten).toBe(false); + expect(await readFile(mapPath)).toEqual(mapBefore); + }); + + test("stamps the map with the id the module already carries", async () => { + const wasmPath = await writeWasm("app.wasm", FIXED_UUID); + const before = await readFile(wasmPath); + const mapPath = await writeMap("app.wasm.map"); + + const result = await syncWasmSourcemap({ wasmPath, mapPath }); + + expect(result.debugId).toBe(FIXED_UUID); + expect(result.mapWritten).toBe(true); + expect(result.moduleStamped).toBe(false); + const map = await readMap(mapPath); + expect(map["debug_id"]).toBe(FIXED_UUID); + expect(map["debugId"]).toBe(FIXED_UUID); + // The module is the source of truth, so it is never rewritten. + expect(await readFile(wasmPath)).toEqual(before); + }); + + test("stamps a module that has no build_id, then the map", async () => { + const wasmPath = await writeWasm("bare.wasm"); + const mapPath = await writeMap("bare.wasm.map"); + + const result = await syncWasmSourcemap({ wasmPath, mapPath }); + + expect(result.moduleStamped).toBe(true); + // The minted id is random, so the invariant to check is that both sides + // ended up with the one now on the module. + expect(result.debugId).toBe(await readModuleDebugId(wasmPath)); + expect((await readMap(mapPath))["debug_id"]).toBe(result.debugId); + }); + + test("writes nothing when the map already carries the module's id", async () => { + const wasmPath = await writeWasm("app.wasm", FIXED_UUID); + const mapPath = await writeMap("app.wasm.map", FIXED_UUID); + const before = await readFile(mapPath); + + const result = await syncWasmSourcemap({ wasmPath, mapPath }); + + expect(result.debugId).toBe(FIXED_UUID); + expect(result.mapWritten).toBe(false); + expect(await readFile(mapPath)).toEqual(before); + }); + + test("overwrites a map id that disagrees with the module", async () => { + const wasmPath = await writeWasm("app.wasm", FIXED_UUID); + const mapPath = await writeMap("app.wasm.map", OTHER_UUID); + + const result = await syncWasmSourcemap({ wasmPath, mapPath }); + + expect(result.mapWritten).toBe(true); + expect((await readMap(mapPath))["debug_id"]).toBe(FIXED_UUID); + }); + + test("preserves the rest of the map", async () => { + const wasmPath = await writeWasm("app.wasm", FIXED_UUID); + const mapPath = await writeMap("app.wasm.map"); + + await syncWasmSourcemap({ wasmPath, mapPath }); + + const map = await readMap(mapPath); + expect(map["version"]).toBe(3); + expect(map["sources"]).toEqual(["app.c"]); + expect(map["mappings"]).toBe("AAAA"); + }); + + test("dry run leaves both files untouched", async () => { + const wasmPath = await writeWasm("app.wasm", FIXED_UUID); + const mapPath = await writeMap("app.wasm.map"); + const wasmBefore = await readFile(wasmPath); + const mapBefore = await readFile(mapPath); + + const result = await syncWasmSourcemap( + { wasmPath, mapPath }, + { dryRun: true }, + ); + + // The id is still reportable: it was read off the module. + expect(result.debugId).toBe(FIXED_UUID); + // Reported as a real run would write it, so `inject --dry-run` counts it. + expect(result.mapWritten).toBe(true); + expect(result.moduleStamped).toBe(false); + expect(await readFile(wasmPath)).toEqual(wasmBefore); + expect(await readFile(mapPath)).toEqual(mapBefore); + }); + + test("dry run over an unstamped module reports no id but both changes", async () => { + const wasmPath = await writeWasm("bare.wasm"); + const mapPath = await writeMap("bare.wasm.map"); + const wasmBefore = await readFile(wasmPath); + const mapBefore = await readFile(mapPath); + + const result = await syncWasmSourcemap( + { wasmPath, mapPath }, + { dryRun: true }, + ); + + expect(result.debugId).toBeUndefined(); + expect(result.moduleStamped).toBe(true); + expect(result.mapWritten).toBe(true); + expect(await readFile(wasmPath)).toEqual(wasmBefore); + expect(await readFile(mapPath)).toEqual(mapBefore); + }); + + test("dry run over an already-synced pair reports nothing to change", async () => { + const wasmPath = await writeWasm("app.wasm", FIXED_UUID); + const mapPath = await writeMap("app.wasm.map", FIXED_UUID); + + const result = await syncWasmSourcemap( + { wasmPath, mapPath }, + { dryRun: true }, + ); + + expect(result.mapWritten).toBe(false); + expect(result.moduleStamped).toBe(false); + }); +}); + +describe("discoverWasmPairs", () => { + test("pairs a module with the map beside it", async () => { + const wasmPath = await writeWasm("app.wasm", FIXED_UUID); + const mapPath = await writeMap("app.wasm.map"); + + expect(await discoverWasmPairs(dir)).toEqual([{ wasmPath, mapPath }]); + }); + + test("skips DWARF companions written by debug-files wasm-upload", async () => { + const companion = "app.00000000000040008000000000000000.debug.wasm"; + await writeWasm(companion, FIXED_UUID); + await writeMap(`${companion}.map`); + + expect(await discoverWasmPairs(dir)).toEqual([]); + }); + + test("pairs a debug build named app.debug.wasm with its map", async () => { + // Only the ..debug.wasm name marks a companion. + const wasmPath = await writeWasm("app.debug.wasm", FIXED_UUID); + const mapPath = await writeMap("app.debug.wasm.map"); + + expect(await discoverWasmPairs(dir)).toEqual([{ wasmPath, mapPath }]); + }); + + test("skips a module with no map beside it", async () => { + await writeWasm("lonely.wasm", FIXED_UUID); + + expect(await discoverWasmPairs(dir)).toEqual([]); + }); + + test("honours a gitignore-style ignore matcher", async () => { + await mkdir(join(dir, "vendor")); + await writeFile( + join(dir, "vendor", "lib.wasm"), + wasmModule([ + customSection( + "build_id", + byteVector(uuidToBytes(FIXED_UUID) as Uint8Array), + ), + ]), + ); + await writeFile(join(dir, "vendor", "lib.wasm.map"), '{"version":3}'); + const wasmPath = await writeWasm("app.wasm", FIXED_UUID); + await writeMap("app.wasm.map"); + + const matcher = ignore(); + matcher.add(["vendor/**"]); + + const pairs = await discoverWasmPairs(dir, { ignoreMatcher: matcher }); + + expect(pairs.map((p) => p.wasmPath)).toEqual([wasmPath]); + }); + + test("keeps only pairs a glob target matches", async () => { + await mkdir(join(dir, "pkg")); + await writeFile( + join(dir, "pkg", "app.wasm"), + wasmModule([customSection("name", fromHex("00"))]), + ); + await writeFile(join(dir, "pkg", "app.wasm.map"), '{"version":3}'); + await writeWasm("other.wasm", FIXED_UUID); + await writeMap("other.wasm.map"); + + const pairs = await discoverWasmPairs(dir, { + include: picomatch("pkg/**"), + }); + + expect(pairs.map((p) => p.wasmPath)).toEqual([ + join(dir, "pkg", "app.wasm"), + ]); + }); + + test("keeps a pair when only its map matches the glob", async () => { + const wasmPath = await writeWasm("app.wasm", FIXED_UUID); + await writeMap("app.wasm.map"); + + const pairs = await discoverWasmPairs(dir, { + include: picomatch("**/*.map"), + }); + + expect(pairs.map((p) => p.wasmPath)).toEqual([wasmPath]); + }); +}); + +describe("addWasmDiscoveryCounts", () => { + test("counts modules and moves .wasm.map out of the JS map tally", async () => { + await writeWasm("app.wasm", FIXED_UUID); + await writeMap("app.wasm.map"); + + const diag = await addWasmDiscoveryCounts(dir, { + jsFiles: 0, + mapFiles: 1, + }); + + expect(diag).toEqual({ + jsFiles: 0, + mapFiles: 0, + wasmFiles: 1, + wasmMaps: 1, + }); + }); + + test("reports modules built without -gsource-map", async () => { + await writeWasm("app.wasm", FIXED_UUID); + + const diag = await addWasmDiscoveryCounts(dir, { + jsFiles: 0, + mapFiles: 0, + }); + + expect(diag.wasmFiles).toBe(1); + expect(diag.wasmMaps).toBe(0); + }); + + test("attributes a map with no module to wasm, not JS", async () => { + await writeMap("app.wasm.map"); + + const diag = await addWasmDiscoveryCounts(dir, { + jsFiles: 0, + mapFiles: 1, + }); + + expect(diag).toEqual({ + jsFiles: 0, + mapFiles: 0, + wasmFiles: 0, + wasmMaps: 1, + }); + expect(buildEmptyDiscoveryError(dir, diag).message).toContain( + "1 .wasm.map file(s)", + ); + }); + + test("explains the pairing rule when modules and maps don't pair", async () => { + await writeWasm("app.wasm", FIXED_UUID); + await writeMap("other.wasm.map"); + + const diag = await addWasmDiscoveryCounts(dir, { + jsFiles: 0, + mapFiles: 1, + }); + const message = buildEmptyDiscoveryError(dir, diag).message; + + expect(diag).toEqual({ + jsFiles: 0, + mapFiles: 0, + wasmFiles: 1, + wasmMaps: 1, + }); + expect(message).toContain("1 .wasm and 1 .wasm.map file(s)"); + expect(message).toContain("`.wasm.map`"); + expect(message).not.toContain("no JS or sourcemap files"); + }); + + test("counts only what a glob target matches", async () => { + await mkdir(join(dir, "pkg")); + await writeFile( + join(dir, "pkg", "app.wasm"), + wasmModule([customSection("name", fromHex("00"))]), + ); + await writeFile(join(dir, "pkg", "app.wasm.map"), '{"version":3}'); + await writeWasm("other.wasm", FIXED_UUID); + await writeMap("other.wasm.map"); + + const diag = await addWasmDiscoveryCounts( + dir, + { jsFiles: 0, mapFiles: 1 }, + { include: picomatch("pkg/**") }, + ); + + expect(diag).toEqual({ + jsFiles: 0, + mapFiles: 0, + wasmFiles: 1, + wasmMaps: 1, + }); + }); + + test("leaves JS maps in the JS tally", async () => { + await writeMap("app.js.map"); + + const diag = await addWasmDiscoveryCounts(dir, { + jsFiles: 0, + mapFiles: 1, + }); + + expect(diag.mapFiles).toBe(1); + expect(diag.wasmMaps).toBe(0); + }); +}); From cbf136ca177acb68b4507579bc8fcee4d96537c9 Mon Sep 17 00:00:00 2001 From: "sentry-junior[bot]" <264270552+sentry-junior[bot]@users.noreply.github.com> Date: Thu, 26 Nov 2026 11:11:32 +0000 Subject: [PATCH 2/4] fix(sourcemap): Leave --ignore'd files out of the zero-pairs counts Discovery skips files matched by --ignore / --ignore-file, but the diagnostic that explains an empty result still counted them. Ignoring every .wasm next to a valid pair reported "none pair up", and ignoring every JS file reported JS files without maps. Both diagnostic walks now apply the same matcher, so the .wasm.map count still lines up with the JS tally it is subtracted from. Also pins the --dry-run report for wasm pairs: a pair a real run would stamp shows as modified, with its debug ID or (pending). Co-Authored-By: BYK <126780+BYK@users.noreply.github.com> --- packages/cli/src/commands/sourcemap/inject.ts | 3 +- packages/cli/src/commands/sourcemap/upload.ts | 3 +- packages/cli/src/lib/sourcemap/inject.ts | 7 +++- packages/cli/src/lib/sourcemap/wasm.ts | 10 ++--- .../test/commands/sourcemap/upload.test.ts | 42 +++++++++++++++++++ 5 files changed, 57 insertions(+), 8 deletions(-) diff --git a/packages/cli/src/commands/sourcemap/inject.ts b/packages/cli/src/commands/sourcemap/inject.ts index 7c1a764d7f..5bfd81e03b 100644 --- a/packages/cli/src/commands/sourcemap/inject.ts +++ b/packages/cli/src/commands/sourcemap/inject.ts @@ -213,7 +213,8 @@ export const injectCommand = buildCommand({ if (pairs.length === 0 && wasmPairs.length === 0 && !flags["allow-empty"]) { const diag = await addWasmDiscoveryCounts( dir, - await diagnoseEmptyDiscovery(dir, { extensions }), + await diagnoseEmptyDiscovery(dir, { extensions, ignoreMatcher }), + { ignoreMatcher }, ); throw buildEmptyDiscoveryError(dir, diag); } diff --git a/packages/cli/src/commands/sourcemap/upload.ts b/packages/cli/src/commands/sourcemap/upload.ts index aea08701bf..a32a24d7f9 100644 --- a/packages/cli/src/commands/sourcemap/upload.ts +++ b/packages/cli/src/commands/sourcemap/upload.ts @@ -475,9 +475,10 @@ export const uploadCommand = buildCommand({ target.dir, await diagnoseEmptyDiscovery(target.dir, { extensions, + ignoreMatcher, include: target.include, }), - { include: target.include }, + { ignoreMatcher, include: target.include }, ); throw buildEmptyDiscoveryError(dir, diag); } diff --git a/packages/cli/src/lib/sourcemap/inject.ts b/packages/cli/src/lib/sourcemap/inject.ts index 18d3e1474c..2be64870d5 100644 --- a/packages/cli/src/lib/sourcemap/inject.ts +++ b/packages/cli/src/lib/sourcemap/inject.ts @@ -747,8 +747,13 @@ export async function diagnoseEmptyDiscovery( maxFileSize: Number.POSITIVE_INFINITY, })) { const isMap = entry.absolutePath.endsWith(".map"); + const rel = relativePosix(absDir, entry.absolutePath); + // Discovery skips ignored files, so counting them would describe files + // the command never considered. + if (options.ignoreMatcher?.ignores(rel)) { + continue; + } if (options.include) { - const rel = relativePosix(absDir, entry.absolutePath); const matched = options.include(rel) || (isMap && options.include(rel.slice(0, -".map".length))); diff --git a/packages/cli/src/lib/sourcemap/wasm.ts b/packages/cli/src/lib/sourcemap/wasm.ts index 2a72f25341..8863252540 100644 --- a/packages/cli/src/lib/sourcemap/wasm.ts +++ b/packages/cli/src/lib/sourcemap/wasm.ts @@ -287,19 +287,19 @@ export async function discoverWasmPairs( * independently of modules, so a map left behind by a missing module is still * recognised as wasm. * - * Narrowed by the glob target only, exactly as `diagnoseEmptyDiscovery` is: - * the `.wasm.map` count is subtracted from the JS tally, so both walks must - * see the same files. + * Narrowed by the same ignore matcher and glob target as + * `diagnoseEmptyDiscovery`: the `.wasm.map` count is subtracted from the JS + * tally, so both walks must see the same files. * * @param dir - Directory to scan * @param js - The diagnostic from `diagnoseEmptyDiscovery` - * @param options - The glob filter the JS diagnostic used + * @param options - The ignore matcher and glob filter the JS diagnostic used * @returns The diagnostic with wasm counts filled in */ export async function addWasmDiscoveryCounts( dir: string, js: DiscoveryDiagnostic, - options: Pick = {}, + options: WasmDiscoveryOptions = {}, ): Promise { const absDir = resolvePath(dir); let wasmFiles = 0; diff --git a/packages/cli/test/commands/sourcemap/upload.test.ts b/packages/cli/test/commands/sourcemap/upload.test.ts index 5470b19c1f..4aac224ee7 100644 --- a/packages/cli/test/commands/sourcemap/upload.test.ts +++ b/packages/cli/test/commands/sourcemap/upload.test.ts @@ -47,6 +47,7 @@ async function writeWasmPair( type InjectFuncArgs = { ext?: string; + ignore?: string; "dry-run"?: boolean; "allow-empty"?: boolean; }; @@ -335,6 +336,47 @@ describe("sourcemap inject command — --allow-empty behavior", () => { expect(await readFile(mapPath)).toEqual(mapBefore); }); + test("--dry-run over a wasm pair: reports the pair it would change", async () => { + await writeWasmPair(dir, "stamped", WASM_DEBUG_ID); + await writeWasmPair(dir, "unstamped"); + const ctx = makeContext(); + + await func.call(ctx, { "dry-run": true }, dir); + + const out = ctx.stdout.write.mock.calls.map((c) => String(c[0])).join(""); + expect(out).toMatch(/Files modified\W+2/); + expect(out).toMatch(new RegExp(`✓ \\S*stamped\\.wasm → ${WASM_DEBUG_ID}`)); + expect(out).toMatch(/✓ \S*unstamped\.wasm → \(pending\)/); + }); + + test("--ignore: ignored wasm files are not counted in the zero-pairs error", async () => { + await writeWasmPair(dir, "app", WASM_DEBUG_ID); + const ctx = makeContext(); + try { + await func.call(ctx, { ignore: "*.wasm" }, dir); + expect.unreachable("should have thrown"); + } catch (err) { + expect(err).toBeInstanceOf(ValidationError); + const msg = (err as Error).message; + expect(msg).not.toContain("none pair up"); + expect(msg).toContain("1 .wasm.map file(s)"); + } + }); + + test("--ignore: ignored JS files are not counted in the zero-pairs error", async () => { + await mkdir(join(dir, "vendor")); + await writeFile(join(dir, "vendor", "lib.js"), "console.log(1)\n"); + await writeFile(join(dir, "vendor", "lib.js.map"), '{"version":3}\n'); + const ctx = makeContext(); + try { + await func.call(ctx, { ignore: "vendor/**" }, dir); + expect.unreachable("should have thrown"); + } catch (err) { + expect(err).toBeInstanceOf(ValidationError); + expect((err as Error).message).toMatch(/no JS or sourcemap files/i); + } + }); + test("sourceMappingURL: invalid inline base64 is skipped (zero pairs)", async () => { await writeFile( join(dir, "bad-inline.js"), From 08e9c3b42ad1146b6a13e1c78fe4828da57c3b26 Mon Sep 17 00:00:00 2001 From: "sentry-junior[bot]" <264270552+sentry-junior[bot]@users.noreply.github.com> Date: Thu, 26 Nov 2026 11:37:24 +0000 Subject: [PATCH 3/4] fix(sourcemap): Don't upload or misreport unusable wasm pairs A wasm-only directory whose pairs all had to be skipped (a .wasm that isn't a module, a broken map) still asked for credentials and uploaded an empty bundle. Pairs are now checked read-only first, so that case fails like an empty directory, or is a no-op with --allow-empty. A map that parses but isn't a sourcemap object, such as [] or null, threw a TypeError after the module was stamped. It is now rejected before anything is written. If the map write itself fails after the module got its build_id, the skip says so instead of claiming nothing was written. Co-Authored-By: BYK Co-Authored-By: bete --- packages/cli/src/commands/sourcemap/upload.ts | 22 +++++++- packages/cli/src/lib/sourcemap/debug-id.ts | 14 ++++- packages/cli/src/lib/sourcemap/wasm.ts | 49 +++++++++++++---- .../test/commands/sourcemap/upload.test.ts | 23 ++++++++ packages/cli/test/lib/sourcemap/wasm.test.ts | 53 ++++++++++++++++++- 5 files changed, 145 insertions(+), 16 deletions(-) diff --git a/packages/cli/src/commands/sourcemap/upload.ts b/packages/cli/src/commands/sourcemap/upload.ts index a32a24d7f9..9da361a8a6 100644 --- a/packages/cli/src/commands/sourcemap/upload.ts +++ b/packages/cli/src/commands/sourcemap/upload.ts @@ -43,6 +43,7 @@ import { addWasmDiscoveryCounts, discoverWasmPairs, syncWasmPairs, + type WasmPair, type WasmSyncResult, } from "../../lib/sourcemap/wasm.js"; import { sentry } from "../../lib/app-identity.js"; @@ -469,8 +470,25 @@ export const uploadCommand = buildCommand({ include: target.include, }); - if (pairs.length === 0 && wasmPairs.length === 0) { + // Read-only pass, so pairs that can't be used (a `.wasm` that isn't a + // module, a broken map) count as nothing to upload before any credential + // check or write. Each skipped pair is warned about here, once. + const usableWasmPairs: WasmPair[] = ( + await syncWasmPairs(wasmPairs, { dryRun: true }) + ) + .filter((result) => !result.skipped) + .map(({ wasmPath, mapPath }) => ({ wasmPath, mapPath })); + + if (pairs.length === 0 && usableWasmPairs.length === 0) { if (!flags["allow-empty"]) { + if (wasmPairs.length > 0) { + throw new ValidationError( + `Found ${wasmPairs.length} wasm sourcemap pair(s) in '${dir}' ` + + "but none can be uploaded; see the warnings above. Pass " + + "--allow-empty to suppress.", + "directory", + ); + } const diag = await addWasmDiscoveryCounts( target.dir, await diagnoseEmptyDiscovery(target.dir, { @@ -532,7 +550,7 @@ export const uploadCommand = buildCommand({ // pair, so it rides along on the manifest entries. // Skipped pairs were already warned about and are left out of the upload. const wasmResults = ( - await syncWasmPairs(wasmPairs, { dryRun: flags["no-rewrite"] }) + await syncWasmPairs(usableWasmPairs, { dryRun: flags["no-rewrite"] }) ).filter((result) => !result.skipped); const urlPrefix = flags["url-prefix"] ?? "~/"; diff --git a/packages/cli/src/lib/sourcemap/debug-id.ts b/packages/cli/src/lib/sourcemap/debug-id.ts index a7105c3b37..4f4e4a533e 100644 --- a/packages/cli/src/lib/sourcemap/debug-id.ts +++ b/packages/cli/src/lib/sourcemap/debug-id.ts @@ -152,13 +152,23 @@ export type SourcemapStampResult = { * * Some toolchains save maps with a BOM, which `JSON.parse` rejects. * - * @throws {SyntaxError} When the file is not JSON + * @throws {SyntaxError} When the file is not JSON, or not shaped like a + * sourcemap: an object whose `sources`, when present, is an array. Editing + * anything else would throw a `TypeError` partway through a run. */ export async function readSourcemapFile( mapPath: string, ): Promise { const text = (await readFile(mapPath, "utf-8")).replace(/^\uFEFF/, ""); - return JSON.parse(text) as SourcemapJson; + const map: unknown = JSON.parse(text); + if (typeof map !== "object" || map === null || Array.isArray(map)) { + throw new SyntaxError("expected a JSON object"); + } + const { sources } = map as { sources?: unknown }; + if (sources !== undefined && !Array.isArray(sources)) { + throw new SyntaxError("expected `sources` to be an array"); + } + return map; } /** diff --git a/packages/cli/src/lib/sourcemap/wasm.ts b/packages/cli/src/lib/sourcemap/wasm.ts index 8863252540..ac8102a3cc 100644 --- a/packages/cli/src/lib/sourcemap/wasm.ts +++ b/packages/cli/src/lib/sourcemap/wasm.ts @@ -33,7 +33,11 @@ import { } from "../wasm/build-id.js"; import { isDebugCompanionPath } from "../wasm/prepare.js"; import { ensureBuildIdOnDisk } from "../wasm/stamp.js"; -import { readSourcemapFile, setSourcemapDebugId } from "./debug-id.js"; +import { + readSourcemapFile, + type SourcemapStampResult, + setSourcemapDebugId, +} from "./debug-id.js"; import { type DiscoveryDiagnostic, type PathFilter, @@ -86,8 +90,9 @@ export type WasmSyncResult = { */ moduleStamped: boolean; /** - * Why the pair was left alone, when it was. A skipped pair has no debug ID, - * wrote nothing, and is not uploaded. + * Why the pair was left alone, when it was. A skipped pair has no debug ID + * and is not uploaded. It wrote nothing unless `moduleStamped` is set: the + * map write can still fail after the module got its `build_id`. */ skipped?: string; }; @@ -154,7 +159,7 @@ function skipReason(error: unknown): string | undefined { return `not a valid wasm module: ${error.message}`; } if (error instanceof SyntaxError) { - return `sourcemap is not valid JSON: ${error.message}`; + return `sourcemap is not a valid JSON sourcemap: ${error.message}`; } const code = (error as NodeJS.ErrnoException | undefined)?.code; if (code && UNWRITABLE_CODES.has(code)) { @@ -163,10 +168,19 @@ function skipReason(error: unknown): string | undefined { return undefined; } -/** Warn about a pair and report it as untouched. */ -function skip(pair: WasmPair, reason: string): WasmSyncResult { +/** + * Warn about a pair and report it as skipped. + * + * @param moduleStamped - Whether the module was already given a `build_id` + * before the pair had to be skipped + */ +function skip( + pair: WasmPair, + reason: string, + moduleStamped = false, +): WasmSyncResult { log.warn(`Skipping ${pair.wasmPath}: ${reason}`); - return { ...pair, mapWritten: false, moduleStamped: false, skipped: reason }; + return { ...pair, mapWritten: false, moduleStamped, skipped: reason }; } async function reconcilePair( @@ -206,9 +220,24 @@ async function reconcilePair( return { wasmPath, mapPath, mapWritten: moduleStamped, moduleStamped }; } - const stamp = await setSourcemapDebugId(mapPath, debugId, { - dryRun: options.dryRun, - }); + let stamp: SourcemapStampResult; + try { + stamp = await setSourcemapDebugId(mapPath, debugId, { + dryRun: options.dryRun, + }); + } catch (error) { + const reason = skipReason(error); + if (!reason || !moduleStamped || options.dryRun) { + throw error; + } + // The module already carries its new id, so say so rather than report + // a pair that wrote nothing. + return skip( + pair, + `${reason}; ${wasmPath} was already given build_id ${formatBuildId(buildId as Uint8Array)}`, + true, + ); + } if (stamp.replaced) { log.debug( `${mapPath} carried debug ID ${stamp.replaced}; replaced with the module's build_id ${debugId}`, diff --git a/packages/cli/test/commands/sourcemap/upload.test.ts b/packages/cli/test/commands/sourcemap/upload.test.ts index 4aac224ee7..97bff1a56a 100644 --- a/packages/cli/test/commands/sourcemap/upload.test.ts +++ b/packages/cli/test/commands/sourcemap/upload.test.ts @@ -1197,6 +1197,29 @@ describe("sourcemap upload command — --allow-empty behavior", () => { } }); + test("fails like an empty directory when no wasm pair is usable", async () => { + await writeFile(join(dir, "broken.wasm"), "Not Found"); + await writeFile( + join(dir, "broken.wasm.map"), + JSON.stringify({ version: 3, sources: [], names: [], mappings: "" }), + ); + + const uploadSpy = vi + .spyOn(sourcemapsApi, "uploadSourcemaps") + .mockResolvedValue(undefined); + try { + const ctx = makeContext(); + await expect(func.call(ctx, {}, dir)).rejects.toThrow( + /1 wasm sourcemap pair\(s\).*none can be uploaded/, + ); + // --allow-empty turns it into a no-op, with no upload either. + await func.call(ctx, { "allow-empty": true }, dir); + expect(uploadSpy).not.toHaveBeenCalled(); + } finally { + uploadSpy.mockRestore(); + } + }); + test("DWARF companions are not uploaded as sourcemap artifacts", async () => { await writeWasmPair(dir, "app", WASM_DEBUG_ID); await writeWasmPair( diff --git a/packages/cli/test/lib/sourcemap/wasm.test.ts b/packages/cli/test/lib/sourcemap/wasm.test.ts index 2023810783..d8c3306f13 100644 --- a/packages/cli/test/lib/sourcemap/wasm.test.ts +++ b/packages/cli/test/lib/sourcemap/wasm.test.ts @@ -11,7 +11,9 @@ import { tmpdir } from "node:os"; import { join } from "node:path"; import ignore from "ignore"; import picomatch from "picomatch"; -import { beforeEach, describe, expect, test } from "vitest"; +import { beforeEach, describe, expect, test, vi } from "vitest"; +// oxlint-disable-next-line sentry-cli/no-namespace-import -- needed for spyOn mocking +import * as replaceFileModule from "../../../src/lib/replace-file.js"; import { buildEmptyDiscoveryError } from "../../../src/lib/sourcemap/inject.js"; import { addWasmDiscoveryCounts, @@ -156,11 +158,58 @@ describe("syncWasmSourcemap", () => { const result = await syncWasmSourcemap({ wasmPath, mapPath }); - expect(result.skipped).toMatch(/not valid JSON/); + expect(result.skipped).toMatch(/not a valid JSON sourcemap/); expect(result.moduleStamped).toBe(false); expect(await readFile(wasmPath)).toEqual(before); }); + test.each([ + ["an array", "[]"], + ["null", "null"], + ["a map whose sources is not an array", '{"version":3,"sources":"app.c"}'], + ])("skips %s without stamping the module", async (_label, contents) => { + const wasmPath = await writeWasm("app.wasm"); + const before = await readFile(wasmPath); + const mapPath = join(dir, "app.wasm.map"); + await writeFile(mapPath, contents); + + const result = await syncWasmSourcemap({ wasmPath, mapPath }); + + expect(result.skipped).toMatch(/not a valid JSON sourcemap/); + expect(result.moduleStamped).toBe(false); + expect(await readFile(wasmPath)).toEqual(before); + expect(await readFile(mapPath, "utf-8")).toBe(contents); + }); + + test("reports the stamp when the map write fails after it", async () => { + const wasmPath = await writeWasm("app.wasm"); + const mapPath = await writeMap("app.wasm.map"); + const mapBefore = await readFile(mapPath); + const realReplace = replaceFileModule.replaceFile; + const spy = vi + .spyOn(replaceFileModule, "replaceFile") + .mockImplementation(async (path, data) => { + if (path === mapPath) { + throw Object.assign(new Error("permission denied"), { + code: "EACCES", + }); + } + return await realReplace(path, data); + }); + + try { + const result = await syncWasmSourcemap({ wasmPath, mapPath }); + + expect(result.skipped).toMatch(/cannot write files \(EACCES\)/); + expect(result.skipped).toMatch(/was already given build_id/); + expect(result.moduleStamped).toBe(true); + expect(await countBuildIdSections(wasmPath)).toBe(1); + expect(await readFile(mapPath)).toEqual(mapBefore); + } finally { + spy.mockRestore(); + } + }); + test("reads a map saved with a BOM", async () => { const wasmPath = await writeWasm("app.wasm", FIXED_UUID); const mapPath = join(dir, "app.wasm.map"); From 28d3b4cea72879ce7fa0821e8585cfb823709c4d Mon Sep 17 00:00:00 2001 From: "sentry-junior[bot]" <264270552+sentry-junior[bot]@users.noreply.github.com> Date: Mon, 30 Nov 2026 12:31:50 +0000 Subject: [PATCH 4/4] chore: Retrigger mergeability check after merging the base branch Co-Authored-By: BYK <126780+BYK@users.noreply.github.com>