eslint-plugin-functype 2.119.0 → 2.121.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +107 -19
- package/dist/cli/list-rules.js.map +1 -1
- package/dist/configs/recommended.d.ts +8 -2
- package/dist/configs/recommended.js +1 -1
- package/dist/configs/recommended.js.map +1 -1
- package/dist/configs/strict.d.ts +2 -2
- package/dist/configs/strict.js +1 -1
- package/dist/configs/strict.js.map +1 -1
- package/dist/index.d.ts +2 -2
- package/dist/index.js.map +1 -1
- package/dist/rules/collection-naming.d.ts +0 -2
- package/dist/rules/collection-naming.js.map +1 -1
- package/dist/rules/index.d.ts +20 -18
- package/dist/rules/index.js +1 -1
- package/dist/rules/index.js.map +1 -1
- package/dist/rules/must-fold-on-component-return.d.ts +4 -0
- package/dist/rules/must-fold-on-component-return.js +2 -0
- package/dist/rules/must-fold-on-component-return.js.map +1 -0
- package/dist/rules/no-array-mutation.d.ts +0 -2
- package/dist/rules/no-array-mutation.js +1 -1
- package/dist/rules/no-array-mutation.js.map +1 -1
- package/dist/rules/no-floating-io.d.ts +0 -2
- package/dist/rules/no-floating-io.js.map +1 -1
- package/dist/rules/no-get-unsafe.d.ts +0 -2
- package/dist/rules/no-get-unsafe.js.map +1 -1
- package/dist/rules/no-getOrThrow-in-render.d.ts +4 -0
- package/dist/rules/no-getOrThrow-in-render.js +2 -0
- package/dist/rules/no-getOrThrow-in-render.js.map +1 -0
- package/dist/rules/no-imperative-loops.d.ts +0 -2
- package/dist/rules/no-imperative-loops.js +1 -1
- package/dist/rules/no-imperative-loops.js.map +1 -1
- package/dist/rules/no-let.d.ts +0 -2
- package/dist/rules/no-let.js.map +1 -1
- package/dist/rules/prefer-do-notation.d.ts +0 -2
- package/dist/rules/prefer-do-notation.js.map +1 -1
- package/dist/rules/prefer-either.d.ts +0 -2
- package/dist/rules/prefer-either.js.map +1 -1
- package/dist/rules/prefer-flatmap.d.ts +0 -2
- package/dist/rules/prefer-flatmap.js +1 -1
- package/dist/rules/prefer-flatmap.js.map +1 -1
- package/dist/rules/prefer-fold.d.ts +0 -2
- package/dist/rules/prefer-fold.js +1 -1
- package/dist/rules/prefer-fold.js.map +1 -1
- package/dist/rules/prefer-functype-map.d.ts +0 -2
- package/dist/rules/prefer-functype-map.js.map +1 -1
- package/dist/rules/prefer-functype-set.d.ts +0 -2
- package/dist/rules/prefer-functype-set.js.map +1 -1
- package/dist/rules/prefer-list.d.ts +0 -2
- package/dist/rules/prefer-list.js +2 -2
- package/dist/rules/prefer-list.js.map +1 -1
- package/dist/rules/prefer-map.d.ts +0 -2
- package/dist/rules/prefer-map.js.map +1 -1
- package/dist/rules/prefer-option.d.ts +0 -2
- package/dist/rules/prefer-option.js.map +1 -1
- package/dist/rules/prefer-try.d.ts +0 -2
- package/dist/rules/prefer-try.js.map +1 -1
- package/dist/types/ast.d.ts +0 -2
- package/dist/utils/array-mutation.d.ts +0 -2
- package/dist/utils/array-mutation.js.map +1 -1
- package/dist/utils/ast-walk.d.ts +0 -2
- package/dist/utils/ast-walk.js.map +1 -1
- package/dist/utils/async-detection.d.ts +0 -2
- package/dist/utils/async-detection.js.map +1 -1
- package/dist/utils/boundary-tags.d.ts +0 -2
- package/dist/utils/boundary-tags.js.map +1 -1
- package/dist/utils/collection-binding.d.ts +0 -2
- package/dist/utils/collection-binding.js.map +1 -1
- package/dist/utils/dependency-validator.d.ts +1 -2
- package/dist/utils/dependency-validator.js.map +1 -1
- package/dist/utils/functype-detection.d.ts +0 -2
- package/dist/utils/functype-detection.js.map +1 -1
- package/dist/utils/functype-predicates.d.ts +38 -0
- package/dist/utils/functype-predicates.js +2 -0
- package/dist/utils/functype-predicates.js.map +1 -0
- package/dist/utils/import-fixer.d.ts +0 -2
- package/dist/utils/import-fixer.js.map +1 -1
- package/dist/utils/mutable-collection.d.ts +0 -2
- package/dist/utils/mutable-collection.js.map +1 -1
- package/dist/utils/react-render.d.ts +13 -0
- package/dist/utils/react-render.js +2 -0
- package/dist/utils/react-render.js.map +1 -0
- package/dist/utils/readonly-contract.d.ts +0 -2
- package/dist/utils/readonly-contract.js.map +1 -1
- package/dist/utils/type-aware.d.ts +0 -2
- package/dist/utils/type-aware.js.map +1 -1
- package/dist/utils/wire-types.d.ts +0 -2
- package/dist/utils/wire-types.js.map +1 -1
- package/package.json +6 -6
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"no-floating-io.js","names":["rule","expression","node","isIOByType","context"],"sources":["../../src/rules/no-floating-io.ts"],"sourcesContent":["import type { Rule } from \"eslint\"\n\nimport type { ASTNode } from \"../types/ast\"\nimport { isIOByType } from \"../utils/type-aware\"\n\n/**\n * Reports an `IO` that is built and then dropped, so it never runs:\n *\n * - an expression statement whose value is an `IO` — `log.info(\"saved\")`, `save(user).tap(audit)`;\n * - `await` on an `IO`. `IO` is not a Promise, so `await io` hands back the `IO` itself, unrun.\n *\n * `no-floating-promises` and `await-thenable` don't see either case, because `IO` is not thenable.\n * Returning, yielding, assigning or passing an `IO` along is fine: someone else runs it. `void io`\n * marks a deliberate drop and isn't reported.\n *\n * Type-aware only: without type information it reports nothing.\n */\nconst rule: Rule.RuleModule = {\n meta: {\n type: \"problem\",\n docs: {\n description: \"Disallow building an IO and never running it\",\n recommended: false,\n },\n schema: [],\n messages: {\n floatingIO:\n \"This IO is built and never run, so it does nothing. Run it (.run(), .runOrThrow(), .runExit()), return it, or yield* it inside IO.gen\",\n awaitedIO:\n \"await on an IO does nothing: IO is not a Promise, so this returns the IO unrun. Await .run() or .runOrThrow() instead\",\n },\n },\n\n create(context) {\n return {\n ExpressionStatement(node: ASTNode) {\n const expression = node.expression as ASTNode\n // `void io` is a deliberate drop; `await io` is reported by the AwaitExpression visitor.\n if (expression.type === \"AwaitExpression\") return\n if (expression.type === \"UnaryExpression\" && expression.operator === \"void\") return\n if (isIOByType(expression, context)) context.report({ node: expression, messageId: \"floatingIO\" })\n },\n AwaitExpression(node: ASTNode) {\n if (isIOByType(node.argument as ASTNode, context)) context.report({ node, messageId: \"awaitedIO\" })\n },\n }\n },\n}\n\nexport default rule\n"],"mappings":"oDAiBA,MAAMA,EAAwB,CAC5B,KAAM,CACJ,KAAM,UACN,KAAM,CACJ,YAAa,+CACb,YAAa,EACf,EACA,OAAQ,CAAC,EACT,SAAU,CACR,WACE,wIACF,UACE,uHACJ,CACF,EAEA,OAAO,EAAS,CACd,MAAO,CACL,oBAAoB,EAAe,CACjC,IAAMC,EAAaC,EAAK,WAEpBD,EAAW,OAAS,oBACpBA,EAAW,OAAS,mBAAqBA,EAAW,WAAa,SACjEE,EAAWF,EAAYG,CAAO,GAAGA,EAAQ,OAAO,CAAE,KAAMH,EAAY,UAAW,YAAa,CAAC,CACnG,EACA,gBAAgB,EAAe,CACzBE,EAAWD,EAAK,SAAqBE,CAAO,GAAGA,EAAQ,OAAO,CAAE,OAAM,UAAW,WAAY,CAAC,CACpG,CACF,CACF,CACF"}
|
|
1
|
+
{"version":3,"file":"no-floating-io.js","names":["rule","expression","node","isIOByType","context"],"sources":["../../src/rules/no-floating-io.ts"],"sourcesContent":["import type { Rule } from \"eslint\"\n\nimport type { ASTNode } from \"../types/ast\"\nimport { isIOByType } from \"../utils/type-aware\"\n\n/**\n * Reports an `IO` that is built and then dropped, so it never runs:\n *\n * - an expression statement whose value is an `IO` — `log.info(\"saved\")`, `save(user).tap(audit)`;\n * - `await` on an `IO`. `IO` is not a Promise, so `await io` hands back the `IO` itself, unrun.\n *\n * `no-floating-promises` and `await-thenable` don't see either case, because `IO` is not thenable.\n * Returning, yielding, assigning or passing an `IO` along is fine: someone else runs it. `void io`\n * marks a deliberate drop and isn't reported.\n *\n * Type-aware only: without type information it reports nothing.\n */\nconst rule: Rule.RuleModule = {\n meta: {\n type: \"problem\",\n docs: {\n description: \"Disallow building an IO and never running it\",\n recommended: false,\n },\n schema: [],\n messages: {\n floatingIO:\n \"This IO is built and never run, so it does nothing. Run it (.run(), .runOrThrow(), .runExit()), return it, or yield* it inside IO.gen\",\n awaitedIO:\n \"await on an IO does nothing: IO is not a Promise, so this returns the IO unrun. Await .run() or .runOrThrow() instead\",\n },\n },\n\n create(context) {\n return {\n ExpressionStatement(node: ASTNode) {\n const expression = node.expression as ASTNode\n // `void io` is a deliberate drop; `await io` is reported by the AwaitExpression visitor.\n if (expression.type === \"AwaitExpression\") return\n if (expression.type === \"UnaryExpression\" && expression.operator === \"void\") return\n if (isIOByType(expression, context)) context.report({ node: expression, messageId: \"floatingIO\" })\n },\n AwaitExpression(node: ASTNode) {\n if (isIOByType(node.argument as ASTNode, context)) context.report({ node, messageId: \"awaitedIO\" })\n },\n }\n },\n}\n\nexport default rule\n"],"mappings":"A,oDAiBA,MAAMA,EAAwB,CAC5B,KAAM,CACJ,KAAM,UACN,KAAM,CACJ,YAAa,+CACb,YAAa,EACf,EACA,OAAQ,CAAC,EACT,SAAU,CACR,WACE,wIACF,UACE,uHACJ,CACF,EAEA,OAAO,EAAS,CACd,MAAO,CACL,oBAAoB,EAAe,CACjC,IAAMC,EAAaC,EAAK,WAEpBD,EAAW,OAAS,oBACpBA,EAAW,OAAS,mBAAqBA,EAAW,WAAa,SACjEE,EAAWF,EAAYG,CAAO,GAAGA,EAAQ,OAAO,CAAE,KAAMH,EAAY,UAAW,YAAa,CAAC,CACnG,EACA,gBAAgB,EAAe,CACzBE,EAAWD,EAAK,SAAqBE,CAAO,GAAGA,EAAQ,OAAO,CAAE,OAAM,UAAW,WAAY,CAAC,CACpG,CACF,CACF,CACF,E"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"no-get-unsafe.js","names":["DEFAULT_UNSAFE_METHODS","rule","options","context","allowInTests","unsafeMethods","allowInteropMarker","isChosenErrorThrow","methodName","node","isInTestFile","filename","isMonadicType","text","varName","property","isInsideTaggedDeclaration","isExtractableByType","sourceCode","objectText","argsText","a","wasSuffix","fixer"],"sources":["../../src/rules/no-get-unsafe.ts"],"sourcesContent":["import type { Rule } from \"eslint\"\n\nimport type { ASTNode } from \"../types/ast\"\nimport { INTEROP_TAG, isInsideTaggedDeclaration } from \"../utils/boundary-tags\"\nimport { isExtractableByType } from \"../utils/type-aware\"\n\nconst DEFAULT_UNSAFE_METHODS: readonly string[] = [\"orThrow\", \"expect\", \"get\", \"getOrThrow\", \"unwrap\"]\n\nconst rule: Rule.RuleModule = {\n meta: {\n type: \"problem\",\n docs: {\n description: \"Avoid unsafe extractor calls on Option, Either, and other Extractable types\",\n recommended: true,\n },\n hasSuggestions: true,\n schema: [\n {\n type: \"object\",\n properties: {\n allowInTests: {\n type: \"boolean\",\n default: true,\n },\n allowInteropMarker: {\n type: \"boolean\",\n default: true,\n },\n unsafeMethods: {\n type: \"array\",\n items: { type: \"string\" },\n default: [...DEFAULT_UNSAFE_METHODS],\n },\n },\n additionalProperties: false,\n },\n ],\n messages: {\n noUnsafeGet:\n \"Avoid unsafe .{{method}}() call: it throws a generic error. Use .fold(), .map(), or .orElse() instead. If a host needs the throw, name the error: .orThrow((e) => new MyError(e))\",\n suggestOrElse: \"Replace with .orElse(default) for a value fallback\",\n suggestFold: \"Replace with .fold(onNone, onSome) for branch handling\",\n },\n },\n\n create(context) {\n const options = context.options[0] || {}\n const allowInTests = options.allowInTests !== false\n const unsafeMethods: readonly string[] = options.unsafeMethods || DEFAULT_UNSAFE_METHODS\n // `@interop <reason>` on an enclosing declaration marks a host-contract boundary, as in prefer-either.\n const allowInteropMarker = options.allowInteropMarker !== false\n\n /**\n * `.orThrow(error)` / `.orThrow((e) => error)`: the caller chose the error. That is the documented way\n * to throw for a host that needs it, not an unsafe extraction; `prefer-either` and the README's\n * decision table both treat it that way. Only a bare `.orThrow()` throws a generic error.\n */\n const isChosenErrorThrow = (methodName: string, node: ASTNode): boolean =>\n methodName === \"orThrow\" && node.arguments.length > 0\n\n function isInTestFile() {\n const filename = context.filename\n return (\n /\\.(test|spec)\\.(ts|js|tsx|jsx)$/.test(filename) ||\n filename.includes(\"__tests__\") ||\n filename.includes(\"/test/\") ||\n filename.includes(\"/tests/\")\n )\n }\n\n function isMonadicType(node: ASTNode): boolean {\n // This is a simplified check - in a real implementation, you'd want\n // more sophisticated type checking using TypeScript's type checker\n if (!node) return false\n\n const sourceCode = context.sourceCode\n\n // Check for common patterns that indicate monadic types\n const text = sourceCode.getText(node)\n\n // Direct type checks - constructors or type names\n if (/\\b(Option|Either|Maybe|Result|Some|None|Left|Right)\\b/.test(text)) {\n return true\n }\n\n // Method chains that suggest monadic operations\n if (/\\.(map|flatMap|filter|fold)\\s*\\(/.test(text)) {\n return true\n }\n\n // Variable names that suggest monadic types (case insensitive)\n if (/\\b(option|either|maybe|result|some|none|left|right)\\w*\\b/i.test(text)) {\n return true\n }\n\n // Check the specific node type and name\n if (node.type === \"Identifier\") {\n const varName = node.name.toLowerCase()\n if (/(option|either|maybe|result|some|none|left|right|opt)/.test(varName)) {\n return true\n }\n }\n\n // Check for CallExpression pattern like Some(\"test\").map()\n if (node.type === \"CallExpression\" && node.callee.type === \"MemberExpression\" && node.callee.object) {\n return isMonadicType(node.callee.object)\n }\n\n return false\n }\n\n return {\n CallExpression(node: ASTNode) {\n if (allowInTests && isInTestFile()) return\n\n if (node.callee.type !== \"MemberExpression\") return\n\n const property = node.callee.property\n if (!property || property.type !== \"Identifier\") return\n\n const methodName = property.name\n if (!unsafeMethods.includes(methodName)) return\n if (isChosenErrorThrow(methodName, node)) return\n if (allowInteropMarker && isInsideTaggedDeclaration(node, INTEROP_TAG, context.sourceCode)) return\n\n // With type information, the receiver's type decides: no name guessing, so `missing.orThrow()`\n // on an Option is reported and `options.get(\"k\")` on a native Map is not. Without it, fall\n // back to the name/shape heuristic.\n const byType = isExtractableByType(node.callee.object, context)\n if (byType ?? isMonadicType(node.callee.object)) {\n const sourceCode = context.sourceCode\n const objectText = sourceCode.getText(node.callee.object)\n\n // Preserve the original call's argument text in the TODO comment so a suggestion\n // applied to `.expect(\"Should have a user here\")` or `.orThrow(new NotFound())`\n // doesn't silently drop information the developer intended to keep. Omit the\n // \"was\" suffix when the original call had no args (`.get()`, `.unwrap()`, etc.).\n const argsText = node.arguments.map((a: ASTNode) => sourceCode.getText(a)).join(\", \")\n const wasSuffix = argsText ? `; was ${methodName}(${argsText})` : \"\"\n\n context.report({\n node,\n messageId: \"noUnsafeGet\",\n data: { method: methodName },\n suggest: [\n {\n messageId: \"suggestOrElse\",\n fix(fixer) {\n return fixer.replaceText(node, `${objectText}.orElse(undefined /* TODO: default${wasSuffix} */)`)\n },\n },\n {\n messageId: \"suggestFold\",\n fix(fixer) {\n return fixer.replaceText(\n node,\n `${objectText}.fold(() => undefined /* TODO: onNone${wasSuffix} */, (v) => v /* TODO: onSome */)`,\n )\n },\n },\n ],\n })\n }\n },\n }\n },\n}\n\nexport default rule\n"],"mappings":"mIAMA,MAAMA,EAA4C,CAAC,UAAW,SAAU,MAAO,aAAc,QAAQ,EAE/FC,EAAwB,CAC5B,KAAM,CACJ,KAAM,UACN,KAAM,CACJ,YAAa,8EACb,YAAa,EACf,EACA,eAAgB,GAChB,OAAQ,CACN,CACE,KAAM,SACN,WAAY,CACV,aAAc,CACZ,KAAM,UACN,QAAS,EACX,EACA,mBAAoB,CAClB,KAAM,UACN,QAAS,EACX,EACA,cAAe,CACb,KAAM,QACN,MAAO,CAAE,KAAM,QAAS,EACxB,QAAS,CAAC,GAAGD,CAAsB,CACrC,CACF,EACA,qBAAsB,EACxB,CACF,EACA,SAAU,CACR,YACE,oLACF,cAAe,qDACf,YAAa,wDACf,CACF,EAEA,OAAO,EAAS,CACd,IAAME,EAAUC,EAAQ,QAAQ,IAAM,CAAC,EACjCC,EAAeF,EAAQ,eAAiB,GACxCG,EAAmCH,EAAQ,eAAiBF,EAE5DM,EAAqBJ,EAAQ,qBAAuB,GAOpDK,GAAsB,EAAoB,IAC9CC,IAAe,WAAaC,EAAK,UAAU,OAAS,EAEtD,SAASC,GAAe,CACtB,IAAMC,EAAWR,EAAQ,SACzB,MACE,kCAAkC,KAAKQ,CAAQ,GAC/CA,EAAS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W,gBACX,IAAI,EAAO,CACT,OAAOe,EAAM,YAAYd,EAAM,GAAGU,EAAW,oCAAoCG,EAAU,KAAK,CAClG,CACF,EACA,CACE,UAAW,cACX,IAAI,EAAO,CACT,OAAOC,EAAM,YACXd,EACA,GAAGU,EAAW,uCAAuCG,EAAU,kCACjE,CACF,CACF,CACF,CACF,CAAC,CACH,CACF,CACF,CACF,CACF"}
|
|
1
|
+
{"version":3,"file":"no-get-unsafe.js","names":["DEFAULT_UNSAFE_METHODS","rule","options","context","allowInTests","unsafeMethods","allowInteropMarker","isChosenErrorThrow","methodName","node","isInTestFile","filename","isMonadicType","text","varName","property","isInsideTaggedDeclaration","isExtractableByType","sourceCode","objectText","argsText","a","wasSuffix","fixer"],"sources":["../../src/rules/no-get-unsafe.ts"],"sourcesContent":["import type { Rule } from \"eslint\"\n\nimport type { ASTNode } from \"../types/ast\"\nimport { INTEROP_TAG, isInsideTaggedDeclaration } from \"../utils/boundary-tags\"\nimport { isExtractableByType } from \"../utils/type-aware\"\n\nconst DEFAULT_UNSAFE_METHODS: readonly string[] = [\"orThrow\", \"expect\", \"get\", \"getOrThrow\", \"unwrap\"]\n\nconst rule: Rule.RuleModule = {\n meta: {\n type: \"problem\",\n docs: {\n description: \"Avoid unsafe extractor calls on Option, Either, and other Extractable types\",\n recommended: true,\n },\n hasSuggestions: true,\n schema: [\n {\n type: \"object\",\n properties: {\n allowInTests: {\n type: \"boolean\",\n default: true,\n },\n allowInteropMarker: {\n type: \"boolean\",\n default: true,\n },\n unsafeMethods: {\n type: \"array\",\n items: { type: \"string\" },\n default: [...DEFAULT_UNSAFE_METHODS],\n },\n },\n additionalProperties: false,\n },\n ],\n messages: {\n noUnsafeGet:\n \"Avoid unsafe .{{method}}() call: it throws a generic error. Use .fold(), .map(), or .orElse() instead. If a host needs the throw, name the error: .orThrow((e) => new MyError(e))\",\n suggestOrElse: \"Replace with .orElse(default) for a value fallback\",\n suggestFold: \"Replace with .fold(onNone, onSome) for branch handling\",\n },\n },\n\n create(context) {\n const options = context.options[0] || {}\n const allowInTests = options.allowInTests !== false\n const unsafeMethods: readonly string[] = options.unsafeMethods || DEFAULT_UNSAFE_METHODS\n // `@interop <reason>` on an enclosing declaration marks a host-contract boundary, as in prefer-either.\n const allowInteropMarker = options.allowInteropMarker !== false\n\n /**\n * `.orThrow(error)` / `.orThrow((e) => error)`: the caller chose the error. That is the documented way\n * to throw for a host that needs it, not an unsafe extraction; `prefer-either` and the README's\n * decision table both treat it that way. Only a bare `.orThrow()` throws a generic error.\n */\n const isChosenErrorThrow = (methodName: string, node: ASTNode): boolean =>\n methodName === \"orThrow\" && node.arguments.length > 0\n\n function isInTestFile() {\n const filename = context.filename\n return (\n /\\.(test|spec)\\.(ts|js|tsx|jsx)$/.test(filename) ||\n filename.includes(\"__tests__\") ||\n filename.includes(\"/test/\") ||\n filename.includes(\"/tests/\")\n )\n }\n\n function isMonadicType(node: ASTNode): boolean {\n // This is a simplified check - in a real implementation, you'd want\n // more sophisticated type checking using TypeScript's type checker\n if (!node) return false\n\n const sourceCode = context.sourceCode\n\n // Check for common patterns that indicate monadic types\n const text = sourceCode.getText(node)\n\n // Direct type checks - constructors or type names\n if (/\\b(Option|Either|Maybe|Result|Some|None|Left|Right)\\b/.test(text)) {\n return true\n }\n\n // Method chains that suggest monadic operations\n if (/\\.(map|flatMap|filter|fold)\\s*\\(/.test(text)) {\n return true\n }\n\n // Variable names that suggest monadic types (case insensitive)\n if (/\\b(option|either|maybe|result|some|none|left|right)\\w*\\b/i.test(text)) {\n return true\n }\n\n // Check the specific node type and name\n if (node.type === \"Identifier\") {\n const varName = node.name.toLowerCase()\n if (/(option|either|maybe|result|some|none|left|right|opt)/.test(varName)) {\n return true\n }\n }\n\n // Check for CallExpression pattern like Some(\"test\").map()\n if (node.type === \"CallExpression\" && node.callee.type === \"MemberExpression\" && node.callee.object) {\n return isMonadicType(node.callee.object)\n }\n\n return false\n }\n\n return {\n CallExpression(node: ASTNode) {\n if (allowInTests && isInTestFile()) return\n\n if (node.callee.type !== \"MemberExpression\") return\n\n const property = node.callee.property\n if (!property || property.type !== \"Identifier\") return\n\n const methodName = property.name\n if (!unsafeMethods.includes(methodName)) return\n if (isChosenErrorThrow(methodName, node)) return\n if (allowInteropMarker && isInsideTaggedDeclaration(node, INTEROP_TAG, context.sourceCode)) return\n\n // With type information, the receiver's type decides: no name guessing, so `missing.orThrow()`\n // on an Option is reported and `options.get(\"k\")` on a native Map is not. Without it, fall\n // back to the name/shape heuristic.\n const byType = isExtractableByType(node.callee.object, context)\n if (byType ?? isMonadicType(node.callee.object)) {\n const sourceCode = context.sourceCode\n const objectText = sourceCode.getText(node.callee.object)\n\n // Preserve the original call's argument text in the TODO comment so a suggestion\n // applied to `.expect(\"Should have a user here\")` or `.orThrow(new NotFound())`\n // doesn't silently drop information the developer intended to keep. Omit the\n // \"was\" suffix when the original call had no args (`.get()`, `.unwrap()`, etc.).\n const argsText = node.arguments.map((a: ASTNode) => sourceCode.getText(a)).join(\", \")\n const wasSuffix = argsText ? `; was ${methodName}(${argsText})` : \"\"\n\n context.report({\n node,\n messageId: \"noUnsafeGet\",\n data: { method: methodName },\n suggest: [\n {\n messageId: \"suggestOrElse\",\n fix(fixer) {\n return fixer.replaceText(node, `${objectText}.orElse(undefined /* TODO: default${wasSuffix} */)`)\n },\n },\n {\n messageId: \"suggestFold\",\n fix(fixer) {\n return fixer.replaceText(\n node,\n `${objectText}.fold(() => undefined /* TODO: onNone${wasSuffix} */, (v) => v /* TODO: onSome */)`,\n )\n },\n },\n ],\n })\n }\n },\n }\n },\n}\n\nexport default rule\n"],"mappings":"A,mIAMA,MAAMA,EAA4C,CAAC,UAAW,SAAU,MAAO,aAAc,QAAQ,EAE/FC,EAAwB,CAC5B,KAAM,CACJ,KAAM,UACN,KAAM,CACJ,YAAa,8EACb,YAAa,EACf,EACA,eAAgB,GAChB,OAAQ,CACN,CACE,KAAM,SACN,WAAY,CACV,aAAc,CACZ,KAAM,UACN,QAAS,EACX,E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AAMP,EAAaO,EAAS,KAC5B,GAAKV,EAAc,SAASG,CAAU,GAClC,GAAmBA,EAAYC,CAAI,GACnC,KAAsBO,EAA0BP,EAAA,UAAmBN,EAAQ,UAAU,KAK1Ec,EAAoBR,EAAK,OAAO,OAAQN,CAC9C,GAAKS,EAAcH,EAAK,OAAO,MAAM,GAAG,CAC/C,IAAMS,EAAaf,EAAQ,WACrBgB,EAAaD,EAAW,QAAQT,EAAK,OAAO,MAAM,EAMlDW,EAAWX,EAAK,UAAU,IAAK,GAAeS,EAAW,QAAQG,CAAC,CAAC,CAAC,CAAC,KAAK,IAAI,EAC9EC,EAAYF,EAAW,SAASZ,EAAW,GAAGY,EAAS,GAAK,GAElEjB,EAAQ,OAAO,CACb,OACA,UAAW,cACX,KAAM,CAAE,OAAQK,CAAW,EAC3B,QAAS,CACP,CACE,UAAW,gBACX,IAAI,EAAO,CACT,OAAOe,EAAM,YAAYd,EAAM,GAAGU,EAAW,oCAAoCG,EAAU,KAAK,CAClG,CACF,EACA,CACE,UAAW,cACX,IAAI,EAAO,CACT,OAAOC,EAAM,YACXd,EACA,GAAGU,EAAW,uCAAuCG,EAAU,kCACjE,CACF,CACF,CACF,CACF,CAAC,CACH,CACF,CACF,CACF,CACF,E"}
|
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
import{isInsideTaggedDeclaration as e}from"../utils/boundary-tags.js";import{compact as t,provesWhen as n}from"../utils/functype-predicates.js";import{enclosingFunction as r,renderKind as i}from"../utils/react-render.js";import{isExtractableByType as a}from"../utils/type-aware.js";const o=/* @__PURE__ */ new Set([`orThrow`,`getOrThrow`]),s=e=>e.type===`ReturnStatement`||e.type===`ThrowStatement`||e.type===`BlockStatement`&&e.body.length>0&&s(e.body.at(-1)),c=(e,t,r)=>{if(e.type===`IfStatement`)return s(e.consequent)?n(e.test,!1,t,r)===`present`?!0:e.alternate?c(e.alternate,t,r):!1:!1;let i=e.type===`ExpressionStatement`?e.expression:null;return i?.type===`CallExpression`&&i.callee.type===`Identifier`&&i.callee.name===`invariant`&&i.arguments.length>0&&n(i.arguments[0],!0,t,r)===`present`},l=(e,t,r,i)=>{let a=(e,t)=>n(e,t,r,i)===`present`,o=(e,n)=>{if(!n||n===t)return!1;let s=n.type===`IfStatement`||n.type===`ConditionalExpression`;return s&&n.consequent===e&&a(n.test,!0)||s&&n.alternate===e&&a(n.test,!1)||n.type===`LogicalExpression`&&n.right===e&&(n.operator===`&&`&&a(n.left,!0)||n.operator===`||`&&a(n.left,!1))||n.type===`BlockStatement`&&n.body.slice(0,n.body.indexOf(e)).some(e=>c(e,r,i))?!0:o(n,n.parent)};return o(e,e.parent)},u={meta:{type:`problem`,docs:{description:`Disallow a throwing extractor (.orThrow(), .getOrThrow()) in a React component or hook body`,recommended:!1},schema:[{type:`object`,properties:{allowInteropMarker:{type:`boolean`,default:!0}},additionalProperties:!1}],messages:{throwInRender:`{{receiver}}.{{method}}() throws during render when the value is missing, and a throw in render unmounts the tree up to the nearest error boundary. Render both cases with .fold(…) or <MatchOption> / <MatchEither> / <MatchTry>, or read a fallback with .orElse(…). To reach an error boundary on purpose, name the error: .orThrow((e) => new MyError(e))`}},create(n){let s=(n.options[0]||{}).allowInteropMarker!==!1,c=n.sourceCode;return{CallExpression(u){let d=u.callee;if(d.type!==`MemberExpression`||d.computed||d.property.type!==`Identifier`)return;let f=d.property.name;if(!o.has(f)||u.arguments.length>0)return;let p=r(u);if(!p||i(p)===null||a(d.object,n)===!1)return;let m=t(c.getText(d.object));l(u,p,m,c)||s&&e(u,`interop`,c)||n.report({node:u,messageId:`throwInRender`,data:{receiver:c.getText(d.object),method:f}})}}}};export{u as default};
|
|
2
|
+
//# sourceMappingURL=no-getOrThrow-in-render.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"no-getOrThrow-in-render.js","names":["THROWING_METHODS","exits","statement","continuesWithValue","provesWhen","receiverText","sourceCode","call","isGuarded","present","test","outcome","walk","node","stop","branch","child","rule","allowInteropMarker","context","callee","method","fn","enclosingFunction","renderKind","isExtractableByType","compact","isInsideTaggedDeclaration"],"sources":["../../src/rules/no-getOrThrow-in-render.ts"],"sourcesContent":["import type { Rule, SourceCode } from \"eslint\"\n\nimport type { ASTNode } from \"../types/ast\"\nimport { INTEROP_TAG, isInsideTaggedDeclaration } from \"../utils/boundary-tags\"\nimport { compact, provesWhen } from \"../utils/functype-predicates\"\nimport { enclosingFunction, renderKind } from \"../utils/react-render\"\nimport { isExtractableByType } from \"../utils/type-aware\"\n\n/**\n * The extractors that throw a generic error when the value is missing. `orThrow` is the one functype's\n * containers carry; `getOrThrow` is its older name, which the rule is named after. Each is reported only\n * bare: `orThrow(error)` names the error, the way to send a failure to an error boundary on purpose.\n * `expect(handler)` is never reported, because its handler is the chosen throw.\n */\nconst THROWING_METHODS: ReadonlySet<string> = new Set([\"orThrow\", \"getOrThrow\"])\n\n/** A statement that leaves the function: `return …`, `throw …`, or a block that ends in one. */\nconst exits = (statement: ASTNode): boolean =>\n statement.type === \"ReturnStatement\" ||\n statement.type === \"ThrowStatement\" ||\n (statement.type === \"BlockStatement\" && statement.body.length > 0 && exits(statement.body.at(-1)))\n\n/**\n * Does `statement` only let control continue past it once the value is known to be there?\n *\n * - an early exit on the missing case: `if (!o.isSome()) return null`, `if (busy || o.isNone()) return <S />`,\n * `if (o.isEmpty) throw …`;\n * - an if / else-if chain whose every branch exits, except the way out that proves it:\n * `if (x) return <B />; else if (o.isNone()) return null`;\n * - `invariant(o.isSome(), \"…\")` from functype, which narrows the code after it.\n */\nconst continuesWithValue = (statement: ASTNode, receiverText: string, sourceCode: SourceCode): boolean => {\n if (statement.type === \"IfStatement\") {\n if (!exits(statement.consequent)) return false\n if (provesWhen(statement.test, false, receiverText, sourceCode) === \"present\") return true\n return statement.alternate ? continuesWithValue(statement.alternate, receiverText, sourceCode) : false\n }\n const call = statement.type === \"ExpressionStatement\" ? statement.expression : null\n return (\n call?.type === \"CallExpression\" &&\n call.callee.type === \"Identifier\" &&\n call.callee.name === \"invariant\" &&\n call.arguments.length > 0 &&\n provesWhen(call.arguments[0], true, receiverText, sourceCode) === \"present\"\n )\n}\n\n/**\n * Is the call inside a branch that already proved the value is there? `o.isSome() ? o.orThrow() : …`,\n * `!o.isSome() ? null : o.orThrow()`, `if (e.isRight()) return e.orThrow()`, `t.isSuccess() && t.orThrow()`,\n * or after a statement in an enclosing block that only continues once it is (`continuesWithValue`). Then\n * the call cannot throw.\n */\nconst isGuarded = (call: ASTNode, stop: ASTNode, receiverText: string, sourceCode: SourceCode): boolean => {\n const present = (test: ASTNode, outcome: boolean): boolean =>\n provesWhen(test, outcome, receiverText, sourceCode) === \"present\"\n\n const walk = (child: ASTNode, node: ASTNode | undefined): boolean => {\n if (!node || node === stop) return false\n const branch = node.type === \"IfStatement\" || node.type === \"ConditionalExpression\"\n if (branch && node.consequent === child && present(node.test, true)) return true\n if (branch && node.alternate === child && present(node.test, false)) return true\n if (node.type === \"LogicalExpression\" && node.right === child) {\n if (node.operator === \"&&\" && present(node.left, true)) return true\n if (node.operator === \"||\" && present(node.left, false)) return true\n }\n if (node.type === \"BlockStatement\") {\n const before = (node.body as ReadonlyArray<ASTNode>).slice(0, node.body.indexOf(child))\n if (before.some((statement) => continuesWithValue(statement, receiverText, sourceCode))) return true\n }\n return walk(node, node.parent)\n }\n return walk(call, call.parent)\n}\n\nconst rule: Rule.RuleModule = {\n meta: {\n type: \"problem\",\n docs: {\n description: \"Disallow a throwing extractor (.orThrow(), .getOrThrow()) in a React component or hook body\",\n recommended: false,\n },\n schema: [\n {\n type: \"object\",\n properties: {\n allowInteropMarker: {\n type: \"boolean\",\n default: true,\n },\n },\n additionalProperties: false,\n },\n ],\n messages: {\n throwInRender:\n \"{{receiver}}.{{method}}() throws during render when the value is missing, and a throw in render unmounts the tree up to the nearest error boundary. Render both cases with .fold(…) or <MatchOption> / <MatchEither> / <MatchTry>, or read a fallback with .orElse(…). To reach an error boundary on purpose, name the error: .orThrow((e) => new MyError(e))\",\n },\n },\n\n create(context) {\n const options = context.options[0] || {}\n // `@interop <reason>` on an enclosing declaration marks a host contract, such as React's `use()`.\n const allowInteropMarker = options.allowInteropMarker !== false\n const sourceCode = context.sourceCode\n\n return {\n CallExpression(node: ASTNode) {\n const callee = node.callee as ASTNode\n if (callee.type !== \"MemberExpression\" || callee.computed || callee.property.type !== \"Identifier\") return\n const method = callee.property.name as string\n if (!THROWING_METHODS.has(method) || node.arguments.length > 0) return\n\n // Only the component's or hook's own body runs during render. An event handler, an effect or a\n // `.map` callback is a separate function, so a call there is not attributed to the render.\n const fn = enclosingFunction(node)\n if (!fn || renderKind(fn) === null) return\n\n // With type information the receiver must be a functype container (it has `orThrow` and `fold`);\n // without it, the method name decides — `orThrow()` is functype's own spelling.\n if (isExtractableByType(callee.object, context) === false) return\n const receiverText = compact(sourceCode.getText(callee.object))\n if (isGuarded(node, fn, receiverText, sourceCode)) return\n if (allowInteropMarker && isInsideTaggedDeclaration(node, INTEROP_TAG, sourceCode)) return\n\n context.report({\n node,\n messageId: \"throwInRender\",\n data: { receiver: sourceCode.getText(callee.object), method },\n })\n },\n }\n },\n}\n\nexport default rule\n"],"mappings":"A,0RAcA,MAAMA,kBAAwC,IAAI,IAAI,CAAC,UAAW,YAAY,CAAC,EAGzEC,EAAS,GACbC,EAAU,OAAS,mBACnBA,EAAU,OAAS,kBAClBA,EAAU,OAAS,kBAAoBA,EAAU,KAAK,OAAS,GAAKD,EAAMC,EAAU,KAAK,GAAG,EAAE,CAAC,EAW5FC,GAAsB,EAAoB,EAAsB,IAAoC,CACxG,GAAID,EAAU,OAAS,cAGrB,OAFKD,EAAMC,EAAU,UAAU,EAC3BE,EAAWF,EAAU,KAAM,GAAOG,EAAcC,CAAU,IAAM,UAAkB,GAC/EJ,EAAU,UAAYC,EAAmBD,EAAU,UAAWG,EAAcC,CAAU,EAAI,GAFxD,GAI3C,IAAMC,EAAOL,EAAU,OAAS,sBAAwBA,EAAU,WAAa,KAC/E,OACEK,GAAM,OAAS,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MAAO,CACL,eAAe,EAAe,CAC5B,IAAMC,EAASP,EAAK,OACpB,GAAIO,EAAO,OAAS,oBAAsBA,EAAO,UAAYA,EAAO,SAAS,OAAS,aAAc,OACpG,IAAMC,EAASD,EAAO,SAAS,KAC/B,GAAI,CAACpB,EAAiB,IAAIqB,CAAM,GAAKR,EAAK,UAAU,OAAS,EAAG,OAIhE,IAAMS,EAAKC,EAAkBV,CAAI,EAKjC,GAJI,CAACS,GAAME,EAAWF,CAAE,IAAM,MAI1BG,EAAoBL,EAAO,OAAQD,CAAO,IAAM,GAAO,OAC3D,IAAMd,EAAeqB,EAAQpB,EAAW,QAAQc,EAAO,MAAM,CAAC,EAC1DZ,EAAUK,EAAMS,EAAIjB,EAAcC,CAAU,GAC5CY,GAAsBS,EAA0Bd,EAAA,UAAmBP,CAAU,GAEjFa,EAAQ,OAAO,CACb,OACA,UAAW,gBACX,KAAM,CAAE,SAAUb,EAAW,QAAQc,EAAO,MAAM,EAAG,QAAO,CAC9D,CAAC,CACH,CACF,CACF,CACF,E"}
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import{containsAwait as e,containsYield as t}from"../utils/async-detection.js";const n={meta:{type:`suggestion`,
|
|
1
|
+
import{containsAwait as e,containsYield as t}from"../utils/async-detection.js";const n={meta:{type:`suggestion`,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:`Replace this for loop with the method for what it does: .map/.filter/.flatMap to build a new collection, .reduce (List: .foldLeft) to accumulate, .find/.some (List: .exists) to stop at a match. Need the index? array.map((x, i) => ...) or List(xs).zipWithIndex()`,noForInLoop:`Replace this for..in with Object.entries/keys/values(obj) and the method for what it does: .map/.filter to build, .reduce to accumulate. for..in also visits inherited enumerable keys`,noForOfLoop:`Replace this for..of with the method for what it does: .map/.filter/.flatMap to build a new collection, .reduce (List: .foldLeft) to accumulate, .find/.some (List: .exists) to stop at a match. Use .forEach only for side effects. On a Set, Map, string or generator, spread it to an array first or wrap it in List(...)`,noAsyncLoop:`This loop awaits, which .forEach()/.map() cannot do. To await in order use List(items).mapAsync(f), or Either.traverseAsync(items, f) when f returns Either (stops at the first Left). Inside IO, use IO.forEach(items, f)`,noWhileLoop:`Prefer functional iteration or recursion over while loops`,noDoWhileLoop:`Prefer functional iteration or recursion over do..while loops`}},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.type===`ForOfStatement`&&e.await===!0||t(e.body)}return{ForStatement(t){l(t)||o&&s()||i&&c(t)||(e(t.body)?n.report({node:t,messageId:`noAsyncLoop`}):n.report({node:t,messageId:`noForLoop`}))},ForInStatement(t){l(t)||o&&s()||(e(t.body)?n.report({node:t,messageId:`noAsyncLoop`}):n.report({node:t,messageId:`noForInLoop`}))},ForOfStatement(t){l(t)||o&&s()||(e(t.body)?n.report({node:t,messageId:`noAsyncLoop`}):n.report({node:t,messageId:`noForOfLoop`}))},WhileStatement(e){l(e)||a||o&&s()||n.report({node:e,messageId:`noWhileLoop`})},DoWhileStatement(e){l(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":["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:\n \"Replace this for loop with the method for what it does: .map/.filter/.flatMap to build a new collection, .reduce (List: .foldLeft) to accumulate, .find/.some (List: .exists) to stop at a match. Need the index? array.map((x, i) => ...) or List(xs).zipWithIndex()\",\n noForInLoop:\n \"Replace this for..in with Object.entries/keys/values(obj) and the method for what it does: .map/.filter to build, .reduce to accumulate. for..in also visits inherited enumerable keys\",\n noForOfLoop:\n \"Replace this for..of with the method for what it does: .map/.filter/.flatMap to build a new collection, .reduce (List: .foldLeft) to accumulate, .find/.some (List: .exists) to stop at a match. Use .forEach only for side effects. On a Set, Map, string or generator, spread it to an array first or wrap it in List(...)\",\n noAsyncLoop:\n \"This loop awaits, which .forEach()/.map() cannot do. To await in order use List(items).mapAsync(f), or Either.traverseAsync(items, f) when f returns Either (stops at the first Left). Inside IO, use IO.forEach(items, f)\",\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 async-traversal 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,UACE,wQACF,YACE,yLACF,YACE,+TACF,YACE,6NACF,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,CAC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AAK,KAAK,EACzB,CACA,IAAMW,EAAalB,EAAQ,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
|
+
{"version":3,"file":"no-imperative-loops.js","names":["rule","options","context","allowForIndexAccess","allowWhileLoops","allowInTests","isInTestFile","filename","needsIndexAccess","node","bodyText","hasNoFunctionalEquivalent","containsYield","containsAwait"],"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 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:\n \"Replace this for loop with the method for what it does: .map/.filter/.flatMap to build a new collection, .reduce (List: .foldLeft) to accumulate, .find/.some (List: .exists) to stop at a match. Need the index? array.map((x, i) => ...) or List(xs).zipWithIndex()\",\n noForInLoop:\n \"Replace this for..in with Object.entries/keys/values(obj) and the method for what it does: .map/.filter to build, .reduce to accumulate. for..in also visits inherited enumerable keys\",\n noForOfLoop:\n \"Replace this for..of with the method for what it does: .map/.filter/.flatMap to build a new collection, .reduce (List: .foldLeft) to accumulate, .find/.some (List: .exists) to stop at a match. Use .forEach only for side effects. On a Set, Map, string or generator, spread it to an array first or wrap it in List(...)\",\n noAsyncLoop:\n \"This loop awaits, which .forEach()/.map() cannot do. To await in order use List(items).mapAsync(f), or Either.traverseAsync(items, f) when f returns Either (stops at the first Left). Inside IO, use IO.forEach(items, f)\",\n noWhileLoop: \"Prefer functional iteration or recursion over while loops\",\n noDoWhileLoop: \"Prefer functional iteration or recursion over do..while loops\",\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 /**\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 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 context.report({\n node,\n messageId: \"noForInLoop\",\n })\n },\n\n ForOfStatement(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 context.report({\n node,\n messageId: \"noForOfLoop\",\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":"A,+EAKA,MAAMA,EAAwB,CAC5B,KAAM,CACJ,KAAM,aACN,KAAM,CACJ,YAAa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BJ,GAAgBC,EAAa,IAE7BO,EAAcJ,EAAK,IAAI,EACzBP,EAAQ,OAAO,CAAE,OAAM,UAAW,aAAc,CAAC,EAInDA,EAAQ,OAAO,CACb,OACA,UAAW,aACb,CAAC,EACH,EAEA,eAAe,EAAe,CACxBS,EAA0BF,CAAI,GAC9BJ,GAAgBC,EAAa,IAE7BO,EAAcJ,EAAK,IAAI,EACzBP,EAAQ,OAAO,CAAE,OAAM,UAAW,aAAc,CAAC,EAInDA,EAAQ,OAAO,CACb,OACA,UAAW,aACb,CAAC,EACH,EAEA,eAAe,EAAe,CACxBS,EAA0BF,CAAI,GAC9BL,GACAC,GAAgBC,EAAa,GAEjCJ,EAAQ,OAAO,CACb,OACA,UAAW,aACb,CAAC,CACH,EAEA,iBAAiB,EAAe,CAC1BS,EAA0BF,CAAI,GAC9BL,GACAC,GAAgBC,EAAa,GAEjCJ,EAAQ,OAAO,CACb,OACA,UAAW,eACb,CAAC,CACH,CACF,CACF,CACF,E"}
|
package/dist/rules/no-let.d.ts
CHANGED
package/dist/rules/no-let.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
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
|
+
{"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,E"}
|
|
@@ -1 +1 @@
|
|
|
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,CAOA,SAASC,EAAY,EAAmC,CACtD,OAAO,OAAO,QAAQF,CAAI,CAAC,CACxB,QAAQ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AoB,EAAqB,CAChD,GAAI,CAACC,EAAoBhC,EAAM,SAAS,EAAG,OAE3C,IAAMiC,EAAatB,EAAcX,CAAI,EAEjCiC,GAAcZ,GAChBD,EAAQ,OAAO,CACb,OACA,UAAW,4BACX,KAAM,CAAE,MAAOa,EAAW,SAAS,CAAE,EACrC,IAAKR,EAAe,GAAUS,EAAkBL,EAAO7B,CAAI,EAAI,IAAA,EACjE,CAAC,CAEL,CAKA,SAAS4B,EAAgB,EAAuB,EAAyB,CACvE,IAAMO,EAAOf,EAAQ,WAAW,QAAQpB,CAAI,EAItCoC,EAAQD,EAAK,MAAM,eAAe,EACxC,GAAIC,EAAO,CACT,IAAMC,EAAUD,EAAM,GAGhBE,EAAa;gCACKD,EAAQ;8BAHlBD,EAAM,EAIO,CAAC,UAAUC,EAAQ,MAAM,EAAE;IAGtD,OAAOR,EAAM,YAAY7B,EAAMsC,CAAU,CAC3C,CAEA,OAAOT,EAAM,YAAY7B,EAAM,sCAAsCmC,GAAM,CAC7E,CAKA,SAASD,EAAkB,EAAuB,EAAyB,CACzE,IAAMC,EAAOf,EAAQ,WAAW,QAAQpB,CAAI,EAG5C,OAAO6B,EAAM,YAAY7B,EAAM,uDAAuDmC,GAAM,CAC9F,CAuBA,SAASI,EAAiB,EAAqB,CACxCjB,GAKAP,EAAmBf,CAAI,GACxBK,EAASL,CAAI,CAAC,CAAC,MAAQ,GACzBoB,EAAQ,OAAO,CAAE,OAAM,UAAW,wBAAyB,CAAC,CAEhE,CAEA,MAAO,CACL,kBAAkB,EAAM,CACtBM,EAAsB1B,CAAI,CAC5B,EAEA,eAAe,EAAM,CACnB+B,EAAoB/B,CAAI,EACxBuC,EAAiBvC,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":"A,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,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5B,EAEA,eAAe,EAAM,CACnB+B,EAAoB/B,CAAI,EACxBuC,EAAiBvC,CAAI,CACvB,CACF,CACF,CACF,E"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"prefer-either.js","names":["insideCatchClause","parent","node","rule","options","context","allowInteropMarker","isExemptByMarker","isInsideTaggedDeclaration","allowThrowInTests","isInTestFile","filename","enclosingFunction","isFunctionLike","nonEitherReturnType","returnType","fn","text","isDirectInFunctionBody","ifParent","sourceCode","suggest","throwArg","argText","eitherArg","fixer","hasFunctypeSymbol","createImportFixer"],"sources":["../../src/rules/prefer-either.ts"],"sourcesContent":["import type { Rule } from \"eslint\"\n\nimport type { ASTNode } from \"../types/ast\"\nimport { INTEROP_TAG, isInsideTaggedDeclaration } from \"../utils/boundary-tags\"\nimport { createImportFixer, hasFunctypeSymbol } from \"../utils/import-fixer\"\n\n/** True iff any ancestor of `node` is a `CatchClause`. Pure tail recursion. */\nfunction insideCatchClause(node: ASTNode | null | undefined): boolean {\n const parent = node?.parent as ASTNode | undefined\n if (!parent) return false\n return parent.type === \"CatchClause\" || insideCatchClause(parent)\n}\n\nconst rule: Rule.RuleModule = {\n meta: {\n type: \"suggestion\",\n hasSuggestions: true,\n docs: {\n description: \"Use Either/Left/Right for typed domain errors instead of throwing\",\n recommended: true,\n },\n schema: [\n {\n type: \"object\",\n properties: {\n allowInteropMarker: {\n type: \"boolean\",\n default: true,\n },\n allowThrowInTests: {\n type: \"boolean\",\n default: true,\n },\n },\n additionalProperties: false,\n },\n ],\n messages: {\n preferEitherOverThrow:\n \"Prefer Either.left(error) over throw statement. For a bug check use invariant(); for a host that needs the throw, tag the function @interop\",\n preferEitherReturn:\n \"Consider returning Either<Error, {{type}}> instead of throwing. For a bug check use invariant(); for a host that needs the throw, tag the function @interop\",\n suggestEitherLeft: \"Replace with Either.left(...)\",\n suggestAddImport: \"Add {{symbol}} import from functype\",\n },\n },\n\n create(context) {\n const options = context.options[0] || {}\n // `@interop <reason>` on an enclosing declaration marks a host-contract boundary (#241).\n const allowInteropMarker = options.allowInteropMarker !== false\n // Bug checks are `invariant()` calls from functype (#342): a call, not a throw, so nothing to exempt.\n const isExemptByMarker = (node: ASTNode): boolean =>\n allowInteropMarker && isInsideTaggedDeclaration(node, INTEROP_TAG, context.sourceCode)\n const allowThrowInTests = options.allowThrowInTests !== 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 /** The nearest function the throw belongs to — a nested function owns its own throws. */\n function enclosingFunction(node: ASTNode): ASTNode | null {\n const parent = node.parent\n if (!parent) return null\n return isFunctionLike(parent) ? parent : enclosingFunction(parent)\n }\n\n /** The declared return type when the function declares one that is not already an Either. */\n function nonEitherReturnType(fn: ASTNode | null): string | null {\n const returnType = fn?.returnType?.typeAnnotation\n if (!returnType) return null\n const text = context.sourceCode.getText(returnType)\n return text.includes(\"Either\") ? null : text\n }\n\n function isFunctionLike(node: ASTNode): boolean {\n if (!node) return false\n return [\"FunctionDeclaration\", \"FunctionExpression\", \"ArrowFunctionExpression\"].includes(node.type)\n }\n\n function isDirectInFunctionBody(node: ASTNode): boolean {\n const parent = node.parent\n if (!parent) return false\n if (parent.type === \"BlockStatement\" && isFunctionLike(parent.parent)) return true\n if (parent.type === \"BlockStatement\" && parent.parent?.type === \"IfStatement\") {\n const ifParent = parent.parent.parent\n return ifParent?.type === \"BlockStatement\" && isFunctionLike(ifParent.parent)\n }\n return false\n }\n\n return {\n ThrowStatement(node: ASTNode) {\n if (isExemptByMarker(node)) return\n // Allow throws in test files if configured\n if (allowThrowInTests && isInTestFile()) return\n\n // Allow re-throwing in catch blocks (common pattern)\n if (insideCatchClause(node)) return\n\n const sourceCode = context.sourceCode\n const suggest: Rule.SuggestionReportDescriptor[] = []\n\n if (isDirectInFunctionBody(node)) {\n const throwArg = node.argument\n const argText = sourceCode.getText(throwArg)\n const isErrorExpr =\n throwArg?.type === \"NewExpression\" &&\n throwArg.callee?.type === \"Identifier\" &&\n throwArg.callee.name === \"Error\"\n const eitherArg = isErrorExpr ? argText : `new Error(String(${argText}))`\n\n suggest.push({\n messageId: \"suggestEitherLeft\",\n fix(fixer) {\n return fixer.replaceText(node, `return Either.left(${eitherArg})`)\n },\n })\n\n if (!hasFunctypeSymbol(sourceCode, \"Either\")) {\n suggest.push({\n messageId: \"suggestAddImport\",\n data: { symbol: \"Either\" },\n fix: createImportFixer(sourceCode, \"Either\"),\n })\n }\n }\n\n // One report per throw (#324). When the enclosing function declares a non-Either return type,\n // the message names the Either it should return instead of reporting the function separately.\n const returnType = nonEitherReturnType(enclosingFunction(node))\n context.report({\n node,\n ...(returnType === null\n ? { messageId: \"preferEitherOverThrow\" }\n : { messageId: \"preferEitherReturn\", data: { type: returnType } }),\n suggest,\n })\n },\n }\n },\n}\n\nexport default rule\n"],"mappings":"0JAOA,SAASA,EAAkB,EAA2C,CACpE,IAAMC,EAASC,GAAM,OAErB,OADKD,EACEA,EAAO,OAAS,eAAiBD,EAAkBC,CAAM,EAD5C,EAEtB,CAEA,MAAME,EAAwB,CAC5B,KAAM,CACJ,KAAM,aACN,eAAgB,GAChB,KAAM,CACJ,YAAa,oEACb,YAAa,EACf,EACA,OAAQ,CACN,CACE,KAAM,SACN,WAAY,CACV,mBAAoB,CAClB,KAAM,UACN,QAAS,EACX,EACA,kBAAmB,CACjB,KAAM,UACN,QAAS,EACX,CACF,EACA,qBAAsB,EACxB,CACF,EACA,SAAU,CACR,sBACE,8IACF,mBACE,8JACF,kBAAmB,gCACnB,iBAAkB,qCACpB,CACF,EAEA,OAAO,EAAS,CACd,IAAMC,EAAUC,EAAQ,QAAQ,IAAM,CAAC,EAEjCC,EAAqBF,EAAQ,qBAAuB,GAEpDG,EAAoB,GACxBD,GAAsBE,EAA0BN,EAAA,UAAmBG,EAAQ,UAAU,EACjFI,EAAoBL,E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AAS,iBACnBA,EAAS,QAAQ,OAAS,cAC1BA,EAAS,OAAO,OAAS,QACKC,EAAU,oBAAoBA,EAAQ,IAEtEF,EAAQ,KAAK,CACX,UAAW,oBACX,IAAI,EAAO,CACT,OAAOI,EAAM,YAAYvB,EAAM,sBAAsBsB,EAAU,EAAE,CACnE,CACF,CAAC,EAEIE,EAAkBN,EAAY,QAAQ,GACzCC,EAAQ,KAAK,CACX,UAAW,mBACX,KAAM,CAAE,OAAQ,QAAS,EACzB,IAAKM,EAAkBP,EAAY,QAAQ,CAC7C,CAAC,CAEL,CAIA,IAAML,EAAaD,EAAoBF,EAAkBV,CAAI,CAAC,EAC9DG,EAAQ,OAAO,CACb,OACA,GAAIU,IAAe,KACf,CAAE,UAAW,uBAAwB,EACrC,CAAE,UAAW,qBAAsB,KAAM,CAAE,KAAMA,CAAW,CAAE,EAClE,SACF,CAAC,CACH,CACF,CACF,CACF"}
|
|
1
|
+
{"version":3,"file":"prefer-either.js","names":["insideCatchClause","parent","node","rule","options","context","allowInteropMarker","isExemptByMarker","isInsideTaggedDeclaration","allowThrowInTests","isInTestFile","filename","enclosingFunction","isFunctionLike","nonEitherReturnType","returnType","fn","text","isDirectInFunctionBody","ifParent","sourceCode","suggest","throwArg","argText","eitherArg","fixer","hasFunctypeSymbol","createImportFixer"],"sources":["../../src/rules/prefer-either.ts"],"sourcesContent":["import type { Rule } from \"eslint\"\n\nimport type { ASTNode } from \"../types/ast\"\nimport { INTEROP_TAG, isInsideTaggedDeclaration } from \"../utils/boundary-tags\"\nimport { createImportFixer, hasFunctypeSymbol } from \"../utils/import-fixer\"\n\n/** True iff any ancestor of `node` is a `CatchClause`. Pure tail recursion. */\nfunction insideCatchClause(node: ASTNode | null | undefined): boolean {\n const parent = node?.parent as ASTNode | undefined\n if (!parent) return false\n return parent.type === \"CatchClause\" || insideCatchClause(parent)\n}\n\nconst rule: Rule.RuleModule = {\n meta: {\n type: \"suggestion\",\n hasSuggestions: true,\n docs: {\n description: \"Use Either/Left/Right for typed domain errors instead of throwing\",\n recommended: true,\n },\n schema: [\n {\n type: \"object\",\n properties: {\n allowInteropMarker: {\n type: \"boolean\",\n default: true,\n },\n allowThrowInTests: {\n type: \"boolean\",\n default: true,\n },\n },\n additionalProperties: false,\n },\n ],\n messages: {\n preferEitherOverThrow:\n \"Prefer Either.left(error) over throw statement. For a bug check use invariant(); for a host that needs the throw, tag the function @interop\",\n preferEitherReturn:\n \"Consider returning Either<Error, {{type}}> instead of throwing. For a bug check use invariant(); for a host that needs the throw, tag the function @interop\",\n suggestEitherLeft: \"Replace with Either.left(...)\",\n suggestAddImport: \"Add {{symbol}} import from functype\",\n },\n },\n\n create(context) {\n const options = context.options[0] || {}\n // `@interop <reason>` on an enclosing declaration marks a host-contract boundary (#241).\n const allowInteropMarker = options.allowInteropMarker !== false\n // Bug checks are `invariant()` calls from functype (#342): a call, not a throw, so nothing to exempt.\n const isExemptByMarker = (node: ASTNode): boolean =>\n allowInteropMarker && isInsideTaggedDeclaration(node, INTEROP_TAG, context.sourceCode)\n const allowThrowInTests = options.allowThrowInTests !== 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 /** The nearest function the throw belongs to — a nested function owns its own throws. */\n function enclosingFunction(node: ASTNode): ASTNode | null {\n const parent = node.parent\n if (!parent) return null\n return isFunctionLike(parent) ? parent : enclosingFunction(parent)\n }\n\n /** The declared return type when the function declares one that is not already an Either. */\n function nonEitherReturnType(fn: ASTNode | null): string | null {\n const returnType = fn?.returnType?.typeAnnotation\n if (!returnType) return null\n const text = context.sourceCode.getText(returnType)\n return text.includes(\"Either\") ? null : text\n }\n\n function isFunctionLike(node: ASTNode): boolean {\n if (!node) return false\n return [\"FunctionDeclaration\", \"FunctionExpression\", \"ArrowFunctionExpression\"].includes(node.type)\n }\n\n function isDirectInFunctionBody(node: ASTNode): boolean {\n const parent = node.parent\n if (!parent) return false\n if (parent.type === \"BlockStatement\" && isFunctionLike(parent.parent)) return true\n if (parent.type === \"BlockStatement\" && parent.parent?.type === \"IfStatement\") {\n const ifParent = parent.parent.parent\n return ifParent?.type === \"BlockStatement\" && isFunctionLike(ifParent.parent)\n }\n return false\n }\n\n return {\n ThrowStatement(node: ASTNode) {\n if (isExemptByMarker(node)) return\n // Allow throws in test files if configured\n if (allowThrowInTests && isInTestFile()) return\n\n // Allow re-throwing in catch blocks (common pattern)\n if (insideCatchClause(node)) return\n\n const sourceCode = context.sourceCode\n const suggest: Rule.SuggestionReportDescriptor[] = []\n\n if (isDirectInFunctionBody(node)) {\n const throwArg = node.argument\n const argText = sourceCode.getText(throwArg)\n const isErrorExpr =\n throwArg?.type === \"NewExpression\" &&\n throwArg.callee?.type === \"Identifier\" &&\n throwArg.callee.name === \"Error\"\n const eitherArg = isErrorExpr ? argText : `new Error(String(${argText}))`\n\n suggest.push({\n messageId: \"suggestEitherLeft\",\n fix(fixer) {\n return fixer.replaceText(node, `return Either.left(${eitherArg})`)\n },\n })\n\n if (!hasFunctypeSymbol(sourceCode, \"Either\")) {\n suggest.push({\n messageId: \"suggestAddImport\",\n data: { symbol: \"Either\" },\n fix: createImportFixer(sourceCode, \"Either\"),\n })\n }\n }\n\n // One report per throw (#324). When the enclosing function declares a non-Either return type,\n // the message names the Either it should return instead of reporting the function separately.\n const returnType = nonEitherReturnType(enclosingFunction(node))\n context.report({\n node,\n ...(returnType === null\n ? { messageId: \"preferEitherOverThrow\" }\n : { messageId: \"preferEitherReturn\", data: { type: returnType } }),\n suggest,\n })\n },\n }\n },\n}\n\nexport default rule\n"],"mappings":"A,0JAOA,SAASA,EAAkB,EAA2C,CACpE,IAAMC,EAASC,GAAM,OAErB,OADKD,EACEA,EAAO,OAAS,eAAiBD,EAAkBC,CAAM,EAD5C,EAEtB,CAEA,MAAME,EAAwB,CAC5B,KAAM,CACJ,KAAM,aAC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E,GAAIA,EAAO,OAAS,kBAAoBA,EAAO,QAAQ,OAAS,cAAe,CAC7E,IAAMkB,EAAWlB,EAAO,OAAO,OAC/B,OAAOkB,GAAU,OAAS,kBAAoBN,EAAeM,EAAS,MAAM,CAC9E,CACA,MAAO,EACT,CAEA,MAAO,CACL,eAAe,EAAe,CAM5B,GALIZ,EAAiBL,CAAI,GAErBO,GAAqBC,EAAa,GAGlCV,EAAkBE,CAAI,EAAG,OAE7B,IAAMkB,EAAaf,EAAQ,WACrBgB,EAA6C,CAAC,EAEpD,GAAIH,EAAuBhB,CAAI,EAAG,CAChC,IAAMoB,EAAWpB,EAAK,SAChBqB,EAAUH,EAAW,QAAQE,CAAQ,EAKrCE,EAHJF,GAAU,OAAS,iBACnBA,EAAS,QAAQ,OAAS,cAC1BA,EAAS,OAAO,OAAS,QACKC,EAAU,oBAAoBA,EAAQ,IAEtEF,EAAQ,KAAK,CACX,UAAW,oBACX,IAAI,EAAO,CACT,OAAOI,EAAM,YAAYvB,EAAM,sBAAsBsB,EAAU,EAAE,CACnE,CACF,CAAC,EAEIE,EAAkBN,EAAY,QAAQ,GACzCC,EAAQ,KAAK,CACX,UAAW,mBACX,KAAM,CAAE,OAAQ,QAAS,EACzB,IAAKM,EAAkBP,EAAY,QAAQ,CAC7C,CAAC,CAEL,CAIA,IAAML,EAAaD,EAAoBF,EAAkBV,CAAI,CAAC,EAC9DG,EAAQ,OAAO,CACb,OACA,GAAIU,IAAe,KACf,CAAE,UAAW,uBAAwB,EACrC,CAAE,UAAW,qBAAsB,KAAM,CAAE,KAAMA,CAAW,CAAE,EAClE,SACF,CAAC,CACH,CACF,CACF,CACF,E"}
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
const e=/* @__PURE__ */ new Set([`map`,`filter`,`slice`,`concat`,`split`]),t={meta:{type:`suggestion`,docs:{description:`Prefer .flatMap() over .map().flat() and nested transformations`,recommended:!0},fixable:`code`,schema:[{type:`object`,properties:{checkNestedMaps:{type:`boolean`,default:!0}},additionalProperties:!1}],messages:{preferFlatMapOverMapFlat:`Use .flatMap() instead of .map().flat()`,preferFlatMapNested:`Consider .flatMap() for nested transformations that return arrays`,preferFlatMapChain:`Use .flatMap() instead of chained .map() operations that flatten results`}},create(t){let n=(t.options[0]||{}).checkNestedMaps!==!1;function r(e){if(e.type!==`CallExpression`)return!1;let t=e.callee;if(t.type!==`MemberExpression`)return!1;if(t.property.name===`flat`){let e=t.object;if(e.type===`CallExpression`&&e.callee.type===`MemberExpression`&&e.callee.property.name===`map`)return!0}return!1}function i(e){let t=e.elements??[];return!t.some(e=>e&&e.type===`SpreadElement`)&&t.some(e=>e&&e.type===`ArrayExpression`)}function a(e){return e.type===`CallExpression`?a(e.callee):e.type===`MemberExpression`?a(e.object):e.type===`ChainExpression`||e.type===`TSNonNullExpression`||e.type===`TSAsExpression`||e.type===`TSSatisfiesExpression`?a(e.expression):e}function o(e){return e?e.type===`Identifier`?[e.name]:e.type===`AssignmentPattern`?o(e.left):e.type===`RestElement`?o(e.argument):e.type===`ArrayPattern`?e.elements.flatMap(e=>o(e)):e.type===`ObjectPattern`?e.properties.flatMap(e=>e.type===`RestElement`?o(e.argument):o(e.value)):[]:[]}function s(e,t){let n=a(t);return n.type===`Identifier`&&e.params.flatMap(o).includes(n.name)}function c(t){if(!t||!t.body)return!1;if(t.body.type===`ArrayExpression`)return i(t.body);if(t.body.type===`CallExpression`){let n=t.body;if(s(t,n))return!1;if(n.callee.type===`MemberExpression`){let t=n.callee.property.name;if(e.has(t))return!0}}return t.body.type===`BlockStatement`&&t.body.body.some(e=>l(e)&&!(e.argument.type===`CallExpression`&&s(t,e.argument)))}function l(t){return t.type!==`ReturnStatement`||!t.argument?!1:t.argument.type===`ArrayExpression`?i(t.argument):!!(t.argument.type===`CallExpression`&&t.argument.callee.type===`MemberExpression`&&e.has(t.argument.callee.property.name))}function u(e){if(e.type!==`CallExpression`)return!1;let t=e.callee;if(t.type!==`MemberExpression`)return!1;if(t.property.name===`map`){let t=e.arguments[0];if(t&&(t.type===`ArrowFunctionExpression`||t.type===`FunctionExpression`))return c(t)}return!1}function d(e){let t=/* @__PURE__ */ new Set([`Option`,`Some`,`None`,`Either`,`Right`,`Left`,`Try`,`Success`,`Failure`,`Task`,`Ok`,`Err`,`IO`]);return!!(e.type===`CallExpression`&&e.callee?.type===`Identifier`&&t.has(e.callee.name)||e.type===`CallExpression`&&e.callee?.type===`MemberExpression`&&e.callee.object?.type===`Identifier`&&t.has(e.callee.object.name))}return{CallExpression(e){if(r(e)){let n=t.sourceCode;t.report({node:e,messageId:`preferFlatMapOverMapFlat`,fix(t){let r=e.callee.object,i=n.getText(r).replace(/\.map\s*\(/,`.flatMap(`);return t.replaceText(e,i)}})
|
|
1
|
+
const e=/* @__PURE__ */ new Set([`map`,`filter`,`slice`,`concat`,`split`]),t={meta:{type:`suggestion`,docs:{description:`Prefer .flatMap() over .map().flat() and nested transformations`,recommended:!0},fixable:`code`,schema:[{type:`object`,properties:{checkNestedMaps:{type:`boolean`,default:!0}},additionalProperties:!1}],messages:{preferFlatMapOverMapFlat:`Use .flatMap() instead of .map().flat()`,preferFlatMapNested:`Consider .flatMap() for nested transformations that return arrays`,preferFlatMapChain:`Use .flatMap() instead of chained .map() operations that flatten results`}},create(t){let n=(t.options[0]||{}).checkNestedMaps!==!1;function r(e){if(e.type!==`CallExpression`)return!1;let t=e.callee;if(t.type!==`MemberExpression`)return!1;if(t.property.name===`flat`){let e=t.object;if(e.type===`CallExpression`&&e.callee.type===`MemberExpression`&&e.callee.property.name===`map`)return!0}return!1}function i(e){let t=e.elements??[];return!t.some(e=>e&&e.type===`SpreadElement`)&&t.some(e=>e&&e.type===`ArrayExpression`)}function a(e){return e.type===`CallExpression`?a(e.callee):e.type===`MemberExpression`?a(e.object):e.type===`ChainExpression`||e.type===`TSNonNullExpression`||e.type===`TSAsExpression`||e.type===`TSSatisfiesExpression`?a(e.expression):e}function o(e){return e?e.type===`Identifier`?[e.name]:e.type===`AssignmentPattern`?o(e.left):e.type===`RestElement`?o(e.argument):e.type===`ArrayPattern`?e.elements.flatMap(e=>o(e)):e.type===`ObjectPattern`?e.properties.flatMap(e=>e.type===`RestElement`?o(e.argument):o(e.value)):[]:[]}function s(e,t){let n=a(t);return n.type===`Identifier`&&e.params.flatMap(o).includes(n.name)}function c(t){if(!t||!t.body)return!1;if(t.body.type===`ArrayExpression`)return i(t.body);if(t.body.type===`CallExpression`){let n=t.body;if(s(t,n))return!1;if(n.callee.type===`MemberExpression`){let t=n.callee.property.name;if(e.has(t))return!0}}return t.body.type===`BlockStatement`&&t.body.body.some(e=>l(e)&&!(e.argument.type===`CallExpression`&&s(t,e.argument)))}function l(t){return t.type!==`ReturnStatement`||!t.argument?!1:t.argument.type===`ArrayExpression`?i(t.argument):!!(t.argument.type===`CallExpression`&&t.argument.callee.type===`MemberExpression`&&e.has(t.argument.callee.property.name))}function u(e){if(e.type!==`CallExpression`)return!1;let t=e.callee;if(t.type!==`MemberExpression`)return!1;if(t.property.name===`map`){let t=e.arguments[0];if(t&&(t.type===`ArrowFunctionExpression`||t.type===`FunctionExpression`))return c(t)}return!1}function d(e){let t=/* @__PURE__ */ new Set([`Option`,`Some`,`None`,`Either`,`Right`,`Left`,`Try`,`Success`,`Failure`,`Task`,`Ok`,`Err`,`IO`]);return!!(e.type===`CallExpression`&&e.callee?.type===`Identifier`&&t.has(e.callee.name)||e.type===`CallExpression`&&e.callee?.type===`MemberExpression`&&e.callee.object?.type===`Identifier`&&t.has(e.callee.object.name))}return{CallExpression(e){if(r(e)){let n=t.sourceCode;t.report({node:e,messageId:`preferFlatMapOverMapFlat`,fix(t){let r=e.callee.object,i=n.getText(r).replace(/\.map\s*\(/,`.flatMap(`);return t.replaceText(e,i)}})}else{if(e.callee.type===`MemberExpression`&&e.callee.property.name===`map`){let n=e.callee.object;if(n.type===`CallExpression`&&n.callee.type===`MemberExpression`&&n.callee.property.name===`map`){let e=n.arguments[0];if(e&&c(e)){t.report({node:n,messageId:`preferFlatMapChain`});return}}}if(n&&u(e)){if(e.parent&&e.parent.type===`MemberExpression`&&e.parent.parent&&e.parent.parent.type===`CallExpression`&&e.parent.property.name===`flat`)return;let n=e.callee?.object;if(n?.type===`CallExpression`&&n.callee?.type===`MemberExpression`&&n.callee?.property?.name===`map`||e.parent?.type===`MemberExpression`&&e.parent.parent?.type===`CallExpression`&&e.parent.parent.callee?.property?.name===`map`||n&&d(n))return;t.report({node:e,messageId:`preferFlatMapNested`})}}}}}};export{t as default};
|
|
2
2
|
//# sourceMappingURL=prefer-flatmap.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"prefer-flatmap.js","names":["ARRAY_PRODUCING_METHODS","rule","checkNestedMaps","context","isMapFollowedByFlat","node","callee","object","isFlattenCandidateArrayLiteral","elements","arrayExpr","el","chainRoot","boundNames","param","prop","isShapePreserving","root","returned","functionNode","returnsArray","call","methodName","returnsArrayShape","stmt","isNestedMapReturningArrays","callback","isNonCollectionMonadReceiver","monadConstructors","sourceCode","mapCall","flatMapText","fixer","firstMapCallback"],"sources":["../../src/rules/prefer-flatmap.ts"],"sourcesContent":["import type { Rule } from \"eslint\"\n\nimport type { ASTNode } from \"../types/ast\"\n\n/** Array-prototype methods whose call expression always returns an array. */\nconst ARRAY_PRODUCING_METHODS: ReadonlySet<string> = new Set([\"map\", \"filter\", \"slice\", \"concat\", \"split\"])\n\nconst rule: Rule.RuleModule = {\n meta: {\n type: \"suggestion\",\n docs: {\n description: \"Prefer .flatMap() over .map().flat() and nested transformations\",\n recommended: true,\n },\n fixable: \"code\",\n schema: [\n {\n type: \"object\",\n properties: {\n checkNestedMaps: {\n type: \"boolean\",\n default: true,\n },\n },\n additionalProperties: false,\n },\n ],\n messages: {\n preferFlatMapOverMapFlat: \"Use .flatMap() instead of .map().flat()\",\n preferFlatMapNested: \"Consider .flatMap() for nested transformations that return arrays\",\n preferFlatMapChain: \"Use .flatMap() instead of chained .map() operations that flatten results\",\n },\n },\n\n create(context) {\n const options = context.options[0] || {}\n const checkNestedMaps = options.checkNestedMaps !== false\n\n function isMapFollowedByFlat(node: ASTNode): boolean {\n if (node.type !== \"CallExpression\") return false\n\n const callee = node.callee\n if (callee.type !== \"MemberExpression\") return false\n\n // Check if this is .flat()\n if (callee.property.name === \"flat\") {\n const object = callee.object\n\n // Check if the object is a .map() call\n if (\n object.type === \"CallExpression\" &&\n object.callee.type === \"MemberExpression\" &&\n object.callee.property.name === \"map\"\n ) {\n return true\n }\n }\n\n return false\n }\n\n /**\n * Heuristic for array literals that look like flatten candidates.\n * Skips append/identity patterns (`[...arr, x]`, `[...arr]`) and tuple\n * shapes (`[k, v]`) — those are not nested arrays, so .flatMap()\n * doesn't apply. Only flag when at least one element is itself an\n * ArrayExpression, signaling a true nested-array shape.\n */\n function isFlattenCandidateArrayLiteral(arrayExpr: ASTNode): boolean {\n const elements = arrayExpr.elements ?? []\n if (elements.some((el: ASTNode | null) => el && el.type === \"SpreadElement\")) {\n return false\n }\n return elements.some((el: ASTNode | null) => el && el.type === \"ArrayExpression\")\n }\n\n /**\n * The base identifier of a call/member chain: `members` in `members.filter(f).map(g)`, `r` in\n * `r.cells.map(f)`.\n */\n function chainRoot(node: ASTNode): ASTNode {\n if (node.type === \"CallExpression\") return chainRoot(node.callee)\n if (node.type === \"MemberExpression\") return chainRoot(node.object)\n if (\n node.type === \"ChainExpression\" ||\n node.type === \"TSNonNullExpression\" ||\n node.type === \"TSAsExpression\" ||\n node.type === \"TSSatisfiesExpression\"\n ) {\n return chainRoot(node.expression)\n }\n return node\n }\n\n /** Every name a parameter binds — plain, destructured, defaulted or rest. */\n function boundNames(param: ASTNode): ReadonlyArray<string> {\n if (!param) return []\n if (param.type === \"Identifier\") return [param.name]\n if (param.type === \"AssignmentPattern\") return boundNames(param.left)\n if (param.type === \"RestElement\") return boundNames(param.argument)\n if (param.type === \"ArrayPattern\") return param.elements.flatMap((el: ASTNode) => boundNames(el))\n if (param.type === \"ObjectPattern\") {\n return param.properties.flatMap((prop: ASTNode) =>\n prop.type === \"RestElement\" ? boundNames(prop.argument) : boundNames(prop.value),\n )\n }\n return []\n }\n\n /**\n * A callback that transforms its OWN element's array (`(r) => r.cells.map(f)`, `(s) => s.split(\" \")`,\n * `(xs) => xs.filter(p).map(g)`) keeps the shape: one array per element, a matrix, or an array inside\n * an Either/Option/Task being mapped. Nothing is being flattened, so .flatMap is not the fix (#324).\n */\n function isShapePreserving(functionNode: ASTNode, returned: ASTNode): boolean {\n const root = chainRoot(returned)\n return root.type === \"Identifier\" && functionNode.params.flatMap(boundNames).includes(root.name)\n }\n\n function returnsArray(functionNode: ASTNode): boolean {\n if (!functionNode || !functionNode.body) return false\n\n // Arrow function with expression body\n if (functionNode.body.type === \"ArrayExpression\") {\n return isFlattenCandidateArrayLiteral(functionNode.body)\n }\n\n // Arrow function with call expression body\n if (functionNode.body.type === \"CallExpression\") {\n const call = functionNode.body\n if (isShapePreserving(functionNode, call)) return false\n if (call.callee.type === \"MemberExpression\") {\n const methodName = call.callee.property.name\n // Common methods that return arrays\n if (ARRAY_PRODUCING_METHODS.has(methodName)) {\n return true\n }\n }\n }\n\n // Function with block body — any return statement returning an array shape?\n if (functionNode.body.type === \"BlockStatement\") {\n return functionNode.body.body.some(\n (stmt: ASTNode) =>\n returnsArrayShape(stmt) &&\n !(stmt.argument.type === \"CallExpression\" && isShapePreserving(functionNode, stmt.argument)),\n )\n }\n\n return false\n }\n\n /** A single statement that's `return <array-shaped-expression>`. */\n function returnsArrayShape(stmt: ASTNode): boolean {\n if (stmt.type !== \"ReturnStatement\" || !stmt.argument) return false\n if (stmt.argument.type === \"ArrayExpression\") return isFlattenCandidateArrayLiteral(stmt.argument)\n if (\n stmt.argument.type === \"CallExpression\" &&\n stmt.argument.callee.type === \"MemberExpression\" &&\n ARRAY_PRODUCING_METHODS.has(stmt.argument.callee.property.name)\n ) {\n return true\n }\n return false\n }\n\n function isNestedMapReturningArrays(node: ASTNode): boolean {\n if (node.type !== \"CallExpression\") return false\n\n const callee = node.callee\n if (callee.type !== \"MemberExpression\") return false\n\n // Check if this is .map()\n if (callee.property.name === \"map\") {\n const callback = node.arguments[0]\n if (callback && (callback.type === \"ArrowFunctionExpression\" || callback.type === \"FunctionExpression\")) {\n return returnsArray(callback)\n }\n }\n\n return false\n }\n\n /**\n * Skip the warning when the receiver (`.map`'s left side) is a known\n * non-collection monad constructor call. The rule has no type info, so\n * it can't tell `arr.map(cb => arr2)` (collection, .flatMap is the fix)\n * from `Try(...).map(cb => arr)` (non-collection — .flatMap on Try\n * expects Try<T>, not an array, so .flatMap is NOT the fix).\n *\n * We can't enumerate every non-collection receiver, but we *can* detect\n * the unambiguous case: the receiver is literally `Try(...)` /\n * `Option(...)` / `Either(...)` / `Right(...)` / `Left(...)` / etc.\n * When that holds, suppress the warning. For bare identifiers (`items`)\n * or array literals or array-method chains, we can't tell, so the rule\n * still fires as before.\n */\n function isNonCollectionMonadReceiver(node: ASTNode): boolean {\n const monadConstructors = new Set([\n \"Option\",\n \"Some\",\n \"None\",\n \"Either\",\n \"Right\",\n \"Left\",\n \"Try\",\n \"Success\",\n \"Failure\",\n \"Task\",\n \"Ok\",\n \"Err\",\n \"IO\",\n ])\n // Bare constructor: Try(...), Option(...), Right(x), etc.\n if (\n node.type === \"CallExpression\" &&\n node.callee?.type === \"Identifier\" &&\n monadConstructors.has(node.callee.name)\n ) {\n return true\n }\n // Companion call: Either.right(x), Option.none(), Try.success(v)\n if (\n node.type === \"CallExpression\" &&\n node.callee?.type === \"MemberExpression\" &&\n node.callee.object?.type === \"Identifier\" &&\n monadConstructors.has(node.callee.object.name)\n ) {\n return true\n }\n return false\n }\n\n return {\n CallExpression(node: ASTNode) {\n // Check for .map().flat() pattern first (highest priority)\n if (isMapFollowedByFlat(node)) {\n const sourceCode = context.sourceCode\n\n context.report({\n node,\n messageId: \"preferFlatMapOverMapFlat\",\n fix(fixer) {\n // Get the .map() call\n const mapCall = (node.callee as ASTNode).object\n const mapCallText = sourceCode.getText(mapCall)\n\n // Replace .map() with .flatMap() and remove .flat()\n const flatMapText = mapCallText.replace(/\\.map\\s*\\(/, \".flatMap(\")\n\n return fixer.replaceText(node, flatMapText)\n },\n })\n return // Don't check other patterns if we found .map().flat()\n }\n\n // Check for chained maps where intermediate results are arrays (highest priority after map().flat())\n if (node.callee.type === \"MemberExpression\" && node.callee.property.name === \"map\") {\n const object = node.callee.object\n if (\n object.type === \"CallExpression\" &&\n object.callee.type === \"MemberExpression\" &&\n object.callee.property.name === \"map\"\n ) {\n // Check if the first map returns arrays\n const firstMapCallback = object.arguments[0]\n if (firstMapCallback && returnsArray(firstMapCallback)) {\n context.report({\n node: object, // Report on the first map call\n messageId: \"preferFlatMapChain\",\n })\n return // Don't check other patterns for this chain\n }\n }\n }\n\n // Check for nested maps that return arrays (but not if they're part of map().flat() or chains)\n if (checkNestedMaps && isNestedMapReturningArrays(node)) {\n // Don't flag if this map is immediately followed by flat()\n if (\n node.parent &&\n node.parent.type === \"MemberExpression\" &&\n node.parent.parent &&\n node.parent.parent.type === \"CallExpression\" &&\n node.parent.property.name === \"flat\"\n ) {\n return // Skip - this will be handled by the map().flat() rule\n }\n\n // Don't flag if this map is part of a chain (either as first or second map)\n const object = node.callee?.object\n if (\n object?.type === \"CallExpression\" &&\n object.callee?.type === \"MemberExpression\" &&\n object.callee?.property?.name === \"map\"\n ) {\n return // Skip - this is part of a chain\n }\n\n // Check if this map feeds into another map\n if (\n node.parent?.type === \"MemberExpression\" &&\n node.parent.parent?.type === \"CallExpression\" &&\n node.parent.parent.callee?.property?.name === \"map\"\n ) {\n return // Skip - this feeds into a chain\n }\n\n // Don't flag when the receiver is a known non-collection monad\n // constructor — .flatMap on Try / Option / Either / etc. expects\n // a wrapped value, not an array, so suggesting it is wrong.\n if (object && isNonCollectionMonadReceiver(object)) {\n return\n }\n\n context.report({\n node,\n messageId: \"preferFlatMapNested\",\n })\n }\n },\n }\n },\n}\n\nexport default rule\n"],"mappings":"AAKA,MAAMA,kBAA+C,IAAI,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,EAAO,OAAS,kBAChBA,EAAO,OAAO,OAAS,oBACvBA,EAAO,OAAO,SAAS,OAAS,MAChC,CAEA,IAAM0B,EAAmB1B,EAAO,UAAU,GAC1C,GAAI0B,GAAoBb,EAAaa,CAAgB,EAAG,CACtD9B,EAAQ,OAAO,CACb,KAAMI,EACN,UAAW,oBACb,CAAC,EACD,MACF,CACF,CACF,CAGA,GAAIL,GAAmBuB,EAA2BpB,CAAI,EAAG,CAEvD,GACEA,EAAK,QACLA,EAAK,OAAO,OAAS,oBACrBA,EAAK,OAAO,QACZA,EAAK,OAAO,OAAO,OAAS,kBAC5BA,EAAK,OAAO,SAAS,OAAS,OAE9B,OAIF,IAAME,EAASF,EAAK,QAAQ,OAqB5B,GAnBEE,GAAQ,OAAS,kBACjBA,EAAO,QAAQ,OAAS,oBACxBA,EAAO,QAAQ,UAAU,OAAS,OAOlCF,EAAK,QAAQ,OAAS,oBACtBA,EAAK,OAAO,QAAQ,OAAS,kBAC7BA,EAAK,OAAO,OAAO,QAAQ,UAAU,OAAS,OAQ5CE,GAAUoB,EAA6BpB,CAAM,EAC/C,OAGFJ,EAAQ,OAAO,CACb,OACA,UAAW,qBACb,CAAC,CACH,CACF,CACF,CACF,CACF"}
|
|
1
|
+
{"version":3,"file":"prefer-flatmap.js","names":["ARRAY_PRODUCING_METHODS","rule","checkNestedMaps","context","isMapFollowedByFlat","node","callee","object","isFlattenCandidateArrayLiteral","elements","arrayExpr","el","chainRoot","boundNames","param","prop","isShapePreserving","root","returned","functionNode","returnsArray","call","methodName","returnsArrayShape","stmt","isNestedMapReturningArrays","callback","isNonCollectionMonadReceiver","monadConstructors","sourceCode","mapCall","flatMapText","fixer","firstMapCallback"],"sources":["../../src/rules/prefer-flatmap.ts"],"sourcesContent":["import type { Rule } from \"eslint\"\n\nimport type { ASTNode } from \"../types/ast\"\n\n/** Array-prototype methods whose call expression always returns an array. */\nconst ARRAY_PRODUCING_METHODS: ReadonlySet<string> = new Set([\"map\", \"filter\", \"slice\", \"concat\", \"split\"])\n\nconst rule: Rule.RuleModule = {\n meta: {\n type: \"suggestion\",\n docs: {\n description: \"Prefer .flatMap() over .map().flat() and nested transformations\",\n recommended: true,\n },\n fixable: \"code\",\n schema: [\n {\n type: \"object\",\n properties: {\n checkNestedMaps: {\n type: \"boolean\",\n default: true,\n },\n },\n additionalProperties: false,\n },\n ],\n messages: {\n preferFlatMapOverMapFlat: \"Use .flatMap() instead of .map().flat()\",\n preferFlatMapNested: \"Consider .flatMap() for nested transformations that return arrays\",\n preferFlatMapChain: \"Use .flatMap() instead of chained .map() operations that flatten results\",\n },\n },\n\n create(context) {\n const options = context.options[0] || {}\n const checkNestedMaps = options.checkNestedMaps !== false\n\n function isMapFollowedByFlat(node: ASTNode): boolean {\n if (node.type !== \"CallExpression\") return false\n\n const callee = node.callee\n if (callee.type !== \"MemberExpression\") return false\n\n // Check if this is .flat()\n if (callee.property.name === \"flat\") {\n const object = callee.object\n\n // Check if the object is a .map() call\n if (\n object.type === \"CallExpression\" &&\n object.callee.type === \"MemberExpression\" &&\n object.callee.property.name === \"map\"\n ) {\n return true\n }\n }\n\n return false\n }\n\n /**\n * Heuristic for array literals that look like flatten candidates.\n * Skips append/identity patterns (`[...arr, x]`, `[...arr]`) and tuple\n * shapes (`[k, v]`) — those are not nested arrays, so .flatMap()\n * doesn't apply. Only flag when at least one element is itself an\n * ArrayExpression, signaling a true nested-array shape.\n */\n function isFlattenCandidateArrayLiteral(arrayExpr: ASTNode): boolean {\n const elements = arrayExpr.elements ?? []\n if (elements.some((el: ASTNode | null) => el && el.type === \"SpreadElement\")) {\n return false\n }\n return elements.some((el: ASTNode | null) => el && el.type === \"ArrayExpression\")\n }\n\n /**\n * The base identifier of a call/member chain: `members` in `members.filter(f).map(g)`, `r` in\n * `r.cells.map(f)`.\n */\n function chainRoot(node: ASTNode): ASTNode {\n if (node.type === \"CallExpression\") return chainRoot(node.callee)\n if (node.type === \"MemberExpression\") return chainRoot(node.object)\n if (\n node.type === \"ChainExpression\" ||\n node.type === \"TSNonNullExpression\" ||\n node.type === \"TSAsExpression\" ||\n node.type === \"TSSatisfiesExpression\"\n ) {\n return chainRoot(node.expression)\n }\n return node\n }\n\n /** Every name a parameter binds — plain, destructured, defaulted or rest. */\n function boundNames(param: ASTNode): ReadonlyArray<string> {\n if (!param) return []\n if (param.type === \"Identifier\") return [param.name]\n if (param.type === \"AssignmentPattern\") return boundNames(param.left)\n if (param.type === \"RestElement\") return boundNames(param.argument)\n if (param.type === \"ArrayPattern\") return param.elements.flatMap((el: ASTNode) => boundNames(el))\n if (param.type === \"ObjectPattern\") {\n return param.properties.flatMap((prop: ASTNode) =>\n prop.type === \"RestElement\" ? boundNames(prop.argument) : boundNames(prop.value),\n )\n }\n return []\n }\n\n /**\n * A callback that transforms its OWN element's array (`(r) => r.cells.map(f)`, `(s) => s.split(\" \")`,\n * `(xs) => xs.filter(p).map(g)`) keeps the shape: one array per element, a matrix, or an array inside\n * an Either/Option/Task being mapped. Nothing is being flattened, so .flatMap is not the fix (#324).\n */\n function isShapePreserving(functionNode: ASTNode, returned: ASTNode): boolean {\n const root = chainRoot(returned)\n return root.type === \"Identifier\" && functionNode.params.flatMap(boundNames).includes(root.name)\n }\n\n function returnsArray(functionNode: ASTNode): boolean {\n if (!functionNode || !functionNode.body) return false\n\n // Arrow function with expression body\n if (functionNode.body.type === \"ArrayExpression\") {\n return isFlattenCandidateArrayLiteral(functionNode.body)\n }\n\n // Arrow function with call expression body\n if (functionNode.body.type === \"CallExpression\") {\n const call = functionNode.body\n if (isShapePreserving(functionNode, call)) return false\n if (call.callee.type === \"MemberExpression\") {\n const methodName = call.callee.property.name\n // Common methods that return arrays\n if (ARRAY_PRODUCING_METHODS.has(methodName)) {\n return true\n }\n }\n }\n\n // Function with block body — any return statement returning an array shape?\n if (functionNode.body.type === \"BlockStatement\") {\n return functionNode.body.body.some(\n (stmt: ASTNode) =>\n returnsArrayShape(stmt) &&\n !(stmt.argument.type === \"CallExpression\" && isShapePreserving(functionNode, stmt.argument)),\n )\n }\n\n return false\n }\n\n /** A single statement that's `return <array-shaped-expression>`. */\n function returnsArrayShape(stmt: ASTNode): boolean {\n if (stmt.type !== \"ReturnStatement\" || !stmt.argument) return false\n if (stmt.argument.type === \"ArrayExpression\") return isFlattenCandidateArrayLiteral(stmt.argument)\n if (\n stmt.argument.type === \"CallExpression\" &&\n stmt.argument.callee.type === \"MemberExpression\" &&\n ARRAY_PRODUCING_METHODS.has(stmt.argument.callee.property.name)\n ) {\n return true\n }\n return false\n }\n\n function isNestedMapReturningArrays(node: ASTNode): boolean {\n if (node.type !== \"CallExpression\") return false\n\n const callee = node.callee\n if (callee.type !== \"MemberExpression\") return false\n\n // Check if this is .map()\n if (callee.property.name === \"map\") {\n const callback = node.arguments[0]\n if (callback && (callback.type === \"ArrowFunctionExpression\" || callback.type === \"FunctionExpression\")) {\n return returnsArray(callback)\n }\n }\n\n return false\n }\n\n /**\n * Skip the warning when the receiver (`.map`'s left side) is a known\n * non-collection monad constructor call. The rule has no type info, so\n * it can't tell `arr.map(cb => arr2)` (collection, .flatMap is the fix)\n * from `Try(...).map(cb => arr)` (non-collection — .flatMap on Try\n * expects Try<T>, not an array, so .flatMap is NOT the fix).\n *\n * We can't enumerate every non-collection receiver, but we *can* detect\n * the unambiguous case: the receiver is literally `Try(...)` /\n * `Option(...)` / `Either(...)` / `Right(...)` / `Left(...)` / etc.\n * When that holds, suppress the warning. For bare identifiers (`items`)\n * or array literals or array-method chains, we can't tell, so the rule\n * still fires as before.\n */\n function isNonCollectionMonadReceiver(node: ASTNode): boolean {\n const monadConstructors = new Set([\n \"Option\",\n \"Some\",\n \"None\",\n \"Either\",\n \"Right\",\n \"Left\",\n \"Try\",\n \"Success\",\n \"Failure\",\n \"Task\",\n \"Ok\",\n \"Err\",\n \"IO\",\n ])\n // Bare constructor: Try(...), Option(...), Right(x), etc.\n if (\n node.type === \"CallExpression\" &&\n node.callee?.type === \"Identifier\" &&\n monadConstructors.has(node.callee.name)\n ) {\n return true\n }\n // Companion call: Either.right(x), Option.none(), Try.success(v)\n if (\n node.type === \"CallExpression\" &&\n node.callee?.type === \"MemberExpression\" &&\n node.callee.object?.type === \"Identifier\" &&\n monadConstructors.has(node.callee.object.name)\n ) {\n return true\n }\n return false\n }\n\n return {\n CallExpression(node: ASTNode) {\n // Check for .map().flat() pattern first (highest priority)\n if (isMapFollowedByFlat(node)) {\n const sourceCode = context.sourceCode\n\n context.report({\n node,\n messageId: \"preferFlatMapOverMapFlat\",\n fix(fixer) {\n // Get the .map() call\n const mapCall = (node.callee as ASTNode).object\n const mapCallText = sourceCode.getText(mapCall)\n\n // Replace .map() with .flatMap() and remove .flat()\n const flatMapText = mapCallText.replace(/\\.map\\s*\\(/, \".flatMap(\")\n\n return fixer.replaceText(node, flatMapText)\n },\n })\n return // Don't check other patterns if we found .map().flat()\n }\n\n // Check for chained maps where intermediate results are arrays (highest priority after map().flat())\n if (node.callee.type === \"MemberExpression\" && node.callee.property.name === \"map\") {\n const object = node.callee.object\n if (\n object.type === \"CallExpression\" &&\n object.callee.type === \"MemberExpression\" &&\n object.callee.property.name === \"map\"\n ) {\n // Check if the first map returns arrays\n const firstMapCallback = object.arguments[0]\n if (firstMapCallback && returnsArray(firstMapCallback)) {\n context.report({\n node: object, // Report on the first map call\n messageId: \"preferFlatMapChain\",\n })\n return // Don't check other patterns for this chain\n }\n }\n }\n\n // Check for nested maps that return arrays (but not if they're part of map().flat() or chains)\n if (checkNestedMaps && isNestedMapReturningArrays(node)) {\n // Don't flag if this map is immediately followed by flat()\n if (\n node.parent &&\n node.parent.type === \"MemberExpression\" &&\n node.parent.parent &&\n node.parent.parent.type === \"CallExpression\" &&\n node.parent.property.name === \"flat\"\n ) {\n return // Skip - this will be handled by the map().flat() rule\n }\n\n // Don't flag if this map is part of a chain (either as first or second map)\n const object = node.callee?.object\n if (\n object?.type === \"CallExpression\" &&\n object.callee?.type === \"MemberExpression\" &&\n object.callee?.property?.name === \"map\"\n ) {\n return // Skip - this is part of a chain\n }\n\n // Check if this map feeds into another map\n if (\n node.parent?.type === \"MemberExpression\" &&\n node.parent.parent?.type === \"CallExpression\" &&\n node.parent.parent.callee?.property?.name === \"map\"\n ) {\n return // Skip - this feeds into a chain\n }\n\n // Don't flag when the receiver is a known non-collection monad\n // constructor — .flatMap on Try / Option / Either / etc. expects\n // a wrapped value, not an array, so suggesting it is wrong.\n if (object && isNonCollectionMonadReceiver(object)) {\n return\n }\n\n context.report({\n node,\n messageId: \"preferFlatMapNested\",\n })\n }\n },\n }\n },\n}\n\nexport default rule\n"],"mappings":"AAKA,MAAMA,kBAA+C,IAAI,IAAI,CAAC,MAAO,SAAU,QAAS,SAAU,OAAO,CAAC,EAEpGC,EAAwB,CAC5B,KAAM,CACJ,KAAM,aACN,KAAM,CACJ,YAAa,kEACb,YAAa,EACf,EACA,QAAS,OACT,OAAQ,CACN,CACE,KAAM,SACN,WAAY,CACV,gBAAiB,CACf,KAAM,UACN,QAAS,EACX,CACF,EACA,qBAAsB,EACxB,CACF,EACA,SAAU,CACR,yBAA0B,0CAC1B,oBAAqB,oEACrB,mBAAoB,0EACtB,CACF,EAEA,OAAO,EAAS,CAEd,IAAMC,GADUC,EAAQ,QAAQ,IAAM,CAAC,EAAA,CACP,kBAAoB,GAEpD,SAASC,EAAoB,EAAwB,CACnD,GAAIC,EAAK,OAAS,iBAAkB,MAAO,GAE3C,IAAMC,EAASD,EAAK,OACpB,GAAIC,EAAO,OAAS,mBAAoB,MAAO,GAG/C,GAAIA,EAAO,SAAS,OAAS,OAAQ,CACnC,IAAMC,EAASD,EAAO,OAGtB,GACEC,EAAO,OAAS,kBAChBA,EAAO,OAAO,OAAS,oBACvBA,EAAO,OAAO,SAAS,OAAS,MAEhC,MAAO,EAEX,CAEA,MAAO,EACT,CASA,SAASC,EAA+B,EAA6B,CACnE,IAAMC,EAAWC,EAAU,UAAY,CAAC,EAIxC,MAHA,CAAID,EAAS,KAAM,GAAuBE,GAAMA,EAAG,OAA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boundary-tags.js";import{
|
|
1
|
+
import{isInsideTaggedDeclaration as e}from"../utils/boundary-tags.js";import{NEGATIVE_PREDICATES as t,POSITIVE_PREDICATES as n,compact as r}from"../utils/functype-predicates.js";import{childNodes as i,descendants as a}from"../utils/ast-walk.js";import{containsAwait as o}from"../utils/async-detection.js";const s={isSome:null,isNone:null,isRight:{param:`left`,member:`value`},isLeft:{param:`left`,member:`value`},isSuccess:{param:`error`,member:`error`},isFailure:{param:`error`,member:`error`}},c=[`get`,`orThrow`],l=`value`;function u(e){return e.type===`Literal`&&e.value===null||e.type===`Identifier`&&e.name===`undefined`}function d(e,r){if(e.type!==`CallExpression`||e.callee.type!==`MemberExpression`)return null;let i=e.callee.property.name,a=r.getText(e.callee.object),o=s[i]??null;return n.has(i)?{obj:a,isNegated:!1,failure:o}:t.has(i)?{obj:a,isNegated:!0,failure:o}:null}const f={members:[l],methods:c};function p(e,t,n,a){let o=e=>{let n=e.type===`TSNonNullExpression`?e.expression:e;return r(a.getText(n))===r(t)},s=(e,t)=>e.type===`MemberExpression`&&!e.computed&&e.property.type===`Identifier`&&t.includes(e.property.name)&&o(e.object),c=e=>{let t=e.parent,r=t?.type===`CallExpression`&&t.callee===e,a=t?.type===`AssignmentExpression`&&t.left===e||t?.type===`UpdateExpression`;return s(e,n.members)&&!r&&!a||e.type===`CallExpression`&&e.arguments.length===0&&s(e.callee,n.methods)?[e.range]:i(e).flatMap(c)};return c(e)}const m=(e,t)=>{let n=e=>t.some(t=>RegExp(`(?<![\\w$.])${e}(?![\\w$])`).test(t));return[e,...Array.from({length:20},(t,n)=>`${e}${n+1}`)].find(e=>!n(e))??`${e}_`},h=(e,t)=>e.type===`ObjectExpression`||e.type===`SequenceExpression`?`(${t})`:t;function g(e,t,n,r,i){let a=i.getText(e),o=n===null?[]:p(e,t,n,i);if(o.length===0)return`() => ${h(e,a)}`;let s=e.range[0],c=[...o].sort((e,t)=>t[0]-e[0]).reduce((e,[t,n])=>e.slice(0,t-s)+r+e.slice(n-s),a);return`(${r}) => ${h(e,c)}`}function _(e,t,n,r,i){let a=[i.getText(n),i.getText(r)],o=g(r,e,f,m(`value`,a),i);return`${e}.fold(${t===null?g(n,e,null,``,i):g(n,e,{members:[t.member],methods:[]},m(t.param,a),i)}, ${o})`}function v(e){let t=e.type===`BlockStatement`&&e.body.length===1?e.body[0]:e;return t.type===`ReturnStatement`&&t.argument?t.argument:null}function y(e){return e.alternate?e.alternate.type===`IfStatement`?1+y(e.alternate):2:1}const b=/* @__PURE__ */ new Set([`Left`,`None`,`Failure`,`left`,`none`,`failure`]);function x(e,t,n,i){return a(e).some(e=>e.type===`MemberExpression`&&!e.computed&&e.property.type===`Identifier`&&e.property.name===n&&r(i.getText(e.object))===t)}function S(e){if(e.type===`ReturnStatement`||e.type===`ThrowStatement`)return{exit:e,extraWork:!1};if(e.type!==`BlockStatement`||e.body.length===0)return null;let t=e.body[e.body.length-1];return t.type!==`ReturnStatement`&&t.type!==`ThrowStatement`?null:{exit:t,extraWork:e.body.length>1}}function C(e,t,n,i){let a=S(e);if(!a)return null;if(a.exit.type===`ThrowStatement`)return`throw`;if(a.extraWork)return`effect`;let o=a.exit.argument;if(!o)return`effect`;if(r(i.getText(o))===t)return`passthrough`;let s=o.type===`CallExpression`?o.callee:null,c=s?.type===`Identifier`?s.name:s?.type===`MemberExpression`&&s.property.type===`Identifier`?s.property.name:null;if(c&&b.has(c)){let e=o.arguments??[];return e.length===0||e.length===1&&n!==null&&r(i.getText(e[0]))===`${t}.${n}`?`passthrough`:`mappedFailure`}return n!==null&&x(o,t,n,i)?`effect`:`default`}function w(e,t,n){let i=e.flatMap(e=>a(e));return!i.some(e=>e.type===`AssignmentExpression`&&r(n.getText(e.left))===t)&&i.some(e=>{if(e.type!==`MemberExpression`||r(n.getText(e.object))!==t)return!1;let i=e.property.type===`Identifier`?e.property.name:null;if(i===l)return!0;let a=e.parent;return i===null||!c.includes(i)||a?.type!==`CallExpression`||a.callee!==e?!1:!(i===`orThrow`&&a.arguments.length>0)})}function T(e,t){if(e.type!==`IfStatement`||e.alternate)return null;let n=d(e.test,t);return!n?.isNegated||!S(e.consequent)?null:n}const E={meta:{type:`suggestion`,docs:{description:`Prefer .fold() over if/else chains when working with monadic types`,recommended:!0},hasSuggestions:!0,schema:[{type:`object`,properties:{allowInteropMarker:{type:`boolean`,default:!0},minComplexity:{type:`integer`,minimum:1,default:2},checkNullable:{type:`boolean`,default:!1},checkGuards:{type:`boolean`,default:!1}},additionalProperties:!1}],messages:{preferFold:`Prefer .fold() over if/else when working with {{type}} types`,preferFoldTernary:`Consider using .fold() instead of ternary operator for {{type}}`,preferFoldGuard:`{{receiver}} is checked with an early exit and then unwrapped. {{advice}} Branching first and unwrapping after is the imperative form.`,suggestFold:`Replace with .fold()`,suggestOr:`Replace with {{receiver}}.or({{alternative}}) — keep the first when it is present, else the alternative`}},create(t){let n=t.options[0]||{},i=n.allowInteropMarker!==!1,a=n=>i&&e(n,`interop`,t.sourceCode),s=n.minComplexity||2,c=n.checkNullable===!0,l=n.checkGuards===!0,f=e=>e?`Several guards in a row pass their failures through: sequence them with DoAsync(async function* () { const a = yield* $(await …) … }).`:`Several guards in a row pass their failures through: sequence them with Do(function* () { const a = yield* $(…); const b = yield* $(…); return … }).`,p={passthrough:(e,t)=>t?`Keep it in the chain: ${e}.flatMapAsync(…), or lift the steps into IO.`:`Keep it in the chain: ${e}.flatMap(…) or ${e}.map(…); the failure passes through on its own.`,mappedFailure:(e,t)=>`Keep it in the chain: ${e}.mapLeft(…).${t?`flatMapAsync`:`flatMap`}(…) builds the new failure and continues on success.`,default:e=>`Use ${e}.map(…).orElse(fallback), or ${e}.fold(() => fallback, (value) => …).`,throw:e=>`If a host needs the throw, use ${e}.orThrow((e) => new YourError(e)); otherwise keep it in the chain with .flatMap or .fold.`,effect:(e,t)=>t?`Use ${e}.foldAsync(onFailure, onSuccess).`:`Use ${e}.fold(onFailure, onSuccess).`};function m(e){if(!l)return;let n=t.sourceCode,i=T(e,n);if(!i)return;let a=e.parent;if(a?.type!==`BlockStatement`&&a?.type!==`Program`)return;let s=a.body,c=s.slice(s.indexOf(e)+1),u=r(i.obj);if(!w(c,u,n))return;let d=C(e.consequent,u,i.failure?.member??null,n);if(!d)return;let m=c.some(e=>o(e)),h=(d===`passthrough`||d===`mappedFailure`)&&s.filter(e=>{let t=T(e,n);if(!t)return!1;let i=r(t.obj),a=s.slice(s.indexOf(e)+1),o=C(e.consequent,i,t.failure?.member??null,n);return(o===`passthrough`||o===`mappedFailure`)&&w(a,i,n)}).length>1;t.report({node:e,messageId:`preferFoldGuard`,data:{receiver:i.obj,advice:h?f(m):p[d](i.obj,m)}})}function h(e){let n=t.sourceCode;if(e.type!==`IfStatement`||!e.alternate)return null;let r=d(e.test,n);if(!r)return null;let i=v(e.consequent),a=v(e.alternate);if(!i||!a)return null;let o=[e.test,i,a];if(!n.getCommentsInside(e).every(e=>e.range!==void 0&&o.some(t=>e.range[0]>=t.range[0]&&e.range[1]<=t.range[1])))return null;let{obj:s,isNegated:c,failure:l}=r,[u,f]=c?[i,a]:[a,i];return`return ${_(s,l,u,f,n)}`}function g(e){let n=t.sourceCode,i=d(e.test,n);if(!i)return[];let{obj:a,isNegated:o,failure:s}=i,[c,l]=o?[e.consequent,e.alternate]:[e.alternate,e.consequent],f=n.getText(c),p=n.getText(l);if(r(p)===r(a))return c.type===`Literal`||c.type===`TemplateLiteral`||u(c)?[]:[{messageId:`suggestOr`,data:{receiver:a,alternative:f},fix:t=>t.replaceText(e,`${a}.or(${f})`)}];let m=_(a,s,c,l,n);return[{messageId:`suggestFold`,fix:t=>t.replaceText(e,m)}]}function b(e){if(e.type===`CallExpression`&&e.callee.type===`MemberExpression`){let t=e.callee.property.name;return[`isSome`,`isNone`,`isRight`,`isLeft`,`isSuccess`,`isFailure`].includes(t)}return!1}function x(e){let n=t.sourceCode.getText(e);if(/\.(isSome|isNone|isDefined)\s*\(\s*\)/.test(n))return{isMonadic:!0,type:`Option`,via:`method`};if(/\.(isLeft|isRight)\s*\(\s*\)/.test(n))return{isMonadic:!0,type:`Either`,via:`method`};if(/\.(isSuccess|isFailure)\s*\(\s*\)/.test(n))return{isMonadic:!0,type:`Result`,via:`method`};if(c&&e.type===`BinaryExpression`){if((e.operator===`===`||e.operator===`!==`||e.operator===`==`||e.operator===`!=`)&&(e.left.type===`Literal`&&(e.left.value===null||e.left.value===void 0)||e.right.type===`Literal`&&(e.right.value===null||e.right.value===void 0)))return{isMonadic:!0,type:`Option`,via:`nullable`};if(e.operator===`==`||e.operator===`!=`||e.operator===`===`||e.operator===`!==`){let t=e.left.type===`Identifier`&&e.left.name===`undefined`,n=e.right.type===`Identifier`&&e.right.name===`undefined`;if(t||n)return{isMonadic:!0,type:`Option`,via:`nullable`}}}return{isMonadic:!1,type:``,via:``}}function S(e){if(!b(e.test))return[];let t=h(e);return t?[{messageId:`suggestFold`,fix:n=>n.replaceText(e,t)}]:[]}function E(e){let n=e.test,r=x(n);r.isMonadic&&(e.parent&&e.parent.type===`IfStatement`||y(e)>=s&&t.report({node:e,messageId:`preferFold`,data:{type:r.type},suggest:S(e)}))}return{IfStatement(e){a(e)||(E(e),m(e))},ConditionalExpression(e){if(a(e))return;let n=x(e.test);(n.via!==`nullable`||!u(e.consequent)&&!u(e.alternate))&&n.isMonadic&&t.report({node:e,messageId:`preferFoldTernary`,data:{type:n.type},suggest:b(e.test)?g(e):[]})}}}};export{E as default};
|
|
2
2
|
//# sourceMappingURL=prefer-fold.js.map
|