Skip to content

Commit 6536826

Browse files
whydidoodannyhw
andauthored
fix(repack): lower RN 0.81+ Flow syntax in flow-loader and keep Flow enums in Babel loaders (#1492)
Co-authored-by: Daniel Williams <dannyhyunsoowilliams@gmail.com> Co-authored-by: Daniel Williams <me@dannyhw.com>
1 parent 1a5e2f6 commit 6536826

29 files changed

Lines changed: 1004 additions & 100 deletions
Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,5 @@
1+
---
2+
"@callstack/repack": patch
3+
---
4+
5+
Fix Flow enums disappearing in `babel-loader` and `babel-swc-loader`: `@react-native/babel-preset` strips enum declarations before its enum plugin runs, leaving references such as React Native's `VirtualViewMode.cast()` undefined at runtime. Both loaders now run the preset's `babel-plugin-transform-flow-enums` ahead of the preset, so enums are lowered to `flow-enums-runtime` (resolved from the project or from `react-native`) in every Flow file, with or without an `@flow` pragma. Flow `component` declarations are also lowered for the project's React version instead of always targeting React 19 (`hermesParserOverrides.reactRuntimeTarget` still takes precedence).
Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,5 @@
1+
---
2+
"@callstack/repack": patch
3+
---
4+
5+
Fix `babel-loader` and `babel-swc-loader` failing with `SyntaxError: "[object Object]" is not valid JSON` when a previous loader passes its source map as an object, e.g. `flow-loader` (for lowered Flow syntax or with `pretty: true`) or the stock `babel-loader` used by `getCodegenTransformRules`. Both loaders now accept serialized and object source maps.
Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,5 @@
1+
---
2+
"@callstack/repack": patch
3+
---
4+
5+
Fix `flow-loader`, and with it `getJsTransformRules`, emitting invalid JavaScript for Flow `component` and `hook` declarations, enums and `match` expressions, which React Native ships since 0.81. Files using them are now compiled with the project's React Native parser (`hermes-parser` or `flow-parser`), `babel-plugin-transform-flow-enums` and `@babel/plugin-transform-flow-strip-types`, while other files still go through `flow-remove-types`. Lowered enums use `flow-enums-runtime`, resolved from the project or from `react-native`. `component` declarations follow the project's React version (`ref` as a prop on React 19, `forwardRef` on React 18). Also fix `flow-loader` crashing under webpack with `Maximum call stack size exceeded`.

‎apps/tester-app/__tests__/bundle.test.ts‎

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -22,6 +22,10 @@ describe('bundle command', () => {
2222
bundler: 'rspack',
2323
configFile: './rspack.config.mjs',
2424
},
25+
{
26+
bundler: 'rspack-swc',
27+
configFile: './rspack.swc.config.mjs',
28+
},
2529
])('using $bundler', ({ bundler, configFile }) => {
2630
const bundleCommand = commands.find((command) => command.name === 'bundle');
2731
if (!bundleCommand) throw new Error('bundle command not found');
Lines changed: 23 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,23 @@
1+
import * as Repack from '@callstack/repack';
2+
import baseConfig from '../../rspack.config.mjs';
3+
4+
// Same app, but JS goes through the SWC-native rules instead of babel-swc-loader,
5+
// so React Native's own Flow sources are compiled by `getJsTransformRules`
6+
export default (env) => {
7+
const config = baseConfig(env);
8+
const assetRules = config.module.rules.filter(
9+
(rule) => rule.use?.loader !== '@callstack/repack/babel-swc-loader'
10+
);
11+
12+
return {
13+
...config,
14+
module: {
15+
...config.module,
16+
rules: [...Repack.getJsTransformRules(), ...assetRules],
17+
},
18+
output: {
19+
...config.output,
20+
path: process.env.TEST_WEBPACK_OUTPUT_DIR,
21+
},
22+
};
23+
};

‎packages/repack/src/helpers/resolveReactNativeParser.ts‎

Lines changed: 141 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -1,20 +1,152 @@
11
import { createRequire } from 'node:module';
2+
import type { PluginItem, types } from '@babel/core';
23

3-
export function resolveReactNativeParser(projectRoot: string) {
4+
function resolvePreset(projectRoot: string) {
5+
const presetPath = require.resolve(
6+
'@react-native/babel-preset/package.json',
7+
{
8+
paths: [projectRoot],
9+
}
10+
);
11+
const presetRequire = createRequire(presetPath);
12+
const { version, dependencies } = presetRequire('./package.json');
13+
14+
return {
15+
presetRequire,
16+
dependencies: dependencies as Record<string, string> | undefined,
17+
location: `@react-native/babel-preset@${version} (${presetPath})`,
18+
};
19+
}
20+
21+
/**
22+
* Caches a lookup per project root: failed resolutions aren't cached by Node,
23+
* and these run for every transformed file.
24+
*/
25+
function cacheByProjectRoot<T>(resolve: (projectRoot: string) => T) {
26+
const cache = new Map<string, T>();
27+
return (projectRoot: string): T => {
28+
if (!cache.has(projectRoot)) {
29+
cache.set(projectRoot, resolve(projectRoot));
30+
}
31+
return cache.get(projectRoot)!;
32+
};
33+
}
34+
35+
/**
36+
* Resolves a dependency of the project's `@react-native/babel-preset`,
37+
* e.g. a Babel plugin the preset ships with.
38+
*/
39+
export function resolveFromReactNativePreset(
40+
projectRoot: string,
41+
request: string
42+
): string {
443
let presetLocation = projectRoot;
544

645
try {
7-
const presetPath = require.resolve(
8-
'@react-native/babel-preset/package.json',
9-
{
10-
paths: [projectRoot],
11-
}
46+
const { presetRequire, location } = resolvePreset(projectRoot);
47+
presetLocation = location;
48+
return presetRequire.resolve(request);
49+
} catch (cause) {
50+
throw Object.assign(
51+
new Error(
52+
`Failed to resolve '${request}' from ${presetLocation}. ` +
53+
`Make sure '@react-native/babel-preset' is installed.`
54+
),
55+
{ cause }
1256
);
57+
}
58+
}
1359

14-
const presetRequire = createRequire(presetPath);
15-
const { version, dependencies } = presetRequire('./package.json');
60+
/**
61+
* Resolves `flow-enums-runtime`, which lowered Flow enums require.
62+
*
63+
* Only React Native depends on it, so with isolated installs (pnpm) it often
64+
* can't be resolved from the project root or from the file using an enum.
65+
*/
66+
const resolveFlowEnumsRuntime = cacheByProjectRoot(
67+
(projectRoot): string | null => {
68+
try {
69+
return require.resolve('flow-enums-runtime', { paths: [projectRoot] });
70+
} catch {}
1671

17-
presetLocation = `@react-native/babel-preset@${version} (${presetPath})`;
72+
try {
73+
const reactNativePath = require.resolve('react-native/package.json', {
74+
paths: [projectRoot],
75+
});
76+
return createRequire(reactNativePath).resolve('flow-enums-runtime');
77+
} catch {
78+
return null;
79+
}
80+
}
81+
);
82+
83+
// lets the plugin run alongside a copy the project adds itself, which Babel
84+
// rejects as a duplicate when neither copy is named
85+
const FLOW_ENUMS_PLUGIN_NAME = '@callstack/repack/flow-enums';
86+
87+
/**
88+
* `babel-plugin-transform-flow-enums` from the project's React Native preset,
89+
* or nothing when the preset isn't installed.
90+
*
91+
* Has to run ahead of the preset: the preset's `flow-strip-types` removes enum
92+
* declarations before the preset's own enum plugin gets to them.
93+
*/
94+
export const getFlowEnumsPlugins = cacheByProjectRoot(
95+
(projectRoot): PluginItem[] => {
96+
let pluginPath: string;
97+
try {
98+
pluginPath = resolveFromReactNativePreset(
99+
projectRoot,
100+
'babel-plugin-transform-flow-enums'
101+
);
102+
} catch {
103+
return [];
104+
}
105+
106+
const runtimePath = resolveFlowEnumsRuntime(projectRoot);
107+
// the plugin defaults to `require('flow-enums-runtime')`
108+
if (!runtimePath) return [[pluginPath, {}, FLOW_ENUMS_PLUGIN_NAME]];
109+
110+
return [
111+
[
112+
pluginPath,
113+
{
114+
getRuntime: (t: typeof types) =>
115+
t.callExpression(t.identifier('require'), [
116+
t.stringLiteral(runtimePath),
117+
]),
118+
},
119+
FLOW_ENUMS_PLUGIN_NAME,
120+
],
121+
];
122+
}
123+
);
124+
125+
/**
126+
* Picks the React runtime that Flow `component` declarations are lowered for,
127+
* based on the project's `react` version: React 19 passes `ref` as a prop,
128+
* React 18 needs `forwardRef`. Defaults to React 19.
129+
*/
130+
export const resolveReactRuntimeTarget = cacheByProjectRoot(
131+
(projectRoot): '18' | '19' => {
132+
try {
133+
const { version } = require(
134+
require.resolve('react/package.json', { paths: [projectRoot] })
135+
);
136+
return Number.parseInt(version, 10) < 19 ? '18' : '19';
137+
} catch {
138+
return '19';
139+
}
140+
}
141+
);
142+
143+
export function resolveReactNativeParser(projectRoot: string) {
144+
let presetLocation = projectRoot;
145+
146+
try {
147+
const { presetRequire, dependencies, location } =
148+
resolvePreset(projectRoot);
149+
presetLocation = location;
18150

19151
// A hoisted parser must not override the one declared by the preset.
20152
if (dependencies?.['flow-parser']) {

‎packages/repack/src/loaders/babelLoader/__tests__/babelLoader.test.ts‎

Lines changed: 10 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -1,24 +1,24 @@
11
import { transform } from '../babelLoader.js';
2-
import { loadReactNativeParser } from '../utils.js';
2+
import { parseReactNativeSource } from '../utils.js';
33

44
jest.mock('../utils.js', () => {
55
const actual = jest.requireActual('../utils.js');
66
const { parseSync } = require('@babel/core');
77
return {
88
...actual,
9-
loadReactNativeParser: jest.fn(async () => ({
10-
parse: (
9+
parseReactNativeSource: jest.fn(
10+
async (
1111
src: string,
12-
opts: { sourceType?: 'script' | 'module' | 'unambiguous' }
12+
opts: { sourceType?: 'script' | 'module' | 'unambiguous' | null }
1313
) =>
1414
parseSync(src, {
1515
sourceType: opts?.sourceType ?? 'unambiguous',
1616
// the stand-in parser runs outside of a file context, so skip config lookup
1717
filename: '/virtual/hermes-parser-stand-in.js',
1818
babelrc: false,
1919
configFile: false,
20-
}),
21-
})),
20+
})
21+
),
2222
};
2323
});
2424

@@ -43,7 +43,7 @@ describe('babelLoader', () => {
4343
baseTransformOptions('/virtual/plain.js')
4444
);
4545

46-
expect(loadReactNativeParser).not.toHaveBeenCalled();
46+
expect(parseReactNativeSource).not.toHaveBeenCalled();
4747
});
4848

4949
it('uses hermes-parser for sources with an @flow pragma', async () => {
@@ -52,7 +52,7 @@ describe('babelLoader', () => {
5252
baseTransformOptions('/virtual/flow.js')
5353
);
5454

55-
expect(loadReactNativeParser).toHaveBeenCalled();
55+
expect(parseReactNativeSource).toHaveBeenCalled();
5656
});
5757

5858
it('uses hermes-parser for every source when flow is set to all', async () => {
@@ -62,7 +62,7 @@ describe('babelLoader', () => {
6262
{ hermesParserOverrides: { flow: 'all' } }
6363
);
6464

65-
expect(loadReactNativeParser).toHaveBeenCalled();
65+
expect(parseReactNativeSource).toHaveBeenCalled();
6666
});
6767

6868
it('skips hermes-parser for TypeScript sources', async () => {
@@ -71,7 +71,7 @@ describe('babelLoader', () => {
7171
baseTransformOptions('/virtual/typescript.ts')
7272
);
7373

74-
expect(loadReactNativeParser).not.toHaveBeenCalled();
74+
expect(parseReactNativeSource).not.toHaveBeenCalled();
7575
});
7676
});
7777

0 commit comments

Comments
 (0)