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
12 changes: 12 additions & 0 deletions .changeset/sentry-debug-id-plugin.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
---
"@callstack/repack": minor
---

Add `SentryDebugIdPlugin`, which stamps a Sentry Debug ID into the bundle and
its source map so Sentry can pair a JS stack trace with the source map that
resolves it. This is the Re.Pack counterpart of what `@sentry/react-native`
provides for Metro through `createSentryMetroSerializer`.

The Debug ID is derived from the bundle content, and the runtime snippet is
copied from `@sentry/bundler-plugin-core`. `HermesBytecodePlugin` now carries
the Debug ID over to the composed source map.
Original file line number Diff line number Diff line change
@@ -1,6 +1,10 @@
import fs from 'node:fs';
import path from 'node:path';
import execa from 'execa';
import {
addDebugIdToSourceMap,
getSourceMapDebugId,
} from '../../utils/sourceMapDebugId.js';

/**
* {@link composeSourceMaps} options.
Expand Down Expand Up @@ -33,11 +37,28 @@ export const composeSourceMaps = async ({
const composedSourceMapPath = packagerMapPath + '.composed';

try {
// `compose-source-maps.js` writes a fresh map without the Debug ID, and the packager map is
// removed below, so carry the id over to the composed map.
const debugId = getSourceMapDebugId(
await fs.promises.readFile(packagerMapPath, 'utf-8')
);

await execa.node(
path.join(reactNativePath, 'scripts', 'compose-source-maps.js'),
[packagerMapPath, compilerMapPath, '-o', composedSourceMapPath]
);

if (debugId) {
const composedSourceMap = await fs.promises.readFile(
composedSourceMapPath,
'utf-8'
);
await fs.promises.writeFile(
composedSourceMapPath,
addDebugIdToSourceMap(composedSourceMap, debugId)
);
}

// Remove intermediate files
await fs.promises.unlink(packagerMapPath);
await fs.promises.unlink(compilerMapPath);
Expand Down
191 changes: 191 additions & 0 deletions packages/repack/src/plugins/SentryDebugIdPlugin.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,191 @@
import { createHash } from 'node:crypto';
import type { Compiler as RspackCompiler } from '@rspack/core';
import type { Compiler as WebpackCompiler } from 'webpack';

import { addDebugIdToSourceMap } from './utils/sourceMapDebugId.js';

/**
* {@link SentryDebugIdPlugin} configuration options.
*/
export interface SentryDebugIdPluginConfig {
/**
* Matches the bundles that should receive a Debug ID.
*
* @default /\.([cm]?jsx?|bundle)$/
*/
test?: RegExp;
}

const DEFAULT_TEST = /\.([cm]?jsx?|bundle)$/;

const PLUGIN_NAME = 'RepackSentryDebugIdPlugin';

/**
* Creates the snippet that registers the Debug ID on the global object.
*
* The snippet is copied from `@sentry/bundler-plugin-core`, so the Sentry SDK picks the id up at
* runtime. Diff against it when Sentry changes the format. The function wrapper keeps its
* variables out of the global scope, since the snippet runs at the top level of the bundle.
*/
function getDebugIdSnippet(debugId: string) {
return `;!function(){try{var e="undefined"!=typeof window?window:"undefined"!=typeof global?global:"undefined"!=typeof globalThis?globalThis:"undefined"!=typeof self?self:{};var n=(new e.Error).stack;n&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[n]="${debugId}",e._sentryDebugIdIdentifier="sentry-dbid-${debugId}")}catch(e){}}();\n`;
}

/**
* Turns a string into a UUID the same way `stringToUUID` in `@sentry/bundler-plugin-core` does,
* so the same input always gets the same Debug ID.
*/
function stringToUUID(value: string) {
const hash = createHash('sha256').update(value).digest('hex');
const variant = ['8', '9', 'a', 'b'][hash.charCodeAt(16) % 4];
return [
hash.substring(0, 8),
hash.substring(8, 12),
`4${hash.substring(13, 16)}`,
`${variant}${hash.substring(17, 20)}`,
hash.substring(20, 32),
].join('-');
}

