Skip to content
Source
Sign inSign up
pingdotgg/t3code
Open History to see the last commit

react-effect-budget.ts

71 lines3.2 KB

1import { defineRule, type ESTree } from "@oxlint/plugins";
2import * as Option from "effect/Option";
3​
4import budget from "../../scripts/effect-budget.json" with { type: "json" };
5import { getPropertyName, unwrapExpression } from "../utils.ts";
6​
7const BUDGET_FILE = "scripts/effect-budget.json";
8const EFFECT_HOOKS = new Set(["useEffect", "useLayoutEffect", "useInsertionEffect"]);
9const EFFECT_HOOK_TEXT = /use(?:Layout|Insertion)?Effect/;
10const UNBUDGETED_FILE = /\.test\.[cm]?[jt]sx?$|[\\/](?:test|__tests__)[\\/]/;
11const budgets: Readonly<Record<string, number>> = budget;
12const JUSTIFIED = /oxlint-disable-next-line[^\n]*t3code\/react-effect-budget\s+--\s*\S/;
13​
14// An effect with a stated reason on the line above is a reviewed decision: it is not counted, and it
15// is always reported so that the suppression comment above it is used.
16const isJustified = (lines: ReadonlyArray<string>, line: number): boolean =>
17 JUSTIFIED.test(lines[line - 2] ?? "");
18​
19const isEffectHookCall = (node: ESTree.CallExpression): boolean => {
20 const callee = unwrapExpression(node.callee);
21 if (Option.isNone(callee)) return false;
22 const expression = callee.value;
23 if (expression.type === "Identifier") return EFFECT_HOOKS.has(expression.name);
24 if (expression.type === "MemberExpression" && !expression.computed) {
25 return Option.exists(getPropertyName(expression.property), (name) => EFFECT_HOOKS.has(name));
26 }
27 return false;
28};
29​
30// Budget keys are repo-relative; matching on the path's end also works for files linted elsewhere.
31const budgetFor = (filename: string): number => {
32 const normalized = filename.replaceAll("\\", "/");
33 const key = Object.keys(budgets).find((file) => normalized.endsWith(`/${file}`));
34 return key === undefined ? 0 : budgets[key]!;
35};
36​
37export default defineRule({
38 meta: {
39 type: "suggestion",
40 docs: {
41 description: `Hold each file to the React effect hooks it is allowed in ${BUDGET_FILE}; a missing entry allows none.`,
42 },
43 },
44 create(context) {
45 if (UNBUDGETED_FILE.test(context.filename) || !EFFECT_HOOK_TEXT.test(context.sourceCode.text)) {
46 return {};
47 }
48 const lines = context.sourceCode.text.split("\n");
49 const calls: Array<ESTree.CallExpression> = [];
50 const justified: Array<ESTree.CallExpression> = [];
51 return {
52 CallExpression(node) {
53 if (!isEffectHookCall(node)) return;
54 (isJustified(lines, node.loc.start.line) ? justified : calls).push(node);
55 },
56 "Program:exit"() {
57 for (const node of justified) {
58 context.report({ node, message: "A React effect with a stated reason." });
59 }
60 const allowed = budgetFor(context.filename);
61 if (calls.length <= allowed) return;
62 const message =
63 `This file has ${calls.length} React ${calls.length === 1 ? "effect" : "effects"} against a budget of ${allowed}. ` +
64 "First ask whether this is synchronization that belongs in render or in the handler that causes it. " +
65 "If an effect is the honest model, say why on the line above it: " +
66 "`// oxlint-disable-next-line t3code/react-effect-budget -- <why>`.";
67 for (const node of calls.slice(allowed)) context.report({ node, message });
68 },
69 };
70 },
71});