Fix Hermes bytecode version mismatch in SwiftPM Release builds (#57928)

Summary:
`react-native spm add`'s Release builds crash on launch with:

```
Compiling JS failed: Wrong bytecode version. Expected 99 but got 98
```

This happens because the SwiftPM integration resolves the Hermes **runtime**
(the downloaded `hermes-engine.xcframework`) and the Hermes **compiler** (the
`hermesc` binary that turns the JS bundle into bytecode) from two independent,
unsynced sources:

- `download-spm-artifacts.js`'s `resolveHermesArtifact()` picked the runtime
  by querying the `hermes-compiler` package's `latest-v1` dist-tag on the npm
  registry **live, at build time**.
- `generate-spm-xcodeproj.js`'s `resolveHermesCliPathSetting()` (and
  `react-native-xcode.sh`, for the CocoaPods-free fallback) points
  `HERMES_CLI_PATH` at the `hermes-compiler` package **already installed in
  this project's own `node_modules`** — whatever got pinned the last time
  `npm install` ran.

If the `latest-v1` dist-tag advances on npm between `npm install` and the
Release build (which happens routinely as new Hermes builds are published),
the downloaded VM and the locally pinned `hermesc` fall out of sync and the
app crashes at launch. `react-native-xcode.sh` already documents this exact
invariant ("react native pins the hermes-compiler version, so the compiler's
bytecode version always matches the prebuilt hermes VM artifacts") — SwiftPM's
artifact download just wasn't honoring it.

This PR makes `resolveHermesArtifact()` read the pinned `hermes-compiler`
version from `node_modules` first (the same `require.resolve` lookup already
used for `HERMES_CLI_PATH`), so the runtime download and the compiler always
agree. It falls back to the previous `latest-v1` npm lookup only when
`hermes-compiler` isn't locally resolvable (e.g. `USE_HERMES=false` apps that
never installed it). Explicit `HERMES_VERSION` overrides (`nightly`,
`latest-v1`, a literal version) are unchanged.

Fixes https://github.com/react/react-native/issues/57917.

## Changelog:

[IOS] [FIXED] - Fix Hermes runtime/compiler version mismatch causing "Wrong bytecode version" crashes in SwiftPM Release builds

Pull Request resolved: https://github.com/react/react-native/pull/57928

Test Plan:
Added unit tests covering the new local-resolution path, the fallback when
`hermes-compiler` isn't installed, and confirming existing `HERMES_VERSION`
overrides still take precedence over the local pin.

```
$ node_modules/.bin/jest packages/react-native/scripts/spm/__tests__/download-spm-artifacts-test.js
Test Suites: 1 passed, 1 total
Tests:       70 passed, 70 total

$ node_modules/.bin/flow check packages/react-native/scripts/spm/download-spm-artifacts.js
No errors!

$ node_modules/.bin/eslint packages/react-native/scripts/spm/download-spm-artifacts.js packages/react-native/scripts/spm/__tests__/download-spm-artifacts-test.js
(no output — clean)

$ node_modules/.bin/prettier --check packages/react-native/scripts/spm/download-spm-artifacts.js packages/react-native/scripts/spm/__tests__/download-spm-artifacts-test.js
All matched files use Prettier code style!
```