/**
* Plugin for stamping a Sentry Debug ID into the bundle and its source map.
*
* A Debug ID is a UUID present in both artifacts. Sentry uses it to pair a JS stack trace with
* the source map that resolves it, which is what Metro provides through
* `@sentry/react-native`'s `createSentryMetroSerializer`.
*
* `@sentry/webpack-plugin` cannot fill this role for React Native: it only processes `.js`-like
* filenames, so it skips `index.bundle` and its source map.
*
* The plugin only runs in `production` mode, like `createSentryMetroSerializer`, which skips
* development builds.
*
* @example Usage in Rspack config (ESM):
* ```ts
* import * as Repack from '@callstack/repack';
*
* export default (env) => ({
* plugins: [new Repack.plugins.SentryDebugIdPlugin()],
* });
* ```
*
* @category Webpack Plugin
*/
export class SentryDebugIdPlugin {
constructor(private config: SentryDebugIdPluginConfig = {}) {}

apply(compiler: RspackCompiler): void;
apply(compiler: WebpackCompiler): void;

apply(__compiler: unknown) {
Comment thread
MrMuzyk marked this conversation as resolved.
Resolved
const compiler = __compiler as RspackCompiler;
const logger = compiler.getInfrastructureLogger(PLUGIN_NAME);

// Plugins are applied before config defaults, and an unset mode means production.
if ((compiler.options.mode ?? 'production') !== 'production') {
logger.debug('Skipping Debug IDs outside of production mode.');
return;
}

const { Compilation, sources } = compiler.webpack;
const test = this.config.test ?? DEFAULT_TEST;

compiler.hooks.thisCompilation.tap(PLUGIN_NAME, (compilation) => {
// Scoped to the compilation, so watch rebuilds never reuse a stale id.
const debugIds = new Map<string, string>();

// Inject before minification and source map generation, so the snippet is minified with the
// bundle and the maps account for it. The id comes from the chunk's pre-injection hash,
// since a hash of the output would depend on the id it contains.
compilation.hooks.processAssets.tap(
{
name: PLUGIN_NAME,
stage: Compilation.PROCESS_ASSETS_STAGE_ADDITIONS,
},
() => {
for (const chunk of compilation.chunks) {
for (const file of chunk.files) {
const asset = compilation.getAsset(file);
if (!asset || !test.test(file)) {
continue;
}

const debugId = stringToUUID(
chunk.contentHash.javascript ??
chunk.hash ??
asset.source.source().toString()
);
debugIds.set(file, debugId);

compilation.updateAsset(
file,
(source) =>
new sources.ConcatSource(getDebugIdSnippet(debugId), source)
);
Comment on lines +120 to +124

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🟡 Minor · Prepending the Debug ID snippet breaks strict-mode semantics of the bundle

Prepending ;{try{...}} before a bundle whose first statement is "use strict" (or "use asm" or a shebang) means the directive is no longer the first statement, so the whole bundle silently loses strict-mode. The snippet is inserted as the very first bytes of the asset via ConcatSource(getDebugIdSnippet(debugId), source) with no check of what the asset starts with. Rspack/webpack emit "use strict" at the top of generated modules, and the default test /\.([cm]?jsx?|bundle)$/ matches those assets.

⚠️ Check this patch before you commit it: the review doubted it would be right as written.

Suggested change
compilation.updateAsset(
file,
(source) =>
new sources.ConcatSource(getDebugIdSnippet(debugId), source)
);
compilation.updateAsset(
file,
(source) =>
new sources.ConcatSource(
source,
getDebugIdSnippet(debugId)
)
);

Suggested change

Append the snippet after the existing source instead of prepending it (Metro does the same), or detect a leading "use strict"/"use asm"/shebang directive and insert the snippet after it. Note that appending shifts the debug-id comment position, so keep the //# debugId= insertion logic consistent with wherever the snippet lands.

Details

persona: senior-developer

Useful? Reply @apex-sentinel-staging like, or @apex-sentinel-staging dislike <why> if it is not.

Reply @apex-sentinel-staging note ... to add context, or @apex-sentinel-staging pivot ... if it is wrong — I will re-check the cited code.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@apex-sentinel-staging pivot False positive for Re.Pack output. Rspack/webpack wrap the bundle in an IIFE (output.iife defaults to true), so "use strict" is a function-level directive inside the wrapper, and a statement before it doesn't change it. Real iOS/Android production bundles don't start with a "use strict" directive: Re.Pack's own repackGlobal banner (var self = self || this || ...) is already the first statement, and it relies on sloppy-mode this. Shebangs and "use asm" don't appear in RN bundles. Prepending also matches upstream: @sentry/webpack-plugin prepends the same snippet, and createSentryMetroSerializer puts the debug ID module first, not last. Appending would also break the //# debugId= placement before //# sourceMappingURL=.

}
}
}
);

// Stamp the maps right after the devtool stage emits them, so later stages, like content
// hashing, see the final assets.
compilation.hooks.processAssets.tap(
{
name: PLUGIN_NAME,
stage: Compilation.PROCESS_ASSETS_STAGE_DEV_TOOLING + 1,
},
() => {
for (const [file, debugId] of debugIds) {
const asset = compilation.getAsset(file);
if (!asset) {
continue;
}

// `sentry-cli` pairs the bundle with its map through this comment, which matters for
// JSC builds and for uploads outside the Gradle and Xcode scripts.
const code = asset.source.source().toString();
const sourceMappingURLIndex = code.lastIndexOf(
'//# sourceMappingURL='
);
compilation.updateAsset(file, (source) => {
const updated = new sources.ReplaceSource(source);
if (sourceMappingURLIndex === -1) {
updated.insert(code.length, `\n//# debugId=${debugId}\n`);
} else {
updated.insert(
sourceMappingURLIndex,
`//# debugId=${debugId}\n`
);
}
return updated;
});

const related = asset.info.related?.sourceMap;
const mapFile = [
...(Array.isArray(related) ? related : [related]),
`${file}.map`,
].find(
(name): name is string => !!name && !!compilation.getAsset(name)
);
if (!mapFile) {
continue;
}

let sourceMap: string;
try {
sourceMap = addDebugIdToSourceMap(
compilation.getAsset(mapFile)!.source.source().toString(),
debugId
);
} catch {
logger.warn(`Could not parse ${mapFile}, skipping Debug ID.`);
continue;
}

compilation.updateAsset(mapFile, new sources.RawSource(sourceMap));
}
}
);
});
}
}
39 changes: 39 additions & 0 deletions packages/repack/src/plugins/__tests__/HermesBytecodePlugin.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ import path from 'node:path';
import { type Compiler, ModuleFilenameHelpers } from '@rspack/core';
import execa from 'execa';
import { HermesBytecodePlugin } from '../HermesBytecodePlugin/index.js';
import { composeSourceMaps } from '../HermesBytecodePlugin/utils/composeSourceMaps.js';
import { getHermesCLIPath } from '../HermesBytecodePlugin/utils/getHermesCLIPath.js';

