eslint-plugin-functype 2.113.0 → 2.115.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +91 -5
- package/dist/configs/recommended.d.ts +5 -0
- package/dist/configs/recommended.js +1 -1
- package/dist/configs/recommended.js.map +1 -1
- package/dist/configs/strict.d.ts +1 -0
- package/dist/configs/strict.js +1 -1
- package/dist/configs/strict.js.map +1 -1
- package/dist/index.d.ts +1 -0
- package/dist/rules/index.d.ts +16 -14
- package/dist/rules/index.js +1 -1
- package/dist/rules/index.js.map +1 -1
- package/dist/rules/no-array-mutation.d.ts +17 -0
- package/dist/rules/no-array-mutation.js +2 -0
- package/dist/rules/no-array-mutation.js.map +1 -0
- package/dist/rules/no-get-unsafe.js +1 -1
- package/dist/rules/no-get-unsafe.js.map +1 -1
- package/dist/rules/prefer-fold.js +1 -1
- package/dist/rules/prefer-fold.js.map +1 -1
- package/dist/rules/prefer-list.js +2 -1
- package/dist/rules/prefer-list.js.map +1 -1
- package/dist/rules/prefer-option.js +1 -1
- package/dist/rules/prefer-try.js +1 -1
- package/dist/utils/array-mutation.d.ts +7 -0
- package/dist/utils/array-mutation.js +2 -0
- package/dist/utils/array-mutation.js.map +1 -0
- package/dist/utils/type-aware.d.ts +40 -0
- package/dist/utils/type-aware.js +2 -0
- package/dist/utils/type-aware.js.map +1 -0
- package/package.json +3 -3
package/README.md
CHANGED
|
@@ -43,6 +43,7 @@ export default [functype.configs.strict]
|
|
|
43
43
|
| `functype/prefer-do-notation` | warn | warn | Use `Do` notation for chained operations |
|
|
44
44
|
| `functype/no-get-unsafe` | off | error | Disallow unsafe extraction (`.orThrow()`, `.expect()`) |
|
|
45
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 |
|
|
46
47
|
|
|
47
48
|
### Severity policy
|
|
48
49
|
|
|
@@ -98,6 +99,29 @@ Prefer either tool to `eslint-disable`. A disable covers a whole file or line an
|
|
|
98
99
|
| `allowReadonlyArrays` | `true` | When `true`, `ReadonlyArray<T>` **and** `readonly T[]` pass. When `false`, both are flagged consistently. Use `false` in combination with `Wire<T>` from `functype` to hold the rule at `error` — every unmarked `ReadonlyArray<T>` becomes a lint error, and wrapping a boundary type in `Wire<…>` is the explicit escape hatch. |
|
|
99
100
|
| `allowArrayLiterals` | `false` | When `true`, `const xs = [1, 2, 3]` is not reported. Useful when you want type-position enforcement but tolerate idiomatic literals like `[...map.entries()]`. Mutable `T[]` in type positions is always reported regardless. |
|
|
100
101
|
|
|
102
|
+
**What it reports.** The defect is a collection that can change under you, so:
|
|
103
|
+
|
|
104
|
+
- **A mutable `T[]` / `Array<T>` type.** The first suggestion is `ReadonlyArray<T>`, which every caller and library accepts; `List<T>` is second, for a collection you transform. With `allowReadonlyArrays: true` (the default) one accepted suggestion silences the report, so in practice the rule asks for read-only types; set it to `false` with `Wire<T>` at boundaries to push towards `List`.
|
|
105
|
+
- **An array changed in place** (`push`, `sort`, `splice`, `x[i] = …`, on a binding, a literal accumulator or a field). This gets advice instead of a suggestion, because `ReadonlyArray` wouldn't compile there: build it with `map` / `filter` / `flatMap`, a `List`, or a fold. (This only fires where the rule has an annotation or a literal to hook onto; an inferred array that's pushed to isn't seen.)
|
|
106
|
+
- **A cast of untyped data to an array** (`JSON.parse(raw) as Row[]`, `raw as Row[]` after `Array.isArray`), with type information. Decoded outside data belongs in a `Wire<ReadonlyArray<Row>>` shape.
|
|
107
|
+
- **An array literal that becomes a collection in your own code** (stored, then transformed with `map` / `filter` / `slice` / `reduce`), with type information.
|
|
108
|
+
|
|
109
|
+
**What it leaves alone.** Data handed to a library in the shape the library demands isn't yours to change. With type-aware linting (`projectService`) the rule skips:
|
|
110
|
+
|
|
111
|
+
- a literal passed where an array is expected (drizzle `.values([...])`, an index definition, a prop typed as an array, a parameter typed `Iterable`), or spread into a call (`and(...conds)`);
|
|
112
|
+
- a literal inside an object passed to an untyped parameter (a `JSON.stringify` request body), or to a generic one that doesn't hand it back (`c.json<T>(data: T)`). A generic that returns the argument (`useState(init)`, including React's `S | (() => S)` signature, `identity(x)`, `Promise<T>`) leaves the shape with you, so it's reported;
|
|
113
|
+
- a method chain whose result goes to JSX children or an array slot (`{["PDF", "DOCX"].map((f) => <Chip />)}`);
|
|
114
|
+
- a mutable type whose value goes to a slot that **requires** a mutable array (pg's `query(text, values: unknown[])`, an SDK option typed `string[]`), including through a function's declared return type;
|
|
115
|
+
- a `const` whose every use is one of those, or a single-value read.
|
|
116
|
+
|
|
117
|
+
**Single-value reads** are temporaries, with or without type information: `.length`, `[i]`, `join` / `includes` / `indexOf` / `some` / `every` / `find` / `at`, and chains that end in one (`[a, b].filter(Boolean).join(" ")`, `[...xs].sort(byRank)[0]`). A chain that produces another collection is collection work and is reported.
|
|
118
|
+
|
|
119
|
+
**Without type information, array literals aren't reported at all.** The rule can't tell a literal handed to a library from one of your own, so it reports neither rather than guess. Type positions and in-place mutation are still reported. Turn on type-aware linting to get literal checks.
|
|
120
|
+
|
|
121
|
+
Also skipped: `as const` and other tuple assertions, tuple rest elements (`[string, ...string[]]`), rest parameters (`...args: T[]`), literals passed straight into `List(…)` / `Set(…)`, and files marked generated (`@generated`, "auto-generated", "DO NOT EDIT"). Generators with no marker, such as Supabase's types, need an `ignores` entry. Anything still reported that is a deliberate host shape gets `Wire<…>`.
|
|
122
|
+
|
|
123
|
+
Measured on five consumers (2026-10-10), with type-aware linting: **2,000 hits under 2.114, 696 after.** By repo, before → after: CivalaOS 821 → 215, agent-todo 843 → 328, dokploy-mcp-server 170 → 68, ts-builds 111 → 43, supabase-typed-query 55 → 42. Known false positives left: 25 hits in agent-todo's unmarked Supabase types (an `ignores` entry), one nested ReactFlow return type (`Wire`), one AWS SES request built in an untyped object. Linting all of CivalaOS with the rule on takes about 18 seconds.
|
|
124
|
+
|
|
101
125
|
**Boundary recipe (recommended for codebases touching serialization boundaries):**
|
|
102
126
|
|
|
103
127
|
```jsonc
|
|
@@ -116,14 +140,53 @@ type UserRow = Wire<{ readonly email: string | null; readonly tags: ReadonlyArra
|
|
|
116
140
|
|
|
117
141
|
`Wire<T>` is assignable both ways with the plain type, so no casts. `prefer-list` and `prefer-option` skip everything inside a `Wire<…>` type argument (`wireTypes` option, default `["Wire"]`; `[]` turns it off), and consumer aliases stack cleanly.
|
|
118
142
|
|
|
143
|
+
### `functype/no-array-mutation`
|
|
144
|
+
|
|
145
|
+
Reports changing an array in place:
|
|
146
|
+
|
|
147
|
+
- the methods `push`, `pop`, `shift`, `unshift`, `splice`, `sort`, `reverse`, `fill` and `copyWithin`;
|
|
148
|
+
- assigning to an element (`xs[i] = v`, `xs[i] += 1`, `xs[i]++`);
|
|
149
|
+
- `delete xs[i]`;
|
|
150
|
+
- setting `length`.
|
|
151
|
+
|
|
152
|
+
It catches the mutation wherever the array came from, including an inferred `const rows = load(); rows.push(x)`, which `prefer-list` can't see because there's no annotation or literal.
|
|
153
|
+
|
|
154
|
+
```ts
|
|
155
|
+
rows.push(row) // reported → [...rows, row], or build rows with map / flatMap
|
|
156
|
+
xs.sort(byRank) // reported → xs.toSorted(byRank)
|
|
157
|
+
xs[i] = v // reported → xs.with(i, v)
|
|
158
|
+
const sorted = [...xs].sort(byRank) // fine: sorts a fresh copy
|
|
159
|
+
```
|
|
160
|
+
|
|
161
|
+
**It only runs with type-aware linting** (`parserOptions.projectService`). It checks the receiver's type, so `push` on a queue class, a `Set` or an `any` value is never mistaken for an array. Without type information it reports nothing.
|
|
162
|
+
|
|
163
|
+
**What it skips:**
|
|
164
|
+
|
|
165
|
+
- mutating a value assumed fresh on the spot: a literal or any call result (`[...xs].sort()`, `xs.slice().reverse()`, `(await load()).sort()`). This also misses a call that returns a shared array (`getSharedCache().push(x)`), a recall gap the rule accepts to stay free of false positives;
|
|
166
|
+
- `ReadonlyArray`, which the compiler already guards.
|
|
167
|
+
|
|
168
|
+
For a host that has to mutate, such as a charting library that takes the array it fills, tag the function `@interop <reason>`.
|
|
169
|
+
|
|
170
|
+
| Option | Default | Description |
|
|
171
|
+
| -------------------- | ------- | ---------------------------------------------------------- |
|
|
172
|
+
| `allowInTests` | `true` | Silence the rule inside test files. |
|
|
173
|
+
| `allowInteropMarker` | `true` | Skip code inside a declaration tagged `@interop <reason>`. |
|
|
174
|
+
|
|
175
|
+
Measured on five consumers (2026-10-10): 91 hits, every one a real in-place mutation. Most were `push` accumulators building a list or a Markdown body line by line; the rest were `sort` on a named array and element assignment. It's `off` in `recommended` until 2.0, to avoid failing builds on a 1.x upgrade.
|
|
176
|
+
|
|
119
177
|
### `functype/no-get-unsafe`
|
|
120
178
|
|
|
121
|
-
| Option
|
|
122
|
-
|
|
|
123
|
-
| `allowInTests`
|
|
124
|
-
| `
|
|
179
|
+
| Option | Default | Description |
|
|
180
|
+
| -------------------- | ------------------------------------------------------ | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
|
|
181
|
+
| `allowInTests` | `true` | Silence the rule inside test files (same predicate as above). |
|
|
182
|
+
| `allowInteropMarker` | `true` | Skip calls inside a declaration tagged `@interop <reason>`, as `prefer-either` does. |
|
|
183
|
+
| `unsafeMethods` | `["orThrow", "expect", "get", "getOrThrow", "unwrap"]` | Method names flagged when called on a suspected `Option` / `Either` / other `Extractable` receiver. Includes both current (`orThrow`, `expect`) and legacy (`get`, `getOrThrow`, `unwrap`) names. |
|
|
184
|
+
|
|
185
|
+
**Which receivers count.** With type-aware linting on (`parserOptions.projectService` or `project`), the rule checks the receiver's type: anything with both `orThrow` and `fold` (every functype container) is checked, whatever the variable is called, and a native `Map` named `options` is not. Without type information it falls back to guessing from the receiver's name and shape (`option`, `either`, `result`… or a `.map/.flatMap/.filter/.fold` chain), which misses a container bound to any other name. Turn type-aware linting on if you rely on this rule.
|
|
186
|
+
|
|
187
|
+
`.orThrow(error)` and `.orThrow((e) => error)` are not reported: the caller chose the error, which is the documented way to throw for a host that needs it (see the decision table above). A bare `.orThrow()` throws a generic error and is reported.
|
|
125
188
|
|
|
126
|
-
The rule reports each match with two suggestions — `.orElse(default)` for value fallback and `.fold(onNone, onSome)` for branch handling. There is no autofix: the correct replacement depends on human judgment about a default value, and `.expect(msg)`
|
|
189
|
+
The rule reports each match with two suggestions — `.orElse(default)` for value fallback and `.fold(onNone, onSome)` for branch handling. There is no autofix: the correct replacement depends on human judgment about a default value, and `.expect(msg)` would silently lose its argument. Apply a suggestion explicitly in your editor when you know which one fits.
|
|
127
190
|
|
|
128
191
|
### `functype/prefer-fold`
|
|
129
192
|
|
|
@@ -131,9 +194,32 @@ The rule reports each match with two suggestions — `.orElse(default)` for valu
|
|
|
131
194
|
| --------------- | ------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ |
|
|
132
195
|
| `minComplexity` | `2` | Minimum if/else chain length (root + branches) before it is reported. |
|
|
133
196
|
| `checkNullable` | `false` | Also report null checks on plain values (`x === null ? a : b`). Off because whether `x` should be an `Option` is `prefer-option`'s call; at `error` this path fired on JSX, style objects and conditional spreads. |
|
|
197
|
+
| `checkGuards` | `false` | Also report a guard followed by an unwrap: `if (e.isLeft()) return …` and then `e.value` / `e.orThrow()` / `e.get()` later in the same block. Off while it rolls out: `prefer-fold` is `error` in `recommended`. |
|
|
134
198
|
|
|
135
199
|
Reports only; the rewrite is a **suggestion, never an autofix**. A fold rewrite can't be proven type-correct without type information, and `eslint --fix` applies fixable rules at warn severity too, so an autofix here would rewrite working code during `validate`. The suggestion reads narrowed values through the fold's parameters (`e.value` after `isLeft()` becomes `left`), omits unused parameters, keeps `return` on if/else chains, parenthesizes object-literal branches, and offers `a.or(b)` for `a.isSome() ? a : b`. Rewrites follow the syntax tree, so text inside strings, template literals and comments is left alone. No suggestion is offered when the rewrite would drop a comment or could not type-check (`a.isSome() ? a : 5`). Suggestions are applied by hand, so review each one: the rule has no type information and can't prove the result compiles.
|
|
136
200
|
|
|
201
|
+
**`checkGuards`: guard, then unwrap.** Checking a container with an early exit and then pulling the value out is imperative branching. Getting a value out is fine: `orElse(default)` and `fold` are both proper exits and are never reported. What's reported is the shape below. The message picks its advice from what the guard does:
|
|
202
|
+
|
|
203
|
+
```ts
|
|
204
|
+
if (e.isLeft()) return e // hands the failure back → e.flatMap(…) / e.map(…)
|
|
205
|
+
if (e.isLeft()) return Left({ kind: e.value.kind }) // a new failure → e.mapLeft(…).flatMap(…)
|
|
206
|
+
if (o.isNone()) return 0 // a fallback → o.map(…).orElse(0), or o.fold(() => 0, …)
|
|
207
|
+
if (r.isLeft()) return c.json({ error: r.value }, 500) // fallback reads the failure → r.fold(…), only
|
|
208
|
+
if (a.isLeft()) return a
|
|
209
|
+
if (b.isLeft()) return b // several in a row → Do(function* () { … })
|
|
210
|
+
if (e.isLeft()) throw new Error("x") // a host throw → e.orThrow((err) => new MyError(err))
|
|
211
|
+
if (t.isFailure()) {
|
|
212
|
+
log(t.error)
|
|
213
|
+
return
|
|
214
|
+
} // other work first → t.fold(onFailure, onSuccess)
|
|
215
|
+
```
|
|
216
|
+
|
|
217
|
+
`orThrow(error)` / `orThrow((e) => …)` after a guard isn't counted as an unwrap, matching `no-get-unsafe`, which treats a named error as a deliberate host throw. A receiver reassigned after the guard isn't reported. Only the negative predicates (`isLeft` / `isNone` / `isFailure`) are matched; `if (!e.isRight())` isn't yet.
|
|
218
|
+
|
|
219
|
+
Pass-through guards are the clear case: they are hand-written `flatMap`. Fallback and other-work-first guards are closer to a style choice, since TypeScript narrows `Either` after the guard (Rust's `let-else` and Swift's `guard let` make the same trade). For `Option` and `Try` the guard doesn't narrow `.value`, so the case is stronger there. That split is why this is planned for `strict`, not `recommended`, in 2.0.
|
|
220
|
+
|
|
221
|
+
When the code after the guard awaits, the advice uses `flatMapAsync` / `foldAsync`. Declarations tagged `@interop <reason>` are skipped. On CivalaOS it finds 75 guards, all of this shape.
|
|
222
|
+
|
|
137
223
|
### `functype/prefer-option`
|
|
138
224
|
|
|
139
225
|
| Option | Default | Description |
|
|
@@ -18,6 +18,10 @@
|
|
|
18
18
|
*
|
|
19
19
|
* collection-naming is a convention, not a heuristic — functype's Map/Set imported under their own names,
|
|
20
20
|
* the built-in spelled globalThis.Map — so it has no false-positive class and starts at error.
|
|
21
|
+
*
|
|
22
|
+
* no-array-mutation is off here only because turning a new error on in a 1.x minor would fail consumers'
|
|
23
|
+
* builds on upgrade (91 hits across five consumers, every one a real in-place mutation). It's `error` in
|
|
24
|
+
* strict, and planned for `error` here in 2.0. It is type-aware: without type information it reports nothing.
|
|
21
25
|
*/
|
|
22
26
|
declare const recommendedRules: {
|
|
23
27
|
"functype/no-let": string;
|
|
@@ -34,6 +38,7 @@ declare const recommendedRules: {
|
|
|
34
38
|
"functype/prefer-do-notation": string;
|
|
35
39
|
"functype/no-get-unsafe": string;
|
|
36
40
|
"functype/prefer-list": string;
|
|
41
|
+
"functype/no-array-mutation": string;
|
|
37
42
|
};
|
|
38
43
|
//#endregion
|
|
39
44
|
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`};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`};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 */\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}\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 */\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}\n\nexport default recommendedRules\n"],"mappings":"AAwBA,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,KAChC"}
|
package/dist/configs/strict.d.ts
CHANGED
|
@@ -5,6 +5,7 @@ declare const strictRules: {
|
|
|
5
5
|
"functype/prefer-try": string;
|
|
6
6
|
"functype/no-get-unsafe": string;
|
|
7
7
|
"functype/prefer-list": string;
|
|
8
|
+
"functype/no-array-mutation": string;
|
|
8
9
|
"functype/prefer-functype-map": string;
|
|
9
10
|
"functype/prefer-functype-set": string;
|
|
10
11
|
"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/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/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/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,+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/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,+BAAgC,QAChC,+BAAgC,QAChC,+BAAgC,OAClC"}
|
package/dist/index.d.ts
CHANGED
|
@@ -15,6 +15,7 @@ declare const plugin: {
|
|
|
15
15
|
"no-imperative-loops": import("eslint").Rule.RuleModule;
|
|
16
16
|
"prefer-do-notation": import("eslint").Rule.RuleModule;
|
|
17
17
|
"collection-naming": import("eslint").Rule.RuleModule;
|
|
18
|
+
"no-array-mutation": import("eslint").Rule.RuleModule;
|
|
18
19
|
};
|
|
19
20
|
meta: {
|
|
20
21
|
name: string;
|
package/dist/rules/index.d.ts
CHANGED
|
@@ -1,17 +1,18 @@
|
|
|
1
1
|
import rule from "./collection-naming.js";
|
|
2
|
-
import rule$1 from "./no-
|
|
3
|
-
import rule$2 from "./no-
|
|
4
|
-
import rule$3 from "./no-
|
|
5
|
-
import rule$4 from "./
|
|
6
|
-
import rule$5 from "./prefer-
|
|
7
|
-
import rule$6 from "./prefer-
|
|
8
|
-
import rule$7 from "./prefer-
|
|
9
|
-
import rule$8 from "./prefer-
|
|
10
|
-
import rule$9 from "./prefer-functype-
|
|
11
|
-
import rule$10 from "./prefer-
|
|
12
|
-
import rule$11 from "./prefer-
|
|
13
|
-
import rule$12 from "./prefer-
|
|
14
|
-
import rule$13 from "./prefer-
|
|
2
|
+
import rule$1 from "./no-array-mutation.js";
|
|
3
|
+
import rule$2 from "./no-get-unsafe.js";
|
|
4
|
+
import rule$3 from "./no-imperative-loops.js";
|
|
5
|
+
import rule$4 from "./no-let.js";
|
|
6
|
+
import rule$5 from "./prefer-do-notation.js";
|
|
7
|
+
import rule$6 from "./prefer-either.js";
|
|
8
|
+
import rule$7 from "./prefer-flatmap.js";
|
|
9
|
+
import rule$8 from "./prefer-fold.js";
|
|
10
|
+
import rule$9 from "./prefer-functype-map.js";
|
|
11
|
+
import rule$10 from "./prefer-functype-set.js";
|
|
12
|
+
import rule$11 from "./prefer-list.js";
|
|
13
|
+
import rule$12 from "./prefer-map.js";
|
|
14
|
+
import rule$13 from "./prefer-option.js";
|
|
15
|
+
import rule$14 from "./prefer-try.js";
|
|
15
16
|
//#region src/rules/index.d.ts
|
|
16
17
|
declare const _default: {
|
|
17
18
|
"prefer-option": import("eslint").Rule.RuleModule;
|
|
@@ -28,7 +29,8 @@ declare const _default: {
|
|
|
28
29
|
"no-imperative-loops": import("eslint").Rule.RuleModule;
|
|
29
30
|
"prefer-do-notation": import("eslint").Rule.RuleModule;
|
|
30
31
|
"collection-naming": import("eslint").Rule.RuleModule;
|
|
32
|
+
"no-array-mutation": import("eslint").Rule.RuleModule;
|
|
31
33
|
};
|
|
32
34
|
//#endregion
|
|
33
|
-
export { rule as collectionNaming, _default as default, rule$1 as
|
|
35
|
+
export { rule as collectionNaming, _default as default, rule$1 as noArrayMutation, rule$2 as noGetUnsafe, rule$3 as noImperativeLoops, rule$4 as noLet, rule$5 as preferDoNotation, rule$6 as preferEither, rule$7 as preferFlatmap, rule$8 as preferFold, rule$9 as preferFunctypeMap, rule$10 as preferFunctypeSet, rule$11 as preferList, rule$12 as preferMap, rule$13 as preferOption, rule$14 as preferTry };
|
|
34
36
|
//# 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-get-unsafe.js";import
|
|
1
|
+
import e from"./collection-naming.js";import t from"./no-array-mutation.js";import n from"./no-get-unsafe.js";import r from"./no-imperative-loops.js";import i from"./no-let.js";import a from"./prefer-do-notation.js";import o from"./prefer-either.js";import s from"./prefer-flatmap.js";import c from"./prefer-fold.js";import l from"./prefer-functype-map.js";import u from"./prefer-functype-set.js";import d from"./prefer-list.js";import f from"./prefer-map.js";import p from"./prefer-option.js";import m from"./prefer-try.js";var h={"prefer-option":p,"prefer-either":o,"prefer-try":m,"prefer-list":d,"no-get-unsafe":n,"no-let":i,"prefer-fold":c,"prefer-map":f,"prefer-flatmap":s,"prefer-functype-map":l,"prefer-functype-set":u,"no-imperative-loops":r,"prefer-do-notation":a,"collection-naming":e,"no-array-mutation":t};export{e as collectionNaming,h as default,t as noArrayMutation,n as noGetUnsafe,r as noImperativeLoops,i as noLet,a as preferDoNotation,o as preferEither,s as preferFlatmap,c as preferFold,l as preferFunctypeMap,u as preferFunctypeSet,d as preferList,f as preferMap,p as preferOption,m 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","rule","rule$1","rule$2","rule$3","rule$4","rule$5","rule$6","rule$7","rule$8","rule$9","rule$10","rule$11","rule$12","rule$13","rules_default"],"sources":["../../src/rules/index.ts"],"sourcesContent":["import collectionNaming from \"./collection-naming\"\nimport noGetUnsafe from \"./no-get-unsafe\"\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 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}\n"],"mappings":"
|
|
1
|
+
{"version":3,"file":"index.js","names":["preferOption","preferEither","preferTry","preferList","noGetUnsafe","noLet","preferFold","preferMap","preferFlatmap","preferFunctypeMap","preferFunctypeSet","noImperativeLoops","preferDoNotation","collectionNaming","noArrayMutation","rule","rule$1","rule$2","rule$3","rule$4","rule$5","rule$6","rule$7","rule$8","rule$9","rule$10","rule$11","rule$12","rule$13","rule$14","rules_default"],"sources":["../../src/rules/index.ts"],"sourcesContent":["import collectionNaming from \"./collection-naming\"\nimport noArrayMutation from \"./no-array-mutation\"\nimport noGetUnsafe from \"./no-get-unsafe\"\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 noArrayMutation,\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}\n"],"mappings":"6gBAkCA,IAAA8B,EAAe,CACb,gBAAiB9B,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,CACvB"}
|
|
@@ -0,0 +1,17 @@
|
|
|
1
|
+
import { Rule } from "eslint";
|
|
2
|
+
//#region src/rules/no-array-mutation.d.ts
|
|
3
|
+
/**
|
|
4
|
+
* Reports in-place mutation of a mutable array: `push` / `pop` / `shift` / `unshift` / `splice` / `sort` /
|
|
5
|
+
* `reverse` / `fill` / `copyWithin`, assignment to an element (`xs[i] = v`, `xs[i] += 1`, `xs[i]++`),
|
|
6
|
+
* `delete xs[i]`, and setting `length`.
|
|
7
|
+
*
|
|
8
|
+
* This is the mutation itself, wherever the array came from — an inferred `const rows = load()` included,
|
|
9
|
+
* which `prefer-list` can't see because it has no annotation or literal to hook onto. Type-aware only:
|
|
10
|
+
* without type information it reports nothing, so `push` on a custom class or a `Set` is never mistaken
|
|
11
|
+
* for an array. Mutating a literal or a call result on the spot (`[...xs].sort(byRank)`) isn't reported:
|
|
12
|
+
* it's assumed to be a fresh copy (see isFreshValue for the recall gap that leaves).
|
|
13
|
+
*/
|
|
14
|
+
declare const rule: Rule.RuleModule;
|
|
15
|
+
//#endregion
|
|
16
|
+
export { rule as default };
|
|
17
|
+
//# sourceMappingURL=no-array-mutation.d.ts.map
|
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
import{isMutableArrayExpression as e}from"../utils/array-mutation.js";import{isInsideTaggedDeclaration as t}from"../utils/boundary-tags.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=e=>c&&t(e,`interop`,l),d=t=>{if(t?.type!==`MemberExpression`)return null;let n=t.object;return r(n)?null:t.computed&&e(n,a)?n:null},f=t=>{if(t?.type!==`MemberExpression`||t.computed)return null;let n=t.object;return t.property?.type!==`Identifier`||t.property.name!==`length`||r(n)?null:e(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(t){let o=t.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(t)||e(c,a)&&a.report({node:t,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
|
+
//# sourceMappingURL=no-array-mutation.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"no-array-mutation.js","names":["MUTATING_METHODS","isFreshValue","node","nameOf","text","sourceCode","rule","options","context","allowInTests","allowInteropMarker","filename","isExempt","isInsideTaggedDeclaration","elementTarget","array","isMutableArrayExpression","lengthTarget","reportWrite","element","target","length","callee","method"],"sources":["../../src/rules/no-array-mutation.ts"],"sourcesContent":["import type { Rule } from \"eslint\"\n\nimport type { ASTNode } from \"../types/ast\"\nimport { isMutableArrayExpression } from \"../utils/array-mutation\"\nimport { INTEROP_TAG, isInsideTaggedDeclaration } from \"../utils/boundary-tags\"\n\n/** Array methods that change the array they're called on. */\nconst MUTATING_METHODS: ReadonlySet<string> = new Set([\n \"push\",\n \"pop\",\n \"shift\",\n \"unshift\",\n \"splice\",\n \"sort\",\n \"reverse\",\n \"fill\",\n \"copyWithin\",\n])\n\n/**\n * Is `node` assumed to be a value nothing else can see yet — `[...xs]`, `xs.slice()`, `Array.from(it)`,\n * `items.map(f)`? Mutating it on the spot (`[...xs].sort(byRank)`) is the common copy-then-sort idiom.\n * Every call result is assumed fresh, so `getSharedCache().push(x)` is missed too: a recall gap the rule\n * accepts to keep false positives at zero. Only a named array (a binding or a property) is reported.\n */\nconst isFreshValue = (node: ASTNode): boolean =>\n node.type === \"ArrayExpression\" ||\n node.type === \"CallExpression\" ||\n node.type === \"NewExpression\" ||\n (node.type === \"AwaitExpression\" && isFreshValue(node.argument as ASTNode))\n\n/** The variable or property name of a mutated array, for the message: `rows`, `this.events`, `acc.errors`. */\nconst nameOf = (node: ASTNode, sourceCode: Rule.RuleContext[\"sourceCode\"]): string => {\n const text = sourceCode.getText(node)\n return text.length > 40 ? `${text.slice(0, 37)}…` : text\n}\n\n/**\n * Reports in-place mutation of a mutable array: `push` / `pop` / `shift` / `unshift` / `splice` / `sort` /\n * `reverse` / `fill` / `copyWithin`, assignment to an element (`xs[i] = v`, `xs[i] += 1`, `xs[i]++`),\n * `delete xs[i]`, and setting `length`.\n *\n * This is the mutation itself, wherever the array came from — an inferred `const rows = load()` included,\n * which `prefer-list` can't see because it has no annotation or literal to hook onto. Type-aware only:\n * without type information it reports nothing, so `push` on a custom class or a `Set` is never mistaken\n * for an array. Mutating a literal or a call result on the spot (`[...xs].sort(byRank)`) isn't reported:\n * it's assumed to be a fresh copy (see isFreshValue for the recall gap that leaves).\n */\nconst rule: Rule.RuleModule = {\n meta: {\n type: \"problem\",\n docs: {\n description: \"Disallow changing an array in place — build a new one\",\n recommended: true,\n },\n schema: [\n {\n type: \"object\",\n properties: {\n allowInTests: { type: \"boolean\", default: true },\n allowInteropMarker: { type: \"boolean\", default: true },\n },\n additionalProperties: false,\n },\n ],\n messages: {\n mutatingMethod:\n \"{{name}}.{{method}}() changes the array in place. Build a new one instead: [...{{name}}, x], map / filter / flatMap / toSorted, a List, or a fold\",\n elementAssignment:\n \"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\",\n lengthAssignment:\n \"Setting {{name}}.length changes the array in place. Build a new one instead: {{name}}.slice(0, n), or start from []\",\n },\n },\n\n create(context) {\n const options = context.options[0] || {}\n const allowInTests = options.allowInTests !== false\n const allowInteropMarker = options.allowInteropMarker !== false\n const sourceCode = context.sourceCode\n\n const isInTestFile = (): boolean => {\n const filename = context.filename\n return (\n /\\.(test|spec)\\.(ts|js|tsx|jsx)$/.test(filename) ||\n filename.includes(\"__tests__\") ||\n filename.includes(\"/test/\") ||\n filename.includes(\"/tests/\")\n )\n }\n if (allowInTests && isInTestFile()) return {}\n\n /** `@interop <reason>` on an enclosing declaration marks a host boundary that has to mutate. */\n const isExempt = (node: ASTNode): boolean =>\n allowInteropMarker && isInsideTaggedDeclaration(node, INTEROP_TAG, sourceCode)\n\n /** `xs[i]` (a computed member) on a named mutable array, or null. */\n const elementTarget = (node: ASTNode | null | undefined): ASTNode | null => {\n if (node?.type !== \"MemberExpression\") return null\n const array = node.object as ASTNode\n if (isFreshValue(array)) return null\n if (node.computed) return isMutableArrayExpression(array, context) ? array : null\n return null\n }\n\n /** `xs.length` on a named mutable array, or null. */\n const lengthTarget = (node: ASTNode | null | undefined): ASTNode | null => {\n if (node?.type !== \"MemberExpression\" || node.computed) return null\n const array = node.object as ASTNode\n if (node.property?.type !== \"Identifier\" || node.property.name !== \"length\" || isFreshValue(array)) return null\n return isMutableArrayExpression(array, context) ? array : null\n }\n\n const reportWrite = (node: ASTNode, target: ASTNode): void => {\n if (isExempt(node)) return\n const element = elementTarget(target)\n if (element) {\n context.report({ node, messageId: \"elementAssignment\", data: { name: nameOf(element, sourceCode) } })\n return\n }\n const length = lengthTarget(target)\n if (length) {\n context.report({ node, messageId: \"lengthAssignment\", data: { name: nameOf(length, sourceCode) } })\n }\n }\n\n return {\n CallExpression(node: ASTNode) {\n const callee = node.callee as ASTNode\n if (callee.type !== \"MemberExpression\" || callee.computed) return\n const method = callee.property?.type === \"Identifier\" ? callee.property.name : null\n if (method === null || !MUTATING_METHODS.has(method)) return\n const array = callee.object as ASTNode\n if (isFreshValue(array) || isExempt(node)) return\n if (!isMutableArrayExpression(array, context)) return\n context.report({\n node,\n messageId: \"mutatingMethod\",\n data: { name: nameOf(array, sourceCode), method },\n })\n },\n\n AssignmentExpression(node: ASTNode) {\n reportWrite(node, node.left as ASTNode)\n },\n\n UpdateExpression(node: ASTNode) {\n reportWrite(node, node.argument as ASTNode)\n },\n\n UnaryExpression(node: ASTNode) {\n if (node.operator === \"delete\") reportWrite(node, node.argument as ASTNode)\n },\n }\n },\n}\n\nexport default rule\n"],"mappings":"4IAOA,MAAMA,kBAAwC,IAAI,IAAI,CACpD,OACA,MACA,QACA,UACA,SACA,OACA,UACA,OACA,YACF,CAAC,EAQKC,EAAgB,GACpBC,EAAK,OAAS,mBACdA,EAAK,OAAS,kBACdA,EAAK,OAAS,iBACbA,EAAK,OAAS,mBAAqBD,EAAaC,EAAK,QAAmB,EAGrEC,GAAU,EAAe,IAAuD,CACpF,IAAMC,EAAOC,EAAW,QAAQH,CAAI,EACpC,OAAOE,EAAK,OAAS,GAAK,GAAGA,EAAK,MAAM,EAAG,EAAE,EAAE,GAAKA,CACtD,EAaME,EAAwB,CAC5B,KAAM,CACJ,KAAM,UACN,KAAM,CACJ,YAAa,wDACb,YAAa,EACf,EACA,OAAQ,CACN,CACE,KAAM,SACN,WAAY,CACV,aAAc,CAAE,KAAM,UAAW,QAAS,EAAK,EAC/C,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EAAQ,OAAO,CAAE,OAAM,UAAW,mBAAoB,KAAM,CAAE,KAAML,EAAOkB,EAAQhB,CAAU,CAAE,CAAE,CAAC,CAEtG,EAEA,MAAO,CACL,eAAe,EAAe,CAC5B,IAAMiB,EAASpB,EAAK,OACpB,GAAIoB,EAAO,OAAS,oBAAsBA,EAAO,SAAU,OAC3D,IAAMC,EAASD,EAAO,UAAU,OAAS,aAAeA,EAAO,SAAS,KAAO,KAC/E,GAAIC,IAAW,MAAQ,CAACvB,EAAiB,IAAIuB,CAAM,EAAG,OACtD,IAAMR,EAAQO,EAAO,OACjBrB,EAAac,CAAK,GAAKH,EAASV,CAAI,GACnCc,EAAyBD,EAAOP,CAAO,GAC5CA,EAAQ,OAAO,CACb,OACA,UAAW,iBACX,KAAM,CAAE,KAAML,EAAOY,EAAOV,CAAU,EAAG,QAAO,CAClD,CAAC,CACH,EAEA,qBAAqB,EAAe,CAClCa,EAAYhB,EAAMA,EAAK,IAAe,CACxC,EAEA,iBAAiB,EAAe,CAC9BgB,EAAYhB,EAAMA,EAAK,QAAmB,CAC5C,EAEA,gBAAgB,EAAe,CACzBA,EAAK,WAAa,UAAUgB,EAAYhB,EAAMA,EAAK,QAAmB,CAC5E,CACF,CACF,CACF"}
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
const
|
|
1
|
+
import{isInsideTaggedDeclaration as e}from"../utils/boundary-tags.js";import{isExtractableByType as t}from"../utils/type-aware.js";const n=[`orThrow`,`expect`,`get`,`getOrThrow`,`unwrap`],r={meta:{type:`problem`,docs:{description:`Avoid unsafe extractor calls on Option, Either, and other Extractable types`,recommended:!0},hasSuggestions:!0,schema:[{type:`object`,properties:{allowInTests:{type:`boolean`,default:!0},allowInteropMarker:{type:`boolean`,default:!0},unsafeMethods:{type:`array`,items:{type:`string`},default:[...n]}},additionalProperties:!1}],messages:{noUnsafeGet:`Avoid unsafe .{{method}}() call: it throws a generic error. Use .fold(), .map(), or .orElse() instead. If a host needs the throw, name the error: .orThrow((e) => new MyError(e))`,suggestOrElse:`Replace with .orElse(default) for a value fallback`,suggestFold:`Replace with .fold(onNone, onSome) for branch handling`}},create(r){let i=r.options[0]||{},a=i.allowInTests!==!1,o=i.unsafeMethods||n,s=i.allowInteropMarker!==!1,c=(e,t)=>e===`orThrow`&&t.arguments.length>0;function l(){let e=r.filename;return/\.(test|spec)\.(ts|js|tsx|jsx)$/.test(e)||e.includes(`__tests__`)||e.includes(`/test/`)||e.includes(`/tests/`)}function u(e){if(!e)return!1;let t=r.sourceCode.getText(e);if(/\b(Option|Either|Maybe|Result|Some|None|Left|Right)\b/.test(t)||/\.(map|flatMap|filter|fold)\s*\(/.test(t)||/\b(option|either|maybe|result|some|none|left|right)\w*\b/i.test(t))return!0;if(e.type===`Identifier`){let t=e.name.toLowerCase();if(/(option|either|maybe|result|some|none|left|right|opt)/.test(t))return!0}return e.type===`CallExpression`&&e.callee.type===`MemberExpression`&&e.callee.object?u(e.callee.object):!1}return{CallExpression(n){if(a&&l()||n.callee.type!==`MemberExpression`)return;let i=n.callee.property;if(!i||i.type!==`Identifier`)return;let d=i.name;if(o.includes(d)&&!c(d,n)&&!(s&&e(n,`interop`,r.sourceCode))&&(t(n.callee.object,r)??u(n.callee.object))){let e=r.sourceCode,t=e.getText(n.callee.object),i=n.arguments.map(t=>e.getText(t)).join(`, `),a=i?`; was ${d}(${i})`:``;r.report({node:n,messageId:`noUnsafeGet`,data:{method:d},suggest:[{messageId:`suggestOrElse`,fix(e){return e.replaceText(n,`${t}.orElse(undefined /* TODO: default${a} */)`)}},{messageId:`suggestFold`,fix(e){return e.replaceText(n,`${t}.fold(() => undefined /* TODO: onNone${a} */, (v) => v /* TODO: onSome */)`)}}]})}}}}};export{r as default};
|
|
2
2
|
//# sourceMappingURL=no-get-unsafe.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"no-get-unsafe.js","names":["DEFAULT_UNSAFE_METHODS","rule","options","context","allowInTests","unsafeMethods","
|
|
1
|
+
{"version":3,"file":"no-get-unsafe.js","names":["DEFAULT_UNSAFE_METHODS","rule","options","context","allowInTests","unsafeMethods","allowInteropMarker","isChosenErrorThrow","methodName","node","isInTestFile","filename","isMonadicType","text","varName","property","isInsideTaggedDeclaration","isExtractableByType","sourceCode","objectText","argsText","a","wasSuffix","fixer"],"sources":["../../src/rules/no-get-unsafe.ts"],"sourcesContent":["import type { Rule } from \"eslint\"\n\nimport type { ASTNode } from \"../types/ast\"\nimport { INTEROP_TAG, isInsideTaggedDeclaration } from \"../utils/boundary-tags\"\nimport { isExtractableByType } from \"../utils/type-aware\"\n\nconst DEFAULT_UNSAFE_METHODS: readonly string[] = [\"orThrow\", \"expect\", \"get\", \"getOrThrow\", \"unwrap\"]\n\nconst rule: Rule.RuleModule = {\n meta: {\n type: \"problem\",\n docs: {\n description: \"Avoid unsafe extractor calls on Option, Either, and other Extractable types\",\n recommended: true,\n },\n hasSuggestions: true,\n schema: [\n {\n type: \"object\",\n properties: {\n allowInTests: {\n type: \"boolean\",\n default: true,\n },\n allowInteropMarker: {\n type: \"boolean\",\n default: true,\n },\n unsafeMethods: {\n type: \"array\",\n items: { type: \"string\" },\n default: [...DEFAULT_UNSAFE_METHODS],\n },\n },\n additionalProperties: false,\n },\n ],\n messages: {\n noUnsafeGet:\n \"Avoid unsafe .{{method}}() call: it throws a generic error. Use .fold(), .map(), or .orElse() instead. If a host needs the throw, name the error: .orThrow((e) => new MyError(e))\",\n suggestOrElse: \"Replace with .orElse(default) for a value fallback\",\n suggestFold: \"Replace with .fold(onNone, onSome) for branch handling\",\n },\n },\n\n create(context) {\n const options = context.options[0] || {}\n const allowInTests = options.allowInTests !== false\n const unsafeMethods: readonly string[] = options.unsafeMethods || DEFAULT_UNSAFE_METHODS\n // `@interop <reason>` on an enclosing declaration marks a host-contract boundary, as in prefer-either.\n const allowInteropMarker = options.allowInteropMarker !== false\n\n /**\n * `.orThrow(error)` / `.orThrow((e) => error)`: the caller chose the error. That is the documented way\n * to throw for a host that needs it, not an unsafe extraction; `prefer-either` and the README's\n * decision table both treat it that way. Only a bare `.orThrow()` throws a generic error.\n */\n const isChosenErrorThrow = (methodName: string, node: ASTNode): boolean =>\n methodName === \"orThrow\" && node.arguments.length > 0\n\n function isInTestFile() {\n const filename = context.filename\n return (\n /\\.(test|spec)\\.(ts|js|tsx|jsx)$/.test(filename) ||\n filename.includes(\"__tests__\") ||\n filename.includes(\"/test/\") ||\n filename.includes(\"/tests/\")\n )\n }\n\n function isMonadicType(node: ASTNode): boolean {\n // This is a simplified check - in a real implementation, you'd want\n // more sophisticated type checking using TypeScript's type checker\n if (!node) return false\n\n const sourceCode = context.sourceCode\n\n // Check for common patterns that indicate monadic types\n const text = sourceCode.getText(node)\n\n // Direct type checks - constructors or type names\n if (/\\b(Option|Either|Maybe|Result|Some|None|Left|Right)\\b/.test(text)) {\n return true\n }\n\n // Method chains that suggest monadic operations\n if (/\\.(map|flatMap|filter|fold)\\s*\\(/.test(text)) {\n return true\n }\n\n // Variable names that suggest monadic types (case insensitive)\n if (/\\b(option|either|maybe|result|some|none|left|right)\\w*\\b/i.test(text)) {\n return true\n }\n\n // Check the specific node type and name\n if (node.type === \"Identifier\") {\n const varName = node.name.toLowerCase()\n if (/(option|either|maybe|result|some|none|left|right|opt)/.test(varName)) {\n return true\n }\n }\n\n // Check for CallExpression pattern like Some(\"test\").map()\n if (node.type === \"CallExpression\" && node.callee.type === \"MemberExpression\" && node.callee.object) {\n return isMonadicType(node.callee.object)\n }\n\n return false\n }\n\n return {\n CallExpression(node: ASTNode) {\n if (allowInTests && isInTestFile()) return\n\n if (node.callee.type !== \"MemberExpression\") return\n\n const property = node.callee.property\n if (!property || property.type !== \"Identifier\") return\n\n const methodName = property.name\n if (!unsafeMethods.includes(methodName)) return\n if (isChosenErrorThrow(methodName, node)) return\n if (allowInteropMarker && isInsideTaggedDeclaration(node, INTEROP_TAG, context.sourceCode)) return\n\n // With type information, the receiver's type decides: no name guessing, so `missing.orThrow()`\n // on an Option is reported and `options.get(\"k\")` on a native Map is not. Without it, fall\n // back to the name/shape heuristic.\n const byType = isExtractableByType(node.callee.object, context)\n if (byType ?? isMonadicType(node.callee.object)) {\n const sourceCode = context.sourceCode\n const objectText = sourceCode.getText(node.callee.object)\n\n // Preserve the original call's argument text in the TODO comment so a suggestion\n // applied to `.expect(\"Should have a user here\")` or `.orThrow(new NotFound())`\n // doesn't silently drop information the developer intended to keep. Omit the\n // \"was\" suffix when the original call had no args (`.get()`, `.unwrap()`, etc.).\n const argsText = node.arguments.map((a: ASTNode) => sourceCode.getText(a)).join(\", \")\n const wasSuffix = argsText ? `; was ${methodName}(${argsText})` : \"\"\n\n context.report({\n node,\n messageId: \"noUnsafeGet\",\n data: { method: methodName },\n suggest: [\n {\n messageId: \"suggestOrElse\",\n fix(fixer) {\n return fixer.replaceText(node, `${objectText}.orElse(undefined /* TODO: default${wasSuffix} */)`)\n },\n },\n {\n messageId: \"suggestFold\",\n fix(fixer) {\n return fixer.replaceText(\n node,\n `${objectText}.fold(() => undefined /* TODO: onNone${wasSuffix} */, (v) => v /* TODO: onSome */)`,\n )\n },\n },\n ],\n })\n }\n },\n }\n },\n}\n\nexport default rule\n"],"mappings":"mIAMA,MAAMA,EAA4C,CAAC,UAAW,SAAU,MAAO,aAAc,QAAQ,EAE/FC,EAAwB,CAC5B,KAAM,CACJ,KAAM,UACN,KAAM,CACJ,YAAa,8EACb,YAAa,EACf,EACA,eAAgB,GAChB,OAAQ,CACN,CACE,KAAM,SACN,WAAY,CACV,aAAc,CACZ,KAAM,UACN,QAAS,EACX,EACA,mBAAoB,CAClB,KAAM,UACN,QAAS,EACX,EACA,cAAe,CACb,KAAM,QACN,MAAO,CAAE,KAAM,QAAS,EACxB,QAAS,CAAC,GAAGD,CAAsB,CACrC,CACF,EACA,qBAAsB,EACxB,CACF,EACA,SAAU,CACR,YACE,oLACF,cAAe,qDACf,YAAa,wDACf,CACF,EAEA,OAAO,EAAS,CACd,IAAME,EAAUC,EAAQ,QA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AAW,QAAQT,EAAK,OAAO,MAAM,EAMlDW,EAAWX,EAAK,UAAU,IAAK,GAAeS,EAAW,QAAQG,CAAC,CAAC,CAAC,CAAC,KAAK,IAAI,EAC9EC,EAAYF,EAAW,SAASZ,EAAW,GAAGY,EAAS,GAAK,GAElEjB,EAAQ,OAAO,CACb,OACA,UAAW,cACX,KAAM,CAAE,OAAQK,CAAW,EAC3B,QAAS,CACP,CACE,UAAW,gBACX,IAAI,EAAO,CACT,OAAOe,EAAM,YAAYd,EAAM,GAAGU,EAAW,oCAAoCG,EAAU,KAAK,CAClG,CACF,EACA,CACE,UAAW,cACX,IAAI,EAAO,CACT,OAAOC,EAAM,YACXd,EACA,GAAGU,EAAW,uCAAuCG,EAAU,kCACjE,CACF,CACF,CACF,CACF,CAAC,CACH,CACF,CACF,CACF,CACF"}
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import{
|
|
1
|
+
import{isInsideTaggedDeclaration as e}from"../utils/boundary-tags.js";import{childNodes as t,descendants as n}from"../utils/ast-walk.js";import{containsAwait as r}from"../utils/async-detection.js";const i=/* @__PURE__ */ new Set([`isSome`,`isRight`,`isSuccess`]),a=/* @__PURE__ */ new Set([`isNone`,`isLeft`,`isFailure`]),o={isSome:null,isNone:null,isRight:{param:`left`,member:`value`},isLeft:{param:`left`,member:`value`},isSuccess:{param:`error`,member:`error`},isFailure:{param:`error`,member:`error`}},s=[`get`,`orThrow`],c=`value`;function l(e){return e.type===`Literal`&&e.value===null||e.type===`Identifier`&&e.name===`undefined`}function u(e,t){if(e.type!==`CallExpression`||e.callee.type!==`MemberExpression`)return null;let n=e.callee.property.name,r=t.getText(e.callee.object),s=o[n]??null;return i.has(n)?{obj:r,isNegated:!1,failure:s}:a.has(n)?{obj:r,isNegated:!0,failure:s}:null}const d=e=>e.replace(/\s+/g,``),f={members:[c],methods:s};function p(e,n,r,i){let a=e=>{let t=e.type===`TSNonNullExpression`?e.expression:e;return d(i.getText(t))===d(n)},o=(e,t)=>e.type===`MemberExpression`&&!e.computed&&e.property.type===`Identifier`&&t.includes(e.property.name)&&a(e.object),s=e=>{let n=e.parent,i=n?.type===`CallExpression`&&n.callee===e,a=n?.type===`AssignmentExpression`&&n.left===e||n?.type===`UpdateExpression`;return o(e,r.members)&&!i&&!a||e.type===`CallExpression`&&e.arguments.length===0&&o(e.callee,r.methods)?[e.range]:t(e).flatMap(s)};return s(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,r,i){return n(e).some(e=>e.type===`MemberExpression`&&!e.computed&&e.property.type===`Identifier`&&e.property.name===r&&d(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,r){let i=S(e);if(!i)return null;if(i.exit.type===`ThrowStatement`)return`throw`;if(i.extraWork)return`effect`;let a=i.exit.argument;if(!a)return`effect`;if(d(r.getText(a))===t)return`passthrough`;let o=a.type===`CallExpression`?a.callee:null,s=o?.type===`Identifier`?o.name:o?.type===`MemberExpression`&&o.property.type===`Identifier`?o.property.name:null;if(s&&b.has(s)){let e=a.arguments??[];return e.length===0||e.length===1&&n!==null&&d(r.getText(e[0]))===`${t}.${n}`?`passthrough`:`mappedFailure`}return n!==null&&x(a,t,n,r)?`effect`:`default`}function w(e,t,r){let i=e.flatMap(e=>n(e));return!i.some(e=>e.type===`AssignmentExpression`&&d(r.getText(e.left))===t)&&i.some(e=>{if(e.type!==`MemberExpression`||d(r.getText(e.object))!==t)return!1;let n=e.property.type===`Identifier`?e.property.name:null;if(n===c)return!0;let i=e.parent;return n===null||!s.includes(n)||i?.type!==`CallExpression`||i.callee!==e?!1:!(n===`orThrow`&&i.arguments.length>0)})}function T(e,t){if(e.type!==`IfStatement`||e.alternate)return null;let n=u(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),o=n.minComplexity||2,s=n.checkNullable===!0,c=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(!c)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 o=a.body,s=o.slice(o.indexOf(e)+1),l=d(i.obj);if(!w(s,l,n))return;let u=C(e.consequent,l,i.failure?.member??null,n);if(!u)return;let m=s.some(e=>r(e)),h=(u===`passthrough`||u===`mappedFailure`)&&o.filter(e=>{let t=T(e,n);if(!t)return!1;let r=d(t.obj),i=o.slice(o.indexOf(e)+1),a=C(e.consequent,r,t.failure?.member??null,n);return(a===`passthrough`||a===`mappedFailure`)&&w(i,r,n)}).length>1;t.report({node:e,messageId:`preferFoldGuard`,data:{receiver:i.obj,advice:h?f(m):p[u](i.obj,m)}})}function h(e){let n=t.sourceCode;if(e.type!==`IfStatement`||!e.alternate)return null;let r=u(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,[d,f]=c?[i,a]:[a,i];return`return ${_(s,l,d,f,n)}`}function g(e){let n=t.sourceCode,r=u(e.test,n);if(!r)return[];let{obj:i,isNegated:a,failure:o}=r,[s,c]=a?[e.consequent,e.alternate]:[e.alternate,e.consequent],f=n.getText(s),p=n.getText(c);if(d(p)===d(i))return s.type===`Literal`||s.type===`TemplateLiteral`||l(s)?[]:[{messageId:`suggestOr`,data:{receiver:i,alternative:f},fix:t=>t.replaceText(e,`${i}.or(${f})`)}];let m=_(i,o,s,c,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(s&&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)>=o&&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`||!l(e.consequent)&&!l(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","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","rule","options","context","allowInteropMarker","isExemptByMarker","isInsideTaggedDeclaration","minComplexity","checkNullable","generateFoldFromIf","extracted","thenExpr","elseExpr","kept","c","n","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 } from \"../utils/ast-walk\"\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\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 },\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 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\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 },\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 },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E,EAAY,YAIb7E,EAAK,QAAUA,EAAK,OAAO,OAAS,eAGpC8C,EAAkB9C,CAAI,GAAKqD,GAC7BJ,EAAQ,OAAO,CACb,OACA,UAAW,aACX,KAAM,CAAE,KAAM4B,EAAY,IAAK,EAC/B,QAASH,EAAiB1E,CAAI,CAChC,CAAC,EAEL,CAEA,MAAO,CACL,YAAY,EAAe,CACrBmD,EAAiBnD,CAAI,GACzB4E,EAAmB5E,CAAI,CACzB,EAEA,sBAAsB,EAAe,CACnC,GAAImD,EAAiBnD,CAAI,EAAG,OAC5B,IAAM6E,EAAcN,EAAevE,EAAK,IAAI,GAKxC6E,EAAY,MAAQ,YAAe,GAAiB7E,EAAK,UAAU,GAAK,GAAiBA,EAAK,SAAS,IAGvG6E,EAAY,WACd5B,EAAQ,OAAO,CACb,OACA,UAAW,oBACX,KAAM,CAAE,KAAM4B,EAAY,IAAK,EAC/B,QAASP,EAAwBtE,EAAK,IAAI,EAAIiE,EAAmBjE,CAAI,EAAI,CAAC,CAC5E,CAAC,CAEL,CACF,CACF,CACF"}
|
|
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: isFunctypePredicateCall(node.test) ? ternarySuggestions(node) : [],\n })\n }\n },\n }\n },\n}\n\nexport default rule\n"],"mappings":"qMAQA,MAAMA,kBAA2C,IAAI,IAAI,CAAC,SAAU,UAAW,WAAW,CAAC,EAIrFC,kBAA2C,IAAI,IAAI,CAAC,SAAU,SAAU,WAAW,CAAC,EAUpFC,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,O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B,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,2 +1,3 @@
|
|
|
1
|
-
import{
|
|
1
|
+
import{flowsIntoArraySlot as e,flowsIntoMutableArraySlot as t,hasTypeInformation as n,isUntypedExpression as r}from"../utils/type-aware.js";import{descendants as i}from"../utils/ast-walk.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){return e.type===`VariableDeclarator`&&!!e.id?.typeAnnotation||e.type===`TSTypeAnnotation`}const A={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))return{};let y=u.options[0]||{},A=y.wireTypes??l,j=y.allowArraysInTests!==!1,M=y.allowReadonlyArrays!==!1,N=y.allowArrayLiterals===!0,P=a(u);function F(){let e=u.filename;return/\.(test|spec)\.(ts|js|tsx|jsx)$/.test(e)||e.includes(`__tests__`)||e.includes(`/test/`)||e.includes(`/tests/`)}function I(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 L(e,t){return t?.type===`CallExpression`&&t.callee.type===`Identifier`&&P.has(t.callee.name)&&t.arguments.includes(e)}function R(t){if(e(t,u)===!0||w(t))return!0;let n=t.parent;return n?.type===`SpreadElement`&&n.parent?.type===`ArrayExpression`&&e(n.parent,u)===!0}function z(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=>R(e.identifier)||C(e.identifier))}function B(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 V(e){return B(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 H={};function U(e){if(!H.map){let e=i(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]]:[]});H.map=new globalThis.Map(e.reverse())}return H.map.get(e)??null}function W(e){return B(e).some(({identifier:e})=>t(e,u)===!0)}function G(e,n,i){let a=O(e),o=e=>e.type===`TSAsExpression`?o(e.expression):e;if(a&&t(a,u)===!0)return;let s=a?o(a):null,c=s!==null&&s.type!==`ArrayExpression`&&r(s,u)===!0;if(a&&c){u.report({node:e,messageId:`preferWireCast`,data:{type:n,arrayType:i},suggest:[{messageId:`suggestReadonlyArray`,data:{type:n},fix:t=>t.replaceText(e,`ReadonlyArray<${n}>`)}]});return}let l=E(e);if(l!==null&&B(l).some(({identifier:e})=>{let n=e.parent;return n?.type===`CallExpression`&&n.callee===e&&t(n,u)===!0}))return;let d=D(e),f=d===null?null:U(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(W(p))return;let t=V(p);if(t){u.report({node:e,messageId:`mutatedArray`,data:{name:p.name,how:t}});return}}K(e,n,i)}function K(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,A)||j&&F())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&&M)return;let r=u.sourceCode,i=r.getText(e.elementType),a=n?t:e,o=r.getText(a);if(!n){G(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,A)||j&&F())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`){G(e,I(e,t)||`T`,t.getText(e));return}if(n===`ReadonlyArray`){if(M)return;let n=I(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(t){if(j&&F()||N||t.elements.length===0)return;let r=t.parent;if(r&&o(r,P)||h(r)||m(t,e=>e.type===`ArrayExpression`)||m(t,k))return;let i=v(t),a=i.parent;if(g(r)||e(t,u)===!0||e(i,u)===!0||L(i,a)||x(t)||x(i))return;let l=b(i);if(l!==i&&(S(l)||e(l,u)===!0)||w(t))return;if(a?.type===`VariableDeclarator`&&a.id?.type===`Identifier`){let e=V(a.id);if(e){u.report({node:t,messageId:`mutatedArray`,data:{name:a.id.name,how:e}});return}}if(!n(u)||z(a))return;if(t.elements.some(e=>e!==null&&e.type===`SpreadElement`)){u.report({node:t,messageId:`preferListLiteral`});return}let d=u.sourceCode,f=t.elements.filter(e=>e!==null).map(e=>d.getText(e)),p=[{messageId:`suggestListOf`,fix(e){return e.replaceText(t,`List.of(${f.join(`, `)})`)}}];c(d,`List`)||p.push({messageId:`suggestAddImport`,data:{symbol:`List`},fix:s(d,`List`)}),u.report({node:t,messageId:`preferListLiteral`,suggest:p})}}}};export{A as default};
|
|
2
3
|
//# sourceMappingURL=prefer-list.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"prefer-list.js","names":["NON_CHILD_KEYS","astChildren","node","k","v","ancestorSatisfies","parent","pred","isListFactoryArg","hasOwnTypeAnnotation","rule","WIRE_TYPES_SCHEMA","options","context","wireTypes","DEFAULT_WIRE_TYPES","allowArraysInTests","allowReadonlyArrays","allowArrayLiterals","functypeImports","getFunctypeImportsLegacy","isInTestFile","filename","findTypeParameter","findInNode","n","sourceCode","c","child","r","isInsideWireType","isReadonly","elementType","reportNode","fullType","suggest","fixer","hasFunctypeSymbol","createImportFixer","typeName","typeParam","resolvedType","isFunctypeCall","el","elementTexts"],"sources":["../../src/rules/prefer-list.ts"],"sourcesContent":["import type { Rule } from \"eslint\"\n\nimport type { ASTNode } from \"../types/ast\"\nimport { getFunctypeImportsLegacy, isFunctypeCall } from \"../utils/functype-detection\"\nimport { createImportFixer, hasFunctypeSymbol } from \"../utils/import-fixer\"\nimport { DEFAULT_WIRE_TYPES, isInsideWireType, WIRE_TYPES_SCHEMA } from \"../utils/wire-types\"\n\n/** AST keys that don't represent syntax children — back-edges and source metadata. */\nconst NON_CHILD_KEYS: ReadonlySet<string> = new Set([\"parent\", \"loc\", \"range\"])\n\n/** AST children of `node`: drops back-edges, flattens array-valued keys, filters non-object leaves. */\nfunction astChildren(node: ASTNode): readonly unknown[] {\n return Object.entries(node)\n .filter(([k]) => !NON_CHILD_KEYS.has(k))\n .flatMap(([, v]) => (Array.isArray(v) ? v : [v]))\n .filter((v) => v !== null && typeof v === \"object\")\n}\n\n/** True iff any ancestor of `node` satisfies `pred`. Pure tail recursion. */\nfunction ancestorSatisfies(node: ASTNode | null | undefined, pred: (n: ASTNode) => boolean): boolean {\n const parent = node?.parent as ASTNode | undefined\n if (!parent) return false\n return pred(parent) || ancestorSatisfies(parent, pred)\n}\n\n/** `parent` is `List.from(arr)` or `List.of(...arr)`. */\nfunction isListFactoryArg(parent: ASTNode | null | undefined): boolean {\n return (\n parent?.type === \"CallExpression\" &&\n parent.callee.type === \"MemberExpression\" &&\n parent.callee.object.type === \"Identifier\" &&\n parent.callee.object.name === \"List\" &&\n [\"from\", \"of\"].includes(parent.callee.property.name)\n )\n}\n\n/** `node` is a VariableDeclarator with its own type annotation, or a TSTypeAnnotation node directly. */\nfunction hasOwnTypeAnnotation(node: ASTNode): boolean {\n return (node.type === \"VariableDeclarator\" && Boolean(node.id?.typeAnnotation)) || node.type === \"TSTypeAnnotation\"\n}\n\nconst rule: Rule.RuleModule = {\n meta: {\n type: \"suggestion\",\n hasSuggestions: true,\n docs: {\n description: \"Prefer List<T> over native arrays for immutable collections\",\n recommended: true,\n },\n schema: [\n {\n type: \"object\",\n properties: {\n allowArraysInTests: {\n type: \"boolean\",\n default: true,\n },\n wireTypes: WIRE_TYPES_SCHEMA,\n allowReadonlyArrays: {\n type: \"boolean\",\n default: true,\n },\n allowArrayLiterals: {\n type: \"boolean\",\n default: false,\n },\n },\n additionalProperties: false,\n },\n ],\n messages: {\n preferList: \"Prefer List<{{type}}> over array type {{arrayType}}\",\n preferListLiteral: \"Prefer List.of(...) or List.from([...]) over array literal\",\n suggestListType: \"Replace with List<{{type}}>\",\n suggestListOf: \"Replace with List.of(...)\",\n suggestAddImport: \"Add {{symbol}} import from functype\",\n },\n },\n\n create(context) {\n const options = context.options[0] || {}\n // Everything inside `Wire<…>` is the declared serialization shape (#325 B).\n const wireTypes: ReadonlyArray<string> = options.wireTypes ?? DEFAULT_WIRE_TYPES\n const allowArraysInTests = options.allowArraysInTests !== false\n const allowReadonlyArrays = options.allowReadonlyArrays !== false\n const allowArrayLiterals = options.allowArrayLiterals === true\n\n // Get functype imports if available (but still apply rule even without explicit import)\n const functypeImports = getFunctypeImportsLegacy(context)\n\n function isInTestFile() {\n const filename = context.filename\n return (\n /\\.(test|spec)\\.(ts|js|tsx|jsx)$/.test(filename) ||\n filename.includes(\"__tests__\") ||\n filename.includes(\"/test/\") ||\n filename.includes(\"/tests/\")\n )\n }\n\n function findTypeParameter(node: ASTNode, sourceCode: typeof context.sourceCode): string | null {\n // Pure pre-order search: look at this node, then recursively at each\n // child until we find a TSTypeParameterInstantiation with a first param.\n function findInNode(n: ASTNode): string | null {\n if (n.type === \"TSTypeParameterInstantiation\" && n.params && n.params[0]) {\n return sourceCode.getText(n.params[0])\n }\n const results = astChildren(n)\n .filter((c): c is ASTNode => typeof (c as ASTNode)?.type === \"string\")\n .map((child) => findInNode(child))\n return results.find((r) => r !== null) ?? null\n }\n return findInNode(node)\n }\n\n return {\n TSArrayType(node: ASTNode) {\n if (isInsideWireType(node, wireTypes)) return\n if (allowArraysInTests && isInTestFile()) return\n\n // `readonly T[]` parses as TSTypeOperator(operator: \"readonly\") wrapping TSArrayType.\n // When the parent is that readonly wrapper, we treat the whole `readonly T[]` as\n // the reported unit — both for gating (parity with the ReadonlyArray<T> branch\n // below) and for the suggestion's replacement range. Replacing only the inner\n // TSArrayType would leave `readonly List<T>` behind, which is invalid TS\n // (TS1354: `readonly` only applies to array/tuple types).\n const parent = node.parent as ASTNode | undefined\n const isReadonly =\n parent?.type === \"TSTypeOperator\" && (parent as { operator?: string }).operator === \"readonly\"\n\n if (isReadonly && allowReadonlyArrays) return\n\n const sourceCode = context.sourceCode\n const elementType = sourceCode.getText(node.elementType)\n const reportNode = isReadonly ? (parent as ASTNode) : node\n const fullType = sourceCode.getText(reportNode)\n\n const suggest: Rule.SuggestionReportDescriptor[] = [\n {\n messageId: \"suggestListType\",\n data: { type: elementType },\n fix(fixer: Rule.RuleFixer) {\n return fixer.replaceText(reportNode, `List<${elementType}>`)\n },\n },\n ]\n\n if (!hasFunctypeSymbol(sourceCode, \"List\")) {\n suggest.push({\n messageId: \"suggestAddImport\",\n data: { symbol: \"List\" },\n fix: createImportFixer(sourceCode, \"List\"),\n })\n }\n\n context.report({\n node: reportNode,\n messageId: \"preferList\",\n data: {\n type: elementType,\n arrayType: fullType,\n },\n suggest,\n })\n },\n\n TSTypeReference(node: ASTNode) {\n if (isInsideWireType(node, wireTypes)) return\n if (allowArraysInTests && isInTestFile()) return\n\n const sourceCode = context.sourceCode\n\n // Get type name - handle both simple identifiers and member expressions\n if (!node.typeName) return // No type name found\n\n const typeName = node.typeName.type === \"Identifier\" ? node.typeName.name : sourceCode.getText(node.typeName)\n\n // Handle Array<T> syntax\n if (typeName === \"Array\") {\n // Look for type parameters in child nodes\n const typeParam = findTypeParameter(node, sourceCode)\n const fullType = sourceCode.getText(node)\n\n const resolvedType = typeParam || \"T\"\n\n const suggest: Rule.SuggestionReportDescriptor[] = [\n {\n messageId: \"suggestListType\",\n data: { type: resolvedType },\n fix(fixer: Rule.RuleFixer) {\n return fixer.replaceText(node, `List<${resolvedType}>`)\n },\n },\n ]\n\n if (!hasFunctypeSymbol(sourceCode, \"List\")) {\n suggest.push({\n messageId: \"suggestAddImport\",\n data: { symbol: \"List\" },\n fix: createImportFixer(sourceCode, \"List\"),\n })\n }\n\n context.report({\n node,\n messageId: \"preferList\",\n data: {\n type: resolvedType,\n arrayType: fullType,\n },\n suggest,\n })\n }\n\n // Handle ReadonlyArray<T> — gated on allowReadonlyArrays (parity with `readonly T[]`).\n if (typeName === \"ReadonlyArray\") {\n if (allowReadonlyArrays) return\n\n const typeParam = findTypeParameter(node, sourceCode)\n const fullType = sourceCode.getText(node)\n const resolvedType = typeParam || \"T\"\n\n const suggest: Rule.SuggestionReportDescriptor[] = [\n {\n messageId: \"suggestListType\",\n data: { type: resolvedType },\n fix(fixer: Rule.RuleFixer) {\n return fixer.replaceText(node, `List<${resolvedType}>`)\n },\n },\n ]\n\n if (!hasFunctypeSymbol(sourceCode, \"List\")) {\n suggest.push({\n messageId: \"suggestAddImport\",\n data: { symbol: \"List\" },\n fix: createImportFixer(sourceCode, \"List\"),\n })\n }\n\n context.report({\n node,\n messageId: \"preferList\",\n data: {\n type: resolvedType,\n arrayType: fullType,\n },\n suggest,\n })\n }\n },\n\n ArrayExpression(node: ASTNode) {\n if (allowArraysInTests && isInTestFile()) return\n if (allowArrayLiterals) return\n\n // Only flag non-empty arrays to avoid noise\n if (node.elements.length === 0) return\n\n const parent = node.parent\n\n // Don't flag arrays that are already arguments to functype calls.\n if (parent && isFunctypeCall(parent, functypeImports)) return\n\n // Don't flag arrays that are arguments to List.from / List.of.\n if (isListFactoryArg(parent)) return\n\n // Don't flag nested array literals — let the outermost one handle it.\n if (ancestorSatisfies(node, (n) => n.type === \"ArrayExpression\")) return\n\n // Don't flag array literals that already live in a type-annotated\n // context (those are handled by the type-checking rules).\n if (ancestorSatisfies(node, hasOwnTypeAnnotation)) return\n\n // Check if any element is a SpreadElement — ambiguous semantics, skip suggestions\n const hasSpread = node.elements.some((el) => el !== null && el.type === \"SpreadElement\")\n\n if (hasSpread) {\n context.report({\n node,\n messageId: \"preferListLiteral\",\n })\n return\n }\n\n const sourceCode = context.sourceCode\n const elementTexts = node.elements.filter((el) => el !== null).map((el) => sourceCode.getText(el))\n\n const suggest: Rule.SuggestionReportDescriptor[] = [\n {\n messageId: \"suggestListOf\",\n fix(fixer: Rule.RuleFixer) {\n return fixer.replaceText(node, `List.of(${elementTexts.join(\", \")})`)\n },\n },\n ]\n\n if (!hasFunctypeSymbol(sourceCode, \"List\")) {\n suggest.push({\n messageId: \"suggestAddImport\",\n data: { symbol: \"List\" },\n fix: createImportFixer(sourceCode, \"List\"),\n })\n }\n\n context.report({\n node,\n messageId: \"preferListLiteral\",\n suggest,\n })\n },\n }\n },\n}\n\nexport default rule\n"],"mappings":"2RAQA,MAAMA,kBAAsC,IAAI,IAAI,CAAC,SAAU,MAAO,OAAO,CAAC,EAG9E,SAASC,EAAY,EAAmC,CACtD,OAAO,OAAO,QAAQC,CAAI,CAAC,CACxB,QAAQ,CAACC,KAAO,CAACH,EAAe,IAAIG,CAAC,CAAC,CAAC,CACvC,SAAS,EAAGC,KAAQ,MAAM,QAAQA,CAAC,EAAIA,EAAI,CAACA,CAAC,CAAE,CAAC,CAChD,OAAQ,GAAoB,OAAOA,GAAM,YAA3BA,CAAmC,CACtD,CAGA,SAASC,EAAkB,EAAkC,EAAwC,CACnG,IAAMC,EAASJ,GAAM,OAErB,OADKI,EACEC,EAAKD,CAAM,GAAKD,EAAkBC,EAAQC,CAAI,EADjC,EAEtB,CAGA,SAASC,EAAiB,EAA6C,CACrE,OACEF,GAAQ,OAAS,kBACjBA,EAAO,OAAO,OAAS,oBACvBA,EAAO,OAAO,OAAO,OAAS,cAC9BA,EAAO,OAAO,OAAO,OAAS,QAC9B,CAAC,OAAQ,IAAI,CAAC,CAAC,SAASA,EAAO,OAAO,SAAS,IAAI,CAEvD,CAGA,SAASG,EAAqB,EAAwB,CACpD,OAAQP,EAAK,OAAS,sBAAwB,EAAQA,EAAK,IAAI,gBAAoBA,EAAK,OAAS,kBACnG,CAEA,MAAMQ,E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AK,GAAOjB,EAAW,QAAQiB,CAAE,CAAC,EAE3FR,EAA6C,CACjD,CACE,UAAW,gBACX,IAAI,EAAuB,CACzB,OAAOC,EAAM,YAAYlC,EAAM,WAAW0C,EAAa,KAAK,IAAI,EAAE,EAAE,CACtE,CACF,CACF,EAEKP,EAAkBX,EAAY,MAAM,GACvCS,EAAQ,KAAK,CACX,UAAW,mBACX,KAAM,CAAE,OAAQ,MAAO,EACvB,IAAKG,EAAkBZ,EAAY,MAAM,CAC3C,CAAC,EAGHb,EAAQ,OAAO,CACb,OACA,UAAW,oBACX,SACF,CAAC,CACH,CACF,CACF,CACF"}
|
|
1
|
+
{"version":3,"file":"prefer-list.js","names":["NON_CHILD_KEYS","astChildren","node","k","v","ancestorSatisfies","parent","pred","isListFactoryArg","isTupleAssertion","raw","annotation","MUTATING_METHODS","throughConditionals","TERMINAL_METHODS","chainEnd","member","receiver","call","chainEndsInSingleValue","isTerminalRead","isJsxChild","grand","name","isSpreadIntoCall","annotatedBinding","climb","n","typeNode","returningFunctionName","fn","declarator","annotatedFieldName","field","castOf","child","outer","current","hasOwnTypeAnnotation","rule","WIRE_TYPES_SCHEMA","header","context","comment","options","wireTypes","DEFAULT_WIRE_TYPES","allowArraysInTests","allowReadonlyArrays","allowArrayLiterals","functypeImports","getFunctypeImportsLegacy","isInTestFile","filename","findTypeParameter","findInNode","sourceCode","c","r","isFunctypeConstructorArg","reachesArraySlot","flowsIntoArraySlot","isOnlyHandedToArraySlots","uses","variable","ref","usesOf","owner","binding","mutationOf","identifier","how","mutatedFields","fieldMutationIn","entries","descendants","method","target","feedsMutableSlot","flowsIntoMutableArraySlot","checkMutable","cast","reportNode","castSource","source","decodes","isUntypedExpression","elementType","fullType","fixer","fnName","fieldMutation","reportMutable","suggest","hasFunctypeSymbol","createImportFixer","isInsideWireType","isReadonly","typeName","typeParam","resolvedType","isFunctypeCall","targetParent","end","hasTypeInformation","el","elementTexts"],"sources":["../../src/rules/prefer-list.ts"],"sourcesContent":["import type { Rule } from \"eslint\"\n\nimport type { ASTNode } from \"../types/ast\"\nimport { descendants } from \"../utils/ast-walk\"\nimport { getFunctypeImportsLegacy, isFunctypeCall } from \"../utils/functype-detection\"\nimport { createImportFixer, hasFunctypeSymbol } from \"../utils/import-fixer\"\nimport {\n flowsIntoArraySlot,\n flowsIntoMutableArraySlot,\n hasTypeInformation,\n isUntypedExpression,\n} from \"../utils/type-aware\"\nimport { DEFAULT_WIRE_TYPES, isInsideWireType, WIRE_TYPES_SCHEMA } from \"../utils/wire-types\"\n\n/** AST keys that don't represent syntax children — back-edges and source metadata. */\nconst NON_CHILD_KEYS: ReadonlySet<string> = new Set([\"parent\", \"loc\", \"range\"])\n\n/** AST children of `node`: drops back-edges, flattens array-valued keys, filters non-object leaves. */\nfunction astChildren(node: ASTNode): readonly unknown[] {\n return Object.entries(node)\n .filter(([k]) => !NON_CHILD_KEYS.has(k))\n .flatMap(([, v]) => (Array.isArray(v) ? v : [v]))\n .filter((v) => v !== null && typeof v === \"object\")\n}\n\n/** True iff any ancestor of `node` satisfies `pred`. Pure tail recursion. */\nfunction ancestorSatisfies(node: ASTNode | null | undefined, pred: (n: ASTNode) => boolean): boolean {\n const parent = node?.parent as ASTNode | undefined\n if (!parent) return false\n return pred(parent) || ancestorSatisfies(parent, pred)\n}\n\n/** `parent` is `List.from(arr)` or `List.of(...arr)`. */\nfunction isListFactoryArg(parent: ASTNode | null | undefined): boolean {\n return (\n parent?.type === \"CallExpression\" &&\n parent.callee.type === \"MemberExpression\" &&\n parent.callee.object.type === \"Identifier\" &&\n parent.callee.object.name === \"List\" &&\n [\"from\", \"of\"].includes(parent.callee.property.name)\n )\n}\n\n/**\n * `[…] as const` or `[…] as [string, ...string[]]`: the literal is asserted to a tuple, a fixed shape that\n * `List` can't express (an enum's values, the argument zod's `z.enum` requires).\n */\nfunction isTupleAssertion(parent: ASTNode | null | undefined): boolean {\n const raw = parent?.type === \"TSAsExpression\" ? parent.typeAnnotation : undefined\n const annotation = raw?.type === \"TSTypeOperator\" ? raw.typeAnnotation : raw\n if (annotation?.type === \"TSTupleType\") return true\n return (\n annotation?.type === \"TSTypeReference\" &&\n annotation.typeName?.type === \"Identifier\" &&\n annotation.typeName.name === \"const\"\n )\n}\n\n/** Array methods that change the array in place. */\nconst MUTATING_METHODS: ReadonlySet<string> = new Set([\n \"push\",\n \"pop\",\n \"shift\",\n \"unshift\",\n \"splice\",\n \"sort\",\n \"reverse\",\n \"fill\",\n \"copyWithin\",\n])\n\n/**\n * The expression a literal stands in for once conditionals are looked through: `[x]` in\n * `List(c ? xs : [x])` or `const args = c ? [a] : [\"--fix\", a]` behaves like the whole conditional.\n */\nfunction throughConditionals(node: ASTNode): ASTNode {\n const parent = node.parent as ASTNode | undefined\n if (parent?.type === \"ConditionalExpression\" && parent.test !== node) return throughConditionals(parent)\n if (parent?.type === \"LogicalExpression\") return throughConditionals(parent)\n return node\n}\n\n/**\n * Methods that turn an array into a single value: using a collection only through these makes it a\n * temporary (`lines.join(\"\\n\")`, `[a, b].includes(x)`). Methods that produce another collection\n * (`map`, `filter`, `slice`, `concat`, `reduce`…) are collection work, which is what `List` is for.\n */\nconst TERMINAL_METHODS: ReadonlySet<string> = new Set([\n \"join\",\n \"includes\",\n \"indexOf\",\n \"lastIndexOf\",\n \"some\",\n \"every\",\n \"find\",\n \"findIndex\",\n \"findLast\",\n \"findLastIndex\",\n \"at\",\n])\n\n/**\n * The end of a method chain that starts at `receiver`: `[…].map(f).filter(g)` → the `.filter(g)` call.\n * `receiver` itself when no method is called on it.\n */\nfunction chainEnd(receiver: ASTNode): ASTNode {\n const member = receiver.parent as ASTNode | undefined\n const call = member?.parent as ASTNode | undefined\n if (member?.type !== \"MemberExpression\" || member.object !== receiver) return receiver\n return call?.type === \"CallExpression\" && call.callee === member ? chainEnd(call) : receiver\n}\n\n/**\n * Does the method chain starting at `receiver` end in a single value: `[a, b].filter(Boolean).length`,\n * `[name, email].filter(nonEmpty).join(\"\\n\")`, `[...xs].sort(byRank)[0]`? Then every array in it is a\n * temporary, the same as `lines.join(\"\\n\")`.\n */\nfunction chainEndsInSingleValue(receiver: ASTNode): boolean {\n if (isTerminalRead(receiver)) return true\n const member = receiver.parent as ASTNode | undefined\n const call = member?.parent as ASTNode | undefined\n if (member?.type !== \"MemberExpression\" || member.object !== receiver) return false\n return call?.type === \"CallExpression\" && call.callee === member && chainEndsInSingleValue(call)\n}\n\n/** `{items.map((i) => <Row />)}`: an expression rendered as JSX children, which React takes as an array. */\nfunction isJsxChild(node: ASTNode): boolean {\n return (node.parent as ASTNode | undefined)?.type === \"JSXExpressionContainer\"\n}\n\n/**\n * Is `receiver` read down to a single value on the spot: `.length`, `[i]`, or a terminal method call?\n * The same test applies to a literal (`[a, b].includes(x)`) and to every use of a const (`lines.join`).\n */\nfunction isTerminalRead(receiver: ASTNode): boolean {\n const member = receiver.parent as ASTNode | undefined\n if (member?.type !== \"MemberExpression\" || member.object !== receiver) return false\n const grand = member.parent as ASTNode | undefined\n if (grand?.type === \"AssignmentExpression\" && grand.left === member) return false\n if (member.computed) return true\n const name = member.property?.type === \"Identifier\" ? member.property.name : null\n if (name === \"length\") return true\n return name !== null && TERMINAL_METHODS.has(name) && grand?.type === \"CallExpression\" && grand.callee === member\n}\n\n/**\n * Is `node` spread straight into a call's arguments, `and(...conds)` or `and(...(c ? [x] : []))`?\n * The function receives the elements one by one; the array is never a collection of your own.\n */\nfunction isSpreadIntoCall(node: ASTNode): boolean {\n const parent = node.parent as ASTNode | undefined\n if (!parent) return false\n if (parent.type === \"ConditionalExpression\" && parent.test !== node) return isSpreadIntoCall(parent)\n if (parent.type === \"LogicalExpression\" && parent.right === node) return isSpreadIntoCall(parent)\n return (\n parent.type === \"SpreadElement\" &&\n (parent.parent?.type === \"CallExpression\" || parent.parent?.type === \"NewExpression\")\n )\n}\n\n/** The `x` in `const x: T[] = …` or `(x: T[]) => …`, when the array type is (part of) its annotation. */\nfunction annotatedBinding(typeNode: ASTNode): ASTNode | null {\n const climb = (n: ASTNode | null | undefined): ASTNode | null => {\n if (!n) return null\n if (n.type === \"TSTypeAnnotation\") return n.parent?.type === \"Identifier\" ? (n.parent as ASTNode) : null\n if (n.type === \"TSAsExpression\" || n.type === \"TSSatisfiesExpression\" || n.type.endsWith(\"Statement\")) return null\n return climb(n.parent as ASTNode | undefined)\n }\n return climb(typeNode.parent as ASTNode | undefined)\n}\n\n/**\n * The name of the function whose declared return type *is* this array type: `f` in\n * `function f(): T[]` or `const f = (): T[] => …`. Null for anything nested (`(): { nodes: T[] }`).\n */\nfunction returningFunctionName(typeNode: ASTNode): ASTNode | null {\n const annotation = typeNode.parent as ASTNode | undefined\n const fn = annotation?.type === \"TSTypeAnnotation\" ? (annotation.parent as ASTNode | undefined) : undefined\n if (!fn || fn.returnType !== annotation) return null\n if (fn.type === \"FunctionDeclaration\") return fn.id?.type === \"Identifier\" ? (fn.id as ASTNode) : null\n const declarator = fn.parent as ASTNode | undefined\n return (fn.type === \"ArrowFunctionExpression\" || fn.type === \"FunctionExpression\") &&\n declarator?.type === \"VariableDeclarator\" &&\n declarator.init === fn &&\n declarator.id?.type === \"Identifier\"\n ? (declarator.id as ASTNode)\n : null\n}\n\n/** The property name when the array type annotates a field: `errors` in `{ errors: string[] }` or `class { errors: T[] }`. */\nfunction annotatedFieldName(typeNode: ASTNode): string | null {\n const annotation = typeNode.parent as ASTNode | undefined\n const field = annotation?.type === \"TSTypeAnnotation\" ? (annotation.parent as ASTNode | undefined) : undefined\n if (field?.type !== \"TSPropertySignature\" && field?.type !== \"PropertyDefinition\") return null\n return field.key?.type === \"Identifier\" && !field.computed ? field.key.name : null\n}\n\n/** The outermost `x as … as T[]` around an array type used as a cast target, or null. */\nfunction castOf(typeNode: ASTNode): ASTNode | null {\n const climb = (n: ASTNode | null | undefined, child: ASTNode): ASTNode | null => {\n if (!n || n.type === \"TSTypeAnnotation\" || n.type.endsWith(\"Statement\")) return null\n if (n.type === \"TSAsExpression\" && n.typeAnnotation === child) {\n const outer = (current: ASTNode): ASTNode =>\n current.parent?.type === \"TSAsExpression\" ? outer(current.parent as ASTNode) : current\n return outer(n)\n }\n return climb(n.parent as ASTNode | undefined, n)\n }\n return climb(typeNode.parent as ASTNode | undefined, typeNode)\n}\n\n/** `node` is a VariableDeclarator with its own type annotation, or a TSTypeAnnotation node directly. */\nfunction hasOwnTypeAnnotation(node: ASTNode): boolean {\n return (node.type === \"VariableDeclarator\" && Boolean(node.id?.typeAnnotation)) || node.type === \"TSTypeAnnotation\"\n}\n\nconst rule: Rule.RuleModule = {\n meta: {\n type: \"suggestion\",\n hasSuggestions: true,\n docs: {\n description: \"Prefer List<T> over native arrays for immutable collections\",\n recommended: true,\n },\n schema: [\n {\n type: \"object\",\n properties: {\n allowArraysInTests: {\n type: \"boolean\",\n default: true,\n },\n wireTypes: WIRE_TYPES_SCHEMA,\n allowReadonlyArrays: {\n type: \"boolean\",\n default: true,\n },\n allowArrayLiterals: {\n type: \"boolean\",\n default: false,\n },\n },\n additionalProperties: false,\n },\n ],\n messages: {\n preferList: \"Prefer List<{{type}}> over array type {{arrayType}}\",\n preferReadonlyOrList:\n \"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\",\n preferWireCast:\n \"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\",\n mutatedArray:\n \"{{name}} is a mutable array changed in place (.{{how}}()). Build it without mutation instead: map/filter/flatMap, a List, or a fold\",\n preferListLiteral: \"Prefer List.of(...) or List.from([...]) over array literal\",\n suggestListType: \"Replace with List<{{type}}>\",\n suggestReadonlyArray: \"Replace with ReadonlyArray<{{type}}>\",\n suggestListOf: \"Replace with List.of(...)\",\n suggestAddImport: \"Add {{symbol}} import from functype\",\n },\n },\n\n create(context) {\n // A generated file (`// @generated`, \"Auto-generated … DO NOT EDIT\") isn't edited by hand, so there's\n // nothing for its author to fix. Generators without a marker (Supabase types) need a config ignore.\n const header = context.sourceCode\n .getAllComments()\n .slice(0, 3)\n .map((comment) => comment.value)\n .join(\"\\n\")\n if (/@generated|auto-generated|do not edit/i.test(header)) return {}\n\n const options = context.options[0] || {}\n // Everything inside `Wire<…>` is the declared serialization shape (#325 B).\n const wireTypes: ReadonlyArray<string> = options.wireTypes ?? DEFAULT_WIRE_TYPES\n const allowArraysInTests = options.allowArraysInTests !== false\n const allowReadonlyArrays = options.allowReadonlyArrays !== false\n const allowArrayLiterals = options.allowArrayLiterals === true\n\n // Get functype imports if available (but still apply rule even without explicit import)\n const functypeImports = getFunctypeImportsLegacy(context)\n\n function isInTestFile() {\n const filename = context.filename\n return (\n /\\.(test|spec)\\.(ts|js|tsx|jsx)$/.test(filename) ||\n filename.includes(\"__tests__\") ||\n filename.includes(\"/test/\") ||\n filename.includes(\"/tests/\")\n )\n }\n\n function findTypeParameter(node: ASTNode, sourceCode: typeof context.sourceCode): string | null {\n // Pure pre-order search: look at this node, then recursively at each\n // child until we find a TSTypeParameterInstantiation with a first param.\n function findInNode(n: ASTNode): string | null {\n if (n.type === \"TSTypeParameterInstantiation\" && n.params && n.params[0]) {\n return sourceCode.getText(n.params[0])\n }\n const results = astChildren(n)\n .filter((c): c is ASTNode => typeof (c as ASTNode)?.type === \"string\")\n .map((child) => findInNode(child))\n return results.find((r) => r !== null) ?? null\n }\n return findInNode(node)\n }\n\n /** `List([...x])`, `Set([a, b])`: the literal is already being captured into a functype value. */\n function isFunctypeConstructorArg(node: ASTNode, parent: ASTNode | null | undefined): boolean {\n return (\n parent?.type === \"CallExpression\" &&\n parent.callee.type === \"Identifier\" &&\n functypeImports.has(parent.callee.name) &&\n parent.arguments.includes(node)\n )\n }\n\n /** Is `node` handed straight to an array-typed slot, directly or spread into a literal that is? */\n function reachesArraySlot(node: ASTNode): boolean {\n if (flowsIntoArraySlot(node, context) === true) return true\n if (isSpreadIntoCall(node)) return true\n const parent = node.parent as ASTNode | undefined\n return (\n parent?.type === \"SpreadElement\" &&\n parent.parent?.type === \"ArrayExpression\" &&\n flowsIntoArraySlot(parent.parent as ASTNode, context) === true\n )\n }\n\n /**\n * `const OPTIONS = [...]` whose every use hands it to an array-typed slot (`<Select data={OPTIONS} />`,\n * `db.insert(t).values(ROWS)`) or reads it down to a single value (`lines.join(\"\\n\")`, `xs.length`): data\n * built to give to a library, or a temporary, declared before it's used. Needs at least one local use; an exported\n * constant with no local use is still reported, because its consumers aren't visible here.\n */\n function isOnlyHandedToArraySlots(declarator: ASTNode | null | undefined): boolean {\n if (declarator?.type !== \"VariableDeclarator\" || declarator.id?.type !== \"Identifier\") return false\n const uses = context.sourceCode\n .getDeclaredVariables(declarator)\n .flatMap((variable) => variable.references.filter((ref) => !ref.init))\n return (\n uses.length > 0 &&\n uses.every((ref) => reachesArraySlot(ref.identifier as ASTNode) || isTerminalRead(ref.identifier as ASTNode))\n )\n }\n\n /** References to `binding` other than its declaration. */\n function usesOf(binding: ASTNode): ReadonlyArray<{ identifier: ASTNode }> {\n // The declaring node: a VariableDeclarator, a FunctionDeclaration (its name lives in the outer\n // scope) or, for a parameter, its function. getDeclaredVariables on it yields the binding.\n const owner = (binding.parent as ASTNode | undefined) ?? binding\n const variable =\n context.sourceCode.getDeclaredVariables(owner).find((v) => v.name === binding.name) ??\n context.sourceCode.getScope(binding).set.get(binding.name)\n return (variable?.references ?? [])\n .filter((ref) => !ref.init && ref.identifier !== binding)\n .map((ref) => ({ identifier: ref.identifier as ASTNode }))\n }\n\n /** The in-place mutation applied to `binding` (`push`, `sort`, `x[i] = …`), if any. */\n function mutationOf(binding: ASTNode): string | null {\n const found = usesOf(binding)\n .map(({ identifier }) => {\n const parent = identifier.parent as ASTNode | undefined\n if (parent?.type !== \"MemberExpression\" || parent.object !== identifier) return null\n const grand = parent.parent as ASTNode | undefined\n if (grand?.type === \"AssignmentExpression\" && grand.left === parent) return \"[index] =\"\n const name = parent.property?.type === \"Identifier\" && !parent.computed ? parent.property.name : null\n return name && MUTATING_METHODS.has(name) && grand?.type === \"CallExpression\" && grand.callee === parent\n ? name\n : null\n })\n .find((how) => how !== null)\n return found ?? null\n }\n\n /**\n * Fields mutated in place anywhere in the file, `errors` → `push` for `t.errors.push(e)`. Built once per\n * file, on first use, from the syntax tree.\n */\n const mutatedFields: { map?: ReadonlyMap<string, string> } = {}\n function fieldMutationIn(field: string): string | null {\n if (!mutatedFields.map) {\n const entries = descendants(context.sourceCode.ast as unknown as ASTNode).flatMap(\n (node): [string, string][] => {\n if (node.type !== \"CallExpression\" || node.callee?.type !== \"MemberExpression\") return []\n const method = node.callee.property?.type === \"Identifier\" ? node.callee.property.name : null\n const target = node.callee.object as ASTNode\n const name =\n target?.type === \"MemberExpression\" && target.property?.type === \"Identifier\" && !target.computed\n ? target.property.name\n : null\n return method && name && MUTATING_METHODS.has(method) ? [[name, method]] : []\n },\n )\n mutatedFields.map = new globalThis.Map(entries.reverse())\n }\n return mutatedFields.map.get(field) ?? null\n }\n\n /** Is `binding` handed to a slot that requires a mutable array (pg `query` values, ReactFlow `nodes`)? */\n function feedsMutableSlot(binding: ASTNode): boolean {\n return usesOf(binding).some(({ identifier }) => flowsIntoMutableArraySlot(identifier, context) === true)\n }\n\n /**\n * Report a mutable array type, unless a library demands it. The order matters: a library slot that\n * requires `T[]` makes the type correct as written; a binding mutated in place can't take\n * `ReadonlyArray` without a rewrite, so it gets advice instead of a suggestion that wouldn't compile;\n * a cast is decoded outside data, so it points at `Wire`.\n */\n function checkMutable(reportNode: ASTNode, elementType: string, fullType: string): void {\n const cast = castOf(reportNode)\n // The value under every `as`: `JSON.parse(raw)` in `JSON.parse(raw) as unknown as T[]`.\n const castSource = (n: ASTNode): ASTNode =>\n n.type === \"TSAsExpression\" ? castSource(n.expression as ASTNode) : n\n if (cast && flowsIntoMutableArraySlot(cast, context) === true) return\n // Only a cast of an untyped value (`JSON.parse`, `res.json()`, a raw row) is decoding outside data,\n // the Wire case. It needs type evidence: without it the rule can't tell decoding from re-casting a\n // typed value, so it gives the plain message rather than advice that flips when types are turned on.\n const source = cast ? castSource(cast) : null\n const decodes =\n source !== null && source.type !== \"ArrayExpression\" && isUntypedExpression(source, context) === true\n if (cast && decodes) {\n context.report({\n node: reportNode,\n messageId: \"preferWireCast\",\n data: { type: elementType, arrayType: fullType },\n suggest: [\n {\n messageId: \"suggestReadonlyArray\",\n data: { type: elementType },\n fix: (fixer: Rule.RuleFixer) => fixer.replaceText(reportNode, `ReadonlyArray<${elementType}>`),\n },\n ],\n })\n return\n }\n // `function allowedTools(): string[]` whose result goes to an SDK option typed `string[]`.\n const fnName = returningFunctionName(reportNode)\n const feedsFromCall =\n fnName !== null &&\n usesOf(fnName).some(({ identifier }) => {\n const call = identifier.parent as ASTNode | undefined\n return (\n call?.type === \"CallExpression\" &&\n call.callee === identifier &&\n flowsIntoMutableArraySlot(call, context) === true\n )\n })\n if (feedsFromCall) return\n // A field mutated somewhere in the file (`result.errors.push(e)`, `this.events.push(e)`): a\n // ReadonlyArray suggestion wouldn't compile, so give the mutation advice. Matched by name, which only\n // picks the message, never whether to report.\n const field = annotatedFieldName(reportNode)\n const fieldMutation = field === null ? null : fieldMutationIn(field)\n if (field !== null && fieldMutation !== null) {\n context.report({ node: reportNode, messageId: \"mutatedArray\", data: { name: field, how: fieldMutation } })\n return\n }\n const binding = annotatedBinding(reportNode)\n if (binding) {\n if (feedsMutableSlot(binding)) return\n const how = mutationOf(binding)\n if (how) {\n context.report({ node: reportNode, messageId: \"mutatedArray\", data: { name: binding.name, how } })\n return\n }\n }\n reportMutable(reportNode, elementType, fullType)\n }\n\n /**\n * A mutable `T[]` / `Array<T>` is the real defect: anything holding it can push, sort or splice.\n * `ReadonlyArray<T>` fixes that and still fits wherever a library expects an array, so it's offered\n * first; `List<T>` is for collections that live inside your own code.\n */\n function reportMutable(reportNode: ASTNode, elementType: string, fullType: string): void {\n const sourceCode = context.sourceCode\n const suggest: Rule.SuggestionReportDescriptor[] = [\n {\n messageId: \"suggestReadonlyArray\",\n data: { type: elementType },\n fix: (fixer: Rule.RuleFixer) => fixer.replaceText(reportNode, `ReadonlyArray<${elementType}>`),\n },\n {\n messageId: \"suggestListType\",\n data: { type: elementType },\n fix: (fixer: Rule.RuleFixer) => fixer.replaceText(reportNode, `List<${elementType}>`),\n },\n ]\n if (!hasFunctypeSymbol(sourceCode, \"List\")) {\n suggest.push({\n messageId: \"suggestAddImport\",\n data: { symbol: \"List\" },\n fix: createImportFixer(sourceCode, \"List\"),\n })\n }\n context.report({\n node: reportNode,\n messageId: \"preferReadonlyOrList\",\n data: { type: elementType, arrayType: fullType },\n suggest,\n })\n }\n\n return {\n TSArrayType(node: ASTNode) {\n if (isInsideWireType(node, wireTypes)) return\n if (allowArraysInTests && isInTestFile()) return\n\n // `readonly T[]` parses as TSTypeOperator(operator: \"readonly\") wrapping TSArrayType.\n // When the parent is that readonly wrapper, we treat the whole `readonly T[]` as\n // the reported unit — both for gating (parity with the ReadonlyArray<T> branch\n // below) and for the suggestion's replacement range. Replacing only the inner\n // TSArrayType would leave `readonly List<T>` behind, which is invalid TS\n // (TS1354: `readonly` only applies to array/tuple types).\n const parent = node.parent as ASTNode | undefined\n // `[string, ...string[]]`: a tuple's rest element must be written as an array type, and libraries\n // such as zod's `z.enum` require exactly that shape. The tuple is the type; its rest isn't a list.\n if (parent?.type === \"TSRestType\") return\n // `(...args: string[])`: a rest parameter is a fresh array on every call, owned by the callee.\n if (parent?.type === \"TSTypeAnnotation\" && parent.parent?.type === \"RestElement\") return\n\n const isReadonly =\n parent?.type === \"TSTypeOperator\" && (parent as { operator?: string }).operator === \"readonly\"\n\n if (isReadonly && allowReadonlyArrays) return\n\n const sourceCode = context.sourceCode\n const elementType = sourceCode.getText(node.elementType)\n const reportNode = isReadonly ? (parent as ASTNode) : node\n const fullType = sourceCode.getText(reportNode)\n\n if (!isReadonly) {\n checkMutable(reportNode, elementType, fullType)\n return\n }\n\n const suggest: Rule.SuggestionReportDescriptor[] = [\n {\n messageId: \"suggestListType\",\n data: { type: elementType },\n fix(fixer: Rule.RuleFixer) {\n return fixer.replaceText(reportNode, `List<${elementType}>`)\n },\n },\n ]\n\n if (!hasFunctypeSymbol(sourceCode, \"List\")) {\n suggest.push({\n messageId: \"suggestAddImport\",\n data: { symbol: \"List\" },\n fix: createImportFixer(sourceCode, \"List\"),\n })\n }\n\n context.report({\n node: reportNode,\n messageId: \"preferList\",\n data: {\n type: elementType,\n arrayType: fullType,\n },\n suggest,\n })\n },\n\n TSTypeReference(node: ASTNode) {\n if (isInsideWireType(node, wireTypes)) return\n if (allowArraysInTests && isInTestFile()) return\n\n const sourceCode = context.sourceCode\n\n // Get type name - handle both simple identifiers and member expressions\n if (!node.typeName) return // No type name found\n\n const typeName = node.typeName.type === \"Identifier\" ? node.typeName.name : sourceCode.getText(node.typeName)\n\n // Handle Array<T> syntax: mutable, same as T[]\n if (typeName === \"Array\") {\n const typeParam = findTypeParameter(node, sourceCode)\n checkMutable(node, typeParam || \"T\", sourceCode.getText(node))\n return\n }\n\n // Handle ReadonlyArray<T> — gated on allowReadonlyArrays (parity with `readonly T[]`).\n if (typeName === \"ReadonlyArray\") {\n if (allowReadonlyArrays) return\n\n const typeParam = findTypeParameter(node, sourceCode)\n const fullType = sourceCode.getText(node)\n const resolvedType = typeParam || \"T\"\n\n const suggest: Rule.SuggestionReportDescriptor[] = [\n {\n messageId: \"suggestListType\",\n data: { type: resolvedType },\n fix(fixer: Rule.RuleFixer) {\n return fixer.replaceText(node, `List<${resolvedType}>`)\n },\n },\n ]\n\n if (!hasFunctypeSymbol(sourceCode, \"List\")) {\n suggest.push({\n messageId: \"suggestAddImport\",\n data: { symbol: \"List\" },\n fix: createImportFixer(sourceCode, \"List\"),\n })\n }\n\n context.report({\n node,\n messageId: \"preferList\",\n data: {\n type: resolvedType,\n arrayType: fullType,\n },\n suggest,\n })\n }\n },\n\n ArrayExpression(node: ASTNode) {\n if (allowArraysInTests && isInTestFile()) return\n if (allowArrayLiterals) return\n\n // Only flag non-empty arrays to avoid noise\n if (node.elements.length === 0) return\n\n const parent = node.parent\n\n // Don't flag arrays that are already arguments to functype calls.\n if (parent && isFunctypeCall(parent, functypeImports)) return\n\n // Don't flag arrays that are arguments to List.from / List.of.\n if (isListFactoryArg(parent)) return\n\n // Don't flag nested array literals — let the outermost one handle it.\n if (ancestorSatisfies(node, (n) => n.type === \"ArrayExpression\")) return\n\n // Don't flag array literals that already live in a type-annotated\n // context (those are handled by the type-checking rules).\n if (ancestorSatisfies(node, hasOwnTypeAnnotation)) return\n\n // Look through `c ? xs : [x]` / `xs ?? [x]`: the checks below apply to the whole expression.\n const target = throughConditionals(node)\n const targetParent = target.parent as ASTNode | undefined\n\n // A literal asserted to a tuple (`as const`, `as [string, ...string[]]`) is a fixed shape.\n if (isTupleAssertion(parent)) return\n\n // With type information: a literal passed where an array is expected — drizzle's\n // `.values([...])`, an index definition, a schema `target: [...]` — is handed straight to code\n // that requires an array. It never becomes a collection in your own code, so it's the\n // boundary itself and `List` can't go there.\n if (flowsIntoArraySlot(node, context) === true || flowsIntoArraySlot(target, context) === true) return\n if (isFunctypeConstructorArg(target, targetParent)) return\n // Read down to one value on the spot (`[a, b].includes(x)`, `[a, b].filter(Boolean).join(\" \")`):\n // nothing is stored.\n if (chainEndsInSingleValue(node) || chainEndsInSingleValue(target)) return\n // A chain whose result goes to React or a library (`{[\"PDF\", \"DOCX\"].map((f) => <Chip />)}`,\n // `marks={[3, 4].map(…)}`): the transformed array is what's handed over, so the literal is too.\n const end = chainEnd(target)\n if (end !== target && (isJsxChild(end) || flowsIntoArraySlot(end, context) === true)) return\n // Spread into a call (`and(...(c ? [x] : []))`): the function gets the elements one by one.\n if (isSpreadIntoCall(node)) return\n // `const acc = [...]; acc.push(x)`: an accumulator. The defect is the mutation, so it gets the same\n // advice as a mutated `T[]` binding, not a List.of suggestion that has no push.\n if (targetParent?.type === \"VariableDeclarator\" && targetParent.id?.type === \"Identifier\") {\n const how = mutationOf(targetParent.id as ASTNode)\n if (how) {\n context.report({ node, messageId: \"mutatedArray\", data: { name: targetParent.id.name, how } })\n return\n }\n }\n // Without type information the rule can't tell a literal handed to a library (drizzle\n // `.values([...])`) from a collection of your own, so it reports neither rather than guess.\n if (!hasTypeInformation(context)) return\n if (isOnlyHandedToArraySlots(targetParent)) return\n\n // Check if any element is a SpreadElement — ambiguous semantics, skip suggestions\n const hasSpread = node.elements.some((el) => el !== null && el.type === \"SpreadElement\")\n\n if (hasSpread) {\n context.report({\n node,\n messageId: \"preferListLiteral\",\n })\n return\n }\n\n const sourceCode = context.sourceCode\n const elementTexts = node.elements.filter((el) => el !== null).map((el) => sourceCode.getText(el))\n\n const suggest: Rule.SuggestionReportDescriptor[] = [\n {\n messageId: \"suggestListOf\",\n fix(fixer: Rule.RuleFixer) {\n return fixer.replaceText(node, `List.of(${elementTexts.join(\", \")})`)\n },\n },\n ]\n\n if (!hasFunctypeSymbol(sourceCode, \"List\")) {\n suggest.push({\n messageId: \"suggestAddImport\",\n data: { symbol: \"List\" },\n fix: createImportFixer(sourceCode, \"List\"),\n })\n }\n\n context.report({\n node,\n messageId: \"preferListLiteral\",\n suggest,\n })\n },\n }\n },\n}\n\nexport default rule\n"],"mappings":"0dAeA,MAAMA,kBAAsC,IAAI,IAAI,CAAC,SAAU,MAAO,OAAO,CAAC,EAG9E,SAASC,EAAY,EAAmC,CACtD,OAAO,OAAO,QAAQC,CAAI,CAAC,CACxB,QAAQ,CAACC,KAAO,CAACH,EAAe,IAAIG,CAAC,CAAC,CAAC,CACvC,SAAS,EAAGC,KAAQ,MAAM,QAAQA,CAAC,EAAIA,EAAI,CAACA,CAAC,CAAE,CAAC,CAChD,OAAQ,GAAoB,OAAOA,GAAM,YAA3BA,CAAmC,CACtD,CAGA,SAASC,EAAkB,EAAkC,EAAwC,CACnG,IAAMC,EAASJ,GAAM,OAErB,OADKI,EACEC,EAAKD,CAAM,GAAKD,EAAkBC,EAAQC,CAAI,EADjC,EAEtB,CAGA,SAASC,EAAiB,EAA6C,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AC,IAAK,GAAOjD,EAAW,QAAQiD,CAAE,CAAC,EAE3FZ,EAA6C,CACjD,CACE,UAAW,gBACX,IAAI,EAAuB,CACzB,OAAOJ,EAAM,YAAYvF,EAAM,WAAWwG,EAAa,KAAK,IAAI,EAAE,EAAE,CACtE,CACF,CACF,EAEKZ,EAAkBtC,EAAY,MAAM,GACvCqC,EAAQ,KAAK,CACX,UAAW,mBACX,KAAM,CAAE,OAAQ,MAAO,EACvB,IAAKE,EAAkBvC,EAAY,MAAM,CAC3C,CAAC,EAGHd,EAAQ,OAAO,CACb,OACA,UAAW,oBACX,SACF,CAAC,CACH,CACF,CACF,CACF"}
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import{
|
|
1
|
+
import{isInsideTaggedDeclaration as e}from"../utils/boundary-tags.js";import{getFunctypeImportsLegacy as t,isAlreadyUsingFunctype as n,isFunctypeType as r}from"../utils/functype-detection.js";import{createImportFixer as i,hasFunctypeSymbol as a}from"../utils/import-fixer.js";import{DEFAULT_WIRE_TYPES as o,WIRE_TYPES_SCHEMA as s,isInsideWireType as c}from"../utils/wire-types.js";const l=/* @__PURE__ */ new Set([`useState`,`useRef`]),u={meta:{type:`suggestion`,hasSuggestions:!0,docs:{description:`Prefer Option<T> over nullable types (T | null | undefined)`,recommended:!0},schema:[{type:`object`,properties:{allowInteropMarker:{type:`boolean`,default:!0},wireTypes:s,allowNullableIntersections:{type:`boolean`,default:!1},allowUseState:{type:`boolean`,default:!0}},additionalProperties:!1}],messages:{preferOption:`Prefer Option<{{type}}> over nullable type '{{nullable}}'`,preferOptionReturn:`Prefer Option<{{type}}> as return type over nullable '{{nullable}}'`,suggestOptionType:`Replace with Option<{{type}}>`,suggestAddImport:`Add {{symbol}} import from functype`}},create(s){let u=s.options[0]||{},d=u.wireTypes??o,f=u.allowInteropMarker!==!1,p=t=>f&&e(t,`interop`,s.sourceCode),m=u.allowUseState!==!1;function h(e){let t=e.parent;if(!t)return!1;if(t.type===`TSTypeParameterInstantiation`&&t.parent?.type===`CallExpression`){let e=t.parent.callee,n=e.type===`Identifier`?e.name:e.type===`MemberExpression`&&e.property.type===`Identifier`?e.property.name:null;if(n!==null&&l.has(n))return!0}return h(t)}let g=t(s);return{TSUnionType(e){if(c(e,d)||p(e)||!e.types||e.types.length<2||m&&h(e)||!e.types.some(e=>e.type===`TSNullKeyword`||e.type===`TSUndefinedKeyword`))return;let t=e.types.filter(e=>e.type!==`TSNullKeyword`&&e.type!==`TSUndefinedKeyword`);if(t.length===1){let o=t[0];if(r(o,g)||n(e,g))return;let c=s.sourceCode,l=c.getText(o),u=c.getText(e);if(l.startsWith(`Option<`))return;let d=[{messageId:`suggestOptionType`,data:{type:l},fix(t){return t.replaceText(e,`Option<${l}>`)}}];a(c,`Option`)||d.push({messageId:`suggestAddImport`,data:{symbol:`Option`},fix:i(c,`Option`)}),s.report({node:e,messageId:`preferOption`,data:{type:l,nullable:u},suggest:d})}}}}};export{u as default};
|
|
2
2
|
//# sourceMappingURL=prefer-option.js.map
|
package/dist/rules/prefer-try.js
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import{
|
|
1
|
+
import{isInsideTaggedDeclaration as e}from"../utils/boundary-tags.js";import{containsAwait as t}from"../utils/async-detection.js";import{createImportFixer as n,hasFunctypeSymbol as r}from"../utils/import-fixer.js";const i={meta:{type:`suggestion`,hasSuggestions:!0,docs:{description:`Prefer Try for computations that may throw`,recommended:!0},schema:[{type:`object`,properties:{allowInteropMarker:{type:`boolean`,default:!0},allowThrowInTests:{type:`boolean`,default:!0}},additionalProperties:!1}],messages:{preferTryOverTryCatch:`Prefer Try(() => ...) over try/catch block`,preferAsyncTryOverTryCatch:`Prefer Try.fromPromise(...), Either.fromPromise(...) or IO.tryPromise(...) over an async try/catch — Try(() => ...) cannot catch an awaited rejection`,suggestTry:`Replace with Try(() => ...)`,suggestTryFromPromise:`Replace with Try.fromPromise(...)`,suggestAddImport:`Add {{symbol}} import from functype`}},create(i){let a=i.options[0]||{},o=a.allowInteropMarker!==!1,s=t=>o&&e(t,`interop`,i.sourceCode),c=a.allowThrowInTests!==!1;function l(){let e=i.filename;return/\.(test|spec)\.(ts|js|tsx|jsx)$/.test(e)||e.includes(`__tests__`)||e.includes(`/test/`)||e.includes(`/tests/`)}function u(e){return e.block?.body?.length===1}function d(e){if(!e.handler?.body)return!1;let t=e.handler.body.body;return t.length===0||t.length===1&&(t[0].type===`ReturnStatement`||t[0].type===`ExpressionStatement`)}function f(e){let t=e.block.body[0];return t.type===`ReturnStatement`&&t.argument?.type===`AwaitExpression`||t.type===`ExpressionStatement`&&t.expression?.type===`AwaitExpression`}return{TryStatement(e){if(s(e)||e.finalizer||c&&l()||e.handler&&e.handler.body&&e.handler.body.body.some(e=>e.type===`ThrowStatement`))return;let a=i.sourceCode,o=[];if(u(e)&&d(e)){let t=e.block.body[0];if(t.type===`ReturnStatement`){let i=t.argument,s=a.getText(i);if(f(e)){let t=i.type===`AwaitExpression`?i.argument:i,n=a.getText(t);o.push({messageId:`suggestTryFromPromise`,fix(t){return t.replaceText(e,`return Try.fromPromise(${n})`)}})}else o.push({messageId:`suggestTry`,fix(t){return t.replaceText(e,`return Try(() => ${s})`)}});r(a,`Try`)||o.push({messageId:`suggestAddImport`,data:{symbol:`Try`},fix:n(a,`Try`)})}}i.report({node:e,messageId:t(e.block)?`preferAsyncTryOverTryCatch`:`preferTryOverTryCatch`,suggest:o})}}}};export{i as default};
|
|
2
2
|
//# sourceMappingURL=prefer-try.js.map
|
|
@@ -0,0 +1,7 @@
|
|
|
1
|
+
import { ASTNode } from "../types/ast.js";
|
|
2
|
+
import { Rule } from "eslint";
|
|
3
|
+
//#region src/utils/array-mutation.d.ts
|
|
4
|
+
/** Is `node` (an expression) typed as a mutable array? `false` without type information. */
|
|
5
|
+
export declare const isMutableArrayExpression: (node: ASTNode, context: Rule.RuleContext) => boolean;
|
|
6
|
+
//#endregion
|
|
7
|
+
//# sourceMappingURL=array-mutation.d.ts.map
|
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
const e=e=>{let t=e.sourceCode.parserServices;return t?.program&&t.esTreeNodeToTSNodeMap?t:void 0},t=(e,n)=>{let{types:r,symbol:i,target:a}=n;return r?r.length>0&&r.every(n=>t(e,n)):e.isTupleType(n)?a?.readonly!==!0:i?.name===`Array`&&e.isArrayLikeType(n)},n=(n,r)=>{let i=e(r),a=i?.esTreeNodeToTSNodeMap.get(n);if(!i||!a)return!1;let o=i.program.getTypeChecker();return t(o,o.getNonNullableType(o.getTypeAtLocation(a)))};export{n as isMutableArrayExpression};
|
|
2
|
+
//# sourceMappingURL=array-mutation.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"array-mutation.js","names":["typedServices","services","context","isMutableArray","type","types","checker","member","target","symbol","isMutableArrayExpression","tsNode","node"],"sources":["../../src/utils/array-mutation.ts"],"sourcesContent":["import type { Rule } from \"eslint\"\n\nimport type { ASTNode } from \"../types/ast\"\n\n/**\n * Type checks for `no-array-mutation`, reached through `parserServices` and typed structurally so the\n * plugin takes no runtime dependency on `typescript`. Every check answers `false` without type\n * information: the rule reports nothing it can't prove is an array.\n */\n\ntype TypeLike = object\n\ntype CheckerLike = {\n getTypeAtLocation(node: unknown): TypeLike\n getNonNullableType(type: TypeLike): TypeLike\n isArrayLikeType(type: TypeLike): boolean\n isTupleType(type: TypeLike): boolean\n}\n\ntype TypedServices = {\n readonly program: { getTypeChecker(): CheckerLike }\n readonly esTreeNodeToTSNodeMap: { get(node: unknown): unknown }\n}\n\nconst typedServices = (context: Rule.RuleContext): TypedServices | undefined => {\n const services = context.sourceCode.parserServices as Partial<TypedServices> | undefined\n return services?.program && services.esTreeNodeToTSNodeMap ? (services as TypedServices) : undefined\n}\n\n/**\n * The mutable `Array` type, or a non-readonly tuple — `ReadonlyArray` has no `push`, so TypeScript\n * already rejects mutating one. Every member of a union must be one, so `string[] | Set<string>`\n * isn't reported on a `.push` the compiler resolves some other way.\n */\nconst isMutableArray = (checker: CheckerLike, type: TypeLike): boolean => {\n const { types, symbol, target } = type as {\n types?: ReadonlyArray<TypeLike>\n symbol?: { name?: string }\n target?: { readonly?: boolean }\n }\n if (types) return types.length > 0 && types.every((member) => isMutableArray(checker, member))\n if (checker.isTupleType(type)) return target?.readonly !== true\n return symbol?.name === \"Array\" && checker.isArrayLikeType(type)\n}\n\n/** Is `node` (an expression) typed as a mutable array? `false` without type information. */\nexport const isMutableArrayExpression = (node: ASTNode, context: Rule.RuleContext): boolean => {\n const services = typedServices(context)\n const tsNode = services?.esTreeNodeToTSNodeMap.get(node)\n if (!services || !tsNode) return false\n const checker = services.program.getTypeChecker()\n return isMutableArray(checker, checker.getNonNullableType(checker.getTypeAtLocation(tsNode)))\n}\n"],"mappings":"AAwBA,MAAMA,EAAiB,GAAyD,CAC9E,IAAMC,EAAWC,EAAQ,WAAW,eACpC,OAAOD,GAAU,SAAWA,EAAS,sBAAyBA,EAA6B,IAAA,EAC7F,EAOME,GAAkB,EAAsB,IAA4B,CACxE,GAAM,CAAE,QAAO,SAAQ,UAAWC,EAOlC,OAFIC,EAAcA,EAAM,OAAS,GAAKA,EAAM,MAAO,GAAWF,EAAeG,EAASC,CAAM,CAAC,EACzFD,EAAQ,YAAYF,CAAI,EAAUI,GAAQ,WAAa,GACpDC,GAAQ,OAAS,SAAWH,EAAQ,gBAAgBF,CAAI,CACjE,EAGaM,GAA4B,EAAe,IAAuC,CAC7F,IAAMT,EAAWD,EAAcE,CAAO,EAChCS,EAASV,GAAU,sBAAsB,IAAIW,CAAI,EACvD,GAAI,CAACX,GAAY,CAACU,EAAQ,MAAO,GACjC,IAAML,EAAUL,EAAS,QAAQ,eAAe,EAChD,OAAOE,EAAeG,EAASA,EAAQ,mBAAmBA,EAAQ,kBAAkBK,CAAM,CAAC,CAAC,CAC9F"}
|
|
@@ -0,0 +1,40 @@
|
|
|
1
|
+
import { ASTNode } from "../types/ast.js";
|
|
2
|
+
import { Rule } from "eslint";
|
|
3
|
+
//#region src/utils/type-aware.d.ts
|
|
4
|
+
/**
|
|
5
|
+
* Is `node`'s type a functype extractable container (Option, Either, Try, Lazy, …)? Structural:
|
|
6
|
+
* the type, after stripping `null` / `undefined`, has both `orThrow` and `fold` — true of every
|
|
7
|
+
* functype container, including union types like `Either` (each member has both). Native
|
|
8
|
+
* collections (`Map#get`) and arbitrary objects don't.
|
|
9
|
+
*
|
|
10
|
+
* `undefined` when type information isn't available, so the caller can fall back.
|
|
11
|
+
*/
|
|
12
|
+
export declare const isExtractableByType: (node: ASTNode, context: Rule.RuleContext) => boolean | undefined;
|
|
13
|
+
/**
|
|
14
|
+
* Does `node` (an expression) flow into a slot that is typed as an array, a tuple or `any`/`unknown`?
|
|
15
|
+
* That's the expected type TypeScript checks it against: the parameter it is passed to, the property
|
|
16
|
+
* it initialises, the declared return type. A literal in such a slot is handed to code that requires an
|
|
17
|
+
* array, such as drizzle's `.values([...])` or an index definition, so `List` can't go there. A literal
|
|
18
|
+
* inside an object passed to an `any` parameter (a `JSON.stringify` request body) counts too.
|
|
19
|
+
*
|
|
20
|
+
* `undefined` when type information isn't available, or when there is no expected type (a free-standing
|
|
21
|
+
* literal), so the caller can fall back.
|
|
22
|
+
*/
|
|
23
|
+
export declare const flowsIntoArraySlot: (node: ASTNode, context: Rule.RuleContext) => boolean | undefined;
|
|
24
|
+
/**
|
|
25
|
+
* Does `node` flow into a slot that requires a *mutable* array — a parameter typed `T[]`, such as pg's
|
|
26
|
+
* `query(text, values: unknown[])`, drizzle's `inArray(col, values)` or ReactFlow's `nodes`? There a
|
|
27
|
+
* `ReadonlyArray` won't type-check, so a mutable annotation is what the library demands.
|
|
28
|
+
*
|
|
29
|
+
* `undefined` when type information isn't available.
|
|
30
|
+
*/
|
|
31
|
+
export declare const flowsIntoMutableArraySlot: (node: ASTNode, context: Rule.RuleContext) => boolean | undefined;
|
|
32
|
+
/**
|
|
33
|
+
* Is `node`'s own type `any` / `unknown`, or an array of them — `JSON.parse(raw)`, `await res.json()`,
|
|
34
|
+
* `raw` after `Array.isArray(raw)` (narrowed to `any[]`)? `undefined` when type information isn't available.
|
|
35
|
+
*/
|
|
36
|
+
export declare const isUntypedExpression: (node: ASTNode, context: Rule.RuleContext) => boolean | undefined;
|
|
37
|
+
/** Is type-aware linting on for this file (`parserOptions.projectService` or `project`)? */
|
|
38
|
+
export declare const hasTypeInformation: (context: Rule.RuleContext) => boolean;
|
|
39
|
+
//#endregion
|
|
40
|
+
//# sourceMappingURL=type-aware.d.ts.map
|
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
const e=/* @__PURE__ */ new Set([`Iterable`,`AsyncIterable`,`IterableIterator`,`ArrayLike`]),t=e=>{let t=e.sourceCode.parserServices;return t?.program&&t.esTreeNodeToTSNodeMap?t:void 0},n=(e,n)=>{let r=t(n);if(!r)return;let i=r.esTreeNodeToTSNodeMap.get(e);if(!i)return;let a=r.program.getTypeChecker(),o=a.getNonNullableType(a.getTypeAtLocation(i));return a.getPropertyOfType(o,`orThrow`)!==void 0&&a.getPropertyOfType(o,`fold`)!==void 0},r=e=>e.isTypeParameter?.()===!0,i=e=>{let t=e.parent;if(!t)return null;if((t.type===`CallExpression`||t.type===`NewExpression`)&&t.callee!==e){let n=t.arguments.indexOf(e);return n<0?null:{call:t,argument:e,index:n}}return t.type===`TSAsExpression`||t.type===`TSSatisfiesExpression`||t.type===`ConditionalExpression`&&t.test!==e||t.type===`LogicalExpression`||t.type===`Property`||t.type===`ObjectExpression`||t.type===`ArrayExpression`||t.type===`SpreadElement`?i(t):null},a=(e,t,n)=>{let a=i(n),o=a?t.esTreeNodeToTSNodeMap.get(a.call):void 0,s=o?e.getResolvedSignature(o)?.getDeclaration()?.parameters:void 0;if(!a||!s||s.length===0)return!1;let c=s[Math.min(a.index,s.length-1)];if(c?.type===void 0)return!1;let l=e.getTypeAtLocation(c.type);return(l.types??[l]).some(r)},o=(e,t,n)=>{let r=i(n),a=r?t.esTreeNodeToTSNodeMap.get(r.call):void 0,o=a?e.getResolvedSignature(a):void 0,s=r?t.esTreeNodeToTSNodeMap.get(r.argument):void 0;if(!o||!s)return!1;let c=e.getTypeAtLocation(s),l=t=>t===c||e.isTypeAssignableTo(c,t)&&e.isTypeAssignableTo(t,c),u=(t,n)=>{if(n>3)return!1;if(l(t))return!0;let{types:r,target:i}=t;if(r)return r.some(e=>u(e,n+1));if(i!==void 0&&(e.isTupleType(t)||e.isArrayLikeType(t)))return e.getTypeArguments(t).some(e=>u(e,n+1));let a=e.getAwaitedType(t);return a!==void 0&&a!==t&&u(a,n+1)};return u(e.getReturnTypeOfSignature(o),0)},s=(e,t,n)=>l(n.type)||r(n.type)&&!o(e,t,n.at),c=(t,n,i)=>{if(s(t,n,i))return!0;let{types:a,symbol:o}=i.type;return a?a.some(e=>c(t,n,{type:e,at:i.at})):o?.name!==void 0&&e.has(o.name)?!0:!r(i.type)&&t.isArrayLikeType(i.type)},l=e=>{let{flags:t}=e;return t!==void 0&&!!(t&3)},u=(e,t)=>{let{types:n,symbol:r}=t;return n?n.some(t=>u(e,t)):r?.name===`Array`&&e.isArrayLikeType(t)},d=e=>e.computed?null:e.key?.type===`Identifier`?e.key.name:e.key?.type===`Literal`&&typeof e.key.value==`string`?e.key.value:null,f=(e,t,n,r,i=0)=>{if(i>4)return;let a=t.esTreeNodeToTSNodeMap.get(n),o=a?e.getContextualType(a):void 0;if(o!==void 0)return{type:o,at:n};let c=n.parent;if(c?.type===`ArrowFunctionExpression`&&c.body===n){let n=c.parent;if(n?.type===`VariableDeclarator`&&n.init===c&&n.id?.type===`Identifier`)return(r.sourceCode.getDeclaredVariables(n)[0]?.references??[]).map(e=>e.identifier.parent).filter(e=>e?.type===`CallExpression`).map(n=>f(e,t,n,r,i+1)).find(e=>e!==void 0)}if((c?.type===`CallExpression`||c?.type===`NewExpression`)&&c.callee!==n){let r=c.arguments.indexOf(n),i=t.esTreeNodeToTSNodeMap.get(c),a=r>=0&&i?e.getResolvedSignature(i)?.parameters[r]:void 0;return a===void 0?void 0:{type:e.getTypeOfSymbolAtLocation(a,i),at:n}}let l=c?.type===`Property`&&c.value===n?c.parent:void 0;if(l?.type!==`ObjectExpression`)return;let u=f(e,t,l,r,i+1);if(u===void 0||s(e,t,u))return u;let p=u.type,m=d(c);if(m===null){let r=c.key,i=r?t.esTreeNodeToTSNodeMap.get(r):void 0,o=i?e.getTypeAtLocation(i):void 0,s=o?.value??o?.types?.[0]?.value,l=typeof s==`string`?e.getPropertyOfType(p,s):void 0,u=l===void 0?e.getIndexInfoOfType(p,0)?.type:e.getTypeOfSymbolAtLocation(l,a);return u===void 0?void 0:{type:u,at:n}}let h=e.getPropertyOfType(p,m);return h===void 0?void 0:{type:e.getTypeOfSymbolAtLocation(h,a),at:n}},p=(e,n)=>{let r=t(n);if(!r)return;let i=r.program.getTypeChecker(),s=f(i,r,e,n);if(s!==void 0)return a(i,r,s.at)?!o(i,r,s.at):c(i,r,s)},m=(e,n)=>{let r=t(n);if(!r)return;let i=r.program.getTypeChecker(),o=f(i,r,e,n);return o===void 0||a(i,r,o.at)?!1:u(i,o.type)},h=(e,n)=>{let r=t(n);if(!r)return;let i=r.esTreeNodeToTSNodeMap.get(e);if(!i)return;let a=r.program.getTypeChecker(),o=a.getTypeAtLocation(i);if(l(o))return!0;if(!a.isArrayLikeType(o))return!1;let s=a.getTypeArguments(o)[0];return s!==void 0&&l(s)},g=e=>t(e)!==void 0;export{p as flowsIntoArraySlot,m as flowsIntoMutableArraySlot,g as hasTypeInformation,n as isExtractableByType,h as isUntypedExpression};
|
|
2
|
+
//# sourceMappingURL=type-aware.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"type-aware.js","names":["CONSUMED_COLLECTION_TYPES","typedServices","services","context","isExtractableByType","tsNode","node","checker","type","isTypeParameter","enclosingCall","parent","at","index","isGenericParameterArgument","found","callTs","parameters","declared","annotated","handsArgumentBack","signature","argTs","argType","sameAsArgument","candidate","search","depth","types","member","target","element","awaited","isOpaqueSink","isUntyped","slot","isArrayLikeOrUntyped","symbol","flags","isMutableArrayType","propertyKey","property","expectedSlot","own","declarator","ref","call","parameter","objectLiteral","outerSlot","outer","key","keyNode","keyTs","keyType","literal","named","flowsIntoArraySlot","flowsIntoMutableArraySlot","isUntypedExpression","hasTypeInformation"],"sources":["../../src/utils/type-aware.ts"],"sourcesContent":["import type { Rule } from \"eslint\"\n\nimport type { ASTNode } from \"../types/ast\"\n\n/**\n * Type-aware helpers that work only when the consumer turns on type-aware linting\n * (`parserOptions.projectService` or `project`). Without it they report \"unknown\", and a rule\n * falls back to its syntactic heuristic.\n *\n * The checker is reached through `parserServices` and typed structurally here, so the plugin\n * takes no runtime dependency on `typescript`.\n */\n\ntype TypeLike = object\n\ntype CheckerLike = {\n getTypeAtLocation(node: unknown): TypeLike\n getNonNullableType(type: TypeLike): TypeLike\n getPropertyOfType(type: TypeLike, name: string): unknown\n getContextualType(node: unknown): TypeLike | undefined\n isArrayLikeType(type: TypeLike): boolean\n getTypeOfSymbolAtLocation(symbol: unknown, node: unknown): TypeLike\n getTypeArguments(type: TypeLike): ReadonlyArray<TypeLike>\n getResolvedSignature(node: unknown): SignatureLike | undefined\n getIndexInfoOfType(type: TypeLike, kind: number): { readonly type: TypeLike } | undefined\n getReturnTypeOfSignature(signature: unknown): TypeLike\n getAwaitedType(type: TypeLike): TypeLike | undefined\n isTupleType(type: TypeLike): boolean\n isTypeAssignableTo(source: TypeLike, target: TypeLike): boolean\n}\n\ntype SignatureLike = {\n readonly parameters: ReadonlyArray<unknown>\n getDeclaration(): { readonly parameters?: ReadonlyArray<unknown> } | undefined\n}\n\n/** `ts.TypeFlags.Any` / `Unknown`, inlined so the plugin needs no runtime `typescript` import. */\nconst ANY_OR_UNKNOWN_FLAGS = 1 | 2\n\n/** Interfaces a consumer reads through rather than keeps: `importKey(…, usages: Iterable<KeyUsage>)`, `new Set(values)`. */\nconst CONSUMED_COLLECTION_TYPES: ReadonlySet<string> = new Set([\n \"Iterable\",\n \"AsyncIterable\",\n \"IterableIterator\",\n \"ArrayLike\",\n])\n\ntype TypedServices = {\n readonly program: { getTypeChecker(): CheckerLike }\n readonly esTreeNodeToTSNodeMap: { get(node: unknown): unknown }\n}\n\nconst typedServices = (context: Rule.RuleContext): TypedServices | undefined => {\n const services = context.sourceCode.parserServices as Partial<TypedServices> | undefined\n return services?.program && services.esTreeNodeToTSNodeMap ? (services as TypedServices) : undefined\n}\n\n/**\n * Is `node`'s type a functype extractable container (Option, Either, Try, Lazy, …)? Structural:\n * the type, after stripping `null` / `undefined`, has both `orThrow` and `fold` — true of every\n * functype container, including union types like `Either` (each member has both). Native\n * collections (`Map#get`) and arbitrary objects don't.\n *\n * `undefined` when type information isn't available, so the caller can fall back.\n */\nexport const isExtractableByType = (node: ASTNode, context: Rule.RuleContext): boolean | undefined => {\n const services = typedServices(context)\n if (!services) return undefined\n const tsNode = services.esTreeNodeToTSNodeMap.get(node)\n if (!tsNode) return undefined\n const checker = services.program.getTypeChecker()\n const type = checker.getNonNullableType(checker.getTypeAtLocation(tsNode))\n return (\n checker.getPropertyOfType(type, \"orThrow\") !== undefined && checker.getPropertyOfType(type, \"fold\") !== undefined\n )\n}\n\n/** A slot's expected type and the expression TypeScript computed it for. */\ntype Slot = { readonly type: TypeLike; readonly at: ASTNode }\n\n/**\n * Uses the `Type` object's own predicate rather than a `TypeFlags` bit: TypeScript renumbers its flags\n * between majors (TypeParameter is `1 << 19` in TS 6, `1 << 18` before), and the plugin has no runtime\n * `typescript` import to read them from.\n */\nconst isTypeParameter = (type: TypeLike): boolean =>\n (type as { isTypeParameter?: () => boolean }).isTypeParameter?.() === true\n\n/**\n * `f(…, arg, …)` where `at` is `arg` or sits inside it (an object property, an array element, a spread,\n * a conditional branch, an `as`): the call, the whole argument, and its index.\n */\nconst enclosingCall = (\n at: ASTNode,\n): { readonly call: ASTNode; readonly argument: ASTNode; readonly index: number } | null => {\n const parent = at.parent as ASTNode | undefined\n if (!parent) return null\n if ((parent.type === \"CallExpression\" || parent.type === \"NewExpression\") && parent.callee !== at) {\n const index = (parent.arguments as ReadonlyArray<ASTNode>).indexOf(at)\n return index < 0 ? null : { call: parent, argument: at, index }\n }\n const passesThrough =\n parent.type === \"TSAsExpression\" ||\n parent.type === \"TSSatisfiesExpression\" ||\n (parent.type === \"ConditionalExpression\" && parent.test !== at) ||\n parent.type === \"LogicalExpression\" ||\n parent.type === \"Property\" ||\n parent.type === \"ObjectExpression\" ||\n parent.type === \"ArrayExpression\" ||\n parent.type === \"SpreadElement\"\n return passesThrough ? enclosingCall(parent) : null\n}\n\n/**\n * Is the parameter that `at` is passed to (directly or nested) declared as a type parameter, or a union\n * containing one — `json<T>(data: T)`, `useState<S>(init: S | (() => S))`? Then TypeScript's expected type for `at` is only an echo of what it inferred from\n * `at` itself (`[1, 2]` → `number[]`), not a shape the library demands.\n */\nconst isGenericParameterArgument = (checker: CheckerLike, services: TypedServices, at: ASTNode): boolean => {\n const found = enclosingCall(at)\n const callTs = found ? services.esTreeNodeToTSNodeMap.get(found.call) : undefined\n const parameters = callTs ? checker.getResolvedSignature(callTs)?.getDeclaration()?.parameters : undefined\n if (!found || !parameters || parameters.length === 0) return false\n const declared = parameters[Math.min(found.index, parameters.length - 1)] as { readonly type?: unknown } | undefined\n // The parameter's type annotation node (`T` in `value: T`); asking for the declaration node's type gives `any`.\n if (declared?.type === undefined) return false\n const annotated = checker.getTypeAtLocation(declared.type)\n // React's `useState<S>(init: S | (() => S))`: a union that contains the type parameter is generic too.\n const members = (annotated as { types?: ReadonlyArray<TypeLike> }).types ?? [annotated]\n return members.some(isTypeParameter)\n}\n\n/**\n * Does the generic call around `at` hand the argument straight back to the caller — `useState(init)`\n * returning `[init, set]`, `identity(x)`, a `Promise` of it? Then the shape stays the caller's, and a\n * type parameter isn't a sink. Looks only at the return type itself, union / intersection members,\n * tuple and array elements, and an awaited Promise, not object properties: Hono's `c.json<T>` returns a\n * `Response` that carries a *parsed* copy of `T` for its RPC client, which the caller doesn't get back.\n */\nconst handsArgumentBack = (checker: CheckerLike, services: TypedServices, at: ASTNode): boolean => {\n const found = enclosingCall(at)\n const callTs = found ? services.esTreeNodeToTSNodeMap.get(found.call) : undefined\n const signature = callTs ? checker.getResolvedSignature(callTs) : undefined\n const argTs = found ? services.esTreeNodeToTSNodeMap.get(found.argument) : undefined\n if (!signature || !argTs) return false\n const argType = checker.getTypeAtLocation(argTs)\n const sameAsArgument = (candidate: TypeLike): boolean =>\n candidate === argType ||\n (checker.isTypeAssignableTo(argType, candidate) && checker.isTypeAssignableTo(candidate, argType))\n const search = (type: TypeLike, depth: number): boolean => {\n if (depth > 3) return false\n if (sameAsArgument(type)) return true\n const { types, target } = type as { types?: ReadonlyArray<TypeLike>; target?: unknown }\n if (types) return types.some((member) => search(member, depth + 1))\n if (target !== undefined && (checker.isTupleType(type) || checker.isArrayLikeType(type))) {\n return checker.getTypeArguments(type).some((element) => search(element, depth + 1))\n }\n const awaited = checker.getAwaitedType(type)\n return awaited !== undefined && awaited !== type && search(awaited, depth + 1)\n }\n return search(checker.getReturnTypeOfSignature(signature), 0)\n}\n\n/**\n * Untyped, or a type parameter of a call that doesn't hand the argument back: an object handed to\n * `c.json<T>(data: T)` or `JSON.stringify` goes to a sink. `useState<T>(init: T)` is not one.\n */\nconst isOpaqueSink = (checker: CheckerLike, services: TypedServices, slot: Slot): boolean =>\n isUntyped(slot.type) || (isTypeParameter(slot.type) && !handsArgumentBack(checker, services, slot.at))\n\nconst isArrayLikeOrUntyped = (checker: CheckerLike, services: TypedServices, slot: Slot): boolean => {\n if (isOpaqueSink(checker, services, slot)) return true\n const { types, symbol } = slot.type as { types?: ReadonlyArray<TypeLike>; symbol?: { name?: string } }\n if (types) return types.some((member) => isArrayLikeOrUntyped(checker, services, { type: member, at: slot.at }))\n if (symbol?.name !== undefined && CONSUMED_COLLECTION_TYPES.has(symbol.name)) return true\n return !isTypeParameter(slot.type) && checker.isArrayLikeType(slot.type)\n}\n\nconst isUntyped = (type: TypeLike): boolean => {\n const { flags } = type as { flags?: number }\n return flags !== undefined && (flags & ANY_OR_UNKNOWN_FLAGS) !== 0\n}\n\n/** The mutable `Array` type, as opposed to `ReadonlyArray`: the one a `ReadonlyArray` can't be passed to. */\nconst isMutableArrayType = (checker: CheckerLike, type: TypeLike): boolean => {\n const { types, symbol } = type as { types?: ReadonlyArray<TypeLike>; symbol?: { name?: string } }\n if (types) return types.some((member) => isMutableArrayType(checker, member))\n return symbol?.name === \"Array\" && checker.isArrayLikeType(type)\n}\n\n/** The name a property is written under: `params` in `{ params }`, `parts` in `{ parts: … }` or `{ \"parts\": … }`. */\nconst propertyKey = (property: ASTNode): string | null => {\n if (property.computed) return null\n if (property.key?.type === \"Identifier\") return property.key.name\n return property.key?.type === \"Literal\" && typeof property.key.value === \"string\" ? property.key.value : null\n}\n\n/**\n * The expected type of `node`, looking through object literals when TypeScript gives the value none of\n * its own. Two cases: a shorthand `{ params }` passed to a function, where the expected type is that\n * property's type on the parameter; and `[…]` in `JSON.stringify({ parts: [...] })`, where the object is\n * passed to an `any` parameter, so the whole object is going to an untyped host.\n */\nconst expectedSlot = (\n checker: CheckerLike,\n services: TypedServices,\n node: ASTNode,\n context: Rule.RuleContext,\n depth = 0,\n): Slot | undefined => {\n if (depth > 4) return undefined\n const tsNode = services.esTreeNodeToTSNodeMap.get(node)\n const own = tsNode ? checker.getContextualType(tsNode) : undefined\n if (own !== undefined) return { type: own, at: node }\n const parent = node.parent as ASTNode | undefined\n // `const metadata = (url) => ({ … })` with no declared return type: the object goes wherever the\n // calls' results go (`c.json(metadata(url))`), so take the expected type at the first call site.\n if (parent?.type === \"ArrowFunctionExpression\" && parent.body === node) {\n const declarator = parent.parent as ASTNode | undefined\n if (\n declarator?.type === \"VariableDeclarator\" &&\n declarator.init === parent &&\n declarator.id?.type === \"Identifier\"\n ) {\n const variable = context.sourceCode.getDeclaredVariables(declarator)[0]\n const calls = (variable?.references ?? [])\n .map((ref) => (ref.identifier as unknown as ASTNode).parent as ASTNode | undefined)\n .filter((call): call is ASTNode => call?.type === \"CallExpression\")\n return calls\n .map((call) => expectedSlot(checker, services, call, context, depth + 1))\n .find((slot) => slot !== undefined)\n }\n }\n // An argument to an overloaded function (`crypto.subtle.importKey(…, [\"decrypt\"])`) gets no contextual\n // type; the parameter of the overload TypeScript picked is the expected type.\n if ((parent?.type === \"CallExpression\" || parent?.type === \"NewExpression\") && parent.callee !== node) {\n const index = (parent.arguments as ReadonlyArray<ASTNode>).indexOf(node)\n const call = services.esTreeNodeToTSNodeMap.get(parent)\n const parameter = index >= 0 && call ? checker.getResolvedSignature(call)?.parameters[index] : undefined\n return parameter === undefined ? undefined : { type: checker.getTypeOfSymbolAtLocation(parameter, call), at: node }\n }\n const objectLiteral = parent?.type === \"Property\" && parent.value === node ? (parent.parent as ASTNode) : undefined\n if (objectLiteral?.type !== \"ObjectExpression\") return undefined\n const outerSlot = expectedSlot(checker, services, objectLiteral, context, depth + 1)\n if (outerSlot === undefined || isOpaqueSink(checker, services, outerSlot)) return outerSlot\n const outer = outerSlot.type\n const key = propertyKey(parent as ASTNode)\n // `{ [k]: [...] }` (a reduce accumulator keyed by category): the property named by the key's literal\n // type, else the string index signature's type.\n if (key === null) {\n const keyNode = (parent as ASTNode).key\n const keyTs = keyNode ? services.esTreeNodeToTSNodeMap.get(keyNode) : undefined\n const keyType = keyTs\n ? (checker.getTypeAtLocation(keyTs) as { value?: unknown; types?: ReadonlyArray<{ value?: unknown }> })\n : undefined\n const literal = keyType?.value ?? keyType?.types?.[0]?.value\n const named = typeof literal === \"string\" ? checker.getPropertyOfType(outer, literal) : undefined\n const type =\n named !== undefined\n ? checker.getTypeOfSymbolAtLocation(named, tsNode)\n : checker.getIndexInfoOfType(outer, 0)?.type\n return type === undefined ? undefined : { type, at: node }\n }\n const member = checker.getPropertyOfType(outer, key)\n return member === undefined ? undefined : { type: checker.getTypeOfSymbolAtLocation(member, tsNode), at: node }\n}\n\n/**\n * Does `node` (an expression) flow into a slot that is typed as an array, a tuple or `any`/`unknown`?\n * That's the expected type TypeScript checks it against: the parameter it is passed to, the property\n * it initialises, the declared return type. A literal in such a slot is handed to code that requires an\n * array, such as drizzle's `.values([...])` or an index definition, so `List` can't go there. A literal\n * inside an object passed to an `any` parameter (a `JSON.stringify` request body) counts too.\n *\n * `undefined` when type information isn't available, or when there is no expected type (a free-standing\n * literal), so the caller can fall back.\n */\nexport const flowsIntoArraySlot = (node: ASTNode, context: Rule.RuleContext): boolean | undefined => {\n const services = typedServices(context)\n if (!services) return undefined\n const checker = services.program.getTypeChecker()\n const slot = expectedSlot(checker, services, node, context)\n if (slot === undefined) return undefined\n // A bare `T` parameter: a sink unless the call hands the argument straight back (`useState`, `identity`).\n if (isGenericParameterArgument(checker, services, slot.at)) return !handsArgumentBack(checker, services, slot.at)\n return isArrayLikeOrUntyped(checker, services, slot)\n}\n\n/**\n * Does `node` flow into a slot that requires a *mutable* array — a parameter typed `T[]`, such as pg's\n * `query(text, values: unknown[])`, drizzle's `inArray(col, values)` or ReactFlow's `nodes`? There a\n * `ReadonlyArray` won't type-check, so a mutable annotation is what the library demands.\n *\n * `undefined` when type information isn't available.\n */\nexport const flowsIntoMutableArraySlot = (node: ASTNode, context: Rule.RuleContext): boolean | undefined => {\n const services = typedServices(context)\n if (!services) return undefined\n const checker = services.program.getTypeChecker()\n const slot = expectedSlot(checker, services, node, context)\n if (slot === undefined || isGenericParameterArgument(checker, services, slot.at)) return false\n return isMutableArrayType(checker, slot.type)\n}\n\n/**\n * Is `node`'s own type `any` / `unknown`, or an array of them — `JSON.parse(raw)`, `await res.json()`,\n * `raw` after `Array.isArray(raw)` (narrowed to `any[]`)? `undefined` when type information isn't available.\n */\nexport const isUntypedExpression = (node: ASTNode, context: Rule.RuleContext): boolean | undefined => {\n const services = typedServices(context)\n if (!services) return undefined\n const tsNode = services.esTreeNodeToTSNodeMap.get(node)\n if (!tsNode) return undefined\n const checker = services.program.getTypeChecker()\n const type = checker.getTypeAtLocation(tsNode)\n if (isUntyped(type)) return true\n if (!checker.isArrayLikeType(type)) return false\n const element = checker.getTypeArguments(type)[0]\n return element !== undefined && isUntyped(element)\n}\n\n/** Is type-aware linting on for this file (`parserOptions.projectService` or `project`)? */\nexport const hasTypeInformation = (context: Rule.RuleContext): boolean => typedServices(context) !== undefined\n"],"mappings":"AAqCA,MAGMA,kBAAiD,IAAI,IAAI,CAC7D,WACA,gBACA,mBACA,WACF,CAAC,EAOKC,EAAiB,GAAyD,CAC9E,IAAMC,EAAWC,EAAQ,WAAW,eACpC,OAAOD,GAAU,SAAWA,EAAS,sBAAyBA,EAA6B,IAAA,EAC7F,EAUaE,GAAuB,EAAe,IAAmD,CACpG,IAAMF,EAAWD,EAAcE,CAAO,EACtC,GAAI,CAACD,EAAU,OACf,IAAMG,EAASH,EAAS,sBAAsB,IAAII,CAAI,EACtD,GAAI,CAACD,EAAQ,OACb,IAAME,EAAUL,EAAS,QAAQ,eAAe,EAC1CM,EAAOD,EAAQ,mBAAmBA,EAAQ,kBAAkBF,CAAM,CAAC,EACzE,OACEE,EAAQ,kBAAkBC,EAAM,SAAS,IAAM,IAAA,IAAaD,EAAQ,kBAAkBC,EAAM,MAAM,IAAM,IAAA,EAE5G,EAUMC,EAAmB,GACtBD,EAA6C,kBAAkB,IAAM,GAMlEE,EACJ,GAC0F,CAC1F,IAAMC,EAASC,EAAG,OAClB,GAAI,CAACD,EAAQ,OAAO,KACpB,IAAKA,EAAO,OAAS,kBAAoBA,EAAO,OAAS,kBAAoBA,EAAO,SAAWC,EAAI,CACjG,IAAMC,EAASF,EAAO,UAAqC,QAAQC,CAAE,EACrE,OAAOC,EAAQ,EAAI,KAAO,CAAE,KAAMF,EAAQ,SAAUC,EAAI,OAAM,CAChE,CAUA,OARED,EAAO,OAAS,kBAChBA,EAAO,OAAS,yBACfA,EAAO,OAAS,yBAA2BA,EAAO,OAASC,GAC5DD,EAAO,OAAS,qBAChBA,EAAO,OAAS,YAChBA,EAAO,OAAS,oBAChBA,EAAO,OAAS,mBAChBA,EAAO,OAAS,g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,EAAK,EAAE,EAAU,CAACf,EAAkBb,EAASL,EAAUiC,EAAK,EAAE,EACzGC,EAAqB7B,EAASL,EAAUiC,CAAI,CACrD,EASauB,GAA6B,EAAe,IAAmD,CAC1G,IAAMxD,EAAWD,EAAcE,CAAO,EACtC,GAAI,CAACD,EAAU,OACf,IAAMK,EAAUL,EAAS,QAAQ,eAAe,EAC1CiC,EAAOO,EAAanC,EAASL,EAAUI,EAAMH,CAAO,EAE1D,OADIgC,IAAS,IAAA,IAAarB,EAA2BP,EAASL,EAAUiC,EAAK,EAAE,EAAU,GAClFI,EAAmBhC,EAAS4B,EAAK,IAAI,CAC9C,EAMawB,GAAuB,EAAe,IAAmD,CACpG,IAAMzD,EAAWD,EAAcE,CAAO,EACtC,GAAI,CAACD,EAAU,OACf,IAAMG,EAASH,EAAS,sBAAsB,IAAII,CAAI,EACtD,GAAI,CAACD,EAAQ,OACb,IAAME,EAAUL,EAAS,QAAQ,eAAe,EAC1CM,EAAOD,EAAQ,kBAAkBF,CAAM,EAC7C,GAAI6B,EAAU1B,CAAI,EAAG,MAAO,GAC5B,GAAI,CAACD,EAAQ,gBAAgBC,CAAI,EAAG,MAAO,GAC3C,IAAMuB,EAAUxB,EAAQ,iBAAiBC,CAAI,CAAC,CAAC,GAC/C,OAAOuB,IAAY,IAAA,IAAaG,EAAUH,CAAO,CACnD,EAGa6B,EAAsB,GAAuC3D,EAAcE,CAAO,IAAM,IAAA"}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "eslint-plugin-functype",
|
|
3
|
-
"version": "2.
|
|
3
|
+
"version": "2.115.0",
|
|
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",
|
|
@@ -39,10 +39,10 @@
|
|
|
39
39
|
"eslint": "^10.2.1"
|
|
40
40
|
},
|
|
41
41
|
"devDependencies": {
|
|
42
|
-
"@types/node": "^24.19.
|
|
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.15.0",
|
|
46
46
|
"ts-builds": "^3.4.3",
|
|
47
47
|
"tsdown": "^0.23.0"
|
|
48
48
|
},
|