eslint-plugin-functype 2.200.0 → 2.201.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (61) hide show
  1. package/README.md +30 -2
  2. package/dist/cli/list-rules.js.map +1 -1
  3. package/dist/configs/recommended.d.ts +5 -1
  4. package/dist/configs/recommended.js +1 -1
  5. package/dist/configs/recommended.js.map +1 -1
  6. package/dist/index.d.ts +1 -0
  7. package/dist/index.js +1 -1
  8. package/dist/index.js.map +1 -1
  9. package/dist/rules/collection-naming.js.map +1 -1
  10. package/dist/rules/index.d.ts +13 -11
  11. package/dist/rules/index.js +1 -1
  12. package/dist/rules/index.js.map +1 -1
  13. package/dist/rules/must-fold-on-component-return.js.map +1 -1
  14. package/dist/rules/no-array-mutation.js.map +1 -1
  15. package/dist/rules/no-floating-io.js.map +1 -1
  16. package/dist/rules/no-floating-result.js.map +1 -1
  17. package/dist/rules/no-get-unsafe.js.map +1 -1
  18. package/dist/rules/no-getOrThrow-in-render.js.map +1 -1
  19. package/dist/rules/no-imperative-loops.js.map +1 -1
  20. package/dist/rules/no-let.js.map +1 -1
  21. package/dist/rules/no-serialize-container.js.map +1 -1
  22. package/dist/rules/no-uncalled-method.d.ts +16 -0
  23. package/dist/rules/no-uncalled-method.js +2 -0
  24. package/dist/rules/no-uncalled-method.js.map +1 -0
  25. package/dist/rules/prefer-do-notation.js +1 -1
  26. package/dist/rules/prefer-do-notation.js.map +1 -1
  27. package/dist/rules/prefer-either.js.map +1 -1
  28. package/dist/rules/prefer-flatmap.js.map +1 -1
  29. package/dist/rules/prefer-fold.js +1 -1
  30. package/dist/rules/prefer-fold.js.map +1 -1
  31. package/dist/rules/prefer-functype-map.js.map +1 -1
  32. package/dist/rules/prefer-functype-set.js.map +1 -1
  33. package/dist/rules/prefer-list.js.map +1 -1
  34. package/dist/rules/prefer-map.js.map +1 -1
  35. package/dist/rules/prefer-option.js.map +1 -1
  36. package/dist/rules/prefer-try.js.map +1 -1
  37. package/dist/utils/array-mutation.d.ts +1 -1
  38. package/dist/utils/array-mutation.js.map +1 -1
  39. package/dist/utils/ast-walk.js.map +1 -1
  40. package/dist/utils/async-detection.js.map +1 -1
  41. package/dist/utils/boundary-tags.d.ts +1 -1
  42. package/dist/utils/boundary-tags.js.map +1 -1
  43. package/dist/utils/collection-binding.d.ts +1 -1
  44. package/dist/utils/collection-binding.js.map +1 -1
  45. package/dist/utils/dependency-validator.js.map +1 -1
  46. package/dist/utils/functype-detection.d.ts +1 -1
  47. package/dist/utils/functype-detection.js.map +1 -1
  48. package/dist/utils/functype-predicates.d.ts +1 -1
  49. package/dist/utils/functype-predicates.js.map +1 -1
  50. package/dist/utils/host-throws.d.ts +1 -1
  51. package/dist/utils/host-throws.js.map +1 -1
  52. package/dist/utils/import-fixer.js.map +1 -1
  53. package/dist/utils/mutable-collection.d.ts +1 -1
  54. package/dist/utils/mutable-collection.js.map +1 -1
  55. package/dist/utils/react-render.js.map +1 -1
  56. package/dist/utils/readonly-contract.js.map +1 -1
  57. package/dist/utils/type-aware.d.ts +13 -1
  58. package/dist/utils/type-aware.js +1 -1
  59. package/dist/utils/type-aware.js.map +1 -1
  60. package/dist/utils/wire-types.js.map +1 -1
  61. package/package.json +3 -3
