eslint-plugin-functype 2.106.2 → 2.107.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/dist/cli/list-rules.d.ts +1 -1
- package/dist/rules/index.d.ts +0 -1
- package/dist/rules/no-get-unsafe.d.ts +0 -1
- package/dist/rules/no-imperative-loops.d.ts +0 -1
- package/dist/rules/no-let.d.ts +0 -1
- package/dist/rules/prefer-do-notation.d.ts +0 -1
- package/dist/rules/prefer-either.d.ts +0 -1
- package/dist/rules/prefer-either.js +1 -1
- package/dist/rules/prefer-either.js.map +1 -1
- package/dist/rules/prefer-flatmap.d.ts +0 -1
- package/dist/rules/prefer-flatmap.js +1 -1
- package/dist/rules/prefer-flatmap.js.map +1 -1
- package/dist/rules/prefer-fold.d.ts +0 -1
- package/dist/rules/prefer-fold.js +1 -1
- package/dist/rules/prefer-fold.js.map +1 -1
- package/dist/rules/prefer-functype-map.d.ts +0 -1
- package/dist/rules/prefer-functype-set.d.ts +0 -1
- package/dist/rules/prefer-list.d.ts +0 -1
- package/dist/rules/prefer-map.d.ts +0 -1
- package/dist/rules/prefer-map.js +1 -1
- package/dist/rules/prefer-map.js.map +1 -1
- package/dist/rules/prefer-option.d.ts +0 -1
- package/dist/rules/prefer-try.d.ts +0 -1
- package/dist/utils/functype-detection.d.ts +0 -1
- package/dist/utils/functype-detection.js +1 -1
- package/dist/utils/functype-detection.js.map +1 -1
- package/dist/utils/import-fixer.d.ts +0 -1
- package/package.json +6 -6
package/dist/cli/list-rules.d.ts
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
export {
|
|
1
|
+
export {}
|
package/dist/rules/index.d.ts
CHANGED
|
@@ -11,7 +11,6 @@ import rule$9 from "./prefer-list.js";
|
|
|
11
11
|
import rule$10 from "./prefer-map.js";
|
|
12
12
|
import rule$11 from "./prefer-option.js";
|
|
13
13
|
import rule$12 from "./prefer-try.js";
|
|
14
|
-
|
|
15
14
|
//#region src/rules/index.d.ts
|
|
16
15
|
declare const _default: {
|
|
17
16
|
"prefer-option": import("eslint").Rule.RuleModule;
|
package/dist/rules/no-let.d.ts
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import{createImportFixer as e,hasFunctypeSymbol as t}from"../utils/import-fixer.js";const n=new Set([`parent`,`loc`,`range`]);function r(e){return Object.entries(e).filter(([e])=>!n.has(e)).flatMap(([,e])=>Array.isArray(e)?e:[e]).filter(e=>typeof e==`object`&&!!e)}function i(e){let t=e?.parent;return t?t.type===`CatchClause`||i(t):!1}const a={meta:{type:`suggestion`,hasSuggestions:!0,docs:{description:`Use Either/Left/Right for typed domain errors instead of throwing`,recommended:!0},schema:[{type:`object`,properties:{allowThrowInTests:{type:`boolean`,default:!0}},additionalProperties:!1}],messages:{preferEitherOverThrow:`Prefer Either.left(error) over throw statement`,preferEitherReturn:`Consider returning Either<Error, {{type}}> instead of throwing`,suggestEitherLeft:`Replace with Either.left(...)`,suggestAddImport:`Add {{symbol}} import from functype`}},create(n){let a=(n.options[0]||{}).allowThrowInTests!==!1;function o(){let e=n.filename;return/\.(test|spec)\.(ts|js|tsx|jsx)$/.test(e)||e.includes(`__tests__`)||e.includes(`/test/`)||e.includes(`/tests/`)}function s(e){return e?e.type===`ThrowStatement`?!i(e):e.type
|
|
1
|
+
import{createImportFixer as e,hasFunctypeSymbol as t}from"../utils/import-fixer.js";const n=new Set([`parent`,`loc`,`range`]);function r(e){return Object.entries(e).filter(([e])=>!n.has(e)).flatMap(([,e])=>Array.isArray(e)?e:[e]).filter(e=>typeof e==`object`&&!!e)}function i(e){let t=e?.parent;return t?t.type===`CatchClause`||i(t):!1}const a={meta:{type:`suggestion`,hasSuggestions:!0,docs:{description:`Use Either/Left/Right for typed domain errors instead of throwing`,recommended:!0},schema:[{type:`object`,properties:{allowThrowInTests:{type:`boolean`,default:!0}},additionalProperties:!1}],messages:{preferEitherOverThrow:`Prefer Either.left(error) over throw statement`,preferEitherReturn:`Consider returning Either<Error, {{type}}> instead of throwing`,suggestEitherLeft:`Replace with Either.left(...)`,suggestAddImport:`Add {{symbol}} import from functype`}},create(n){let a=(n.options[0]||{}).allowThrowInTests!==!1;function o(){let e=n.filename;return/\.(test|spec)\.(ts|js|tsx|jsx)$/.test(e)||e.includes(`__tests__`)||e.includes(`/test/`)||e.includes(`/tests/`)}function s(e){return e?e.type===`ThrowStatement`?!i(e):e.type!==`CatchClause`&&r(e).some(e=>s(e)):!1}function c(e){if(!(a&&o())&&e.body&&s(e.body)){let t=e.returnType?.typeAnnotation;if(t){let r=n.sourceCode.getText(t);r.includes(`Either`)||n.report({node:e.id||e,messageId:`preferEitherReturn`,data:{type:r}})}}}function l(e){return e?[`FunctionDeclaration`,`FunctionExpression`,`ArrowFunctionExpression`].includes(e.type):!1}function u(e){let t=e.parent;if(!t)return!1;if(t.type===`BlockStatement`&&l(t.parent))return!0;if(t.type===`BlockStatement`&&t.parent?.type===`IfStatement`){let e=t.parent.parent;return e?.type===`BlockStatement`&&l(e.parent)}return!1}return{ThrowStatement(r){if(a&&o()||i(r))return;let s=n.sourceCode,c=[];if(u(r)){let n=r.argument,i=s.getText(n),a=n?.type===`NewExpression`&&n.callee?.type===`Identifier`&&n.callee.name===`Error`?i:`new Error(String(${i}))`;c.push({messageId:`suggestEitherLeft`,fix(e){return e.replaceText(r,`return Either.left(${a})`)}}),t(s,`Either`)||c.push({messageId:`suggestAddImport`,data:{symbol:`Either`},fix:e(s,`Either`)})}n.report({node:r,messageId:`preferEitherOverThrow`,suggest:c})},FunctionDeclaration(e){c(e)},ArrowFunctionExpression(e){c(e)}}}};export{a as default};
|
|
2
2
|
//# sourceMappingURL=prefer-either.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"prefer-either.js","names":[],"sources":["../../src/rules/prefer-either.ts"],"sourcesContent":["import type { Rule } from \"eslint\"\n\nimport type { ASTNode } from \"../types/ast\"\nimport { createImportFixer, hasFunctypeSymbol } from \"../utils/import-fixer\"\n\n/** AST keys that don't represent syntax children — back-edges and source metadata. */\nconst NON_CHILD_KEYS: ReadonlySet<string> = new Set([\"parent\", \"loc\", \"range\"])\n\n/** AST children of `node` (drops back-edges, flattens array-valued keys, filters non-object leaves). */\nfunction astChildren(node: ASTNode): readonly unknown[] {\n return Object.entries(node)\n .filter(([k]) => !NON_CHILD_KEYS.has(k))\n .flatMap(([, v]) => (Array.isArray(v) ? v : [v]))\n .filter((v) => v !== null && typeof v === \"object\")\n}\n\n/** True iff any ancestor of `node` 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 allowThrowInTests: {\n type: \"boolean\",\n default: true,\n },\n },\n additionalProperties: false,\n },\n ],\n messages: {\n preferEitherOverThrow: \"Prefer Either.left(error) over throw statement\",\n preferEitherReturn: \"Consider returning Either<Error, {{type}}> instead of throwing\",\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 const allowThrowInTests = options.allowThrowInTests !== false\n\n function isInTestFile() {\n const filename = context.filename\n return (\n /\\.(test|spec)\\.(ts|js|tsx|jsx)$/.test(filename) ||\n filename.includes(\"__tests__\") ||\n filename.includes(\"/test/\") ||\n filename.includes(\"/tests/\")\n )\n }\n\n function hasThrowStatementsOutsideCatch(node: ASTNode): boolean {\n if (!node) return false\n\n // A throw that's *not* inside a catch is the thing we're looking for.\n if (node.type === \"ThrowStatement\") return !insideCatchClause(node)\n\n // Catch bodies don't count — re-throws inside them are allowed.\n if (node.type === \"CatchClause\") return false\n\n // Recurse: true iff any child satisfies the predicate.\n return astChildren(node).some((child) => hasThrowStatementsOutsideCatch(child as ASTNode))\n }\n\n function checkFunctionForThrows(node: ASTNode): void {\n // Allow functions in test files\n if (allowThrowInTests && isInTestFile()) return\n\n if (!node.body) return\n\n // Only report function-level errors if there are throws NOT in catch blocks\n const hasThrowsNotInCatch = hasThrowStatementsOutsideCatch(node.body)\n if (hasThrowsNotInCatch) {\n const returnType = node.returnType?.typeAnnotation\n if (returnType) {\n const sourceCode = context.sourceCode\n const returnTypeText = sourceCode.getText(returnType)\n\n // Don't report if already using Either\n if (!returnTypeText.includes(\"Either\")) {\n context.report({\n node: node.id || node,\n messageId: \"preferEitherReturn\",\n data: { type: returnTypeText },\n })\n }\n }\n }\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 // 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 context.report({\n node,\n messageId: \"preferEitherOverThrow\",\n suggest,\n })\n },\n\n FunctionDeclaration(node: ASTNode) {\n checkFunctionForThrows(node)\n },\n\n ArrowFunctionExpression(node: ASTNode) {\n checkFunctionForThrows(node)\n },\n }\n },\n}\n\nexport default rule\n"],"mappings":"oFAMA,MAAM,EAAsC,IAAI,IAAI,CAAC,SAAU,MAAO,OAAO,CAAC,EAG9E,SAAS,EAAY,EAAmC,CACtD,OAAO,OAAO,QAAQ,CAAI,CAAC,CACxB,QAAQ,CAAC,KAAO,CAAC,EAAe,IAAI,CAAC,CAAC,CAAC,CACvC,SAAS,EAAG,KAAQ,MAAM,QAAQ,CAAC,EAAI,EAAI,CAAC,CAAC,CAAE,CAAC,CAChD,OAAQ,GAAoB,OAAO,GAAM,YAA3B,CAAmC,CACtD,CAGA,SAAS,EAAkB,EAA2C,CACpE,IAAM,EAAS,GAAM,OAErB,OADK,EACE,EAAO,OAAS,eAAiB,EAAkB,CAAM,EAD5C,EAEtB,CAEA,MAAM,EAAwB,CAC5B,KAAM,CACJ,KAAM,aACN,eAAgB,GAChB,KAAM,CACJ,YAAa,oEACb,YAAa,EACf,EACA,OAAQ,CACN,CACE,KAAM,SACN,WAAY,CACV,kBAAmB,CACjB,KAAM,UACN,QAAS,EACX,CACF,EACA,qBAAsB,EACxB,CACF,EACA,SAAU,CACR,sBAAuB,iDACvB,mBAAoB,iEACpB,kBAAmB,gCACnB,iBAAkB,qCACpB,CACF,EAEA,OAAO,EAAS,CAEd,IAAM,GADU,EAAQ,QAAQ,IAAM,CAAC,EAAA,CACL,oBAAsB,GAExD,SAAS,GAAe,CACtB,IAAM,EAAW,EAAQ,SACzB,MACE,kCAAkC,KAAK,CAAQ,GAC/C,EAAS,SAAS,WAAW,GAC7B,EAAS,SAAS,QAAQ,GAC1B,EAAS,SAAS,SAAS,CAE/B,CAEA,SAAS,EAA+B,EAAwB,CAU9D,OATK,EAGD,EAAK,OAAS,iBAAyB,CAAC,EAAkB,CAAI,EAG9D,EAAK,OAAS,
|
|
1
|
+
{"version":3,"file":"prefer-either.js","names":[],"sources":["../../src/rules/prefer-either.ts"],"sourcesContent":["import type { Rule } from \"eslint\"\n\nimport type { ASTNode } from \"../types/ast\"\nimport { createImportFixer, hasFunctypeSymbol } from \"../utils/import-fixer\"\n\n/** AST keys that don't represent syntax children — back-edges and source metadata. */\nconst NON_CHILD_KEYS: ReadonlySet<string> = new Set([\"parent\", \"loc\", \"range\"])\n\n/** AST children of `node` (drops back-edges, flattens array-valued keys, filters non-object leaves). */\nfunction astChildren(node: ASTNode): readonly unknown[] {\n return Object.entries(node)\n .filter(([k]) => !NON_CHILD_KEYS.has(k))\n .flatMap(([, v]) => (Array.isArray(v) ? v : [v]))\n .filter((v) => v !== null && typeof v === \"object\")\n}\n\n/** True iff any ancestor of `node` 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 allowThrowInTests: {\n type: \"boolean\",\n default: true,\n },\n },\n additionalProperties: false,\n },\n ],\n messages: {\n preferEitherOverThrow: \"Prefer Either.left(error) over throw statement\",\n preferEitherReturn: \"Consider returning Either<Error, {{type}}> instead of throwing\",\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 const allowThrowInTests = options.allowThrowInTests !== false\n\n function isInTestFile() {\n const filename = context.filename\n return (\n /\\.(test|spec)\\.(ts|js|tsx|jsx)$/.test(filename) ||\n filename.includes(\"__tests__\") ||\n filename.includes(\"/test/\") ||\n filename.includes(\"/tests/\")\n )\n }\n\n function hasThrowStatementsOutsideCatch(node: ASTNode): boolean {\n if (!node) return false\n\n // A throw that's *not* inside a catch is the thing we're looking for.\n if (node.type === \"ThrowStatement\") return !insideCatchClause(node)\n\n // Catch bodies don't count — re-throws inside them are allowed.\n if (node.type === \"CatchClause\") return false\n\n // Recurse: true iff any child satisfies the predicate.\n return astChildren(node).some((child) => hasThrowStatementsOutsideCatch(child as ASTNode))\n }\n\n function checkFunctionForThrows(node: ASTNode): void {\n // Allow functions in test files\n if (allowThrowInTests && isInTestFile()) return\n\n if (!node.body) return\n\n // Only report function-level errors if there are throws NOT in catch blocks\n const hasThrowsNotInCatch = hasThrowStatementsOutsideCatch(node.body)\n if (hasThrowsNotInCatch) {\n const returnType = node.returnType?.typeAnnotation\n if (returnType) {\n const sourceCode = context.sourceCode\n const returnTypeText = sourceCode.getText(returnType)\n\n // Don't report if already using Either\n if (!returnTypeText.includes(\"Either\")) {\n context.report({\n node: node.id || node,\n messageId: \"preferEitherReturn\",\n data: { type: returnTypeText },\n })\n }\n }\n }\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 // 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 context.report({\n node,\n messageId: \"preferEitherOverThrow\",\n suggest,\n })\n },\n\n FunctionDeclaration(node: ASTNode) {\n checkFunctionForThrows(node)\n },\n\n ArrowFunctionExpression(node: ASTNode) {\n checkFunctionForThrows(node)\n },\n }\n },\n}\n\nexport default rule\n"],"mappings":"oFAMA,MAAM,EAAsC,IAAI,IAAI,CAAC,SAAU,MAAO,OAAO,CAAC,EAG9E,SAAS,EAAY,EAAmC,CACtD,OAAO,OAAO,QAAQ,CAAI,CAAC,CACxB,QAAQ,CAAC,KAAO,CAAC,EAAe,IAAI,CAAC,CAAC,CAAC,CACvC,SAAS,EAAG,KAAQ,MAAM,QAAQ,CAAC,EAAI,EAAI,CAAC,CAAC,CAAE,CAAC,CAChD,OAAQ,GAAoB,OAAO,GAAM,YAA3B,CAAmC,CACtD,CAGA,SAAS,EAAkB,EAA2C,CACpE,IAAM,EAAS,GAAM,OAErB,OADK,EACE,EAAO,OAAS,eAAiB,EAAkB,CAAM,EAD5C,EAEtB,CAEA,MAAM,EAAwB,CAC5B,KAAM,CACJ,KAAM,aACN,eAAgB,GAChB,KAAM,CACJ,YAAa,oEACb,YAAa,EACf,EACA,OAAQ,CACN,CACE,KAAM,SACN,WAAY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AAW,EAAO,OAAO,OAC/B,OAAO,GAAU,OAAS,kBAAoB,EAAe,EAAS,MAAM,CAC9E,CACA,MAAO,EACT,CAEA,MAAO,CACL,eAAe,EAAe,CAK5B,GAHI,GAAqB,EAAa,GAGlC,EAAkB,CAAI,EAAG,OAE7B,IAAM,EAAa,EAAQ,WACrB,EAA6C,CAAC,EAEpD,GAAI,EAAuB,CAAI,EAAG,CAChC,IAAM,EAAW,EAAK,SAChB,EAAU,EAAW,QAAQ,CAAQ,EAKrC,EAHJ,GAAU,OAAS,iBACnB,EAAS,QAAQ,OAAS,cAC1B,EAAS,OAAO,OAAS,QACK,EAAU,oBAAoB,EAAQ,IAEtE,EAAQ,KAAK,CACX,UAAW,oBACX,IAAI,EAAO,CACT,OAAO,EAAM,YAAY,EAAM,sBAAsB,EAAU,EAAE,CACnE,CACF,CAAC,EAEI,EAAkB,EAAY,QAAQ,GACzC,EAAQ,KAAK,CACX,UAAW,mBACX,KAAM,CAAE,OAAQ,QAAS,EACzB,IAAK,EAAkB,EAAY,QAAQ,CAC7C,CAAC,CAEL,CAEA,EAAQ,OAAO,CACb,OACA,UAAW,wBACX,SACF,CAAC,CACH,EAEA,oBAAoB,EAAe,CACjC,EAAuB,CAAI,CAC7B,EAEA,wBAAwB,EAAe,CACrC,EAAuB,CAAI,CAC7B,CACF,CACF,CACF"}
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
const e=new Set([`map`,`filter`,`slice`,`concat`,`split`]),t={meta:{type:`suggestion`,docs:{description:`Prefer .flatMap() over .map().flat() and nested transformations`,recommended:!0},fixable:`code`,schema:[{type:`object`,properties:{checkNestedMaps:{type:`boolean`,default:!0}},additionalProperties:!1}],messages:{preferFlatMapOverMapFlat:`Use .flatMap() instead of .map().flat()`,preferFlatMapNested:`Consider .flatMap() for nested transformations that return arrays`,preferFlatMapChain:`Use .flatMap() instead of chained .map() operations that flatten results`}},create(t){let n=(t.options[0]||{}).checkNestedMaps!==!1;function r(e){if(e.type!==`CallExpression`)return!1;let t=e.callee;if(t.type!==`MemberExpression`)return!1;if(t.property.name===`flat`){let e=t.object;if(e.type===`CallExpression`&&e.callee.type===`MemberExpression`&&e.callee.property.name===`map`)return!0}return!1}function i(e){let t=e.elements??[];return
|
|
1
|
+
const e=new Set([`map`,`filter`,`slice`,`concat`,`split`]),t={meta:{type:`suggestion`,docs:{description:`Prefer .flatMap() over .map().flat() and nested transformations`,recommended:!0},fixable:`code`,schema:[{type:`object`,properties:{checkNestedMaps:{type:`boolean`,default:!0}},additionalProperties:!1}],messages:{preferFlatMapOverMapFlat:`Use .flatMap() instead of .map().flat()`,preferFlatMapNested:`Consider .flatMap() for nested transformations that return arrays`,preferFlatMapChain:`Use .flatMap() instead of chained .map() operations that flatten results`}},create(t){let n=(t.options[0]||{}).checkNestedMaps!==!1;function r(e){if(e.type!==`CallExpression`)return!1;let t=e.callee;if(t.type!==`MemberExpression`)return!1;if(t.property.name===`flat`){let e=t.object;if(e.type===`CallExpression`&&e.callee.type===`MemberExpression`&&e.callee.property.name===`map`)return!0}return!1}function i(e){let t=e.elements??[];return!t.some(e=>e&&e.type===`SpreadElement`)&&t.some(e=>e&&e.type===`ArrayExpression`)}function a(t){if(!t||!t.body)return!1;if(t.body.type===`ArrayExpression`)return i(t.body);if(t.body.type===`CallExpression`){let n=t.body;if(n.callee.type===`MemberExpression`){let t=n.callee.property.name;if(e.has(t))return!0}}return t.body.type===`BlockStatement`&&t.body.body.some(o)}function o(t){return t.type!==`ReturnStatement`||!t.argument?!1:t.argument.type===`ArrayExpression`?i(t.argument):!!(t.argument.type===`CallExpression`&&t.argument.callee.type===`MemberExpression`&&e.has(t.argument.callee.property.name))}function s(e){if(e.type!==`CallExpression`)return!1;let t=e.callee;if(t.type!==`MemberExpression`)return!1;if(t.property.name===`map`){let t=e.arguments[0];if(t&&(t.type===`ArrowFunctionExpression`||t.type===`FunctionExpression`))return a(t)}return!1}function c(e){let t=new Set([`Option`,`Some`,`None`,`Either`,`Right`,`Left`,`Try`,`Success`,`Failure`,`Task`,`Ok`,`Err`,`IO`]);return!!(e.type===`CallExpression`&&e.callee?.type===`Identifier`&&t.has(e.callee.name)||e.type===`CallExpression`&&e.callee?.type===`MemberExpression`&&e.callee.object?.type===`Identifier`&&t.has(e.callee.object.name))}return{CallExpression(e){if(r(e)){let n=t.sourceCode;t.report({node:e,messageId:`preferFlatMapOverMapFlat`,fix(t){let r=e.callee.object,i=n.getText(r).replace(/\.map\s*\(/,`.flatMap(`);return t.replaceText(e,i)}});return}if(e.callee.type===`MemberExpression`&&e.callee.property.name===`map`){let n=e.callee.object;if(n.type===`CallExpression`&&n.callee.type===`MemberExpression`&&n.callee.property.name===`map`){let e=n.arguments[0];if(e&&a(e)){t.report({node:n,messageId:`preferFlatMapChain`});return}}}if(n&&s(e)){if(e.parent&&e.parent.type===`MemberExpression`&&e.parent.parent&&e.parent.parent.type===`CallExpression`&&e.parent.property.name===`flat`)return;let n=e.callee?.object;if(n?.type===`CallExpression`&&n.callee?.type===`MemberExpression`&&n.callee?.property?.name===`map`||e.parent?.type===`MemberExpression`&&e.parent.parent?.type===`CallExpression`&&e.parent.parent.callee?.property?.name===`map`||n&&c(n))return;t.report({node:e,messageId:`preferFlatMapNested`})}}}}};export{t as default};
|
|
2
2
|
//# sourceMappingURL=prefer-flatmap.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"prefer-flatmap.js","names":[],"sources":["../../src/rules/prefer-flatmap.ts"],"sourcesContent":["import type { Rule } from \"eslint\"\n\nimport type { ASTNode } from \"../types/ast\"\n\n/** Array-prototype methods whose call expression always returns an array. */\nconst ARRAY_PRODUCING_METHODS: ReadonlySet<string> = new Set([\"map\", \"filter\", \"slice\", \"concat\", \"split\"])\n\nconst rule: Rule.RuleModule = {\n meta: {\n type: \"suggestion\",\n docs: {\n description: \"Prefer .flatMap() over .map().flat() and nested transformations\",\n recommended: true,\n },\n fixable: \"code\",\n schema: [\n {\n type: \"object\",\n properties: {\n checkNestedMaps: {\n type: \"boolean\",\n default: true,\n },\n },\n additionalProperties: false,\n },\n ],\n messages: {\n preferFlatMapOverMapFlat: \"Use .flatMap() instead of .map().flat()\",\n preferFlatMapNested: \"Consider .flatMap() for nested transformations that return arrays\",\n preferFlatMapChain: \"Use .flatMap() instead of chained .map() operations that flatten results\",\n },\n },\n\n create(context) {\n const options = context.options[0] || {}\n const checkNestedMaps = options.checkNestedMaps !== false\n\n function isMapFollowedByFlat(node: ASTNode): boolean {\n if (node.type !== \"CallExpression\") return false\n\n const callee = node.callee\n if (callee.type !== \"MemberExpression\") return false\n\n // Check if this is .flat()\n if (callee.property.name === \"flat\") {\n const object = callee.object\n\n // Check if the object is a .map() call\n if (\n object.type === \"CallExpression\" &&\n object.callee.type === \"MemberExpression\" &&\n object.callee.property.name === \"map\"\n ) {\n return true\n }\n }\n\n return false\n }\n\n /**\n * Heuristic for array literals that look like flatten candidates.\n * Skips append/identity patterns (`[...arr, x]`, `[...arr]`) and tuple\n * shapes (`[k, v]`) — those are not nested arrays, so .flatMap()\n * doesn't apply. Only flag when at least one element is itself an\n * ArrayExpression, signaling a true nested-array shape.\n */\n function isFlattenCandidateArrayLiteral(arrayExpr: ASTNode): boolean {\n const elements = arrayExpr.elements ?? []\n if (elements.some((el: ASTNode | null) => el && el.type === \"SpreadElement\")) {\n return false\n }\n return elements.some((el: ASTNode | null) => el && el.type === \"ArrayExpression\")\n }\n\n 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 (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(returnsArrayShape)\n }\n\n return false\n }\n\n /** A single statement that's `return <array-shaped-expression>`. */\n function returnsArrayShape(stmt: ASTNode): boolean {\n if (stmt.type !== \"ReturnStatement\" || !stmt.argument) return false\n if (stmt.argument.type === \"ArrayExpression\") return isFlattenCandidateArrayLiteral(stmt.argument)\n if (\n stmt.argument.type === \"CallExpression\" &&\n stmt.argument.callee.type === \"MemberExpression\" &&\n ARRAY_PRODUCING_METHODS.has(stmt.argument.callee.property.name)\n ) {\n return true\n }\n return false\n }\n\n function isNestedMapReturningArrays(node: ASTNode): boolean {\n if (node.type !== \"CallExpression\") return false\n\n const callee = node.callee\n if (callee.type !== \"MemberExpression\") return false\n\n // Check if this is .map()\n if (callee.property.name === \"map\") {\n const callback = node.arguments[0]\n if (callback && (callback.type === \"ArrowFunctionExpression\" || callback.type === \"FunctionExpression\")) {\n return returnsArray(callback)\n }\n }\n\n return false\n }\n\n /**\n * Skip the warning when the receiver (`.map`'s left side) is a known\n * non-collection monad constructor call. The rule has no type info, so\n * it can't tell `arr.map(cb => arr2)` (collection, .flatMap is the fix)\n * from `Try(...).map(cb => arr)` (non-collection — .flatMap on Try\n * expects Try<T>, not an array, so .flatMap is NOT the fix).\n *\n * We can't enumerate every non-collection receiver, but we *can* detect\n * the unambiguous case: the receiver is literally `Try(...)` /\n * `Option(...)` / `Either(...)` / `Right(...)` / `Left(...)` / etc.\n * When that holds, suppress the warning. For bare identifiers (`items`)\n * or array literals or array-method chains, we can't tell, so the rule\n * still fires as before.\n */\n function isNonCollectionMonadReceiver(node: ASTNode): boolean {\n const monadConstructors = new Set([\n \"Option\",\n \"Some\",\n \"None\",\n \"Either\",\n \"Right\",\n \"Left\",\n \"Try\",\n \"Success\",\n \"Failure\",\n \"Task\",\n \"Ok\",\n \"Err\",\n \"IO\",\n ])\n // Bare constructor: Try(...), Option(...), Right(x), etc.\n if (\n node.type === \"CallExpression\" &&\n node.callee?.type === \"Identifier\" &&\n monadConstructors.has(node.callee.name)\n ) {\n return true\n }\n // Companion call: Either.right(x), Option.none(), Try.success(v)\n if (\n node.type === \"CallExpression\" &&\n node.callee?.type === \"MemberExpression\" &&\n node.callee.object?.type === \"Identifier\" &&\n monadConstructors.has(node.callee.object.name)\n ) {\n return true\n }\n return false\n }\n\n return {\n CallExpression(node: ASTNode) {\n // Check for .map().flat() pattern first (highest priority)\n if (isMapFollowedByFlat(node)) {\n const sourceCode = context.sourceCode\n\n context.report({\n node,\n messageId: \"preferFlatMapOverMapFlat\",\n fix(fixer) {\n // Get the .map() call\n const mapCall = (node.callee as ASTNode).object\n const mapCallText = sourceCode.getText(mapCall)\n\n // Replace .map() with .flatMap() and remove .flat()\n const flatMapText = mapCallText.replace(/\\.map\\s*\\(/, \".flatMap(\")\n\n return fixer.replaceText(node, flatMapText)\n },\n })\n return // Don't check other patterns if we found .map().flat()\n }\n\n // Check for chained maps where intermediate results are arrays (highest priority after map().flat())\n if (node.callee.type === \"MemberExpression\" && node.callee.property.name === \"map\") {\n const object = node.callee.object\n if (\n object.type === \"CallExpression\" &&\n object.callee.type === \"MemberExpression\" &&\n object.callee.property.name === \"map\"\n ) {\n // Check if the first map returns arrays\n const firstMapCallback = object.arguments[0]\n if (firstMapCallback && returnsArray(firstMapCallback)) {\n context.report({\n node: object, // Report on the first map call\n messageId: \"preferFlatMapChain\",\n })\n return // Don't check other patterns for this chain\n }\n }\n }\n\n // Check for nested maps that return arrays (but not if they're part of map().flat() or chains)\n if (checkNestedMaps && isNestedMapReturningArrays(node)) {\n // Don't flag if this map is immediately followed by flat()\n if (\n node.parent &&\n node.parent.type === \"MemberExpression\" &&\n node.parent.parent &&\n node.parent.parent.type === \"CallExpression\" &&\n node.parent.property.name === \"flat\"\n ) {\n return // Skip - this will be handled by the map().flat() rule\n }\n\n // Don't flag if this map is part of a chain (either as first or second map)\n const object = node.callee?.object\n if (\n object?.type === \"CallExpression\" &&\n object.callee?.type === \"MemberExpression\" &&\n object.callee?.property?.name === \"map\"\n ) {\n return // Skip - this is part of a chain\n }\n\n // Check if this map feeds into another map\n if (\n node.parent?.type === \"MemberExpression\" &&\n node.parent.parent?.type === \"CallExpression\" &&\n node.parent.parent.callee?.property?.name === \"map\"\n ) {\n return // Skip - this feeds into a chain\n }\n\n // Don't flag when the receiver is a known non-collection monad\n // constructor — .flatMap on Try / Option / Either / etc. expects\n // a wrapped value, not an array, so suggesting it is wrong.\n if (object && isNonCollectionMonadReceiver(object)) {\n return\n }\n\n context.report({\n node,\n messageId: \"preferFlatMapNested\",\n })\n }\n },\n }\n },\n}\n\nexport default rule\n"],"mappings":"AAKA,MAAM,EAA+C,IAAI,IAAI,CAAC,MAAO,SAAU,QAAS,SAAU,OAAO,CAAC,EAEpG,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,IAAM,GADU,EAAQ,QAAQ,IAAM,CAAC,EAAA,CACP,kBAAoB,GAEpD,SAAS,EAAoB,EAAwB,CACnD,GAAI,EAAK,OAAS,iBAAkB,MAAO,GAE3C,IAAM,EAAS,EAAK,OACpB,GAAI,EAAO,OAAS,mBAAoB,MAAO,GAG/C,GAAI,EAAO,SAAS,OAAS,OAAQ,CACnC,IAAM,EAAS,EAAO,OAGtB,GACE,EAAO,OAAS,kBAChB,EAAO,OAAO,OAAS,oBACvB,EAAO,OAAO,SAAS,OAAS,MAEhC,MAAO,EAEX,CAEA,MAAO,EACT,CASA,SAAS,EAA+B,EAA6B,CACnE,IAAM,EAAW,EAAU,UAAY,CAAC,EAIxC,OAHI,EAAS,KAAM,GAAuB,GAAM,EAAG,OAAS,eAAe,EAClE,GA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AW,qBACb,CAAC,CACH,CACF,CACF,CACF,CACF"}
|
|
1
|
+
{"version":3,"file":"prefer-flatmap.js","names":[],"sources":["../../src/rules/prefer-flatmap.ts"],"sourcesContent":["import type { Rule } from \"eslint\"\n\nimport type { ASTNode } from \"../types/ast\"\n\n/** Array-prototype methods whose call expression always returns an array. */\nconst ARRAY_PRODUCING_METHODS: ReadonlySet<string> = new Set([\"map\", \"filter\", \"slice\", \"concat\", \"split\"])\n\nconst rule: Rule.RuleModule = {\n meta: {\n type: \"suggestion\",\n docs: {\n description: \"Prefer .flatMap() over .map().flat() and nested transformations\",\n recommended: true,\n },\n fixable: \"code\",\n schema: [\n {\n type: \"object\",\n properties: {\n checkNestedMaps: {\n type: \"boolean\",\n default: true,\n },\n },\n additionalProperties: false,\n },\n ],\n messages: {\n preferFlatMapOverMapFlat: \"Use .flatMap() instead of .map().flat()\",\n preferFlatMapNested: \"Consider .flatMap() for nested transformations that return arrays\",\n preferFlatMapChain: \"Use .flatMap() instead of chained .map() operations that flatten results\",\n },\n },\n\n create(context) {\n const options = context.options[0] || {}\n const checkNestedMaps = options.checkNestedMaps !== false\n\n function isMapFollowedByFlat(node: ASTNode): boolean {\n if (node.type !== \"CallExpression\") return false\n\n const callee = node.callee\n if (callee.type !== \"MemberExpression\") return false\n\n // Check if this is .flat()\n if (callee.property.name === \"flat\") {\n const object = callee.object\n\n // Check if the object is a .map() call\n if (\n object.type === \"CallExpression\" &&\n object.callee.type === \"MemberExpression\" &&\n object.callee.property.name === \"map\"\n ) {\n return true\n }\n }\n\n return false\n }\n\n /**\n * Heuristic for array literals that look like flatten candidates.\n * Skips append/identity patterns (`[...arr, x]`, `[...arr]`) and tuple\n * shapes (`[k, v]`) — those are not nested arrays, so .flatMap()\n * doesn't apply. Only flag when at least one element is itself an\n * ArrayExpression, signaling a true nested-array shape.\n */\n function isFlattenCandidateArrayLiteral(arrayExpr: ASTNode): boolean {\n const elements = arrayExpr.elements ?? []\n if (elements.some((el: ASTNode | null) => el && el.type === \"SpreadElement\")) {\n return false\n }\n return elements.some((el: ASTNode | null) => el && el.type === \"ArrayExpression\")\n }\n\n 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 (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(returnsArrayShape)\n }\n\n return false\n }\n\n /** A single statement that's `return <array-shaped-expression>`. */\n function returnsArrayShape(stmt: ASTNode): boolean {\n if (stmt.type !== \"ReturnStatement\" || !stmt.argument) return false\n if (stmt.argument.type === \"ArrayExpression\") return isFlattenCandidateArrayLiteral(stmt.argument)\n if (\n stmt.argument.type === \"CallExpression\" &&\n stmt.argument.callee.type === \"MemberExpression\" &&\n ARRAY_PRODUCING_METHODS.has(stmt.argument.callee.property.name)\n ) {\n return true\n }\n return false\n }\n\n function isNestedMapReturningArrays(node: ASTNode): boolean {\n if (node.type !== \"CallExpression\") return false\n\n const callee = node.callee\n if (callee.type !== \"MemberExpression\") return false\n\n // Check if this is .map()\n if (callee.property.name === \"map\") {\n const callback = node.arguments[0]\n if (callback && (callback.type === \"ArrowFunctionExpression\" || callback.type === \"FunctionExpression\")) {\n return returnsArray(callback)\n }\n }\n\n return false\n }\n\n /**\n * Skip the warning when the receiver (`.map`'s left side) is a known\n * non-collection monad constructor call. The rule has no type info, so\n * it can't tell `arr.map(cb => arr2)` (collection, .flatMap is the fix)\n * from `Try(...).map(cb => arr)` (non-collection — .flatMap on Try\n * expects Try<T>, not an array, so .flatMap is NOT the fix).\n *\n * We can't enumerate every non-collection receiver, but we *can* detect\n * the unambiguous case: the receiver is literally `Try(...)` /\n * `Option(...)` / `Either(...)` / `Right(...)` / `Left(...)` / etc.\n * When that holds, suppress the warning. For bare identifiers (`items`)\n * or array literals or array-method chains, we can't tell, so the rule\n * still fires as before.\n */\n function isNonCollectionMonadReceiver(node: ASTNode): boolean {\n const monadConstructors = new Set([\n \"Option\",\n \"Some\",\n \"None\",\n \"Either\",\n \"Right\",\n \"Left\",\n \"Try\",\n \"Success\",\n \"Failure\",\n \"Task\",\n \"Ok\",\n \"Err\",\n \"IO\",\n ])\n // Bare constructor: Try(...), Option(...), Right(x), etc.\n if (\n node.type === \"CallExpression\" &&\n node.callee?.type === \"Identifier\" &&\n monadConstructors.has(node.callee.name)\n ) {\n return true\n }\n // Companion call: Either.right(x), Option.none(), Try.success(v)\n if (\n node.type === \"CallExpression\" &&\n node.callee?.type === \"MemberExpression\" &&\n node.callee.object?.type === \"Identifier\" &&\n monadConstructors.has(node.callee.object.name)\n ) {\n return true\n }\n return false\n }\n\n return {\n CallExpression(node: ASTNode) {\n // Check for .map().flat() pattern first (highest priority)\n if (isMapFollowedByFlat(node)) {\n const sourceCode = context.sourceCode\n\n context.report({\n node,\n messageId: \"preferFlatMapOverMapFlat\",\n fix(fixer) {\n // Get the .map() call\n const mapCall = (node.callee as ASTNode).object\n const mapCallText = sourceCode.getText(mapCall)\n\n // Replace .map() with .flatMap() and remove .flat()\n const flatMapText = mapCallText.replace(/\\.map\\s*\\(/, \".flatMap(\")\n\n return fixer.replaceText(node, flatMapText)\n },\n })\n return // Don't check other patterns if we found .map().flat()\n }\n\n // Check for chained maps where intermediate results are arrays (highest priority after map().flat())\n if (node.callee.type === \"MemberExpression\" && node.callee.property.name === \"map\") {\n const object = node.callee.object\n if (\n object.type === \"CallExpression\" &&\n object.callee.type === \"MemberExpression\" &&\n object.callee.property.name === \"map\"\n ) {\n // Check if the first map returns arrays\n const firstMapCallback = object.arguments[0]\n if (firstMapCallback && returnsArray(firstMapCallback)) {\n context.report({\n node: object, // Report on the first map call\n messageId: \"preferFlatMapChain\",\n })\n return // Don't check other patterns for this chain\n }\n }\n }\n\n // Check for nested maps that return arrays (but not if they're part of map().flat() or chains)\n if (checkNestedMaps && isNestedMapReturningArrays(node)) {\n // Don't flag if this map is immediately followed by flat()\n if (\n node.parent &&\n node.parent.type === \"MemberExpression\" &&\n node.parent.parent &&\n node.parent.parent.type === \"CallExpression\" &&\n node.parent.property.name === \"flat\"\n ) {\n return // Skip - this will be handled by the map().flat() rule\n }\n\n // Don't flag if this map is part of a chain (either as first or second map)\n const object = node.callee?.object\n if (\n object?.type === \"CallExpression\" &&\n object.callee?.type === \"MemberExpression\" &&\n object.callee?.property?.name === \"map\"\n ) {\n return // Skip - this is part of a chain\n }\n\n // Check if this map feeds into another map\n if (\n node.parent?.type === \"MemberExpression\" &&\n node.parent.parent?.type === \"CallExpression\" &&\n node.parent.parent.callee?.property?.name === \"map\"\n ) {\n return // Skip - this feeds into a chain\n }\n\n // Don't flag when the receiver is a known non-collection monad\n // constructor — .flatMap on Try / Option / Either / etc. expects\n // a wrapped value, not an array, so suggesting it is wrong.\n if (object && isNonCollectionMonadReceiver(object)) {\n return\n }\n\n context.report({\n node,\n messageId: \"preferFlatMapNested\",\n })\n }\n },\n }\n },\n}\n\nexport default rule\n"],"mappings":"AAKA,MAAM,EAA+C,IAAI,IAAI,CAAC,MAAO,SAAU,QAAS,SAAU,OAAO,CAAC,EAEpG,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,IAAM,GADU,EAAQ,QAAQ,IAAM,CAAC,EAAA,CACP,kBAAoB,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CAAI,EAAG,CAEvD,GACE,EAAK,QACL,EAAK,OAAO,OAAS,oBACrB,EAAK,OAAO,QACZ,EAAK,OAAO,OAAO,OAAS,kBAC5B,EAAK,OAAO,SAAS,OAAS,OAE9B,OAIF,IAAM,EAAS,EAAK,QAAQ,OAqB5B,GAnBE,GAAQ,OAAS,kBACjB,EAAO,QAAQ,OAAS,oBACxB,EAAO,QAAQ,UAAU,OAAS,OAOlC,EAAK,QAAQ,OAAS,oBACtB,EAAK,OAAO,QAAQ,OAAS,kBAC7B,EAAK,OAAO,OAAO,QAAQ,UAAU,OAAS,OAQ5C,GAAU,EAA6B,CAAM,EAC/C,OAGF,EAAQ,OAAO,CACb,OACA,UAAW,qBACb,CAAC,CACH,CACF,CACF,CACF,CACF"}
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
const e=new Set([`isSome`,`isRight`,`isSuccess`]),t=new Set([`isNone`,`isEmpty`,`isLeft`,`isFailure`]);function n(n,r){if(n.type!==`CallExpression`||n.callee.type!==`MemberExpression`)return null;let i=n.callee.property.name,a=r.getText(n.callee.object);return e.has(i)?{obj:a,isNegated:!1}:t.has(i)?{obj:a,isNegated:!0}:null}function
|
|
1
|
+
const e=new Set([`isSome`,`isRight`,`isSuccess`]),t=new Set([`isNone`,`isEmpty`,`isLeft`,`isFailure`]);function n(e){return e.type===`Literal`&&e.value===null||e.type===`Identifier`&&e.name===`undefined`}function r(n,r){if(n.type!==`CallExpression`||n.callee.type!==`MemberExpression`)return null;let i=n.callee.property.name,a=r.getText(n.callee.object);return e.has(i)?{obj:a,isNegated:!1}:t.has(i)?{obj:a,isNegated:!0}:null}function i(e){return e.alternate?e.alternate.type===`IfStatement`?1+i(e.alternate):2:1}const a={meta:{type:`suggestion`,docs:{description:`Prefer .fold() over if/else chains when working with monadic types`,recommended:!0},fixable:`code`,schema:[{type:`object`,properties:{minComplexity:{type:`integer`,minimum:1,default:2}},additionalProperties:!1}],messages:{preferFold:`Prefer .fold() over if/else when working with {{type}} types`,preferFoldTernary:`Consider using .fold() instead of ternary operator for {{type}}`}},create(e){let t=(e.options[0]||{}).minComplexity||2;function a(e,t){if(e.type===`BlockStatement`){let n=e.body;return n.length===1&&n[0].type===`ReturnStatement`?t.getText(n[0].argument):t.getText(e).slice(1,-1).trim()}else return t.getText(e)}function o(e,t){let n=t.replace(/[.*+?^${}()|[\]\\]/g,`\\$&`);return e.replace(RegExp(`${n}\\.get\\(\\)`,`g`),`value`)}function s(t){let n=e.sourceCode;if(t.type!==`IfStatement`)return null;let i=t.test,s=t.consequent,c=t.alternate;if(!s||!c)return null;let l=r(i,n);if(!l)return null;let{obj:u,isNegated:d}=l;if(s.type===`BlockStatement`&&(s.body.length!==1||s.body[0].type!==`ReturnStatement`))return null;if(c.type===`BlockStatement`){if(c.body.length!==1||c.body[0].type!==`ReturnStatement`)return null}else if(c.type===`IfStatement`)return null;let f=a(s,n),p=a(c,n);return d?`${u}.fold(() => ${f}, (value) => ${o(p,u)})`:`${u}.fold(() => ${p}, (value) => ${o(f,u)})`}function c(t){let n=e.sourceCode;if(t.type!==`ConditionalExpression`)return null;let i=t.test,a=t.consequent,s=t.alternate,c=r(i,n);if(!c)return null;let{obj:l,isNegated:u}=c,d=n.getText(a),f=n.getText(s);return u?`${l}.fold(() => ${d}, (value) => ${o(f,l)})`:`${l}.fold(() => ${f}, (value) => ${o(d,l)})`}function l(e){if(e.type===`CallExpression`&&e.callee.type===`MemberExpression`){let t=e.callee.property.name;return[`isSome`,`isNone`,`isEmpty`,`isRight`,`isLeft`,`isSuccess`,`isFailure`].includes(t)}return!1}function u(t){let n=e.sourceCode.getText(t);if(/\.(isSome|isNone|isEmpty|isDefined)\s*\(\s*\)/.test(n))return{isMonadic:!0,type:`Option`,via:`method`};if(/\.(isLeft|isRight)\s*\(\s*\)/.test(n))return{isMonadic:!0,type:`Either`,via:`method`};if(/\.(isSuccess|isFailure)\s*\(\s*\)/.test(n))return{isMonadic:!0,type:`Result`,via:`method`};if(t.type===`BinaryExpression`){if((t.operator===`===`||t.operator===`!==`||t.operator===`==`||t.operator===`!=`)&&(t.left.type===`Literal`&&(t.left.value===null||t.left.value===void 0)||t.right.type===`Literal`&&(t.right.value===null||t.right.value===void 0)))return{isMonadic:!0,type:`Option`,via:`nullable`};if(t.operator===`==`||t.operator===`!=`||t.operator===`===`||t.operator===`!==`){let e=t.left.type===`Identifier`&&t.left.name===`undefined`,n=t.right.type===`Identifier`&&t.right.name===`undefined`;if(e||n)return{isMonadic:!0,type:`Option`,via:`nullable`}}}return{isMonadic:!1,type:``,via:``}}function d(n){let r=n.test,a=u(r);a.isMonadic&&(n.parent&&n.parent.type===`IfStatement`||i(n)>=t&&e.report({node:n,messageId:`preferFold`,data:{type:a.type},fix(e){if(!l(n.test))return null;let t=s(n);return t?e.replaceText(n,t):null}}))}return{IfStatement(e){d(e)},ConditionalExpression(t){let r=u(t.test);r.via===`nullable`&&(n(t.consequent)||n(t.alternate))||r.isMonadic&&e.report({node:t,messageId:`preferFoldTernary`,data:{type:r.type},fix(e){if(!l(t.test))return null;let n=c(t);return n?e.replaceText(t,n):null}})}}}};export{a as default};
|
|
2
2
|
//# sourceMappingURL=prefer-fold.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"prefer-fold.js","names":[],"sources":["../../src/rules/prefer-fold.ts"],"sourcesContent":["import type { Rule, SourceCode } from \"eslint\"\n\nimport type { ASTNode } from \"../types/ast\"\n\n/** Methods on a monadic value that mean \"this is the Some/Right/Success path.\" */\nconst POSITIVE_PREDICATES: ReadonlySet<string> = new Set([\"isSome\", \"isRight\", \"isSuccess\"])\n/** Methods that mean \"this is the None/Left/Failure path.\" */\nconst NEGATIVE_PREDICATES: ReadonlySet<string> = new Set([\"isNone\", \"isEmpty\", \"isLeft\", \"isFailure\"])\n\n/**\n * If `test` is a monadic predicate call like `option.isSome()` or\n * `either.isLeft()`, returns the receiver expression's text plus whether the\n * predicate is the \"absence\" side. Returns null for anything else.\n */\nfunction extractMonadicTest(test: ASTNode, sourceCode: SourceCode): { obj: string; isNegated: boolean } | null {\n if (test.type !== \"CallExpression\" || test.callee.type !== \"MemberExpression\") return null\n const methodName = test.callee.property.name\n const obj = sourceCode.getText(test.callee.object)\n if (POSITIVE_PREDICATES.has(methodName)) return { obj, isNegated: false }\n if (NEGATIVE_PREDICATES.has(methodName)) return { obj, isNegated: true }\n return null\n}\n\n/**\n * Length of an if/else-if/else chain rooted at `node`. Counts the root as 1\n * and adds 1 per linked alternate IfStatement. Terminates on a non-If\n * alternate (the final `else { ... }`) which counts as the last branch.\n */\nfunction ifElseChainLength(node: ASTNode): number {\n if (!node.alternate) return 1\n if (node.alternate.type === \"IfStatement\") return 1 + ifElseChainLength(node.alternate as ASTNode)\n return 2 // root + the terminal else\n}\n\nconst rule: Rule.RuleModule = {\n meta: {\n type: \"suggestion\",\n docs: {\n description: \"Prefer .fold() over if/else chains when working with monadic types\",\n recommended: true,\n },\n fixable: \"code\",\n schema: [\n {\n type: \"object\",\n properties: {\n minComplexity: {\n type: \"integer\",\n minimum: 1,\n default: 2,\n },\n },\n additionalProperties: false,\n },\n ],\n messages: {\n preferFold: \"Prefer .fold() over if/else when working with {{type}} types\",\n preferFoldTernary: \"Consider using .fold() instead of ternary operator for {{type}}\",\n },\n },\n\n create(context) {\n const options = context.options[0] || {}\n const minComplexity = options.minComplexity || 2\n\n function extractBodyForFold(node: ASTNode, sourceCode: SourceCode): string {\n if (node.type === \"BlockStatement\") {\n const statements = node.body\n if (statements.length === 1 && statements[0].type === \"ReturnStatement\") {\n // Extract just the return value, not the return statement\n return sourceCode.getText(statements[0].argument)\n } else {\n // For complex blocks, keep the full structure but remove outer braces\n return sourceCode.getText(node).slice(1, -1).trim()\n }\n } else {\n return sourceCode.getText(node)\n }\n }\n\n function replaceGetWithValue(body: string, monadicObj: string): string {\n // Replace monadicObj.get() with value, and monadicObj.get().chain with value.chain\n const escaped = monadicObj.replace(/[.*+?^${}()|[\\]\\\\]/g, \"\\\\$&\")\n return body.replace(new RegExp(`${escaped}\\\\.get\\\\(\\\\)`, \"g\"), \"value\")\n }\n\n function generateFoldFromIf(node: ASTNode): string | null {\n const sourceCode = context.sourceCode\n\n if (node.type !== \"IfStatement\") return null\n\n const test = node.test\n const consequent = node.consequent\n const alternate = node.alternate\n\n if (!consequent || !alternate) return null\n\n // Extract the monadic object + negation from the test predicate.\n const extracted = extractMonadicTest(test, sourceCode)\n if (!extracted) return null\n const { obj: monadicObj, isNegated } = extracted\n\n // Only handle simple cases - single return statements in blocks, no nested if statements\n if (consequent.type === \"BlockStatement\") {\n if (consequent.body.length !== 1 || consequent.body[0].type !== \"ReturnStatement\") {\n return null // Too complex, don't auto-fix\n }\n }\n\n if (alternate.type === \"BlockStatement\") {\n if (alternate.body.length !== 1 || alternate.body[0].type !== \"ReturnStatement\") {\n return null // Too complex, don't auto-fix\n }\n } else if (alternate.type === \"IfStatement\") {\n return null // Nested if/else is too complex for simple fold pattern\n }\n\n // Extract consequent and alternate bodies\n const thenBody = extractBodyForFold(consequent, sourceCode)\n const elseBody = extractBodyForFold(alternate, sourceCode)\n\n // Generate fold expression — replace .get() calls with value parameter\n if (isNegated) {\n // isNone/isLeft/isFailure: consequent is the \"none\" branch, alternate is the \"some\" branch\n const successBody = replaceGetWithValue(elseBody, monadicObj)\n return `${monadicObj}.fold(() => ${thenBody}, (value) => ${successBody})`\n } else {\n // isSome/isRight/isSuccess: consequent is the \"some\" branch, alternate is the \"none\" branch\n const successBody = replaceGetWithValue(thenBody, monadicObj)\n return `${monadicObj}.fold(() => ${elseBody}, (value) => ${successBody})`\n }\n }\n\n function generateFoldFromTernary(node: ASTNode): string | null {\n const sourceCode = context.sourceCode\n\n if (node.type !== \"ConditionalExpression\") return null\n\n const test = node.test\n const consequent = node.consequent\n const alternate = node.alternate\n\n // Extract the monadic object + negation from the test predicate.\n const extracted = extractMonadicTest(test, sourceCode)\n if (!extracted) return null\n const { obj: monadicObj, isNegated } = extracted\n\n const thenExpr = sourceCode.getText(consequent)\n const elseExpr = sourceCode.getText(alternate)\n\n // Generate fold expression — replace .get() calls with value parameter\n if (isNegated) {\n const successExpr = replaceGetWithValue(elseExpr, monadicObj)\n return `${monadicObj}.fold(() => ${thenExpr}, (value) => ${successExpr})`\n } else {\n const successExpr = replaceGetWithValue(thenExpr, monadicObj)\n return `${monadicObj}.fold(() => ${elseExpr}, (value) => ${successExpr})`\n }\n }\n\n function shouldAutoFix(node: ASTNode): boolean {\n // Only auto-fix when we detect functype method calls (indicating it's already a functype instance)\n if (node.type === \"CallExpression\" && node.callee.type === \"MemberExpression\") {\n const methodName = node.callee.property.name\n // These methods indicate the object is already a functype instance\n return [\"isSome\", \"isNone\", \"isEmpty\", \"isRight\", \"isLeft\", \"isSuccess\", \"isFailure\"].includes(methodName)\n }\n return false\n }\n\n function isMonadicCheck(node: ASTNode): { isMonadic: boolean; type: string } {\n const sourceCode = context.sourceCode\n const text = sourceCode.getText(node)\n\n // Check for common monadic type checks\n if (/\\.(isSome|isNone|isEmpty|isDefined)\\s*\\(\\s*\\)/.test(text)) {\n return { isMonadic: true, type: \"Option\" }\n }\n\n if (/\\.(isLeft|isRight)\\s*\\(\\s*\\)/.test(text)) {\n return { isMonadic: true, type: \"Either\" }\n }\n\n if (/\\.(isSuccess|isFailure)\\s*\\(\\s*\\)/.test(text)) {\n return { isMonadic: true, type: \"Result\" }\n }\n\n // Check for null/undefined checks on variables that might be Options\n if (node.type === \"BinaryExpression\") {\n if (\n (node.operator === \"===\" || node.operator === \"!==\" || node.operator === \"==\" || node.operator === \"!=\") &&\n ((node.left.type === \"Literal\" && (node.left.value === null || node.left.value === undefined)) ||\n (node.right.type === \"Literal\" && (node.right.value === null || node.right.value === undefined)))\n ) {\n return { isMonadic: true, type: \"Option\" }\n }\n\n // Check for === or == with undefined identifier\n if (node.operator === \"==\" || node.operator === \"!=\" || node.operator === \"===\" || node.operator === \"!==\") {\n const leftIsUndefined = node.left.type === \"Identifier\" && node.left.name === \"undefined\"\n const rightIsUndefined = node.right.type === \"Identifier\" && node.right.name === \"undefined\"\n\n if (leftIsUndefined || rightIsUndefined) {\n return { isMonadic: true, type: \"Option\" }\n }\n }\n }\n\n return { isMonadic: false, type: \"\" }\n }\n\n function analyzeIfStatement(node: ASTNode) {\n const test = node.test\n const monadicInfo = isMonadicCheck(test)\n\n if (!monadicInfo.isMonadic) return\n\n // Don't analyze if this is part of a larger if/else chain\n // (only analyze the outermost if statement)\n if (node.parent && node.parent.type === \"IfStatement\") return\n\n // Count the complexity (if/else if/else chain)\n if (ifElseChainLength(node) >= minComplexity) {\n context.report({\n node,\n messageId: \"preferFold\",\n data: { type: monadicInfo.type },\n fix(fixer) {\n // Only auto-fix if we can detect it's already a functype instance\n if (!shouldAutoFix(node.test)) {\n return null\n }\n const replacement = generateFoldFromIf(node)\n if (replacement) {\n return fixer.replaceText(node, replacement)\n }\n return null\n },\n })\n }\n }\n\n return {\n IfStatement(node: ASTNode) {\n analyzeIfStatement(node)\n },\n\n ConditionalExpression(node: ASTNode) {\n const monadicInfo = isMonadicCheck(node.test)\n if (monadicInfo.isMonadic) {\n context.report({\n node,\n messageId: \"preferFoldTernary\",\n data: { type: monadicInfo.type },\n fix(fixer) {\n // Only auto-fix if we can detect it's already a functype instance\n if (!shouldAutoFix(node.test)) {\n return null\n }\n const replacement = generateFoldFromTernary(node)\n if (replacement) {\n return fixer.replaceText(node, replacement)\n }\n return null\n },\n })\n }\n },\n }\n },\n}\n\nexport default rule\n"],"mappings":"AAKA,MAAM,EAA2C,IAAI,IAAI,CAAC,SAAU,UAAW,WAAW,CAAC,EAErF,EAA2C,IAAI,IAAI,CAAC,SAAU,UAAW,SAAU,WAAW,CAAC,EAOrG,SAAS,EAAmB,EAAe,EAAoE,CAC7G,GAAI,EAAK,OAAS,kBAAoB,EAAK,OAAO,OAAS,mBAAoB,OAAO,KACtF,IAAM,EAAa,EAAK,OAAO,SAAS,KAClC,EAAM,EAAW,QAAQ,EAAK,OAAO,MAAM,EAGjD,OAFI,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IAAI,EAC1B,OAAO,KAET,IAAM,EAAc,EAAmB,CAAI,EAI3C,OAHI,EACK,EAAM,YAAY,EAAM,CAAW,EAErC,IACT,CACF,CAAC,EAEL,CAEA,MAAO,CACL,YAAY,EAAe,CACzB,EAAmB,CAAI,CACzB,EAEA,sBAAsB,EAAe,CACnC,IAAM,EAAc,EAAe,EAAK,IAAI,EACxC,EAAY,WACd,EAAQ,OAAO,CACb,OACA,UAAW,oBACX,KAAM,CAAE,KAAM,EAAY,IAAK,EAC/B,IAAI,EAAO,CAET,GAAI,CAAC,EAAc,EAAK,IAAI,EAC1B,OAAO,KAET,IAAM,EAAc,EAAwB,CAAI,EAIhD,OAHI,EACK,EAAM,YAAY,EAAM,CAAW,EAErC,IACT,CACF,CAAC,CAEL,CACF,CACF,CACF"}
|
|
1
|
+
{"version":3,"file":"prefer-fold.js","names":[],"sources":["../../src/rules/prefer-fold.ts"],"sourcesContent":["import type { Rule, SourceCode } from \"eslint\"\n\nimport type { ASTNode } from \"../types/ast\"\n\n/** Methods on a monadic value that mean \"this is the Some/Right/Success path.\" */\nconst POSITIVE_PREDICATES: ReadonlySet<string> = new Set([\"isSome\", \"isRight\", \"isSuccess\"])\n/** Methods that mean \"this is the None/Left/Failure path.\" */\nconst NEGATIVE_PREDICATES: ReadonlySet<string> = new Set([\"isNone\", \"isEmpty\", \"isLeft\", \"isFailure\"])\n\n/**\n * A literal `null` or the `undefined` identifier. A ternary that yields one of these in a branch is\n * building an optional value (prefer-option's concern), not folding a monad — so the untyped nullable\n * heuristic must not treat `x !== undefined ? \"a\" : undefined` as a fold candidate.\n */\nfunction isNullishLiteral(node: ASTNode): boolean {\n return (node.type === \"Literal\" && node.value === null) || (node.type === \"Identifier\" && node.name === \"undefined\")\n}\n\n/**\n * If `test` is a monadic predicate call like `option.isSome()` or\n * `either.isLeft()`, returns the receiver expression's text plus whether the\n * predicate is the \"absence\" side. Returns null for anything else.\n */\nfunction extractMonadicTest(test: ASTNode, sourceCode: SourceCode): { obj: string; isNegated: boolean } | null {\n if (test.type !== \"CallExpression\" || test.callee.type !== \"MemberExpression\") return null\n const methodName = test.callee.property.name\n const obj = sourceCode.getText(test.callee.object)\n if (POSITIVE_PREDICATES.has(methodName)) return { obj, isNegated: false }\n if (NEGATIVE_PREDICATES.has(methodName)) return { obj, isNegated: true }\n return null\n}\n\n/**\n * Length of an if/else-if/else chain rooted at `node`. Counts the root as 1\n * and adds 1 per linked alternate IfStatement. Terminates on a non-If\n * alternate (the final `else { ... }`) which counts as the last branch.\n */\nfunction ifElseChainLength(node: ASTNode): number {\n if (!node.alternate) return 1\n if (node.alternate.type === \"IfStatement\") return 1 + ifElseChainLength(node.alternate as ASTNode)\n return 2 // root + the terminal else\n}\n\nconst rule: Rule.RuleModule = {\n meta: {\n type: \"suggestion\",\n docs: {\n description: \"Prefer .fold() over if/else chains when working with monadic types\",\n recommended: true,\n },\n fixable: \"code\",\n schema: [\n {\n type: \"object\",\n properties: {\n minComplexity: {\n type: \"integer\",\n minimum: 1,\n default: 2,\n },\n },\n additionalProperties: false,\n },\n ],\n messages: {\n preferFold: \"Prefer .fold() over if/else when working with {{type}} types\",\n preferFoldTernary: \"Consider using .fold() instead of ternary operator for {{type}}\",\n },\n },\n\n create(context) {\n const options = context.options[0] || {}\n const minComplexity = options.minComplexity || 2\n\n function extractBodyForFold(node: ASTNode, sourceCode: SourceCode): string {\n if (node.type === \"BlockStatement\") {\n const statements = node.body\n if (statements.length === 1 && statements[0].type === \"ReturnStatement\") {\n // Extract just the return value, not the return statement\n return sourceCode.getText(statements[0].argument)\n } else {\n // For complex blocks, keep the full structure but remove outer braces\n return sourceCode.getText(node).slice(1, -1).trim()\n }\n } else {\n return sourceCode.getText(node)\n }\n }\n\n function replaceGetWithValue(body: string, monadicObj: string): string {\n // Replace monadicObj.get() with value, and monadicObj.get().chain with value.chain\n const escaped = monadicObj.replace(/[.*+?^${}()|[\\]\\\\]/g, \"\\\\$&\")\n return body.replace(new RegExp(`${escaped}\\\\.get\\\\(\\\\)`, \"g\"), \"value\")\n }\n\n function generateFoldFromIf(node: ASTNode): string | null {\n const sourceCode = context.sourceCode\n\n if (node.type !== \"IfStatement\") return null\n\n const test = node.test\n const consequent = node.consequent\n const alternate = node.alternate\n\n if (!consequent || !alternate) return null\n\n // Extract the monadic object + negation from the test predicate.\n const extracted = extractMonadicTest(test, sourceCode)\n if (!extracted) return null\n const { obj: monadicObj, isNegated } = extracted\n\n // Only handle simple cases - single return statements in blocks, no nested if statements\n if (consequent.type === \"BlockStatement\") {\n if (consequent.body.length !== 1 || consequent.body[0].type !== \"ReturnStatement\") {\n return null // Too complex, don't auto-fix\n }\n }\n\n if (alternate.type === \"BlockStatement\") {\n if (alternate.body.length !== 1 || alternate.body[0].type !== \"ReturnStatement\") {\n return null // Too complex, don't auto-fix\n }\n } else if (alternate.type === \"IfStatement\") {\n return null // Nested if/else is too complex for simple fold pattern\n }\n\n // Extract consequent and alternate bodies\n const thenBody = extractBodyForFold(consequent, sourceCode)\n const elseBody = extractBodyForFold(alternate, sourceCode)\n\n // Generate fold expression — replace .get() calls with value parameter\n if (isNegated) {\n // isNone/isLeft/isFailure: consequent is the \"none\" branch, alternate is the \"some\" branch\n const successBody = replaceGetWithValue(elseBody, monadicObj)\n return `${monadicObj}.fold(() => ${thenBody}, (value) => ${successBody})`\n } else {\n // isSome/isRight/isSuccess: consequent is the \"some\" branch, alternate is the \"none\" branch\n const successBody = replaceGetWithValue(thenBody, monadicObj)\n return `${monadicObj}.fold(() => ${elseBody}, (value) => ${successBody})`\n }\n }\n\n function generateFoldFromTernary(node: ASTNode): string | null {\n const sourceCode = context.sourceCode\n\n if (node.type !== \"ConditionalExpression\") return null\n\n const test = node.test\n const consequent = node.consequent\n const alternate = node.alternate\n\n // Extract the monadic object + negation from the test predicate.\n const extracted = extractMonadicTest(test, sourceCode)\n if (!extracted) return null\n const { obj: monadicObj, isNegated } = extracted\n\n const thenExpr = sourceCode.getText(consequent)\n const elseExpr = sourceCode.getText(alternate)\n\n // Generate fold expression — replace .get() calls with value parameter\n if (isNegated) {\n const successExpr = replaceGetWithValue(elseExpr, monadicObj)\n return `${monadicObj}.fold(() => ${thenExpr}, (value) => ${successExpr})`\n } else {\n const successExpr = replaceGetWithValue(thenExpr, monadicObj)\n return `${monadicObj}.fold(() => ${elseExpr}, (value) => ${successExpr})`\n }\n }\n\n function shouldAutoFix(node: ASTNode): boolean {\n // Only auto-fix when we detect functype method calls (indicating it's already a functype instance)\n if (node.type === \"CallExpression\" && node.callee.type === \"MemberExpression\") {\n const methodName = node.callee.property.name\n // These methods indicate the object is already a functype instance\n return [\"isSome\", \"isNone\", \"isEmpty\", \"isRight\", \"isLeft\", \"isSuccess\", \"isFailure\"].includes(methodName)\n }\n return false\n }\n\n // `via` records HOW we matched: a functype predicate call (`method`, precise) vs the untyped\n // null/undefined heuristic (`nullable`, a guess that can't tell a real Option from a plain nullable).\n function isMonadicCheck(node: ASTNode): { isMonadic: boolean; type: string; via: \"method\" | \"nullable\" | \"\" } {\n const sourceCode = context.sourceCode\n const text = sourceCode.getText(node)\n\n // Check for common monadic type checks\n if (/\\.(isSome|isNone|isEmpty|isDefined)\\s*\\(\\s*\\)/.test(text)) {\n return { isMonadic: true, type: \"Option\", via: \"method\" }\n }\n\n if (/\\.(isLeft|isRight)\\s*\\(\\s*\\)/.test(text)) {\n return { isMonadic: true, type: \"Either\", via: \"method\" }\n }\n\n if (/\\.(isSuccess|isFailure)\\s*\\(\\s*\\)/.test(text)) {\n return { isMonadic: true, type: \"Result\", via: \"method\" }\n }\n\n // Check for null/undefined checks on variables that might be Options\n if (node.type === \"BinaryExpression\") {\n if (\n (node.operator === \"===\" || node.operator === \"!==\" || node.operator === \"==\" || node.operator === \"!=\") &&\n ((node.left.type === \"Literal\" && (node.left.value === null || node.left.value === undefined)) ||\n (node.right.type === \"Literal\" && (node.right.value === null || node.right.value === undefined)))\n ) {\n return { isMonadic: true, type: \"Option\", via: \"nullable\" }\n }\n\n // Check for === or == with undefined identifier\n if (node.operator === \"==\" || node.operator === \"!=\" || node.operator === \"===\" || node.operator === \"!==\") {\n const leftIsUndefined = node.left.type === \"Identifier\" && node.left.name === \"undefined\"\n const rightIsUndefined = node.right.type === \"Identifier\" && node.right.name === \"undefined\"\n\n if (leftIsUndefined || rightIsUndefined) {\n return { isMonadic: true, type: \"Option\", via: \"nullable\" }\n }\n }\n }\n\n return { isMonadic: false, type: \"\", via: \"\" }\n }\n\n function analyzeIfStatement(node: ASTNode) {\n const test = node.test\n const monadicInfo = isMonadicCheck(test)\n\n if (!monadicInfo.isMonadic) return\n\n // Don't analyze if this is part of a larger if/else chain\n // (only analyze the outermost if statement)\n if (node.parent && node.parent.type === \"IfStatement\") return\n\n // Count the complexity (if/else if/else chain)\n if (ifElseChainLength(node) >= minComplexity) {\n context.report({\n node,\n messageId: \"preferFold\",\n data: { type: monadicInfo.type },\n fix(fixer) {\n // Only auto-fix if we can detect it's already a functype instance\n if (!shouldAutoFix(node.test)) {\n return null\n }\n const replacement = generateFoldFromIf(node)\n if (replacement) {\n return fixer.replaceText(node, replacement)\n }\n return null\n },\n })\n }\n }\n\n return {\n IfStatement(node: ASTNode) {\n analyzeIfStatement(node)\n },\n\n ConditionalExpression(node: ASTNode) {\n const monadicInfo = isMonadicCheck(node.test)\n // The untyped nullable heuristic can't distinguish a real Option from a plain nullable primitive.\n // When it fires on a ternary that yields `undefined`/`null` in a branch, that's optional value\n // construction (prefer-option's concern), not a fold — skip it. False positive this kills:\n // `x !== undefined ? \"a\" : undefined`. Predicate-call matches (`.isSome()` etc.) are unaffected.\n if (monadicInfo.via === \"nullable\" && (isNullishLiteral(node.consequent) || isNullishLiteral(node.alternate))) {\n return\n }\n if (monadicInfo.isMonadic) {\n context.report({\n node,\n messageId: \"preferFoldTernary\",\n data: { type: monadicInfo.type },\n fix(fixer) {\n // Only auto-fix if we can detect it's already a functype instance\n if (!shouldAutoFix(node.test)) {\n return null\n }\n const replacement = generateFoldFromTernary(node)\n if (replacement)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Each`,`for`]);function t(n){let r=n?.parent;return r?r.type===`CallExpression`&&r.callee.type===`MemberExpression`&&e.has(r.callee.property.name)?!0:t(r):!1}const n={meta:{type:`suggestion`,docs:{description:`Prefer .map() over manual transformations and imperative patterns`,recommended:!0},fixable:`code`,schema:[{type:`object`,properties:{checkArrayMethods:{type:`boolean`,default:!0},checkForLoops:{type:`boolean`,default:!0}},additionalProperties:!1}],messages:{preferMapOverLoop:`Prefer .map() over for loop for transforming {{collection}}`,preferMapOverPush:`Prefer .map() over manual .push() in loop`,preferMapChain:`Consider using .map() for transformation instead of manual property access`}},create(e){let n=e.options[0]||{},r=n.checkArrayMethods!==!1,i=n.checkForLoops!==!1;function a(e){if(e.type!==`CallExpression`||e.callee.type!==`MemberExpression`||e.callee.property.name!==`forEach`)return!1;let t=e.arguments[0];return t&&(t.type===`ArrowFunctionExpression`||t.type===`FunctionExpression`)?t.body.type===`MemberExpression`:!1}function o(e){if(!e.body||e.body.type!==`BlockStatement`)return!1;let t=e.body.body;return t.length
|
|
1
|
+
const e=new Set([`forEach`,`for`]);function t(n){let r=n?.parent;return r?r.type===`CallExpression`&&r.callee.type===`MemberExpression`&&e.has(r.callee.property.name)?!0:t(r):!1}const n={meta:{type:`suggestion`,docs:{description:`Prefer .map() over manual transformations and imperative patterns`,recommended:!0},fixable:`code`,schema:[{type:`object`,properties:{checkArrayMethods:{type:`boolean`,default:!0},checkForLoops:{type:`boolean`,default:!0}},additionalProperties:!1}],messages:{preferMapOverLoop:`Prefer .map() over for loop for transforming {{collection}}`,preferMapOverPush:`Prefer .map() over manual .push() in loop`,preferMapChain:`Consider using .map() for transformation instead of manual property access`}},create(e){let n=e.options[0]||{},r=n.checkArrayMethods!==!1,i=n.checkForLoops!==!1;function a(e){if(e.type!==`CallExpression`||e.callee.type!==`MemberExpression`||e.callee.property.name!==`forEach`)return!1;let t=e.arguments[0];return t&&(t.type===`ArrowFunctionExpression`||t.type===`FunctionExpression`)?t.body.type===`MemberExpression`:!1}function o(e){if(!e.body||e.body.type!==`BlockStatement`)return!1;let t=e.body.body;return t.length!==0&&t.some(e=>{if(e.type===`ExpressionStatement`&&e.expression.type===`CallExpression`){let t=e.expression;return t.callee.type===`MemberExpression`&&t.callee.property.name===`push`}return!1})}function s(e){if(e.type===`CallExpression`&&e.callee.type===`MemberExpression`&&e.callee.property.name===`forEach`){let t=e.arguments[0];if(t&&(t.type===`ArrowFunctionExpression`||t.type===`FunctionExpression`)&&t.body.type===`MemberExpression`)return!0}return!1}return{ForStatement(t){i&&o(t)&&e.report({node:t,messageId:`preferMapOverLoop`,data:{collection:`array`}})},ForInStatement(t){i&&o(t)&&e.report({node:t,messageId:`preferMapOverLoop`,data:{collection:`object`}})},ForOfStatement(t){i&&o(t)&&e.report({node:t,messageId:`preferMapOverLoop`,data:{collection:`iterable`}})},CallExpression(n){r&&(n.callee.type===`MemberExpression`&&n.callee.property.name===`forEach`&&s(n)&&e.report({node:n,messageId:`preferMapChain`,fix(t){if(!a(n))return null;let r=e.sourceCode.getText(n).replace(/\.forEach\s*\(/g,`.map(`);return t.replaceText(n,r)}}),n.callee.type===`MemberExpression`&&n.callee.property.name===`push`&&t(n)&&e.report({node:n,messageId:`preferMapOverPush`}))}}}};export{n as default};
|
|
2
2
|
//# sourceMappingURL=prefer-map.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"prefer-map.js","names":[],"sources":["../../src/rules/prefer-map.ts"],"sourcesContent":["import type { Rule } from \"eslint\"\n\nimport type { ASTNode } from \"../types/ast\"\n\nconst ITERATION_METHOD_NAMES: ReadonlySet<string> = new Set([\"forEach\", \"for\"])\n\n/** True iff any ancestor of `node` is a `.forEach(...)` or `.for(...)` call. */\nfunction insideIterationCallback(node: ASTNode | null | undefined): boolean {\n const parent = node?.parent as ASTNode | undefined\n if (!parent) return false\n if (\n parent.type === \"CallExpression\" &&\n parent.callee.type === \"MemberExpression\" &&\n ITERATION_METHOD_NAMES.has(parent.callee.property.name)\n ) {\n return true\n }\n return insideIterationCallback(parent)\n}\n\nconst rule: Rule.RuleModule = {\n meta: {\n type: \"suggestion\",\n docs: {\n description: \"Prefer .map() over manual transformations and imperative patterns\",\n recommended: true,\n },\n fixable: \"code\",\n schema: [\n {\n type: \"object\",\n properties: {\n checkArrayMethods: {\n type: \"boolean\",\n default: true,\n },\n checkForLoops: {\n type: \"boolean\",\n default: true,\n },\n },\n additionalProperties: false,\n },\n ],\n messages: {\n preferMapOverLoop: \"Prefer .map() over for loop for transforming {{collection}}\",\n preferMapOverPush: \"Prefer .map() over manual .push() in loop\",\n preferMapChain: \"Consider using .map() for transformation instead of manual property access\",\n },\n },\n\n create(context) {\n const options = context.options[0] || {}\n const checkArrayMethods = options.checkArrayMethods !== false\n const checkForLoops = options.checkForLoops !== false\n\n function isForEachToMapSafe(node: ASTNode): boolean {\n // Only auto-fix simple forEach → map transformations on expressions that return values\n // This is safe because both native arrays and functype Lists have these methods\n if (\n node.type !== \"CallExpression\" ||\n node.callee.type !== \"MemberExpression\" ||\n node.callee.property.name !== \"forEach\"\n ) {\n return false\n }\n\n // Check if the callback returns a value (simple property access pattern)\n const callback = node.arguments[0]\n if (callback && (callback.type === \"ArrowFunctionExpression\" || callback.type === \"FunctionExpression\")) {\n const body = callback.body\n // Simple property access in arrow function (e.g., item => item.name)\n return body.type === \"MemberExpression\"\n }\n return false\n }\n\n function isTransformationLoop(node: ASTNode): boolean {\n if (!node.body || node.body.type !== \"BlockStatement\") return false\n\n const statements = node.body.body\n if (statements.length === 0) return false\n\n // Look for patterns like: newArray.push(transform(item))\n return statements.some((stmt: ASTNode) => {\n if (stmt.type === \"ExpressionStatement\" && stmt.expression.type === \"CallExpression\") {\n const call = stmt.expression\n return call.callee.type === \"MemberExpression\" && call.callee.property.name === \"push\"\n }\n return false\n })\n }\n\n function isSimplePropertyAccess(node: ASTNode): boolean {\n // Check for patterns like: items.forEach(item => console.log(item.name))\n // These could often be: items.map(item => item.name)\n if (\n node.type === \"CallExpression\" &&\n node.callee.type === \"MemberExpression\" &&\n node.callee.property.name === \"forEach\"\n ) {\n const callback = node.arguments[0]\n if (callback && (callback.type === \"ArrowFunctionExpression\" || callback.type === \"FunctionExpression\")) {\n const body = callback.body\n // Simple property access in arrow function\n if (body.type === \"MemberExpression\") {\n return true\n }\n }\n }\n return false\n }\n\n return {\n ForStatement(node: ASTNode) {\n if (!checkForLoops) return\n\n if (isTransformationLoop(node)) {\n context.report({\n node,\n messageId: \"preferMapOverLoop\",\n data: { collection: \"array\" },\n })\n }\n },\n\n ForInStatement(node: ASTNode) {\n if (!checkForLoops) return\n\n if (isTransformationLoop(node)) {\n context.report({\n node,\n messageId: \"preferMapOverLoop\",\n data: { collection: \"object\" },\n })\n }\n },\n\n ForOfStatement(node: ASTNode) {\n if (!checkForLoops) return\n\n if (isTransformationLoop(node)) {\n context.report({\n node,\n messageId: \"preferMapOverLoop\",\n data: { collection: \"iterable\" },\n })\n }\n },\n\n CallExpression(node: ASTNode) {\n if (!checkArrayMethods) return\n\n // Check for forEach that could be map\n if (node.callee.type === \"MemberExpression\" && node.callee.property.name === \"forEach\") {\n if (isSimplePropertyAccess(node)) {\n context.report({\n node,\n messageId: \"preferMapChain\",\n fix(fixer) {\n // Only auto-fix safe forEach → map transformations\n if (!isForEachToMapSafe(node)) {\n return null\n }\n\n const sourceCode = context.sourceCode\n const text = sourceCode.getText(node)\n\n // Simple replacement: forEach -> map\n const fixedText = text.replace(/\\.forEach\\s*\\(/g, \".map(\")\n return fixer.replaceText(node, fixedText)\n },\n })\n }\n }\n\n // Check for manual push patterns in callbacks\n if (\n node.callee.type === \"MemberExpression\" &&\n node.callee.property.name === \"push\" &&\n insideIterationCallback(node)\n ) {\n context.report({ node, messageId: \"preferMapOverPush\" })\n }\n },\n }\n },\n}\n\nexport default rule\n"],"mappings":"AAIA,MAAM,EAA8C,IAAI,IAAI,CAAC,UAAW,KAAK,CAAC,EAG9E,SAAS,EAAwB,EAA2C,CAC1E,IAAM,EAAS,GAAM,OASrB,OARK,EAEH,EAAO,OAAS,kBAChB,EAAO,OAAO,OAAS,oBACvB,EAAuB,IAAI,EAAO,OAAO,SAAS,IAAI,EAE/C,GAEF,EAAwB,CAAM,EARjB,EAStB,CAEA,MAAM,EAAwB,CAC5B,KAAM,CACJ,KAAM,aACN,KAAM,CACJ,YAAa,oEACb,YAAa,EACf,EACA,QAAS,OACT,OAAQ,CACN,CACE,KAAM,SACN,WAAY,CACV,kBAAmB,CACjB,KAAM,UACN,QAAS,EACX,EACA,cAAe,CACb,KAAM,UACN,QAAS,EACX,CACF,EACA,qBAAsB,EACxB,CACF,EACA,SAAU,CACR,kBAAmB,8DACnB,kBAAmB,4CACnB,eAAgB,4EAClB,CACF,EAEA,OAAO,EAAS,CACd,IAAM,EAAU,EAAQ,QAAQ,IAAM,CAAC,EACjC,EAAoB,EAAQ,oBAAsB,GAClD,EAAgB,EAAQ,gBAAkB,GAEhD,SAAS,EAAmB,EAAwB,CAGlD,GACE,EAAK,OAAS,kBACd,EAAK,OAAO,OAAS,oBACrB,EAAK,OAAO,SAAS,OAAS,UAE9B,MAAO,GAIT,IAAM,EAAW,EAAK,UAAU,GAMhC,OALI,IAAa,EAAS,OAAS,2BAA6B,EAAS,OAAS,sBACnE,EAAS,KAEV,OAAS,mBAEhB,EACT,CAEA,SAAS,EAAqB,EAAwB,CACpD,GAAI,CAAC,EAAK,MAAQ,EAAK,KAAK,OAAS,iBAAkB,MAAO,GAE9D,IAAM,EAAa,EAAK,KAAK,KAI7B,OAHI,EAAW,SAAW,
|
|
1
|
+
{"version":3,"file":"prefer-map.js","names":[],"sources":["../../src/rules/prefer-map.ts"],"sourcesContent":["import type { Rule } from \"eslint\"\n\nimport type { ASTNode } from \"../types/ast\"\n\nconst ITERATION_METHOD_NAMES: ReadonlySet<string> = new Set([\"forEach\", \"for\"])\n\n/** True iff any ancestor of `node` is a `.forEach(...)` or `.for(...)` call. */\nfunction insideIterationCallback(node: ASTNode | null | undefined): boolean {\n const parent = node?.parent as ASTNode | undefined\n if (!parent) return false\n if (\n parent.type === \"CallExpression\" &&\n parent.callee.type === \"MemberExpression\" &&\n ITERATION_METHOD_NAMES.has(parent.callee.property.name)\n ) {\n return true\n }\n return insideIterationCallback(parent)\n}\n\nconst rule: Rule.RuleModule = {\n meta: {\n type: \"suggestion\",\n docs: {\n description: \"Prefer .map() over manual transformations and imperative patterns\",\n recommended: true,\n },\n fixable: \"code\",\n schema: [\n {\n type: \"object\",\n properties: {\n checkArrayMethods: {\n type: \"boolean\",\n default: true,\n },\n checkForLoops: {\n type: \"boolean\",\n default: true,\n },\n },\n additionalProperties: false,\n },\n ],\n messages: {\n preferMapOverLoop: \"Prefer .map() over for loop for transforming {{collection}}\",\n preferMapOverPush: \"Prefer .map() over manual .push() in loop\",\n preferMapChain: \"Consider using .map() for transformation instead of manual property access\",\n },\n },\n\n create(context) {\n const options = context.options[0] || {}\n const checkArrayMethods = options.checkArrayMethods !== false\n const checkForLoops = options.checkForLoops !== false\n\n function isForEachToMapSafe(node: ASTNode): boolean {\n // Only auto-fix simple forEach → map transformations on expressions that return values\n // This is safe because both native arrays and functype Lists have these methods\n if (\n node.type !== \"CallExpression\" ||\n node.callee.type !== \"MemberExpression\" ||\n node.callee.property.name !== \"forEach\"\n ) {\n return false\n }\n\n // Check if the callback returns a value (simple property access pattern)\n const callback = node.arguments[0]\n if (callback && (callback.type === \"ArrowFunctionExpression\" || callback.type === \"FunctionExpression\")) {\n const body = callback.body\n // Simple property access in arrow function (e.g., item => item.name)\n return body.type === \"MemberExpression\"\n }\n return false\n }\n\n function isTransformationLoop(node: ASTNode): boolean {\n if (!node.body || node.body.type !== \"BlockStatement\") return false\n\n const statements = node.body.body\n if (statements.length === 0) return false\n\n // Look for patterns like: newArray.push(transform(item))\n return statements.some((stmt: ASTNode) => {\n if (stmt.type === \"ExpressionStatement\" && stmt.expression.type === \"CallExpression\") {\n const call = stmt.expression\n return call.callee.type === \"MemberExpression\" && call.callee.property.name === \"push\"\n }\n return false\n })\n }\n\n function isSimplePropertyAccess(node: ASTNode): boolean {\n // Check for patterns like: items.forEach(item => console.log(item.name))\n // These could often be: items.map(item => item.name)\n if (\n node.type === \"CallExpression\" &&\n node.callee.type === \"MemberExpression\" &&\n node.callee.property.name === \"forEach\"\n ) {\n const callback = node.arguments[0]\n if (callback && (callback.type === \"ArrowFunctionExpression\" || callback.type === \"FunctionExpression\")) {\n const body = callback.body\n // Simple property access in arrow function\n if (body.type === \"MemberExpression\") {\n return true\n }\n }\n }\n return false\n }\n\n return {\n ForStatement(node: ASTNode) {\n if (!checkForLoops) return\n\n if (isTransformationLoop(node)) {\n context.report({\n node,\n messageId: \"preferMapOverLoop\",\n data: { collection: \"array\" },\n })\n }\n },\n\n ForInStatement(node: ASTNode) {\n if (!checkForLoops) return\n\n if (isTransformationLoop(node)) {\n context.report({\n node,\n messageId: \"preferMapOverLoop\",\n data: { collection: \"object\" },\n })\n }\n },\n\n ForOfStatement(node: ASTNode) {\n if (!checkForLoops) return\n\n if (isTransformationLoop(node)) {\n context.report({\n node,\n messageId: \"preferMapOverLoop\",\n data: { collection: \"iterable\" },\n })\n }\n },\n\n CallExpression(node: ASTNode) {\n if (!checkArrayMethods) return\n\n // Check for forEach that could be map\n if (node.callee.type === \"MemberExpression\" && node.callee.property.name === \"forEach\") {\n if (isSimplePropertyAccess(node)) {\n context.report({\n node,\n messageId: \"preferMapChain\",\n fix(fixer) {\n // Only auto-fix safe forEach → map transformations\n if (!isForEachToMapSafe(node)) {\n return null\n }\n\n const sourceCode = context.sourceCode\n const text = sourceCode.getText(node)\n\n // Simple replacement: forEach -> map\n const fixedText = text.replace(/\\.forEach\\s*\\(/g, \".map(\")\n return fixer.replaceText(node, fixedText)\n },\n })\n }\n }\n\n // Check for manual push patterns in callbacks\n if (\n node.callee.type === \"MemberExpression\" &&\n node.callee.property.name === \"push\" &&\n insideIterationCallback(node)\n ) {\n context.report({ node, messageId: \"preferMapOverPush\" })\n }\n },\n }\n },\n}\n\nexport default rule\n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LazyList`,`Task`,`Try`,`Map`,`Set`,`Stack`]),t=e=>e.type===`ImportDeclaration`&&e.source.type===`Literal`&&e.source.value===`functype`;function n(e){return e.sourceCode.ast.body.some(t)}function r(t){if(t.type===`ImportSpecifier`&&t.imported.type===`Identifier`){let n=t.imported.name;return e.has(n)?{type:n,fn:null,all:n}:{type:null,fn:n,all:n}}return t.type===`ImportDefaultSpecifier`?{type:null,fn:`default`,all:`default`}:t.type===`ImportNamespaceSpecifier`?{type:`*`,fn:`*`,all:`*`}:null}const i=(e,t)=>e.flatMap(e=>{let n=e[t];return n===null?[]:[n]});function a(e){let n=e.sourceCode.ast.body.filter(t).flatMap(e=>e.specifiers??[]).map(r).filter(e=>e!==null);return{types:new Set(i(n,`type`)),functions:new Set(i(n,`fn`)),all:new Set(n.map(e=>e.all))}}function o(e){return a(e).all}function s(e,t){if(!e)return!1;let n=t instanceof Set?t:t.types||t.all;if(e.type===`TSTypeReference`&&e.typeName?.type===`Identifier`){let t=e.typeName.name;return n.has(t)||[`Option`,`Either`,`List`,`LazyList`,`Task`,`Try`,`Map`,`Set`,`Stack`].includes(t)}return!1}function c(e,t){if(!e||e.type!==`CallExpression`)return!1;let n=e.callee;if(n.type===`MemberExpression`&&n.object.type===`Identifier`){let e=n.object.name,r=n.property?.name;if(t.has(e)||e===`Option`&&[`some`,`none`,`of`].includes(r)||e===`Either`&&[`left`,`right`,`of`].includes(r)||e===`List`&&[`of`,`from`,`empty`].includes(r)||e===`Map`&&[`of`,`empty`].includes(r)||e===`Set`&&[`of`,`empty`].includes(r))return!0}if(n.type===`MemberExpression`){let e=n.property?.name;if([`map`,`flatMap`,`filter`,`fold`,`foldLeft`,`foldRight`,`getOrElse`,`orElse`,`isEmpty`,`nonEmpty`,`isDefined`,`isSome`,`isNone`,`isLeft`,`isRight`,`toArray`].includes(e))return!0}return!1}function l(e,t){let n=e?.parent;return n?t(n)||l(n,t):!1}function u(e,t){return l(e,e=>c(e,t)||s(e,t))}function d(e,t){return e.typeAnnotation?.typeAnnotation?s(e.typeAnnotation.typeAnnotation,t):!1}function f(e,t){if(!e||e.type!==`CallExpression`)return!1;let n=e.callee;if(n.type===`Identifier`){let e=n.name;return t.functions.has(e)&&[`Do`,`DoAsync`].includes(e)}return!1}function p(e,t){if(!e||e.type!==`CallExpression`)return!1;let n=e.callee;return n.type===`Identifier`&&n.name
|
|
1
|
+
const e=new Set([`Option`,`Either`,`List`,`LazyList`,`Task`,`Try`,`Map`,`Set`,`Stack`]),t=e=>e.type===`ImportDeclaration`&&e.source.type===`Literal`&&e.source.value===`functype`;function n(e){return e.sourceCode.ast.body.some(t)}function r(t){if(t.type===`ImportSpecifier`&&t.imported.type===`Identifier`){let n=t.imported.name;return e.has(n)?{type:n,fn:null,all:n}:{type:null,fn:n,all:n}}return t.type===`ImportDefaultSpecifier`?{type:null,fn:`default`,all:`default`}:t.type===`ImportNamespaceSpecifier`?{type:`*`,fn:`*`,all:`*`}:null}const i=(e,t)=>e.flatMap(e=>{let n=e[t];return n===null?[]:[n]});function a(e){let n=e.sourceCode.ast.body.filter(t).flatMap(e=>e.specifiers??[]).map(r).filter(e=>e!==null);return{types:new Set(i(n,`type`)),functions:new Set(i(n,`fn`)),all:new Set(n.map(e=>e.all))}}function o(e){return a(e).all}function s(e,t){if(!e)return!1;let n=t instanceof Set?t:t.types||t.all;if(e.type===`TSTypeReference`&&e.typeName?.type===`Identifier`){let t=e.typeName.name;return n.has(t)||[`Option`,`Either`,`List`,`LazyList`,`Task`,`Try`,`Map`,`Set`,`Stack`].includes(t)}return!1}function c(e,t){if(!e||e.type!==`CallExpression`)return!1;let n=e.callee;if(n.type===`MemberExpression`&&n.object.type===`Identifier`){let e=n.object.name,r=n.property?.name;if(t.has(e)||e===`Option`&&[`some`,`none`,`of`].includes(r)||e===`Either`&&[`left`,`right`,`of`].includes(r)||e===`List`&&[`of`,`from`,`empty`].includes(r)||e===`Map`&&[`of`,`empty`].includes(r)||e===`Set`&&[`of`,`empty`].includes(r))return!0}if(n.type===`MemberExpression`){let e=n.property?.name;if([`map`,`flatMap`,`filter`,`fold`,`foldLeft`,`foldRight`,`getOrElse`,`orElse`,`isEmpty`,`nonEmpty`,`isDefined`,`isSome`,`isNone`,`isLeft`,`isRight`,`toArray`].includes(e))return!0}return!1}function l(e,t){let n=e?.parent;return n?t(n)||l(n,t):!1}function u(e,t){return l(e,e=>c(e,t)||s(e,t))}function d(e,t){return e.typeAnnotation?.typeAnnotation?s(e.typeAnnotation.typeAnnotation,t):!1}function f(e,t){if(!e||e.type!==`CallExpression`)return!1;let n=e.callee;if(n.type===`Identifier`){let e=n.name;return t.functions.has(e)&&[`Do`,`DoAsync`].includes(e)}return!1}function p(e,t){if(!e||e.type!==`CallExpression`)return!1;let n=e.callee;return n.type===`Identifier`&&n.name===`$`&&t.functions.has(`$`)}function m(e,t){return l(e,e=>e.type===`CallExpression`&&f(e,t))}function h(e,t){if(!e||e.type!==`CallExpression`)return!1;let n=e.callee;return n.type===`MemberExpression`&&n.property.type===`Identifier`&&n.property.name===t}function g(e,t){if(m(e,t))return{shouldUse:!1,reason:null};if(e.type===`LogicalExpression`&&e.operator===`&&`){let t=e.toString?e.toString():``;if(t.includes(`&&`)&&t.match(/\w+(\.\w+){2,}/))return{shouldUse:!0,reason:`nested-checks`}}return h(e,`flatMap`)&&_(e)>=3?{shouldUse:!0,reason:`chained-flatmaps`}:{shouldUse:!1,reason:null}}function _(e){return!e||e.type!==`CallExpression`||!h(e,`flatMap`)?0:e.callee.type===`MemberExpression`?1+_(e.callee.object):1}export{a as getFunctypeImports,o as getFunctypeImportsLegacy,n as hasFunctypeImport,d as hasFunctypeTypeAnnotation,u as isAlreadyUsingFunctype,h as isChainedMethodCall,f as isDoNotationCall,p as isDollarHelper,c as isFunctypeCall,s as isFunctypeType,m as isInsideDoNotation,g as shouldUseDoNotation};
|
|
2
2
|
//# sourceMappingURL=functype-detection.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"functype-detection.js","names":[],"sources":["../../src/utils/functype-detection.ts"],"sourcesContent":["import type { Rule } from \"eslint\"\n\nimport type { ASTNode } from \"../types/ast\"\n\n/**\n * Utility functions for detecting functype library usage in ESLint rules.\n *\n * Implementation style: pure helpers operating over native immutable\n * primitives (Array.prototype methods + ReadonlySet). No mutable\n * accumulators, no `for-of` driving state changes. The plugin's domain\n * (AST traversal) is naturally tree-shaped; the helpers compose as\n * folds/filters/maps over those trees.\n */\n\nconst TYPE_NAMES: ReadonlySet<string> = new Set([\n \"Option\",\n \"Either\",\n \"List\",\n \"LazyList\",\n \"Task\",\n \"Try\",\n \"Map\",\n \"Set\",\n \"Stack\",\n])\n\n/** `import ... from \"functype\"` — including `functype/<subpath>` */\nconst isFunctypeImport = (node: ASTNode): boolean =>\n node.type === \"ImportDeclaration\" && node.source.type === \"Literal\" && node.source.value === \"functype\"\n\n/**\n * Check if functype library is imported in the current file\n */\nexport function hasFunctypeImport(context: Rule.RuleContext): boolean {\n return context.sourceCode.ast.body.some(isFunctypeImport)\n}\n\n/**\n * Enhanced functype imports tracking\n */\nexport interface FunctypeImports {\n types: Set<string> // Option, Either, List, etc.\n functions: Set<string> // Do, DoAsync, $, etc.\n all: Set<string> // Combined for compatibility\n}\n\ntype SpecifierBuckets = { readonly type: string | null; readonly fn: string | null; readonly all: string }\n\n/** Sort a single import specifier into the three buckets (or none). */\nfunction categorizeSpecifier(spec: ASTNode): SpecifierBuckets | null {\n if (spec.type === \"ImportSpecifier\" && spec.imported.type === \"Identifier\") {\n const name = spec.imported.name\n // Named imports split by whether they're a functype TYPE or anything else.\n // (Do/DoAsync/$ + any other named import bucket as `functions`, matching\n // the original behavior — the explicit Do/DoAsync/$ branch was redundant.)\n return TYPE_NAMES.has(name) ? { type: name, fn: null, all: name } : { type: null, fn: name, all: name }\n }\n if (spec.type === \"ImportDefaultSpecifier\") return { type: null, fn: \"default\", all: \"default\" }\n if (spec.type === \"ImportNamespaceSpecifier\") return { type: \"*\", fn: \"*\", all: \"*\" }\n return null\n}\n\nconst pickPresent = <K extends keyof SpecifierBuckets>(buckets: readonly SpecifierBuckets[], key: K): string[] =>\n buckets.flatMap((b) => {\n const v = b[key]\n return v === null ? [] : [v as string]\n })\n\n/**\n * Get imported functype symbols from the current file\n */\nexport function getFunctypeImports(context: Rule.RuleContext): FunctypeImports {\n const buckets = context.sourceCode.ast.body\n .filter(isFunctypeImport)\n .flatMap((node: ASTNode) => (node.specifiers ?? []) as ASTNode[])\n .map(categorizeSpecifier)\n .filter((b): b is SpecifierBuckets => b !== null)\n\n return {\n types: new Set(pickPresent(buckets, \"type\")),\n functions: new Set(pickPresent(buckets, \"fn\")),\n all: new Set(buckets.map((b) => b.all)),\n }\n}\n\n/**\n * Legacy compatibility - returns the 'all' set\n */\nexport function getFunctypeImportsLegacy(context: Rule.RuleContext): Set<string> {\n return getFunctypeImports(context).all\n}\n\n/**\n * Check if a type reference is using functype types\n */\nexport function isFunctypeType(node: ASTNode, functypeImports: FunctypeImports | Set<string>): boolean {\n if (!node) return false\n\n // Handle both new and legacy API\n const types = functypeImports instanceof Set ? functypeImports : functypeImports.types || functypeImports.all\n\n // Check direct type names\n if (node.type === \"TSTypeReference\" && node.typeName?.type === \"Identifier\") {\n const typeName = node.typeName.name\n return (\n types.has(typeName) ||\n [\"Option\", \"Either\", \"List\", \"LazyList\", \"Task\", \"Try\", \"Map\", \"Set\", \"Stack\"].includes(typeName)\n )\n }\n\n return false\n}\n\n/**\n * Check if a call expression is using functype methods\n */\nexport function isFunctypeCall(node: ASTNode, functypeImports: Set<string>): boolean {\n if (!node || node.type !== \"CallExpression\") return false\n\n const callee = node.callee\n\n // Check for static method calls like Option.some(), Either.left(), List.of()\n if (callee.type === \"MemberExpression\" && callee.object.type === \"Identifier\") {\n const objectName = callee.object.name\n const methodName = callee.property?.name\n\n // Check if calling methods on imported functype types\n if (functypeImports.has(objectName)) return true\n\n // Check for common functype patterns\n if (\n (objectName === \"Option\" && [\"some\", \"none\", \"of\"].includes(methodName)) ||\n (objectName === \"Either\" && [\"left\", \"right\", \"of\"].includes(methodName)) ||\n (objectName === \"List\" && [\"of\", \"from\", \"empty\"].includes(methodName)) ||\n (objectName === \"Map\" && [\"of\", \"empty\"].includes(methodName)) ||\n (objectName === \"Set\" && [\"of\", \"empty\"].includes(methodName))\n ) {\n return true\n }\n }\n\n // Check for method calls on functype instances like someOption.map()\n if (callee.type === \"MemberExpression\") {\n const methodName = callee.property?.name\n\n // Common functype methods\n if (\n [\n \"map\",\n \"flatMap\",\n \"filter\",\n \"fold\",\n \"foldLeft\",\n \"foldRight\",\n \"getOrElse\",\n \"orElse\",\n \"isEmpty\",\n \"nonEmpty\",\n \"isDefined\",\n \"isSome\",\n \"isNone\",\n \"isLeft\",\n \"isRight\",\n \"toArray\",\n ].includes(methodName)\n ) {\n return true\n }\n }\n\n return false\n}\n\n/** True iff any ancestor of `node` satisfies `pred`. Pure tail recursion. */\nfunction ancestorSatisfies(node: ASTNode | null | undefined, pred: (n: ASTNode) => boolean): boolean {\n const parent = node?.parent as ASTNode | undefined\n if (!parent) return false\n return pred(parent) || ancestorSatisfies(parent, pred)\n}\n\n/**\n * Check if current context is already using functype patterns appropriately\n */\nexport function isAlreadyUsingFunctype(node: ASTNode, functypeImports: Set<string>): boolean {\n return ancestorSatisfies(\n node,\n (parent) => isFunctypeCall(parent, functypeImports) || isFunctypeType(parent, functypeImports),\n )\n}\n\n/**\n * Check if a variable or parameter is typed with functype types\n */\nexport function hasFunctypeTypeAnnotation(node: ASTNode, functypeImports: FunctypeImports | Set<string>): boolean {\n // Check for type annotation\n if (node.typeAnnotation?.typeAnnotation) {\n return isFunctypeType(node.typeAnnotation.typeAnnotation, functypeImports)\n }\n\n return false\n}\n\n/**\n * Check if a call expression is a Do notation call\n */\nexport function isDoNotationCall(node: ASTNode, functypeImports: FunctypeImports): boolean {\n if (!node || node.type !== \"CallExpression\") return false\n\n const callee = node.callee\n\n // Check for Do() or DoAsync() calls\n if (callee.type === \"Identifier\") {\n const name = callee.name\n return functypeImports.functions.has(name) && [\"Do\", \"DoAsync\"].includes(name)\n }\n\n return false\n}\n\n/**\n * Check if a call expression uses the $ helper function\n */\nexport function isDollarHelper(node: ASTNode, functypeImports: FunctypeImports): boolean {\n if (!node || node.type !== \"CallExpression\") return false\n\n const callee = node.callee\n\n // Check for $() calls\n if (callee.type === \"Identifier\" && callee.name === \"$\") {\n return functypeImports.functions.has(\"$\")\n }\n\n return false\n}\n\n/**\n * Check if current expression is inside a Do notation block\n */\nexport function isInsideDoNotation(node: ASTNode, functypeImports: FunctypeImports): boolean {\n return ancestorSatisfies(node, (n) => n.type === \"CallExpression\" && isDoNotationCall(n, functypeImports))\n}\n\n/**\n * Check if a method call is a chained method call on functype types\n */\nexport function isChainedMethodCall(node: ASTNode, methodName: string): boolean {\n if (!node || node.type !== \"CallExpression\") return false\n\n const callee = node.callee\n\n if (\n callee.type === \"MemberExpression\" &&\n callee.property.type === \"Identifier\" &&\n callee.property.name === methodName\n ) {\n return true\n }\n\n return false\n}\n\n/**\n * Detect if code could benefit from Do notation\n */\nexport function shouldUseDoNotation(\n node: ASTNode,\n functypeImports: FunctypeImports,\n): {\n shouldUse: boolean\n reason: \"nested-checks\" | \"chained-flatmaps\" | \"mixed-monads\" | \"async-chains\" | null\n} {\n // Already using Do notation\n if (isInsideDoNotation(node, functypeImports)) {\n return { shouldUse: false, reason: null }\n }\n\n // Check for nested null checks (a && a.b && a.b.c pattern)\n if (node.type === \"LogicalExpression\" && node.operator === \"&&\") {\n const text = node.toString ? node.toString() : \"\"\n if (text.includes(\"&&\") && text.match(/\\w+(\\.\\w+){2,}/)) {\n return { shouldUse: true, reason: \"nested-checks\" }\n }\n }\n\n // Check for chained flatMap calls\n if (isChainedMethodCall(node, \"flatMap\") && flatMapChainDepth(node) >= 3) {\n return { shouldUse: true, reason: \"chained-flatmaps\" }\n }\n\n return { shouldUse: false, reason: null }\n}\n\n/** Length of an unbroken `.flatMap().flatMap()...` chain starting at `node`. */\nfunction flatMapChainDepth(node: ASTNode): number {\n if (!node || node.type !== \"CallExpression\" || !isChainedMethodCall(node, \"flatMap\")) return 0\n if (node.callee.type !== \"MemberExpression\") return 1\n return 1 + flatMapChainDepth(node.callee.object as ASTNode)\n}\n"],"mappings":"AAcA,MAAM,EAAkC,IAAI,IAAI,CAC9C,SACA,SACA,OACA,WACA,OACA,MACA,MACA,MACA,OACF,CAAC,EAGK,EAAoB,GACxB,EAAK,OAAS,qBAAuB,EAAK,OAAO,OAAS,WAAa,EAAK,OAAO,QAAU,WAK/F,SAAgB,EAAkB,EAAoC,CACpE,OAAO,EAAQ,WAAW,IAAI,KAAK,KAAK,CAAgB,CAC1D,CAcA,SAAS,EAAoB,EAAwC,CACnE,GAAI,EAAK,OAAS,mBAAqB,EAAK,SAAS,OAAS,aAAc,CAC1E,IAAM,EAAO,EAAK,SAAS,KAI3B,OAAO,EAAW,IAAI,CAAI,EAAI,CAAE,KAAM,EAAM,GAAI,KAAM,IAAK,CAAK,EAAI,CAAE,KAAM,KAAM,GAAI,EAAM,IAAK,CAAK,CACxG,CAGA,OAFI,EAAK,OAAS,yBAAiC,CAAE,KAAM,KAAM,GAAI,UAAW,IAAK,SAAU,EAC3F,EAAK,OAAS,2BAAmC,CAAE,KAAM,IAAK,GAAI,IAAK,IAAK,GAAI,EAC7E,IACT,CAEA,MAAM,GAAiD,EAAsC,IAC3F,EAAQ,QAAS,GAAM,CACrB,IAAM,EAAI,EAAE,GACZ,OAAO,IAAM,KAAO,CAAC,EAAI,CAAC,CAAW,CACvC,CAAC,EAKH,SAAgB,EAAmB,EAA4C,CAC7E,IAAM,EAAU,EAAQ,WAAW,IAAI,KACpC,OAAO,CAAgB,CAAC,CACxB,QAAS,GAAmB,EAAK,YAAc,CAAC,CAAe,CAAC,CAChE,IAAI,CAAmB,CAAC,CACxB,OAAQ,GAA6B,IAAM,IAAI,EAElD,MAAO,CACL,MAAO,IAAI,IAAI,EAAY,EAAS,MAAM,CAAC,EAC3C,UAAW,IAAI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S,cACzB,EAAO,SAAS,OAAS,CAM7B,CAKA,SAAgB,EACd,EACA,EAIA,CAEA,GAAI,EAAmB,EAAM,CAAe,EAC1C,MAAO,CAAE,UAAW,GAAO,OAAQ,IAAK,EAI1C,GAAI,EAAK,OAAS,qBAAuB,EAAK,WAAa,KAAM,CAC/D,IAAM,EAAO,EAAK,SAAW,EAAK,SAAS,EAAI,GAC/C,GAAI,EAAK,SAAS,IAAI,GAAK,EAAK,MAAM,gBAAgB,EACpD,MAAO,CAAE,UAAW,GAAM,OAAQ,eAAgB,CAEtD,CAOA,OAJI,EAAoB,EAAM,SAAS,GAAK,EAAkB,CAAI,GAAK,EAC9D,CAAE,UAAW,GAAM,OAAQ,kBAAmB,EAGhD,CAAE,UAAW,GAAO,OAAQ,IAAK,CAC1C,CAGA,SAAS,EAAkB,EAAuB,CAGhD,MAFI,CAAC,GAAQ,EAAK,OAAS,kBAAoB,CAAC,EAAoB,EAAM,SAAS,EAAU,EACzF,EAAK,OAAO,OAAS,mBAClB,EAAI,EAAkB,EAAK,OAAO,MAAiB,EADN,CAEtD"}
|
|
1
|
+
{"version":3,"file":"functype-detection.js","names":[],"sources":["../../src/utils/functype-detection.ts"],"sourcesContent":["import type { Rule } from \"eslint\"\n\nimport type { ASTNode } from \"../types/ast\"\n\n/**\n * Utility functions for detecting functype library usage in ESLint rules.\n *\n * Implementation style: pure helpers operating over native immutable\n * primitives (Array.prototype methods + ReadonlySet). No mutable\n * accumulators, no `for-of` driving state changes. The plugin's domain\n * (AST traversal) is naturally tree-shaped; the helpers compose as\n * folds/filters/maps over those trees.\n */\n\nconst TYPE_NAMES: ReadonlySet<string> = new Set([\n \"Option\",\n \"Either\",\n \"List\",\n \"LazyList\",\n \"Task\",\n \"Try\",\n \"Map\",\n \"Set\",\n \"Stack\",\n])\n\n/** `import ... from \"functype\"` — including `functype/<subpath>` */\nconst isFunctypeImport = (node: ASTNode): boolean =>\n node.type === \"ImportDeclaration\" && node.source.type === \"Literal\" && node.source.value === \"functype\"\n\n/**\n * Check if functype library is imported in the current file\n */\nexport function hasFunctypeImport(context: Rule.RuleContext): boolean {\n return context.sourceCode.ast.body.some(isFunctypeImport)\n}\n\n/**\n * Enhanced functype imports tracking\n */\nexport interface FunctypeImports {\n types: Set<string> // Option, Either, List, etc.\n functions: Set<string> // Do, DoAsync, $, etc.\n all: Set<string> // Combined for compatibility\n}\n\ntype SpecifierBuckets = { readonly type: string | null; readonly fn: string | null; readonly all: string }\n\n/** Sort a single import specifier into the three buckets (or none). */\nfunction categorizeSpecifier(spec: ASTNode): SpecifierBuckets | null {\n if (spec.type === \"ImportSpecifier\" && spec.imported.type === \"Identifier\") {\n const name = spec.imported.name\n // Named imports split by whether they're a functype TYPE or anything else.\n // (Do/DoAsync/$ + any other named import bucket as `functions`, matching\n // the original behavior — the explicit Do/DoAsync/$ branch was redundant.)\n return TYPE_NAMES.has(name) ? { type: name, fn: null, all: name } : { type: null, fn: name, all: name }\n }\n if (spec.type === \"ImportDefaultSpecifier\") return { type: null, fn: \"default\", all: \"default\" }\n if (spec.type === \"ImportNamespaceSpecifier\") return { type: \"*\", fn: \"*\", all: \"*\" }\n return null\n}\n\nconst pickPresent = <K extends keyof SpecifierBuckets>(buckets: readonly SpecifierBuckets[], key: K): string[] =>\n buckets.flatMap((b) => {\n const v = b[key]\n return v === null ? [] : [v as string]\n })\n\n/**\n * Get imported functype symbols from the current file\n */\nexport function getFunctypeImports(context: Rule.RuleContext): FunctypeImports {\n const buckets = context.sourceCode.ast.body\n .filter(isFunctypeImport)\n .flatMap((node: ASTNode) => (node.specifiers ?? []) as ASTNode[])\n .map(categorizeSpecifier)\n .filter((b): b is SpecifierBuckets => b !== null)\n\n return {\n types: new Set(pickPresent(buckets, \"type\")),\n functions: new Set(pickPresent(buckets, \"fn\")),\n all: new Set(buckets.map((b) => b.all)),\n }\n}\n\n/**\n * Legacy compatibility - returns the 'all' set\n */\nexport function getFunctypeImportsLegacy(context: Rule.RuleContext): Set<string> {\n return getFunctypeImports(context).all\n}\n\n/**\n * Check if a type reference is using functype types\n */\nexport function isFunctypeType(node: ASTNode, functypeImports: FunctypeImports | Set<string>): boolean {\n if (!node) return false\n\n // Handle both new and legacy API\n const types = functypeImports instanceof Set ? functypeImports : functypeImports.types || functypeImports.all\n\n // Check direct type names\n if (node.type === \"TSTypeReference\" && node.typeName?.type === \"Identifier\") {\n const typeName = node.typeName.name\n return (\n types.has(typeName) ||\n [\"Option\", \"Either\", \"List\", \"LazyList\", \"Task\", \"Try\", \"Map\", \"Set\", \"Stack\"].includes(typeName)\n )\n }\n\n return false\n}\n\n/**\n * Check if a call expression is using functype methods\n */\nexport function isFunctypeCall(node: ASTNode, functypeImports: Set<string>): boolean {\n if (!node || node.type !== \"CallExpression\") return false\n\n const callee = node.callee\n\n // Check for static method calls like Option.some(), Either.left(), List.of()\n if (callee.type === \"MemberExpression\" && callee.object.type === \"Identifier\") {\n const objectName = callee.object.name\n const methodName = callee.property?.name\n\n // Check if calling methods on imported functype types\n if (functypeImports.has(objectName)) return true\n\n // Check for common functype patterns\n if (\n (objectName === \"Option\" && [\"some\", \"none\", \"of\"].includes(methodName)) ||\n (objectName === \"Either\" && [\"left\", \"right\", \"of\"].includes(methodName)) ||\n (objectName === \"List\" && [\"of\", \"from\", \"empty\"].includes(methodName)) ||\n (objectName === \"Map\" && [\"of\", \"empty\"].includes(methodName)) ||\n (objectName === \"Set\" && [\"of\", \"empty\"].includes(methodName))\n ) {\n return true\n }\n }\n\n // Check for method calls on functype instances like someOption.map()\n if (callee.type === \"MemberExpression\") {\n const methodName = callee.property?.name\n\n // Common functype methods\n if (\n [\n \"map\",\n \"flatMap\",\n \"filter\",\n \"fold\",\n \"foldLeft\",\n \"foldRight\",\n \"getOrElse\",\n \"orElse\",\n \"isEmpty\",\n \"nonEmpty\",\n \"isDefined\",\n \"isSome\",\n \"isNone\",\n \"isLeft\",\n \"isRight\",\n \"toArray\",\n ].includes(methodName)\n ) {\n return true\n }\n }\n\n return false\n}\n\n/** True iff any ancestor of `node` satisfies `pred`. Pure tail recursion. */\nfunction ancestorSatisfies(node: ASTNode | null | undefined, pred: (n: ASTNode) => boolean): boolean {\n const parent = node?.parent as ASTNode | undefined\n if (!parent) return false\n return pred(parent) || ancestorSatisfies(parent, pred)\n}\n\n/**\n * Check if current context is already using functype patterns appropriately\n */\nexport function isAlreadyUsingFunctype(node: ASTNode, functypeImports: Set<string>): boolean {\n return ancestorSatisfies(\n node,\n (parent) => isFunctypeCall(parent, functypeImports) || isFunctypeType(parent, functypeImports),\n )\n}\n\n/**\n * Check if a variable or parameter is typed with functype types\n */\nexport function hasFunctypeTypeAnnotation(node: ASTNode, functypeImports: FunctypeImports | Set<string>): boolean {\n // Check for type annotation\n if (node.typeAnnotation?.typeAnnotation) {\n return isFunctypeType(node.typeAnnotation.typeAnnotation, functypeImports)\n }\n\n return false\n}\n\n/**\n * Check if a call expression is a Do notation call\n */\nexport function isDoNotationCall(node: ASTNode, functypeImports: FunctypeImports): boolean {\n if (!node || node.type !== \"CallExpression\") return false\n\n const callee = node.callee\n\n // Check for Do() or DoAsync() calls\n if (callee.type === \"Identifier\") {\n const name = callee.name\n return functypeImports.functions.has(name) && [\"Do\", \"DoAsync\"].includes(name)\n }\n\n return false\n}\n\n/**\n * Check if a call expression uses the $ helper function\n */\nexport function isDollarHelper(node: ASTNode, functypeImports: FunctypeImports): boolean {\n if (!node || node.type !== \"CallExpression\") return false\n\n const callee = node.callee\n\n // Check for $() calls\n if (callee.type === \"Identifier\" && callee.name === \"$\") {\n return functypeImports.functions.has(\"$\")\n }\n\n return false\n}\n\n/**\n * Check if current expression is inside a Do notation block\n */\nexport function isInsideDoNotation(node: ASTNode, functypeImports: FunctypeImports): boolean {\n return ancestorSatisfies(node, (n) => n.type === \"CallExpression\" && isDoNotationCall(n, functypeImports))\n}\n\n/**\n * Check if a method call is a chained method call on functype types\n */\nexport function isChainedMethodCall(node: ASTNode, methodName: string): boolean {\n if (!node || node.type !== \"CallExpression\") return false\n\n const callee = node.callee\n\n if (\n callee.type === \"MemberExpression\" &&\n callee.property.type === \"Identifier\" &&\n callee.property.name === methodName\n ) {\n return true\n }\n\n return false\n}\n\n/**\n * Detect if code could benefit from Do notation\n */\nexport function shouldUseDoNotation(\n node: ASTNode,\n functypeImports: FunctypeImports,\n): {\n shouldUse: boolean\n reason: \"nested-checks\" | \"chained-flatmaps\" | \"mixed-monads\" | \"async-chains\" | null\n} {\n // Already using Do notation\n if (isInsideDoNotation(node, functypeImports)) {\n return { shouldUse: false, reason: null }\n }\n\n // Check for nested null checks (a && a.b && a.b.c pattern)\n if (node.type === \"LogicalExpression\" && node.operator === \"&&\") {\n const text = node.toString ? node.toString() : \"\"\n if (text.includes(\"&&\") && text.match(/\\w+(\\.\\w+){2,}/)) {\n return { shouldUse: true, reason: \"nested-checks\" }\n }\n }\n\n // Check for chained flatMap calls\n if (isChainedMethodCall(node, \"flatMap\") && flatMapChainDepth(node) >= 3) {\n return { shouldUse: true, reason: \"chained-flatmaps\" }\n }\n\n return { shouldUse: false, reason: null }\n}\n\n/** Length of an unbroken `.flatMap().flatMap()...` chain starting at `node`. */\nfunction flatMapChainDepth(node: ASTNode): number {\n if (!node || node.type !== \"CallExpression\" || !isChainedMethodCall(node, \"flatMap\")) return 0\n if (node.callee.type !== \"MemberExpression\") return 1\n return 1 + flatMapChainDepth(node.callee.object as ASTNode)\n}\n"],"mappings":"AAcA,MAAM,EAAkC,IAAI,IAAI,CAC9C,SACA,SACA,OACA,WACA,OACA,MACA,MACA,MACA,OACF,CAAC,EAGK,EAAoB,GACxB,EAAK,OAAS,qBAAuB,EAAK,OAAO,OAAS,WAAa,EAAK,OAAO,QAAU,WAK/F,SAAgB,EAAkB,EAAoC,CACpE,OAAO,EAAQ,WAAW,IAAI,KAAK,KAAK,CAAgB,CAC1D,CAcA,SAAS,EAAoB,EAAwC,CACnE,GAAI,EAAK,OAAS,mBAAqB,EAAK,SAAS,OAAS,aAAc,CAC1E,IAAM,EAAO,EAAK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AFI,CAAC,GAAQ,EAAK,OAAS,kBAAoB,CAAC,EAAoB,EAAM,SAAS,EAAU,EACzF,EAAK,OAAO,OAAS,mBAClB,EAAI,EAAkB,EAAK,OAAO,MAAiB,EADN,CAEtD"}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "eslint-plugin-functype",
|
|
3
|
-
"version": "2.
|
|
3
|
+
"version": "2.107.0",
|
|
4
4
|
"description": "Custom ESLint rules for functional TypeScript programming with functype library patterns including Do notation (ESLint 10+)",
|
|
5
5
|
"type": "module",
|
|
6
6
|
"main": "./dist/index.js",
|
|
@@ -39,12 +39,12 @@
|
|
|
39
39
|
"eslint": "^10.2.1"
|
|
40
40
|
},
|
|
41
41
|
"devDependencies": {
|
|
42
|
-
"@types/node": "^24.13.
|
|
43
|
-
"@typescript-eslint/rule-tester": "^8.
|
|
42
|
+
"@types/node": "^24.13.3",
|
|
43
|
+
"@typescript-eslint/rule-tester": "^8.65.0",
|
|
44
44
|
"eslint-config-prettier": "^10.1.8",
|
|
45
|
-
"ts-builds": "^3.2.
|
|
46
|
-
"tsdown": "^0.22.
|
|
47
|
-
"functype": "^1.
|
|
45
|
+
"ts-builds": "^3.2.3",
|
|
46
|
+
"tsdown": "^0.22.14",
|
|
47
|
+
"functype": "^1.7.0"
|
|
48
48
|
},
|
|
49
49
|
"publishConfig": {
|
|
50
50
|
"access": "public",
|