Skip to content

Commit 8f04196

Browse files
raju-opticlaude
andcommitted
load react native polyfills only when missing, from separate modules
fast-text-encoding and react-native-get-random-values are now only required when TextEncoder / crypto.getRandomValues are missing, so apps can drop them or load their own polyfill before the SDK. These requires and the async-storage require are moved into their own modules (imported as react_native_optional/*, shipped in dist/react_native_optional) instead of being bundled. Metro before 0.82.5 drops a missing optional dependency from a module's dependency map, which shifts every later require in that module to the wrong module. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
1 parent fd652c3 commit 8f04196

11 files changed

Lines changed: 200 additions & 48 deletions

File tree

‎lib/event_processor/event_processor_factory.react_native.spec.ts‎

Lines changed: 4 additions & 20 deletions
Original file line numberDiff line numberDiff line change
@@ -55,26 +55,10 @@ vi.mock('@react-native-community/netinfo', () => {
5555
});
5656
let isAsyncStorageAvailable = true;
5757

58-
// Mock Node.js module loader to simulate missing @react-native-async-storage/async-storage
59-
vi.hoisted(() => {
60-
mockRequireNetInfo();
61-
});
62-
63-
function mockRequireNetInfo() {
64-
// Dynamically import module synchronously in Node environment
65-
// eslint-disable-next-line @typescript-eslint/no-var-requires
66-
const { Module } = require('module');
67-
const M: any = Module;
68-
69-
M._load_original = M._load;
70-
M._load = (uri: string, parent: string) => {
71-
if (uri === '@react-native-async-storage/async-storage') {
72-
if (isAsyncStorageAvailable) return {};
73-
throw new Error("Module not found: @react-native-async-storage/async-storage");
74-
}
75-
return M._load_original(uri, parent);
76-
};
77-
}
58+
// Simulate a missing @react-native-async-storage/async-storage
59+
vi.mock('react_native_optional/async_storage', () => ({
60+
loadAsyncStorageModule: () => (isAsyncStorageAvailable ? { default: {} } : undefined),
61+
}));
7862

7963
import { createForwardingEventProcessor, createBatchEventProcessor } from './event_processor_factory.react_native';
8064
import defaultEventDispatcher from './event_dispatcher/default_dispatcher.browser';

‎lib/index.react_native.ts‎

Lines changed: 4 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -13,8 +13,10 @@
1313
* See the License for the specific language governing permissions and
1414
* limitations under the License.
1515
*/
16-
import 'fast-text-encoding';
17-
import 'react-native-get-random-values';
16+
// Each polyfill is only loaded when its global is missing, so apps can provide their own polyfill
17+
// instead by loading it before the SDK is imported.
18+
import 'react_native_optional/fast_text_encoding';
19+
import 'react_native_optional/get_random_values';
1820

1921
import { Client, Config } from './shared_types';
2022
import { getOptimizelyInstance, OptimizelyFactoryConfig } from './client_factory';

‎lib/project_config/config_manager_factory.react_native.spec.ts‎

Lines changed: 3 additions & 18 deletions
Original file line numberDiff line numberDiff line change
@@ -16,26 +16,11 @@
1616

1717
import { describe, it, expect, beforeEach, vi } from 'vitest';
1818

19-
vi.hoisted(async () => {
20-
mockRequireAsyncStorage();
21-
});
22-
2319
let isAsyncStorageAvailable = true;
2420

25-
function mockRequireAsyncStorage() {
26-
// eslint-disable-next-line @typescript-eslint/no-var-requires
27-
const { Module } = require('module');
28-
const M: any = Module;
29-
30-
M._load_original = M._load;
31-
M._load = (uri: string, parent: string) => {
32-
if (uri === '@react-native-async-storage/async-storage') {
33-
if (isAsyncStorageAvailable) return { default: {} };
34-
throw new Error("Module not found: @react-native-async-storage/async-storage");
35-
}
36-
return M._load_original(uri, parent);
37-
};
38-
}
21+
vi.mock('react_native_optional/async_storage', () => ({
22+
loadAsyncStorageModule: () => (isAsyncStorageAvailable ? { default: {} } : undefined),
23+
}));
3924

4025
vi.mock('./config_manager_factory', () => {
4126
return {

‎lib/utils/import.react_native/@react-native-async-storage/async-storage.spec.ts‎

Lines changed: 39 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -15,7 +15,45 @@
1515
*/
1616

1717
import { vi, describe, it, expect } from 'vitest';
18-
import { ensureMultiGet } from './async-storage';
18+
19+
vi.mock('react_native_optional/async_storage', () => ({
20+
loadAsyncStorageModule: vi.fn(),
21+
}));
22+
23+
import { ensureMultiGet, getDefaultAsyncStorage, MODULE_NOT_FOUND_REACT_NATIVE_ASYNC_STORAGE } from './async-storage';
24+
import { loadAsyncStorageModule } from 'react_native_optional/async_storage';
25+
26+
describe('getDefaultAsyncStorage', () => {
27+
it('should throw module not found error when async storage is not installed', () => {
28+
vi.mocked(loadAsyncStorageModule).mockReturnValueOnce(undefined);
29+
30+
expect(() => getDefaultAsyncStorage()).toThrow(MODULE_NOT_FOUND_REACT_NATIVE_ASYNC_STORAGE);
31+
});
32+
33+
it('should throw module not found error when the module has no default export', () => {
34+
vi.mocked(loadAsyncStorageModule).mockReturnValueOnce({});
35+
36+
expect(() => getDefaultAsyncStorage()).toThrow(MODULE_NOT_FOUND_REACT_NATIVE_ASYNC_STORAGE);
37+
});
38+
39+
it('should return the default export of the async storage module', () => {
40+
const multiGet = vi.fn();
41+
const storage = {
42+
getItem: vi.fn(),
43+
setItem: vi.fn(),
44+
removeItem: vi.fn(),
45+
getAllKeys: vi.fn(),
46+
clear: vi.fn(),
47+
multiGet,
48+
};
49+
vi.mocked(loadAsyncStorageModule).mockReturnValueOnce({ default: storage });
50+
51+
const result = getDefaultAsyncStorage();
52+
53+
expect(result).toBe(storage);
54+
expect(result.multiGet).toBe(multiGet);
55+
});
56+
});
1957

2058
describe('ensureMultiGet', () => {
2159
it('should preserve multiGet when already present (v1/v2)', () => {

‎lib/utils/import.react_native/@react-native-async-storage/async-storage.ts‎

Lines changed: 4 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -15,6 +15,7 @@
1515
*/
1616

1717
import { Platform } from '../../../platform_support';
18+
import { loadAsyncStorageModule } from 'react_native_optional/async_storage';
1819

1920
export interface AsyncStorageCompat {
2021
getItem(key: string): Promise<string | null>;
@@ -59,13 +60,11 @@ export const ensureMultiGet = (storage: RawAsyncStorage): AsyncStorageCompat =>
5960
};
6061

6162
export const getDefaultAsyncStorage = (): AsyncStorageCompat => {
62-
try {
63-
// eslint-disable-next-line @typescript-eslint/no-var-requires
64-
const storage = require('@react-native-async-storage/async-storage').default;
65-
return ensureMultiGet(storage);
66-
} catch (e) {
63+
const storage = loadAsyncStorageModule()?.default as RawAsyncStorage | undefined;
64+
if (!storage) {
6765
throw new Error(MODULE_NOT_FOUND_REACT_NATIVE_ASYNC_STORAGE);
6866
}
67+
return ensureMultiGet(storage);
6968
};
7069

7170
export const __platforms: Platform[] = ['__universal__'];
Lines changed: 35 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,35 @@
1+
/**
2+
* Copyright 2026, Optimizely
3+
*
4+
* Licensed under the Apache License, Version 2.0 (the "License");
5+
* you may not use this file except in compliance with the License.
6+
* You may obtain a copy of the License at
7+
*
8+
* https://www.apache.org/licenses/LICENSE-2.0
9+
*
10+
* Unless required by applicable law or agreed to in writing, software
11+
* distributed under the License is distributed on an "AS IS" BASIS,
12+
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13+
* See the License for the specific language governing permissions and
14+
* limitations under the License.
15+
*/
16+
17+
import { Platform } from '../../../platform_support';
18+
19+
// Shipped as its own module so the optional require cannot shift others; see fast_text_encoding.ts.
20+
21+
// Required while this module loads rather than when loadAsyncStorageModule is called: on Metro before
22+
// 0.82.5, requiring a missing module only throws to the caller during module loading. Outside of it,
23+
// Metro reports the error as fatal and returns undefined instead of throwing.
24+
let asyncStorageModule: { default?: unknown } | undefined;
25+
try {
26+
// eslint-disable-next-line @typescript-eslint/no-var-requires
27+
asyncStorageModule = require('@react-native-async-storage/async-storage');
28+
} catch (e) {
29+
asyncStorageModule = undefined;
30+
}
31+
32+
// Returns the @react-native-async-storage/async-storage module, or undefined if it is not available.
33+
export const loadAsyncStorageModule = (): { default?: unknown } | undefined => asyncStorageModule;
34+
35+
export const __platforms: Platform[] = ['__universal__'];
Lines changed: 39 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,39 @@
1+
/**
2+
* Copyright 2026, Optimizely
3+
*
4+
* Licensed under the Apache License, Version 2.0 (the "License");
5+
* you may not use this file except in compliance with the License.
6+
* You may obtain a copy of the License at
7+
*
8+
* https://www.apache.org/licenses/LICENSE-2.0
9+
*
10+
* Unless required by applicable law or agreed to in writing, software
11+
* distributed under the License is distributed on an "AS IS" BASIS,
12+
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13+
* See the License for the specific language governing permissions and
14+
* limitations under the License.
15+
*/
16+
17+
import { Platform } from '../../../platform_support';
18+
19+
// Files in this directory are not bundled into the main SDK bundle; each is shipped as its own
20+
// module under dist/react_native_optional (see rollup.config.mjs). Metro before 0.82.5 drops a missing
21+
// optional dependency from the module's dependency map, which shifts every later require in that module.
22+
// Keeping each optional require alone in its own module limits that to the require itself.
23+
24+
// murmurhash needs a global TextEncoder. Newer Hermes provides one; older Hermes and JSC do not.
25+
// The try/catch lets Metro treat fast-text-encoding as an optional dependency
26+
// (requires allowOptionalDependencies, which React Native's and Expo's default Metro configs enable).
27+
if (typeof TextEncoder === 'undefined') {
28+
try {
29+
// eslint-disable-next-line @typescript-eslint/no-var-requires
30+
require('fast-text-encoding');
31+
} catch (e) {
32+
throw new Error(
33+
'TextEncoder is not available in this environment. Install fast-text-encoding, ' +
34+
'or load another TextEncoder polyfill before importing the SDK.'
35+
);
36+
}
37+
}
38+
39+
export const __platforms: Platform[] = ['react_native'];
Lines changed: 34 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,34 @@
1+
/**
2+
* Copyright 2026, Optimizely
3+
*
4+
* Licensed under the Apache License, Version 2.0 (the "License");
5+
* you may not use this file except in compliance with the License.
6+
* You may obtain a copy of the License at
7+
*
8+
* https://www.apache.org/licenses/LICENSE-2.0
9+
*
10+
* Unless required by applicable law or agreed to in writing, software
11+
* distributed under the License is distributed on an "AS IS" BASIS,
12+
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13+
* See the License for the specific language governing permissions and
14+
* limitations under the License.
15+
*/
16+
17+
import { Platform } from '../../../platform_support';
18+
19+
// Shipped as its own module so the optional require cannot shift others; see fast_text_encoding.ts.
20+
21+
// uuid needs a global crypto.getRandomValues, which React Native does not provide.
22+
if (typeof crypto === 'undefined' || typeof crypto.getRandomValues !== 'function') {
23+
try {
24+
// eslint-disable-next-line @typescript-eslint/no-var-requires
25+
require('react-native-get-random-values');
26+
} catch (e) {
27+
throw new Error(
28+
'crypto.getRandomValues is not available in this environment. Install react-native-get-random-values, ' +
29+
'or load another crypto.getRandomValues polyfill before importing the SDK.'
30+
);
31+
}
32+
}
33+
34+
export const __platforms: Platform[] = ['react_native'];

‎rollup.config.mjs‎

Lines changed: 34 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -20,6 +20,7 @@ import terser from '@rollup/plugin-terser';
2020
import alias from '@rollup/plugin-alias';
2121
import { createRequire } from 'module';
2222
import { fileURLToPath } from 'url';
23+
import { readdirSync } from 'fs';
2324
import { dirname, join } from 'path';
2425

2526
const __filename = fileURLToPath(import.meta.url);
@@ -58,6 +59,32 @@ const externalDeps = ['https', 'http', 'url'].concat(Object.keys({ ...dependenci
5859
// into the CJS output instead of leaving it as an external dependency.
5960
const externalDepsWithoutUuid = externalDeps.filter(dep => dep !== 'uuid');
6061

62+
// React Native optional-dependency loaders (imported as 'react_native_optional/<name>', see the tsconfig
63+
// paths) are not bundled into the main bundles. Each is shipped as its own module in
64+
// dist/react_native_optional and required from the main bundle by relative path, because Metro before
65+
// 0.82.5 shifts every later require in a module when an optional dependency is missing.
66+
// See lib/utils/import.react_native/optional/fast_text_encoding.ts.
67+
const RN_OPTIONAL = 'react_native_optional';
68+
const RN_OPTIONAL_LOADERS = readdirSync(join(__dirname, 'lib/utils/import.react_native/optional'))
69+
.filter(file => file.endsWith('.ts') && !file.endsWith('.spec.ts'))
70+
.map(file => file.replace(/\.ts$/, ''));
71+
72+
const isRnOptionalLoader = id => id.startsWith(`${RN_OPTIONAL}/`);
73+
74+
const externalWithRnOptionalLoaders = deps => id => deps.includes(id) || isRnOptionalLoader(id);
75+
76+
const rnOptionalLoaderPaths = id => (isRnOptionalLoader(id) ? `./${id}.js` : id);
77+
78+
const rnOptionalLoaderBundle = name => ({
79+
external: externalDeps,
80+
input: join(__dirname, `.build/utils/import.react_native/optional/${name}.js`),
81+
output: {
82+
exports: 'named',
83+
format: 'cjs',
84+
file: `dist/${RN_OPTIONAL}/${name}.js`,
85+
},
86+
});
87+
6188
const cjsBundleFor = (platform, opt = {}) => {
6289
const { minify, ext } = {
6390
minify: true,
@@ -69,12 +96,13 @@ const cjsBundleFor = (platform, opt = {}) => {
6996

7097
return {
7198
plugins: [aliasPlugin, resolvePluginByPlatform[platform] || resolvePlugin, commonjs()],
72-
external: externalDepsWithoutUuid,
99+
external: externalWithRnOptionalLoaders(externalDepsWithoutUuid),
73100
input: `.build/index.${platform}.js`,
74101
output: {
75102
exports: 'named',
76103
format: 'cjs',
77104
file: `dist/index.${platform}${min}${ext}`,
105+
paths: rnOptionalLoaderPaths,
78106
plugins: minify ? [terser()] : undefined,
79107
sourcemap: true,
80108
},
@@ -92,11 +120,12 @@ const esmBundleFor = (platform, opt) => {
92120

93121
return {
94122
...cjsBundleFor(platform),
95-
external: externalDeps,
123+
external: externalWithRnOptionalLoaders(externalDeps),
96124
output: [
97125
{
98126
format: 'es',
99127
file: `dist/index.${platform}.es${min}${ext}`,
128+
paths: rnOptionalLoaderPaths,
100129
plugins: minify ? [terser()] : undefined,
101130
sourcemap: true,
102131
},
@@ -198,6 +227,9 @@ const bundles = {
198227
'esm-node-min': esmBundleFor('node', { ext: '.mjs' }),
199228
'esm-react-native-min': esmBundleFor('react_native'),
200229
'esm-universal': esmBundleFor('universal'),
230+
...Object.fromEntries(
231+
RN_OPTIONAL_LOADERS.map(name => [`cjs-react-native-optional-${name}`, rnOptionalLoaderBundle(name)])
232+
),
201233
'json-schema': jsonSchemaBundle,
202234
'cjs-ua-parser-min': cjsBundleForUAParser(),
203235
'esm-ua-parser-min': esmBundleForUAParser(),

‎tsconfig.json‎

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -24,6 +24,9 @@
2424
"log_message": [
2525
"./lib/message/log_message"
2626
],
27+
"react_native_optional/*": [
28+
"./lib/utils/import.react_native/optional/*"
29+
],
2730
},
2831
"resolveJsonModule": true,
2932
"allowJs": true,

0 commit comments

Comments
 (0)