Skip to content

Commit cfc11a6

Browse files
emanueleperuffoEmanuele Peruffo
andauthored
fix: compose Hermes source maps for every chunk (#1516)
Co-authored-by: Emanuele Peruffo <emanuele.peruffo@klarna.com>
1 parent 171e3ec commit cfc11a6

3 files changed

Lines changed: 138 additions & 47 deletions

File tree

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,5 @@
1+
---
2+
"@callstack/repack": patch
3+
---
4+
5+
Fix `HermesBytecodePlugin` skipping source map composition for many chunks. The plugin ran in `assetEmitted`, where a chunk's `.map` file might not be written yet, so hermesc ran without source maps, embedded debug info in the bytecode and skipped source map composition. It now runs in `afterEmit`, once all assets are on disk.

‎packages/repack/src/plugins/HermesBytecodePlugin/HermesBytecodePlugin.ts‎

Lines changed: 52 additions & 32 deletions
Original file line numberDiff line numberDiff line change
@@ -105,9 +105,13 @@ export class HermesBytecodePlugin {
105105
const hermesCLIPath =
106106
this.config.hermesCLIPath || getHermesCLIPath(reactNativePath);
107107

108-
compiler.hooks.assetEmitted.tapPromise(
109-
{ name: 'RepackHermesBytecodePlugin', stage: 10 },
110-
async (file, { outputPath }) => {
108+
const emittedAssets = new Map<string, string>();
109+
110+
// Only assets written in this compilation: on rebuilds in the same process, unchanged
111+
// assets are not re-emitted and are already bytecode on disk.
112+
compiler.hooks.assetEmitted.tap(
113+
'RepackHermesBytecodePlugin',
114+
(file, { outputPath }) => {
111115
const shouldTransformAsset =
112116
compiler.webpack.ModuleFilenameHelpers.matchObject(
113117
{
@@ -118,37 +122,53 @@ export class HermesBytecodePlugin {
118122
file
119123
);
120124

121-
if (!shouldTransformAsset) {
122-
return;
125+
if (shouldTransformAsset) {
126+
emittedAssets.set(file, outputPath);
123127
}
128+
}
129+
);
124130

125-
const bundlePath = path.join(outputPath, file);
126-
const sourceMapPath = `${bundlePath}.map`;
127-
const useSourceMaps = await fs.promises
128-
.access(sourceMapPath)
129-
.then(() => true)
130-
.catch(() => false);
131-
132-
logger.debug(`Starting hermes compilation for asset: ${bundlePath}`);
133-
134-
const { sourceMap: hermesSourceMapPath } =
135-
await transformBundleToHermesBytecode({
136-
hermesCLIPath,
137-
useSourceMaps,
138-
bundlePath,
139-
});
140-
141-
logger.info(`Asset transformed: ${file}`);
142-
143-
if (useSourceMaps) {
144-
await composeSourceMaps({
145-
reactNativePath,
146-
packagerMapPath: sourceMapPath,
147-
compilerMapPath: hermesSourceMapPath,
148-
});
149-
150-
logger.info(`Asset sourceMap transformed: ${file}.map`);
151-
}
131+
// Transform once every asset is on disk: a chunk's `.map` can still be unwritten when its own
132+
// `assetEmitted` fires, which made hermesc run without source maps and skipped composition.
133+
compiler.hooks.afterEmit.tapPromise(
134+
{ name: 'RepackHermesBytecodePlugin', stage: -100 },
135+
async () => {
136+
const assets = Array.from(emittedAssets);
137+
emittedAssets.clear();
138+
139+
await Promise.all(
140+
assets.map(async ([file, outputPath]) => {
141+
const bundlePath = path.join(outputPath, file);
142+
const sourceMapPath = `${bundlePath}.map`;
143+
const useSourceMaps = await fs.promises
144+
.access(sourceMapPath)
145+
.then(() => true)
146+
.catch(() => false);
147+
148+
logger.debug(
149+
`Starting hermes compilation for asset: ${bundlePath}`
150+
);
151+
152+
const { sourceMap: hermesSourceMapPath } =
153+
await transformBundleToHermesBytecode({
154+
hermesCLIPath,
155+
useSourceMaps,
156+
bundlePath,
157+
});
158+
159+
logger.info(`Asset transformed: ${file}`);
160+
161+
if (useSourceMaps) {
162+
await composeSourceMaps({
163+
reactNativePath,
164+
packagerMapPath: sourceMapPath,
165+
compilerMapPath: hermesSourceMapPath,
166+
});
167+
168+
logger.info(`Asset sourceMap transformed: ${file}.map`);
169+
}
170+
})
171+
);
152172
}
153173
);
154174
}

‎packages/repack/src/plugins/__tests__/HermesBytecodePlugin.test.ts‎

Lines changed: 81 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -20,6 +20,13 @@ jest.mock('node:fs', () => ({
2020

2121
jest.mock('execa');
2222

23+
function emitAssets(files: string[]) {
24+
const [, onAssetEmitted] = compilerMock.hooks.assetEmitted.tap.mock.calls[0];
25+
for (const file of files) {
26+
onAssetEmitted(file, { outputPath: 'output/path/' });
27+
}
28+
}
29+
2330
const compilerMock = {
2431
context: __dirname,
2532
options: {
@@ -29,6 +36,9 @@ const compilerMock = {
2936
},
3037
hooks: {
3138
assetEmitted: {
39+
tap: jest.fn(),
40+
},
41+
afterEmit: {
3242
tapPromise: jest.fn(),
3343
},
3444
},
@@ -56,7 +66,7 @@ describe('HermesBytecodePlugin', () => {
5666

5767
pluginInstance.apply(compilerMock as unknown as Compiler);
5868

59-
expect(compilerMock.hooks.assetEmitted.tapPromise).not.toHaveBeenCalled();
69+
expect(compilerMock.hooks.afterEmit.tapPromise).not.toHaveBeenCalled();
6070
});
6171

6272
it('overrides compareBeforeEmit webpack option by default', () => {
@@ -87,11 +97,10 @@ describe('HermesBytecodePlugin', () => {
8797
fsMock.access.mockResolvedValueOnce();
8898

8999
await new Promise<void>((resolve, reject) => {
90-
compilerMock.hooks.assetEmitted.tapPromise.mockImplementationOnce(
100+
compilerMock.hooks.afterEmit.tapPromise.mockImplementationOnce(
91101
(_, callback) => {
92-
callback('example.bundle', { outputPath: 'output/path/' })
93-
.then(resolve)
94-
.catch(reject);
102+
emitAssets(['example.bundle']);
103+
callback().then(resolve).catch(reject);
95104
}
96105
);
97106
pluginInstance.apply(compilerMock as unknown as Compiler);
@@ -101,9 +110,7 @@ describe('HermesBytecodePlugin', () => {
101110
typeof execa.node
102111
>;
103112

104-
expect(compilerMock.hooks.assetEmitted.tapPromise).toHaveBeenCalledTimes(
105-
1
106-
);
113+
expect(compilerMock.hooks.afterEmit.tapPromise).toHaveBeenCalledTimes(1);
107114
expect(execaMock).toHaveBeenCalledTimes(1);
108115
expect(execaMock.mock.calls[0][0]).toEqual('path/to/hermesc');
109116

@@ -127,26 +134,85 @@ describe('HermesBytecodePlugin', () => {
127134
fsMock.access.mockRejectedValueOnce(new Error('File not found'));
128135

129136
await new Promise<void>((resolve, reject) => {
130-
compilerMock.hooks.assetEmitted.tapPromise.mockImplementationOnce(
137+
compilerMock.hooks.afterEmit.tapPromise.mockImplementationOnce(
131138
(_, callback) => {
132-
callback('example.bundle', { outputPath: 'output/path/' })
133-
.then(resolve)
134-
.catch(reject);
139+
emitAssets(['example.bundle']);
140+
callback().then(resolve).catch(reject);
135141
}
136142
);
137143
pluginInstance.apply(compilerMock as unknown as Compiler);
138144
});
139145

140146
const execaMock = execa as jest.MockedFunction<typeof execa>;
141147

142-
expect(compilerMock.hooks.assetEmitted.tapPromise).toHaveBeenCalledTimes(
143-
1
144-
);
148+
expect(compilerMock.hooks.afterEmit.tapPromise).toHaveBeenCalledTimes(1);
145149
expect(execaMock).toHaveBeenCalledTimes(1);
146150
expect(execaMock.mock.calls[0][0]).toEqual('path/to/hermesc');
147151
});
148152
});
149153

154+
it('transforms every matching asset and skips excluded ones', async () => {
155+
const pluginInstance = new HermesBytecodePlugin({
156+
enabled: true,
157+
test: /\.(js)?bundle$/,
158+
exclude: /index.bundle$/,
159+
reactNativePath: 'path/to/react-native',
160+
hermesCLIPath: 'path/to/hermesc',
161+
});
162+
163+
const fsMock = fs.promises as jest.Mocked<typeof fs.promises>;
164+
fsMock.access.mockResolvedValue();
165+
166+
await new Promise<void>((resolve, reject) => {
167+
compilerMock.hooks.afterEmit.tapPromise.mockImplementationOnce(
168+
(_, callback) => {
169+
emitAssets(['a.chunk.bundle', 'b.chunk.bundle', 'index.bundle']);
170+
callback().then(resolve).catch(reject);
171+
}
172+
);
173+
pluginInstance.apply(compilerMock as unknown as Compiler);
174+
});
175+
176+
const execaMock = execa as jest.MockedFunction<typeof execa>;
177+
const execaNodeMock = execa.node as jest.MockedFunction<typeof execa.node>;
178+
179+
expect(execaMock).toHaveBeenCalledTimes(2);
180+
expect(execaNodeMock).toHaveBeenCalledTimes(2);
181+
});
182+
183+
it('ignores unchanged assets on rebuild', async () => {
184+
const pluginInstance = new HermesBytecodePlugin({
185+
enabled: true,
186+
test: /\.(js)?bundle$/,
187+
exclude: /index.bundle$/,
188+
reactNativePath: 'path/to/react-native',
189+
hermesCLIPath: 'path/to/hermesc',
190+
});
191+
192+
const fsMock = fs.promises as jest.Mocked<typeof fs.promises>;
193+
fsMock.access.mockResolvedValue();
194+
195+
pluginInstance.apply(compilerMock as unknown as Compiler);
196+
const [, afterEmit] = compilerMock.hooks.afterEmit.tapPromise.mock.calls[0];
197+
198+
emitAssets(['a.chunk.bundle', 'b.chunk.bundle']);
199+
await afterEmit();
200+
201+
emitAssets(['b.chunk.bundle']);
202+
await afterEmit();
203+
204+
const execaMock = execa as jest.MockedFunction<typeof execa>;
205+
const transformedBundles = execaMock.mock.calls.map(([, args]) =>
206+
(args as string[]).at(-1)
207+
);
208+
209+
expect(transformedBundles).toEqual([
210+
path.join('output/path/', 'a.chunk.bundle'),
211+
path.join('output/path/', 'b.chunk.bundle'),
212+
path.join('output/path/', 'b.chunk.bundle'),
213+
]);
214+
});
215+
150216
describe('getHermesCLIPath', () => {
151217
const reactNativePath = 'path/to/react-native';
152218

0 commit comments

Comments
 (0)