@autotelic/plumb 0.4.0 → 0.5.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,3 @@
1
+ /** Opt-in Oxlint rules for React composition (the "perfect component" contract). */
2
+ declare const plumbReactPlugin: import("@oxlint/plugins").Plugin;
3
+ export default plumbReactPlugin;
@@ -0,0 +1,16 @@
1
+ import { eslintCompatPlugin } from "@oxlint/plugins";
2
+ import { requireTripartiteContextRule } from "./rules/require-tripartite-context.js";
3
+ import { requireGuardedContextHookRule } from "./rules/require-guarded-context-hook.js";
4
+ import { requireDotNotationExportsRule } from "./rules/require-dot-notation-exports.js";
5
+ import { useEncapsulationRule } from "./rules/use-encapsulation.js";
6
+ /** Opt-in Oxlint rules for React composition (the "perfect component" contract). */
7
+ const plumbReactPlugin = eslintCompatPlugin({
8
+ meta: { name: "plumb-react" },
9
+ rules: {
10
+ "require-tripartite-context": requireTripartiteContextRule,
11
+ "require-guarded-context-hook": requireGuardedContextHookRule,
12
+ "require-dot-notation-exports": requireDotNotationExportsRule,
13
+ "use-encapsulation": useEncapsulationRule,
14
+ },
15
+ });
16
+ export default plumbReactPlugin;
@@ -0,0 +1,20 @@
1
+ /**
2
+ * Whether a component family (a Provider export plus a useXxx hook export)
3
+ * must carry a dot-notation aggregate export.
4
+ *
5
+ * @param {{ hasProvider: boolean; hasHook: boolean; aggregateOk: boolean }} input - The family's export facts.
6
+ * @returns {boolean} True when an aggregate is required but absent/incomplete.
7
+ */
8
+ export declare function familyRequiresAggregate(input: {
9
+ hasProvider: boolean;
10
+ hasHook: boolean;
11
+ aggregateOk: boolean;
12
+ }): boolean;
13
+ /**
14
+ * A component family (a Provider plus a `useXxx` consumer hook) must be exported
15
+ * through a single dot-notation aggregate (`export const Family = { Provider, ... }`)
16
+ * so consumers compose `Family.Provider` / `Family.Header` and the blocks are
17
+ * discoverable. Bare re-exports of `Provider`/`useXxx` without the aggregate
18
+ * hide the family boundary.
19
+ */
20
+ export declare const requireDotNotationExportsRule: import("@oxlint/plugins").Rule;
@@ -0,0 +1,134 @@
1
+ import { defineRule } from "@oxlint/plugins";
2
+ import { isString } from "../../shared/structural.js";
3
+ const TEST_FILE = /.(?:test|spec).[cm]?[jt]sx?$/u;
4
+ /**
5
+ * Whether a component family (a Provider export plus a useXxx hook export)
6
+ * must carry a dot-notation aggregate export.
7
+ *
8
+ * @param {{ hasProvider: boolean; hasHook: boolean; aggregateOk: boolean }} input - The family's export facts.
9
+ * @returns {boolean} True when an aggregate is required but absent/incomplete.
10
+ */
11
+ export function familyRequiresAggregate(input) {
12
+ return input.hasProvider && input.hasHook && !input.aggregateOk;
13
+ }
14
+ /**
15
+ * Property key names of an object literal.
16
+ *
17
+ * @param {ESTree.Node} node - The object expression node.
18
+ * @returns {Set<string>} The property key names.
19
+ */
20
+ function objectPropKeys(node) {
21
+ const keys = new Set();
22
+ if (node.type !== "ObjectExpression")
23
+ return keys;
24
+ for (const prop of node.properties) {
25
+ if (prop.type === "Property") {
26
+ const key = prop.key;
27
+ if (key.type === "Identifier")
28
+ keys.add(key.name);
29
+ else if (key.type === "Literal" && isString(key.value))
30
+ keys.add(key.value);
31
+ }
32
+ }
33
+ return keys;
34
+ }
35
+ /**
36
+ * Family name contributed by a useXxx export binding.
37
+ *
38
+ * @param {string} name - The exported binding name.
39
+ * @returns {string | null} The family name, or null when not a useXxx hook.
40
+ */
41
+ function hookFamily(name) {
42
+ const match = /^use([A-Z]\w*)$/u.exec(name);
43
+ return match === null ? null : (match[1] ?? null);
44
+ }
45
+ /**
46
+ * A component family (a Provider plus a `useXxx` consumer hook) must be exported
47
+ * through a single dot-notation aggregate (`export const Family = { Provider, ... }`)
48
+ * so consumers compose `Family.Provider` / `Family.Header` and the blocks are
49
+ * discoverable. Bare re-exports of `Provider`/`useXxx` without the aggregate
50
+ * hide the family boundary.
51
+ */
52
+ export const requireDotNotationExportsRule = defineRule({
53
+ meta: {
54
+ type: "problem",
55
+ docs: {
56
+ description: "Require a component family (Provider + useXxx hook) to be exported via a single dot-notation aggregate (export const Family = { Provider, ... }).",
57
+ },
58
+ messages: {
59
+ missingAggregate: "Component family `{{family}}` exports a Provider and a `use{{family}}` hook but no dot-notation aggregate `export const {{family}} = { Provider, ... }`. Export the family as one object so consumers compose `{{family}}.Provider` / `{{family}}.Header` and the blocks are discoverable.",
60
+ },
61
+ },
62
+ createOnce(context) {
63
+ const providerExports = new Set();
64
+ const hookFamilies = new Set();
65
+ const aggregates = new Map();
66
+ let reportNode = null;
67
+ const recordName = (entry) => {
68
+ if (reportNode === null)
69
+ reportNode = entry.node;
70
+ if (entry.name === "Provider" || entry.name.endsWith("Provider"))
71
+ providerExports.add(entry.name);
72
+ const hf = hookFamily(entry.name);
73
+ if (hf !== null)
74
+ hookFamilies.add(hf);
75
+ };
76
+ /**
77
+ * Whether an aggregate's keys include the Provider and the useXxx hook.
78
+ *
79
+ * @param {Set<string>} keys - The aggregate object's property keys.
80
+ * @returns {boolean} True when both the Provider and the hook are present.
81
+ */
82
+ function hasProviderKey(keys) {
83
+ for (const k of keys)
84
+ if (k === "Provider" || /Provider$/u.test(k))
85
+ return true;
86
+ return false;
87
+ }
88
+ return {
89
+ before() {
90
+ if (TEST_FILE.test(context.filename.replaceAll("\\", "/")))
91
+ return false;
92
+ },
93
+ ExportNamedDeclaration(node) {
94
+ const decl = node.declaration;
95
+ if (decl !== null && decl !== undefined) {
96
+ if (decl.type === "VariableDeclaration") {
97
+ for (const declarator of decl.declarations) {
98
+ if (declarator.id.type !== "Identifier")
99
+ continue;
100
+ recordName({ name: declarator.id.name, node });
101
+ if (declarator.init?.type === "ObjectExpression") {
102
+ aggregates.set(declarator.id.name, objectPropKeys(declarator.init));
103
+ }
104
+ }
105
+ }
106
+ else if (decl.type === "FunctionDeclaration" && decl.id !== null) {
107
+ recordName({ name: decl.id.name, node });
108
+ }
109
+ }
110
+ for (const specifier of node.specifiers) {
111
+ if (specifier.type !== "ExportSpecifier")
112
+ continue;
113
+ const exported = specifier.exported;
114
+ const name = exported.type === "Identifier" ? exported.name : (exported.value ?? "");
115
+ recordName({ name, node });
116
+ }
117
+ },
118
+ "Program:exit"() {
119
+ if (providerExports.size === 0 || hookFamilies.size === 0)
120
+ return;
121
+ const node = reportNode;
122
+ if (node === null)
123
+ return;
124
+ for (const family of hookFamilies) {
125
+ const agg = aggregates.get(family);
126
+ const ok = agg !== undefined && hasProviderKey(agg) && agg.has("use" + family);
127
+ if (ok)
128
+ continue;
129
+ context.report({ node, messageId: "missingAggregate", data: { family } });
130
+ }
131
+ },
132
+ };
133
+ },
134
+ });
@@ -0,0 +1,19 @@
1
+ /**
2
+ * Whether a custom context hook that reads context must be reported for
3
+ * lacking a guard against a missing Provider.
4
+ *
5
+ * @param {{ isHook: boolean; callsUseContext: boolean; guarded: boolean }} input - The hook's shape facts.
6
+ * @returns {boolean} True when the hook needs a guard but has none.
7
+ */
8
+ export declare function requiresContextGuard(input: {
9
+ isHook: boolean;
10
+ callsUseContext: boolean;
11
+ guarded: boolean;
12
+ }): boolean;
13
+ /**
14
+ * A custom hook that reads context with `useContext` must throw when the
15
+ * Provider is missing, rather than returning `undefined` and pushing a
16
+ * null-check onto every consumer. Returning a possibly-undefined context is the
17
+ * same hidden-nullable defect the rest of the library forbids.
18
+ */
19
+ export declare const requireGuardedContextHookRule: import("@oxlint/plugins").Rule;
@@ -0,0 +1,174 @@
1
+ import { defineRule } from "@oxlint/plugins";
2
+ import { ancestorsOf } from "../../shared/ancestors.js";
3
+ const TEST_FILE = /.(?:test|spec).[cm]?[jt]sx?$/u;
4
+ /**
5
+ * Whether a custom context hook that reads context must be reported for
6
+ * lacking a guard against a missing Provider.
7
+ *
8
+ * @param {{ isHook: boolean; callsUseContext: boolean; guarded: boolean }} input - The hook's shape facts.
9
+ * @returns {boolean} True when the hook needs a guard but has none.
10
+ */
11
+ export function requiresContextGuard(input) {
12
+ return input.isHook && input.callsUseContext && !input.guarded;
13
+ }
14
+ /**
15
+ * Whether a function name denotes a custom hook.
16
+ *
17
+ * @param {string | null} name - The function's name, if known.
18
+ * @returns {name is string} True when the name starts with "use" + a capital.
19
+ */
20
+ function isHookName(name) {
21
+ return name !== null && /^use[A-Z]/u.test(name);
22
+ }
23
+ /**
24
+ * The variable name an `if` test guards against a nullish value.
25
+ *
26
+ * @param {ESTree.Node} test - The if-statement test expression.
27
+ * @returns {string | null} The guarded variable name, or null when not a nullish guard.
28
+ */
29
+ function checkedVar(test) {
30
+ if (test.type === "UnaryExpression" && test.operator === "!" && test.argument.type === "Identifier") {
31
+ return test.argument.name;
32
+ }
33
+ if (test.type === "BinaryExpression") {
34
+ const nullish = (operand) => (operand.type === "Identifier" && (operand.name === "undefined" || operand.name === "null")) ||
35
+ (operand.type === "Literal" && (operand.value === null || operand.value === undefined));
36
+ if (test.operator === "===" || test.operator === "!==" || test.operator === "==" || test.operator === "!=") {
37
+ if (test.left.type === "Identifier" && nullish(test.right))
38
+ return test.left.name;
39
+ if (test.right.type === "Identifier" && nullish(test.left))
40
+ return test.right.name;
41
+ }
42
+ }
43
+ return null;
44
+ }
45
+ /**
46
+ * Whether a statement (or its block body) throws.
47
+ *
48
+ * @param {ESTree.Node} node - The statement node to inspect.
49
+ * @returns {boolean} True when the statement throws.
50
+ */
51
+ function containsThrow(node) {
52
+ if (node.type === "ThrowStatement")
53
+ return true;
54
+ if (node.type === "BlockStatement")
55
+ return node.body.some((s) => s.type === "ThrowStatement");
56
+ return false;
57
+ }
58
+ /**
59
+ * Whether the callee references `useContext`.
60
+ *
61
+ * @param {ESTree.Node} callee - The callee expression of a call.
62
+ * @returns {boolean} True when the callee is `useContext`.
63
+ */
64
+ function isUseContext(callee) {
65
+ if (callee.type === "Identifier")
66
+ return callee.name === "useContext";
67
+ if (callee.type === "MemberExpression" && !callee.computed && callee.property.type === "Identifier")
68
+ return callee.property.name === "useContext";
69
+ return false;
70
+ }
71
+ /**
72
+ * A custom hook that reads context with `useContext` must throw when the
73
+ * Provider is missing, rather than returning `undefined` and pushing a
74
+ * null-check onto every consumer. Returning a possibly-undefined context is the
75
+ * same hidden-nullable defect the rest of the library forbids.
76
+ */
77
+ export const requireGuardedContextHookRule = defineRule({
78
+ meta: {
79
+ type: "problem",
80
+ docs: {
81
+ description: "Require custom context hooks (useXxx calling useContext) to throw when the Provider is missing, instead of returning a possibly-undefined context.",
82
+ },
83
+ messages: {
84
+ unguardedContext: "`{{name}}` reads context with useContext but never guards against a missing Provider (no `if (!context) throw`). A context read outside the Provider returns undefined; throw when it is absent so consumers get a clear error instead of a nullable value.",
85
+ },
86
+ },
87
+ createOnce(context) {
88
+ const frames = [];
89
+ const push = (entry) => {
90
+ frames.push({ name: entry.name, node: entry.node, useContextVars: new Set(), guardedVars: new Set() });
91
+ };
92
+ const current = () => frames[frames.length - 1];
93
+ /**
94
+ * Nearest enclosing function name for a node (declaration or variable binding).
95
+ *
96
+ * @param {ESTree.Node} node - The reference node.
97
+ * @returns {string | null} The nearest function name, or null when anonymous.
98
+ */
99
+ function nearestFunctionName(node) {
100
+ const ancestors = ancestorsOf(context.sourceCode, node);
101
+ for (let i = ancestors.length - 1; i >= 0; i--) {
102
+ const a = ancestors[i];
103
+ if (a === undefined)
104
+ continue;
105
+ if (a.type === "FunctionDeclaration" && a.id !== null && a.id !== undefined)
106
+ return a.id.name;
107
+ if (a.type === "FunctionExpression" && a.id !== null && a.id !== undefined)
108
+ return a.id.name;
109
+ if (a.type === "VariableDeclarator" && a.id.type === "Identifier") {
110
+ const init = a.init;
111
+ if (init !== null &&
112
+ init !== undefined &&
113
+ (init.type === "ArrowFunctionExpression" || init.type === "FunctionExpression"))
114
+ return a.id.name;
115
+ }
116
+ }
117
+ return null;
118
+ }
119
+ return {
120
+ before() {
121
+ if (TEST_FILE.test(context.filename.replaceAll("\\", "/")))
122
+ return false;
123
+ },
124
+ FunctionDeclaration(node) {
125
+ push({ name: node.id?.name ?? null, node });
126
+ },
127
+ "FunctionDeclaration:exit"() {
128
+ const frame = frames.pop();
129
+ if (frame !== undefined)
130
+ report(frame);
131
+ },
132
+ FunctionExpression(node) {
133
+ push({ name: node.id?.name ?? null, node });
134
+ },
135
+ "FunctionExpression:exit"() {
136
+ const frame = frames.pop();
137
+ if (frame !== undefined)
138
+ report(frame);
139
+ },
140
+ ArrowFunctionExpression(node) {
141
+ push({ name: nearestFunctionName(node), node });
142
+ },
143
+ "ArrowFunctionExpression:exit"() {
144
+ const frame = frames.pop();
145
+ if (frame !== undefined)
146
+ report(frame);
147
+ },
148
+ CallExpression(node) {
149
+ if (!isUseContext(node.callee))
150
+ return;
151
+ const parent = ancestorsOf(context.sourceCode, node).at(-1);
152
+ if (parent?.type === "VariableDeclarator" && parent.id.type === "Identifier") {
153
+ current()?.useContextVars.add(parent.id.name);
154
+ }
155
+ },
156
+ IfStatement(node) {
157
+ const variable = checkedVar(node.test);
158
+ if (variable === null)
159
+ return;
160
+ if (containsThrow(node.consequent) || (node.alternate !== null && containsThrow(node.alternate))) {
161
+ current()?.guardedVars.add(variable);
162
+ }
163
+ },
164
+ };
165
+ function report(frame) {
166
+ if (!isHookName(frame.name))
167
+ return;
168
+ const unguarded = [...frame.useContextVars].filter((v) => !frame.guardedVars.has(v));
169
+ if (unguarded.length === 0)
170
+ return;
171
+ context.report({ node: frame.node, messageId: "unguardedContext", data: { name: frame.name } });
172
+ }
173
+ },
174
+ });
@@ -0,0 +1,17 @@
1
+ /**
2
+ * Whether a context value type's member keys form the tripartite
3
+ * state/actions/meta contract.
4
+ *
5
+ * @param {ReadonlyArray<string>} members - The declared member key names.
6
+ * @returns {boolean} True when `state`, `actions`, and `meta` are all present.
7
+ */
8
+ export declare function isTripartiteContextValue(members: ReadonlyArray<string>): boolean;
9
+ /**
10
+ * A React context's value must be shaped as `{ state, actions, meta }`: state is
11
+ * the data, actions are the functions that change it, and meta holds
12
+ * non-reactive configuration. This is the explicit I/O boundary of the
13
+ * component family - the same "perfect function" contract as the composition
14
+ * pattern. A context that omits one of the three leaks an implicit, unnamed
15
+ * channel that consumers cannot reason about.
16
+ */
17
+ export declare const requireTripartiteContextRule: import("@oxlint/plugins").Rule;
@@ -0,0 +1,158 @@
1
+ import { defineRule } from "@oxlint/plugins";
2
+ import { isString } from "../../shared/structural.js";
3
+ const TEST_FILE = /.(?:test|spec).[cm]?[jt]sx?$/u;
4
+ /** The three required keys of a context value type. */
5
+ const REQUIRED_KEYS = ["state", "actions", "meta"];
6
+ /**
7
+ * Whether a context value type's member keys form the tripartite
8
+ * state/actions/meta contract.
9
+ *
10
+ * @param {ReadonlyArray<string>} members - The declared member key names.
11
+ * @returns {boolean} True when `state`, `actions`, and `meta` are all present.
12
+ */
13
+ export function isTripartiteContextValue(members) {
14
+ const present = new Set(members);
15
+ return REQUIRED_KEYS.every((key) => present.has(key));
16
+ }
17
+ /**
18
+ * Member key names of a TS object type (interface body or inline literal).
19
+ *
20
+ * @param {ESTree.Node} node - The interface or type-literal node.
21
+ * @returns {ReadonlyArray<string>} The declared member key names.
22
+ */
23
+ function memberKeys(node) {
24
+ const keys = [];
25
+ const addKey = (key) => {
26
+ if (key.type === "Identifier")
27
+ keys.push(key.name);
28
+ else if (key.type === "Literal" && isString(key.value))
29
+ keys.push(key.value);
30
+ };
31
+ if (node.type === "TSInterfaceDeclaration") {
32
+ for (const member of node.body.body) {
33
+ if (member.type === "TSPropertySignature" || member.type === "TSMethodSignature")
34
+ addKey(member.key);
35
+ }
36
+ }
37
+ else if (node.type === "TSTypeLiteral") {
38
+ for (const member of node.members) {
39
+ if (member.type === "TSPropertySignature" || member.type === "TSMethodSignature")
40
+ addKey(member.key);
41
+ }
42
+ }
43
+ return keys;
44
+ }
45
+ /**
46
+ * Final segment of a type reference name.
47
+ *
48
+ * @param {ESTree.TSTypeReference} node - The type reference node.
49
+ * @returns {string | null} The unqualified type name, or null when unavailable.
50
+ */
51
+ function typeName(node) {
52
+ const tn = node.typeName;
53
+ if (tn.type === "Identifier")
54
+ return tn.name;
55
+ if (tn.type === "TSQualifiedName")
56
+ return tn.right.name;
57
+ return null;
58
+ }
59
+ /**
60
+ * Whether the callee references `createContext`.
61
+ *
62
+ * @param {ESTree.Node} callee - The callee expression of a call.
63
+ * @returns {boolean} True when the callee is `createContext`.
64
+ */
65
+ function isCreateContext(callee) {
66
+ if (callee.type === "Identifier")
67
+ return callee.name === "createContext";
68
+ if (callee.type === "MemberExpression" && !callee.computed && callee.property.type === "Identifier")
69
+ return callee.property.name === "createContext";
70
+ return false;
71
+ }
72
+ /**
73
+ * A React context's value must be shaped as `{ state, actions, meta }`: state is
74
+ * the data, actions are the functions that change it, and meta holds
75
+ * non-reactive configuration. This is the explicit I/O boundary of the
76
+ * component family - the same "perfect function" contract as the composition
77
+ * pattern. A context that omits one of the three leaks an implicit, unnamed
78
+ * channel that consumers cannot reason about.
79
+ */
80
+ export const requireTripartiteContextRule = defineRule({
81
+ meta: {
82
+ type: "problem",
83
+ docs: {
84
+ description: "Require React context value types to be the tripartite { state, actions, meta } shape; missing keys leak an implicit, unnamed I/O channel.",
85
+ },
86
+ messages: {
87
+ tripartiteContext: "Context value type is missing required key(s): {{missing}}. A context value must be { state, actions, meta } so its I/O boundary is explicit.",
88
+ },
89
+ },
90
+ createOnce(context) {
91
+ const localTypes = new Map();
92
+ const calls = [];
93
+ /**
94
+ * Resolve a context type argument to declared member keys, if local.
95
+ *
96
+ * @param {ESTree.Node} typeArg - The type argument node passed to createContext.
97
+ * @returns {ReadonlyArray<string> | null} The member keys, or null when unresolved.
98
+ */
99
+ function resolveKeys(typeArg) {
100
+ if (typeArg.type === "TSTypeLiteral")
101
+ return memberKeys(typeArg);
102
+ if (typeArg.type === "TSTypeReference") {
103
+ const name = typeName(typeArg);
104
+ return name === null ? null : localTypes.get(name) ?? null;
105
+ }
106
+ if (typeArg.type === "TSUnionType") {
107
+ for (const member of typeArg.types) {
108
+ if (member.type === "TSUndefinedKeyword" || member.type === "TSNullKeyword")
109
+ continue;
110
+ const resolved = resolveKeys(member);
111
+ if (resolved !== null)
112
+ return resolved;
113
+ }
114
+ }
115
+ return null;
116
+ }
117
+ return {
118
+ before() {
119
+ if (TEST_FILE.test(context.filename.replaceAll("\\", "/")))
120
+ return false;
121
+ },
122
+ TSInterfaceDeclaration(node) {
123
+ localTypes.set(node.id.name, memberKeys(node));
124
+ },
125
+ TSTypeAliasDeclaration(node) {
126
+ if (node.typeAnnotation.type === "TSTypeLiteral") {
127
+ localTypes.set(node.id.name, memberKeys(node.typeAnnotation));
128
+ }
129
+ },
130
+ CallExpression(node) {
131
+ if (isCreateContext(node.callee))
132
+ calls.push(node);
133
+ },
134
+ "Program:exit"() {
135
+ for (const call of calls) {
136
+ const params = call.typeArguments?.params;
137
+ if (params === undefined || params.length === 0)
138
+ continue;
139
+ const first = params[0];
140
+ if (first === undefined)
141
+ continue;
142
+ const keys = resolveKeys(first);
143
+ if (keys === null)
144
+ continue;
145
+ if (isTripartiteContextValue(keys))
146
+ continue;
147
+ const present = new Set(keys);
148
+ const missing = REQUIRED_KEYS.filter((key) => !present.has(key));
149
+ context.report({
150
+ node: call,
151
+ messageId: "tripartiteContext",
152
+ data: { missing: missing.join(", ") },
153
+ });
154
+ }
155
+ },
156
+ };
157
+ },
158
+ });
@@ -0,0 +1,19 @@
1
+ /**
2
+ * Whether a React hook used at `hookName` inside a function named `parentName`
3
+ * violates the encapsulation rule (hook used directly in a non-hook function).
4
+ *
5
+ * @param {{ hookName: string; parentName: string }} input - The usage facts.
6
+ * @returns {boolean} True when the usage should be reported.
7
+ */
8
+ export declare function isEncapsulationViolation(input: {
9
+ hookName: string;
10
+ parentName: string;
11
+ }): boolean;
12
+ /**
13
+ * Do not call React's hooks directly inside a component. Abstract the
14
+ * functionality into a custom hook (`useXxx`) and call that instead - the
15
+ * "useEncapsulation" pattern. A component that reaches for `useState`/`useEffect`
16
+ * inline hides its state and effects; a custom hook names them and can be tested
17
+ * and composed in isolation.
18
+ */
19
+ export declare const useEncapsulationRule: import("@oxlint/plugins").Rule;
@@ -0,0 +1,93 @@
1
+ import { defineRule } from "@oxlint/plugins";
2
+ import { ancestorsOf } from "../../shared/ancestors.js";
3
+ import { readField } from "../../shared/structural.js";
4
+ const TEST_FILE = /.(?:test|spec).[cm]?[jt]sx?$/u;
5
+ /** Pattern identifying custom hooks (names starting with `use`). */
6
+ const HOOK_PATTERN = /^use/u;
7
+ /** React's built-in hooks that must not be used directly inside components. */
8
+ const REACT_HOOKS = new Set([
9
+ "useCallback",
10
+ "useContext",
11
+ "useDebugValue",
12
+ "useDeferredValue",
13
+ "useEffect",
14
+ "useId",
15
+ "useImperativeHandle",
16
+ "useInsertionEffect",
17
+ "useLayoutEffect",
18
+ "useMemo",
19
+ "useReducer",
20
+ "useRef",
21
+ "useState",
22
+ "useSyncExternalStore",
23
+ "useTransition",
24
+ ]);
25
+ /**
26
+ * Whether a React hook used at `hookName` inside a function named `parentName`
27
+ * violates the encapsulation rule (hook used directly in a non-hook function).
28
+ *
29
+ * @param {{ hookName: string; parentName: string }} input - The usage facts.
30
+ * @returns {boolean} True when the usage should be reported.
31
+ */
32
+ export function isEncapsulationViolation(input) {
33
+ return REACT_HOOKS.has(input.hookName) && !HOOK_PATTERN.test(input.parentName);
34
+ }
35
+ /**
36
+ * Do not call React's hooks directly inside a component. Abstract the
37
+ * functionality into a custom hook (`useXxx`) and call that instead - the
38
+ * "useEncapsulation" pattern. A component that reaches for `useState`/`useEffect`
39
+ * inline hides its state and effects; a custom hook names them and can be tested
40
+ * and composed in isolation.
41
+ */
42
+ export const useEncapsulationRule = defineRule({
43
+ meta: {
44
+ type: "problem",
45
+ docs: {
46
+ description: "Disallow using React's hooks directly inside a component; abstract them into a custom hook (useXxx) and call that instead (useEncapsulation).",
47
+ },
48
+ messages: {
49
+ noDirectHooks: "Do not use React hook `{{hook}}` directly inside component `{{parent}}`. Abstract the functionality into a custom hook (useXxx) and call that instead.",
50
+ },
51
+ },
52
+ createOnce(context) {
53
+ const raw = readField(context, "options");
54
+ const options = raw?.[0] ?? {};
55
+ const allowed = new Set(options.allow ?? []);
56
+ const blocked = new Set(options.block ?? []);
57
+ const hooksToCheck = new Set([...REACT_HOOKS, ...blocked].filter((h) => !allowed.has(h)));
58
+ function nearestFunctionName(node) {
59
+ const ancestors = ancestorsOf(context.sourceCode, node);
60
+ for (let i = ancestors.length - 1; i >= 0; i--) {
61
+ const a = ancestors[i];
62
+ if (a === undefined)
63
+ continue;
64
+ if (a.type === "FunctionDeclaration" && a.id !== null && a.id !== undefined)
65
+ return a.id.name;
66
+ if (a.type === "FunctionExpression" && a.id !== null && a.id !== undefined)
67
+ return a.id.name;
68
+ if (a.type === "VariableDeclarator" && a.id.type === "Identifier") {
69
+ const init = a.init;
70
+ if (init !== null &&
71
+ init !== undefined &&
72
+ (init.type === "ArrowFunctionExpression" || init.type === "FunctionExpression"))
73
+ return a.id.name;
74
+ }
75
+ }
76
+ return null;
77
+ }
78
+ return {
79
+ before() {
80
+ if (TEST_FILE.test(context.filename.replaceAll("\\", "/")))
81
+ return false;
82
+ },
83
+ Identifier(node) {
84
+ if (!hooksToCheck.has(node.name))
85
+ return;
86
+ const parent = nearestFunctionName(node);
87
+ if (parent !== null && !HOOK_PATTERN.test(parent)) {
88
+ context.report({ node, messageId: "noDirectHooks", data: { hook: node.name, parent } });
89
+ }
90
+ },
91
+ };
92
+ },
93
+ });
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@autotelic/plumb",
3
- "version": "0.4.0",
3
+ "version": "0.5.0",
4
4
  "description": "Opinionated Oxlint rules that keep TypeScript true: generic and Effect-specific patterns, maintained as one source of truth for the autotelic repos.",
5
5
  "license": "MIT",
6
6
  "files": [
@@ -14,7 +14,8 @@
14
14
  ".": "./dist/index.js",
15
15
  "./effect": "./dist/effect/index.js",
16
16
  "./meta": "./dist/meta/index.js",
17
- "./testing": "./dist/testing/index.js"
17
+ "./testing": "./dist/testing/index.js",
18
+ "./react": "./dist/react/index.js"
18
19
  },
19
20
  "scripts": {
20
21
  "check": "pnpm lint && pnpm typecheck && pnpm test && pnpm check:rule-tests && pnpm check:config",