eslint-plugin-functype 2.200.0 → 2.201.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +30 -2
- package/dist/cli/list-rules.js.map +1 -1
- package/dist/configs/recommended.d.ts +5 -1
- package/dist/configs/recommended.js +1 -1
- package/dist/configs/recommended.js.map +1 -1
- package/dist/index.d.ts +1 -0
- package/dist/index.js +1 -1
- package/dist/index.js.map +1 -1
- package/dist/rules/collection-naming.js.map +1 -1
- package/dist/rules/index.d.ts +13 -11
- package/dist/rules/index.js +1 -1
- package/dist/rules/index.js.map +1 -1
- package/dist/rules/must-fold-on-component-return.js.map +1 -1
- package/dist/rules/no-array-mutation.js.map +1 -1
- package/dist/rules/no-floating-io.js.map +1 -1
- package/dist/rules/no-floating-result.js.map +1 -1
- package/dist/rules/no-get-unsafe.js.map +1 -1
- package/dist/rules/no-getOrThrow-in-render.js.map +1 -1
- package/dist/rules/no-imperative-loops.js.map +1 -1
- package/dist/rules/no-let.js.map +1 -1
- package/dist/rules/no-serialize-container.js.map +1 -1
- package/dist/rules/no-uncalled-method.d.ts +16 -0
- package/dist/rules/no-uncalled-method.js +2 -0
- package/dist/rules/no-uncalled-method.js.map +1 -0
- package/dist/rules/prefer-do-notation.js +1 -1
- package/dist/rules/prefer-do-notation.js.map +1 -1
- package/dist/rules/prefer-either.js.map +1 -1
- package/dist/rules/prefer-flatmap.js.map +1 -1
- package/dist/rules/prefer-fold.js +1 -1
- package/dist/rules/prefer-fold.js.map +1 -1
- package/dist/rules/prefer-functype-map.js.map +1 -1
- package/dist/rules/prefer-functype-set.js.map +1 -1
- package/dist/rules/prefer-list.js.map +1 -1
- package/dist/rules/prefer-map.js.map +1 -1
- package/dist/rules/prefer-option.js.map +1 -1
- package/dist/rules/prefer-try.js.map +1 -1
- package/dist/utils/array-mutation.d.ts +1 -1
- package/dist/utils/array-mutation.js.map +1 -1
- package/dist/utils/ast-walk.js.map +1 -1
- package/dist/utils/async-detection.js.map +1 -1
- package/dist/utils/boundary-tags.d.ts +1 -1
- package/dist/utils/boundary-tags.js.map +1 -1
- package/dist/utils/collection-binding.d.ts +1 -1
- package/dist/utils/collection-binding.js.map +1 -1
- package/dist/utils/dependency-validator.js.map +1 -1
- package/dist/utils/functype-detection.d.ts +1 -1
- package/dist/utils/functype-detection.js.map +1 -1
- package/dist/utils/functype-predicates.d.ts +1 -1
- package/dist/utils/functype-predicates.js.map +1 -1
- package/dist/utils/host-throws.d.ts +1 -1
- package/dist/utils/host-throws.js.map +1 -1
- package/dist/utils/import-fixer.js.map +1 -1
- package/dist/utils/mutable-collection.d.ts +1 -1
- package/dist/utils/mutable-collection.js.map +1 -1
- package/dist/utils/react-render.js.map +1 -1
- package/dist/utils/readonly-contract.js.map +1 -1
- package/dist/utils/type-aware.d.ts +13 -1
- package/dist/utils/type-aware.js +1 -1
- package/dist/utils/type-aware.js.map +1 -1
- package/dist/utils/wire-types.js.map +1 -1
- package/package.json +3 -3
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"prefer-map.js","names":["ITERATION_METHOD_NAMES","insideIterationCallback","parent","node","rule","options","context","checkArrayMethods","checkForLoops","isForEachToMapSafe","callback","isTransformationLoop","statements","stmt","call","isSimplePropertyAccess","suspends","containsAwait","containsYield","fixedText","fixer"],"sources":["../../src/rules/prefer-map.ts"],"sourcesContent":["import type { Rule } from \"eslint\"\n\nimport type { ASTNode } from \"../types/ast\"\nimport { containsAwait, containsYield } from \"../utils/async-detection\"\n\nconst ITERATION_METHOD_NAMES: ReadonlySet<string> = new Set([\"forEach\", \"for\"])\n\n/** True iff any ancestor of `node` is a `.forEach(...)` or `.for(...)` call. */\nfunction insideIterationCallback(node: ASTNode | null | undefined): boolean {\n const parent = node?.parent as ASTNode | undefined\n if (!parent) return false\n if (\n parent.type === \"CallExpression\" &&\n parent.callee.type === \"MemberExpression\" &&\n ITERATION_METHOD_NAMES.has(parent.callee.property.name)\n ) {\n return true\n }\n return insideIterationCallback(parent)\n}\n\nconst rule: Rule.RuleModule = {\n meta: {\n type: \"suggestion\",\n docs: {\n description: \"Prefer .map() over manual transformations and imperative patterns\",\n recommended: true,\n },\n fixable: \"code\",\n schema: [\n {\n type: \"object\",\n properties: {\n checkArrayMethods: {\n type: \"boolean\",\n default: true,\n },\n checkForLoops: {\n type: \"boolean\",\n default: false,\n },\n },\n additionalProperties: false,\n },\n ],\n messages: {\n preferMapOverLoop: \"Prefer .map() over for loop for transforming {{collection}}\",\n preferMapOverPush: \"Prefer .map() over manual .push() in loop\",\n preferMapChain: \"Consider using .map() for transformation instead of manual property access\",\n },\n },\n\n create(context) {\n const options = context.options[0] || {}\n const checkArrayMethods = options.checkArrayMethods !== false\n // Off by default (#325): no-imperative-loops already reports every loop, and reporting the same loop\n // here too doubled each hit. Opt in when no-imperative-loops is disabled.\n const checkForLoops = options.checkForLoops === true\n\n function isForEachToMapSafe(node: ASTNode): boolean {\n // Only auto-fix simple forEach → map transformations on expressions that return values\n // This is safe because both native arrays and functype Lists have these methods\n if (\n node.type !== \"CallExpression\" ||\n node.callee.type !== \"MemberExpression\" ||\n node.callee.property.name !== \"forEach\"\n ) {\n return false\n }\n\n // Check if the callback returns a value (simple property access pattern)\n const callback = node.arguments[0]\n if (callback && (callback.type === \"ArrowFunctionExpression\" || callback.type === \"FunctionExpression\")) {\n const body = callback.body\n // Simple property access in arrow function (e.g., item => item.name)\n return body.type === \"MemberExpression\"\n }\n return false\n }\n\n function isTransformationLoop(node: ASTNode): boolean {\n if (!node.body || node.body.type !== \"BlockStatement\") return false\n\n const statements = node.body.body\n if (statements.length === 0) return false\n\n // Look for patterns like: newArray.push(transform(item))\n return statements.some((stmt: ASTNode) => {\n if (stmt.type === \"ExpressionStatement\" && stmt.expression.type === \"CallExpression\") {\n const call = stmt.expression\n return call.callee.type === \"MemberExpression\" && call.callee.property.name === \"push\"\n }\n return false\n })\n }\n\n function isSimplePropertyAccess(node: ASTNode): boolean {\n // Check for patterns like: items.forEach(item => console.log(item.name))\n // These could often be: items.map(item => item.name)\n if (\n node.type === \"CallExpression\" &&\n node.callee.type === \"MemberExpression\" &&\n node.callee.property.name === \"forEach\"\n ) {\n const callback = node.arguments[0]\n if (callback && (callback.type === \"ArrowFunctionExpression\" || callback.type === \"FunctionExpression\")) {\n const body = callback.body\n // Simple property access in arrow function\n if (body.type === \"MemberExpression\") {\n return true\n }\n }\n }\n return false\n }\n\n function suspends(node: ASTNode): boolean {\n return node.await === true || containsAwait(node.body) || containsYield(node.body)\n }\n\n return {\n ForStatement(node: ASTNode) {\n if (!checkForLoops) return\n\n // An awaiting loop is a sequential traversal, not a map: `.map` cannot await (#323), and neither a\n // `for await` stream nor a generator's yielding loop has a .map form (#324).\n if (isTransformationLoop(node) && !suspends(node)) {\n context.report({\n node,\n messageId: \"preferMapOverLoop\",\n data: { collection: \"array\" },\n })\n }\n },\n\n ForInStatement(node: ASTNode) {\n if (!checkForLoops) return\n\n // An awaiting loop is a sequential traversal, not a map: `.map` cannot await (#323), and neither a\n // `for await` stream nor a generator's yielding loop has a .map form (#324).\n if (isTransformationLoop(node) && !suspends(node)) {\n context.report({\n node,\n messageId: \"preferMapOverLoop\",\n data: { collection: \"object\" },\n })\n }\n },\n\n ForOfStatement(node: ASTNode) {\n if (!checkForLoops) return\n\n // An awaiting loop is a sequential traversal, not a map: `.map` cannot await (#323), and neither a\n // `for await` stream nor a generator's yielding loop has a .map form (#324).\n if (isTransformationLoop(node) && !suspends(node)) {\n context.report({\n node,\n messageId: \"preferMapOverLoop\",\n data: { collection: \"iterable\" },\n })\n }\n },\n\n CallExpression(node: ASTNode) {\n if (!checkArrayMethods) return\n\n // Check for forEach that could be map\n if (node.callee.type === \"MemberExpression\" && node.callee.property.name === \"forEach\") {\n if (isSimplePropertyAccess(node)) {\n context.report({\n node,\n messageId: \"preferMapChain\",\n fix(fixer) {\n // Only auto-fix safe forEach → map transformations\n if (!isForEachToMapSafe(node)) {\n return null\n }\n\n const sourceCode = context.sourceCode\n const text = sourceCode.getText(node)\n\n // Simple replacement: forEach -> map\n const fixedText = text.replace(/\\.forEach\\s*\\(/g, \".map(\")\n return fixer.replaceText(node, fixedText)\n },\n })\n }\n }\n\n // Check for manual push patterns in callbacks\n if (\n node.callee.type === \"MemberExpression\" &&\n node.callee.property.name === \"push\" &&\n insideIterationCallback(node)\n ) {\n context.report({ node, messageId: \"preferMapOverPush\" })\n }\n },\n }\n },\n}\n\nexport default rule\n"],"mappings":"A,+EAKA,MAAMA,kBAA8C,IAAI,IAAI,CAAC,UAAW,KAAK,CAAC,EAG9E,SAASC,EAAwB,EAA2C,CAC1E,IAAMC,EAASC,GAAM,OASrB,OARKD,EAEHA,EAAO,OAAS,kBAChBA,EAAO,OAAO,OAAS,oBACvBF,EAAuB,IAAIE,EAAO,OAAO,SAAS,IAAI,EAE/C,GAEFD,EAAwBC,CAAM,EARjB,EAStB,CAEA,MAAME,EAAwB,CAC5B,KAAM,CACJ,KAAM,aACN,KAAM,CACJ,YAAa,oEACb,YAAa,EACf,EACA,QAAS,OACT,OAAQ,CACN,CACE,KAAM,SACN,WAAY,CACV,kBAAmB,CACjB,KAAM,UACN,QAAS,EACX,EACA,cAAe,CACb,KAAM,UACN,QAAS,EACX,CACF,EACA,qBAAsB,EACxB,CACF,EACA,SAAU,CACR,kBAAmB,8DACnB,kBAAmB,4CACnB,eAAgB,4EAClB,CACF,EAEA,OAAO,EAAS,CACd,IAAMC,EAAUC,EAAQ,QAAQ,IAAM,CAAC,EACjCC,EAAoBF,EAAQ,oBAAsB,GAGlDG,EAAgBH,EAAQ,gBAAkB,GAEhD,SAASI,EAAmB,EAAwB,CAGlD,GACEN,EAAK,OAAS,kBACdA,EAAK,OAAO,OAAS,oBACrBA,EAAK,OAAO,SAAS,OAAS,UAE9B,MAAO,GAIT,IAAMO,EAAWP,EAAK,UAAU,GAMhC,OALIO,IAAaA,EAAS,OAAS,2BAA6BA,EAAS,OAAS,sBACnEA,EAAS,KAEV,OAAS,mBA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AEA,eAAe,EAAe,CACvBC,IAGDJ,EAAK,OAAO,OAAS,oBAAsBA,EAAK,OAAO,SAAS,OAAS,WACvEY,EAAuBZ,CAAI,GAC7BG,EAAQ,OAAO,CACb,OACA,UAAW,iBACX,IAAI,EAAO,CAET,GAAI,CAACG,EAAmBN,CAAI,EAC1B,OAAO,KAOT,IAAMgB,EAJab,EAAQ,WACH,QAAQH,CAGX,CAAC,CAAC,QAAQ,kBAAmB,OAAO,EACzD,OAAOiB,EAAM,YAAYjB,EAAMgB,CAAS,CAC1C,CACF,CAAC,EAMHhB,EAAK,OAAO,OAAS,oBACrBA,EAAK,OAAO,SAAS,OAAS,QAC9BF,EAAwBE,CAAI,GAE5BG,EAAQ,OAAO,CAAE,OAAM,UAAW,mBAAoB,CAAC,EAE3D,CACF,CACF,CACF,E"}
|
|
1
|
+
{"version":3,"file":"prefer-map.js","names":["containsAwait","containsYield","ITERATION_METHOD_NAMES","insideIterationCallback","node","parent","rule","context","options","checkArrayMethods","checkForLoops","isForEachToMapSafe","callback","isTransformationLoop","statements","stmt","call","isSimplePropertyAccess","suspends","fixer","fixedText"],"sources":["../../src/rules/prefer-map.ts"],"sourcesContent":["import type { Rule } from \"eslint\"\n\nimport type { ASTNode } from \"../types/ast\"\nimport { containsAwait, containsYield } from \"../utils/async-detection\"\n\nconst ITERATION_METHOD_NAMES: ReadonlySet<string> = new Set([\"forEach\", \"for\"])\n\n/** True iff any ancestor of `node` is a `.forEach(...)` or `.for(...)` call. */\nfunction insideIterationCallback(node: ASTNode | null | undefined): boolean {\n const parent = node?.parent as ASTNode | undefined\n if (!parent) return false\n if (\n parent.type === \"CallExpression\" &&\n parent.callee.type === \"MemberExpression\" &&\n ITERATION_METHOD_NAMES.has(parent.callee.property.name)\n ) {\n return true\n }\n return insideIterationCallback(parent)\n}\n\nconst rule: Rule.RuleModule = {\n meta: {\n type: \"suggestion\",\n docs: {\n description: \"Prefer .map() over manual transformations and imperative patterns\",\n recommended: true,\n },\n fixable: \"code\",\n schema: [\n {\n type: \"object\",\n properties: {\n checkArrayMethods: {\n type: \"boolean\",\n default: true,\n },\n checkForLoops: {\n type: \"boolean\",\n default: false,\n },\n },\n additionalProperties: false,\n },\n ],\n messages: {\n preferMapOverLoop: \"Prefer .map() over for loop for transforming {{collection}}\",\n preferMapOverPush: \"Prefer .map() over manual .push() in loop\",\n preferMapChain: \"Consider using .map() for transformation instead of manual property access\",\n },\n },\n\n create(context) {\n const options = context.options[0] || {}\n const checkArrayMethods = options.checkArrayMethods !== false\n // Off by default (#325): no-imperative-loops already reports every loop, and reporting the same loop\n // here too doubled each hit. Opt in when no-imperative-loops is disabled.\n const checkForLoops = options.checkForLoops === true\n\n function isForEachToMapSafe(node: ASTNode): boolean {\n // Only auto-fix simple forEach → map transformations on expressions that return values\n // This is safe because both native arrays and functype Lists have these methods\n if (\n node.type !== \"CallExpression\" ||\n node.callee.type !== \"MemberExpression\" ||\n node.callee.property.name !== \"forEach\"\n ) {\n return false\n }\n\n // Check if the callback returns a value (simple property access pattern)\n const callback = node.arguments[0]\n if (callback && (callback.type === \"ArrowFunctionExpression\" || callback.type === \"FunctionExpression\")) {\n const body = callback.body\n // Simple property access in arrow function (e.g., item => item.name)\n return body.type === \"MemberExpression\"\n }\n return false\n }\n\n function isTransformationLoop(node: ASTNode): boolean {\n if (!node.body || node.body.type !== \"BlockStatement\") return false\n\n const statements = node.body.body\n if (statements.length === 0) return false\n\n // Look for patterns like: newArray.push(transform(item))\n return statements.some((stmt: ASTNode) => {\n if (stmt.type === \"ExpressionStatement\" && stmt.expression.type === \"CallExpression\") {\n const call = stmt.expression\n return call.callee.type === \"MemberExpression\" && call.callee.property.name === \"push\"\n }\n return false\n })\n }\n\n function isSimplePropertyAccess(node: ASTNode): boolean {\n // Check for patterns like: items.forEach(item => console.log(item.name))\n // These could often be: items.map(item => item.name)\n if (\n node.type === \"CallExpression\" &&\n node.callee.type === \"MemberExpression\" &&\n node.callee.property.name === \"forEach\"\n ) {\n const callback = node.arguments[0]\n if (callback && (callback.type === \"ArrowFunctionExpression\" || callback.type === \"FunctionExpression\")) {\n const body = callback.body\n // Simple property access in arrow function\n if (body.type === \"MemberExpression\") {\n return true\n }\n }\n }\n return false\n }\n\n function suspends(node: ASTNode): boolean {\n return node.await === true || containsAwait(node.body) || containsYield(node.body)\n }\n\n return {\n ForStatement(node: ASTNode) {\n if (!checkForLoops) return\n\n // An awaiting loop is a sequential traversal, not a map: `.map` cannot await (#323), and neither a\n // `for await` stream nor a generator's yielding loop has a .map form (#324).\n if (isTransformationLoop(node) && !suspends(node)) {\n context.report({\n node,\n messageId: \"preferMapOverLoop\",\n data: { collection: \"array\" },\n })\n }\n },\n\n ForInStatement(node: ASTNode) {\n if (!checkForLoops) return\n\n // An awaiting loop is a sequential traversal, not a map: `.map` cannot await (#323), and neither a\n // `for await` stream nor a generator's yielding loop has a .map form (#324).\n if (isTransformationLoop(node) && !suspends(node)) {\n context.report({\n node,\n messageId: \"preferMapOverLoop\",\n data: { collection: \"object\" },\n })\n }\n },\n\n ForOfStatement(node: ASTNode) {\n if (!checkForLoops) return\n\n // An awaiting loop is a sequential traversal, not a map: `.map` cannot await (#323), and neither a\n // `for await` stream nor a generator's yielding loop has a .map form (#324).\n if (isTransformationLoop(node) && !suspends(node)) {\n context.report({\n node,\n messageId: \"preferMapOverLoop\",\n data: { collection: \"iterable\" },\n })\n }\n },\n\n CallExpression(node: ASTNode) {\n if (!checkArrayMethods) return\n\n // Check for forEach that could be map\n if (node.callee.type === \"MemberExpression\" && node.callee.property.name === \"forEach\") {\n if (isSimplePropertyAccess(node)) {\n context.report({\n node,\n messageId: \"preferMapChain\",\n fix(fixer) {\n // Only auto-fix safe forEach → map transformations\n if (!isForEachToMapSafe(node)) {\n return null\n }\n\n const sourceCode = context.sourceCode\n const text = sourceCode.getText(node)\n\n // Simple replacement: forEach -> map\n const fixedText = text.replace(/\\.forEach\\s*\\(/g, \".map(\")\n return fixer.replaceText(node, fixedText)\n },\n })\n }\n }\n\n // Check for manual push patterns in callbacks\n if (\n node.callee.type === \"MemberExpression\" &&\n node.callee.property.name === \"push\" &&\n insideIterationCallback(node)\n ) {\n context.report({ node, messageId: \"preferMapOverPush\" })\n }\n },\n }\n },\n}\n\nexport default rule\n"],"mappings":"A,+EAKA,MAAME,kBAA8C,IAAI,IAAI,CAAC,UAAW,KAAK,CAAC,EAG9E,SAASC,EAAwBC,EAA2C,CAC1E,IAAMC,EAASD,GAAM,OASrB,OARKC,EAEHA,EAAO,OAAS,kBAChBA,EAAO,OAAO,OAAS,oBACvBH,EAAuB,IAAIG,EAAO,OAAO,SAAS,IAAI,EAE/C,GAEFF,EAAwBE,CAAM,EARjB,EAStB,CAEA,MAAMC,EAAwB,CAC5B,KAAM,CACJ,KAAM,aACN,KAAM,CACJ,YAAa,oEACb,YAAa,EACf,EACA,QAAS,OACT,OAAQ,CACN,CACE,KAAM,SACN,WAAY,CACV,kBAAmB,CACjB,KAAM,UACN,QAAS,EACX,EACA,cAAe,CACb,KAAM,UACN,QAAS,EACX,CACF,EACA,qBAAsB,EACxB,CACF,EACA,SAAU,CACR,kBAAmB,8DACnB,kBAAmB,4CACnB,eAAgB,4EAClB,CACF,EAEA,OAAOC,EAAS,CACd,IAAMC,EAAUD,EAAQ,QAAQ,IAAM,CAAC,EACjCE,EAAoBD,EAAQ,oBAAsB,GAGlDE,EAAgBF,EAAQ,gBAAkB,GAEhD,SAASG,EAAmBP,EAAwB,CAGlD,GACEA,EAAK,OAAS,kBACdA,EAAK,OAAO,OAAS,oBACrBA,EAAK,OAAO,SAAS,OAAS,UAE9B,MAAO,GAIT,IAAMQ,EAAWR,EAAK,UAAU,GAMhC,OALIQ,IAAaA,EAAS,OAAS,2BAA6BA,EAAS,OAAS,sBACnEA,EAAS,KAEV,OAAS,mBAEhB,EACT,CAEA,SAASC,EAAqBT,EAAwB,CACpD,GAAI,CAACA,EAAK,MAAQA,EAAK,KAAK,OAAS,iBAAkB,MAAO,GAE9D,IAAMU,EAAaV,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7BG,EAAQ,OAAO,CACbH,OACA,UAAW,iBACX,IAAIe,EAAO,CAET,GAAI,CAACR,EAAmBP,CAAI,EAC1B,OAAO,KAOT,IAAMgB,EAJab,EAAQ,WACH,QAAQH,CAGX,CAAC,CAAC,QAAQ,kBAAmB,OAAO,EACzD,OAAOe,EAAM,YAAYf,EAAMgB,CAAS,CAC1C,CACF,CAAC,EAMHhB,EAAK,OAAO,OAAS,oBACrBA,EAAK,OAAO,SAAS,OAAS,QAC9BD,EAAwBC,CAAI,GAE5BG,EAAQ,OAAO,CAAEH,OAAM,UAAW,mBAAoB,CAAC,EAE3D,CACF,CACF,CACF,E"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"prefer-option.js","names":["REACT_STATE_HOOKS","isNullish","type","isParameter","parent","node","params","memberOrParameterOf","owner","annotation","unionMembers","union","t","threeStateSpellings","members","member","rule","WIRE_TYPES_SCHEMA","options","context","wireTypes","DEFAULT_WIRE_TYPES","allowInteropMarker","isExemptByMarker","isInsideTaggedDeclaration","allowUseState","checkOptionalMembers","isInHookTypeArgument","callee","name","functypeImports","getFunctypeImportsLegacy","checkOptional","isInsideWireType","isFunctypeType","kept","key","direct","undefinedOnly","nonNullTypes","nonNullType","isAlreadyUsingFunctype","sourceCode","nonNullTypeText","fullType","drop","suggestions","fixer","hasFunctypeSymbol","createImportFixer"],"sources":["../../src/rules/prefer-option.ts"],"sourcesContent":["import type { Rule } from \"eslint\"\n\nimport type { ASTNode } from \"../types/ast\"\nimport { INTEROP_TAG, isInsideTaggedDeclaration } from \"../utils/boundary-tags\"\nimport { getFunctypeImportsLegacy, isAlreadyUsingFunctype, isFunctypeType } from \"../utils/functype-detection\"\nimport { createImportFixer, hasFunctypeSymbol } from \"../utils/import-fixer\"\nimport { DEFAULT_WIRE_TYPES, isInsideWireType, WIRE_TYPES_SCHEMA } from \"../utils/wire-types\"\n\nconst REACT_STATE_HOOKS: ReadonlySet<string> = new Set([\"useState\", \"useRef\"])\n\nconst isNullish = (type: ASTNode): boolean => type.type === \"TSNullKeyword\" || type.type === \"TSUndefinedKeyword\"\n\n/** Is `node` a parameter: of a function, a method signature or a function type, with or without a default? */\nfunction isParameter(node: ASTNode): boolean {\n const parent = node.parent as ASTNode | undefined\n if (!parent) return false\n if (parent.type === \"AssignmentPattern\" && parent.left === node) return isParameter(parent)\n if (parent.type === \"TSParameterProperty\") return true\n const params = (parent as { readonly params?: ReadonlyArray<ASTNode> }).params\n return Array.isArray(params) && params.includes(node)\n}\n\n/**\n * The member or parameter a type annotation belongs to, when it's the annotation of a type-literal or\n * interface member (`b: string | undefined`) or a parameter (`(x: string | undefined) => …`). Those are\n * the caller's shapes: a prop, an options-bag field, an argument (#446).\n */\nfunction memberOrParameterOf(annotation: ASTNode | undefined): ASTNode | undefined {\n const owner = annotation?.type === \"TSTypeAnnotation\" ? (annotation.parent as ASTNode | undefined) : undefined\n if (!owner) return undefined\n if (owner.type === \"TSPropertySignature\") return owner\n return isParameter(owner) ? owner : undefined\n}\n\n/**\n * A union's members, with nested unions spread in. The parser drops parentheses, so `(A | null) | undefined`\n * is a union holding a union; spread, it holds A, null and undefined.\n */\nfunction unionMembers(union: ASTNode): ReadonlyArray<ASTNode> {\n return union.types.flatMap((t: ASTNode) => (t.type === \"TSUnionType\" ? unionMembers(t) : [t]))\n}\n\n/**\n * Does a nullable union describe a three-state shape? Left out, cleared and set are three states, and\n * `Option` has two (#448). That's a type alias's body or a type-literal or interface member holding both\n * `null` and `undefined`, or an optional member that can also be `null` (`a?: T | null`). A parameter is a\n * converter's input and a return type is a result, so neither counts.\n *\n * Returns the two spellings of \"absent\" the type uses, for the message to say which to drop, or `undefined`\n * when the union isn't a three-state shape.\n */\nfunction threeStateSpellings(union: ASTNode, members: ReadonlyArray<ASTNode>): string | undefined {\n if (!members.some((t) => t.type === \"TSNullKeyword\")) return undefined\n const parent = union.parent as ASTNode | undefined\n const owner = parent?.type === \"TSTypeAnnotation\" ? (parent.parent as ASTNode | undefined) : undefined\n const member = owner?.type === \"TSPropertySignature\" ? owner : undefined\n if (member?.optional === true) return \"the ? or the | null\"\n if (!members.some((t) => t.type === \"TSUndefinedKeyword\")) return undefined\n return parent?.type === \"TSTypeAliasDeclaration\" || member !== undefined ? \"the | null or the | undefined\" : undefined\n}\n\nconst rule: Rule.RuleModule = {\n meta: {\n type: \"suggestion\",\n hasSuggestions: true,\n docs: {\n description: \"Prefer Option<T> over nullable types (T | null | undefined)\",\n recommended: true,\n },\n schema: [\n {\n type: \"object\",\n properties: {\n allowInteropMarker: {\n type: \"boolean\",\n default: true,\n },\n wireTypes: WIRE_TYPES_SCHEMA,\n allowNullableIntersections: {\n type: \"boolean\",\n default: false,\n },\n allowUseState: {\n type: \"boolean\",\n default: true,\n },\n checkOptionalMembers: {\n type: \"boolean\",\n default: false,\n },\n },\n additionalProperties: false,\n },\n ],\n messages: {\n preferOption:\n \"Prefer Option<{{type}}> over nullable type '{{nullable}}'. If this is a row, body or payload shape, wrap the type in Wire<…>\",\n preferOptionReturn: \"Prefer Option<{{type}}> as return type over nullable '{{nullable}}'\",\n preferOptionOverOptional:\n \"Prefer '{{name}}: Option<{{type}}>' over the optional '{{name}}?'. If this is a row, body or payload shape, wrap the type in Wire<…>\",\n preferWireForThreeStates:\n 'This type has three states, left out, null and set, and Option holds two. If it\\'s a row, body or payload shape, wrap the type in Wire<…>. If it only meant \"may be absent\", drop {{drop}} and use Option<{{type}}>',\n suggestOptionType: \"Replace with Option<{{type}}>\",\n suggestAddImport: \"Add {{symbol}} import from functype\",\n },\n },\n\n create(context) {\n const options = context.options[0] || {}\n // Everything inside `Wire<…>` is the declared serialization shape (#325 B).\n const wireTypes: ReadonlyArray<string> = options.wireTypes ?? DEFAULT_WIRE_TYPES\n // `@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 // `null` is idiomatic React state (`useState<User | null>(null)`, `useRef<El | null>(null)`); an\n // Option in a hook's type argument buys nothing and fights the hook's own API (#325).\n const allowUseState = options.allowUseState !== false\n // `a?: T` and `a: T | undefined` on a member or parameter both mean \"may be absent\", and the caller\n // writes `<X b=\"v\" />` or `f()`. Skip both unless asked to report them (#446).\n const checkOptionalMembers = options.checkOptionalMembers === true\n\n /** Is `node` inside the type argument of a `useState` / `useRef` call (bare or `React.`-qualified)? */\n function isInHookTypeArgument(node: ASTNode): boolean {\n const parent = node.parent\n if (!parent) return false\n if (parent.type === \"TSTypeParameterInstantiation\" && parent.parent?.type === \"CallExpression\") {\n const callee = parent.parent.callee\n const name =\n callee.type === \"Identifier\"\n ? callee.name\n : callee.type === \"MemberExpression\" && callee.property.type === \"Identifier\"\n ? callee.property.name\n : null\n if (name !== null && REACT_STATE_HOOKS.has(name)) return true\n }\n return isInHookTypeArgument(parent)\n }\n\n // Get functype imports if available (but still apply rule even without explicit import)\n const functypeImports = getFunctypeImportsLegacy(context)\n\n /** With checkOptionalMembers, `a?: T` on a member or parameter is reported like `a: T | undefined`. */\n function checkOptional(node: ASTNode): void {\n if (!checkOptionalMembers || node.optional !== true) return\n if (node.type !== \"TSPropertySignature\" && !isParameter(node)) return\n if (isInsideWireType(node, wireTypes) || isExemptByMarker(node)) return\n const annotation = (node.typeAnnotation as ASTNode | undefined)?.typeAnnotation as ASTNode | undefined\n if (!annotation || isFunctypeType(annotation, functypeImports)) return\n const members = annotation.type === \"TSUnionType\" ? unionMembers(annotation) : [annotation]\n // `a?: T | null` is reported once, by the union check.\n if (members.some((t) => t.type === \"TSNullKeyword\")) return\n const kept = members.filter((t) => !isNullish(t))\n if (kept.length !== 1 || isFunctypeType(kept[0], functypeImports)) return\n const key = (node.type === \"TSPropertySignature\" ? node.key : node) as ASTNode\n const name =\n key.type === \"Identifier\"\n ? key.name\n : key.type === \"Literal\"\n ? String(key.value)\n : context.sourceCode.getText(key)\n context.report({\n node: key,\n messageId: \"preferOptionOverOptional\",\n data: { name, type: context.sourceCode.getText(kept[0]) },\n })\n }\n\n return {\n TSPropertySignature: checkOptional,\n Identifier: checkOptional,\n\n TSUnionType(node: ASTNode) {\n // A union nested in a union is part of the outer one, which reports for both.\n if ((node.parent as ASTNode | undefined)?.type === \"TSUnionType\") return\n if (isInsideWireType(node, wireTypes)) return\n if (isExemptByMarker(node)) return\n if (!node.types || node.types.length < 2) return\n // The gate the rule always had: a nullish member of its own beside exactly one other. Spreading\n // nested unions below only refines what that one member is, so nothing new gets reported.\n const direct: ReadonlyArray<ASTNode> = node.types\n if (!direct.some((t) => isNullish(t)) || direct.filter((t) => !isNullish(t)).length !== 1) return\n if (allowUseState && isInHookTypeArgument(node)) return\n\n const members = unionMembers(node)\n const hasNull = members.some((type) => isNullish(type))\n\n if (!hasNull) return\n\n // On a member or parameter, `T | undefined` is the same \"may be absent\" as `?:`: skipped unless\n // checkOptionalMembers is on, and never reported on an optional one (`c?: T | undefined` is the\n // spelling exactOptionalPropertyTypes needs; the optional-member check reports it, once).\n const owner = memberOrParameterOf(node.parent)\n const undefinedOnly = !members.some((type) => type.type === \"TSNullKeyword\")\n if (owner && undefinedOnly && (!checkOptionalMembers || owner.optional === true)) return\n\n const nonNullTypes = members.filter((type) => !isNullish(type))\n\n if (nonNullTypes.length === 1) {\n const nonNullType = nonNullTypes[0]\n\n // Skip if it's already an Option type or other functype type\n if (isFunctypeType(nonNullType, functypeImports)) return\n\n // Skip if we're already in a functype context\n if (isAlreadyUsingFunctype(node, functypeImports)) return\n\n const sourceCode = context.sourceCode\n const nonNullTypeText = sourceCode.getText(nonNullType)\n const fullType = sourceCode.getText(node)\n\n // Skip if it's already an Option type (fallback check)\n if (nonNullTypeText.startsWith(\"Option<\")) return\n\n const drop = threeStateSpellings(node, members)\n if (drop !== undefined) {\n context.report({ node, messageId: \"preferWireForThreeStates\", data: { type: nonNullTypeText, drop } })\n return\n }\n\n const suggestions: Rule.SuggestionReportDescriptor[] = [\n {\n messageId: \"suggestOptionType\",\n data: { type: nonNullTypeText },\n fix(fixer) {\n return fixer.replaceText(node, `Option<${nonNullTypeText}>`)\n },\n },\n ]\n\n if (!hasFunctypeSymbol(sourceCode, \"Option\")) {\n suggestions.push({\n messageId: \"suggestAddImport\",\n data: { symbol: \"Option\" },\n fix: createImportFixer(sourceCode, \"Option\"),\n })\n }\n\n context.report({\n node,\n messageId: \"preferOption\",\n data: {\n type: nonNullTypeText,\n nullable: fullType,\n },\n suggest: suggestions,\n })\n }\n },\n }\n },\n}\n\nexport default rule\n"],"mappings":"A,6XAQA,MAAMA,kBAAyC,IAAI,IAAI,CAAC,WAAY,QAAQ,CAAC,EAEvEC,EAAa,GAA2BC,EAAK,OAAS,iBAAmBA,EAAK,OAAS,qBAG7F,SAASC,EAAY,EAAwB,CAC3C,IAAMC,EAASC,EAAK,OACpB,GAAI,CAACD,EAAQ,MAAO,GACpB,GAAIA,EAAO,OAAS,qBAAuBA,EAAO,OAASC,EAAM,OAAOF,EAAYC,CAAM,EAC1F,GAAIA,EAAO,OAAS,sBAAuB,MAAO,GAClD,IAAME,EAAUF,EAAwD,OACxE,OAAO,MAAM,QAAQE,CAAM,GAAKA,EAAO,SAASD,CAAI,CACtD,CAOA,SAASE,EAAoB,EAAsD,CACjF,IAAMC,EAAQC,GAAY,OAAS,mBAAsBA,EAAW,OAAiC,IAAA,GACrG,GAAKD,EAEL,OADIA,EAAM,OAAS,uBACZL,EAAYK,CAAK,EADyBA,EACb,IAAA,EACtC,CAMA,SAASE,EAAa,EAAwC,CAC5D,OAAOC,EAAM,MAAM,QAAS,GAAgBC,EAAE,OAAS,cAAgBF,EAAaE,CAAC,EAAI,CAACA,CAAC,CAAE,CAC/F,CAWA,SAASC,EAAoB,EAAgB,EAAqD,CAChG,GAAI,CAACC,EAAQ,KAAM,GAAMF,EAAE,OAAS,eAAe,EAAG,OACtD,IAAMR,EAASO,EAAM,OACfH,EAAQJ,GAAQ,OAAS,mBAAsBA,EAAO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AC,EAGHvB,EAAQ,OAAO,CACb,OACA,UAAW,eACX,KAAM,CACJ,KAAMwB,EACN,SAAUC,CACZ,EACA,QAASE,CACX,CAAC,CACH,CACF,CACF,CACF,CACF,E"}
|
|
1
|
+
{"version":3,"file":"prefer-option.js","names":["isInsideTaggedDeclaration","getFunctypeImportsLegacy","isAlreadyUsingFunctype","isFunctypeType","createImportFixer","hasFunctypeSymbol","DEFAULT_WIRE_TYPES","WIRE_TYPES_SCHEMA","isInsideWireType","REACT_STATE_HOOKS","isNullish","type","isParameter","node","parent","params","memberOrParameterOf","annotation","owner","unionMembers","union","t","threeStateSpellings","members","member","rule","context","options","wireTypes","allowInteropMarker","isExemptByMarker","allowUseState","checkOptionalMembers","isInHookTypeArgument","callee","name","functypeImports","checkOptional","kept","key","direct","undefinedOnly","nonNullTypes","nonNullType","sourceCode","nonNullTypeText","fullType","drop","suggestions","fixer"],"sources":["../../src/rules/prefer-option.ts"],"sourcesContent":["import type { Rule } from \"eslint\"\n\nimport type { ASTNode } from \"../types/ast\"\nimport { INTEROP_TAG, isInsideTaggedDeclaration } from \"../utils/boundary-tags\"\nimport { getFunctypeImportsLegacy, isAlreadyUsingFunctype, isFunctypeType } from \"../utils/functype-detection\"\nimport { createImportFixer, hasFunctypeSymbol } from \"../utils/import-fixer\"\nimport { DEFAULT_WIRE_TYPES, isInsideWireType, WIRE_TYPES_SCHEMA } from \"../utils/wire-types\"\n\nconst REACT_STATE_HOOKS: ReadonlySet<string> = new Set([\"useState\", \"useRef\"])\n\nconst isNullish = (type: ASTNode): boolean => type.type === \"TSNullKeyword\" || type.type === \"TSUndefinedKeyword\"\n\n/** Is `node` a parameter: of a function, a method signature or a function type, with or without a default? */\nfunction isParameter(node: ASTNode): boolean {\n const parent = node.parent as ASTNode | undefined\n if (!parent) return false\n if (parent.type === \"AssignmentPattern\" && parent.left === node) return isParameter(parent)\n if (parent.type === \"TSParameterProperty\") return true\n const params = (parent as { readonly params?: ReadonlyArray<ASTNode> }).params\n return Array.isArray(params) && params.includes(node)\n}\n\n/**\n * The member or parameter a type annotation belongs to, when it's the annotation of a type-literal or\n * interface member (`b: string | undefined`) or a parameter (`(x: string | undefined) => …`). Those are\n * the caller's shapes: a prop, an options-bag field, an argument (#446).\n */\nfunction memberOrParameterOf(annotation: ASTNode | undefined): ASTNode | undefined {\n const owner = annotation?.type === \"TSTypeAnnotation\" ? (annotation.parent as ASTNode | undefined) : undefined\n if (!owner) return undefined\n if (owner.type === \"TSPropertySignature\") return owner\n return isParameter(owner) ? owner : undefined\n}\n\n/**\n * A union's members, with nested unions spread in. The parser drops parentheses, so `(A | null) | undefined`\n * is a union holding a union; spread, it holds A, null and undefined.\n */\nfunction unionMembers(union: ASTNode): ReadonlyArray<ASTNode> {\n return union.types.flatMap((t: ASTNode) => (t.type === \"TSUnionType\" ? unionMembers(t) : [t]))\n}\n\n/**\n * Does a nullable union describe a three-state shape? Left out, cleared and set are three states, and\n * `Option` has two (#448). That's a type alias's body or a type-literal or interface member holding both\n * `null` and `undefined`, or an optional member that can also be `null` (`a?: T | null`). A parameter is a\n * converter's input and a return type is a result, so neither counts.\n *\n * Returns the two spellings of \"absent\" the type uses, for the message to say which to drop, or `undefined`\n * when the union isn't a three-state shape.\n */\nfunction threeStateSpellings(union: ASTNode, members: ReadonlyArray<ASTNode>): string | undefined {\n if (!members.some((t) => t.type === \"TSNullKeyword\")) return undefined\n const parent = union.parent as ASTNode | undefined\n const owner = parent?.type === \"TSTypeAnnotation\" ? (parent.parent as ASTNode | undefined) : undefined\n const member = owner?.type === \"TSPropertySignature\" ? owner : undefined\n if (member?.optional === true) return \"the ? or the | null\"\n if (!members.some((t) => t.type === \"TSUndefinedKeyword\")) return undefined\n return parent?.type === \"TSTypeAliasDeclaration\" || member !== undefined ? \"the | null or the | undefined\" : undefined\n}\n\nconst rule: Rule.RuleModule = {\n meta: {\n type: \"suggestion\",\n hasSuggestions: true,\n docs: {\n description: \"Prefer Option<T> over nullable types (T | null | undefined)\",\n recommended: true,\n },\n schema: [\n {\n type: \"object\",\n properties: {\n allowInteropMarker: {\n type: \"boolean\",\n default: true,\n },\n wireTypes: WIRE_TYPES_SCHEMA,\n allowNullableIntersections: {\n type: \"boolean\",\n default: false,\n },\n allowUseState: {\n type: \"boolean\",\n default: true,\n },\n checkOptionalMembers: {\n type: \"boolean\",\n default: false,\n },\n },\n additionalProperties: false,\n },\n ],\n messages: {\n preferOption:\n \"Prefer Option<{{type}}> over nullable type '{{nullable}}'. If this is a row, body or payload shape, wrap the type in Wire<…>\",\n preferOptionReturn: \"Prefer Option<{{type}}> as return type over nullable '{{nullable}}'\",\n preferOptionOverOptional:\n \"Prefer '{{name}}: Option<{{type}}>' over the optional '{{name}}?'. If this is a row, body or payload shape, wrap the type in Wire<…>\",\n preferWireForThreeStates:\n 'This type has three states, left out, null and set, and Option holds two. If it\\'s a row, body or payload shape, wrap the type in Wire<…>. If it only meant \"may be absent\", drop {{drop}} and use Option<{{type}}>',\n suggestOptionType: \"Replace with Option<{{type}}>\",\n suggestAddImport: \"Add {{symbol}} import from functype\",\n },\n },\n\n create(context) {\n const options = context.options[0] || {}\n // Everything inside `Wire<…>` is the declared serialization shape (#325 B).\n const wireTypes: ReadonlyArray<string> = options.wireTypes ?? DEFAULT_WIRE_TYPES\n // `@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 // `null` is idiomatic React state (`useState<User | null>(null)`, `useRef<El | null>(null)`); an\n // Option in a hook's type argument buys nothing and fights the hook's own API (#325).\n const allowUseState = options.allowUseState !== false\n // `a?: T` and `a: T | undefined` on a member or parameter both mean \"may be absent\", and the caller\n // writes `<X b=\"v\" />` or `f()`. Skip both unless asked to report them (#446).\n const checkOptionalMembers = options.checkOptionalMembers === true\n\n /** Is `node` inside the type argument of a `useState` / `useRef` call (bare or `React.`-qualified)? */\n function isInHookTypeArgument(node: ASTNode): boolean {\n const parent = node.parent\n if (!parent) return false\n if (parent.type === \"TSTypeParameterInstantiation\" && parent.parent?.type === \"CallExpression\") {\n const callee = parent.parent.callee\n const name =\n callee.type === \"Identifier\"\n ? callee.name\n : callee.type === \"MemberExpression\" && callee.property.type === \"Identifier\"\n ? callee.property.name\n : null\n if (name !== null && REACT_STATE_HOOKS.has(name)) return true\n }\n return isInHookTypeArgument(parent)\n }\n\n // Get functype imports if available (but still apply rule even without explicit import)\n const functypeImports = getFunctypeImportsLegacy(context)\n\n /** With checkOptionalMembers, `a?: T` on a member or parameter is reported like `a: T | undefined`. */\n function checkOptional(node: ASTNode): void {\n if (!checkOptionalMembers || node.optional !== true) return\n if (node.type !== \"TSPropertySignature\" && !isParameter(node)) return\n if (isInsideWireType(node, wireTypes) || isExemptByMarker(node)) return\n const annotation = (node.typeAnnotation as ASTNode | undefined)?.typeAnnotation as ASTNode | undefined\n if (!annotation || isFunctypeType(annotation, functypeImports)) return\n const members = annotation.type === \"TSUnionType\" ? unionMembers(annotation) : [annotation]\n // `a?: T | null` is reported once, by the union check.\n if (members.some((t) => t.type === \"TSNullKeyword\")) return\n const kept = members.filter((t) => !isNullish(t))\n if (kept.length !== 1 || isFunctypeType(kept[0], functypeImports)) return\n const key = (node.type === \"TSPropertySignature\" ? node.key : node) as ASTNode\n const name =\n key.type === \"Identifier\"\n ? key.name\n : key.type === \"Literal\"\n ? String(key.value)\n : context.sourceCode.getText(key)\n context.report({\n node: key,\n messageId: \"preferOptionOverOptional\",\n data: { name, type: context.sourceCode.getText(kept[0]) },\n })\n }\n\n return {\n TSPropertySignature: checkOptional,\n Identifier: checkOptional,\n\n TSUnionType(node: ASTNode) {\n // A union nested in a union is part of the outer one, which reports for both.\n if ((node.parent as ASTNode | undefined)?.type === \"TSUnionType\") return\n if (isInsideWireType(node, wireTypes)) return\n if (isExemptByMarker(node)) return\n if (!node.types || node.types.length < 2) return\n // The gate the rule always had: a nullish member of its own beside exactly one other. Spreading\n // nested unions below only refines what that one member is, so nothing new gets reported.\n const direct: ReadonlyArray<ASTNode> = node.types\n if (!direct.some((t) => isNullish(t)) || direct.filter((t) => !isNullish(t)).length !== 1) return\n if (allowUseState && isInHookTypeArgument(node)) return\n\n const members = unionMembers(node)\n const hasNull = members.some((type) => isNullish(type))\n\n if (!hasNull) return\n\n // On a member or parameter, `T | undefined` is the same \"may be absent\" as `?:`: skipped unless\n // checkOptionalMembers is on, and never reported on an optional one (`c?: T | undefined` is the\n // spelling exactOptionalPropertyTypes needs; the optional-member check reports it, once).\n const owner = memberOrParameterOf(node.parent)\n const undefinedOnly = !members.some((type) => type.type === \"TSNullKeyword\")\n if (owner && undefinedOnly && (!checkOptionalMembers || owner.optional === true)) return\n\n const nonNullTypes = members.filter((type) => !isNullish(type))\n\n if (nonNullTypes.length === 1) {\n const nonNullType = nonNullTypes[0]\n\n // Skip if it's already an Option type or other functype type\n if (isFunctypeType(nonNullType, functypeImports)) return\n\n // Skip if we're already in a functype context\n if (isAlreadyUsingFunctype(node, functypeImports)) return\n\n const sourceCode = context.sourceCode\n const nonNullTypeText = sourceCode.getText(nonNullType)\n const fullType = sourceCode.getText(node)\n\n // Skip if it's already an Option type (fallback check)\n if (nonNullTypeText.startsWith(\"Option<\")) return\n\n const drop = threeStateSpellings(node, members)\n if (drop !== undefined) {\n context.report({ node, messageId: \"preferWireForThreeStates\", data: { type: nonNullTypeText, drop } })\n return\n }\n\n const suggestions: Rule.SuggestionReportDescriptor[] = [\n {\n messageId: \"suggestOptionType\",\n data: { type: nonNullTypeText },\n fix(fixer) {\n return fixer.replaceText(node, `Option<${nonNullTypeText}>`)\n },\n },\n ]\n\n if (!hasFunctypeSymbol(sourceCode, \"Option\")) {\n suggestions.push({\n messageId: \"suggestAddImport\",\n data: { symbol: \"Option\" },\n fix: createImportFixer(sourceCode, \"Option\"),\n })\n }\n\n context.report({\n node,\n messageId: \"preferOption\",\n data: {\n type: nonNullTypeText,\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createImportFixer","hasFunctypeSymbol","rule","context","options","allowInteropMarker","isExemptByMarker","node","allowThrowInTests","isInTestFile","filename","isSimpleTryBody","isSimpleCatch","catchBody","tryBodyHasAwait","stmt","sourceCode","suggest","tryStmt","expr","exprText","awaitExpr","innerText","fixer"],"sources":["../../src/rules/prefer-try.ts"],"sourcesContent":["import type { Rule } from \"eslint\"\n\nimport type { ASTNode } from \"../types/ast\"\nimport { containsAwait } from \"../utils/async-detection\"\nimport { INTEROP_TAG, isInsideTaggedDeclaration } from \"../utils/boundary-tags\"\nimport { createImportFixer, hasFunctypeSymbol } from \"../utils/import-fixer\"\n\nconst rule: Rule.RuleModule = {\n meta: {\n type: \"suggestion\",\n hasSuggestions: true,\n docs: {\n description: \"Prefer Try for computations that may throw\",\n recommended: true,\n },\n schema: [\n {\n type: \"object\",\n properties: {\n allowInteropMarker: {\n type: \"boolean\",\n default: true,\n },\n allowThrowInTests: {\n type: \"boolean\",\n default: true,\n },\n },\n additionalProperties: false,\n },\n ],\n messages: {\n preferTryOverTryCatch: \"Prefer Try(() => ...) over try/catch block\",\n preferAsyncTryOverTryCatch:\n \"Prefer Try.fromPromise(...), Either.fromPromise(...) or IO.tryPromise(...) over an async try/catch — Try(() => ...) cannot catch an awaited rejection\",\n suggestTry: \"Replace with Try(() => ...)\",\n suggestTryFromPromise: \"Replace with Try.fromPromise(...)\",\n suggestAddImport: \"Add {{symbol}} import from functype\",\n },\n },\n\n create(context) {\n const options = context.options[0] || {}\n // `@interop <reason>` on an enclosing declaration marks a host-contract boundary (#241).\n const allowInteropMarker = options.allowInteropMarker !== false\n const isExemptByMarker = (node: ASTNode): boolean =>\n allowInteropMarker && isInsideTaggedDeclaration(node, INTEROP_TAG, context.sourceCode)\n const allowThrowInTests = options.allowThrowInTests !== false\n\n function isInTestFile() {\n const filename = context.filename\n return (\n /\\.(test|spec)\\.(ts|js|tsx|jsx)$/.test(filename) ||\n filename.includes(\"__tests__\") ||\n filename.includes(\"/test/\") ||\n filename.includes(\"/tests/\")\n )\n }\n\n function isSimpleTryBody(node: ASTNode): boolean {\n return node.block?.body?.length === 1\n }\n\n function isSimpleCatch(node: ASTNode): boolean {\n if (!node.handler?.body) return false\n const catchBody = node.handler.body.body\n return (\n catchBody.length === 0 ||\n (catchBody.length === 1 &&\n (catchBody[0].type === \"ReturnStatement\" || catchBody[0].type === \"ExpressionStatement\"))\n )\n }\n\n function tryBodyHasAwait(node: ASTNode): boolean {\n const stmt = node.block.body[0]\n if (stmt.type === \"ReturnStatement\" && stmt.argument?.type === \"AwaitExpression\") return true\n if (stmt.type === \"ExpressionStatement\" && stmt.expression?.type === \"AwaitExpression\") return true\n return false\n }\n\n return {\n TryStatement(node: ASTNode) {\n if (isExemptByMarker(node)) return\n // Try cannot model `finally` — bail on any try statement with a finalizer.\n // Covers two bugs: (1) catch-less try/finally fires a misleading warning\n // with no useful autofix; (2) try/catch/finally autofix would lift the\n // catch into Try(() => …) and silently drop the finally clause. The FP\n // primitive for guaranteed cleanup is IO.bracket, on the lazy IO type.\n // See #206.\n if (node.finalizer) return\n\n // Allow try/catch in test files\n if (allowThrowInTests && isInTestFile()) return\n\n // Allow try/catch that re-throws in the catch block (even with logging)\n if (node.handler && node.handler.body) {\n const catchBody = node.handler.body.body\n const hasRethrow = catchBody.some((stmt: ASTNode) => stmt.type === \"ThrowStatement\")\n if (hasRethrow) return\n }\n\n const sourceCode = context.sourceCode\n const suggest: Rule.SuggestionReportDescriptor[] = []\n\n if (isSimpleTryBody(node) && isSimpleCatch(node)) {\n const tryStmt = node.block.body[0]\n const isReturn = tryStmt.type === \"ReturnStatement\"\n\n // Only suggest when the try body is a return statement — non-return expression\n // replacements would produce syntactically ambiguous code without knowing the context\n if (isReturn) {\n const expr = tryStmt.argument\n const exprText = sourceCode.getText(expr)\n\n if (tryBodyHasAwait(node)) {\n const awaitExpr = expr.type === \"AwaitExpression\" ? expr.argument : expr\n const innerText = sourceCode.getText(awaitExpr)\n suggest.push({\n messageId: \"suggestTryFromPromise\",\n fix(fixer) {\n return fixer.replaceText(node, `return Try.fromPromise(${innerText})`)\n },\n })\n } else {\n suggest.push({\n messageId: \"suggestTry\",\n fix(fixer) {\n return fixer.replaceText(node, `return Try(() => ${exprText})`)\n },\n })\n }\n\n if (!hasFunctypeSymbol(sourceCode, \"Try\")) {\n suggest.push({\n messageId: \"suggestAddImport\",\n data: { symbol: \"Try\" },\n fix: createImportFixer(sourceCode, \"Try\"),\n })\n }\n }\n }\n\n context.report({\n node,\n messageId: containsAwait(node.block) ? \"preferAsyncTryOverTryCatch\" : \"preferTryOverTryCatch\",\n suggest,\n })\n },\n }\n },\n}\n\nexport default rule\n"],"mappings":"A,sNAOA,MAAMI,EAAwB,CAC5B,KAAM,CACJ,KAAM,aACN,eAAgB,GAChB,KAAM,CACJ,YAAa,6CACb,YAAa,EACf,EACA,OAAQ,CACN,CACE,KAAM,SACN,WAAY,CACV,mBAAoB,CAClB,KAAM,UACN,QAAS,EACX,EACA,kBAAmB,CACjB,KAAM,UACN,QAAS,EACX,CACF,EACA,qBAAsB,EACxB,CACF,EACA,SAAU,CACR,sBAAuB,6CACvB,2BACE,wJACF,WAAY,8BACZ,sBAAuB,oCACvB,iBAAkB,qCACpB,CACF,EAEA,OAAOC,EAAS,CACd,IAAMC,EAAUD,EAAQ,QAAQ,IAAM,CAAC,EAEjCE,EAAqBD,EAAQ,qBAAuB,GACpDE,EAAoBC,GACxBF,GAAsBN,EAA0BQ,EAAA,UAAmBJ,EAAQ,UAAU,EACjFK,EAAoBJ,EAAQ,oBAAsB,GAExD,SAASK,GAAe,CACtB,IAAMC,EAAWP,EAAQ,SACzB,MACE,kCAAkC,KAAKO,CAAQ,GAC/CA,EAAS,SAAS,WAAW,GAC7BA,EAAS,SAAS,QAAQ,GAC1BA,EAAS,SAAS,SAAS,CAE/B,CAEA,SAASC,EAAgBJ,EAAwB,CAC/C,OAAOA,EAAK,OAAO,MAAM,SAAW,CACtC,CAEA,SAASK,EAAcL,EAAwB,CAC7C,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AAK,CACX,UAAW,mBACX,KAAM,CAAE,OAAQ,KAAM,EACtB,IAAKjB,EAAkBgB,EAAY,KAAK,CAC1C,CAAC,CAEL,CACF,CAEAb,EAAQ,OAAO,CACbI,OACA,UAAWT,EAAcS,EAAK,KAAK,EAAI,6BAA+B,wBACtEU,SACF,CAAC,CACH,CACF,CACF,CACF,E"}
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { ASTNode } from "../types/ast.js";
|
|
2
1
|
import { Rule } from "eslint";
|
|
2
|
+
import { ASTNode } from "../types/ast.js";
|
|
3
3
|
/** Is `node` (an expression) typed as a mutable array? `false` without type information. */
|
|
4
4
|
export declare const isMutableArrayExpression: (node: ASTNode, context: Rule.RuleContext) => boolean;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"array-mutation.js","names":["typedServices","
|
|
1
|
+
{"version":3,"file":"array-mutation.js","names":["typedServices","context","services","isMutableArray","checker","type","types","symbol","target","member","isMutableArrayExpression","node","tsNode"],"sources":["../../src/utils/array-mutation.ts"],"sourcesContent":["import type { Rule } from \"eslint\"\n\nimport type { ASTNode } from \"../types/ast\"\n\n/**\n * Type checks for `no-array-mutation`, reached through `parserServices` and typed structurally so the\n * plugin takes no runtime dependency on `typescript`. Every check answers `false` without type\n * information: the rule reports nothing it can't prove is an array.\n */\n\ntype TypeLike = object\n\ntype CheckerLike = {\n getTypeAtLocation(node: unknown): TypeLike\n getNonNullableType(type: TypeLike): TypeLike\n isArrayLikeType(type: TypeLike): boolean\n isTupleType(type: TypeLike): boolean\n}\n\ntype TypedServices = {\n readonly program: { getTypeChecker(): CheckerLike }\n readonly esTreeNodeToTSNodeMap: { get(node: unknown): unknown }\n}\n\nconst typedServices = (context: Rule.RuleContext): TypedServices | undefined => {\n const services = context.sourceCode.parserServices as Partial<TypedServices> | undefined\n return services?.program && services.esTreeNodeToTSNodeMap ? (services as TypedServices) : undefined\n}\n\n/**\n * The mutable `Array` type, or a non-readonly tuple — `ReadonlyArray` has no `push`, so TypeScript\n * already rejects mutating one. Every member of a union must be one, so `string[] | Set<string>`\n * isn't reported on a `.push` the compiler resolves some other way.\n */\nconst isMutableArray = (checker: CheckerLike, type: TypeLike): boolean => {\n const { types, symbol, target } = type as {\n types?: ReadonlyArray<TypeLike>\n symbol?: { name?: string }\n target?: { readonly?: boolean }\n }\n if (types) return types.length > 0 && types.every((member) => isMutableArray(checker, member))\n if (checker.isTupleType(type)) return target?.readonly !== true\n return symbol?.name === \"Array\" && checker.isArrayLikeType(type)\n}\n\n/** Is `node` (an expression) typed as a mutable array? `false` without type information. */\nexport const isMutableArrayExpression = (node: ASTNode, context: Rule.RuleContext): boolean => {\n const services = typedServices(context)\n const tsNode = services?.esTreeNodeToTSNodeMap.get(node)\n if (!services || !tsNode) return false\n const checker = services.program.getTypeChecker()\n return isMutableArray(checker, checker.getNonNullableType(checker.getTypeAtLocation(tsNode)))\n}\n"],"mappings":"AAwBA,MAAMA,EAAiBC,GAAyD,CAC9E,IAAMC,EAAWD,EAAQ,WAAW,eACpC,OAAOC,GAAU,SAAWA,EAAS,sBAAyBA,EAA6B,IAAA,EAC7F,EAOMC,GAAkBC,EAAsBC,IAA4B,CACxE,GAAM,CAAEC,QAAOC,SAAQC,UAAWH,EAOlC,OAFIC,EAAcA,EAAM,OAAS,GAAKA,EAAM,MAAOG,GAAWN,EAAeC,EAASK,CAAM,CAAC,EACzFL,EAAQ,YAAYC,CAAI,EAAUG,GAAQ,WAAa,GACpDD,GAAQ,OAAS,SAAWH,EAAQ,gBAAgBC,CAAI,CACjE,EAGaK,GAA4BC,EAAeV,IAAuC,CAC7F,IAAMC,EAAWF,EAAcC,CAAO,EAChCW,EAASV,GAAU,sBAAsB,IAAIS,CAAI,EACvD,GAAI,CAACT,GAAY,CAACU,EAAQ,MAAO,GACjC,IAAMR,EAAUF,EAAS,QAAQ,eAAe,EAChD,OAAOC,EAAeC,EAASA,EAAQ,mBAAmBA,EAAQ,kBAAkBQ,CAAM,CAAC,CAAC,CAC9F,E"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"ast-walk.js","names":["isNode","value","childNodes","node","key","descendants"],"sources":["../../src/utils/ast-walk.ts"],"sourcesContent":["import type { ASTNode } from \"../types/ast\"\n\n/**\n * Generic ESTree child traversal for rules that need to look inside a subtree without a visitor.\n * `parent` is skipped (it points up, not down); `loc`/`range`/tokens are plain data, not nodes.\n */\n\nexport const isNode = (value: unknown): value is ASTNode =>\n typeof value === \"object\" && value !== null && typeof (value as { type?: unknown }).type === \"string\"\n\nexport const childNodes = (node: ASTNode): ReadonlyArray<ASTNode> =>\n Object.entries(node)\n .filter(([key]) => key !== \"parent\")\n .flatMap(([, value]) => (Array.isArray(value) ? value.filter(isNode) : isNode(value) ? [value] : []))\n\n/** Every node in the subtree rooted at `node`, root included. */\nexport const descendants = (node: ASTNode): ReadonlyArray<ASTNode> => [node, ...childNodes(node).flatMap(descendants)]\n"],"mappings":"AAOA,MAAaA,
|
|
1
|
+
{"version":3,"file":"ast-walk.js","names":["isNode","value","childNodes","node","key","descendants"],"sources":["../../src/utils/ast-walk.ts"],"sourcesContent":["import type { ASTNode } from \"../types/ast\"\n\n/**\n * Generic ESTree child traversal for rules that need to look inside a subtree without a visitor.\n * `parent` is skipped (it points up, not down); `loc`/`range`/tokens are plain data, not nodes.\n */\n\nexport const isNode = (value: unknown): value is ASTNode =>\n typeof value === \"object\" && value !== null && typeof (value as { type?: unknown }).type === \"string\"\n\nexport const childNodes = (node: ASTNode): ReadonlyArray<ASTNode> =>\n Object.entries(node)\n .filter(([key]) => key !== \"parent\")\n .flatMap(([, value]) => (Array.isArray(value) ? value.filter(isNode) : isNode(value) ? [value] : []))\n\n/** Every node in the subtree rooted at `node`, root included. */\nexport const descendants = (node: ASTNode): ReadonlyArray<ASTNode> => [node, ...childNodes(node).flatMap(descendants)]\n"],"mappings":"AAOA,MAAaA,EAAUC,GACrB,OAAOA,GAAU,YAAYA,GAAkB,OAAQA,EAA6B,MAAS,SAElFC,EAAcC,GACzB,OAAO,QAAQA,CAAI,CAAC,CACjB,QAAQ,CAACC,KAASA,IAAQ,QAAQ,CAAC,CACnC,SAAS,EAAGH,KAAY,MAAM,QAAQA,CAAK,EAAIA,EAAM,OAAOD,CAAM,EAAIA,EAAOC,CAAK,EAAI,CAACA,CAAK,EAAI,CAAC,CAAE,EAG3FI,EAAeF,GAA0C,CAACA,EAAM,GAAGD,EAAWC,CAAI,CAAC,CAAC,QAAQE,CAAW,CAAC,E"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"async-detection.js","names":["
|
|
1
|
+
{"version":3,"file":"async-detection.js","names":["childNodes","isNode","FUNCTION_BOUNDARIES","containsInOwnFlow","matches","node","walk","n","containsAwait","containsYield"],"sources":["../../src/utils/async-detection.ts"],"sourcesContent":["import type { ASTNode } from \"../types/ast\"\nimport { childNodes, isNode } from \"./ast-walk\"\n\n/**\n * Detects suspension points — `await` and `yield` — in a statement's own control flow.\n *\n * A suspension inside a nested function (arrow, expression, declaration, method) belongs to that\n * function, not to the enclosing loop or try block, so the walk stops at function boundaries. That\n * distinction is what makes the answer useful: `try { run(async () => { await x }) }` is a synchronous\n * try block, and `Try(() => ...)` is a correct replacement for it; `try { await x }` is not. Likewise a\n * loop body that yields cannot become a `.forEach` callback, but one that only defines a generator can.\n */\n\nconst FUNCTION_BOUNDARIES: ReadonlySet<string> = new Set([\n \"ArrowFunctionExpression\",\n \"FunctionExpression\",\n \"FunctionDeclaration\",\n])\n\nconst containsInOwnFlow =\n (matches: (node: ASTNode) => boolean) =>\n (node: ASTNode): boolean => {\n const walk = (n: ASTNode): boolean => {\n if (!isNode(n)) return false\n if (matches(n)) return true\n if (FUNCTION_BOUNDARIES.has(n.type)) return false\n return childNodes(n).some(walk)\n }\n return walk(node)\n }\n\nexport const containsAwait = containsInOwnFlow(\n (node) => node.type === \"AwaitExpression\" || (node.type === \"ForOfStatement\" && node.await === true),\n)\n\nexport const containsYield = containsInOwnFlow((node) => node.type === \"YieldExpression\")\n"],"mappings":"A,uDAaA,MAAME,kBAA2C,IAAI,IAAI,CACvD,0BACA,qBACA,qBACF,CAAC,EAEKC,EACHC,GACAC,GAA2B,CAC1B,IAAMC,EAAQC,GACPN,EAAOM,CAAC,EACTH,EAAQG,CAAC,EAAU,GACvB,CAAIL,EAAoB,IAAIK,EAAE,IAAI,GAC3BP,EAAWO,CAAC,CAAC,CAAC,KAAKD,CAAI,EAHP,GAKzB,OAAOA,EAAKD,CAAI,CAClB,EAEWG,EAAgBL,EAC1BE,GAASA,EAAK,OAAS,mBAAsBA,EAAK,OAAS,kBAAoBA,EAAK,QAAU,EACjG,EAEaI,EAAgBN,EAAmBE,GAASA,EAAK,OAAS,iBAAiB,E"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"boundary-tags.js","names":["INTEROP_TAG","DOCUMENTABLE","EXPORT_WRAPPERS","leadingJSDoc","
|
|
1
|
+
{"version":3,"file":"boundary-tags.js","names":["INTEROP_TAG","DOCUMENTABLE","EXPORT_WRAPPERS","leadingJSDoc","node","sourceCode","anchor","comments","last","hasTagWithReason","jsdoc","tag","isInsideTaggedDeclaration","check","current"],"sources":["../../src/utils/boundary-tags.ts"],"sourcesContent":["import type { SourceCode } from \"eslint\"\n\nimport type { ASTNode } from \"../types/ast\"\n\n/**\n * Structural exemptions recorded in JSDoc, instead of `eslint-disable` (#241).\n *\n * `@interop <reason>` — the enclosing declaration bridges functype to a host whose contract is the\n * non-FP shape: React's `use()` needs a throw, React Query needs a rejected promise, a hook that converts\n * nullables into `Option` must accept nullables.\n *\n * Bug checks are not tagged: they are `invariant(cond, msg)` calls from functype, which narrow types and\n * cover one statement. (An `@invariant` tag shipped in 1.10.0 and was removed in #342 — it exempted a\n * whole function, including any expected-failure throw added to it later.)\n *\n * Why a tag rather than a disable comment: it covers one declaration (and what is nested inside it), not\n * a whole file; it must carry a reason on the same line, so a bare tag exempts nothing; and it is\n * greppable — `rg '@interop'` is the inventory of every place the code touches a throw-based host.\n */\n\nexport const INTEROP_TAG = \"interop\"\n\n/** Declarations whose leading JSDoc can carry a tag. */\nconst DOCUMENTABLE: ReadonlySet<string> = new Set([\n \"FunctionDeclaration\",\n \"VariableDeclaration\",\n \"MethodDefinition\",\n \"PropertyDefinition\",\n \"Property\",\n \"TSTypeAliasDeclaration\",\n \"TSInterfaceDeclaration\",\n \"TSPropertySignature\",\n \"TSMethodSignature\",\n])\n\nconst EXPORT_WRAPPERS: ReadonlySet<string> = new Set([\"ExportNamedDeclaration\", \"ExportDefaultDeclaration\"])\n\n/** The JSDoc block (`/** … *\\/`) directly before `node`, or before its `export` wrapper. */\nconst leadingJSDoc = (node: ASTNode, sourceCode: SourceCode): string | null => {\n const anchor = node.parent && EXPORT_WRAPPERS.has(node.parent.type) ? node.parent : node\n const comments = sourceCode.getCommentsBefore(anchor)\n const last = comments[comments.length - 1]\n return last?.type === \"Block\" && last.value.startsWith(\"*\") ? last.value : null\n}\n\n/** `@tag` followed by a reason on the same line. A bare tag carries no reason and exempts nothing. */\nconst hasTagWithReason = (jsdoc: string, tag: string): boolean =>\n new RegExp(`(^|[\\\\s*])@${tag}[ \\\\t]+\\\\S`, \"m\").test(jsdoc)\n\n/**\n * Is `node` inside a declaration whose JSDoc carries `@<tag> <reason>`? Every enclosing documentable\n * declaration is checked, so a tag on a function covers the callbacks nested inside it.\n */\nexport const isInsideTaggedDeclaration = (node: ASTNode, tag: string, sourceCode: SourceCode): boolean => {\n const check = (current: ASTNode | null | undefined): boolean => {\n if (!current) return false\n if (DOCUMENTABLE.has(current.type)) {\n const jsdoc = leadingJSDoc(current, sourceCode)\n if (jsdoc !== null && hasTagWithReason(jsdoc, tag)) return true\n }\n return check(current.parent)\n }\n return check(node)\n}\n"],"mappings":"AAoBA,MAAaA,EAAc,UAGrBC,kBAAoC,IAAI,IAAI,CAChD,sBACA,sBACA,mBACA,qBACA,WACA,yBACA,yBACA,sBACA,mBACF,CAAC,EAEKC,kBAAuC,IAAI,IAAI,CAAC,yBAA0B,0BAA0B,CAAC,EAGrGC,GAAgBC,EAAeC,IAA0C,CAC7E,IAAMC,EAASF,EAAK,QAAUF,EAAgB,IAAIE,EAAK,OAAO,IAAI,EAAIA,EAAK,OAASA,EAC9EG,EAAWF,EAAW,kBAAkBC,CAAM,EAC9CE,EAAOD,EAASA,EAAS,OAAS,GACxC,OAAOC,GAAM,OAAS,SAAWA,EAAK,MAAM,WAAW,GAAG,EAAIA,EAAK,MAAQ,IAC7E,EAGMC,GAAoBC,EAAeC,IACnC,OAAO,cAAcA,EAAI,YAAa,GAAG,CAAC,CAAC,KAAKD,CAAK,EAM9CE,GAA6BR,EAAeO,EAAaN,IAAoC,CACxG,IAAMQ,EAASC,GAAiD,CAC9D,GAAI,CAACA,EAAS,MAAO,GACrB,GAAIb,EAAa,IAAIa,EAAQ,IAAI,EAAG,CAClC,IAAMJ,EAAQP,EAAaW,EAAST,CAAU,EAC9C,GAAIK,IAAU,MAAQD,EAAiBC,EAAOC,CAAG,EAAG,MAAO,EAC7D,CACA,OAAOE,EAAMC,EAAQ,MAAM,CAC7B,EACA,OAAOD,EAAMT,CAAI,CACnB,E"}
|
|
@@ -1,5 +1,5 @@
|
|
|
1
|
-
import { ASTNode } from "../types/ast.js";
|
|
2
1
|
import { SourceCode } from "eslint";
|
|
2
|
+
import { ASTNode } from "../types/ast.js";
|
|
3
3
|
/**
|
|
4
4
|
* What `Map` / `Set` means at a use site (#350). Deciding from the file's import list was wrong both ways:
|
|
5
5
|
* `import { Map as FMap } from "functype"` silenced the whole file even though the bare `Map` there is still
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"collection-binding.js","names":["isFunctypeSource","value","resolve","
|
|
1
|
+
{"version":3,"file":"collection-binding.js","names":["isFunctypeSource","value","resolve","node","name","sourceCode","lookup","scope","bindingOf","variable","def","functypeLocalName","n","decl","spec","COLLECTION_NAMES","functypeCollectionAt","expr","isExplicitNativeCollection","callee"],"sources":["../../src/utils/collection-binding.ts"],"sourcesContent":["import type { Scope, SourceCode } from \"eslint\"\n\nimport type { ASTNode } from \"../types/ast\"\n\n/**\n * What `Map` / `Set` means at a use site (#350). Deciding from the file's import list was wrong both ways:\n * `import { Map as FMap } from \"functype\"` silenced the whole file even though the bare `Map` there is still\n * the native one. Resolving the identifier through scope asks the question that matters.\n *\n * - `functype` — it is functype's import (under any local name), so there is nothing to report;\n * - `shadowed` — a local declaration or a non-functype import, so it isn't the native collection;\n * - `native` — unresolved, or a global / lib binding with no declaration: the built-in.\n */\nexport type CollectionBinding = \"native\" | \"functype\" | \"shadowed\"\n\nconst isFunctypeSource = (value: unknown): boolean =>\n typeof value === \"string\" && (value === \"functype\" || value.startsWith(\"functype/\"))\n\nconst resolve = (node: ASTNode, name: string, sourceCode: SourceCode): Scope.Variable | null => {\n const lookup = (scope: Scope.Scope | null): Scope.Variable | null =>\n scope === null ? null : (scope.set.get(name) ?? lookup(scope.upper))\n return lookup(sourceCode.getScope(node))\n}\n\nexport const bindingOf = (node: ASTNode, name: string, sourceCode: SourceCode): CollectionBinding => {\n const variable = resolve(node, name, sourceCode)\n if (variable === null || variable.defs.length === 0) return \"native\"\n const def = variable.defs[0] as unknown as { readonly type: string; readonly parent?: ASTNode }\n if (def.type === \"ImportBinding\") return isFunctypeSource(def.parent?.source?.value) ? \"functype\" : \"shadowed\"\n return \"shadowed\"\n}\n\n/**\n * The name this file already uses for functype's `name`: `\"FMap\"` for `import { Map as FMap }`,\n * `\"F.Map\"` for `import * as F`, or null when it isn't imported (so the fix must add the import).\n */\nexport const functypeLocalName = (sourceCode: SourceCode, name: string): string | null => {\n const names = (sourceCode.ast.body as ReadonlyArray<ASTNode>)\n .filter((n) => n.type === \"ImportDeclaration\" && isFunctypeSource(n.source?.value))\n .flatMap((decl) => (decl.specifiers ?? []) as ReadonlyArray<ASTNode>)\n .flatMap((spec): ReadonlyArray<string> => {\n if (spec.type === \"ImportSpecifier\" && spec.imported?.type === \"Identifier\" && spec.imported.name === name) {\n return [spec.local.name]\n }\n if (spec.type === \"ImportNamespaceSpecifier\") return [`${spec.local.name}.${name}`]\n return []\n })\n return names[0] ?? null\n}\n\nexport const COLLECTION_NAMES: ReadonlyArray<string> = [\"Map\", \"Set\"]\n\n/**\n * If `expr` names functype's `Map` / `Set` — an identifier bound to its import (any local name), or a\n * namespace member like `F.Map` — returns the imported name and how this file spells it; else null.\n */\nexport const functypeCollectionAt = (\n expr: ASTNode,\n sourceCode: SourceCode,\n): { readonly name: string; readonly local: string } | null => {\n if (expr?.type === \"Identifier\") {\n const def = resolve(expr, expr.name, sourceCode)?.defs[0] as\n { readonly type: string; readonly node?: ASTNode; readonly parent?: ASTNode } | undefined\n if (def?.type !== \"ImportBinding\" || !isFunctypeSource(def.parent?.source?.value)) return null\n const spec = def.node\n if (spec?.type !== \"ImportSpecifier\" || spec.imported?.type !== \"Identifier\") return null\n return COLLECTION_NAMES.includes(spec.imported.name) ? { name: spec.imported.name, local: expr.name } : null\n }\n if (\n expr?.type === \"MemberExpression\" &&\n !expr.computed &&\n expr.object.type === \"Identifier\" &&\n expr.property.type === \"Identifier\" &&\n COLLECTION_NAMES.includes(expr.property.name)\n ) {\n const def = resolve(expr.object, expr.object.name, sourceCode)?.defs[0] as\n { readonly type: string; readonly node?: ASTNode; readonly parent?: ASTNode } | undefined\n const isNamespace =\n def?.type === \"ImportBinding\" &&\n def.node?.type === \"ImportNamespaceSpecifier\" &&\n isFunctypeSource(def.parent?.source?.value)\n return isNamespace ? { name: expr.property.name, local: `${expr.object.name}.${expr.property.name}` } : null\n }\n return null\n}\n\n/**\n * Is `callee` the built-in constructor spelled explicitly — `globalThis.Map` / `globalThis.Set`, or\n * functype's `ESMap` re-export of the native Map? Bare `Map` is handled by {@link bindingOf}.\n */\nexport const isExplicitNativeCollection = (callee: ASTNode, name: string, sourceCode: SourceCode): boolean => {\n if (\n callee?.type === \"MemberExpression\" &&\n !callee.computed &&\n callee.object.type === \"Identifier\" &&\n callee.object.name === \"globalThis\" &&\n callee.property.type === \"Identifier\" &&\n callee.property.name === name\n ) {\n // A local binding named `globalThis` would shadow the real one.\n return resolve(callee.object, \"globalThis\", sourceCode)?.defs.length ? false : true\n }\n if (callee?.type === \"Identifier\" && name === \"Map\") {\n const def = resolve(callee, callee.name, sourceCode)?.defs[0] as\n { readonly type: string; readonly node?: ASTNode; readonly parent?: ASTNode } | undefined\n return (\n def?.type === \"ImportBinding\" &&\n isFunctypeSource(def.parent?.source?.value) &&\n def.node?.type === \"ImportSpecifier\" &&\n def.node.imported?.name === \"ESMap\"\n )\n }\n return false\n}\n"],"mappings":"AAeA,MAAMA,EAAoBC,GACxB,OAAOA,GAAU,WAAaA,IAAU,YAAcA,EAAM,WAAW,WAAW,GAE9EC,GAAWC,EAAeC,EAAcC,IAAkD,CAC9F,IAAMC,EAAUC,GACdA,IAAU,KAAO,KAAQA,EAAM,IAAI,IAAIH,CAAI,GAAKE,EAAOC,EAAM,KAAK,EACpE,OAAOD,EAAOD,EAAW,SAASF,CAAI,CAAC,CACzC,EAEaK,GAAaL,EAAeC,EAAcC,IAA8C,CACnG,IAAMI,EAAWP,EAAQC,EAAMC,EAAMC,CAAU,EAC/C,GAAII,IAAa,MAAQA,EAAS,KAAK,SAAW,EAAG,MAAO,SAC5D,IAAMC,EAAMD,EAAS,KAAK,GAE1B,OADIC,EAAI,OAAS,iBAAwBV,EAAiBU,EAAI,QAAQ,QAAQ,KAAK,EAAI,WAChF,UACT,EAMaC,GAAqBN,EAAwBD,IACzCC,EAAW,IAAI,KAC3B,OAAQO,GAAMA,EAAE,OAAS,qBAAuBZ,EAAiBY,EAAE,QAAQ,KAAK,CAAC,CAAC,CAClF,QAASC,GAAUA,EAAK,YAAc,CAAC,CAA4B,CAAC,CACpE,QAASC,GACJA,EAAK,OAAS,mBAAqBA,EAAK,UAAU,OAAS,cAAgBA,EAAK,SAAS,OAASV,EAC7F,CAACU,EAAK,MAAM,IAAI,EAErBA,EAAK,OAAS,2BAAmC,CAAC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,GAAQ,OAAS,cAAgBf,IAAS,MAAO,CACnD,IAAMM,EAAMR,EAAQiB,EAAQA,EAAO,KAAMd,CAAU,CAAC,EAAE,KAAK,GAE3D,OACEK,GAAK,OAAS,iBACdV,EAAiBU,EAAI,QAAQ,QAAQ,KAAK,GAC1CA,EAAI,MAAM,OAAS,mBACnBA,EAAI,KAAK,UAAU,OAAS,OAEhC,CACA,MAAO,EACT,E"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"dependency-validator.js","names":["__require","PEER_DEPENDENCIES","tryRequire","packageName","validatePeerDependencies","available","missing","ok","bad","dep","warnings","requiredMissing","installCommand","createValidationError","result","message","shouldValidateDependencies"],"sources":["../../src/utils/dependency-validator.ts"],"sourcesContent":["// Utility to validate peer dependencies and provide helpful error messages\n\ninterface PeerDependency {\n name: string\n packageName: string\n description: string\n required: boolean\n}\n\nconst PEER_DEPENDENCIES: PeerDependency[] = [\n {\n name: \"@typescript-eslint/eslint-plugin\",\n packageName: \"@typescript-eslint/eslint-plugin\",\n description: \"TypeScript-aware ESLint rules\",\n required: true,\n },\n {\n name: \"@typescript-eslint/parser\",\n packageName: \"@typescript-eslint/parser\",\n description: \"TypeScript parser for ESLint\",\n required: true,\n },\n {\n name: \"eslint-plugin-functional\",\n packageName: \"eslint-plugin-functional\",\n description: \"Functional programming ESLint rules\",\n required: true,\n },\n {\n name: \"eslint-plugin-prettier\",\n packageName: \"eslint-plugin-prettier\",\n description: \"Code formatting rules\",\n required: false,\n },\n {\n name: \"eslint-plugin-simple-import-sort\",\n packageName: \"eslint-plugin-simple-import-sort\",\n description: \"Import sorting rules\",\n required: false,\n },\n {\n name: \"prettier\",\n packageName: \"prettier\",\n description: \"Code formatter\",\n required: false,\n },\n]\n\nexport interface ValidationResult {\n isValid: boolean\n missing: PeerDependency[]\n available: PeerDependency[]\n installCommand: string\n warnings: string[]\n}\n\nfunction tryRequire(packageName: string): boolean {\n try {\n require.resolve(packageName)\n return true\n } catch {\n return false\n }\n}\n\nexport function validatePeerDependencies(): ValidationResult {\n // Partition each dep into present/absent up-front; downstream calcs are\n // pure derivations from those two arrays.\n const [available, missing] = PEER_DEPENDENCIES.reduce<[PeerDependency[], PeerDependency[]]>(\n ([ok, bad], dep) => (tryRequire(dep.packageName) ? [[...ok, dep], bad] : [ok, [...bad, dep]]),\n [[], []],\n )\n\n const warnings = missing\n .filter((dep) => !dep.required)\n .map((dep) => `Optional plugin '${dep.name}' not found. Some rules will be skipped.`)\n\n const requiredMissing = missing.filter((dep) => dep.required)\n const installCommand = missing.length > 0 ? `pnpm add -D ${missing.map((dep) => dep.packageName).join(\" \")}` : \"\"\n\n return {\n isValid: requiredMissing.length === 0,\n missing,\n available,\n installCommand,\n warnings,\n }\n}\n\nexport function createValidationError(result: ValidationResult): Error {\n const requiredMissing = result.missing.filter((dep) => dep.required)\n\n if (requiredMissing.length === 0) {\n return new Error(\"No validation errors\")\n }\n\n const missingList = requiredMissing.map((dep) => ` • ${dep.name} - ${dep.description}`).join(\"\\n\")\n\n const message = [\n \"❌ Missing required peer dependencies for eslint-plugin-functype:\",\n \"\",\n missingList,\n \"\",\n \"📦 Install missing dependencies:\",\n ` ${result.installCommand}`,\n \"\",\n \"📖 See installation guide: https://github.com/jordanburke/eslint-plugin-functype#installation\",\n ].join(\"\\n\")\n\n return new Error(message)\n}\n\nexport function shouldValidateDependencies(): boolean {\n // Skip validation in test environments or when explicitly disabled\n return process.env.NODE_ENV !== \"test\" && process.env.FUNCTYPE_SKIP_VALIDATION !== \"true\"\n}\n"],"mappings":"A,qFASA,
|
|
1
|
+
{"version":3,"file":"dependency-validator.js","names":["createRequire","__require","PEER_DEPENDENCIES","tryRequire","packageName","validatePeerDependencies","available","missing","ok","bad","dep","warnings","requiredMissing","installCommand","createValidationError","result","message","shouldValidateDependencies"],"sources":["../../src/utils/dependency-validator.ts"],"sourcesContent":["// Utility to validate peer dependencies and provide helpful error messages\n\ninterface PeerDependency {\n name: string\n packageName: string\n description: string\n required: boolean\n}\n\nconst PEER_DEPENDENCIES: PeerDependency[] = [\n {\n name: \"@typescript-eslint/eslint-plugin\",\n packageName: \"@typescript-eslint/eslint-plugin\",\n description: \"TypeScript-aware ESLint rules\",\n required: true,\n },\n {\n name: \"@typescript-eslint/parser\",\n packageName: \"@typescript-eslint/parser\",\n description: \"TypeScript parser for ESLint\",\n required: true,\n },\n {\n name: \"eslint-plugin-functional\",\n packageName: \"eslint-plugin-functional\",\n description: \"Functional programming ESLint rules\",\n required: true,\n },\n {\n name: \"eslint-plugin-prettier\",\n packageName: \"eslint-plugin-prettier\",\n description: \"Code formatting rules\",\n required: false,\n },\n {\n name: \"eslint-plugin-simple-import-sort\",\n packageName: \"eslint-plugin-simple-import-sort\",\n description: \"Import sorting rules\",\n required: false,\n },\n {\n name: \"prettier\",\n packageName: \"prettier\",\n description: \"Code formatter\",\n required: false,\n },\n]\n\nexport interface ValidationResult {\n isValid: boolean\n missing: PeerDependency[]\n available: PeerDependency[]\n installCommand: string\n warnings: string[]\n}\n\nfunction tryRequire(packageName: string): boolean {\n try {\n require.resolve(packageName)\n return true\n } catch {\n return false\n }\n}\n\nexport function validatePeerDependencies(): ValidationResult {\n // Partition each dep into present/absent up-front; downstream calcs are\n // pure derivations from those two arrays.\n const [available, missing] = PEER_DEPENDENCIES.reduce<[PeerDependency[], PeerDependency[]]>(\n ([ok, bad], dep) => (tryRequire(dep.packageName) ? [[...ok, dep], bad] : [ok, [...bad, dep]]),\n [[], []],\n )\n\n const warnings = missing\n .filter((dep) => !dep.required)\n .map((dep) => `Optional plugin '${dep.name}' not found. Some rules will be skipped.`)\n\n const requiredMissing = missing.filter((dep) => dep.required)\n const installCommand = missing.length > 0 ? `pnpm add -D ${missing.map((dep) => dep.packageName).join(\" \")}` : \"\"\n\n return {\n isValid: requiredMissing.length === 0,\n missing,\n available,\n installCommand,\n warnings,\n }\n}\n\nexport function createValidationError(result: ValidationResult): Error {\n const requiredMissing = result.missing.filter((dep) => dep.required)\n\n if (requiredMissing.length === 0) {\n return new Error(\"No validation errors\")\n }\n\n const missingList = requiredMissing.map((dep) => ` • ${dep.name} - ${dep.description}`).join(\"\\n\")\n\n const message = [\n \"❌ Missing required peer dependencies for eslint-plugin-functype:\",\n \"\",\n missingList,\n \"\",\n \"📦 Install missing dependencies:\",\n ` ${result.installCommand}`,\n \"\",\n \"📖 See installation guide: https://github.com/jordanburke/eslint-plugin-functype#installation\",\n ].join(\"\\n\")\n\n return new Error(message)\n}\n\nexport function shouldValidateDependencies(): boolean {\n // Skip validation in test environments or when explicitly disabled\n return process.env.NODE_ENV !== \"test\" && process.env.FUNCTYPE_SKIP_VALIDATION !== \"true\"\n}\n"],"mappings":"A,qFASA,MAAME,EAAsC,CAC1C,CACE,KAAM,mCACN,YAAa,mCACb,YAAa,gCACb,SAAU,EACZ,EACA,CACE,KAAM,4BACN,YAAa,4BACb,YAAa,+BACb,SAAU,EACZ,EACA,CACE,KAAM,2BACN,YAAa,2BACb,YAAa,sCACb,SAAU,EACZ,EACA,CACE,KAAM,yBACN,YAAa,yBACb,YAAa,wBACb,SAAU,EACZ,EACA,CACE,KAAM,mCACN,YAAa,mCACb,YAAa,uBACb,SAAU,EACZ,EACA,CACE,KAAM,WACN,YAAa,WACb,YAAa,iBACb,SAAU,EACZ,CACF,EAUA,SAASC,EAAWC,EAA8B,CAChD,GAAI,CAEF,OADAH,EAAQ,QAAQG,CAAW,EACpB,EACT,MAAQ,CACN,MAAO,EACT,CACF,CAEA,SAAgBC,GAA6C,CAG3D,GAAM,CAACC,EAAWC,GAAWL,EAAkB,QAC5C,CAACM,EAAIC,GAAMC,IAASP,EAAWO,EAAI,WAAW,EAAI,CAAC,CAAC,GAAGF,EAAIE,CAAG,EAAGD,CAAG,EAAI,CAACD,EAAI,CAAC,GAAGC,EAAKC,CAAG,CAAC,EAC3F,CAAC,CAAC,EAAG,CAAC,CAAC,CACT,EAEMC,EAAWJ,EACd,OAAQG,GAAQ,CAACA,EAAI,QAAQ,CAAC,CAC9B,IAAKA,GAAQ,oBAAoBA,EAAI,KAAK,yCAAyC,EAEhFE,EAAkBL,EAAQ,OAAQG,GAAQA,EAAI,QAAQ,EACtDG,EAAiBN,EAAQ,OAAS,EAAI,eAAeA,EAAQ,IAAKG,GAAQA,EAAI,WAAW,CAAC,CAAC,KAAK,GAAG,IAAM,GAE/G,MAAO,CACL,QAASE,EAAgB,SAAW,EACpCL,UACAD,YACAO,iBACAF,UACF,CACF,CAEA,SAAgBG,EAAsBC,EAAiC,CACrE,IAAMH,EAAkBG,EAAO,QAAQ,OAAQL,GAAQA,EAAI,QAAQ,EAEnE,GAAIE,EAAgB,SAAW,EAC7B,MAAO,gBAAI,MAAM,sBAAsB,EAKzC,IAAMI,EAAU,CACd,mEACA,GAJkBJ,EAAgB,IAAKF,GAAQ,OAAOA,EAAI,KAAK,KAAKA,EAAI,aAAa,CAAC,CAAC,KAAK;CAKlF,EACV,GACA,mCACA,MAAMK,EAAO,iBACb,GACA,+FACF,CAAC,CAAC,KAAK;CAAI,EAEX,OAAW,MAAMC,CAAO,CAC1B,CAEA,SAAgBC,GAAsC,CAEpD,OAAO,QAAQ,IAAI,WAAa,QAAU,QAAQ,IAAI,2BAA6B,MACrF,C"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"functype-detection.js","names":["TYPE_NAMES","isFunctypeImport","node","hasFunctypeImport","context","categorizeSpecifier","spec","name","pickPresent","buckets","v","b","key","getFunctypeImports","getFunctypeImportsLegacy","isFunctypeType","types","functypeImports","typeName","isFunctypeCall","callee","objectName","methodName","ancestorSatisfies","parent","pred","isAlreadyUsingFunctype","hasFunctypeTypeAnnotation","isDoNotationCall","isDollarHelper","isInsideDoNotation","n","isChainedMethodCall","shouldUseDoNotation","text","flatMapChainDepth"],"sources":["../../src/utils/functype-detection.ts"],"sourcesContent":["import type { Rule } from \"eslint\"\n\nimport type { ASTNode } from \"../types/ast\"\n\n/**\n * Utility functions for detecting functype library usage in ESLint rules.\n *\n * Implementation style: pure helpers operating over native immutable\n * primitives (Array.prototype methods + ReadonlySet). No mutable\n * accumulators, no `for-of` driving state changes. The plugin's domain\n * (AST traversal) is naturally tree-shaped; the helpers compose as\n * folds/filters/maps over those trees.\n */\n\nconst TYPE_NAMES: ReadonlySet<string> = new Set([\"Option\", \"Either\", \"List\", \"LazyList\", \"Try\", \"Map\", \"Set\", \"Stack\"])\n\n/** `import ... from \"functype\"` — including `functype/<subpath>` */\nconst isFunctypeImport = (node: ASTNode): boolean =>\n node.type === \"ImportDeclaration\" && node.source.type === \"Literal\" && node.source.value === \"functype\"\n\n/**\n * Check if functype library is imported in the current file\n */\nexport function hasFunctypeImport(context: Rule.RuleContext): boolean {\n return context.sourceCode.ast.body.some(isFunctypeImport)\n}\n\n/**\n * Enhanced functype imports tracking\n */\nexport interface FunctypeImports {\n types: Set<string> // Option, Either, List, etc.\n functions: Set<string> // Do, DoAsync, $, etc.\n all: Set<string> // Combined for compatibility\n}\n\ntype SpecifierBuckets = { readonly type: string | null; readonly fn: string | null; readonly all: string }\n\n/** Sort a single import specifier into the three buckets (or none). */\nfunction categorizeSpecifier(spec: ASTNode): SpecifierBuckets | null {\n if (spec.type === \"ImportSpecifier\" && spec.imported.type === \"Identifier\") {\n const name = spec.imported.name\n // Named imports split by whether they're a functype TYPE or anything else.\n // (Do/DoAsync/$ + any other named import bucket as `functions`, matching\n // the original behavior — the explicit Do/DoAsync/$ branch was redundant.)\n return TYPE_NAMES.has(name) ? { type: name, fn: null, all: name } : { type: null, fn: name, all: name }\n }\n if (spec.type === \"ImportDefaultSpecifier\") return { type: null, fn: \"default\", all: \"default\" }\n if (spec.type === \"ImportNamespaceSpecifier\") return { type: \"*\", fn: \"*\", all: \"*\" }\n return null\n}\n\nconst pickPresent = <K extends keyof SpecifierBuckets>(buckets: readonly SpecifierBuckets[], key: K): string[] =>\n buckets.flatMap((b) => {\n const v = b[key]\n return v === null ? [] : [v as string]\n })\n\n/**\n * Get imported functype symbols from the current file\n */\nexport function getFunctypeImports(context: Rule.RuleContext): FunctypeImports {\n const buckets = context.sourceCode.ast.body\n .filter(isFunctypeImport)\n .flatMap((node: ASTNode) => (node.specifiers ?? []) as ASTNode[])\n .map(categorizeSpecifier)\n .filter((b): b is SpecifierBuckets => b !== null)\n\n return {\n types: new Set(pickPresent(buckets, \"type\")),\n functions: new Set(pickPresent(buckets, \"fn\")),\n all: new Set(buckets.map((b) => b.all)),\n }\n}\n\n/**\n * Legacy compatibility - returns the 'all' set\n */\nexport function getFunctypeImportsLegacy(context: Rule.RuleContext): Set<string> {\n return getFunctypeImports(context).all\n}\n\n/**\n * Check if a type reference is using functype types\n */\nexport function isFunctypeType(node: ASTNode, functypeImports: FunctypeImports | Set<string>): boolean {\n if (!node) return false\n\n // Handle both new and legacy API\n const types = functypeImports instanceof Set ? functypeImports : functypeImports.types || functypeImports.all\n\n // Check direct type names\n if (node.type === \"TSTypeReference\" && node.typeName?.type === \"Identifier\") {\n const typeName = node.typeName.name\n return (\n types.has(typeName) || [\"Option\", \"Either\", \"List\", \"LazyList\", \"Try\", \"Map\", \"Set\", \"Stack\"].includes(typeName)\n )\n }\n\n return false\n}\n\n/**\n * Check if a call expression is using functype methods\n */\nexport function isFunctypeCall(node: ASTNode, functypeImports: Set<string>): boolean {\n if (!node || node.type !== \"CallExpression\") return false\n\n const callee = node.callee\n\n // Check for static method calls like Option.some(), Either.left(), List.of()\n if (callee.type === \"MemberExpression\" && callee.object.type === \"Identifier\") {\n const objectName = callee.object.name\n const methodName = callee.property?.name\n\n // Check if calling methods on imported functype types\n if (functypeImports.has(objectName)) return true\n\n // Check for common functype patterns\n if (\n (objectName === \"Option\" && [\"some\", \"none\", \"of\"].includes(methodName)) ||\n (objectName === \"Either\" && [\"left\", \"right\", \"of\"].includes(methodName)) ||\n (objectName === \"List\" && [\"of\", \"from\", \"empty\"].includes(methodName)) ||\n (objectName === \"Map\" && [\"of\", \"empty\"].includes(methodName)) ||\n (objectName === \"Set\" && [\"of\", \"empty\"].includes(methodName))\n ) {\n return true\n }\n }\n\n // Check for method calls on functype instances like someOption.map()\n if (callee.type === \"MemberExpression\") {\n const methodName = callee.property?.name\n\n // Common functype methods\n if (\n [\n \"map\",\n \"flatMap\",\n \"filter\",\n \"fold\",\n \"foldLeft\",\n \"foldRight\",\n \"getOrElse\",\n \"orElse\",\n \"isEmpty\",\n \"nonEmpty\",\n \"isDefined\",\n \"isSome\",\n \"isNone\",\n \"isLeft\",\n \"isRight\",\n \"toArray\",\n ].includes(methodName)\n ) {\n return true\n }\n }\n\n return false\n}\n\n/** True iff any ancestor of `node` satisfies `pred`. Pure tail recursion. */\nfunction ancestorSatisfies(node: ASTNode | null | undefined, pred: (n: ASTNode) => boolean): boolean {\n const parent = node?.parent as ASTNode | undefined\n if (!parent) return false\n return pred(parent) || ancestorSatisfies(parent, pred)\n}\n\n/**\n * Check if current context is already using functype patterns appropriately\n */\nexport function isAlreadyUsingFunctype(node: ASTNode, functypeImports: Set<string>): boolean {\n return ancestorSatisfies(\n node,\n (parent) => isFunctypeCall(parent, functypeImports) || isFunctypeType(parent, functypeImports),\n )\n}\n\n/**\n * Check if a variable or parameter is typed with functype types\n */\nexport function hasFunctypeTypeAnnotation(node: ASTNode, functypeImports: FunctypeImports | Set<string>): boolean {\n // Check for type annotation\n if (node.typeAnnotation?.typeAnnotation) {\n return isFunctypeType(node.typeAnnotation.typeAnnotation, functypeImports)\n }\n\n return false\n}\n\n/**\n * Check if a call expression is a Do notation call\n */\nexport function isDoNotationCall(node: ASTNode, functypeImports: FunctypeImports): boolean {\n if (!node || node.type !== \"CallExpression\") return false\n\n const callee = node.callee\n\n // Check for Do() or DoAsync() calls\n if (callee.type === \"Identifier\") {\n const name = callee.name\n return functypeImports.functions.has(name) && [\"Do\", \"DoAsync\"].includes(name)\n }\n\n return false\n}\n\n/**\n * Check if a call expression uses the $ helper function\n */\nexport function isDollarHelper(node: ASTNode, functypeImports: FunctypeImports): boolean {\n if (!node || node.type !== \"CallExpression\") return false\n\n const callee = node.callee\n\n // Check for $() calls\n if (callee.type === \"Identifier\" && callee.name === \"$\") {\n return functypeImports.functions.has(\"$\")\n }\n\n return false\n}\n\n/**\n * Check if current expression is inside a Do notation block\n */\nexport function isInsideDoNotation(node: ASTNode, functypeImports: FunctypeImports): boolean {\n return ancestorSatisfies(node, (n) => n.type === \"CallExpression\" && isDoNotationCall(n, functypeImports))\n}\n\n/**\n * Check if a method call is a chained method call on functype types\n */\nexport function isChainedMethodCall(node: ASTNode, methodName: string): boolean {\n if (!node || node.type !== \"CallExpression\") return false\n\n const callee = node.callee\n\n if (\n callee.type === \"MemberExpression\" &&\n callee.property.type === \"Identifier\" &&\n callee.property.name === methodName\n ) {\n return true\n }\n\n return false\n}\n\n/**\n * Detect if code could benefit from Do notation\n */\nexport function shouldUseDoNotation(\n node: ASTNode,\n functypeImports: FunctypeImports,\n): {\n shouldUse: boolean\n reason: \"nested-checks\" | \"chained-flatmaps\" | \"mixed-monads\" | \"async-chains\" | null\n} {\n // Already using Do notation\n if (isInsideDoNotation(node, functypeImports)) {\n return { shouldUse: false, reason: null }\n }\n\n // Check for nested null checks (a && a.b && a.b.c pattern)\n if (node.type === \"LogicalExpression\" && node.operator === \"&&\") {\n const text = node.toString ? node.toString() : \"\"\n if (text.includes(\"&&\") && text.match(/\\w+(\\.\\w+){2,}/)) {\n return { shouldUse: true, reason: \"nested-checks\" }\n }\n }\n\n // Check for chained flatMap calls\n if (isChainedMethodCall(node, \"flatMap\") && flatMapChainDepth(node) >= 3) {\n return { shouldUse: true, reason: \"chained-flatmaps\" }\n }\n\n return { shouldUse: false, reason: null }\n}\n\n/** Length of an unbroken `.flatMap().flatMap()...` chain starting at `node`. */\nfunction flatMapChainDepth(node: ASTNode): number {\n if (!node || node.type !== \"CallExpression\" || !isChainedMethodCall(node, \"flatMap\")) return 0\n if (node.callee.type !== \"MemberExpression\") return 1\n return 1 + flatMapChainDepth(node.callee.object as ASTNode)\n}\n"],"mappings":"AAcA,MAAMA,kBAAk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E,CAM7B,CAKA,SAAgBW,EACd,EACA,EAIA,CAEA,GAAIH,EAAmB5B,EAAMe,CAAe,EAC1C,MAAO,CAAE,UAAW,GAAO,OAAQ,IAAK,EAI1C,GAAIf,EAAK,OAAS,qBAAuBA,EAAK,WAAa,KAAM,CAC/D,IAAMgC,EAAOhC,EAAK,SAAWA,EAAK,SAAS,EAAI,GAC/C,GAAIgC,EAAK,SAAS,IAAI,GAAKA,EAAK,MAAM,gBAAgB,EACpD,MAAO,CAAE,UAAW,GAAM,OAAQ,eAAgB,CAEtD,CAOA,OAJIF,EAAoB9B,EAAM,SAAS,GAAKiC,EAAkBjC,CAAI,GAAK,EAC9D,CAAE,UAAW,GAAM,OAAQ,kBAAmB,EAGhD,CAAE,UAAW,GAAO,OAAQ,IAAK,CAC1C,CAGA,SAASiC,EAAkB,EAAuB,CAGhD,MAFI,CAACjC,GAAQA,EAAK,OAAS,kBAAoB,CAAC8B,EAAoB9B,EAAM,SAAS,EAAU,EACzFA,EAAK,OAAO,OAAS,mBAClB,EAAIiC,EAAkBjC,EAAK,OAAO,MAAiB,EADN,CAEtD,C"}
|
|
1
|
+
{"version":3,"file":"functype-detection.js","names":["TYPE_NAMES","isFunctypeImport","node","hasFunctypeImport","context","categorizeSpecifier","spec","name","pickPresent","buckets","key","b","v","getFunctypeImports","getFunctypeImportsLegacy","isFunctypeType","functypeImports","types","typeName","isFunctypeCall","callee","objectName","methodName","ancestorSatisfies","pred","parent","isAlreadyUsingFunctype","hasFunctypeTypeAnnotation","isDoNotationCall","isDollarHelper","isInsideDoNotation","n","isChainedMethodCall","shouldUseDoNotation","text","flatMapChainDepth"],"sources":["../../src/utils/functype-detection.ts"],"sourcesContent":["import type { Rule } from \"eslint\"\n\nimport type { ASTNode } from \"../types/ast\"\n\n/**\n * Utility functions for detecting functype library usage in ESLint rules.\n *\n * Implementation style: pure helpers operating over native immutable\n * primitives (Array.prototype methods + ReadonlySet). No mutable\n * accumulators, no `for-of` driving state changes. The plugin's domain\n * (AST traversal) is naturally tree-shaped; the helpers compose as\n * folds/filters/maps over those trees.\n */\n\nconst TYPE_NAMES: ReadonlySet<string> = new Set([\"Option\", \"Either\", \"List\", \"LazyList\", \"Try\", \"Map\", \"Set\", \"Stack\"])\n\n/** `import ... from \"functype\"` — including `functype/<subpath>` */\nconst isFunctypeImport = (node: ASTNode): boolean =>\n node.type === \"ImportDeclaration\" && node.source.type === \"Literal\" && node.source.value === \"functype\"\n\n/**\n * Check if functype library is imported in the current file\n */\nexport function hasFunctypeImport(context: Rule.RuleContext): boolean {\n return context.sourceCode.ast.body.some(isFunctypeImport)\n}\n\n/**\n * Enhanced functype imports tracking\n */\nexport interface FunctypeImports {\n types: Set<string> // Option, Either, List, etc.\n functions: Set<string> // Do, DoAsync, $, etc.\n all: Set<string> // Combined for compatibility\n}\n\ntype SpecifierBuckets = { readonly type: string | null; readonly fn: string | null; readonly all: string }\n\n/** Sort a single import specifier into the three buckets (or none). */\nfunction categorizeSpecifier(spec: ASTNode): SpecifierBuckets | null {\n if (spec.type === \"ImportSpecifier\" && spec.imported.type === \"Identifier\") {\n const name = spec.imported.name\n // Named imports split by whether they're a functype TYPE or anything else.\n // (Do/DoAsync/$ + any other named import bucket as `functions`, matching\n // the original behavior — the explicit Do/DoAsync/$ branch was redundant.)\n return TYPE_NAMES.has(name) ? { type: name, fn: null, all: name } : { type: null, fn: name, all: name }\n }\n if (spec.type === \"ImportDefaultSpecifier\") return { type: null, fn: \"default\", all: \"default\" }\n if (spec.type === \"ImportNamespaceSpecifier\") return { type: \"*\", fn: \"*\", all: \"*\" }\n return null\n}\n\nconst pickPresent = <K extends keyof SpecifierBuckets>(buckets: readonly SpecifierBuckets[], key: K): string[] =>\n buckets.flatMap((b) => {\n const v = b[key]\n return v === null ? [] : [v as string]\n })\n\n/**\n * Get imported functype symbols from the current file\n */\nexport function getFunctypeImports(context: Rule.RuleContext): FunctypeImports {\n const buckets = context.sourceCode.ast.body\n .filter(isFunctypeImport)\n .flatMap((node: ASTNode) => (node.specifiers ?? []) as ASTNode[])\n .map(categorizeSpecifier)\n .filter((b): b is SpecifierBuckets => b !== null)\n\n return {\n types: new Set(pickPresent(buckets, \"type\")),\n functions: new Set(pickPresent(buckets, \"fn\")),\n all: new Set(buckets.map((b) => b.all)),\n }\n}\n\n/**\n * Legacy compatibility - returns the 'all' set\n */\nexport function getFunctypeImportsLegacy(context: Rule.RuleContext): Set<string> {\n return getFunctypeImports(context).all\n}\n\n/**\n * Check if a type reference is using functype types\n */\nexport function isFunctypeType(node: ASTNode, functypeImports: FunctypeImports | Set<string>): boolean {\n if (!node) return false\n\n // Handle both new and legacy API\n const types = functypeImports instanceof Set ? functypeImports : functypeImports.types || functypeImports.all\n\n // Check direct type names\n if (node.type === \"TSTypeReference\" && node.typeName?.type === \"Identifier\") {\n const typeName = node.typeName.name\n return (\n types.has(typeName) || [\"Option\", \"Either\", \"List\", \"LazyList\", \"Try\", \"Map\", \"Set\", \"Stack\"].includes(typeName)\n )\n }\n\n return false\n}\n\n/**\n * Check if a call expression is using functype methods\n */\nexport function isFunctypeCall(node: ASTNode, functypeImports: Set<string>): boolean {\n if (!node || node.type !== \"CallExpression\") return false\n\n const callee = node.callee\n\n // Check for static method calls like Option.some(), Either.left(), List.of()\n if (callee.type === \"MemberExpression\" && callee.object.type === \"Identifier\") {\n const objectName = callee.object.name\n const methodName = callee.property?.name\n\n // Check if calling methods on imported functype types\n if (functypeImports.has(objectName)) return true\n\n // Check for common functype patterns\n if (\n (objectName === \"Option\" && [\"some\", \"none\", \"of\"].includes(methodName)) ||\n (objectName === \"Either\" && [\"left\", \"right\", \"of\"].includes(methodName)) ||\n (objectName === \"List\" && [\"of\", \"from\", \"empty\"].includes(methodName)) ||\n (objectName === \"Map\" && [\"of\", \"empty\"].includes(methodName)) ||\n (objectName === \"Set\" && [\"of\", \"empty\"].includes(methodName))\n ) {\n return true\n }\n }\n\n // Check for method calls on functype instances like someOption.map()\n if (callee.type === \"MemberExpression\") {\n const methodName = callee.property?.name\n\n // Common functype methods\n if (\n [\n \"map\",\n \"flatMap\",\n \"filter\",\n \"fold\",\n \"foldLeft\",\n \"foldRight\",\n \"getOrElse\",\n \"orElse\",\n \"isEmpty\",\n \"nonEmpty\",\n \"isDefined\",\n \"isSome\",\n \"isNone\",\n \"isLeft\",\n \"isRight\",\n \"toArray\",\n ].includes(methodName)\n ) {\n return true\n }\n }\n\n return false\n}\n\n/** True iff any ancestor of `node` satisfies `pred`. Pure tail recursion. */\nfunction ancestorSatisfies(node: ASTNode | null | undefined, pred: (n: ASTNode) => boolean): boolean {\n const parent = node?.parent as ASTNode | undefined\n if (!parent) return false\n return pred(parent) || ancestorSatisfies(parent, pred)\n}\n\n/**\n * Check if current context is already using functype patterns appropriately\n */\nexport function isAlreadyUsingFunctype(node: ASTNode, functypeImports: Set<string>): boolean {\n return ancestorSatisfies(\n node,\n (parent) => isFunctypeCall(parent, functypeImports) || isFunctypeType(parent, functypeImports),\n )\n}\n\n/**\n * Check if a variable or parameter is typed with functype types\n */\nexport function hasFunctypeTypeAnnotation(node: ASTNode, functypeImports: FunctypeImports | Set<string>): boolean {\n // Check for type annotation\n if (node.typeAnnotation?.typeAnnotation) {\n return isFunctypeType(node.typeAnnotation.typeAnnotation, functypeImports)\n }\n\n return false\n}\n\n/**\n * Check if a call expression is a Do notation call\n */\nexport function isDoNotationCall(node: ASTNode, functypeImports: FunctypeImports): boolean {\n if (!node || node.type !== \"CallExpression\") return false\n\n const callee = node.callee\n\n // Check for Do() or DoAsync() calls\n if (callee.type === \"Identifier\") {\n const name = callee.name\n return functypeImports.functions.has(name) && [\"Do\", \"DoAsync\"].includes(name)\n }\n\n return false\n}\n\n/**\n * Check if a call expression uses the $ helper function\n */\nexport function isDollarHelper(node: ASTNode, functypeImports: FunctypeImports): boolean {\n if (!node || node.type !== \"CallExpression\") return false\n\n const callee = node.callee\n\n // Check for $() calls\n if (callee.type === \"Identifier\" && callee.name === \"$\") {\n return functypeImports.functions.has(\"$\")\n }\n\n return false\n}\n\n/**\n * Check if current expression is inside a Do notation block\n */\nexport function isInsideDoNotation(node: ASTNode, functypeImports: FunctypeImports): boolean {\n return ancestorSatisfies(node, (n) => n.type === \"CallExpression\" && isDoNotationCall(n, functypeImports))\n}\n\n/**\n * Check if a method call is a chained method call on functype types\n */\nexport function isChainedMethodCall(node: ASTNode, methodName: string): boolean {\n if (!node || node.type !== \"CallExpression\") return false\n\n const callee = node.callee\n\n if (\n callee.type === \"MemberExpression\" &&\n callee.property.type === \"Identifier\" &&\n callee.property.name === methodName\n ) {\n return true\n }\n\n return false\n}\n\n/**\n * Detect if code could benefit from Do notation\n */\nexport function shouldUseDoNotation(\n node: ASTNode,\n functypeImports: FunctypeImports,\n): {\n shouldUse: boolean\n reason: \"nested-checks\" | \"chained-flatmaps\" | \"mixed-monads\" | \"async-chains\" | null\n} {\n // Already using Do notation\n if (isInsideDoNotation(node, functypeImports)) {\n return { shouldUse: false, reason: null }\n }\n\n // Check for nested null checks (a && a.b && a.b.c pattern)\n if (node.type === \"LogicalExpression\" && node.operator === \"&&\") {\n const text = node.toString ? node.toString() : \"\"\n if (text.includes(\"&&\") && text.match(/\\w+(\\.\\w+){2,}/)) {\n return { shouldUse: true, reason: \"nested-checks\" }\n }\n }\n\n // Check for chained flatMap calls\n if (isChainedMethodCall(node, \"flatMap\") && flatMapChainDepth(node) >= 3) {\n return { shouldUse: true, reason: \"chained-flatmaps\" }\n }\n\n return { shouldUse: false, reason: null }\n}\n\n/** Length of an unbroken `.flatMap().flatMap()...` chain starting at `node`. */\nfunction flatMapChainDepth(node: ASTNode): number {\n if (!node || node.type !== \"CallExpression\" || !isChainedMethodCall(node, \"flatMap\")) return 0\n if (node.callee.type !== \"MemberExpression\") return 1\n return 1 + flatMapChainDepth(node.callee.object as ASTNode)\n}\n"],"mappings":"AAcA,MAAMA,kBAAkC,IAAI,IAAI,CAAC,SAAU,SAAU,OAAQ,WAAY,MAAO,MAAO,MAAO,OAAO,CAAC,EAGhHC,E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AAmB5B,EAAMc,CAAe,EAC1C,MAAO,CAAE,UAAW,GAAO,OAAQ,IAAK,EAI1C,GAAId,EAAK,OAAS,qBAAuBA,EAAK,WAAa,KAAM,CAC/D,IAAMgC,EAAOhC,EAAK,SAAWA,EAAK,SAAS,EAAI,GAC/C,GAAIgC,EAAK,SAAS,IAAI,GAAKA,EAAK,MAAM,gBAAgB,EACpD,MAAO,CAAE,UAAW,GAAM,OAAQ,eAAgB,CAEtD,CAOA,OAJIF,EAAoB9B,EAAM,SAAS,GAAKiC,EAAkBjC,CAAI,GAAK,EAC9D,CAAE,UAAW,GAAM,OAAQ,kBAAmB,EAGhD,CAAE,UAAW,GAAO,OAAQ,IAAK,CAC1C,CAGA,SAASiC,EAAkBjC,EAAuB,CAGhD,MAFI,CAACA,GAAQA,EAAK,OAAS,kBAAoB,CAAC8B,EAAoB9B,EAAM,SAAS,EAAU,EACzFA,EAAK,OAAO,OAAS,mBAClB,EAAIiC,EAAkBjC,EAAK,OAAO,MAAiB,EADN,CAEtD,C"}
|
|
@@ -1,5 +1,5 @@
|
|
|
1
|
-
import { ASTNode } from "../types/ast.js";
|
|
2
1
|
import { SourceCode } from "eslint";
|
|
2
|
+
import { ASTNode } from "../types/ast.js";
|
|
3
3
|
/** Methods on a monadic value that mean "this is the Some/Right/Success path." */
|
|
4
4
|
export declare const POSITIVE_PREDICATES: ReadonlySet<string>;
|
|
5
5
|
/** Methods that mean "this is the None/Left/Failure path." */
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"functype-predicates.js","names":["POSITIVE_PREDICATES","NEGATIVE_PREDICATES","compact","text","predicateCall","node","callee","method","isNegated","
|
|
1
|
+
{"version":3,"file":"functype-predicates.js","names":["POSITIVE_PREDICATES","NEGATIVE_PREDICATES","compact","text","predicateCall","node","sourceCode","callee","method","isNegated","testedPredicate","test","inner","isEmptyRead","receiverText","provesWhen","outcome","self","value","left","right","predicate","isAbsenceTest","MATCH_COMPONENT"],"sources":["../../src/utils/functype-predicates.ts"],"sourcesContent":["import type { SourceCode } from \"eslint\"\n\nimport type { ASTNode } from \"../types/ast\"\n\n/** Methods on a monadic value that mean \"this is the Some/Right/Success path.\" */\nexport const POSITIVE_PREDICATES: ReadonlySet<string> = new Set([\"isSome\", \"isRight\", \"isSuccess\"])\n/** Methods that mean \"this is the None/Left/Failure path.\" */\n// `isEmpty` is deliberately absent: it is a property on every functype container, never a method, so\n// `x.isEmpty()` is not functype code (and on a List, `.fold` is a reduce, not a branch).\nexport const NEGATIVE_PREDICATES: ReadonlySet<string> = new Set([\"isNone\", \"isLeft\", \"isFailure\"])\n\n/** Source text with all whitespace removed — receivers match however they are line-broken. */\nexport const compact = (text: string): string => text.replace(/\\s+/g, \"\")\n\n/** A functype predicate call such as `o.isSome()`, split into its receiver and method. */\nexport type PredicateCall = {\n readonly receiver: ASTNode\n /** The receiver's source text, whitespace removed, for matching against other reads of it. */\n readonly receiverText: string\n readonly method: string\n readonly isNegated: boolean\n}\n\n/**\n * `o.isSome()`, `e.isLeft()`, `t.isFailure()` — a zero-argument call of a functype predicate method.\n * A property read (`state.isPending`, `items.isEmpty`) is not a call, so it never matches.\n */\nexport const predicateCall = (node: ASTNode, sourceCode: SourceCode): PredicateCall | null => {\n if (node?.type !== \"CallExpression\" || node.arguments.length !== 0) return null\n const callee = node.callee as ASTNode\n if (callee.type !== \"MemberExpression\" || callee.computed || callee.property.type !== \"Identifier\") return null\n const method = callee.property.name as string\n const isNegated = NEGATIVE_PREDICATES.has(method)\n if (!isNegated && !POSITIVE_PREDICATES.has(method)) return null\n return { receiver: callee.object, receiverText: compact(sourceCode.getText(callee.object)), method, isNegated }\n}\n\n/**\n * The first predicate call a test branches on, looking through `!` (which flips it) and `&&` / `||`:\n * `o.isSome()`, `!o.isSome()`, `loading || o.isNone()`. `isNegated` is the predicate's own meaning\n * with any `!` applied, so `!o.isSome()` reads like `o.isNone()`.\n */\nexport const testedPredicate = (test: ASTNode, sourceCode: SourceCode): PredicateCall | null => {\n if (test?.type === \"UnaryExpression\" && test.operator === \"!\") {\n const inner = testedPredicate(test.argument, sourceCode)\n return inner === null ? null : { ...inner, isNegated: !inner.isNegated }\n }\n if (test?.type === \"LogicalExpression\" && (test.operator === \"&&\" || test.operator === \"||\")) {\n return testedPredicate(test.left, sourceCode) ?? testedPredicate(test.right, sourceCode)\n }\n return predicateCall(test, sourceCode)\n}\n\n/** What a test proves about a receiver's value: there, missing, or nothing. */\nexport type Presence = \"present\" | \"absent\" | null\n\n/** `o.isEmpty` read (not called): Option's narrowing property, true when the value is missing. */\nconst isEmptyRead = (node: ASTNode, receiverText: string, sourceCode: SourceCode): boolean =>\n node?.type === \"MemberExpression\" &&\n !node.computed &&\n node.property.type === \"Identifier\" &&\n node.property.name === \"isEmpty\" &&\n !(node.parent?.type === \"CallExpression\" && node.parent.callee === node) &&\n compact(sourceCode.getText(node.object)) === receiverText\n\n/**\n * What `test` evaluating to `outcome` proves about `receiverText`. Looks through `!`, `&&` and `||`:\n * `a && b` being true proves whatever either side proves, `a || b` being false likewise, and the other\n * two cases prove something only when both sides agree. `o.isEmpty` counts as a test for absence.\n */\nexport const provesWhen = (test: ASTNode, outcome: boolean, receiverText: string, sourceCode: SourceCode): Presence => {\n const self = (node: ASTNode, value: boolean): Presence => provesWhen(node, value, receiverText, sourceCode)\n if (test?.type === \"UnaryExpression\" && test.operator === \"!\") return self(test.argument, !outcome)\n if (test?.type === \"LogicalExpression\" && (test.operator === \"&&\" || test.operator === \"||\")) {\n const left = self(test.left, outcome)\n const right = self(test.right, outcome)\n // `a && b` true, or `a || b` false: both sides hold that outcome, so either one's proof counts.\n if ((test.operator === \"&&\") === outcome) return left ?? right\n return left === right ? left : null\n }\n const predicate = predicateCall(test, sourceCode)\n const isAbsenceTest =\n predicate !== null && predicate.receiverText === receiverText\n ? predicate.isNegated\n : isEmptyRead(test, receiverText, sourceCode)\n ? true\n : null\n if (isAbsenceTest === null) return null\n return isAbsenceTest === outcome ? \"absent\" : \"present\"\n}\n\n/** The functype-react component that renders both cases of the container a predicate belongs to. */\nexport const MATCH_COMPONENT: Readonly<Record<string, string>> = {\n isSome: \"MatchOption\",\n isNone: \"MatchOption\",\n isLeft: \"MatchEither\",\n isRight: \"MatchEither\",\n isSuccess: \"MatchTry\",\n isFailure: \"MatchTry\",\n}\n"],"mappings":"AAKA,MAAaA,kBAA2C,IAAI,IAAI,CAAC,SAAU,UAAW,WAAW,CAAC,EAIrFC,kBAA2C,IAAI,IAAI,CAAC,SAAU,SAAU,WAAW,CAAC,EAGpFC,EAAWC,GAAyBA,EAAK,QAAQ,OAAQ,EAAE,EAe3DC,GAAiBC,EAAeC,IAAiD,CAC5F,GAAID,GAAM,OAAS,kBAAoBA,EAAK,UAAU,SAAW,EAAG,OAAO,KAC3E,IAAME,EAASF,EAAK,OACpB,GAAIE,EAAO,OAAS,oBAAsBA,EAAO,UAAYA,EAAO,SAAS,OAAS,aAAc,OAAO,KAC3G,IAAMC,EAASD,EAAO,SAAS,KACzBE,EAAYR,EAAoB,IAAIO,CAAM,EAEhD,MADI,CAACC,GAAa,CAACT,EAAoB,IAAIQ,CAAM,EAAU,KACpD,CAAE,SAAUD,EAAO,OAAQ,aAAcL,EAAQI,EAAW,QAAQC,EAAO,MAAM,CAAC,EAAGC,SAAQC,WAAU,CAChH,EAOaC,GAAmBC,EAAeL,IAAiD,CAC9F,GAAIK,GAAM,OAAS,mBAAqBA,EAAK,WAAa,IAAK,CAC7D,IAAMC,EAAQF,EAAgBC,EAAK,SAAUL,CAAU,EACvD,OAAOM,IAAU,KAAO,KAAO,CAAE,GAAGA,EAAO,UAAW,CAACA,EAAM,SAAU,CACzE,CAIA,OAHID,GAAM,OAAS,sBAAwBA,EAAK,WAAa,MAAQA,EAAK,WAAa,MAC9ED,EAAgBC,EAAK,KAAML,CAAU,GAAKI,EAAgBC,EAAK,MAAOL,CAAU,EAElFF,EAAcO,EAAML,CAAU,CACvC,EAMMO,GAAeR,EAAeS,EAAsBR,IACxDD,GAAM,OAAS,oBACf,CAACA,EAAK,UACNA,EAAK,SAAS,OAAS,cACvBA,EAAK,SAAS,OAAS,YACrBA,EAAK,QAAQ,OAAS,kBAAoBA,EAAK,OAAO,SAAWA,IACnEH,EAAQI,EAAW,QAAQD,EAAK,MAAM,CAAC,IAAMS,EAOlCC,GAAcJ,EAAeK,EAAkBF,EAAsBR,IAAqC,CACrH,IAAMW,GAAQZ,EAAea,IAA6BH,EAAWV,EAAMa,EAAOJ,EAAcR,CAAU,EAC1G,GAAIK,GAAM,OAAS,mBAAqBA,EAAK,WAAa,IAAK,OAAOM,EAAKN,EAAK,SAAU,CAACK,CAAO,EAClG,GAAIL,GAAM,OAAS,sBAAwBA,EAAK,WAAa,MAAQA,EAAK,WAAa,MAAO,CAC5F,IAAMQ,EAAOF,EAAKN,EAAK,KAAMK,CAAO,EAC9BI,EAAQH,EAAKN,EAAK,MAAOK,CAAO,EAGtC,OADKL,EAAK,WAAa,OAAUK,EAAgBG,GAAQC,EAClDD,IAASC,EAAQD,EAAO,IACjC,CACA,IAAME,EAAYjB,EAAcO,EAAML,CAAU,EAC1CgB,EACJD,IAAc,MAAQA,EAAU,eAAiBP,EAC7CO,EAAU,UACVR,EAAYF,EAAMG,EAAcR,CAAU,EACxC,GACA,KAER,OADIgB,IAAkB,KAAa,KAC5BA,IAAkBN,EAAU,SAAW,SAChD,EAGaO,EAAoD,CAC/D,OAAQ,cACR,OAAQ,cACR,OAAQ,cACR,QAAS,cACT,UAAW,WACX,UAAW,UACb,E"}
|
|
@@ -1,5 +1,5 @@
|
|
|
1
|
-
import { ASTNode } from "../types/ast.js";
|
|
2
1
|
import { Rule } from "eslint";
|
|
2
|
+
import { ASTNode } from "../types/ast.js";
|
|
3
3
|
/**
|
|
4
4
|
* Router helpers whose return value a loader or route guard throws to redirect or show Not found
|
|
5
5
|
* (#445). The throw is the framework's API, not an error path: returning `Either.left(…)` instead
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"host-throws.js","names":["DEFAULT_HOST_THROWS","HOST_THROWS_SCHEMA","hostThrowsWith","
|
|
1
|
+
{"version":3,"file":"host-throws.js","names":["DEFAULT_HOST_THROWS","HOST_THROWS_SCHEMA","hostThrowsWith","overrides","modules","module","added","names","importOf","identifier","context","def","reference","importedName","specifier","isHostThrow","argument","hostThrows","callee","name"],"sources":["../../src/utils/host-throws.ts"],"sourcesContent":["import type { Rule } from \"eslint\"\n\nimport type { ASTNode } from \"../types/ast\"\n\n/**\n * Router helpers whose return value a loader or route guard throws to redirect or show Not found\n * (#445). The throw is the framework's API, not an error path: returning `Either.left(…)` instead\n * breaks it. Each name was checked against the package's exports on 2026-10-31. React Router 6 loaders\n * import from react-router-dom, and Remix on Workers from @remix-run/cloudflare.\n */\nexport const DEFAULT_HOST_THROWS: Readonly<Record<string, ReadonlyArray<string>>> = {\n \"@tanstack/react-router\": [\"redirect\", \"notFound\"],\n \"@tanstack/router-core\": [\"redirect\", \"notFound\"],\n \"react-router\": [\"redirect\", \"redirectDocument\", \"replace\", \"data\"],\n \"react-router-dom\": [\"redirect\", \"redirectDocument\", \"replace\", \"data\", \"json\"],\n \"@remix-run/node\": [\"redirect\", \"redirectDocument\", \"replace\", \"data\", \"json\"],\n \"@remix-run/cloudflare\": [\"redirect\", \"redirectDocument\", \"replace\", \"data\", \"json\"],\n}\n\nexport const HOST_THROWS_SCHEMA = {\n type: \"object\",\n additionalProperties: { type: \"array\", items: { type: \"string\" } },\n} as const\n\n/**\n * The defaults with a project's own `hostThrows` added: naming a module adds helpers to its defaults,\n * so `{ \"react-router\": [\"myRedirect\"] }` keeps `redirect` and the rest, and `[]` turns that module's\n * defaults off. A module the defaults don't name is added.\n */\nexport const hostThrowsWith = (\n overrides: Readonly<Record<string, ReadonlyArray<string>>> | undefined,\n): ReadonlyMap<string, ReadonlySet<string>> => {\n const modules = new Set([...Object.keys(DEFAULT_HOST_THROWS), ...Object.keys(overrides ?? {})])\n return new Map(\n [...modules].map((module) => {\n const added = overrides?.[module]\n const names =\n added !== undefined && added.length === 0 ? [] : [...(DEFAULT_HOST_THROWS[module] ?? []), ...(added ?? [])]\n return [module, new Set(names)]\n }),\n )\n}\n\ntype ImportDef = {\n readonly type: string\n readonly node: ASTNode\n readonly parent?: ASTNode | null\n}\n\n/** The import an identifier is bound to, through scope, so a local helper of the same name isn't one. */\nfunction importOf(identifier: ASTNode, context: Rule.RuleContext): ImportDef | undefined {\n const variable = context.sourceCode\n .getScope(identifier)\n .references.find((reference) => reference.identifier === identifier)?.resolved\n const def = variable?.defs[0] as unknown as ImportDef | undefined\n return def?.type === \"ImportBinding\" ? def : undefined\n}\n\n/** The name a specifier imports: `redirect` for `import { redirect as go }`. */\nconst importedName = (specifier: ASTNode): string | undefined =>\n specifier.type === \"ImportSpecifier\"\n ? (specifier.imported.name ?? specifier.imported.value)\n : specifier.type === \"ImportDefaultSpecifier\"\n ? \"default\"\n : undefined\n\n/**\n * Is `argument`, the value a `throw` throws, a call to a host helper? `throw redirect(…)` and\n * `throw notFound()` with the name imported from a listed module, under any local name, or\n * `throw Router.redirect(…)` through a namespace import of one.\n */\nexport function isHostThrow(\n argument: ASTNode | null | undefined,\n hostThrows: ReadonlyMap<string, ReadonlySet<string>>,\n context: Rule.RuleContext,\n): boolean {\n if (argument?.type !== \"CallExpression\") return false\n const callee = argument.callee as ASTNode\n if (callee.type === \"Identifier\") {\n const def = importOf(callee, context)\n const module = def?.parent?.source?.value as string | undefined\n const name = def ? importedName(def.node) : undefined\n return module !== undefined && name !== undefined && hostThrows.get(module)?.has(name) === true\n }\n if (callee.type !== \"MemberExpression\" || callee.computed || callee.object.type !== \"Identifier\") return false\n const def = importOf(callee.object as ASTNode, context)\n if (def?.node.type !== \"ImportNamespaceSpecifier\") return false\n const module = def.parent?.source?.value as string | undefined\n return module !== undefined && hostThrows.get(module)?.has(callee.property.name) === true\n}\n"],"mappings":"AAUA,MAAaA,EAAuE,CAClF,yBAA0B,CAAC,WAAY,UAAU,EACjD,wBAAyB,CAAC,W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