eslint-plugin-functype 2.109.0 → 2.111.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.
Files changed (58) hide show
  1. package/README.md +117 -19
  2. package/dist/cli/list-rules.js.map +1 -1
  3. package/dist/configs/recommended.d.ts +22 -5
  4. package/dist/configs/recommended.js +1 -1
  5. package/dist/configs/recommended.js.map +1 -1
  6. package/dist/configs/strict.d.ts +1 -1
  7. package/dist/configs/strict.js.map +1 -1
  8. package/dist/index.js.map +1 -1
  9. package/dist/rules/index.js.map +1 -1
  10. package/dist/rules/no-get-unsafe.js.map +1 -1
  11. package/dist/rules/no-imperative-loops.js +1 -1
  12. package/dist/rules/no-imperative-loops.js.map +1 -1
  13. package/dist/rules/no-let.js.map +1 -1
  14. package/dist/rules/prefer-do-notation.js +1 -1
  15. package/dist/rules/prefer-do-notation.js.map +1 -1
  16. package/dist/rules/prefer-either.js +1 -1
  17. package/dist/rules/prefer-either.js.map +1 -1
  18. package/dist/rules/prefer-flatmap.js +1 -1
  19. package/dist/rules/prefer-flatmap.js.map +1 -1
  20. package/dist/rules/prefer-fold.js +1 -1
  21. package/dist/rules/prefer-fold.js.map +1 -1
  22. package/dist/rules/prefer-functype-map.js +1 -1
  23. package/dist/rules/prefer-functype-map.js.map +1 -1
  24. package/dist/rules/prefer-functype-set.js +1 -1
  25. package/dist/rules/prefer-functype-set.js.map +1 -1
  26. package/dist/rules/prefer-list.js +1 -1
  27. package/dist/rules/prefer-list.js.map +1 -1
  28. package/dist/rules/prefer-map.js +1 -1
  29. package/dist/rules/prefer-map.js.map +1 -1
  30. package/dist/rules/prefer-option.js +1 -1
  31. package/dist/rules/prefer-option.js.map +1 -1
  32. package/dist/rules/prefer-try.js +1 -1
  33. package/dist/rules/prefer-try.js.map +1 -1
  34. package/dist/types/ast.d.ts +1 -2
  35. package/dist/utils/ast-walk.d.ts +12 -0
  36. package/dist/utils/ast-walk.js +2 -0
  37. package/dist/utils/ast-walk.js.map +1 -0
  38. package/dist/utils/async-detection.d.ts +6 -0
  39. package/dist/utils/async-detection.js +2 -0
  40. package/dist/utils/async-detection.js.map +1 -0
  41. package/dist/utils/boundary-tags.d.ts +26 -0
  42. package/dist/utils/boundary-tags.js +2 -0
  43. package/dist/utils/boundary-tags.js.map +1 -0
  44. package/dist/utils/dependency-validator.d.ts +4 -5
  45. package/dist/utils/dependency-validator.js +1 -1
  46. package/dist/utils/dependency-validator.js.map +1 -1
  47. package/dist/utils/functype-detection.d.ts +13 -14
  48. package/dist/utils/functype-detection.js +1 -1
  49. package/dist/utils/functype-detection.js.map +1 -1
  50. package/dist/utils/import-fixer.d.ts +2 -3
  51. package/dist/utils/import-fixer.js.map +1 -1
  52. package/dist/utils/mutable-collection.d.ts +30 -0
  53. package/dist/utils/mutable-collection.js +2 -0
  54. package/dist/utils/mutable-collection.js.map +1 -0
  55. package/dist/utils/wire-types.d.ts +21 -0
  56. package/dist/utils/wire-types.js +2 -0
  57. package/dist/utils/wire-types.js.map +1 -0
  58. package/package.json +6 -6
package/README.md CHANGED
@@ -27,28 +27,75 @@ export default [functype.configs.strict]
27
27
 
28
28
  ## Rules
29
29
 
30
- | Rule | Recommended | Strict | Description |
31
- | ------------------------------ | :---------: | :----: | -------------------------------------------------------- |
32
- | `functype/prefer-option` | warn | error | Use `Option`/`Some`/`None` instead of `null`/`undefined` |
33
- | `functype/prefer-either` | warn | error | Use `Either`/`Left`/`Right` for typed domain errors |
34
- | `functype/prefer-try` | warn | error | Prefer `Try(() => …)` for computations that may throw |
35
- | `functype/prefer-fold` | warn | warn | Use `fold`/`match` instead of manual unwrapping |
36
- | `functype/prefer-map` | warn | warn | Use `map` instead of manual option/either checks |
37
- | `functype/prefer-flatmap` | warn | warn | Use `flatMap` instead of nested `map` |
38
- | `functype/no-imperative-loops` | warn | warn | Use `List` methods instead of imperative loops |
39
- | `functype/prefer-do-notation` | warn | warn | Use `Do` notation for chained operations |
40
- | `functype/no-get-unsafe` | off | error | Disallow unsafe `.get()` on `Option`/`Either` |
41
- | `functype/prefer-list` | off | warn | Use `List` instead of native arrays |
30
+ | Rule | Recommended | Strict | Description |
31
+ | ------------------------------ | :---------: | :----: | ---------------------------------------------------------- |
32
+ | `functype/no-let` | error | error | Use `const`; no reassignment |
33
+ | `functype/no-imperative-loops` | error | error | Use `List`/array methods or `IO.forEach` instead of loops |
34
+ | `functype/prefer-functype-map` | error | error | Use functype `Map` instead of a native `Map` you only read |
35
+ | `functype/prefer-functype-set` | error | error | Use functype `Set` instead of a native `Set` you only read |
36
+ | `functype/prefer-map` | error | error | Use `map` instead of pushing inside `forEach` |
37
+ | `functype/prefer-fold` | error | error | Use `fold` instead of branching on `isSome()`/`isLeft()`/… |
38
+ | `functype/prefer-option` | warn | error | Use `Option` instead of `null`/`undefined` |
39
+ | `functype/prefer-either` | warn | error | Use `Either` for typed domain errors instead of `throw` |
40
+ | `functype/prefer-try` | warn | error | Use `Try` / `Try.fromPromise` instead of try/catch |
41
+ | `functype/prefer-flatmap` | warn | warn | Use `flatMap` instead of `map().flat()` |
42
+ | `functype/prefer-do-notation` | warn | warn | Use `Do` notation for chained operations |
43
+ | `functype/no-get-unsafe` | off | error | Disallow unsafe extraction (`.orThrow()`, `.expect()`) |
44
+ | `functype/prefer-list` | off | warn | Use `List` instead of native arrays |
45
+
46
+ ### Severity policy
47
+
48
+ A rule is **`error` in `recommended` once it is right on ~95–99% of real code**, meaning its known false-positive classes are closed. It stays `warn` only while those classes are still open. FP here is governance: a rule that is reliably right should fail the build, not print advice nobody reads. Expect `recommended` to get stricter as boundary markers (`Wire<T>`, `@interop`) close the remaining cases for `prefer-option`, `prefer-either` and `prefer-try`.
49
+
50
+ `prefer-fold` reports only; its rewrite is a suggestion you apply, never an autofix, so `eslint --fix` can't change code on your behalf.
51
+
52
+ ## Throwing on purpose: `invariant()` and `@interop`
53
+
54
+ `prefer-either` reports every `throw`. Two kinds of throw are correct, and each has its own tool:
55
+
56
+ | The throw is… | Use |
57
+ | --------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------- |
58
+ | A bug check: the condition can only fail because of a programmer error | `invariant(cond, msg)` from `functype` |
59
+ | A host contract: the caller (React `use()`, React Query, a step runner, an MCP tool) needs a throw or rejection | `@interop <reason>` on the declaration, or `orThrow(builder)` |
60
+ | Anything that can fail in normal operation | return an `Either` |
61
+
62
+ ```ts
63
+ import { invariant } from "functype"
64
+
65
+ function deriveRunId(workflowId: string, step: number): string {
66
+ invariant(step >= 0, "step must be non-negative") // a call, not a throw: nothing to report
67
+ return `${workflowId}:${step}`
68
+ }
69
+
70
+ /**
71
+ * Runs the effect, or throws a boxed error.
72
+ *
73
+ * @interop React Query signals failure only by promise rejection; an Either return reads as success.
74
+ */
75
+ const runBoxed = async <E, A>(effect: () => IO<never, E, A>): Promise<A> => { … }
76
+
77
+ // A host throw built from the failure, with no tag at all:
78
+ const value = either.orThrow((left) => new StepError(left.message))
79
+ ```
80
+
81
+ `invariant()` covers one statement and narrows the condition for the code after it, so a function can mix bug checks with `Either`-returning failures. `@interop` rules:
82
+
83
+ - **Scope:** the tagged declaration and everything nested in it. That can be a function, `const`, method, class field, object property, type alias or interface. A sibling declaration is not covered. Honored by `prefer-either`, `prefer-option`, `prefer-fold` and `prefer-try`.
84
+ - **The reason is required**, on the same line as the tag. A bare `@interop` exempts nothing.
85
+ - **Only JSDoc (`/** … */`) counts.** A `//` comment mentioning the tag does not.
86
+ - **Opt out** per rule with `allowInteropMarker: false`.
87
+
88
+ Prefer either tool to `eslint-disable`. A disable covers a whole file or line and says only "be quiet". `rg 'invariant\('` lists every bug check, and `rg '@interop'` lists every place the code touches a throw-based host.
42
89
 
43
90
  ## Rule options
44
91
 
45
92
  ### `functype/prefer-list`
46
93
 
47
- | Option | Default | Description |
48
- | --------------------- | :-----: | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
49
- | `allowArraysInTests` | `true` | Silence the rule inside test files (`.test.ts`, `.spec.ts`, `__tests__/`, `/test/`, `/tests/`). |
50
- | `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 `Wire<T>` is the sole explicit escape hatch. |
51
- | `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. |
94
+ | Option | Default | Description |
95
+ | --------------------- | :-----: | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
96
+ | `allowArraysInTests` | `true` | Silence the rule inside test files (`.test.ts`, `.spec.ts`, `__tests__/`, `/test/`, `/tests/`). |
97
+ | `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. |
98
+ | `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. |
52
99
 
53
100
  **Boundary recipe (recommended for codebases touching serialization boundaries):**
54
101
 
@@ -62,10 +109,11 @@ Then annotate boundaries with `Wire<T>` from `functype`:
62
109
 
63
110
  ```ts
64
111
  import type { Wire } from "functype"
65
- type ClaimedDoc = Wire<Row>
112
+ type ClaimedDocs = Wire<ReadonlyArray<Row>>
113
+ type UserRow = Wire<{ readonly email: string | null; readonly tags: ReadonlyArray<string> }>
66
114
  ```
67
115
 
68
- `Wire<T>` is `ReadonlyArray<T>` structurally, so no casts. The syntactic rule ignores unrecognized type names — `Wire<T>` passes for free, and consumer aliases stack cleanly.
116
+ `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.
69
117
 
70
118
  ### `functype/no-get-unsafe`
71
119
 
@@ -76,6 +124,56 @@ type ClaimedDoc = Wire<Row>
76
124
 
77
125
  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)` / `.orThrow(err)` would silently lose their argument. Apply a suggestion explicitly in your editor when you know which one fits.
78
126
 
