eslint-plugin-functype 2.200.0 → 2.202.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (64) hide show
  1. package/README.md +64 -2
  2. package/dist/cli/list-rules.js.map +1 -1
  3. package/dist/configs/recommended.d.ts +9 -1
  4. package/dist/configs/recommended.js +1 -1
  5. package/dist/configs/recommended.js.map +1 -1
  6. package/dist/index.d.ts +2 -0
  7. package/dist/index.js +1 -1
  8. package/dist/index.js.map +1 -1
  9. package/dist/rules/collection-naming.js.map +1 -1
  10. package/dist/rules/index.d.ts +22 -18
  11. package/dist/rules/index.js +1 -1
  12. package/dist/rules/index.js.map +1 -1
  13. package/dist/rules/must-fold-on-component-return.js.map +1 -1
  14. package/dist/rules/no-array-mutation.js.map +1 -1
  15. package/dist/rules/no-container-mutation.d.ts +21 -0
  16. package/dist/rules/no-container-mutation.js +2 -0
  17. package/dist/rules/no-container-mutation.js.map +1 -0
  18. package/dist/rules/no-floating-io.js.map +1 -1
  19. package/dist/rules/no-floating-result.js.map +1 -1
  20. package/dist/rules/no-get-unsafe.js.map +1 -1
  21. package/dist/rules/no-getOrThrow-in-render.js.map +1 -1
  22. package/dist/rules/no-imperative-loops.js.map +1 -1
  23. package/dist/rules/no-let.js.map +1 -1
  24. package/dist/rules/no-serialize-container.js.map +1 -1
  25. package/dist/rules/no-uncalled-method.d.ts +16 -0
  26. package/dist/rules/no-uncalled-method.js +2 -0
  27. package/dist/rules/no-uncalled-method.js.map +1 -0
  28. package/dist/rules/prefer-do-notation.js +1 -1
  29. package/dist/rules/prefer-do-notation.js.map +1 -1
  30. package/dist/rules/prefer-either.js.map +1 -1
  31. package/dist/rules/prefer-flatmap.js.map +1 -1
  32. package/dist/rules/prefer-fold.js +1 -1
  33. package/dist/rules/prefer-fold.js.map +1 -1
  34. package/dist/rules/prefer-functype-map.js.map +1 -1
  35. package/dist/rules/prefer-functype-set.js.map +1 -1
  36. package/dist/rules/prefer-list.js.map +1 -1
  37. package/dist/rules/prefer-map.js.map +1 -1
  38. package/dist/rules/prefer-option.js.map +1 -1
  39. package/dist/rules/prefer-try.js.map +1 -1
  40. package/dist/utils/array-mutation.d.ts +1 -1
  41. package/dist/utils/array-mutation.js.map +1 -1
  42. package/dist/utils/ast-walk.js.map +1 -1
  43. package/dist/utils/async-detection.js.map +1 -1
  44. package/dist/utils/boundary-tags.d.ts +1 -1
  45. package/dist/utils/boundary-tags.js.map +1 -1
  46. package/dist/utils/collection-binding.d.ts +1 -1
  47. package/dist/utils/collection-binding.js.map +1 -1
  48. package/dist/utils/dependency-validator.js.map +1 -1
  49. package/dist/utils/functype-detection.d.ts +1 -1
  50. package/dist/utils/functype-detection.js.map +1 -1
  51. package/dist/utils/functype-predicates.d.ts +1 -1
  52. package/dist/utils/functype-predicates.js.map +1 -1
  53. package/dist/utils/host-throws.d.ts +1 -1
  54. package/dist/utils/host-throws.js.map +1 -1
  55. package/dist/utils/import-fixer.js.map +1 -1
  56. package/dist/utils/mutable-collection.d.ts +1 -1
  57. package/dist/utils/mutable-collection.js.map +1 -1
  58. package/dist/utils/react-render.js.map +1 -1
  59. package/dist/utils/readonly-contract.js.map +1 -1
  60. package/dist/utils/type-aware.d.ts +22 -1
  61. package/dist/utils/type-aware.js +1 -1
  62. package/dist/utils/type-aware.js.map +1 -1
  63. package/dist/utils/wire-types.js.map +1 -1
  64. package/package.json +3 -3
