Skip to content

Commit 9a46d92

Browse files
raju-opticlaude
andcommitted
move react native optional loaders to lib/react_native_optional
The loaders now live in lib/react_native_optional and are built to the same path in dist, so the main bundles can require them by the same relative path as in the source. This replaces the react_native_optional/* path alias and the rollup output.paths rewrite with a small resolveId plugin, and builds all loaders in one multi-input rollup build. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
1 parent 8f04196 commit 9a46d92

11 files changed

Lines changed: 46 additions & 39 deletions

File tree

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

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -56,7 +56,7 @@ vi.mock('@react-native-community/netinfo', () => {
5656
let isAsyncStorageAvailable = true;
5757

5858
// Simulate a missing @react-native-async-storage/async-storage
59-
vi.mock('react_native_optional/async_storage', () => ({
59+
vi.mock('../react_native_optional/async_storage', () => ({
6060
loadAsyncStorageModule: () => (isAsyncStorageAvailable ? { default: {} } : undefined),
6161
}));
6262

‎lib/index.react_native.ts‎

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -15,8 +15,8 @@
1515
*/
1616
// Each polyfill is only loaded when its global is missing, so apps can provide their own polyfill
1717
// 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';
18+
import './react_native_optional/fast_text_encoding';
19+
import './react_native_optional/get_random_values';
2020

2121
import { Client, Config } from './shared_types';
2222
import { getOptimizelyInstance, OptimizelyFactoryConfig } from './client_factory';

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

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -18,7 +18,7 @@ import { describe, it, expect, beforeEach, vi } from 'vitest';
1818

1919
let isAsyncStorageAvailable = true;
2020

