@autotelic/plumb 0.3.2 → 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.
- package/dist/index.js +2 -0
- package/dist/react/index.d.ts +3 -0
- package/dist/react/index.js +16 -0
- package/dist/react/rules/require-dot-notation-exports.d.ts +20 -0
- package/dist/react/rules/require-dot-notation-exports.js +134 -0
- package/dist/react/rules/require-guarded-context-hook.d.ts +19 -0
- package/dist/react/rules/require-guarded-context-hook.js +174 -0
- package/dist/react/rules/require-tripartite-context.d.ts +17 -0
- package/dist/react/rules/require-tripartite-context.js +158 -0
- package/dist/react/rules/use-encapsulation.d.ts +19 -0
- package/dist/react/rules/use-encapsulation.js +93 -0
- package/dist/rules/no-mutable-environment-capture.d.ts +7 -0
- package/dist/rules/no-mutable-environment-capture.js +134 -0
- package/dist/rules/no-single-use-private-functions.d.ts +14 -3
- package/dist/rules/no-single-use-private-functions.js +142 -18
- package/package.json +3 -2
package/dist/index.js
CHANGED
|
@@ -46,6 +46,7 @@ import { requireExhaustiveTagSwitchRule } from "./rules/require-exhaustive-tag-s
|
|
|
46
46
|
import { noMultipleFunctionParamsRule } from "./rules/no-multiple-function-params.js";
|
|
47
47
|
import { noOptionalFunctionParametersRule } from "./rules/no-optional-function-parameters.js";
|
|
48
48
|
import { noSingleUsePrivateFunctionsRule } from "./rules/no-single-use-private-functions.js";
|
|
49
|
+
import { noMutableEnvironmentCaptureRule } from "./rules/no-mutable-environment-capture.js";
|
|
49
50
|
/** Generic Oxlint rules that reject low-evidence and low-signal implementation patterns. */
|
|
50
51
|
const plumbPlugin = eslintCompatPlugin({
|
|
51
52
|
meta: { name: "plumb" },
|
|
@@ -97,6 +98,7 @@ const plumbPlugin = eslintCompatPlugin({
|
|
|
97
98
|
"no-multiple-function-params": noMultipleFunctionParamsRule,
|
|
98
99
|
"no-optional-function-parameters": noOptionalFunctionParametersRule,
|
|
99
100
|
"no-single-use-private-functions": noSingleUsePrivateFunctionsRule,
|
|
101
|
+
"no-mutable-environment-capture": noMutableEnvironmentCaptureRule,
|
|
100
102
|
},
|
|
101
103
|
});
|
|
102
104
|
export default plumbPlugin;
|
|
@@ -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
|
+
});
|
|
@@ -0,0 +1,7 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* A function that reads or writes module state instead of taking it as a
|
|
3
|
+
* parameter is dishonest: its result depends on outside context, so it is not
|
|
4
|
+
* locally testable. Inject the value at the call site (the document's seed-the
|
|
5
|
+
* PRNG-once, pass-it-in pattern) so the dependency is explicit in the signature.
|
|
6
|
+
*/
|
|
7
|
+
export declare const noMutableEnvironmentCaptureRule: import("@oxlint/plugins").Rule;
|
|
@@ -0,0 +1,134 @@
|
|
|
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 the identifier sits inside a type annotation rather than a value position.
|
|
6
|
+
*
|
|
7
|
+
* @param {SourceCode} sourceCode - The rule's source-code accessor.
|
|
8
|
+
* @param {ESTree.Node} identifier - The reference identifier to test.
|
|
9
|
+
* @returns {boolean} True when an ancestor is a TypeScript type node.
|
|
10
|
+
*/
|
|
11
|
+
function isTypePosition(sourceCode, identifier) {
|
|
12
|
+
for (const ancestor of ancestorsOf(sourceCode, identifier)) {
|
|
13
|
+
if (ancestor.type.startsWith("TS"))
|
|
14
|
+
return true;
|
|
15
|
+
}
|
|
16
|
+
return false;
|
|
17
|
+
}
|
|
18
|
+
/**
|
|
19
|
+
* The name a function is called by at its definition site.
|
|
20
|
+
*
|
|
21
|
+
* @param {ESTree.Node} node - The function-like node.
|
|
22
|
+
* @param {SourceCode} sourceCode - The rule's source-code accessor.
|
|
23
|
+
* @returns {string} The function's name, or "(anonymous)".
|
|
24
|
+
*/
|
|
25
|
+
function functionName(node, sourceCode) {
|
|
26
|
+
if (node.type === "FunctionDeclaration" && node.id !== null)
|
|
27
|
+
return node.id.name;
|
|
28
|
+
const parent = ancestorsOf(sourceCode, node)[0];
|
|
29
|
+
if (parent !== undefined) {
|
|
30
|
+
if (parent.type === "VariableDeclarator" && parent.id.type === "Identifier")
|
|
31
|
+
return parent.id.name;
|
|
32
|
+
if (parent.type === "AssignmentExpression" && parent.left.type === "Identifier")
|
|
33
|
+
return parent.left.name;
|
|
34
|
+
if (parent.type === "MethodDefinition" && parent.key.type === "Identifier")
|
|
35
|
+
return parent.key.name;
|
|
36
|
+
if (parent.type === "Property" && parent.key.type === "Identifier")
|
|
37
|
+
return parent.key.name;
|
|
38
|
+
if (parent.type === "ExportDefaultDeclaration")
|
|
39
|
+
return "default";
|
|
40
|
+
}
|
|
41
|
+
return "(anonymous)";
|
|
42
|
+
}
|
|
43
|
+
/**
|
|
44
|
+
* Collect module-scope let/var bindings, separating real state from
|
|
45
|
+
* function-valued helpers (which are legitimate module-private utilities).
|
|
46
|
+
*
|
|
47
|
+
* @param {ESTree.Program} program - The file's root node.
|
|
48
|
+
* @returns {ModuleState} Mutable state names and helper names.
|
|
49
|
+
*/
|
|
50
|
+
function collectModuleState(program) {
|
|
51
|
+
const state = new Set();
|
|
52
|
+
const helpers = new Set();
|
|
53
|
+
for (const statement of program.body) {
|
|
54
|
+
const declaration = statement.type === "ExportNamedDeclaration" ? statement.declaration : statement;
|
|
55
|
+
if (declaration === null || declaration === undefined)
|
|
56
|
+
continue;
|
|
57
|
+
if (declaration.type !== "VariableDeclaration")
|
|
58
|
+
continue;
|
|
59
|
+
if (declaration.kind !== "let" && declaration.kind !== "var")
|
|
60
|
+
continue;
|
|
61
|
+
for (const declarator of declaration.declarations) {
|
|
62
|
+
if (declarator.id.type !== "Identifier")
|
|
63
|
+
continue;
|
|
64
|
+
const init = declarator.init;
|
|
65
|
+
const isHelper = init !== null &&
|
|
66
|
+
init !== undefined &&
|
|
67
|
+
(init.type === "ArrowFunctionExpression" || init.type === "FunctionExpression");
|
|
68
|
+
(isHelper ? helpers : state).add(declarator.id.name);
|
|
69
|
+
}
|
|
70
|
+
}
|
|
71
|
+
return { state, helpers };
|
|
72
|
+
}
|
|
73
|
+
/**
|
|
74
|
+
* A function that reads or writes module state instead of taking it as a
|
|
75
|
+
* parameter is dishonest: its result depends on outside context, so it is not
|
|
76
|
+
* locally testable. Inject the value at the call site (the document's seed-the
|
|
77
|
+
* PRNG-once, pass-it-in pattern) so the dependency is explicit in the signature.
|
|
78
|
+
*/
|
|
79
|
+
export const noMutableEnvironmentCaptureRule = defineRule({
|
|
80
|
+
meta: {
|
|
81
|
+
type: "problem",
|
|
82
|
+
docs: {
|
|
83
|
+
description: "Disallow functions that read or write module-scope mutable state (let/var) instead of receiving it as a parameter; hidden module state makes a function dishonest and not locally testable.",
|
|
84
|
+
},
|
|
85
|
+
messages: {
|
|
86
|
+
mutableModuleState: "Function `{{name}}` {{kind}} module-scope mutable state `{{binding}}` rather than receiving it as a parameter. Hidden module state makes the function dishonest: its result depends on outside context, so it is not locally testable. Inject `{{binding}}` at the call site or thread it through the signature so the dependency is explicit.",
|
|
87
|
+
},
|
|
88
|
+
},
|
|
89
|
+
createOnce(context) {
|
|
90
|
+
let moduleState = { state: new Set(), helpers: new Set() };
|
|
91
|
+
const check = (node) => {
|
|
92
|
+
if (node.type !== "FunctionDeclaration" &&
|
|
93
|
+
node.type !== "FunctionExpression" &&
|
|
94
|
+
node.type !== "ArrowFunctionExpression") {
|
|
95
|
+
return;
|
|
96
|
+
}
|
|
97
|
+
const scope = context.sourceCode.getScope(node);
|
|
98
|
+
const { state, helpers } = moduleState;
|
|
99
|
+
for (const reference of scope.references) {
|
|
100
|
+
const resolved = reference.resolved;
|
|
101
|
+
if (resolved === null || resolved === undefined)
|
|
102
|
+
continue;
|
|
103
|
+
const name = resolved.name;
|
|
104
|
+
if (helpers.has(name))
|
|
105
|
+
continue;
|
|
106
|
+
if (!state.has(name))
|
|
107
|
+
continue;
|
|
108
|
+
if (isTypePosition(context.sourceCode, reference.identifier))
|
|
109
|
+
continue;
|
|
110
|
+
context.report({
|
|
111
|
+
node: reference.identifier,
|
|
112
|
+
messageId: "mutableModuleState",
|
|
113
|
+
data: {
|
|
114
|
+
name: functionName(node, context.sourceCode),
|
|
115
|
+
kind: reference.isWrite() ? "writes" : "reads",
|
|
116
|
+
binding: name,
|
|
117
|
+
},
|
|
118
|
+
});
|
|
119
|
+
}
|
|
120
|
+
};
|
|
121
|
+
return {
|
|
122
|
+
before() {
|
|
123
|
+
if (TEST_FILE.test(context.filename.replaceAll("\\", "/")))
|
|
124
|
+
return false;
|
|
125
|
+
},
|
|
126
|
+
Program(node) {
|
|
127
|
+
moduleState = collectModuleState(node);
|
|
128
|
+
},
|
|
129
|
+
FunctionDeclaration: check,
|
|
130
|
+
FunctionExpression: check,
|
|
131
|
+
ArrowFunctionExpression: check,
|
|
132
|
+
};
|
|
133
|
+
},
|
|
134
|
+
});
|
|
@@ -1,6 +1,17 @@
|
|
|
1
|
-
|
|
1
|
+
import type { ESTree } from "@oxlint/plugins";
|
|
2
|
+
/**
|
|
3
|
+
* Whether a function is a pure alias: it returns a single call that forwards
|
|
4
|
+
* each of its parameters verbatim (a generator may delegate-yield such a call).
|
|
5
|
+
* Anything else raises the level of abstraction and earns its name.
|
|
2
6
|
*
|
|
3
|
-
*
|
|
4
|
-
*
|
|
7
|
+
* @param {ESTree.Node} fn - The function-like node to inspect.
|
|
8
|
+
* @returns {boolean} True when the function is dead indirection.
|
|
9
|
+
*/
|
|
10
|
+
export declare function isTrivialForwarder(fn: ESTree.Node): boolean;
|
|
11
|
+
/**
|
|
12
|
+
* Top-level privates referenced exactly once are only worth inlining when they
|
|
13
|
+
* are pure aliases (they forward their inputs verbatim to another call). A
|
|
14
|
+
* single-use helper that earns its name by raising the level of abstraction is
|
|
15
|
+
* kept: the document argues for factoring proactively, even at n=1.
|
|
5
16
|
*/
|
|
6
17
|
export declare const noSingleUsePrivateFunctionsRule: import("@oxlint/plugins").Rule;
|
|
@@ -27,10 +27,10 @@ function memberName(member) {
|
|
|
27
27
|
}
|
|
28
28
|
return null;
|
|
29
29
|
}
|
|
30
|
-
/** Whether the call resolves to
|
|
30
|
+
/** Whether the call resolves to Effect.<method> (one invocation wrapper allowed for Effect.fn("N")(...)).
|
|
31
31
|
*
|
|
32
32
|
* @param {{ call: ESTree.Node; method: string }} payload - The candidate call and Effect method name.
|
|
33
|
-
* @returns {boolean} True when the call targets
|
|
33
|
+
* @returns {boolean} True when the call targets Effect.<method>.
|
|
34
34
|
*/
|
|
35
35
|
function isEffectMethodCall(payload) {
|
|
36
36
|
let callee = payload.call;
|
|
@@ -111,7 +111,7 @@ function exportedNames(program) {
|
|
|
111
111
|
}
|
|
112
112
|
return names;
|
|
113
113
|
}
|
|
114
|
-
/** Reads inside type positions (
|
|
114
|
+
/** Reads inside type positions (: T, as T, generics) are not runtime reads.
|
|
115
115
|
*
|
|
116
116
|
* @param {SourceCode} sourceCode - The rule's source-code accessor.
|
|
117
117
|
* @param {ESTree.Node} identifier - The identifier reference being counted.
|
|
@@ -188,26 +188,150 @@ function useCount(payload) {
|
|
|
188
188
|
*
|
|
189
189
|
* @param {{ sourceCode: SourceCode; node: ESTree.Node; name: string }} payload - Lookup inputs.
|
|
190
190
|
* @returns {DeclaredVariable | undefined} The matching record, if any.
|
|
191
|
+
* For a VariableDeclarator the binding lives on its parent VariableDeclaration, so the declarator is unwrapped first.
|
|
191
192
|
*/
|
|
192
193
|
function declaredVariablesOf(payload) {
|
|
193
|
-
|
|
194
|
+
const node = payload.node.type === "VariableDeclarator"
|
|
195
|
+
? (ancestorsOf(payload.sourceCode, payload.node).find((ancestor) => ancestor.type === "VariableDeclaration") ?? payload.node)
|
|
196
|
+
: payload.node;
|
|
197
|
+
return payload.sourceCode.getDeclaredVariables(node).find((variable) => variable.name === payload.name);
|
|
194
198
|
}
|
|
195
|
-
/**
|
|
199
|
+
/** Extract the handler function nested inside an Effect initializer (Effect.fn / Effect.gen).
|
|
196
200
|
*
|
|
197
|
-
*
|
|
198
|
-
*
|
|
201
|
+
* @param {ESTree.Node | null | undefined} init - The candidate's initializer expression.
|
|
202
|
+
* @returns {ESTree.Node | null} The handler function node, or null when absent.
|
|
203
|
+
*/
|
|
204
|
+
function effectHandler(init) {
|
|
205
|
+
if (init === null || init === undefined || init.type !== "CallExpression")
|
|
206
|
+
return null;
|
|
207
|
+
let handler = null;
|
|
208
|
+
for (const arg of init.arguments) {
|
|
209
|
+
if (arg.type === "FunctionExpression" ||
|
|
210
|
+
arg.type === "ArrowFunctionExpression" ||
|
|
211
|
+
arg.type === "FunctionDeclaration") {
|
|
212
|
+
handler = arg;
|
|
213
|
+
}
|
|
214
|
+
}
|
|
215
|
+
return handler;
|
|
216
|
+
}
|
|
217
|
+
/** Simple identifier parameter names, or null when any parameter is a pattern.
|
|
218
|
+
*
|
|
219
|
+
* @param {ESTree.Node} fn - The function-like node to inspect.
|
|
220
|
+
* @returns {Set<string> | null} The parameter names, or null for non-functions/patterns.
|
|
221
|
+
*/
|
|
222
|
+
function paramNames(fn) {
|
|
223
|
+
if (fn.type !== "FunctionDeclaration" &&
|
|
224
|
+
fn.type !== "FunctionExpression" &&
|
|
225
|
+
fn.type !== "ArrowFunctionExpression") {
|
|
226
|
+
return null;
|
|
227
|
+
}
|
|
228
|
+
const names = new Set();
|
|
229
|
+
for (const param of fn.params) {
|
|
230
|
+
if (param.type !== "Identifier")
|
|
231
|
+
return null;
|
|
232
|
+
names.add(param.name);
|
|
233
|
+
}
|
|
234
|
+
return names;
|
|
235
|
+
}
|
|
236
|
+
/**
|
|
237
|
+
* Whether a function is a pure alias: it returns a single call that forwards
|
|
238
|
+
* each of its parameters verbatim (a generator may delegate-yield such a call).
|
|
239
|
+
* Anything else raises the level of abstraction and earns its name.
|
|
240
|
+
*
|
|
241
|
+
* @param {ESTree.Node} fn - The function-like node to inspect.
|
|
242
|
+
* @returns {boolean} True when the function is dead indirection.
|
|
243
|
+
*/
|
|
244
|
+
export function isTrivialForwarder(fn) {
|
|
245
|
+
if (fn.type !== "FunctionDeclaration" &&
|
|
246
|
+
fn.type !== "FunctionExpression" &&
|
|
247
|
+
fn.type !== "ArrowFunctionExpression") {
|
|
248
|
+
return false;
|
|
249
|
+
}
|
|
250
|
+
const names = paramNames(fn);
|
|
251
|
+
if (names === null || names.size === 0)
|
|
252
|
+
return false;
|
|
253
|
+
let call = null;
|
|
254
|
+
if (fn.body !== null && fn.body.type === "BlockStatement") {
|
|
255
|
+
const statements = fn.body.body;
|
|
256
|
+
const statement = statements[0];
|
|
257
|
+
if (statement !== undefined && statement.type === "ReturnStatement") {
|
|
258
|
+
const argument = statement.argument;
|
|
259
|
+
if (argument !== null && argument !== undefined && argument.type === "CallExpression") {
|
|
260
|
+
call = argument;
|
|
261
|
+
}
|
|
262
|
+
else if (argument !== null &&
|
|
263
|
+
argument !== undefined &&
|
|
264
|
+
argument.type === "YieldExpression" &&
|
|
265
|
+
argument.delegate === true &&
|
|
266
|
+
argument.argument !== null &&
|
|
267
|
+
argument.argument !== undefined &&
|
|
268
|
+
argument.argument.type === "CallExpression") {
|
|
269
|
+
call = argument.argument;
|
|
270
|
+
}
|
|
271
|
+
}
|
|
272
|
+
}
|
|
273
|
+
else if (fn.type === "ArrowFunctionExpression" && fn.body !== null && fn.body.type === "CallExpression") {
|
|
274
|
+
call = fn.body;
|
|
275
|
+
}
|
|
276
|
+
if (call === null)
|
|
277
|
+
return false;
|
|
278
|
+
const seen = new Set();
|
|
279
|
+
for (const arg of call.arguments) {
|
|
280
|
+
if (arg.type !== "Identifier")
|
|
281
|
+
return false;
|
|
282
|
+
if (!names.has(arg.name) || seen.has(arg.name))
|
|
283
|
+
return false;
|
|
284
|
+
seen.add(arg.name);
|
|
285
|
+
}
|
|
286
|
+
return seen.size === names.size;
|
|
287
|
+
}
|
|
288
|
+
/**
|
|
289
|
+
* Whether a single-use candidate is dead indirection worth inlining: a pure
|
|
290
|
+
* alias that forwards its inputs verbatim. Substantial single-use helpers that
|
|
291
|
+
* raise the level of abstraction are kept (the document's "factor at n=1").
|
|
292
|
+
*
|
|
293
|
+
* @param {SourceCode} sourceCode - The rule's source-code accessor.
|
|
294
|
+
* @param {Candidate} candidate - The candidate to grade.
|
|
295
|
+
* @returns {boolean} True when the candidate is a pure alias.
|
|
296
|
+
*/
|
|
297
|
+
function isDeadIndirection(sourceCode, candidate) {
|
|
298
|
+
if (candidate.kind === "type")
|
|
299
|
+
return false;
|
|
300
|
+
let fn = null;
|
|
301
|
+
if (candidate.kind === "function") {
|
|
302
|
+
const node = candidate.node;
|
|
303
|
+
if (node.type === "FunctionDeclaration") {
|
|
304
|
+
fn = node;
|
|
305
|
+
}
|
|
306
|
+
else if (node.type === "VariableDeclarator") {
|
|
307
|
+
fn = node.init ?? null;
|
|
308
|
+
}
|
|
309
|
+
}
|
|
310
|
+
else {
|
|
311
|
+
const node = candidate.node;
|
|
312
|
+
fn = node.type === "VariableDeclarator" ? effectHandler(node.init) : null;
|
|
313
|
+
}
|
|
314
|
+
if (fn === null)
|
|
315
|
+
return false;
|
|
316
|
+
return isTrivialForwarder(fn);
|
|
317
|
+
}
|
|
318
|
+
/**
|
|
319
|
+
* Top-level privates referenced exactly once are only worth inlining when they
|
|
320
|
+
* are pure aliases (they forward their inputs verbatim to another call). A
|
|
321
|
+
* single-use helper that earns its name by raising the level of abstraction is
|
|
322
|
+
* kept: the document argues for factoring proactively, even at n=1.
|
|
199
323
|
*/
|
|
200
324
|
export const noSingleUsePrivateFunctionsRule = defineRule({
|
|
201
325
|
meta: {
|
|
202
326
|
type: "suggestion",
|
|
203
327
|
docs: {
|
|
204
|
-
description: "Inline private top-level functions
|
|
328
|
+
description: "Inline private top-level functions and Effect values that are referenced exactly once as a pure alias (they forward their inputs verbatim to another call); single-use indirection that adds no abstraction hides shape. Single-use helpers that raise the level of abstraction earn their name and are kept.",
|
|
205
329
|
},
|
|
206
330
|
messages: {
|
|
207
|
-
singleUseFunction: "Private function
|
|
208
|
-
singleUseEffectFunction: "Private Effect function
|
|
209
|
-
singleUseEffectProgram: "Private Effect program
|
|
210
|
-
singleUseType: "Private type
|
|
331
|
+
singleUseFunction: "Private function {{name}} is a single-use pure alias: it forwards its inputs verbatim to another call. Inline the forwarded call at its use site instead of naming zero-abstraction indirection.",
|
|
332
|
+
singleUseEffectFunction: "Private Effect function {{name}} is run exactly once as a pure alias. Inline the forwarded handler at its single use site instead of naming zero-abstraction indirection.",
|
|
333
|
+
singleUseEffectProgram: "Private Effect program {{name}} is composed into exactly one pipeline as a pure alias. Inline it there instead of naming zero-abstraction indirection.",
|
|
334
|
+
singleUseType: "Private type {{name}} is referenced exactly once. Inline the annotation at that use site instead of naming it.",
|
|
211
335
|
},
|
|
212
336
|
},
|
|
213
337
|
createOnce(context) {
|
|
@@ -264,12 +388,10 @@ export const noSingleUsePrivateFunctionsRule = defineRule({
|
|
|
264
388
|
if (candidateKind === null)
|
|
265
389
|
continue;
|
|
266
390
|
const chain = ancestorsOf(sourceCode, declarator);
|
|
267
|
-
const
|
|
268
|
-
const
|
|
269
|
-
|
|
270
|
-
|
|
271
|
-
parent.type !== "VariableDeclaration" ||
|
|
272
|
-
grandparent.type !== "Program") {
|
|
391
|
+
const parentIndex = chain.findIndex((ancestor) => ancestor.type === "VariableDeclaration");
|
|
392
|
+
const parent = parentIndex >= 0 ? chain[parentIndex] : undefined;
|
|
393
|
+
const grandparent = parentIndex > 0 ? chain[parentIndex - 1] : chain[parentIndex + 1];
|
|
394
|
+
if (parent === undefined || grandparent === undefined || grandparent.type !== "Program") {
|
|
273
395
|
continue;
|
|
274
396
|
}
|
|
275
397
|
if (exported.has(name) || isPascalCase(name))
|
|
@@ -283,6 +405,8 @@ export const noSingleUsePrivateFunctionsRule = defineRule({
|
|
|
283
405
|
for (const candidate of candidates) {
|
|
284
406
|
if (useCount({ sourceCode, candidate }) !== 1)
|
|
285
407
|
continue;
|
|
408
|
+
if (!isDeadIndirection(sourceCode, candidate))
|
|
409
|
+
continue;
|
|
286
410
|
context.report({
|
|
287
411
|
node: candidate.node,
|
|
288
412
|
messageId: MESSAGE_BY_KIND[candidate.kind],
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@autotelic/plumb",
|
|
3
|
-
"version": "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",
|