eslint-plugin-functype 2.109.0 → 2.110.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +110 -19
- package/dist/cli/list-rules.js.map +1 -1
- package/dist/configs/recommended.d.ts +21 -5
- package/dist/configs/recommended.js +1 -1
- package/dist/configs/recommended.js.map +1 -1
- package/dist/configs/strict.d.ts +1 -1
- package/dist/configs/strict.js.map +1 -1
- package/dist/index.js.map +1 -1
- package/dist/rules/index.js.map +1 -1
- package/dist/rules/no-get-unsafe.js.map +1 -1
- package/dist/rules/no-imperative-loops.js +1 -1
- package/dist/rules/no-imperative-loops.js.map +1 -1
- package/dist/rules/no-let.js.map +1 -1
- package/dist/rules/prefer-do-notation.js +1 -1
- package/dist/rules/prefer-do-notation.js.map +1 -1
- package/dist/rules/prefer-either.js +1 -1
- package/dist/rules/prefer-either.js.map +1 -1
- package/dist/rules/prefer-flatmap.js +1 -1
- package/dist/rules/prefer-flatmap.js.map +1 -1
- package/dist/rules/prefer-fold.js +1 -1
- package/dist/rules/prefer-fold.js.map +1 -1
- package/dist/rules/prefer-functype-map.js +1 -1
- package/dist/rules/prefer-functype-map.js.map +1 -1
- package/dist/rules/prefer-functype-set.js +1 -1
- package/dist/rules/prefer-functype-set.js.map +1 -1
- package/dist/rules/prefer-list.js +1 -1
- package/dist/rules/prefer-list.js.map +1 -1
- package/dist/rules/prefer-map.js +1 -1
- package/dist/rules/prefer-map.js.map +1 -1
- package/dist/rules/prefer-option.js +1 -1
- package/dist/rules/prefer-option.js.map +1 -1
- package/dist/rules/prefer-try.js +1 -1
- package/dist/rules/prefer-try.js.map +1 -1
- package/dist/types/ast.d.ts +1 -2
- package/dist/utils/ast-walk.d.ts +12 -0
- package/dist/utils/ast-walk.js +2 -0
- package/dist/utils/ast-walk.js.map +1 -0
- package/dist/utils/async-detection.d.ts +6 -0
- package/dist/utils/async-detection.js +2 -0
- package/dist/utils/async-detection.js.map +1 -0
- package/dist/utils/boundary-tags.d.ts +25 -0
- package/dist/utils/boundary-tags.js +2 -0
- package/dist/utils/boundary-tags.js.map +1 -0
- package/dist/utils/dependency-validator.d.ts +4 -5
- package/dist/utils/dependency-validator.js +1 -1
- package/dist/utils/dependency-validator.js.map +1 -1
- package/dist/utils/functype-detection.d.ts +13 -14
- package/dist/utils/functype-detection.js +1 -1
- package/dist/utils/functype-detection.js.map +1 -1
- package/dist/utils/import-fixer.d.ts +2 -3
- package/dist/utils/import-fixer.js.map +1 -1
- package/dist/utils/mutable-collection.d.ts +30 -0
- package/dist/utils/mutable-collection.js +2 -0
- package/dist/utils/mutable-collection.js.map +1 -0
- package/dist/utils/wire-types.d.ts +21 -0
- package/dist/utils/wire-types.js +2 -0
- package/dist/utils/wire-types.js.map +1 -0
- package/package.json +6 -6
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import{createImportFixer as
|
|
1
|
+
import{isInsideTaggedDeclaration as e}from"../utils/boundary-tags.js";import{createImportFixer as t,hasFunctypeSymbol as n}from"../utils/import-fixer.js";function r(e){let t=e?.parent;return t?t.type===`CatchClause`||r(t):!1}const i={meta:{type:`suggestion`,hasSuggestions:!0,docs:{description:`Use Either/Left/Right for typed domain errors instead of throwing`,recommended:!0},schema:[{type:`object`,properties:{allowInteropMarker:{type:`boolean`,default:!0},allowInvariantMarker:{type:`boolean`,default:!0},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(i){let a=i.options[0]||{},o=a.allowInteropMarker!==!1,s=a.allowInvariantMarker!==!1,c=t=>o&&e(t,`interop`,i.sourceCode)||s&&e(t,`invariant`,i.sourceCode),l=a.allowThrowInTests!==!1;function u(){let e=i.filename;return/\.(test|spec)\.(ts|js|tsx|jsx)$/.test(e)||e.includes(`__tests__`)||e.includes(`/test/`)||e.includes(`/tests/`)}function d(e){let t=e.parent;return t?p(t)?t:d(t):null}function f(e){let t=e?.returnType?.typeAnnotation;if(!t)return null;let n=i.sourceCode.getText(t);return n.includes(`Either`)?null:n}function p(e){return e?[`FunctionDeclaration`,`FunctionExpression`,`ArrowFunctionExpression`].includes(e.type):!1}function m(e){let t=e.parent;if(!t)return!1;if(t.type===`BlockStatement`&&p(t.parent))return!0;if(t.type===`BlockStatement`&&t.parent?.type===`IfStatement`){let e=t.parent.parent;return e?.type===`BlockStatement`&&p(e.parent)}return!1}return{ThrowStatement(e){if(c(e)||l&&u()||r(e))return;let a=i.sourceCode,o=[];if(m(e)){let r=e.argument,i=a.getText(r),s=r?.type===`NewExpression`&&r.callee?.type===`Identifier`&&r.callee.name===`Error`?i:`new Error(String(${i}))`;o.push({messageId:`suggestEitherLeft`,fix(t){return t.replaceText(e,`return Either.left(${s})`)}}),n(a,`Either`)||o.push({messageId:`suggestAddImport`,data:{symbol:`Either`},fix:t(a,`Either`)})}let s=f(d(e));i.report({node:e,...s===null?{messageId:`preferEitherOverThrow`}:{messageId:`preferEitherReturn`,data:{type:s}},suggest:o})}}}};export{i 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 {
|
|
1
|
+
{"version":3,"file":"prefer-either.js","names":["insideCatchClause","parent","node","rule","options","context","allowInteropMarker","allowInvariantMarker","isExemptByMarker","isInsideTaggedDeclaration","allowThrowInTests","isInTestFile","filename","enclosingFunction","isFunctionLike","nonEitherReturnType","returnType","fn","text","isDirectInFunctionBody","ifParent","sourceCode","suggest","throwArg","argText","eitherArg","fixer","hasFunctypeSymbol","createImportFixer"],"sources":["../../src/rules/prefer-either.ts"],"sourcesContent":["import type { Rule } from \"eslint\"\n\nimport type { ASTNode } from \"../types/ast\"\nimport { INTEROP_TAG, INVARIANT_TAG, isInsideTaggedDeclaration } from \"../utils/boundary-tags\"\nimport { createImportFixer, hasFunctypeSymbol } from \"../utils/import-fixer\"\n\n/** True iff any ancestor of `node` is a `CatchClause`. Pure tail recursion. */\nfunction insideCatchClause(node: ASTNode | null | undefined): boolean {\n const parent = node?.parent as ASTNode | undefined\n if (!parent) return false\n return parent.type === \"CatchClause\" || insideCatchClause(parent)\n}\n\nconst rule: Rule.RuleModule = {\n meta: {\n type: \"suggestion\",\n hasSuggestions: true,\n docs: {\n description: \"Use Either/Left/Right for typed domain errors instead of throwing\",\n recommended: true,\n },\n schema: [\n {\n type: \"object\",\n properties: {\n allowInteropMarker: {\n type: \"boolean\",\n default: true,\n },\n allowInvariantMarker: {\n type: \"boolean\",\n default: true,\n },\n allowThrowInTests: {\n type: \"boolean\",\n default: true,\n },\n },\n additionalProperties: false,\n },\n ],\n messages: {\n preferEitherOverThrow: \"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 // `@interop <reason>` on an enclosing declaration marks a host-contract boundary (#241).\n const allowInteropMarker = options.allowInteropMarker !== false\n // `@invariant <reason>` marks throws that signal programmer errors, not expected failures (#325 D).\n const allowInvariantMarker = options.allowInvariantMarker !== false\n const isExemptByMarker = (node: ASTNode): boolean =>\n (allowInteropMarker && isInsideTaggedDeclaration(node, INTEROP_TAG, context.sourceCode)) ||\n (allowInvariantMarker && isInsideTaggedDeclaration(node, INVARIANT_TAG, context.sourceCode))\n const allowThrowInTests = options.allowThrowInTests !== false\n\n function isInTestFile() {\n const filename = context.filename\n return (\n /\\.(test|spec)\\.(ts|js|tsx|jsx)$/.test(filename) ||\n filename.includes(\"__tests__\") ||\n filename.includes(\"/test/\") ||\n filename.includes(\"/tests/\")\n )\n }\n\n /** The nearest function the throw belongs to — a nested function owns its own throws. */\n function enclosingFunction(node: ASTNode): ASTNode | null {\n const parent = node.parent\n if (!parent) return null\n return isFunctionLike(parent) ? parent : enclosingFunction(parent)\n }\n\n /** The declared return type when the function declares one that is not already an Either. */\n function nonEitherReturnType(fn: ASTNode | null): string | null {\n const returnType = fn?.returnType?.typeAnnotation\n if (!returnType) return null\n const text = context.sourceCode.getText(returnType)\n return text.includes(\"Either\") ? null : text\n }\n\n function isFunctionLike(node: ASTNode): boolean {\n if (!node) return false\n return [\"FunctionDeclaration\", \"FunctionExpression\", \"ArrowFunctionExpression\"].includes(node.type)\n }\n\n function isDirectInFunctionBody(node: ASTNode): boolean {\n const parent = node.parent\n if (!parent) return false\n if (parent.type === \"BlockStatement\" && isFunctionLike(parent.parent)) return true\n if (parent.type === \"BlockStatement\" && parent.parent?.type === \"IfStatement\") {\n const ifParent = parent.parent.parent\n return ifParent?.type === \"BlockStatement\" && isFunctionLike(ifParent.parent)\n }\n return false\n }\n\n return {\n ThrowStatement(node: ASTNode) {\n if (isExemptByMarker(node)) return\n // Allow throws in test files if configured\n if (allowThrowInTests && isInTestFile()) return\n\n // Allow re-throwing in catch blocks (common pattern)\n if (insideCatchClause(node)) return\n\n const sourceCode = context.sourceCode\n const suggest: Rule.SuggestionReportDescriptor[] = []\n\n if (isDirectInFunctionBody(node)) {\n const throwArg = node.argument\n const argText = sourceCode.getText(throwArg)\n const isErrorExpr =\n throwArg?.type === \"NewExpression\" &&\n throwArg.callee?.type === \"Identifier\" &&\n throwArg.callee.name === \"Error\"\n const eitherArg = isErrorExpr ? argText : `new Error(String(${argText}))`\n\n suggest.push({\n messageId: \"suggestEitherLeft\",\n fix(fixer) {\n return fixer.replaceText(node, `return Either.left(${eitherArg})`)\n },\n })\n\n if (!hasFunctypeSymbol(sourceCode, \"Either\")) {\n suggest.push({\n messageId: \"suggestAddImport\",\n data: { symbol: \"Either\" },\n fix: createImportFixer(sourceCode, \"Either\"),\n })\n }\n }\n\n // One report per throw (#324). When the enclosing function declares a non-Either return type,\n // the message names the Either it should return instead of reporting the function separately.\n const returnType = nonEitherReturnType(enclosingFunction(node))\n context.report({\n node,\n ...(returnType === null\n ? { messageId: \"preferEitherOverThrow\" }\n : { messageId: \"preferEitherReturn\", data: { type: returnType } }),\n suggest,\n })\n },\n }\n },\n}\n\nexport default rule\n"],"mappings":"0JAOA,SAASA,EAAkB,EAA2C,CACpE,IAAMC,EAASC,GAAM,OAErB,OADKD,EACEA,EAAO,OAAS,eAAiBD,EAAkBC,CAAM,EAD5C,EAEtB,CAEA,MAAME,EAAwB,CAC5B,KAAM,CACJ,KAAM,aACN,eAAgB,GAChB,KAAM,CACJ,YAAa,oEACb,YAAa,EACf,EACA,OAAQ,CACN,CACE,KAAM,SACN,WAAY,CACV,mBAAoB,CAClB,KAAM,UACN,QAAS,EACX,EACA,qBAAsB,CACpB,KAAM,UACN,QAAS,EACX,EACA,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,CACd,IAAMC,EAAUC,EAAQ,QAAQ,IAAM,CAAC,EAEjCC,EAAqBF,EAAQ,qBAAuB,GAEpDG,EAAuBH,EAAQ,uBAAyB,GACxDI,EAAoB,GACvBF,GAAsBG,EAA0BP,EAAA,UAAmBG,EAAQ,UAAU,GACrFE,GAAwBE,EAA0BP,EAAA,YAAqBG,EAAQ,UAAU,EACtFK,EAAoBN,EAAQ,oBAAsB,GAExD,SAASO,GAAe,CACtB,IAAMC,EAAWP,EAAQ,SACzB,MACE,kCAAkC,KAAKO,CAAQ,GAC/CA,EAAS,SAAS,WAAW,GAC7BA,EAAS,SAAS,QAAQ,GAC1BA,EAAS,SAAS,SAAS,CAE/B,CAGA,SAASC,EAAkB,EAA+B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AAC,EAEIE,EAAkBN,EAAY,QAAQ,GACzCC,EAAQ,KAAK,CACX,UAAW,mBACX,KAAM,CAAE,OAAQ,QAAS,EACzB,IAAKM,EAAkBP,EAAY,QAAQ,CAC7C,CAAC,CAEL,CAIA,IAAML,EAAaD,EAAoBF,EAAkBX,CAAI,CAAC,EAC9DG,EAAQ,OAAO,CACb,OACA,GAAIW,IAAe,KACf,CAAE,UAAW,uBAAwB,EACrC,CAAE,UAAW,qBAAsB,KAAM,CAAE,KAAMA,CAAW,CAAE,EAClE,SACF,CAAC,CACH,CACF,CACF,CACF"}
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
const e
|
|
1
|
+
const e=/* @__PURE__ */ new Set([`map`,`filter`,`slice`,`concat`,`split`]),t={meta:{type:`suggestion`,docs:{description:`Prefer .flatMap() over .map().flat() and nested transformations`,recommended:!0},fixable:`code`,schema:[{type:`object`,properties:{checkNestedMaps:{type:`boolean`,default:!0}},additionalProperties:!1}],messages:{preferFlatMapOverMapFlat:`Use .flatMap() instead of .map().flat()`,preferFlatMapNested:`Consider .flatMap() for nested transformations that return arrays`,preferFlatMapChain:`Use .flatMap() instead of chained .map() operations that flatten results`}},create(t){let n=(t.options[0]||{}).checkNestedMaps!==!1;function r(e){if(e.type!==`CallExpression`)return!1;let t=e.callee;if(t.type!==`MemberExpression`)return!1;if(t.property.name===`flat`){let e=t.object;if(e.type===`CallExpression`&&e.callee.type===`MemberExpression`&&e.callee.property.name===`map`)return!0}return!1}function i(e){let t=e.elements??[];return!t.some(e=>e&&e.type===`SpreadElement`)&&t.some(e=>e&&e.type===`ArrayExpression`)}function a(e){return e.type===`CallExpression`?a(e.callee):e.type===`MemberExpression`?a(e.object):e.type===`ChainExpression`||e.type===`TSNonNullExpression`||e.type===`TSAsExpression`||e.type===`TSSatisfiesExpression`?a(e.expression):e}function o(e){return e?e.type===`Identifier`?[e.name]:e.type===`AssignmentPattern`?o(e.left):e.type===`RestElement`?o(e.argument):e.type===`ArrayPattern`?e.elements.flatMap(e=>o(e)):e.type===`ObjectPattern`?e.properties.flatMap(e=>e.type===`RestElement`?o(e.argument):o(e.value)):[]:[]}function s(e,t){let n=a(t);return n.type===`Identifier`&&e.params.flatMap(o).includes(n.name)}function c(t){if(!t||!t.body)return!1;if(t.body.type===`ArrayExpression`)return i(t.body);if(t.body.type===`CallExpression`){let n=t.body;if(s(t,n))return!1;if(n.callee.type===`MemberExpression`){let t=n.callee.property.name;if(e.has(t))return!0}}return t.body.type===`BlockStatement`&&t.body.body.some(e=>l(e)&&!(e.argument.type===`CallExpression`&&s(t,e.argument)))}function l(t){return t.type!==`ReturnStatement`||!t.argument?!1:t.argument.type===`ArrayExpression`?i(t.argument):!!(t.argument.type===`CallExpression`&&t.argument.callee.type===`MemberExpression`&&e.has(t.argument.callee.property.name))}function u(e){if(e.type!==`CallExpression`)return!1;let t=e.callee;if(t.type!==`MemberExpression`)return!1;if(t.property.name===`map`){let t=e.arguments[0];if(t&&(t.type===`ArrowFunctionExpression`||t.type===`FunctionExpression`))return c(t)}return!1}function d(e){let t=/* @__PURE__ */ new Set([`Option`,`Some`,`None`,`Either`,`Right`,`Left`,`Try`,`Success`,`Failure`,`Task`,`Ok`,`Err`,`IO`]);return!!(e.type===`CallExpression`&&e.callee?.type===`Identifier`&&t.has(e.callee.name)||e.type===`CallExpression`&&e.callee?.type===`MemberExpression`&&e.callee.object?.type===`Identifier`&&t.has(e.callee.object.name))}return{CallExpression(e){if(r(e)){let n=t.sourceCode;t.report({node:e,messageId:`preferFlatMapOverMapFlat`,fix(t){let r=e.callee.object,i=n.getText(r).replace(/\.map\s*\(/,`.flatMap(`);return t.replaceText(e,i)}});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&&c(e)){t.report({node:n,messageId:`preferFlatMapChain`});return}}}if(n&&u(e)){if(e.parent&&e.parent.type===`MemberExpression`&&e.parent.parent&&e.parent.parent.type===`CallExpression`&&e.parent.property.name===`flat`)return;let n=e.callee?.object;if(n?.type===`CallExpression`&&n.callee?.type===`MemberExpression`&&n.callee?.property?.name===`map`||e.parent?.type===`MemberExpression`&&e.parent.parent?.type===`CallExpression`&&e.parent.parent.callee?.property?.name===`map`||n&&d(n))return;t.report({node:e,messageId:`preferFlatMapNested`})}}}}};export{t as default};
|
|
2
2
|
//# sourceMappingURL=prefer-flatmap.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"prefer-flatmap.js","names":[],"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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AAM,EAAS,EAAK,OAAO,OAC3B,GACE,EAAO,OAAS,kBAChB,EAAO,OAAO,OAAS,oBACvB,EAAO,OAAO,SAAS,OAAS,MAChC,CAEA,IAAM,EAAmB,EAAO,UAAU,GAC1C,GAAI,GAAoB,EAAa,CAAgB,EAAG,CACtD,EAAQ,OAAO,CACb,KAAM,EACN,UAAW,oBACb,CAAC,EACD,MACF,CACF,CACF,CAGA,GAAI,GAAmB,EAA2B,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
|
+
{"version":3,"file":"prefer-flatmap.js","names":["ARRAY_PRODUCING_METHODS","rule","checkNestedMaps","context","isMapFollowedByFlat","node","callee","object","isFlattenCandidateArrayLiteral","elements","arrayExpr","el","chainRoot","boundNames","param","prop","isShapePreserving","root","returned","functionNode","returnsArray","call","methodName","returnsArrayShape","stmt","isNestedMapReturningArrays","callback","isNonCollectionMonadReceiver","monadConstructors","sourceCode","mapCall","flatMapText","fixer","firstMapCallback"],"sources":["../../src/rules/prefer-flatmap.ts"],"sourcesContent":["import type { Rule } from \"eslint\"\n\nimport type { ASTNode } from \"../types/ast\"\n\n/** Array-prototype methods whose call expression always returns an array. */\nconst ARRAY_PRODUCING_METHODS: ReadonlySet<string> = new Set([\"map\", \"filter\", \"slice\", \"concat\", \"split\"])\n\nconst rule: Rule.RuleModule = {\n meta: {\n type: \"suggestion\",\n docs: {\n description: \"Prefer .flatMap() over .map().flat() and nested transformations\",\n recommended: true,\n },\n fixable: \"code\",\n schema: [\n {\n type: \"object\",\n properties: {\n checkNestedMaps: {\n type: \"boolean\",\n default: true,\n },\n },\n additionalProperties: false,\n },\n ],\n messages: {\n preferFlatMapOverMapFlat: \"Use .flatMap() instead of .map().flat()\",\n preferFlatMapNested: \"Consider .flatMap() for nested transformations that return arrays\",\n preferFlatMapChain: \"Use .flatMap() instead of chained .map() operations that flatten results\",\n },\n },\n\n create(context) {\n const options = context.options[0] || {}\n const checkNestedMaps = options.checkNestedMaps !== false\n\n function isMapFollowedByFlat(node: ASTNode): boolean {\n if (node.type !== \"CallExpression\") return false\n\n const callee = node.callee\n if (callee.type !== \"MemberExpression\") return false\n\n // Check if this is .flat()\n if (callee.property.name === \"flat\") {\n const object = callee.object\n\n // Check if the object is a .map() call\n if (\n object.type === \"CallExpression\" &&\n object.callee.type === \"MemberExpression\" &&\n object.callee.property.name === \"map\"\n ) {\n return true\n }\n }\n\n return false\n }\n\n /**\n * Heuristic for array literals that look like flatten candidates.\n * Skips append/identity patterns (`[...arr, x]`, `[...arr]`) and tuple\n * shapes (`[k, v]`) — those are not nested arrays, so .flatMap()\n * doesn't apply. Only flag when at least one element is itself an\n * ArrayExpression, signaling a true nested-array shape.\n */\n function isFlattenCandidateArrayLiteral(arrayExpr: ASTNode): boolean {\n const elements = arrayExpr.elements ?? []\n if (elements.some((el: ASTNode | null) => el && el.type === \"SpreadElement\")) {\n return false\n }\n return elements.some((el: ASTNode | null) => el && el.type === \"ArrayExpression\")\n }\n\n /**\n * The base identifier of a call/member chain: `members` in `members.filter(f).map(g)`, `r` in\n * `r.cells.map(f)`.\n */\n function chainRoot(node: ASTNode): ASTNode {\n if (node.type === \"CallExpression\") return chainRoot(node.callee)\n if (node.type === \"MemberExpression\") return chainRoot(node.object)\n if (\n node.type === \"ChainExpression\" ||\n node.type === \"TSNonNullExpression\" ||\n node.type === \"TSAsExpression\" ||\n node.type === \"TSSatisfiesExpression\"\n ) {\n return chainRoot(node.expression)\n }\n return node\n }\n\n /** Every name a parameter binds — plain, destructured, defaulted or rest. */\n function boundNames(param: ASTNode): ReadonlyArray<string> {\n if (!param) return []\n if (param.type === \"Identifier\") return [param.name]\n if (param.type === \"AssignmentPattern\") return boundNames(param.left)\n if (param.type === \"RestElement\") return boundNames(param.argument)\n if (param.type === \"ArrayPattern\") return param.elements.flatMap((el: ASTNode) => boundNames(el))\n if (param.type === \"ObjectPattern\") {\n return param.properties.flatMap((prop: ASTNode) =>\n prop.type === \"RestElement\" ? boundNames(prop.argument) : boundNames(prop.value),\n )\n }\n return []\n }\n\n /**\n * A callback that transforms its OWN element's array (`(r) => r.cells.map(f)`, `(s) => s.split(\" \")`,\n * `(xs) => xs.filter(p).map(g)`) keeps the shape: one array per element, a matrix, or an array inside\n * an Either/Option/Task being mapped. Nothing is being flattened, so .flatMap is not the fix (#324).\n */\n function isShapePreserving(functionNode: ASTNode, returned: ASTNode): boolean {\n const root = chainRoot(returned)\n return root.type === \"Identifier\" && functionNode.params.flatMap(boundNames).includes(root.name)\n }\n\n function returnsArray(functionNode: ASTNode): boolean {\n if (!functionNode || !functionNode.body) return false\n\n // Arrow function with expression body\n if (functionNode.body.type === \"ArrayExpression\") {\n return isFlattenCandidateArrayLiteral(functionNode.body)\n }\n\n // Arrow function with call expression body\n if (functionNode.body.type === \"CallExpression\") {\n const call = functionNode.body\n if (isShapePreserving(functionNode, call)) return false\n if (call.callee.type === \"MemberExpression\") {\n const methodName = call.callee.property.name\n // Common methods that return arrays\n if (ARRAY_PRODUCING_METHODS.has(methodName)) {\n return true\n }\n }\n }\n\n // Function with block body — any return statement returning an array shape?\n if (functionNode.body.type === \"BlockStatement\") {\n return functionNode.body.body.some(\n (stmt: ASTNode) =>\n returnsArrayShape(stmt) &&\n !(stmt.argument.type === \"CallExpression\" && isShapePreserving(functionNode, stmt.argument)),\n )\n }\n\n return false\n }\n\n /** A single statement that's `return <array-shaped-expression>`. */\n function returnsArrayShape(stmt: ASTNode): boolean {\n if (stmt.type !== \"ReturnStatement\" || !stmt.argument) return false\n if (stmt.argument.type === \"ArrayExpression\") return isFlattenCandidateArrayLiteral(stmt.argument)\n if (\n stmt.argument.type === \"CallExpression\" &&\n stmt.argument.callee.type === \"MemberExpression\" &&\n ARRAY_PRODUCING_METHODS.has(stmt.argument.callee.property.name)\n ) {\n return true\n }\n return false\n }\n\n function isNestedMapReturningArrays(node: ASTNode): boolean {\n if (node.type !== \"CallExpression\") return false\n\n const callee = node.callee\n if (callee.type !== \"MemberExpression\") return false\n\n // Check if this is .map()\n if (callee.property.name === \"map\") {\n const callback = node.arguments[0]\n if (callback && (callback.type === \"ArrowFunctionExpression\" || callback.type === \"FunctionExpression\")) {\n return returnsArray(callback)\n }\n }\n\n return false\n }\n\n /**\n * Skip the warning when the receiver (`.map`'s left side) is a known\n * non-collection monad constructor call. The rule has no type info, so\n * it can't tell `arr.map(cb => arr2)` (collection, .flatMap is the fix)\n * from `Try(...).map(cb => arr)` (non-collection — .flatMap on Try\n * expects Try<T>, not an array, so .flatMap is NOT the fix).\n *\n * We can't enumerate every non-collection receiver, but we *can* detect\n * the unambiguous case: the receiver is literally `Try(...)` /\n * `Option(...)` / `Either(...)` / `Right(...)` / `Left(...)` / etc.\n * When that holds, suppress the warning. For bare identifiers (`items`)\n * or array literals or array-method chains, we can't tell, so the rule\n * still fires as before.\n */\n function isNonCollectionMonadReceiver(node: ASTNode): boolean {\n const monadConstructors = new Set([\n \"Option\",\n \"Some\",\n \"None\",\n \"Either\",\n \"Right\",\n \"Left\",\n \"Try\",\n \"Success\",\n \"Failure\",\n \"Task\",\n \"Ok\",\n \"Err\",\n \"IO\",\n ])\n // Bare constructor: Try(...), Option(...), Right(x), etc.\n if (\n node.type === \"CallExpression\" &&\n node.callee?.type === \"Identifier\" &&\n monadConstructors.has(node.callee.name)\n ) {\n return true\n }\n // Companion call: Either.right(x), Option.none(), Try.success(v)\n if (\n node.type === \"CallExpression\" &&\n node.callee?.type === \"MemberExpression\" &&\n node.callee.object?.type === \"Identifier\" &&\n monadConstructors.has(node.callee.object.name)\n ) {\n return true\n }\n return false\n }\n\n return {\n CallExpression(node: ASTNode) {\n // Check for .map().flat() pattern first (highest priority)\n if (isMapFollowedByFlat(node)) {\n const sourceCode = context.sourceCode\n\n context.report({\n node,\n messageId: \"preferFlatMapOverMapFlat\",\n fix(fixer) {\n // Get the .map() call\n const mapCall = (node.callee as ASTNode).object\n const mapCallText = sourceCode.getText(mapCall)\n\n // Replace .map() with .flatMap() and remove .flat()\n const flatMapText = mapCallText.replace(/\\.map\\s*\\(/, \".flatMap(\")\n\n return fixer.replaceText(node, flatMapText)\n },\n })\n return // Don't check other patterns if we found .map().flat()\n }\n\n // Check for chained maps where intermediate results are arrays (highest priority after map().flat())\n if (node.callee.type === \"MemberExpression\" && node.callee.property.name === \"map\") {\n const object = node.callee.object\n if (\n object.type === \"CallExpression\" &&\n object.callee.type === \"MemberExpression\" &&\n object.callee.property.name === \"map\"\n ) {\n // Check if the first map returns arrays\n const firstMapCallback = object.arguments[0]\n if (firstMapCallback && returnsArray(firstMapCallback)) {\n context.report({\n node: object, // Report on the first map call\n messageId: \"preferFlatMapChain\",\n })\n return // Don't check other patterns for this chain\n }\n }\n }\n\n // Check for nested maps that return arrays (but not if they're part of map().flat() or chains)\n if (checkNestedMaps && isNestedMapReturningArrays(node)) {\n // Don't flag if this map is immediately followed by flat()\n if (\n node.parent &&\n node.parent.type === \"MemberExpression\" &&\n node.parent.parent &&\n node.parent.parent.type === \"CallExpression\" &&\n node.parent.property.name === \"flat\"\n ) {\n return // Skip - this will be handled by the map().flat() rule\n }\n\n // Don't flag if this map is part of a chain (either as first or second map)\n const object = node.callee?.object\n if (\n object?.type === \"CallExpression\" &&\n object.callee?.type === \"MemberExpression\" &&\n object.callee?.property?.name === \"map\"\n ) {\n return // Skip - this is part of a chain\n }\n\n // Check if this map feeds into another map\n if (\n node.parent?.type === \"MemberExpression\" &&\n node.parent.parent?.type === \"CallExpression\" &&\n node.parent.parent.callee?.property?.name === \"map\"\n ) {\n return // Skip - this feeds into a chain\n }\n\n // Don't flag when the receiver is a known non-collection monad\n // constructor — .flatMap on Try / Option / Either / etc. expects\n // a wrapped value, not an array, so suggesting it is wrong.\n if (object && isNonCollectionMonadReceiver(object)) {\n return\n }\n\n context.report({\n node,\n messageId: \"preferFlatMapNested\",\n })\n }\n },\n }\n },\n}\n\nexport default rule\n"],"mappings":"AAKA,MAAMA,kBAA+C,IAAI,IAAI,CAAC,MAAO,SAAU,QAAS,SAAU,OAAO,CAAC,EAEpGC,EAAwB,CAC5B,KAAM,CACJ,KAAM,aACN,KAAM,CACJ,YAAa,kEACb,YAAa,EACf,EACA,QAAS,OACT,OAAQ,CACN,CACE,KAAM,SACN,WAAY,CACV,gBAAiB,CACf,KAAM,UACN,QAAS,EACX,CACF,EACA,qBAAsB,EACxB,CACF,EACA,SAAU,CACR,yBAA0B,0CAC1B,oBAAqB,oEACrB,mBAAoB,0EACtB,CACF,EAEA,OAAO,EAAS,CAEd,IAAMC,GADUC,EAAQ,QAAQ,IAAM,CAAC,EAAA,CACP,kBAAoB,GAEpD,SAASC,EAAoB,EAAwB,CACnD,GAAIC,EAAK,OAAS,iBAAkB,MAAO,GAE3C,IAAMC,EAASD,EAAK,OACpB,GAAIC,EAAO,OAAS,mBAAoB,MAAO,GAG/C,GAAIA,EAAO,SAAS,OAAS,OAAQ,CACnC,IAAMC,EAASD,EAAO,OAGtB,GACEC,EAAO,OAAS,kBAChBA,EAAO,OAAO,OAAS,oBACvBA,EAAO,OAAO,SAAS,OAAS,MAEhC,MAAO,EAEX,CAEA,MAAO,EACT,CASA,SAASC,EAA+B,EAA6B,CACnE,IAAMC,EAAWC,EAAU,UAAY,CAAC,EAIxC,MAHA,CAAID,EAAS,KAAM,GAAuBE,GAAMA,EAAG,OAAS,eAAe,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InsideTaggedDeclaration as t}from"../utils/boundary-tags.js";const n=/* @__PURE__ */ new Set([`isSome`,`isRight`,`isSuccess`]),r=/* @__PURE__ */ new Set([`isNone`,`isLeft`,`isFailure`]),i={isSome:null,isNone:null,isRight:{param:`left`,member:`value`},isLeft:{param:`left`,member:`value`},isSuccess:{param:`error`,member:`error`},isFailure:{param:`error`,member:`error`}},a=[`get`,`orThrow`];function o(e){return e.type===`Literal`&&e.value===null||e.type===`Identifier`&&e.name===`undefined`}function s(e,t){if(e.type!==`CallExpression`||e.callee.type!==`MemberExpression`)return null;let a=e.callee.property.name,o=t.getText(e.callee.object),s=i[a]??null;return n.has(a)?{obj:o,isNegated:!1,failure:s}:r.has(a)?{obj:o,isNegated:!0,failure:s}:null}const c=e=>e.replace(/\s+/g,``),l={members:[`value`],methods:a};function u(t,n,r,i){let a=e=>{let t=e.type===`TSNonNullExpression`?e.expression:e;return c(i.getText(t))===c(n)},o=(e,t)=>e.type===`MemberExpression`&&!e.computed&&e.property.type===`Identifier`&&t.includes(e.property.name)&&a(e.object),s=t=>{let n=t.parent,i=n?.type===`CallExpression`&&n.callee===t,a=n?.type===`AssignmentExpression`&&n.left===t||n?.type===`UpdateExpression`;return o(t,r.members)&&!i&&!a||t.type===`CallExpression`&&t.arguments.length===0&&o(t.callee,r.methods)?[t.range]:e(t).flatMap(s)};return s(t)}const d=(e,t)=>{let n=e=>t.some(t=>RegExp(`(?<![\\w$.])${e}(?![\\w$])`).test(t));return[e,...Array.from({length:20},(t,n)=>`${e}${n+1}`)].find(e=>!n(e))??`${e}_`},f=(e,t)=>e.type===`ObjectExpression`||e.type===`SequenceExpression`?`(${t})`:t;function p(e,t,n,r,i){let a=i.getText(e),o=n===null?[]:u(e,t,n,i);if(o.length===0)return`() => ${f(e,a)}`;let s=e.range[0],c=[...o].sort((e,t)=>t[0]-e[0]).reduce((e,[t,n])=>e.slice(0,t-s)+r+e.slice(n-s),a);return`(${r}) => ${f(e,c)}`}function m(e,t,n,r,i){let a=[i.getText(n),i.getText(r)],o=p(r,e,l,d(`value`,a),i);return`${e}.fold(${t===null?p(n,e,null,``,i):p(n,e,{members:[t.member],methods:[]},d(t.param,a),i)}, ${o})`}function h(e){let t=e.type===`BlockStatement`&&e.body.length===1?e.body[0]:e;return t.type===`ReturnStatement`&&t.argument?t.argument:null}function g(e){return e.alternate?e.alternate.type===`IfStatement`?1+g(e.alternate):2:1}const _={meta:{type:`suggestion`,docs:{description:`Prefer .fold() over if/else chains when working with monadic types`,recommended:!0},hasSuggestions:!0,schema:[{type:`object`,properties:{allowInteropMarker:{type:`boolean`,default:!0},minComplexity:{type:`integer`,minimum:1,default:2},checkNullable:{type:`boolean`,default:!1}},additionalProperties:!1}],messages:{preferFold:`Prefer .fold() over if/else when working with {{type}} types`,preferFoldTernary:`Consider using .fold() instead of ternary operator for {{type}}`,suggestFold:`Replace with .fold()`,suggestOr:`Replace with {{receiver}}.or({{alternative}}) — keep the first when it is present, else the alternative`}},create(e){let n=e.options[0]||{},r=n.allowInteropMarker!==!1,i=n=>r&&t(n,`interop`,e.sourceCode),a=n.minComplexity||2,l=n.checkNullable===!0;function u(t){let n=e.sourceCode;if(t.type!==`IfStatement`||!t.alternate)return null;let r=s(t.test,n);if(!r)return null;let i=h(t.consequent),a=h(t.alternate);if(!i||!a)return null;let o=[t.test,i,a];if(!n.getCommentsInside(t).every(e=>e.range!==void 0&&o.some(t=>e.range[0]>=t.range[0]&&e.range[1]<=t.range[1])))return null;let{obj:c,isNegated:l,failure:u}=r,[d,f]=l?[i,a]:[a,i];return`return ${m(c,u,d,f,n)}`}function d(t){let n=e.sourceCode,r=s(t.test,n);if(!r)return[];let{obj:i,isNegated:a,failure:l}=r,[u,d]=a?[t.consequent,t.alternate]:[t.alternate,t.consequent],f=n.getText(u),p=n.getText(d);if(c(p)===c(i))return u.type===`Literal`||u.type===`TemplateLiteral`||o(u)?[]:[{messageId:`suggestOr`,data:{receiver:i,alternative:f},fix:e=>e.replaceText(t,`${i}.or(${f})`)}];let h=m(i,l,u,d,n);return[{messageId:`suggestFold`,fix:e=>e.replaceText(t,h)}]}function f(e){if(e.type===`CallExpression`&&e.callee.type===`MemberExpression`){let t=e.callee.property.name;return[`isSome`,`isNone`,`isRight`,`isLeft`,`isSuccess`,`isFailure`].includes(t)}return!1}function p(t){let n=e.sourceCode.getText(t);if(/\.(isSome|isNone|isDefined)\s*\(\s*\)/.test(n))return{isMonadic:!0,type:`Option`,via:`method`};if(/\.(isLeft|isRight)\s*\(\s*\)/.test(n))return{isMonadic:!0,type:`Either`,via:`method`};if(/\.(isSuccess|isFailure)\s*\(\s*\)/.test(n))return{isMonadic:!0,type:`Result`,via:`method`};if(l&&t.type===`BinaryExpression`){if((t.operator===`===`||t.operator===`!==`||t.operator===`==`||t.operator===`!=`)&&(t.left.type===`Literal`&&(t.left.value===null||t.left.value===void 0)||t.right.type===`Literal`&&(t.right.value===null||t.right.value===void 0)))return{isMonadic:!0,type:`Option`,via:`nullable`};if(t.operator===`==`||t.operator===`!=`||t.operator===`===`||t.operator===`!==`){let e=t.left.type===`Identifier`&&t.left.name===`undefined`,n=t.right.type===`Identifier`&&t.right.name===`undefined`;if(e||n)return{isMonadic:!0,type:`Option`,via:`nullable`}}}return{isMonadic:!1,type:``,via:``}}function _(e){if(!f(e.test))return[];let t=u(e);return t?[{messageId:`suggestFold`,fix:n=>n.replaceText(e,t)}]:[]}function v(t){let n=t.test,r=p(n);r.isMonadic&&(t.parent&&t.parent.type===`IfStatement`||g(t)>=a&&e.report({node:t,messageId:`preferFold`,data:{type:r.type},suggest:_(t)}))}return{IfStatement(e){i(e)||v(e)},ConditionalExpression(t){if(i(t))return;let n=p(t.test);(n.via!==`nullable`||!o(t.consequent)&&!o(t.alternate))&&n.isMonadic&&e.report({node:t,messageId:`preferFoldTernary`,data:{type:n.type},suggest:f(t.test)?d(t):[]})}}}};export{_ 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 * 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) {\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,EAAiB,EAAwB,CAChD,OAAQ,EAAK,OAAS,WAAa,EAAK,QAAU,MAAU,EAAK,OAAS,cAAgB,EAAK,OAAS,WAC1G,CAOA,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,O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,aACX,KAAM,CAAE,KAAM,EAAY,IAAK,EAC/B,IAAI,EAAO,CAET,GAAI,CAAC,EAAc,EAAK,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,EAKxC,EAAY,MAAQ,aAAe,EAAiB,EAAK,UAAU,GAAK,EAAiB,EAAK,SAAS,IAGvG,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":["POSITIVE_PREDICATES","NEGATIVE_PREDICATES","FAILURE_SIDE","SUCCESS_METHODS","isNullishLiteral","node","extractMonadicTest","test","methodName","obj","sourceCode","failure","compact","text","SUCCESS_READS","receiverReads","isReceiver","target","receiver","isMember","names","visit","parent","isCalled","isWritten","reads","childNodes","branch","freshName","isTaken","branches","name","b","base","i","asArrowBody","foldCallback","ranges","offset","rewritten","a","start","end","acc","param","buildFold","failureNode","successNode","onSuccess","returnedExpression","statement","ifElseChainLength","rule","options","context","allowInteropMarker","isExemptByMarker","isInsideTaggedDeclaration","minComplexity","checkNullable","generateFoldFromIf","extracted","thenExpr","elseExpr","kept","c","n","failureExpr","successExpr","isNegated","ternarySuggestions","failureText","successText","fixer","fold","isFunctypePredicateCall","isMonadicCheck","leftIsUndefined","rightIsUndefined","suggestionsForIf","replacement","analyzeIfStatement","monadicInfo"],"sources":["../../src/rules/prefer-fold.ts"],"sourcesContent":["import type { Rule, SourceCode } from \"eslint\"\n\nimport type { ASTNode } from \"../types/ast\"\nimport { childNodes } from \"../utils/ast-walk\"\nimport { INTEROP_TAG, isInsideTaggedDeclaration } from \"../utils/boundary-tags\"\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.\" */\n// `isEmpty` is deliberately absent: it is a property on every functype container, never a method, so\n// `x.isEmpty()` is not functype code (and on a List, `.fold` is a reduce, not a branch).\nconst NEGATIVE_PREDICATES: ReadonlySet<string> = new Set([\"isNone\", \"isLeft\", \"isFailure\"])\n\n/**\n * How each container's fold exposes its failure side. `fold(onFailure, onSuccess)` everywhere, but\n * only Either and Try hand the failure callback a value — Option's `onNone` takes nothing. `member`\n * is the property a narrowed branch reads that value through (`e.value` after `isLeft()`,\n * `t.error` after `isFailure()`).\n */\ntype FailureSide = { readonly param: string; readonly member: string } | null\n\nconst FAILURE_SIDE: Readonly<Record<string, FailureSide>> = {\n isSome: null,\n isNone: null,\n isRight: { param: \"left\", member: \"value\" },\n isLeft: { param: \"left\", member: \"value\" },\n isSuccess: { param: \"error\", member: \"error\" },\n isFailure: { param: \"error\", member: \"error\" },\n}\n\n/** Reads of the success value that the fold's success parameter replaces. */\nconst SUCCESS_METHODS = [\"get\", \"orThrow\"]\nconst SUCCESS_MEMBER = \"value\"\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(\n test: ASTNode,\n sourceCode: SourceCode,\n): { obj: string; isNegated: boolean; failure: FailureSide } | 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 const failure = FAILURE_SIDE[methodName] ?? null\n if (POSITIVE_PREDICATES.has(methodName)) return { obj, isNegated: false, failure }\n if (NEGATIVE_PREDICATES.has(methodName)) return { obj, isNegated: true, failure }\n return null\n}\n\n/** Source text with all whitespace removed — receivers match however they are line-broken. */\nconst compact = (text: string): string => text.replace(/\\s+/g, \"\")\n\n/** Which reads of the narrowed receiver a fold parameter replaces. */\ntype Reads = { readonly members: ReadonlyArray<string>; readonly methods: ReadonlyArray<string> }\n\nconst SUCCESS_READS: Reads = { members: [SUCCESS_MEMBER], methods: SUCCESS_METHODS }\n\n/**\n * Source ranges inside `branch` that read the narrowed receiver: `e.value`, `e!.value`, `e?.value`,\n * `e.orThrow()`. Driven by the AST rather than the text, so a read never matches inside a string or\n * template literal, a comment, a longer name, or another object's member (`other.e.value`). A member\n * that is called (`e.value()`) or assigned (`e.value = 3`) is not a read.\n */\nfunction receiverReads(\n branch: ASTNode,\n receiver: string,\n reads: Reads,\n sourceCode: SourceCode,\n): ReadonlyArray<readonly [number, number]> {\n const isReceiver = (node: ASTNode): boolean => {\n const target = node.type === \"TSNonNullExpression\" ? node.expression : node\n return compact(sourceCode.getText(target)) === compact(receiver)\n }\n const isMember = (node: ASTNode, names: ReadonlyArray<string>): boolean =>\n node.type === \"MemberExpression\" &&\n !node.computed &&\n node.property.type === \"Identifier\" &&\n names.includes(node.property.name) &&\n isReceiver(node.object)\n\n const visit = (node: ASTNode): ReadonlyArray<readonly [number, number]> => {\n const parent = node.parent\n const isCalled = parent?.type === \"CallExpression\" && parent.callee === node\n const isWritten =\n (parent?.type === \"AssignmentExpression\" && parent.left === node) || parent?.type === \"UpdateExpression\"\n if (isMember(node, reads.members) && !isCalled && !isWritten) return [node.range]\n if (node.type === \"CallExpression\" && node.arguments.length === 0 && isMember(node.callee, reads.methods)) {\n return [node.range]\n }\n return childNodes(node).flatMap(visit)\n }\n return visit(branch)\n}\n\n/** A parameter name no branch already uses, so the fold never shadows a captured identifier. */\nconst freshName = (base: string, branches: ReadonlyArray<string>): string => {\n // `(?<![\\\\w$.])`: a property access (`e.value`) is not a free identifier, so it cannot be shadowed.\n const isTaken = (name: string): boolean => branches.some((b) => new RegExp(`(?<![\\\\w$.])${name}(?![\\\\w$])`).test(b))\n const candidates = [base, ...Array.from({ length: 20 }, (_, i) => `${base}${i + 1}`)]\n return candidates.find((name) => !isTaken(name)) ?? `${base}_`\n}\n\n/**\n * An arrow body must not start with `{` (it would parse as a block) and a comma expression must stay\n * one argument, so those two shapes are parenthesized. ESTree ranges exclude the source's own parens.\n */\nconst asArrowBody = (node: ASTNode, text: string): string =>\n node.type === \"ObjectExpression\" || node.type === \"SequenceExpression\" ? `(${text})` : text\n\n/**\n * One fold callback. Reads of the narrowed receiver become reads of the callback's parameter — the\n * receiver is NOT narrowed inside the callback, so leaving `e.value` there is a type error (#323).\n * A branch that never reads the value gets a parameterless callback, not an unused parameter.\n */\nfunction foldCallback(\n branch: ASTNode,\n receiver: string,\n reads: Reads | null,\n param: string,\n sourceCode: SourceCode,\n): string {\n const text = sourceCode.getText(branch)\n const ranges = reads === null ? [] : receiverReads(branch, receiver, reads, sourceCode)\n if (ranges.length === 0) return `() => ${asArrowBody(branch, text)}`\n const offset = branch.range[0]\n // Replace right-to-left so earlier offsets stay valid.\n const rewritten = [...ranges]\n .sort((a, b) => b[0] - a[0])\n .reduce((acc, [start, end]) => acc.slice(0, start - offset) + param + acc.slice(end - offset), text)\n return `(${param}) => ${asArrowBody(branch, rewritten)}`\n}\n\n/** `receiver.fold(onFailure, onSuccess)` from the two branch nodes. */\nfunction buildFold(\n receiver: string,\n failure: FailureSide,\n failureNode: ASTNode,\n successNode: ASTNode,\n sourceCode: SourceCode,\n): string {\n const branches = [sourceCode.getText(failureNode), sourceCode.getText(successNode)]\n const onSuccess = foldCallback(successNode, receiver, SUCCESS_READS, freshName(\"value\", branches), sourceCode)\n const onFailure =\n failure === null\n ? foldCallback(failureNode, receiver, null, \"\", sourceCode)\n : foldCallback(\n failureNode,\n receiver,\n { members: [failure.member], methods: [] },\n freshName(failure.param, branches),\n sourceCode,\n )\n return `${receiver}.fold(${onFailure}, ${onSuccess})`\n}\n\n/** The returned expression of a `return x` statement or a `{ return x }` block; null for anything else. */\nfunction returnedExpression(node: ASTNode): ASTNode | null {\n const statement = node.type === \"BlockStatement\" && node.body.length === 1 ? node.body[0] : node\n return statement.type === \"ReturnStatement\" && statement.argument ? statement.argument : 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 // Suggestions, never an autofix (#323): `ts-builds validate` runs `eslint --fix`, which applies\n // fixable rules at warn severity too, and a fold rewrite cannot be proven type-correct without type\n // information. The developer applies it, and the compiler checks it.\n hasSuggestions: true,\n schema: [\n {\n type: \"object\",\n properties: {\n allowInteropMarker: {\n type: \"boolean\",\n default: true,\n },\n minComplexity: {\n type: \"integer\",\n minimum: 1,\n default: 2,\n },\n checkNullable: {\n type: \"boolean\",\n default: false,\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 suggestFold: \"Replace with .fold()\",\n suggestOr:\n \"Replace with {{receiver}}.or({{alternative}}) — keep the first when it is present, else the alternative\",\n },\n },\n\n create(context) {\n const options = context.options[0] || {}\n // `@interop <reason>` on an enclosing declaration marks a host-contract boundary (#241).\n const allowInteropMarker = options.allowInteropMarker !== false\n const isExemptByMarker = (node: ASTNode): boolean =>\n allowInteropMarker && isInsideTaggedDeclaration(node, INTEROP_TAG, context.sourceCode)\n const minComplexity = options.minComplexity || 2\n // Off by default (#325): a null check on a plain value (`x === null ? a : b`) is not a fold of a\n // functype value. Whether that value should be an Option is prefer-option's call, and at error this\n // path fired on JSX conditionals, style objects and conditional spreads (31 of 31 hits in CivalaOS,\n // 0 of which were functype values). Predicate calls (`o.isSome()`, `e.isLeft()`) are always checked.\n const checkNullable = options.checkNullable === true\n\n function generateFoldFromIf(node: ASTNode): string | null {\n const sourceCode = context.sourceCode\n if (node.type !== \"IfStatement\" || !node.alternate) return null\n\n const extracted = extractMonadicTest(node.test, sourceCode)\n if (!extracted) return null\n\n // Only if/else where both branches return a value — the fold then replaces the whole statement\n // as `return receiver.fold(...)`. Anything else (side effects, nested else-if) is left alone.\n const thenExpr = returnedExpression(node.consequent)\n const elseExpr = returnedExpression(node.alternate)\n if (!thenExpr || !elseExpr) return null\n\n // The suggestion keeps only the test and the two returned values; a comment anywhere else in the\n // statement would be silently dropped, so none is offered.\n const kept = [node.test, thenExpr, elseExpr]\n const within = (c: { range?: [number, number] }): boolean =>\n c.range !== undefined && kept.some((n) => c.range![0] >= n.range[0] && c.range![1] <= n.range[1])\n if (!sourceCode.getCommentsInside(node).every(within)) return null\n\n const { obj, isNegated, failure } = extracted\n const [failureExpr, successExpr] = isNegated ? [thenExpr, elseExpr] : [elseExpr, thenExpr]\n return `return ${buildFold(obj, failure, failureExpr, successExpr, sourceCode)}`\n }\n\n function ternarySuggestions(node: ASTNode): Rule.SuggestionReportDescriptor[] {\n const sourceCode = context.sourceCode\n const extracted = extractMonadicTest(node.test, sourceCode)\n if (!extracted) return []\n\n const { obj, isNegated, failure } = extracted\n const [failureNode, successNode] = isNegated\n ? [node.consequent, node.alternate]\n : [node.alternate, node.consequent]\n const failureText = sourceCode.getText(failureNode)\n const successText = sourceCode.getText(successNode)\n\n // `a.isSome() ? a : b` keeps the container when present and falls back otherwise — that is `.or`,\n // and a fold would only rebuild it with an unused parameter. `.or` takes a container, so a literal\n // or `undefined` fallback gets no suggestion at all: neither `.or(5)` nor a fold mixing a container\n // with a plain value would type-check.\n if (compact(successText) === compact(obj)) {\n if (failureNode.type === \"Literal\" || failureNode.type === \"TemplateLiteral\" || isNullishLiteral(failureNode)) {\n return []\n }\n return [\n {\n messageId: \"suggestOr\",\n data: { receiver: obj, alternative: failureText },\n fix: (fixer) => fixer.replaceText(node, `${obj}.or(${failureText})`),\n },\n ]\n }\n\n const fold = buildFold(obj, failure, failureNode, successNode, sourceCode)\n return [{ messageId: \"suggestFold\", fix: (fixer) => fixer.replaceText(node, fold) }]\n }\n\n function isFunctypePredicateCall(node: ASTNode): boolean {\n // Suggest a rewrite only when the test is a functype predicate call (the receiver is a functype value)\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\", \"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|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 (checkNullable && 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 suggestionsForIf(node: ASTNode): Rule.SuggestionReportDescriptor[] {\n if (!isFunctypePredicateCall(node.test)) return []\n const replacement = generateFoldFromIf(node)\n return replacement ? [{ messageId: \"suggestFold\", fix: (fixer) => fixer.replaceText(node, replacement) }] : []\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 suggest: suggestionsForIf(node),\n })\n }\n }\n\n return {\n IfStatement(node: ASTNode) {\n if (isExemptByMarker(node)) return\n analyzeIfStatement(node)\n },\n\n ConditionalExpression(node: ASTNode) {\n if (isExemptByMarker(node)) return\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 suggest: isFunctypePredicateCall(node.test) ? ternarySuggestions(node) : [],\n })\n }\n },\n }\n },\n}\n\nexport default rule\n"],"mappings":"wHAOA,MAAMA,kBAA2C,IAAI,IAAI,CAAC,SAAU,UAAW,WAAW,CAAC,EAIrFC,kBAA2C,IAAI,IAAI,CAAC,SAAU,SAAU,WAAW,CAAC,EAUpFC,EAAsD,CAC1D,OAAQ,KACR,OAAQ,KACR,QAAS,CAAE,MAAO,OAAQ,OAAQ,OAAQ,EAC1C,OAAQ,CAAE,MAAO,OAAQ,OAAQ,OAAQ,EACzC,UAAW,CAAE,MAAO,QAAS,OAAQ,OAAQ,EAC7C,UAAW,CAAE,MAAO,QAAS,OAAQ,OAAQ,CAC/C,EAGMC,EAAkB,CAAC,MAAO,SAAS,EAQzC,SAASC,EAAiB,EAAwB,CAChD,OAAQC,EAAK,OAAS,WAAaA,EAAK,QAAU,MAAUA,EAAK,OAAS,cAAgBA,EAAK,OAAS,WAC1G,CAOA,SAASC,EACP,EACA,EACkE,CAClE,GAAIC,EAAK,OAAS,kBAAoBA,EAAK,OAAO,OAAS,mBAAoB,OAAO,KACtF,IAAMC,EAAaD,EAAK,OAAO,SAAS,KAClCE,EAAMC,EAAW,QAAQH,EAAK,OAAO,MAAM,EAC3CI,EAAUT,EAAaM,IAAe,KAG5C,OAFIR,EAAoB,IAAIQ,CAAU,EAAU,CAAE,MAAK,UAAW,GAAO,SAA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AAI,IAAK,EAAG,CAC/C,CAEA,SAASC,EAAiB,EAAkD,CAC1E,GAAI,CAACJ,EAAwBtE,EAAK,IAAI,EAAG,MAAO,CAAC,EACjD,IAAM2E,EAAcpB,EAAmBvD,CAAI,EAC3C,OAAO2E,EAAc,CAAC,CAAE,UAAW,cAAe,IAAM,GAAUP,EAAM,YAAYpE,EAAM2E,CAAW,CAAE,CAAC,EAAI,CAAC,CAC/G,CAEA,SAASC,EAAmB,EAAe,CACzC,IAAM1E,EAAOF,EAAK,KACZ6E,EAAcN,EAAerE,CAAI,EAElC2E,EAAY,YAIb7E,EAAK,QAAUA,EAAK,OAAO,OAAS,eAGpC8C,EAAkB9C,CAAI,GAAKqD,GAC7BJ,EAAQ,OAAO,CACb,OACA,UAAW,aACX,KAAM,CAAE,KAAM4B,EAAY,IAAK,EAC/B,QAASH,EAAiB1E,CAAI,CAChC,CAAC,EAEL,CAEA,MAAO,CACL,YAAY,EAAe,CACrBmD,EAAiBnD,CAAI,GACzB4E,EAAmB5E,CAAI,CACzB,EAEA,sBAAsB,EAAe,CACnC,GAAImD,EAAiBnD,CAAI,EAAG,OAC5B,IAAM6E,EAAcN,EAAevE,EAAK,IAAI,GAKxC6E,EAAY,MAAQ,YAAe,GAAiB7E,EAAK,UAAU,GAAK,GAAiBA,EAAK,SAAS,IAGvG6E,EAAY,WACd5B,EAAQ,OAAO,CACb,OACA,UAAW,oBACX,KAAM,CAAE,KAAM4B,EAAY,IAAK,EAC/B,QAASP,EAAwBtE,EAAK,IAAI,EAAIiE,EAAmBjE,CAAI,EAAI,CAAC,CAC5E,CAAC,CAEL,CACF,CACF,CACF"}
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import{getFunctypeImportsLegacy as e,isAlreadyUsingFunctype as t}from"../utils/functype-detection.js";import{createImportFixer as n,hasFunctypeSymbol as r}from"../utils/import-fixer.js";const
|
|
1
|
+
import{getFunctypeImportsLegacy as e,isAlreadyUsingFunctype as t}from"../utils/functype-detection.js";import{createImportFixer as n,hasFunctypeSymbol as r}from"../utils/import-fixer.js";import{MAP_MUTATORS as i,annotatesMutatedBinding as a,isMutatedCollection as o}from"../utils/mutable-collection.js";const s={meta:{type:`suggestion`,hasSuggestions:!0,docs:{description:`Prefer functype Map<K, V> over native Map for immutable key-value collections`,recommended:!0},schema:[{type:`object`,properties:{allowInTests:{type:`boolean`,default:!0},allowMutable:{type:`boolean`,default:!0}},additionalProperties:!1}],messages:{preferFunctypeMap:`Prefer functype Map<{{keyType}}, {{valueType}}> over native Map`,preferFunctypeMapLiteral:`Prefer Map.of(...) or Map.empty() over new Map()`,suggestMapEmpty:`Replace with Map.empty()`,suggestMapOf:`Replace with Map.of(...)`,suggestMapFrom:`Replace with Map(...)`,suggestAddImport:`Add {{symbol}} import from functype`}},create(s){let c=s.options[0]||{},l=c.allowInTests!==!1,u=c.allowMutable!==!1;function d(){let e=s.filename;return/\.(test|spec)\.(ts|js|tsx|jsx)$/.test(e)||e.includes(`__tests__`)||e.includes(`/test/`)||e.includes(`/tests/`)}let f=e(s);function p(){return r(s.sourceCode,`Map`)}return{NewExpression(e){if(l&&d()||!e.callee||e.callee.type!==`Identifier`||e.callee.name!==`Map`||u&&o(e,i,s.sourceCode)||p()||t(e,f))return;let r=s.sourceCode,a=e.arguments,c=[];if(a.length===0)c.push({messageId:`suggestMapEmpty`,fix(t){return t.replaceText(e,`Map.empty()`)}});else if(a.length===1&&a[0].type===`ArrayExpression`){let t=a[0].elements.map(e=>r.getText(e)).join(`, `);c.push({messageId:`suggestMapOf`,fix(n){return n.replaceText(e,`Map.of(${t})`)}})}else if(a.length===1){let t=r.getText(a[0]);c.push({messageId:`suggestMapFrom`,fix(n){return n.replaceText(e,`Map(${t})`)}})}else c.push({messageId:`suggestMapEmpty`,fix(t){return t.replaceText(e,`Map.empty()`)}});p()||c.push({messageId:`suggestAddImport`,data:{symbol:`Map`},fix:n(r,`Map`)}),s.report({node:e,messageId:`preferFunctypeMapLiteral`,suggest:c})},TSTypeReference(e){if(l&&d()||!e.typeName)return;let t=s.sourceCode;if((e.typeName.type===`Identifier`?e.typeName.name:t.getText(e.typeName))!==`Map`||u&&a(e,i,s.sourceCode)||p())return;let r=e.typeArguments?.params??e.typeParameters?.params,o=r?.[0]?t.getText(r[0]):`K`,c=r&&r.length>=2?t.getText(r[1]):`V`,f=[{messageId:`suggestAddImport`,data:{symbol:`Map`},fix:n(t,`Map`)}];s.report({node:e,messageId:`preferFunctypeMap`,data:{keyType:o,valueType:c},suggest:f})}}}};export{s as default};
|
|
2
2
|
//# sourceMappingURL=prefer-functype-map.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"prefer-functype-map.js","names":[],"sources":["../../src/rules/prefer-functype-map.ts"],"sourcesContent":["import type { Rule } from \"eslint\"\n\nimport type { ASTNode } from \"../types/ast\"\nimport { getFunctypeImportsLegacy, isAlreadyUsingFunctype } from \"../utils/functype-detection\"\nimport { createImportFixer, hasFunctypeSymbol } from \"../utils/import-fixer\"\n\nconst rule: Rule.RuleModule = {\n meta: {\n type: \"suggestion\",\n hasSuggestions: true,\n docs: {\n description: \"Prefer functype Map<K, V> over native Map for immutable key-value collections\",\n recommended: true,\n },\n schema: [\n {\n type: \"object\",\n properties: {\n allowInTests: {\n type: \"boolean\",\n default: true,\n },\n },\n additionalProperties: false,\n },\n ],\n messages: {\n preferFunctypeMap: \"Prefer functype Map<{{keyType}}, {{valueType}}> over native Map\",\n preferFunctypeMapLiteral: \"Prefer Map.of(...) or Map.empty() over new Map()\",\n suggestMapEmpty: \"Replace with Map.empty()\",\n suggestMapOf: \"Replace with Map.of(...)\",\n suggestMapFrom: \"Replace with Map(...)\",\n suggestAddImport: \"Add {{symbol}} import from functype\",\n },\n },\n\n create(context) {\n const options = context.options[0] || {}\n const allowInTests = options.allowInTests !== false\n\n function isInTestFile() {\n const filename = context.filename\n return (\n /\\.(test|spec)\\.(ts|js|tsx|jsx)$/.test(filename) ||\n filename.includes(\"__tests__\") ||\n filename.includes(\"/test/\") ||\n filename.includes(\"/tests/\")\n )\n }\n\n const functypeImports = getFunctypeImportsLegacy(context)\n\n function isMapImportedFromFunctype(): boolean {\n return hasFunctypeSymbol(context.sourceCode, \"Map\")\n }\n\n return {\n NewExpression(node: ASTNode) {\n if (allowInTests && isInTestFile()) return\n\n // Only flag `new Map(...)` calls\n if (!node.callee || node.callee.type !== \"Identifier\" || node.callee.name !== \"Map\") return\n\n // Skip if Map is already imported from functype\n if (isMapImportedFromFunctype()) return\n\n // Skip if already using functype\n if (isAlreadyUsingFunctype(node, functypeImports)) return\n\n const sourceCode = context.sourceCode\n const args = node.arguments as ASTNode[]\n\n const suggestions: Rule.SuggestionReportDescriptor[] = []\n\n if (args.length === 0) {\n // new Map() → Map.empty()\n suggestions.push({\n messageId: \"suggestMapEmpty\",\n fix(fixer) {\n return fixer.replaceText(node, \"Map.empty()\")\n },\n })\n } else if (args.length === 1 && args[0].type === \"ArrayExpression\") {\n // new Map([[\"a\", 1], [\"b\", 2]]) → Map.of([\"a\", 1], [\"b\", 2])\n const arrayArg = args[0] as ASTNode\n const elements = arrayArg.elements as ASTNode[]\n const tupleTexts = elements.map((el: ASTNode) => sourceCode.getText(el))\n const mapOfArgs = tupleTexts.join(\", \")\n suggestions.push({\n messageId: \"suggestMapOf\",\n fix(fixer) {\n return fixer.replaceText(node, `Map.of(${mapOfArgs})`)\n },\n })\n } else if (args.length === 1) {\n // new Map(someVar) → Map(someVar)\n const argText = sourceCode.getText(args[0])\n suggestions.push({\n messageId: \"suggestMapFrom\",\n fix(fixer) {\n return fixer.replaceText(node, `Map(${argText})`)\n },\n })\n } else {\n // Generic fallback for any other args\n suggestions.push({\n messageId: \"suggestMapEmpty\",\n fix(fixer) {\n return fixer.replaceText(node, \"Map.empty()\")\n },\n })\n }\n\n if (!isMapImportedFromFunctype()) {\n suggestions.push({\n messageId: \"suggestAddImport\",\n data: { symbol: \"Map\" },\n fix: createImportFixer(sourceCode, \"Map\"),\n })\n }\n\n context.report({\n node,\n messageId: \"preferFunctypeMapLiteral\",\n suggest: suggestions,\n })\n },\n\n TSTypeReference(node: ASTNode) {\n if (allowInTests && isInTestFile()) return\n\n if (!node.typeName) return\n\n const sourceCode = context.sourceCode\n const typeName = node.typeName.type === \"Identifier\" ? node.typeName.name : sourceCode.getText(node.typeName)\n\n if (typeName !== \"Map\") return\n\n // Skip if Map is already imported from functype\n if (isMapImportedFromFunctype()) return\n\n // Extract key/value type params if present (typeArguments for newer TS-ESLint, typeParameters for older)\n const typeParams = node.typeArguments?.params ?? node.typeParameters?.params\n const keyType = typeParams?.[0] ? sourceCode.getText(typeParams[0]) : \"K\"\n const valueType = typeParams && typeParams.length >= 2 ? sourceCode.getText(typeParams[1]) : \"V\"\n\n const suggestions: Rule.SuggestionReportDescriptor[] = [\n {\n messageId: \"suggestAddImport\",\n data: { symbol: \"Map\" },\n fix: createImportFixer(sourceCode, \"Map\"),\n },\n ]\n\n context.report({\n node,\n messageId: \"preferFunctypeMap\",\n data: { keyType, valueType },\n suggest: suggestions,\n })\n },\n }\n },\n}\n\nexport default rule\n"],"mappings":"
|
|
1
|
+
{"version":3,"file":"prefer-functype-map.js","names":["rule","options","context","allowInTests","allowMutable","isInTestFile","filename","functypeImports","getFunctypeImportsLegacy","isMapImportedFromFunctype","hasFunctypeSymbol","node","isMutatedCollection","MAP_MUTATORS","isAlreadyUsingFunctype","sourceCode","args","suggestions","fixer","mapOfArgs","el","argText","createImportFixer","annotatesMutatedBinding","typeParams","keyType","valueType"],"sources":["../../src/rules/prefer-functype-map.ts"],"sourcesContent":["import type { Rule } from \"eslint\"\n\nimport type { ASTNode } from \"../types/ast\"\nimport { getFunctypeImportsLegacy, isAlreadyUsingFunctype } from \"../utils/functype-detection\"\nimport { createImportFixer, hasFunctypeSymbol } from \"../utils/import-fixer\"\nimport { annotatesMutatedBinding, isMutatedCollection, MAP_MUTATORS } from \"../utils/mutable-collection\"\n\nconst rule: Rule.RuleModule = {\n meta: {\n type: \"suggestion\",\n hasSuggestions: true,\n docs: {\n description: \"Prefer functype Map<K, V> over native Map for immutable key-value collections\",\n recommended: true,\n },\n schema: [\n {\n type: \"object\",\n properties: {\n allowInTests: {\n type: \"boolean\",\n default: true,\n },\n allowMutable: {\n type: \"boolean\",\n default: true,\n },\n },\n additionalProperties: false,\n },\n ],\n messages: {\n preferFunctypeMap: \"Prefer functype Map<{{keyType}}, {{valueType}}> over native Map\",\n preferFunctypeMapLiteral: \"Prefer Map.of(...) or Map.empty() over new Map()\",\n suggestMapEmpty: \"Replace with Map.empty()\",\n suggestMapOf: \"Replace with Map.of(...)\",\n suggestMapFrom: \"Replace with Map(...)\",\n suggestAddImport: \"Add {{symbol}} import from functype\",\n },\n },\n\n create(context) {\n const options = context.options[0] || {}\n const allowInTests = options.allowInTests !== false\n // A native Map the code mutates on purpose (cache, registry, accumulator) is a deliberate choice —\n // functype's Map is immutable and cannot express it (#324).\n const allowMutable = options.allowMutable !== 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 const functypeImports = getFunctypeImportsLegacy(context)\n\n function isMapImportedFromFunctype(): boolean {\n return hasFunctypeSymbol(context.sourceCode, \"Map\")\n }\n\n return {\n NewExpression(node: ASTNode) {\n if (allowInTests && isInTestFile()) return\n\n // Only flag `new Map(...)` calls\n if (!node.callee || node.callee.type !== \"Identifier\" || node.callee.name !== \"Map\") return\n\n if (allowMutable && isMutatedCollection(node, MAP_MUTATORS, context.sourceCode)) return\n\n // Skip if Map is already imported from functype\n if (isMapImportedFromFunctype()) return\n\n // Skip if already using functype\n if (isAlreadyUsingFunctype(node, functypeImports)) return\n\n const sourceCode = context.sourceCode\n const args = node.arguments as ASTNode[]\n\n const suggestions: Rule.SuggestionReportDescriptor[] = []\n\n if (args.length === 0) {\n // new Map() → Map.empty()\n suggestions.push({\n messageId: \"suggestMapEmpty\",\n fix(fixer) {\n return fixer.replaceText(node, \"Map.empty()\")\n },\n })\n } else if (args.length === 1 && args[0].type === \"ArrayExpression\") {\n // new Map([[\"a\", 1], [\"b\", 2]]) → Map.of([\"a\", 1], [\"b\", 2])\n const arrayArg = args[0] as ASTNode\n const elements = arrayArg.elements as ASTNode[]\n const tupleTexts = elements.map((el: ASTNode) => sourceCode.getText(el))\n const mapOfArgs = tupleTexts.join(\", \")\n suggestions.push({\n messageId: \"suggestMapOf\",\n fix(fixer) {\n return fixer.replaceText(node, `Map.of(${mapOfArgs})`)\n },\n })\n } else if (args.length === 1) {\n // new Map(someVar) → Map(someVar)\n const argText = sourceCode.getText(args[0])\n suggestions.push({\n messageId: \"suggestMapFrom\",\n fix(fixer) {\n return fixer.replaceText(node, `Map(${argText})`)\n },\n })\n } else {\n // Generic fallback for any other args\n suggestions.push({\n messageId: \"suggestMapEmpty\",\n fix(fixer) {\n return fixer.replaceText(node, \"Map.empty()\")\n },\n })\n }\n\n if (!isMapImportedFromFunctype()) {\n suggestions.push({\n messageId: \"suggestAddImport\",\n data: { symbol: \"Map\" },\n fix: createImportFixer(sourceCode, \"Map\"),\n })\n }\n\n context.report({\n node,\n messageId: \"preferFunctypeMapLiteral\",\n suggest: suggestions,\n })\n },\n\n TSTypeReference(node: ASTNode) {\n if (allowInTests && isInTestFile()) return\n\n if (!node.typeName) return\n\n const sourceCode = context.sourceCode\n const typeName = node.typeName.type === \"Identifier\" ? node.typeName.name : sourceCode.getText(node.typeName)\n\n if (typeName !== \"Map\") return\n\n if (allowMutable && annotatesMutatedBinding(node, MAP_MUTATORS, context.sourceCode)) return\n\n // Skip if Map is already imported from functype\n if (isMapImportedFromFunctype()) return\n\n // Extract key/value type params if present (typeArguments for newer TS-ESLint, typeParameters for older)\n const typeParams = node.typeArguments?.params ?? node.typeParameters?.params\n const keyType = typeParams?.[0] ? sourceCode.getText(typeParams[0]) : \"K\"\n const valueType = typeParams && typeParams.length >= 2 ? sourceCode.getText(typeParams[1]) : \"V\"\n\n const suggestions: Rule.SuggestionReportDescriptor[] = [\n {\n messageId: \"suggestAddImport\",\n data: { symbol: \"Map\" },\n fix: createImportFixer(sourceCode, \"Map\"),\n },\n ]\n\n context.report({\n node,\n messageId: \"preferFunctypeMap\",\n data: { keyType, valueType },\n suggest: suggestions,\n })\n },\n }\n },\n}\n\nexport default rule\n"],"mappings":"8SAOA,MAAMA,EAAwB,CAC5B,KAAM,CACJ,KAAM,aACN,eAAgB,GAChB,KAAM,CACJ,YAAa,gFACb,YAAa,EACf,EACA,OAAQ,CACN,CACE,KAAM,SACN,WAAY,CACV,aAAc,CACZ,KAAM,UACN,QAAS,EACX,EACA,aAAc,CACZ,KAAM,UACN,QAAS,EACX,CACF,EACA,qBAAsB,EACxB,CACF,EACA,SAAU,CACR,kBAAmB,kEACnB,yBAA0B,mDAC1B,gBAAiB,2BACjB,aAAc,2BACd,eAAgB,wBAChB,iBAAkB,qCACpB,CACF,EAEA,OAAO,EAAS,CACd,IAAMC,EAAUC,EAAQ,QAAQ,IAAM,CAAC,EACjCC,EAAeF,EAAQ,eAAiB,GAGxCG,EAAeH,EAAQ,eAAiB,GAE9C,SAASI,GAAe,CACtB,IAAMC,EAAWJ,EAAQ,SACzB,MACE,kCAAkC,KAAKI,CAAQ,GAC/CA,EAAS,SAAS,WAAW,GAC7BA,EAAS,SAAS,QAAQ,GAC1BA,EAAS,SAAS,SAAS,CAE/B,CAEA,IAAMC,EAAkBC,EAAyBN,CAAO,EAExD,SAASO,GAAqC,CAC5C,OAAOC,EAAkBR,EAAQ,WAAY,KAAK,CACpD,CAEA,MAAO,CACL,cAAc,EAAe,CAY3B,GAXIC,GAAgBE,EAAa,GAG7B,CAACM,EAAK,QAAUA,EAAK,OAAO,OAAS,cAAgBA,EAAK,OAAO,OAAS,OAE1EP,GAAgBQ,EAAoBD,EAAME,EAAcX,EAAQ,UAAU,GAG1EO,EAA0B,GAG1BK,EAAuBH,EAAMJ,CAAe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Q,UAAU,GAG9EO,EAA0B,EAAG,OAGjC,IAAMe,EAAab,EAAK,eAAe,QAAUA,EAAK,gBAAgB,OAChEc,EAAUD,IAAa,GAAKT,EAAW,QAAQS,EAAW,EAAE,EAAI,IAChEE,EAAYF,GAAcA,EAAW,QAAU,EAAIT,EAAW,QAAQS,EAAW,EAAE,EAAI,IAEvFP,EAAiD,CACrD,CACE,UAAW,mBACX,KAAM,CAAE,OAAQ,KAAM,EACtB,IAAKK,EAAkBP,EAAY,KAAK,CAC1C,CACF,EAEAb,EAAQ,OAAO,CACb,OACA,UAAW,oBACX,KAAM,CAAE,UAAS,WAAU,EAC3B,QAASe,CACX,CAAC,CACH,CACF,CACF,CACF"}
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import{getFunctypeImportsLegacy as e,isAlreadyUsingFunctype as t}from"../utils/functype-detection.js";import{createImportFixer as n,hasFunctypeSymbol as r}from"../utils/import-fixer.js";const
|
|
1
|
+
import{getFunctypeImportsLegacy as e,isAlreadyUsingFunctype as t}from"../utils/functype-detection.js";import{createImportFixer as n,hasFunctypeSymbol as r}from"../utils/import-fixer.js";import{SET_MUTATORS as i,annotatesMutatedBinding as a,isMutatedCollection as o}from"../utils/mutable-collection.js";const s={meta:{type:`suggestion`,hasSuggestions:!0,docs:{description:`Prefer functype Set<T> over native Set for immutable collections`,recommended:!0},schema:[{type:`object`,properties:{allowInTests:{type:`boolean`,default:!0},allowMutable:{type:`boolean`,default:!0}},additionalProperties:!1}],messages:{preferFunctypeSet:`Prefer functype Set<{{type}}> over native Set`,preferFunctypeSetLiteral:`Prefer Set.of(...) or Set.empty() over new Set()`,suggestSetEmpty:`Replace with Set.empty()`,suggestSetOf:`Replace with Set.of(...)`,suggestSetFrom:`Replace with Set(...)`,suggestAddImport:`Add {{symbol}} import from functype`}},create(s){let c=s.options[0]||{},l=c.allowInTests!==!1,u=c.allowMutable!==!1;function d(){let e=s.filename;return/\.(test|spec)\.(ts|js|tsx|jsx)$/.test(e)||e.includes(`__tests__`)||e.includes(`/test/`)||e.includes(`/tests/`)}let f=e(s);function p(){return r(s.sourceCode,`Set`)}return{NewExpression(e){if(l&&d()||!e.callee||e.callee.type!==`Identifier`||e.callee.name!==`Set`||u&&o(e,i,s.sourceCode)||p()||t(e,f))return;let r=s.sourceCode,a=e.arguments||[],c=[];if(a.length===0)c.push({messageId:`suggestSetEmpty`,fix(t){return t.replaceText(e,`Set.empty()`)}});else if(a.length===1&&a[0].type===`ArrayExpression`){let t=(a[0].elements||[]).map(e=>r.getText(e)).join(`, `);c.push({messageId:`suggestSetOf`,fix(n){return n.replaceText(e,`Set.of(${t})`)}})}else if(a.length===1){let t=r.getText(a[0]);c.push({messageId:`suggestSetFrom`,fix(n){return n.replaceText(e,`Set(${t})`)}})}else c.push({messageId:`suggestSetEmpty`,fix(t){return t.replaceText(e,`Set.empty()`)}});p()||c.push({messageId:`suggestAddImport`,data:{symbol:`Set`},fix:n(r,`Set`)}),s.report({node:e,messageId:`preferFunctypeSetLiteral`,suggest:c})},TSTypeReference(e){if(l&&d()||!e.typeName)return;let t=s.sourceCode;if((e.typeName.type===`Identifier`?e.typeName.name:t.getText(e.typeName))!==`Set`||u&&a(e,i,s.sourceCode)||p())return;let r=e.typeParameters?.params?.[0]??e.typeArguments?.params?.[0],o=r?t.getText(r):`T`,c=[{messageId:`suggestAddImport`,data:{symbol:`Set`},fix:n(t,`Set`)}];s.report({node:e,messageId:`preferFunctypeSet`,data:{type:o},suggest:c})}}}};export{s as default};
|
|
2
2
|
//# sourceMappingURL=prefer-functype-set.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"prefer-functype-set.js","names":[],"sources":["../../src/rules/prefer-functype-set.ts"],"sourcesContent":["import type { Rule } from \"eslint\"\n\nimport type { ASTNode } from \"../types/ast\"\nimport { getFunctypeImportsLegacy, isAlreadyUsingFunctype } from \"../utils/functype-detection\"\nimport { createImportFixer, hasFunctypeSymbol } from \"../utils/import-fixer\"\n\nconst rule: Rule.RuleModule = {\n meta: {\n type: \"suggestion\",\n hasSuggestions: true,\n docs: {\n description: \"Prefer functype Set<T> over native Set for immutable collections\",\n recommended: true,\n },\n schema: [\n {\n type: \"object\",\n properties: {\n allowInTests: {\n type: \"boolean\",\n default: true,\n },\n },\n additionalProperties: false,\n },\n ],\n messages: {\n preferFunctypeSet: \"Prefer functype Set<{{type}}> over native Set\",\n preferFunctypeSetLiteral: \"Prefer Set.of(...) or Set.empty() over new Set()\",\n suggestSetEmpty: \"Replace with Set.empty()\",\n suggestSetOf: \"Replace with Set.of(...)\",\n suggestSetFrom: \"Replace with Set(...)\",\n suggestAddImport: \"Add {{symbol}} import from functype\",\n },\n },\n\n create(context) {\n const options = context.options[0] || {}\n const allowInTests = options.allowInTests !== false\n\n function isInTestFile() {\n const filename = context.filename\n return (\n /\\.(test|spec)\\.(ts|js|tsx|jsx)$/.test(filename) ||\n filename.includes(\"__tests__\") ||\n filename.includes(\"/test/\") ||\n filename.includes(\"/tests/\")\n )\n }\n\n const functypeImports = getFunctypeImportsLegacy(context)\n\n function isSetImportedFromFunctype() {\n return hasFunctypeSymbol(context.sourceCode, \"Set\")\n }\n\n return {\n NewExpression(node: ASTNode) {\n if (allowInTests && isInTestFile()) return\n\n // Only handle `new Set(...)` calls\n if (!node.callee || node.callee.type !== \"Identifier\" || node.callee.name !== \"Set\") return\n\n // Skip if Set is already imported from functype\n if (isSetImportedFromFunctype()) return\n\n // Skip if already in a functype context\n if (isAlreadyUsingFunctype(node, functypeImports)) return\n\n const sourceCode = context.sourceCode\n const args = node.arguments || []\n const suggestions: Rule.SuggestionReportDescriptor[] = []\n\n if (args.length === 0) {\n // new Set() → Set.empty()\n suggestions.push({\n messageId: \"suggestSetEmpty\",\n fix(fixer) {\n return fixer.replaceText(node, \"Set.empty()\")\n },\n })\n } else if (args.length === 1 && args[0].type === \"ArrayExpression\") {\n // new Set([\"a\", \"b\", \"c\"]) → Set.of(\"a\", \"b\", \"c\")\n const arrayNode = args[0]\n const elements = arrayNode.elements || []\n const elementTexts = elements.map((el: ASTNode) => sourceCode.getText(el))\n const argsText = elementTexts.join(\", \")\n suggestions.push({\n messageId: \"suggestSetOf\",\n fix(fixer) {\n return fixer.replaceText(node, `Set.of(${argsText})`)\n },\n })\n } else if (args.length === 1) {\n // new Set(someVar) → Set(someVar)\n const argText = sourceCode.getText(args[0])\n suggestions.push({\n messageId: \"suggestSetFrom\",\n fix(fixer) {\n return fixer.replaceText(node, `Set(${argText})`)\n },\n })\n } else {\n // Fallback for unexpected cases\n suggestions.push({\n messageId: \"suggestSetEmpty\",\n fix(fixer) {\n return fixer.replaceText(node, \"Set.empty()\")\n },\n })\n }\n\n if (!isSetImportedFromFunctype()) {\n suggestions.push({\n messageId: \"suggestAddImport\",\n data: { symbol: \"Set\" },\n fix: createImportFixer(sourceCode, \"Set\"),\n })\n }\n\n context.report({\n node,\n messageId: \"preferFunctypeSetLiteral\",\n suggest: suggestions,\n })\n },\n\n TSTypeReference(node: ASTNode) {\n if (allowInTests && isInTestFile()) return\n\n if (!node.typeName) return\n\n const sourceCode = context.sourceCode\n const typeName = node.typeName.type === \"Identifier\" ? node.typeName.name : sourceCode.getText(node.typeName)\n\n if (typeName !== \"Set\") return\n\n // Skip if Set is already imported from functype\n if (isSetImportedFromFunctype()) return\n\n // Extract type parameter if present (typeArguments for newer TS-ESLint, typeParameters for older)\n const typeParamNode = node.typeParameters?.params?.[0] ?? node.typeArguments?.params?.[0]\n const typeParam = typeParamNode ? sourceCode.getText(typeParamNode) : \"T\"\n\n const suggestions: Rule.SuggestionReportDescriptor[] = [\n {\n messageId: \"suggestAddImport\",\n data: { symbol: \"Set\" },\n fix: createImportFixer(sourceCode, \"Set\"),\n },\n ]\n\n context.report({\n node,\n messageId: \"preferFunctypeSet\",\n data: { type: typeParam },\n suggest: suggestions,\n })\n },\n }\n },\n}\n\nexport default rule\n"],"mappings":"
|
|
1
|
+
{"version":3,"file":"prefer-functype-set.js","names":["rule","options","context","allowInTests","allowMutable","isInTestFile","filename","functypeImports","getFunctypeImportsLegacy","isSetImportedFromFunctype","hasFunctypeSymbol","node","isMutatedCollection","SET_MUTATORS","isAlreadyUsingFunctype","sourceCode","args","suggestions","fixer","argsText","el","argText","createImportFixer","annotatesMutatedBinding","typeParamNode","typeParam"],"sources":["../../src/rules/prefer-functype-set.ts"],"sourcesContent":["import type { Rule } from \"eslint\"\n\nimport type { ASTNode } from \"../types/ast\"\nimport { getFunctypeImportsLegacy, isAlreadyUsingFunctype } from \"../utils/functype-detection\"\nimport { createImportFixer, hasFunctypeSymbol } from \"../utils/import-fixer\"\nimport { annotatesMutatedBinding, isMutatedCollection, SET_MUTATORS } from \"../utils/mutable-collection\"\n\nconst rule: Rule.RuleModule = {\n meta: {\n type: \"suggestion\",\n hasSuggestions: true,\n docs: {\n description: \"Prefer functype Set<T> over native Set for immutable collections\",\n recommended: true,\n },\n schema: [\n {\n type: \"object\",\n properties: {\n allowInTests: {\n type: \"boolean\",\n default: true,\n },\n allowMutable: {\n type: \"boolean\",\n default: true,\n },\n },\n additionalProperties: false,\n },\n ],\n messages: {\n preferFunctypeSet: \"Prefer functype Set<{{type}}> over native Set\",\n preferFunctypeSetLiteral: \"Prefer Set.of(...) or Set.empty() over new Set()\",\n suggestSetEmpty: \"Replace with Set.empty()\",\n suggestSetOf: \"Replace with Set.of(...)\",\n suggestSetFrom: \"Replace with Set(...)\",\n suggestAddImport: \"Add {{symbol}} import from functype\",\n },\n },\n\n create(context) {\n const options = context.options[0] || {}\n const allowInTests = options.allowInTests !== false\n // A native Set the code mutates on purpose (cache, registry, accumulator) is a deliberate choice —\n // functype's Set is immutable and cannot express it (#324).\n const allowMutable = options.allowMutable !== 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 const functypeImports = getFunctypeImportsLegacy(context)\n\n function isSetImportedFromFunctype() {\n return hasFunctypeSymbol(context.sourceCode, \"Set\")\n }\n\n return {\n NewExpression(node: ASTNode) {\n if (allowInTests && isInTestFile()) return\n\n // Only handle `new Set(...)` calls\n if (!node.callee || node.callee.type !== \"Identifier\" || node.callee.name !== \"Set\") return\n\n if (allowMutable && isMutatedCollection(node, SET_MUTATORS, context.sourceCode)) return\n\n // Skip if Set is already imported from functype\n if (isSetImportedFromFunctype()) return\n\n // Skip if already in a functype context\n if (isAlreadyUsingFunctype(node, functypeImports)) return\n\n const sourceCode = context.sourceCode\n const args = node.arguments || []\n const suggestions: Rule.SuggestionReportDescriptor[] = []\n\n if (args.length === 0) {\n // new Set() → Set.empty()\n suggestions.push({\n messageId: \"suggestSetEmpty\",\n fix(fixer) {\n return fixer.replaceText(node, \"Set.empty()\")\n },\n })\n } else if (args.length === 1 && args[0].type === \"ArrayExpression\") {\n // new Set([\"a\", \"b\", \"c\"]) → Set.of(\"a\", \"b\", \"c\")\n const arrayNode = args[0]\n const elements = arrayNode.elements || []\n const elementTexts = elements.map((el: ASTNode) => sourceCode.getText(el))\n const argsText = elementTexts.join(\", \")\n suggestions.push({\n messageId: \"suggestSetOf\",\n fix(fixer) {\n return fixer.replaceText(node, `Set.of(${argsText})`)\n },\n })\n } else if (args.length === 1) {\n // new Set(someVar) → Set(someVar)\n const argText = sourceCode.getText(args[0])\n suggestions.push({\n messageId: \"suggestSetFrom\",\n fix(fixer) {\n return fixer.replaceText(node, `Set(${argText})`)\n },\n })\n } else {\n // Fallback for unexpected cases\n suggestions.push({\n messageId: \"suggestSetEmpty\",\n fix(fixer) {\n return fixer.replaceText(node, \"Set.empty()\")\n },\n })\n }\n\n if (!isSetImportedFromFunctype()) {\n suggestions.push({\n messageId: \"suggestAddImport\",\n data: { symbol: \"Set\" },\n fix: createImportFixer(sourceCode, \"Set\"),\n })\n }\n\n context.report({\n node,\n messageId: \"preferFunctypeSetLiteral\",\n suggest: suggestions,\n })\n },\n\n TSTypeReference(node: ASTNode) {\n if (allowInTests && isInTestFile()) return\n\n if (!node.typeName) return\n\n const sourceCode = context.sourceCode\n const typeName = node.typeName.type === \"Identifier\" ? node.typeName.name : sourceCode.getText(node.typeName)\n\n if (typeName !== \"Set\") return\n\n if (allowMutable && annotatesMutatedBinding(node, SET_MUTATORS, context.sourceCode)) return\n\n // Skip if Set is already imported from functype\n if (isSetImportedFromFunctype()) return\n\n // Extract type parameter if present (typeArguments for newer TS-ESLint, typeParameters for older)\n const typeParamNode = node.typeParameters?.params?.[0] ?? node.typeArguments?.params?.[0]\n const typeParam = typeParamNode ? sourceCode.getText(typeParamNode) : \"T\"\n\n const suggestions: Rule.SuggestionReportDescriptor[] = [\n {\n messageId: \"suggestAddImport\",\n data: { symbol: \"Set\" },\n fix: createImportFixer(sourceCode, \"Set\"),\n },\n ]\n\n context.report({\n node,\n messageId: \"preferFunctypeSet\",\n data: { type: typeParam },\n suggest: suggestions,\n })\n },\n }\n },\n}\n\nexport default rule\n"],"mappings":"8SAOA,MAAMA,EAAwB,CAC5B,KAAM,CACJ,KAAM,aACN,eAAgB,GAChB,KAAM,CACJ,YAAa,mEACb,YAAa,EACf,EACA,OAAQ,CACN,CACE,KAAM,SACN,WAAY,CACV,aAAc,CACZ,KAAM,UACN,QAAS,EACX,EACA,aAAc,CACZ,KAAM,UACN,QAAS,EACX,CACF,EACA,qBAAsB,EACxB,CACF,EACA,SAAU,CACR,kBAAmB,gDACnB,yBAA0B,mDAC1B,gBAAiB,2BACjB,aAAc,2BACd,eAAgB,wBAChB,iBAAkB,qCACpB,CACF,EAEA,OAAO,EAAS,CACd,IAAMC,EAAUC,EAAQ,QAAQ,IAAM,CAAC,EACjCC,EAAeF,EAAQ,eAAiB,GAGxCG,EAAeH,EAAQ,eAAiB,GAE9C,SAASI,GAAe,CACtB,IAAMC,EAAWJ,EAAQ,SACzB,MACE,kCAAkC,KAAKI,CAAQ,GAC/CA,EAAS,SAAS,WAAW,GAC7BA,EAAS,SAAS,Q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,KAAK,CACf,UAAW,mBACX,KAAM,CAAE,OAAQ,KAAM,EACtB,IAAKK,EAAkBP,EAAY,KAAK,CAC1C,CAAC,EAGHb,EAAQ,OAAO,CACb,OACA,UAAW,2BACX,QAASe,CACX,CAAC,CACH,EAEA,gBAAgB,EAAe,CAG7B,GAFId,GAAgBE,EAAa,GAE7B,CAACM,EAAK,SAAU,OAEpB,IAAMI,EAAab,EAAQ,WAQ3B,IAPiBS,EAAK,SAAS,OAAS,aAAeA,EAAK,SAAS,KAAOI,EAAW,QAAQJ,EAAK,QAAQ,KAE3F,OAEbP,GAAgBmB,EAAwBZ,EAAME,EAAcX,EAAQ,UAAU,GAG9EO,EAA0B,EAAG,OAGjC,IAAMe,EAAgBb,EAAK,gBAAgB,SAAS,IAAMA,EAAK,eAAe,SAAS,GACjFc,EAAYD,EAAgBT,EAAW,QAAQS,CAAa,EAAI,IAEhEP,EAAiD,CACrD,CACE,UAAW,mBACX,KAAM,CAAE,OAAQ,KAAM,EACtB,IAAKK,EAAkBP,EAAY,KAAK,CAC1C,CACF,EAEAb,EAAQ,OAAO,CACb,OACA,UAAW,oBACX,KAAM,CAAE,KAAMuB,CAAU,EACxB,QAASR,CACX,CAAC,CACH,CACF,CACF,CACF"}
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import{getFunctypeImportsLegacy as e,isFunctypeCall as t}from"../utils/functype-detection.js";import{createImportFixer as n,hasFunctypeSymbol as r}from"../utils/import-fixer.js";const
|
|
1
|
+
import{getFunctypeImportsLegacy as e,isFunctypeCall as t}from"../utils/functype-detection.js";import{createImportFixer as n,hasFunctypeSymbol as r}from"../utils/import-fixer.js";import{DEFAULT_WIRE_TYPES as i,WIRE_TYPES_SCHEMA as a,isInsideWireType as o}from"../utils/wire-types.js";const s=/* @__PURE__ */ new Set([`parent`,`loc`,`range`]);function c(e){return Object.entries(e).filter(([e])=>!s.has(e)).flatMap(([,e])=>Array.isArray(e)?e:[e]).filter(e=>typeof e==`object`&&!!e)}function l(e,t){let n=e?.parent;return n?t(n)||l(n,t):!1}function u(e){return e?.type===`CallExpression`&&e.callee.type===`MemberExpression`&&e.callee.object.type===`Identifier`&&e.callee.object.name===`List`&&[`from`,`of`].includes(e.callee.property.name)}function d(e){return e.type===`VariableDeclarator`&&!!e.id?.typeAnnotation||e.type===`TSTypeAnnotation`}const f={meta:{type:`suggestion`,hasSuggestions:!0,docs:{description:`Prefer List<T> over native arrays for immutable collections`,recommended:!0},schema:[{type:`object`,properties:{allowArraysInTests:{type:`boolean`,default:!0},wireTypes:a,allowReadonlyArrays:{type:`boolean`,default:!0},allowArrayLiterals:{type:`boolean`,default:!1}},additionalProperties:!1}],messages:{preferList:`Prefer List<{{type}}> over array type {{arrayType}}`,preferListLiteral:`Prefer List.of(...) or List.from([...]) over array literal`,suggestListType:`Replace with List<{{type}}>`,suggestListOf:`Replace with List.of(...)`,suggestAddImport:`Add {{symbol}} import from functype`}},create(a){let s=a.options[0]||{},f=s.wireTypes??i,p=s.allowArraysInTests!==!1,m=s.allowReadonlyArrays!==!1,h=s.allowArrayLiterals===!0,g=e(a);function _(){let e=a.filename;return/\.(test|spec)\.(ts|js|tsx|jsx)$/.test(e)||e.includes(`__tests__`)||e.includes(`/test/`)||e.includes(`/tests/`)}function v(e,t){function n(e){return e.type===`TSTypeParameterInstantiation`&&e.params&&e.params[0]?t.getText(e.params[0]):c(e).filter(e=>typeof e?.type==`string`).map(e=>n(e)).find(e=>e!==null)??null}return n(e)}return{TSArrayType(e){if(o(e,f)||p&&_())return;let t=e.parent,i=t?.type===`TSTypeOperator`&&t.operator===`readonly`;if(i&&m)return;let s=a.sourceCode,c=s.getText(e.elementType),l=i?t:e,u=s.getText(l),d=[{messageId:`suggestListType`,data:{type:c},fix(e){return e.replaceText(l,`List<${c}>`)}}];r(s,`List`)||d.push({messageId:`suggestAddImport`,data:{symbol:`List`},fix:n(s,`List`)}),a.report({node:l,messageId:`preferList`,data:{type:c,arrayType:u},suggest:d})},TSTypeReference(e){if(o(e,f)||p&&_())return;let t=a.sourceCode;if(!e.typeName)return;let i=e.typeName.type===`Identifier`?e.typeName.name:t.getText(e.typeName);if(i===`Array`){let i=v(e,t),o=t.getText(e),s=i||`T`,c=[{messageId:`suggestListType`,data:{type:s},fix(t){return t.replaceText(e,`List<${s}>`)}}];r(t,`List`)||c.push({messageId:`suggestAddImport`,data:{symbol:`List`},fix:n(t,`List`)}),a.report({node:e,messageId:`preferList`,data:{type:s,arrayType:o},suggest:c})}if(i===`ReadonlyArray`){if(m)return;let i=v(e,t),o=t.getText(e),s=i||`T`,c=[{messageId:`suggestListType`,data:{type:s},fix(t){return t.replaceText(e,`List<${s}>`)}}];r(t,`List`)||c.push({messageId:`suggestAddImport`,data:{symbol:`List`},fix:n(t,`List`)}),a.report({node:e,messageId:`preferList`,data:{type:s,arrayType:o},suggest:c})}},ArrayExpression(e){if(p&&_()||h||e.elements.length===0)return;let i=e.parent;if(i&&t(i,g)||u(i)||l(e,e=>e.type===`ArrayExpression`)||l(e,d))return;if(e.elements.some(e=>e!==null&&e.type===`SpreadElement`)){a.report({node:e,messageId:`preferListLiteral`});return}let o=a.sourceCode,s=e.elements.filter(e=>e!==null).map(e=>o.getText(e)),c=[{messageId:`suggestListOf`,fix(t){return t.replaceText(e,`List.of(${s.join(`, `)})`)}}];r(o,`List`)||c.push({messageId:`suggestAddImport`,data:{symbol:`List`},fix:n(o,`List`)}),a.report({node:e,messageId:`preferListLiteral`,suggest:c})}}}};export{f as default};
|
|
2
2
|
//# sourceMappingURL=prefer-list.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"prefer-list.js","names":[],"sources":["../../src/rules/prefer-list.ts"],"sourcesContent":["import type { Rule } from \"eslint\"\n\nimport type { ASTNode } from \"../types/ast\"\nimport { getFunctypeImportsLegacy, isFunctypeCall } from \"../utils/functype-detection\"\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` 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/** `parent` is `List.from(arr)` or `List.of(...arr)`. */\nfunction isListFactoryArg(parent: ASTNode | null | undefined): boolean {\n return (\n parent?.type === \"CallExpression\" &&\n parent.callee.type === \"MemberExpression\" &&\n parent.callee.object.type === \"Identifier\" &&\n parent.callee.object.name === \"List\" &&\n [\"from\", \"of\"].includes(parent.callee.property.name)\n )\n}\n\n/** `node` is a VariableDeclarator with its own type annotation, or a TSTypeAnnotation node directly. */\nfunction hasOwnTypeAnnotation(node: ASTNode): boolean {\n return (node.type === \"VariableDeclarator\" && Boolean(node.id?.typeAnnotation)) || node.type === \"TSTypeAnnotation\"\n}\n\nconst rule: Rule.RuleModule = {\n meta: {\n type: \"suggestion\",\n hasSuggestions: true,\n docs: {\n description: \"Prefer List<T> over native arrays for immutable collections\",\n recommended: true,\n },\n schema: [\n {\n type: \"object\",\n properties: {\n allowArraysInTests: {\n type: \"boolean\",\n default: true,\n },\n allowReadonlyArrays: {\n type: \"boolean\",\n default: true,\n },\n allowArrayLiterals: {\n type: \"boolean\",\n default: false,\n },\n },\n additionalProperties: false,\n },\n ],\n messages: {\n preferList: \"Prefer List<{{type}}> over array type {{arrayType}}\",\n preferListLiteral: \"Prefer List.of(...) or List.from([...]) over array literal\",\n suggestListType: \"Replace with List<{{type}}>\",\n suggestListOf: \"Replace with List.of(...)\",\n suggestAddImport: \"Add {{symbol}} import from functype\",\n },\n },\n\n create(context) {\n const options = context.options[0] || {}\n const allowArraysInTests = options.allowArraysInTests !== false\n const allowReadonlyArrays = options.allowReadonlyArrays !== false\n const allowArrayLiterals = options.allowArrayLiterals === true\n\n // Get functype imports if available (but still apply rule even without explicit import)\n const functypeImports = getFunctypeImportsLegacy(context)\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 findTypeParameter(node: ASTNode, sourceCode: typeof context.sourceCode): string | null {\n // Pure pre-order search: look at this node, then recursively at each\n // child until we find a TSTypeParameterInstantiation with a first param.\n function findInNode(n: ASTNode): string | null {\n if (n.type === \"TSTypeParameterInstantiation\" && n.params && n.params[0]) {\n return sourceCode.getText(n.params[0])\n }\n const results = astChildren(n)\n .filter((c): c is ASTNode => typeof (c as ASTNode)?.type === \"string\")\n .map((child) => findInNode(child))\n return results.find((r) => r !== null) ?? null\n }\n return findInNode(node)\n }\n\n return {\n TSArrayType(node: ASTNode) {\n if (allowArraysInTests && isInTestFile()) return\n\n // `readonly T[]` parses as TSTypeOperator(operator: \"readonly\") wrapping TSArrayType.\n // When the parent is that readonly wrapper, we treat the whole `readonly T[]` as\n // the reported unit — both for gating (parity with the ReadonlyArray<T> branch\n // below) and for the suggestion's replacement range. Replacing only the inner\n // TSArrayType would leave `readonly List<T>` behind, which is invalid TS\n // (TS1354: `readonly` only applies to array/tuple types).\n const parent = node.parent as ASTNode | undefined\n const isReadonly =\n parent?.type === \"TSTypeOperator\" && (parent as { operator?: string }).operator === \"readonly\"\n\n if (isReadonly && allowReadonlyArrays) return\n\n const sourceCode = context.sourceCode\n const elementType = sourceCode.getText(node.elementType)\n const reportNode = isReadonly ? (parent as ASTNode) : node\n const fullType = sourceCode.getText(reportNode)\n\n const suggest: Rule.SuggestionReportDescriptor[] = [\n {\n messageId: \"suggestListType\",\n data: { type: elementType },\n fix(fixer: Rule.RuleFixer) {\n return fixer.replaceText(reportNode, `List<${elementType}>`)\n },\n },\n ]\n\n if (!hasFunctypeSymbol(sourceCode, \"List\")) {\n suggest.push({\n messageId: \"suggestAddImport\",\n data: { symbol: \"List\" },\n fix: createImportFixer(sourceCode, \"List\"),\n })\n }\n\n context.report({\n node: reportNode,\n messageId: \"preferList\",\n data: {\n type: elementType,\n arrayType: fullType,\n },\n suggest,\n })\n },\n\n TSTypeReference(node: ASTNode) {\n if (allowArraysInTests && isInTestFile()) return\n\n const sourceCode = context.sourceCode\n\n // Get type name - handle both simple identifiers and member expressions\n if (!node.typeName) return // No type name found\n\n const typeName = node.typeName.type === \"Identifier\" ? node.typeName.name : sourceCode.getText(node.typeName)\n\n // Handle Array<T> syntax\n if (typeName === \"Array\") {\n // Look for type parameters in child nodes\n const typeParam = findTypeParameter(node, sourceCode)\n const fullType = sourceCode.getText(node)\n\n const resolvedType = typeParam || \"T\"\n\n const suggest: Rule.SuggestionReportDescriptor[] = [\n {\n messageId: \"suggestListType\",\n data: { type: resolvedType },\n fix(fixer: Rule.RuleFixer) {\n return fixer.replaceText(node, `List<${resolvedType}>`)\n },\n },\n ]\n\n if (!hasFunctypeSymbol(sourceCode, \"List\")) {\n suggest.push({\n messageId: \"suggestAddImport\",\n data: { symbol: \"List\" },\n fix: createImportFixer(sourceCode, \"List\"),\n })\n }\n\n context.report({\n node,\n messageId: \"preferList\",\n data: {\n type: resolvedType,\n arrayType: fullType,\n },\n suggest,\n })\n }\n\n // Handle ReadonlyArray<T> — gated on allowReadonlyArrays (parity with `readonly T[]`).\n if (typeName === \"ReadonlyArray\") {\n if (allowReadonlyArrays) return\n\n const typeParam = findTypeParameter(node, sourceCode)\n const fullType = sourceCode.getText(node)\n const resolvedType = typeParam || \"T\"\n\n const suggest: Rule.SuggestionReportDescriptor[] = [\n {\n messageId: \"suggestListType\",\n data: { type: resolvedType },\n fix(fixer: Rule.RuleFixer) {\n return fixer.replaceText(node, `List<${resolvedType}>`)\n },\n },\n ]\n\n if (!hasFunctypeSymbol(sourceCode, \"List\")) {\n suggest.push({\n messageId: \"suggestAddImport\",\n data: { symbol: \"List\" },\n fix: createImportFixer(sourceCode, \"List\"),\n })\n }\n\n context.report({\n node,\n messageId: \"preferList\",\n data: {\n type: resolvedType,\n arrayType: fullType,\n },\n suggest,\n })\n }\n },\n\n ArrayExpression(node: ASTNode) {\n if (allowArraysInTests && isInTestFile()) return\n if (allowArrayLiterals) return\n\n // Only flag non-empty arrays to avoid noise\n if (node.elements.length === 0) return\n\n const parent = node.parent\n\n // Don't flag arrays that are already arguments to functype calls.\n if (parent && isFunctypeCall(parent, functypeImports)) return\n\n // Don't flag arrays that are arguments to List.from / List.of.\n if (isListFactoryArg(parent)) return\n\n // Don't flag nested array literals — let the outermost one handle it.\n if (ancestorSatisfies(node, (n) => n.type === \"ArrayExpression\")) return\n\n // Don't flag array literals that already live in a type-annotated\n // context (those are handled by the type-checking rules).\n if (ancestorSatisfies(node, hasOwnTypeAnnotation)) return\n\n // Check if any element is a SpreadElement — ambiguous semantics, skip suggestions\n const hasSpread = node.elements.some((el) => el !== null && el.type === \"SpreadElement\")\n\n if (hasSpread) {\n context.report({\n node,\n messageId: \"preferListLiteral\",\n })\n return\n }\n\n const sourceCode = context.sourceCode\n const elementTexts = node.elements.filter((el) => el !== null).map((el) => sourceCode.getText(el))\n\n const suggest: Rule.SuggestionReportDescriptor[] = [\n {\n messageId: \"suggestListOf\",\n fix(fixer: Rule.RuleFixer) {\n return fixer.replaceText(node, `List.of(${elementTexts.join(\", \")})`)\n },\n },\n ]\n\n if (!hasFunctypeSymbol(sourceCode, \"List\")) {\n suggest.push({\n messageId: \"suggestAddImport\",\n data: { symbol: \"List\" },\n fix: createImportFixer(sourceCode, \"List\"),\n })\n }\n\n context.report({\n node,\n messageId: \"preferListLiteral\",\n suggest,\n })\n },\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ACF,CAAC,CACH,CACF,EAEA,gBAAgB,EAAe,CAK7B,GAJI,GAAsB,EAAa,GACnC,GAGA,EAAK,SAAS,SAAW,EAAG,OAEhC,IAAM,EAAS,EAAK,OAapB,GAVI,GAAU,EAAe,EAAQ,CAAe,GAGhD,EAAiB,CAAM,GAGvB,EAAkB,EAAO,GAAM,EAAE,OAAS,iBAAiB,GAI3D,EAAkB,EAAM,CAAoB,EAAG,OAKnD,GAFkB,EAAK,SAAS,KAAM,GAAO,IAAO,MAAQ,EAAG,OAAS,eAE5D,EAAG,CACb,EAAQ,OAAO,CACb,OACA,UAAW,mBACb,CAAC,EACD,MACF,CAEA,IAAM,EAAa,EAAQ,WACrB,EAAe,EAAK,SAAS,OAAQ,GAAO,IAAO,IAAI,CAAC,CAAC,IAAK,GAAO,EAAW,QAAQ,CAAE,CAAC,EAE3F,EAA6C,CACjD,CACE,UAAW,gBACX,IAAI,EAAuB,CACzB,OAAO,EAAM,YAAY,EAAM,WAAW,EAAa,KAAK,IAAI,EAAE,EAAE,CACtE,CACF,CACF,EAEK,EAAkB,EAAY,MAAM,GACvC,EAAQ,KAAK,CACX,UAAW,mBACX,KAAM,CAAE,OAAQ,MAAO,EACvB,IAAK,EAAkB,EAAY,MAAM,CAC3C,CAAC,EAGH,EAAQ,OAAO,CACb,OACA,UAAW,oBACX,SACF,CAAC,CACH,CACF,CACF,CACF"}
|
|
1
|
+
{"version":3,"file":"prefer-list.js","names":["NON_CHILD_KEYS","astChildren","node","k","v","ancestorSatisfies","parent","pred","isListFactoryArg","hasOwnTypeAnnotation","rule","WIRE_TYPES_SCHEMA","options","context","wireTypes","DEFAULT_WIRE_TYPES","allowArraysInTests","allowReadonlyArrays","allowArrayLiterals","functypeImports","getFunctypeImportsLegacy","isInTestFile","filename","findTypeParameter","findInNode","n","sourceCode","c","child","r","isInsideWireType","isReadonly","elementType","reportNode","fullType","suggest","fixer","hasFunctypeSymbol","createImportFixer","typeName","typeParam","resolvedType","isFunctypeCall","el","elementTexts"],"sources":["../../src/rules/prefer-list.ts"],"sourcesContent":["import type { Rule } from \"eslint\"\n\nimport type { ASTNode } from \"../types/ast\"\nimport { getFunctypeImportsLegacy, isFunctypeCall } from \"../utils/functype-detection\"\nimport { createImportFixer, hasFunctypeSymbol } from \"../utils/import-fixer\"\nimport { DEFAULT_WIRE_TYPES, isInsideWireType, WIRE_TYPES_SCHEMA } from \"../utils/wire-types\"\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` 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/** `parent` is `List.from(arr)` or `List.of(...arr)`. */\nfunction isListFactoryArg(parent: ASTNode | null | undefined): boolean {\n return (\n parent?.type === \"CallExpression\" &&\n parent.callee.type === \"MemberExpression\" &&\n parent.callee.object.type === \"Identifier\" &&\n parent.callee.object.name === \"List\" &&\n [\"from\", \"of\"].includes(parent.callee.property.name)\n )\n}\n\n/** `node` is a VariableDeclarator with its own type annotation, or a TSTypeAnnotation node directly. */\nfunction hasOwnTypeAnnotation(node: ASTNode): boolean {\n return (node.type === \"VariableDeclarator\" && Boolean(node.id?.typeAnnotation)) || node.type === \"TSTypeAnnotation\"\n}\n\nconst rule: Rule.RuleModule = {\n meta: {\n type: \"suggestion\",\n hasSuggestions: true,\n docs: {\n description: \"Prefer List<T> over native arrays for immutable collections\",\n recommended: true,\n },\n schema: [\n {\n type: \"object\",\n properties: {\n allowArraysInTests: {\n type: \"boolean\",\n default: true,\n },\n wireTypes: WIRE_TYPES_SCHEMA,\n allowReadonlyArrays: {\n type: \"boolean\",\n default: true,\n },\n allowArrayLiterals: {\n type: \"boolean\",\n default: false,\n },\n },\n additionalProperties: false,\n },\n ],\n messages: {\n preferList: \"Prefer List<{{type}}> over array type {{arrayType}}\",\n preferListLiteral: \"Prefer List.of(...) or List.from([...]) over array literal\",\n suggestListType: \"Replace with List<{{type}}>\",\n suggestListOf: \"Replace with List.of(...)\",\n suggestAddImport: \"Add {{symbol}} import from functype\",\n },\n },\n\n create(context) {\n const options = context.options[0] || {}\n // Everything inside `Wire<…>` is the declared serialization shape (#325 B).\n const wireTypes: ReadonlyArray<string> = options.wireTypes ?? DEFAULT_WIRE_TYPES\n const allowArraysInTests = options.allowArraysInTests !== false\n const allowReadonlyArrays = options.allowReadonlyArrays !== false\n const allowArrayLiterals = options.allowArrayLiterals === true\n\n // Get functype imports if available (but still apply rule even without explicit import)\n const functypeImports = getFunctypeImportsLegacy(context)\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 findTypeParameter(node: ASTNode, sourceCode: typeof context.sourceCode): string | null {\n // Pure pre-order search: look at this node, then recursively at each\n // child until we find a TSTypeParameterInstantiation with a first param.\n function findInNode(n: ASTNode): string | null {\n if (n.type === \"TSTypeParameterInstantiation\" && n.params && n.params[0]) {\n return sourceCode.getText(n.params[0])\n }\n const results = astChildren(n)\n .filter((c): c is ASTNode => typeof (c as ASTNode)?.type === \"string\")\n .map((child) => findInNode(child))\n return results.find((r) => r !== null) ?? null\n }\n return findInNode(node)\n }\n\n return {\n TSArrayType(node: ASTNode) {\n if (isInsideWireType(node, wireTypes)) return\n if (allowArraysInTests && isInTestFile()) return\n\n // `readonly T[]` parses as TSTypeOperator(operator: \"readonly\") wrapping TSArrayType.\n // When the parent is that readonly wrapper, we treat the whole `readonly T[]` as\n // the reported unit — both for gating (parity with the ReadonlyArray<T> branch\n // below) and for the suggestion's replacement range. Replacing only the inner\n // TSArrayType would leave `readonly List<T>` behind, which is invalid TS\n // (TS1354: `readonly` only applies to array/tuple types).\n const parent = node.parent as ASTNode | undefined\n const isReadonly =\n parent?.type === \"TSTypeOperator\" && (parent as { operator?: string }).operator === \"readonly\"\n\n if (isReadonly && allowReadonlyArrays) return\n\n const sourceCode = context.sourceCode\n const elementType = sourceCode.getText(node.elementType)\n const reportNode = isReadonly ? (parent as ASTNode) : node\n const fullType = sourceCode.getText(reportNode)\n\n const suggest: Rule.SuggestionReportDescriptor[] = [\n {\n messageId: \"suggestListType\",\n data: { type: elementType },\n fix(fixer: Rule.RuleFixer) {\n return fixer.replaceText(reportNode, `List<${elementType}>`)\n },\n },\n ]\n\n if (!hasFunctypeSymbol(sourceCode, \"List\")) {\n suggest.push({\n messageId: \"suggestAddImport\",\n data: { symbol: \"List\" },\n fix: createImportFixer(sourceCode, \"List\"),\n })\n }\n\n context.report({\n node: reportNode,\n messageId: \"preferList\",\n data: {\n type: elementType,\n arrayType: fullType,\n },\n suggest,\n })\n },\n\n TSTypeReference(node: ASTNode) {\n if (isInsideWireType(node, wireTypes)) return\n if (allowArraysInTests && isInTestFile()) return\n\n const sourceCode = context.sourceCode\n\n // Get type name - handle both simple identifiers and member expressions\n if (!node.typeName) return // No type name found\n\n const typeName = node.typeName.type === \"Identifier\" ? node.typeName.name : sourceCode.getText(node.typeName)\n\n // Handle Array<T> syntax\n if (typeName === \"Array\") {\n // Look for type parameters in child nodes\n const typeParam = findTypeParameter(node, sourceCode)\n const fullType = sourceCode.getText(node)\n\n const resolvedType = typeParam || \"T\"\n\n const suggest: Rule.SuggestionReportDescriptor[] = [\n {\n messageId: \"suggestListType\",\n data: { type: resolvedType },\n fix(fixer: Rule.RuleFixer) {\n return fixer.replaceText(node, `List<${resolvedType}>`)\n },\n },\n ]\n\n if (!hasFunctypeSymbol(sourceCode, \"List\")) {\n suggest.push({\n messageId: \"suggestAddImport\",\n data: { symbol: \"List\" },\n fix: createImportFixer(sourceCode, \"List\"),\n })\n }\n\n context.report({\n node,\n messageId: \"preferList\",\n data: {\n type: resolvedType,\n arrayType: fullType,\n },\n suggest,\n })\n }\n\n // Handle ReadonlyArray<T> — gated on allowReadonlyArrays (parity with `readonly T[]`).\n if (typeName === \"ReadonlyArray\") {\n if (allowReadonlyArrays) return\n\n const typeParam = findTypeParameter(node, sourceCode)\n const fullType = sourceCode.getText(node)\n const resolvedType = typeParam || \"T\"\n\n const suggest: Rule.SuggestionReportDescriptor[] = [\n {\n messageId: \"suggestListType\",\n data: { type: resolvedType },\n fix(fixer: Rule.RuleFixer) {\n return fixer.replaceText(node, `List<${resolvedType}>`)\n },\n },\n ]\n\n if (!hasFunctypeSymbol(sourceCode, \"List\")) {\n suggest.push({\n messageId: \"suggestAddImport\",\n data: { symbol: \"List\" },\n fix: createImportFixer(sourceCode, \"List\"),\n })\n }\n\n context.report({\n node,\n messageId: \"preferList\",\n data: {\n type: resolvedType,\n arrayType: fullType,\n },\n suggest,\n })\n }\n },\n\n ArrayExpression(node: ASTNode) {\n if (allowArraysInTests && isInTestFile()) return\n if (allowArrayLiterals) return\n\n // Only flag non-empty arrays to avoid noise\n if (node.elements.length === 0) return\n\n const parent = node.parent\n\n // Don't flag arrays that are already arguments to functype calls.\n if (parent && isFunctypeCall(parent, functypeImports)) return\n\n // Don't flag arrays that are arguments to List.from / List.of.\n if (isListFactoryArg(parent)) return\n\n // Don't flag nested array literals — let the outermost one handle it.\n if (ancestorSatisfies(node, (n) => n.type === \"ArrayExpression\")) return\n\n // Don't flag array literals that already live in a type-annotated\n // context (those are handled by the type-checking rules).\n if (ancestorSatisfies(node, hasOwnTypeAnnotation)) return\n\n // Check if any element is a SpreadElement — ambiguous semantics, skip suggestions\n const hasSpread = node.elements.some((el) => el !== null && el.type === \"SpreadElement\")\n\n if (hasSpread) {\n context.report({\n node,\n messageId: \"preferListLiteral\",\n })\n return\n }\n\n const sourceCode = context.sourceCode\n const elementTexts = node.elements.filter((el) => el !== null).map((el) => sourceCode.getText(el))\n\n const suggest: Rule.SuggestionReportDescriptor[] = [\n {\n messageId: \"suggestListOf\",\n fix(fixer: Rule.RuleFixer) {\n return fixer.replaceText(node, `List.of(${elementTexts.join(\", \")})`)\n },\n },\n ]\n\n if (!hasFunctypeSymbol(sourceCode, \"List\")) {\n suggest.push({\n messageId: \"suggestAddImport\",\n data: { symbol: \"List\" },\n fix: createImportFixer(sourceCode, \"List\"),\n })\n }\n\n context.report({\n node,\n messageId: \"preferListLiteral\",\n suggest,\n })\n },\n }\n },\n}\n\nexport default rule\n"],"mappings":"2RAQA,MAAMA,kBAAsC,IAAI,IAAI,CAAC,SAAU,MAAO,OAAO,CAAC,EAG9E,SAASC,EAAY,EAAmC,CACtD,OAAO,OAAO,QAAQC,CAAI,CAAC,CACxB,QAAQ,CAACC,KAAO,CAACH,EAAe,IAAIG,CAAC,CAAC,CAAC,CACvC,SAAS,EAAGC,KAAQ,MAAM,QAAQA,CAAC,EAAIA,EAAI,CAACA,CAAC,CAAE,CAAC,CAChD,OAAQ,GAAoB,OAAOA,GAAM,YAA3BA,CAAmC,CACtD,CAGA,SAASC,EAAkB,EAAkC,EAAwC,CACnG,IAAMC,EAASJ,GAAM,OAErB,OADKI,EACEC,EAAKD,CAAM,GAAKD,EAAkBC,EAAQC,CAAI,EADjC,EAEtB,CAGA,SAASC,EAAiB,EAA6C,CACrE,OACEF,GAAQ,OAAS,kBACjBA,EAAO,OAAO,OAAS,oBACvBA,EAAO,OAAO,OAAO,OAAS,cAC9BA,EAAO,OAAO,OAAO,OAAS,QAC9B,CAAC,OAAQ,IAAI,CAAC,CAAC,SAASA,EAAO,OAAO,SAAS,IAAI,CAEvD,CAGA,SAASG,EAAqB,EAAwB,CACpD,OAAQP,EAAK,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