Open History to see the last commit
1// @effect-diagnostics nodeBuiltinImport:off - compiles real source files on disk.
2import * as NodeFS from "node:fs";
3import * as NodeModule from "node:module";
4import * as NodePath from "node:path";
5import { describe, expect, it } from "vite-plus/test";
6
7const mobileRoot = NodePath.resolve(__dirname, "..");
8const requireFromMobile = NodeModule.createRequire(NodePath.join(mobileRoot, "package.json"));
9const babel: {
10 transformFileSync: (file: string, options: Record<string, unknown>) => unknown;
11} = requireFromMobile("@babel/core");
12const metroConfig: Promise<{ transformer: { babelTransformerPath: string } }> =
13 requireFromMobile("./metro.config.js");
14
15// Remove bailout entries and manual memoization when compilation starts; this check rejects stale entries.
16const KNOWN_BAILOUTS: Record<string, string> = {
17 "src/components/ComposerAttachmentStrip.tsx": "unsupported syntax",
18 "src/components/ui/AndroidAnchoredMenu.tsx": "ref read during render",
19 "src/components/ui/Menu.tsx": "ref read during render",
20 "src/features/diffs/nativeReviewDiffSurface.ts": "ref read during render",
21 "src/features/home/thread-swipe-actions.tsx": "ref read during render",
22 "src/features/threads/PendingUserInputCard.tsx": "mutates a frozen value",
23 "src/features/threads/ThreadArrangementSheet.tsx": "ref read during render",
24 "src/features/voice-input/VoiceInputProvider.tsx": "ref read during render",
25 "src/features/voice-input/useVoiceInputController.ts": "ref read during render",
26 "src/native/StackHeader.tsx": "ref read during render",
27 "src/native/T3ComposerEditor.ios.tsx": "ref read during render",
28 "src/native/T3ComposerEditor.native.tsx": "ref read during render",
29};
30
31// Use Metro's iOS release flags; experiments.reactCompiler enables supportsReactCompiler.
32const metroCaller = {
33 name: "metro",
34 bundler: "metro",
35 platform: "ios",
36 isDev: false,
37 isServer: false,
38 isNodeModule: false,
39 supportsStaticESM: true,
40 supportsReactCompiler: true,
41};
42
43const sourceFiles = NodeFS.readdirSync(NodePath.join(mobileRoot, "src"), { recursive: true })
44 .map(String)
45 .filter((file) => /\.tsx?$/.test(file) && !/\.(test\.tsx?|d\.ts)$/.test(file))
46 .map((file) => `src/${file.split(NodePath.sep).join("/")}`)
47 .sort();
48
49type CompilerLoc = { readonly start?: { readonly line?: number } } | null;
50
51interface CompilerEvent {
52 readonly kind: string;
53 readonly detail?: {
54 readonly options?: {
55 readonly category?: string;
56 readonly reason?: string;
57 readonly loc?: CompilerLoc;
58 readonly details?: readonly { readonly loc?: CompilerLoc }[];
59 };
60 };
61}
62
63// babel.config.js is the file Metro loads; the logger rides on the preset's
64// own react-compiler option so the plugin runs with Metro's exact settings.
65function compileLikeMetro(file: string, events: CompilerEvent[], output: Record<string, unknown>) {
66 const babelConfig = requireFromMobile("./babel.config.js")({ cache: () => {} });
67 const presets = babelConfig.presets.map(([name, options]: [string, object]) =>
68 name === "babel-preset-expo"
69 ? [
70 requireFromMobile.resolve(name),
71 {
72 ...options,
73 "react-compiler": {
74 logger: { logEvent: (_: string, event: CompilerEvent) => events.push(event) },
75 },
76 },
77 ]
78 : [name, options],
79 );
80 return babel.transformFileSync(NodePath.join(mobileRoot, file), {
81 babelrc: false,
82 configFile: false,
83 cwd: mobileRoot,
84 presets,
85 caller: metroCaller,
86 code: false,
87 ...output,
88 });
89}
90
91function compilerBailouts(file: string): string[] {
92 const events: CompilerEvent[] = [];
93 compileLikeMetro(file, events, {});
94 return events
95 .filter((event) => event.kind === "CompileError" || event.kind === "CompileSkip")
96 .map(
97 (event) =>
98 `line ${(event.detail?.options?.loc ?? event.detail?.options?.details?.[0]?.loc)?.start?.line ?? "?"}: ${event.detail?.options?.category ?? event.kind} ${event.detail?.options?.reason ?? ""}`,
99 );
100}
101
102interface AstNode {
103 readonly type: string;
104 readonly [key: string]: unknown;
105}
106
107const isAstNode = (value: unknown): value is AstNode =>
108 typeof value === "object" && value !== null && "type" in value && typeof value.type === "string";
109
110function walkAst(
111 value: unknown,
112 visit: (node: AstNode, ancestors: readonly AstNode[]) => void,
113 ancestors: readonly AstNode[] = [],
114) {
115 if (typeof value !== "object" || value === null) return;
116 const node = isAstNode(value) ? value : null;
117 if (node) visit(node, ancestors);
118 const childAncestors = node ? [...ancestors, node] : ancestors;
119 for (const child of Object.values(value)) walkAst(child, visit, childAncestors);
120}
121
122// For each call to `callee`, whether it runs only on the cache-miss branch of
123// an `if ($[n] !== dep)` block rather than on every render.
124function compilerCachedCalls(file: string, callee: string): boolean[] {
125 const result = compileLikeMetro(file, [], { ast: true });
126 const cached: boolean[] = [];
127 if (typeof result !== "object" || result === null || !("ast" in result)) return cached;
128 walkAst(result.ast, (node, ancestors) => {
129 if (node.type !== "CallExpression" || !isAstNode(node.callee)) return;
130 if (node.callee.type !== "Identifier" || node.callee.name !== callee) return;
131 cached.push(
132 ancestors.some(
133 (ancestor, index) =>
134 ancestor.type === "IfStatement" &&
135 ancestors[index + 1] === ancestor.consequent &&
136 JSON.stringify(ancestor.test).includes('"name":"$"'),
137 ),
138 );
139 });
140 return cached;
141}
142
143describe("React Compiler coverage", () => {
144 it("Metro's transformer applies the compiler", async () => {
145 const { transformer } = await metroConfig;
146 const metroTransformer = requireFromMobile(transformer.babelTransformerPath);
147 const filename = NodePath.join(
148 mobileRoot,
149 "src/features/archive/ArchivedThreadsRouteScreen.tsx",
150 );
151 const transformed = (reactCompiler: string) => {
152 const { ast } = metroTransformer.transform({
153 filename,
154 src: NodeFS.readFileSync(filename, "utf8"),
155 plugins: [],
156 options: {
157 dev: false,
158 hot: false,
159 platform: "ios",
160 projectRoot: mobileRoot,
161 type: "module",
162 enableBabelRCLookup: false,
163 experimentalImportSupport: false,
164 customTransformOptions: { reactCompiler, routerRoot: "app" },
165 },
166 });
167 return JSON.stringify(ast.program.body);
168 };
169 expect(transformed("true")).toContain("react/compiler-runtime");
170 expect(transformed("false")).not.toContain("react/compiler-runtime");
171 });
172
173 it.each(sourceFiles)("compiles %s", (file) => {
174 const bailouts = compilerBailouts(file);
175 if (file in KNOWN_BAILOUTS) {
176 expect(bailouts, `${file} compiles now; remove it from KNOWN_BAILOUTS`).not.toEqual([]);
177 } else {
178 expect(bailouts).toEqual([]);
179 }
180 });
181
182 // The compiler once silently dropped this cache, so every
183 // ThreadFeed render rebuilt the feed and handed LegendList a new data array.
184 it("caches the thread feed derivation", () => {
185 expect(
186 compilerCachedCalls("src/features/threads/ThreadFeed.tsx", "deriveThreadFeedPresentation"),
187 ).toEqual([true]);
188 });
189
190 it("lists only files that exist", () => {
191 expect(Object.keys(KNOWN_BAILOUTS).filter((file) => !sourceFiles.includes(file))).toEqual([]);
192 });
193});