@@ -1,2 +1,2 @@
1
- import{childNodes as e,descendants as t}from"../utils/ast-walk.js";import{containsAwait as n,containsYield as r}from"../utils/async-detection.js";import{isInsideTaggedDeclaration as i}from"../utils/boundary-tags.js";import{NEGATIVE_PREDICATES as a,POSITIVE_PREDICATES as o,compact as s}from"../utils/functype-predicates.js";const c={isSome:null,isNone:null,isRight:{param:`left`,member:`value`},isLeft:{param:`left`,member:`value`},isSuccess:{param:`error`,member:`error`},isFailure:{param:`error`,member:`error`}},l=[`get`,`orThrow`],u=`value`;function d(e){return e.type===`Literal`&&e.value===null||e.type===`Identifier`&&e.name===`undefined`}function f(e,t){if(e.type!==`CallExpression`||e.callee.type!==`MemberExpression`)return null;let n=e.callee.property.name,r=t.getText(e.callee.object),i=c[n]??null;return o.has(n)?{obj:r,isNegated:!1,failure:i}:a.has(n)?{obj:r,isNegated:!0,failure:i}:null}const p={members:[u],methods:l};function m(t,n,r,i){let a=e=>{let t=e.type===`TSNonNullExpression`?e.expression:e;return s(i.getText(t))===s(n)},o=(e,t)=>e.type===`MemberExpression`&&!e.computed&&e.property.type===`Identifier`&&t.includes(e.property.name)&&a(e.object),c=t=>{let n=t.parent,i=n?.type===`CallExpression`&&n.callee===t,a=n?.type===`AssignmentExpression`&&n.left===t||n?.type===`UpdateExpression`;return o(t,r.members)&&!i&&!a||t.type===`CallExpression`&&t.arguments.length===0&&o(t.callee,r.methods)?[t.range]:e(t).flatMap(c)};return c(t)}const h=(e,t)=>{let n=e=>t.some(t=>RegExp(`(?<![\\w$.])${e}(?![\\w$])`).test(t));return[e,...Array.from({length:20},(t,n)=>`${e}${n+1}`)].find(e=>!n(e))??`${e}_`},g=(e,t)=>e.type===`ObjectExpression`||e.type===`SequenceExpression`?`(${t})`:t;function _(e,t,n,r,i){let a=i.getText(e),o=n===null?[]:m(e,t,n,i);if(o.length===0)return`() => ${g(e,a)}`;let s=e.range[0],c=[...o].sort((e,t)=>t[0]-e[0]).reduce((e,[t,n])=>e.slice(0,t-s)+r+e.slice(n-s),a);return`(${r}) => ${g(e,c)}`}function v(e,t,n,r,i){let a=[i.getText(n),i.getText(r)],o=_(r,e,p,h(`value`,a),i);return`${e}.fold(${t===null?_(n,e,null,``,i):_(n,e,{members:[t.member],methods:[]},h(t.param,a),i)}, ${o})`}function y(e){let t=e.type===`BlockStatement`&&e.body.length===1?e.body[0]:e;return t.type===`ReturnStatement`&&t.argument?t.argument:null}function b(e){return e.alternate?e.alternate.type===`IfStatement`?1+b(e.alternate):2:1}const x=/* @__PURE__ */ new Set([`Left`,`None`,`Failure`,`left`,`none`,`failure`]);function S(e,n,r,i){return t(e).some(e=>e.type===`MemberExpression`&&!e.computed&&e.property.type===`Identifier`&&e.property.name===r&&s(i.getText(e.object))===n)}function C(e){if(e.type===`ReturnStatement`||e.type===`ThrowStatement`)return{exit:e,extraWork:!1};if(e.type!==`BlockStatement`||e.body.length===0)return null;let t=e.body[e.body.length-1];return t.type!==`ReturnStatement`&&t.type!==`ThrowStatement`?null:{exit:t,extraWork:e.body.length>1}}function w(e,t,n,r){let i=C(e);if(!i)return null;if(i.exit.type===`ThrowStatement`)return`throw`;if(i.extraWork)return`effect`;let a=i.exit.argument;if(!a)return`effect`;if(s(r.getText(a))===t)return`passthrough`;let o=a.type===`CallExpression`?a.callee:null,c=o?.type===`Identifier`?o.name:o?.type===`MemberExpression`&&o.property.type===`Identifier`?o.property.name:null;if(c&&x.has(c)){let e=a.arguments??[];return e.length===0||e.length===1&&n!==null&&s(r.getText(e[0]))===`${t}.${n}`?`passthrough`:`mappedFailure`}return n!==null&&S(a,t,n,r)?`effect`:`default`}function T(e,n,r){let i=e.flatMap(e=>t(e));return!i.some(e=>e.type===`AssignmentExpression`&&s(r.getText(e.left))===n)&&i.some(e=>{if(e.type!==`MemberExpression`||s(r.getText(e.object))!==n)return!1;let t=e.property.type===`Identifier`?e.property.name:null;if(t===u)return!0;let i=e.parent;return t===null||!l.includes(t)||i?.type!==`CallExpression`||i.callee!==e?!1:!(t===`orThrow`&&i.arguments.length>0)})}function E(e,t){if(e.type!==`IfStatement`||e.alternate)return null;let n=f(e.test,t);return!n?.isNegated||!C(e.consequent)?null:n}const D={meta:{type:`suggestion`,docs:{description:`Prefer .fold() over if/else chains when working with monadic types`,recommended:!0},hasSuggestions:!0,schema:[{type:`object`,properties:{allowInteropMarker:{type:`boolean`,default:!0},minComplexity:{type:`integer`,minimum:1,default:2},checkNullable:{type:`boolean`,default:!1},checkGuards:{type:`boolean`,default:!1}},additionalProperties:!1}],messages:{preferFold:`Prefer .fold() over if/else when working with {{type}} types`,preferFoldTernary:`Consider using .fold() instead of ternary operator for {{type}}`,preferFoldGuard:`{{receiver}} is checked with an early exit and then unwrapped. {{advice}} Branching first and unwrapping after is the imperative form.`,suggestFold:`Replace with .fold()`,suggestOrElse:`Replace with {{receiver}}.orElse(() => {{alternative}}) — keep the first when it is present, else the alternative`}},create(e){let t=e.options[0]||{},a=t.allowInteropMarker!==!1,o=t=>a&&i(t,`interop`,e.sourceCode),c=t.minComplexity||2,l=t.checkNullable===!0,u=t.checkGuards===!0,p=e=>e?`Several guards in a row pass their failures through: sequence them with DoAsync(async function* () { const a = yield* $(await …) … }).`:`Several guards in a row pass their failures through: sequence them with Do(function* () { const a = yield* $(…); const b = yield* $(…); return … }).`,m={passthrough:(e,t)=>t?`Keep it in the chain: ${e}.flatMapAsync(…), or lift the steps into IO.`:`Keep it in the chain: ${e}.flatMap(…) or ${e}.map(…); the failure passes through on its own.`,mappedFailure:(e,t)=>`Keep it in the chain: ${e}.mapLeft(…).${t?`flatMapAsync`:`flatMap`}(…) builds the new failure and continues on success.`,default:e=>`Use ${e}.map(…).getOrElse(() => fallback), or ${e}.fold(() => fallback, (value) => …).`,throw:e=>`If a host needs the throw, use ${e}.orThrow((e) => new YourError(e)); otherwise keep it in the chain with .flatMap or .fold.`,effect:(e,t)=>t?`Use ${e}.foldAsync(onFailure, onSuccess).`:`Use ${e}.fold(onFailure, onSuccess).`};function h(t){if(!u)return;let r=e.sourceCode,i=E(t,r);if(!i)return;let a=t.parent;if(a?.type!==`BlockStatement`&&a?.type!==`Program`)return;let o=a.body,c=o.slice(o.indexOf(t)+1),l=s(i.obj);if(!T(c,l,r))return;let d=w(t.consequent,l,i.failure?.member??null,r);if(!d)return;let f=c.some(e=>n(e)),h=(d===`passthrough`||d===`mappedFailure`)&&o.filter(e=>{let t=E(e,r);if(!t)return!1;let n=s(t.obj),i=o.slice(o.indexOf(e)+1),a=w(e.consequent,n,t.failure?.member??null,r);return(a===`passthrough`||a===`mappedFailure`)&&T(i,n,r)}).length>1;e.report({node:t,messageId:`preferFoldGuard`,data:{receiver:i.obj,advice:h?p(f):m[d](i.obj,f)}})}function g(t){let n=e.sourceCode;if(t.type!==`IfStatement`||!t.alternate)return null;let r=f(t.test,n);if(!r)return null;let i=y(t.consequent),a=y(t.alternate);if(!i||!a)return null;let o=[t.test,i,a];if(!n.getCommentsInside(t).every(e=>e.range!==void 0&&o.some(t=>e.range[0]>=t.range[0]&&e.range[1]<=t.range[1])))return null;let{obj:s,isNegated:c,failure:l}=r,[u,d]=c?[i,a]:[a,i];return`return ${v(s,l,u,d,n)}`}function _(t){let i=e.sourceCode,a=f(t.test,i);if(!a)return[];let{obj:o,isNegated:c,failure:l}=a,[u,p]=c?[t.consequent,t.alternate]:[t.alternate,t.consequent],m=i.getText(u),h=i.getText(p);if(s(h)===s(o)){if(u.type===`Literal`||u.type===`TemplateLiteral`||d(u)||n(u)||r(u))return[];let e=m.trimStart().startsWith(`{`)||u.type===`SequenceExpression`?`(${m})`:m;return[{messageId:`suggestOrElse`,data:{receiver:o,alternative:m},fix:n=>n.replaceText(t,`${o}.orElse(() => ${e})`)}]}let g=v(o,l,u,p,i);return[{messageId:`suggestFold`,fix:e=>e.replaceText(t,g)}]}function x(e){if(e.type===`CallExpression`&&e.callee.type===`MemberExpression`){let t=e.callee.property.name;return[`isSome`,`isNone`,`isRight`,`isLeft`,`isSuccess`,`isFailure`].includes(t)}return!1}function S(t){let n=e.sourceCode.getText(t);if(/\.(isSome|isNone|isDefined)\s*\(\s*\)/.test(n))return{isMonadic:!0,type:`Option`,via:`method`};if(/\.(isLeft|isRight)\s*\(\s*\)/.test(n))return{isMonadic:!0,type:`Either`,via:`method`};if(/\.(isSuccess|isFailure)\s*\(\s*\)/.test(n))return{isMonadic:!0,type:`Result`,via:`method`};if(l&&t.type===`BinaryExpression`){if((t.operator===`===`||t.operator===`!==`||t.operator===`==`||t.operator===`!=`)&&(t.left.type===`Literal`&&(t.left.value===null||t.left.value===void 0)||t.right.type===`Literal`&&(t.right.value===null||t.right.value===void 0)))return{isMonadic:!0,type:`Option`,via:`nullable`};if(t.operator===`==`||t.operator===`!=`||t.operator===`===`||t.operator===`!==`){let e=t.left.type===`Identifier`&&t.left.name===`undefined`,n=t.right.type===`Identifier`&&t.right.name===`undefined`;if(e||n)return{isMonadic:!0,type:`Option`,via:`nullable`}}}return{isMonadic:!1,type:``,via:``}}function C(e){if(!x(e.test))return[];let t=g(e);return t?[{messageId:`suggestFold`,fix:n=>n.replaceText(e,t)}]:[]}function D(t){let n=t.test,r=S(n);r.isMonadic&&(t.parent&&t.parent.type===`IfStatement`||b(t)>=c&&e.report({node:t,messageId:`preferFold`,data:{type:r.type},suggest:C(t)}))}return{IfStatement(e){o(e)||(D(e),h(e))},ConditionalExpression(t){if(o(t))return;let n=S(t.test);(n.via!==`nullable`||!d(t.consequent)&&!d(t.alternate))&&n.isMonadic&&e.report({node:t,messageId:`preferFoldTernary`,data:{type:n.type},suggest:x(t.test)?_(t):[]})}}}};export{D as default};
1
+ import{childNodes as e,descendants as t}from"../utils/ast-walk.js";import{containsAwait as n,containsYield as r}from"../utils/async-detection.js";import{isInsideTaggedDeclaration as i}from"../utils/boundary-tags.js";import{NEGATIVE_PREDICATES as a,POSITIVE_PREDICATES as o,compact as s}from"../utils/functype-predicates.js";const c={isSome:null,isNone:null,isRight:{param:`left`,member:`value`},isLeft:{param:`left`,member:`value`},isSuccess:{param:`error`,member:`error`},isFailure:{param:`error`,member:`error`}},l=[`get`,`orThrow`],u=`value`;function d(e){return e.type===`Literal`&&e.value===null||e.type===`Identifier`&&e.name===`undefined`}function f(e,t){if(e.type!==`CallExpression`||e.callee.type!==`MemberExpression`)return null;let n=e.callee.property.name,r=t.getText(e.callee.object),i=c[n]??null;return o.has(n)?{obj:r,isNegated:!1,failure:i}:a.has(n)?{obj:r,isNegated:!0,failure:i}:null}const p={members:[u],methods:l};function m(t,n,r,i){let a=e=>{let t=e.type===`TSNonNullExpression`?e.expression:e;return s(i.getText(t))===s(n)},o=(e,t)=>e.type===`MemberExpression`&&!e.computed&&e.property.type===`Identifier`&&t.includes(e.property.name)&&a(e.object),c=t=>{let n=t.parent,i=n?.type===`CallExpression`&&n.callee===t,a=n?.type===`AssignmentExpression`&&n.left===t||n?.type===`UpdateExpression`;return o(t,r.members)&&!i&&!a||t.type===`CallExpression`&&t.arguments.length===0&&o(t.callee,r.methods)?[t.range]:e(t).flatMap(c)};return c(t)}const h=(e,t)=>{let n=e=>t.some(t=>RegExp(`(?<![\\w$.])${e}(?![\\w$])`).test(t));return[e,...Array.from({length:20},(t,n)=>`${e}${n+1}`)].find(e=>!n(e))??`${e}_`},g=(e,t)=>e.type===`ObjectExpression`||e.type===`SequenceExpression`?`(${t})`:t;function _(e,t,n,r,i){let a=i.getText(e),o=n===null?[]:m(e,t,n,i);if(o.length===0)return`() => ${g(e,a)}`;let s=e.range[0],c=[...o].sort((e,t)=>t[0]-e[0]).reduce((e,[t,n])=>e.slice(0,t-s)+r+e.slice(n-s),a);return`(${r}) => ${g(e,c)}`}function v(e,t,n,r,i){let a=[i.getText(n),i.getText(r)],o=_(r,e,p,h(`value`,a),i);return`${e}.fold(${t===null?_(n,e,null,``,i):_(n,e,{members:[t.member],methods:[]},h(t.param,a),i)}, ${o})`}function y(e){let t=e.type===`BlockStatement`&&e.body.length===1?e.body[0]:e;return t.type===`ReturnStatement`&&t.argument?t.argument:null}function b(e){return e.alternate?e.alternate.type===`IfStatement`?1+b(e.alternate):2:1}const x=/* @__PURE__ */ new Set([`Left`,`None`,`Failure`,`left`,`none`,`failure`]);function S(e,n,r,i){return t(e).some(e=>e.type===`MemberExpression`&&!e.computed&&e.property.type===`Identifier`&&e.property.name===r&&s(i.getText(e.object))===n)}function C(e){if(e.type===`ReturnStatement`||e.type===`ThrowStatement`)return{exit:e,extraWork:!1};if(e.type!==`BlockStatement`||e.body.length===0)return null;let t=e.body[e.body.length-1];return t.type!==`ReturnStatement`&&t.type!==`ThrowStatement`?null:{exit:t,extraWork:e.body.length>1}}function w(e,t,n,r){let i=C(e);if(!i)return null;if(i.exit.type===`ThrowStatement`)return`throw`;if(i.extraWork)return`effect`;let a=i.exit.argument;if(!a)return`effect`;if(s(r.getText(a))===t)return`passthrough`;let o=a.type===`CallExpression`?a.callee:null,c=o?.type===`Identifier`?o.name:o?.type===`MemberExpression`&&o.property.type===`Identifier`?o.property.name:null;if(c&&x.has(c)){let e=a.arguments??[];return e.length===0||e.length===1&&n!==null&&s(r.getText(e[0]))===`${t}.${n}`?`passthrough`:`mappedFailure`}return n!==null&&S(a,t,n,r)?`effect`:`default`}function T(e,n,r){let i=e.flatMap(e=>t(e));return!i.some(e=>e.type===`AssignmentExpression`&&s(r.getText(e.left))===n)&&i.some(e=>{if(e.type!==`MemberExpression`||s(r.getText(e.object))!==n)return!1;let t=e.property.type===`Identifier`?e.property.name:null;if(t===u)return!0;let i=e.parent;return t===null||!l.includes(t)||i?.type!==`CallExpression`||i.callee!==e?!1:!(t===`orThrow`&&i.arguments.length>0)})}function E(e,t){if(e.type!==`IfStatement`||e.alternate)return null;let n=f(e.test,t);return!n?.isNegated||!C(e.consequent)?null:n}const D={meta:{type:`suggestion`,docs:{description:`Prefer .fold() over if/else chains when working with monadic types`,recommended:!0},hasSuggestions:!0,schema:[{type:`object`,properties:{allowInteropMarker:{type:`boolean`,default:!0},minComplexity:{type:`integer`,minimum:1,default:2},checkNullable:{type:`boolean`,default:!1},checkGuards:{type:`boolean`,default:!1}},additionalProperties:!1}],messages:{preferFold:`Prefer .fold() over if/else when working with {{type}} types`,preferFoldTernary:`Consider using .fold() instead of ternary operator for {{type}}`,preferFoldGuard:`{{receiver}} is checked with an early exit and then unwrapped. {{advice}} Branching first and unwrapping after is the imperative form.`,suggestFold:`Replace with .fold()`,suggestOrElse:`Replace with {{receiver}}.orElse(() => {{alternative}}) — keep the first when it is present, else the alternative`}},create(e){let t=e.options[0]||{},a=t.allowInteropMarker!==!1,o=t=>a&&i(t,`interop`,e.sourceCode),c=t.minComplexity||2,l=t.checkNullable===!0,u=t.checkGuards===!0,p=e=>e?`Several guards in a row pass their failures through: sequence them with DoAsync(async function* () { const a = yield* $(await …) … }).`:`Several guards in a row pass their failures through: sequence them with Do(function* () { const a = yield* $(…); const b = yield* $(…); return … }).`,m={passthrough:(e,t)=>t?`Keep it in the chain: ${e}.flatMapAsync(…), or lift the steps into IO.`:`Keep it in the chain: ${e}.flatMap(…) or ${e}.map(…); the failure passes through on its own.`,mappedFailure:(e,t)=>`Keep it in the chain: ${e}.mapLeft(…).${t?`flatMapAsync`:`flatMap`}(…) builds the new failure and continues on success.`,default:e=>`Use ${e}.map(…).getOrElse(() => fallback), or ${e}.fold(() => fallback, (value) => …).`,throw:e=>`If a host needs the throw, use ${e}.orThrow((e) => new YourError(e)); otherwise keep it in the chain with .flatMap or .fold.`,effect:(e,t)=>t?`Use ${e}.foldAsync(onFailure, onSuccess).`:`Use ${e}.fold(onFailure, onSuccess).`};function h(t){if(!u)return;let r=e.sourceCode,i=E(t,r);if(!i)return;let a=t.parent;if(a?.type!==`BlockStatement`&&a?.type!==`Program`)return;let o=a.body,c=o.slice(o.indexOf(t)+1),l=s(i.obj);if(!T(c,l,r))return;let d=w(t.consequent,l,i.failure?.member??null,r);if(!d)return;let f=c.some(e=>n(e)),h=(d===`passthrough`||d===`mappedFailure`)&&o.filter(e=>{let t=E(e,r);if(!t)return!1;let n=s(t.obj),i=o.slice(o.indexOf(e)+1),a=w(e.consequent,n,t.failure?.member??null,r);return(a===`passthrough`||a===`mappedFailure`)&&T(i,n,r)}).length>1;e.report({node:t,messageId:`preferFoldGuard`,data:{receiver:i.obj,advice:h?p(f):m[d](i.obj,f)}})}function g(t){let n=e.sourceCode;if(t.type!==`IfStatement`||!t.alternate)return null;let r=f(t.test,n);if(!r)return null;let i=y(t.consequent),a=y(t.alternate);if(!i||!a)return null;let o=[t.test,i,a];if(!n.getCommentsInside(t).every(e=>e.range!==void 0&&o.some(t=>e.range[0]>=t.range[0]&&e.range[1]<=t.range[1])))return null;let{obj:s,isNegated:c,failure:l}=r,[u,d]=c?[i,a]:[a,i];return`return ${v(s,l,u,d,n)}`}function _(t){let i=e.sourceCode,a=f(t.test,i);if(!a)return[];let{obj:o,isNegated:c,failure:l}=a,[u,p]=c?[t.consequent,t.alternate]:[t.alternate,t.consequent],m=i.getText(u),h=i.getText(p);if(s(h)===s(o)){if(u.type===`Literal`||u.type===`TemplateLiteral`||d(u)||n(u)||r(u))return[];let e=m.trimStart().startsWith(`{`)||u.type===`SequenceExpression`?`(${m})`:m;return[{messageId:`suggestOrElse`,data:{receiver:o,alternative:m},fix:n=>n.replaceText(t,`${o}.orElse(() => ${e})`)}]}let g=v(o,l,u,p,i);return[{messageId:`suggestFold`,fix:e=>e.replaceText(t,g)}]}function x(e){if(e.type===`CallExpression`&&e.callee.type===`MemberExpression`){let t=e.callee.property.name;return[`isSome`,`isNone`,`isRight`,`isLeft`,`isSuccess`,`isFailure`].includes(t)}return!1}function S(t){let n=e.sourceCode.getText(t);if(/\.(isSome|isNone|isDefined)\s*\(\s*\)/.test(n))return{isMonadic:!0,type:`Option`,via:`method`};if(/\.(isLeft|isRight)\s*\(\s*\)/.test(n))return{isMonadic:!0,type:`Either`,via:`method`};if(/\.(isSuccess|isFailure)\s*\(\s*\)/.test(n))return{isMonadic:!0,type:`Result`,via:`method`};if(l&&t.type===`BinaryExpression`){if((t.operator===`===`||t.operator===`!==`||t.operator===`==`||t.operator===`!=`)&&(t.left.type===`Literal`&&(t.left.value===null||t.left.value===void 0)||t.right.type===`Literal`&&(t.right.value===null||t.right.value===void 0)))return{isMonadic:!0,type:`Option`,via:`nullable`};if(t.operator===`==`||t.operator===`!=`||t.operator===`===`||t.operator===`!==`){let e=t.left.type===`Identifier`&&t.left.name===`undefined`,n=t.right.type===`Identifier`&&t.right.name===`undefined`;if(e||n)return{isMonadic:!0,type:`Option`,via:`nullable`}}}return{isMonadic:!1,type:``,via:``}}function C(e){if(!x(e.test))return[];let t=g(e);return t?[{messageId:`suggestFold`,fix:n=>n.replaceText(e,t)}]:[]}function D(t){let n=S(t.test);n.isMonadic&&(t.parent&&t.parent.type===`IfStatement`||b(t)>=c&&e.report({node:t,messageId:`preferFold`,data:{type:n.type},suggest:C(t)}))}return{IfStatement(e){o(e)||(D(e),h(e))},ConditionalExpression(t){if(o(t))return;let n=S(t.test);(n.via!==`nullable`||!d(t.consequent)&&!d(t.alternate))&&n.isMonadic&&e.report({node:t,messageId:`preferFoldTernary`,data:{type:n.type},suggest:x(t.test)?_(t):[]})}}}};export{D as default};
2
2
  //# sourceMappingURL=prefer-fold.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"prefer-fold.js","names":["FAILURE_SIDE","SUCCESS_METHODS","SUCCESS_MEMBER","isNullishLiteral","node","extractMonadicTest","test","methodName","obj","sourceCode","failure","POSITIVE_PREDICATES","NEGATIVE_PREDICATES","SUCCESS_READS","receiverReads","isReceiver","target","compact","receiver","isMember","names","visit","parent","isCalled","isWritten","reads","childNodes","branch","freshName","isTaken","branches","name","b","base","i","asArrowBody","text","foldCallback","ranges","offset","rewritten","a","start","end","acc","param","buildFold","failureNode","successNode","onSuccess","returnedExpression","statement","ifElseChainLength","FAILURE_CONSTRUCTORS","readsMember","descendants","n","member","guardExitStatement","consequent","last","classifyGuardExit","found","argument","callee","calleeName","args","failureMember","unwrapsReceiver","nodes","statements","guardOf","extracted","rule","options","context","allowInteropMarker","isExemptByMarker","isInsideTaggedDeclaration","minComplexity","checkNullable","checkGuards","SEQUENCE_ADVICE","isAsync","GUARD_ADVICE","r","checkGuard","block","body","after","exit","containsAwait","sequenced","other","candidate","otherReceiver","otherAfter","kind","generateFoldFromIf","thenExpr","elseExpr","kept","c","failureExpr","successExpr","isNegated","ternarySuggestions","failureText","successText","containsYield","thunkBody","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, descendants } from \"../utils/ast-walk\"\nimport { containsAwait, containsYield } from \"../utils/async-detection\"\nimport { INTEROP_TAG, isInsideTaggedDeclaration } from \"../utils/boundary-tags\"\nimport { compact, NEGATIVE_PREDICATES, POSITIVE_PREDICATES } from \"../utils/functype-predicates\"\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/** 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\n/**\n * What a guard's early exit does, which decides the advice:\n * - `passthrough`: hands the failure back unchanged (`return e`, `return Left(e.value)`, `return None()`),\n * so the rest of the function is a `flatMap`/`map`.\n * - `mappedFailure`: returns a new failure built from the old one (`return Left({ kind: e.value.kind })`),\n * so it's `mapLeft(…)` then `flatMap`.\n * - `default`: returns a plain fallback, so it's `map(…).getOrElse(() => fallback)` or a `fold`.\n * - `throw`: a host that needs a throw, so it's `orThrow((e) => …)`.\n * - `effect`: does other work first (logging, setting state), so it's a `fold`.\n */\ntype GuardExit = \"passthrough\" | \"mappedFailure\" | \"default\" | \"throw\" | \"effect\"\n\n/** Constructors (and companion methods) that build a failure: `Left(…)`, `None()`, `Failure(…)`, `Either.left(…)`. */\nconst FAILURE_CONSTRUCTORS: ReadonlySet<string> = new Set([\"Left\", \"None\", \"Failure\", \"left\", \"none\", \"failure\"])\n\n/** Does `node` read `<receiver>.<member>` anywhere inside it? */\nfunction readsMember(node: ASTNode, receiver: string, member: string, sourceCode: SourceCode): boolean {\n return descendants(node).some(\n (n) =>\n n.type === \"MemberExpression\" &&\n !n.computed &&\n n.property.type === \"Identifier\" &&\n n.property.name === member &&\n compact(sourceCode.getText(n.object)) === receiver,\n )\n}\n\n/** The single exit statement of a guard's consequent: `return x` / `throw x`, alone or as a one-statement block. */\nfunction guardExitStatement(consequent: ASTNode): { readonly exit: ASTNode; readonly extraWork: boolean } | null {\n if (consequent.type === \"ReturnStatement\" || consequent.type === \"ThrowStatement\") {\n return { exit: consequent, extraWork: false }\n }\n if (consequent.type !== \"BlockStatement\" || consequent.body.length === 0) return null\n const last = consequent.body[consequent.body.length - 1] as ASTNode\n if (last.type !== \"ReturnStatement\" && last.type !== \"ThrowStatement\") return null\n return { exit: last, extraWork: consequent.body.length > 1 }\n}\n\n/**\n * `receiver` is the compacted receiver text; `failureMember` is where the failure value lives once\n * narrowed (`value` for Either, `error` for Try, null for Option, whose None carries nothing).\n */\nfunction classifyGuardExit(\n consequent: ASTNode,\n receiver: string,\n failureMember: string | null,\n sourceCode: SourceCode,\n): GuardExit | null {\n const found = guardExitStatement(consequent)\n if (!found) return null\n if (found.exit.type === \"ThrowStatement\") return \"throw\"\n if (found.extraWork) return \"effect\"\n const argument = found.exit.argument as ASTNode | null\n if (!argument) return \"effect\"\n if (compact(sourceCode.getText(argument)) === receiver) return \"passthrough\"\n const callee = argument.type === \"CallExpression\" ? (argument.callee as ASTNode) : null\n const calleeName =\n callee?.type === \"Identifier\"\n ? callee.name\n : callee?.type === \"MemberExpression\" && callee.property.type === \"Identifier\"\n ? callee.property.name\n : null\n if (calleeName && FAILURE_CONSTRUCTORS.has(calleeName)) {\n const args = (argument.arguments ?? []) as ReadonlyArray<ASTNode>\n const unchanged =\n args.length === 0 ||\n (args.length === 1 &&\n failureMember !== null &&\n compact(sourceCode.getText(args[0])) === `${receiver}.${failureMember}`)\n return unchanged ? \"passthrough\" : \"mappedFailure\"\n }\n // A fallback built from the failure (`c.json({ error: r.value }, 500)`) can only be written as a fold:\n // outside the guard the failure isn't narrowed, so `map(…).getOrElse(() => …)` couldn't read it.\n if (failureMember !== null && readsMember(argument, receiver, failureMember, sourceCode)) return \"effect\"\n return \"default\"\n}\n\n/**\n * Does `statements` unwrap `receiver` the imperative way — `receiver.value`, `.orThrow()`, `.get()`?\n * Reads through `map`, `flatMap`, `fold`, `getOrElse`… are already the functional form and don't count.\n */\nfunction unwrapsReceiver(statements: ReadonlyArray<ASTNode>, receiver: string, sourceCode: SourceCode): boolean {\n const nodes = statements.flatMap((statement) => descendants(statement))\n // `e = next()` after the guard: later reads are of a different value, which the guard didn't check.\n const reassigned = nodes.some(\n (node) => node.type === \"AssignmentExpression\" && compact(sourceCode.getText(node.left)) === receiver,\n )\n if (reassigned) return false\n return nodes.some((node) => {\n if (node.type !== \"MemberExpression\" || compact(sourceCode.getText(node.object)) !== receiver) return false\n const name = node.property.type === \"Identifier\" ? node.property.name : null\n if (name === SUCCESS_MEMBER) return true\n const parent = node.parent as ASTNode | undefined\n if (name === null || !SUCCESS_METHODS.includes(name)) return false\n if (parent?.type !== \"CallExpression\" || parent.callee !== node) return false\n // `orThrow(error)` / `orThrow((e) => …)` names its error: no-get-unsafe treats that as a deliberate\n // host throw, so this rule doesn't count it as an unwrap either.\n return !(name === \"orThrow\" && (parent.arguments as ReadonlyArray<ASTNode>).length > 0)\n })\n}\n\n/** An exit-only negative guard (`if (e.isLeft()) return …`) on a functype predicate, or null. */\nfunction guardOf(node: ASTNode, sourceCode: SourceCode): ReturnType<typeof extractMonadicTest> {\n if (node.type !== \"IfStatement\" || node.alternate) return null\n const extracted = extractMonadicTest(node.test, sourceCode)\n if (!extracted?.isNegated || !guardExitStatement(node.consequent)) return null\n return extracted\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 checkGuards: {\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 preferFoldGuard:\n \"{{receiver}} is checked with an early exit and then unwrapped. {{advice}} Branching first and unwrapping after is the imperative form.\",\n suggestFold: \"Replace with .fold()\",\n suggestOrElse:\n \"Replace with {{receiver}}.orElse(() => {{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 a private app monorepo,\n // 0 of which were functype values). Predicate calls (`o.isSome()`, `e.isLeft()`) are always checked.\n const checkNullable = options.checkNullable === true\n // Guard-then-unwrap (`if (e.isLeft()) return …; use(e.value)`). Opt-in while it's measured on real\n // code: prefer-fold is `error` in recommended, so turning this on by default would fail builds.\n const checkGuards = options.checkGuards === true\n\n const SEQUENCE_ADVICE = (isAsync: boolean): string =>\n isAsync\n ? \"Several guards in a row pass their failures through: sequence them with DoAsync(async function* () { const a = yield* $(await …) … }).\"\n : \"Several guards in a row pass their failures through: sequence them with Do(function* () { const a = yield* $(…); const b = yield* $(…); return … }).\"\n\n const GUARD_ADVICE: Readonly<Record<GuardExit, (receiver: string, isAsync: boolean) => string>> = {\n passthrough: (r, isAsync) =>\n isAsync\n ? `Keep it in the chain: ${r}.flatMapAsync(…), or lift the steps into IO.`\n : `Keep it in the chain: ${r}.flatMap(…) or ${r}.map(…); the failure passes through on its own.`,\n mappedFailure: (r, isAsync) =>\n `Keep it in the chain: ${r}.mapLeft(…).${isAsync ? \"flatMapAsync\" : \"flatMap\"}(…) builds the new failure and continues on success.`,\n default: (r) => `Use ${r}.map(…).getOrElse(() => fallback), or ${r}.fold(() => fallback, (value) => …).`,\n throw: (r) =>\n `If a host needs the throw, use ${r}.orThrow((e) => new YourError(e)); otherwise keep it in the chain with .flatMap or .fold.`,\n effect: (r, isAsync) =>\n isAsync ? `Use ${r}.foldAsync(onFailure, onSuccess).` : `Use ${r}.fold(onFailure, onSuccess).`,\n }\n\n /**\n * `if (e.isLeft()) return …` followed, in the same block, by reads of `e.value` / `e.orThrow()`.\n * `getOrElse` and `fold` are never flagged: both are proper ways to leave the container.\n */\n function checkGuard(node: ASTNode): void {\n if (!checkGuards) return\n const sourceCode = context.sourceCode\n const extracted = guardOf(node, sourceCode)\n if (!extracted) return\n const block = node.parent as ASTNode | undefined\n if (block?.type !== \"BlockStatement\" && block?.type !== \"Program\") return\n const body = block.body as ReadonlyArray<ASTNode>\n const after = body.slice(body.indexOf(node) + 1)\n const receiver = compact(extracted.obj)\n if (!unwrapsReceiver(after, receiver, sourceCode)) return\n const exit = classifyGuardExit(node.consequent, receiver, extracted.failure?.member ?? null, sourceCode)\n if (!exit) return\n const isAsync = after.some((statement) => containsAwait(statement))\n // Two or more pass-through guards in one block, each unwrapped later: nested flatMaps would be worse\n // than the guards, so the advice is a Do comprehension.\n const passThrough = (candidate: ASTNode): boolean => {\n const other = guardOf(candidate, sourceCode)\n if (!other) return false\n const otherReceiver = compact(other.obj)\n const otherAfter = body.slice(body.indexOf(candidate) + 1)\n const kind = classifyGuardExit(candidate.consequent, otherReceiver, other.failure?.member ?? null, sourceCode)\n return (\n (kind === \"passthrough\" || kind === \"mappedFailure\") && unwrapsReceiver(otherAfter, otherReceiver, sourceCode)\n )\n }\n const sequenced = (exit === \"passthrough\" || exit === \"mappedFailure\") && body.filter(passThrough).length > 1\n context.report({\n node,\n messageId: \"preferFoldGuard\",\n data: {\n receiver: extracted.obj,\n advice: sequenced ? SEQUENCE_ADVICE(isAsync) : GUARD_ADVICE[exit](extracted.obj, isAsync),\n },\n })\n }\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\n // `.orElse(() => b)`, and a fold would only rebuild it with an unused parameter. `.orElse` takes a\n // thunk that returns a container, so a literal or `undefined` fallback gets no suggestion at all:\n // neither `.orElse(() => 5)` nor a fold mixing a container with a plain value would type-check. An\n // `await` or `yield` in the fallback can't move into the thunk, so that gets none either.\n if (compact(successText) === compact(obj)) {\n if (failureNode.type === \"Literal\" || failureNode.type === \"TemplateLiteral\" || isNullishLiteral(failureNode)) {\n return []\n }\n if (containsAwait(failureNode) || containsYield(failureNode)) return []\n // An arrow body that starts with `{` reads as a block, and a sequence's comma would split the call's\n // arguments, so both go in parentheses: `{}.x` and `(b, c)` stay one expression.\n const needsParens = failureText.trimStart().startsWith(\"{\") || failureNode.type === \"SequenceExpression\"\n const thunkBody = needsParens ? `(${failureText})` : failureText\n return [\n {\n messageId: \"suggestOrElse\",\n data: { receiver: obj, alternative: failureText },\n fix: (fixer) => fixer.replaceText(node, `${obj}.orElse(() => ${thunkBody})`),\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 checkGuard(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":"A,oUAgBA,MAAMA,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,EACnCC,EAAiB,QAOvB,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,EAAUV,EAAaO,IAAe,KAG5C,OAFII,EAAoB,IAAIJ,CAAU,EAAU,CAAE,MAAK,UAAW,GAAO,SAAQ,EAC7EK,EAAoB,IAAIL,CAAU,EAAU,CAAE,MAAK,UAAW,GAAM,SAAQ,EACzE,IACT,CAKA,MAAMM,EAAuB,CAAE,QAAS,CAACX,CAAc,EAAG,QAASD,CAAgB,EAQnF,SAASa,EACP,EACA,EACA,EACA,EAC0C,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AAI,EAAI,CAAC,CAC5E,CAAC,CAEL,CACF,CACF,CACF,E"}
