eslint-plugin-functype 2.120.0 → 2.121.1
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/README.md +107 -19
- package/dist/configs/recommended.d.ts +8 -0
- package/dist/configs/recommended.js +1 -1
- package/dist/configs/recommended.js.map +1 -1
- package/dist/configs/strict.d.ts +2 -0
- package/dist/configs/strict.js +1 -1
- package/dist/configs/strict.js.map +1 -1
- package/dist/index.d.ts +2 -0
- package/dist/rules/index.d.ts +20 -16
- package/dist/rules/index.js +1 -1
- package/dist/rules/index.js.map +1 -1
- package/dist/rules/must-fold-on-component-return.d.ts +6 -0
- package/dist/rules/must-fold-on-component-return.js +2 -0
- package/dist/rules/must-fold-on-component-return.js.map +1 -0
- package/dist/rules/no-array-mutation.js +1 -1
- package/dist/rules/no-getOrThrow-in-render.d.ts +6 -0
- package/dist/rules/no-getOrThrow-in-render.js +2 -0
- package/dist/rules/no-getOrThrow-in-render.js.map +1 -0
- package/dist/rules/prefer-fold.js +1 -1
- package/dist/rules/prefer-fold.js.map +1 -1
- package/dist/rules/prefer-list.js +2 -2
- package/dist/utils/functype-predicates.d.ts +40 -0
- package/dist/utils/functype-predicates.js +2 -0
- package/dist/utils/functype-predicates.js.map +1 -0
- package/dist/utils/react-render.d.ts +15 -0
- package/dist/utils/react-render.js +2 -0
- package/dist/utils/react-render.js.map +1 -0
- package/package.json +2 -2
package/README.md
CHANGED
|
@@ -27,24 +27,26 @@ export default [functype.configs.strict]
|
|
|
27
27
|
|
|
28
28
|
## Rules
|
|
29
29
|
|
|
30
|
-
| Rule
|
|
31
|
-
|
|
|
32
|
-
| `functype/no-let`
|
|
33
|
-
| `functype/no-imperative-loops`
|
|
34
|
-
| `functype/prefer-functype-map`
|
|
35
|
-
| `functype/prefer-functype-set`
|
|
36
|
-
| `functype/collection-naming`
|
|
37
|
-
| `functype/prefer-map`
|
|
38
|
-
| `functype/prefer-fold`
|
|
39
|
-
| `functype/prefer-option`
|
|
40
|
-
| `functype/prefer-either`
|
|
41
|
-
| `functype/prefer-try`
|
|
42
|
-
| `functype/prefer-flatmap`
|
|
43
|
-
| `functype/prefer-do-notation`
|
|
44
|
-
| `functype/no-get-unsafe`
|
|
45
|
-
| `functype/prefer-list`
|
|
46
|
-
| `functype/no-array-mutation`
|
|
47
|
-
| `functype/no-floating-io`
|
|
30
|
+
| Rule | Recommended | Strict | Description |
|
|
31
|
+
| ---------------------------------------- | :---------: | :----: | -------------------------------------------------------------------------------------------- |
|
|
32
|
+
| `functype/no-let` | error | error | Use `const`; no reassignment |
|
|
33
|
+
| `functype/no-imperative-loops` | error | error | Use `List`/array methods, async traversal or `IO.forEach` instead of loops |
|
|
34
|
+
| `functype/prefer-functype-map` | error | error | Use functype `Map` instead of a native `Map` you only read |
|
|
35
|
+
| `functype/prefer-functype-set` | error | error | Use functype `Set` instead of a native `Set` you only read |
|
|
36
|
+
| `functype/collection-naming` | error | error | Import functype's `Map`/`Set` under their own names; spell the built-in `globalThis.Map` |
|
|
37
|
+
| `functype/prefer-map` | error | error | Use `map` instead of pushing inside `forEach` |
|
|
38
|
+
| `functype/prefer-fold` | error | error | Use `fold` instead of branching on `isSome()`/`isLeft()`/… |
|
|
39
|
+
| `functype/prefer-option` | warn | error | Use `Option` instead of `null`/`undefined` |
|
|
40
|
+
| `functype/prefer-either` | warn | error | Use `Either` for typed domain errors instead of `throw` |
|
|
41
|
+
| `functype/prefer-try` | warn | error | Use `Try` / `Try.fromPromise` instead of try/catch |
|
|
42
|
+
| `functype/prefer-flatmap` | warn | warn | Use `flatMap` instead of `map().flat()` |
|
|
43
|
+
| `functype/prefer-do-notation` | warn | warn | Use `Do` notation for chained operations |
|
|
44
|
+
| `functype/no-get-unsafe` | off | error | Disallow unsafe extraction (`.orThrow()`, `.expect()`) |
|
|
45
|
+
| `functype/prefer-list` | off | warn | Use `List` instead of native arrays |
|
|
46
|
+
| `functype/no-array-mutation` | off | error | Don't change an array in place (`push`, `sort`, `xs[i] = v`…); build a new one |
|
|
47
|
+
| `functype/no-floating-io` | off | warn | Don't build an `IO` and drop it, or `await` it unrun; run, return or `yield*` it |
|
|
48
|
+
| `functype/no-getOrThrow-in-render` | off | warn | React: no bare `.orThrow()` in a component or hook body; a throw in render unmounts the tree |
|
|
49
|
+
| `functype/must-fold-on-component-return` | off | warn | React: render an `Option`/`Either`/`Try` with `fold` or `<MatchOption>`, not a guard or `&&` |
|
|
48
50
|
|
|
49
51
|
### Severity policy
|
|
50
52
|
|
|
@@ -83,7 +85,7 @@ const value = either.orThrow((left) => new StepError(left.message))
|
|
|
83
85
|
|
|
84
86
|
`invariant()` covers one statement and narrows the condition for the code after it, so a function can mix bug checks with `Either`-returning failures. `@interop` rules:
|
|
85
87
|
|
|
86
|
-
- **Scope:** the tagged declaration and everything nested in it. That can be a function, `const`, method, class field, object property, type alias or interface. A sibling declaration is not covered. Honored by `prefer-either`, `prefer-option`, `prefer-fold` and `
|
|
88
|
+
- **Scope:** the tagged declaration and everything nested in it. That can be a function, `const`, method, class field, object property, type alias or interface. A sibling declaration is not covered. Honored by `prefer-either`, `prefer-option`, `prefer-fold`, `prefer-try`, `no-get-unsafe`, `no-getOrThrow-in-render` and `must-fold-on-component-return`.
|
|
87
89
|
- **The reason is required**, on the same line as the tag. A bare `@interop` exempts nothing.
|
|
88
90
|
- **Only JSDoc (`/** … */`) counts.** A `//` comment mentioning the tag does not.
|
|
89
91
|
- **Opt out** per rule with `allowInteropMarker: false`.
|
|
@@ -196,6 +198,92 @@ void save(user) // fine: a deliberate drop
|
|
|
196
198
|
|
|
197
199
|
Measured (2026-10-16) on functype's own source and tests, functype-log, functype-react, agent-todo's agent-gate-api and civala.ai's API: 0 false positives across about 1,340 IO-typed calls. The only hits were four deliberate drops in type-only tests. It's `off` in `recommended` and `warn` in `strict` while it is measured further.
|
|
198
200
|
|
|
201
|
+
### React rules
|
|
202
|
+
|
|
203
|
+
Two rules are for React code. They fire only inside a **component** (a function named in PascalCase whose body has JSX, including one wrapped in `memo` or `forwardRef`) or a **hook** (a function named `use` + a capital letter), so other code rarely trips them. The one exception is a non-React function whose name starts with `use` + a capital letter, which is read as a hook. Both are `off` in `recommended` and `warn` in `strict` while they're measured on real React code. To turn them on with `recommended`:
|
|
204
|
+
|
|
205
|
+
```js
|
|
206
|
+
import functype from "eslint-plugin-functype"
|
|
207
|
+
|
|
208
|
+
export default [
|
|
209
|
+
functype.configs.recommended,
|
|
210
|
+
{
|
|
211
|
+
files: ["**/*.tsx", "**/*.jsx"],
|
|
212
|
+
rules: {
|
|
213
|
+
"functype/no-getOrThrow-in-render": "error",
|
|
214
|
+
"functype/must-fold-on-component-return": "warn",
|
|
215
|
+
},
|
|
216
|
+
},
|
|
217
|
+
]
|
|
218
|
+
```
|
|
219
|
+
|
|
220
|
+
Both work without type information. With it (`parserOptions.projectService`), the receiver must also be a functype container, so an unrelated object that happens to have an `orThrow` or `isSome` method is not reported.
|
|
221
|
+
|
|
222
|
+
Only the component's or hook's own body counts as render. An event handler, an effect, or a callback passed to `.map` is a separate function, so a call there is not reported. That also means a call inside a callback that does run during render (`useMemo(() => …)`, `items.map((o) => o.orThrow())` in JSX) is missed: the rules prefer missing a case to reporting valid code.
|
|
223
|
+
|
|
224
|
+
### `functype/no-getOrThrow-in-render`
|
|
225
|
+
|
|
226
|
+
Reports a bare `.orThrow()` (or the older `.getOrThrow()`) in a component or hook body. When the value is missing it throws during render, and React unmounts the tree up to the nearest error boundary.
|
|
227
|
+
|
|
228
|
+
```tsx
|
|
229
|
+
function Profile({ user }: { user: Option<User> }) {
|
|
230
|
+
const u = user.orThrow() // reported → user.fold(() => <SignIn />, (u) => <Card user={u} />)
|
|
231
|
+
return <Card user={u} />
|
|
232
|
+
}
|
|
233
|
+
|
|
234
|
+
user.isSome() ? <Card user={user.orThrow()} /> : null // fine: guarded, it can't throw
|
|
235
|
+
if (user.isNone()) return null // …and every later user.orThrow() in this body is guarded too
|
|
236
|
+
const u = user.orThrow((e) => new NotFound(e)) // fine: a named error, sent to the error boundary on purpose
|
|
237
|
+
<button onClick={() => save(user.orThrow())} /> // fine: an event handler runs after render
|
|
238
|
+
```
|
|
239
|
+
|
|
240
|
+
A call is guarded when its test proves the value is there on the same receiver:
|
|
241
|
+
|
|
242
|
+
- it sits in the branch of an `if`, a ternary, an `&&` or an `||` that only runs once the value is there: `user.isSome() ? … : …`, `!user.isSome() ? null : …`, `busy && user.isSome() ? … : …`, `user.isNone() || …`;
|
|
243
|
+
- it comes after a statement that only lets control past once the value is there: an early `return` / `throw` on the missing case (`if (!user.isSome()) return null`, `if (busy || user.isNone()) return <Spinner />`, `if (user.isEmpty) return null`), an if / else-if chain whose branches all exit, or `invariant(user.isSome(), "…")`.
|
|
244
|
+
|
|
245
|
+
The test can be `isSome()` / `isRight()` / `isSuccess()`, their opposites, `isEmpty`, and `!`, `&&` and `||` over them. `.expect(handler)` is not reported, because its handler is the chosen throw. The rule is named after `getOrThrow`, the method's older name; functype's containers spell it `orThrow`.
|
|
246
|
+
|
|
247
|
+
| Option | Default | Description |
|
|
248
|
+
| -------------------- | :-----: | ----------------------------------------------------------- |
|
|
249
|
+
| `allowInteropMarker` | `true` | Skip calls inside a declaration tagged `@interop <reason>`. |
|
|
250
|
+
|
|
251
|
+
`no-get-unsafe` reports the same calls anywhere. This rule is narrower and more confident: it reports only where the throw lands in render.
|
|
252
|
+
|
|
253
|
+
### `functype/must-fold-on-component-return`
|
|
254
|
+
|
|
255
|
+
Reports a component that chooses what it renders by asking an `Option`, `Either` or `Try` which case it holds, in the two shapes `prefer-fold` doesn't report at its default options:
|
|
256
|
+
|
|
257
|
+
- an **early return**: `if (user.isNone()) return <SignIn />` (or `return null`, `if (!user.isSome())`, `if (busy || user.isNone())`), with the other case rendered below it;
|
|
258
|
+
- a **short-circuit**: `{user.isSome() && <Card />}`, which renders one case and silently drops the other.
|
|
259
|
+
|
|
260
|
+
```tsx
|
|
261
|
+
function Profile({ user }: { user: Option<User> }) {
|
|
262
|
+
if (user.isNone()) return <SignIn /> // reported
|
|
263
|
+
return <Card user={user.orThrow()} />
|
|
264
|
+
}
|
|
265
|
+
|
|
266
|
+
// → one expression for both cases:
|
|
267
|
+
return user.fold(
|
|
268
|
+
() => <SignIn />,
|
|
269
|
+
(u) => <Card user={u} />,
|
|
270
|
+
)
|
|
271
|
+
// → or, from functype-react:
|
|
272
|
+
return <MatchOption value={user} Some={(u) => <Card user={u} />} None={() => <SignIn />} />
|
|
273
|
+
|
|
274
|
+
const header = <h1>{user.isSome() && <Badge />}</h1> // reported → {user.fold(() => null, () => <Badge />)}
|
|
275
|
+
```
|
|
276
|
+
|
|
277
|
+
The message names the `Match` component that fits: `<MatchOption>` for `isSome`/`isNone`, `<MatchEither>` for `isLeft`/`isRight`, `<MatchTry>` for `isSuccess`/`isFailure`.
|
|
278
|
+
|
|
279
|
+
A ternary or an if/else on a predicate is `prefer-fold`'s, everywhere, so this rule leaves it alone rather than report it twice. If you turn on `prefer-fold`'s `checkGuards`, an early return followed by an unwrap is reported by both rules. Only a predicate _call_ counts: `state.isPending` on a `useIO` result and `items.isEmpty` are properties, and are never reported. A guard that does other work before it returns, or returns something other than JSX or `null`, is not reported either. The rule reports only; there are no suggestions, because the rewrite moves code between branches.
|
|
280
|
+
|
|
281
|
+
| Option | Default | Description |
|
|
282
|
+
| -------------------- | :-----: | ---------------------------------------------------------- |
|
|
283
|
+
| `allowInteropMarker` | `true` | Skip code inside a declaration tagged `@interop <reason>`. |
|
|
284
|
+
|
|
285
|
+
Measured (2026-10-25) with both rules on functype-react's source and tests (type-aware), and on agent-todo, mnemons and civala.ai (1,403 files, without type information): no reports. None of that code uses these shapes in a component, and `useIOValue`'s `exit.orThrow()` is guarded by `exit.isSuccess()`, so the measurement shows the false-positive rate, not the hit rate.
|
|
286
|
+
|
|
199
287
|
### `functype/no-get-unsafe`
|
|
200
288
|
|
|
201
289
|
| Option | Default | Description |
|
|
@@ -26,6 +26,12 @@
|
|
|
26
26
|
* no-floating-io (1.17) is off here and `warn` in strict while it is measured: 0 false positives across
|
|
27
27
|
* ~1,340 IO-typed calls in five codebases, but no real hits yet either. 2.0 decides `recommended` after
|
|
28
28
|
* measuring it against functype-os, whose async methods return IO there. Type-aware, like no-array-mutation.
|
|
29
|
+
*
|
|
30
|
+
* no-getOrThrow-in-render and must-fold-on-component-return are React rules: they fire only inside a
|
|
31
|
+
* component (a PascalCase function with JSX) or a hook (`use*`), so non-React code rarely trips them (a
|
|
32
|
+
* non-React function named `use*` is read as a hook). Both are new and unmeasured on real React code, so
|
|
33
|
+
* they start where no-floating-io did: off here, `warn` in strict. They work without type information and
|
|
34
|
+
* are more precise with it.
|
|
29
35
|
*/
|
|
30
36
|
declare const recommendedRules: {
|
|
31
37
|
"functype/no-let": string;
|
|
@@ -44,6 +50,8 @@ declare const recommendedRules: {
|
|
|
44
50
|
"functype/prefer-list": string;
|
|
45
51
|
"functype/no-array-mutation": string;
|
|
46
52
|
"functype/no-floating-io": string;
|
|
53
|
+
"functype/no-getOrThrow-in-render": string;
|
|
54
|
+
"functype/must-fold-on-component-return": string;
|
|
47
55
|
};
|
|
48
56
|
//#endregion
|
|
49
57
|
export { recommendedRules as default };
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
const e={"functype/no-let":`error`,"functype/no-imperative-loops":`error`,"functype/prefer-functype-map":`error`,"functype/prefer-functype-set":`error`,"functype/prefer-map":`error`,"functype/prefer-fold":`error`,"functype/collection-naming":`error`,"functype/prefer-option":`warn`,"functype/prefer-either":`warn`,"functype/prefer-try":`warn`,"functype/prefer-flatmap":`warn`,"functype/prefer-do-notation":`warn`,"functype/no-get-unsafe":`off`,"functype/prefer-list":`off`,"functype/no-array-mutation":`off`,"functype/no-floating-io":`off`};export{e as default};
|
|
1
|
+
const e={"functype/no-let":`error`,"functype/no-imperative-loops":`error`,"functype/prefer-functype-map":`error`,"functype/prefer-functype-set":`error`,"functype/prefer-map":`error`,"functype/prefer-fold":`error`,"functype/collection-naming":`error`,"functype/prefer-option":`warn`,"functype/prefer-either":`warn`,"functype/prefer-try":`warn`,"functype/prefer-flatmap":`warn`,"functype/prefer-do-notation":`warn`,"functype/no-get-unsafe":`off`,"functype/prefer-list":`off`,"functype/no-array-mutation":`off`,"functype/no-floating-io":`off`,"functype/no-getOrThrow-in-render":`off`,"functype/must-fold-on-component-return":`off`};export{e as default};
|
|
2
2
|
//# sourceMappingURL=recommended.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"recommended.js","names":["recommendedRules"],"sources":["../../src/configs/recommended.ts"],"sourcesContent":["/**\n * Severity policy (#325): a rule is `error` once it is right on ~95–99% of real code and its known\n * false-positive classes are closed; it stays `warn` only while those classes are still open. FP here\n * is governance — a rule that is reliably right should fail the build, not print advice nobody reads\n * (CivalaOS shipped 85 new violations under \"lint OK\" because every rule but `no-let` warned).\n *\n * Still `warn`, and why:\n * - prefer-option / prefer-either / prefer-try: fire on correct code at serialization boundaries\n * (JSON rows, DTOs) and on throws that are correct (bug checks, host contracts). Wire<T> (#325 B),\n * invariant() and @interop (#342) close those; graduating them is a measured decision.\n * - prefer-flatmap / prefer-do-notation: heuristics without type information; precision unmeasured.\n *\n * Graduated with a precision condition: prefer-fold checks functype predicate calls (`isSome()`,\n * `isLeft()`) only; its null-check heuristic is opt-in (`checkNullable`) because it fired on plain\n * nullables — 31 of 31 hits in CivalaOS. prefer-map leaves loops to no-imperative-loops (`checkForLoops`\n * off), so one loop is one error.\n *\n * collection-naming is a convention, not a heuristic — functype's Map/Set imported under their own names,\n * the built-in spelled globalThis.Map — so it has no false-positive class and starts at error.\n *\n * no-array-mutation is off here only because turning a new error on in a 1.x minor would fail consumers'\n * builds on upgrade (91 hits across five consumers, every one a real in-place mutation). It's `error` in\n * strict, and planned for `error` here in 2.0. It is type-aware: without type information it reports nothing.\n *\n * no-floating-io (1.17) is off here and `warn` in strict while it is measured: 0 false positives across\n * ~1,340 IO-typed calls in five codebases, but no real hits yet either. 2.0 decides `recommended` after\n * measuring it against functype-os, whose async methods return IO there. Type-aware, like no-array-mutation.\n */\nconst recommendedRules = {\n \"functype/no-let\": \"error\",\n \"functype/no-imperative-loops\": \"error\",\n \"functype/prefer-functype-map\": \"error\",\n \"functype/prefer-functype-set\": \"error\",\n \"functype/prefer-map\": \"error\",\n \"functype/prefer-fold\": \"error\",\n \"functype/collection-naming\": \"error\",\n \"functype/prefer-option\": \"warn\",\n \"functype/prefer-either\": \"warn\",\n \"functype/prefer-try\": \"warn\",\n \"functype/prefer-flatmap\": \"warn\",\n \"functype/prefer-do-notation\": \"warn\",\n \"functype/no-get-unsafe\": \"off\",\n \"functype/prefer-list\": \"off\",\n \"functype/no-array-mutation\": \"off\",\n \"functype/no-floating-io\": \"off\",\n}\n\nexport default recommendedRules\n"],"mappings":"
|
|
1
|
+
{"version":3,"file":"recommended.js","names":["recommendedRules"],"sources":["../../src/configs/recommended.ts"],"sourcesContent":["/**\n * Severity policy (#325): a rule is `error` once it is right on ~95–99% of real code and its known\n * false-positive classes are closed; it stays `warn` only while those classes are still open. FP here\n * is governance — a rule that is reliably right should fail the build, not print advice nobody reads\n * (CivalaOS shipped 85 new violations under \"lint OK\" because every rule but `no-let` warned).\n *\n * Still `warn`, and why:\n * - prefer-option / prefer-either / prefer-try: fire on correct code at serialization boundaries\n * (JSON rows, DTOs) and on throws that are correct (bug checks, host contracts). Wire<T> (#325 B),\n * invariant() and @interop (#342) close those; graduating them is a measured decision.\n * - prefer-flatmap / prefer-do-notation: heuristics without type information; precision unmeasured.\n *\n * Graduated with a precision condition: prefer-fold checks functype predicate calls (`isSome()`,\n * `isLeft()`) only; its null-check heuristic is opt-in (`checkNullable`) because it fired on plain\n * nullables — 31 of 31 hits in CivalaOS. prefer-map leaves loops to no-imperative-loops (`checkForLoops`\n * off), so one loop is one error.\n *\n * collection-naming is a convention, not a heuristic — functype's Map/Set imported under their own names,\n * the built-in spelled globalThis.Map — so it has no false-positive class and starts at error.\n *\n * no-array-mutation is off here only because turning a new error on in a 1.x minor would fail consumers'\n * builds on upgrade (91 hits across five consumers, every one a real in-place mutation). It's `error` in\n * strict, and planned for `error` here in 2.0. It is type-aware: without type information it reports nothing.\n *\n * no-floating-io (1.17) is off here and `warn` in strict while it is measured: 0 false positives across\n * ~1,340 IO-typed calls in five codebases, but no real hits yet either. 2.0 decides `recommended` after\n * measuring it against functype-os, whose async methods return IO there. Type-aware, like no-array-mutation.\n *\n * no-getOrThrow-in-render and must-fold-on-component-return are React rules: they fire only inside a\n * component (a PascalCase function with JSX) or a hook (`use*`), so non-React code rarely trips them (a\n * non-React function named `use*` is read as a hook). Both are new and unmeasured on real React code, so\n * they start where no-floating-io did: off here, `warn` in strict. They work without type information and\n * are more precise with it.\n */\nconst recommendedRules = {\n \"functype/no-let\": \"error\",\n \"functype/no-imperative-loops\": \"error\",\n \"functype/prefer-functype-map\": \"error\",\n \"functype/prefer-functype-set\": \"error\",\n \"functype/prefer-map\": \"error\",\n \"functype/prefer-fold\": \"error\",\n \"functype/collection-naming\": \"error\",\n \"functype/prefer-option\": \"warn\",\n \"functype/prefer-either\": \"warn\",\n \"functype/prefer-try\": \"warn\",\n \"functype/prefer-flatmap\": \"warn\",\n \"functype/prefer-do-notation\": \"warn\",\n \"functype/no-get-unsafe\": \"off\",\n \"functype/prefer-list\": \"off\",\n \"functype/no-array-mutation\": \"off\",\n \"functype/no-floating-io\": \"off\",\n \"functype/no-getOrThrow-in-render\": \"off\",\n \"functype/must-fold-on-component-return\": \"off\",\n}\n\nexport default recommendedRules\n"],"mappings":"AAkCA,MAAMA,EAAmB,CACvB,kBAAmB,QACnB,+BAAgC,QAChC,+BAAgC,QAChC,+BAAgC,QAChC,sBAAuB,QACvB,uBAAwB,QACxB,6BAA8B,QAC9B,yBAA0B,OAC1B,yBAA0B,OAC1B,sBAAuB,OACvB,0BAA2B,OAC3B,8BAA+B,OAC/B,yBAA0B,MAC1B,uBAAwB,MACxB,6BAA8B,MAC9B,0BAA2B,MAC3B,mCAAoC,MACpC,yCAA0C,KAC5C"}
|
package/dist/configs/strict.d.ts
CHANGED
|
@@ -7,6 +7,8 @@ declare const strictRules: {
|
|
|
7
7
|
"functype/prefer-list": string;
|
|
8
8
|
"functype/no-array-mutation": string;
|
|
9
9
|
"functype/no-floating-io": string;
|
|
10
|
+
"functype/no-getOrThrow-in-render": string;
|
|
11
|
+
"functype/must-fold-on-component-return": string;
|
|
10
12
|
"functype/prefer-functype-map": string;
|
|
11
13
|
"functype/prefer-functype-set": string;
|
|
12
14
|
"functype/no-imperative-loops": string;
|
package/dist/configs/strict.js
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import e from"./recommended.js";const t={...e,"functype/prefer-option":`error`,"functype/prefer-either":`error`,"functype/prefer-try":`error`,"functype/no-get-unsafe":`error`,"functype/prefer-list":`warn`,"functype/no-array-mutation":`error`,"functype/no-floating-io":`warn`,"functype/prefer-functype-map":`error`,"functype/prefer-functype-set":`error`,"functype/no-imperative-loops":`error`};export{t as default};
|
|
1
|
+
import e from"./recommended.js";const t={...e,"functype/prefer-option":`error`,"functype/prefer-either":`error`,"functype/prefer-try":`error`,"functype/no-get-unsafe":`error`,"functype/prefer-list":`warn`,"functype/no-array-mutation":`error`,"functype/no-floating-io":`warn`,"functype/no-getOrThrow-in-render":`warn`,"functype/must-fold-on-component-return":`warn`,"functype/prefer-functype-map":`error`,"functype/prefer-functype-set":`error`,"functype/no-imperative-loops":`error`};export{t as default};
|
|
2
2
|
//# sourceMappingURL=strict.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"strict.js","names":["recommendedRules","strictRules"],"sources":["../../src/configs/strict.ts"],"sourcesContent":["import recommendedRules from \"./recommended\"\n\nconst strictRules = {\n ...recommendedRules,\n \"functype/prefer-option\": \"error\",\n \"functype/prefer-either\": \"error\",\n \"functype/prefer-try\": \"error\",\n \"functype/no-get-unsafe\": \"error\",\n \"functype/prefer-list\": \"warn\",\n \"functype/no-array-mutation\": \"error\",\n \"functype/no-floating-io\": \"warn\",\n \"functype/prefer-functype-map\": \"error\",\n \"functype/prefer-functype-set\": \"error\",\n \"functype/no-imperative-loops\": \"error\",\n}\n\nexport default strictRules\n"],"mappings":"gCAEA,MAAMC,EAAc,CAClB,GAAGD,EACH,yBAA0B,QAC1B,yBAA0B,QAC1B,sBAAuB,QACvB,yBAA0B,QAC1B,uBAAwB,OACxB,6BAA8B,QAC9B,0BAA2B,OAC3B,+BAAgC,QAChC,+BAAgC,QAChC,+BAAgC,OAClC"}
|
|
1
|
+
{"version":3,"file":"strict.js","names":["recommendedRules","strictRules"],"sources":["../../src/configs/strict.ts"],"sourcesContent":["import recommendedRules from \"./recommended\"\n\nconst strictRules = {\n ...recommendedRules,\n \"functype/prefer-option\": \"error\",\n \"functype/prefer-either\": \"error\",\n \"functype/prefer-try\": \"error\",\n \"functype/no-get-unsafe\": \"error\",\n \"functype/prefer-list\": \"warn\",\n \"functype/no-array-mutation\": \"error\",\n \"functype/no-floating-io\": \"warn\",\n \"functype/no-getOrThrow-in-render\": \"warn\",\n \"functype/must-fold-on-component-return\": \"warn\",\n \"functype/prefer-functype-map\": \"error\",\n \"functype/prefer-functype-set\": \"error\",\n \"functype/no-imperative-loops\": \"error\",\n}\n\nexport default strictRules\n"],"mappings":"gCAEA,MAAMC,EAAc,CAClB,GAAGD,EACH,yBAA0B,QAC1B,yBAA0B,QAC1B,sBAAuB,QACvB,yBAA0B,QAC1B,uBAAwB,OACxB,6BAA8B,QAC9B,0BAA2B,OAC3B,mCAAoC,OACpC,yCAA0C,OAC1C,+BAAgC,QAChC,+BAAgC,QAChC,+BAAgC,OAClC"}
|
package/dist/index.d.ts
CHANGED
|
@@ -17,6 +17,8 @@ declare const plugin: {
|
|
|
17
17
|
"collection-naming": import("eslint").Rule.RuleModule;
|
|
18
18
|
"no-array-mutation": import("eslint").Rule.RuleModule;
|
|
19
19
|
"no-floating-io": import("eslint").Rule.RuleModule;
|
|
20
|
+
"no-getOrThrow-in-render": import("eslint").Rule.RuleModule;
|
|
21
|
+
"must-fold-on-component-return": import("eslint").Rule.RuleModule;
|
|
20
22
|
};
|
|
21
23
|
meta: {
|
|
22
24
|
name: string;
|
package/dist/rules/index.d.ts
CHANGED
|
@@ -1,19 +1,21 @@
|
|
|
1
1
|
import rule from "./collection-naming.js";
|
|
2
|
-
import rule$1 from "./
|
|
3
|
-
import rule$2 from "./no-
|
|
4
|
-
import rule$3 from "./no-
|
|
5
|
-
import rule$
|
|
6
|
-
import rule$
|
|
7
|
-
import rule$6 from "./
|
|
8
|
-
import rule$7 from "./
|
|
9
|
-
import rule$8 from "./prefer-
|
|
10
|
-
import rule$9 from "./prefer-
|
|
11
|
-
import rule$10 from "./prefer-
|
|
12
|
-
import rule$11 from "./prefer-
|
|
13
|
-
import rule$12 from "./prefer-
|
|
14
|
-
import rule$13 from "./prefer-
|
|
15
|
-
import rule$14 from "./prefer-
|
|
16
|
-
import rule$15 from "./prefer-
|
|
2
|
+
import rule$1 from "./must-fold-on-component-return.js";
|
|
3
|
+
import rule$2 from "./no-array-mutation.js";
|
|
4
|
+
import rule$3 from "./no-floating-io.js";
|
|
5
|
+
import rule$5 from "./no-get-unsafe.js";
|
|
6
|
+
import rule$4 from "./no-getOrThrow-in-render.js";
|
|
7
|
+
import rule$6 from "./no-imperative-loops.js";
|
|
8
|
+
import rule$7 from "./no-let.js";
|
|
9
|
+
import rule$8 from "./prefer-do-notation.js";
|
|
10
|
+
import rule$9 from "./prefer-either.js";
|
|
11
|
+
import rule$10 from "./prefer-flatmap.js";
|
|
12
|
+
import rule$11 from "./prefer-fold.js";
|
|
13
|
+
import rule$12 from "./prefer-functype-map.js";
|
|
14
|
+
import rule$13 from "./prefer-functype-set.js";
|
|
15
|
+
import rule$14 from "./prefer-list.js";
|
|
16
|
+
import rule$15 from "./prefer-map.js";
|
|
17
|
+
import rule$16 from "./prefer-option.js";
|
|
18
|
+
import rule$17 from "./prefer-try.js";
|
|
17
19
|
//#region src/rules/index.d.ts
|
|
18
20
|
declare const _default: {
|
|
19
21
|
"prefer-option": import("eslint").Rule.RuleModule;
|
|
@@ -32,7 +34,9 @@ declare const _default: {
|
|
|
32
34
|
"collection-naming": import("eslint").Rule.RuleModule;
|
|
33
35
|
"no-array-mutation": import("eslint").Rule.RuleModule;
|
|
34
36
|
"no-floating-io": import("eslint").Rule.RuleModule;
|
|
37
|
+
"no-getOrThrow-in-render": import("eslint").Rule.RuleModule;
|
|
38
|
+
"must-fold-on-component-return": import("eslint").Rule.RuleModule;
|
|
35
39
|
};
|
|
36
40
|
//#endregion
|
|
37
|
-
export { rule as collectionNaming, _default as default, rule$1 as
|
|
41
|
+
export { rule as collectionNaming, _default as default, rule$1 as mustFoldOnComponentReturn, rule$2 as noArrayMutation, rule$3 as noFloatingIo, rule$4 as noGetOrThrowInRender, rule$5 as noGetUnsafe, rule$6 as noImperativeLoops, rule$7 as noLet, rule$8 as preferDoNotation, rule$9 as preferEither, rule$10 as preferFlatmap, rule$11 as preferFold, rule$12 as preferFunctypeMap, rule$13 as preferFunctypeSet, rule$14 as preferList, rule$15 as preferMap, rule$16 as preferOption, rule$17 as preferTry };
|
|
38
42
|
//# sourceMappingURL=index.d.ts.map
|
package/dist/rules/index.js
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import e from"./collection-naming.js";import t from"./no-array-mutation.js";import
|
|
1
|
+
import e from"./collection-naming.js";import t from"./must-fold-on-component-return.js";import n from"./no-array-mutation.js";import r from"./no-floating-io.js";import i from"./no-get-unsafe.js";import a from"./no-getOrThrow-in-render.js";import o from"./no-imperative-loops.js";import s from"./no-let.js";import c from"./prefer-do-notation.js";import l from"./prefer-either.js";import u from"./prefer-flatmap.js";import d from"./prefer-fold.js";import f from"./prefer-functype-map.js";import p from"./prefer-functype-set.js";import m from"./prefer-list.js";import h from"./prefer-map.js";import g from"./prefer-option.js";import _ from"./prefer-try.js";var v={"prefer-option":g,"prefer-either":l,"prefer-try":_,"prefer-list":m,"no-get-unsafe":i,"no-let":s,"prefer-fold":d,"prefer-map":h,"prefer-flatmap":u,"prefer-functype-map":f,"prefer-functype-set":p,"no-imperative-loops":o,"prefer-do-notation":c,"collection-naming":e,"no-array-mutation":n,"no-floating-io":r,"no-getOrThrow-in-render":a,"must-fold-on-component-return":t};export{e as collectionNaming,v as default,t as mustFoldOnComponentReturn,n as noArrayMutation,r as noFloatingIo,a as noGetOrThrowInRender,i as noGetUnsafe,o as noImperativeLoops,s as noLet,c as preferDoNotation,l as preferEither,u as preferFlatmap,d as preferFold,f as preferFunctypeMap,p as preferFunctypeSet,m as preferList,h as preferMap,g as preferOption,_ as preferTry};
|
|
2
2
|
//# sourceMappingURL=index.js.map
|
package/dist/rules/index.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.js","names":["preferOption","preferEither","preferTry","preferList","noGetUnsafe","noLet","preferFold","preferMap","preferFlatmap","preferFunctypeMap","preferFunctypeSet","noImperativeLoops","preferDoNotation","collectionNaming","noArrayMutation","noFloatingIo","rule","rule$1","rule$2","rule$3","rule$
|
|
1
|
+
{"version":3,"file":"index.js","names":["preferOption","preferEither","preferTry","preferList","noGetUnsafe","noLet","preferFold","preferMap","preferFlatmap","preferFunctypeMap","preferFunctypeSet","noImperativeLoops","preferDoNotation","collectionNaming","noArrayMutation","noFloatingIo","noGetOrThrowInRender","mustFoldOnComponentReturn","rule","rule$1","rule$2","rule$3","rule$5","rule$4","rule$6","rule$7","rule$8","rule$9","rule$10","rule$11","rule$12","rule$13","rule$14","rule$15","rule$16","rule$17","rules_default"],"sources":["../../src/rules/index.ts"],"sourcesContent":["import collectionNaming from \"./collection-naming\"\nimport mustFoldOnComponentReturn from \"./must-fold-on-component-return\"\nimport noArrayMutation from \"./no-array-mutation\"\nimport noFloatingIo from \"./no-floating-io\"\nimport noGetUnsafe from \"./no-get-unsafe\"\nimport noGetOrThrowInRender from \"./no-getOrThrow-in-render\"\nimport noImperativeLoops from \"./no-imperative-loops\"\nimport noLet from \"./no-let\"\nimport preferDoNotation from \"./prefer-do-notation\"\nimport preferEither from \"./prefer-either\"\nimport preferFlatmap from \"./prefer-flatmap\"\nimport preferFold from \"./prefer-fold\"\nimport preferFunctypeMap from \"./prefer-functype-map\"\nimport preferFunctypeSet from \"./prefer-functype-set\"\nimport preferList from \"./prefer-list\"\nimport preferMap from \"./prefer-map\"\nimport preferOption from \"./prefer-option\"\nimport preferTry from \"./prefer-try\"\n\nexport {\n collectionNaming,\n mustFoldOnComponentReturn,\n noArrayMutation,\n noFloatingIo,\n noGetOrThrowInRender,\n noGetUnsafe,\n noImperativeLoops,\n noLet,\n preferDoNotation,\n preferEither,\n preferFlatmap,\n preferFold,\n preferFunctypeMap,\n preferFunctypeSet,\n preferList,\n preferMap,\n preferOption,\n preferTry,\n}\n\nexport default {\n \"prefer-option\": preferOption,\n \"prefer-either\": preferEither,\n \"prefer-try\": preferTry,\n \"prefer-list\": preferList,\n \"no-get-unsafe\": noGetUnsafe,\n \"no-let\": noLet,\n \"prefer-fold\": preferFold,\n \"prefer-map\": preferMap,\n \"prefer-flatmap\": preferFlatmap,\n \"prefer-functype-map\": preferFunctypeMap,\n \"prefer-functype-set\": preferFunctypeSet,\n \"no-imperative-loops\": noImperativeLoops,\n \"prefer-do-notation\": preferDoNotation,\n \"collection-naming\": collectionNaming,\n \"no-array-mutation\": noArrayMutation,\n \"no-floating-io\": noFloatingIo,\n \"no-getOrThrow-in-render\": noGetOrThrowInRender,\n \"must-fold-on-component-return\": mustFoldOnComponentReturn,\n}\n"],"mappings":"8oBAwCA,IAAAoC,EAAe,CACb,gBAAiBpC,EACjB,gBAAiBC,EACjB,aAAcC,EACd,cAAeC,EACf,gBAAiBC,EACjB,SAAUC,EACV,cAAeC,EACf,aAAcC,EACd,iBAAkBC,EAClB,sBAAuBC,EACvB,sBAAuBC,EACvB,sBAAuBC,EACvB,qBAAsBC,EACtB,oBAAqBC,EACrB,oBAAqBC,EACrB,iBAAkBC,EAClB,0BAA2BC,EAC3B,gCAAiCC,CACnC"}
|
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
import{isInsideTaggedDeclaration as e}from"../utils/boundary-tags.js";import{MATCH_COMPONENT as t,testedPredicate as n}from"../utils/functype-predicates.js";import{enclosingFunction as r,producesJSX as i,renderKind as a}from"../utils/react-render.js";import{isExtractableByType as o}from"../utils/type-aware.js";const s=e=>{let t=e.type===`BlockStatement`&&e.body.length===1?e.body[0]:e;return t?.type===`ReturnStatement`?t.argument??null:void 0},c=e=>e?.type===`Literal`&&e.value===null,l={meta:{type:`suggestion`,docs:{description:`Require a React component to render an Option, Either or Try with fold or a Match component, not an isSome()/isLeft() guard or &&`,recommended:!1},schema:[{type:`object`,properties:{allowInteropMarker:{type:`boolean`,default:!0}},additionalProperties:!1}],messages:{guardReturn:`This component picks what it renders with an early return on {{receiver}}.{{method}}(). Render both cases in one expression: {{receiver}}.fold(…) or <{{matcher}}>, so neither branch reads a value that isn't there.`,shortCircuit:`{{receiver}}.{{method}}() && … renders one case and drops the other. Use {{receiver}}.fold(…) with null for the case that renders nothing, or <{{matcher}}>.`}},create(l){let u=(l.options[0]||{}).allowInteropMarker!==!1,d=l.sourceCode,f=(t,i)=>{let s=n(i,d);if(!s)return null;let c=r(t);return!c||a(c)!==`component`||o(s.receiver,l)===!1||u&&e(t,`interop`,d)?null:s},p=(e,n,r)=>l.report({node:e,messageId:n,data:{receiver:d.getText(r.receiver),method:r.method,matcher:t[r.method]??`Match`}});return{IfStatement(e){if(e.alternate)return;let t=s(e.consequent);if(t===void 0||!(i(t)||c(t)))return;let n=f(e,e.test);n&&p(e,`guardReturn`,n)},LogicalExpression(e){if(e.operator!==`&&`||!i(e.right))return;let t=f(e,e.left);t&&p(e,`shortCircuit`,t)}}}};export{l as default};
|
|
2
|
+
//# sourceMappingURL=must-fold-on-component-return.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"must-fold-on-component-return.js","names":["returnedValue","statement","consequent","isNullLiteral","node","rule","allowInteropMarker","context","sourceCode","componentPredicate","predicate","testedPredicate","test","fn","enclosingFunction","renderKind","isExtractableByType","isInsideTaggedDeclaration","report","MATCH_COMPONENT","returned","producesJSX"],"sources":["../../src/rules/must-fold-on-component-return.ts"],"sourcesContent":["import type { Rule } from \"eslint\"\n\nimport type { ASTNode } from \"../types/ast\"\nimport { INTEROP_TAG, isInsideTaggedDeclaration } from \"../utils/boundary-tags\"\nimport { MATCH_COMPONENT, testedPredicate } from \"../utils/functype-predicates\"\nimport { enclosingFunction, producesJSX, renderKind } from \"../utils/react-render\"\nimport { isExtractableByType } from \"../utils/type-aware\"\n\n/**\n * Reports a component that chooses what it renders by asking an Option / Either / Try which case it\n * holds, in the two shapes `prefer-fold` leaves alone:\n *\n * - an early return: `if (user.isNone()) return <SignIn />`, then the other case below it;\n * - a short-circuit: `{user.isSome() && <Profile />}`, which renders one case and drops the other.\n *\n * A ternary or an if/else on `isSome()` / `isLeft()` / … is `prefer-fold`'s, everywhere, so this rule\n * doesn't report it a second time.\n *\n * The test may wrap the call: `if (!o.isSome()) return null`, `if (busy || o.isNone()) return <S />`.\n * Only a functype predicate *call* counts. `state.isPending` (a `useIO` result) and `items.isEmpty` are\n * properties, never calls, so they're not reported. With type information the receiver must also be a\n * functype container.\n */\n\n/** `return x` alone, or as the only statement of a block: what an early-return guard hands back. */\nconst returnedValue = (consequent: ASTNode): ASTNode | null | undefined => {\n const statement =\n consequent.type === \"BlockStatement\" && consequent.body.length === 1 ? consequent.body[0] : consequent\n return statement?.type === \"ReturnStatement\" ? (statement.argument ?? null) : undefined\n}\n\nconst isNullLiteral = (node: ASTNode): boolean => node?.type === \"Literal\" && node.value === null\n\nconst rule: Rule.RuleModule = {\n meta: {\n type: \"suggestion\",\n docs: {\n description:\n \"Require a React component to render an Option, Either or Try with fold or a Match component, not an isSome()/isLeft() guard or &&\",\n recommended: false,\n },\n schema: [\n {\n type: \"object\",\n properties: {\n allowInteropMarker: {\n type: \"boolean\",\n default: true,\n },\n },\n additionalProperties: false,\n },\n ],\n messages: {\n guardReturn:\n \"This component picks what it renders with an early return on {{receiver}}.{{method}}(). Render both cases in one expression: {{receiver}}.fold(…) or <{{matcher}}>, so neither branch reads a value that isn't there.\",\n shortCircuit:\n \"{{receiver}}.{{method}}() && … renders one case and drops the other. Use {{receiver}}.fold(…) with null for the case that renders nothing, or <{{matcher}}>.\",\n },\n },\n\n create(context) {\n const options = context.options[0] || {}\n const allowInteropMarker = options.allowInteropMarker !== false\n const sourceCode = context.sourceCode\n\n /** The predicate `test` calls, when `node` sits directly in a component's body (not a nested callback). */\n const componentPredicate = (node: ASTNode, test: ASTNode) => {\n const predicate = testedPredicate(test, sourceCode)\n if (!predicate) return null\n const fn = enclosingFunction(node)\n if (!fn || renderKind(fn) !== \"component\") return null\n if (isExtractableByType(predicate.receiver, context) === false) return null\n if (allowInteropMarker && isInsideTaggedDeclaration(node, INTEROP_TAG, sourceCode)) return null\n return predicate\n }\n\n const report = (node: ASTNode, messageId: string, predicate: NonNullable<ReturnType<typeof componentPredicate>>) =>\n context.report({\n node,\n messageId,\n data: {\n receiver: sourceCode.getText(predicate.receiver),\n method: predicate.method,\n matcher: MATCH_COMPONENT[predicate.method] ?? \"Match\",\n },\n })\n\n return {\n IfStatement(node: ASTNode) {\n // An if/else is prefer-fold's. A guard is an `if` with no `else` that returns JSX or `null`.\n if (node.alternate) return\n const returned = returnedValue(node.consequent)\n if (returned === undefined || !(producesJSX(returned) || isNullLiteral(returned))) return\n const predicate = componentPredicate(node, node.test)\n if (predicate) report(node, \"guardReturn\", predicate)\n },\n\n LogicalExpression(node: ASTNode) {\n if (node.operator !== \"&&\" || !producesJSX(node.right)) return\n const predicate = componentPredicate(node, node.left)\n if (predicate) report(node, \"shortCircuit\", predicate)\n },\n }\n },\n}\n\nexport default rule\n"],"mappings":"wTAyBA,MAAMA,EAAiB,GAAoD,CACzE,IAAMC,EACJC,EAAW,OAAS,kBAAoBA,EAAW,KAAK,SAAW,EAAIA,EAAW,KAAK,GAAKA,E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IN,EAAK,WAAa,MAAQ,CAACiB,EAAYjB,EAAK,KAAK,EAAG,OACxD,IAAMM,EAAYD,EAAmBL,EAAMA,EAAK,IAAI,EAChDM,GAAWQ,EAAOd,EAAM,eAAgBM,CAAS,CACvD,CACF,CACF,CACF"}
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import{
|
|
1
|
+
import{isInsideTaggedDeclaration as e}from"../utils/boundary-tags.js";import{isMutableArrayExpression as t}from"../utils/array-mutation.js";const n=/* @__PURE__ */ new Set([`push`,`pop`,`shift`,`unshift`,`splice`,`sort`,`reverse`,`fill`,`copyWithin`]),r=e=>e.type===`ArrayExpression`||e.type===`CallExpression`||e.type===`NewExpression`||e.type===`AwaitExpression`&&r(e.argument),i=(e,t)=>{let n=t.getText(e);return n.length>40?`${n.slice(0,37)}…`:n},a={meta:{type:`problem`,docs:{description:`Disallow changing an array in place — build a new one`,recommended:!0},schema:[{type:`object`,properties:{allowInTests:{type:`boolean`,default:!0},allowInteropMarker:{type:`boolean`,default:!0}},additionalProperties:!1}],messages:{mutatingMethod:`{{name}}.{{method}}() changes the array in place. Build a new one instead: [...{{name}}, x], map / filter / flatMap / toSorted, a List, or a fold`,elementAssignment:`Assigning to an element of {{name}} changes the array in place. Build a new one instead: {{name}}.with(i, v), map, a List, or a fold`,lengthAssignment:`Setting {{name}}.length changes the array in place. Build a new one instead: {{name}}.slice(0, n), or start from []`}},create(a){let o=a.options[0]||{},s=o.allowInTests!==!1,c=o.allowInteropMarker!==!1,l=a.sourceCode;if(s&&(()=>{let e=a.filename;return/\.(test|spec)\.(ts|js|tsx|jsx)$/.test(e)||e.includes(`__tests__`)||e.includes(`/test/`)||e.includes(`/tests/`)})())return{};let u=t=>c&&e(t,`interop`,l),d=e=>{if(e?.type!==`MemberExpression`)return null;let n=e.object;return r(n)?null:e.computed&&t(n,a)?n:null},f=e=>{if(e?.type!==`MemberExpression`||e.computed)return null;let n=e.object;return e.property?.type!==`Identifier`||e.property.name!==`length`||r(n)?null:t(n,a)?n:null},p=(e,t)=>{if(u(e))return;let n=d(t);if(n){a.report({node:e,messageId:`elementAssignment`,data:{name:i(n,l)}});return}let r=f(t);r&&a.report({node:e,messageId:`lengthAssignment`,data:{name:i(r,l)}})};return{CallExpression(e){let o=e.callee;if(o.type!==`MemberExpression`||o.computed)return;let s=o.property?.type===`Identifier`?o.property.name:null;if(s===null||!n.has(s))return;let c=o.object;r(c)||u(e)||t(c,a)&&a.report({node:e,messageId:`mutatingMethod`,data:{name:i(c,l),method:s}})},AssignmentExpression(e){p(e,e.left)},UpdateExpression(e){p(e,e.argument)},UnaryExpression(e){e.operator===`delete`&&p(e,e.argument)}}}};export{a as default};
|
|
2
2
|
//# sourceMappingURL=no-array-mutation.js.map
|
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
import{isInsideTaggedDeclaration as e}from"../utils/boundary-tags.js";import{compact as t,provesWhen as n}from"../utils/functype-predicates.js";import{enclosingFunction as r,renderKind as i}from"../utils/react-render.js";import{isExtractableByType as a}from"../utils/type-aware.js";const o=/* @__PURE__ */ new Set([`orThrow`,`getOrThrow`]),s=e=>e.type===`ReturnStatement`||e.type===`ThrowStatement`||e.type===`BlockStatement`&&e.body.length>0&&s(e.body.at(-1)),c=(e,t,r)=>{if(e.type===`IfStatement`)return s(e.consequent)?n(e.test,!1,t,r)===`present`?!0:e.alternate?c(e.alternate,t,r):!1:!1;let i=e.type===`ExpressionStatement`?e.expression:null;return i?.type===`CallExpression`&&i.callee.type===`Identifier`&&i.callee.name===`invariant`&&i.arguments.length>0&&n(i.arguments[0],!0,t,r)===`present`},l=(e,t,r,i)=>{let a=(e,t)=>n(e,t,r,i)===`present`,o=(e,n)=>{if(!n||n===t)return!1;let s=n.type===`IfStatement`||n.type===`ConditionalExpression`;return s&&n.consequent===e&&a(n.test,!0)||s&&n.alternate===e&&a(n.test,!1)||n.type===`LogicalExpression`&&n.right===e&&(n.operator===`&&`&&a(n.left,!0)||n.operator===`||`&&a(n.left,!1))||n.type===`BlockStatement`&&n.body.slice(0,n.body.indexOf(e)).some(e=>c(e,r,i))?!0:o(n,n.parent)};return o(e,e.parent)},u={meta:{type:`problem`,docs:{description:`Disallow a throwing extractor (.orThrow(), .getOrThrow()) in a React component or hook body`,recommended:!1},schema:[{type:`object`,properties:{allowInteropMarker:{type:`boolean`,default:!0}},additionalProperties:!1}],messages:{throwInRender:`{{receiver}}.{{method}}() throws during render when the value is missing, and a throw in render unmounts the tree up to the nearest error boundary. Render both cases with .fold(…) or <MatchOption> / <MatchEither> / <MatchTry>, or read a fallback with .orElse(…). To reach an error boundary on purpose, name the error: .orThrow((e) => new MyError(e))`}},create(n){let s=(n.options[0]||{}).allowInteropMarker!==!1,c=n.sourceCode;return{CallExpression(u){let d=u.callee;if(d.type!==`MemberExpression`||d.computed||d.property.type!==`Identifier`)return;let f=d.property.name;if(!o.has(f)||u.arguments.length>0)return;let p=r(u);if(!p||i(p)===null||a(d.object,n)===!1)return;let m=t(c.getText(d.object));l(u,p,m,c)||s&&e(u,`interop`,c)||n.report({node:u,messageId:`throwInRender`,data:{receiver:c.getText(d.object),method:f}})}}}};export{u as default};
|
|
2
|
+
//# sourceMappingURL=no-getOrThrow-in-render.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"no-getOrThrow-in-render.js","names":["THROWING_METHODS","exits","statement","continuesWithValue","provesWhen","receiverText","sourceCode","call","isGuarded","present","test","outcome","walk","node","stop","branch","child","rule","allowInteropMarker","context","callee","method","fn","enclosingFunction","renderKind","isExtractableByType","compact","isInsideTaggedDeclaration"],"sources":["../../src/rules/no-getOrThrow-in-render.ts"],"sourcesContent":["import type { Rule, SourceCode } from \"eslint\"\n\nimport type { ASTNode } from \"../types/ast\"\nimport { INTEROP_TAG, isInsideTaggedDeclaration } from \"../utils/boundary-tags\"\nimport { compact, provesWhen } from \"../utils/functype-predicates\"\nimport { enclosingFunction, renderKind } from \"../utils/react-render\"\nimport { isExtractableByType } from \"../utils/type-aware\"\n\n/**\n * The extractors that throw a generic error when the value is missing. `orThrow` is the one functype's\n * containers carry; `getOrThrow` is its older name, which the rule is named after. Each is reported only\n * bare: `orThrow(error)` names the error, the way to send a failure to an error boundary on purpose.\n * `expect(handler)` is never reported, because its handler is the chosen throw.\n */\nconst THROWING_METHODS: ReadonlySet<string> = new Set([\"orThrow\", \"getOrThrow\"])\n\n/** A statement that leaves the function: `return …`, `throw …`, or a block that ends in one. */\nconst exits = (statement: ASTNode): boolean =>\n statement.type === \"ReturnStatement\" ||\n statement.type === \"ThrowStatement\" ||\n (statement.type === \"BlockStatement\" && statement.body.length > 0 && exits(statement.body.at(-1)))\n\n/**\n * Does `statement` only let control continue past it once the value is known to be there?\n *\n * - an early exit on the missing case: `if (!o.isSome()) return null`, `if (busy || o.isNone()) return <S />`,\n * `if (o.isEmpty) throw …`;\n * - an if / else-if chain whose every branch exits, except the way out that proves it:\n * `if (x) return <B />; else if (o.isNone()) return null`;\n * - `invariant(o.isSome(), \"…\")` from functype, which narrows the code after it.\n */\nconst continuesWithValue = (statement: ASTNode, receiverText: string, sourceCode: SourceCode): boolean => {\n if (statement.type === \"IfStatement\") {\n if (!exits(statement.consequent)) return false\n if (provesWhen(statement.test, false, receiverText, sourceCode) === \"present\") return true\n return statement.alternate ? continuesWithValue(statement.alternate, receiverText, sourceCode) : false\n }\n const call = statement.type === \"ExpressionStatement\" ? statement.expression : null\n return (\n call?.type === \"CallExpression\" &&\n call.callee.type === \"Identifier\" &&\n call.callee.name === \"invariant\" &&\n call.arguments.length > 0 &&\n provesWhen(call.arguments[0], true, receiverText, sourceCode) === \"present\"\n )\n}\n\n/**\n * Is the call inside a branch that already proved the value is there? `o.isSome() ? o.orThrow() : …`,\n * `!o.isSome() ? null : o.orThrow()`, `if (e.isRight()) return e.orThrow()`, `t.isSuccess() && t.orThrow()`,\n * or after a statement in an enclosing block that only continues once it is (`continuesWithValue`). Then\n * the call cannot throw.\n */\nconst isGuarded = (call: ASTNode, stop: ASTNode, receiverText: string, sourceCode: SourceCode): boolean => {\n const present = (test: ASTNode, outcome: boolean): boolean =>\n provesWhen(test, outcome, receiverText, sourceCode) === \"present\"\n\n const walk = (child: ASTNode, node: ASTNode | undefined): boolean => {\n if (!node || node === stop) return false\n const branch = node.type === \"IfStatement\" || node.type === \"ConditionalExpression\"\n if (branch && node.consequent === child && present(node.test, true)) return true\n if (branch && node.alternate === child && present(node.test, false)) return true\n if (node.type === \"LogicalExpression\" && node.right === child) {\n if (node.operator === \"&&\" && present(node.left, true)) return true\n if (node.operator === \"||\" && present(node.left, false)) return true\n }\n if (node.type === \"BlockStatement\") {\n const before = (node.body as ReadonlyArray<ASTNode>).slice(0, node.body.indexOf(child))\n if (before.some((statement) => continuesWithValue(statement, receiverText, sourceCode))) return true\n }\n return walk(node, node.parent)\n }\n return walk(call, call.parent)\n}\n\nconst rule: Rule.RuleModule = {\n meta: {\n type: \"problem\",\n docs: {\n description: \"Disallow a throwing extractor (.orThrow(), .getOrThrow()) in a React component or hook body\",\n recommended: false,\n },\n schema: [\n {\n type: \"object\",\n properties: {\n allowInteropMarker: {\n type: \"boolean\",\n default: true,\n },\n },\n additionalProperties: false,\n },\n ],\n messages: {\n throwInRender:\n \"{{receiver}}.{{method}}() throws during render when the value is missing, and a throw in render unmounts the tree up to the nearest error boundary. Render both cases with .fold(…) or <MatchOption> / <MatchEither> / <MatchTry>, or read a fallback with .orElse(…). To reach an error boundary on purpose, name the error: .orThrow((e) => new MyError(e))\",\n },\n },\n\n create(context) {\n const options = context.options[0] || {}\n // `@interop <reason>` on an enclosing declaration marks a host contract, such as React's `use()`.\n const allowInteropMarker = options.allowInteropMarker !== false\n const sourceCode = context.sourceCode\n\n return {\n CallExpression(node: ASTNode) {\n const callee = node.callee as ASTNode\n if (callee.type !== \"MemberExpression\" || callee.computed || callee.property.type !== \"Identifier\") return\n const method = callee.property.name as string\n if (!THROWING_METHODS.has(method) || node.arguments.length > 0) return\n\n // Only the component's or hook's own body runs during render. An event handler, an effect or a\n // `.map` callback is a separate function, so a call there is not attributed to the render.\n const fn = enclosingFunction(node)\n if (!fn || renderKind(fn) === null) return\n\n // With type information the receiver must be a functype container (it has `orThrow` and `fold`);\n // without it, the method name decides — `orThrow()` is functype's own spelling.\n if (isExtractableByType(callee.object, context) === false) return\n const receiverText = compact(sourceCode.getText(callee.object))\n if (isGuarded(node, fn, receiverText, sourceCode)) return\n if (allowInteropMarker && isInsideTaggedDeclaration(node, INTEROP_TAG, sourceCode)) return\n\n context.report({\n node,\n messageId: \"throwInRender\",\n data: { receiver: sourceCode.getText(callee.object), method },\n })\n },\n }\n },\n}\n\nexport default rule\n"],"mappings":"0RAcA,MAAMA,kBAAwC,IAAI,IAAI,CAAC,UAAW,YAAY,CAAC,EAGzEC,EAAS,GACbC,EAAU,OAAS,mBACnBA,EAAU,OAAS,kBAClBA,EAAU,OAAS,kBAAoBA,EAAU,KAAK,OAAS,GAAKD,EAAMC,EAAU,KAAK,GAAG,EAAE,CAAC,EAW5FC,GAAsB,EAAoB,EAAsB,IAAoC,CACxG,GAAID,EAAU,OAAS,cAGrB,OAFKD,EAAMC,EAAU,UAAU,EAC3BE,EAAWF,EAAU,KAAM,GAAOG,EAAcC,CAAU,IAAM,UAAkB,GAC/EJ,EAAU,UAAYC,EAAmBD,EAAU,UAAWG,EAAcC,CAAU,EAAI,GAFxD,GAI3C,IAAMC,EAAOL,EAAU,OAAS,sBAAwBA,EAAU,WAAa,KAC/E,OACEK,GAAM,OAAS,kBACfA,EAAK,OAAO,OAAS,cACrBA,EAAK,OAAO,OAAS,aACrBA,EAAK,UAAU,OAAS,GACxBH,EAAWG,EAAK,UAAU,GAAI,GAAMF,EAAcC,CAAU,IAAM,SAEtE,EAQME,GAAa,EAAe,EAAe,EAAsB,IAAoC,CACzG,IAAMC,GAAW,EAAe,IAC9BL,EAAWM,EAAMC,EAASN,EAAcC,CAAU,IAAM,UAEpDM,GAAQ,EAAgB,IAAuC,CACnE,GAAI,CAACC,GAAQA,IAASC,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EAAoBL,EAAO,OAAQD,CAAO,IAAM,GAAO,OAC3D,IAAMd,EAAeqB,EAAQpB,EAAW,QAAQc,EAAO,MAAM,CAAC,EAC1DZ,EAAUK,EAAMS,EAAIjB,EAAcC,CAAU,GAC5CY,GAAsBS,EAA0Bd,EAAA,UAAmBP,CAAU,GAEjFa,EAAQ,OAAO,CACb,OACA,UAAW,gBACX,KAAM,CAAE,SAAUb,EAAW,QAAQc,EAAO,MAAM,EAAG,QAAO,CAC9D,CAAC,CACH,CACF,CACF,CACF"}
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import{isInsideTaggedDeclaration as e}from"../utils/boundary-tags.js";import{
|
|
1
|
+
import{isInsideTaggedDeclaration as e}from"../utils/boundary-tags.js";import{NEGATIVE_PREDICATES as t,POSITIVE_PREDICATES as n,compact as r}from"../utils/functype-predicates.js";import{childNodes as i,descendants as a}from"../utils/ast-walk.js";import{containsAwait as o}from"../utils/async-detection.js";const s={isSome:null,isNone:null,isRight:{param:`left`,member:`value`},isLeft:{param:`left`,member:`value`},isSuccess:{param:`error`,member:`error`},isFailure:{param:`error`,member:`error`}},c=[`get`,`orThrow`],l=`value`;function u(e){return e.type===`Literal`&&e.value===null||e.type===`Identifier`&&e.name===`undefined`}function d(e,r){if(e.type!==`CallExpression`||e.callee.type!==`MemberExpression`)return null;let i=e.callee.property.name,a=r.getText(e.callee.object),o=s[i]??null;return n.has(i)?{obj:a,isNegated:!1,failure:o}:t.has(i)?{obj:a,isNegated:!0,failure:o}:null}const f={members:[l],methods:c};function p(e,t,n,a){let o=e=>{let n=e.type===`TSNonNullExpression`?e.expression:e;return r(a.getText(n))===r(t)},s=(e,t)=>e.type===`MemberExpression`&&!e.computed&&e.property.type===`Identifier`&&t.includes(e.property.name)&&o(e.object),c=e=>{let t=e.parent,r=t?.type===`CallExpression`&&t.callee===e,a=t?.type===`AssignmentExpression`&&t.left===e||t?.type===`UpdateExpression`;return s(e,n.members)&&!r&&!a||e.type===`CallExpression`&&e.arguments.length===0&&s(e.callee,n.methods)?[e.range]:i(e).flatMap(c)};return c(e)}const m=(e,t)=>{let n=e=>t.some(t=>RegExp(`(?<![\\w$.])${e}(?![\\w$])`).test(t));return[e,...Array.from({length:20},(t,n)=>`${e}${n+1}`)].find(e=>!n(e))??`${e}_`},h=(e,t)=>e.type===`ObjectExpression`||e.type===`SequenceExpression`?`(${t})`:t;function g(e,t,n,r,i){let a=i.getText(e),o=n===null?[]:p(e,t,n,i);if(o.length===0)return`() => ${h(e,a)}`;let s=e.range[0],c=[...o].sort((e,t)=>t[0]-e[0]).reduce((e,[t,n])=>e.slice(0,t-s)+r+e.slice(n-s),a);return`(${r}) => ${h(e,c)}`}function _(e,t,n,r,i){let a=[i.getText(n),i.getText(r)],o=g(r,e,f,m(`value`,a),i);return`${e}.fold(${t===null?g(n,e,null,``,i):g(n,e,{members:[t.member],methods:[]},m(t.param,a),i)}, ${o})`}function v(e){let t=e.type===`BlockStatement`&&e.body.length===1?e.body[0]:e;return t.type===`ReturnStatement`&&t.argument?t.argument:null}function y(e){return e.alternate?e.alternate.type===`IfStatement`?1+y(e.alternate):2:1}const b=/* @__PURE__ */ new Set([`Left`,`None`,`Failure`,`left`,`none`,`failure`]);function x(e,t,n,i){return a(e).some(e=>e.type===`MemberExpression`&&!e.computed&&e.property.type===`Identifier`&&e.property.name===n&&r(i.getText(e.object))===t)}function S(e){if(e.type===`ReturnStatement`||e.type===`ThrowStatement`)return{exit:e,extraWork:!1};if(e.type!==`BlockStatement`||e.body.length===0)return null;let t=e.body[e.body.length-1];return t.type!==`ReturnStatement`&&t.type!==`ThrowStatement`?null:{exit:t,extraWork:e.body.length>1}}function C(e,t,n,i){let a=S(e);if(!a)return null;if(a.exit.type===`ThrowStatement`)return`throw`;if(a.extraWork)return`effect`;let o=a.exit.argument;if(!o)return`effect`;if(r(i.getText(o))===t)return`passthrough`;let s=o.type===`CallExpression`?o.callee:null,c=s?.type===`Identifier`?s.name:s?.type===`MemberExpression`&&s.property.type===`Identifier`?s.property.name:null;if(c&&b.has(c)){let e=o.arguments??[];return e.length===0||e.length===1&&n!==null&&r(i.getText(e[0]))===`${t}.${n}`?`passthrough`:`mappedFailure`}return n!==null&&x(o,t,n,i)?`effect`:`default`}function w(e,t,n){let i=e.flatMap(e=>a(e));return!i.some(e=>e.type===`AssignmentExpression`&&r(n.getText(e.left))===t)&&i.some(e=>{if(e.type!==`MemberExpression`||r(n.getText(e.object))!==t)return!1;let i=e.property.type===`Identifier`?e.property.name:null;if(i===l)return!0;let a=e.parent;return i===null||!c.includes(i)||a?.type!==`CallExpression`||a.callee!==e?!1:!(i===`orThrow`&&a.arguments.length>0)})}function T(e,t){if(e.type!==`IfStatement`||e.alternate)return null;let n=d(e.test,t);return!n?.isNegated||!S(e.consequent)?null:n}const E={meta:{type:`suggestion`,docs:{description:`Prefer .fold() over if/else chains when working with monadic types`,recommended:!0},hasSuggestions:!0,schema:[{type:`object`,properties:{allowInteropMarker:{type:`boolean`,default:!0},minComplexity:{type:`integer`,minimum:1,default:2},checkNullable:{type:`boolean`,default:!1},checkGuards:{type:`boolean`,default:!1}},additionalProperties:!1}],messages:{preferFold:`Prefer .fold() over if/else when working with {{type}} types`,preferFoldTernary:`Consider using .fold() instead of ternary operator for {{type}}`,preferFoldGuard:`{{receiver}} is checked with an early exit and then unwrapped. {{advice}} Branching first and unwrapping after is the imperative form.`,suggestFold:`Replace with .fold()`,suggestOr:`Replace with {{receiver}}.or({{alternative}}) — keep the first when it is present, else the alternative`}},create(t){let n=t.options[0]||{},i=n.allowInteropMarker!==!1,a=n=>i&&e(n,`interop`,t.sourceCode),s=n.minComplexity||2,c=n.checkNullable===!0,l=n.checkGuards===!0,f=e=>e?`Several guards in a row pass their failures through: sequence them with DoAsync(async function* () { const a = yield* $(await …) … }).`:`Several guards in a row pass their failures through: sequence them with Do(function* () { const a = yield* $(…); const b = yield* $(…); return … }).`,p={passthrough:(e,t)=>t?`Keep it in the chain: ${e}.flatMapAsync(…), or lift the steps into IO.`:`Keep it in the chain: ${e}.flatMap(…) or ${e}.map(…); the failure passes through on its own.`,mappedFailure:(e,t)=>`Keep it in the chain: ${e}.mapLeft(…).${t?`flatMapAsync`:`flatMap`}(…) builds the new failure and continues on success.`,default:e=>`Use ${e}.map(…).orElse(fallback), or ${e}.fold(() => fallback, (value) => …).`,throw:e=>`If a host needs the throw, use ${e}.orThrow((e) => new YourError(e)); otherwise keep it in the chain with .flatMap or .fold.`,effect:(e,t)=>t?`Use ${e}.foldAsync(onFailure, onSuccess).`:`Use ${e}.fold(onFailure, onSuccess).`};function m(e){if(!l)return;let n=t.sourceCode,i=T(e,n);if(!i)return;let a=e.parent;if(a?.type!==`BlockStatement`&&a?.type!==`Program`)return;let s=a.body,c=s.slice(s.indexOf(e)+1),u=r(i.obj);if(!w(c,u,n))return;let d=C(e.consequent,u,i.failure?.member??null,n);if(!d)return;let m=c.some(e=>o(e)),h=(d===`passthrough`||d===`mappedFailure`)&&s.filter(e=>{let t=T(e,n);if(!t)return!1;let i=r(t.obj),a=s.slice(s.indexOf(e)+1),o=C(e.consequent,i,t.failure?.member??null,n);return(o===`passthrough`||o===`mappedFailure`)&&w(a,i,n)}).length>1;t.report({node:e,messageId:`preferFoldGuard`,data:{receiver:i.obj,advice:h?f(m):p[d](i.obj,m)}})}function h(e){let n=t.sourceCode;if(e.type!==`IfStatement`||!e.alternate)return null;let r=d(e.test,n);if(!r)return null;let i=v(e.consequent),a=v(e.alternate);if(!i||!a)return null;let o=[e.test,i,a];if(!n.getCommentsInside(e).every(e=>e.range!==void 0&&o.some(t=>e.range[0]>=t.range[0]&&e.range[1]<=t.range[1])))return null;let{obj:s,isNegated:c,failure:l}=r,[u,f]=c?[i,a]:[a,i];return`return ${_(s,l,u,f,n)}`}function g(e){let n=t.sourceCode,i=d(e.test,n);if(!i)return[];let{obj:a,isNegated:o,failure:s}=i,[c,l]=o?[e.consequent,e.alternate]:[e.alternate,e.consequent],f=n.getText(c),p=n.getText(l);if(r(p)===r(a))return c.type===`Literal`||c.type===`TemplateLiteral`||u(c)?[]:[{messageId:`suggestOr`,data:{receiver:a,alternative:f},fix:t=>t.replaceText(e,`${a}.or(${f})`)}];let m=_(a,s,c,l,n);return[{messageId:`suggestFold`,fix:t=>t.replaceText(e,m)}]}function b(e){if(e.type===`CallExpression`&&e.callee.type===`MemberExpression`){let t=e.callee.property.name;return[`isSome`,`isNone`,`isRight`,`isLeft`,`isSuccess`,`isFailure`].includes(t)}return!1}function x(e){let n=t.sourceCode.getText(e);if(/\.(isSome|isNone|isDefined)\s*\(\s*\)/.test(n))return{isMonadic:!0,type:`Option`,via:`method`};if(/\.(isLeft|isRight)\s*\(\s*\)/.test(n))return{isMonadic:!0,type:`Either`,via:`method`};if(/\.(isSuccess|isFailure)\s*\(\s*\)/.test(n))return{isMonadic:!0,type:`Result`,via:`method`};if(c&&e.type===`BinaryExpression`){if((e.operator===`===`||e.operator===`!==`||e.operator===`==`||e.operator===`!=`)&&(e.left.type===`Literal`&&(e.left.value===null||e.left.value===void 0)||e.right.type===`Literal`&&(e.right.value===null||e.right.value===void 0)))return{isMonadic:!0,type:`Option`,via:`nullable`};if(e.operator===`==`||e.operator===`!=`||e.operator===`===`||e.operator===`!==`){let t=e.left.type===`Identifier`&&e.left.name===`undefined`,n=e.right.type===`Identifier`&&e.right.name===`undefined`;if(t||n)return{isMonadic:!0,type:`Option`,via:`nullable`}}}return{isMonadic:!1,type:``,via:``}}function S(e){if(!b(e.test))return[];let t=h(e);return t?[{messageId:`suggestFold`,fix:n=>n.replaceText(e,t)}]:[]}function E(e){let n=e.test,r=x(n);r.isMonadic&&(e.parent&&e.parent.type===`IfStatement`||y(e)>=s&&t.report({node:e,messageId:`preferFold`,data:{type:r.type},suggest:S(e)}))}return{IfStatement(e){a(e)||(E(e),m(e))},ConditionalExpression(e){if(a(e))return;let n=x(e.test);(n.via!==`nullable`||!u(e.consequent)&&!u(e.alternate))&&n.isMonadic&&t.report({node:e,messageId:`preferFoldTernary`,data:{type:n.type},suggest:b(e.test)?g(e):[]})}}}};export{E as default};
|
|
2
2
|
//# sourceMappingURL=prefer-fold.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"prefer-fold.js","names":["POSITIVE_PREDICATES","NEGATIVE_PREDICATES","FAILURE_SIDE","SUCCESS_METHODS","SUCCESS_MEMBER","isNullishLiteral","node","extractMonadicTest","test","methodName","obj","sourceCode","failure","compact","text","SUCCESS_READS","receiverReads","isReceiver","target","receiver","isMember","names","visit","parent","isCalled","isWritten","reads","childNodes","branch","freshName","isTaken","branches","name","b","base","i","asArrowBody","foldCallback","ranges","offset","rewritten","a","start","end","acc","param","buildFold","failureNode","successNode","onSuccess","returnedExpression","statement","ifElseChainLength","FAILURE_CONSTRUCTORS","readsMember","descendants","n","member","guardExitStatement","consequent","last","classifyGuardExit","found","argument","callee","calleeName","args","failureMember","unwrapsReceiver","nodes","statements","guardOf","extracted","rule","options","context","allowInteropMarker","isExemptByMarker","isInsideTaggedDeclaration","minComplexity","checkNullable","checkGuards","SEQUENCE_ADVICE","isAsync","GUARD_ADVICE","r","checkGuard","block","body","after","exit","containsAwait","sequenced","other","candidate","otherReceiver","otherAfter","kind","generateFoldFromIf","thenExpr","elseExpr","kept","c","failureExpr","successExpr","isNegated","ternarySuggestions","failureText","successText","fixer","fold","isFunctypePredicateCall","isMonadicCheck","leftIsUndefined","rightIsUndefined","suggestionsForIf","replacement","analyzeIfStatement","monadicInfo"],"sources":["../../src/rules/prefer-fold.ts"],"sourcesContent":["import type { Rule, SourceCode } from \"eslint\"\n\nimport type { ASTNode } from \"../types/ast\"\nimport { childNodes, descendants } from \"../utils/ast-walk\"\nimport { containsAwait } from \"../utils/async-detection\"\nimport { INTEROP_TAG, isInsideTaggedDeclaration } from \"../utils/boundary-tags\"\n\n/** Methods on a monadic value that mean \"this is the Some/Right/Success path.\" */\nconst POSITIVE_PREDICATES: ReadonlySet<string> = new Set([\"isSome\", \"isRight\", \"isSuccess\"])\n/** Methods that mean \"this is the None/Left/Failure path.\" */\n// `isEmpty` is deliberately absent: it is a property on every functype container, never a method, so\n// `x.isEmpty()` is not functype code (and on a List, `.fold` is a reduce, not a branch).\nconst NEGATIVE_PREDICATES: ReadonlySet<string> = new Set([\"isNone\", \"isLeft\", \"isFailure\"])\n\n/**\n * How each container's fold exposes its failure side. `fold(onFailure, onSuccess)` everywhere, but\n * only Either and Try hand the failure callback a value — Option's `onNone` takes nothing. `member`\n * is the property a narrowed branch reads that value through (`e.value` after `isLeft()`,\n * `t.error` after `isFailure()`).\n */\ntype FailureSide = { readonly param: string; readonly member: string } | null\n\nconst FAILURE_SIDE: Readonly<Record<string, FailureSide>> = {\n isSome: null,\n isNone: null,\n isRight: { param: \"left\", member: \"value\" },\n isLeft: { param: \"left\", member: \"value\" },\n isSuccess: { param: \"error\", member: \"error\" },\n isFailure: { param: \"error\", member: \"error\" },\n}\n\n/** Reads of the success value that the fold's success parameter replaces. */\nconst SUCCESS_METHODS = [\"get\", \"orThrow\"]\nconst SUCCESS_MEMBER = \"value\"\n\n/**\n * A literal `null` or the `undefined` identifier. A ternary that yields one of these in a branch is\n * building an optional value (prefer-option's concern), not folding a monad — so the untyped nullable\n * heuristic must not treat `x !== undefined ? \"a\" : undefined` as a fold candidate.\n */\nfunction isNullishLiteral(node: ASTNode): boolean {\n return (node.type === \"Literal\" && node.value === null) || (node.type === \"Identifier\" && node.name === \"undefined\")\n}\n\n/**\n * If `test` is a monadic predicate call like `option.isSome()` or\n * `either.isLeft()`, returns the receiver expression's text plus whether the\n * predicate is the \"absence\" side. Returns null for anything else.\n */\nfunction extractMonadicTest(\n test: ASTNode,\n sourceCode: SourceCode,\n): { obj: string; isNegated: boolean; failure: FailureSide } | null {\n if (test.type !== \"CallExpression\" || test.callee.type !== \"MemberExpression\") return null\n const methodName = test.callee.property.name\n const obj = sourceCode.getText(test.callee.object)\n const failure = FAILURE_SIDE[methodName] ?? null\n if (POSITIVE_PREDICATES.has(methodName)) return { obj, isNegated: false, failure }\n if (NEGATIVE_PREDICATES.has(methodName)) return { obj, isNegated: true, failure }\n return null\n}\n\n/** Source text with all whitespace removed — receivers match however they are line-broken. */\nconst compact = (text: string): string => text.replace(/\\s+/g, \"\")\n\n/** Which reads of the narrowed receiver a fold parameter replaces. */\ntype Reads = { readonly members: ReadonlyArray<string>; readonly methods: ReadonlyArray<string> }\n\nconst SUCCESS_READS: Reads = { members: [SUCCESS_MEMBER], methods: SUCCESS_METHODS }\n\n/**\n * Source ranges inside `branch` that read the narrowed receiver: `e.value`, `e!.value`, `e?.value`,\n * `e.orThrow()`. Driven by the AST rather than the text, so a read never matches inside a string or\n * template literal, a comment, a longer name, or another object's member (`other.e.value`). A member\n * that is called (`e.value()`) or assigned (`e.value = 3`) is not a read.\n */\nfunction receiverReads(\n branch: ASTNode,\n receiver: string,\n reads: Reads,\n sourceCode: SourceCode,\n): ReadonlyArray<readonly [number, number]> {\n const isReceiver = (node: ASTNode): boolean => {\n const target = node.type === \"TSNonNullExpression\" ? node.expression : node\n return compact(sourceCode.getText(target)) === compact(receiver)\n }\n const isMember = (node: ASTNode, names: ReadonlyArray<string>): boolean =>\n node.type === \"MemberExpression\" &&\n !node.computed &&\n node.property.type === \"Identifier\" &&\n names.includes(node.property.name) &&\n isReceiver(node.object)\n\n const visit = (node: ASTNode): ReadonlyArray<readonly [number, number]> => {\n const parent = node.parent\n const isCalled = parent?.type === \"CallExpression\" && parent.callee === node\n const isWritten =\n (parent?.type === \"AssignmentExpression\" && parent.left === node) || parent?.type === \"UpdateExpression\"\n if (isMember(node, reads.members) && !isCalled && !isWritten) return [node.range]\n if (node.type === \"CallExpression\" && node.arguments.length === 0 && isMember(node.callee, reads.methods)) {\n return [node.range]\n }\n return childNodes(node).flatMap(visit)\n }\n return visit(branch)\n}\n\n/** A parameter name no branch already uses, so the fold never shadows a captured identifier. */\nconst freshName = (base: string, branches: ReadonlyArray<string>): string => {\n // `(?<![\\\\w$.])`: a property access (`e.value`) is not a free identifier, so it cannot be shadowed.\n const isTaken = (name: string): boolean => branches.some((b) => new RegExp(`(?<![\\\\w$.])${name}(?![\\\\w$])`).test(b))\n const candidates = [base, ...Array.from({ length: 20 }, (_, i) => `${base}${i + 1}`)]\n return candidates.find((name) => !isTaken(name)) ?? `${base}_`\n}\n\n/**\n * An arrow body must not start with `{` (it would parse as a block) and a comma expression must stay\n * one argument, so those two shapes are parenthesized. ESTree ranges exclude the source's own parens.\n */\nconst asArrowBody = (node: ASTNode, text: string): string =>\n node.type === \"ObjectExpression\" || node.type === \"SequenceExpression\" ? `(${text})` : text\n\n/**\n * One fold callback. Reads of the narrowed receiver become reads of the callback's parameter — the\n * receiver is NOT narrowed inside the callback, so leaving `e.value` there is a type error (#323).\n * A branch that never reads the value gets a parameterless callback, not an unused parameter.\n */\nfunction foldCallback(\n branch: ASTNode,\n receiver: string,\n reads: Reads | null,\n param: string,\n sourceCode: SourceCode,\n): string {\n const text = sourceCode.getText(branch)\n const ranges = reads === null ? [] : receiverReads(branch, receiver, reads, sourceCode)\n if (ranges.length === 0) return `() => ${asArrowBody(branch, text)}`\n const offset = branch.range[0]\n // Replace right-to-left so earlier offsets stay valid.\n const rewritten = [...ranges]\n .sort((a, b) => b[0] - a[0])\n .reduce((acc, [start, end]) => acc.slice(0, start - offset) + param + acc.slice(end - offset), text)\n return `(${param}) => ${asArrowBody(branch, rewritten)}`\n}\n\n/** `receiver.fold(onFailure, onSuccess)` from the two branch nodes. */\nfunction buildFold(\n receiver: string,\n failure: FailureSide,\n failureNode: ASTNode,\n successNode: ASTNode,\n sourceCode: SourceCode,\n): string {\n const branches = [sourceCode.getText(failureNode), sourceCode.getText(successNode)]\n const onSuccess = foldCallback(successNode, receiver, SUCCESS_READS, freshName(\"value\", branches), sourceCode)\n const onFailure =\n failure === null\n ? foldCallback(failureNode, receiver, null, \"\", sourceCode)\n : foldCallback(\n failureNode,\n receiver,\n { members: [failure.member], methods: [] },\n freshName(failure.param, branches),\n sourceCode,\n )\n return `${receiver}.fold(${onFailure}, ${onSuccess})`\n}\n\n/** The returned expression of a `return x` statement or a `{ return x }` block; null for anything else. */\nfunction returnedExpression(node: ASTNode): ASTNode | null {\n const statement = node.type === \"BlockStatement\" && node.body.length === 1 ? node.body[0] : node\n return statement.type === \"ReturnStatement\" && statement.argument ? statement.argument : null\n}\n\n/**\n * Length of an if/else-if/else chain rooted at `node`. Counts the root as 1\n * and adds 1 per linked alternate IfStatement. Terminates on a non-If\n * alternate (the final `else { ... }`) which counts as the last branch.\n */\nfunction ifElseChainLength(node: ASTNode): number {\n if (!node.alternate) return 1\n if (node.alternate.type === \"IfStatement\") return 1 + ifElseChainLength(node.alternate as ASTNode)\n return 2 // root + the terminal else\n}\n\n/**\n * What a guard's early exit does, which decides the advice:\n * - `passthrough`: hands the failure back unchanged (`return e`, `return Left(e.value)`, `return None()`),\n * so the rest of the function is a `flatMap`/`map`.\n * - `mappedFailure`: returns a new failure built from the old one (`return Left({ kind: e.value.kind })`),\n * so it's `mapLeft(…)` then `flatMap`.\n * - `default`: returns a plain fallback, so it's `map(…).orElse(fallback)` or a `fold`.\n * - `throw`: a host that needs a throw, so it's `orThrow((e) => …)`.\n * - `effect`: does other work first (logging, setting state), so it's a `fold`.\n */\ntype GuardExit = \"passthrough\" | \"mappedFailure\" | \"default\" | \"throw\" | \"effect\"\n\n/** Constructors (and companion methods) that build a failure: `Left(…)`, `None()`, `Failure(…)`, `Either.left(…)`. */\nconst FAILURE_CONSTRUCTORS: ReadonlySet<string> = new Set([\"Left\", \"None\", \"Failure\", \"left\", \"none\", \"failure\"])\n\n/** Does `node` read `<receiver>.<member>` anywhere inside it? */\nfunction readsMember(node: ASTNode, receiver: string, member: string, sourceCode: SourceCode): boolean {\n return descendants(node).some(\n (n) =>\n n.type === \"MemberExpression\" &&\n !n.computed &&\n n.property.type === \"Identifier\" &&\n n.property.name === member &&\n compact(sourceCode.getText(n.object)) === receiver,\n )\n}\n\n/** The single exit statement of a guard's consequent: `return x` / `throw x`, alone or as a one-statement block. */\nfunction guardExitStatement(consequent: ASTNode): { readonly exit: ASTNode; readonly extraWork: boolean } | null {\n if (consequent.type === \"ReturnStatement\" || consequent.type === \"ThrowStatement\") {\n return { exit: consequent, extraWork: false }\n }\n if (consequent.type !== \"BlockStatement\" || consequent.body.length === 0) return null\n const last = consequent.body[consequent.body.length - 1] as ASTNode\n if (last.type !== \"ReturnStatement\" && last.type !== \"ThrowStatement\") return null\n return { exit: last, extraWork: consequent.body.length > 1 }\n}\n\n/**\n * `receiver` is the compacted receiver text; `failureMember` is where the failure value lives once\n * narrowed (`value` for Either, `error` for Try, null for Option, whose None carries nothing).\n */\nfunction classifyGuardExit(\n consequent: ASTNode,\n receiver: string,\n failureMember: string | null,\n sourceCode: SourceCode,\n): GuardExit | null {\n const found = guardExitStatement(consequent)\n if (!found) return null\n if (found.exit.type === \"ThrowStatement\") return \"throw\"\n if (found.extraWork) return \"effect\"\n const argument = found.exit.argument as ASTNode | null\n if (!argument) return \"effect\"\n if (compact(sourceCode.getText(argument)) === receiver) return \"passthrough\"\n const callee = argument.type === \"CallExpression\" ? (argument.callee as ASTNode) : null\n const calleeName =\n callee?.type === \"Identifier\"\n ? callee.name\n : callee?.type === \"MemberExpression\" && callee.property.type === \"Identifier\"\n ? callee.property.name\n : null\n if (calleeName && FAILURE_CONSTRUCTORS.has(calleeName)) {\n const args = (argument.arguments ?? []) as ReadonlyArray<ASTNode>\n const unchanged =\n args.length === 0 ||\n (args.length === 1 &&\n failureMember !== null &&\n compact(sourceCode.getText(args[0])) === `${receiver}.${failureMember}`)\n return unchanged ? \"passthrough\" : \"mappedFailure\"\n }\n // A fallback built from the failure (`c.json({ error: r.value }, 500)`) can only be written as a fold:\n // outside the guard the failure isn't narrowed, so `map(…).orElse(…)` couldn't read it.\n if (failureMember !== null && readsMember(argument, receiver, failureMember, sourceCode)) return \"effect\"\n return \"default\"\n}\n\n/**\n * Does `statements` unwrap `receiver` the imperative way — `receiver.value`, `.orThrow()`, `.get()`?\n * Reads through `map`, `flatMap`, `fold`, `orElse`… are already the functional form and don't count.\n */\nfunction unwrapsReceiver(statements: ReadonlyArray<ASTNode>, receiver: string, sourceCode: SourceCode): boolean {\n const nodes = statements.flatMap((statement) => descendants(statement))\n // `e = next()` after the guard: later reads are of a different value, which the guard didn't check.\n const reassigned = nodes.some(\n (node) => node.type === \"AssignmentExpression\" && compact(sourceCode.getText(node.left)) === receiver,\n )\n if (reassigned) return false\n return nodes.some((node) => {\n if (node.type !== \"MemberExpression\" || compact(sourceCode.getText(node.object)) !== receiver) return false\n const name = node.property.type === \"Identifier\" ? node.property.name : null\n if (name === SUCCESS_MEMBER) return true\n const parent = node.parent as ASTNode | undefined\n if (name === null || !SUCCESS_METHODS.includes(name)) return false\n if (parent?.type !== \"CallExpression\" || parent.callee !== node) return false\n // `orThrow(error)` / `orThrow((e) => …)` names its error: no-get-unsafe treats that as a deliberate\n // host throw, so this rule doesn't count it as an unwrap either.\n return !(name === \"orThrow\" && (parent.arguments as ReadonlyArray<ASTNode>).length > 0)\n })\n}\n\n/** An exit-only negative guard (`if (e.isLeft()) return …`) on a functype predicate, or null. */\nfunction guardOf(node: ASTNode, sourceCode: SourceCode): ReturnType<typeof extractMonadicTest> {\n if (node.type !== \"IfStatement\" || node.alternate) return null\n const extracted = extractMonadicTest(node.test, sourceCode)\n if (!extracted?.isNegated || !guardExitStatement(node.consequent)) return null\n return extracted\n}\n\nconst rule: Rule.RuleModule = {\n meta: {\n type: \"suggestion\",\n docs: {\n description: \"Prefer .fold() over if/else chains when working with monadic types\",\n recommended: true,\n },\n // Suggestions, never an autofix (#323): `ts-builds validate` runs `eslint --fix`, which applies\n // fixable rules at warn severity too, and a fold rewrite cannot be proven type-correct without type\n // information. The developer applies it, and the compiler checks it.\n hasSuggestions: true,\n schema: [\n {\n type: \"object\",\n properties: {\n allowInteropMarker: {\n type: \"boolean\",\n default: true,\n },\n minComplexity: {\n type: \"integer\",\n minimum: 1,\n default: 2,\n },\n checkNullable: {\n type: \"boolean\",\n default: false,\n },\n checkGuards: {\n type: \"boolean\",\n default: false,\n },\n },\n additionalProperties: false,\n },\n ],\n messages: {\n preferFold: \"Prefer .fold() over if/else when working with {{type}} types\",\n preferFoldTernary: \"Consider using .fold() instead of ternary operator for {{type}}\",\n preferFoldGuard:\n \"{{receiver}} is checked with an early exit and then unwrapped. {{advice}} Branching first and unwrapping after is the imperative form.\",\n suggestFold: \"Replace with .fold()\",\n suggestOr:\n \"Replace with {{receiver}}.or({{alternative}}) — keep the first when it is present, else the alternative\",\n },\n },\n\n create(context) {\n const options = context.options[0] || {}\n // `@interop <reason>` on an enclosing declaration marks a host-contract boundary (#241).\n const allowInteropMarker = options.allowInteropMarker !== false\n const isExemptByMarker = (node: ASTNode): boolean =>\n allowInteropMarker && isInsideTaggedDeclaration(node, INTEROP_TAG, context.sourceCode)\n const minComplexity = options.minComplexity || 2\n // Off by default (#325): a null check on a plain value (`x === null ? a : b`) is not a fold of a\n // functype value. Whether that value should be an Option is prefer-option's call, and at error this\n // path fired on JSX conditionals, style objects and conditional spreads (31 of 31 hits in CivalaOS,\n // 0 of which were functype values). Predicate calls (`o.isSome()`, `e.isLeft()`) are always checked.\n const checkNullable = options.checkNullable === true\n // Guard-then-unwrap (`if (e.isLeft()) return …; use(e.value)`). Opt-in while it's measured on real\n // code: prefer-fold is `error` in recommended, so turning this on by default would fail builds.\n const checkGuards = options.checkGuards === true\n\n const SEQUENCE_ADVICE = (isAsync: boolean): string =>\n isAsync\n ? \"Several guards in a row pass their failures through: sequence them with DoAsync(async function* () { const a = yield* $(await …) … }).\"\n : \"Several guards in a row pass their failures through: sequence them with Do(function* () { const a = yield* $(…); const b = yield* $(…); return … }).\"\n\n const GUARD_ADVICE: Readonly<Record<GuardExit, (receiver: string, isAsync: boolean) => string>> = {\n passthrough: (r, isAsync) =>\n isAsync\n ? `Keep it in the chain: ${r}.flatMapAsync(…), or lift the steps into IO.`\n : `Keep it in the chain: ${r}.flatMap(…) or ${r}.map(…); the failure passes through on its own.`,\n mappedFailure: (r, isAsync) =>\n `Keep it in the chain: ${r}.mapLeft(…).${isAsync ? \"flatMapAsync\" : \"flatMap\"}(…) builds the new failure and continues on success.`,\n default: (r) => `Use ${r}.map(…).orElse(fallback), or ${r}.fold(() => fallback, (value) => …).`,\n throw: (r) =>\n `If a host needs the throw, use ${r}.orThrow((e) => new YourError(e)); otherwise keep it in the chain with .flatMap or .fold.`,\n effect: (r, isAsync) =>\n isAsync ? `Use ${r}.foldAsync(onFailure, onSuccess).` : `Use ${r}.fold(onFailure, onSuccess).`,\n }\n\n /**\n * `if (e.isLeft()) return …` followed, in the same block, by reads of `e.value` / `e.orThrow()`.\n * `orElse` and `fold` are never flagged: both are proper ways to leave the container.\n */\n function checkGuard(node: ASTNode): void {\n if (!checkGuards) return\n const sourceCode = context.sourceCode\n const extracted = guardOf(node, sourceCode)\n if (!extracted) return\n const block = node.parent as ASTNode | undefined\n if (block?.type !== \"BlockStatement\" && block?.type !== \"Program\") return\n const body = block.body as ReadonlyArray<ASTNode>\n const after = body.slice(body.indexOf(node) + 1)\n const receiver = compact(extracted.obj)\n if (!unwrapsReceiver(after, receiver, sourceCode)) return\n const exit = classifyGuardExit(node.consequent, receiver, extracted.failure?.member ?? null, sourceCode)\n if (!exit) return\n const isAsync = after.some((statement) => containsAwait(statement))\n // Two or more pass-through guards in one block, each unwrapped later: nested flatMaps would be worse\n // than the guards, so the advice is a Do comprehension.\n const passThrough = (candidate: ASTNode): boolean => {\n const other = guardOf(candidate, sourceCode)\n if (!other) return false\n const otherReceiver = compact(other.obj)\n const otherAfter = body.slice(body.indexOf(candidate) + 1)\n const kind = classifyGuardExit(candidate.consequent, otherReceiver, other.failure?.member ?? null, sourceCode)\n return (\n (kind === \"passthrough\" || kind === \"mappedFailure\") && unwrapsReceiver(otherAfter, otherReceiver, sourceCode)\n )\n }\n const sequenced = (exit === \"passthrough\" || exit === \"mappedFailure\") && body.filter(passThrough).length > 1\n context.report({\n node,\n messageId: \"preferFoldGuard\",\n data: {\n receiver: extracted.obj,\n advice: sequenced ? SEQUENCE_ADVICE(isAsync) : GUARD_ADVICE[exit](extracted.obj, isAsync),\n },\n })\n }\n\n function generateFoldFromIf(node: ASTNode): string | null {\n const sourceCode = context.sourceCode\n if (node.type !== \"IfStatement\" || !node.alternate) return null\n\n const extracted = extractMonadicTest(node.test, sourceCode)\n if (!extracted) return null\n\n // Only if/else where both branches return a value — the fold then replaces the whole statement\n // as `return receiver.fold(...)`. Anything else (side effects, nested else-if) is left alone.\n const thenExpr = returnedExpression(node.consequent)\n const elseExpr = returnedExpression(node.alternate)\n if (!thenExpr || !elseExpr) return null\n\n // The suggestion keeps only the test and the two returned values; a comment anywhere else in the\n // statement would be silently dropped, so none is offered.\n const kept = [node.test, thenExpr, elseExpr]\n const within = (c: { range?: [number, number] }): boolean =>\n c.range !== undefined && kept.some((n) => c.range![0] >= n.range[0] && c.range![1] <= n.range[1])\n if (!sourceCode.getCommentsInside(node).every(within)) return null\n\n const { obj, isNegated, failure } = extracted\n const [failureExpr, successExpr] = isNegated ? [thenExpr, elseExpr] : [elseExpr, thenExpr]\n return `return ${buildFold(obj, failure, failureExpr, successExpr, sourceCode)}`\n }\n\n function ternarySuggestions(node: ASTNode): Rule.SuggestionReportDescriptor[] {\n const sourceCode = context.sourceCode\n const extracted = extractMonadicTest(node.test, sourceCode)\n if (!extracted) return []\n\n const { obj, isNegated, failure } = extracted\n const [failureNode, successNode] = isNegated\n ? [node.consequent, node.alternate]\n : [node.alternate, node.consequent]\n const failureText = sourceCode.getText(failureNode)\n const successText = sourceCode.getText(successNode)\n\n // `a.isSome() ? a : b` keeps the container when present and falls back otherwise — that is `.or`,\n // and a fold would only rebuild it with an unused parameter. `.or` takes a container, so a literal\n // or `undefined` fallback gets no suggestion at all: neither `.or(5)` nor a fold mixing a container\n // with a plain value would type-check.\n if (compact(successText) === compact(obj)) {\n if (failureNode.type === \"Literal\" || failureNode.type === \"TemplateLiteral\" || isNullishLiteral(failureNode)) {\n return []\n }\n return [\n {\n messageId: \"suggestOr\",\n data: { receiver: obj, alternative: failureText },\n fix: (fixer) => fixer.replaceText(node, `${obj}.or(${failureText})`),\n },\n ]\n }\n\n const fold = buildFold(obj, failure, failureNode, successNode, sourceCode)\n return [{ messageId: \"suggestFold\", fix: (fixer) => fixer.replaceText(node, fold) }]\n }\n\n function isFunctypePredicateCall(node: ASTNode): boolean {\n // Suggest a rewrite only when the test is a functype predicate call (the receiver is a functype value)\n if (node.type === \"CallExpression\" && node.callee.type === \"MemberExpression\") {\n const methodName = node.callee.property.name\n // These methods indicate the object is already a functype instance\n return [\"isSome\", \"isNone\", \"isRight\", \"isLeft\", \"isSuccess\", \"isFailure\"].includes(methodName)\n }\n return false\n }\n\n // `via` records HOW we matched: a functype predicate call (`method`, precise) vs the untyped\n // null/undefined heuristic (`nullable`, a guess that can't tell a real Option from a plain nullable).\n function isMonadicCheck(node: ASTNode): { isMonadic: boolean; type: string; via: \"method\" | \"nullable\" | \"\" } {\n const sourceCode = context.sourceCode\n const text = sourceCode.getText(node)\n\n // Check for common monadic type checks\n if (/\\.(isSome|isNone|isDefined)\\s*\\(\\s*\\)/.test(text)) {\n return { isMonadic: true, type: \"Option\", via: \"method\" }\n }\n\n if (/\\.(isLeft|isRight)\\s*\\(\\s*\\)/.test(text)) {\n return { isMonadic: true, type: \"Either\", via: \"method\" }\n }\n\n if (/\\.(isSuccess|isFailure)\\s*\\(\\s*\\)/.test(text)) {\n return { isMonadic: true, type: \"Result\", via: \"method\" }\n }\n\n // Check for null/undefined checks on variables that might be Options\n if (checkNullable && node.type === \"BinaryExpression\") {\n if (\n (node.operator === \"===\" || node.operator === \"!==\" || node.operator === \"==\" || node.operator === \"!=\") &&\n ((node.left.type === \"Literal\" && (node.left.value === null || node.left.value === undefined)) ||\n (node.right.type === \"Literal\" && (node.right.value === null || node.right.value === undefined)))\n ) {\n return { isMonadic: true, type: \"Option\", via: \"nullable\" }\n }\n\n // Check for === or == with undefined identifier\n if (node.operator === \"==\" || node.operator === \"!=\" || node.operator === \"===\" || node.operator === \"!==\") {\n const leftIsUndefined = node.left.type === \"Identifier\" && node.left.name === \"undefined\"\n const rightIsUndefined = node.right.type === \"Identifier\" && node.right.name === \"undefined\"\n\n if (leftIsUndefined || rightIsUndefined) {\n return { isMonadic: true, type: \"Option\", via: \"nullable\" }\n }\n }\n }\n\n return { isMonadic: false, type: \"\", via: \"\" }\n }\n\n function suggestionsForIf(node: ASTNode): Rule.SuggestionReportDescriptor[] {\n if (!isFunctypePredicateCall(node.test)) return []\n const replacement = generateFoldFromIf(node)\n return replacement ? [{ messageId: \"suggestFold\", fix: (fixer) => fixer.replaceText(node, replacement) }] : []\n }\n\n function analyzeIfStatement(node: ASTNode) {\n const test = node.test\n const monadicInfo = isMonadicCheck(test)\n\n if (!monadicInfo.isMonadic) return\n\n // Don't analyze if this is part of a larger if/else chain\n // (only analyze the outermost if statement)\n if (node.parent && node.parent.type === \"IfStatement\") return\n\n // Count the complexity (if/else if/else chain)\n if (ifElseChainLength(node) >= minComplexity) {\n context.report({\n node,\n messageId: \"preferFold\",\n data: { type: monadicInfo.type },\n suggest: suggestionsForIf(node),\n })\n }\n }\n\n return {\n IfStatement(node: ASTNode) {\n if (isExemptByMarker(node)) return\n analyzeIfStatement(node)\n checkGuard(node)\n },\n\n ConditionalExpression(node: ASTNode) {\n if (isExemptByMarker(node)) return\n const monadicInfo = isMonadicCheck(node.test)\n // The untyped nullable heuristic can't distinguish a real Option from a plain nullable primitive.\n // When it fires on a ternary that yields `undefined`/`null` in a branch, that's optional value\n // construction (prefer-option's concern), not a fold — skip it. False positive this kills:\n // `x !== undefined ? \"a\" : undefined`. Predicate-call matches (`.isSome()` etc.) are unaffected.\n if (monadicInfo.via === \"nullable\" && (isNullishLiteral(node.consequent) || isNullishLiteral(node.alternate))) {\n return\n }\n if (monadicInfo.isMonadic) {\n context.report({\n node,\n messageId: \"preferFoldTernary\",\n data: { type: monadicInfo.type },\n suggest: isFunctyp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CAC1E,GAAI,CAACJ,EAAwBzG,EAAK,IAAI,EAAG,MAAO,CAAC,EACjD,IAAM8G,EAAclB,EAAmB5F,CAAI,EAC3C,OAAO8G,EAAc,CAAC,CAAE,UAAW,cAAe,IAAM,GAAUP,EAAM,YAAYvG,EAAM8G,CAAW,CAAE,CAAC,EAAI,CAAC,CAC/G,CAEA,SAASC,EAAmB,EAAe,CACzC,IAAM7G,EAAOF,EAAK,KACZgH,EAAcN,EAAexG,CAAI,EAElC8G,EAAY,YAIbhH,EAAK,QAAUA,EAAK,OAAO,OAAS,eAGpC8C,EAAkB9C,CAAI,GAAKyE,GAC7BJ,EAAQ,OAAO,CACb,OACA,UAAW,aACX,KAAM,CAAE,KAAM2C,EAAY,IAAK,EAC/B,QAASH,EAAiB7G,CAAI,CAChC,CAAC,EAEL,CAEA,MAAO,CACL,YAAY,EAAe,CACrBuE,EAAiBvE,CAAI,IACzB+G,EAAmB/G,CAAI,EACvBgF,EAAWhF,CAAI,EACjB,EAEA,sBAAsB,EAAe,CACnC,GAAIuE,EAAiBvE,CAAI,EAAG,OAC5B,IAAMgH,EAAcN,EAAe1G,EAAK,IAAI,GAKxCgH,EAAY,MAAQ,YAAe,GAAiBhH,EAAK,UAAU,GAAK,GAAiBA,EAAK,SAAS,IAGvGgH,EAAY,WACd3C,EAAQ,OAAO,CACb,OACA,UAAW,oBACX,KAAM,CAAE,KAAM2C,EAAY,IAAK,EAC/B,QAASP,EAAwBzG,EAAK,IAAI,EAAIoG,EAAmBpG,CAAI,EAAI,CAAC,CAC5E,CAAC,CAEL,CACF,CACF,CACF"}
|
|
1
|
+
{"version":3,"file":"prefer-fold.js","names":["FAILURE_SIDE","SUCCESS_METHODS","SUCCESS_MEMBER","isNullishLiteral","node","extractMonadicTest","test","methodName","obj","sourceCode","failure","POSITIVE_PREDICATES","NEGATIVE_PREDICATES","SUCCESS_READS","receiverReads","isReceiver","target","compact","receiver","isMember","names","visit","parent","isCalled","isWritten","reads","childNodes","branch","freshName","isTaken","branches","name","b","base","i","asArrowBody","text","foldCallback","ranges","offset","rewritten","a","start","end","acc","param","buildFold","failureNode","successNode","onSuccess","returnedExpression","statement","ifElseChainLength","FAILURE_CONSTRUCTORS","readsMember","descendants","n","member","guardExitStatement","consequent","last","classifyGuardExit","found","argument","callee","calleeName","args","failureMember","unwrapsReceiver","nodes","statements","guardOf","extracted","rule","options","context","allowInteropMarker","isExemptByMarker","isInsideTaggedDeclaration","minComplexity","checkNullable","checkGuards","SEQUENCE_ADVICE","isAsync","GUARD_ADVICE","r","checkGuard","block","body","after","exit","containsAwait","sequenced","other","candidate","otherReceiver","otherAfter","kind","generateFoldFromIf","thenExpr","elseExpr","kept","c","failureExpr","successExpr","isNegated","ternarySuggestions","failureText","successText","fixer","fold","isFunctypePredicateCall","isMonadicCheck","leftIsUndefined","rightIsUndefined","suggestionsForIf","replacement","analyzeIfStatement","monadicInfo"],"sources":["../../src/rules/prefer-fold.ts"],"sourcesContent":["import type { Rule, SourceCode } from \"eslint\"\n\nimport type { ASTNode } from \"../types/ast\"\nimport { childNodes, descendants } from \"../utils/ast-walk\"\nimport { containsAwait } from \"../utils/async-detection\"\nimport { INTEROP_TAG, isInsideTaggedDeclaration } from \"../utils/boundary-tags\"\nimport { compact, NEGATIVE_PREDICATES, POSITIVE_PREDICATES } from \"../utils/functype-predicates\"\n\n/**\n * How each container's fold exposes its failure side. `fold(onFailure, onSuccess)` everywhere, but\n * only Either and Try hand the failure callback a value — Option's `onNone` takes nothing. `member`\n * is the property a narrowed branch reads that value through (`e.value` after `isLeft()`,\n * `t.error` after `isFailure()`).\n */\ntype FailureSide = { readonly param: string; readonly member: string } | null\n\nconst FAILURE_SIDE: Readonly<Record<string, FailureSide>> = {\n isSome: null,\n isNone: null,\n isRight: { param: \"left\", member: \"value\" },\n isLeft: { param: \"left\", member: \"value\" },\n isSuccess: { param: \"error\", member: \"error\" },\n isFailure: { param: \"error\", member: \"error\" },\n}\n\n/** Reads of the success value that the fold's success parameter replaces. */\nconst SUCCESS_METHODS = [\"get\", \"orThrow\"]\nconst SUCCESS_MEMBER = \"value\"\n\n/**\n * A literal `null` or the `undefined` identifier. A ternary that yields one of these in a branch is\n * building an optional value (prefer-option's concern), not folding a monad — so the untyped nullable\n * heuristic must not treat `x !== undefined ? \"a\" : undefined` as a fold candidate.\n */\nfunction isNullishLiteral(node: ASTNode): boolean {\n return (node.type === \"Literal\" && node.value === null) || (node.type === \"Identifier\" && node.name === \"undefined\")\n}\n\n/**\n * If `test` is a monadic predicate call like `option.isSome()` or\n * `either.isLeft()`, returns the receiver expression's text plus whether the\n * predicate is the \"absence\" side. Returns null for anything else.\n */\nfunction extractMonadicTest(\n test: ASTNode,\n sourceCode: SourceCode,\n): { obj: string; isNegated: boolean; failure: FailureSide } | null {\n if (test.type !== \"CallExpression\" || test.callee.type !== \"MemberExpression\") return null\n const methodName = test.callee.property.name\n const obj = sourceCode.getText(test.callee.object)\n const failure = FAILURE_SIDE[methodName] ?? null\n if (POSITIVE_PREDICATES.has(methodName)) return { obj, isNegated: false, failure }\n if (NEGATIVE_PREDICATES.has(methodName)) return { obj, isNegated: true, failure }\n return null\n}\n\n/** Which reads of the narrowed receiver a fold parameter replaces. */\ntype Reads = { readonly members: ReadonlyArray<string>; readonly methods: ReadonlyArray<string> }\n\nconst SUCCESS_READS: Reads = { members: [SUCCESS_MEMBER], methods: SUCCESS_METHODS }\n\n/**\n * Source ranges inside `branch` that read the narrowed receiver: `e.value`, `e!.value`, `e?.value`,\n * `e.orThrow()`. Driven by the AST rather than the text, so a read never matches inside a string or\n * template literal, a comment, a longer name, or another object's member (`other.e.value`). A member\n * that is called (`e.value()`) or assigned (`e.value = 3`) is not a read.\n */\nfunction receiverReads(\n branch: ASTNode,\n receiver: string,\n reads: Reads,\n sourceCode: SourceCode,\n): ReadonlyArray<readonly [number, number]> {\n const isReceiver = (node: ASTNode): boolean => {\n const target = node.type === \"TSNonNullExpression\" ? node.expression : node\n return compact(sourceCode.getText(target)) === compact(receiver)\n }\n const isMember = (node: ASTNode, names: ReadonlyArray<string>): boolean =>\n node.type === \"MemberExpression\" &&\n !node.computed &&\n node.property.type === \"Identifier\" &&\n names.includes(node.property.name) &&\n isReceiver(node.object)\n\n const visit = (node: ASTNode): ReadonlyArray<readonly [number, number]> => {\n const parent = node.parent\n const isCalled = parent?.type === \"CallExpression\" && parent.callee === node\n const isWritten =\n (parent?.type === \"AssignmentExpression\" && parent.left === node) || parent?.type === \"UpdateExpression\"\n if (isMember(node, reads.members) && !isCalled && !isWritten) return [node.range]\n if (node.type === \"CallExpression\" && node.arguments.length === 0 && isMember(node.callee, reads.methods)) {\n return [node.range]\n }\n return childNodes(node).flatMap(visit)\n }\n return visit(branch)\n}\n\n/** A parameter name no branch already uses, so the fold never shadows a captured identifier. */\nconst freshName = (base: string, branches: ReadonlyArray<string>): string => {\n // `(?<![\\\\w$.])`: a property access (`e.value`) is not a free identifier, so it cannot be shadowed.\n const isTaken = (name: string): boolean => branches.some((b) => new RegExp(`(?<![\\\\w$.])${name}(?![\\\\w$])`).test(b))\n const candidates = [base, ...Array.from({ length: 20 }, (_, i) => `${base}${i + 1}`)]\n return candidates.find((name) => !isTaken(name)) ?? `${base}_`\n}\n\n/**\n * An arrow body must not start with `{` (it would parse as a block) and a comma expression must stay\n * one argument, so those two shapes are parenthesized. ESTree ranges exclude the source's own parens.\n */\nconst asArrowBody = (node: ASTNode, text: string): string =>\n node.type === \"ObjectExpression\" || node.type === \"SequenceExpression\" ? `(${text})` : text\n\n/**\n * One fold callback. Reads of the narrowed receiver become reads of the callback's parameter — the\n * receiver is NOT narrowed inside the callback, so leaving `e.value` there is a type error (#323).\n * A branch that never reads the value gets a parameterless callback, not an unused parameter.\n */\nfunction foldCallback(\n branch: ASTNode,\n receiver: string,\n reads: Reads | null,\n param: string,\n sourceCode: SourceCode,\n): string {\n const text = sourceCode.getText(branch)\n const ranges = reads === null ? [] : receiverReads(branch, receiver, reads, sourceCode)\n if (ranges.length === 0) return `() => ${asArrowBody(branch, text)}`\n const offset = branch.range[0]\n // Replace right-to-left so earlier offsets stay valid.\n const rewritten = [...ranges]\n .sort((a, b) => b[0] - a[0])\n .reduce((acc, [start, end]) => acc.slice(0, start - offset) + param + acc.slice(end - offset), text)\n return `(${param}) => ${asArrowBody(branch, rewritten)}`\n}\n\n/** `receiver.fold(onFailure, onSuccess)` from the two branch nodes. */\nfunction buildFold(\n receiver: string,\n failure: FailureSide,\n failureNode: ASTNode,\n successNode: ASTNode,\n sourceCode: SourceCode,\n): string {\n const branches = [sourceCode.getText(failureNode), sourceCode.getText(successNode)]\n const onSuccess = foldCallback(successNode, receiver, SUCCESS_READS, freshName(\"value\", branches), sourceCode)\n const onFailure =\n failure === null\n ? foldCallback(failureNode, receiver, null, \"\", sourceCode)\n : foldCallback(\n failureNode,\n receiver,\n { members: [failure.member], methods: [] },\n freshName(failure.param, branches),\n sourceCode,\n )\n return `${receiver}.fold(${onFailure}, ${onSuccess})`\n}\n\n/** The returned expression of a `return x` statement or a `{ return x }` block; null for anything else. */\nfunction returnedExpression(node: ASTNode): ASTNode | null {\n const statement = node.type === \"BlockStatement\" && node.body.length === 1 ? node.body[0] : node\n return statement.type === \"ReturnStatement\" && statement.argument ? statement.argument : null\n}\n\n/**\n * Length of an if/else-if/else chain rooted at `node`. Counts the root as 1\n * and adds 1 per linked alternate IfStatement. Terminates on a non-If\n * alternate (the final `else { ... }`) which counts as the last branch.\n */\nfunction ifElseChainLength(node: ASTNode): number {\n if (!node.alternate) return 1\n if (node.alternate.type === \"IfStatement\") return 1 + ifElseChainLength(node.alternate as ASTNode)\n return 2 // root + the terminal else\n}\n\n/**\n * What a guard's early exit does, which decides the advice:\n * - `passthrough`: hands the failure back unchanged (`return e`, `return Left(e.value)`, `return None()`),\n * so the rest of the function is a `flatMap`/`map`.\n * - `mappedFailure`: returns a new failure built from the old one (`return Left({ kind: e.value.kind })`),\n * so it's `mapLeft(…)` then `flatMap`.\n * - `default`: returns a plain fallback, so it's `map(…).orElse(fallback)` or a `fold`.\n * - `throw`: a host that needs a throw, so it's `orThrow((e) => …)`.\n * - `effect`: does other work first (logging, setting state), so it's a `fold`.\n */\ntype GuardExit = \"passthrough\" | \"mappedFailure\" | \"default\" | \"throw\" | \"effect\"\n\n/** Constructors (and companion methods) that build a failure: `Left(…)`, `None()`, `Failure(…)`, `Either.left(…)`. */\nconst FAILURE_CONSTRUCTORS: ReadonlySet<string> = new Set([\"Left\", \"None\", \"Failure\", \"left\", \"none\", \"failure\"])\n\n/** Does `node` read `<receiver>.<member>` anywhere inside it? */\nfunction readsMember(node: ASTNode, receiver: string, member: string, sourceCode: SourceCode): boolean {\n return descendants(node).some(\n (n) =>\n n.type === \"MemberExpression\" &&\n !n.computed &&\n n.property.type === \"Identifier\" &&\n n.property.name === member &&\n compact(sourceCode.getText(n.object)) === receiver,\n )\n}\n\n/** The single exit statement of a guard's consequent: `return x` / `throw x`, alone or as a one-statement block. */\nfunction guardExitStatement(consequent: ASTNode): { readonly exit: ASTNode; readonly extraWork: boolean } | null {\n if (consequent.type === \"ReturnStatement\" || consequent.type === \"ThrowStatement\") {\n return { exit: consequent, extraWork: false }\n }\n if (consequent.type !== \"BlockStatement\" || consequent.body.length === 0) return null\n const last = consequent.body[consequent.body.length - 1] as ASTNode\n if (last.type !== \"ReturnStatement\" && last.type !== \"ThrowStatement\") return null\n return { exit: last, extraWork: consequent.body.length > 1 }\n}\n\n/**\n * `receiver` is the compacted receiver text; `failureMember` is where the failure value lives once\n * narrowed (`value` for Either, `error` for Try, null for Option, whose None carries nothing).\n */\nfunction classifyGuardExit(\n consequent: ASTNode,\n receiver: string,\n failureMember: string | null,\n sourceCode: SourceCode,\n): GuardExit | null {\n const found = guardExitStatement(consequent)\n if (!found) return null\n if (found.exit.type === \"ThrowStatement\") return \"throw\"\n if (found.extraWork) return \"effect\"\n const argument = found.exit.argument as ASTNode | null\n if (!argument) return \"effect\"\n if (compact(sourceCode.getText(argument)) === receiver) return \"passthrough\"\n const callee = argument.type === \"CallExpression\" ? (argument.callee as ASTNode) : null\n const calleeName =\n callee?.type === \"Identifier\"\n ? callee.name\n : callee?.type === \"MemberExpression\" && callee.property.type === \"Identifier\"\n ? callee.property.name\n : null\n if (calleeName && FAILURE_CONSTRUCTORS.has(calleeName)) {\n const args = (argument.arguments ?? []) as ReadonlyArray<ASTNode>\n const unchanged =\n args.length === 0 ||\n (args.length === 1 &&\n failureMember !== null &&\n compact(sourceCode.getText(args[0])) === `${receiver}.${failureMember}`)\n return unchanged ? \"passthrough\" : \"mappedFailure\"\n }\n // A fallback built from the failure (`c.json({ error: r.value }, 500)`) can only be written as a fold:\n // outside the guard the failure isn't narrowed, so `map(…).orElse(…)` couldn't read it.\n if (failureMember !== null && readsMember(argument, receiver, failureMember, sourceCode)) return \"effect\"\n return \"default\"\n}\n\n/**\n * Does `statements` unwrap `receiver` the imperative way — `receiver.value`, `.orThrow()`, `.get()`?\n * Reads through `map`, `flatMap`, `fold`, `orElse`… are already the functional form and don't count.\n */\nfunction unwrapsReceiver(statements: ReadonlyArray<ASTNode>, receiver: string, sourceCode: SourceCode): boolean {\n const nodes = statements.flatMap((statement) => descendants(statement))\n // `e = next()` after the guard: later reads are of a different value, which the guard didn't check.\n const reassigned = nodes.some(\n (node) => node.type === \"AssignmentExpression\" && compact(sourceCode.getText(node.left)) === receiver,\n )\n if (reassigned) return false\n return nodes.some((node) => {\n if (node.type !== \"MemberExpression\" || compact(sourceCode.getText(node.object)) !== receiver) return false\n const name = node.property.type === \"Identifier\" ? node.property.name : null\n if (name === SUCCESS_MEMBER) return true\n const parent = node.parent as ASTNode | undefined\n if (name === null || !SUCCESS_METHODS.includes(name)) return false\n if (parent?.type !== \"CallExpression\" || parent.callee !== node) return false\n // `orThrow(error)` / `orThrow((e) => …)` names its error: no-get-unsafe treats that as a deliberate\n // host throw, so this rule doesn't count it as an unwrap either.\n return !(name === \"orThrow\" && (parent.arguments as ReadonlyArray<ASTNode>).length > 0)\n })\n}\n\n/** An exit-only negative guard (`if (e.isLeft()) return …`) on a functype predicate, or null. */\nfunction guardOf(node: ASTNode, sourceCode: SourceCode): ReturnType<typeof extractMonadicTest> {\n if (node.type !== \"IfStatement\" || node.alternate) return null\n const extracted = extractMonadicTest(node.test, sourceCode)\n if (!extracted?.isNegated || !guardExitStatement(node.consequent)) return null\n return extracted\n}\n\nconst rule: Rule.RuleModule = {\n meta: {\n type: \"suggestion\",\n docs: {\n description: \"Prefer .fold() over if/else chains when working with monadic types\",\n recommended: true,\n },\n // Suggestions, never an autofix (#323): `ts-builds validate` runs `eslint --fix`, which applies\n // fixable rules at warn severity too, and a fold rewrite cannot be proven type-correct without type\n // information. The developer applies it, and the compiler checks it.\n hasSuggestions: true,\n schema: [\n {\n type: \"object\",\n properties: {\n allowInteropMarker: {\n type: \"boolean\",\n default: true,\n },\n minComplexity: {\n type: \"integer\",\n minimum: 1,\n default: 2,\n },\n checkNullable: {\n type: \"boolean\",\n default: false,\n },\n checkGuards: {\n type: \"boolean\",\n default: false,\n },\n },\n additionalProperties: false,\n },\n ],\n messages: {\n preferFold: \"Prefer .fold() over if/else when working with {{type}} types\",\n preferFoldTernary: \"Consider using .fold() instead of ternary operator for {{type}}\",\n preferFoldGuard:\n \"{{receiver}} is checked with an early exit and then unwrapped. {{advice}} Branching first and unwrapping after is the imperative form.\",\n suggestFold: \"Replace with .fold()\",\n suggestOr:\n \"Replace with {{receiver}}.or({{alternative}}) — keep the first when it is present, else the alternative\",\n },\n },\n\n create(context) {\n const options = context.options[0] || {}\n // `@interop <reason>` on an enclosing declaration marks a host-contract boundary (#241).\n const allowInteropMarker = options.allowInteropMarker !== false\n const isExemptByMarker = (node: ASTNode): boolean =>\n allowInteropMarker && isInsideTaggedDeclaration(node, INTEROP_TAG, context.sourceCode)\n const minComplexity = options.minComplexity || 2\n // Off by default (#325): a null check on a plain value (`x === null ? a : b`) is not a fold of a\n // functype value. Whether that value should be an Option is prefer-option's call, and at error this\n // path fired on JSX conditionals, style objects and conditional spreads (31 of 31 hits in CivalaOS,\n // 0 of which were functype values). Predicate calls (`o.isSome()`, `e.isLeft()`) are always checked.\n const checkNullable = options.checkNullable === true\n // Guard-then-unwrap (`if (e.isLeft()) return …; use(e.value)`). Opt-in while it's measured on real\n // code: prefer-fold is `error` in recommended, so turning this on by default would fail builds.\n const checkGuards = options.checkGuards === true\n\n const SEQUENCE_ADVICE = (isAsync: boolean): string =>\n isAsync\n ? \"Several guards in a row pass their failures through: sequence them with DoAsync(async function* () { const a = yield* $(await …) … }).\"\n : \"Several guards in a row pass their failures through: sequence them with Do(function* () { const a = yield* $(…); const b = yield* $(…); return … }).\"\n\n const GUARD_ADVICE: Readonly<Record<GuardExit, (receiver: string, isAsync: boolean) => string>> = {\n passthrough: (r, isAsync) =>\n isAsync\n ? `Keep it in the chain: ${r}.flatMapAsync(…), or lift the steps into IO.`\n : `Keep it in the chain: ${r}.flatMap(…) or ${r}.map(…); the failure passes through on its own.`,\n mappedFailure: (r, isAsync) =>\n `Keep it in the chain: ${r}.mapLeft(…).${isAsync ? \"flatMapAsync\" : \"flatMap\"}(…) builds the new failure and continues on success.`,\n default: (r) => `Use ${r}.map(…).orElse(fallback), or ${r}.fold(() => fallback, (value) => …).`,\n throw: (r) =>\n `If a host needs the throw, use ${r}.orThrow((e) => new YourError(e)); otherwise keep it in the chain with .flatMap or .fold.`,\n effect: (r, isAsync) =>\n isAsync ? `Use ${r}.foldAsync(onFailure, onSuccess).` : `Use ${r}.fold(onFailure, onSuccess).`,\n }\n\n /**\n * `if (e.isLeft()) return …` followed, in the same block, by reads of `e.value` / `e.orThrow()`.\n * `orElse` and `fold` are never flagged: both are proper ways to leave the container.\n */\n function checkGuard(node: ASTNode): void {\n if (!checkGuards) return\n const sourceCode = context.sourceCode\n const extracted = guardOf(node, sourceCode)\n if (!extracted) return\n const block = node.parent as ASTNode | undefined\n if (block?.type !== \"BlockStatement\" && block?.type !== \"Program\") return\n const body = block.body as ReadonlyArray<ASTNode>\n const after = body.slice(body.indexOf(node) + 1)\n const receiver = compact(extracted.obj)\n if (!unwrapsReceiver(after, receiver, sourceCode)) return\n const exit = classifyGuardExit(node.consequent, receiver, extracted.failure?.member ?? null, sourceCode)\n if (!exit) return\n const isAsync = after.some((statement) => containsAwait(statement))\n // Two or more pass-through guards in one block, each unwrapped later: nested flatMaps would be worse\n // than the guards, so the advice is a Do comprehension.\n const passThrough = (candidate: ASTNode): boolean => {\n const other = guardOf(candidate, sourceCode)\n if (!other) return false\n const otherReceiver = compact(other.obj)\n const otherAfter = body.slice(body.indexOf(candidate) + 1)\n const kind = classifyGuardExit(candidate.consequent, otherReceiver, other.failure?.member ?? null, sourceCode)\n return (\n (kind === \"passthrough\" || kind === \"mappedFailure\") && unwrapsReceiver(otherAfter, otherReceiver, sourceCode)\n )\n }\n const sequenced = (exit === \"passthrough\" || exit === \"mappedFailure\") && body.filter(passThrough).length > 1\n context.report({\n node,\n messageId: \"preferFoldGuard\",\n data: {\n receiver: extracted.obj,\n advice: sequenced ? SEQUENCE_ADVICE(isAsync) : GUARD_ADVICE[exit](extracted.obj, isAsync),\n },\n })\n }\n\n function generateFoldFromIf(node: ASTNode): string | null {\n const sourceCode = context.sourceCode\n if (node.type !== \"IfStatement\" || !node.alternate) return null\n\n const extracted = extractMonadicTest(node.test, sourceCode)\n if (!extracted) return null\n\n // Only if/else where both branches return a value — the fold then replaces the whole statement\n // as `return receiver.fold(...)`. Anything else (side effects, nested else-if) is left alone.\n const thenExpr = returnedExpression(node.consequent)\n const elseExpr = returnedExpression(node.alternate)\n if (!thenExpr || !elseExpr) return null\n\n // The suggestion keeps only the test and the two returned values; a comment anywhere else in the\n // statement would be silently dropped, so none is offered.\n const kept = [node.test, thenExpr, elseExpr]\n const within = (c: { range?: [number, number] }): boolean =>\n c.range !== undefined && kept.some((n) => c.range![0] >= n.range[0] && c.range![1] <= n.range[1])\n if (!sourceCode.getCommentsInside(node).every(within)) return null\n\n const { obj, isNegated, failure } = extracted\n const [failureExpr, successExpr] = isNegated ? [thenExpr, elseExpr] : [elseExpr, thenExpr]\n return `return ${buildFold(obj, failure, failureExpr, successExpr, sourceCode)}`\n }\n\n function ternarySuggestions(node: ASTNode): Rule.SuggestionReportDescriptor[] {\n const sourceCode = context.sourceCode\n const extracted = extractMonadicTest(node.test, sourceCode)\n if (!extracted) return []\n\n const { obj, isNegated, failure } = extracted\n const [failureNode, successNode] = isNegated\n ? [node.consequent, node.alternate]\n : [node.alternate, node.consequent]\n const failureText = sourceCode.getText(failureNode)\n const successText = sourceCode.getText(successNode)\n\n // `a.isSome() ? a : b` keeps the container when present and falls back otherwise — that is `.or`,\n // and a fold would only rebuild it with an unused parameter. `.or` takes a container, so a literal\n // or `undefined` fallback gets no suggestion at all: neither `.or(5)` nor a fold mixing a container\n // with a plain value would type-check.\n if (compact(successText) === compact(obj)) {\n if (failureNode.type === \"Literal\" || failureNode.type === \"TemplateLiteral\" || isNullishLiteral(failureNode)) {\n return []\n }\n return [\n {\n messageId: \"suggestOr\",\n data: { receiver: obj, alternative: failureText },\n fix: (fixer) => fixer.replaceText(node, `${obj}.or(${failureText})`),\n },\n ]\n }\n\n const fold = buildFold(obj, failure, failureNode, successNode, sourceCode)\n return [{ messageId: \"suggestFold\", fix: (fixer) => fixer.replaceText(node, fold) }]\n }\n\n function isFunctypePredicateCall(node: ASTNode): boolean {\n // Suggest a rewrite only when the test is a functype predicate call (the receiver is a functype value)\n if (node.type === \"CallExpression\" && node.callee.type === \"MemberExpression\") {\n const methodName = node.callee.property.name\n // These methods indicate the object is already a functype instance\n return [\"isSome\", \"isNone\", \"isRight\", \"isLeft\", \"isSuccess\", \"isFailure\"].includes(methodName)\n }\n return false\n }\n\n // `via` records HOW we matched: a functype predicate call (`method`, precise) vs the untyped\n // null/undefined heuristic (`nullable`, a guess that can't tell a real Option from a plain nullable).\n function isMonadicCheck(node: ASTNode): { isMonadic: boolean; type: string; via: \"method\" | \"nullable\" | \"\" } {\n const sourceCode = context.sourceCode\n const text = sourceCode.getText(node)\n\n // Check for common monadic type checks\n if (/\\.(isSome|isNone|isDefined)\\s*\\(\\s*\\)/.test(text)) {\n return { isMonadic: true, type: \"Option\", via: \"method\" }\n }\n\n if (/\\.(isLeft|isRight)\\s*\\(\\s*\\)/.test(text)) {\n return { isMonadic: true, type: \"Either\", via: \"method\" }\n }\n\n if (/\\.(isSuccess|isFailure)\\s*\\(\\s*\\)/.test(text)) {\n return { isMonadic: true, type: \"Result\", via: \"method\" }\n }\n\n // Check for null/undefined checks on variables that might be Options\n if (checkNullable && node.type === \"BinaryExpression\") {\n if (\n (node.operator === \"===\" || node.operator === \"!==\" || node.operator === \"==\" || node.operator === \"!=\") &&\n ((node.left.type === \"Literal\" && (node.left.value === null || node.left.value === undefined)) ||\n (node.right.type === \"Literal\" && (node.right.value === null || node.right.value === undefined)))\n ) {\n return { isMonadic: true, type: \"Option\", via: \"nullable\" }\n }\n\n // Check for === or == with undefined identifier\n if (node.operator === \"==\" || node.operator === \"!=\" || node.operator === \"===\" || node.operator === \"!==\") {\n const leftIsUndefined = node.left.type === \"Identifier\" && node.left.name === \"undefined\"\n const rightIsUndefined = node.right.type === \"Identifier\" && node.right.name === \"undefined\"\n\n if (leftIsUndefined || rightIsUndefined) {\n return { isMonadic: true, type: \"Option\", via: \"nullable\" }\n }\n }\n }\n\n return { isMonadic: false, type: \"\", via: \"\" }\n }\n\n function suggestionsForIf(node: ASTNode): Rule.SuggestionReportDescriptor[] {\n if (!isFunctypePredicateCall(node.test)) return []\n const replacement = generateFoldFromIf(node)\n return replacement ? [{ messageId: \"suggestFold\", fix: (fixer) => fixer.replaceText(node, replacement) }] : []\n }\n\n function analyzeIfStatement(node: ASTNode) {\n const test = node.test\n const monadicInfo = isMonadicCheck(test)\n\n if (!monadicInfo.isMonadic) return\n\n // Don't analyze if this is part of a larger if/else chain\n // (only analyze the outermost if statement)\n if (node.parent && node.parent.type === \"IfStatement\") return\n\n // Count the complexity (if/else if/else chain)\n if (ifElseChainLength(node) >= minComplexity) {\n context.report({\n node,\n messageId: \"preferFold\",\n data: { type: monadicInfo.type },\n suggest: suggestionsForIf(node),\n })\n }\n }\n\n return {\n IfStatement(node: ASTNode) {\n if (isExemptByMarker(node)) return\n analyzeIfStatement(node)\n checkGuard(node)\n },\n\n ConditionalExpression(node: ASTNode) {\n if (isExemptByMarker(node)) return\n const monadicInfo = isMonadicCheck(node.test)\n // The untyped nullable heuristic can't distinguish a real Option from a plain nullable primitive.\n // When it fires on a ternary that yields `undefined`/`null` in a branch, that's optional value\n // construction (prefer-option's concern), not a fold — skip it. False positive this kills:\n // `x !== undefined ? \"a\" : undefined`. Predicate-call matches (`.isSome()` etc.) are unaffected.\n if (monadicInfo.via === \"nullable\" && (isNullishLiteral(node.consequent) || isNullishLiteral(node.alternate))) {\n return\n }\n if (monadicInfo.isMonadic) {\n context.report({\n node,\n messageId: \"preferFoldTernary\",\n data: { type: monadicInfo.type },\n suggest: isFunctypePredicateCall(node.test) ? ternarySuggestions(node) : [],\n })\n }\n },\n }\n },\n}\n\nexport default rule\n"],"mappings":"iTAgBA,MAAMA,EAAsD,CAC1D,OAAQ,KACR,OAAQ,KACR,QAAS,CAAE,MAAO,OAAQ,OAAQ,OAAQ,EAC1C,OAAQ,CAAE,MAAO,OAAQ,OAAQ,OAAQ,EACzC,UAAW,CAAE,MAAO,QAAS,OAAQ,OAAQ,EAC7C,UAAW,CAAE,MAAO,QAAS,OAAQ,OAAQ,CAC/C,EAGMC,EAAkB,CAAC,MAAO,SAAS,EACnCC,EAAiB,QAOvB,SAASC,EAAiB,EAAwB,CAChD,OAAQC,EAAK,OAAS,WAAaA,EAAK,QAAU,MAAUA,EAAK,OAAS,cAAgBA,EAAK,OAAS,WAC1G,CAOA,SAASC,EACP,EACA,EACkE,CAClE,GAAIC,EAAK,OAAS,kBAAoBA,EAAK,OAAO,OAAS,mBAAoB,OAAO,KACtF,IAAMC,EAAaD,EAAK,OAAO,SAAS,KAClCE,EAAMC,EAAW,QAAQH,EAAK,OAAO,MAAM,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UAAW,oBACX,KAAM,CAAE,KAAM2C,EAAY,IAAK,EAC/B,QAASP,EAAwB3G,EAAK,IAAI,EAAIsG,EAAmBtG,CAAI,EAAI,CAAC,CAC5E,CAAC,CAEL,CACF,CACF,CACF"}
|
|
@@ -1,3 +1,3 @@
|
|
|
1
|
-
import{
|
|
2
|
-
`);if(/@generated|auto-generated|do not edit/i.test(f)||A(u.sourceCode.ast))return{};let y=u.options[0]||{},k=y.wireTypes??l,M=y.allowArraysInTests!==!1,N=y.allowReadonlyArrays!==!1,P=y.allowArrayLiterals===!0,F=a(u);function I(){let e=u.filename;return/\.(test|spec)\.(ts|js|tsx|jsx)$/.test(e)||e.includes(`__tests__`)||e.includes(`/test/`)||e.includes(`/tests/`)}function L(e,t){function n(e){return e.type===`TSTypeParameterInstantiation`&&e.params&&e.params[0]?t.getText(e.params[0]):p(e).filter(e=>typeof e?.type==`string`).map(e=>n(e)).find(e=>e!==null)??null}return n(e)}function R(e,t){return t?.type===`CallExpression`&&t.callee.type===`Identifier`&&F.has(t.callee.name)&&t.arguments.includes(e)}function z(
|
|
1
|
+
import{descendants as e}from"../utils/ast-walk.js";import{flowsIntoArraySlot as t,flowsIntoMutableArraySlot as n,hasTypeInformation as r,isUntypedExpression as i}from"../utils/type-aware.js";import{getFunctypeImportsLegacy as a,isFunctypeCall as o}from"../utils/functype-detection.js";import{createImportFixer as s,hasFunctypeSymbol as c}from"../utils/import-fixer.js";import{DEFAULT_WIRE_TYPES as l,WIRE_TYPES_SCHEMA as u,isInsideWireType as d}from"../utils/wire-types.js";const f=/* @__PURE__ */ new Set([`parent`,`loc`,`range`]);function p(e){return Object.entries(e).filter(([e])=>!f.has(e)).flatMap(([,e])=>Array.isArray(e)?e:[e]).filter(e=>typeof e==`object`&&!!e)}function m(e,t){let n=e?.parent;return n?t(n)||m(n,t):!1}function h(e){return e?.type===`CallExpression`&&e.callee.type===`MemberExpression`&&e.callee.object.type===`Identifier`&&e.callee.object.name===`List`&&[`from`,`of`].includes(e.callee.property.name)}function g(e){let t=e?.type===`TSAsExpression`?e.typeAnnotation:void 0,n=t?.type===`TSTypeOperator`?t.typeAnnotation:t;return n?.type===`TSTupleType`||n?.type===`TSTypeReference`&&n.typeName?.type===`Identifier`&&n.typeName.name===`const`}const _=/* @__PURE__ */ new Set([`push`,`pop`,`shift`,`unshift`,`splice`,`sort`,`reverse`,`fill`,`copyWithin`]);function v(e){let t=e.parent;return t?.type===`ConditionalExpression`&&t.test!==e||t?.type===`LogicalExpression`?v(t):e}const y=/* @__PURE__ */ new Set([`join`,`includes`,`indexOf`,`lastIndexOf`,`some`,`every`,`find`,`findIndex`,`findLast`,`findLastIndex`,`at`]);function b(e){let t=e.parent,n=t?.parent;return t?.type!==`MemberExpression`||t.object!==e?e:n?.type===`CallExpression`&&n.callee===t?b(n):e}function x(e){if(C(e))return!0;let t=e.parent,n=t?.parent;return t?.type!==`MemberExpression`||t.object!==e?!1:n?.type===`CallExpression`&&n.callee===t&&x(n)}function S(e){return e.parent?.type===`JSXExpressionContainer`}function C(e){let t=e.parent;if(t?.type!==`MemberExpression`||t.object!==e)return!1;let n=t.parent;if(n?.type===`AssignmentExpression`&&n.left===t)return!1;if(t.computed)return!0;let r=t.property?.type===`Identifier`?t.property.name:null;return r===`length`||r!==null&&y.has(r)&&n?.type===`CallExpression`&&n.callee===t}function w(e){let t=e.parent;return t?t.type===`ConditionalExpression`&&t.test!==e||t.type===`LogicalExpression`&&t.right===e?w(t):t.type===`SpreadElement`&&(t.parent?.type===`CallExpression`||t.parent?.type===`NewExpression`):!1}function T(e){let t=e=>e?e.type===`TSTypeAnnotation`?e.parent?.type===`Identifier`?e.parent:null:e.type===`TSAsExpression`||e.type===`TSSatisfiesExpression`||e.type.endsWith(`Statement`)?null:t(e.parent):null;return t(e.parent)}function E(e){let t=e.parent,n=t?.type===`TSTypeAnnotation`?t.parent:void 0;if(!n||n.returnType!==t)return null;if(n.type===`FunctionDeclaration`)return n.id?.type===`Identifier`?n.id:null;let r=n.parent;return(n.type===`ArrowFunctionExpression`||n.type===`FunctionExpression`)&&r?.type===`VariableDeclarator`&&r.init===n&&r.id?.type===`Identifier`?r.id:null}function D(e){let t=e.parent,n=t?.type===`TSTypeAnnotation`?t.parent:void 0;return n?.type!==`TSPropertySignature`&&n?.type!==`PropertyDefinition`?null:n.key?.type===`Identifier`&&!n.computed?n.key.name:null}function O(e){let t=(e,n)=>{if(!e||e.type===`TSTypeAnnotation`||e.type.endsWith(`Statement`))return null;if(e.type===`TSAsExpression`&&e.typeAnnotation===n){let t=e=>e.parent?.type===`TSAsExpression`?t(e.parent):e;return t(e)}return t(e.parent,e)};return t(e.parent,e)}function k(e){let t=e.type===`ExportNamedDeclaration`?e.declaration:null;if(t?.type===`TSTypeAliasDeclaration`||t?.type===`TSInterfaceDeclaration`)return t.id?.name}function A(e){let t=new Set(e.body.map(k));return t.has(`Json`)&&t.has(`Database`)}function j(e){return e.type===`VariableDeclarator`&&!!e.id?.typeAnnotation||e.type===`TSTypeAnnotation`}const M={meta:{type:`suggestion`,hasSuggestions:!0,docs:{description:`Prefer List<T> over native arrays for immutable collections`,recommended:!0},schema:[{type:`object`,properties:{allowArraysInTests:{type:`boolean`,default:!0},wireTypes:u,allowReadonlyArrays:{type:`boolean`,default:!0},allowArrayLiterals:{type:`boolean`,default:!1}},additionalProperties:!1}],messages:{preferList:`Prefer List<{{type}}> over array type {{arrayType}}`,preferReadonlyOrList:`Mutable array type {{arrayType}}: anything holding it can change it. Use ReadonlyArray<{{type}}>, which every caller and library accepts, or List<{{type}}> for a collection you transform`,preferWireCast:`Cast to the mutable array {{arrayType}}: this is data decoded from outside. Declare its shape once as Wire<ReadonlyArray<{{type}}>> (functype's boundary marker) and cast to that`,mutatedArray:`{{name}} is a mutable array changed in place (.{{how}}()). Build it without mutation instead: map/filter/flatMap, a List, or a fold`,preferListLiteral:`Prefer List.of(...) or List.from([...]) over array literal`,suggestListType:`Replace with List<{{type}}>`,suggestReadonlyArray:`Replace with ReadonlyArray<{{type}}>`,suggestListOf:`Replace with List.of(...)`,suggestAddImport:`Add {{symbol}} import from functype`}},create(u){let f=u.sourceCode.getAllComments().slice(0,3).map(e=>e.value).join(`
|
|
2
|
+
`);if(/@generated|auto-generated|do not edit/i.test(f)||A(u.sourceCode.ast))return{};let y=u.options[0]||{},k=y.wireTypes??l,M=y.allowArraysInTests!==!1,N=y.allowReadonlyArrays!==!1,P=y.allowArrayLiterals===!0,F=a(u);function I(){let e=u.filename;return/\.(test|spec)\.(ts|js|tsx|jsx)$/.test(e)||e.includes(`__tests__`)||e.includes(`/test/`)||e.includes(`/tests/`)}function L(e,t){function n(e){return e.type===`TSTypeParameterInstantiation`&&e.params&&e.params[0]?t.getText(e.params[0]):p(e).filter(e=>typeof e?.type==`string`).map(e=>n(e)).find(e=>e!==null)??null}return n(e)}function R(e,t){return t?.type===`CallExpression`&&t.callee.type===`Identifier`&&F.has(t.callee.name)&&t.arguments.includes(e)}function z(e){if(t(e,u)===!0||w(e))return!0;let n=e.parent;return n?.type===`SpreadElement`&&n.parent?.type===`ArrayExpression`&&t(n.parent,u)===!0}function B(e){if(e?.type!==`VariableDeclarator`||e.id?.type!==`Identifier`)return!1;let t=u.sourceCode.getDeclaredVariables(e).flatMap(e=>e.references.filter(e=>!e.init));return t.length>0&&t.every(e=>z(e.identifier)||C(e.identifier))}function V(e){let t=e.parent??e;return((u.sourceCode.getDeclaredVariables(t).find(t=>t.name===e.name)??u.sourceCode.getScope(e).set.get(e.name))?.references??[]).filter(t=>!t.init&&t.identifier!==e).map(e=>({identifier:e.identifier}))}function H(e){return V(e).map(({identifier:e})=>{let t=e.parent;if(t?.type!==`MemberExpression`||t.object!==e)return null;let n=t.parent;if(n?.type===`AssignmentExpression`&&n.left===t)return`[index] =`;let r=t.property?.type===`Identifier`&&!t.computed?t.property.name:null;return r&&_.has(r)&&n?.type===`CallExpression`&&n.callee===t?r:null}).find(e=>e!==null)??null}let U={};function W(t){if(!U.map){let t=e(u.sourceCode.ast).flatMap(e=>{if(e.type!==`CallExpression`||e.callee?.type!==`MemberExpression`)return[];let t=e.callee.property?.type===`Identifier`?e.callee.property.name:null,n=e.callee.object,r=n?.type===`MemberExpression`&&n.property?.type===`Identifier`&&!n.computed?n.property.name:null;return t&&r&&_.has(t)?[[r,t]]:[]});U.map=new globalThis.Map(t.reverse())}return U.map.get(t)??null}function G(e){return V(e).some(({identifier:e})=>n(e,u)===!0)}function K(e,t,r){let a=O(e),o=e=>e.type===`TSAsExpression`?o(e.expression):e;if(a&&n(a,u)===!0)return;let s=a?o(a):null,c=s!==null&&s.type!==`ArrayExpression`&&i(s,u)===!0;if(a&&c){u.report({node:e,messageId:`preferWireCast`,data:{type:t,arrayType:r},suggest:[{messageId:`suggestReadonlyArray`,data:{type:t},fix:n=>n.replaceText(e,`ReadonlyArray<${t}>`)}]});return}let l=E(e);if(l!==null&&V(l).some(({identifier:e})=>{let t=e.parent;return t?.type===`CallExpression`&&t.callee===e&&n(t,u)===!0}))return;let d=D(e),f=d===null?null:W(d);if(d!==null&&f!==null){u.report({node:e,messageId:`mutatedArray`,data:{name:d,how:f}});return}let p=T(e);if(p){if(G(p))return;let t=H(p);if(t){u.report({node:e,messageId:`mutatedArray`,data:{name:p.name,how:t}});return}}q(e,t,r)}function q(e,t,n){let r=u.sourceCode,i=[{messageId:`suggestReadonlyArray`,data:{type:t},fix:n=>n.replaceText(e,`ReadonlyArray<${t}>`)},{messageId:`suggestListType`,data:{type:t},fix:n=>n.replaceText(e,`List<${t}>`)}];c(r,`List`)||i.push({messageId:`suggestAddImport`,data:{symbol:`List`},fix:s(r,`List`)}),u.report({node:e,messageId:`preferReadonlyOrList`,data:{type:t,arrayType:n},suggest:i})}return{TSArrayType(e){if(d(e,k)||M&&I())return;let t=e.parent;if(t?.type===`TSRestType`||t?.type===`TSTypeAnnotation`&&t.parent?.type===`RestElement`)return;let n=t?.type===`TSTypeOperator`&&t.operator===`readonly`;if(n&&N)return;let r=u.sourceCode,i=r.getText(e.elementType),a=n?t:e,o=r.getText(a);if(!n){K(a,i,o);return}let l=[{messageId:`suggestListType`,data:{type:i},fix(e){return e.replaceText(a,`List<${i}>`)}}];c(r,`List`)||l.push({messageId:`suggestAddImport`,data:{symbol:`List`},fix:s(r,`List`)}),u.report({node:a,messageId:`preferList`,data:{type:i,arrayType:o},suggest:l})},TSTypeReference(e){if(d(e,k)||M&&I())return;let t=u.sourceCode;if(!e.typeName)return;let n=e.typeName.type===`Identifier`?e.typeName.name:t.getText(e.typeName);if(n===`Array`){K(e,L(e,t)||`T`,t.getText(e));return}if(n===`ReadonlyArray`){if(N)return;let n=L(e,t),r=t.getText(e),i=n||`T`,a=[{messageId:`suggestListType`,data:{type:i},fix(t){return t.replaceText(e,`List<${i}>`)}}];c(t,`List`)||a.push({messageId:`suggestAddImport`,data:{symbol:`List`},fix:s(t,`List`)}),u.report({node:e,messageId:`preferList`,data:{type:i,arrayType:r},suggest:a})}},ArrayExpression(e){if(M&&I()||P||e.elements.length===0)return;let n=e.parent;if(n&&o(n,F)||h(n)||m(e,e=>e.type===`ArrayExpression`)||m(e,j))return;let i=v(e),a=i.parent;if(g(n)||t(e,u)===!0||t(i,u)===!0||R(i,a)||x(e)||x(i))return;let l=b(i);if(l!==i&&(S(l)||t(l,u)===!0)||w(e))return;if(a?.type===`VariableDeclarator`&&a.id?.type===`Identifier`){let t=H(a.id);if(t){u.report({node:e,messageId:`mutatedArray`,data:{name:a.id.name,how:t}});return}}if(!r(u)||B(a))return;if(e.elements.some(e=>e!==null&&e.type===`SpreadElement`)){u.report({node:e,messageId:`preferListLiteral`});return}let d=u.sourceCode,f=e.elements.filter(e=>e!==null).map(e=>d.getText(e)),p=[{messageId:`suggestListOf`,fix(t){return t.replaceText(e,`List.of(${f.join(`, `)})`)}}];c(d,`List`)||p.push({messageId:`suggestAddImport`,data:{symbol:`List`},fix:s(d,`List`)}),u.report({node:e,messageId:`preferListLiteral`,suggest:p})}}}};export{M as default};
|
|
3
3
|
//# sourceMappingURL=prefer-list.js.map
|
|
@@ -0,0 +1,40 @@
|
|
|
1
|
+
import { ASTNode } from "../types/ast.js";
|
|
2
|
+
import { SourceCode } from "eslint";
|
|
3
|
+
//#region src/utils/functype-predicates.d.ts
|
|
4
|
+
/** Methods on a monadic value that mean "this is the Some/Right/Success path." */
|
|
5
|
+
export declare const POSITIVE_PREDICATES: ReadonlySet<string>;
|
|
6
|
+
/** Methods that mean "this is the None/Left/Failure path." */
|
|
7
|
+
export declare const NEGATIVE_PREDICATES: ReadonlySet<string>;
|
|
8
|
+
/** Source text with all whitespace removed — receivers match however they are line-broken. */
|
|
9
|
+
export declare const compact: (text: string) => string;
|
|
10
|
+
/** A functype predicate call such as `o.isSome()`, split into its receiver and method. */
|
|
11
|
+
export type PredicateCall = {
|
|
12
|
+
readonly receiver: ASTNode;
|
|
13
|
+
/** The receiver's source text, whitespace removed, for matching against other reads of it. */
|
|
14
|
+
readonly receiverText: string;
|
|
15
|
+
readonly method: string;
|
|
16
|
+
readonly isNegated: boolean;
|
|
17
|
+
};
|
|
18
|
+
/**
|
|
19
|
+
* `o.isSome()`, `e.isLeft()`, `t.isFailure()` — a zero-argument call of a functype predicate method.
|
|
20
|
+
* A property read (`state.isPending`, `items.isEmpty`) is not a call, so it never matches.
|
|
21
|
+
*/
|
|
22
|
+
export declare const predicateCall: (node: ASTNode, sourceCode: SourceCode) => PredicateCall | null;
|
|
23
|
+
/**
|
|
24
|
+
* The first predicate call a test branches on, looking through `!` (which flips it) and `&&` / `||`:
|
|
25
|
+
* `o.isSome()`, `!o.isSome()`, `loading || o.isNone()`. `isNegated` is the predicate's own meaning
|
|
26
|
+
* with any `!` applied, so `!o.isSome()` reads like `o.isNone()`.
|
|
27
|
+
*/
|
|
28
|
+
export declare const testedPredicate: (test: ASTNode, sourceCode: SourceCode) => PredicateCall | null;
|
|
29
|
+
/** What a test proves about a receiver's value: there, missing, or nothing. */
|
|
30
|
+
export type Presence = "present" | "absent" | null;
|
|
31
|
+
/**
|
|
32
|
+
* What `test` evaluating to `outcome` proves about `receiverText`. Looks through `!`, `&&` and `||`:
|
|
33
|
+
* `a && b` being true proves whatever either side proves, `a || b` being false likewise, and the other
|
|
34
|
+
* two cases prove something only when both sides agree. `o.isEmpty` counts as a test for absence.
|
|
35
|
+
*/
|
|
36
|
+
export declare const provesWhen: (test: ASTNode, outcome: boolean, receiverText: string, sourceCode: SourceCode) => Presence;
|
|
37
|
+
/** The functype-react component that renders both cases of the container a predicate belongs to. */
|
|
38
|
+
export declare const MATCH_COMPONENT: Readonly<Record<string, string>>;
|
|
39
|
+
//#endregion
|
|
40
|
+
//# sourceMappingURL=functype-predicates.d.ts.map
|
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
const e=/* @__PURE__ */ new Set([`isSome`,`isRight`,`isSuccess`]),t=/* @__PURE__ */ new Set([`isNone`,`isLeft`,`isFailure`]),n=e=>e.replace(/\s+/g,``),r=(r,i)=>{if(r?.type!==`CallExpression`||r.arguments.length!==0)return null;let a=r.callee;if(a.type!==`MemberExpression`||a.computed||a.property.type!==`Identifier`)return null;let o=a.property.name,s=t.has(o);return!s&&!e.has(o)?null:{receiver:a.object,receiverText:n(i.getText(a.object)),method:o,isNegated:s}},i=(e,t)=>{if(e?.type===`UnaryExpression`&&e.operator===`!`){let n=i(e.argument,t);return n===null?null:{...n,isNegated:!n.isNegated}}return e?.type===`LogicalExpression`&&(e.operator===`&&`||e.operator===`||`)?i(e.left,t)??i(e.right,t):r(e,t)},a=(e,t,r)=>e?.type===`MemberExpression`&&!e.computed&&e.property.type===`Identifier`&&e.property.name===`isEmpty`&&(e.parent?.type!==`CallExpression`||e.parent.callee!==e)&&n(r.getText(e.object))===t,o=(e,t,n,i)=>{let s=(e,t)=>o(e,t,n,i);if(e?.type===`UnaryExpression`&&e.operator===`!`)return s(e.argument,!t);if(e?.type===`LogicalExpression`&&(e.operator===`&&`||e.operator===`||`)){let n=s(e.left,t),r=s(e.right,t);return e.operator===`&&`===t?n??r:n===r?n:null}let c=r(e,i),l=c!==null&&c.receiverText===n?c.isNegated:a(e,n,i)?!0:null;return l===null?null:l===t?`absent`:`present`},s={isSome:`MatchOption`,isNone:`MatchOption`,isLeft:`MatchEither`,isRight:`MatchEither`,isSuccess:`MatchTry`,isFailure:`MatchTry`};export{s as MATCH_COMPONENT,t as NEGATIVE_PREDICATES,e as POSITIVE_PREDICATES,n as compact,r as predicateCall,o as provesWhen,i as testedPredicate};
|
|
2
|
+
//# sourceMappingURL=functype-predicates.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"functype-predicates.js","names":["POSITIVE_PREDICATES","NEGATIVE_PREDICATES","compact","text","predicateCall","node","callee","method","isNegated","sourceCode","testedPredicate","test","inner","isEmptyRead","receiverText","provesWhen","self","value","outcome","left","right","predicate","isAbsenceTest","MATCH_COMPONENT"],"sources":["../../src/utils/functype-predicates.ts"],"sourcesContent":["import type { SourceCode } from \"eslint\"\n\nimport type { ASTNode } from \"../types/ast\"\n\n/** Methods on a monadic value that mean \"this is the Some/Right/Success path.\" */\nexport const POSITIVE_PREDICATES: ReadonlySet<string> = new Set([\"isSome\", \"isRight\", \"isSuccess\"])\n/** Methods that mean \"this is the None/Left/Failure path.\" */\n// `isEmpty` is deliberately absent: it is a property on every functype container, never a method, so\n// `x.isEmpty()` is not functype code (and on a List, `.fold` is a reduce, not a branch).\nexport const NEGATIVE_PREDICATES: ReadonlySet<string> = new Set([\"isNone\", \"isLeft\", \"isFailure\"])\n\n/** Source text with all whitespace removed — receivers match however they are line-broken. */\nexport const compact = (text: string): string => text.replace(/\\s+/g, \"\")\n\n/** A functype predicate call such as `o.isSome()`, split into its receiver and method. */\nexport type PredicateCall = {\n readonly receiver: ASTNode\n /** The receiver's source text, whitespace removed, for matching against other reads of it. */\n readonly receiverText: string\n readonly method: string\n readonly isNegated: boolean\n}\n\n/**\n * `o.isSome()`, `e.isLeft()`, `t.isFailure()` — a zero-argument call of a functype predicate method.\n * A property read (`state.isPending`, `items.isEmpty`) is not a call, so it never matches.\n */\nexport const predicateCall = (node: ASTNode, sourceCode: SourceCode): PredicateCall | null => {\n if (node?.type !== \"CallExpression\" || node.arguments.length !== 0) return null\n const callee = node.callee as ASTNode\n if (callee.type !== \"MemberExpression\" || callee.computed || callee.property.type !== \"Identifier\") return null\n const method = callee.property.name as string\n const isNegated = NEGATIVE_PREDICATES.has(method)\n if (!isNegated && !POSITIVE_PREDICATES.has(method)) return null\n return { receiver: callee.object, receiverText: compact(sourceCode.getText(callee.object)), method, isNegated }\n}\n\n/**\n * The first predicate call a test branches on, looking through `!` (which flips it) and `&&` / `||`:\n * `o.isSome()`, `!o.isSome()`, `loading || o.isNone()`. `isNegated` is the predicate's own meaning\n * with any `!` applied, so `!o.isSome()` reads like `o.isNone()`.\n */\nexport const testedPredicate = (test: ASTNode, sourceCode: SourceCode): PredicateCall | null => {\n if (test?.type === \"UnaryExpression\" && test.operator === \"!\") {\n const inner = testedPredicate(test.argument, sourceCode)\n return inner === null ? null : { ...inner, isNegated: !inner.isNegated }\n }\n if (test?.type === \"LogicalExpression\" && (test.operator === \"&&\" || test.operator === \"||\")) {\n return testedPredicate(test.left, sourceCode) ?? testedPredicate(test.right, sourceCode)\n }\n return predicateCall(test, sourceCode)\n}\n\n/** What a test proves about a receiver's value: there, missing, or nothing. */\nexport type Presence = \"present\" | \"absent\" | null\n\n/** `o.isEmpty` read (not called): Option's narrowing property, true when the value is missing. */\nconst isEmptyRead = (node: ASTNode, receiverText: string, sourceCode: SourceCode): boolean =>\n node?.type === \"MemberExpression\" &&\n !node.computed &&\n node.property.type === \"Identifier\" &&\n node.property.name === \"isEmpty\" &&\n !(node.parent?.type === \"CallExpression\" && node.parent.callee === node) &&\n compact(sourceCode.getText(node.object)) === receiverText\n\n/**\n * What `test` evaluating to `outcome` proves about `receiverText`. Looks through `!`, `&&` and `||`:\n * `a && b` being true proves whatever either side proves, `a || b` being false likewise, and the other\n * two cases prove something only when both sides agree. `o.isEmpty` counts as a test for absence.\n */\nexport const provesWhen = (test: ASTNode, outcome: boolean, receiverText: string, sourceCode: SourceCode): Presence => {\n const self = (node: ASTNode, value: boolean): Presence => provesWhen(node, value, receiverText, sourceCode)\n if (test?.type === \"UnaryExpression\" && test.operator === \"!\") return self(test.argument, !outcome)\n if (test?.type === \"LogicalExpression\" && (test.operator === \"&&\" || test.operator === \"||\")) {\n const left = self(test.left, outcome)\n const right = self(test.right, outcome)\n // `a && b` true, or `a || b` false: both sides hold that outcome, so either one's proof counts.\n if ((test.operator === \"&&\") === outcome) return left ?? right\n return left === right ? left : null\n }\n const predicate = predicateCall(test, sourceCode)\n const isAbsenceTest =\n predicate !== null && predicate.receiverText === receiverText\n ? predicate.isNegated\n : isEmptyRead(test, receiverText, sourceCode)\n ? true\n : null\n if (isAbsenceTest === null) return null\n return isAbsenceTest === outcome ? \"absent\" : \"present\"\n}\n\n/** The functype-react component that renders both cases of the container a predicate belongs to. */\nexport const MATCH_COMPONENT: Readonly<Record<string, string>> = {\n isSome: \"MatchOption\",\n isNone: \"MatchOption\",\n isLeft: \"MatchEither\",\n isRight: \"MatchEither\",\n isSuccess: \"MatchTry\",\n isFailure: \"MatchTry\",\n}\n"],"mappings":"AAKA,MAAaA,kBAA2C,IAAI,IAAI,CAAC,SAAU,UAAW,WAAW,CAAC,EAIrFC,kBAA2C,IAAI,IAAI,CAAC,SAAU,SAAU,WAAW,CAAC,EAGpFC,EAAW,GAAyBC,EAAK,QAAQ,OAAQ,EAAE,EAe3DC,GAAiB,EAAe,IAAiD,CAC5F,GAAIC,GAAM,OAAS,kBAAoBA,EAAK,UAAU,SAAW,EAAG,OAAO,KAC3E,IAAMC,EAASD,EAAK,OACpB,GAAIC,EAAO,OAAS,oBAAsBA,EAAO,UAAYA,EAAO,SAAS,OAAS,aAAc,OAAO,KAC3G,IAAMC,EAASD,EAAO,SAAS,KACzBE,EAAYP,EAAoB,IAAIM,CAAM,EAEhD,MADI,CAACC,GAAa,CAACR,EAAoB,IAAIO,CAAM,E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EAAU,eAAiBP,EAC7CO,EAAU,UACVR,EAAYF,EAAMG,EAAcL,CAAU,EACxC,GACA,KAER,OADIa,IAAkB,KAAa,KAC5BA,IAAkBJ,EAAU,SAAW,SAChD,EAGaK,EAAoD,CAC/D,OAAQ,cACR,OAAQ,cACR,OAAQ,cACR,QAAS,cACT,UAAW,WACX,UAAW,UACb"}
|
|
@@ -0,0 +1,15 @@
|
|
|
1
|
+
import { ASTNode } from "../types/ast.js";
|
|
2
|
+
//#region src/utils/react-render.d.ts
|
|
3
|
+
/** The nearest function enclosing `node`, or null at the top level. */
|
|
4
|
+
export declare const enclosingFunction: (node: ASTNode) => ASTNode | null;
|
|
5
|
+
export declare const isJSX: (node: ASTNode) => boolean;
|
|
6
|
+
/** JSX, or a conditional / logical expression with JSX in a branch: `<A />`, `ok ? <A /> : null`, `ok && <A />`. */
|
|
7
|
+
export declare const producesJSX: (node: ASTNode) => boolean;
|
|
8
|
+
export type RenderKind = "component" | "hook";
|
|
9
|
+
/**
|
|
10
|
+
* Is `fn` a component or a hook, and which? Null for any other function. Rules call this only for a
|
|
11
|
+
* candidate node (an unwrap, a predicate call), so the JSX scan over the body stays rare.
|
|
12
|
+
*/
|
|
13
|
+
export declare const renderKind: (fn: ASTNode) => RenderKind | null;
|
|
14
|
+
//#endregion
|
|
15
|
+
//# sourceMappingURL=react-render.d.ts.map
|
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
import{descendants as e}from"./ast-walk.js";const t=/* @__PURE__ */ new Set([`FunctionDeclaration`,`FunctionExpression`,`ArrowFunctionExpression`]),n=/* @__PURE__ */ new Set([`memo`,`forwardRef`]),r=(e,t)=>{if(e?.type!==`CallExpression`||e.arguments[0]!==t)return!1;let r=e.callee,i=r.type===`Identifier`?r.name:r.type===`MemberExpression`&&r.property.type===`Identifier`?r.property.name:null;return i!==null&&n.has(i)},i=e=>{let n=e.parent;return n?t.has(n.type)?n:i(n):null},a=e=>{if(e.id?.type===`Identifier`)return e.id.name;let t=e.parent,n=r(t,e)?t?.parent:t;return n?.type===`VariableDeclarator`&&n.id.type===`Identifier`?n.id.name:null},o=e=>e?.type===`JSXElement`||e?.type===`JSXFragment`,s=e=>o(e)?!0:e?.type===`ConditionalExpression`?s(e.consequent)||s(e.alternate):e?.type===`LogicalExpression`&&s(e.right),c=/^use[A-Z0-9]/,l=/^[A-Z]/,u=t=>{let n=a(t);return n===null?null:c.test(n)?`hook`:l.test(n)&&e(t.body).some(o)?`component`:null};export{i as enclosingFunction,o as isJSX,s as producesJSX,u as renderKind};
|
|
2
|
+
//# sourceMappingURL=react-render.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"react-render.js","names":["FUNCTION_TYPES","WRAPPERS","isWrapperCall","node","fn","callee","name","enclosingFunction","parent","functionName","holder","isJSX","producesJSX","HOOK_NAME","COMPONENT_NAME","renderKind","descendants"],"sources":["../../src/utils/react-render.ts"],"sourcesContent":["import type { ASTNode } from \"../types/ast\"\nimport { descendants } from \"./ast-walk\"\n\n/**\n * Finds the function a node renders in: a React function component or a hook. Syntactic, by the\n * conventions React's own tooling uses (`eslint-plugin-react-hooks`):\n *\n * - a **component** is a function named in PascalCase whose body contains JSX — declared\n * (`function Card() {}`), assigned (`const Card = () => …`) or wrapped (`memo(…)`, `forwardRef(…)`);\n * - a **hook** is a function named `use` + an uppercase letter or digit (`useThing`, `use2D`).\n *\n * Only the function's own body is its render path. A function nested inside it (an event handler, a\n * `useEffect` callback, a `.map` callback) is a separate function: the rules that use this ask for the\n * *nearest* enclosing function, so code in a nested callback is never attributed to the render.\n */\n\nconst FUNCTION_TYPES: ReadonlySet<string> = new Set([\n \"FunctionDeclaration\",\n \"FunctionExpression\",\n \"ArrowFunctionExpression\",\n])\n\n/** `memo(fn)`, `forwardRef(fn)`, `React.memo(fn)`: the wrapped function keeps the variable's name. */\nconst WRAPPERS: ReadonlySet<string> = new Set([\"memo\", \"forwardRef\"])\n\nconst isWrapperCall = (node: ASTNode, fn: ASTNode): boolean => {\n if (node?.type !== \"CallExpression\" || node.arguments[0] !== fn) return false\n const callee = node.callee as ASTNode\n const name =\n callee.type === \"Identifier\"\n ? callee.name\n : callee.type === \"MemberExpression\" && callee.property.type === \"Identifier\"\n ? callee.property.name\n : null\n return name !== null && WRAPPERS.has(name)\n}\n\n/** The nearest function enclosing `node`, or null at the top level. */\nexport const enclosingFunction = (node: ASTNode): ASTNode | null => {\n const parent = node.parent as ASTNode | undefined\n if (!parent) return null\n return FUNCTION_TYPES.has(parent.type) ? parent : enclosingFunction(parent)\n}\n\n/** The name a function is known by: its own id, or the variable it (or its `memo` wrapper) is assigned to. */\nconst functionName = (fn: ASTNode): string | null => {\n if (fn.id?.type === \"Identifier\") return fn.id.name\n const parent = fn.parent as ASTNode | undefined\n const holder = isWrapperCall(parent, fn) ? (parent?.parent as ASTNode | undefined) : parent\n return holder?.type === \"VariableDeclarator\" && holder.id.type === \"Identifier\" ? holder.id.name : null\n}\n\nexport const isJSX = (node: ASTNode): boolean => node?.type === \"JSXElement\" || node?.type === \"JSXFragment\"\n\n/** JSX, or a conditional / logical expression with JSX in a branch: `<A />`, `ok ? <A /> : null`, `ok && <A />`. */\nexport const producesJSX = (node: ASTNode): boolean => {\n if (isJSX(node)) return true\n if (node?.type === \"ConditionalExpression\") return producesJSX(node.consequent) || producesJSX(node.alternate)\n if (node?.type === \"LogicalExpression\") return producesJSX(node.right)\n return false\n}\n\nexport type RenderKind = \"component\" | \"hook\"\n\nconst HOOK_NAME = /^use[A-Z0-9]/\nconst COMPONENT_NAME = /^[A-Z]/\n\n/**\n * Is `fn` a component or a hook, and which? Null for any other function. Rules call this only for a\n * candidate node (an unwrap, a predicate call), so the JSX scan over the body stays rare.\n */\nexport const renderKind = (fn: ASTNode): RenderKind | null => {\n const name = functionName(fn)\n if (name === null) return null\n if (HOOK_NAME.test(name)) return \"hook\"\n return COMPONENT_NAME.test(name) && descendants(fn.body).some(isJSX) ? \"component\" : null\n}\n"],"mappings":"4CAgBA,M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
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "eslint-plugin-functype",
|
|
3
|
-
"version": "2.
|
|
3
|
+
"version": "2.121.1",
|
|
4
4
|
"description": "Custom ESLint rules for functional TypeScript programming with functype library patterns including Do notation (ESLint 10+)",
|
|
5
5
|
"type": "module",
|
|
6
6
|
"main": "./dist/index.js",
|
|
@@ -42,7 +42,7 @@
|
|
|
42
42
|
"@types/node": "^24.19.1",
|
|
43
43
|
"@typescript-eslint/rule-tester": "^8.71.0",
|
|
44
44
|
"eslint-config-prettier": "^10.1.8",
|
|
45
|
-
"functype": "^1.
|
|
45
|
+
"functype": "^1.21.1",
|
|
46
46
|
"ts-builds": "^3.4.3",
|
|
47
47
|
"tsdown": "^0.23.0"
|
|
48
48
|
},
|