[babel] Add a sources option

This allows the plugin to be configured to run on an allowlist, rather
than compiling all files helping with an incremental rollout plan.

The sources option takes both an array of path strings or a function
to be flexible.

For now I've left this be optional but we can make it required.

ghstack-source-id: 282a33dc8d08d47f699894692e0fcc813dff5b77
Pull Request resolved: https://github.com/facebook/react-forget/pull/2855
This commit is contained in:
Sathya Gunsasekaran
2024-04-16 14:41:16 +01:00
parent 5bceb3cb3b
commit 6bf64df538
2 changed files with 40 additions and 0 deletions
@@ -108,6 +108,8 @@ export type PluginOptions = {
* Ignore 'use no forget' annotations. Helpful during testing but should not be used in production.
*/
ignoreUseNoForget: boolean;
sources?: Array<string> | ((filename: string) => boolean) | null;
};
const CompilationModeSchema = z.enum([
@@ -195,12 +195,50 @@ const DEFAULT_ESLINT_SUPPRESSIONS = [
"react-hooks/rules-of-hooks",
];
function isFilePartOfSources(
sources: Array<string> | ((filename: string) => boolean),
filename: string
): boolean {
if (typeof sources === "function") {
return sources(filename);
}
for (const prefix in sources) {
if (filename.indexOf(prefix) !== -1) {
return true;
}
}
return false;
}
export function compileProgram(
program: NodePath<t.Program>,
pass: CompilerPass
): void {
const options = parsePluginOptions(pass.opts);
if (options.sources) {
if (pass.filename === null) {
const error = new CompilerError();
error.pushErrorDetail(
new CompilerErrorDetail({
reason: `Expected a filename but found none.`,
description:
"When the 'sources' config options is specified, the React compiler will only compile files with a name",
severity: ErrorSeverity.InvalidConfig,
loc: null,
})
);
handleError(error, pass, null);
return;
}
if (!isFilePartOfSources(options.sources, pass.filename)) {
return;
}
}
// Top level "use no forget", skip this file entirely
if (
findDirectiveDisablingMemoization(program.node.directives, options) != null