mirror of
https://github.com/facebook/react-native.git
synced 2026-11-18 20:19:07 +00:00
Install globalEvalWithSourceUrl on bridgeless ReactInstance (#58718)
Summary: **Problem:** On the New Architecture (bridgeless), fetching and evaluating a Metro split bundle in development (`lazy=true`, `import()`, `React.lazy()`) can fail with: ``` SyntaxError: Parsing source code unsupported: __d(function (global, require, _ ``` The main bundle still loads. **Root cause:** `global.globalEvalWithSourceUrl` is never installed on bridgeless. Bridge mode installs it in `JSIExecutor::initializeRuntime`. ```js typeof global.globalEvalWithSourceUrl // bridgeless: "undefined" // bridge: "function" ``` The debug loader (`Libraries/Core/Devtools/loadBundleFromServer.js`) prefers that helper and only falls back to JS `eval()` when it is missing. The two paths are not equivalent in Hermes: - `eval()` / `Function` go through `evalInEnvironment`, which raises `Parsing source code unsupported` when `RuntimeConfig::EnableEval` is false (and, on legacy Hermes, when the engine is built lean). - `globalEvalWithSourceUrl` goes through `Runtime::evaluateJavaScript`, the same entry point used to run the main bundle. It is not gated by `EnableEval`, and it attaches the given source URL to stack traces. So on a runtime where `EnableEval` is off (or the engine is lean), the main bundle loads but every split bundle falls into `eval()` and throws. Bridgeless has no way to reach the JSI path from JS today. **Fix:** Port the existing `JSIExecutor` binding into `ReactInstance::initializeRuntime` so bridgeless exposes the same helper. ## Changelog: [General] [Fixed] - Install globalEvalWithSourceUrl on bridgeless ReactInstance so debug bundle loaders can evaluate split bundles via JSI instead of eval() Pull Request resolved: https://github.com/react/react-native/pull/58718 Test Plan: 1. `ReactInstanceTest.testGlobalEvalWithSourceUrlIsInstalled`: helper is absent before `initializeRuntime` and present after. 2. `ReactInstanceTest.testGlobalEvalWithSourceUrlMatchesEvalWhenEvalIsEnabled`: with the default `RuntimeConfig`, `eval('1 + 2')` and `globalEvalWithSourceUrl('1 + 2', 'chunk.js')` both return `3`. 3. `ReactInstanceWithoutEvalTest.testGlobalEvalWithSourceUrlWorksWhenEvalIsDisabled`: runtime built with `RuntimeConfig::Builder().withEnableEval(false)`; `eval('1 + 2')` throws `Parsing source code unsupported`, `globalEvalWithSourceUrl('1 + 2', 'chunk.js')` returns `3`. 4. Fantom `Libraries/Core/Devtools/__tests__/globalEvalWithSourceUrl-itest.js`: helper is installed on bridgeless; `eval()` and the helper evaluate the same source to the same result; an error thrown from the helper carries the given source URL in its stack while the `eval()` one does not; wrong arity throws. 5. In a bridgeless debug app, `typeof global.globalEvalWithSourceUrl` is `'function'` and a `React.lazy(() => import('./SomeModule'))` split bundle loads without `Parsing source code unsupported`. Reviewed By: fabriziocucci Differential Revision: D122329977 Pulled By: javache fbshipit-source-id: 789294c7806a331828effd407588208a55e1d9a3
This commit is contained in:
1 parent
44ffdbaa96
commit
2a2ccaa522
3 files changed
+168
-2
No files matched your search
+82
@@ -0,0 +1,82 @@
|
||||
/**
|
||||
* Copyright (c) Meta Platforms, Inc. and affiliates.
|
||||
*
|
||||
* This source code is licensed under the MIT license found in the
|
||||
* LICENSE file in the root directory of this source tree.
|
||||
*
|
||||
* @flow strict
|
||||
* @format
|
||||
*/
|
||||
|
||||
import '@react-native/fantom/src/setUpDefaultReactNativeEnvironment';
|
||||
|
||||
// Must not be a substring of this test's own bundle URL, which appears in
|
||||
// every stack trace.
|
||||
const SOURCE_URL = 'split-chunk-under-test.bundle';
|
||||
|
||||
function getHelper(): (code: string, sourceUrl?: string) => unknown {
|
||||
// $FlowFixMe[prop-missing]
|
||||
const helper = global.globalEvalWithSourceUrl;
|
||||
if (typeof helper !== 'function') {
|
||||
throw new Error(
|
||||
`Expected global.globalEvalWithSourceUrl to be a function, got ${typeof helper}`,
|
||||
);
|
||||
}
|
||||
return helper;
|
||||
}
|
||||
|
||||
function getStack(fn: () => unknown): string {
|
||||
try {
|
||||
fn();
|
||||
} catch (e) {
|
||||
return String(e?.stack ?? '');
|
||||
}
|
||||
throw new Error('Expected the evaluated code to throw');
|
||||
}
|
||||
|
||||
describe('globalEvalWithSourceUrl', () => {
|
||||
afterEach(() => {
|
||||
// $FlowFixMe[prop-missing]
|
||||
delete globalThis.__fantomEvalMarker;
|
||||
});
|
||||
|
||||
it('is installed on the bridgeless runtime', () => {
|
||||
// $FlowFixMe[prop-missing]
|
||||
expect(typeof global.globalEvalWithSourceUrl).toBe('function');
|
||||
});
|
||||
|
||||
it('evaluates the same source as JS eval() in the global scope', () => {
|
||||
const source = 'globalThis.__fantomEvalMarker = 17; 17';
|
||||
|
||||
// eslint-disable-next-line no-eval
|
||||
expect(eval(source)).toBe(17);
|
||||
// $FlowFixMe[prop-missing]
|
||||
expect(globalThis.__fantomEvalMarker).toBe(17);
|
||||
|
||||
// $FlowFixMe[prop-missing]
|
||||
delete globalThis.__fantomEvalMarker;
|
||||
|
||||
expect(getHelper()(source, SOURCE_URL)).toBe(17);
|
||||
// $FlowFixMe[prop-missing]
|
||||
expect(globalThis.__fantomEvalMarker).toBe(17);
|
||||
});
|
||||
|
||||
it('attributes evaluated code to the given source URL, unlike eval()', () => {
|
||||
const source = 'throw new Error("thrown from evaluated source")';
|
||||
|
||||
// eslint-disable-next-line no-eval
|
||||
const evalStack = getStack(() => eval(source));
|
||||
const helperStack = getStack(() => getHelper()(source, SOURCE_URL));
|
||||
|
||||
expect(evalStack).not.toContain(SOURCE_URL);
|
||||
expect(helperStack).toContain(SOURCE_URL);
|
||||
});
|
||||
|
||||
it('rejects an invalid argument count', () => {
|
||||
const helper = getHelper();
|
||||
// $FlowFixMe[incompatible-type]
|
||||
expect(() => helper()).toThrow(
|
||||
'globalEvalWithSourceUrl arg count must be 1 or 2',
|
||||
);
|
||||
});
|
||||
});
|
||||
@@ -458,6 +458,39 @@ void ReactInstance::initializeRuntime(
|
||||
|
||||
defineReactInstanceFlags(runtime, options);
|
||||
|
||||
// Bridge JSIExecutor installs this so debug bundle loaders can evaluate
|
||||
// fetched Metro source through Runtime::evaluateJavaScript, with a source
|
||||
// URL for stack traces. Unlike JS eval(), that path is not disabled by
|
||||
// Hermes' RuntimeConfig::EnableEval or by lean engine builds. Left
|
||||
// writable, like in JSIExecutor, so hosts can override or wrap it.
|
||||
runtime.global().setProperty(
|
||||
runtime,
|
||||
"globalEvalWithSourceUrl",
|
||||
jsi::Function::createFromHostFunction(
|
||||
runtime,
|
||||
jsi::PropNameID::forAscii(runtime, "globalEvalWithSourceUrl"),
|
||||
2,
|
||||
[](jsi::Runtime& rt,
|
||||
const jsi::Value& /*thisValue*/,
|
||||
const jsi::Value* args,
|
||||
size_t count) {
|
||||
if (count != 1 && count != 2) {
|
||||
throw jsi::JSError(
|
||||
rt, "globalEvalWithSourceUrl arg count must be 1 or 2");
|
||||
}
|
||||
|
||||
// NOLINTBEGIN(cppcoreguidelines-pro-bounds-pointer-arithmetic)
|
||||
auto code = args[0].asString(rt).utf8(rt);
|
||||
std::string url;
|
||||
if (count > 1 && args[1].isString()) {
|
||||
url = args[1].asString(rt).utf8(rt);
|
||||
}
|
||||
// NOLINTEND(cppcoreguidelines-pro-bounds-pointer-arithmetic)
|
||||
|
||||
return rt.evaluateJavaScript(
|
||||
std::make_unique<jsi::StringBuffer>(std::move(code)), url);
|
||||
}));
|
||||
|
||||
defineReadOnlyGlobal(
|
||||
runtime,
|
||||
"RN$useAlwaysAvailableJSErrorHandling",
|
||||
|
||||
@@ -118,9 +118,13 @@ class ReactInstanceTest : public ::testing::Test {
|
||||
protected:
|
||||
ReactInstanceTest() = default;
|
||||
|
||||
virtual ::hermes::vm::RuntimeConfig makeRuntimeConfig() {
|
||||
return {};
|
||||
}
|
||||
|
||||
void SetUp() override {
|
||||
auto runtime =
|
||||
std::make_unique<JSIRuntimeHolder>(hermes::makeHermesRuntime());
|
||||
auto runtime = std::make_unique<JSIRuntimeHolder>(
|
||||
hermes::makeHermesRuntime(makeRuntimeConfig()));
|
||||
runtime_ = &runtime->getRuntime();
|
||||
messageQueueThread_ = std::make_shared<MockMessageQueueThread>();
|
||||
auto mockRegistry = std::make_unique<MockTimerRegistry>();
|
||||
@@ -255,6 +259,53 @@ TEST_F(ReactInstanceTest, testBridgelessFlagIsSet) {
|
||||
EXPECT_EQ(val.getBool(), true);
|
||||
}
|
||||
|
||||
TEST_F(ReactInstanceTest, testGlobalEvalWithSourceUrlIsInstalled) {
|
||||
auto before =
|
||||
tryEval("typeof globalEvalWithSourceUrl === 'function'", "false");
|
||||
EXPECT_EQ(before.getBool(), false);
|
||||
initializeRuntimeWithScript("");
|
||||
auto isFn = eval("typeof globalEvalWithSourceUrl === 'function'");
|
||||
EXPECT_EQ(isFn.getBool(), true);
|
||||
auto result = eval("globalEvalWithSourceUrl('1 + 2')");
|
||||
EXPECT_EQ(result.getNumber(), 3);
|
||||
}
|
||||
|
||||
TEST_F(
|
||||
ReactInstanceTest,
|
||||
testGlobalEvalWithSourceUrlMatchesEvalWhenEvalIsEnabled) {
|
||||
initializeRuntimeWithScript("");
|
||||
|
||||
EXPECT_EQ(eval("eval('1 + 2')").getNumber(), 3);
|
||||
EXPECT_EQ(
|
||||
eval("globalEvalWithSourceUrl('1 + 2', 'chunk.js')").getNumber(), 3);
|
||||
}
|
||||
|
||||
// Hermes gates eval() and the Function constructor behind
|
||||
// RuntimeConfig::EnableEval, but Runtime::evaluateJavaScript is not gated.
|
||||
// globalEvalWithSourceUrl goes through the latter, which is why the debug
|
||||
// bundle loaders prefer it over eval().
|
||||
class ReactInstanceWithoutEvalTest : public ReactInstanceTest {
|
||||
protected:
|
||||
::hermes::vm::RuntimeConfig makeRuntimeConfig() override {
|
||||
return ::hermes::vm::RuntimeConfig::Builder().withEnableEval(false).build();
|
||||
}
|
||||
};
|
||||
|
||||
TEST_F(
|
||||
ReactInstanceWithoutEvalTest,
|
||||
testGlobalEvalWithSourceUrlWorksWhenEvalIsDisabled) {
|
||||
initializeRuntimeWithScript("");
|
||||
|
||||
auto evalOutcome = eval(
|
||||
"(function() { try { eval('1 + 2'); return 'no error'; } catch (e) { return String(e.message); } })()");
|
||||
EXPECT_THAT(
|
||||
evalOutcome.getString(*runtime_).utf8(*runtime_),
|
||||
HasSubstr("Parsing source code unsupported"));
|
||||
|
||||
EXPECT_EQ(
|
||||
eval("globalEvalWithSourceUrl('1 + 2', 'chunk.js')").getNumber(), 3);
|
||||
}
|
||||
|
||||
TEST_F(ReactInstanceTest, testProfilingFlag) {
|
||||
auto valBefore = tryEval("__RCTProfileIsProfiling === true", "false");
|
||||
EXPECT_EQ(valBefore.getBool(), false);
|
||||
|
||||
Reference in new issue
Block a user