Skip to content

Commit 9de42bb

Browse files
authored
Breaking: Apply globalPrefix to all module system globals (#2186)
1 parent 8a7f97b commit 9de42bb

11 files changed

Lines changed: 290 additions & 35 deletions

File tree

‎docs/Configuration.md‎

Lines changed: 4 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -658,7 +658,9 @@ A file size threshold (in bytes) above which some expensive optimizations are sk
658658
659659
Type: `string`
660660
661-
A prefix for the global names used by Metro's module system, e.g. with `'app1'`, each module is wrapped in `app1__d(...)` instead of `__d(...)`. Defaults to `''`.
661+
A prefix for the global names used by Metro's module system, so that several bundles with different prefixes can share one JavaScript realm. E.g. with `'app1'`, each module is wrapped in `app1__d(...)` instead of `__d(...)`, and the bundle runs its entry point with `app1__r(...)`. Defaults to `''`.
662+
663+
The prefix applies to `__d`, `__r`, `__c` and `__registerSegment`, to `__loadBundleAsync`, and in development to `__accept`, `__requireCycleIgnorePatterns`, `__unstable_forceFullRefreshPatterns`, `__ReactRefresh` and `__SYSTRACE`. Code that calls any of these by name, such as a custom [`getRunModuleStatement`](#getrunmodulestatement) or native code that calls `__r`, must apply the same prefix. Each bundle also declares its prefix as the global `__METRO_GLOBAL_PREFIX__`.
662664
663665
#### `allowOptionalDependencies`
664666
@@ -754,7 +756,7 @@ Serializer options control [serialization](./Concepts.md#serialization): how tra
754756
755757
Type: `(moduleId: number | string, globalPrefix: string) => string`
756758
757-
Formats the require statements appended to the end of the bundle: one for each module from [`getModulesRunBeforeMainModule`](#getmodulesrunbeforemainmodule) that is in the bundle, then one for the [entry point](./Concepts.md#entry-point). Defaults to `` `__r(${JSON.stringify(moduleId)});` ``, e.g. `__r(42);` for module ID `42`.
759+
Formats the require statements appended to the end of the bundle: one for each module from [`getModulesRunBeforeMainModule`](#getmodulesrunbeforemainmodule) that is in the bundle, then one for the [entry point](./Concepts.md#entry-point). Defaults to `` `${globalPrefix}__r(${JSON.stringify(moduleId)});` ``, e.g. `__r(42);` for module ID `42` with the default [`globalPrefix`](#globalprefix).
758760
759761
#### `createModuleIdFactory`
760762
Lines changed: 30 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,30 @@
1+
/**
2+
* Copyright (c) Meta Platforms, Inc. and affiliates.
3+
*
4+
* This source code is licensed under the MIT license found in the
5+
* LICENSE file in the root directory of this source tree.
6+
*
7+
* @flow strict-local
8+
* @format
9+
* @oncall react_native
10+
*/
11+
12+
import getDefaultConfig from '../index';
13+
14+
const {getRunModuleStatement} = getDefaultConfig.getDefaultValues().serializer;
15+
16+
test.each([
17+
[42, '', '__r(42);'],
18+
[42, 'app1', 'app1__r(42);'],
19+
['foo.js', 'app1', 'app1__r("foo.js");'],
20+
])(
21+
'getRunModuleStatement(%p, %p) is %p',
22+
(moduleId, globalPrefix, expected) => {
23+
expect(getRunModuleStatement(moduleId, globalPrefix)).toBe(expected);
24+
},
25+
);
26+
27+
test('getRunModuleStatement treats a missing prefix as empty', () => {
28+
// $FlowExpectedError[incompatible-type] Wrappers may omit the prefix.
29+
expect(getRunModuleStatement(42)).toBe('__r(42);');
30+
});

‎packages/metro-config/src/defaults/index.js‎

Lines changed: 5 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -62,8 +62,11 @@ const getDefaultValues = (projectRoot: ?string): ConfigT => ({
6262

6363
serializer: {
6464
polyfillModuleNames: [],
65-
getRunModuleStatement: (moduleId: number | string, globalPrefix: string) =>
66-
`__r(${JSON.stringify(moduleId)});`,
65+
// `globalPrefix` defaults to '' for wrappers that pass only the module ID.
66+
getRunModuleStatement: (
67+
moduleId: number | string,
68+
globalPrefix: string = '',
69+
) => `${globalPrefix}__r(${JSON.stringify(moduleId)});`,
6770
getPolyfills: () => [],
6871
getModulesRunBeforeMainModule: () => [],
6972
processModuleFilter: module => true,
Lines changed: 61 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,61 @@
1+
/**
2+
* Copyright (c) Meta Platforms, Inc. and affiliates.
3+
*
4+
* This source code is licensed under the MIT license found in the
5+
* LICENSE file in the root directory of this source tree.
6+
*
7+
* @flow
8+
* @format
9+
* @oncall react_native
10+
*/
11+
12+
import {transformSync} from '@babel/core';
13+
import fs from 'node:fs';
14+
import vm from 'node:vm';
15+
16+
const asyncRequireCode = transformSync(
17+
fs.readFileSync(require.resolve('../asyncRequire'), 'utf8'),
18+
{
19+
ast: false,
20+
babelrc: false,
21+
cwd: '/',
22+
filename: 'asyncRequire.js',
23+
presets: [
24+
[
25+
require.resolve('@react-native/babel-preset'),
26+
{enableBabelRuntime: false},
27+
],
28+
],
29+
sourceType: 'module',
30+
},
31+
).code;
32+
33+
test('loads bundles through its own bundle loader after another bundle reassigns the prefix', async () => {
34+
const loaded: Array<string> = [];
35+
const context = vm.createContext({
36+
hostRequire: {importAll: () => 'HostSplit'},
37+
host__loadBundleAsync: async (path: string) => {
38+
loaded.push(`host:${path}`);
39+
},
40+
remote__loadBundleAsync: async (path: string) => {
41+
loaded.push(`remote:${path}`);
42+
},
43+
});
44+
vm.runInContext('var __METRO_GLOBAL_PREFIX__ = "host";', context);
45+
const asyncRequire = vm.runInContext(
46+
`(function (global, require) {
47+
var module = {exports: {}};
48+
${asyncRequireCode}
49+
return module.exports;
50+
})(globalThis, hostRequire)`,
51+
context,
52+
);
53+
54+
// A Module Federation remote's prelude.
55+
vm.runInContext('var __METRO_GLOBAL_PREFIX__ = "remote";', context);
56+
57+
await expect(asyncRequire(1, {'1': '/host-split.bundle'})).resolves.toBe(
58+
'HostSplit',
59+
);
60+
expect(loaded).toEqual(['host:/host-split.bundle']);
61+
});

‎packages/metro-runtime/src/modules/asyncRequire.js‎

Lines changed: 6 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -52,12 +52,17 @@ type AsyncRequire = {
5252

5353
declare var __METRO_GLOBAL_PREFIX__: string;
5454

55+
// A later bundle in the same realm (e.g. a Module Federation remote) may
56+
// reassign `__METRO_GLOBAL_PREFIX__`. Read it once, so that this module keeps
57+
// using its own bundle's loader.
58+
const GLOBAL_PREFIX: string = __METRO_GLOBAL_PREFIX__;
59+
5560
function maybeLoadBundle(
5661
moduleID: number,
5762
paths: DependencyMapPaths,
5863
): void | Promise<void> {
5964
const loadBundle: (bundlePath: unknown) => Promise<void> =
60-
global[`${__METRO_GLOBAL_PREFIX__}__loadBundleAsync`];
65+
global[`${GLOBAL_PREFIX}__loadBundleAsync`];
6166

6267
if (loadBundle != null) {
6368
const stringModuleID = String(moduleID);

‎packages/metro-runtime/src/polyfills/__tests__/MetroFastRefreshMockRuntime.js‎

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -120,7 +120,8 @@ export class Runtime {
120120
);
121121
this.define = this.#global[this.#globalPrefix + '__d'];
122122
this.metroRequire = this.#global[this.#globalPrefix + '__r'];
123-
this.registerSegment = this.#global.__registerSegment;
123+
this.registerSegment =
124+
this.#global[this.#globalPrefix + '__registerSegment'];
124125

125126
// Set up Fast Refresh. Adapted from `setUpReactRefresh.js` in React Native.
126127
jest.isolateModules(() => {

‎packages/metro-runtime/src/polyfills/__tests__/require-test.js‎

Lines changed: 100 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -12,6 +12,7 @@
1212

1313
const {transformSync} = require('@babel/core');
1414
const fs = require('node:fs');
15+
const vm = require('node:vm');
1516

1617
function createModule(
1718
moduleSystem,
@@ -128,11 +129,17 @@ describe('require', () => {
128129
expect(mockFactory.mock.calls[0][6]).toEqual([2, 3]);
129130
});
130131

131-
test('properly prefixes __d with global prefix', () => {
132-
createModuleSystem(moduleSystem, false, '__metro');
133-
expect(moduleSystem.__d).toBeUndefined();
134-
expect(moduleSystem.__metro__d).not.toBeUndefined();
135-
});
132+
test.each([['__r'], ['__d'], ['__c'], ['__registerSegment'], ['__accept']])(
133+
'properly prefixes %s with global prefix',
134+
property => {
135+
const prefix = '__metro';
136+
137+
createModuleSystem(moduleSystem, true, prefix);
138+
139+
expect(moduleSystem[property]).toBeUndefined();
140+
expect(moduleSystem[`${prefix}${property}`]).not.toBeUndefined();
141+
},
142+
);
136143

137144
test('works with Random Access Modules (RAM) bundles', () => {
138145
const mockExports = {foo: 'bar'};
@@ -748,7 +755,7 @@ describe('require', () => {
748755
const warn = console.warn;
749756
console.warn = jest.fn();
750757

751-
moduleSystem.__r(0);
758+
moduleSystem.__customPrefix__r(0);
752759
expect(console.warn).toHaveBeenCalledTimes(0);
753760
console.warn = warn;
754761
});
@@ -1000,6 +1007,93 @@ describe('require', () => {
10001007
});
10011008
});
10021009

1010+
describe('several module systems in one realm', () => {
1011+
// Evaluates a prelude and the module system as a bundle does, so that
1012+
// `__METRO_GLOBAL_PREFIX__` is a global that each bundle reassigns, as
1013+
// Module Federation's host and remote bundles do.
1014+
function evaluateBundleRuntime(context, globalPrefix) {
1015+
vm.runInContext(
1016+
`var __METRO_GLOBAL_PREFIX__ = ${JSON.stringify(globalPrefix)};`,
1017+
context,
1018+
);
1019+
vm.runInContext(
1020+
`(function (global, __DEV__) {\n${moduleSystemCode}\n})(globalThis, true);`,
1021+
context,
1022+
);
1023+
}
1024+
1025+
test('keeps the globals of each module system separate', () => {
1026+
const context = vm.createContext({console});
1027+
evaluateBundleRuntime(context, 'host');
1028+
evaluateBundleRuntime(context, 'remote');
1029+
1030+
createModule(
1031+
context,
1032+
0,
1033+
'host.js',
1034+
(g, r, i, a, module) => {
1035+
module.exports = 'host';
1036+
},
1037+
[],
1038+
'host',
1039+
);
1040+
createModule(
1041+
context,
1042+
0,
1043+
'remote.js',
1044+
(g, r, i, a, module) => {
1045+
module.exports = 'remote';
1046+
},
1047+
[],
1048+
'remote',
1049+
);
1050+
1051+
expect(context.host__r(0)).toBe('host');
1052+
expect(context.remote__r(0)).toBe('remote');
1053+
for (const name of ['__r', '__d', '__c', '__registerSegment']) {
1054+
expect(context[`host${name}`]).not.toBe(context[`remote${name}`]);
1055+
}
1056+
});
1057+
1058+
test('applies a hot update to the module system that defines the module', () => {
1059+
const context = vm.createContext({console});
1060+
const versionedFactory = version => (g, r, i, a, module) => {
1061+
module.exports = version;
1062+
module.hot.accept();
1063+
};
1064+
evaluateBundleRuntime(context, 'host');
1065+
createModule(
1066+
context,
1067+
0,
1068+
'host.js',
1069+
versionedFactory('HostV1'),
1070+
[],
1071+
'host',
1072+
);
1073+
expect(context.host__r(0)).toBe('HostV1');
1074+
1075+
// A remote's prelude reassigns `__METRO_GLOBAL_PREFIX__`, and its module
1076+
// system defines a module with the same ID.
1077+
evaluateBundleRuntime(context, 'remote');
1078+
createModule(
1079+
context,
1080+
0,
1081+
'remote.js',
1082+
versionedFactory('RemoteV1'),
1083+
[],
1084+
'remote',
1085+
);
1086+
expect(context.remote__r(0)).toBe('RemoteV1');
1087+
1088+
// An HMR update for the host redefines its module with inverse
1089+
// dependencies.
1090+
context.host__d(versionedFactory('HostV2'), 0, [], 'host.js', {0: []});
1091+
1092+
expect(context.host__r(0)).toBe('HostV2');
1093+
expect(context.remote__r(0)).toBe('RemoteV1');
1094+
});
1095+
});
1096+
10031097
describe('hot reloading', () => {
10041098
test('is disabled in production', () => {
10051099
createModuleSystem(moduleSystem, false, '');

‎packages/metro-runtime/src/polyfills/require.js‎

Lines changed: 28 additions & 19 deletions
Original file line numberDiff line numberDiff line change
@@ -81,10 +81,16 @@ export type DefineFn = (
8181
type VerboseModuleNameForDev = string;
8282
type ModuleDefiner = (moduleId: ModuleID) => void;
8383

84-
global.__r = metroRequire as RequireFn;
85-
global[`${__METRO_GLOBAL_PREFIX__}__d`] = define as DefineFn;
86-
global.__c = clear;
87-
global.__registerSegment = registerSegment;
84+
// The bundle's prelude declares `__METRO_GLOBAL_PREFIX__` as a global
85+
// immediately before this runs, and any later bundle in the same realm (e.g.
86+
// a Module Federation remote) reassigns it. Read it once, so that this module
87+
// system keeps addressing its own globals.
88+
const GLOBAL_PREFIX: string = __METRO_GLOBAL_PREFIX__;
89+
90+
global[`${GLOBAL_PREFIX}__r`] = metroRequire as RequireFn;
91+
global[`${GLOBAL_PREFIX}__d`] = define as DefineFn;
92+
global[`${GLOBAL_PREFIX}__c`] = clear;
93+
global[`${GLOBAL_PREFIX}__registerSegment`] = registerSegment;
8894

8995
var modules = clear();
9096

@@ -134,7 +140,12 @@ function define(
134140
// If the module has already been defined and the define method has been
135141
// called with inverseDependencies, we can hot reload it.
136142
if (inverseDependencies) {
137-
global.__accept(moduleId, factory, dependencyMap, inverseDependencies);
143+
global[`${GLOBAL_PREFIX}__accept`](
144+
moduleId,
145+
factory,
146+
dependencyMap,
147+
inverseDependencies,
148+
);
138149
}
139150
}
140151

@@ -224,8 +235,7 @@ function metroRequire(
224235
// We print require cycles unless they match a pattern in the
225236
// `requireCycleIgnorePatterns` configuration.
226237
function shouldPrintRequireCycle(modules: ReadonlyArray<?string>): boolean {
227-
const regExps =
228-
global[__METRO_GLOBAL_PREFIX__ + '__requireCycleIgnorePatterns'];
238+
const regExps = global[GLOBAL_PREFIX + '__requireCycleIgnorePatterns'];
229239
if (!Array.isArray(regExps)) {
230240
return true;
231241
}
@@ -473,8 +483,7 @@ function loadModuleImplementation(
473483
const RefreshRuntime = Refresh;
474484
global.$RefreshReg$ = (type, id) => {
475485
// prefix the id with global prefix to enable multiple HMR clients
476-
const prefixedModuleId =
477-
__METRO_GLOBAL_PREFIX__ + ' ' + moduleId + ' ' + id;
486+
const prefixedModuleId = GLOBAL_PREFIX + ' ' + moduleId + ' ' + id;
478487
RefreshRuntime.register(type, prefixedModuleId);
479488
};
480489
global.$RefreshSig$ =
@@ -509,7 +518,7 @@ function loadModuleImplementation(
509518

510519
if (Refresh != null) {
511520
// prefix the id with global prefix to enable multiple HMR clients
512-
const prefixedModuleId = __METRO_GLOBAL_PREFIX__ + ' ' + moduleId;
521+
const prefixedModuleId = GLOBAL_PREFIX + ' ' + moduleId;
513522
registerExportsForReactRefresh(
514523
Refresh,
515524
moduleObject.exports,
@@ -618,7 +627,7 @@ if (__DEV__) {
618627
// specifying patterns for modules that should trigger a full refresh
619628
// instead of attempting hot reload.
620629
const forceFullRefreshPatterns =
621-
global[__METRO_GLOBAL_PREFIX__ + '__unstable_forceFullRefreshPatterns'];
630+
global[GLOBAL_PREFIX + '__unstable_forceFullRefreshPatterns'];
622631

623632
if (
624633
forceFullRefreshPatterns != null &&
@@ -1082,7 +1091,7 @@ if (__DEV__) {
10821091
}
10831092
};
10841093

1085-
global.__accept = metroHotUpdateModule;
1094+
global[`${GLOBAL_PREFIX}__accept`] = metroHotUpdateModule;
10861095
}
10871096

10881097
if (__DEV__) {
@@ -1095,18 +1104,18 @@ if (__DEV__) {
10951104
var requireSystrace = function requireSystrace() {
10961105
return (
10971106
// $FlowFixMe[prop-missing]
1098-
global[__METRO_GLOBAL_PREFIX__ + '__SYSTRACE'] || metroRequire.Systrace
1107+
global[GLOBAL_PREFIX + '__SYSTRACE'] || metroRequire.Systrace
10991108
);
11001109
};
11011110

11021111
var requireRefresh = function requireRefresh() {
1103-
// __METRO_GLOBAL_PREFIX__ and global.__METRO_GLOBAL_PREFIX__ differ from
1104-
// each other when multiple module systems are used - e.g, in the context
1105-
// of Module Federation, the first one would refer to the local prefix
1106-
// defined at the top of the bundle, while the other always refers to the
1107-
// one coming from the Host
1112+
// GLOBAL_PREFIX and global.__METRO_GLOBAL_PREFIX__ differ from each other
1113+
// when multiple module systems are used - e.g, in the context of Module
1114+
// Federation, the first one would refer to the local prefix defined at the
1115+
// top of the bundle, while the other always refers to the one coming from
1116+
// the Host
11081117
return (
1109-
global[__METRO_GLOBAL_PREFIX__ + '__ReactRefresh'] ||
1118+
global[GLOBAL_PREFIX + '__ReactRefresh'] ||
11101119
global[global.__METRO_GLOBAL_PREFIX__ + '__ReactRefresh'] ||
11111120
// $FlowFixMe[prop-missing]
11121121
metroRequire.Refresh

0 commit comments

Comments
 (0)