@@ -1 +1 @@
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,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,KA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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"}
1
+ {"version":3,"file":"no-imperative-loops.js","names":["containsAwait","containsYield","rule","context","options","allowForIndexAccess","allowWhileLoops","allowInTests","isInTestFile","filename","needsIndexAccess","node","bodyText","hasNoFunctionalEquivalent"],"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,MAAME,EAAwB,CAC5B,KAAM,CACJ,KAAM,aACN,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,+DACjB,CACF,EAEA,OAAOC,EAAS,CACd,IAAMC,EAAUD,EAAQ,QAAQ,IAAM,CAAC,EACjCE,EAAsBD,EAAQ,qBAAuB,GACrDE,EAAkBF,EAAQ,iBAAmB,GAC7CG,EAAeH,EAAQ,eAAiB,GAE9C,SAASI,GAAe,CACtB,IAAMC,EAAWN,EA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,iBAAiBA,EAAe,CAC1BE,EAA0BF,CAAI,GAC9BL,GACAC,GAAgBC,EAAa,GAEjCL,EAAQ,OAAO,CACbQ,OACA,UAAW,eACb,CAAC,CACH,CACF,CACF,CACF,E"}
@@ -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,E"}
1
+ {"version":3,"file":"no-let.js","names":["rule","context","allowInTests","isInTestFile","filename","node","variable","ref","fixer","firstToken"],"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,OAAOC,EAAS,CAEd,IAAMC,GADUD,EAAQ,QAAQ,IAAM,CAAC,EAAA,CACV,eAAiB,GAE9C,SAASE,GAAe,CACtB,IAAMC,EAAWH,EAAQ,SACzB,MACE,kCAAkC,KAAKG,CAAQ,GAC/CA,EAAS,SAAS,WAAW,GAC7BA,EAAS,SAAS,QAAQ,GAC1BA,EAAS,SAAS,SAAS,CAE/B,CAEA,MAAO,CACL,oBAAoBC,EAAe,CAC7BA,EAAK,OAAS,QACdH,GAAgBC,EAAa,IAEZF,EAAQ,WAAW,qBAAqBI,CAC1B,CAAC,CAAC,KAAMC,GACzCA,EAAS,WAAW,KAAMC,GAAiBA,EAAI,QAAQ,GAAKA,EAAI,aAAeD,EAAS,KAAK,EAAE,EAAE,IAAI,CAGpF,EAgBjBL,EAAQ,OAAO,CACbI,OACA,UAAW,QACX,QAAS,CACP,CACE,UAAW,eACX,IAAIG,EAAuB,CAEzB,IAAMC,EADaR,EAAQ,WACG,cAAcI,CAAI,EAIhD,OAHII,GAAcA,EAAW,QAAU,MAC9BD,EAAM,YAAYC,EAAY,OAAO,EAEvC,IACT,CACF,CACF,CACF,CAAC,EA9BDR,EAAQ,OAAO,CACbI,OACA,UAAW,QACX,IAAIG,EAAuB,CAEzB,IAAMC,EADaR,EAAQ,WACG,cAAcI,CAAI,EAIhD,OAHII,GAAcA,EAAW,QAAU,MAC9BD,EAAM,YAAYC,EAAY,OAAO,EAEvC,IACT,CACF,CAAC,GAqBL,CACF,CACF,CACF,E"}
@@ -1 +1 @@
1
- {"version":3,"file":"no-serialize-container.js","names":["serializedArgument","callee","call","first","object","rule","argument","node","found","containerInsideByType","context"],"sources":["../../src/rules/no-serialize-container.ts"],"sourcesContent":["import type { Rule } from \"eslint\"\n\nimport type { ASTNode } from \"../types/ast\"\nimport { containerInsideByType } from \"../utils/type-aware\"\n\n/**\n * `JSON.stringify(x)` or `*.json(x)`: Hono's `c.json`, `Response.json`, Express's `res.json`. A read\n * such as `await res.json()` has no argument, so it never matches.\n */\nfunction serializedArgument(call: ASTNode): ASTNode | undefined {\n const callee = call.callee as ASTNode\n const [first] = call.arguments as ReadonlyArray<ASTNode>\n if (first === undefined || first.type === \"SpreadElement\") return undefined\n if (callee.type !== \"MemberExpression\" || callee.computed || callee.property.type !== \"Identifier\") return undefined\n if (callee.property.name === \"json\") return first\n const object = callee.object as ASTNode\n return callee.property.name === \"stringify\" && object.type === \"Identifier\" && object.name === \"JSON\"\n ? first\n : undefined\n}\n\n/**\n * Reports a functype container handed to a JSON sink, anywhere inside the value. An Either, Option or\n * List serializes as its `{\"@functype\", _tag, value}` envelope, so a client reading `subscription.plan`\n * gets `undefined`, and a body built around a Left answers 200. The compiler can't catch it, because\n * `c.json()` and `JSON.stringify()` accept any value (#364).\n *\n * Calling `.toJSON()` or `.serialize()` first says the envelope is what you mean, 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 passing an Either, Option, List or other functype container to a JSON sink\",\n recommended: false,\n },\n schema: [],\n messages: {\n serializedContainer:\n \"This sends the {{name}}'s {_tag, value} envelope{{where}}, not its value. Unwrap it first: check isLeft() / isNone() and return the error, fold() it, or call .toArray() on a List. Use .toJSON() if the envelope is what you mean\",\n },\n },\n\n create(context) {\n return {\n CallExpression(node: ASTNode) {\n const argument = serializedArgument(node)\n if (argument === undefined) return\n const found = containerInsideByType(argument, context)\n if (found === undefined) return\n context.report({\n node: argument,\n messageId: \"serializedContainer\",\n data: { name: found.name, where: found.path === \"\" ? \"\" : ` at ${found.path}` },\n })\n },\n }\n },\n}\n\nexport default rule\n"],"mappings":"A,+DASA,SAASA,EAAmB,EAAoC,CAC9D,IAAMC,EAASC,EAAK,OACd,CAACC,GAASD,EAAK,UAErB,GADIC,IAAU,IAAA,IAAaA,EAAM,OAAS,iBACtCF,EAAO,OAAS,oBAAsBA,EAAO,UAAYA,EAAO,SAAS,OAAS,aAAc,OACpG,GAAIA,EAAO,SAAS,OAAS,OAAQ,OAAOE,EAC5C,IAAMC,EAASH,EAAO,OACtB,OAAOA,EAAO,SAAS,OAAS,aAAeG,EAAO,OAAS,cAAgBA,EAAO,OAAS,OAC3FD,EACA,IAAA,EACN,CAYA,MAAME,EAAwB,CAC5B,KAAM,CACJ,KAAM,UACN,KAAM,CACJ,YAAa,sFACb,YAAa,EACf,EACA,OAAQ,CAAC,EACT,SAAU,CACR,oBACE,oOACJ,CACF,EAEA,OAAO,EAAS,CACd,MAAO,CACL,eAAe,EAAe,CAC5B,IAAMC,EAAWN,EAAmBO,CAAI,EACxC,GAAID,IAAa,IAAA,GAAW,OAC5B,IAAME,EAAQC,EAAsBH,EAAUI,CAAO,EACjDF,IAAU,IAAA,IACdE,EAAQ,OAAO,CACb,KAAMJ,EACN,UAAW,sBACX,KAAM,CAAE,KAAME,EAAM,KAAM,MAAOA,EAAM,OAAS,GAAK,GAAK,OAAOA,EAAM,MAAO,CAChF,CAAC,CACH,CACF,CACF,CACF,E"}
1
+ {"version":3,"file":"no-serialize-container.js","names":["containerInsideByType","serializedArgument","call","callee","first","object","rule","context","node","argument","found"],"sources":["../../src/rules/no-serialize-container.ts"],"sourcesContent":["import type { Rule } from \"eslint\"\n\nimport type { ASTNode } from \"../types/ast\"\nimport { containerInsideByType } from \"../utils/type-aware\"\n\n/**\n * `JSON.stringify(x)` or `*.json(x)`: Hono's `c.json`, `Response.json`, Express's `res.json`. A read\n * such as `await res.json()` has no argument, so it never matches.\n */\nfunction serializedArgument(call: ASTNode): ASTNode | undefined {\n const callee = call.callee as ASTNode\n const [first] = call.arguments as ReadonlyArray<ASTNode>\n if (first === undefined || first.type === \"SpreadElement\") return undefined\n if (callee.type !== \"MemberExpression\" || callee.computed || callee.property.type !== \"Identifier\") return undefined\n if (callee.property.name === \"json\") return first\n const object = callee.object as ASTNode\n return callee.property.name === \"stringify\" && object.type === \"Identifier\" && object.name === \"JSON\"\n ? first\n : undefined\n}\n\n/**\n * Reports a functype container handed to a JSON sink, anywhere inside the value. An Either, Option or\n * List serializes as its `{\"@functype\", _tag, value}` envelope, so a client reading `subscription.plan`\n * gets `undefined`, and a body built around a Left answers 200. The compiler can't catch it, because\n * `c.json()` and `JSON.stringify()` accept any value (#364).\n *\n * Calling `.toJSON()` or `.serialize()` first says the envelope is what you mean, 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 passing an Either, Option, List or other functype container to a JSON sink\",\n recommended: false,\n },\n schema: [],\n messages: {\n serializedContainer:\n \"This sends the {{name}}'s {_tag, value} envelope{{where}}, not its value. Unwrap it first: check isLeft() / isNone() and return the error, fold() it, or call .toArray() on a List. Use .toJSON() if the envelope is what you mean\",\n },\n },\n\n create(context) {\n return {\n CallExpression(node: ASTNode) {\n const argument = serializedArgument(node)\n if (argument === undefined) return\n const found = containerInsideByType(argument, context)\n if (found === undefined) return\n context.report({\n node: argument,\n messageId: \"serializedContainer\",\n data: { name: found.name, where: found.path === \"\" ? \"\" : ` at ${found.path}` },\n })\n },\n }\n },\n}\n\nexport default rule\n"],"mappings":"A,+DASA,SAASC,EAAmBC,EAAoC,CAC9D,IAAMC,EAASD,EAAK,OACd,CAACE,GAASF,EAAK,UAErB,GADIE,IAAU,IAAA,IAAaA,EAAM,OAAS,iBACtCD,EAAO,OAAS,oBAAsBA,EAAO,UAAYA,EAAO,SAAS,OAAS,aAAc,OACpG,GAAIA,EAAO,SAAS,OAAS,OAAQ,OAAOC,EAC5C,IAAMC,EAASF,EAAO,OACtB,OAAOA,EAAO,SAAS,OAAS,aAAeE,EAAO,OAAS,cAAgBA,EAAO,OAAS,OAC3FD,EACA,IAAA,EACN,CAYA,MAAME,EAAwB,CAC5B,KAAM,CACJ,KAAM,UACN,KAAM,CACJ,YAAa,sFACb,YAAa,EACf,EACA,OAAQ,CAAC,EACT,SAAU,CACR,oBACE,oOACJ,CACF,EAEA,OAAOC,EAAS,CACd,MAAO,CACL,eAAeC,EAAe,CAC5B,IAAMC,EAAWR,EAAmBO,CAAI,EACxC,GAAIC,IAAa,IAAA,GAAW,OAC5B,IAAMC,EAAQV,EAAsBS,EAAUF,CAAO,EACjDG,IAAU,IAAA,IACdH,EAAQ,OAAO,CACb,KAAME,EACN,UAAW,sBACX,KAAM,CAAE,KAAMC,EAAM,KAAM,MAAOA,EAAM,OAAS,GAAK,GAAK,OAAOA,EAAM,MAAO,CAChF,CAAC,CACH,CACF,CACF,CACF,E"}
@@ -0,0 +1,16 @@
1
+ import { Rule } from "eslint";
2
+ /**
3
+ * Reports a functype method read as a value: `list.head` without `()`, `if (opt.isSome)`,
4
+ * `Option(list.head)`, `expect(list.head)`, `const { head } = list`. On functype 2, `head`, `last`,
5
+ * `tail`, `init`, `headOption` and `lastOption` are methods, and such a read compiles wherever any value
6
+ * is accepted: a truthiness check, `??`, a template string, an `unknown` or generic parameter. It
7
+ * yields the method itself, which is always truthy and never the element; and a detached functype
8
+ * method throws when it is called later (#603).
9
+ *
10
+ * Only members that functype declares as methods count, so function-valued data (`Some(fn).value`,
11
+ * a `Ref` holding a callback) is never reported.
12
+ *
13
+ * Type-aware only: without type information it reports nothing.
14
+ */
15
+ declare const rule: Rule.RuleModule;
16
+ export { rule as default };
@@ -0,0 +1,2 @@
1
+ import{functypeMethodByType as e}from"../utils/type-aware.js";const t=/* @__PURE__ */ new Set([`bind`,`call`,`apply`]),n=/* @__PURE__ */ new Set([`ChainExpression`,`TSNonNullExpression`,`TSAsExpression`,`TSSatisfiesExpression`,`TSTypeAssertion`]),r=e=>{let t=e.parent;return t!==void 0&&n.has(t.type)?r(t):e},i=e=>{let n=r(e),i=n.parent;if(i===void 0)return!1;switch(i.type){case`CallExpression`:case`NewExpression`:return i.callee===n;case`TaggedTemplateExpression`:return i.tag===n;case`MemberExpression`:return i.object===n&&!i.computed&&i.property.type===`Identifier`&&t.has(i.property.name);case`UnaryExpression`:return i.operator===`typeof`||i.operator===`delete`;case`AssignmentExpression`:return i.left===n;default:return!1}},a=e=>{let t=e.property;return!e.computed&&t.type===`Identifier`?t.name:e.computed&&t.type===`Literal`&&typeof t.value==`string`?t.value:void 0},o={meta:{type:`problem`,docs:{description:`Disallow reading a functype method as a value instead of calling it`,recommended:!1},schema:[],messages:{uncalledMethod:"`{{name}}` is a method of {{owner}}, so this reads the function itself, not a value. Call it: `{{name}}()`. A detached functype method throws when it's called later; use `.bind()` if you really mean the function"}},create(t){let n=(n,r,i)=>{let a=e(r,i,t);a!==void 0&&t.report({node:n,messageId:`uncalledMethod`,data:{name:i,owner:a}})},r=(e,t)=>{if(e.type===`ObjectPattern`)for(let r of e.properties){if(r.type!==`Property`||r.computed)continue;let e=r.key,i=e.type===`Identifier`?e.name:typeof e.value==`string`?e.value:void 0;i!==void 0&&n(r,t,i)}};return{MemberExpression(e){let t=a(e);t===void 0||i(e)||n(e,e.object,t)},VariableDeclarator(e){e.init!=null&&r(e.id,e.init)},AssignmentExpression(e){e.operator===`=`&&r(e.left,e.right)}}}};export{o as default};
2
+ //# sourceMappingURL=no-uncalled-method.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"no-uncalled-method.js","names":["functypeMethodByType","RECEIVER_METHODS","PASS_THROUGH","outermost","node","parent","isDeliberateUse","read","memberName","property","rule","context","report","object","name","owner","destructured","pattern","source","key"],"sources":["../../src/rules/no-uncalled-method.ts"],"sourcesContent":["import type { Rule } from \"eslint\"\n\nimport type { ASTNode } from \"../types/ast\"\nimport { functypeMethodByType } from \"../utils/type-aware\"\n\n/** `fn.bind(x)`, `fn.call(x, …)`, `fn.apply(x, …)`: the function is used on purpose, with a receiver. */\nconst RECEIVER_METHODS: ReadonlySet<string> = new Set([\"bind\", \"call\", \"apply\"])\n\n/** Wrappers that pass a value through unchanged: `a?.b`, `x!`, `x as F`, `x satisfies F`, `<F>x`. */\nconst PASS_THROUGH: ReadonlySet<string> = new Set([\n \"ChainExpression\",\n \"TSNonNullExpression\",\n \"TSAsExpression\",\n \"TSSatisfiesExpression\",\n \"TSTypeAssertion\",\n])\n\n/** The expression a member read evaluates into, looking through the pass-through wrappers. */\nconst outermost = (node: ASTNode): ASTNode => {\n const parent = node.parent as ASTNode | undefined\n return parent !== undefined && PASS_THROUGH.has(parent.type) ? outermost(parent) : node\n}\n\n/**\n * Is the read used as a function on purpose: called (`list.head()`, `list.head?.()`), given a receiver\n * (`.bind` / `.call` / `.apply`), checked with `typeof`, assigned to, or deleted?\n */\nconst isDeliberateUse = (read: ASTNode): boolean => {\n const node = outermost(read)\n const parent = node.parent as ASTNode | undefined\n if (parent === undefined) return false\n switch (parent.type) {\n case \"CallExpression\":\n case \"NewExpression\":\n return parent.callee === node\n case \"TaggedTemplateExpression\":\n return parent.tag === node\n case \"MemberExpression\":\n return (\n parent.object === node &&\n !parent.computed &&\n parent.property.type === \"Identifier\" &&\n RECEIVER_METHODS.has(parent.property.name)\n )\n case \"UnaryExpression\":\n return parent.operator === \"typeof\" || parent.operator === \"delete\"\n case \"AssignmentExpression\":\n return parent.left === node\n default:\n return false\n }\n}\n\n/** The name a member is read under: `head` in `list.head` or `list[\"head\"]`. */\nconst memberName = (node: ASTNode): string | undefined => {\n const property = node.property as ASTNode\n if (!node.computed && property.type === \"Identifier\") return property.name\n return node.computed && property.type === \"Literal\" && typeof property.value === \"string\" ? property.value : undefined\n}\n\n/**\n * Reports a functype method read as a value: `list.head` without `()`, `if (opt.isSome)`,\n * `Option(list.head)`, `expect(list.head)`, `const { head } = list`. On functype 2, `head`, `last`,\n * `tail`, `init`, `headOption` and `lastOption` are methods, and such a read compiles wherever any value\n * is accepted: a truthiness check, `??`, a template string, an `unknown` or generic parameter. It\n * yields the method itself, which is always truthy and never the element; and a detached functype\n * method throws when it is called later (#603).\n *\n * Only members that functype declares as methods count, so function-valued data (`Some(fn).value`,\n * a `Ref` holding a callback) is never 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 reading a functype method as a value instead of calling it\",\n recommended: false,\n },\n schema: [],\n messages: {\n uncalledMethod:\n \"`{{name}}` is a method of {{owner}}, so this reads the function itself, not a value. Call it: `{{name}}()`. A detached functype method throws when it's called later; use `.bind()` if you really mean the function\",\n },\n },\n\n create(context) {\n const report = (node: ASTNode, object: ASTNode, name: string): void => {\n const owner = functypeMethodByType(object, name, context)\n if (owner === undefined) return\n context.report({ node, messageId: \"uncalledMethod\", data: { name, owner } })\n }\n\n /** `const { head } = list`, `({ head } = list)`, `const { \"head\": h } = list`. */\n const destructured = (pattern: ASTNode, source: ASTNode): void => {\n if (pattern.type !== \"ObjectPattern\") return\n for (const property of pattern.properties as ReadonlyArray<ASTNode>) {\n if (property.type !== \"Property\" || property.computed) continue\n const key = property.key as ASTNode\n const name = key.type === \"Identifier\" ? key.name : typeof key.value === \"string\" ? key.value : undefined\n if (name !== undefined) report(property, source, name)\n }\n }\n\n return {\n MemberExpression(node: ASTNode) {\n const name = memberName(node)\n if (name === undefined || isDeliberateUse(node)) return\n report(node, node.object as ASTNode, name)\n },\n VariableDeclarator(node: ASTNode) {\n if (node.init != null) destructured(node.id as ASTNode, node.init as ASTNode)\n },\n AssignmentExpression(node: ASTNode) {\n if (node.operator === \"=\") destructured(node.left as ASTNode, node.right as ASTNode)\n },\n }\n },\n}\n\nexport default rule\n"],"mappings":"A,8DAMA,MAAMC,kBAAwC,IAAI,IAAI,CAAC,OAAQ,OAAQ,OAAO,CAAC,EAGzEC,kBAAoC,IAAI,IAAI,CAChD,kBACA,sBACA,iBACA,wBACA,iBACF,CAAC,EAGKC,EAAaC,GAA2B,CAC5C,IAAMC,EAASD,EAAK,OACpB,OAAOC,IAAW,IAAA,IAAaH,EAAa,IAAIG,EAAO,IAAI,EAAIF,EAAUE,CAAM,EAAID,CACrF,EAMME,EAAmBC,GAA2B,CAClD,IAAMH,EAAOD,EAAUI,CAAI,EACrBF,EAASD,EAAK,OACpB,GAAIC,IAAW,IAAA,GAAW,MAAO,GACjC,OAAQA,EAAO,KAAf,CACE,IAAK,iBACL,IAAK,gBACH,OAAOA,EAAO,SAAWD,EAC3B,IAAK,2BACH,OAAOC,EAAO,MAAQD,EACxB,IAAK,mBACH,OACEC,EAAO,SAAWD,GAClB,CAACC,EAAO,UACRA,EAAO,SAAS,OAAS,cACzBJ,EAAiB,IAAII,EAAO,SAAS,IAAI,EAE7C,IAAK,kBACH,OAAOA,EAAO,WAAa,UAAYA,EAAO,WAAa,SAC7D,IAAK,uBACH,OAAOA,EAAO,OAASD,EACzB,QACE,MAAO,EACX,CACF,EAGMI,EAAcJ,GAAsC,CACxD,IAAMK,EAAWL,EAAK,SAEtB,MADI,CAACA,EAAK,UAAYK,EAAS,OAAS,aAAqBA,EAAS,KAC/DL,EAAK,UAAYK,EAAS,OAAS,WAAa,OAAOA,EAAS,OAAU,SAAWA,EAAS,MAAQ,IAAA,EAC/G,EAeMC,EAAwB,CAC5B,KAAM,CACJ,KAAM,UACN,KAAM,CACJ,YAAa,sEACb,YAAa,EACf,EACA,OAAQ,CAAC,EACT,SAAU,CACR,eACE,qNACJ,CACF,EAEA,OAAOC,EAAS,CACd,IAAMC,GAAUR,EAAeS,EAAiBC,IAAuB,CACrE,IAAMC,EAAQf,EAAqBa,EAAQC,EAAMH,CAAO,EACpDI,IAAU,IAAA,IACdJ,EAAQ,OAAO,CAAEP,OAAM,UAAW,iBAAkB,KAAM,CAAEU,OAAMC,OAAM,CAAE,CAAC,CAC7E,EAGMC,GAAgBC,EAAkBC,IAA0B,CAChE,GAAID,EAAQ,OAAS,gBACrB,IAAK,IAAMR,KAAYQ,EAAQ,WAAsC,CACnE,GAAIR,EAAS,OAAS,YAAcA,EAAS,SAAU,SACvD,IAAMU,EAAMV,EAAS,IACfK,EAAOK,EAAI,OAAS,aAAeA,EAAI,KAAO,OAAOA,EAAI,OAAU,SAAWA,EAAI,MAAQ,IAAA,GAC5FL,IAAS,IAAA,IAAWF,EAAOH,EAAUS,EAAQJ,CAAI,CACvD,CACF,EAEA,MAAO,CACL,iBAAiBV,EAAe,CAC9B,IAAMU,EAAON,EAAWJ,CAAI,EACxBU,IAAS,IAAA,IAAaR,EAAgBF,CAAI,GAC9CQ,EAAOR,EAAMA,EAAK,OAAmBU,CAAI,CAC3C,EACA,mBAAmBV,EAAe,CAC5BA,EAAK,MAAQ,MAAMY,EAAaZ,EAAK,GAAeA,EAAK,IAAe,CAC9E,EACA,qBAAqBA,EAAe,CAC9BA,EAAK,WAAa,KAAKY,EAAaZ,EAAK,KAAiBA,EAAK,KAAgB,CACrF,CACF,CACF,CACF,E"}
@@ -1,2 +1,2 @@
1
- import{isChainedMethodCall as e}from"../utils/functype-detection.js";import{isExtractableByType as t}from"../utils/type-aware.js";const n=/* @__PURE__ */ new Set([`Option`,`Either`,`Try`]),r=/* @__PURE__ */ new Set([`parent`,`loc`,`range`]),i=(e,t)=>/* @__PURE__ */ new Set([...e,...t]);function a(e){if(e.type!==`CallExpression`)return/* @__PURE__ */ new Set;let t=e.callee;return t?.type===`Identifier`&&n.has(t.name)?/* @__PURE__ */ new Set([t.name]):t?.type===`MemberExpression`&&t.object?.type===`Identifier`&&n.has(t.object.name)?/* @__PURE__ */ new Set([t.object.name]):/* @__PURE__ */ new Set}function o(e){return Object.entries(e).filter(([e])=>!r.has(e)).flatMap(([,e])=>Array.isArray(e)?e:[e]).filter(e=>typeof e==`object`&&!!e)}const s=/* @__PURE__ */ new Set([`flatMap`,`map`,`filter`,`fold`]),c=/* @__PURE__ */ new Set([`flatMap`]),l=/* @__PURE__ */ new Set([`flatMap`,`map`,`filter`]);function u(e){if(e.type!==`CallExpression`||e.callee?.type!==`MemberExpression`)return 0;let t=e.callee.property;return(t.type===`Identifier`&&s.has(t.name)?1:0)+u(e.callee.object)}function d(e){if(e.callee?.type!==`MemberExpression`||e.callee.object?.type!==`CallExpression`)return 0;let t=e.callee.property,n=e.callee.object;return(t.type===`Identifier`&&l.has(t.name)?1:0)+d(n)}function f(e){if(e.callee?.type!==`MemberExpression`)return!1;let t=e.callee.property;return t.type!==`Identifier`||!l.has(t.name)?!1:d(e)>=1}function p(e){return e.type!==`LogicalExpression`||e.operator!==`&&`?[e]:[...p(e.left),...p(e.right)]}const m=e=>e.type===`Identifier`||e.type===`ThisExpression`||e.type===`MemberExpression`,h=/* @__PURE__ */ new Set,g=/* @__PURE__ */ new Set([`ArrowFunctionExpression`,`FunctionExpression`,`FunctionDeclaration`]);function _(e){let t=e?.typeAnnotation;return t?.type!==`TSTypeReference`||t.typeName?.type!==`Identifier`?h:n.has(t.typeName.name)?/* @__PURE__ */ new Set([t.typeName.name]):h}const v=/^(option|opt|either|result|maybe)\d*$/i,y=/[a-z0-9](Option|Either|Result|Maybe|Try)\d*$/,b=/* @__PURE__ */ new Map([[`toOption`,`Option`],[`toEither`,`Either`],[`toTry`,`Try`]]);function x(e){if(e.type===`ConditionalExpression`)return i(x(e.consequent),x(e.alternate));if(e.type!==`CallExpression`)return h;if(a(e).size>0)return a(e);if(e.callee?.type!==`MemberExpression`||e.callee.property.type!==`Identifier`)return h;let t=b.get(e.callee.property.name);return t===void 0?l.has(e.callee.property.name)?x(e.callee.object):h:/* @__PURE__ */ new Set([t])}function S(e){return e.type!==`CallExpression`||a(e).size>0||e.callee?.type!==`MemberExpression`||e.callee.property.type!==`Identifier`||!l.has(e.callee.property.name)?e:S(e.callee.object)}const C={meta:{type:`suggestion`,docs:{description:`Prefer Do notation for complex monadic compositions and nested operations`,recommended:!0},messages:{preferDoForNestedChecks:`This && chain guards each step of a property path. Use optional chaining (a?.b?.c), or Option(a).flatMap(…) when you want an Option`,preferDoForChainedMethods:`Prefer Do notation for complex flatMap chains ({{count}} levels deep)`,preferDoForMixedMonads:`Consider Do notation when mixing Option, Either, and Try operations`,preferDoAsyncForChainedTasks:`Prefer DoAsync notation for chained async operations`},schema:[{type:`object`,properties:{minChainDepth:{type:`integer`,minimum:2,default:3},detectMixedMonads:{type:`boolean`,default:!0}},additionalProperties:!1}]},create(n){let r=n.options[0]||{},d=r.minChainDepth||3,C=r.detectMixedMonads!==!1,w=e=>n.sourceCode.getText(e).replace(/\s+/g,``);function T(e){let t=(n.sourceCode.getScope(e).references.find(t=>t.identifier===e)?.resolved)?.defs[0]?.name;return _(t?.typeAnnotation)}function E(e){let r=t(e.callee.object,n);if(r!==void 0)return r;let i=S(e);return x(i).size>0?!0:i.type===`Identifier`?T(i).size>0||v.test(i.name)||y.test(i.name):!1}function D(e){let t=e.parent,n=t?.parent;if(t?.type===`MemberExpression`&&t.object===e&&n?.type===`CallExpression`&&n.callee===t)return t.property.type===`Identifier`&&s.has(t.property.name)?n:void 0}function O(e,t){let n=D(e);if(n===void 0)return!1;let r=n.callee.property;return r.type===`Identifier`&&t.has(r.name)||O(n,t)}function k(e){if(e.operator!==`&&`)return;let t=e.parent;if(t?.type===`LogicalExpression`&&t.operator===`&&`)return;let r=p(e);r.reduce((e,t,n)=>{let i=r[n-1],a=i!==void 0&&m(i)&&t.type===`MemberExpression`&&w(t.object)===w(i)?e.run+1:1;return{run:a,best:Math.max(e.best,a)}},{run:0,best:0}).best>=3&&n.report({node:e,messageId:`preferDoForNestedChecks`})}function A(t){if(!e(t,`flatMap`)||O(t,c))return;let r=u(t);r<d||!E(t)||n.report({node:t,messageId:`preferDoForChainedMethods`,data:{count:r.toString()}})}function j(e){if(e?.type!==`ArrowFunctionExpression`&&e?.type!==`FunctionExpression`)return[];let t=e.body;if(t.type!==`BlockStatement`)return[t];let n=e=>e.type===`ReturnStatement`?e.argument?[e.argument]:[]:g.has(e.type)?[]:o(e).flatMap(n);return n(t)}function M(e){if(e.type===`Identifier`)return T(e);if(e.type!==`CallExpression`||e.callee?.type!==`MemberExpression`)return a(e);let t=e.callee.property,n=t.type===`Identifier`&&l.has(t.name)?j(e.arguments[0]).reduce((e,t)=>i(e,x(t)),h):h;if(a(e).size>0)return i(n,a(e));let r=t.type===`Identifier`?b.get(t.name):void 0;return r===void 0?i(n,M(e.callee.object)):i(n,/* @__PURE__ */ new Set([r]))}function N(e){C&&f(e)&&!O(e,l)&&E(e)&&M(e).size>=2&&n.report({node:e,messageId:`preferDoForMixedMonads`})}return{LogicalExpression(e){k(e)},CallExpression(e){A(e),N(e)}}}};export{C as default};
1
+ import{isChainedMethodCall as e}from"../utils/functype-detection.js";import{isExtractableByType as t}from"../utils/type-aware.js";const n=/* @__PURE__ */ new Set([`Option`,`Either`,`Try`]),r=/* @__PURE__ */ new Set([`parent`,`loc`,`range`]),i=(e,t)=>/* @__PURE__ */ new Set([...e,...t]);function a(e){if(e.type!==`CallExpression`)return/* @__PURE__ */ new Set;let t=e.callee;return t?.type===`Identifier`&&n.has(t.name)?/* @__PURE__ */ new Set([t.name]):t?.type===`MemberExpression`&&t.object?.type===`Identifier`&&n.has(t.object.name)?/* @__PURE__ */ new Set([t.object.name]):/* @__PURE__ */ new Set}function o(e){return Object.entries(e).filter(([e])=>!r.has(e)).flatMap(([,e])=>Array.isArray(e)?e:[e]).filter(e=>typeof e==`object`&&!!e)}const s=/* @__PURE__ */ new Set([`flatMap`,`map`,`filter`,`fold`]),c=/* @__PURE__ */ new Set([`flatMap`]),l=/* @__PURE__ */ new Set([`flatMap`,`map`,`filter`]);function u(e){if(e.type!==`CallExpression`||e.callee?.type!==`MemberExpression`)return 0;let t=e.callee.property;return(t.type===`Identifier`&&s.has(t.name)?1:0)+u(e.callee.object)}function d(e){if(e.callee?.type!==`MemberExpression`||e.callee.object?.type!==`CallExpression`)return 0;let t=e.callee.property,n=e.callee.object;return(t.type===`Identifier`&&l.has(t.name)?1:0)+d(n)}function f(e){if(e.callee?.type!==`MemberExpression`)return!1;let t=e.callee.property;return t.type!==`Identifier`||!l.has(t.name)?!1:d(e)>=1}function p(e){return e.type!==`LogicalExpression`||e.operator!==`&&`?[e]:[...p(e.left),...p(e.right)]}const m=e=>e.type===`Identifier`||e.type===`ThisExpression`||e.type===`MemberExpression`,h=/* @__PURE__ */ new Set,g=/* @__PURE__ */ new Set([`ArrowFunctionExpression`,`FunctionExpression`,`FunctionDeclaration`]);function _(e){let t=e?.typeAnnotation;return t?.type!==`TSTypeReference`||t.typeName?.type!==`Identifier`?h:n.has(t.typeName.name)?/* @__PURE__ */ new Set([t.typeName.name]):h}const v=/^(option|opt|either|result|maybe)\d*$/i,y=/[a-z0-9](Option|Either|Result|Maybe|Try)\d*$/,b=/* @__PURE__ */ new Map([[`toOption`,`Option`],[`toEither`,`Either`],[`toTry`,`Try`]]);function x(e){if(e.type===`ConditionalExpression`)return i(x(e.consequent),x(e.alternate));if(e.type!==`CallExpression`)return h;if(a(e).size>0)return a(e);if(e.callee?.type!==`MemberExpression`||e.callee.property.type!==`Identifier`)return h;let t=b.get(e.callee.property.name);return t===void 0?l.has(e.callee.property.name)?x(e.callee.object):h:/* @__PURE__ */ new Set([t])}function S(e){return e.type!==`CallExpression`||a(e).size>0||e.callee?.type!==`MemberExpression`||e.callee.property.type!==`Identifier`||!l.has(e.callee.property.name)?e:S(e.callee.object)}const C={meta:{type:`suggestion`,docs:{description:`Prefer Do notation for complex monadic compositions and nested operations`,recommended:!0},messages:{preferDoForNestedChecks:`This && chain guards each step of a property path. Use optional chaining (a?.b?.c), or Option(a).flatMap(…) when you want an Option`,preferDoForChainedMethods:`Prefer Do notation for complex flatMap chains ({{count}} levels deep)`,preferDoForMixedMonads:`Consider Do notation when mixing Option, Either, and Try operations`,preferDoAsyncForChainedTasks:`Prefer DoAsync notation for chained async operations`},schema:[{type:`object`,properties:{minChainDepth:{type:`integer`,minimum:2,default:3},detectMixedMonads:{type:`boolean`,default:!0}},additionalProperties:!1}]},create(n){let r=n.options[0]||{},d=r.minChainDepth||3,C=r.detectMixedMonads!==!1,w=e=>n.sourceCode.getText(e).replace(/\s+/g,``);function T(e){return _((n.sourceCode.getScope(e).references.find(t=>t.identifier===e)?.resolved)?.defs[0]?.name?.typeAnnotation)}function E(e){let r=t(e.callee.object,n);if(r!==void 0)return r;let i=S(e);return x(i).size>0?!0:i.type===`Identifier`?T(i).size>0||v.test(i.name)||y.test(i.name):!1}function D(e){let t=e.parent,n=t?.parent;if(t?.type===`MemberExpression`&&t.object===e&&n?.type===`CallExpression`&&n.callee===t)return t.property.type===`Identifier`&&s.has(t.property.name)?n:void 0}function O(e,t){let n=D(e);if(n===void 0)return!1;let r=n.callee.property;return r.type===`Identifier`&&t.has(r.name)||O(n,t)}function k(e){if(e.operator!==`&&`)return;let t=e.parent;if(t?.type===`LogicalExpression`&&t.operator===`&&`)return;let r=p(e);r.reduce((e,t,n)=>{let i=r[n-1],a=i!==void 0&&m(i)&&t.type===`MemberExpression`&&w(t.object)===w(i)?e.run+1:1;return{run:a,best:Math.max(e.best,a)}},{run:0,best:0}).best>=3&&n.report({node:e,messageId:`preferDoForNestedChecks`})}function A(t){if(!e(t,`flatMap`)||O(t,c))return;let r=u(t);r<d||!E(t)||n.report({node:t,messageId:`preferDoForChainedMethods`,data:{count:r.toString()}})}function j(e){if(e?.type!==`ArrowFunctionExpression`&&e?.type!==`FunctionExpression`)return[];let t=e.body;if(t.type!==`BlockStatement`)return[t];let n=e=>e.type===`ReturnStatement`?e.argument?[e.argument]:[]:g.has(e.type)?[]:o(e).flatMap(n);return n(t)}function M(e){if(e.type===`Identifier`)return T(e);if(e.type!==`CallExpression`||e.callee?.type!==`MemberExpression`)return a(e);let t=e.callee.property,n=t.type===`Identifier`&&l.has(t.name)?j(e.arguments[0]).reduce((e,t)=>i(e,x(t)),h):h;if(a(e).size>0)return i(n,a(e));let r=t.type===`Identifier`?b.get(t.name):void 0;return r===void 0?i(n,M(e.callee.object)):i(n,/* @__PURE__ */ new Set([r]))}function N(e){C&&f(e)&&!O(e,l)&&E(e)&&M(e).size>=2&&n.report({node:e,messageId:`preferDoForMixedMonads`})}return{LogicalExpression(e){k(e)},CallExpression(e){A(e),N(e)}}}};export{C as default};
2
2
  //# sourceMappingURL=prefer-do-notation.js.map
