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