Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
73 changes: 59 additions & 14 deletions packages/cli/src/lib/sourcemap/debug-id.ts
Original file line number Diff line number Diff line change
Expand Up @@ -111,6 +111,33 @@ export function hasDebugIdRegistration(js: string, debugId: string): boolean {
return false;
}

/**
* Read the debug ID a runtime snippet already registers, for a file that
* carries it nowhere else. A bundler plugin's output is in that state: the
* snippet is in the bundle, while the `//# debugId=` comment and the map's ID
* are only added to the copies the plugin uploads.
*
* Reusing it keeps the bundle on one ID. Minting another would add a second
* snippet, and the SDK reports the ID registered last, which is the original
* one and not the one the sourcemap was uploaded under.
*
* @param js - JavaScript file content
* @returns The canonical ID, or `undefined` when the file registers none, or
* registers more than one and so does not identify a single bundle
* @internal
*/
export function readRegisteredDebugId(js: string): string | undefined {
const ids = new Set<string>();
for (const match of js.matchAll(DEBUGID_REGISTRATION_RE)) {
const id = normalizeDebugId(match[2]);
if (id) {
ids.add(id);
}
}
const [only] = ids;
return ids.size === 1 ? only : undefined;
}

/**
* Read a pre-existing debug ID off a parsed sourcemap.
*
Expand Down Expand Up @@ -305,25 +332,32 @@ export async function injectDebugId(
// separator can't occur in JS/JSON text, so the two inputs can't bleed
// across the boundary. Collisions now require both files to be
// byte-identical, in which case sharing an ID is correct.
const debugId = existingId ?? contentToDebugId(`${jsContent}\0${mapContent}`);
//
// A file with no ID of its own may still register one at runtime; that ID
// is reused, see {@link readRegisteredDebugId}.
const registeredId =
existingId || skipRuntimeCheck
? undefined
: readRegisteredDebugId(jsContent);
const debugId =
existingId ??
registeredId ??
contentToDebugId(`${jsContent}\0${mapContent}`);

// --- Mutate JS file ---
let newJs: string;
if (skipSnippet) {
// Metadata-only mode: just append the debugId comment, no IIFE snippet.
// Used by the CLI's own build where the debug ID is registered in source.
newJs = jsContent;
} else {
// Full mode: prepend the runtime IIFE snippet (for user-facing injection).
newJs = prependDebugIdSnippet(jsContent, getDebugIdSnippet(debugId));
}
// No IIFE snippet in metadata-only mode (the CLI's own build registers the
// ID in source), nor when the bundle already registers this ID.
const addSnippet = !skipSnippet && !registeredId;
let newJs = addSnippet
? prependDebugIdSnippet(jsContent, getDebugIdSnippet(debugId))
: jsContent;
if (!jsDebugId) {
newJs += `\n${DEBUGID_COMMENT_PREFIX}${debugId}\n`;
}

// --- Mutate sourcemap ---
mutateSourcemap(map, debugId, {
snippetLine: skipSnippet ? undefined : countHeaderLines(jsContent),
snippetLine: addSnippet ? countHeaderLines(jsContent) : undefined,
});

// Write both files concurrently
Expand Down Expand Up @@ -503,8 +537,16 @@ export async function injectInlineDebugId(
// byte-identical inline map still get distinct debug IDs
// (getsentry/sentry-cli#3350). `jsContent` already embeds the inline map,
// so this is belt-and-suspenders, but keeps the two paths symmetric.
//
// As on the external path, an ID the bundle already registers is reused.
const registeredId =
existingId || isLikelyBinary(jsBytes)
? undefined
: readRegisteredDebugId(jsContent);
const debugId =
existingId ?? contentToDebugId(`${jsContent}\0${decoded.json}`);
existingId ??
registeredId ??
contentToDebugId(`${jsContent}\0${decoded.json}`);

// Locate the LAST inline directive to rewrite. If it can't be found (the
// discovery parser and this regex disagree on an edge case), abort WITHOUT
Expand All @@ -521,9 +563,10 @@ export async function injectInlineDebugId(
}

// Mutate the decoded map (IIFE adds one top line — same offset as external).
// A reused registration adds no snippet, so no line either.
const map = decoded.map as SourcemapJson;
mutateSourcemap(map, debugId, {
snippetLine: countHeaderLines(jsContent),
snippetLine: registeredId ? undefined : countHeaderLines(jsContent),
});
const newDataUrl = encodeInlineSourcemap(map, decoded.dataUrlPrefix);

Expand All @@ -540,7 +583,9 @@ export async function injectInlineDebugId(
newDataUrl +
jsContent.slice(end);

let newJs = prependDebugIdSnippet(rewritten, getDebugIdSnippet(debugId));
let newJs = registeredId
? rewritten
: prependDebugIdSnippet(rewritten, getDebugIdSnippet(debugId));
if (!jsDebugId) {
newJs += `\n${DEBUGID_COMMENT_PREFIX}${debugId}\n`;
}
Expand Down
10 changes: 8 additions & 2 deletions packages/cli/src/lib/sourcemap/inject.ts
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,7 @@ import {
injectDebugId,
injectInlineDebugId,
readJsDebugId,
readRegisteredDebugId,
readSourcemapDebugId,
} from "./debug-id.js";
import {
Expand Down Expand Up @@ -179,16 +180,21 @@ export async function injectDirectory(
// Match the real run's ID precedence and runtime registration check.
const jsBytes = await readFile(jsPath);
const js = jsBytes.toString("utf-8");
const binary = isLikelyBinary(jsBytes);
const existing = readJsDebugId(js) ?? (await readMapDebugId(map));
// An ID the bundle only registers at runtime is reused; the file still
// changes, since the comment and the map ID are written.
const registered =
existing || binary ? undefined : readRegisteredDebugId(js);
results.push({
jsPath,
map,
mapPath,
injected: !(
existing &&
(isLikelyBinary(jsBytes) || hasDebugIdRegistration(js, existing))
(binary || hasDebugIdRegistration(js, existing))
),
debugId: existing ?? "(pending)",
debugId: existing ?? registered ?? "(pending)",
});
continue;
}
Expand Down
92 changes: 92 additions & 0 deletions packages/cli/test/lib/sourcemap/inject.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -683,6 +683,98 @@ describe.each(["external", "inline"] as const)(
},
);

// What a bundler plugin leaves in its output directory: the snippet, but
// neither the comment nor a map ID (getsentry/toolkit#2269).
const pluginSnippet = (id: string): string =>
`!function(){try{var e="undefined"!=typeof globalThis?globalThis:"undefined"!=typeof window?window:"undefined"!=typeof global?global:"undefined"!=typeof self?self:{};var n=(new e.Error).stack;n&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[n]="${id}",e._sentryDebugIdIdentifier="sentry-dbid-${id}");}catch(e){}}();`;

/** Write `main.js` with no debug ID comment and a map with no ID. */
function writeUnstampedBundle(body: string): {
jsPath: string;
js: string;
} {
const jsPath = join(dir, "main.js");
const mapContent = JSON.stringify({
version: 3,
sources: ["main.ts"],
names: [],
mappings: ";AAAA",
});
const mapUrl =
kind === "inline"
? `data:application/json;base64,${Buffer.from(mapContent).toString("base64")}`
: "main.js.map";
const js = `${body}\n//# sourceMappingURL=${mapUrl}\n`;
writeFileSync(jsPath, js);
if (kind === "external") {
writeFileSync(`${jsPath}.map`, mapContent);
}
return { jsPath, js };
}