@@ -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","CHAIN_METHODS","FLAT_MAP","COMPOSITION_METHODS","getChainDepth","method","compositionChainDepth","next","isCompositionChain","andOperands","isPathStart","NONE","FUNCTION_TYPES","monadOfAnnotation","type","annotation","MONAD_NAME","MONAD_SUFFIX","CONVERSIONS","monadOfValue","converted","chainRoot","rule","options","context","minChainDepth","detectMixedMonads","text","declaredMonad","declared","identifier","reference","onMonad","byType","isExtractableByType","step","root","nextStep","member","call","hasStepAbove","methods","checkNestedNullChecks","parent","operands","previous","i","run","operand","acc","checkChainedMethods","isChainedMethodCall","chainDepth","returnedBy","callback","body","returns","monadsAlongChain","returned","checkMixedMonads"],"sources":["../../src/rules/prefer-do-notation.ts"],"sourcesContent":["import type { Rule } from \"eslint\"\n\nimport type { ASTNode } from \"../types/ast\"\nimport { isChainedMethodCall } from \"../utils/functype-detection\"\nimport { isExtractableByType } from \"../utils/type-aware\"\n\nconst MONAD_TYPES: ReadonlySet<string> = new Set([\"Option\", \"Either\", \"Try\"])\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(...)\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\nconst CHAIN_METHODS: ReadonlySet<string> = new Set([\"flatMap\", \"map\", \"filter\", \"fold\"])\n\nconst FLAT_MAP: ReadonlySet<string> = new Set([\"flatMap\"])\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 * Number of `.flatMap()/.map()/.filter()/.fold()` steps walking left from `node`. Only the steps\n * count: the receiver they start from, `o` or `Option(x)`, is not a level, so\n * `Option(x).flatMap(f).flatMap(g)` is 2 deep.\n */\nfunction getChainDepth(node: ASTNode): number {\n if (node.type !== \"CallExpression\" || node.callee?.type !== \"MemberExpression\") return 0\n const method = node.callee.property\n const here = method.type === \"Identifier\" && CHAIN_METHODS.has(method.name) ? 1 : 0\n return here + getChainDepth(node.callee.object as ASTNode)\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/** The operands of an `a && b && c` chain, left to right, through any nesting of `&&`. */\nfunction andOperands(node: ASTNode): ReadonlyArray<ASTNode> {\n if (node.type !== \"LogicalExpression\" || node.operator !== \"&&\") return [node]\n return [...andOperands(node.left as ASTNode), ...andOperands(node.right as ASTNode)]\n}\n\n/** A plain property path a guard can start from: `a`, `this`, `a.b`. Optional chains are already the fix. */\nconst isPathStart = (node: ASTNode): boolean =>\n node.type === \"Identifier\" || node.type === \"ThisExpression\" || node.type === \"MemberExpression\"\n\nconst NONE: ReadonlySet<string> = new Set()\n\nconst FUNCTION_TYPES: ReadonlySet<string> = new Set([\n \"ArrowFunctionExpression\",\n \"FunctionExpression\",\n \"FunctionDeclaration\",\n])\n\n/** `MONAD_TYPES` entries a type annotation names: `Option<number>` → Option. */\nfunction monadOfAnnotation(annotation: ASTNode | undefined): ReadonlySet<string> {\n const type = annotation?.typeAnnotation as ASTNode | undefined\n if (type?.type !== \"TSTypeReference\" || type.typeName?.type !== \"Identifier\") return NONE\n return MONAD_TYPES.has(type.typeName.name) ? new Set([type.typeName.name]) : NONE\n}\n\n/**\n * Receiver names that say \"this holds a monad\", for code linted without type information: `option`,\n * `opt`, `either`, `result`, `maybe`, or a numbered one such as `option1`, in any case; or a\n * camelCase suffix such as `userOption` or `parseResult`, which must be capitalized, so `entry`,\n * `retry` and `registry` don't count.\n */\nconst MONAD_NAME = /^(option|opt|either|result|maybe)\\d*$/i\nconst MONAD_SUFFIX = /[a-z0-9](Option|Either|Result|Maybe|Try)\\d*$/\n\n/** Methods that turn one monad into another: `Try(f).toOption()` is an Option. */\nconst CONVERSIONS: ReadonlyMap<string, string> = new Map([\n [\"toOption\", \"Option\"],\n [\"toEither\", \"Either\"],\n [\"toTry\", \"Try\"],\n])\n\n/**\n * The monad an expression's value is, as far as the syntax shows: a constructor or companion call\n * (`Option(x)`, `Either.right(x)`), a conversion (`Try(f).toOption()` is an Option), a step that keeps\n * its receiver's monad (`Option(x).map(f)`), or either branch of `ok ? a : b`. Anything else is unknown.\n */\nfunction monadOfValue(node: ASTNode): ReadonlySet<string> {\n if (node.type === \"ConditionalExpression\")\n return union(monadOfValue(node.consequent as ASTNode), monadOfValue(node.alternate as ASTNode))\n if (node.type !== \"CallExpression\") return NONE\n if (monadAt(node).size > 0) return monadAt(node)\n if (node.callee?.type !== \"MemberExpression\" || node.callee.property.type !== \"Identifier\") return NONE\n const converted = CONVERSIONS.get(node.callee.property.name)\n if (converted !== undefined) return new Set([converted])\n return COMPOSITION_METHODS.has(node.callee.property.name) ? monadOfValue(node.callee.object as ASTNode) : NONE\n}\n\n/**\n * The receiver a method chain starts from: `Option(x)` in `Option(x).map(f).flatMap(g)`, `o` in\n * `o.flatMap(f)`. Walks back only through steps that keep the monad (`flatMap`, `map`, `filter`), so\n * in `Option(xs).getOrElse(() => []).flatMap(f)` or after a `.fold(…)` the root is the unwrapped value, not\n * `Option(xs)`. A monad constructor or companion\n * call is a root of its own.\n */\nfunction chainRoot(node: ASTNode): ASTNode {\n if (node.type !== \"CallExpression\" || monadAt(node).size > 0) return node\n if (node.callee?.type !== \"MemberExpression\" || node.callee.property.type !== \"Identifier\") return node\n if (!COMPOSITION_METHODS.has(node.callee.property.name)) return node\n return chainRoot(node.callee.object 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 messages: {\n preferDoForNestedChecks:\n \"This && chain guards each step of a property path. Use optional chaining (a?.b?.c), or Option(a).flatMap(…) when you want an Option\",\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 const text = (node: ASTNode): string => context.sourceCode.getText(node).replace(/\\s+/g, \"\")\n\n /** The monad a chain root is declared as, through its variable's or parameter's annotation. */\n function declaredMonad(identifier: ASTNode): ReadonlySet<string> {\n const variable = context.sourceCode\n .getScope(identifier)\n .references.find((reference) => reference.identifier === identifier)?.resolved\n const declared = variable?.defs[0]?.name as ASTNode | undefined\n return monadOfAnnotation(declared?.typeAnnotation as ASTNode | undefined)\n }\n\n /**\n * Is `step` a step on a functype monad? With type information, the type of the value it's called on\n * decides, so a `string[]`, or an Option already unwrapped with `.getOrElse(() => [])`, never counts, and\n * `service.getUser(1)` returning an Option does. Without it, the chain's root must be a monad\n * constructor, companion or conversion, an identifier annotated with a monad type, or one named\n * like a monad.\n */\n function onMonad(step: ASTNode): boolean {\n const byType = isExtractableByType(step.callee.object as ASTNode, context)\n if (byType !== undefined) return byType\n const root = chainRoot(step)\n if (monadOfValue(root).size > 0) return true\n if (root.type !== \"Identifier\") return false\n return declaredMonad(root).size > 0 || MONAD_NAME.test(root.name) || MONAD_SUFFIX.test(root.name)\n }\n\n /** The call that takes `node` as its receiver for a further `.flatMap/.map/.filter/.fold` step, if any. */\n function nextStep(node: ASTNode): ASTNode | undefined {\n const member = node.parent as ASTNode | undefined\n const call = member?.parent as ASTNode | undefined\n if (member?.type !== \"MemberExpression\" || member.object !== node) return undefined\n if (call?.type !== \"CallExpression\" || call.callee !== member) return undefined\n return member.property.type === \"Identifier\" && CHAIN_METHODS.has(member.property.name) ? call : undefined\n }\n\n /**\n * Is there a `methods` step further out on this chain? Then that step reports, once, for the whole\n * chain. A trailing `.fold(…)` or `.map(…)` isn't one, so it doesn't hide the flatMaps under it.\n */\n function hasStepAbove(node: ASTNode, methods: ReadonlySet<string>): boolean {\n const step = nextStep(node)\n if (step === undefined) return false\n const method = step.callee.property\n return (method.type === \"Identifier\" && methods.has(method.name)) || hasStepAbove(step, methods)\n }\n\n /**\n * `a && a.b && a.b.c`: at least three operands in a row, each a property of the one before it.\n * Matched on the AST, so `isAdmin && settings.theme && user.profile.name` is not a guard chain.\n */\n function checkNestedNullChecks(node: ASTNode): void {\n if (node.operator !== \"&&\") return\n const parent = node.parent as ASTNode | undefined\n if (parent?.type === \"LogicalExpression\" && parent.operator === \"&&\") return\n const operands = andOperands(node)\n const longestRun = operands.reduce<{ readonly run: number; readonly best: number }>(\n (acc, operand, i) => {\n const previous = operands[i - 1]\n const extends_ =\n previous !== undefined &&\n isPathStart(previous) &&\n operand.type === \"MemberExpression\" &&\n text(operand.object as ASTNode) === text(previous)\n const run = extends_ ? acc.run + 1 : 1\n return { run, best: Math.max(acc.best, run) }\n },\n { run: 0, best: 0 },\n ).best\n if (longestRun >= 3) context.report({ node, messageId: \"preferDoForNestedChecks\" })\n }\n\n /** A long `.flatMap(…)` chain on a monad, reported once at its outermost step. */\n function checkChainedMethods(node: ASTNode): void {\n if (!isChainedMethodCall(node, \"flatMap\") || hasStepAbove(node, FLAT_MAP)) return\n const chainDepth = getChainDepth(node)\n if (chainDepth < minChainDepth || !onMonad(node)) return\n context.report({\n node,\n messageId: \"preferDoForChainedMethods\",\n data: { count: chainDepth.toString() },\n })\n }\n\n /** What a step's callback returns: its expression body, or the arguments of its own `return`s. */\n function returnedBy(callback: ASTNode | undefined): ReadonlyArray<ASTNode> {\n if (callback?.type !== \"ArrowFunctionExpression\" && callback?.type !== \"FunctionExpression\") return []\n const body = callback.body as ASTNode\n if (body.type !== \"BlockStatement\") return [body]\n const returns = (node: ASTNode): ReadonlyArray<ASTNode> => {\n if (node.type === \"ReturnStatement\") return node.argument ? [node.argument as ASTNode] : []\n if (FUNCTION_TYPES.has(node.type)) return []\n return (astChildren(node) as ASTNode[]).flatMap(returns)\n }\n return returns(body)\n }\n\n /** The monads a composition chain moves through: its root, and what each step's callback returns. */\n function monadsAlongChain(node: ASTNode): ReadonlySet<string> {\n if (node.type === \"Identifier\") return declaredMonad(node)\n if (node.type !== \"CallExpression\" || node.callee?.type !== \"MemberExpression\") return monadAt(node)\n const method = node.callee.property\n const step =\n method.type === \"Identifier\" && COMPOSITION_METHODS.has(method.name)\n ? returnedBy(node.arguments[0] as ASTNode | undefined).reduce<ReadonlySet<string>>(\n (acc, returned) => union(acc, monadOfValue(returned)),\n NONE,\n )\n : NONE\n if (monadAt(node).size > 0) return union(step, monadAt(node))\n // From a conversion on, the chain is the converted monad: what it converted from doesn't count.\n const converted = method.type === \"Identifier\" ? CONVERSIONS.get(method.name) : undefined\n if (converted !== undefined) return union(step, new Set([converted]))\n return union(step, monadsAlongChain(node.callee.object as ASTNode))\n }\n\n /**\n * Mixed monads along one composition chain: `option.flatMap((x) => Either.right(x)).flatMap((y) => Try(…))`.\n * Only the chain's own steps count, not every monad written somewhere inside its callbacks, and\n * only a chain that starts from a monad: an array's `.map((x) => Option(x))` is not a mix.\n * Conversions such as `.toEither(…)` and terminal handlers such as `.fold(…)` are not steps (#205).\n */\n function checkMixedMonads(node: ASTNode): void {\n if (!detectMixedMonads || !isCompositionChain(node) || hasStepAbove(node, COMPOSITION_METHODS)) return\n if (!onMonad(node)) return\n if (monadsAlongChain(node).size >= 2) context.report({ node, messageId: \"preferDoForMixedMonads\" })\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,kIAMA,MAAMA,kBAAmC,IAAI,IAAI,CAAC,SAAU,SAAU,KAAK,CAAC,EAGtEC,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,CAACG,KAAO,CAACR,EAAe,IAAIQ,CAAC,CAAC,CAAC,CACvC,SAAS,EAAGC,KAAQ,MAAM,Q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AAaA,EAAMO,CAAmB,GACxF6B,EAAQpC,CAAI,GACb6D,EAAiB7D,CAAI,CAAC,CAAC,MAAQ,GAAG4B,EAAQ,OAAO,CAAE,OAAM,UAAW,wBAAyB,CAAC,CACpG,CAEA,MAAO,CACL,kBAAkB,EAAM,CACtBkB,EAAsB9C,CAAI,CAC5B,EAEA,eAAe,EAAM,CACnBsD,EAAoBtD,CAAI,EACxB+D,EAAiB/D,CAAI,CACvB,CACF,CACF,CACF,E"}
1
+ {"version":3,"file":"prefer-do-notation.js","names":["isChainedMethodCall","isExtractableByType","MONAD_TYPES","NON_CHILD_KEYS","union","a","b","monadAt","node","callee","astChildren","k","v","CHAIN_METHODS","FLAT_MAP","COMPOSITION_METHODS","getChainDepth","method","compositionChainDepth","next","isCompositionChain","andOperands","isPathStart","NONE","FUNCTION_TYPES","monadOfAnnotation","annotation","type","MONAD_NAME","MONAD_SUFFIX","CONVERSIONS","monadOfValue","converted","chainRoot","rule","context","options","minChainDepth","detectMixedMonads","text","declaredMonad","identifier","reference","onMonad","step","byType","root","nextStep","member","call","hasStepAbove","methods","checkNestedNullChecks","parent","operands","acc","operand","i","previous","run","checkChainedMethods","chainDepth","returnedBy","callback","body","returns","monadsAlongChain","returned","checkMixedMonads"],"sources":["../../src/rules/prefer-do-notation.ts"],"sourcesContent":["import type { Rule } from \"eslint\"\n\nimport type { ASTNode } from \"../types/ast\"\nimport { isChainedMethodCall } from \"../utils/functype-detection\"\nimport { isExtractableByType } from \"../utils/type-aware\"\n\nconst MONAD_TYPES: ReadonlySet<string> = new Set([\"Option\", \"Either\", \"Try\"])\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(...)\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\nconst CHAIN_METHODS: ReadonlySet<string> = new Set([\"flatMap\", \"map\", \"filter\", \"fold\"])\n\nconst FLAT_MAP: ReadonlySet<string> = new Set([\"flatMap\"])\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 * Number of `.flatMap()/.map()/.filter()/.fold()` steps walking left from `node`. Only the steps\n * count: the receiver they start from, `o` or `Option(x)`, is not a level, so\n * `Option(x).flatMap(f).flatMap(g)` is 2 deep.\n */\nfunction getChainDepth(node: ASTNode): number {\n if (node.type !== \"CallExpression\" || node.callee?.type !== \"MemberExpression\") return 0\n const method = node.callee.property\n const here = method.type === \"Identifier\" && CHAIN_METHODS.has(method.name) ? 1 : 0\n return here + getChainDepth(node.callee.object as ASTNode)\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/** The operands of an `a && b && c` chain, left to right, through any nesting of `&&`. */\nfunction andOperands(node: ASTNode): ReadonlyArray<ASTNode> {\n if (node.type !== \"LogicalExpression\" || node.operator !== \"&&\") return [node]\n return [...andOperands(node.left as ASTNode), ...andOperands(node.right as ASTNode)]\n}\n\n/** A plain property path a guard can start from: `a`, `this`, `a.b`. Optional chains are already the fix. */\nconst isPathStart = (node: ASTNode): boolean =>\n node.type === \"Identifier\" || node.type === \"ThisExpression\" || node.type === \"MemberExpression\"\n\nconst NONE: ReadonlySet<string> = new Set()\n\nconst FUNCTION_TYPES: ReadonlySet<string> = new Set([\n \"ArrowFunctionExpression\",\n \"FunctionExpression\",\n \"FunctionDeclaration\",\n])\n\n/** `MONAD_TYPES` entries a type annotation names: `Option<number>` → Option. */\nfunction monadOfAnnotation(annotation: ASTNode | undefined): ReadonlySet<string> {\n const type = annotation?.typeAnnotation as ASTNode | undefined\n if (type?.type !== \"TSTypeReference\" || type.typeName?.type !== \"Identifier\") return NONE\n return MONAD_TYPES.has(type.typeName.name) ? new Set([type.typeName.name]) : NONE\n}\n\n/**\n * Receiver names that say \"this holds a monad\", for code linted without type information: `option`,\n * `opt`, `either`, `result`, `maybe`, or a numbered one such as `option1`, in any case; or a\n * camelCase suffix such as `userOption` or `parseResult`, which must be capitalized, so `entry`,\n * `retry` and `registry` don't count.\n */\nconst MONAD_NAME = /^(option|opt|either|result|maybe)\\d*$/i\nconst MONAD_SUFFIX = /[a-z0-9](Option|Either|Result|Maybe|Try)\\d*$/\n\n/** Methods that turn one monad into another: `Try(f).toOption()` is an Option. */\nconst CONVERSIONS: ReadonlyMap<string, string> = new Map([\n [\"toOption\", \"Option\"],\n [\"toEither\", \"Either\"],\n [\"toTry\", \"Try\"],\n])\n\n/**\n * The monad an expression's value is, as far as the syntax shows: a constructor or companion call\n * (`Option(x)`, `Either.right(x)`), a conversion (`Try(f).toOption()` is an Option), a step that keeps\n * its receiver's monad (`Option(x).map(f)`), or either branch of `ok ? a : b`. Anything else is unknown.\n */\nfunction monadOfValue(node: ASTNode): ReadonlySet<string> {\n if (node.type === \"ConditionalExpression\")\n return union(monadOfValue(node.consequent as ASTNode), monadOfValue(node.alternate as ASTNode))\n if (node.type !== \"CallExpression\") return NONE\n if (monadAt(node).size > 0) return monadAt(node)\n if (node.callee?.type !== \"MemberExpression\" || node.callee.property.type !== \"Identifier\") return NONE\n const converted = CONVERSIONS.get(node.callee.property.name)\n if (converted !== undefined) return new Set([converted])\n return COMPOSITION_METHODS.has(node.callee.property.name) ? monadOfValue(node.callee.object as ASTNode) : NONE\n}\n\n/**\n * The receiver a method chain starts from: `Option(x)` in `Option(x).map(f).flatMap(g)`, `o` in\n * `o.flatMap(f)`. Walks back only through steps that keep the monad (`flatMap`, `map`, `filter`), so\n * in `Option(xs).getOrElse(() => []).flatMap(f)` or after a `.fold(…)` the root is the unwrapped value, not\n * `Option(xs)`. A monad constructor or companion\n * call is a root of its own.\n */\nfunction chainRoot(node: ASTNode): ASTNode {\n if (node.type !== \"CallExpression\" || monadAt(node).size > 0) return node\n if (node.callee?.type !== \"MemberExpression\" || node.callee.property.type !== \"Identifier\") return node\n if (!COMPOSITION_METHODS.has(node.callee.property.name)) return node\n return chainRoot(node.callee.object 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 messages: {\n preferDoForNestedChecks:\n \"This && chain guards each step of a property path. Use optional chaining (a?.b?.c), or Option(a).flatMap(…) when you want an Option\",\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 const text = (node: ASTNode): string => context.sourceCode.getText(node).replace(/\\s+/g, \"\")\n\n /** The monad a chain root is declared as, through its variable's or parameter's annotation. */\n function declaredMonad(identifier: ASTNode): ReadonlySet<string> {\n const variable = context.sourceCode\n .getScope(identifier)\n .references.find((reference) => reference.identifier === identifier)?.resolved\n const declared = variable?.defs[0]?.name as ASTNode | undefined\n return monadOfAnnotation(declared?.typeAnnotation as ASTNode | undefined)\n }\n\n /**\n * Is `step` a step on a functype monad? With type information, the type of the value it's called on\n * decides, so a `string[]`, or an Option already unwrapped with `.getOrElse(() => [])`, never counts, and\n * `service.getUser(1)` returning an Option does. Without it, the chain's root must be a monad\n * constructor, companion or conversion, an identifier annotated with a monad type, or one named\n * like a monad.\n */\n function onMonad(step: ASTNode): boolean {\n const byType = isExtractableByType(step.callee.object as ASTNode, context)\n if (byType !== undefined) return byType\n const root = chainRoot(step)\n if (monadOfValue(root).size > 0) return true\n if (root.type !== \"Identifier\") return false\n return declaredMonad(root).size > 0 || MONAD_NAME.test(root.name) || MONAD_SUFFIX.test(root.name)\n }\n\n /** The call that takes `node` as its receiver for a further `.flatMap/.map/.filter/.fold` step, if any. */\n function nextStep(node: ASTNode): ASTNode | undefined {\n const member = node.parent as ASTNode | undefined\n const call = member?.parent as ASTNode | undefined\n if (member?.type !== \"MemberExpression\" || member.object !== node) return undefined\n if (call?.type !== \"CallExpression\" || call.callee !== member) return undefined\n return member.property.type === \"Identifier\" && CHAIN_METHODS.has(member.property.name) ? call : undefined\n }\n\n /**\n * Is there a `methods` step further out on this chain? Then that step reports, once, for the whole\n * chain. A trailing `.fold(…)` or `.map(…)` isn't one, so it doesn't hide the flatMaps under it.\n */\n function hasStepAbove(node: ASTNode, methods: ReadonlySet<string>): boolean {\n const step = nextStep(node)\n if (step === undefined) return false\n const method = step.callee.property\n return (method.type === \"Identifier\" && methods.has(method.name)) || hasStepAbove(step, methods)\n }\n\n /**\n * `a && a.b && a.b.c`: at least three operands in a row, each a property of the one before it.\n * Matched on the AST, so `isAdmin && settings.theme && user.profile.name` is not a guard chain.\n */\n function checkNestedNullChecks(node: ASTNode): void {\n if (node.operator !== \"&&\") return\n const parent = node.parent as ASTNode | undefined\n if (parent?.type === \"LogicalExpression\" && parent.operator === \"&&\") return\n const operands = andOperands(node)\n const longestRun = operands.reduce<{ readonly run: number; readonly best: number }>(\n (acc, operand, i) => {\n const previous = operands[i - 1]\n const extends_ =\n previous !== undefined &&\n isPathStart(previous) &&\n operand.type === \"MemberExpression\" &&\n text(operand.object as ASTNode) === text(previous)\n const run = extends_ ? acc.run + 1 : 1\n return { run, best: Math.max(acc.best, run) }\n },\n { run: 0, best: 0 },\n ).best\n if (longestRun >= 3) context.report({ node, messageId: \"preferDoForNestedChecks\" })\n }\n\n /** A long `.flatMap(…)` chain on a monad, reported once at its outermost step. */\n function checkChainedMethods(node: ASTNode): void {\n if (!isChainedMethodCall(node, \"flatMap\") || hasStepAbove(node, FLAT_MAP)) return\n const chainDepth = getChainDepth(node)\n if (chainDepth < minChainDepth || !onMonad(node)) return\n context.report({\n node,\n messageId: \"preferDoForChainedMethods\",\n data: { count: chainDepth.toString() },\n })\n }\n\n /** What a step's callback returns: its expression body, or the arguments of its own `return`s. */\n function returnedBy(callback: ASTNode | undefined): ReadonlyArray<ASTNode> {\n if (callback?.type !== \"ArrowFunctionExpression\" && callback?.type !== \"FunctionExpression\") return []\n const body = callback.body as ASTNode\n if (body.type !== \"BlockStatement\") return [body]\n const returns = (node: ASTNode): ReadonlyArray<ASTNode> => {\n if (node.type === \"ReturnStatement\") return node.argument ? [node.argument as ASTNode] : []\n if (FUNCTION_TYPES.has(node.type)) return []\n return (astChildren(node) as ASTNode[]).flatMap(returns)\n }\n return returns(body)\n }\n\n /** The monads a composition chain moves through: its root, and what each step's callback returns. */\n function monadsAlongChain(node: ASTNode): ReadonlySet<string> {\n if (node.type === \"Identifier\") return declaredMonad(node)\n if (node.type !== \"CallExpression\" || node.callee?.type !== \"MemberExpression\") return monadAt(node)\n const method = node.callee.property\n const step =\n method.type === \"Identifier\" && COMPOSITION_METHODS.has(method.name)\n ? returnedBy(node.arguments[0] as ASTNode | undefined).reduce<ReadonlySet<string>>(\n (acc, returned) => union(acc, monadOfValue(returned)),\n NONE,\n )\n : NONE\n if (monadAt(node).size > 0) return union(step, monadAt(node))\n // From a conversion on, the chain is the converted monad: what it converted from doesn't count.\n const converted = method.type === \"Identifier\" ? CONVERSIONS.get(method.name) : undefined\n if (converted !== undefined) return union(step, new Set([converted]))\n return union(step, monadsAlongChain(node.callee.object as ASTNode))\n }\n\n /**\n * Mixed monads along one composition chain: `option.flatMap((x) => Either.right(x)).flatMap((y) => Try(…))`.\n * Only the chain's own steps count, not every monad written somewhere inside its callbacks, and\n * only a chain that starts from a monad: an array's `.map((x) => Option(x))` is not a mix.\n * Conversions such as `.toEither(…)` and terminal handlers such as `.fold(…)` are not steps (#205).\n */\n function checkMixedMonads(node: ASTNode): void {\n if (!detectMixedMonads || !isCompositionChain(node) || hasStepAbove(node, COMPOSITION_METHODS)) return\n if (!onMonad(node)) return\n if (monadsAlongChain(node).size >= 2) context.report({ node, messageId: \"preferDoForMixedMonads\" })\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,kIAMA,MAAME,kBAAmC,IAAI,IAAI,CAAC,SAAU,SAAU,KAAK,CAAC,EAGtEC,kBAAsC,IAAI,IAAI,CAAC,SAAU,MAAO,OAAO,CAAC,EAExEC,GAAYC,EAAmBC,oBAAsC,IAAI,IAAI,CAAC,GAAGD,EAAG,GAAGC,CAAC,CAAC,EAM/F,SAASC,EAAQC,EAAoC,CACnD,GAAIA,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,EAAYF,EAAmC,CACtD,OAAO,OAAO,QAAQA,CAAI,CAAC,CACxB,QAAQ,CAACG,KAAO,CAACR,EAAe,IAAIQ,CAAC,CAAC,CAAC,CACvC,SAAS,EAAGC,KAAQ,MAAM,QAAQA,CAAC,EAAIA,EAAI,CAACA,CAAC,CAAE,CAAC,CAChD,OAAQA,GAAoB,OAAOA,GAAM,YAA3BA,CAAmC,CACtD,CAEA,MAAMC,kBAAqC,IAAI,IAAI,CAAC,UAAW,MAAO,SAAU,MAAM,CAAC,EAEjFC,kBAAgC,IAAI,IAAI,CAAC,S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tB4C,EAAsB5C,CAAI,CAC5B,EAEA,eAAeA,EAAM,CACnBoD,EAAoBpD,CAAI,EACxB4D,EAAiB5D,CAAI,CACvB,CACF,CACF,CACF,E"}
@@ -1 +1 @@
1
- {"version":3,"file":"prefer-either.js","names":["insideCatchClause","parent","node","rule","HOST_THROWS_SCHEMA","options","context","allowInteropMarker","isExemptByMarker","isInsideTaggedDeclaration","allowThrowInTests","hostThrows","hostThrowsWith","isInTestFile","filename","enclosingFunction","isFunctionLike","nonEitherReturnType","returnType","fn","text","isDirectInFunctionBody","ifParent","isHostThrow","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 { HOST_THROWS_SCHEMA, hostThrowsWith, isHostThrow } from \"../utils/host-throws\"\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 hostThrows: HOST_THROWS_SCHEMA,\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 // `throw redirect(…)` / `throw notFound()` from a router is the router's API, not an error (#445).\n const hostThrows = hostThrowsWith(options.hostThrows)\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 if (isHostThrow(node.argument, hostThrows, context)) 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,4PAQA,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,EACA,WAAYC,CACd,EACA,qBAAsB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E,CACA,MAAO,EACT,CAEA,MAAO,CACL,eAAe,EAAe,CAO5B,GANId,EAAiBN,CAAI,GACrBqB,EAAYrB,EAAK,SAAUS,EAAYL,CAAO,GAE9CI,GAAqBG,EAAa,GAGlCb,EAAkBE,CAAI,EAAG,OAE7B,IAAMsB,EAAalB,EAAQ,WACrBmB,EAA6C,CAAC,EAEpD,GAAIJ,EAAuBnB,CAAI,EAAG,CAChC,IAAMwB,EAAWxB,EAAK,SAChByB,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,YAAY3B,EAAM,sBAAsB0B,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,IAAMN,EAAaD,EAAoBF,EAAkBb,CAAI,CAAC,EAC9DI,EAAQ,OAAO,CACb,OACA,GAAIY,IAAe,KACf,CAAE,UAAW,uBAAwB,EACrC,CAAE,UAAW,qBAAsB,KAAM,CAAE,KAAMA,CAAW,CAAE,EAClE,SACF,CAAC,CACH,CACF,CACF,CACF,E"}
1
+ {"version":3,"file":"prefer-either.js","names":["isInsideTaggedDeclaration","HOST_THROWS_SCHEMA","hostThrowsWith","isHostThrow","createImportFixer","hasFunctypeSymbol","insideCatchClause","node","parent","rule","context","options","allowInteropMarker","isExemptByMarker","allowThrowInTests","hostThrows","isInTestFile","filename","enclosingFunction","isFunctionLike","nonEitherReturnType","fn","returnType","text","isDirectInFunctionBody","ifParent","sourceCode","suggest","throwArg","argText","eitherArg","fixer"],"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 { HOST_THROWS_SCHEMA, hostThrowsWith, isHostThrow } from \"../utils/host-throws\"\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 hostThrows: HOST_THROWS_SCHEMA,\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 // `throw redirect(…)` / `throw notFound()` from a router is the router's API, not an error (#445).\n const hostThrows = hostThrowsWith(options.hostThrows)\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 if (isHostThrow(node.argument, hostThrows, context)) 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,4PAQA,SAASM,EAAkBC,EAA2C,CACpE,IAAMC,EAASD,GAAM,OAErB,OADKC,EACEA,EAAO,OAAS,eAAiBF,EAAkBE,CAAM,EAD5C,EAEtB,CAEA,MAAMC,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,EACA,WAAYR,CACd,EACA,qBAAsB,EACxB,CACF,EACA,SAAU,CACR,sBACE,8IACF,mBACE,8JACF,kBAAmB,gCACnB,iBAAkB,qCACpB,CACF,EAEA,OAAOS,EAAS,CACd,IAAMC,EAAUD,EAAQ,QAAQ,IAAM,CAAC,EAEjCE,EAAqBD,EAAQ,qBAAuB,GAEpDE,EAAoBN,GACxBK,GAAsBZ,EAA0BO,EAAA,UAAmBG,EAAQ,UAAU,EACjFI,EAAoBH,EAAQ,oBAAsB,GAElDI,EAAab,EAAeS,EAAQ,UAAU,EAEpD,SAASK,GAAe,CACtB,IAAMC,EAAWP,EAAQ,SACzB,MACE,kCAAkC,KAAKO,CAAQ,GAC/CA,EAAS,SAAS,WAAW,GAC7BA,EAAS,SAAS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tEF,EAAQ,KAAK,CACX,UAAW,oBACX,IAAII,EAAO,CACT,OAAOA,EAAM,YAAYxB,EAAM,sBAAsBuB,EAAU,EAAE,CACnE,CACF,CAAC,EAEIzB,EAAkBqB,EAAY,QAAQ,GACzCC,EAAQ,KAAK,CACX,UAAW,mBACX,KAAM,CAAE,OAAQ,QAAS,EACzB,IAAKvB,EAAkBsB,EAAY,QAAQ,CAC7C,CAAC,CAEL,CAIA,IAAMJ,EAAaF,EAAoBF,EAAkBX,CAAI,CAAC,EAC9DG,EAAQ,OAAO,CACbH,OACA,GAAIe,IAAe,KACf,CAAE,UAAW,uBAAwB,EACrC,CAAE,UAAW,qBAAsB,KAAM,CAAE,KAAMA,CAAW,CAAE,EAClEK,SACF,CAAC,CACH,CACF,CACF,CACF,E"}
@@ -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","isNonCollectionReceiver","receiver","isExtractableByType","isIOByType","sourceCode","mapCall","flatMapText","fixer","firstMapCallback"],"sources":["../../src/rules/prefer-flatmap.ts"],"sourcesContent":["import type { Rule } from \"eslint\"\n\nimport type { ASTNode } from \"../types/ast\"\nimport { isExtractableByType, isIOByType } from \"../utils/type-aware\"\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/IO 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 * The syntactic half of the receiver check, used with or without type information: the receiver\n * is literally a constructor or companion call, `Try(...)` / `Option(...)` / `Either.right(x)` /\n * etc. `.flatMap` on those expects the same container back, not an array. A bare identifier, an\n * array literal or an array-method chain can't be told apart without types, so it still reports;\n * `isNonCollectionReceiver` adds the type-aware check for those.\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 \"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 /**\n * Is `.map`'s receiver a container that isn't a collection, so `.flatMap` expects the same\n * container back and an array won't do (#520)? A literal constructor call counts. With type\n * information, so does any Option, Either, Try, Lazy or IO value, however it was\n * built: a variable, a parameter, a function's return. Collections (List, Set, arrays) have no\n * `orThrow` and aren't IO, so they still report. Without type information only the literal\n * call is recognized.\n */\n function isNonCollectionReceiver(receiver: ASTNode): boolean {\n return (\n isNonCollectionMonadReceiver(receiver) ||\n isExtractableByType(receiver, context) === true ||\n isIOByType(receiver, context) === true\n )\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) && !isNonCollectionReceiver(object.callee.object)) {\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 non-collection container: .flatMap on\n // Try / Option / Either / IO / etc. expects a wrapped value, not an array.\n if (object && isNonCollectionReceiver(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":"A,6EAMA,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,OAAS,eAAe,GAGpEF,EAAS,KAAM,GAAuBE,GAAMA,EAAG,OAAS,iBA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,CA5CA,CA6CF,CACF,CACF,CACF,E"}
1
+ {"version":3,"file":"prefer-flatmap.js","names":["isExtractableByType","isIOByType","ARRAY_PRODUCING_METHODS","rule","context","checkNestedMaps","isMapFollowedByFlat","node","callee","object","isFlattenCandidateArrayLiteral","arrayExpr","elements","el","chainRoot","boundNames","param","prop","isShapePreserving","functionNode","returned","root","returnsArray","call","methodName","stmt","returnsArrayShape","isNestedMapReturningArrays","callback","isNonCollectionMonadReceiver","monadConstructors","isNonCollectionReceiver","receiver","sourceCode","fixer","mapCall","flatMapText","firstMapCallback"],"sources":["../../src/rules/prefer-flatmap.ts"],"sourcesContent":["import type { Rule } from \"eslint\"\n\nimport type { ASTNode } from \"../types/ast\"\nimport { isExtractableByType, isIOByType } from \"../utils/type-aware\"\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/IO 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 * The syntactic half of the receiver check, used with or without type information: the receiver\n * is literally a constructor or companion call, `Try(...)` / `Option(...)` / `Either.right(x)` /\n * etc. `.flatMap` on those expects the same container back, not an array. A bare identifier, an\n * array literal or an array-method chain can't be told apart without types, so it still reports;\n * `isNonCollectionReceiver` adds the type-aware check for those.\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 \"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 /**\n * Is `.map`'s receiver a container that isn't a collection, so `.flatMap` expects the same\n * container back and an array won't do (#520)? A literal constructor call counts. With type\n * information, so does any Option, Either, Try, Lazy or IO value, however it was\n * built: a variable, a parameter, a function's return. Collections (List, Set, arrays) have no\n * `orThrow` and aren't IO, so they still report. Without type information only the literal\n * call is recognized.\n */\n function isNonCollectionReceiver(receiver: ASTNode): boolean {\n return (\n isNonCollectionMonadReceiver(receiver) ||\n isExtractableByType(receiver, context) === true ||\n isIOByType(receiver, context) === true\n )\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) && !isNonCollectionReceiver(object.callee.object)) {\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 non-collection container: .flatMap on\n // Try / Option / Either / IO / etc. expects a wrapped value, not an array.\n if (object && isNonCollectionReceiver(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":"A,6EAMA,MAAME,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,QA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B,GACEE,EAAO,OAAS,kBAChBA,EAAO,OAAO,OAAS,oBACvBA,EAAO,OAAO,SAAS,OAAS,MAChC,CAEA,IAAM4B,EAAmB5B,EAAO,UAAU,GAC1C,GAAI4B,GAAoBf,EAAae,CAAgB,GAAK,CAACN,EAAwBtB,EAAO,OAAO,MAAM,EAAG,CACxGL,EAAQ,OAAO,CACb,KAAMK,EACN,UAAW,oBACb,CAAC,EACD,MACF,CACF,CACF,CAGA,GAAIJ,GAAmBsB,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,OAoB5B,GAlBEE,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,OAO5CE,GAAUsB,EAAwBtB,CAAM,EAC1C,OAGFL,EAAQ,OAAO,CACbG,OACA,UAAW,qBACb,CAAC,CACH,CA5CA,CA6CF,CACF,CACF,CACF,E"}
@@ -1,2 +1,2 @@
1
- import{childNodes as e,descendants as t}from"../utils/ast-walk.js";import{containsAwait as n,containsYield as r}from"../utils/async-detection.js";import{isInsideTaggedDeclaration as i}from"../utils/boundary-tags.js";import{NEGATIVE_PREDICATES as a,POSITIVE_PREDICATES as o,compact as s}from"../utils/functype-predicates.js";const c={isSome:null,isNone:null,isRight:{param:`left`,member:`value`},isLeft:{param:`left`,member:`value`},isSuccess:{param:`error`,member:`error`},isFailure:{param:`error`,member:`error`}},l=[`get`,`orThrow`],u=`value`;function d(e){return e.type===`Literal`&&e.value===null||e.type===`Identifier`&&e.name===`undefined`}function f(e,t){if(e.type!==`CallExpression`||e.callee.type!==`MemberExpression`)return null;let n=e.callee.property.name,r=t.getText(e.callee.object),i=c[n]??null;return o.has(n)?{obj:r,isNegated:!1,failure:i}:a.has(n)?{obj:r,isNegated:!0,failure:i}:null}const p={members:[u],methods:l};function m(t,n,r,i){let a=e=>{let t=e.type===`TSNonNullExpression`?e.expression:e;return s(i.getText(t))===s(n)},o=(e,t)=>e.type===`MemberExpression`&&!e.computed&&e.property.type===`Identifier`&&t.includes(e.property.name)&&a(e.object),c=t=>{let n=t.parent,i=n?.type===`CallExpression`&&n.callee===t,a=n?.type===`AssignmentExpression`&&n.left===t||n?.type===`UpdateExpression`;return o(t,r.members)&&!i&&!a||t.type===`CallExpression`&&t.arguments.length===0&&o(t.callee,r.methods)?[t.range]:e(t).flatMap(c)};return c(t)}const h=(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}_`},g=(e,t)=>e.type===`ObjectExpression`||e.type===`SequenceExpression`?`(${t})`:t;function _(e,t,n,r,i){let a=i.getText(e),o=n===null?[]:m(e,t,n,i);if(o.length===0)return`() => ${g(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}) => ${g(e,c)}`}function v(e,t,n,r,i){let a=[i.getText(n),i.getText(r)],o=_(r,e,p,h(`value`,a),i);return`${e}.fold(${t===null?_(n,e,null,``,i):_(n,e,{members:[t.member],methods:[]},h(t.param,a),i)}, ${o})`}function y(e){let t=e.type===`BlockStatement`&&e.body.length===1?e.body[0]:e;return t.type===`ReturnStatement`&&t.argument?t.argument:null}function b(e){return e.alternate?e.alternate.type===`IfStatement`?1+b(e.alternate):2:1}const x=/* @__PURE__ */ new Set([`Left`,`None`,`Failure`,`left`,`none`,`failure`]);function S(e,n,r,i){return t(e).some(e=>e.type===`MemberExpression`&&!e.computed&&e.property.type===`Identifier`&&e.property.name===r&&s(i.getText(e.object))===n)}function C(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 w(e,t,n,r){let i=C(e);if(!i)return null;if(i.exit.type===`ThrowStatement`)return`throw`;if(i.extraWork)return`effect`;let a=i.exit.argument;if(!a)return`effect`;if(s(r.getText(a))===t)return`passthrough`;let o=a.type===`CallExpression`?a.callee:null,c=o?.type===`Identifier`?o.name:o?.type===`MemberExpression`&&o.property.type===`Identifier`?o.property.name:null;if(c&&x.has(c)){let e=a.arguments??[];return e.length===0||e.length===1&&n!==null&&s(r.getText(e[0]))===`${t}.${n}`?`passthrough`:`mappedFailure`}return n!==null&&S(a,t,n,r)?`effect`:`default`}function T(e,n,r){let i=e.flatMap(e=>t(e));return!i.some(e=>e.type===`AssignmentExpression`&&s(r.getText(e.left))===n)&&i.some(e=>{if(e.type!==`MemberExpression`||s(r.getText(e.object))!==n)return!1;let t=e.property.type===`Identifier`?e.property.name:null;if(t===u)return!0;let i=e.parent;return t===null||!l.includes(t)||i?.type!==`CallExpression`||i.callee!==e?!1:!(t===`orThrow`&&i.arguments.length>0)})}function E(e,t){if(e.type!==`IfStatement`||e.alternate)return null;let n=f(e.test,t);return!n?.isNegated||!C(e.consequent)?null:n}const D={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()`,suggestOrElse:`Replace with {{receiver}}.orElse(() => {{alternative}}) — keep the first when it is present, else the alternative`}},create(e){let t=e.options[0]||{},a=t.allowInteropMarker!==!1,o=t=>a&&i(t,`interop`,e.sourceCode),c=t.minComplexity||2,l=t.checkNullable===!0,u=t.checkGuards===!0,p=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 … }).`,m={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(…).getOrElse(() => 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 h(t){if(!u)return;let r=e.sourceCode,i=E(t,r);if(!i)return;let a=t.parent;if(a?.type!==`BlockStatement`&&a?.type!==`Program`)return;let o=a.body,c=o.slice(o.indexOf(t)+1),l=s(i.obj);if(!T(c,l,r))return;let d=w(t.consequent,l,i.failure?.member??null,r);if(!d)return;let f=c.some(e=>n(e)),h=(d===`passthrough`||d===`mappedFailure`)&&o.filter(e=>{let t=E(e,r);if(!t)return!1;let n=s(t.obj),i=o.slice(o.indexOf(e)+1),a=w(e.consequent,n,t.failure?.member??null,r);return(a===`passthrough`||a===`mappedFailure`)&&T(i,n,r)}).length>1;e.report({node:t,messageId:`preferFoldGuard`,data:{receiver:i.obj,advice:h?p(f):m[d](i.obj,f)}})}function g(t){let n=e.sourceCode;if(t.type!==`IfStatement`||!t.alternate)return null;let r=f(t.test,n);if(!r)return null;let i=y(t.consequent),a=y(t.alternate);if(!i||!a)return null;let o=[t.test,i,a];if(!n.getCommentsInside(t).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,d]=c?[i,a]:[a,i];return`return ${v(s,l,u,d,n)}`}function _(t){let i=e.sourceCode,a=f(t.test,i);if(!a)return[];let{obj:o,isNegated:c,failure:l}=a,[u,p]=c?[t.consequent,t.alternate]:[t.alternate,t.consequent],m=i.getText(u),h=i.getText(p);if(s(h)===s(o)){if(u.type===`Literal`||u.type===`TemplateLiteral`||d(u)||n(u)||r(u))return[];let e=m.trimStart().startsWith(`{`)||u.type===`SequenceExpression`?`(${m})`:m;return[{messageId:`suggestOrElse`,data:{receiver:o,alternative:m},fix:n=>n.replaceText(t,`${o}.orElse(() => ${e})`)}]}let g=v(o,l,u,p,i);return[{messageId:`suggestFold`,fix:e=>e.replaceText(t,g)}]}function x(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 S(t){let n=e.sourceCode.getText(t);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(l&&t.type===`BinaryExpression`){if((t.operator===`===`||t.operator===`!==`||t.operator===`==`||t.operator===`!=`)&&(t.left.type===`Literal`&&(t.left.value===null||t.left.value===void 0)||t.right.type===`Literal`&&(t.right.value===null||t.right.value===void 0)))return{isMonadic:!0,type:`Option`,via:`nullable`};if(t.operator===`==`||t.operator===`!=`||t.operator===`===`||t.operator===`!==`){let e=t.left.type===`Identifier`&&t.left.name===`undefined`,n=t.right.type===`Identifier`&&t.right.name===`undefined`;if(e||n)return{isMonadic:!0,type:`Option`,via:`nullable`}}}return{isMonadic:!1,type:``,via:``}}function C(e){if(!x(e.test))return[];let t=g(e);return t?[{messageId:`suggestFold`,fix:n=>n.replaceText(e,t)}]:[]}function D(t){let n=t.test,r=S(n);r.isMonadic&&(t.parent&&t.parent.type===`IfStatement`||b(t)>=c&&e.report({node:t,messageId:`preferFold`,data:{type:r.type},suggest:C(t)}))}return{IfStatement(e){o(e)||(D(e),h(e))},ConditionalExpression(t){if(o(t))return;let n=S(t.test);(n.via!==`nullable`||!d(t.consequent)&&!d(t.alternate))&&n.isMonadic&&e.report({node:t,messageId:`preferFoldTernary`,data:{type:n.type},suggest:x(t.test)?_(t):[]})}}}};export{D as default};
1
+ import{childNodes as e,descendants as t}from"../utils/ast-walk.js";import{containsAwait as n,containsYield as r}from"../utils/async-detection.js";import{isInsideTaggedDeclaration as i}from"../utils/boundary-tags.js";import{NEGATIVE_PREDICATES as a,POSITIVE_PREDICATES as o,compact as s}from"../utils/functype-predicates.js";const c={isSome:null,isNone:null,isRight:{param:`left`,member:`value`},isLeft:{param:`left`,member:`value`},isSuccess:{param:`error`,member:`error`},isFailure:{param:`error`,member:`error`}},l=[`get`,`orThrow`],u=`value`;function d(e){return e.type===`Literal`&&e.value===null||e.type===`Identifier`&&e.name===`undefined`}function f(e,t){if(e.type!==`CallExpression`||e.callee.type!==`MemberExpression`)return null;let n=e.callee.property.name,r=t.getText(e.callee.object),i=c[n]??null;return o.has(n)?{obj:r,isNegated:!1,failure:i}:a.has(n)?{obj:r,isNegated:!0,failure:i}:null}const p={members:[u],methods:l};function m(t,n,r,i){let a=e=>{let t=e.type===`TSNonNullExpression`?e.expression:e;return s(i.getText(t))===s(n)},o=(e,t)=>e.type===`MemberExpression`&&!e.computed&&e.property.type===`Identifier`&&t.includes(e.property.name)&&a(e.object),c=t=>{let n=t.parent,i=n?.type===`CallExpression`&&n.callee===t,a=n?.type===`AssignmentExpression`&&n.left===t||n?.type===`UpdateExpression`;return o(t,r.members)&&!i&&!a||t.type===`CallExpression`&&t.arguments.length===0&&o(t.callee,r.methods)?[t.range]:e(t).flatMap(c)};return c(t)}const h=(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}_`},g=(e,t)=>e.type===`ObjectExpression`||e.type===`SequenceExpression`?`(${t})`:t;function _(e,t,n,r,i){let a=i.getText(e),o=n===null?[]:m(e,t,n,i);if(o.length===0)return`() => ${g(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}) => ${g(e,c)}`}function v(e,t,n,r,i){let a=[i.getText(n),i.getText(r)],o=_(r,e,p,h(`value`,a),i);return`${e}.fold(${t===null?_(n,e,null,``,i):_(n,e,{members:[t.member],methods:[]},h(t.param,a),i)}, ${o})`}function y(e){let t=e.type===`BlockStatement`&&e.body.length===1?e.body[0]:e;return t.type===`ReturnStatement`&&t.argument?t.argument:null}function b(e){return e.alternate?e.alternate.type===`IfStatement`?1+b(e.alternate):2:1}const x=/* @__PURE__ */ new Set([`Left`,`None`,`Failure`,`left`,`none`,`failure`]);function S(e,n,r,i){return t(e).some(e=>e.type===`MemberExpression`&&!e.computed&&e.property.type===`Identifier`&&e.property.name===r&&s(i.getText(e.object))===n)}function C(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 w(e,t,n,r){let i=C(e);if(!i)return null;if(i.exit.type===`ThrowStatement`)return`throw`;if(i.extraWork)return`effect`;let a=i.exit.argument;if(!a)return`effect`;if(s(r.getText(a))===t)return`passthrough`;let o=a.type===`CallExpression`?a.callee:null,c=o?.type===`Identifier`?o.name:o?.type===`MemberExpression`&&o.property.type===`Identifier`?o.property.name:null;if(c&&x.has(c)){let e=a.arguments??[];return e.length===0||e.length===1&&n!==null&&s(r.getText(e[0]))===`${t}.${n}`?`passthrough`:`mappedFailure`}return n!==null&&S(a,t,n,r)?`effect`:`default`}function T(e,n,r){let i=e.flatMap(e=>t(e));return!i.some(e=>e.type===`AssignmentExpression`&&s(r.getText(e.left))===n)&&i.some(e=>{if(e.type!==`MemberExpression`||s(r.getText(e.object))!==n)return!1;let t=e.property.type===`Identifier`?e.property.name:null;if(t===u)return!0;let i=e.parent;return t===null||!l.includes(t)||i?.type!==`CallExpression`||i.callee!==e?!1:!(t===`orThrow`&&i.arguments.length>0)})}function E(e,t){if(e.type!==`IfStatement`||e.alternate)return null;let n=f(e.test,t);return!n?.isNegated||!C(e.consequent)?null:n}const D={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()`,suggestOrElse:`Replace with {{receiver}}.orElse(() => {{alternative}}) — keep the first when it is present, else the alternative`}},create(e){let t=e.options[0]||{},a=t.allowInteropMarker!==!1,o=t=>a&&i(t,`interop`,e.sourceCode),c=t.minComplexity||2,l=t.checkNullable===!0,u=t.checkGuards===!0,p=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 … }).`,m={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(…).getOrElse(() => 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 h(t){if(!u)return;let r=e.sourceCode,i=E(t,r);if(!i)return;let a=t.parent;if(a?.type!==`BlockStatement`&&a?.type!==`Program`)return;let o=a.body,c=o.slice(o.indexOf(t)+1),l=s(i.obj);if(!T(c,l,r))return;let d=w(t.consequent,l,i.failure?.member??null,r);if(!d)return;let f=c.some(e=>n(e)),h=(d===`passthrough`||d===`mappedFailure`)&&o.filter(e=>{let t=E(e,r);if(!t)return!1;let n=s(t.obj),i=o.slice(o.indexOf(e)+1),a=w(e.consequent,n,t.failure?.member??null,r);return(a===`passthrough`||a===`mappedFailure`)&&T(i,n,r)}).length>1;e.report({node:t,messageId:`preferFoldGuard`,data:{receiver:i.obj,advice:h?p(f):m[d](i.obj,f)}})}function g(t){let n=e.sourceCode;if(t.type!==`IfStatement`||!t.alternate)return null;let r=f(t.test,n);if(!r)return null;let i=y(t.consequent),a=y(t.alternate);if(!i||!a)return null;let o=[t.test,i,a];if(!n.getCommentsInside(t).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,d]=c?[i,a]:[a,i];return`return ${v(s,l,u,d,n)}`}function _(t){let i=e.sourceCode,a=f(t.test,i);if(!a)return[];let{obj:o,isNegated:c,failure:l}=a,[u,p]=c?[t.consequent,t.alternate]:[t.alternate,t.consequent],m=i.getText(u),h=i.getText(p);if(s(h)===s(o)){if(u.type===`Literal`||u.type===`TemplateLiteral`||d(u)||n(u)||r(u))return[];let e=m.trimStart().startsWith(`{`)||u.type===`SequenceExpression`?`(${m})`:m;return[{messageId:`suggestOrElse`,data:{receiver:o,alternative:m},fix:n=>n.replaceText(t,`${o}.orElse(() => ${e})`)}]}let g=v(o,l,u,p,i);return[{messageId:`suggestFold`,fix:e=>e.replaceText(t,g)}]}function x(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 S(t){let n=e.sourceCode.getText(t);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(l&&t.type===`BinaryExpression`){if((t.operator===`===`||t.operator===`!==`||t.operator===`==`||t.operator===`!=`)&&(t.left.type===`Literal`&&(t.left.value===null||t.left.value===void 0)||t.right.type===`Literal`&&(t.right.value===null||t.right.value===void 0)))return{isMonadic:!0,type:`Option`,via:`nullable`};if(t.operator===`==`||t.operator===`!=`||t.operator===`===`||t.operator===`!==`){let e=t.left.type===`Identifier`&&t.left.name===`undefined`,n=t.right.type===`Identifier`&&t.right.name===`undefined`;if(e||n)return{isMonadic:!0,type:`Option`,via:`nullable`}}}return{isMonadic:!1,type:``,via:``}}function C(e){if(!x(e.test))return[];let t=g(e);return t?[{messageId:`suggestFold`,fix:n=>n.replaceText(e,t)}]:[]}function D(t){let n=S(t.test);n.isMonadic&&(t.parent&&t.parent.type===`IfStatement`||b(t)>=c&&e.report({node:t,messageId:`preferFold`,data:{type:n.type},suggest:C(t)}))}return{IfStatement(e){o(e)||(D(e),h(e))},ConditionalExpression(t){if(o(t))return;let n=S(t.test);(n.via!==`nullable`||!d(t.consequent)&&!d(t.alternate))&&n.isMonadic&&e.report({node:t,messageId:`preferFoldTernary`,data:{type:n.type},suggest:x(t.test)?_(t):[]})}}}};export{D as default};
2
2
  //# sourceMappingURL=prefer-fold.js.map