eslint-plugin-functype 2.200.0 → 2.202.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +64 -2
- package/dist/cli/list-rules.js.map +1 -1
- package/dist/configs/recommended.d.ts +9 -1
- package/dist/configs/recommended.js +1 -1
- package/dist/configs/recommended.js.map +1 -1
- package/dist/index.d.ts +2 -0
- package/dist/index.js +1 -1
- package/dist/index.js.map +1 -1
- package/dist/rules/collection-naming.js.map +1 -1
- package/dist/rules/index.d.ts +22 -18
- package/dist/rules/index.js +1 -1
- package/dist/rules/index.js.map +1 -1
- package/dist/rules/must-fold-on-component-return.js.map +1 -1
- package/dist/rules/no-array-mutation.js.map +1 -1
- package/dist/rules/no-container-mutation.d.ts +21 -0
- package/dist/rules/no-container-mutation.js +2 -0
- package/dist/rules/no-container-mutation.js.map +1 -0
- package/dist/rules/no-floating-io.js.map +1 -1
- package/dist/rules/no-floating-result.js.map +1 -1
- package/dist/rules/no-get-unsafe.js.map +1 -1
- package/dist/rules/no-getOrThrow-in-render.js.map +1 -1
- package/dist/rules/no-imperative-loops.js.map +1 -1
- package/dist/rules/no-let.js.map +1 -1
- package/dist/rules/no-serialize-container.js.map +1 -1
- package/dist/rules/no-uncalled-method.d.ts +16 -0
- package/dist/rules/no-uncalled-method.js +2 -0
- package/dist/rules/no-uncalled-method.js.map +1 -0
- package/dist/rules/prefer-do-notation.js +1 -1
- package/dist/rules/prefer-do-notation.js.map +1 -1
- package/dist/rules/prefer-either.js.map +1 -1
- package/dist/rules/prefer-flatmap.js.map +1 -1
- package/dist/rules/prefer-fold.js +1 -1
- package/dist/rules/prefer-fold.js.map +1 -1
- package/dist/rules/prefer-functype-map.js.map +1 -1
- package/dist/rules/prefer-functype-set.js.map +1 -1
- package/dist/rules/prefer-list.js.map +1 -1
- package/dist/rules/prefer-map.js.map +1 -1
- package/dist/rules/prefer-option.js.map +1 -1
- package/dist/rules/prefer-try.js.map +1 -1
- package/dist/utils/array-mutation.d.ts +1 -1
- package/dist/utils/array-mutation.js.map +1 -1
- package/dist/utils/ast-walk.js.map +1 -1
- package/dist/utils/async-detection.js.map +1 -1
- package/dist/utils/boundary-tags.d.ts +1 -1
- package/dist/utils/boundary-tags.js.map +1 -1
- package/dist/utils/collection-binding.d.ts +1 -1
- package/dist/utils/collection-binding.js.map +1 -1
- package/dist/utils/dependency-validator.js.map +1 -1
- package/dist/utils/functype-detection.d.ts +1 -1
- package/dist/utils/functype-detection.js.map +1 -1
- package/dist/utils/functype-predicates.d.ts +1 -1
- package/dist/utils/functype-predicates.js.map +1 -1
- package/dist/utils/host-throws.d.ts +1 -1
- package/dist/utils/host-throws.js.map +1 -1
- package/dist/utils/import-fixer.js.map +1 -1
- package/dist/utils/mutable-collection.d.ts +1 -1
- package/dist/utils/mutable-collection.js.map +1 -1
- package/dist/utils/react-render.js.map +1 -1
- package/dist/utils/readonly-contract.js.map +1 -1
- package/dist/utils/type-aware.d.ts +22 -1
- package/dist/utils/type-aware.js +1 -1
- package/dist/utils/type-aware.js.map +1 -1
- package/dist/utils/wire-types.js.map +1 -1
- package/package.json +3 -3
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"no-floating-result.js","names":["CHECKED","FAILURE_HANDLERS","FAILURE_SOURCES","handlesItsFailure","node","callee","property","name","rule","
|
|
1
|
+
{"version":3,"file":"no-floating-result.js","names":["canCarryFailureByType","CHECKED","FAILURE_HANDLERS","FAILURE_SOURCES","handlesItsFailure","node","callee","property","name","rule","context","expression"],"sources":["../../src/rules/no-floating-result.ts"],"sourcesContent":["import type { Rule } from \"eslint\"\n\nimport type { ASTNode } from \"../types/ast\"\nimport { canCarryFailureByType } from \"../utils/type-aware\"\n\n/** `f()`, `a?.f()`, `await …`, and `ok && f()` / `ok ? f() : g()`: statements whose only job is a value. */\nconst CHECKED: ReadonlySet<string> = new Set([\n \"CallExpression\",\n \"ChainExpression\",\n \"AwaitExpression\",\n \"LogicalExpression\",\n \"ConditionalExpression\",\n])\n\n/** Methods that run a callback on the failure, so a chain through one has handled it. */\nconst FAILURE_HANDLERS: ReadonlySet<string> = new Set([\"tapError\", \"tapLeft\"])\n\n/** Methods that can bring in a new failure, so a handler before one no longer covers the result. */\nconst FAILURE_SOURCES: ReadonlySet<string> = new Set([\"flatMap\", \"chain\", \"andThen\", \"flatMapError\", \"orElse\"])\n\n/**\n * Does the call chain in `node` handle its own failure? Walks the receiver chain from the outermost\n * call in: a `.tapError(…)` or `.tapLeft(…)` counts, unless a later `.flatMap(…)` can bring in a new,\n * unlogged failure. Arguments are never walked into.\n */\nconst handlesItsFailure = (node: ASTNode | undefined): boolean => {\n if (!node) return false\n if (node.type === \"AwaitExpression\") return handlesItsFailure(node.argument as ASTNode)\n if (node.type === \"ChainExpression\") return handlesItsFailure(node.expression as ASTNode)\n if (node.type !== \"CallExpression\") return false\n const callee = node.callee as ASTNode\n if (callee.type !== \"MemberExpression\") return false\n const property = callee.property as ASTNode\n const name = property.type === \"Identifier\" ? (property.name as string) : \"\"\n if (FAILURE_HANDLERS.has(name)) return true\n if (FAILURE_SOURCES.has(name)) return false\n return handlesItsFailure(callee.object as ASTNode)\n}\n\n/**\n * Reports a statement that computes an Either, Try or other failure-carrying result and drops it:\n * `await userService.updateSubscription(id, plan)` on its own line, or `parse(input)`. A Left or a\n * Failure in it is silently ignored. `no-floating-promises` doesn't help, because awaiting the promise\n * satisfies it while the result inside is thrown away.\n *\n * Only results that can carry a failure count: an ignored Option or List loses no error. A chain that\n * handles its own failure with `.tapError(…)` or `.tapLeft(…)` isn't reported: that is a best-effort\n * write that logs a failure on purpose, as in agent-todo's audit and cleanup writes. `void result`\n * marks any other deliberate drop. An `IO` that is never run is no-floating-io's.\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 dropping an Either, Try or other result that can carry a failure\",\n recommended: false,\n },\n schema: [],\n messages: {\n floatingResult:\n \"This result is dropped, so a failure in it is silently ignored. Check isLeft() / isFailure(), fold it, or return it. Use void if dropping it is deliberate\",\n },\n },\n\n create(context) {\n return {\n ExpressionStatement(node: ASTNode) {\n const expression = node.expression as ASTNode\n // `void result` is a UnaryExpression, so a deliberate drop never gets this far.\n if (!CHECKED.has(expression.type) || handlesItsFailure(expression)) return\n if (canCarryFailureByType(expression, context))\n context.report({ node: expression, messageId: \"floatingResult\" })\n },\n }\n },\n}\n\nexport default rule\n"],"mappings":"A,+DAMA,MAAMC,kBAA+B,IAAI,IAAI,CAC3C,iBACA,kBACA,kBACA,oBACA,uBACF,CAAC,EAGKC,kBAAwC,IAAI,IAAI,CAAC,WAAY,SAAS,CAAC,EAGvEC,kBAAuC,IAAI,IAAI,CAAC,UAAW,QAAS,UAAW,eAAgB,QAAQ,CAAC,EAOxGC,EAAqBC,GAAuC,CAChE,GAAI,CAACA,EAAM,MAAO,GAClB,GAAIA,EAAK,OAAS,kBAAmB,OAAOD,EAAkBC,EAAK,QAAmB,EACtF,GAAIA,EAAK,OAAS,kBAAmB,OAAOD,EAAkBC,EAAK,UAAqB,EACxF,GAAIA,EAAK,OAAS,iBAAkB,MAAO,GAC3C,IAAMC,EAASD,EAAK,OACpB,GAAIC,EAAO,OAAS,mBAAoB,MAAO,GAC/C,IAAMC,EAAWD,EAAO,SAClBE,EAAOD,EAAS,OAAS,aAAgBA,EAAS,KAAkB,GAG1E,OAFIL,EAAiB,IAAIM,CAAI,EAAU,GACvC,CAAIL,EAAgB,IAAIK,CAAI,GACrBJ,EAAkBE,EAAO,MAAiB,CACnD,EAeMG,EAAwB,CAC5B,KAAM,CACJ,KAAM,UACN,KAAM,CACJ,YAAa,4EACb,YAAa,EACf,EACA,OAAQ,CAAC,EACT,SAAU,CACR,eACE,4JACJ,CACF,EAEA,OAAOC,EAAS,CACd,MAAO,CACL,oBAAoBL,EAAe,CACjC,IAAMM,EAAaN,EAAK,WAEnBJ,EAAQ,IAAIU,EAAW,IAAI,GAAKP,GAAkBO,CAAU,GAC7DX,EAAsBW,EAAYD,CAAO,GAC3CA,EAAQ,OAAO,CAAE,KAAMC,EAAY,UAAW,gBAAiB,CAAC,CACpE,CACF,CACF,CACF,E"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"no-get-unsafe.js","names":["DEFAULT_UNSAFE_METHODS","rule","
|
|
1
|
+
{"version":3,"file":"no-get-unsafe.js","names":["isInsideTaggedDeclaration","isExtractableByType","DEFAULT_UNSAFE_METHODS","rule","context","options","allowInTests","unsafeMethods","allowInteropMarker","isChosenErrorThrow","methodName","node","isInTestFile","filename","isMonadicType","text","varName","property","sourceCode","objectText","argsText","a","wasSuffix","fixer"],"sources":["../../src/rules/no-get-unsafe.ts"],"sourcesContent":["import type { Rule } from \"eslint\"\n\nimport type { ASTNode } from \"../types/ast\"\nimport { INTEROP_TAG, isInsideTaggedDeclaration } from \"../utils/boundary-tags\"\nimport { isExtractableByType } from \"../utils/type-aware\"\n\nconst DEFAULT_UNSAFE_METHODS: readonly string[] = [\"orThrow\", \"expect\", \"get\", \"getOrThrow\", \"unwrap\"]\n\nconst rule: Rule.RuleModule = {\n meta: {\n type: \"problem\",\n docs: {\n description: \"Avoid unsafe extractor calls on Option, Either, and other Extractable types\",\n recommended: true,\n },\n hasSuggestions: true,\n schema: [\n {\n type: \"object\",\n properties: {\n allowInTests: {\n type: \"boolean\",\n default: true,\n },\n allowInteropMarker: {\n type: \"boolean\",\n default: true,\n },\n unsafeMethods: {\n type: \"array\",\n items: { type: \"string\" },\n default: [...DEFAULT_UNSAFE_METHODS],\n },\n },\n additionalProperties: false,\n },\n ],\n messages: {\n noUnsafeGet:\n \"Avoid unsafe .{{method}}() call: it throws a generic error. Use .fold(), .map(), or .getOrElse(() => default) instead. If a host needs the throw, name the error: .orThrow((e) => new MyError(e))\",\n suggestGetOrElse: \"Replace with .getOrElse(() => default) for a value fallback\",\n suggestFold: \"Replace with .fold(onNone, onSome) for branch handling\",\n },\n },\n\n create(context) {\n const options = context.options[0] || {}\n const allowInTests = options.allowInTests !== false\n const unsafeMethods: readonly string[] = options.unsafeMethods || DEFAULT_UNSAFE_METHODS\n // `@interop <reason>` on an enclosing declaration marks a host-contract boundary, as in prefer-either.\n const allowInteropMarker = options.allowInteropMarker !== false\n\n /**\n * `.orThrow(error)` / `.orThrow((e) => error)`: the caller chose the error. That is the documented way\n * to throw for a host that needs it, not an unsafe extraction; `prefer-either` and the README's\n * decision table both treat it that way. Only a bare `.orThrow()` throws a generic error.\n */\n const isChosenErrorThrow = (methodName: string, node: ASTNode): boolean =>\n methodName === \"orThrow\" && node.arguments.length > 0\n\n function isInTestFile() {\n const filename = context.filename\n return (\n /\\.(test|spec)\\.(ts|js|tsx|jsx)$/.test(filename) ||\n filename.includes(\"__tests__\") ||\n filename.includes(\"/test/\") ||\n filename.includes(\"/tests/\")\n )\n }\n\n function isMonadicType(node: ASTNode): boolean {\n // This is a simplified check - in a real implementation, you'd want\n // more sophisticated type checking using TypeScript's type checker\n if (!node) return false\n\n const sourceCode = context.sourceCode\n\n // Check for common patterns that indicate monadic types\n const text = sourceCode.getText(node)\n\n // Direct type checks - constructors or type names\n if (/\\b(Option|Either|Maybe|Result|Some|None|Left|Right)\\b/.test(text)) {\n return true\n }\n\n // Method chains that suggest monadic operations\n if (/\\.(map|flatMap|filter|fold)\\s*\\(/.test(text)) {\n return true\n }\n\n // Variable names that suggest monadic types (case insensitive)\n if (/\\b(option|either|maybe|result|some|none|left|right)\\w*\\b/i.test(text)) {\n return true\n }\n\n // Check the specific node type and name\n if (node.type === \"Identifier\") {\n const varName = node.name.toLowerCase()\n if (/(option|either|maybe|result|some|none|left|right|opt)/.test(varName)) {\n return true\n }\n }\n\n // Check for CallExpression pattern like Some(\"test\").map()\n if (node.type === \"CallExpression\" && node.callee.type === \"MemberExpression\" && node.callee.object) {\n return isMonadicType(node.callee.object)\n }\n\n return false\n }\n\n return {\n CallExpression(node: ASTNode) {\n if (allowInTests && isInTestFile()) return\n\n if (node.callee.type !== \"MemberExpression\") return\n\n const property = node.callee.property\n if (!property || property.type !== \"Identifier\") return\n\n const methodName = property.name\n if (!unsafeMethods.includes(methodName)) return\n if (isChosenErrorThrow(methodName, node)) return\n if (allowInteropMarker && isInsideTaggedDeclaration(node, INTEROP_TAG, context.sourceCode)) return\n\n // With type information, the receiver's type decides: no name guessing, so `missing.orThrow()`\n // on an Option is reported and `options.get(\"k\")` on a native Map is not. Without it, fall\n // back to the name/shape heuristic.\n const byType = isExtractableByType(node.callee.object, context)\n if (byType ?? isMonadicType(node.callee.object)) {\n const sourceCode = context.sourceCode\n const objectText = sourceCode.getText(node.callee.object)\n\n // Preserve the original call's argument text in the TODO comment so a suggestion\n // applied to `.expect(\"Should have a user here\")` or `.orThrow(new NotFound())`\n // doesn't silently drop information the developer intended to keep. Omit the\n // \"was\" suffix when the original call had no args (`.get()`, `.unwrap()`, etc.).\n const argsText = node.arguments.map((a: ASTNode) => sourceCode.getText(a)).join(\", \")\n const wasSuffix = argsText ? `; was ${methodName}(${argsText})` : \"\"\n\n context.report({\n node,\n messageId: \"noUnsafeGet\",\n data: { method: methodName },\n suggest: [\n {\n messageId: \"suggestGetOrElse\",\n fix(fixer) {\n return fixer.replaceText(\n node,\n `${objectText}.getOrElse(() => undefined /* TODO: default${wasSuffix} */)`,\n )\n },\n },\n {\n messageId: \"suggestFold\",\n fix(fixer) {\n return fixer.replaceText(\n node,\n `${objectText}.fold(() => undefined /* TODO: onNone${wasSuffix} */, (v) => v /* TODO: onSome */)`,\n )\n },\n },\n ],\n })\n }\n },\n }\n },\n}\n\nexport default rule\n"],"mappings":"A,mIAMA,MAAME,EAA4C,CAAC,UAAW,SAAU,MAAO,aAAc,QAAQ,EAE/FC,EAAwB,CAC5B,KAAM,CACJ,KAAM,UACN,KAAM,CACJ,YAAa,8EACb,YAAa,EACf,EACA,eAAgB,GAChB,OAAQ,CACN,CACE,KAAM,SACN,WAAY,CACV,aAAc,CACZ,KAAM,UACN,QAAS,EAC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Ac,OAEjD,IAAMP,EAAaO,EAAS,KAC5B,GAAKV,EAAc,SAASG,CAAU,GAClCD,GAAmBC,EAAYC,CAAI,GACnCH,KAAsBR,EAA0BW,EAAA,UAAmBP,EAAQ,UAAU,KAK1EH,EAAoBU,EAAK,OAAO,OAAQP,CAC9C,GAAKU,EAAcH,EAAK,OAAO,MAAM,GAAG,CAC/C,IAAMO,EAAad,EAAQ,WACrBe,EAAaD,EAAW,QAAQP,EAAK,OAAO,MAAM,EAMlDS,EAAWT,EAAK,UAAU,IAAKU,GAAeH,EAAW,QAAQG,CAAC,CAAC,CAAC,CAAC,KAAK,IAAI,EAC9EC,EAAYF,EAAW,SAASV,EAAW,GAAGU,EAAS,GAAK,GAElEhB,EAAQ,OAAO,CACbO,OACA,UAAW,cACX,KAAM,CAAE,OAAQD,CAAW,EAC3B,QAAS,CACP,CACE,UAAW,mBACX,IAAIa,EAAO,CACT,OAAOA,EAAM,YACXZ,EACA,GAAGQ,EAAW,6CAA6CG,EAAU,KACvE,CACF,CACF,EACA,CACE,UAAW,cACX,IAAIC,EAAO,CACT,OAAOA,EAAM,YACXZ,EACA,GAAGQ,EAAW,uCAAuCG,EAAU,kCACjE,CACF,CACF,CACF,CACF,CAAC,CACH,CACF,CACF,CACF,CACF,E"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"no-getOrThrow-in-render.js","names":["
|
|
1
|
+
{"version":3,"file":"no-getOrThrow-in-render.js","names":["isInsideTaggedDeclaration","compact","provesWhen","enclosingFunction","renderKind","isExtractableByType","THROWING_METHODS","exits","statement","continuesWithValue","receiverText","sourceCode","call","isGuarded","stop","present","test","outcome","walk","child","node","branch","rule","context","allowInteropMarker","callee","method","fn"],"sources":["../../src/rules/no-getOrThrow-in-render.ts"],"sourcesContent":["import type { Rule, SourceCode } from \"eslint\"\n\nimport type { ASTNode } from \"../types/ast\"\nimport { INTEROP_TAG, isInsideTaggedDeclaration } from \"../utils/boundary-tags\"\nimport { compact, provesWhen } from \"../utils/functype-predicates\"\nimport { enclosingFunction, renderKind } from \"../utils/react-render\"\nimport { isExtractableByType } from \"../utils/type-aware\"\n\n/**\n * The extractors that throw a generic error when the value is missing. `orThrow` is the one functype's\n * containers carry; `getOrThrow` is its older name, which the rule is named after. Each is reported only\n * bare: `orThrow(error)` names the error, the way to send a failure to an error boundary on purpose.\n * `expect(handler)` is never reported, because its handler is the chosen throw.\n */\nconst THROWING_METHODS: ReadonlySet<string> = new Set([\"orThrow\", \"getOrThrow\"])\n\n/** A statement that leaves the function: `return …`, `throw …`, or a block that ends in one. */\nconst exits = (statement: ASTNode): boolean =>\n statement.type === \"ReturnStatement\" ||\n statement.type === \"ThrowStatement\" ||\n (statement.type === \"BlockStatement\" && statement.body.length > 0 && exits(statement.body.at(-1)))\n\n/**\n * Does `statement` only let control continue past it once the value is known to be there?\n *\n * - an early exit on the missing case: `if (!o.isSome()) return null`, `if (busy || o.isNone()) return <S />`,\n * `if (o.isEmpty) throw …`;\n * - an if / else-if chain whose every branch exits, except the way out that proves it:\n * `if (x) return <B />; else if (o.isNone()) return null`;\n * - `invariant(o.isSome(), \"…\")` from functype, which narrows the code after it.\n */\nconst continuesWithValue = (statement: ASTNode, receiverText: string, sourceCode: SourceCode): boolean => {\n if (statement.type === \"IfStatement\") {\n if (!exits(statement.consequent)) return false\n if (provesWhen(statement.test, false, receiverText, sourceCode) === \"present\") return true\n return statement.alternate ? continuesWithValue(statement.alternate, receiverText, sourceCode) : false\n }\n const call = statement.type === \"ExpressionStatement\" ? statement.expression : null\n return (\n call?.type === \"CallExpression\" &&\n call.callee.type === \"Identifier\" &&\n call.callee.name === \"invariant\" &&\n call.arguments.length > 0 &&\n provesWhen(call.arguments[0], true, receiverText, sourceCode) === \"present\"\n )\n}\n\n/**\n * Is the call inside a branch that already proved the value is there? `o.isSome() ? o.orThrow() : …`,\n * `!o.isSome() ? null : o.orThrow()`, `if (e.isRight()) return e.orThrow()`, `t.isSuccess() && t.orThrow()`,\n * or after a statement in an enclosing block that only continues once it is (`continuesWithValue`). Then\n * the call cannot throw.\n */\nconst isGuarded = (call: ASTNode, stop: ASTNode, receiverText: string, sourceCode: SourceCode): boolean => {\n const present = (test: ASTNode, outcome: boolean): boolean =>\n provesWhen(test, outcome, receiverText, sourceCode) === \"present\"\n\n const walk = (child: ASTNode, node: ASTNode | undefined): boolean => {\n if (!node || node === stop) return false\n const branch = node.type === \"IfStatement\" || node.type === \"ConditionalExpression\"\n if (branch && node.consequent === child && present(node.test, true)) return true\n if (branch && node.alternate === child && present(node.test, false)) return true\n if (node.type === \"LogicalExpression\" && node.right === child) {\n if (node.operator === \"&&\" && present(node.left, true)) return true\n if (node.operator === \"||\" && present(node.left, false)) return true\n }\n if (node.type === \"BlockStatement\") {\n const before = (node.body as ReadonlyArray<ASTNode>).slice(0, node.body.indexOf(child))\n if (before.some((statement) => continuesWithValue(statement, receiverText, sourceCode))) return true\n }\n return walk(node, node.parent)\n }\n return walk(call, call.parent)\n}\n\nconst rule: Rule.RuleModule = {\n meta: {\n type: \"problem\",\n docs: {\n description: \"Disallow a throwing extractor (.orThrow(), .getOrThrow()) in a React component or hook body\",\n recommended: false,\n },\n schema: [\n {\n type: \"object\",\n properties: {\n allowInteropMarker: {\n type: \"boolean\",\n default: true,\n },\n },\n additionalProperties: false,\n },\n ],\n messages: {\n throwInRender:\n \"{{receiver}}.{{method}}() throws during render when the value is missing, and a throw in render unmounts the tree up to the nearest error boundary. Render both cases with .fold(…) or <MatchOption> / <MatchEither> / <MatchTry>, or read a fallback with .getOrElse(() => …). To reach an error boundary on purpose, name the error: .orThrow((e) => new MyError(e))\",\n },\n },\n\n create(context) {\n const options = context.options[0] || {}\n // `@interop <reason>` on an enclosing declaration marks a host contract, such as React's `use()`.\n const allowInteropMarker = options.allowInteropMarker !== false\n const sourceCode = context.sourceCode\n\n return {\n CallExpression(node: ASTNode) {\n const callee = node.callee as ASTNode\n if (callee.type !== \"MemberExpression\" || callee.computed || callee.property.type !== \"Identifier\") return\n const method = callee.property.name as string\n if (!THROWING_METHODS.has(method) || node.arguments.length > 0) return\n\n // Only the component's or hook's own body runs during render. An event handler, an effect or a\n // `.map` callback is a separate function, so a call there is not attributed to the render.\n const fn = enclosingFunction(node)\n if (!fn || renderKind(fn) === null) return\n\n // With type information the receiver must be a functype container (it has `orThrow` and `fold`);\n // without it, the method name decides — `orThrow()` is functype's own spelling.\n if (isExtractableByType(callee.object, context) === false) return\n const receiverText = compact(sourceCode.getText(callee.object))\n if (isGuarded(node, fn, receiverText, sourceCode)) return\n if (allowInteropMarker && isInsideTaggedDeclaration(node, INTEROP_TAG, sourceCode)) return\n\n context.report({\n node,\n messageId: \"throwInRender\",\n data: { receiver: sourceCode.getText(callee.object), method },\n })\n },\n }\n },\n}\n\nexport default rule\n"],"mappings":"A,0RAcA,MAAMM,kBAAwC,IAAI,IAAI,CAAC,UAAW,YAAY,CAAC,EAGzEC,EAASC,GACbA,EAAU,OAAS,mBACnBA,EAAU,OAAS,kBAClBA,EAAU,OAAS,kBAAoBA,EAAU,KAAK,OAAS,GAAKD,EAAMC,EAAU,KAAK,GAAG,EAAE,CAAC,EAW5FC,GAAsBD,EAAoBE,EAAsBC,IAAoC,CACxG,GAAIH,EAAU,OAAS,cAGrB,OAFKD,EAAMC,EAAU,UAAU,EAC3BN,EAAWM,EAAU,KAAM,GAAOE,EAAcC,CAAU,IAAM,UAAkB,GAC/EH,EAAU,UAAYC,EAAmBD,EAAU,UAAWE,EAAcC,CAAU,EAAI,GAFxD,GAI3C,IAAMC,EAAOJ,EAAU,OAAS,sBAAwBA,EAAU,WAAa,KAC/E,OACEI,GAAM,OAAS,kBACfA,EAAK,OAAO,OAAS,cACrBA,EAAK,OAAO,OAAS,aACrBA,EAAK,UAAU,OAAS,GACxBV,EAAWU,EAAK,UAAU,GAAI,GAAMF,EAAcC,CAAU,IAAM,SAEtE,EAQME,GAAaD,EAAeE,EAAeJ,EAAsBC,IAAoC,CACzG,IAAMI,GAAWC,EAAeC,IAC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EAAK,UAAU,OAAS,EAAG,OAIhE,IAAMO,EAAKxB,EAAkBiB,CAAI,EAKjC,GAJI,CAACO,GAAMvB,EAAWuB,CAAE,IAAM,MAI1BtB,EAAoBoB,EAAO,OAAQF,CAAO,IAAM,GAAO,OAC3D,IAAMb,EAAeT,EAAQU,EAAW,QAAQc,EAAO,MAAM,CAAC,EAC1DZ,EAAUO,EAAMO,EAAIjB,EAAcC,CAAU,GAC5Ca,GAAsBxB,EAA0BoB,EAAA,UAAmBT,CAAU,GAEjFY,EAAQ,OAAO,CACbH,OACA,UAAW,gBACX,KAAM,CAAE,SAAUT,EAAW,QAAQc,EAAO,MAAM,EAAGC,QAAO,CAC9D,CAAC,CACH,CACF,CACF,CACF,E"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"no-imperative-loops.js","names":["
|
|
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,GA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BC,EAAa,GAEjCL,EAAQ,OAAO,CACbQ,OACA,UAAW,aACb,CAAC,CACH,EAEA,iBAAiBA,EAAe,CAC1BE,EAA0BF,CAAI,GAC9BL,GACAC,GAAgBC,EAAa,GAEjCL,EAAQ,OAAO,CACbQ,OACA,UAAW,eACb,CAAC,CACH,CACF,CACF,CACF,E"}
|
package/dist/rules/no-let.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"no-let.js","names":["rule","
|
|
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":["
|
|
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,C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AiBV,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){
|
|
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,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AI,EACnG,IAAMS,EAAST,EAAK,OAAO,SACrBuC,EACJ9B,EAAO,OAAS,cAAgBF,EAAoB,IAAIE,EAAO,IAAI,EAC/DgD,EAAWzD,EAAK,UAAU,EAAyB,CAAC,CAAC,QAClD,EAAK,IAAaJ,EAAMyD,EAAK9B,EAAauC,CAAQ,CAAC,EACpD/C,CACF,EACAA,EACN,GAAIhB,EAAQC,CAAI,CAAC,CAAC,KAAO,EAAG,OAAOJ,EAAM2C,EAAMxC,EAAQC,CAAI,CAAC,EAE5D,IAAMwB,EAAYf,EAAO,OAAS,aAAea,EAAY,IAAIb,EAAO,IAAI,EAAI,IAAA,GAEhF,OADIe,IAAc,IAAA,GACX5B,EAAM2C,EAAMsB,EAAiB7D,EAAK,OAAO,MAAiB,CAAC,EAD9BJ,EAAM2C,kBAAM,IAAI,IAAI,CAACf,CAAS,CAAC,CAAC,CAEtE,CAQA,SAASuC,EAAiB,EAAqB,CACxCjC,GAAsBlB,EAAmBZ,CAAI,GAAK,GAAaA,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,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,EAAaoC,CAAQ,CAAC,EACpD5C,CACF,EACAA,EACN,GAAIhB,EAAQC,CAAI,CAAC,CAAC,KAAO,EAAG,OAAOJ,EAAMwC,EAAMrC,EAAQC,CAAI,CAAC,EAE5D,IAAMwB,EAAYf,EAAO,OAAS,aAAea,EAAY,IAAIb,EAAO,IAAI,EAAI,IAAA,GAEhF,OADIe,IAAc,IAAA,GACX5B,EAAMwC,EAAMsB,EAAiB1D,EAAK,OAAO,MAAiB,CAAC,EAD9BJ,EAAMwC,kBAAM,IAAI,IAAI,CAACZ,CAAS,CAAC,CAAC,CAEtE,CAQA,SAASoC,EAAiB5D,EAAqB,CACxC8B,GAAsBlB,EAAmBZ,CAAI,GAAK0C,GAAa1C,EAAMO,CAAmB,GACxF4B,EAAQnC,CAAI,GACb0D,EAAiB1D,CAAI,CAAC,CAAC,MAAQ,GAAG2B,EAAQ,OAAO,CAAE3B,OAAM,UAAW,wBAAyB,CAAC,CACpG,CAEA,MAAO,CACL,kBAAkBA,EAAM,CACtB4C,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":["
|
|
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,QAAQ,GAC1BA,EAAS,SAAS,SAAS,CAE/B,CAGA,SAASC,EAAkBX,EAA+B,CACxD,IAAMC,EAASD,EAAK,OAEpB,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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,iBAAiB,CAClF,CAMA,SAASC,EAAU,EAAwB,CAWzC,OAVIP,EAAK,OAAS,iBAAyBO,EAAUP,EAAK,M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IOByType","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,QAAS,OACT,OAAQ,CACN,CACE,KAAM,SACN,WAAY,CACV,gBAAiB,CACf,KAAM,UACN,QAAS,EAC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