21-
vi.mock('react_native_optional/async_storage', () => ({
21+
vi.mock('../react_native_optional/async_storage', () => ({
2222
loadAsyncStorageModule: () => (isAsyncStorageAvailable ? { default: {} } : undefined),
2323
}));
2424

lib/utils/import.react_native/optional/async_storage.ts renamed to lib/react_native_optional/async_storage.ts

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -14,7 +14,7 @@
1414
* limitations under the License.
1515
*/
1616

17-
import { Platform } from '../../../platform_support';
17+
import { Platform } from '../platform_support';
1818

1919
// Shipped as its own module so the optional require cannot shift others; see fast_text_encoding.ts.
2020

lib/utils/import.react_native/optional/fast_text_encoding.ts renamed to lib/react_native_optional/fast_text_encoding.ts

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -14,7 +14,7 @@
1414
* limitations under the License.
1515
*/
1616

17-
import { Platform } from '../../../platform_support';
17+
import { Platform } from '../platform_support';
1818

1919
// Files in this directory are not bundled into the main SDK bundle; each is shipped as its own
2020
// module under dist/react_native_optional (see rollup.config.mjs). Metro before 0.82.5 drops a missing

lib/utils/import.react_native/optional/get_random_values.ts renamed to lib/react_native_optional/get_random_values.ts

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -14,7 +14,7 @@
1414
* limitations under the License.
1515
*/
1616

17-
import { Platform } from '../../../platform_support';
17+
import { Platform } from '../platform_support';
1818

1919
// Shipped as its own module so the optional require cannot shift others; see fast_text_encoding.ts.
2020

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

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -16,12 +16,12 @@
1616

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

19-
vi.mock('react_native_optional/async_storage', () => ({
19+
vi.mock('../../../react_native_optional/async_storage', () => ({
2020
loadAsyncStorageModule: vi.fn(),
2121
}));
2222

2323
import { ensureMultiGet, getDefaultAsyncStorage, MODULE_NOT_FOUND_REACT_NATIVE_ASYNC_STORAGE } from './async-storage';
24-
import { loadAsyncStorageModule } from 'react_native_optional/async_storage';
24+
import { loadAsyncStorageModule } from '../../../react_native_optional/async_storage';
2525

2626
describe('getDefaultAsyncStorage', () => {
2727
it('should throw module not found error when async storage is not installed', () => {

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

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

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

2020
export interface AsyncStorageCompat {
2121
getItem(key: string): Promise<string | null>;

‎rollup.config.mjs‎

Lines changed: 36 additions & 25 deletions
Original file line numberDiff line numberDiff line change
@@ -21,7 +21,7 @@ import alias from '@rollup/plugin-alias';
2121
import { createRequire } from 'module';
2222
import { fileURLToPath } from 'url';
2323
import { readdirSync } from 'fs';
24-
import { dirname, join } from 'path';
24+
import { dirname, join, relative, resolve } from 'path';
2525

2626
const __filename = fileURLToPath(import.meta.url);
2727
const __dirname = dirname(__filename);
@@ -59,31 +59,46 @@ const externalDeps = ['https', 'http', 'url'].concat(Object.keys({ ...dependenci
5959
// into the CJS output instead of leaving it as an external dependency.
6060
const externalDepsWithoutUuid = externalDeps.filter(dep => dep !== 'uuid');
6161

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'))
62+
// React Native optional-dependency loaders (lib/react_native_optional) are not bundled into the
63+
// main bundles. Each is shipped as its own module at the same relative location in dist, because Metro
64+
// before 0.82.5 shifts every later require in a module when an optional dependency is missing.
65+
// See lib/react_native_optional/fast_text_encoding.ts.
66+
const BUILD_DIR = join(__dirname, '.build');
67+
const RN_OPTIONAL_DIR = 'react_native_optional';
68+
const RN_OPTIONAL_LOADERS = readdirSync(join(__dirname, 'lib', RN_OPTIONAL_DIR))
6969
.filter(file => file.endsWith('.ts') && !file.endsWith('.spec.ts'))
7070
.map(file => file.replace(/\.ts$/, ''));
7171

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);
72+
// Leaves loader imports out of the main bundles and writes them as a path relative to the bundle, e.g.
73+
// import '../../../react_native_optional/async_storage' (from a file deep in .build)
74+
// -> require("./react_native_optional/async_storage.js") (in dist/index.react_native.min.js)
75+
// The bundles are at the root of dist and the loaders are built to dist/react_native_optional,
76+
// so that path points to the built loader.
77+
// Marking the imports external via the `external` option is not enough: Rollup would resolve them to the
78+
// file in .build and write a path from the bundle back into .build (../.build/react_native_optional/...).
79+
// Returning a relative id from resolveId makes Rollup write it exactly as given.
80+
const rnOptionalExternalPlugin = {
81+
name: 'rn-optional-external',
82+
resolveId(source, importer) {
83+
if (!importer || !source.startsWith('.')) return null;
84+
const pathInBuild = relative(BUILD_DIR, resolve(dirname(importer), source)).replace(/\.js$/, '');
85+
if (!pathInBuild.startsWith(`${RN_OPTIONAL_DIR}/`)) return null;
86+
return { id: `./${pathInBuild}.js`, external: true };
87+
},
88+
};
7789

78-
const rnOptionalLoaderBundle = name => ({
90+
const rnOptionalLoadersBundle = {
7991
external: externalDeps,
80-
input: join(__dirname, `.build/utils/import.react_native/optional/${name}.js`),
92+
input: Object.fromEntries(
93+
RN_OPTIONAL_LOADERS.map(name => [name, join(BUILD_DIR, RN_OPTIONAL_DIR, `${name}.js`)])
94+
),
8195
output: {
8296
exports: 'named',
8397
format: 'cjs',
84-
file: `dist/${RN_OPTIONAL}/${name}.js`,
98+
dir: join('dist', RN_OPTIONAL_DIR),
99+
entryFileNames: '[name].js',
85100
},
86-
});
101+
};
87102

88103
const cjsBundleFor = (platform, opt = {}) => {
89104
const { minify, ext } = {
@@ -95,14 +110,13 @@ const cjsBundleFor = (platform, opt = {}) => {
95110
const min = minify ? '.min' : '';
96111

97112
return {
98-
plugins: [aliasPlugin, resolvePluginByPlatform[platform] || resolvePlugin, commonjs()],
99-
external: externalWithRnOptionalLoaders(externalDepsWithoutUuid),
113+
plugins: [rnOptionalExternalPlugin, aliasPlugin, resolvePluginByPlatform[platform] || resolvePlugin, commonjs()],
114+
external: externalDepsWithoutUuid,
100115
input: `.build/index.${platform}.js`,
101116
output: {
102117
exports: 'named',
103118
format: 'cjs',
104119
file: `dist/index.${platform}${min}${ext}`,
105-
paths: rnOptionalLoaderPaths,
106120
plugins: minify ? [terser()] : undefined,
107121
sourcemap: true,
108122
},
@@ -120,12 +134,11 @@ const esmBundleFor = (platform, opt) => {
120134

121135
return {
122136
...cjsBundleFor(platform),
123-
external: externalWithRnOptionalLoaders(externalDeps),
137+
external: externalDeps,
124138
output: [
125139
{
126140
format: 'es',
127141
file: `dist/index.${platform}.es${min}${ext}`,
128-
paths: rnOptionalLoaderPaths,
129142
plugins: minify ? [terser()] : undefined,
130143
sourcemap: true,
131144
},
@@ -227,9 +240,7 @@ const bundles = {
227240
'esm-node-min': esmBundleFor('node', { ext: '.mjs' }),
228241
'esm-react-native-min': esmBundleFor('react_native'),
229242
'esm-universal': esmBundleFor('universal'),
230-
...Object.fromEntries(
231-
RN_OPTIONAL_LOADERS.map(name => [`cjs-react-native-optional-${name}`, rnOptionalLoaderBundle(name)])
232-
),
243+
'cjs-react-native-optional': rnOptionalLoadersBundle,
233244
'json-schema': jsonSchemaBundle,
234245
'cjs-ua-parser-min': cjsBundleForUAParser(),
235246
'esm-ua-parser-min': esmBundleForUAParser(),

‎tsconfig.json‎

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

0 commit comments

Comments
 (0)