Reproduced the crash and confirmed the fix end-to-end using the public
reproducer linked from the issue
(https://github.com/marandaneto/react-native-087-swiftpm-hermes-bytecode-repro):

- Before the fix: `npm run reproduce` builds successfully but launching the
  app in the iOS Simulator crashes with `Compiling JS failed: Wrong bytecode
  version. Expected 99 but got 98`.
- After applying the equivalent fix to the reproducer's installed
  `react-native` copy: the log shows `Using locally pinned hermes-compiler:
  250829098.0.16`, and both the debug and release Hermes runtime artifacts
  resolve to that exact version — matching the `hermesc` used for
  `HERMES_CLI_PATH`. `xcodebuild ... -configuration Release` succeeds, and
  the app installs and launches cleanly on an iPhone 17 Pro (iOS 26.5)
  simulator with no crash.

Reviewed By: cortinico

Differential Revision: D115859923

Pulled By: cipolleschi

fbshipit-source-id: 1b65a7aa28f502374a3553c1849b8ff29b5afd10
This commit is contained in:
Nycollas authored and meta-codesync[bot] committed 2026-08-14 07:12:17 -07:00
1 parent 88043334e3
commit ead93778a1
2 files changed
+191 -28

No files matched your search

@@ -23,6 +23,7 @@ const {
resolveCacheSlotVersion,
resolveHermesArtifact,
resolveLatestV1Version,
resolveLocalHermesCompilerVersion,
resolveNightlyVersion,
resolveRNCoreArtifact,
resolveRNDepsArtifact,
@@ -95,6 +96,67 @@ function routerFetch(routes /*: {[string]: any} */) {
// artifact at the RN nightly version (which won't exist on Maven).
// ---------------------------------------------------------------------------
// Creates a scratch dir with (optionally) a `node_modules/hermes-compiler`
// package inside it, mimicking a real project root for
// resolveLocalHermesCompilerVersion()'s require.resolve({paths: [rnRoot]}).
function makeFakeRnRoot(hermesCompilerVersion /*: ?string */) /*: string */ {
const root = fs.mkdtempSync(path.join(os.tmpdir(), 'rn-root-'));
if (hermesCompilerVersion != null) {
const pkgDir = path.join(root, 'node_modules', 'hermes-compiler');
fs.mkdirSync(pkgDir, {recursive: true});
fs.writeFileSync(
path.join(pkgDir, 'package.json'),
JSON.stringify({name: 'hermes-compiler', version: hermesCompilerVersion}),
);
}
return root;
}
// Forces resolveLocalHermesCompilerVersion() to behave as if hermes-compiler
// isn't installed, regardless of any workspace-hoisted hermes-compiler the host
// environment provides. Jest's require.resolve ignores the {paths: [rnRoot]}
// scoping and still finds the hoisted package, so stubbing module resolution is
// ineffective here; instead we stub fs.readFileSync to throw MODULE_NOT_FOUND
// for the resolved hermes-compiler/package.json — the exact signal a genuine
// resolution miss produces — which drives the function down its "not installed"
// branch. Reads of any other file fall through to the real implementation.
// Undo with jest.restoreAllMocks().
function mockHermesCompilerUnresolvable() {
const realReadFileSync = fs.readFileSync;
jest.spyOn(fs, 'readFileSync').mockImplementation((file, ...rest) => {
if (String(file).includes(`${path.sep}hermes-compiler${path.sep}`)) {
const error = new Error(
"Cannot find module 'hermes-compiler/package.json'",
);
error.code = 'MODULE_NOT_FOUND';
throw error;
}
return realReadFileSync.call(fs, file, ...rest);
});
}
describe('resolveLocalHermesCompilerVersion', () => {
afterEach(() => {
jest.restoreAllMocks();
});
it('reads the version from the locally installed hermes-compiler package', () => {
const root = makeFakeRnRoot('0.13.7');
expect(resolveLocalHermesCompilerVersion(root)).toBe('0.13.7');
});
it('returns null when no hermes-compiler is resolvable from the given root', () => {
// Resolve from a real, isolated scratch root that has no hermes-compiler
// installed (same setup as the fallback test below) so require.resolve
// stays scoped to that root and misses, rather than falling back to
// whatever hermes-compiler the host environment happens to hoist. The
// function must report absence rather than fabricating a version.
const root = makeFakeRnRoot(null);
mockHermesCompilerUnresolvable();
expect(resolveLocalHermesCompilerVersion(root)).toBeNull();
});
});
describe('resolveHermesArtifact', () => {
let origFetch;
let origHermesEnv;
@@ -112,6 +174,7 @@ describe('resolveHermesArtifact', () => {
} else {
delete process.env.HERMES_VERSION;
}
jest.restoreAllMocks();
});
// Mock fetch with a router: each entry's key is a URL substring; the value
@@ -122,43 +185,74 @@ describe('resolveHermesArtifact', () => {
}
describe('default behavior (no HERMES_VERSION set)', () => {
it('resolves to the latest-v1 hermes-compiler dist-tag, NOT the RN version', async () => {
it('uses the locally pinned hermes-compiler version, without hitting npm', async () => {
const rnRoot = makeFakeRnRoot('0.13.7');
mockFetch({
'hermes-ios/0.13.7/hermes-ios-0.13.7': {ok: true},
});
const result = await resolveHermesArtifact(
'0.87.0-nightly-20260519-58cd1bf58',
'debug',
null,
rnRoot,
);
expect(result.version).toBe('0.13.7');
expect(result.url).toContain('/0.13.7/');
// Must resolve straight from node_modules — no npm registry round trip.
expect(globalThis.fetch).not.toHaveBeenCalledWith(
expect.stringContaining('registry.npmjs.org'),
expect.anything(),
);
});
it('ignores rawVersion (the RN --version arg) when HERMES_VERSION is unset', async () => {
const rnRoot = makeFakeRnRoot('0.13.7');
mockFetch({
'hermes-ios/0.13.7/hermes-ios-0.13.7': {ok: true},
});
// Caller passes the original RN --version verbatim; hermes should
// still use the locally pinned version instead of using this.
const result = await resolveHermesArtifact(
'0.87.0-nightly-20260519-58cd1bf58',
'debug',
'0.87.0-nightly-20260519-58cd1bf58',
rnRoot,
);
expect(result.version).toBe('0.13.7');
expect(result.url).not.toContain('20260519');
});
it('falls back to the latest-v1 npm dist-tag when hermes-compiler is not locally installed', async () => {
const rnRoot = makeFakeRnRoot(null);
// Stub require.resolve to fail so the local lookup is guaranteed to miss,
// even in environments that hoist a workspace hermes-compiler. The
// resolver must then fall through to the latest-v1 dist-tag (0.13.0).
mockHermesCompilerUnresolvable();
mockFetch({
'hermes-compiler/latest-v1': {json: {version: '0.13.0'}},
// Pretend the release URL exists once we ask for 0.13.0.
'hermes-ios/0.13.0/hermes-ios-0.13.0': {ok: true},
});
const result = await resolveHermesArtifact(
'0.87.0-nightly-20260519-58cd1bf58',
'debug',
null,
rnRoot,
);
expect(result.version).toBe('0.13.0');
expect(result.url).toContain('/0.13.0/');
// The RN nightly hash MUST NOT leak into the hermes URL.
expect(result.url).not.toContain('20260519');
});
it('ignores rawVersion (the RN --version arg) when HERMES_VERSION is unset', async () => {
mockFetch({
'hermes-compiler/latest-v1': {json: {version: '0.13.0'}},
'hermes-ios/0.13.0/hermes-ios-0.13.0': {ok: true},
});
// Caller passes the original RN --version verbatim; hermes should
// still default to latest-v1 instead of using this.
const result = await resolveHermesArtifact(
'0.87.0-nightly-20260519-58cd1bf58',
'debug',
'0.87.0-nightly-20260519-58cd1bf58',
// Confirm the dist-tag lookup actually ran — the fallback path, not a
// locally pinned version, produced this result.
const hitLatestV1 = globalThis.fetch.mock.calls.some(([url]) =>
String(url).includes('hermes-compiler/latest-v1'),
);
expect(result.version).toBe('0.13.0');
expect(result.url).not.toContain('20260519');
expect(hitLatestV1).toBe(true);
});
});
describe('HERMES_VERSION escape hatches', () => {
it('HERMES_VERSION=<literal-version> uses it verbatim', async () => {
it('HERMES_VERSION=<literal-version> uses it verbatim, even with a local package installed', async () => {
process.env.HERMES_VERSION = '0.13.5';
const rnRoot = makeFakeRnRoot('0.13.7');
mockFetch({
'hermes-ios/0.13.5/hermes-ios-0.13.5': {ok: true},
});
@@ -166,13 +260,15 @@ describe('resolveHermesArtifact', () => {
'0.87.0-nightly-anything',
'debug',
null,
rnRoot,
);
expect(result.version).toBe('0.13.5');
expect(result.url).toContain('/0.13.5/');
});
it('HERMES_VERSION=latest-v1 resolves via npm dist-tag', async () => {
it('HERMES_VERSION=latest-v1 resolves via npm dist-tag, even with a local package installed', async () => {
process.env.HERMES_VERSION = 'latest-v1';
const rnRoot = makeFakeRnRoot('0.13.7');
mockFetch({
'hermes-compiler/latest-v1': {json: {version: '0.13.0'}},
'hermes-ios/0.13.0/hermes-ios-0.13.0': {ok: true},
@@ -181,12 +277,14 @@ describe('resolveHermesArtifact', () => {
'0.87.0-nightly-anything',
'debug',
null,
rnRoot,
);
expect(result.version).toBe('0.13.0');
});
it('HERMES_VERSION=nightly resolves hermes-compiler@nightly from npm', async () => {
process.env.HERMES_VERSION = 'nightly';
const rnRoot = makeFakeRnRoot(null);
mockFetch({
'hermes-compiler/nightly': {json: {version: '0.14.0-nightly-abc'}},
'hermes-ios/0.14.0-nightly-abc/hermes-ios-0.14.0-nightly-abc': {
@@ -197,12 +295,14 @@ describe('resolveHermesArtifact', () => {
'0.87.0-nightly-anything',
'debug',
null,
rnRoot,
);
expect(result.version).toBe('0.14.0-nightly-abc');
});
it('falls back to the hermes snapshot URL when the release is missing', async () => {
process.env.HERMES_VERSION = '0.13.5';
const rnRoot = makeFakeRnRoot(null);
globalThis.fetch = jest.fn(async (url, opts) => {
if (opts && opts.method === 'HEAD') {
return {status: 404};
@@ -215,7 +315,12 @@ describe('resolveHermesArtifact', () => {
'<buildNumber>2</buildNumber></metadata>',
};
});
const result = await resolveHermesArtifact('0.87.0', 'debug', null);
const result = await resolveHermesArtifact(
'0.87.0',
'debug',
null,
rnRoot,
);
expect(result.url).toContain('maven-snapshots');
expect(result.url).toContain('hermes-ios-debug.tar.gz');
});
+64 -6
View File
@@ -452,15 +452,63 @@ async function resolveRNDepsArtifact(
return {url: snapshotUrl, version};
}
/**
* Resolves the `hermes-compiler` npm package's version from THIS project's own
* node_modules — the exact same lookup generate-spm-xcodeproj.js's
* resolveHermesCliPathSetting() uses to find the hermesc binary that will
* compile the JS bundle, and the same one react-native-xcode.sh falls back to
* for SwiftPM builds. Returns null when the package isn't resolvable (e.g.
* USE_HERMES=false apps that never installed it) so the caller can fall back
* to the npm dist-tag lookup.
*/
function resolveLocalHermesCompilerVersion(
rnRoot /*: string */,
) /*: string | null */ {
try {
const pkgPath = require.resolve('hermes-compiler/package.json', {
paths: [rnRoot],
});
// $FlowFixMe[incompatible-type] JSON.parse returns any
const pkg /*: {version: string} */ = JSON.parse(
fs.readFileSync(pkgPath, 'utf8'),
);
assertSafeVersion(pkg.version, 'local hermes-compiler/package.json');
return pkg.version;
} catch (error) {
// A MODULE_NOT_FOUND resolution failure is the expected case (e.g.
// USE_HERMES=false apps that never installed hermes-compiler) — fall back
// silently. Any other failure means hermes-compiler IS installed but its
// package.json is unreadable/malformed or carries an unsafe version; warn
// loudly rather than silently regressing to the live latest-v1 dist-tag,
// which would re-introduce the version-skew crash this resolves (#57917).
if (error.code !== 'MODULE_NOT_FOUND') {
log(
` WARNING: hermes-compiler is installed but its version could not be resolved (${error.message}); falling back to the latest-v1 dist-tag, which may not match the pinned hermesc and can crash at launch with "Wrong bytecode version".`,
);
}
return null;
}
}
/**
* Returns {url, version} for Hermes. Hermes uses its own version space
* decoupled from React Native's nightly cadence — RN's `hermes-compiler`
* npm package publishes a `latest-v1` dist-tag that always resolves to a
* binary that's been built and uploaded to Maven. Our default mirrors RN's
* CocoaPods prebuild path (see scripts/ios-prebuild/hermes.js):
* binary that's been built and uploaded to Maven.
*
* HERMES_VERSION unset → 'latest-v1' dist-tag
* HERMES_VERSION=latest-v1 → same (explicit)
* HERMES_VERSION unset → version pinned by the locally installed
* hermes-compiler package (node_modules).
* This is the SAME source
* resolveHermesCliPathSetting() reads for
* HERMES_CLI_PATH, so the downloaded VM and
* the hermesc that compiles the JS bundle
* always agree — a mismatched pair crashes at
* launch with "Wrong bytecode version" (#57917).
* Falls back to the 'latest-v1' npm dist-tag
* (RN's CocoaPods prebuild default; see
* scripts/ios-prebuild/hermes.js) only when
* hermes-compiler isn't locally resolvable.
* HERMES_VERSION=latest-v1 → 'latest-v1' dist-tag (explicit)
* HERMES_VERSION=nightly → hermes-compiler@nightly dist-tag
* HERMES_VERSION=<literal> → use that version verbatim
*
@@ -472,8 +520,17 @@ async function resolveHermesArtifact(
rnVersion /*: string */,
flavor /*: string */,
rawVersion /*: string | null */,
rnRoot /*: string */,
) /*: Promise<ResolvedArtifact> */ {
let version = process.env.HERMES_VERSION ?? 'latest-v1';
let version = process.env.HERMES_VERSION;
if (version == null) {
const localVersion = resolveLocalHermesCompilerVersion(rnRoot);
if (localVersion != null) {
log(` Using locally pinned hermes-compiler: ${localVersion}`);
}
version = localVersion ?? 'latest-v1';
}
if (version === 'nightly') {
version = await resolveNightlyVersion('hermes-compiler');
@@ -1178,7 +1235,7 @@ async function main(argv /*:: ?: Array<string> */) /*: Promise<void> */ {
label: 'hermes',
name: 'hermes-engine',
resolve: () =>
resolveHermesArtifact(resolvedRnVersion, flavor, rawVersion),
resolveHermesArtifact(resolvedRnVersion, flavor, rawVersion, rnRoot),
sharedName: (v /*: string */) => `hermes-ios-${v}-${flavor}.tar.gz`,
},
];
@@ -1449,6 +1506,7 @@ module.exports = {
main,
resolveCacheSlotVersion,
resolveHermesArtifact,
resolveLocalHermesCompilerVersion,
REQUIRED_ARTIFACTS,
validateArtifactsCache,
// Exposed for unit tests (pure / fetch-stubbable helpers).