jest.mock('node:fs', () => ({
Expand All @@ -12,8 +13,10 @@ jest.mock('node:fs', () => ({
existsSync: jest.fn(),
promises: {
access: jest.fn(),
readFile: jest.fn(),
rename: jest.fn(),
unlink: jest.fn(),
writeFile: jest.fn(),
},
},
}));
Expand Down Expand Up @@ -213,6 +216,42 @@ describe('HermesBytecodePlugin', () => {
]);
});

describe('composeSourceMaps', () => {
const options = {
reactNativePath: 'path/to/react-native',
packagerMapPath: 'output/path/example.bundle.map',
compilerMapPath: 'output/path/example.bundle.hbc.map',
};

it('carries the Debug ID over to the composed source map', async () => {
const debugId = '3f1c2d4e-5a6b-4c7d-8e9f-0a1b2c3d4e5f';
const fsMock = fs.promises as jest.Mocked<typeof fs.promises>;
fsMock.readFile
.mockResolvedValueOnce(`{"version":3,"debugId":"${debugId}"}`)
.mockResolvedValueOnce('{"version":3}');

await composeSourceMaps(options);

expect(fsMock.writeFile).toHaveBeenCalledWith(
`${options.packagerMapPath}.composed`,
`{"version":3,"debugId":"${debugId}","debug_id":"${debugId}"}`
);
expect(fsMock.rename).toHaveBeenCalledWith(
`${options.packagerMapPath}.composed`,
options.packagerMapPath
);
});

it('leaves the composed source map alone without a Debug ID', async () => {
const fsMock = fs.promises as jest.Mocked<typeof fs.promises>;
fsMock.readFile.mockResolvedValueOnce('{"version":3}');

await composeSourceMaps(options);

expect(fsMock.writeFile).not.toHaveBeenCalled();
});
});

describe('getHermesCLIPath', () => {
const reactNativePath = 'path/to/react-native';

Expand Down
Loading
Loading