eslint-plugin-functype 2.121.1 → 2.123.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 +147 -24
- package/dist/configs/agent.d.ts +45 -0
- package/dist/configs/agent.js +2 -0
- package/dist/configs/agent.js.map +1 -0
- package/dist/configs/recommended.d.ts +10 -0
- package/dist/configs/recommended.js +1 -1
- package/dist/configs/recommended.js.map +1 -1
- package/dist/configs/strict.d.ts +2 -0
- package/dist/configs/strict.js +1 -1
- package/dist/configs/strict.js.map +1 -1
- package/dist/index.d.ts +2 -0
- package/dist/index.js +1 -1
- package/dist/index.js.map +1 -1
- package/dist/rules/index.d.ts +19 -15
- package/dist/rules/index.js +1 -1
- package/dist/rules/index.js.map +1 -1
- package/dist/rules/no-floating-result.d.ts +19 -0
- package/dist/rules/no-floating-result.js +2 -0
- package/dist/rules/no-floating-result.js.map +1 -0
- package/dist/rules/no-serialize-container.d.ts +16 -0
- package/dist/rules/no-serialize-container.js +2 -0
- package/dist/rules/no-serialize-container.js.map +1 -0
- package/dist/rules/prefer-do-notation.js +1 -4
- package/dist/rules/prefer-do-notation.js.map +1 -1
- package/dist/rules/prefer-either.js +1 -1
- package/dist/rules/prefer-either.js.map +1 -1
- package/dist/rules/prefer-option.js +1 -1
- package/dist/rules/prefer-option.js.map +1 -1
- package/dist/utils/host-throws.d.ts +33 -0
- package/dist/utils/host-throws.js +2 -0
- package/dist/utils/host-throws.js.map +1 -0
- package/dist/utils/type-aware.d.ts +24 -0
- package/dist/utils/type-aware.js +1 -1
- package/dist/utils/type-aware.js.map +1 -1
- package/package.json +2 -2
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"prefer-do-notation.js","names":["MONAD_TYPES","NON_CHILD_KEYS","union","a","b","monadAt","node","callee","astChildren","k","v","monadsIn","ast","acc","child","CHAIN_METHODS","COMPOSITION_METHODS","getChainDepth","method","next","compositionChainDepth","isCompositionChain","andChainDepth","rhs","rule","options","context","minChainDepth","detectMixedMonads","functypeImports","getFunctypeImports","hasDoImport","checkNestedNullChecks","hasNestedPropertyAccess","fixNestedChecks","fixer","matches","checkChainedMethods","isChainedMethodCall","chainDepth","fixChainedMethods","text","match","baseVar","doNotation","checkMixedMonads"],"sources":["../../src/rules/prefer-do-notation.ts"],"sourcesContent":["import type { Rule } from \"eslint\"\n\nimport type { ASTNode } from \"../types/ast\"\nimport { getFunctypeImports, isChainedMethodCall } from \"../utils/functype-detection\"\n\nconst MONAD_TYPES: ReadonlySet<string> = new Set([\"Option\", \"Either\", \"Try\", \"Task\"])\n\n/** AST keys that don't represent syntax children — back-edges and source metadata. */\nconst NON_CHILD_KEYS: ReadonlySet<string> = new Set([\"parent\", \"loc\", \"range\"])\n\nconst union = <T>(a: ReadonlySet<T>, b: ReadonlySet<T>): ReadonlySet<T> => new Set([...a, ...b])\n\n/**\n * Set of monad names that *this single AST node* names as a constructor call.\n * Does not look at children. Returns empty set for any non-monad-constructor node.\n */\nfunction monadAt(node: ASTNode): ReadonlySet<string> {\n if (node.type !== \"CallExpression\") return new Set()\n const callee = node.callee\n // Bare constructor: Option(...), Try(...), Either(...), Task(...)\n if (callee?.type === \"Identifier\" && MONAD_TYPES.has(callee.name)) {\n return new Set([callee.name])\n }\n // Companion call: Option.none(), Either.right(x), Try.success(v)\n if (\n callee?.type === \"MemberExpression\" &&\n callee.object?.type === \"Identifier\" &&\n MONAD_TYPES.has(callee.object.name)\n ) {\n return new Set([callee.object.name])\n }\n return new Set()\n}\n\n/**\n * AST children of `node` worth recursing into. Drops back-edges and source\n * metadata; flattens array-valued keys (e.g. `arguments`); filters non-object\n * leaves (literals, raw strings, numbers).\n */\nfunction astChildren(node: ASTNode): readonly unknown[] {\n return Object.entries(node)\n .filter(([k]) => !NON_CHILD_KEYS.has(k))\n .flatMap(([, v]) => (Array.isArray(v) ? v : [v]))\n .filter((v) => v !== null && typeof v === \"object\")\n}\n\n/**\n * Pure recursion: the set of all monad names reachable from `node` (including\n * `node` itself if it is a monad constructor call). No mutation, no\n * accumulator parameter — just a fold over the children's results.\n */\nfunction monadsIn(node: unknown): ReadonlySet<string> {\n if (!node || typeof node !== \"object\") return new Set()\n const ast = node as ASTNode\n return astChildren(ast).reduce<ReadonlySet<string>>((acc, child) => union(acc, monadsIn(child)), monadAt(ast))\n}\n\nconst CHAIN_METHODS: ReadonlySet<string> = new Set([\"flatMap\", \"map\", \"filter\", \"fold\"])\n\n/**\n * Methods that *compose* monadic operations (stay in the monad and feed the\n * next step). Distinct from terminal handlers (`fold`, `match`, `getOrElse`)\n * which *exit* the monad — those are conversions, not composition, and Do\n * notation doesn't apply to them.\n */\nconst COMPOSITION_METHODS: ReadonlySet<string> = new Set([\"flatMap\", \"map\", \"filter\"])\n\n/**\n * Length of the chain of `.flatMap()/.map()/.filter()/.fold()` calls walking\n * left from `node`. Returns 1 for a single call, N for N stacked calls. Pure\n * tail recursion — no mutable counter, no `while` loop.\n */\nfunction getChainDepth(node: ASTNode): number {\n if (node.callee.type !== \"MemberExpression\" || node.callee.object.type !== \"CallExpression\") return 1\n const method = node.callee.property\n const next = node.callee.object as ASTNode\n const here = method.type === \"Identifier\" && CHAIN_METHODS.has(method.name) ? 1 : 0\n return here + getChainDepth(next)\n}\n\n/**\n * Number of composition methods (`flatMap`/`map`/`filter`) stacked under\n * `node` via `.callee.object`. 0 if the callee isn't a member expression on\n * another call. Excludes terminal handlers by design.\n */\nfunction compositionChainDepth(node: ASTNode): number {\n if (node.callee?.type !== \"MemberExpression\" || node.callee.object?.type !== \"CallExpression\") return 0\n const method = node.callee.property\n const next = node.callee.object as ASTNode\n const here = method.type === \"Identifier\" && COMPOSITION_METHODS.has(method.name) ? 1 : 0\n return here + compositionChainDepth(next)\n}\n\n/**\n * True when `node`'s outermost call is a composition method AND at least one\n * more composition method appears below it — i.e. this is a real\n * `.flatMap(...).flatMap(...)`-style chain, not a terminal exit like\n * `.fold(...)` or a bare receiver like `option.flatMap(...)`.\n */\nfunction isCompositionChain(node: ASTNode): boolean {\n if (node.callee?.type !== \"MemberExpression\") return false\n const method = node.callee.property\n if (method.type !== \"Identifier\" || !COMPOSITION_METHODS.has(method.name)) return false\n return compositionChainDepth(node) >= 1\n}\n\n/**\n * Depth of a logical-AND chain (`a && b && c && ...`) where each right-hand\n * side is either a MemberExpression or another && chain — the shape that\n * indicates nested property-access guarding rather than arbitrary booleans.\n */\nfunction andChainDepth(node: ASTNode): number {\n if (node.type !== \"LogicalExpression\" || node.operator !== \"&&\") return 0\n const rhs = node.right\n const here = rhs.type === \"MemberExpression\" || (rhs.type === \"LogicalExpression\" && rhs.operator === \"&&\") ? 1 : 0\n return here + andChainDepth(node.left as ASTNode)\n}\n\nconst rule: Rule.RuleModule = {\n meta: {\n type: \"suggestion\",\n docs: {\n description: \"Prefer Do notation for complex monadic compositions and nested operations\",\n recommended: true,\n },\n fixable: \"code\",\n messages: {\n preferDoForNestedChecks: \"Prefer Do notation for nested null/undefined checks instead of logical AND chains\",\n preferDoForChainedMethods: \"Prefer Do notation for complex flatMap chains ({{count}} levels deep)\",\n preferDoForMixedMonads: \"Consider Do notation when mixing Option, Either, and Try operations\",\n preferDoAsyncForChainedTasks: \"Prefer DoAsync notation for chained async operations\",\n },\n schema: [\n {\n type: \"object\",\n properties: {\n minChainDepth: {\n type: \"integer\",\n minimum: 2,\n default: 3,\n },\n detectMixedMonads: {\n type: \"boolean\",\n default: true,\n },\n },\n additionalProperties: false,\n },\n ],\n },\n create(context) {\n const options = context.options[0] || {}\n const minChainDepth = options.minChainDepth || 3\n const detectMixedMonads = options.detectMixedMonads !== false\n\n const functypeImports = getFunctypeImports(context)\n\n // Track if Do notation is already imported\n const hasDoImport = functypeImports.functions.has(\"Do\") || functypeImports.functions.has(\"DoAsync\")\n\n /**\n * Detect nested null/undefined checks like: a && a.b && a.b.c\n */\n function checkNestedNullChecks(node: ASTNode): void {\n if (node.operator !== \"&&\") return\n\n // Check if this looks like nested property access guarding\n if (andChainDepth(node) >= 2 && hasNestedPropertyAccess(node)) {\n context.report({\n node,\n messageId: \"preferDoForNestedChecks\",\n fix: hasDoImport ? (fixer) => fixNestedChecks(fixer, node) : undefined,\n })\n }\n }\n\n /**\n * Check if logical expression contains nested property access patterns\n */\n function hasNestedPropertyAccess(node: ASTNode): boolean {\n // Look for patterns like: obj && obj.prop && obj.prop.nested\n const matches = context.sourceCode.getText(node).match(/\\w+(\\.\\w+){2,}/g)\n return matches !== null && matches.length > 0\n }\n\n /**\n * Detect long flatMap chains\n */\n function checkChainedMethods(node: ASTNode): void {\n if (!isChainedMethodCall(node, \"flatMap\")) return\n\n const chainDepth = getChainDepth(node)\n\n if (chainDepth >= minChainDepth) {\n context.report({\n node,\n messageId: \"preferDoForChainedMethods\",\n data: { count: chainDepth.toString() },\n fix: hasDoImport ? (fixer) => fixChainedMethods(fixer, node) : undefined,\n })\n }\n }\n\n /**\n * Auto-fix for nested null checks\n */\n function fixNestedChecks(fixer: Rule.RuleFixer, node: ASTNode): Rule.Fix {\n const text = context.sourceCode.getText(node)\n\n // Simple transformation for common patterns\n // a && a.b && a.b.c -> Do(function* () { const x = yield* $(Option(a)); const y = yield* $(Option(x.b)); return Option(y.c) })\n const match = text.match(/(\\w+)(\\.\\w+)+/)\n if (match) {\n const baseVar = match[1]\n const chain = match[0]\n\n const doNotation = `Do(function* () {\n const obj = yield* $(Option(${baseVar}))\n return yield* $(Option(obj${chain.substring(baseVar.length)}))\n})`\n\n return fixer.replaceText(node, doNotation)\n }\n\n return fixer.replaceText(node, `/* TODO: Convert to Do notation */ ${text}`)\n }\n\n /**\n * Auto-fix for chained methods (basic)\n */\n function fixChainedMethods(fixer: Rule.RuleFixer, node: ASTNode): Rule.Fix {\n const text = context.sourceCode.getText(node)\n\n // For now, just add a comment suggesting Do notation\n return fixer.replaceText(node, `/* TODO: Consider Do notation for complex chains */ ${text}`)\n }\n\n /**\n * Detect mixed monad usage by walking the AST under `node` and counting\n * *distinct* monad constructor calls — not substring matches.\n *\n * A \"monad constructor call\" is a CallExpression whose callee is either:\n * - a bare identifier matching a known monad type (`Option(...)`, `Try(...)`),\n * or\n * - a member expression whose object is a known monad type\n * (`Option.none()`, `Either.right(...)`, `Try.success(...)`).\n *\n * Method calls like `.toEither(...)`, `.toOption()`, `.toTry()` are NOT\n * constructor calls — they're the idiomatic *conversion* API for crossing\n * monad boundaries. The old substring-based check fired on these because\n * `.toEither` contains \"Either\" as a substring; the AST check correctly\n * sees them as method calls, not new monad constructions.\n *\n * Implementation is pure recursion over the AST: `monadAt` reports what\n * a single node names; `monadsIn` returns the union of `monadAt(self)`\n * with the results from each child. No mutable accumulator, no for-loops\n * driving state changes.\n */\n function checkMixedMonads(node: ASTNode): void {\n if (!detectMixedMonads) return\n // Only flag genuine composition chains (.flatMap/.map/.filter stacked at\n // least twice deep). Terminal handlers (.fold/.match/.getOrElse) and\n // bare co-occurrence in arg lists are conversions, not compositions —\n // Do notation doesn't apply. See issue #205.\n if (!isCompositionChain(node)) return\n if (monadsIn(node).size >= 2) {\n context.report({ node, messageId: \"preferDoForMixedMonads\" })\n }\n }\n\n return {\n LogicalExpression(node) {\n checkNestedNullChecks(node)\n },\n\n CallExpression(node) {\n checkChainedMethods(node)\n checkMixedMonads(node)\n },\n }\n },\n}\n\nexport default rule\n"],"mappings":"6FAKA,MAAMA,kBAAmC,IAAI,IAAI,CAAC,SAAU,SAAU,MAAO,MAAM,CAAC,EAG9EC,kBAAsC,IAAI,IAAI,CAAC,SAAU,MAAO,OAAO,CAAC,EAExEC,GAAY,EAAmB,oBAAsC,IAAI,IAAI,CAAC,GAAGC,EAAG,GAAGC,CAAC,CAAC,EAM/F,SAASC,EAAQ,EAAoC,CACnD,GAAIC,EAAK,OAAS,iBAAkB,sBAAO,IAAI,IAC/C,IAAMC,EAASD,EAAK,OAapB,OAXIC,GAAQ,OAAS,cAAgBP,EAAY,IAAIO,EAAO,IAAI,kBACvD,IAAI,IAAI,CAACA,EAAO,IAAI,CAAC,EAI5BA,GAAQ,OAAS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,CAAI,EACxBuC,EAAiBvC,CAAI,CACvB,CACF,CACF,CACF"}
|
|
1
|
+
{"version":3,"file":"prefer-do-notation.js","names":["MONAD_TYPES","NON_CHILD_KEYS","union","a","b","monadAt","node","callee","astChildren","k","v","CHAIN_METHODS","FLAT_MAP","COMPOSITION_METHODS","getChainDepth","method","compositionChainDepth","next","isCompositionChain","andOperands","isPathStart","NONE","FUNCTION_TYPES","monadOfAnnotation","type","annotation","MONAD_NAME","MONAD_SUFFIX","CONVERSIONS","monadOfValue","converted","chainRoot","rule","options","context","minChainDepth","detectMixedMonads","text","declaredMonad","declared","identifier","reference","onMonad","byType","isExtractableByType","step","root","nextStep","member","call","hasStepAbove","methods","checkNestedNullChecks","parent","operands","previous","i","run","operand","acc","checkChainedMethods","isChainedMethodCall","chainDepth","returnedBy","callback","body","returns","monadsAlongChain","returned","checkMixedMonads"],"sources":["../../src/rules/prefer-do-notation.ts"],"sourcesContent":["import type { Rule } from \"eslint\"\n\nimport type { ASTNode } from \"../types/ast\"\nimport { isChainedMethodCall } from \"../utils/functype-detection\"\nimport { isExtractableByType } from \"../utils/type-aware\"\n\nconst MONAD_TYPES: ReadonlySet<string> = new Set([\"Option\", \"Either\", \"Try\", \"Task\"])\n\n/** AST keys that don't represent syntax children — back-edges and source metadata. */\nconst NON_CHILD_KEYS: ReadonlySet<string> = new Set([\"parent\", \"loc\", \"range\"])\n\nconst union = <T>(a: ReadonlySet<T>, b: ReadonlySet<T>): ReadonlySet<T> => new Set([...a, ...b])\n\n/**\n * Set of monad names that *this single AST node* names as a constructor call.\n * Does not look at children. Returns empty set for any non-monad-constructor node.\n */\nfunction monadAt(node: ASTNode): ReadonlySet<string> {\n if (node.type !== \"CallExpression\") return new Set()\n const callee = node.callee\n // Bare constructor: Option(...), Try(...), Either(...), Task(...)\n if (callee?.type === \"Identifier\" && MONAD_TYPES.has(callee.name)) {\n return new Set([callee.name])\n }\n // Companion call: Option.none(), Either.right(x), Try.success(v)\n if (\n callee?.type === \"MemberExpression\" &&\n callee.object?.type === \"Identifier\" &&\n MONAD_TYPES.has(callee.object.name)\n ) {\n return new Set([callee.object.name])\n }\n return new Set()\n}\n\n/**\n * AST children of `node` worth recursing into. Drops back-edges and source\n * metadata; flattens array-valued keys (e.g. `arguments`); filters non-object\n * leaves (literals, raw strings, numbers).\n */\nfunction astChildren(node: ASTNode): readonly unknown[] {\n return Object.entries(node)\n .filter(([k]) => !NON_CHILD_KEYS.has(k))\n .flatMap(([, v]) => (Array.isArray(v) ? v : [v]))\n .filter((v) => v !== null && typeof v === \"object\")\n}\n\nconst CHAIN_METHODS: ReadonlySet<string> = new Set([\"flatMap\", \"map\", \"filter\", \"fold\"])\n\nconst FLAT_MAP: ReadonlySet<string> = new Set([\"flatMap\"])\n\n/**\n * Methods that *compose* monadic operations (stay in the monad and feed the\n * next step). Distinct from terminal handlers (`fold`, `match`, `getOrElse`)\n * which *exit* the monad — those are conversions, not composition, and Do\n * notation doesn't apply to them.\n */\nconst COMPOSITION_METHODS: ReadonlySet<string> = new Set([\"flatMap\", \"map\", \"filter\"])\n\n/**\n * Number of `.flatMap()/.map()/.filter()/.fold()` steps walking left from `node`. Only the steps\n * count: the receiver they start from, `o` or `Option(x)`, is not a level, so\n * `Option(x).flatMap(f).flatMap(g)` is 2 deep.\n */\nfunction getChainDepth(node: ASTNode): number {\n if (node.type !== \"CallExpression\" || node.callee?.type !== \"MemberExpression\") return 0\n const method = node.callee.property\n const here = method.type === \"Identifier\" && CHAIN_METHODS.has(method.name) ? 1 : 0\n return here + getChainDepth(node.callee.object as ASTNode)\n}\n\n/**\n * Number of composition methods (`flatMap`/`map`/`filter`) stacked under\n * `node` via `.callee.object`. 0 if the callee isn't a member expression on\n * another call. Excludes terminal handlers by design.\n */\nfunction compositionChainDepth(node: ASTNode): number {\n if (node.callee?.type !== \"MemberExpression\" || node.callee.object?.type !== \"CallExpression\") return 0\n const method = node.callee.property\n const next = node.callee.object as ASTNode\n const here = method.type === \"Identifier\" && COMPOSITION_METHODS.has(method.name) ? 1 : 0\n return here + compositionChainDepth(next)\n}\n\n/**\n * True when `node`'s outermost call is a composition method AND at least one\n * more composition method appears below it — i.e. this is a real\n * `.flatMap(...).flatMap(...)`-style chain, not a terminal exit like\n * `.fold(...)` or a bare receiver like `option.flatMap(...)`.\n */\nfunction isCompositionChain(node: ASTNode): boolean {\n if (node.callee?.type !== \"MemberExpression\") return false\n const method = node.callee.property\n if (method.type !== \"Identifier\" || !COMPOSITION_METHODS.has(method.name)) return false\n return compositionChainDepth(node) >= 1\n}\n\n/** The operands of an `a && b && c` chain, left to right, through any nesting of `&&`. */\nfunction andOperands(node: ASTNode): ReadonlyArray<ASTNode> {\n if (node.type !== \"LogicalExpression\" || node.operator !== \"&&\") return [node]\n return [...andOperands(node.left as ASTNode), ...andOperands(node.right as ASTNode)]\n}\n\n/** A plain property path a guard can start from: `a`, `this`, `a.b`. Optional chains are already the fix. */\nconst isPathStart = (node: ASTNode): boolean =>\n node.type === \"Identifier\" || node.type === \"ThisExpression\" || node.type === \"MemberExpression\"\n\nconst NONE: ReadonlySet<string> = new Set()\n\nconst FUNCTION_TYPES: ReadonlySet<string> = new Set([\n \"ArrowFunctionExpression\",\n \"FunctionExpression\",\n \"FunctionDeclaration\",\n])\n\n/** `MONAD_TYPES` entries a type annotation names: `Option<number>` → Option. */\nfunction monadOfAnnotation(annotation: ASTNode | undefined): ReadonlySet<string> {\n const type = annotation?.typeAnnotation as ASTNode | undefined\n if (type?.type !== \"TSTypeReference\" || type.typeName?.type !== \"Identifier\") return NONE\n return MONAD_TYPES.has(type.typeName.name) ? new Set([type.typeName.name]) : NONE\n}\n\n/**\n * Receiver names that say \"this holds a monad\", for code linted without type information: `option`,\n * `opt`, `either`, `result`, `maybe`, `task`, or a numbered one such as `option1`, in any case; or a\n * camelCase suffix such as `userOption` or `parseResult`, which must be capitalized, so `entry`,\n * `retry` and `registry` don't count.\n */\nconst MONAD_NAME = /^(option|opt|either|result|maybe|task)\\d*$/i\nconst MONAD_SUFFIX = /[a-z0-9](Option|Either|Result|Maybe|Try|Task)\\d*$/\n\n/** Methods that turn one monad into another: `Try(f).toOption()` is an Option. */\nconst CONVERSIONS: ReadonlyMap<string, string> = new Map([\n [\"toOption\", \"Option\"],\n [\"toEither\", \"Either\"],\n [\"toTry\", \"Try\"],\n])\n\n/**\n * The monad an expression's value is, as far as the syntax shows: a constructor or companion call\n * (`Option(x)`, `Either.right(x)`), a conversion (`Try(f).toOption()` is an Option), a step that keeps\n * its receiver's monad (`Option(x).map(f)`), or either branch of `ok ? a : b`. Anything else is unknown.\n */\nfunction monadOfValue(node: ASTNode): ReadonlySet<string> {\n if (node.type === \"ConditionalExpression\")\n return union(monadOfValue(node.consequent as ASTNode), monadOfValue(node.alternate as ASTNode))\n if (node.type !== \"CallExpression\") return NONE\n if (monadAt(node).size > 0) return monadAt(node)\n if (node.callee?.type !== \"MemberExpression\" || node.callee.property.type !== \"Identifier\") return NONE\n const converted = CONVERSIONS.get(node.callee.property.name)\n if (converted !== undefined) return new Set([converted])\n return COMPOSITION_METHODS.has(node.callee.property.name) ? monadOfValue(node.callee.object as ASTNode) : NONE\n}\n\n/**\n * The receiver a method chain starts from: `Option(x)` in `Option(x).map(f).flatMap(g)`, `o` in\n * `o.flatMap(f)`. Walks back only through steps that keep the monad (`flatMap`, `map`, `filter`), so\n * in `Option(xs).getOrElse([]).flatMap(f)` or after a `.fold(…)` the root is the unwrapped value, not\n * `Option(xs)`. A monad constructor or companion\n * call is a root of its own.\n */\nfunction chainRoot(node: ASTNode): ASTNode {\n if (node.type !== \"CallExpression\" || monadAt(node).size > 0) return node\n if (node.callee?.type !== \"MemberExpression\" || node.callee.property.type !== \"Identifier\") return node\n if (!COMPOSITION_METHODS.has(node.callee.property.name)) return node\n return chainRoot(node.callee.object as ASTNode)\n}\n\nconst rule: Rule.RuleModule = {\n meta: {\n type: \"suggestion\",\n docs: {\n description: \"Prefer Do notation for complex monadic compositions and nested operations\",\n recommended: true,\n },\n messages: {\n preferDoForNestedChecks:\n \"This && chain guards each step of a property path. Use optional chaining (a?.b?.c), or Option(a).flatMap(…) when you want an Option\",\n preferDoForChainedMethods: \"Prefer Do notation for complex flatMap chains ({{count}} levels deep)\",\n preferDoForMixedMonads: \"Consider Do notation when mixing Option, Either, and Try operations\",\n preferDoAsyncForChainedTasks: \"Prefer DoAsync notation for chained async operations\",\n },\n schema: [\n {\n type: \"object\",\n properties: {\n minChainDepth: {\n type: \"integer\",\n minimum: 2,\n default: 3,\n },\n detectMixedMonads: {\n type: \"boolean\",\n default: true,\n },\n },\n additionalProperties: false,\n },\n ],\n },\n create(context) {\n const options = context.options[0] || {}\n const minChainDepth = options.minChainDepth || 3\n const detectMixedMonads = options.detectMixedMonads !== false\n const text = (node: ASTNode): string => context.sourceCode.getText(node).replace(/\\s+/g, \"\")\n\n /** The monad a chain root is declared as, through its variable's or parameter's annotation. */\n function declaredMonad(identifier: ASTNode): ReadonlySet<string> {\n const variable = context.sourceCode\n .getScope(identifier)\n .references.find((reference) => reference.identifier === identifier)?.resolved\n const declared = variable?.defs[0]?.name as ASTNode | undefined\n return monadOfAnnotation(declared?.typeAnnotation as ASTNode | undefined)\n }\n\n /**\n * Is `step` a step on a functype monad? With type information, the type of the value it's called on\n * decides, so a `string[]`, or an Option already unwrapped with `.getOrElse([])`, never counts, and\n * `service.getUser(1)` returning an Option does. Without it, the chain's root must be a monad\n * constructor, companion or conversion, an identifier annotated with a monad type, or one named\n * like a monad.\n */\n function onMonad(step: ASTNode): boolean {\n const byType = isExtractableByType(step.callee.object as ASTNode, context)\n if (byType !== undefined) return byType\n const root = chainRoot(step)\n if (monadOfValue(root).size > 0) return true\n if (root.type !== \"Identifier\") return false\n return declaredMonad(root).size > 0 || MONAD_NAME.test(root.name) || MONAD_SUFFIX.test(root.name)\n }\n\n /** The call that takes `node` as its receiver for a further `.flatMap/.map/.filter/.fold` step, if any. */\n function nextStep(node: ASTNode): ASTNode | undefined {\n const member = node.parent as ASTNode | undefined\n const call = member?.parent as ASTNode | undefined\n if (member?.type !== \"MemberExpression\" || member.object !== node) return undefined\n if (call?.type !== \"CallExpression\" || call.callee !== member) return undefined\n return member.property.type === \"Identifier\" && CHAIN_METHODS.has(member.property.name) ? call : undefined\n }\n\n /**\n * Is there a `methods` step further out on this chain? Then that step reports, once, for the whole\n * chain. A trailing `.fold(…)` or `.map(…)` isn't one, so it doesn't hide the flatMaps under it.\n */\n function hasStepAbove(node: ASTNode, methods: ReadonlySet<string>): boolean {\n const step = nextStep(node)\n if (step === undefined) return false\n const method = step.callee.property\n return (method.type === \"Identifier\" && methods.has(method.name)) || hasStepAbove(step, methods)\n }\n\n /**\n * `a && a.b && a.b.c`: at least three operands in a row, each a property of the one before it.\n * Matched on the AST, so `isAdmin && settings.theme && user.profile.name` is not a guard chain.\n */\n function checkNestedNullChecks(node: ASTNode): void {\n if (node.operator !== \"&&\") return\n const parent = node.parent as ASTNode | undefined\n if (parent?.type === \"LogicalExpression\" && parent.operator === \"&&\") return\n const operands = andOperands(node)\n const longestRun = operands.reduce<{ readonly run: number; readonly best: number }>(\n (acc, operand, i) => {\n const previous = operands[i - 1]\n const extends_ =\n previous !== undefined &&\n isPathStart(previous) &&\n operand.type === \"MemberExpression\" &&\n text(operand.object as ASTNode) === text(previous)\n const run = extends_ ? acc.run + 1 : 1\n return { run, best: Math.max(acc.best, run) }\n },\n { run: 0, best: 0 },\n ).best\n if (longestRun >= 3) context.report({ node, messageId: \"preferDoForNestedChecks\" })\n }\n\n /** A long `.flatMap(…)` chain on a monad, reported once at its outermost step. */\n function checkChainedMethods(node: ASTNode): void {\n if (!isChainedMethodCall(node, \"flatMap\") || hasStepAbove(node, FLAT_MAP)) return\n const chainDepth = getChainDepth(node)\n if (chainDepth < minChainDepth || !onMonad(node)) return\n context.report({\n node,\n messageId: \"preferDoForChainedMethods\",\n data: { count: chainDepth.toString() },\n })\n }\n\n /** What a step's callback returns: its expression body, or the arguments of its own `return`s. */\n function returnedBy(callback: ASTNode | undefined): ReadonlyArray<ASTNode> {\n if (callback?.type !== \"ArrowFunctionExpression\" && callback?.type !== \"FunctionExpression\") return []\n const body = callback.body as ASTNode\n if (body.type !== \"BlockStatement\") return [body]\n const returns = (node: ASTNode): ReadonlyArray<ASTNode> => {\n if (node.type === \"ReturnStatement\") return node.argument ? [node.argument as ASTNode] : []\n if (FUNCTION_TYPES.has(node.type)) return []\n return (astChildren(node) as ASTNode[]).flatMap(returns)\n }\n return returns(body)\n }\n\n /** The monads a composition chain moves through: its root, and what each step's callback returns. */\n function monadsAlongChain(node: ASTNode): ReadonlySet<string> {\n if (node.type === \"Identifier\") return declaredMonad(node)\n if (node.type !== \"CallExpression\" || node.callee?.type !== \"MemberExpression\") return monadAt(node)\n const method = node.callee.property\n const step =\n method.type === \"Identifier\" && COMPOSITION_METHODS.has(method.name)\n ? returnedBy(node.arguments[0] as ASTNode | undefined).reduce<ReadonlySet<string>>(\n (acc, returned) => union(acc, monadOfValue(returned)),\n NONE,\n )\n : NONE\n if (monadAt(node).size > 0) return union(step, monadAt(node))\n // From a conversion on, the chain is the converted monad: what it converted from doesn't count.\n const converted = method.type === \"Identifier\" ? CONVERSIONS.get(method.name) : undefined\n if (converted !== undefined) return union(step, new Set([converted]))\n return union(step, monadsAlongChain(node.callee.object as ASTNode))\n }\n\n /**\n * Mixed monads along one composition chain: `option.flatMap((x) => Either.right(x)).flatMap((y) => Try(…))`.\n * Only the chain's own steps count, not every monad written somewhere inside its callbacks, and\n * only a chain that starts from a monad: an array's `.map((x) => Option(x))` is not a mix.\n * Conversions such as `.toEither(…)` and terminal handlers such as `.fold(…)` are not steps (#205).\n */\n function checkMixedMonads(node: ASTNode): void {\n if (!detectMixedMonads || !isCompositionChain(node) || hasStepAbove(node, COMPOSITION_METHODS)) return\n if (!onMonad(node)) return\n if (monadsAlongChain(node).size >= 2) context.report({ node, messageId: \"preferDoForMixedMonads\" })\n }\n\n return {\n LogicalExpression(node) {\n checkNestedNullChecks(node)\n },\n\n CallExp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ags.js";import{HOST_THROWS_SCHEMA as t,hostThrowsWith as n,isHostThrow as r}from"../utils/host-throws.js";import{createImportFixer as i,hasFunctypeSymbol as a}from"../utils/import-fixer.js";function o(e){let t=e?.parent;return t?t.type===`CatchClause`||o(t):!1}const s={meta:{type:`suggestion`,hasSuggestions:!0,docs:{description:`Use Either/Left/Right for typed domain errors instead of throwing`,recommended:!0},schema:[{type:`object`,properties:{allowInteropMarker:{type:`boolean`,default:!0},allowThrowInTests:{type:`boolean`,default:!0},hostThrows:t},additionalProperties:!1}],messages:{preferEitherOverThrow:`Prefer Either.left(error) over throw statement. For a bug check use invariant(); for a host that needs the throw, tag the function @interop`,preferEitherReturn:`Consider returning Either<Error, {{type}}> instead of throwing. For a bug check use invariant(); for a host that needs the throw, tag the function @interop`,suggestEitherLeft:`Replace with Either.left(...)`,suggestAddImport:`Add {{symbol}} import from functype`}},create(t){let s=t.options[0]||{},c=s.allowInteropMarker!==!1,l=n=>c&&e(n,`interop`,t.sourceCode),u=s.allowThrowInTests!==!1,d=n(s.hostThrows);function f(){let e=t.filename;return/\.(test|spec)\.(ts|js|tsx|jsx)$/.test(e)||e.includes(`__tests__`)||e.includes(`/test/`)||e.includes(`/tests/`)}function p(e){let t=e.parent;return t?h(t)?t:p(t):null}function m(e){let n=e?.returnType?.typeAnnotation;if(!n)return null;let r=t.sourceCode.getText(n);return r.includes(`Either`)?null:r}function h(e){return e?[`FunctionDeclaration`,`FunctionExpression`,`ArrowFunctionExpression`].includes(e.type):!1}function g(e){let t=e.parent;if(!t)return!1;if(t.type===`BlockStatement`&&h(t.parent))return!0;if(t.type===`BlockStatement`&&t.parent?.type===`IfStatement`){let e=t.parent.parent;return e?.type===`BlockStatement`&&h(e.parent)}return!1}return{ThrowStatement(e){if(l(e)||r(e.argument,d,t)||u&&f()||o(e))return;let n=t.sourceCode,s=[];if(g(e)){let t=e.argument,r=n.getText(t),o=t?.type===`NewExpression`&&t.callee?.type===`Identifier`&&t.callee.name===`Error`?r:`new Error(String(${r}))`;s.push({messageId:`suggestEitherLeft`,fix(t){return t.replaceText(e,`return Either.left(${o})`)}}),a(n,`Either`)||s.push({messageId:`suggestAddImport`,data:{symbol:`Either`},fix:i(n,`Either`)})}let c=m(p(e));t.report({node:e,...c===null?{messageId:`preferEitherOverThrow`}:{messageId:`preferEitherReturn`,data:{type:c}},suggest:s})}}}};export{s as default};
|
|
2
2
|
//# sourceMappingURL=prefer-either.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"prefer-either.js","names":["insideCatchClause","parent","node","rule","options","context","allowInteropMarker","isExemptByMarker","isInsideTaggedDeclaration","allowThrowInTests","isInTestFile","filename","enclosingFunction","isFunctionLike","nonEitherReturnType","returnType","fn","text","isDirectInFunctionBody","ifParent","sourceCode","suggest","throwArg","argText","eitherArg","fixer","hasFunctypeSymbol","createImportFixer"],"sources":["../../src/rules/prefer-either.ts"],"sourcesContent":["import type { Rule } from \"eslint\"\n\nimport type { ASTNode } from \"../types/ast\"\nimport { INTEROP_TAG, isInsideTaggedDeclaration } from \"../utils/boundary-tags\"\nimport { createImportFixer, hasFunctypeSymbol } from \"../utils/import-fixer\"\n\n/** True iff any ancestor of `node` is a `CatchClause`. Pure tail recursion. */\nfunction insideCatchClause(node: ASTNode | null | undefined): boolean {\n const parent = node?.parent as ASTNode | undefined\n if (!parent) return false\n return parent.type === \"CatchClause\" || insideCatchClause(parent)\n}\n\nconst rule: Rule.RuleModule = {\n meta: {\n type: \"suggestion\",\n hasSuggestions: true,\n docs: {\n description: \"Use Either/Left/Right for typed domain errors instead of throwing\",\n recommended: true,\n },\n schema: [\n {\n type: \"object\",\n properties: {\n allowInteropMarker: {\n type: \"boolean\",\n default: true,\n },\n allowThrowInTests: {\n type: \"boolean\",\n default: true,\n },\n },\n additionalProperties: false,\n },\n ],\n messages: {\n preferEitherOverThrow:\n \"Prefer Either.left(error) over throw statement. For a bug check use invariant(); for a host that needs the throw, tag the function @interop\",\n preferEitherReturn:\n \"Consider returning Either<Error, {{type}}> instead of throwing. For a bug check use invariant(); for a host that needs the throw, tag the function @interop\",\n suggestEitherLeft: \"Replace with Either.left(...)\",\n suggestAddImport: \"Add {{symbol}} import from functype\",\n },\n },\n\n create(context) {\n const options = context.options[0] || {}\n // `@interop <reason>` on an enclosing declaration marks a host-contract boundary (#241).\n const allowInteropMarker = options.allowInteropMarker !== false\n // Bug checks are `invariant()` calls from functype (#342): a call, not a throw, so nothing to exempt.\n const isExemptByMarker = (node: ASTNode): boolean =>\n allowInteropMarker && isInsideTaggedDeclaration(node, INTEROP_TAG, context.sourceCode)\n const allowThrowInTests = options.allowThrowInTests !== false\n\n function isInTestFile() {\n const filename = context.filename\n return (\n /\\.(test|spec)\\.(ts|js|tsx|jsx)$/.test(filename) ||\n filename.includes(\"__tests__\") ||\n filename.includes(\"/test/\") ||\n filename.includes(\"/tests/\")\n )\n }\n\n /** The nearest function the throw belongs to — a nested function owns its own throws. */\n function enclosingFunction(node: ASTNode): ASTNode | null {\n const parent = node.parent\n if (!parent) return null\n return isFunctionLike(parent) ? parent : enclosingFunction(parent)\n }\n\n /** The declared return type when the function declares one that is not already an Either. */\n function nonEitherReturnType(fn: ASTNode | null): string | null {\n const returnType = fn?.returnType?.typeAnnotation\n if (!returnType) return null\n const text = context.sourceCode.getText(returnType)\n return text.includes(\"Either\") ? null : text\n }\n\n function isFunctionLike(node: ASTNode): boolean {\n if (!node) return false\n return [\"FunctionDeclaration\", \"FunctionExpression\", \"ArrowFunctionExpression\"].includes(node.type)\n }\n\n function isDirectInFunctionBody(node: ASTNode): boolean {\n const parent = node.parent\n if (!parent) return false\n if (parent.type === \"BlockStatement\" && isFunctionLike(parent.parent)) return true\n if (parent.type === \"BlockStatement\" && parent.parent?.type === \"IfStatement\") {\n const ifParent = parent.parent.parent\n return ifParent?.type === \"BlockStatement\" && isFunctionLike(ifParent.parent)\n }\n return false\n }\n\n return {\n ThrowStatement(node: ASTNode) {\n if (isExemptByMarker(node)) return\n // Allow throws in test files if configured\n if (allowThrowInTests && isInTestFile()) return\n\n // Allow re-throwing in catch blocks (common pattern)\n if (insideCatchClause(node)) return\n\n const sourceCode = context.sourceCode\n const suggest: Rule.SuggestionReportDescriptor[] = []\n\n if (isDirectInFunctionBody(node)) {\n const throwArg = node.argument\n const argText = sourceCode.getText(throwArg)\n const isErrorExpr =\n throwArg?.type === \"NewExpression\" &&\n throwArg.callee?.type === \"Identifier\" &&\n throwArg.callee.name === \"Error\"\n const eitherArg = isErrorExpr ? argText : `new Error(String(${argText}))`\n\n suggest.push({\n messageId: \"suggestEitherLeft\",\n fix(fixer) {\n return fixer.replaceText(node, `return Either.left(${eitherArg})`)\n },\n })\n\n if (!hasFunctypeSymbol(sourceCode, \"Either\")) {\n suggest.push({\n messageId: \"suggestAddImport\",\n data: { symbol: \"Either\" },\n fix: createImportFixer(sourceCode, \"Either\"),\n })\n }\n }\n\n // One report per throw (#324). When the enclosing function declares a non-Either return type,\n // the message names the Either it should return instead of reporting the function separately.\n const returnType = nonEitherReturnType(enclosingFunction(node))\n context.report({\n node,\n ...(returnType === null\n ? { messageId: \"preferEitherOverThrow\" }\n : { messageId: \"preferEitherReturn\", data: { type: returnType } }),\n suggest,\n })\n },\n }\n },\n}\n\nexport default rule\n"],"mappings":"
|
|
1
|
+
{"version":3,"file":"prefer-either.js","names":["insideCatchClause","parent","node","rule","HOST_THROWS_SCHEMA","options","context","allowInteropMarker","isExemptByMarker","isInsideTaggedDeclaration","allowThrowInTests","hostThrows","hostThrowsWith","isInTestFile","filename","enclosingFunction","isFunctionLike","nonEitherReturnType","returnType","fn","text","isDirectInFunctionBody","ifParent","isHostThrow","sourceCode","suggest","throwArg","argText","eitherArg","fixer","hasFunctypeSymbol","createImportFixer"],"sources":["../../src/rules/prefer-either.ts"],"sourcesContent":["import type { Rule } from \"eslint\"\n\nimport type { ASTNode } from \"../types/ast\"\nimport { INTEROP_TAG, isInsideTaggedDeclaration } from \"../utils/boundary-tags\"\nimport { HOST_THROWS_SCHEMA, hostThrowsWith, isHostThrow } from \"../utils/host-throws\"\nimport { createImportFixer, hasFunctypeSymbol } from \"../utils/import-fixer\"\n\n/** True iff any ancestor of `node` is a `CatchClause`. Pure tail recursion. */\nfunction insideCatchClause(node: ASTNode | null | undefined): boolean {\n const parent = node?.parent as ASTNode | undefined\n if (!parent) return false\n return parent.type === \"CatchClause\" || insideCatchClause(parent)\n}\n\nconst rule: Rule.RuleModule = {\n meta: {\n type: \"suggestion\",\n hasSuggestions: true,\n docs: {\n description: \"Use Either/Left/Right for typed domain errors instead of throwing\",\n recommended: true,\n },\n schema: [\n {\n type: \"object\",\n properties: {\n allowInteropMarker: {\n type: \"boolean\",\n default: true,\n },\n allowThrowInTests: {\n type: \"boolean\",\n default: true,\n },\n hostThrows: HOST_THROWS_SCHEMA,\n },\n additionalProperties: false,\n },\n ],\n messages: {\n preferEitherOverThrow:\n \"Prefer Either.left(error) over throw statement. For a bug check use invariant(); for a host that needs the throw, tag the function @interop\",\n preferEitherReturn:\n \"Consider returning Either<Error, {{type}}> instead of throwing. For a bug check use invariant(); for a host that needs the throw, tag the function @interop\",\n suggestEitherLeft: \"Replace with Either.left(...)\",\n suggestAddImport: \"Add {{symbol}} import from functype\",\n },\n },\n\n create(context) {\n const options = context.options[0] || {}\n // `@interop <reason>` on an enclosing declaration marks a host-contract boundary (#241).\n const allowInteropMarker = options.allowInteropMarker !== false\n // Bug checks are `invariant()` calls from functype (#342): a call, not a throw, so nothing to exempt.\n const isExemptByMarker = (node: ASTNode): boolean =>\n allowInteropMarker && isInsideTaggedDeclaration(node, INTEROP_TAG, context.sourceCode)\n const allowThrowInTests = options.allowThrowInTests !== false\n // `throw redirect(…)` / `throw notFound()` from a router is the router's API, not an error (#445).\n const hostThrows = hostThrowsWith(options.hostThrows)\n\n function isInTestFile() {\n const filename = context.filename\n return (\n /\\.(test|spec)\\.(ts|js|tsx|jsx)$/.test(filename) ||\n filename.includes(\"__tests__\") ||\n filename.includes(\"/test/\") ||\n filename.includes(\"/tests/\")\n )\n }\n\n /** The nearest function the throw belongs to — a nested function owns its own throws. */\n function enclosingFunction(node: ASTNode): ASTNode | null {\n const parent = node.parent\n if (!parent) return null\n return isFunctionLike(parent) ? parent : enclosingFunction(parent)\n }\n\n /** The declared return type when the function declares one that is not already an Either. */\n function nonEitherReturnType(fn: ASTNode | null): string | null {\n const returnType = fn?.returnType?.typeAnnotation\n if (!returnType) return null\n const text = context.sourceCode.getText(returnType)\n return text.includes(\"Either\") ? null : text\n }\n\n function isFunctionLike(node: ASTNode): boolean {\n if (!node) return false\n return [\"FunctionDeclaration\", \"FunctionExpression\", \"ArrowFunctionExpression\"].includes(node.type)\n }\n\n function isDirectInFunctionBody(node: ASTNode): boolean {\n const parent = node.parent\n if (!parent) return false\n if (parent.type === \"BlockStatement\" && isFunctionLike(parent.parent)) return true\n if (parent.type === \"BlockStatement\" && parent.parent?.type === \"IfStatement\") {\n const ifParent = parent.parent.parent\n return ifParent?.type === \"BlockStatement\" && isFunctionLike(ifParent.parent)\n }\n return false\n }\n\n return {\n ThrowStatement(node: ASTNode) {\n if (isExemptByMarker(node)) return\n if (isHostThrow(node.argument, hostThrows, context)) return\n // Allow throws in test files if configured\n if (allowThrowInTests && isInTestFile()) return\n\n // Allow re-throwing in catch blocks (common pattern)\n if (insideCatchClause(node)) return\n\n const sourceCode = context.sourceCode\n const suggest: Rule.SuggestionReportDescriptor[] = []\n\n if (isDirectInFunctionBody(node)) {\n const throwArg = node.argument\n const argText = sourceCode.getText(throwArg)\n const isErrorExpr =\n throwArg?.type === \"NewExpression\" &&\n throwArg.callee?.type === \"Identifier\" &&\n throwArg.callee.name === \"Error\"\n const eitherArg = isErrorExpr ? argText : `new Error(String(${argText}))`\n\n suggest.push({\n messageId: \"suggestEitherLeft\",\n fix(fixer) {\n return fixer.replaceText(node, `return Either.left(${eitherArg})`)\n },\n })\n\n if (!hasFunctypeSymbol(sourceCode, \"Either\")) {\n suggest.push({\n messageId: \"suggestAddImport\",\n data: { symbol: \"Either\" },\n fix: createImportFixer(sourceCode, \"Either\"),\n })\n }\n }\n\n // One report per throw (#324). When the enclosing function declares a non-Either return type,\n // the message names the Either it should return instead of reporting the function separately.\n const returnType = nonEitherReturnType(enclosingFunction(node))\n context.report({\n node,\n ...(returnType === null\n ? { messageId: \"preferEitherOverThrow\" }\n : { messageId: \"preferEitherReturn\", data: { type: returnType } }),\n suggest,\n })\n },\n }\n },\n}\n\nexport default rule\n"],"mappings":"4PAQA,SAASA,EAAkB,EAA2C,CACpE,IAAMC,EAASC,GAAM,OAErB,OADKD,EACEA,EAAO,OAAS,eAAiBD,EAAkBC,CAAM,EAD5C,EAEtB,CAEA,MAAME,EAAwB,CAC5B,KAAM,CACJ,KAAM,aACN,eAAgB,GAChB,KAAM,CACJ,YAAa,oEACb,YAAa,EACf,EACA,OAAQ,CACN,CACE,KAAM,SACN,WAAY,CACV,mBAAoB,CAClB,KAAM,UACN,QAAS,EACX,EACA,kBAAmB,CACjB,KAAM,UACN,QAAS,EACX,EACA,WAAYC,CACd,EACA,qBAAsB,EACxB,CACF,EACA,SAAU,CACR,sBACE,8IACF,mBACE,8JACF,kBAAmB,gCACnB,iBAAkB,qCACpB,CACF,EAEA,OAAO,EAAS,CACd,IAAMC,EAAUC,EAAQ,QAAQ,IAAM,CAAC,EAEjCC,EAAqBF,EAAQ,qBAAuB,GAEpDG,EAAoB,GACxBD,GAAsBE,EAA0BP,EAAA,UAAmBI,EAAQ,UAAU,EACjFI,EAAoBL,EAAQ,oBAAsB,GAElDM,EAAaC,EAAeP,EAAQ,UAAU,EAEpD,SAASQ,GAAe,CACtB,IAAMC,EAAWR,EAAQ,SACzB,MACE,kCAAkC,KAAKQ,CAAQ,GAC/CA,EAAS,SAAS,WAAW,GAC7BA,EAAS,SAAS,QAAQ,GAC1BA,EAAS,SAAS,SAAS,CAE/B,CAGA,SAASC,EAAkB,EAA+B,CACxD,IAAMd,EAASC,EAAK,OAEpB,OADKD,EACEe,EAAef,CAAM,EA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Y,QAAQ,GACzCC,EAAQ,KAAK,CACX,UAAW,mBACX,KAAM,CAAE,OAAQ,QAAS,EACzB,IAAKM,EAAkBP,EAAY,QAAQ,CAC7C,CAAC,CAEL,CAIA,IAAMN,EAAaD,EAAoBF,EAAkBb,CAAI,CAAC,EAC9DI,EAAQ,OAAO,CACb,OACA,GAAIY,IAAe,KACf,CAAE,UAAW,uBAAwB,EACrC,CAAE,UAAW,qBAAsB,KAAM,CAAE,KAAMA,CAAW,CAAE,EAClE,SACF,CAAC,CACH,CACF,CACF,CACF"}
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import{isInsideTaggedDeclaration as e}from"../utils/boundary-tags.js";import{getFunctypeImportsLegacy as t,isAlreadyUsingFunctype as n,isFunctypeType as r}from"../utils/functype-detection.js";import{createImportFixer as i,hasFunctypeSymbol as a}from"../utils/import-fixer.js";import{DEFAULT_WIRE_TYPES as o,WIRE_TYPES_SCHEMA as s,isInsideWireType as c}from"../utils/wire-types.js";const l=/* @__PURE__ */ new Set([`useState`,`useRef`]),u={meta:{type:`suggestion`,hasSuggestions:!0,docs:{description:`Prefer Option<T> over nullable types (T | null | undefined)`,recommended:!0},schema:[{type:`object`,properties:{allowInteropMarker:{type:`boolean`,default:!0},wireTypes:s,allowNullableIntersections:{type:`boolean`,default:!1},allowUseState:{type:`boolean`,default:!0}},additionalProperties:!1}],messages:{preferOption:`Prefer Option<{{type}}> over nullable type '{{nullable}}'`,preferOptionReturn:`Prefer Option<{{type}}> as return type over nullable '{{nullable}}'`,suggestOptionType:`Replace with Option<{{type}}>`,suggestAddImport:`Add {{symbol}} import from functype`}},create(s){let
|
|
1
|
+
import{isInsideTaggedDeclaration as e}from"../utils/boundary-tags.js";import{getFunctypeImportsLegacy as t,isAlreadyUsingFunctype as n,isFunctypeType as r}from"../utils/functype-detection.js";import{createImportFixer as i,hasFunctypeSymbol as a}from"../utils/import-fixer.js";import{DEFAULT_WIRE_TYPES as o,WIRE_TYPES_SCHEMA as s,isInsideWireType as c}from"../utils/wire-types.js";const l=/* @__PURE__ */ new Set([`useState`,`useRef`]),u=e=>e.type===`TSNullKeyword`||e.type===`TSUndefinedKeyword`;function d(e){let t=e.parent;if(!t)return!1;if(t.type===`AssignmentPattern`&&t.left===e)return d(t);if(t.type===`TSParameterProperty`)return!0;let n=t.params;return Array.isArray(n)&&n.includes(e)}function f(e){let t=e?.type===`TSTypeAnnotation`?e.parent:void 0;if(t)return t.type===`TSPropertySignature`||d(t)?t:void 0}const p={meta:{type:`suggestion`,hasSuggestions:!0,docs:{description:`Prefer Option<T> over nullable types (T | null | undefined)`,recommended:!0},schema:[{type:`object`,properties:{allowInteropMarker:{type:`boolean`,default:!0},wireTypes:s,allowNullableIntersections:{type:`boolean`,default:!1},allowUseState:{type:`boolean`,default:!0},checkOptionalMembers:{type:`boolean`,default:!1}},additionalProperties:!1}],messages:{preferOption:`Prefer Option<{{type}}> over nullable type '{{nullable}}'`,preferOptionReturn:`Prefer Option<{{type}}> as return type over nullable '{{nullable}}'`,preferOptionOverOptional:`Prefer '{{name}}: Option<{{type}}>' over the optional '{{name}}?'`,suggestOptionType:`Replace with Option<{{type}}>`,suggestAddImport:`Add {{symbol}} import from functype`}},create(s){let p=s.options[0]||{},m=p.wireTypes??o,h=p.allowInteropMarker!==!1,g=t=>h&&e(t,`interop`,s.sourceCode),_=p.allowUseState!==!1,v=p.checkOptionalMembers===!0;function y(e){let t=e.parent;if(!t)return!1;if(t.type===`TSTypeParameterInstantiation`&&t.parent?.type===`CallExpression`){let e=t.parent.callee,n=e.type===`Identifier`?e.name:e.type===`MemberExpression`&&e.property.type===`Identifier`?e.property.name:null;if(n!==null&&l.has(n))return!0}return y(t)}let b=t(s);function x(e){if(!v||e.optional!==!0||e.type!==`TSPropertySignature`&&!d(e)||c(e,m)||g(e))return;let t=e.typeAnnotation?.typeAnnotation;if(!t||r(t,b)||t.type===`TSUnionType`&&t.types.some(e=>e.type===`TSNullKeyword`))return;let n=t.type===`TSUnionType`?t.types.filter(e=>!u(e)):[t];if(n.length!==1||r(n[0],b))return;let i=e.type===`TSPropertySignature`?e.key:e,a=i.type===`Identifier`?i.name:i.type===`Literal`?String(i.value):s.sourceCode.getText(i);s.report({node:i,messageId:`preferOptionOverOptional`,data:{name:a,type:s.sourceCode.getText(n[0])}})}return{TSPropertySignature:x,Identifier:x,TSUnionType(e){if(c(e,m)||g(e)||!e.types||e.types.length<2||_&&y(e)||!e.types.some(e=>u(e)))return;let t=f(e.parent),o=!e.types.some(e=>e.type===`TSNullKeyword`);if(t&&o&&(!v||t.optional===!0))return;let l=e.types.filter(e=>!u(e));if(l.length===1){let t=l[0];if(r(t,b)||n(e,b))return;let o=s.sourceCode,c=o.getText(t),u=o.getText(e);if(c.startsWith(`Option<`))return;let d=[{messageId:`suggestOptionType`,data:{type:c},fix(t){return t.replaceText(e,`Option<${c}>`)}}];a(o,`Option`)||d.push({messageId:`suggestAddImport`,data:{symbol:`Option`},fix:i(o,`Option`)}),s.report({node:e,messageId:`preferOption`,data:{type:c,nullable:u},suggest:d})}}}}};export{p as default};
|
|
2
2
|
//# sourceMappingURL=prefer-option.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"prefer-option.js","names":["REACT_STATE_HOOKS","rule","WIRE_TYPES_SCHEMA","options","context","wireTypes","DEFAULT_WIRE_TYPES","allowInteropMarker","isExemptByMarker","isInsideTaggedDeclaration","node","allowUseState","isInHookTypeArgument","parent","callee","name","functypeImports","getFunctypeImportsLegacy","isInsideWireType","type","nonNullTypes","nonNullType","isFunctypeType","isAlreadyUsingFunctype","sourceCode","nonNullTypeText","fullType","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 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 },\n additionalProperties: false,\n },\n ],\n messages: {\n preferOption: \"Prefer Option<{{type}}> over nullable type '{{nullable}}'\",\n preferOptionReturn: \"Prefer Option<{{type}}> as return type over nullable '{{nullable}}'\",\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\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 return {\n TSUnionType(node: ASTNode) {\n if (isInsideWireType(node, wireTypes)) return\n if (isExemptByMarker(node)) return\n if (!node.types || node.types.length < 2) return\n if (allowUseState && isInHookTypeArgument(node)) return\n\n const hasNull = node.types.some(\n (type: ASTNode) => type.type === \"TSNullKeyword\" || type.type === \"TSUndefinedKeyword\",\n )\n\n if (!hasNull) return\n\n const nonNullTypes = node.types.filter(\n (type: ASTNode) => type.type !== \"TSNullKeyword\" && type.type !== \"TSUndefinedKeyword\",\n )\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 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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,EAAqBF,CAAI,GAM1C,CAJYA,EAAK,MAAM,KACxB,GAAkBS,EAAK,OAAS,iBAAmBA,EAAK,OAAS,oBAGzD,EAAG,OAEd,IAAMC,EAAeV,EAAK,MAAM,OAC7B,GAAkBS,EAAK,OAAS,iBAAmBA,EAAK,OAAS,oBACpE,EAEA,GAAIC,EAAa,SAAW,EAAG,CAC7B,IAAMC,EAAcD,EAAa,GAMjC,GAHIE,EAAeD,EAAaL,CAAe,GAG3CO,EAAuBb,EAAMM,CAAe,EAAG,OAEnD,IAAMQ,EAAapB,EAAQ,WACrBqB,EAAkBD,EAAW,QAAQH,CAAW,EAChDK,EAAWF,EAAW,QAAQd,CAAI,EAGxC,GAAIe,EAAgB,WAAW,SAAS,EAAG,OAE3C,IAAME,EAAiD,CACrD,CACE,UAAW,oBACX,KAAM,CAAE,KAAMF,CAAgB,EAC9B,IAAI,EAAO,CACT,OAAOG,EAAM,YAAYlB,EAAM,UAAUe,EAAgB,EAAE,CAC7D,CACF,CACF,EAEKI,EAAkBL,EAAY,QAAQ,GACzCG,EAAY,KAAK,CACf,UAAW,mBACX,KAAM,CAAE,OAAQ,QAAS,EACzB,IAAKG,EAAkBN,EAAY,QAAQ,CAC7C,CAAC,EAGHpB,EAAQ,OAAO,CACb,OACA,UAAW,eACX,KAAM,CACJ,KAAMqB,EACN,SAAUC,CACZ,EACA,QAASC,CACX,CAAC,CACH,CACF,CACF,CACF,CACF"}
|
|
1
|
+
{"version":3,"file":"prefer-option.js","names":["REACT_STATE_HOOKS","isNullish","type","isParameter","parent","node","params","memberOrParameterOf","owner","annotation","rule","WIRE_TYPES_SCHEMA","options","context","wireTypes","DEFAULT_WIRE_TYPES","allowInteropMarker","isExemptByMarker","isInsideTaggedDeclaration","allowUseState","checkOptionalMembers","isInHookTypeArgument","callee","name","functypeImports","getFunctypeImportsLegacy","checkOptional","isInsideWireType","isFunctypeType","t","kept","key","undefinedOnly","nonNullTypes","nonNullType","isAlreadyUsingFunctype","sourceCode","nonNullTypeText","fullType","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\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: \"Prefer Option<{{type}}> over nullable type '{{nullable}}'\",\n preferOptionReturn: \"Prefer Option<{{type}}> as return type over nullable '{{nullable}}'\",\n preferOptionOverOptional: \"Prefer '{{name}}: Option<{{type}}>' over the optional '{{name}}?'\",\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 // `a?: T | null` is reported once, by the union check, which keeps its suggestions.\n if (annotation.type === \"TSUnionType\" && annotation.types.some((t: ASTNode) => t.type === \"TSNullKeyword\")) return\n const kept =\n annotation.type === \"TSUnionType\" ? annotation.types.filter((t: ASTNode) => !isNullish(t)) : [annotation]\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 if (isInsideWireType(node, wireTypes)) return\n if (isExemptByMarker(node)) return\n if (!node.types || node.types.length < 2) return\n if (allowUseState && isInHookTypeArgument(node)) return\n\n const hasNull = node.types.some((type: ASTNode) => 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 = !node.types.some((type: ASTNode) => type.type === \"TSNullKeyword\")\n if (owner && undefinedOnly && (!checkOptionalMembers || owner.optional === true)) return\n\n const nonNullTypes = node.types.filter((type: ASTNode) => !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 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":"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,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,GAASwB,IAAkB,CAACZ,GAAwBZ,EAAM,WAAa,IAAO,OAElF,IAAMyB,EAAe5B,EAAK,MAAM,OAAQ,GAAkB,CAACJ,EAAUC,CAAI,CAAC,EAE1E,GAAI+B,EAAa,SAAW,EAAG,CAC7B,IAAMC,EAAcD,EAAa,GAMjC,GAHIL,EAAeM,EAAaV,CAAe,GAG3CW,EAAuB9B,EAAMmB,CAAe,EAAG,OAEnD,IAAMY,EAAavB,EAAQ,WACrBwB,EAAkBD,EAAW,QAAQF,CAAW,EAChDI,EAAWF,EAAW,QAAQ/B,CAAI,EAGxC,GAAIgC,EAAgB,WAAW,SAAS,EAAG,OAE3C,IAAME,EAAiD,CACrD,CACE,UAAW,oBACX,KAAM,CAAE,KAAMF,CAAgB,EAC9B,IAAI,EAAO,CACT,OAAOG,EAAM,YAAYnC,EAAM,UAAUgC,EAAgB,EAAE,CAC7D,CACF,CACF,EAEKI,EAAkBL,EAAY,QAAQ,GACzCG,EAAY,KAAK,CACf,UAAW,mBACX,KAAM,CAAE,OAAQ,QAAS,EACzB,IAAKG,EAAkBN,EAAY,QAAQ,CAC7C,CAAC,EAGHvB,EAAQ,OAAO,CACb,OACA,UAAW,eACX,KAAM,CACJ,KAAMwB,EACN,SAAUC,CACZ,EACA,QAASC,CACX,CAAC,CACH,CACF,CACF,CACF,CACF"}
|
|
@@ -0,0 +1,33 @@
|
|
|
1
|
+
import { ASTNode } from "../types/ast.js";
|
|
2
|
+
import { Rule } from "eslint";
|
|
3
|
+
//#region src/utils/host-throws.d.ts
|
|
4
|
+
/**
|
|
5
|
+
* Router helpers whose return value a loader or route guard throws to redirect or show Not found
|
|
6
|
+
* (#445). The throw is the framework's API, not an error path: returning `Either.left(…)` instead
|
|
7
|
+
* breaks it. Each name was checked against the package's exports on 2026-10-31. React Router 6 loaders
|
|
8
|
+
* import from react-router-dom, and Remix on Workers from @remix-run/cloudflare.
|
|
9
|
+
*/
|
|
10
|
+
export declare const DEFAULT_HOST_THROWS: Readonly<Record<string, ReadonlyArray<string>>>;
|
|
11
|
+
export declare const HOST_THROWS_SCHEMA: {
|
|
12
|
+
readonly type: "object";
|
|
13
|
+
readonly additionalProperties: {
|
|
14
|
+
readonly type: "array";
|
|
15
|
+
readonly items: {
|
|
16
|
+
readonly type: "string";
|
|
17
|
+
};
|
|
18
|
+
};
|
|
19
|
+
};
|
|
20
|
+
/**
|
|
21
|
+
* The defaults with a project's own `hostThrows` added: naming a module adds helpers to its defaults,
|
|
22
|
+
* so `{ "react-router": ["myRedirect"] }` keeps `redirect` and the rest, and `[]` turns that module's
|
|
23
|
+
* defaults off. A module the defaults don't name is added.
|
|
24
|
+
*/
|
|
25
|
+
export declare const hostThrowsWith: (overrides: Readonly<Record<string, ReadonlyArray<string>>> | undefined) => ReadonlyMap<string, ReadonlySet<string>>;
|
|
26
|
+
/**
|
|
27
|
+
* Is `argument`, the value a `throw` throws, a call to a host helper? `throw redirect(…)` and
|
|
28
|
+
* `throw notFound()` with the name imported from a listed module, under any local name, or
|
|
29
|
+
* `throw Router.redirect(…)` through a namespace import of one.
|
|
30
|
+
*/
|
|
31
|
+
export declare function isHostThrow(argument: ASTNode | null | undefined, hostThrows: ReadonlyMap<string, ReadonlySet<string>>, context: Rule.RuleContext): boolean;
|
|
32
|
+
//#endregion
|
|
33
|
+
//# sourceMappingURL=host-throws.d.ts.map
|
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
const e={"@tanstack/react-router":[`redirect`,`notFound`],"@tanstack/router-core":[`redirect`,`notFound`],"react-router":[`redirect`,`redirectDocument`,`replace`,`data`],"react-router-dom":[`redirect`,`redirectDocument`,`replace`,`data`,`json`],"@remix-run/node":[`redirect`,`redirectDocument`,`replace`,`data`,`json`],"@remix-run/cloudflare":[`redirect`,`redirectDocument`,`replace`,`data`,`json`]},t={type:`object`,additionalProperties:{type:`array`,items:{type:`string`}}},n=t=>{let n=/* @__PURE__ */ new Set([...Object.keys(e),...Object.keys(t??{})]);return new Map([...n].map(n=>{let r=t?.[n],i=r!==void 0&&r.length===0?[]:[...e[n]??[],...r??[]];return[n,new Set(i)]}))};function r(e,t){let n=(t.sourceCode.getScope(e).references.find(t=>t.identifier===e)?.resolved)?.defs[0];return n?.type===`ImportBinding`?n:void 0}const i=e=>e.type===`ImportSpecifier`?e.imported.name??e.imported.value:e.type===`ImportDefaultSpecifier`?`default`:void 0;function a(e,t,n){if(e?.type!==`CallExpression`)return!1;let a=e.callee;if(a.type===`Identifier`){let e=r(a,n),o=e?.parent?.source?.value,s=e?i(e.node):void 0;return o!==void 0&&s!==void 0&&t.get(o)?.has(s)===!0}if(a.type!==`MemberExpression`||a.computed||a.object.type!==`Identifier`)return!1;let o=r(a.object,n);if(o?.node.type!==`ImportNamespaceSpecifier`)return!1;let s=o.parent?.source?.value;return s!==void 0&&t.get(s)?.has(a.property.name)===!0}export{e as DEFAULT_HOST_THROWS,t as HOST_THROWS_SCHEMA,n as hostThrowsWith,a as isHostThrow};
|
|
2
|
+
//# sourceMappingURL=host-throws.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"host-throws.js","names":["DEFAULT_HOST_THROWS","HOST_THROWS_SCHEMA","hostThrowsWith","modules","overrides","added","module","names","importOf","def","context","identifier","reference","importedName","specifier","isHostThrow","argument","callee","name","hostThrows"],"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,WAAY,UAAU,EAChD,eAAgB,CAAC,WAAY,mBAAoB,UAAW,MAAM,EAClE,mBAAoB,CAAC,WAAY,mBAAoB,UAAW,OAAQ,MAAM,EAC9E,kBAAmB,CAAC,WAAY,mBAAoB,UAAW,OAAQ,MAAM,EAC7E,wBAAyB,CAAC,WAAY,mBAAoB,UAAW,OAAQ,MAAM,CACrF,EAEaC,EAAqB,CAChC,KAAM,SACN,qBAAsB,CAAE,KAAM,QAAS,MAAO,CAAE,KAAM,QAAS,CAAE,CACnE,EAOaC,EACX,GAC6C,CAC7C,IAAMC,kBAAU,IAAI,IAAI,CAAC,GAAG,OAAO,KAAKH,CAAmB,EAAG,GAAG,OAAO,KAAKI,GAAa,CAAC,CAAC,CAAC,CAAC,EAC9F,OAAO,IAAI,IACT,CAAC,GAAGD,CAAO,CAAC,CAAC,IAAK,GAAW,CAC3B,IAAME,EAAQD,IAAYE,GACpBC,EACJF,IAAU,IAAA,IAAaA,EAAM,SAAW,EAAI,CAAC,EAAI,CAAC,GAAIL,EAAoBM,IAAW,CAAC,EAAI,GAAID,GAAS,CAAC,CAAE,EAC5G,MAAO,CAACC,EAAQ,IAAI,IAAIC,CAAK,CAAC,CAChC,CAAC,CACH,CACF,EASA,SAASC,EAAS,EAAqB,EAAkD,CAIvF,IAAMC,GAHWC,EAAQ,WACtB,SAASC,CAAU,CAAC,CACpB,WAAW,KAAM,GAAcC,EAAU,aAAeD,CAAU,CAAC,EAAE,SAAA,EAClD,KAAK,GAC3B,OAAOF,GAAK,OAAS,gBAAkBA,EAAM,IAAA,EAC/C,CAGA,MAAMI,EAAgB,GACpBC,EAAU,OAAS,kBACdA,EAAU,SAAS,MAAQA,EAAU,SAAS,MAC/CA,EAAU,OAAS,yBACjB,UACA,IAAA,GAOR,SAAgBC,EACd,EACA,EACA,EACS,CACT,GAAIC,GAAU,OAAS,iBAAkB,MAAO,GAChD,IAAMC,EAASD,EAAS,OACxB,GAAIC,EAAO,OAAS,aAAc,CAChC,IAAMR,EAAMD,EAASS,EAAQP,CAAO,EAC9BJ,EAASG,GAAK,QAAQ,QAAQ,MAC9BS,EAAOT,EAAMI,EAAaJ,EAAI,IAAI,EAAI,IAAA,GAC5C,OAAOH,IAAW,IAAA,IAAaY,IAAS,IAAA,IAAaC,EAAW,IAAIb,CAAM,CAAC,EAAE,IAAIY,CAAI,IAAM,EAC7F,CACA,GAAID,EAAO,OAAS,oBAAsBA,EAAO,UAAYA,EAAO,OAAO,OAAS,aAAc,MAAO,GACzG,IAAMR,EAAMD,EAASS,EAAO,OAAmBP,CAAO,EACtD,GAAID,GAAK,KAAK,OAAS,2BAA4B,MAAO,GAC1D,IAAMH,EAASG,EAAI,QAAQ,QAAQ,MACnC,OAAOH,IAAW,IAAA,IAAaa,EAAW,IAAIb,CAAM,CAAC,EAAE,IAAIW,EAAO,SAAS,IAAI,IAAM,EACvF"}
|
|
@@ -19,6 +19,30 @@ export declare const isExtractableByType: (node: ASTNode, context: Rule.RuleCont
|
|
|
19
19
|
* `undefined` when type information isn't available.
|
|
20
20
|
*/
|
|
21
21
|
export declare const isIOByType: (node: ASTNode, context: Rule.RuleContext) => boolean | undefined;
|
|
22
|
+
/**
|
|
23
|
+
* Can `node`'s value carry a failure that dropping it would lose? Structural: the type, or a member of
|
|
24
|
+
* its union, has `fold` and `isLeft` or `isFailure`. That covers Either, Try, Exit, Validation and
|
|
25
|
+
* Either-shaped wrappers such as a `ServiceResult`, and leaves out Option and List, whose `None` or
|
|
26
|
+
* empty value is no error. An `IO` is left to no-floating-io: it hasn't run, so it holds no failure yet.
|
|
27
|
+
*
|
|
28
|
+
* `undefined` when type information isn't available.
|
|
29
|
+
*/
|
|
30
|
+
export declare const canCarryFailureByType: (node: ASTNode, context: Rule.RuleContext) => boolean | undefined;
|
|
31
|
+
/** Where a functype container sits inside a value, and what it is called. */
|
|
32
|
+
export type ContainerAt = {
|
|
33
|
+
readonly path: string;
|
|
34
|
+
readonly name: string;
|
|
35
|
+
};
|
|
36
|
+
/**
|
|
37
|
+
* The first functype container inside the value `node` evaluates to, and the path to it: `subscription`,
|
|
38
|
+
* `items[]`, or empty for the whole value. A container is a type with `_tag` and `fold`, which every
|
|
39
|
+
* functype container has and its `toJSON()` envelope doesn't. Walks unions, intersections, array and
|
|
40
|
+
* tuple elements, object properties and string index signatures, up to 4 levels deep, and checks for a
|
|
41
|
+
* container before skipping types declared in node_modules, where functype itself lives (#364).
|
|
42
|
+
*
|
|
43
|
+
* `undefined` when there is none, or when type information isn't available.
|
|
44
|
+
*/
|
|
45
|
+
export declare const containerInsideByType: (node: ASTNode, context: Rule.RuleContext) => ContainerAt | undefined;
|
|
22
46
|
/**
|
|
23
47
|
* Does `node` (an expression) flow into a slot that is typed as an array, a tuple or `any`/`unknown`?
|
|
24
48
|
* That's the expected type TypeScript checks it against: the parameter it is passed to, the property
|
package/dist/utils/type-aware.js
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
const e=/* @__PURE__ */ new Set([`Iterable`,`AsyncIterable`,`IterableIterator`,`ArrayLike`]),t=e=>{let t=e.sourceCode.parserServices;return t?.program&&t.esTreeNodeToTSNodeMap?t:void 0},n=(e,n)=>{let r=t(n);if(!r)return;let i=r.esTreeNodeToTSNodeMap.get(e);if(!i)return;let a=r.program.getTypeChecker(),o=a.getNonNullableType(a.getTypeAtLocation(i));return a.getPropertyOfType(o,`orThrow`)!==void 0&&a.getPropertyOfType(o,`fold`)!==void 0},r=(e,n)=>{let r=t(n);if(!r)return;let i=r.esTreeNodeToTSNodeMap.get(e);if(!i)return;let a=r.program.getTypeChecker(),o=a.getNonNullableType(a.getTypeAtLocation(i));return a.getPropertyOfType(o,`runExit`)!==void 0&&a.getPropertyOfType(o,`provideLayer`)!==void 0},i=e=>e.
|
|
1
|
+
const e=/* @__PURE__ */ new Set([`Iterable`,`AsyncIterable`,`IterableIterator`,`ArrayLike`]),t=e=>{let t=e.sourceCode.parserServices;return t?.program&&t.esTreeNodeToTSNodeMap?t:void 0},n=(e,n)=>{let r=t(n);if(!r)return;let i=r.esTreeNodeToTSNodeMap.get(e);if(!i)return;let a=r.program.getTypeChecker(),o=a.getNonNullableType(a.getTypeAtLocation(i));return a.getPropertyOfType(o,`orThrow`)!==void 0&&a.getPropertyOfType(o,`fold`)!==void 0},r=(e,n)=>{let r=t(n);if(!r)return;let i=r.esTreeNodeToTSNodeMap.get(e);if(!i)return;let a=r.program.getTypeChecker(),o=a.getNonNullableType(a.getTypeAtLocation(i));return a.getPropertyOfType(o,`runExit`)!==void 0&&a.getPropertyOfType(o,`provideLayer`)!==void 0},i=(e,n)=>{let r=t(n);if(!r)return;let i=r.esTreeNodeToTSNodeMap.get(e);if(!i)return;let a=r.program.getTypeChecker(),o=a.getNonNullableType(a.getTypeAtLocation(i)),s=(e,t)=>a.getPropertyOfType(e,t)!==void 0;return(o.types??[o]).some(e=>s(e,`fold`)&&(s(e,`isLeft`)||s(e,`isFailure`))&&!s(e,`runExit`))},a={LeftOf:`Either`,RightOf:`Either`},o=e=>{let t=(e.aliasSymbol?.name??e.getSymbol?.()?.name)?.replace(/\$\d+$/,``);return t===void 0||t.startsWith(`__`)?`functype container`:a[t]??t},s=e=>{let t=e.getSymbol?.();return t===void 0||t.name.startsWith(`__`)?!1:(t.getDeclarations?.()??[]).some(e=>e.getSourceFile().fileName.includes(`/node_modules/`))},c=(e,n)=>{let r=t(n);if(!r)return;let i=r.esTreeNodeToTSNodeMap.get(e);if(!i)return;let a=r.program.getTypeChecker(),c=/* @__PURE__ */ new Set,u=e=>a.getPropertyOfType(e,`_tag`)!==void 0&&a.getPropertyOfType(e,`fold`)!==void 0,d=(e,t)=>e===``?t:t.startsWith(`[`)?e+t:`${e}.${t}`,f=(e,t,n)=>{if(n>4||c.has(e)||l(e))return;c.add(e);let r=e;if(u(e))return{path:t,name:o(r)};if(r.isUnionOrIntersection?.()===!0)return(r.types??[]).map(e=>f(e,t,n)).find(e=>e!==void 0);if((r.getCallSignatures?.()??[]).length>0)return;if(a.isArrayLikeType(e)||a.isTupleType(e))return a.getTypeArguments(e).map(e=>f(e,t===``?`[]`:`${t}[]`,n+1)).find(e=>e!==void 0);let p=a.getIndexInfoOfType(e,0)?.type,m=p===void 0?void 0:f(p,d(t,`[key]`),n+1);if(m!==void 0)return m;if(!(r.getSymbol?.()===void 0||s(r)))return a.getPropertiesOfType(e).map(e=>f(a.getTypeOfSymbolAtLocation(e,i),d(t,e.name),n+1)).find(e=>e!==void 0)};return f(a.getTypeAtLocation(i),``,0)},l=e=>e.isTypeParameter?.()===!0,u=e=>{let t=e.parent;if(!t)return null;if((t.type===`CallExpression`||t.type===`NewExpression`)&&t.callee!==e){let n=t.arguments.indexOf(e);return n<0?null:{call:t,argument:e,index:n}}return t.type===`TSAsExpression`||t.type===`TSSatisfiesExpression`||t.type===`ConditionalExpression`&&t.test!==e||t.type===`LogicalExpression`||t.type===`Property`||t.type===`ObjectExpression`||t.type===`ArrayExpression`||t.type===`SpreadElement`?u(t):null},d=(e,t,n)=>{let r=u(n),i=r?t.esTreeNodeToTSNodeMap.get(r.call):void 0,a=i?e.getResolvedSignature(i)?.getDeclaration()?.parameters:void 0;if(!r||!a||a.length===0)return!1;let o=a[Math.min(r.index,a.length-1)];if(o?.type===void 0)return!1;let s=e.getTypeAtLocation(o.type);return(s.types??[s]).some(l)},f=(e,t,n)=>{let r=u(n),i=r?t.esTreeNodeToTSNodeMap.get(r.call):void 0,a=i?e.getResolvedSignature(i):void 0,o=r?t.esTreeNodeToTSNodeMap.get(r.argument):void 0;if(!a||!o)return!1;let s=e.getTypeAtLocation(o),c=t=>t===s||e.isTypeAssignableTo(s,t)&&e.isTypeAssignableTo(t,s),l=(t,n)=>{if(n>3)return!1;if(c(t))return!0;let{types:r,target:i}=t;if(r)return r.some(e=>l(e,n+1));if(i!==void 0&&(e.isTupleType(t)||e.isArrayLikeType(t)))return e.getTypeArguments(t).some(e=>l(e,n+1));let a=e.getAwaitedType(t);return a!==void 0&&a!==t&&l(a,n+1)};return l(e.getReturnTypeOfSignature(a),0)},p=(e,t,n)=>h(n.type)||l(n.type)&&!f(e,t,n.at),m=(t,n,r)=>{if(p(t,n,r))return!0;let{types:i,symbol:a}=r.type;return i?i.some(e=>m(t,n,{type:e,at:r.at})):a?.name!==void 0&&e.has(a.name)?!0:!l(r.type)&&t.isArrayLikeType(r.type)},h=e=>{let{flags:t}=e;return t!==void 0&&!!(t&3)},g=(e,t)=>{let{types:n,symbol:r}=t;return n?n.some(t=>g(e,t)):r?.name===`Array`&&e.isArrayLikeType(t)},_=e=>e.computed?null:e.key?.type===`Identifier`?e.key.name:e.key?.type===`Literal`&&typeof e.key.value==`string`?e.key.value:null,v=(e,t,n,r,i=0)=>{if(i>4)return;let a=t.esTreeNodeToTSNodeMap.get(n),o=a?e.getContextualType(a):void 0;if(o!==void 0)return{type:o,at:n};let s=n.parent;if(s?.type===`ArrowFunctionExpression`&&s.body===n){let n=s.parent;if(n?.type===`VariableDeclarator`&&n.init===s&&n.id?.type===`Identifier`)return(r.sourceCode.getDeclaredVariables(n)[0]?.references??[]).map(e=>e.identifier.parent).filter(e=>e?.type===`CallExpression`).map(n=>v(e,t,n,r,i+1)).find(e=>e!==void 0)}if((s?.type===`CallExpression`||s?.type===`NewExpression`)&&s.callee!==n){let r=s.arguments.indexOf(n),i=t.esTreeNodeToTSNodeMap.get(s),a=r>=0&&i?e.getResolvedSignature(i)?.parameters[r]:void 0;return a===void 0?void 0:{type:e.getTypeOfSymbolAtLocation(a,i),at:n}}let c=s?.type===`Property`&&s.value===n?s.parent:void 0;if(c?.type!==`ObjectExpression`)return;let l=v(e,t,c,r,i+1);if(l===void 0||p(e,t,l))return l;let u=l.type,d=_(s);if(d===null){let r=s.key,i=r?t.esTreeNodeToTSNodeMap.get(r):void 0,o=i?e.getTypeAtLocation(i):void 0,c=o?.value??o?.types?.[0]?.value,l=typeof c==`string`?e.getPropertyOfType(u,c):void 0,d=l===void 0?e.getIndexInfoOfType(u,0)?.type:e.getTypeOfSymbolAtLocation(l,a);return d===void 0?void 0:{type:d,at:n}}let f=e.getPropertyOfType(u,d);return f===void 0?void 0:{type:e.getTypeOfSymbolAtLocation(f,a),at:n}},y=(e,n)=>{let r=t(n);if(!r)return;let i=r.program.getTypeChecker(),a=v(i,r,e,n);if(a!==void 0)return d(i,r,a.at)?!f(i,r,a.at):m(i,r,a)},b=(e,n)=>{let r=t(n);if(!r)return;let i=r.program.getTypeChecker(),a=v(i,r,e,n);return a===void 0||d(i,r,a.at)?!1:g(i,a.type)},x=(e,n)=>{let r=t(n);if(!r)return;let i=r.esTreeNodeToTSNodeMap.get(e);if(!i)return;let a=r.program.getTypeChecker(),o=a.getTypeAtLocation(i);if(h(o))return!0;if(!a.isArrayLikeType(o))return!1;let s=a.getTypeArguments(o)[0];return s!==void 0&&h(s)},S=e=>t(e)!==void 0;export{i as canCarryFailureByType,c as containerInsideByType,y as flowsIntoArraySlot,b as flowsIntoMutableArraySlot,S as hasTypeInformation,n as isExtractableByType,r as isIOByType,x as isUntypedExpression};
|
|
2
2
|
//# sourceMappingURL=type-aware.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"type-aware.js","names":["CONSUMED_COLLECTION_TYPES","typedServices","services","context","isExtractableByType","tsNode","node","checker","type","isIOByType","isTypeParameter","enclosingCall","parent","at","index","isGenericParameterArgument","found","callTs","parameters","declared","annotated","handsArgumentBack","signature","argTs","argType","sameAsArgument","candidate","search","depth","types","member","target","element","awaited","isOpaqueSink","isUntyped","slot","isArrayLikeOrUntyped","symbol","flags","isMutableArrayType","propertyKey","property","expectedSlot","own","declarator","ref","call","parameter","objectLiteral","outerSlot","outer","key","keyNode","keyTs","keyType","literal","named","flowsIntoArraySlot","flowsIntoMutableArraySlot","isUntypedExpression","hasTypeInformation"],"sources":["../../src/utils/type-aware.ts"],"sourcesContent":["import type { Rule } from \"eslint\"\n\nimport type { ASTNode } from \"../types/ast\"\n\n/**\n * Type-aware helpers that work only when the consumer turns on type-aware linting\n * (`parserOptions.projectService` or `project`). Without it they report \"unknown\", and a rule\n * falls back to its syntactic heuristic.\n *\n * The checker is reached through `parserServices` and typed structurally here, so the plugin\n * takes no runtime dependency on `typescript`.\n */\n\ntype TypeLike = object\n\ntype CheckerLike = {\n getTypeAtLocation(node: unknown): TypeLike\n getNonNullableType(type: TypeLike): TypeLike\n getPropertyOfType(type: TypeLike, name: string): unknown\n getContextualType(node: unknown): TypeLike | undefined\n isArrayLikeType(type: TypeLike): boolean\n getTypeOfSymbolAtLocation(symbol: unknown, node: unknown): TypeLike\n getTypeArguments(type: TypeLike): ReadonlyArray<TypeLike>\n getResolvedSignature(node: unknown): SignatureLike | undefined\n getIndexInfoOfType(type: TypeLike, kind: number): { readonly type: TypeLike } | undefined\n getReturnTypeOfSignature(signature: unknown): TypeLike\n getAwaitedType(type: TypeLike): TypeLike | undefined\n isTupleType(type: TypeLike): boolean\n isTypeAssignableTo(source: TypeLike, target: TypeLike): boolean\n}\n\ntype SignatureLike = {\n readonly parameters: ReadonlyArray<unknown>\n getDeclaration(): { readonly parameters?: ReadonlyArray<unknown> } | undefined\n}\n\n/** `ts.TypeFlags.Any` / `Unknown`, inlined so the plugin needs no runtime `typescript` import. */\nconst ANY_OR_UNKNOWN_FLAGS = 1 | 2\n\n/** Interfaces a consumer reads through rather than keeps: `importKey(…, usages: Iterable<KeyUsage>)`, `new Set(values)`. */\nconst CONSUMED_COLLECTION_TYPES: ReadonlySet<string> = new Set([\n \"Iterable\",\n \"AsyncIterable\",\n \"IterableIterator\",\n \"ArrayLike\",\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 * Is `node`'s type a functype extractable container (Option, Either, Try, Lazy, …)? Structural:\n * the type, after stripping `null` / `undefined`, has both `orThrow` and `fold` — true of every\n * functype container, including union types like `Either` (each member has both). Native\n * collections (`Map#get`) and arbitrary objects don't.\n *\n * `undefined` when type information isn't available, so the caller can fall back.\n */\nexport const isExtractableByType = (node: ASTNode, context: Rule.RuleContext): boolean | undefined => {\n const services = typedServices(context)\n if (!services) return undefined\n const tsNode = services.esTreeNodeToTSNodeMap.get(node)\n if (!tsNode) return undefined\n const checker = services.program.getTypeChecker()\n const type = checker.getNonNullableType(checker.getTypeAtLocation(tsNode))\n return (\n checker.getPropertyOfType(type, \"orThrow\") !== undefined && checker.getPropertyOfType(type, \"fold\") !== undefined\n )\n}\n\n/**\n * Is `node`'s type a functype `IO`? Structural: the type has both `runExit` and `provideLayer`, which\n * only `IO` carries — `Task`, `Lazy` and the other containers have neither — and has carried since\n * well before 1.9, so older functype versions are recognized too. A union of IOs counts.\n * `any` and `unknown` have no properties, so they don't.\n *\n * `undefined` when type information isn't available.\n */\nexport const isIOByType = (node: ASTNode, context: Rule.RuleContext): boolean | undefined => {\n const services = typedServices(context)\n if (!services) return undefined\n const tsNode = services.esTreeNodeToTSNodeMap.get(node)\n if (!tsNode) return undefined\n const checker = services.program.getTypeChecker()\n const type = checker.getNonNullableType(checker.getTypeAtLocation(tsNode))\n return (\n checker.getPropertyOfType(type, \"runExit\") !== undefined &&\n checker.getPropertyOfType(type, \"provideLayer\") !== undefined\n )\n}\n\n/** A slot's expected type and the expression TypeScript computed it for. */\ntype Slot = { readonly type: TypeLike; readonly at: ASTNode }\n\n/**\n * Uses the `Type` object's own predicate rather than a `TypeFlags` bit: TypeScript renumbers its flags\n * between majors (TypeParameter is `1 << 19` in TS 6, `1 << 18` before), and the plugin has no runtime\n * `typescript` import to read them from.\n */\nconst isTypeParameter = (type: TypeLike): boolean =>\n (type as { isTypeParameter?: () => boolean }).isTypeParameter?.() === true\n\n/**\n * `f(…, arg, …)` where `at` is `arg` or sits inside it (an object property, an array element, a spread,\n * a conditional branch, an `as`): the call, the whole argument, and its index.\n */\nconst enclosingCall = (\n at: ASTNode,\n): { readonly call: ASTNode; readonly argument: ASTNode; readonly index: number } | null => {\n const parent = at.parent as ASTNode | undefined\n if (!parent) return null\n if ((parent.type === \"CallExpression\" || parent.type === \"NewExpression\") && parent.callee !== at) {\n const index = (parent.arguments as ReadonlyArray<ASTNode>).indexOf(at)\n return index < 0 ? null : { call: parent, argument: at, index }\n }\n const passesThrough =\n parent.type === \"TSAsExpression\" ||\n parent.type === \"TSSatisfiesExpression\" ||\n (parent.type === \"ConditionalExpression\" && parent.test !== at) ||\n parent.type === \"LogicalExpression\" ||\n parent.type === \"Property\" ||\n parent.type === \"ObjectExpression\" ||\n parent.type === \"ArrayExpression\" ||\n parent.type === \"SpreadElement\"\n return passesThrough ? enclosingCall(parent) : null\n}\n\n/**\n * Is the parameter that `at` is passed to (directly or nested) declared as a type parameter, or a union\n * containing one — `json<T>(data: T)`, `useState<S>(init: S | (() => S))`? Then TypeScript's expected type for `at` is only an echo of what it inferred from\n * `at` itself (`[1, 2]` → `number[]`), not a shape the library demands.\n */\nconst isGenericParameterArgument = (checker: CheckerLike, services: TypedServices, at: ASTNode): boolean => {\n const found = enclosingCall(at)\n const callTs = found ? services.esTreeNodeToTSNodeMap.get(found.call) : undefined\n const parameters = callTs ? checker.getResolvedSignature(callTs)?.getDeclaration()?.parameters : undefined\n if (!found || !parameters || parameters.length === 0) return false\n const declared = parameters[Math.min(found.index, parameters.length - 1)] as { readonly type?: unknown } | undefined\n // The parameter's type annotation node (`T` in `value: T`); asking for the declaration node's type gives `any`.\n if (declared?.type === undefined) return false\n const annotated = checker.getTypeAtLocation(declared.type)\n // React's `useState<S>(init: S | (() => S))`: a union that contains the type parameter is generic too.\n const members = (annotated as { types?: ReadonlyArray<TypeLike> }).types ?? [annotated]\n return members.some(isTypeParameter)\n}\n\n/**\n * Does the generic call around `at` hand the argument straight back to the caller — `useState(init)`\n * returning `[init, set]`, `identity(x)`, a `Promise` of it? Then the shape stays the caller's, and a\n * type parameter isn't a sink. Looks only at the return type itself, union / intersection members,\n * tuple and array elements, and an awaited Promise, not object properties: Hono's `c.json<T>` returns a\n * `Response` that carries a *parsed* copy of `T` for its RPC client, which the caller doesn't get back.\n */\nconst handsArgumentBack = (checker: CheckerLike, services: TypedServices, at: ASTNode): boolean => {\n const found = enclosingCall(at)\n const callTs = found ? services.esTreeNodeToTSNodeMap.get(found.call) : undefined\n const signature = callTs ? checker.getResolvedSignature(callTs) : undefined\n const argTs = found ? services.esTreeNodeToTSNodeMap.get(found.argument) : undefined\n if (!signature || !argTs) return false\n const argType = checker.getTypeAtLocation(argTs)\n const sameAsArgument = (candidate: TypeLike): boolean =>\n candidate === argType ||\n (checker.isTypeAssignableTo(argType, candidate) && checker.isTypeAssignableTo(candidate, argType))\n const search = (type: TypeLike, depth: number): boolean => {\n if (depth > 3) return false\n if (sameAsArgument(type)) return true\n const { types, target } = type as { types?: ReadonlyArray<TypeLike>; target?: unknown }\n if (types) return types.some((member) => search(member, depth + 1))\n if (target !== undefined && (checker.isTupleType(type) || checker.isArrayLikeType(type))) {\n return checker.getTypeArguments(type).some((element) => search(element, depth + 1))\n }\n const awaited = checker.getAwaitedType(type)\n return awaited !== undefined && awaited !== type && search(awaited, depth + 1)\n }\n return search(checker.getReturnTypeOfSignature(signature), 0)\n}\n\n/**\n * Untyped, or a type parameter of a call that doesn't hand the argument back: an object handed to\n * `c.json<T>(data: T)` or `JSON.stringify` goes to a sink. `useState<T>(init: T)` is not one.\n */\nconst isOpaqueSink = (checker: CheckerLike, services: TypedServices, slot: Slot): boolean =>\n isUntyped(slot.type) || (isTypeParameter(slot.type) && !handsArgumentBack(checker, services, slot.at))\n\nconst isArrayLikeOrUntyped = (checker: CheckerLike, services: TypedServices, slot: Slot): boolean => {\n if (isOpaqueSink(checker, services, slot)) return true\n const { types, symbol } = slot.type as { types?: ReadonlyArray<TypeLike>; symbol?: { name?: string } }\n if (types) return types.some((member) => isArrayLikeOrUntyped(checker, services, { type: member, at: slot.at }))\n if (symbol?.name !== undefined && CONSUMED_COLLECTION_TYPES.has(symbol.name)) return true\n return !isTypeParameter(slot.type) && checker.isArrayLikeType(slot.type)\n}\n\nconst isUntyped = (type: TypeLike): boolean => {\n const { flags } = type as { flags?: number }\n return flags !== undefined && (flags & ANY_OR_UNKNOWN_FLAGS) !== 0\n}\n\n/** The mutable `Array` type, as opposed to `ReadonlyArray`: the one a `ReadonlyArray` can't be passed to. */\nconst isMutableArrayType = (checker: CheckerLike, type: TypeLike): boolean => {\n const { types, symbol } = type as { types?: ReadonlyArray<TypeLike>; symbol?: { name?: string } }\n if (types) return types.some((member) => isMutableArrayType(checker, member))\n return symbol?.name === \"Array\" && checker.isArrayLikeType(type)\n}\n\n/** The name a property is written under: `params` in `{ params }`, `parts` in `{ parts: … }` or `{ \"parts\": … }`. */\nconst propertyKey = (property: ASTNode): string | null => {\n if (property.computed) return null\n if (property.key?.type === \"Identifier\") return property.key.name\n return property.key?.type === \"Literal\" && typeof property.key.value === \"string\" ? property.key.value : null\n}\n\n/**\n * The expected type of `node`, looking through object literals when TypeScript gives the value none of\n * its own. Two cases: a shorthand `{ params }` passed to a function, where the expected type is that\n * property's type on the parameter; and `[…]` in `JSON.stringify({ parts: [...] })`, where the object is\n * passed to an `any` parameter, so the whole object is going to an untyped host.\n */\nconst expectedSlot = (\n checker: CheckerLike,\n services: TypedServices,\n node: ASTNode,\n context: Rule.RuleContext,\n depth = 0,\n): Slot | undefined => {\n if (depth > 4) return undefined\n const tsNode = services.esTreeNodeToTSNodeMap.get(node)\n const own = tsNode ? checker.getContextualType(tsNode) : undefined\n if (own !== undefined) return { type: own, at: node }\n const parent = node.parent as ASTNode | undefined\n // `const metadata = (url) => ({ … })` with no declared return type: the object goes wherever the\n // calls' results go (`c.json(metadata(url))`), so take the expected type at the first call site.\n if (parent?.type === \"ArrowFunctionExpression\" && parent.body === node) {\n const declarator = parent.parent as ASTNode | undefined\n if (\n declarator?.type === \"VariableDeclarator\" &&\n declarator.init === parent &&\n declarator.id?.type === \"Identifier\"\n ) {\n const variable = context.sourceCode.getDeclaredVariables(declarator)[0]\n const calls = (variable?.references ?? [])\n .map((ref) => (ref.identifier as unknown as ASTNode).parent as ASTNode | undefined)\n .filter((call): call is ASTNode => call?.type === \"CallExpression\")\n return calls\n .map((call) => expectedSlot(checker, services, call, context, depth + 1))\n .find((slot) => slot !== undefined)\n }\n }\n // An argument to an overloaded function (`crypto.subtle.importKey(…, [\"decrypt\"])`) gets no contextual\n // type; the parameter of the overload TypeScript picked is the expected type.\n if ((parent?.type === \"CallExpression\" || parent?.type === \"NewExpression\") && parent.callee !== node) {\n const index = (parent.arguments as ReadonlyArray<ASTNode>).indexOf(node)\n const call = services.esTreeNodeToTSNodeMap.get(parent)\n const parameter = index >= 0 && call ? checker.getResolvedSignature(call)?.parameters[index] : undefined\n return parameter === undefined ? undefined : { type: checker.getTypeOfSymbolAtLocation(parameter, call), at: node }\n }\n const objectLiteral = parent?.type === \"Property\" && parent.value === node ? (parent.parent as ASTNode) : undefined\n if (objectLiteral?.type !== \"ObjectExpression\") return undefined\n const outerSlot = expectedSlot(checker, services, objectLiteral, context, depth + 1)\n if (outerSlot === undefined || isOpaqueSink(checker, services, outerSlot)) return outerSlot\n const outer = outerSlot.type\n const key = propertyKey(parent as ASTNode)\n // `{ [k]: [...] }` (a reduce accumulator keyed by category): the property named by the key's literal\n // type, else the string index signature's type.\n if (key === null) {\n const keyNode = (parent as ASTNode).key\n const keyTs = keyNode ? services.esTreeNodeToTSNodeMap.get(keyNode) : undefined\n const keyType = keyTs\n ? (checker.getTypeAtLocation(keyTs) as { value?: unknown; types?: ReadonlyArray<{ value?: unknown }> })\n : undefined\n const literal = keyType?.value ?? keyType?.types?.[0]?.value\n const named = typeof literal === \"string\" ? checker.getPropertyOfType(outer, literal) : undefined\n const type =\n named !== undefined\n ? checker.getTypeOfSymbolAtLocation(named, tsNode)\n : checker.getIndexInfoOfType(outer, 0)?.type\n return type === undefined ? undefined : { type, at: node }\n }\n const member = checker.getPropertyOfType(outer, key)\n return member === undefined ? undefined : { type: checker.getTypeOfSymbolAtLocation(member, tsNode), at: node }\n}\n\n/**\n * Does `node` (an expression) flow into a slot that is typed as an array, a tuple or `any`/`unknown`?\n * That's the expected type TypeScript checks it against: the parameter it is passed to, the property\n * it initialises, the declared return type. A literal in such a slot is handed to code that requires an\n * array, such as drizzle's `.values([...])` or an index definition, so `List` can't go there. A literal\n * inside an object passed to an `any` parameter (a `JSON.stringify` request body) counts too.\n *\n * `undefined` when type information isn't available, or when there is no expected type (a free-standing\n * literal), so the caller can fall back.\n */\nexport const flowsIntoArraySlot = (node: ASTNode, context: Rule.RuleContext): boolean | undefined => {\n const services = typedServices(context)\n if (!services) return undefined\n const checker = services.program.getTypeChecker()\n const slot = expectedSlot(checker, services, node, context)\n if (slot === undefined) return undefined\n // A bare `T` parameter: a sink unless the call hands the argument straight back (`useState`, `identity`).\n if (isGenericParameterArgument(checker, services, slot.at)) return !handsArgumentBack(checker, services, slot.at)\n return isArrayLikeOrUntyped(checker, services, slot)\n}\n\n/**\n * Does `node` flow into a slot that requires a *mutable* array — a parameter typed `T[]`, such as pg's\n * `query(text, values: unknown[])`, drizzle's `inArray(col, values)` or ReactFlow's `nodes`? There a\n * `ReadonlyArray` won't type-check, so a mutable annotation is what the library demands.\n *\n * `undefined` when type information isn't available.\n */\nexport const flowsIntoMutableArraySlot = (node: ASTNode, context: Rule.RuleContext): boolean | undefined => {\n const services = typedServices(context)\n if (!services) return undefined\n const checker = services.program.getTypeChecker()\n const slot = expectedSlot(checker, services, node, context)\n if (slot === undefined || isGenericParameterArgument(checker, services, slot.at)) return false\n return isMutableArrayType(checker, slot.type)\n}\n\n/**\n * Is `node`'s own type `any` / `unknown`, or an array of them — `JSON.parse(raw)`, `await res.json()`,\n * `raw` after `Array.isArray(raw)` (narrowed to `any[]`)? `undefined` when type information isn't available.\n */\nexport const isUntypedExpression = (node: ASTNode, context: Rule.RuleContext): boolean | undefined => {\n const services = typedServices(context)\n if (!services) return undefined\n const tsNode = services.esTreeNodeToTSNodeMap.get(node)\n if (!tsNode) return undefined\n const checker = services.program.getTypeChecker()\n const type = checker.getTypeAtLocation(tsNode)\n if (isUntyped(type)) return true\n if (!checker.isArrayLikeType(type)) return false\n const element = checker.getTypeArguments(type)[0]\n return element !== undefined && isUntyped(element)\n}\n\n/** Is type-aware linting on for this file (`parserOptions.projectService` or `project`)? */\nexport const hasTypeInformation = (context: Rule.RuleContext): boolean => typedServices(context) !== undefined\n"],"mappings":"AAqCA,MAGMA,kBAAiD,IAAI,IAAI,CAC7D,WACA,gBACA,mBACA,WACF,CAAC,EAOKC,EAAiB,GAAyD,CAC9E,IAAMC,EAAWC,EAAQ,WAAW,eACpC,OAAOD,GAAU,SAAWA,EAAS,sBAAyBA,EAA6B,IAAA,EAC7F,EAUaE,GAAuB,EAAe,IAAmD,CACpG,IAAMF,EAAWD,EAAcE,CAAO,EACtC,GAAI,CAACD,EAAU,OACf,IAAMG,EAASH,EAAS,s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GAA6B,EAAe,IAAmD,CAC1G,IAAMzD,EAAWD,EAAcE,CAAO,EACtC,GAAI,CAACD,EAAU,OACf,IAAMK,EAAUL,EAAS,QAAQ,eAAe,EAC1CkC,EAAOO,EAAapC,EAASL,EAAUI,EAAMH,CAAO,EAE1D,OADIiC,IAAS,IAAA,IAAarB,EAA2BR,EAASL,EAAUkC,EAAK,EAAE,EAAU,GAClFI,EAAmBjC,EAAS6B,EAAK,IAAI,CAC9C,EAMawB,GAAuB,EAAe,IAAmD,CACpG,IAAM1D,EAAWD,EAAcE,CAAO,EACtC,GAAI,CAACD,EAAU,OACf,IAAMG,EAASH,EAAS,sBAAsB,IAAII,CAAI,EACtD,GAAI,CAACD,EAAQ,OACb,IAAME,EAAUL,EAAS,QAAQ,eAAe,EAC1CM,EAAOD,EAAQ,kBAAkBF,CAAM,EAC7C,GAAI8B,EAAU3B,CAAI,EAAG,MAAO,GAC5B,GAAI,CAACD,EAAQ,gBAAgBC,CAAI,EAAG,MAAO,GAC3C,IAAMwB,EAAUzB,EAAQ,iBAAiBC,CAAI,CAAC,CAAC,GAC/C,OAAOwB,IAAY,IAAA,IAAaG,EAAUH,CAAO,CACnD,EAGa6B,EAAsB,GAAuC5D,EAAcE,CAAO,IAAM,IAAA"}
|
|
1
|
+
{"version":3,"file":"type-aware.js","names":["CONSUMED_COLLECTION_TYPES","typedServices","services","context","isExtractableByType","tsNode","node","checker","type","isIOByType","canCarryFailureByType","has","member","name","MEMBER_TO_CONTAINER","containerName","raw","isFromDependency","symbol","declaration","containerInsideByType","seen","isContainer","at","path","step","find","depth","isTypeParameter","shape","h","element","indexed","byIndex","property","enclosingCall","parent","index","isGenericParameterArgument","found","callTs","parameters","declared","annotated","handsArgumentBack","signature","argTs","argType","sameAsArgument","candidate","search","types","target","awaited","isOpaqueSink","isUntyped","slot","isArrayLikeOrUntyped","flags","isMutableArrayType","propertyKey","expectedSlot","own","declarator","ref","call","parameter","objectLiteral","outerSlot","outer","key","keyNode","keyTs","keyType","literal","named","flowsIntoArraySlot","flowsIntoMutableArraySlot","isUntypedExpression","hasTypeInformation"],"sources":["../../src/utils/type-aware.ts"],"sourcesContent":["import type { Rule } from \"eslint\"\n\nimport type { ASTNode } from \"../types/ast\"\n\n/**\n * Type-aware helpers that work only when the consumer turns on type-aware linting\n * (`parserOptions.projectService` or `project`). Without it they report \"unknown\", and a rule\n * falls back to its syntactic heuristic.\n *\n * The checker is reached through `parserServices` and typed structurally here, so the plugin\n * takes no runtime dependency on `typescript`.\n */\n\ntype TypeLike = object\n\ntype CheckerLike = {\n getTypeAtLocation(node: unknown): TypeLike\n getNonNullableType(type: TypeLike): TypeLike\n getPropertyOfType(type: TypeLike, name: string): unknown\n getContextualType(node: unknown): TypeLike | undefined\n isArrayLikeType(type: TypeLike): boolean\n getTypeOfSymbolAtLocation(symbol: unknown, node: unknown): TypeLike\n getTypeArguments(type: TypeLike): ReadonlyArray<TypeLike>\n getResolvedSignature(node: unknown): SignatureLike | undefined\n getIndexInfoOfType(type: TypeLike, kind: number): { readonly type: TypeLike } | undefined\n getReturnTypeOfSignature(signature: unknown): TypeLike\n getAwaitedType(type: TypeLike): TypeLike | undefined\n isTupleType(type: TypeLike): boolean\n isTypeAssignableTo(source: TypeLike, target: TypeLike): boolean\n getPropertiesOfType(type: TypeLike): ReadonlyArray<{ readonly name: string }>\n}\n\ntype SignatureLike = {\n readonly parameters: ReadonlyArray<unknown>\n getDeclaration(): { readonly parameters?: ReadonlyArray<unknown> } | undefined\n}\n\n/** `ts.TypeFlags.Any` / `Unknown`, inlined so the plugin needs no runtime `typescript` import. */\nconst ANY_OR_UNKNOWN_FLAGS = 1 | 2\n\n/** Interfaces a consumer reads through rather than keeps: `importKey(…, usages: Iterable<KeyUsage>)`, `new Set(values)`. */\nconst CONSUMED_COLLECTION_TYPES: ReadonlySet<string> = new Set([\n \"Iterable\",\n \"AsyncIterable\",\n \"IterableIterator\",\n \"ArrayLike\",\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 * Is `node`'s type a functype extractable container (Option, Either, Try, Lazy, …)? Structural:\n * the type, after stripping `null` / `undefined`, has both `orThrow` and `fold` — true of every\n * functype container, including union types like `Either` (each member has both). Native\n * collections (`Map#get`) and arbitrary objects don't.\n *\n * `undefined` when type information isn't available, so the caller can fall back.\n */\nexport const isExtractableByType = (node: ASTNode, context: Rule.RuleContext): boolean | undefined => {\n const services = typedServices(context)\n if (!services) return undefined\n const tsNode = services.esTreeNodeToTSNodeMap.get(node)\n if (!tsNode) return undefined\n const checker = services.program.getTypeChecker()\n const type = checker.getNonNullableType(checker.getTypeAtLocation(tsNode))\n return (\n checker.getPropertyOfType(type, \"orThrow\") !== undefined && checker.getPropertyOfType(type, \"fold\") !== undefined\n )\n}\n\n/**\n * Is `node`'s type a functype `IO`? Structural: the type has both `runExit` and `provideLayer`, which\n * only `IO` carries — `Task`, `Lazy` and the other containers have neither — and has carried since\n * well before 1.9, so older functype versions are recognized too. A union of IOs counts.\n * `any` and `unknown` have no properties, so they don't.\n *\n * `undefined` when type information isn't available.\n */\nexport const isIOByType = (node: ASTNode, context: Rule.RuleContext): boolean | undefined => {\n const services = typedServices(context)\n if (!services) return undefined\n const tsNode = services.esTreeNodeToTSNodeMap.get(node)\n if (!tsNode) return undefined\n const checker = services.program.getTypeChecker()\n const type = checker.getNonNullableType(checker.getTypeAtLocation(tsNode))\n return (\n checker.getPropertyOfType(type, \"runExit\") !== undefined &&\n checker.getPropertyOfType(type, \"provideLayer\") !== undefined\n )\n}\n\n/**\n * Can `node`'s value carry a failure that dropping it would lose? Structural: the type, or a member of\n * its union, has `fold` and `isLeft` or `isFailure`. That covers Either, Try, Exit, Validation and\n * Either-shaped wrappers such as a `ServiceResult`, and leaves out Option and List, whose `None` or\n * empty value is no error. An `IO` is left to no-floating-io: it hasn't run, so it holds no failure yet.\n *\n * `undefined` when type information isn't available.\n */\nexport const canCarryFailureByType = (node: ASTNode, context: Rule.RuleContext): boolean | undefined => {\n const services = typedServices(context)\n if (!services) return undefined\n const tsNode = services.esTreeNodeToTSNodeMap.get(node)\n if (!tsNode) return undefined\n const checker = services.program.getTypeChecker()\n const type = checker.getNonNullableType(checker.getTypeAtLocation(tsNode))\n const has = (member: TypeLike, name: string): boolean => checker.getPropertyOfType(member, name) !== undefined\n const carries = (member: TypeLike): boolean =>\n has(member, \"fold\") && (has(member, \"isLeft\") || has(member, \"isFailure\")) && !has(member, \"runExit\")\n const members = (type as { readonly types?: ReadonlyArray<TypeLike> }).types ?? [type]\n return members.some(carries)\n}\n\n/** Where a functype container sits inside a value, and what it is called. */\nexport type ContainerAt = { readonly path: string; readonly name: string }\n\ntype TypeShape = {\n readonly types?: ReadonlyArray<TypeLike>\n readonly aliasSymbol?: SymbolShape\n isUnionOrIntersection?: () => boolean\n getSymbol?: () => SymbolShape | undefined\n getCallSignatures?: () => ReadonlyArray<unknown>\n}\ntype SymbolShape = {\n readonly name: string\n getDeclarations?: () => ReadonlyArray<{ getSourceFile(): { readonly fileName: string } }> | undefined\n}\n\nconst SERIALIZE_DEPTH = 4\n\n/** A name to show for a container type: `Either`, `Option`, `List`, or the generic fallback. */\n/** Member names TypeScript shows once a union loses its alias (`Either<E, A> | null`), mapped back. */\nconst MEMBER_TO_CONTAINER: Readonly<Record<string, string>> = { LeftOf: \"Either\", RightOf: \"Either\" }\n\nconst containerName = (type: TypeShape): string => {\n // A bundled .d.ts renames a clashing declaration `Map$1`.\n const raw = (type.aliasSymbol?.name ?? type.getSymbol?.()?.name)?.replace(/\\$\\d+$/, \"\")\n if (raw === undefined || raw.startsWith(\"__\")) return \"functype container\"\n return MEMBER_TO_CONTAINER[raw] ?? raw\n}\n\n/** Declared in a dependency or the TypeScript lib: Stripe objects, Date, Request. Never descended into. */\nconst isFromDependency = (type: TypeShape): boolean => {\n // The type's own symbol, not its alias: `Partial<User>` and `Omit<Row, \"x\">` are anonymous mapped\n // types whose alias is declared in TypeScript's lib, and their properties are the caller's.\n const symbol = type.getSymbol?.()\n if (symbol === undefined || symbol.name.startsWith(\"__\")) return false\n return (symbol.getDeclarations?.() ?? []).some((declaration) =>\n declaration.getSourceFile().fileName.includes(\"/node_modules/\"),\n )\n}\n\n/**\n * The first functype container inside the value `node` evaluates to, and the path to it: `subscription`,\n * `items[]`, or empty for the whole value. A container is a type with `_tag` and `fold`, which every\n * functype container has and its `toJSON()` envelope doesn't. Walks unions, intersections, array and\n * tuple elements, object properties and string index signatures, up to 4 levels deep, and checks for a\n * container before skipping types declared in node_modules, where functype itself lives (#364).\n *\n * `undefined` when there is none, or when type information isn't available.\n */\nexport const containerInsideByType = (node: ASTNode, context: Rule.RuleContext): ContainerAt | undefined => {\n const services = typedServices(context)\n if (!services) return undefined\n const tsNode = services.esTreeNodeToTSNodeMap.get(node)\n if (!tsNode) return undefined\n const checker = services.program.getTypeChecker()\n const seen = new Set<TypeLike>()\n const isContainer = (type: TypeLike): boolean =>\n checker.getPropertyOfType(type, \"_tag\") !== undefined && checker.getPropertyOfType(type, \"fold\") !== undefined\n const at = (path: string, step: string): string =>\n path === \"\" ? step : step.startsWith(\"[\") ? path + step : `${path}.${step}`\n\n const find = (type: TypeLike, path: string, depth: number): ContainerAt | undefined => {\n if (depth > SERIALIZE_DEPTH || seen.has(type) || isTypeParameter(type)) return undefined\n seen.add(type)\n const shape = type as TypeShape\n // Before splitting: an Either union has `_tag` and `fold` on every member, and `Stack` is an\n // intersection whose `_tag` and `fold` come from different members.\n if (isContainer(type)) return { path, name: containerName(shape) }\n if (shape.isUnionOrIntersection?.() === true) {\n return (shape.types ?? []).map((member) => find(member, path, depth)).find((h) => h !== undefined)\n }\n if ((shape.getCallSignatures?.() ?? []).length > 0) return undefined\n if (checker.isArrayLikeType(type) || checker.isTupleType(type)) {\n return checker\n .getTypeArguments(type)\n .map((element) => find(element, path === \"\" ? \"[]\" : `${path}[]`, depth + 1))\n .find((h) => h !== undefined)\n }\n // Before the dependency skip: `Record<string, Option<T>>` is declared in TypeScript's lib.\n const indexed = checker.getIndexInfoOfType(type, 0)?.type\n const byIndex = indexed === undefined ? undefined : find(indexed, at(path, \"[key]\"), depth + 1)\n if (byIndex !== undefined) return byIndex\n if (shape.getSymbol?.() === undefined || isFromDependency(shape)) return undefined\n return checker\n .getPropertiesOfType(type)\n .map((property) => find(checker.getTypeOfSymbolAtLocation(property, tsNode), at(path, property.name), depth + 1))\n .find((h) => h !== undefined)\n }\n\n return find(checker.getTypeAtLocation(tsNode), \"\", 0)\n}\n\n/** A slot's expected type and the expression TypeScript computed it for. */\ntype Slot = { readonly type: TypeLike; readonly at: ASTNode }\n\n/**\n * Uses the `Type` object's own predicate rather than a `TypeFlags` bit: TypeScript renumbers its flags\n * between majors (TypeParameter is `1 << 19` in TS 6, `1 << 18` before), and the plugin has no runtime\n * `typescript` import to read them from.\n */\nconst isTypeParameter = (type: TypeLike): boolean =>\n (type as { isTypeParameter?: () => boolean }).isTypeParameter?.() === true\n\n/**\n * `f(…, arg, …)` where `at` is `arg` or sits inside it (an object property, an array element, a spread,\n * a conditional branch, an `as`): the call, the whole argument, and its index.\n */\nconst enclosingCall = (\n at: ASTNode,\n): { readonly call: ASTNode; readonly argument: ASTNode; readonly index: number } | null => {\n const parent = at.parent as ASTNode | undefined\n if (!parent) return null\n if ((parent.type === \"CallExpression\" || parent.type === \"NewExpression\") && parent.callee !== at) {\n const index = (parent.arguments as ReadonlyArray<ASTNode>).indexOf(at)\n return index < 0 ? null : { call: parent, argument: at, index }\n }\n const passesThrough =\n parent.type === \"TSAsExpression\" ||\n parent.type === \"TSSatisfiesExpression\" ||\n (parent.type === \"ConditionalExpression\" && parent.test !== at) ||\n parent.type === \"LogicalExpression\" ||\n parent.type === \"Property\" ||\n parent.type === \"ObjectExpression\" ||\n parent.type === \"ArrayExpression\" ||\n parent.type === \"SpreadElement\"\n return passesThrough ? enclosingCall(parent) : null\n}\n\n/**\n * Is the parameter that `at` is passed to (directly or nested) declared as a type parameter, or a union\n * containing one — `json<T>(data: T)`, `useState<S>(init: S | (() => S))`? Then TypeScript's expected type for `at` is only an echo of what it inferred from\n * `at` itself (`[1, 2]` → `number[]`), not a shape the library demands.\n */\nconst isGenericParameterArgument = (checker: CheckerLike, services: TypedServices, at: ASTNode): boolean => {\n const found = enclosingCall(at)\n const callTs = found ? services.esTreeNodeToTSNodeMap.get(found.call) : undefined\n const parameters = callTs ? checker.getResolvedSignature(callTs)?.getDeclaration()?.parameters : undefined\n if (!found || !parameters || parameters.length === 0) return false\n const declared = parameters[Math.min(found.index, parameters.length - 1)] as { readonly type?: unknown } | undefined\n // The parameter's type annotation node (`T` in `value: T`); asking for the declaration node's type gives `any`.\n if (declared?.type === undefined) return false\n const annotated = checker.getTypeAtLocation(declared.type)\n // React's `useState<S>(init: S | (() => S))`: a union that contains the type parameter is generic too.\n const members = (annotated as { types?: ReadonlyArray<TypeLike> }).types ?? [annotated]\n return members.some(isTypeParameter)\n}\n\n/**\n * Does the generic call around `at` hand the argument straight back to the caller — `useState(init)`\n * returning `[init, set]`, `identity(x)`, a `Promise` of it? Then the shape stays the caller's, and a\n * type parameter isn't a sink. Looks only at the return type itself, union / intersection members,\n * tuple and array elements, and an awaited Promise, not object properties: Hono's `c.json<T>` returns a\n * `Response` that carries a *parsed* copy of `T` for its RPC client, which the caller doesn't get back.\n */\nconst handsArgumentBack = (checker: CheckerLike, services: TypedServices, at: ASTNode): boolean => {\n const found = enclosingCall(at)\n const callTs = found ? services.esTreeNodeToTSNodeMap.get(found.call) : undefined\n const signature = callTs ? checker.getResolvedSignature(callTs) : undefined\n const argTs = found ? services.esTreeNodeToTSNodeMap.get(found.argument) : undefined\n if (!signature || !argTs) return false\n const argType = checker.getTypeAtLocation(argTs)\n const sameAsArgument = (candidate: TypeLike): boolean =>\n candidate === argType ||\n (checker.isTypeAssignableTo(argType, candidate) && checker.isTypeAssignableTo(candidate, argType))\n const search = (type: TypeLike, depth: number): boolean => {\n if (depth > 3) return false\n if (sameAsArgument(type)) return true\n const { types, target } = type as { types?: ReadonlyArray<TypeLike>; target?: unknown }\n if (types) return types.some((member) => search(member, depth + 1))\n if (target !== undefined && (checker.isTupleType(type) || checker.isArrayLikeType(type))) {\n return checker.getTypeArguments(type).some((element) => search(element, depth + 1))\n }\n const awaited = checker.getAwaitedType(type)\n return awaited !== undefined && awaited !== type && search(awaited, depth + 1)\n }\n return search(checker.getReturnTypeOfSignature(signature), 0)\n}\n\n/**\n * Untyped, or a type parameter of a call that doesn't hand the argument back: an object handed to\n * `c.json<T>(data: T)` or `JSON.stringify` goes to a sink. `useState<T>(init: T)` is not one.\n */\nconst isOpaqueSink = (checker: CheckerLike, services: TypedServices, slot: Slot): boolean =>\n isUntyped(slot.type) || (isTypeParameter(slot.type) && !handsArgumentBack(checker, services, slot.at))\n\nconst isArrayLikeOrUntyped = (checker: CheckerLike, services: TypedServices, slot: Slot): boolean => {\n if (isOpaqueSink(checker, services, slot)) return true\n const { types, symbol } = slot.type as { types?: ReadonlyArray<TypeLike>; symbol?: { name?: string } }\n if (types) return types.some((member) => isArrayLikeOrUntyped(checker, services, { type: member, at: slot.at }))\n if (symbol?.name !== undefined && CONSUMED_COLLECTION_TYPES.has(symbol.name)) return true\n return !isTypeParameter(slot.type) && checker.isArrayLikeType(slot.type)\n}\n\nconst isUntyped = (type: TypeLike): boolean => {\n const { flags } = type as { flags?: number }\n return flags !== undefined && (flags & ANY_OR_UNKNOWN_FLAGS) !== 0\n}\n\n/** The mutable `Array` type, as opposed to `ReadonlyArray`: the one a `ReadonlyArray` can't be passed to. */\nconst isMutableArrayType = (checker: CheckerLike, type: TypeLike): boolean => {\n const { types, symbol } = type as { types?: ReadonlyArray<TypeLike>; symbol?: { name?: string } }\n if (types) return types.some((member) => isMutableArrayType(checker, member))\n return symbol?.name === \"Array\" && checker.isArrayLikeType(type)\n}\n\n/** The name a property is written under: `params` in `{ params }`, `parts` in `{ parts: … }` or `{ \"parts\": … }`. */\nconst propertyKey = (property: ASTNode): string | null => {\n if (property.computed) return null\n if (property.key?.type === \"Identifier\") return property.key.name\n return property.key?.type === \"Literal\" && typeof property.key.value === \"string\" ? property.key.value : null\n}\n\n/**\n * The expected type of `node`, looking through object literals when TypeScript gives the value none of\n * its own. Two cases: a shorthand `{ params }` passed to a function, where the expected type is that\n * property's type on the parameter; and `[…]` in `JSON.stringify({ parts: [...] })`, where the object is\n * passed to an `any` parameter, so the whole object is going to an untyped host.\n */\nconst expectedSlot = (\n checker: CheckerLike,\n services: TypedServices,\n node: ASTNode,\n context: Rule.RuleContext,\n depth = 0,\n): Slot | undefined => {\n if (depth > 4) return undefined\n const tsNode = services.esTreeNodeToTSNodeMap.get(node)\n const own = tsNode ? checker.getContextualType(tsNode) : undefined\n if (own !== undefined) return { type: own, at: node }\n const parent = node.parent as ASTNode | undefined\n // `const metadata = (url) => ({ … })` with no declared return type: the object goes wherever the\n // calls' results go (`c.json(metadata(url))`), so take the expected type at the first call site.\n if (parent?.type === \"ArrowFunctionExpression\" && parent.body === node) {\n const declarator = parent.parent as ASTNode | undefined\n if (\n declarator?.type === \"VariableDeclarator\" &&\n declarator.init === parent &&\n declarator.id?.type === \"Identifier\"\n ) {\n const variable = context.sourceCode.getDeclaredVariables(declarator)[0]\n const calls = (variable?.references ?? [])\n .map((ref) => (ref.identifier as unknown as ASTNode).parent as ASTNode | undefined)\n .filter((call): call is ASTNode => call?.type === \"CallExpression\")\n return calls\n .map((call) => expectedSlot(checker, services, call, context, depth + 1))\n .find((slot) => slot !== undefined)\n }\n }\n // An argument to an overloaded function (`crypto.subtle.importKey(…, [\"decrypt\"])`) gets no contextual\n // type; the parameter of the overload TypeScript picked is the expected type.\n if ((parent?.type === \"CallExpression\" || parent?.type === \"NewExpression\") && parent.callee !== node) {\n const index = (parent.arguments as ReadonlyArray<ASTNode>).indexOf(node)\n const call = services.esTreeNodeToTSNodeMap.get(parent)\n const parameter = index >= 0 && call ? checker.getResolvedSignature(call)?.parameters[index] : undefined\n return parameter === undefined ? undefined : { type: checker.getTypeOfSymbolAtLocation(parameter, call), at: node }\n }\n const objectLiteral = parent?.type === \"Property\" && parent.value === node ? (parent.parent as ASTNode) : undefined\n if (objectLiteral?.type !== \"ObjectExpression\") return undefined\n const outerSlot = expectedSlot(checker, services, objectLiteral, context, depth + 1)\n if (outerSlot === undefined || isOpaqueSink(checker, services, outerSlot)) return outerSlot\n const outer = outerSlot.type\n const key = propertyKey(parent as ASTNode)\n // `{ [k]: [...] }` (a reduce accumulator keyed by category): the property named by the key's literal\n // type, else the string index signature's type.\n if (key === null) {\n const keyNode = (parent as ASTNode).key\n const keyTs = keyNode ? services.esTreeNodeToTSNodeMap.get(keyNode) : undefined\n const keyType = keyTs\n ? (checker.getTypeAtLocation(keyTs) as { value?: unknown; types?: ReadonlyArray<{ value?: unknown }> })\n : undefined\n const literal = keyType?.value ?? keyType?.types?.[0]?.value\n const named = typeof literal === \"string\" ? checker.getPropertyOfType(outer, literal) : undefined\n const type =\n named !== undefined\n ? checker.getTypeOfSymbolAtLocation(named, tsNode)\n : checker.getIndexInfoOfType(outer, 0)?.type\n return type === undefined ? undefined : { type, at: node }\n }\n const member = checker.getPropertyOfType(outer, key)\n return member === undefined ? undefined : { type: checker.getTypeOfSymbolAtLocation(member, tsNode), at: node }\n}\n\n/**\n * Does `node` (an expression) flow into a slot that is typed as an array, a tuple or `any`/`unknown`?\n * That's the expected type TypeScript checks it against: the parameter it is passed to, the property\n * it initialises, the declared return type. A literal in such a slot is handed to code that requires an\n * array, such as drizzle's `.values([...])` or an index definition, so `List` can't go there. A literal\n * inside an object passed to an `any` parameter (a `JSON.stringify` request body) counts too.\n *\n * `undefined` when type information isn't available, or when there is no expected type (a free-standing\n * literal), so the caller can fall back.\n */\nexport const flowsIntoArraySlot = (node: ASTNode, context: Rule.RuleContext): boolean | undefined => {\n const services = typedServices(context)\n if (!services) return undefined\n const checker = services.program.getTypeChecker()\n const slot = expectedSlot(checker, services, node, context)\n if (slot === undefined) return undefined\n // A bare `T` parameter: a sink unless the call hands the argument straight back (`useState`, `identity`).\n if (isGenericParameterArgument(checker, services, slot.at)) return !handsArgumentBack(checker, services, slot.at)\n return isArrayLikeOrUntyped(checker, services, slot)\n}\n\n/**\n * Does `node` flow into a slot that requires a *mutable* array — a parameter typed `T[]`, such as pg's\n * `query(text, values: unknown[])`, drizzle's `inArray(col, values)` or ReactFlow's `nodes`? There a\n * `ReadonlyArray` won't type-check, so a mutable annotation is what the library demands.\n *\n * `undefined` when type information isn't available.\n */\nexport const flowsIntoMutableArraySlot = (node: ASTNode, context: Rule.RuleContext): boolean | undefined => {\n const services = typedServices(context)\n if (!services) return undefined\n const checker = services.program.getTypeChecker()\n const slot = expectedSlot(checker, services, node, context)\n if (slot === undefined || isGenericParameterArgument(checker, services, slot.at)) return false\n return isMutableArrayType(checker, slot.type)\n}\n\n/**\n * Is `node`'s own type `any` / `unknown`, or an array of them — `JSON.parse(raw)`, `await res.json()`,\n * `raw` after `Array.isArray(raw)` (narrowed to `any[]`)? `undefined` when type information isn't available.\n */\nexport const isUntypedExpression = (node: ASTNode, context: Rule.RuleContext): boolean | undefined => {\n const services = typedServices(context)\n if (!services) return undefined\n const tsNode = services.esTreeNodeToTSNodeMap.get(node)\n if (!tsNode) return undefined\n const checker = services.program.getTypeChecker()\n const type = checker.getTypeAtLocation(tsNode)\n if (isUntyped(type)) return true\n if (!checker.isArrayLikeType(type)) return false\n const element = checker.getTypeArguments(type)[0]\n return element !== undefined && isUntyped(element)\n}\n\n/** Is type-aware linting on for this file (`parserOptions.projectService` or `project`)? */\nexport const hasTypeInformation = (context: Rule.RuleContext): boolean => typedServices(context) !== undefined\n"],"mappings":"AAsCA,MAGMA,kBAAiD,IAAI,IAAI,CAC7D,WACA,gBACA,mBACA,WACF,CAA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xB,CAAO,CACnD,EAGagD,EAAsB,GAAuC9E,EAAcE,CAAO,IAAM,IAAA"}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "eslint-plugin-functype",
|
|
3
|
-
"version": "2.
|
|
3
|
+
"version": "2.123.0",
|
|
4
4
|
"description": "Custom ESLint rules for functional TypeScript programming with functype library patterns including Do notation (ESLint 10+)",
|
|
5
5
|
"type": "module",
|
|
6
6
|
"main": "./dist/index.js",
|
|
@@ -42,7 +42,7 @@
|
|
|
42
42
|
"@types/node": "^24.19.1",
|
|
43
43
|
"@typescript-eslint/rule-tester": "^8.71.0",
|
|
44
44
|
"eslint-config-prettier": "^10.1.8",
|
|
45
|
-
"functype": "^1.
|
|
45
|
+
"functype": "^1.23.0",
|
|
46
46
|
"ts-builds": "^3.4.3",
|
|
47
47
|
"tsdown": "^0.23.0"
|
|
48
48
|
},
|