127
+ ### `functype/prefer-fold`
128
+
129
+ | Option | Default | Description |
130
+ | --------------- | ------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ |
131
+ | `minComplexity` | `2` | Minimum if/else chain length (root + branches) before it is reported. |
132
+ | `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. |
133
+
134
+ 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.
135
+
136
+ ### `functype/prefer-option`
137
+
138
+ | Option | Default | Description |
139
+ | --------------- | ------- | -------------------------------------------------------------------------------------------------------- |
140
+ | `allowUseState` | `true` | Don't report `T \| null` inside the type argument of `useState` / `useRef` (bare or `React.`-qualified). |
141
+
142
+ `null` is idiomatic React state, and an `Option` there fights the hook's own API. Nullable component parameters and props are still reported.
143
+
144
+ ### `functype/prefer-map`
145
+
146
+ | Option | Default | Description |
147
+ | ------------------- | ------- | -------------------------------------------------------------------------------------------------------------- |
148
+ | `checkArrayMethods` | `true` | Report `.push` inside `forEach` callbacks and `forEach` used as a map. |
149
+ | `checkForLoops` | `false` | Also report `for`/`for..of`/`for..in` loops that push. Off because `no-imperative-loops` already reports them. |
150
+
151
+ ### `functype/prefer-functype-set` / `functype/prefer-functype-map`
152
+
153
+ | Option | Default | Description |
154
+ | -------------- | ------- | ----------------------------------------------------------------------------------------------- |
155
+ | `allowInTests` | `true` | Silence the rule inside test files. |
156
+ | `allowMutable` | `true` | Don't report a native `Set`/`Map` the code mutates on purpose. Set `false` to report it anyway. |
157
+
158
+ A collection counts as mutated when `.add` / `.delete` / `.clear` (Set) or `.set` / `.delete` / `.clear` (Map) is called on it, including `x!.add(…)`. The call can be made:
159
+
160
+ - directly on a `new` expression that copies something (`new Set(prev).add(id)`, the React copy-then-add). An empty-`new` builder chain like `new Map().set(a, 1).set(b, 2)` is not exempt; use `Map.of` / `Set.of`.
161
+ - directly through the variable, parameter or later-assigned `let` holding it, in any nested scope.
162
+ - through `this.<field>` in the owning class: a field initializer, a constructor assignment, or a constructor parameter property.
163
+
164
+ Not followed: aliases (`const t = s; t.add(x)`), `useRef(new Set()).current.add(x)`, a mutator passed as a callback (`xs.forEach(seen.add, seen)`), and a collection passed into another function. Those are still reported.
165
+
166
+ functype's collections are immutable, so a cache, registry or in-place accumulator can't use them. A native collection that is only read (`.has`, `.get`, iteration) is still reported.
167
+
168
+ ### `functype/no-imperative-loops` / `functype/prefer-map`
169
+
170
+ These rules don't report loops that have no functional equivalent:
171
+
172
+ - `for await` consumes a stream, and collecting it first would defeat the streaming.
173
+ - A loop whose body `yield`s is a generator's body, and a callback can't yield.
174
+
175
+ A loop whose body `await`s is still reported by `no-imperative-loops`, which points at `IO.forEach`. `prefer-map` doesn't report it.
176
+
79
177
  ## Combining with eslint-config-functype
80
178
 
81
179
  For a complete setup with functional rules, TypeScript, Prettier, and import sorting:
@@ -1 +1 @@
1
- {"version":3,"file":"list-rules.js","names":[],"sources":["../../src/cli/list-rules.ts"],"sourcesContent":["#!/usr/bin/env node\n\nimport plugin from \"../index.js\"\nimport { validatePeerDependencies, type ValidationResult } from \"../utils/dependency-validator.js\"\n\n// Colors for console output\nconst colors = {\n reset: \"\\x1b[0m\",\n bright: \"\\x1b[1m\",\n red: \"\\x1b[31m\",\n green: \"\\x1b[32m\",\n yellow: \"\\x1b[33m\",\n blue: \"\\x1b[34m\",\n magenta: \"\\x1b[35m\",\n cyan: \"\\x1b[36m\",\n} as const\n\nfunction colorize(text: string, color: keyof typeof colors): string {\n return colors[color] + text + colors.reset\n}\n\n// Removed unused utility functions - they were for the old config-based approach\n\nfunction printDependencyStatus(result: ValidationResult): void {\n console.log(colorize(\"\\n🔍 Dependency Status Check:\", \"bright\"))\n console.log(colorize(\"=\".repeat(40), \"blue\"))\n\n // Show available dependencies\n if (result.available.length > 0) {\n console.log(colorize(\"\\n✅ Available:\", \"green\"))\n result.available.forEach((dep) => {\n const icon = dep.required ? \"🔧\" : \"🔌\"\n console.log(` ${icon} ${colorize(dep.name, \"green\")} - ${dep.description}`)\n })\n }\n\n // Show missing dependencies\n if (result.missing.length > 0) {\n console.log(colorize(\"\\n❌ Missing:\", \"red\"))\n result.missing.forEach((dep) => {\n const icon = dep.required ? \"⚠️ \" : \"💡\"\n const color = dep.required ? \"red\" : \"yellow\"\n console.log(` ${icon} ${colorize(dep.name, color)} - ${dep.description}`)\n })\n\n if (result.installCommand) {\n console.log(colorize(\"\\n📦 Install missing dependencies:\", \"bright\"))\n console.log(` ${colorize(result.installCommand, \"cyan\")}`)\n }\n }\n\n // Show warnings\n if (result.warnings.length > 0) {\n console.log(colorize(\"\\n⚠️ Warnings:\", \"yellow\"))\n result.warnings.forEach((warning) => console.log(` ${warning}`))\n }\n\n // Overall status\n const status = result.isValid ? \"✅ Ready to use\" : \"❌ Configuration will fail\"\n const statusColor = result.isValid ? \"green\" : \"red\"\n console.log(colorize(`\\n${status}`, statusColor))\n}\n\nasync function main(): Promise<void> {\n const args = process.argv.slice(2)\n const showHelp = args.includes(\"--help\") || args.includes(\"-h\")\n const showUsage = args.includes(\"--usage\") || args.includes(\"-u\")\n const checkDeps = args.includes(\"--check-deps\") || args.includes(\"--check\")\n\n if (showHelp) {\n console.log(colorize(\"📋 ESLint Plugin Functype - Custom Rules\", \"bright\"))\n console.log(\"\\nUsage: pnpm run list-rules [options]\")\n console.log(\"\\nOptions:\")\n console.log(\" --verbose, -v Show rule descriptions and schemas\")\n console.log(\" --usage, -u Show usage examples\")\n console.log(\" --check-deps Check peer dependency status\")\n console.log(\" --help, -h Show this help message\")\n console.log(\"\\nThis command lists all custom rules provided by the functype plugin.\")\n return\n }\n\n // Handle dependency check\n if (checkDeps) {\n console.log(colorize(\"🔧 ESLint Plugin Functype - Dependency Check\", \"bright\"))\n const result = validatePeerDependencies()\n printDependencyStatus(result)\n\n if (!result.isValid) {\n process.exit(1)\n }\n return\n }\n\n console.log(colorize(\"🔧 ESLint Plugin Functype - Custom Rules\", \"bright\"))\n\n if (!plugin.rules) {\n console.error(colorize(\"❌ No rules found in plugin.\", \"red\"))\n process.exit(1)\n }\n\n console.log(colorize(\"\\n📦 Available Custom Rules:\", \"bright\"))\n console.log(colorize(\"=\".repeat(40), \"blue\"))\n\n const rules = Object.keys(plugin.rules)\n\n rules.forEach((ruleName) => {\n const rule = plugin.rules[ruleName]\n const fullName = `functype/${ruleName}`\n\n console.log(`\\n${colorize(\"●\", \"green\")} ${colorize(fullName, \"bright\")}`)\n\n if (rule.meta?.docs?.description) {\n console.log(` ${colorize(\"Description:\", \"cyan\")} ${rule.meta.docs.description}`)\n }\n\n if (rule.meta?.type) {\n const typeColor = rule.meta.type === \"problem\" ? \"red\" : rule.meta.type === \"suggestion\" ? \"yellow\" : \"blue\"\n console.log(` ${colorize(\"Type:\", \"cyan\")} ${colorize(rule.meta.type, typeColor)}`)\n }\n\n if (rule.meta?.fixable) {\n console.log(` ${colorize(\"Fixable:\", \"cyan\")} ${colorize(\"Yes\", \"green\")}`)\n }\n\n if (showUsage) {\n console.log(` ${colorize(\"Usage:\", \"cyan\")} \"${fullName}\": \"error\"`)\n }\n })\n\n console.log(colorize(`\\n📊 Summary: ${rules.length} custom rules available`, \"bright\"))\n\n if (showUsage) {\n printCustomUsageInfo()\n }\n\n console.log(colorize(\"\\n💡 Tips:\", \"bright\"))\n console.log(\"• Use --verbose to see detailed rule information\")\n console.log(\"• Use --usage to see configuration examples\")\n console.log('• All rules are prefixed with \"functype/\"')\n console.log(\"• Consider using eslint-config-functype for pre-configured setup\")\n\n console.log(colorize(\"\\n🔗 Links:\", \"bright\"))\n console.log(\"• Documentation: https://github.com/jordanburke/eslint-plugin-functype\")\n console.log(\"• Configuration Bundle: https://github.com/jordanburke/eslint-config-functype\")\n console.log(\"• Functype Library: https://github.com/jordanburke/functype\")\n}\n\nfunction printCustomUsageInfo(): void {\n console.log(colorize(\"\\n💡 Usage Examples:\", \"bright\"))\n console.log(colorize(\"=\".repeat(30), \"blue\"))\n console.log(\"\\n\" + colorize(\"ESLint 9+ (flat config):\", \"green\"))\n console.log(' import functypePlugin from \"eslint-plugin-functype\"')\n console.log(\" export default [\")\n console.log(\" {\")\n console.log(\" plugins: { functype: functypePlugin },\")\n console.log(\" rules: {\")\n console.log(' \"functype/prefer-option\": \"error\",')\n console.log(' \"functype/prefer-either\": \"error\",')\n console.log(' \"functype/no-get-unsafe\": \"error\",')\n console.log(\" }\")\n console.log(\" }\")\n console.log(\" ]\")\n console.log(\"\\n\" + colorize(\"With eslint-config-functype (recommended):\", \"green\"))\n console.log(' import functypeConfig from \"eslint-config-functype\"')\n console.log(\" export default [functypeConfig.recommended]\")\n}\n\n// Run the CLI\nmain().catch((error) => {\n console.error(colorize(\"❌ Unexpected error:\", \"red\"), error)\n process.exit(1)\n})\n"],"mappings":";uGAMA,MAAM,EAAS,CACb,MAAO,UACP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,IAAI,uDAAuD,EACnE,QAAQ,IAAI,+CAA+C,CAC7D,CAGA,EAAK,CAAC,CAAC,MAAO,GAAU,CACtB,QAAQ,MAAM,EAAS,sBAAuB,KAAK,EAAG,CAAK,EAC3D,QAAQ,KAAK,CAAC,CAChB,CAAC"}
1
+ {"version":3,"file":"list-rules.js","names":["plugin","colors","colorize","color","text","printDependencyStatus","result","icon","dep","warning","status","statusColor","main","args","showHelp","showUsage","checkDeps","validatePeerDependencies","rules","rule","ruleName","fullName","typeColor","printCustomUsageInfo","error"],"sources":["../../src/cli/list-rules.ts"],"sourcesContent":["#!/usr/bin/env node\n\nimport plugin from \"../index.js\"\nimport { validatePeerDependencies, type ValidationResult } from \"../utils/dependency-validator.js\"\n\n// Colors for console output\nconst colors = {\n reset: \"\\x1b[0m\",\n bright: \"\\x1b[1m\",\n red: \"\\x1b[31m\",\n green: \"\\x1b[32m\",\n yellow: \"\\x1b[33m\",\n blue: \"\\x1b[34m\",\n magenta: \"\\x1b[35m\",\n cyan: \"\\x1b[36m\",\n} as const\n\nfunction colorize(text: string, color: keyof typeof colors): string {\n return colors[color] + text + colors.reset\n}\n\n// Removed unused utility functions - they were for the old config-based approach\n\nfunction printDependencyStatus(result: ValidationResult): void {\n console.log(colorize(\"\\n🔍 Dependency Status Check:\", \"bright\"))\n console.log(colorize(\"=\".repeat(40), \"blue\"))\n\n // Show available dependencies\n if (result.available.length > 0) {\n console.log(colorize(\"\\n✅ Available:\", \"green\"))\n result.available.forEach((dep) => {\n const icon = dep.required ? \"🔧\" : \"🔌\"\n console.log(` ${icon} ${colorize(dep.name, \"green\")} - ${dep.description}`)\n })\n }\n\n // Show missing dependencies\n if (result.missing.length > 0) {\n console.log(colorize(\"\\n❌ Missing:\", \"red\"))\n result.missing.forEach((dep) => {\n const icon = dep.required ? \"⚠️ \" : \"💡\"\n const color = dep.required ? \"red\" : \"yellow\"\n console.log(` ${icon} ${colorize(dep.name, color)} - ${dep.description}`)\n })\n\n if (result.installCommand) {\n console.log(colorize(\"\\n📦 Install missing dependencies:\", \"bright\"))\n console.log(` ${colorize(result.installCommand, \"cyan\")}`)\n }\n }\n\n // Show warnings\n if (result.warnings.length > 0) {\n console.log(colorize(\"\\n⚠️ Warnings:\", \"yellow\"))\n result.warnings.forEach((warning) => console.log(` ${warning}`))\n }\n\n // Overall status\n const status = result.isValid ? \"✅ Ready to use\" : \"❌ Configuration will fail\"\n const statusColor = result.isValid ? \"green\" : \"red\"\n console.log(colorize(`\\n${status}`, statusColor))\n}\n\nasync function main(): Promise<void> {\n const args = process.argv.slice(2)\n const showHelp = args.includes(\"--help\") || args.includes(\"-h\")\n const showUsage = args.includes(\"--usage\") || args.includes(\"-u\")\n const checkDeps = args.includes(\"--check-deps\") || args.includes(\"--check\")\n\n if (showHelp) {\n console.log(colorize(\"📋 ESLint Plugin Functype - Custom Rules\", \"bright\"))\n console.log(\"\\nUsage: pnpm run list-rules [options]\")\n console.log(\"\\nOptions:\")\n console.log(\" --verbose, -v Show rule descriptions and schemas\")\n console.log(\" --usage, -u Show usage examples\")\n console.log(\" --check-deps Check peer dependency status\")\n console.log(\" --help, -h Show this help message\")\n console.log(\"\\nThis command lists all custom rules provided by the functype plugin.\")\n return\n }\n\n // Handle dependency check\n if (checkDeps) {\n console.log(colorize(\"🔧 ESLint Plugin Functype - Dependency Check\", \"bright\"))\n const result = validatePeerDependencies()\n printDependencyStatus(result)\n\n if (!result.isValid) {\n process.exit(1)\n }\n return\n }\n\n console.log(colorize(\"🔧 ESLint Plugin Functype - Custom Rules\", \"bright\"))\n\n if (!plugin.rules) {\n console.error(colorize(\"❌ No rules found in plugin.\", \"red\"))\n process.exit(1)\n }\n\n console.log(colorize(\"\\n📦 Available Custom Rules:\", \"bright\"))\n console.log(colorize(\"=\".repeat(40), \"blue\"))\n\n const rules = Object.keys(plugin.rules)\n\n rules.forEach((ruleName) => {\n const rule = plugin.rules[ruleName]\n const fullName = `functype/${ruleName}`\n\n console.log(`\\n${colorize(\"●\", \"green\")} ${colorize(fullName, \"bright\")}`)\n\n if (rule.meta?.docs?.description) {\n console.log(` ${colorize(\"Description:\", \"cyan\")} ${rule.meta.docs.description}`)\n }\n\n if (rule.meta?.type) {\n const typeColor = rule.meta.type === \"problem\" ? \"red\" : rule.meta.type === \"suggestion\" ? \"yellow\" : \"blue\"\n console.log(` ${colorize(\"Type:\", \"cyan\")} ${colorize(rule.meta.type, typeColor)}`)\n }\n\n if (rule.meta?.fixable) {\n console.log(` ${colorize(\"Fixable:\", \"cyan\")} ${colorize(\"Yes\", \"green\")}`)\n }\n\n if (showUsage) {\n console.log(` ${colorize(\"Usage:\", \"cyan\")} \"${fullName}\": \"error\"`)\n }\n })\n\n console.log(colorize(`\\n📊 Summary: ${rules.length} custom rules available`, \"bright\"))\n\n if (showUsage) {\n printCustomUsageInfo()\n }\n\n console.log(colorize(\"\\n💡 Tips:\", \"bright\"))\n console.log(\"• Use --verbose to see detailed rule information\")\n console.log(\"• Use --usage to see configuration examples\")\n console.log('• All rules are prefixed with \"functype/\"')\n console.log(\"• Consider using eslint-config-functype for pre-configured setup\")\n\n console.log(colorize(\"\\n🔗 Links:\", \"bright\"))\n console.log(\"• Documentation: https://github.com/jordanburke/eslint-plugin-functype\")\n console.log(\"• Configuration Bundle: https://github.com/jordanburke/eslint-config-functype\")\n console.log(\"• Functype Library: https://github.com/jordanburke/functype\")\n}\n\nfunction printCustomUsageInfo(): void {\n console.log(colorize(\"\\n💡 Usage Examples:\", \"bright\"))\n console.log(colorize(\"=\".repeat(30), \"blue\"))\n console.log(\"\\n\" + colorize(\"ESLint 9+ (flat config):\", \"green\"))\n console.log(' import functypePlugin from \"eslint-plugin-functype\"')\n console.log(\" export default [\")\n console.log(\" {\")\n console.log(\" plugins: { functype: functypePlugin },\")\n console.log(\" rules: {\")\n console.log(' \"functype/prefer-option\": \"error\",')\n console.log(' \"functype/prefer-either\": \"error\",')\n console.log(' \"functype/no-get-unsafe\": \"error\",')\n console.log(\" }\")\n console.log(\" }\")\n console.log(\" ]\")\n console.log(\"\\n\" + colorize(\"With eslint-config-functype (recommended):\", \"green\"))\n console.log(' import functypeConfig from \"eslint-config-functype\"')\n console.log(\" export default [functypeConfig.recommended]\")\n}\n\n// Run the CLI\nmain().catch((error) => {\n console.error(colorize(\"❌ Unexpected error:\", \"red\"), error)\n process.exit(1)\n})\n"],"mappings":";uGAMA,MAAMC,EAAS,CACb,MAAO,UACP,OAAQ,UACR,IAAK,WACL,MAAO,WACP,OAAQ,WACR,KAAM,WACN,QAAS,WACT,KAAM,UACR,EAEA,SAASC,EAAS,EAAc,EAAoC,CAClE,OAAOD,EAAOE,GAASC,EAAOH,EAAO,KACvC,CAIA,SAASI,EAAsB,EAAgC,CAC7D,QAAQ,IAAIH,EAAS;6BAAiC,QAAQ,CAAC,EAC/D,QAAQ,IAAIA,EAAS,IAAI,OAAO,EAAE,EAAG,MAAM,CAAC,EAGxCI,EAAO,UAAU,OAAS,IAC5B,QAAQ,IAAIJ,EAAS;cAAkB,OAAO,CAAC,EAC/CI,EAAO,UAAU,QAAS,GAAQ,CAChC,IAAMC,EAAOC,EAAI,SAAW,KAAO,KACnC,QAAQ,IAAI,KAAKD,EAAK,GAAGL,EAASM,EAAI,KAAM,OAAO,EAAE,KAAKA,EAAI,aAAa,CAC7E,CAAC,GAICF,EAAO,QAAQ,OAAS,IAC1B,QAAQ,IAAIJ,EAAS;YAAgB,KAAK,CAAC,EAC3CI,EAAO,QAAQ,QAAS,GAAQ,CAC9B,IAAMC,EAAOC,EAAI,SAAW,MAAQ,KAC9BL,EAAQK,EAAI,SAAW,MAAQ,SACrC,QAAQ,IAAI,KAAKD,EAAK,GAAGL,EAASM,EAAI,KAAML,CAAK,EAAE,KAAKK,EAAI,aAAa,CAC3E,CAAC,EAEGF,EAAO,iBACT,QAAQ,IAAIJ,EAAS;kCAAsC,QAAQ,CAAC,EACpE,QAAQ,IAAI,MAAMA,EAASI,EAAO,eAAgB,MAAM,GAAG,IAK3DA,EAAO,SAAS,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,IAAI;EAAOA,EAAS,2BAA4B,OAAO,CAAC,EAChE,QAAQ,IAAI,uDAAuD,EACnE,QAAQ,IAAI,oBAAoB,EAChC,QAAQ,IAAI,OAAO,EACnB,QAAQ,IAAI,8CAA8C,EAC1D,QAAQ,IAAI,gBAAgB,EAC5B,QAAQ,IAAI,4CAA4C,EACxD,QAAQ,IAAI,4CAA4C,EACxD,QAAQ,IAAI,4CAA4C,EACxD,QAAQ,IAAI,SAAS,EACrB,QAAQ,IAAI,OAAO,EACnB,QAAQ,IAAI,KAAK,EACjB,QAAQ,IAAI;EAAOA,EAAS,6CAA8C,OAAO,CAAC,EAClF,QAAQ,IAAI,uDAAuD,EACnE,QAAQ,IAAI,+CAA+C,CAC7D,CAGAU,EAAK,CAAC,CAAC,MAAO,GAAU,CACtB,QAAQ,MAAMV,EAAS,sBAAuB,KAAK,EAAGsB,CAAK,EAC3D,QAAQ,KAAK,CAAC,CAChB,CAAC"}
@@ -1,15 +1,32 @@
1
1
  //#region src/configs/recommended.d.ts