1
+ {"version":3,"file":"prefer-fold.js","names":["childNodes","descendants","containsAwait","containsYield","isInsideTaggedDeclaration","NEGATIVE_PREDICATES","POSITIVE_PREDICATES","compact","FAILURE_SIDE","SUCCESS_METHODS","SUCCESS_MEMBER","isNullishLiteral","node","extractMonadicTest","test","sourceCode","methodName","obj","failure","SUCCESS_READS","receiverReads","branch","receiver","reads","isReceiver","target","isMember","names","visit","parent","isCalled","isWritten","freshName","base","branches","isTaken","name","b","_","i","asArrowBody","text","foldCallback","param","ranges","offset","rewritten","a","acc","start","end","buildFold","failureNode","successNode","onSuccess","returnedExpression","statement","ifElseChainLength","FAILURE_CONSTRUCTORS","readsMember","member","n","guardExitStatement","consequent","last","classifyGuardExit","failureMember","found","argument","callee","calleeName","args","unwrapsReceiver","statements","nodes","guardOf","extracted","rule","context","options","allowInteropMarker","isExemptByMarker","minComplexity","checkNullable","checkGuards","SEQUENCE_ADVICE","isAsync","GUARD_ADVICE","r","checkGuard","block","body","after","exit","sequenced","candidate","other","otherReceiver","otherAfter","kind","generateFoldFromIf","thenExpr","elseExpr","kept","c","isNegated","failureExpr","successExpr","ternarySuggestions","failureText","successText","thunkBody","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, descendants } from \"../utils/ast-walk\"\nimport { containsAwait, containsYield } from \"../utils/async-detection\"\nimport { INTEROP_TAG, isInsideTaggedDeclaration } from \"../utils/boundary-tags\"\nimport { compact, NEGATIVE_PREDICATES, POSITIVE_PREDICATES } from \"../utils/functype-predicates\"\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/** 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\n/**\n * What a guard's early exit does, which decides the advice:\n * - `passthrough`: hands the failure back unchanged (`return e`, `return Left(e.value)`, `return None()`),\n * so the rest of the function is a `flatMap`/`map`.\n * - `mappedFailure`: returns a new failure built from the old one (`return Left({ kind: e.value.kind })`),\n * so it's `mapLeft(…)` then `flatMap`.\n * - `default`: returns a plain fallback, so it's `map(…).getOrElse(() => fallback)` or a `fold`.\n * - `throw`: a host that needs a throw, so it's `orThrow((e) => …)`.\n * - `effect`: does other work first (logging, setting state), so it's a `fold`.\n */\ntype GuardExit = \"passthrough\" | \"mappedFailure\" | \"default\" | \"throw\" | \"effect\"\n\n/** Constructors (and companion methods) that build a failure: `Left(…)`, `None()`, `Failure(…)`, `Either.left(…)`. */\nconst FAILURE_CONSTRUCTORS: ReadonlySet<string> = new Set([\"Left\", \"None\", \"Failure\", \"left\", \"none\", \"failure\"])\n\n/** Does `node` read `<receiver>.<member>` anywhere inside it? */\nfunction readsMember(node: ASTNode, receiver: string, member: string, sourceCode: SourceCode): boolean {\n return descendants(node).some(\n (n) =>\n n.type === \"MemberExpression\" &&\n !n.computed &&\n n.property.type === \"Identifier\" &&\n n.property.name === member &&\n compact(sourceCode.getText(n.object)) === receiver,\n )\n}\n\n/** The single exit statement of a guard's consequent: `return x` / `throw x`, alone or as a one-statement block. */\nfunction guardExitStatement(consequent: ASTNode): { readonly exit: ASTNode; readonly extraWork: boolean } | null {\n if (consequent.type === \"ReturnStatement\" || consequent.type === \"ThrowStatement\") {\n return { exit: consequent, extraWork: false }\n }\n if (consequent.type !== \"BlockStatement\" || consequent.body.length === 0) return null\n const last = consequent.body[consequent.body.length - 1] as ASTNode\n if (last.type !== \"ReturnStatement\" && last.type !== \"ThrowStatement\") return null\n return { exit: last, extraWork: consequent.body.length > 1 }\n}\n\n/**\n * `receiver` is the compacted receiver text; `failureMember` is where the failure value lives once\n * narrowed (`value` for Either, `error` for Try, null for Option, whose None carries nothing).\n */\nfunction classifyGuardExit(\n consequent: ASTNode,\n receiver: string,\n failureMember: string | null,\n sourceCode: SourceCode,\n): GuardExit | null {\n const found = guardExitStatement(consequent)\n if (!found) return null\n if (found.exit.type === \"ThrowStatement\") return \"throw\"\n if (found.extraWork) return \"effect\"\n const argument = found.exit.argument as ASTNode | null\n if (!argument) return \"effect\"\n if (compact(sourceCode.getText(argument)) === receiver) return \"passthrough\"\n const callee = argument.type === \"CallExpression\" ? (argument.callee as ASTNode) : null\n const calleeName =\n callee?.type === \"Identifier\"\n ? callee.name\n : callee?.type === \"MemberExpression\" && callee.property.type === \"Identifier\"\n ? callee.property.name\n : null\n if (calleeName && FAILURE_CONSTRUCTORS.has(calleeName)) {\n const args = (argument.arguments ?? []) as ReadonlyArray<ASTNode>\n const unchanged =\n args.length === 0 ||\n (args.length === 1 &&\n failureMember !== null &&\n compact(sourceCode.getText(args[0])) === `${receiver}.${failureMember}`)\n return unchanged ? \"passthrough\" : \"mappedFailure\"\n }\n // A fallback built from the failure (`c.json({ error: r.value }, 500)`) can only be written as a fold:\n // outside the guard the failure isn't narrowed, so `map(…).getOrElse(() => …)` couldn't read it.\n if (failureMember !== null && readsMember(argument, receiver, failureMember, sourceCode)) return \"effect\"\n return \"default\"\n}\n\n/**\n * Does `statements` unwrap `receiver` the imperative way — `receiver.value`, `.orThrow()`, `.get()`?\n * Reads through `map`, `flatMap`, `fold`, `getOrElse`… are already the functional form and don't count.\n */\nfunction unwrapsReceiver(statements: ReadonlyArray<ASTNode>, receiver: string, sourceCode: SourceCode): boolean {\n const nodes = statements.flatMap((statement) => descendants(statement))\n // `e = next()` after the guard: later reads are of a different value, which the guard didn't check.\n const reassigned = nodes.some(\n (node) => node.type === \"AssignmentExpression\" && compact(sourceCode.getText(node.left)) === receiver,\n )\n if (reassigned) return false\n return nodes.some((node) => {\n if (node.type !== \"MemberExpression\" || compact(sourceCode.getText(node.object)) !== receiver) return false\n const name = node.property.type === \"Identifier\" ? node.property.name : null\n if (name === SUCCESS_MEMBER) return true\n const parent = node.parent as ASTNode | undefined\n if (name === null || !SUCCESS_METHODS.includes(name)) return false\n if (parent?.type !== \"CallExpression\" || parent.callee !== node) return false\n // `orThrow(error)` / `orThrow((e) => …)` names its error: no-get-unsafe treats that as a deliberate\n // host throw, so this rule doesn't count it as an unwrap either.\n return !(name === \"orThrow\" && (parent.arguments as ReadonlyArray<ASTNode>).length > 0)\n })\n}\n\n/** An exit-only negative guard (`if (e.isLeft()) return …`) on a functype predicate, or null. */\nfunction guardOf(node: ASTNode, sourceCode: SourceCode): ReturnType<typeof extractMonadicTest> {\n if (node.type !== \"IfStatement\" || node.alternate) return null\n const extracted = extractMonadicTest(node.test, sourceCode)\n if (!extracted?.isNegated || !guardExitStatement(node.consequent)) return null\n return extracted\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 checkGuards: {\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 preferFoldGuard:\n \"{{receiver}} is checked with an early exit and then unwrapped. {{advice}} Branching first and unwrapping after is the imperative form.\",\n suggestFold: \"Replace with .fold()\",\n suggestOrElse:\n \"Replace with {{receiver}}.orElse(() => {{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 a private app monorepo,\n // 0 of which were functype values). Predicate calls (`o.isSome()`, `e.isLeft()`) are always checked.\n const checkNullable = options.checkNullable === true\n // Guard-then-unwrap (`if (e.isLeft()) return …; use(e.value)`). Opt-in while it's measured on real\n // code: prefer-fold is `error` in recommended, so turning this on by default would fail builds.\n const checkGuards = options.checkGuards === true\n\n const SEQUENCE_ADVICE = (isAsync: boolean): string =>\n isAsync\n ? \"Several guards in a row pass their failures through: sequence them with DoAsync(async function* () { const a = yield* $(await …) … }).\"\n : \"Several guards in a row pass their failures through: sequence them with Do(function* () { const a = yield* $(…); const b = yield* $(…); return … }).\"\n\n const GUARD_ADVICE: Readonly<Record<GuardExit, (receiver: string, isAsync: boolean) => string>> = {\n passthrough: (r, isAsync) =>\n isAsync\n ? `Keep it in the chain: ${r}.flatMapAsync(…), or lift the steps into IO.`\n : `Keep it in the chain: ${r}.flatMap(…) or ${r}.map(…); the failure passes through on its own.`,\n mappedFailure: (r, isAsync) =>\n `Keep it in the chain: ${r}.mapLeft(…).${isAsync ? \"flatMapAsync\" : \"flatMap\"}(…) builds the new failure and continues on success.`,\n default: (r) => `Use ${r}.map(…).getOrElse(() => fallback), or ${r}.fold(() => fallback, (value) => …).`,\n throw: (r) =>\n `If a host needs the throw, use ${r}.orThrow((e) => new YourError(e)); otherwise keep it in the chain with .flatMap or .fold.`,\n effect: (r, isAsync) =>\n isAsync ? `Use ${r}.foldAsync(onFailure, onSuccess).` : `Use ${r}.fold(onFailure, onSuccess).`,\n }\n\n /**\n * `if (e.isLeft()) return …` followed, in the same block, by reads of `e.value` / `e.orThrow()`.\n * `getOrElse` and `fold` are never flagged: both are proper ways to leave the container.\n */\n function checkGuard(node: ASTNode): void {\n if (!checkGuards) return\n const sourceCode = context.sourceCode\n const extracted = guardOf(node, sourceCode)\n if (!extracted) return\n const block = node.parent as ASTNode | undefined\n if (block?.type !== \"BlockStatement\" && block?.type !== \"Program\") return\n const body = block.body as ReadonlyArray<ASTNode>\n const after = body.slice(body.indexOf(node) + 1)\n const receiver = compact(extracted.obj)\n if (!unwrapsReceiver(after, receiver, sourceCode)) return\n const exit = classifyGuardExit(node.consequent, receiver, extracted.failure?.member ?? null, sourceCode)\n if (!exit) return\n const isAsync = after.some((statement) => containsAwait(statement))\n // Two or more pass-through guards in one block, each unwrapped later: nested flatMaps would be worse\n // than the guards, so the advice is a Do comprehension.\n const passThrough = (candidate: ASTNode): boolean => {\n const other = guardOf(candidate, sourceCode)\n if (!other) return false\n const otherReceiver = compact(other.obj)\n const otherAfter = body.slice(body.indexOf(candidate) + 1)\n const kind = classifyGuardExit(candidate.consequent, otherReceiver, other.failure?.member ?? null, sourceCode)\n return (\n (kind === \"passthrough\" || kind === \"mappedFailure\") && unwrapsReceiver(otherAfter, otherReceiver, sourceCode)\n )\n }\n const sequenced = (exit === \"passthrough\" || exit === \"mappedFailure\") && body.filter(passThrough).length > 1\n context.report({\n node,\n messageId: \"preferFoldGuard\",\n data: {\n receiver: extracted.obj,\n advice: sequenced ? SEQUENCE_ADVICE(isAsync) : GUARD_ADVICE[exit](extracted.obj, isAsync),\n },\n })\n }\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\n // `.orElse(() => b)`, and a fold would only rebuild it with an unused parameter. `.orElse` takes a\n // thunk that returns a container, so a literal or `undefined` fallback gets no suggestion at all:\n // neither `.orElse(() => 5)` nor a fold mixing a container with a plain value would type-check. An\n // `await` or `yield` in the fallback can't move into the thunk, so that gets none either.\n if (compact(successText) === compact(obj)) {\n if (failureNode.type === \"Literal\" || failureNode.type === \"TemplateLiteral\" || isNullishLiteral(failureNode)) {\n return []\n }\n if (containsAwait(failureNode) || containsYield(failureNode)) return []\n // An arrow body that starts with `{` reads as a block, and a sequence's comma would split the call's\n // arguments, so both go in parentheses: `{}.x` and `(b, c)` stay one expression.\n const needsParens = failureText.trimStart().startsWith(\"{\") || failureNode.type === \"SequenceExpression\"\n const thunkBody = needsParens ? `(${failureText})` : failureText\n return [\n {\n messageId: \"suggestOrElse\",\n data: { receiver: obj, alternative: failureText },\n fix: (fixer) => fixer.replaceText(node, `${obj}.orElse(() => ${thunkBody})`),\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 checkGuard(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 })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AAW,GAAM,KAAM,SAAU,IAAK,UAAW,CAE9D,CACF,CAEA,MAAO,CAAE,UAAW,GAAO,KAAM,GAAI,IAAK,EAAG,CAC/C,CAEA,SAASC,EAAiB1G,EAAkD,CAC1E,GAAI,CAACsG,EAAwBtG,EAAK,IAAI,EAAG,MAAO,CAAC,EACjD,IAAM2G,EAAcnB,EAAmBxF,CAAI,EAC3C,OAAO2G,EAAc,CAAC,CAAE,UAAW,cAAe,IAAMP,GAAUA,EAAM,YAAYpG,EAAM2G,CAAW,CAAE,CAAC,EAAI,CAAC,CAC/G,CAEA,SAASC,EAAmB5G,EAAe,CAEzC,IAAM6G,EAAcN,EADPvG,EAAK,IACqB,EAElC6G,EAAY,YAIb7G,EAAK,QAAUA,EAAK,OAAO,OAAS,eAGpC6C,EAAkB7C,CAAI,GAAKsE,GAC7BJ,EAAQ,OAAO,CACblE,OACA,UAAW,aACX,KAAM,CAAE,KAAM6G,EAAY,IAAK,EAC/B,QAASH,EAAiB1G,CAAI,CAChC,CAAC,EAEL,CAEA,MAAO,CACL,YAAYA,EAAe,CACrBqE,EAAiBrE,CAAI,IACzB4G,EAAmB5G,CAAI,EACvB6E,EAAW7E,CAAI,EACjB,EAEA,sBAAsBA,EAAe,CACnC,GAAIqE,EAAiBrE,CAAI,EAAG,OAC5B,IAAM6G,EAAcN,EAAevG,EAAK,IAAI,GAKxC6G,EAAY,MAAQ,YAAe9G,GAAiBC,EAAK,UAAU,GAAKD,GAAiBC,EAAK,SAAS,IAGvG6G,EAAY,WACd3C,EAAQ,OAAO,CACblE,OACA,UAAW,oBACX,KAAM,CAAE,KAAM6G,EAAY,IAAK,EAC/B,QAASP,EAAwBtG,EAAK,IAAI,EAAIgG,EAAmBhG,CAAI,EAAI,CAAC,CAC5E,CAAC,CAEL,CACF,CACF,CACF,E"}
@@ -1 +1 @@
1
- {"version":3,"file":"prefer-functype-map.js","names":["rule","options","context","allowInTests","allowMutable","isInTestFile","filename","functypeImports","getFunctypeImportsLegacy","node","bindingOf","isExplicitNativeCollection","isMutatedCollection","MAP_MUTATORS","flowsIntoReadonlyContract","isAlreadyUsingFunctype","sourceCode","imported","functypeLocalName","name","args","suggestions","fixer","mapOfArgs","el","argText","createImportFixer","typeName","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 { bindingOf, functypeLocalName, isExplicitNativeCollection } from \"../utils/collection-binding\"\nimport { getFunctypeImportsLegacy, isAlreadyUsingFunctype } from \"../utils/functype-detection\"\nimport { createImportFixer } from \"../utils/import-fixer\"\nimport { annotatesMutatedBinding, isMutatedCollection, MAP_MUTATORS } from \"../utils/mutable-collection\"\nimport { flowsIntoReadonlyContract } from \"../utils/readonly-contract\"\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 {{name}}.empty()\",\n suggestMapOf: \"Replace with {{name}}.of(...)\",\n suggestMapFrom: \"Replace with {{name}}(...)\",\n suggestUseLocalName: \"Replace with {{name}}\",\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 return {\n NewExpression(node: ASTNode) {\n if (allowInTests && isInTestFile()) return\n\n // The built-in, however it's spelled: bare `Map` that resolves to the global (functype's import\n // or a local shadow doesn't count, #350), or explicit `globalThis.Map` — the spelling the\n // functype-by-default convention uses, which must not be an escape hatch (#349).\n const isBareNative =\n node.callee?.type === \"Identifier\" &&\n node.callee.name === \"Map\" &&\n bindingOf(node.callee, \"Map\", context.sourceCode) === \"native\"\n if (!isBareNative && !isExplicitNativeCollection(node.callee, \"Map\", context.sourceCode)) return\n\n if (allowMutable && isMutatedCollection(node, MAP_MUTATORS, context.sourceCode)) return\n\n // A native Map flowing into a declared `ReadonlyMap` contract is what that contract requires (#350).\n if (flowsIntoReadonlyContract(node, \"ReadonlyMap\")) return\n\n // Skip if already using functype\n if (isAlreadyUsingFunctype(node, functypeImports)) return\n\n const sourceCode = context.sourceCode\n const imported = functypeLocalName(sourceCode, \"Map\")\n const name = imported ?? \"Map\"\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 data: { name },\n fix(fixer) {\n return fixer.replaceText(node, `${name}.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 data: { name },\n fix(fixer) {\n return fixer.replaceText(node, `${name}.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 data: { name },\n fix(fixer) {\n return fixer.replaceText(node, `${name}(${argText})`)\n },\n })\n } else {\n // Generic fallback for any other args\n suggestions.push({\n messageId: \"suggestMapEmpty\",\n data: { name },\n fix(fixer) {\n return fixer.replaceText(node, `${name}.empty()`)\n },\n })\n }\n\n if (imported === null) {\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 // `Map<…>` or the explicit `globalThis.Map<…>`.\n const typeName = node.typeName.type === \"Identifier\" ? node.typeName.name : sourceCode.getText(node.typeName)\n\n if (typeName !== \"Map\" && typeName !== \"globalThis.Map\") return\n\n if (allowMutable && annotatesMutatedBinding(node, MAP_MUTATORS, context.sourceCode)) return\n\n if (node.typeName.type === \"Identifier\" && bindingOf(node.typeName, \"Map\", context.sourceCode) !== \"native\")\n 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 // Already imported under another name (`Map as FMap`): point at that name instead of adding a\n // second import that would shadow the native `Map` the rest of the file uses.\n const imported = functypeLocalName(sourceCode, \"Map\")\n const suggestions: Rule.SuggestionReportDescriptor[] =\n imported === null\n ? [{ messageId: \"suggestAddImport\", data: { symbol: \"Map\" }, fix: createImportFixer(sourceCode, \"Map\") }]\n : [\n {\n messageId: \"suggestUseLocalName\",\n data: { name: imported },\n fix: (fixer) => fixer.replaceText(node.typeName, imported),\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":"A,mdASA,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,gCACjB,aAAc,gCACd,eAAgB,6BAChB,oBAAqB,wBACrB,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,MAAO,CACL,cAAc,EAAe,CAkB3B,GAjBIC,GAAgBE,EAAa,IAM/BI,EAAK,QAAQ,OAAS,cACtBA,EAAK,OAAO,OAAS,OACrBC,EAAUD,EAAK,OAAQ,MAAOP,EAAQ,UAAU,IAAM,WACnC,CAACS,EAA2BF,EAAK,OAAQ,MAAOP,EAAQ,UAAU,GAEnFE,GAAgBQ,EAAoBH,EAAMI,EAAcX,EAAQ,UAAU,GAG1EY,EAA0BL,EAAM,aAAa,GAG7CM,EAAuBN,EAAMF,CAAe,EAAG,OAEnD,IAAMS,EAAad,EAAQ,WACrBe,EAAWC,EAAkBF,EAAY,KAAK,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WlB,EAAK,SAAS,OAAS,aAAeA,EAAK,SAAS,KAAOO,EAAW,QAAQP,EAAK,QAAQ,EAM5G,GAJIkB,IAAa,OAASA,IAAa,kBAEnCvB,GAAgBwB,EAAwBnB,EAAMI,EAAcX,EAAQ,UAAU,GAE9EO,EAAK,SAAS,OAAS,cAAgBC,EAAUD,EAAK,SAAU,MAAOP,EAAQ,UAAU,IAAM,SACjG,OAGF,IAAM2B,EAAapB,EAAK,eAAe,QAAUA,EAAK,gBAAgB,OAChEqB,EAAUD,IAAa,GAAKb,EAAW,QAAQa,EAAW,EAAE,EAAI,IAChEE,EAAYF,GAAcA,EAAW,QAAU,EAAIb,EAAW,QAAQa,EAAW,EAAE,EAAI,IAIvFZ,EAAWC,EAAkBF,EAAY,KAAK,EAC9CK,EACJJ,IAAa,KACT,CAAC,CAAE,UAAW,mBAAoB,KAAM,CAAE,OAAQ,KAAM,EAAG,IAAKS,EAAkBV,EAAY,KAAK,CAAE,CAAC,EACtG,CACE,CACE,UAAW,sBACX,KAAM,CAAE,KAAMC,CAAS,EACvB,IAAM,GAAUK,EAAM,YAAYb,EAAK,SAAUQ,CAAQ,CAC3D,CACF,EAENf,EAAQ,OAAO,CACb,OACA,UAAW,oBACX,KAAM,CAAE,UAAS,WAAU,EAC3B,QAASmB,CACX,CAAC,CACH,CACF,CACF,CACF,E"}
1
+ {"version":3,"file":"prefer-functype-map.js","names":["bindingOf","functypeLocalName","isExplicitNativeCollection","getFunctypeImportsLegacy","isAlreadyUsingFunctype","createImportFixer","MAP_MUTATORS","annotatesMutatedBinding","isMutatedCollection","flowsIntoReadonlyContract","rule","context","options","allowInTests","allowMutable","isInTestFile","filename","functypeImports","node","sourceCode","imported","name","args","suggestions","fixer","mapOfArgs","el","argText","typeName","typeParams","keyType","valueType"],"sources":["../../src/rules/prefer-functype-map.ts"],"sourcesContent":["import type { Rule } from \"eslint\"\n\nimport type { ASTNode } from \"../types/ast\"\nimport { bindingOf, functypeLocalName, isExplicitNativeCollection } from \"../utils/collection-binding\"\nimport { getFunctypeImportsLegacy, isAlreadyUsingFunctype } from \"../utils/functype-detection\"\nimport { createImportFixer } from \"../utils/import-fixer\"\nimport { annotatesMutatedBinding, isMutatedCollection, MAP_MUTATORS } from \"../utils/mutable-collection\"\nimport { flowsIntoReadonlyContract } from \"../utils/readonly-contract\"\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 {{name}}.empty()\",\n suggestMapOf: \"Replace with {{name}}.of(...)\",\n suggestMapFrom: \"Replace with {{name}}(...)\",\n suggestUseLocalName: \"Replace with {{name}}\",\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 return {\n NewExpression(node: ASTNode) {\n if (allowInTests && isInTestFile()) return\n\n // The built-in, however it's spelled: bare `Map` that resolves to the global (functype's import\n // or a local shadow doesn't count, #350), or explicit `globalThis.Map` — the spelling the\n // functype-by-default convention uses, which must not be an escape hatch (#349).\n const isBareNative =\n node.callee?.type === \"Identifier\" &&\n node.callee.name === \"Map\" &&\n bindingOf(node.callee, \"Map\", context.sourceCode) === \"native\"\n if (!isBareNative && !isExplicitNativeCollection(node.callee, \"Map\", context.sourceCode)) return\n\n if (allowMutable && isMutatedCollection(node, MAP_MUTATORS, context.sourceCode)) return\n\n // A native Map flowing into a declared `ReadonlyMap` contract is what that contract requires (#350).\n if (flowsIntoReadonlyContract(node, \"ReadonlyMap\")) return\n\n // Skip if already using functype\n if (isAlreadyUsingFunctype(node, functypeImports)) return\n\n const sourceCode = context.sourceCode\n const imported = functypeLocalName(sourceCode, \"Map\")\n const name = imported ?? \"Map\"\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 data: { name },\n fix(fixer) {\n return fixer.replaceText(node, `${name}.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 data: { name },\n fix(fixer) {\n return fixer.replaceText(node, `${name}.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 data: { name },\n fix(fixer) {\n return fixer.replaceText(node, `${name}(${argText})`)\n },\n })\n } else {\n // Generic fallback for any other args\n suggestions.push({\n messageId: \"suggestMapEmpty\",\n data: { name },\n fix(fixer) {\n return fixer.replaceText(node, `${name}.empty()`)\n },\n })\n }\n\n if (imported === null) {\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 // `Map<…>` or the explicit `globalThis.Map<…>`.\n const typeName = node.typeName.type === \"Identifier\" ? node.typeName.name : sourceCode.getText(node.typeName)\n\n if (typeName !== \"Map\" && typeName !== \"globalThis.Map\") return\n\n if (allowMutable && annotatesMutatedBinding(node, MAP_MUTATORS, context.sourceCode)) return\n\n if (node.typeName.type === \"Identifier\" && bindingOf(node.typeName, \"Map\", context.sourceCode) !== \"native\")\n 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 // Already imported under another name (`Map as FMap`): point at that name instead of adding a\n // second import that would shadow the native `Map` the rest of the file uses.\n const imported = functypeLocalName(sourceCode, \"Map\")\n const suggestions: Rule.SuggestionReportDescriptor[] =\n imported === null\n ? [{ messageId: \"suggestAddImport\", data: { symbol: \"Map\" }, fix: createImportFixer(sourceCode, \"Map\") }]\n : [\n {\n messageId: \"suggestUseLocalName\",\n data: { name: imported },\n fix: (fixer) => fixer.replaceText(node.typeName, imported),\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":"A,mdASA,MAAMU,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,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eAAe,QAAUA,EAAK,gBAAgB,OAChEY,EAAUD,IAAa,GAAKV,EAAW,QAAQU,EAAW,EAAE,EAAI,IAChEE,EAAYF,GAAcA,EAAW,QAAU,EAAIV,EAAW,QAAQU,EAAW,EAAE,EAAI,IAIvFT,EAAWnB,EAAkBkB,EAAY,KAAK,EAC9CI,EACJH,IAAa,KACT,CAAC,CAAE,UAAW,mBAAoB,KAAM,CAAE,OAAQ,KAAM,EAAG,IAAKf,EAAkBc,EAAY,KAAK,CAAE,CAAC,EACtG,CACE,CACE,UAAW,sBACX,KAAM,CAAE,KAAMC,CAAS,EACvB,IAAMI,GAAUA,EAAM,YAAYN,EAAK,SAAUE,CAAQ,CAC3D,CACF,EAENT,EAAQ,OAAO,CACbO,OACA,UAAW,oBACX,KAAM,CAAEY,UAASC,WAAU,EAC3B,QAASR,CACX,CAAC,CACH,CACF,CACF,CACF,E"}
@@ -1 +1 @@
1
- {"version":3,"file":"prefer-functype-set.js","names":["rule","options","context","allowInTests","allowMutable","isInTestFile","filename","functypeImports","getFunctypeImportsLegacy","node","bindingOf","isExplicitNativeCollection","isMutatedCollection","SET_MUTATORS","flowsIntoReadonlyContract","isAlreadyUsingFunctype","sourceCode","imported","functypeLocalName","name","args","suggestions","fixer","argsText","el","argText","createImportFixer","typeName","annotatesMutatedBinding","typeParamNode","typeParam"],"sources":["../../src/rules/prefer-functype-set.ts"],"sourcesContent":["import type { Rule } from \"eslint\"\n\nimport type { ASTNode } from \"../types/ast\"\nimport { bindingOf, functypeLocalName, isExplicitNativeCollection } from \"../utils/collection-binding\"\nimport { getFunctypeImportsLegacy, isAlreadyUsingFunctype } from \"../utils/functype-detection\"\nimport { createImportFixer } from \"../utils/import-fixer\"\nimport { annotatesMutatedBinding, isMutatedCollection, SET_MUTATORS } from \"../utils/mutable-collection\"\nimport { flowsIntoReadonlyContract } from \"../utils/readonly-contract\"\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 {{name}}.empty()\",\n suggestSetOf: \"Replace with {{name}}.of(...)\",\n suggestSetFrom: \"Replace with {{name}}(...)\",\n suggestUseLocalName: \"Replace with {{name}}\",\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 return {\n NewExpression(node: ASTNode) {\n if (allowInTests && isInTestFile()) return\n\n // The built-in, however it's spelled: bare `Set` that resolves to the global (functype's import\n // or a local shadow doesn't count, #350), or explicit `globalThis.Set` — the spelling the\n // functype-by-default convention uses, which must not be an escape hatch (#349).\n const isBareNative =\n node.callee?.type === \"Identifier\" &&\n node.callee.name === \"Set\" &&\n bindingOf(node.callee, \"Set\", context.sourceCode) === \"native\"\n if (!isBareNative && !isExplicitNativeCollection(node.callee, \"Set\", context.sourceCode)) return\n\n if (allowMutable && isMutatedCollection(node, SET_MUTATORS, context.sourceCode)) return\n\n // A native Set flowing into a declared `ReadonlySet` contract is what that contract requires (#350).\n if (flowsIntoReadonlyContract(node, \"ReadonlySet\")) return\n\n // Skip if already in a functype context\n if (isAlreadyUsingFunctype(node, functypeImports)) return\n\n const sourceCode = context.sourceCode\n const imported = functypeLocalName(sourceCode, \"Set\")\n const name = imported ?? \"Set\"\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 data: { name },\n fix(fixer) {\n return fixer.replaceText(node, `${name}.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 data: { name },\n fix(fixer) {\n return fixer.replaceText(node, `${name}.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 data: { name },\n fix(fixer) {\n return fixer.replaceText(node, `${name}(${argText})`)\n },\n })\n } else {\n // Fallback for unexpected cases\n suggestions.push({\n messageId: \"suggestSetEmpty\",\n data: { name },\n fix(fixer) {\n return fixer.replaceText(node, `${name}.empty()`)\n },\n })\n }\n\n if (imported === null) {\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 // `Set<…>` or the explicit `globalThis.Set<…>`.\n const typeName = node.typeName.type === \"Identifier\" ? node.typeName.name : sourceCode.getText(node.typeName)\n\n if (typeName !== \"Set\" && typeName !== \"globalThis.Set\") return\n\n if (allowMutable && annotatesMutatedBinding(node, SET_MUTATORS, context.sourceCode)) return\n\n if (node.typeName.type === \"Identifier\" && bindingOf(node.typeName, \"Set\", context.sourceCode) !== \"native\")\n 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 // Already imported under another name (`Set as FSet`): point at that name instead of adding a\n // second import that would shadow the native `Set` the rest of the file uses.\n const imported = functypeLocalName(sourceCode, \"Set\")\n const suggestions: Rule.SuggestionReportDescriptor[] =\n imported === null\n ? [{ messageId: \"suggestAddImport\", data: { symbol: \"Set\" }, fix: createImportFixer(sourceCode, \"Set\") }]\n : [\n {\n messageId: \"suggestUseLocalName\",\n data: { name: imported },\n fix: (fixer) => fixer.replaceText(node.typeName, imported),\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":"A,mdASA,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,gCACjB,aAAc,gCACd,eAAgB,6BAChB,oBAAqB,wBACrB,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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,EAAQ,OAAO,CACb,OACA,UAAW,oBACX,KAAM,CAAE,KAAM4B,CAAU,EACxB,QAAST,CACX,CAAC,CACH,CACF,CACF,CACF,E"}
1
+ {"version":3,"file":"prefer-functype-set.js","names":["bindingOf","functypeLocalName","isExplicitNativeCollection","getFunctypeImportsLegacy","isAlreadyUsingFunctype","createImportFixer","SET_MUTATORS","annotatesMutatedBinding","isMutatedCollection","flowsIntoReadonlyContract","rule","context","options","allowInTests","allowMutable","isInTestFile","filename","functypeImports","node","sourceCode","imported","name","args","suggestions","fixer","argsText","el","argText","typeName","typeParamNode","typeParam"],"sources":["../../src/rules/prefer-functype-set.ts"],"sourcesContent":["import type { Rule } from \"eslint\"\n\nimport type { ASTNode } from \"../types/ast\"\nimport { bindingOf, functypeLocalName, isExplicitNativeCollection } from \"../utils/collection-binding\"\nimport { getFunctypeImportsLegacy, isAlreadyUsingFunctype } from \"../utils/functype-detection\"\nimport { createImportFixer } from \"../utils/import-fixer\"\nimport { annotatesMutatedBinding, isMutatedCollection, SET_MUTATORS } from \"../utils/mutable-collection\"\nimport { flowsIntoReadonlyContract } from \"../utils/readonly-contract\"\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 {{name}}.empty()\",\n suggestSetOf: \"Replace with {{name}}.of(...)\",\n suggestSetFrom: \"Replace with {{name}}(...)\",\n suggestUseLocalName: \"Replace with {{name}}\",\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 return {\n NewExpression(node: ASTNode) {\n if (allowInTests && isInTestFile()) return\n\n // The built-in, however it's spelled: bare `Set` that resolves to the global (functype's import\n // or a local shadow doesn't count, #350), or explicit `globalThis.Set` — the spelling the\n // functype-by-default convention uses, which must not be an escape hatch (#349).\n const isBareNative =\n node.callee?.type === \"Identifier\" &&\n node.callee.name === \"Set\" &&\n bindingOf(node.callee, \"Set\", context.sourceCode) === \"native\"\n if (!isBareNative && !isExplicitNativeCollection(node.callee, \"Set\", context.sourceCode)) return\n\n if (allowMutable && isMutatedCollection(node, SET_MUTATORS, context.sourceCode)) return\n\n // A native Set flowing into a declared `ReadonlySet` contract is what that contract requires (#350).\n if (flowsIntoReadonlyContract(node, \"ReadonlySet\")) return\n\n // Skip if already in a functype context\n if (isAlreadyUsingFunctype(node, functypeImports)) return\n\n const sourceCode = context.sourceCode\n const imported = functypeLocalName(sourceCode, \"Set\")\n const name = imported ?? \"Set\"\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 data: { name },\n fix(fixer) {\n return fixer.replaceText(node, `${name}.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 data: { name },\n fix(fixer) {\n return fixer.replaceText(node, `${name}.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 data: { name },\n fix(fixer) {\n return fixer.replaceText(node, `${name}(${argText})`)\n },\n })\n } else {\n // Fallback for unexpected cases\n suggestions.push({\n messageId: \"suggestSetEmpty\",\n data: { name },\n fix(fixer) {\n return fixer.replaceText(node, `${name}.empty()`)\n },\n })\n }\n\n if (imported === null) {\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 // `Set<…>` or the explicit `globalThis.Set<…>`.\n const typeName = node.typeName.type === \"Identifier\" ? node.typeName.name : sourceCode.getText(node.typeName)\n\n if (typeName !== \"Set\" && typeName !== \"globalThis.Set\") return\n\n if (allowMutable && annotatesMutatedBinding(node, SET_MUTATORS, context.sourceCode)) return\n\n if (node.typeName.type === \"Identifier\" && bindingOf(node.typeName, \"Set\", context.sourceCode) !== \"native\")\n 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 // Already imported under another name (`Set as FSet`): point at that name instead of adding a\n // second import that would shadow the native `Set` the rest of the file uses.\n const imported = functypeLocalName(sourceCode, \"Set\")\n const suggestions: Rule.SuggestionReportDescriptor[] =\n imported === null\n ? [{ messageId: \"suggestAddImport\", data: { symbol: \"Set\" }, fix: createImportFixer(sourceCode, \"Set\") }]\n : [\n {\n messageId: \"suggestUseLocalName\",\n data: { name: imported },\n fix: (fixer) => fixer.replaceText(node.typeName, imported),\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":"A,mdASA,MAAMU,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,gCACjB,aAAc,gCACd,eAAgB,6BAChB,oBAAqB,wBACrB,iBAAkB,qCACpB,CACF,EAEA,OAAOC,EAAS,CACd,IAAMC,EAAUD,EAAQ,QAAQ,IAAM,CAAC,EACjCE,EAAeD,EAAQ,eAAiB,GAGxCE,EAAeF,EAAQ,eAAiB,GAE9C,SAASG,GAAe,CACtB,IAAMC,EAAWL,EAAQ,SACzB,MACE,kCAAkC,KAAKK,CAAQ,GAC/CA,EAAS,SAAS,WAAW,GAC7BA,EAAS,SAAS,QAAQ,GAC1BA,EAAS,SAAS,SAAS,CAE/B,CAEA,IAAMC,EAAkBd,EAAyBQ,CAAO,EAExD,MAAO,CACL,cAAcO,EAAe,CAkB3B,GAjBIL,GAAgBE,EAAa,IAM/BG,EAAK,QAAQ,OAAS,cACtBA,EAAK,OAAO,OAAS,OACrBlB,EAAUkB,EAAK,OAAQ,MAAOP,EAAQ,UAAU,IAAM,WACnC,CAACT,EAA2BgB,EAAK,OAAQ,MAAOP,EAAQ,UAAU,GAEnFG,GAAgBN,EAAoBU,EAAMZ,EAAcK,EAAQ,UAAU,GAG1EF,EAA0BS,EAAM,aAAa,GAG7Cd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