/** Read back the map that injection wrote, external or inline. */
function readInjectedMap(jsPath: string): Record<string, unknown> {
if (kind === "external") {
return JSON.parse(readFileSync(`${jsPath}.map`, "utf-8"));
}
const url = readFileSync(jsPath, "utf-8").match(
/\/\/# sourceMappingURL=(\S+)/,
)?.[1];
return tryDecodeInlineSourcemap(url ?? "")?.map as Record<
string,
unknown
>;
}

test("reuses an ID that is only registered at runtime", async () => {
const snippet = pluginSnippet(debugId);
const { jsPath, js } = writeUnstampedBundle(snippet);

expect((await injectDirectory(dir, { dryRun: true }))[0]).toMatchObject({
debugId,
injected: true,
});
expect(readFileSync(jsPath, "utf-8")).toBe(js);

expect((await injectDirectory(dir))[0]).toMatchObject({
debugId,
injected: true,
});
const after = readFileSync(jsPath, "utf-8");
// No second snippet: the bundle still starts with its own.
expect(after.startsWith(snippet)).toBe(true);
expect(after).toContain(`//# debugId=${debugId}`);
expect(readInjectedMap(jsPath)).toMatchObject({
debug_id: debugId,
debugId,
mappings: ";AAAA",
});
const sandbox: { _sentryDebugIds?: Record<string, string> } = {};
runInNewContext(after, sandbox, { filename: "main.js" });
expect(Object.values(sandbox._sentryDebugIds ?? {})).toEqual([debugId]);

// A second run finds the comment and the registration, and does nothing.
expect((await injectDirectory(dir))[0]).toMatchObject({
debugId,
injected: false,
});
expect(readFileSync(jsPath, "utf-8")).toBe(after);
});

test("mints an ID when two different IDs are registered at runtime", async () => {
const otherId = "99999999-8888-5777-9666-555555555555";
const { jsPath } = writeUnstampedBundle(
`${pluginSnippet(debugId)}\n${pluginSnippet(otherId)}`,
);

const [result] = await injectDirectory(dir);
expect(result?.injected).toBe(true);
expect([debugId, otherId]).not.toContain(result?.debugId);
// Two chunks concatenated into one file do not identify one bundle, so
// the file gets its own ID and snippet as before.
expect(readFileSync(jsPath, "utf-8").startsWith(";!function")).toBe(true);
});

test.each(["comment", "debugId", "debug_id", "comment and map"])(
"registers an ID from %s exactly once",
async (source) => {
Expand Down
Loading