2
+ /**
3
+ * Severity policy (#325): a rule is `error` once it is right on ~95–99% of real code and its known
4
+ * false-positive classes are closed; it stays `warn` only while those classes are still open. FP here
5
+ * is governance — a rule that is reliably right should fail the build, not print advice nobody reads
6
+ * (CivalaOS shipped 85 new violations under "lint OK" because every rule but `no-let` warned).
7
+ *
8
+ * Still `warn`, and why:
9
+ * - prefer-option / prefer-either / prefer-try: fire on correct code at serialization boundaries
10
+ * (JSON rows, DTOs) and on throws that are correct (bug checks, host contracts). Wire<T> (#325 B),
11
+ * invariant() and @interop (#342) close those; graduating them is a measured decision.
12
+ * - prefer-flatmap / prefer-do-notation: heuristics without type information; precision unmeasured.
13
+ *
14
+ * Graduated with a precision condition: prefer-fold checks functype predicate calls (`isSome()`,
15
+ * `isLeft()`) only; its null-check heuristic is opt-in (`checkNullable`) because it fired on plain
16
+ * nullables — 31 of 31 hits in CivalaOS. prefer-map leaves loops to no-imperative-loops (`checkForLoops`
17
+ * off), so one loop is one error.
18
+ */
2
19
  declare const recommendedRules: {
3
20
  "functype/no-let": string;
21
+ "functype/no-imperative-loops": string;
22
+ "functype/prefer-functype-map": string;
23
+ "functype/prefer-functype-set": string;
24
+ "functype/prefer-map": string;
25
+ "functype/prefer-fold": string;
4
26
  "functype/prefer-option": string;
5
27
  "functype/prefer-either": string;
6
28
  "functype/prefer-try": string;
7
- "functype/prefer-fold": string;
8
- "functype/prefer-map": string;
9
29
  "functype/prefer-flatmap": string;
10
- "functype/prefer-functype-map": string;
11
- "functype/prefer-functype-set": string;
12
- "functype/no-imperative-loops": string;
13
30
  "functype/prefer-do-notation": string;
14
31
  "functype/no-get-unsafe": string;
15
32
  "functype/prefer-list": string;
@@ -1,2 +1,2 @@
1
- const e={"functype/no-let":`error`,"functype/prefer-option":`warn`,"functype/prefer-either":`warn`,"functype/prefer-try":`warn`,"functype/prefer-fold":`warn`,"functype/prefer-map":`warn`,"functype/prefer-flatmap":`warn`,"functype/prefer-functype-map":`warn`,"functype/prefer-functype-set":`warn`,"functype/no-imperative-loops":`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/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};
2
2
  //# sourceMappingURL=recommended.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"recommended.js","names":[],"sources":["../../src/configs/recommended.ts"],"sourcesContent":["const recommendedRules = {\n \"functype/no-let\": \"error\",\n \"functype/prefer-option\": \"warn\",\n \"functype/prefer-either\": \"warn\",\n \"functype/prefer-try\": \"warn\",\n \"functype/prefer-fold\": \"warn\",\n \"functype/prefer-map\": \"warn\",\n \"functype/prefer-flatmap\": \"warn\",\n \"functype/prefer-functype-map\": \"warn\",\n \"functype/prefer-functype-set\": \"warn\",\n \"functype/no-imperative-loops\": \"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":"AAAA,MAAM,EAAmB,CACvB,kBAAmB,QACnB,yBAA0B,OAC1B,yBAA0B,OAC1B,sBAAuB,OACvB,uBAAwB,OACxB,sBAAuB,OACvB,0BAA2B,OAC3B,+BAAgC,OAChC,+BAAgC,OAChC,+BAAgC,OAChC,8BAA+B,OAC/B,yBAA0B,MAC1B,uBAAwB,KAC1B"}
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 */\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/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":"AAiBA,MAAMA,EAAmB,CACvB,kBAAmB,QACnB,+BAAgC,QAChC,+BAAgC,QAChC,+BAAgC,QAChC,sBAAuB,QACvB,uBAAwB,QACxB,yBAA0B,OAC1B,yBAA0B,OAC1B,sBAAuB,OACvB,0BAA2B,OAC3B,8BAA+B,OAC/B,yBAA0B,MAC1B,uBAAwB,KAC1B"}
@@ -9,8 +9,8 @@ declare const strictRules: {
9
9
  "functype/prefer-functype-set": string;
10
10
  "functype/no-imperative-loops": string;
11
11
  "functype/no-let": string;
12
- "functype/prefer-fold": string;
13
12
  "functype/prefer-map": string;
13
+ "functype/prefer-fold": string;
14
14
  "functype/prefer-flatmap": string;
15
15
  "functype/prefer-do-notation": string;
16
16
  };
@@ -1 +1 @@
1
- {"version":3,"file":"strict.js","names":[],"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,MAAM,EAAc,CAClB,GAAG,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/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"}
package/dist/index.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"file":"index.js","names":[],"sources":["../src/index.ts"],"sourcesContent":["import recommendedRules from \"./configs/recommended\"\nimport strictRules from \"./configs/strict\"\nimport rules from \"./rules\"\n\nconst plugin = {\n rules,\n meta: {\n name: \"eslint-plugin-functype\",\n version: \"2.0.0\",\n },\n configs: {} as Record<string, unknown>,\n}\n\n// Self-referencing plugin in configs (ESLint flat config pattern)\nplugin.configs = {\n recommended: {\n name: \"functype-plugin/recommended\",\n plugins: { functype: plugin },\n rules: recommendedRules,\n },\n strict: {\n name: \"functype-plugin/strict\",\n plugins: { functype: plugin },\n rules: strictRules,\n },\n}\n\nexport default plugin\n"],"mappings":"2GAIA,MAAM,EAAS,CACb,MAAA,EACA,KAAM,CACJ,KAAM,yBACN,QAAS,OACX,EACA,QAAS,CAAC,CACZ,EAGA,EAAO,QAAU,CACf,YAAa,CACX,KAAM,8BACN,QAAS,CAAE,SAAU,CAAO,EAC5B,MAAO,CACT,EACA,OAAQ,CACN,KAAM,yBACN,QAAS,CAAE,SAAU,CAAO,EAC5B,MAAO,CACT,CACF"}
1
+ {"version":3,"file":"index.js","names":["recommendedRules","strictRules","rules_default","plugin"],"sources":["../src/index.ts"],"sourcesContent":["import recommendedRules from \"./configs/recommended\"\nimport strictRules from \"./configs/strict\"\nimport rules from \"./rules\"\n\nconst plugin = {\n rules,\n meta: {\n name: \"eslint-plugin-functype\",\n version: \"2.0.0\",\n },\n configs: {} as Record<string, unknown>,\n}\n\n// Self-referencing plugin in configs (ESLint flat config pattern)\nplugin.configs = {\n recommended: {\n name: \"functype-plugin/recommended\",\n plugins: { functype: plugin },\n rules: recommendedRules,\n },\n strict: {\n name: \"functype-plugin/strict\",\n plugins: { functype: plugin },\n rules: strictRules,\n },\n}\n\nexport default plugin\n"],"mappings":"2GAIA,MAAMG,EAAS,CACb,MAAAD,EACA,KAAM,CACJ,KAAM,yBACN,QAAS,OACX,EACA,QAAS,CAAC,CACZ,EAGA,EAAO,QAAU,CACf,YAAa,CACX,KAAM,8BACN,QAAS,CAAE,SAAUC,CAAO,EAC5B,MAAOH,CACT,EACA,OAAQ,CACN,KAAM,yBACN,QAAS,CAAE,SAAUG,CAAO,EAC5B,MAAOF,CACT,CACF"}
@@ -1 +1 @@
1
- {"version":3,"file":"index.js","names":["preferOption","preferEither","preferTry","preferList","noGetUnsafe","noLet","preferFold","preferMap","preferFlatmap","preferFunctypeMap","preferFunctypeSet","noImperativeLoops","preferDoNotation"],"sources":["../../src/rules/index.ts"],"sourcesContent":["import 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 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}\n"],"mappings":"icA8BA,IAAA,EAAe,CACb,gBAAiBA,EACjB,gBAAiBC,EACjB,aAAcC,EACd,cAAeC,EACf,gBAAiBC,EACjB,SAAUC,EACV,cAAeC,EACf,aAAcC,EACd,iBAAkBC,EAClB,sBAAuBC,EACvB,sBAAuBC,EACvB,sBAAuBC,EACvB,qBAAsBC,CACxB"}
1
+ {"version":3,"file":"index.js","names":["preferOption","preferEither","preferTry","preferList","noGetUnsafe","noLet","preferFold","preferMap","preferFlatmap","preferFunctypeMap","preferFunctypeSet","noImperativeLoops","preferDoNotation","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","rules_default"],"sources":["../../src/rules/index.ts"],"sourcesContent":["import 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 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}\n"],"mappings":"icA8BA,IAAA0B,EAAe,CACb,gBAAiB1B,EACjB,gBAAiBC,EACjB,aAAcC,EACd,cAAeC,EACf,gBAAiBC,EACjB,SAAUC,EACV,cAAeC,EACf,aAAcC,EACd,iBAAkBC,EAClB,sBAAuBC,EACvB,sBAAuBC,EACvB,sBAAuBC,EACvB,qBAAsBC,CACxB"}
@@ -1 +1 @@
1
- {"version":3,"file":"no-get-unsafe.js","names":[],"sources":["../../src/rules/no-get-unsafe.ts"],"sourcesContent":["import type { Rule } from \"eslint\"\n\nimport type { ASTNode } from \"../types/ast\"\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 unsafeMethods: {\n type: \"array\",\n items: { type: \"string\" },\n default: [...DEFAULT_UNSAFE_METHODS],\n },\n },\n additionalProperties: false,\n },\n ],\n messages: {\n noUnsafeGet: \"Avoid unsafe .{{method}}() call. Use .fold(), .map(), or .orElse() instead\",\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\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\n // Check if this looks like it's being called on a monadic type\n if (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":"AAIA,MAAM,EAA4C,CAAC,UAAW,SAAU,MAAO,aAAc,QAAQ,EAE/F,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,cAAe,CACb,KAAM,QACN,MAAO,CAAE,KAAM,QAAS,EACxB,QAAS,CAAC,GAAG,CAAsB,CACrC,CACF,EACA,qBAAsB,EACxB,CACF,EACA,SAAU,CACR,YAAa,6EACb,cAAe,qDACf,YAAa,wDACf,CACF,EAEA,OAAO,EAAS,CACd,IAAM,EAAU,EAAQ,QAAQ,IAAM,CAAC,EACjC,EAAe,EAAQ,eAAiB,GACxC,EAAmC,EAAQ,eAAiB,EAElE,SAAS,GAAe,CACtB,IAAM,EAAW,EAAQ,SACzB,MACE,kCAAkC,KAAK,CAAQ,GAC/C,EAAS,SAAS,WAAW,GAC7B,EAAS,SAAS,QAAQ,GAC1B,EAAS,SAAS,SAAS,CAE/B,CAEA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-unsafe.js","names":["DEFAULT_UNSAFE_METHODS","rule","options","context","allowInTests","unsafeMethods","isInTestFile","filename","isMonadicType","node","text","varName","property","methodName","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\"\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 unsafeMethods: {\n type: \"array\",\n items: { type: \"string\" },\n default: [...DEFAULT_UNSAFE_METHODS],\n },\n },\n additionalProperties: false,\n },\n ],\n messages: {\n noUnsafeGet: \"Avoid unsafe .{{method}}() call. Use .fold(), .map(), or .orElse() instead\",\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\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\n // Check if this looks like it's being called on a monadic type\n if (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 r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,OAAS,mBAAoB,OAE7C,IAAMG,EAAWH,EAAK,OAAO,SAC7B,GAAI,CAACG,GAAYA,EAAS,OAAS,aAAc,OAEjD,IAAMC,EAAaD,EAAS,KAC5B,GAAKP,EAAc,SAASQ,CAAU,GAGlCL,EAAcC,EAAK,OAAO,MAAM,EAAG,CACrC,IAAMK,EAAaX,EAAQ,WACrBY,EAAaD,EAAW,QAAQL,EAAK,OAAO,MAAM,EAMlDO,EAAWP,EAAK,UAAU,IAAK,GAAeK,EAAW,QAAQG,CAAC,CAAC,CAAC,CAAC,KAAK,IAAI,EAC9EC,EAAYF,EAAW,SAASH,EAAW,GAAGG,EAAS,GAAK,GAElEb,EAAQ,OAAO,CACb,OACA,UAAW,cACX,KAAM,CAAE,OAAQU,CAAW,EAC3B,QAAS,CACP,CACE,UAAW,gBACX,IAAI,EAAO,CACT,OAAOM,EAAM,YAAYV,EAAM,GAAGM,EAAW,oCAAoCG,EAAU,KAAK,CAClG,CACF,EACA,CACE,UAAW,cACX,IAAI,EAAO,CACT,OAAOC,EAAM,YACXV,EACA,GAAGM,EAAW,uCAAuCG,EAAU,kCACjE,CACF,CACF,CACF,CACF,CAAC,CACH,CACF,CACF,CACF,CACF"}
@@ -1,2 +1,2 @@
1
- const e={meta:{type:`suggestion`,hasSuggestions:!0,docs:{description:`Prefer functional iteration methods over imperative for loops`,recommended:!0},schema:[{type:`object`,properties:{allowForIndexAccess:{type:`boolean`,default:!1},allowWhileLoops:{type:`boolean`,default:!1},allowInTests:{type:`boolean`,default:!0}},additionalProperties:!1}],messages:{noForLoop:`Prefer functional methods (.map, .filter, .forEach, .reduce) over for loops`,noForInLoop:`Prefer Object.keys().forEach() or functional methods over for..in loops`,noForOfLoop:`Prefer .forEach() or .map() over for..of loops`,noWhileLoop:`Prefer functional iteration or recursion over while loops`,noDoWhileLoop:`Prefer functional iteration or recursion over do..while loops`,suggestForEach:`Replace with {{iterable}}.forEach(...)`,suggestObjectKeys:`Replace with Object.keys({{object}}).forEach(...)`}},create(e){let t=e.options[0]||{},n=t.allowForIndexAccess||!1,r=t.allowWhileLoops||!1,i=t.allowInTests!==!1;function a(){let t=e.filename;return/\.(test|spec)\.(ts|js|tsx|jsx)$/.test(t)||t.includes(`__tests__`)||t.includes(`/test/`)||t.includes(`/tests/`)}function o(t){if(!t.body||t.body.type!==`BlockStatement`)return!1;let n=e.sourceCode.getText(t.body);return/\[\s*\w+\s*\]/.test(n)&&t.init&&t.init.type===`VariableDeclaration`}function s(e){return!e.body||e.body.type!==`BlockStatement`?!1:e.body.body.length===1}function c(e){let t=e.left;if(!t)return!1;if(t.type===`VariableDeclaration`&&t.declarations[0]){let e=t.declarations[0].id;return e.type===`ObjectPattern`||e.type===`ArrayPattern`}return!1}function l(t){let n=e.sourceCode.getText(t.body);return/\b(break|continue)\b/.test(n)}return{ForStatement(t){i&&a()||n&&o(t)||e.report({node:t,messageId:`noForLoop`})},ForInStatement(t){if(i&&a())return;let n=[];if(s(t)&&!c(t)&&!l(t)){let r=e.sourceCode,i=t.body.body[0];if(i&&i.type===`ExpressionStatement`){let e=r.getText(i),a=r.getText(t.right),o=t.left,s=o.type===`VariableDeclaration`&&o.declarations[0]?r.getText(o.declarations[0].id):r.getText(o);n.push({messageId:`suggestObjectKeys`,data:{object:a},fix(n){return n.replaceText(t,`Object.keys(${a}).forEach((${s}) => {\n ${e}\n})`)}})}}e.report({node:t,messageId:`noForInLoop`,suggest:n.length>0?n:void 0})},ForOfStatement(t){if(i&&a())return;let n=[];if(s(t)&&!c(t)&&!l(t)){let r=e.sourceCode,i=t.body.body[0];if(i&&i.type===`ExpressionStatement`){let e=r.getText(i),a=r.getText(t.right),o=t.left,s=o.type===`VariableDeclaration`&&o.declarations[0]?r.getText(o.declarations[0].id):r.getText(o);e.includes(`.push(`)||n.push({messageId:`suggestForEach`,data:{iterable:a},fix(n){return n.replaceText(t,`${a}.forEach((${s}) => {\n ${e}\n})`)}})}}e.report({node:t,messageId:`noForOfLoop`,suggest:n.length>0?n:void 0})},WhileStatement(t){r||i&&a()||e.report({node:t,messageId:`noWhileLoop`})},DoWhileStatement(t){r||i&&a()||e.report({node:t,messageId:`noDoWhileLoop`})}}}};export{e as default};
1
+ import{containsAwait as e,containsYield as t}from"../utils/async-detection.js";const n={meta:{type:`suggestion`,hasSuggestions:!0,docs:{description:`Prefer functional iteration methods over imperative for loops`,recommended:!0},schema:[{type:`object`,properties:{allowForIndexAccess:{type:`boolean`,default:!1},allowWhileLoops:{type:`boolean`,default:!1},allowInTests:{type:`boolean`,default:!0}},additionalProperties:!1}],messages:{noForLoop:`Prefer functional methods (.map, .filter, .forEach, .reduce) over for loops`,noForInLoop:`Prefer Object.keys().forEach() or functional methods over for..in loops`,noForOfLoop:`Prefer .forEach() or .map() over for..of loops`,noAsyncLoop:`This loop awaits, which .forEach()/.map() cannot do. For sequential effects use IO.forEach(items, f) (runs in order, stops at the first failure); for independent ones, IO.all`,noWhileLoop:`Prefer functional iteration or recursion over while loops`,noDoWhileLoop:`Prefer functional iteration or recursion over do..while loops`,suggestForEach:`Replace with {{iterable}}.forEach(...)`,suggestObjectKeys:`Replace with Object.keys({{object}}).forEach(...)`}},create(n){let r=n.options[0]||{},i=r.allowForIndexAccess||!1,a=r.allowWhileLoops||!1,o=r.allowInTests!==!1;function s(){let e=n.filename;return/\.(test|spec)\.(ts|js|tsx|jsx)$/.test(e)||e.includes(`__tests__`)||e.includes(`/test/`)||e.includes(`/tests/`)}function c(e){if(!e.body||e.body.type!==`BlockStatement`)return!1;let t=n.sourceCode.getText(e.body);return/\[\s*\w+\s*\]/.test(t)&&e.init&&e.init.type===`VariableDeclaration`}function l(e){return!e.body||e.body.type!==`BlockStatement`?!1:e.body.body.length===1}function u(e){let t=e.left;if(!t)return!1;if(t.type===`VariableDeclaration`&&t.declarations[0]){let e=t.declarations[0].id;return e.type===`ObjectPattern`||e.type===`ArrayPattern`}return!1}function d(e){return e.type===`ForOfStatement`&&e.await===!0||t(e.body)}function f(e){let t=n.sourceCode.getText(e.body);return/\b(break|continue)\b/.test(t)}return{ForStatement(t){if(!d(t)&&!(o&&s())&&!(i&&c(t))){if(e(t.body)){n.report({node:t,messageId:`noAsyncLoop`});return}n.report({node:t,messageId:`noForLoop`})}},ForInStatement(t){if(d(t)||o&&s())return;if(e(t.body)){n.report({node:t,messageId:`noAsyncLoop`});return}let r=[];if(l(t)&&!u(t)&&!f(t)){let e=n.sourceCode,i=t.body.body[0];if(i&&i.type===`ExpressionStatement`){let n=e.getText(i),a=e.getText(t.right),o=t.left,s=o.type===`VariableDeclaration`&&o.declarations[0]?e.getText(o.declarations[0].id):e.getText(o);r.push({messageId:`suggestObjectKeys`,data:{object:a},fix(e){return e.replaceText(t,`Object.keys(${a}).forEach((${s}) => {\n ${n}\n})`)}})}}n.report({node:t,messageId:`noForInLoop`,suggest:r.length>0?r:void 0})},ForOfStatement(t){if(d(t)||o&&s())return;if(e(t.body)){n.report({node:t,messageId:`noAsyncLoop`});return}let r=[];if(l(t)&&!u(t)&&!f(t)&&!e(t.right)){let e=n.sourceCode,i=t.body.body[0];if(i&&i.type===`ExpressionStatement`){let n=e.getText(i),a=e.getText(t.right),o=t.left,s=o.type===`VariableDeclaration`&&o.declarations[0]?e.getText(o.declarations[0].id):e.getText(o);n.includes(`.push(`)||r.push({messageId:`suggestForEach`,data:{iterable:a},fix(e){return e.replaceText(t,`${a}.forEach((${s}) => {\n ${n}\n})`)}})}}n.report({node:t,messageId:`noForOfLoop`,suggest:r.length>0?r:void 0})},WhileStatement(e){d(e)||a||o&&s()||n.report({node:e,messageId:`noWhileLoop`})},DoWhileStatement(e){d(e)||a||o&&s()||n.report({node:e,messageId:`noDoWhileLoop`})}}}};export{n as default};
2
2
  //# sourceMappingURL=no-imperative-loops.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"no-imperative-loops.js","names":[],"sources":["../../src/rules/no-imperative-loops.ts"],"sourcesContent":["import type { Rule } from \"eslint\"\n\nimport type { ASTNode } from \"../types/ast\"\n\nconst rule: Rule.RuleModule = {\n meta: {\n type: \"suggestion\",\n hasSuggestions: true,\n docs: {\n description: \"Prefer functional iteration methods over imperative for loops\",\n recommended: true,\n },\n schema: [\n {\n type: \"object\",\n properties: {\n allowForIndexAccess: {\n type: \"boolean\",\n default: false,\n },\n allowWhileLoops: {\n type: \"boolean\",\n default: false,\n },\n allowInTests: {\n type: \"boolean\",\n default: true,\n },\n },\n additionalProperties: false,\n },\n ],\n messages: {\n noForLoop: \"Prefer functional methods (.map, .filter, .forEach, .reduce) over for loops\",\n noForInLoop: \"Prefer Object.keys().forEach() or functional methods over for..in loops\",\n noForOfLoop: \"Prefer .forEach() or .map() over for..of loops\",\n noWhileLoop: \"Prefer functional iteration or recursion over while loops\",\n noDoWhileLoop: \"Prefer functional iteration or recursion over do..while loops\",\n suggestForEach: \"Replace with {{iterable}}.forEach(...)\",\n suggestObjectKeys: \"Replace with Object.keys({{object}}).forEach(...)\",\n },\n },\n\n create(context) {\n const options = context.options[0] || {}\n const allowForIndexAccess = options.allowForIndexAccess || false\n const allowWhileLoops = options.allowWhileLoops || false\n const allowInTests = options.allowInTests !== false\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 needsIndexAccess(node: ASTNode): boolean {\n if (!node.body || node.body.type !== \"BlockStatement\") return false\n\n const sourceCode = context.sourceCode\n const bodyText = sourceCode.getText(node.body)\n\n // Look for array index access patterns like arr[i]\n return /\\[\\s*\\w+\\s*\\]/.test(bodyText) && node.init && node.init.type === \"VariableDeclaration\"\n }\n\n function isSingleStatementBody(node: ASTNode): boolean {\n if (!node.body || node.body.type !== \"BlockStatement\") return false\n return node.body.body.length === 1\n }\n\n function hasDestructuringVariable(node: ASTNode): boolean {\n const left = node.left\n if (!left) return false\n if (left.type === \"VariableDeclaration\" && left.declarations[0]) {\n const id = left.declarations[0].id\n return id.type === \"ObjectPattern\" || id.type === \"ArrayPattern\"\n }\n return false\n }\n\n function bodyContainsBreakOrContinue(node: ASTNode): boolean {\n const sourceCode = context.sourceCode\n const bodyText = sourceCode.getText(node.body)\n return /\\b(break|continue)\\b/.test(bodyText)\n }\n\n return {\n ForStatement(node: ASTNode) {\n if (allowInTests && isInTestFile()) return\n\n // Allow traditional for loops if they need index access and option is set\n if (allowForIndexAccess && needsIndexAccess(node)) return\n\n context.report({\n node,\n messageId: \"noForLoop\",\n })\n },\n\n ForInStatement(node: ASTNode) {\n if (allowInTests && isInTestFile()) return\n\n const suggest: Rule.SuggestionReportDescriptor[] = []\n\n if (isSingleStatementBody(node) && !hasDestructuringVariable(node) && !bodyContainsBreakOrContinue(node)) {\n const sourceCode = context.sourceCode\n const bodyStmt = node.body.body[0]\n\n if (bodyStmt && bodyStmt.type === \"ExpressionStatement\") {\n const stmtText = sourceCode.getText(bodyStmt)\n const objText = sourceCode.getText(node.right)\n\n const left = node.left\n const keyVar =\n left.type === \"VariableDeclaration\" && left.declarations[0]\n ? sourceCode.getText(left.declarations[0].id)\n : sourceCode.getText(left)\n\n suggest.push({\n messageId: \"suggestObjectKeys\",\n data: { object: objText },\n fix(fixer) {\n return fixer.replaceText(node, `Object.keys(${objText}).forEach((${keyVar}) => {\\n ${stmtText}\\n})`)\n },\n })\n }\n }\n\n context.report({\n node,\n messageId: \"noForInLoop\",\n suggest: suggest.length > 0 ? suggest : undefined,\n })\n },\n\n ForOfStatement(node: ASTNode) {\n if (allowInTests && isInTestFile()) return\n\n const suggest: Rule.SuggestionReportDescriptor[] = []\n\n if (isSingleStatementBody(node) && !hasDestructuringVariable(node) && !bodyContainsBreakOrContinue(node)) {\n const sourceCode = context.sourceCode\n const bodyStmt = node.body.body[0]\n\n if (bodyStmt && bodyStmt.type === \"ExpressionStatement\") {\n const stmtText = sourceCode.getText(bodyStmt)\n const iterableText = sourceCode.getText(node.right)\n\n const varDecl = node.left\n const varName =\n varDecl.type === \"VariableDeclaration\" && varDecl.declarations[0]\n ? sourceCode.getText(varDecl.declarations[0].id)\n : sourceCode.getText(varDecl)\n\n if (!stmtText.includes(\".push(\")) {\n suggest.push({\n messageId: \"suggestForEach\",\n data: { iterable: iterableText },\n fix(fixer) {\n return fixer.replaceText(node, `${iterableText}.forEach((${varName}) => {\\n ${stmtText}\\n})`)\n },\n })\n }\n }\n }\n\n context.report({\n node,\n messageId: \"noForOfLoop\",\n suggest: suggest.length > 0 ? suggest : undefined,\n })\n },\n\n WhileStatement(node: ASTNode) {\n if (allowWhileLoops) return\n if (allowInTests && isInTestFile()) return\n\n context.report({\n node,\n messageId: \"noWhileLoop\",\n })\n },\n\n DoWhileStatement(node: ASTNode) {\n if (allowWhileLoops) return\n if (allowInTests && isInTestFile()) return\n\n context.report({\n node,\n messageId: \"noDoWhileLoop\",\n })\n },\n }\n },\n}\n\nexport default rule\n"],"mappings":"AAIA,MAAM,EAAwB,CAC5B,KAAM,CACJ,KAAM,aACN,eAAgB,GAChB,KAAM,CACJ,YAAa,gEACb,YAAa,EACf,EACA,OAAQ,CACN,CACE,KAAM,SACN,WAAY,CACV,oBAAqB,CACnB,KAAM,UACN,QAAS,EACX,EACA,gBAAiB,CACf,KAAM,UACN,QAAS,EACX,EACA,aAAc,CACZ,KAAM,UACN,QAAS,EACX,CACF,EACA,qBAAsB,EACxB,CACF,EACA,SAAU,CACR,UAAW,8EACX,YAAa,0EACb,YAAa,iDACb,YAAa,4DACb,cAAe,gEACf,eAAgB,yCAChB,kBAAmB,mDACrB,CACF,EAEA,OAAO,EAAS,CACd,IAAM,EAAU,EAAQ,QAAQ,IAAM,CAAC,EACjC,EAAsB,EAAQ,qBAAuB,GACrD,EAAkB,EAAQ,iBAAmB,GAC7C,EAAe,EAAQ,eAAiB,GAE9C,SAAS,GAAe,CACtB,IAAM,EAAW,EAAQ,SACzB,MACE,kCAAkC,KAAK,CAAQ,GAC/C,EAAS,SAAS,WAAW,GAC7B,EAAS,SAAS,QAAQ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b,CAAC,CACH,EAEA,iBAAiB,EAAe,CAC1B,GACA,GAAgB,EAAa,GAEjC,EAAQ,OAAO,CACb,OACA,UAAW,eACb,CAAC,CACH,CACF,CACF,CACF"}
1
+ {"version":3,"file":"no-imperative-loops.js","names":["rule","options","context","allowForIndexAccess","allowWhileLoops","allowInTests","isInTestFile","filename","needsIndexAccess","node","bodyText","isSingleStatementBody","hasDestructuringVariable","left","id","hasNoFunctionalEquivalent","containsYield","bodyContainsBreakOrContinue","containsAwait","suggest","sourceCode","bodyStmt","stmtText","objText","keyVar","fixer","iterableText","varDecl","varName"],"sources":["../../src/rules/no-imperative-loops.ts"],"sourcesContent":["import type { Rule } from \"eslint\"\n\nimport type { ASTNode } from \"../types/ast\"\nimport { containsAwait, containsYield } from \"../utils/async-detection\"\n\nconst rule: Rule.RuleModule = {\n meta: {\n type: \"suggestion\",\n hasSuggestions: true,\n docs: {\n description: \"Prefer functional iteration methods over imperative for loops\",\n recommended: true,\n },\n schema: [\n {\n type: \"object\",\n properties: {\n allowForIndexAccess: {\n type: \"boolean\",\n default: false,\n },\n allowWhileLoops: {\n type: \"boolean\",\n default: false,\n },\n allowInTests: {\n type: \"boolean\",\n default: true,\n },\n },\n additionalProperties: false,\n },\n ],\n messages: {\n noForLoop: \"Prefer functional methods (.map, .filter, .forEach, .reduce) over for loops\",\n noForInLoop: \"Prefer Object.keys().forEach() or functional methods over for..in loops\",\n noForOfLoop: \"Prefer .forEach() or .map() over for..of loops\",\n noAsyncLoop:\n \"This loop awaits, which .forEach()/.map() cannot do. For sequential effects use IO.forEach(items, f) (runs in order, stops at the first failure); for independent ones, IO.all\",\n noWhileLoop: \"Prefer functional iteration or recursion over while loops\",\n noDoWhileLoop: \"Prefer functional iteration or recursion over do..while loops\",\n suggestForEach: \"Replace with {{iterable}}.forEach(...)\",\n suggestObjectKeys: \"Replace with Object.keys({{object}}).forEach(...)\",\n },\n },\n\n create(context) {\n const options = context.options[0] || {}\n const allowForIndexAccess = options.allowForIndexAccess || false\n const allowWhileLoops = options.allowWhileLoops || false\n const allowInTests = options.allowInTests !== false\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 needsIndexAccess(node: ASTNode): boolean {\n if (!node.body || node.body.type !== \"BlockStatement\") return false\n\n const sourceCode = context.sourceCode\n const bodyText = sourceCode.getText(node.body)\n\n // Look for array index access patterns like arr[i]\n return /\\[\\s*\\w+\\s*\\]/.test(bodyText) && node.init && node.init.type === \"VariableDeclaration\"\n }\n\n function isSingleStatementBody(node: ASTNode): boolean {\n if (!node.body || node.body.type !== \"BlockStatement\") return false\n return node.body.body.length === 1\n }\n\n function hasDestructuringVariable(node: ASTNode): boolean {\n const left = node.left\n if (!left) return false\n if (left.type === \"VariableDeclaration\" && left.declarations[0]) {\n const id = left.declarations[0].id\n return id.type === \"ObjectPattern\" || id.type === \"ArrayPattern\"\n }\n return false\n }\n\n /**\n * Loops with no functional equivalent (#324): `for await` consumes a stream, and collecting it first\n * would defeat the streaming; a loop that yields is a generator's body, and a callback cannot yield.\n */\n function hasNoFunctionalEquivalent(node: ASTNode): boolean {\n return (node.type === \"ForOfStatement\" && node.await === true) || containsYield(node.body)\n }\n\n function bodyContainsBreakOrContinue(node: ASTNode): boolean {\n const sourceCode = context.sourceCode\n const bodyText = sourceCode.getText(node.body)\n return /\\b(break|continue)\\b/.test(bodyText)\n }\n\n return {\n ForStatement(node: ASTNode) {\n if (hasNoFunctionalEquivalent(node)) return\n if (allowInTests && isInTestFile()) return\n\n // Allow traditional for loops if they need index access and option is set\n if (allowForIndexAccess && needsIndexAccess(node)) return\n\n if (containsAwait(node.body)) {\n context.report({ node, messageId: \"noAsyncLoop\" })\n return\n }\n\n context.report({\n node,\n messageId: \"noForLoop\",\n })\n },\n\n ForInStatement(node: ASTNode) {\n if (hasNoFunctionalEquivalent(node)) return\n if (allowInTests && isInTestFile()) return\n\n if (containsAwait(node.body)) {\n context.report({ node, messageId: \"noAsyncLoop\" })\n return\n }\n\n const suggest: Rule.SuggestionReportDescriptor[] = []\n\n if (isSingleStatementBody(node) && !hasDestructuringVariable(node) && !bodyContainsBreakOrContinue(node)) {\n const sourceCode = context.sourceCode\n const bodyStmt = node.body.body[0]\n\n if (bodyStmt && bodyStmt.type === \"ExpressionStatement\") {\n const stmtText = sourceCode.getText(bodyStmt)\n const objText = sourceCode.getText(node.right)\n\n const left = node.left\n const keyVar =\n left.type === \"VariableDeclaration\" && left.declarations[0]\n ? sourceCode.getText(left.declarations[0].id)\n : sourceCode.getText(left)\n\n suggest.push({\n messageId: \"suggestObjectKeys\",\n data: { object: objText },\n fix(fixer) {\n return fixer.replaceText(node, `Object.keys(${objText}).forEach((${keyVar}) => {\\n ${stmtText}\\n})`)\n },\n })\n }\n }\n\n context.report({\n node,\n messageId: \"noForInLoop\",\n suggest: suggest.length > 0 ? suggest : undefined,\n })\n },\n\n ForOfStatement(node: ASTNode) {\n if (hasNoFunctionalEquivalent(node)) return\n if (allowInTests && isInTestFile()) return\n\n // A .forEach suggestion here would move `await` into a non-async callback — a syntax error —\n // so an awaiting body gets the IO.forEach pointer and no suggestion.\n if (containsAwait(node.body)) {\n context.report({ node, messageId: \"noAsyncLoop\" })\n return\n }\n\n const suggest: Rule.SuggestionReportDescriptor[] = []\n\n // `for (x of await xs())` → `await xs().forEach(...)` would bind `await` to the forEach call, so an\n // awaited iterable gets no suggestion.\n if (\n isSingleStatementBody(node) &&\n !hasDestructuringVariable(node) &&\n !bodyContainsBreakOrContinue(node) &&\n !containsAwait(node.right)\n ) {\n const sourceCode = context.sourceCode\n const bodyStmt = node.body.body[0]\n\n if (bodyStmt && bodyStmt.type === \"ExpressionStatement\") {\n const stmtText = sourceCode.getText(bodyStmt)\n const iterableText = sourceCode.getText(node.right)\n\n const varDecl = node.left\n const varName =\n varDecl.type === \"VariableDeclaration\" && varDecl.declarations[0]\n ? sourceCode.getText(varDecl.declarations[0].id)\n : sourceCode.getText(varDecl)\n\n if (!stmtText.includes(\".push(\")) {\n suggest.push({\n messageId: \"suggestForEach\",\n data: { iterable: iterableText },\n fix(fixer) {\n return fixer.replaceText(node, `${iterableText}.forEach((${varName}) => {\\n ${stmtText}\\n})`)\n },\n })\n }\n }\n }\n\n context.report({\n node,\n messageId: \"noForOfLoop\",\n suggest: suggest.length > 0 ? suggest : undefined,\n })\n },\n\n WhileStatement(node: ASTNode) {\n if (hasNoFunctionalEquivalent(node)) return\n if (allowWhileLoops) return\n if (allowInTests && isInTestFile()) return\n\n context.report({\n node,\n messageId: \"noWhileLoop\",\n })\n },\n\n DoWhileStatement(node: ASTNode) {\n if (hasNoFunctionalEquivalent(node)) return\n if (allowWhileLoops) return\n if (allowInTests && isInTestFile()) return\n\n context.report({\n node,\n messageId: \"noDoWhileLoop\",\n })\n },\n }\n },\n}\n\nexport default rule\n"],"mappings":"+EAKA,MAAMA,EAAwB,CAC5B,KAAM,CACJ,KAAM,aACN,eAAgB,GAChB,KAAM,CACJ,YAAa,gEACb,YAAa,EACf,EACA,OAAQ,CACN,CACE,KAAM,SACN,WAAY,CACV,oBAAqB,CACnB,KAAM,UACN,QAAS,EACX,EACA,gBAAiB,CACf,KAAM,UACN,QAAS,EACX,EACA,aAAc,CACZ,KAAM,UACN,QAAS,EACX,CACF,EACA,qBAAsB,EACxB,CACF,EACA,SAAU,CACR,UAAW,8EACX,YAAa,0EACb,YAAa,iDACb,YACE,iLACF,YAAa,4DACb,cAAe,gEACf,eAAgB,yCAChB,kBAAmB,mDACrB,CACF,EAEA,OAAO,EAAS,CACd,IAAMC,EAAUC,EAAQ,QAAQ,IAAM,CAAC,EACjCC,EAAsBF,EAAQ,qBAAuB,GACrDG,EAAkBH,EAAQ,iBAAmB,GAC7CI,EAAeJ,EAAQ,eAAiB,GAE9C,SAASK,GAAe,CACtB,IAAMC,EAAWL,EAAQ,SACzB,MACE,kC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AQ,WACrBmB,EAAWZ,EAAK,KAAK,KAAK,GAEhC,GAAIY,GAAYA,EAAS,OAAS,sBAAuB,CACvD,IAAMC,EAAWF,EAAW,QAAQC,CAAQ,EACtCK,EAAeN,EAAW,QAAQX,EAAK,KAAK,EAE5CkB,EAAUlB,EAAK,KACfmB,EACJD,EAAQ,OAAS,uBAAyBA,EAAQ,aAAa,GAC3DP,EAAW,QAAQO,EAAQ,aAAa,EAAE,CAAC,EAAE,EAC7CP,EAAW,QAAQO,CAAO,EAE3BL,EAAS,SAAS,QAAQ,GAC7BH,EAAQ,KAAK,CACX,UAAW,iBACX,KAAM,CAAE,SAAUO,CAAa,EAC/B,IAAI,EAAO,CACT,OAAOD,EAAM,YAAYhB,EAAM,GAAGiB,EAAa,YAAYE,EAAQ,YAAYN,EAAS,KAAK,CAC/F,CACF,CAAC,CAEL,CACF,CAEApB,EAAQ,OAAO,CACb,OACA,UAAW,cACX,QAASiB,EAAQ,OAAS,EAAIA,EAAU,IAAA,EAC1C,CAAC,CACH,EAEA,eAAe,EAAe,CACxBJ,EAA0BN,CAAI,GAC9BL,GACAC,GAAgBC,EAAa,GAEjCJ,EAAQ,OAAO,CACb,OACA,UAAW,aACb,CAAC,CACH,EAEA,iBAAiB,EAAe,CAC1Ba,EAA0BN,CAAI,GAC9BL,GACAC,GAAgBC,EAAa,GAEjCJ,EAAQ,OAAO,CACb,OACA,UAAW,eACb,CAAC,CACH,CACF,CACF,CACF"}
@@ -1 +1 @@
1
- {"version":3,"file":"no-let.js","names":[],"sources":["../../src/rules/no-let.ts"],"sourcesContent":["import type { Rule } from \"eslint\"\n\nimport type { ASTNode } from \"../types/ast\"\n\nconst rule: Rule.RuleModule = {\n meta: {\n type: \"suggestion\",\n fixable: \"code\",\n hasSuggestions: true,\n docs: {\n description: \"Prefer const over let — use immutable bindings\",\n recommended: true,\n },\n schema: [\n {\n type: \"object\",\n properties: {\n allowInTests: {\n type: \"boolean\",\n default: true,\n },\n },\n additionalProperties: false,\n },\n ],\n messages: {\n noLet: \"Prefer const over let — use immutable bindings\",\n suggestConst: \"Replace let with const\",\n },\n },\n\n create(context) {\n const options = context.options[0] || {}\n const allowInTests = options.allowInTests !== false\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 return {\n VariableDeclaration(node: ASTNode) {\n if (node.kind !== \"let\") return\n if (allowInTests && isInTestFile()) return\n\n const declaredVars = context.sourceCode.getDeclaredVariables(node)\n const hasReassignment = declaredVars.some((variable: ASTNode) =>\n variable.references.some((ref: ASTNode) => ref.isWrite() && ref.identifier !== variable.defs[0]?.name),\n )\n\n if (!hasReassignment) {\n // Safe to autofix — no reassignment detected\n context.report({\n node,\n messageId: \"noLet\",\n fix(fixer: Rule.RuleFixer) {\n const sourceCode = context.sourceCode\n const firstToken = sourceCode.getFirstToken(node)\n if (firstToken && firstToken.value === \"let\") {\n return fixer.replaceText(firstToken, \"const\")\n }\n return null\n },\n })\n } else {\n // Reassignment found — warn only, with suggestion\n context.report({\n node,\n messageId: \"noLet\",\n suggest: [\n {\n messageId: \"suggestConst\",\n fix(fixer: Rule.RuleFixer) {\n const sourceCode = context.sourceCode\n const firstToken = sourceCode.getFirstToken(node)\n if (firstToken && firstToken.value === \"let\") {\n return fixer.replaceText(firstToken, \"const\")\n }\n return null\n },\n },\n ],\n })\n }\n },\n }\n },\n}\n\nexport default rule\n"],"mappings":"AAIA,MAAM,EAAwB,CAC5B,KAAM,CACJ,KAAM,aACN,QAAS,OACT,eAAgB,GAChB,KAAM,CACJ,YAAa,iDACb,YAAa,EACf,EACA,OAAQ,CACN,CACE,KAAM,SACN,WAAY,CACV,aAAc,CACZ,KAAM,UACN,QAAS,EACX,CACF,EACA,qBAAsB,EACxB,CACF,EACA,SAAU,CACR,MAAO,iDACP,aAAc,wBAChB,CACF,EAEA,OAAO,EAAS,CAEd,IAAM,GADU,EAAQ,QAAQ,IAAM,CAAC,EAAA,CACV,eAAiB,GAE9C,SAAS,GAAe,CACtB,IAAM,EAAW,EAAQ,SACzB,MACE,kCAAkC,KAAK,CAAQ,GAC/C,EAAS,SAAS,WAAW,GAC7B,EAAS,SAAS,QAAQ,GAC1B,EAAS,SAAS,SAAS,CAE/B,CAEA,MAAO,CACL,oBAAoB,EAAe,CAC7B,EAAK,OAAS,QACd,GAAgB,EAAa,IAEZ,EAAQ,WAAW,qBAAqB,CAC1B,CAAC,CAAC,KAAM,GACzC,EAAS,WAAW,KAAM,GAAiB,EAAI,QAAQ,GAAK,EAAI,aAAe,EAAS,KAAK,EAAE,EAAE,IAAI,CAGpF,EAgBjB,EAAQ,OAAO,CACb,OACA,UAAW,QACX,QAAS,CACP,CACE,UAAW,eACX,IAAI,EAAuB,CAEzB,IAAM,EADa,EAAQ,WACG,cAAc,CAAI,EAIhD,OAHI,GAAc,EAAW,QAAU,MAC9B,EAAM,YAAY,EAAY,OAAO,EAEvC,IACT,CACF,CACF,CACF,CAAC,EA9BD,EAAQ,OAAO,CACb,OACA,UAAW,QACX,IAAI,EAAuB,CAEzB,IAAM,EADa,EAAQ,WACG,cAAc,CAAI,EAIhD,OAHI,GAAc,EAAW,QAAU,MAC9B,EAAM,YAAY,EAAY,OAAO,EAEvC,IACT,CACF,CAAC,GAqBL,CACF,CACF,CACF"}
1
+ {"version":3,"file":"no-let.js","names":["rule","allowInTests","context","isInTestFile","filename","node","variable","ref","firstToken","fixer"],"sources":["../../src/rules/no-let.ts"],"sourcesContent":["import type { Rule } from \"eslint\"\n\nimport type { ASTNode } from \"../types/ast\"\n\nconst rule: Rule.RuleModule = {\n meta: {\n type: \"suggestion\",\n fixable: \"code\",\n hasSuggestions: true,\n docs: {\n description: \"Prefer const over let — use immutable bindings\",\n recommended: true,\n },\n schema: [\n {\n type: \"object\",\n properties: {\n allowInTests: {\n type: \"boolean\",\n default: true,\n },\n },\n additionalProperties: false,\n },\n ],\n messages: {\n noLet: \"Prefer const over let — use immutable bindings\",\n suggestConst: \"Replace let with const\",\n },\n },\n\n create(context) {\n const options = context.options[0] || {}\n const allowInTests = options.allowInTests !== false\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 return {\n VariableDeclaration(node: ASTNode) {\n if (node.kind !== \"let\") return\n if (allowInTests && isInTestFile()) return\n\n const declaredVars = context.sourceCode.getDeclaredVariables(node)\n const hasReassignment = declaredVars.some((variable: ASTNode) =>\n variable.references.some((ref: ASTNode) => ref.isWrite() && ref.identifier !== variable.defs[0]?.name),\n )\n\n if (!hasReassignment) {\n // Safe to autofix — no reassignment detected\n context.report({\n node,\n messageId: \"noLet\",\n fix(fixer: Rule.RuleFixer) {\n const sourceCode = context.sourceCode\n const firstToken = sourceCode.getFirstToken(node)\n if (firstToken && firstToken.value === \"let\") {\n return fixer.replaceText(firstToken, \"const\")\n }\n return null\n },\n })\n } else {\n // Reassignment found — warn only, with suggestion\n context.report({\n node,\n messageId: \"noLet\",\n suggest: [\n {\n messageId: \"suggestConst\",\n fix(fixer: Rule.RuleFixer) {\n const sourceCode = context.sourceCode\n const firstToken = sourceCode.getFirstToken(node)\n if (firstToken && firstToken.value === \"let\") {\n return fixer.replaceText(firstToken, \"const\")\n }\n return null\n },\n },\n ],\n })\n }\n },\n }\n },\n}\n\nexport default rule\n"],"mappings":"AAIA,MAAMA,EAAwB,CAC5B,KAAM,CACJ,KAAM,aACN,QAAS,OACT,eAAgB,GAChB,KAAM,CACJ,YAAa,iDACb,YAAa,EACf,EACA,OAAQ,CACN,CACE,KAAM,SACN,WAAY,CACV,aAAc,CACZ,KAAM,UACN,QAAS,EACX,CACF,EACA,qBAAsB,EACxB,CACF,EACA,SAAU,CACR,MAAO,iDACP,aAAc,wBAChB,CACF,EAEA,OAAO,EAAS,CAEd,IAAMC,GADUC,EAAQ,QAAQ,IAAM,CAAC,EAAA,CACV,eAAiB,GAE9C,SAASC,GAAe,CACtB,IAAMC,EAAWF,EAAQ,SACzB,MACE,kCAAkC,KAAKE,CAAQ,GAC/CA,EAAS,SAAS,WAAW,GAC7BA,EAAS,SAAS,QAAQ,GAC1BA,EAAS,SAAS,SAAS,CAE/B,CAEA,MAAO,CACL,oBAAoB,EAAe,CAC7BC,EAAK,OAAS,QACdJ,GAAgBE,EAAa,IAEZD,EAAQ,WAAW,qBAAqBG,CAC1B,CAAC,CAAC,KAAM,GACzCC,EAAS,WAAW,KAAM,GAAiBC,EAAI,QAAQ,GAAKA,EAAI,aAAeD,EAAS,KAAK,EAAE,EAAE,IAAI,CAGpF,EAgBjBJ,EAAQ,OAAO,CACb,OACA,UAAW,QACX,QAAS,CACP,CACE,UAAW,eACX,IAAI,EAAuB,CAEzB,IAAMM,EADaN,EAAQ,WACG,cAAcG,CAAI,EAIhD,OAHIG,GAAcA,EAAW,QAAU,MAC9BC,EAAM,YAAYD,EAAY,OAAO,EAEvC,IACT,CACF,CACF,CACF,CAAC,EA9BDN,EAAQ,OAAO,CACb,OACA,UAAW,QACX,IAAI,EAAuB,CAEzB,IAAMM,EADaN,EAAQ,WACG,cAAcG,CAAI,EAIhD,OAHIG,GAAcA,EAAW,QAAU,MAC9BC,EAAM,YAAYD,EAAY,OAAO,EAEvC,IACT,CACF,CAAC,GAqBL,CACF,CACF,CACF"}
@@ -1,4 +1,4 @@
1
- import{getFunctypeImports as e,isChainedMethodCall as t}from"../utils/functype-detection.js";const n=new Set([`Option`,`Either`,`Try`,`Task`]),r=new Set([`parent`,`loc`,`range`]),i=(e,t)=>new Set([...e,...t]);function a(e){if(e.type!==`CallExpression`)return new Set;let t=e.callee;return t?.type===`Identifier`&&n.has(t.name)?new Set([t.name]):t?.type===`MemberExpression`&&t.object?.type===`Identifier`&&n.has(t.object.name)?new Set([t.object.name]):new Set}function o(e){return Object.entries(e).filter(([e])=>!r.has(e)).flatMap(([,e])=>Array.isArray(e)?e:[e]).filter(e=>typeof e==`object`&&!!e)}function s(e){if(!e||typeof e!=`object`)return new Set;let t=e;return o(t).reduce((e,t)=>i(e,s(t)),a(t))}const c=new Set([`flatMap`,`map`,`filter`,`fold`]),l=new Set([`flatMap`,`map`,`filter`]);function u(e){if(e.callee.type!==`MemberExpression`||e.callee.object.type!==`CallExpression`)return 1;let t=e.callee.property,n=e.callee.object;return(t.type===`Identifier`&&c.has(t.name)?1:0)+u(n)}function d(e){if(e.callee?.type!==`MemberExpression`||e.callee.object?.type!==`CallExpression`)return 0;let t=e.callee.property,n=e.callee.object;return(t.type===`Identifier`&&l.has(t.name)?1:0)+d(n)}function f(e){if(e.callee?.type!==`MemberExpression`)return!1;let t=e.callee.property;return t.type!==`Identifier`||!l.has(t.name)?!1:d(e)>=1}function p(e){if(e.type!==`LogicalExpression`||e.operator!==`&&`)return 0;let t=e.right;return+(t.type===`MemberExpression`||t.type===`LogicalExpression`&&t.operator===`&&`)+p(e.left)}const m={meta:{type:`suggestion`,docs:{description:`Prefer Do notation for complex monadic compositions and nested operations`,recommended:!0},fixable:`code`,messages:{preferDoForNestedChecks:`Prefer Do notation for nested null/undefined checks instead of logical AND chains`,preferDoForChainedMethods:`Prefer Do notation for complex flatMap chains ({{count}} levels deep)`,preferDoForMixedMonads:`Consider Do notation when mixing Option, Either, and Try operations`,preferDoAsyncForChainedTasks:`Prefer DoAsync notation for chained async operations`},schema:[{type:`object`,properties:{minChainDepth:{type:`integer`,minimum:2,default:3},detectMixedMonads:{type:`boolean`,default:!0}},additionalProperties:!1}]},create(n){let r=n.options[0]||{},i=r.minChainDepth||3,a=r.detectMixedMonads!==!1,o=e(n),c=o.functions.has(`Do`)||o.functions.has(`DoAsync`);function l(e){e.operator===`&&`&&p(e)>=2&&d(e)&&n.report({node:e,messageId:`preferDoForNestedChecks`,fix:c?t=>h(t,e):void 0})}function d(e){let t=n.sourceCode.getText(e).match(/\w+(\.\w+){2,}/g);return t!==null&&t.length>0}function m(e){if(!t(e,`flatMap`))return;let r=u(e);r>=i&&n.report({node:e,messageId:`preferDoForChainedMethods`,data:{count:r.toString()},fix:c?t=>g(t,e):void 0})}function h(e,t){let r=n.sourceCode.getText(t),i=r.match(/(\w+)(\.\w+)+/);if(i){let n=i[1],r=`Do(function* () {
1
+ import{getFunctypeImports as e,isChainedMethodCall as t}from"../utils/functype-detection.js";const n=/* @__PURE__ */ new Set([`Option`,`Either`,`Try`,`Task`]),r=/* @__PURE__ */ new Set([`parent`,`loc`,`range`]),i=(e,t)=>/* @__PURE__ */ new Set([...e,...t]);function a(e){if(e.type!==`CallExpression`)return/* @__PURE__ */ new Set;let t=e.callee;return t?.type===`Identifier`&&n.has(t.name)?/* @__PURE__ */ new Set([t.name]):t?.type===`MemberExpression`&&t.object?.type===`Identifier`&&n.has(t.object.name)?/* @__PURE__ */ new Set([t.object.name]):/* @__PURE__ */ new Set}function o(e){return Object.entries(e).filter(([e])=>!r.has(e)).flatMap(([,e])=>Array.isArray(e)?e:[e]).filter(e=>typeof e==`object`&&!!e)}function s(e){if(!e||typeof e!=`object`)return/* @__PURE__ */ new Set;let t=e;return o(t).reduce((e,t)=>i(e,s(t)),a(t))}const c=/* @__PURE__ */ new Set([`flatMap`,`map`,`filter`,`fold`]),l=/* @__PURE__ */ new Set([`flatMap`,`map`,`filter`]);function u(e){if(e.callee.type!==`MemberExpression`||e.callee.object.type!==`CallExpression`)return 1;let t=e.callee.property,n=e.callee.object;return(t.type===`Identifier`&&c.has(t.name)?1:0)+u(n)}function d(e){if(e.callee?.type!==`MemberExpression`||e.callee.object?.type!==`CallExpression`)return 0;let t=e.callee.property,n=e.callee.object;return(t.type===`Identifier`&&l.has(t.name)?1:0)+d(n)}function f(e){if(e.callee?.type!==`MemberExpression`)return!1;let t=e.callee.property;return t.type!==`Identifier`||!l.has(t.name)?!1:d(e)>=1}function p(e){if(e.type!==`LogicalExpression`||e.operator!==`&&`)return 0;let t=e.right;return+(t.type===`MemberExpression`||t.type===`LogicalExpression`&&t.operator===`&&`)+p(e.left)}const m={meta:{type:`suggestion`,docs:{description:`Prefer Do notation for complex monadic compositions and nested operations`,recommended:!0},fixable:`code`,messages:{preferDoForNestedChecks:`Prefer Do notation for nested null/undefined checks instead of logical AND chains`,preferDoForChainedMethods:`Prefer Do notation for complex flatMap chains ({{count}} levels deep)`,preferDoForMixedMonads:`Consider Do notation when mixing Option, Either, and Try operations`,preferDoAsyncForChainedTasks:`Prefer DoAsync notation for chained async operations`},schema:[{type:`object`,properties:{minChainDepth:{type:`integer`,minimum:2,default:3},detectMixedMonads:{type:`boolean`,default:!0}},additionalProperties:!1}]},create(n){let r=n.options[0]||{},i=r.minChainDepth||3,a=r.detectMixedMonads!==!1,o=e(n),c=o.functions.has(`Do`)||o.functions.has(`DoAsync`);function l(e){e.operator===`&&`&&p(e)>=2&&d(e)&&n.report({node:e,messageId:`preferDoForNestedChecks`,fix:c?t=>h(t,e):void 0})}function d(e){let t=n.sourceCode.getText(e).match(/\w+(\.\w+){2,}/g);return t!==null&&t.length>0}function m(e){if(!t(e,`flatMap`))return;let r=u(e);r>=i&&n.report({node:e,messageId:`preferDoForChainedMethods`,data:{count:r.toString()},fix:c?t=>g(t,e):void 0})}function h(e,t){let r=n.sourceCode.getText(t),i=r.match(/(\w+)(\.\w+)+/);if(i){let n=i[1],r=`Do(function* () {
2
2
  const obj = yield* $(Option(${n}))
3
3
  return yield* $(Option(obj${i[0].substring(n.length)}))
4
4
  })`;return e.replaceText(t,r)}return e.replaceText(t,`/* TODO: Convert to Do notation */ ${r}`)}function g(e,t){let r=n.sourceCode.getText(t);return e.replaceText(t,`/* TODO: Consider Do notation for complex chains */ ${r}`)}function _(e){a&&f(e)&&s(e).size>=2&&n.report({node:e,messageId:`preferDoForMixedMonads`})}return{LogicalExpression(e){l(e)},CallExpression(e){m(e),_(e)}}}};export{m as default};
@@ -1 +1 @@
1
- {"version":3,"file":"prefer-do-notation.js","names":[],"sources":["../../src/rules/prefer-do-notation.ts"],"sourcesContent":["import type { Rule } from \"eslint\"\n\nimport type { ASTNode } from \"../types/ast\"\nimport { getFunctypeImports, isChainedMethodCall } from \"../utils/functype-detection\"\n\nconst MONAD_TYPES: ReadonlySet<string> = new Set([\"Option\", \"Either\", \"Try\", \"Task\"])\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\nconst union = <T>(a: ReadonlySet<T>, b: ReadonlySet<T>): ReadonlySet<T> => new Set([...a, ...b])\n\n/**\n * Set of monad names that *this single AST node* names as a constructor call.\n * Does not look at children. Returns empty set for any non-monad-constructor node.\n */\nfunction monadAt(node: ASTNode): ReadonlySet<string> {\n if (node.type !== \"CallExpression\") return new Set()\n const callee = node.callee\n // Bare constructor: Option(...), Try(...), Either(...), Task(...)\n if (callee?.type === \"Identifier\" && MONAD_TYPES.has(callee.name)) {\n return new Set([callee.name])\n }\n // Companion call: Option.none(), Either.right(x), Try.success(v)\n if (\n callee?.type === \"MemberExpression\" &&\n callee.object?.type === \"Identifier\" &&\n MONAD_TYPES.has(callee.object.name)\n ) {\n return new Set([callee.object.name])\n }\n return new Set()\n}\n\n/**\n * AST children of `node` worth recursing into. Drops back-edges and source\n * metadata; flattens array-valued keys (e.g. `arguments`); filters non-object\n * leaves (literals, raw strings, numbers).\n */\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/**\n * Pure recursion: the set of all monad names reachable from `node` (including\n * `node` itself if it is a monad constructor call). No mutation, no\n * accumulator parameter — just a fold over the children's results.\n */\nfunction monadsIn(node: unknown): ReadonlySet<string> {\n if (!node || typeof node !== \"object\") return new Set()\n const ast = node as ASTNode\n return astChildren(ast).reduce<ReadonlySet<string>>((acc, child) => union(acc, monadsIn(child)), monadAt(ast))\n}\n\nconst CHAIN_METHODS: ReadonlySet<string> = new Set([\"flatMap\", \"map\", \"filter\", \"fold\"])\n\n/**\n * Methods that *compose* monadic operations (stay in the monad and feed the\n * next step). Distinct from terminal handlers (`fold`, `match`, `getOrElse`)\n * which *exit* the monad — those are conversions, not composition, and Do\n * notation doesn't apply to them.\n */\nconst COMPOSITION_METHODS: ReadonlySet<string> = new Set([\"flatMap\", \"map\", \"filter\"])\n\n/**\n * Length of the chain of `.flatMap()/.map()/.filter()/.fold()` calls walking\n * left from `node`. Returns 1 for a single call, N for N stacked calls. Pure\n * tail recursion — no mutable counter, no `while` loop.\n */\nfunction getChainDepth(node: ASTNode): number {\n if (node.callee.type !== \"MemberExpression\" || node.callee.object.type !== \"CallExpression\") return 1\n const method = node.callee.property\n const next = node.callee.object as ASTNode\n const here = method.type === \"Identifier\" && CHAIN_METHODS.has(method.name) ? 1 : 0\n return here + getChainDepth(next)\n}\n\n/**\n * Number of composition methods (`flatMap`/`map`/`filter`) stacked under\n * `node` via `.callee.object`. 0 if the callee isn't a member expression on\n * another call. Excludes terminal handlers by design.\n */\nfunction compositionChainDepth(node: ASTNode): number {\n if (node.callee?.type !== \"MemberExpression\" || node.callee.object?.type !== \"CallExpression\") return 0\n const method = node.callee.property\n const next = node.callee.object as ASTNode\n const here = method.type === \"Identifier\" && COMPOSITION_METHODS.has(method.name) ? 1 : 0\n return here + compositionChainDepth(next)\n}\n\n/**\n * True when `node`'s outermost call is a composition method AND at least one\n * more composition method appears below it — i.e. this is a real\n * `.flatMap(...).flatMap(...)`-style chain, not a terminal exit like\n * `.fold(...)` or a bare receiver like `option.flatMap(...)`.\n */\nfunction isCompositionChain(node: ASTNode): boolean {\n if (node.callee?.type !== \"MemberExpression\") return false\n const method = node.callee.property\n if (method.type !== \"Identifier\" || !COMPOSITION_METHODS.has(method.name)) return false\n return compositionChainDepth(node) >= 1\n}\n\n/**\n * Depth of a logical-AND chain (`a && b && c && ...`) where each right-hand\n * side is either a MemberExpression or another && chain — the shape that\n * indicates nested property-access guarding rather than arbitrary booleans.\n */\nfunction andChainDepth(node: ASTNode): number {\n if (node.type !== \"LogicalExpression\" || node.operator !== \"&&\") return 0\n const rhs = node.right\n const here = rhs.type === \"MemberExpression\" || (rhs.type === \"LogicalExpression\" && rhs.operator === \"&&\") ? 1 : 0\n return here + andChainDepth(node.left as ASTNode)\n}\n\nconst rule: Rule.RuleModule = {\n meta: {\n type: \"suggestion\",\n docs: {\n description: \"Prefer Do notation for complex monadic compositions and nested operations\",\n recommended: true,\n },\n fixable: \"code\",\n messages: {\n preferDoForNestedChecks: \"Prefer Do notation for nested null/undefined checks instead of logical AND chains\",\n preferDoForChainedMethods: \"Prefer Do notation for complex flatMap chains ({{count}} levels deep)\",\n preferDoForMixedMonads: \"Consider Do notation when mixing Option, Either, and Try operations\",\n preferDoAsyncForChainedTasks: \"Prefer DoAsync notation for chained async operations\",\n },\n schema: [\n {\n type: \"object\",\n properties: {\n minChainDepth: {\n type: \"integer\",\n minimum: 2,\n default: 3,\n },\n detectMixedMonads: {\n type: \"boolean\",\n default: true,\n },\n },\n additionalProperties: false,\n },\n ],\n },\n create(context) {\n const options = context.options[0] || {}\n const minChainDepth = options.minChainDepth || 3\n const detectMixedMonads = options.detectMixedMonads !== false\n\n const functypeImports = getFunctypeImports(context)\n\n // Track if Do notation is already imported\n const hasDoImport = functypeImports.functions.has(\"Do\") || functypeImports.functions.has(\"DoAsync\")\n\n /**\n * Detect nested null/undefined checks like: a && a.b && a.b.c\n */\n function checkNestedNullChecks(node: ASTNode): void {\n if (node.operator !== \"&&\") return\n\n // Check if this looks like nested property access guarding\n if (andChainDepth(node) >= 2 && hasNestedPropertyAccess(node)) {\n context.report({\n node,\n messageId: \"preferDoForNestedChecks\",\n fix: hasDoImport ? (fixer) => fixNestedChecks(fixer, node) : undefined,\n })\n }\n }\n\n /**\n * Check if logical expression contains nested property access patterns\n */\n function hasNestedPropertyAccess(node: ASTNode): boolean {\n // Look for patterns like: obj && obj.prop && obj.prop.nested\n const matches = context.sourceCode.getText(node).match(/\\w+(\\.\\w+){2,}/g)\n return matches !== null && matches.length > 0\n }\n\n /**\n * Detect long flatMap chains\n */\n function checkChainedMethods(node: ASTNode): void {\n if (!isChainedMethodCall(node, \"flatMap\")) return\n\n const chainDepth = getChainDepth(node)\n\n if (chainDepth >= minChainDepth) {\n context.report({\n node,\n messageId: \"preferDoForChainedMethods\",\n data: { count: chainDepth.toString() },\n fix: hasDoImport ? (fixer) => fixChainedMethods(fixer, node) : undefined,\n })\n }\n }\n\n /**\n * Auto-fix for nested null checks\n */\n function fixNestedChecks(fixer: Rule.RuleFixer, node: ASTNode): Rule.Fix {\n const text = context.sourceCode.getText(node)\n\n // Simple transformation for common patterns\n // a && a.b && a.b.c -> Do(function* () { const x = yield* $(Option(a)); const y = yield* $(Option(x.b)); return Option(y.c) })\n const match = text.match(/(\\w+)(\\.\\w+)+/)\n if (match) {\n const baseVar = match[1]\n const chain = match[0]\n\n const doNotation = `Do(function* () {\n const obj = yield* $(Option(${baseVar}))\n return yield* $(Option(obj${chain.substring(baseVar.length)}))\n})`\n\n return fixer.replaceText(node, doNotation)\n }\n\n return fixer.replaceText(node, `/* TODO: Convert to Do notation */ ${text}`)\n }\n\n /**\n * Auto-fix for chained methods (basic)\n */\n function fixChainedMethods(fixer: Rule.RuleFixer, node: ASTNode): Rule.Fix {\n const text = context.sourceCode.getText(node)\n\n // For now, just add a comment suggesting Do notation\n return fixer.replaceText(node, `/* TODO: Consider Do notation for complex chains */ ${text}`)\n }\n\n /**\n * Detect mixed monad usage by walking the AST under `node` and counting\n * *distinct* monad constructor calls — not substring matches.\n *\n * A \"monad constructor call\" is a CallExpression whose callee is either:\n * - a bare identifier matching a known monad type (`Option(...)`, `Try(...)`),\n * or\n * - a member expression whose object is a known monad type\n * (`Option.none()`, `Either.right(...)`, `Try.success(...)`).\n *\n * Method calls like `.toEither(...)`, `.toOption()`, `.toTry()` are NOT\n * constructor calls — they're the idiomatic *conversion* API for crossing\n * monad boundaries. The old substring-based check fired on these because\n * `.toEither` contains \"Either\" as a substring; the AST check correctly\n * sees them as method calls, not new monad constructions.\n *\n * Implementation is pure recursion over the AST: `monadAt` reports what\n * a single node names; `monadsIn` returns the union of `monadAt(self)`\n * with the results from each child. No mutable accumulator, no for-loops\n * driving state changes.\n */\n function checkMixedMonads(node: ASTNode): void {\n if (!detectMixedMonads) return\n // Only flag genuine composition chains (.flatMap/.map/.filter stacked at\n // least twice deep). Terminal handlers (.fold/.match/.getOrElse) and\n // bare co-occurrence in arg lists are conversions, not compositions —\n // Do notation doesn't apply. See issue #205.\n if (!isCompositionChain(node)) return\n if (monadsIn(node).size >= 2) {\n context.report({ node, messageId: \"preferDoForMixedMonads\" })\n }\n }\n\n return {\n LogicalExpression(node) {\n checkNestedNullChecks(node)\n },\n\n CallExpression(node) {\n checkChainedMethods(node)\n checkMixedMonads(node)\n },\n }\n },\n}\n\nexport default rule\n"],"mappings":"6FAKA,MAAM,EAAmC,IAAI,IAAI,CAAC,SAAU,SAAU,MAAO,MAAM,CAAC,EAG9E,EAAsC,IAAI,IAAI,CAAC,SAAU,MAAO,OAAO,CAAC,EAExE,GAAY,EAAmB,IAAsC,IAAI,IAAI,CAAC,GAAG,EAAG,GAAG,CAAC,CAAC,EAM/F,SAAS,EAAQ,EAAoC,CACnD,GAAI,EAAK,OAAS,iBAAkB,OAAO,IAAI,IAC/C,IAAM,EAAS,EAAK,OAapB,OAXI,GAAQ,OAAS,cAAgB,EAAY,IAAI,EAAO,IAAI,EACvD,IAAI,IAAI,CAAC,EAAO,IAAI,CAAC,EAI5B,GAAQ,OAAS,oBACjB,EAAO,QAAQ,OAAS,cACxB,EAAY,IAAI,EAAO,OAAO,IAAI,EAE3B,IAAI,IAAI,CAAC,EAAO,OAAO,IAAI,CAAC,EAE9B,IAAI,GACb,CAOA,SAAS,EAAY,EAAmC,CACtD,OAAO,OAAO,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EAEjC,GAAc,GAChB,EAAQ,OAAO,CACb,OACA,UAAW,4BACX,KAAM,CAAE,MAAO,EAAW,SAAS,CAAE,EACrC,IAAK,EAAe,GAAU,EAAkB,EAAO,CAAI,EAAI,IAAA,EACjE,CAAC,CAEL,CAKA,SAAS,EAAgB,EAAuB,EAAyB,CACvE,IAAM,EAAO,EAAQ,WAAW,QAAQ,CAAI,EAItC,EAAQ,EAAK,MAAM,eAAe,EACxC,GAAI,EAAO,CACT,IAAM,EAAU,EAAM,GAGhB,EAAa;gCACK,EAAQ;8BAHlB,EAAM,EAIO,CAAC,UAAU,EAAQ,MAAM,EAAE;IAGtD,OAAO,EAAM,YAAY,EAAM,CAAU,CAC3C,CAEA,OAAO,EAAM,YAAY,EAAM,sCAAsC,GAAM,CAC7E,CAKA,SAAS,EAAkB,EAAuB,EAAyB,CACzE,IAAM,EAAO,EAAQ,WAAW,QAAQ,CAAI,EAG5C,OAAO,EAAM,YAAY,EAAM,uDAAuD,GAAM,CAC9F,CAuBA,SAAS,EAAiB,EAAqB,CACxC,GAKA,EAAmB,CAAI,GACxB,EAAS,CAAI,CAAC,CAAC,MAAQ,GACzB,EAAQ,OAAO,CAAE,OAAM,UAAW,wBAAyB,CAAC,CAEhE,CAEA,MAAO,CACL,kBAAkB,EAAM,CACtB,EAAsB,CAAI,CAC5B,EAEA,eAAe,EAAM,CACnB,EAAoB,CAAI,EACxB,EAAiB,CAAI,CACvB,CACF,CACF,CACF"}
1
+ {"version":3,"file":"prefer-do-notation.js","names":["MONAD_TYPES","NON_CHILD_KEYS","union","a","b","monadAt","node","callee","astChildren","k","v","monadsIn","ast","acc","child","CHAIN_METHODS","COMPOSITION_METHODS","getChainDepth","method","next","compositionChainDepth","isCompositionChain","andChainDepth","rhs","rule","options","context","minChainDepth","detectMixedMonads","functypeImports","getFunctypeImports","hasDoImport","checkNestedNullChecks","hasNestedPropertyAccess","fixNestedChecks","fixer","matches","checkChainedMethods","isChainedMethodCall","chainDepth","fixChainedMethods","text","match","baseVar","doNotation","checkMixedMonads"],"sources":["../../src/rules/prefer-do-notation.ts"],"sourcesContent":["import type { Rule } from \"eslint\"\n\nimport type { ASTNode } from \"../types/ast\"\nimport { getFunctypeImports, isChainedMethodCall } from \"../utils/functype-detection\"\n\nconst MONAD_TYPES: ReadonlySet<string> = new Set([\"Option\", \"Either\", \"Try\", \"Task\"])\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\nconst union = <T>(a: ReadonlySet<T>, b: ReadonlySet<T>): ReadonlySet<T> => new Set([...a, ...b])\n\n/**\n * Set of monad names that *this single AST node* names as a constructor call.\n * Does not look at children. Returns empty set for any non-monad-constructor node.\n */\nfunction monadAt(node: ASTNode): ReadonlySet<string> {\n if (node.type !== \"CallExpression\") return new Set()\n const callee = node.callee\n // Bare constructor: Option(...), Try(...), Either(...), Task(...)\n if (callee?.type === \"Identifier\" && MONAD_TYPES.has(callee.name)) {\n return new Set([callee.name])\n }\n // Companion call: Option.none(), Either.right(x), Try.success(v)\n if (\n callee?.type === \"MemberExpression\" &&\n callee.object?.type === \"Identifier\" &&\n MONAD_TYPES.has(callee.object.name)\n ) {\n return new Set([callee.object.name])\n }\n return new Set()\n}\n\n/**\n * AST children of `node` worth recursing into. Drops back-edges and source\n * metadata; flattens array-valued keys (e.g. `arguments`); filters non-object\n * leaves (literals, raw strings, numbers).\n */\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/**\n * Pure recursion: the set of all monad names reachable from `node` (including\n * `node` itself if it is a monad constructor call). No mutation, no\n * accumulator parameter — just a fold over the children's results.\n */\nfunction monadsIn(node: unknown): ReadonlySet<string> {\n if (!node || typeof node !== \"object\") return new Set()\n const ast = node as ASTNode\n return astChildren(ast).reduce<ReadonlySet<string>>((acc, child) => union(acc, monadsIn(child)), monadAt(ast))\n}\n\nconst CHAIN_METHODS: ReadonlySet<string> = new Set([\"flatMap\", \"map\", \"filter\", \"fold\"])\n\n/**\n * Methods that *compose* monadic operations (stay in the monad and feed the\n * next step). Distinct from terminal handlers (`fold`, `match`, `getOrElse`)\n * which *exit* the monad — those are conversions, not composition, and Do\n * notation doesn't apply to them.\n */\nconst COMPOSITION_METHODS: ReadonlySet<string> = new Set([\"flatMap\", \"map\", \"filter\"])\n\n/**\n * Length of the chain of `.flatMap()/.map()/.filter()/.fold()` calls walking\n * left from `node`. Returns 1 for a single call, N for N stacked calls. Pure\n * tail recursion — no mutable counter, no `while` loop.\n */\nfunction getChainDepth(node: ASTNode): number {\n if (node.callee.type !== \"MemberExpression\" || node.callee.object.type !== \"CallExpression\") return 1\n const method = node.callee.property\n const next = node.callee.object as ASTNode\n const here = method.type === \"Identifier\" && CHAIN_METHODS.has(method.name) ? 1 : 0\n return here + getChainDepth(next)\n}\n\n/**\n * Number of composition methods (`flatMap`/`map`/`filter`) stacked under\n * `node` via `.callee.object`. 0 if the callee isn't a member expression on\n * another call. Excludes terminal handlers by design.\n */\nfunction compositionChainDepth(node: ASTNode): number {\n if (node.callee?.type !== \"MemberExpression\" || node.callee.object?.type !== \"CallExpression\") return 0\n const method = node.callee.property\n const next = node.callee.object as ASTNode\n const here = method.type === \"Identifier\" && COMPOSITION_METHODS.has(method.name) ? 1 : 0\n return here + compositionChainDepth(next)\n}\n\n/**\n * True when `node`'s outermost call is a composition method AND at least one\n * more composition method appears below it — i.e. this is a real\n * `.flatMap(...).flatMap(...)`-style chain, not a terminal exit like\n * `.fold(...)` or a bare receiver like `option.flatMap(...)`.\n */\nfunction isCompositionChain(node: ASTNode): boolean {\n if (node.callee?.type !== \"MemberExpression\") return false\n const method = node.callee.property\n if (method.type !== \"Identifier\" || !COMPOSITION_METHODS.has(method.name)) return false\n return compositionChainDepth(node) >= 1\n}\n\n/**\n * Depth of a logical-AND chain (`a && b && c && ...`) where each right-hand\n * side is either a MemberExpression or another && chain — the shape that\n * indicates nested property-access guarding rather than arbitrary booleans.\n */\nfunction andChainDepth(node: ASTNode): number {\n if (node.type !== \"LogicalExpression\" || node.operator !== \"&&\") return 0\n const rhs = node.right\n const here = rhs.type === \"MemberExpression\" || (rhs.type === \"LogicalExpression\" && rhs.operator === \"&&\") ? 1 : 0\n return here + andChainDepth(node.left as ASTNode)\n}\n\nconst rule: Rule.RuleModule = {\n meta: {\n type: \"suggestion\",\n docs: {\n description: \"Prefer Do notation for complex monadic compositions and nested operations\",\n recommended: true,\n },\n fixable: \"code\",\n messages: {\n preferDoForNestedChecks: \"Prefer Do notation for nested null/undefined checks instead of logical AND chains\",\n preferDoForChainedMethods: \"Prefer Do notation for complex flatMap chains ({{count}} levels deep)\",\n preferDoForMixedMonads: \"Consider Do notation when mixing Option, Either, and Try operations\",\n preferDoAsyncForChainedTasks: \"Prefer DoAsync notation for chained async operations\",\n },\n schema: [\n {\n type: \"object\",\n properties: {\n minChainDepth: {\n type: \"integer\",\n minimum: 2,\n default: 3,\n },\n detectMixedMonads: {\n type: \"boolean\",\n default: true,\n },\n },\n additionalProperties: false,\n },\n ],\n },\n create(context) {\n const options = context.options[0] || {}\n const minChainDepth = options.minChainDepth || 3\n const detectMixedMonads = options.detectMixedMonads !== false\n\n const functypeImports = getFunctypeImports(context)\n\n // Track if Do notation is already imported\n const hasDoImport = functypeImports.functions.has(\"Do\") || functypeImports.functions.has(\"DoAsync\")\n\n /**\n * Detect nested null/undefined checks like: a && a.b && a.b.c\n */\n function checkNestedNullChecks(node: ASTNode): void {\n if (node.operator !== \"&&\") return\n\n // Check if this looks like nested property access guarding\n if (andChainDepth(node) >= 2 && hasNestedPropertyAccess(node)) {\n context.report({\n node,\n messageId: \"preferDoForNestedChecks\",\n fix: hasDoImport ? (fixer) => fixNestedChecks(fixer, node) : undefined,\n })\n }\n }\n\n /**\n * Check if logical expression contains nested property access patterns\n */\n function hasNestedPropertyAccess(node: ASTNode): boolean {\n // Look for patterns like: obj && obj.prop && obj.prop.nested\n const matches = context.sourceCode.getText(node).match(/\\w+(\\.\\w+){2,}/g)\n return matches !== null && matches.length > 0\n }\n\n /**\n * Detect long flatMap chains\n */\n function checkChainedMethods(node: ASTNode): void {\n if (!isChainedMethodCall(node, \"flatMap\")) return\n\n const chainDepth = getChainDepth(node)\n\n if (chainDepth >= minChainDepth) {\n context.report({\n node,\n messageId: \"preferDoForChainedMethods\",\n data: { count: chainDepth.toString() },\n fix: hasDoImport ? (fixer) => fixChainedMethods(fixer, node) : undefined,\n })\n }\n }\n\n /**\n * Auto-fix for nested null checks\n */\n function fixNestedChecks(fixer: Rule.RuleFixer, node: ASTNode): Rule.Fix {\n const text = context.sourceCode.getText(node)\n\n // Simple transformation for common patterns\n // a && a.b && a.b.c -> Do(function* () { const x = yield* $(Option(a)); const y = yield* $(Option(x.b)); return Option(y.c) })\n const match = text.match(/(\\w+)(\\.\\w+)+/)\n if (match) {\n const baseVar = match[1]\n const chain = match[0]\n\n const doNotation = `Do(function* () {\n const obj = yield* $(Option(${baseVar}))\n return yield* $(Option(obj${chain.substring(baseVar.length)}))\n})`\n\n return fixer.replaceText(node, doNotation)\n }\n\n return fixer.replaceText(node, `/* TODO: Convert to Do notation */ ${text}`)\n }\n\n /**\n * Auto-fix for chained methods (basic)\n */\n function fixChainedMethods(fixer: Rule.RuleFixer, node: ASTNode): Rule.Fix {\n const text = context.sourceCode.getText(node)\n\n // For now, just add a comment suggesting Do notation\n return fixer.replaceText(node, `/* TODO: Consider Do notation for complex chains */ ${text}`)\n }\n\n /**\n * Detect mixed monad usage by walking the AST under `node` and counting\n * *distinct* monad constructor calls — not substring matches.\n *\n * A \"monad constructor call\" is a CallExpression whose callee is either:\n * - a bare identifier matching a known monad type (`Option(...)`, `Try(...)`),\n * or\n * - a member expression whose object is a known monad type\n * (`Option.none()`, `Either.right(...)`, `Try.success(...)`).\n *\n * Method calls like `.toEither(...)`, `.toOption()`, `.toTry()` are NOT\n * constructor calls — they're the idiomatic *conversion* API for crossing\n * monad boundaries. The old substring-based check fired on these because\n * `.toEither` contains \"Either\" as a substring; the AST check correctly\n * sees them as method calls, not new monad constructions.\n *\n * Implementation is pure recursion over the AST: `monadAt` reports what\n * a single node names; `monadsIn` returns the union of `monadAt(self)`\n * with the results from each child. No mutable accumulator, no for-loops\n * driving state changes.\n */\n function checkMixedMonads(node: ASTNode): void {\n if (!detectMixedMonads) return\n // Only flag genuine composition chains (.flatMap/.map/.filter stacked at\n // least twice deep). Terminal handlers (.fold/.match/.getOrElse) and\n // bare co-occurrence in arg lists are conversions, not compositions —\n // Do notation doesn't apply. See issue #205.\n if (!isCompositionChain(node)) return\n if (monadsIn(node).size >= 2) {\n context.report({ node, messageId: \"preferDoForMixedMonads\" })\n }\n }\n\n return {\n LogicalExpression(node) {\n checkNestedNullChecks(node)\n },\n\n CallExpression(node) {\n checkChainedMethods(node)\n checkMixedMonads(node)\n },\n }\n },\n}\n\nexport default rule\n"],"mappings":"6FAKA,MAAMA,kBAAmC,IAAI,IAAI,CAAC,SAAU,SAAU,MAAO,MAAM,CAAC,EAG9EC,kBAAsC,IAAI,IAAI,CAAC,SAAU,MAAO,OAAO,CAAC,EAExEC,GAAY,EAAmB,oBAAsC,IAAI,IAAI,CAAC,GAAGC,EAAG,GAAGC,CAAC,CAAC,EAM/F,SAASC,EAAQ,EAAoC,CACnD,GAAIC,EAAK,OAAS,iBAAkB,sBAAO,IAAI,IAC/C,IAAMC,EAASD,EAAK,OAapB,OAXIC,GAAQ,OAAS,cAAgBP,EAAY,IAAIO,EAAO,IAAI,kBACvD,IAAI,IAAI,CAACA,EAAO,IAAI,CAAC,EAI5BA,GAAQ,OAAS,oBACjBA,EAAO,QAAQ,OAAS,cACxBP,EAAY,IAAIO,EAAO,OAAO,IAAI,kBAE3B,IAAI,IAAI,CAACA,EAAO,OAAO,IAAI,CAAC,kBAE9B,IAAI,GACb,CA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