diff --git a/.changeset/quiet-mangos-nail.md b/.changeset/quiet-mangos-nail.md new file mode 100644 index 000000000..0e07443d6 --- /dev/null +++ b/.changeset/quiet-mangos-nail.md @@ -0,0 +1,5 @@ +--- +'eslint-plugin-svelte': patch +--- + +fix(@typescript-eslint/no-shadow): ignore `{#snippet}` if it uses under component diff --git a/README.md b/README.md index 35c16c8e8..567e686f4 100644 --- a/README.md +++ b/README.md @@ -354,6 +354,7 @@ These rules relate to better ways of doing things to help you avoid problems: | Rule ID | Description | | |:--------|:------------|:---| +| [svelte/@typescript-eslint/no-shadow](https://sveltejs.github.io/eslint-plugin-svelte/rules/@typescript-eslint/no-shadow/) | Disallow variable declarations from shadowing variables declared in the outer scope | | | [svelte/block-lang](https://sveltejs.github.io/eslint-plugin-svelte/rules/block-lang/) | disallows the use of languages other than those specified in the configuration for the lang attribute of ` + + + + {#snippet children()} + + {#snippet children()} + Hello! + {/snippet} + + {/snippet} + + + + {@const foo = 1} + + {@const foo = 2} + + +``` + +## :wrench: Options + +```json +{ + "svelte/no-shadow": [ + "error", + { "builtinGlobals": false, "hoist": "functions", "allow": [], "ignoreOnInitialization": false } + ] +} +``` + +- `builtinGlobals`: The `builtinGlobals` option is `false` by default. If it is `true`, the rule prevents shadowing of built-in global variables: `Object`, `Array`, `Number`, and so on. +- `hoist`: The `hoist` option has three settings: + - `functions` (by default) - reports shadowing before the outer functions are defined. + - `all` - reports all shadowing before the outer variables/functions are defined. + - `never` - never report shadowing before the outer variables/functions are defined. +- `allow`: The `allow` option is an array of identifier names for which shadowing is allowed. For example, `"resolve"`, `"reject"`, `"done"`, `"cb"`. +- `ignoreOnInitialization`: The `ignoreOnInitialization` option is `false` by default. If it is `true`, it prevents reporting shadowing of variables in their initializers when the shadowed variable is presumably still uninitialized. The shadowed variable must be on the left side. The shadowing variable must be on the right side and declared in a callback function or in an IIFE. +- `ignoreTypeValueShadow`: Whether to ignore types named the same as a variable. Default: `true`. This is generally safe because you cannot use variables in type locations without a `typeof` operator, so there's little risk of confusion. +- `ignoreFunctionTypeParameterNameValueShadow`: Whether to ignore function parameters named the same as a variable. Default: `true`. Each of a function type's arguments creates a value variable within the scope of the function type. This is done so that you can reference the type later using the `typeof` operator. + +## :books: Further Reading + +- See [typescript-eslint `no-shadow` rule](https://typescript-eslint.io/rules/no-shadow/) for more information about the base rule. + +## :mag: Implementation + +- [Rule source](https://github.com/sveltejs/eslint-plugin-svelte/blob/main/packages/eslint-plugin-svelte/src/rules/@typescript-eslint/no-shadow.ts) +- [Test source](https://github.com/sveltejs/eslint-plugin-svelte/blob/main/packages/eslint-plugin-svelte/tests/src/rules/@typescript-eslint/no-shadow.ts) + +Taken with ❤️ [from ESLint core](https://eslint.org/docs/rules/@typescript-eslint/no-shadow) diff --git a/packages/eslint-plugin-svelte/src/rule-types.ts b/packages/eslint-plugin-svelte/src/rule-types.ts index b07451a1b..d5382e1cb 100644 --- a/packages/eslint-plugin-svelte/src/rule-types.ts +++ b/packages/eslint-plugin-svelte/src/rule-types.ts @@ -13,6 +13,11 @@ declare module 'eslint' { } export interface RuleOptions { + /** + * Disallow variable declarations from shadowing variables declared in the outer scope + * @see https://sveltejs.github.io/eslint-plugin-svelte/rules/@typescript-eslint/no-shadow/ + */ + 'svelte/@typescript-eslint/no-shadow'?: Linter.RuleEntry /** * disallow conditionals where the type is always truthy or always falsy * @see https://sveltejs.github.io/eslint-plugin-svelte/rules/@typescript-eslint/no-unnecessary-condition/ @@ -363,6 +368,21 @@ export interface RuleOptions { } /* ======= Declarations ======= */ +// ----- svelte/@typescript-eslint/no-shadow ----- +type SvelteTypescriptEslintNoShadow = []|[{ + + allow?: string[] + + builtinGlobals?: boolean + + hoist?: ("all" | "functions" | "never") + + ignoreFunctionTypeParameterNameValueShadow?: boolean + + ignoreOnInitialization?: boolean + + ignoreTypeValueShadow?: boolean +}] // ----- svelte/@typescript-eslint/no-unnecessary-condition ----- type SvelteTypescriptEslintNoUnnecessaryCondition = []|[{ diff --git a/packages/eslint-plugin-svelte/src/rules/@typescript-eslint/no-shadow.ts b/packages/eslint-plugin-svelte/src/rules/@typescript-eslint/no-shadow.ts new file mode 100644 index 000000000..509d89764 --- /dev/null +++ b/packages/eslint-plugin-svelte/src/rules/@typescript-eslint/no-shadow.ts @@ -0,0 +1,83 @@ +import { createRule } from '../../utils/index.js'; +import { defineWrapperListener, getProxyContent, getCoreRule } from '../../utils/eslint-core.js'; +import type { TSESTree } from '@typescript-eslint/types'; +import type { Scope } from '@typescript-eslint/scope-manager'; +import type { Range } from 'svelte-eslint-parser/lib/ast/common.js'; +import { getScope as getScopeUtil } from '../../utils/ast-utils.js'; +import { getSourceCode as getSourceCodeCompat } from '../../utils/compat.js'; + +const coreRule = getCoreRule('@typescript-eslint/no-shadow'); + +function removeSnippetIdentifiers(snippetIdentifierNodeLocations: Range[], scope: Scope): Scope { + return { + ...scope, + variables: scope.variables.filter((variable) => { + return !snippetIdentifierNodeLocations.some(([start, end]) => { + return variable.identifiers.every((identifier) => { + const { range } = identifier; + return range[0] === start && range[1] === end; + }); + }); + }), + childScopes: scope.childScopes.map((scope) => { + return removeSnippetIdentifiers(snippetIdentifierNodeLocations, scope); + }) + } as Scope; +} + +export default createRule('@typescript-eslint/no-shadow', { + meta: { + ...coreRule.meta, + docs: { + description: coreRule.meta.docs.description, + category: 'Best Practices', + recommended: false, + extensionRule: '@typescript-eslint/no-shadow' + } + }, + create(context) { + const snippetIdentifierNodeLocations: Range[] = []; + + function getScope(node: TSESTree.Node) { + const scope = getScopeUtil(context, node); + return removeSnippetIdentifiers(snippetIdentifierNodeLocations, scope); + } + + function getSourceCode() { + const sourceCode = getSourceCodeCompat(context); + return new Proxy(sourceCode, { + get(target, key) { + if (key === 'getScope') { + return getScope; + } + // eslint-disable-next-line @typescript-eslint/no-explicit-any -- ignore + return (target as any)[key]; + } + }); + } + + return defineWrapperListener( + coreRule, + getProxyContent(context, { + sourceCode: getSourceCode() + }), + { + createListenerProxy(coreListener) { + return { + ...coreListener, + SvelteSnippetBlock(node) { + const parent = node.parent; + if (parent.type === 'SvelteElement' && parent.kind === 'component') { + snippetIdentifierNodeLocations.push(node.id.range); + } + coreListener.SvelteSnippetBlock?.(node); + }, + 'Program:exit'(node) { + coreListener['Program:exit']?.(node); + } + }; + } + } + ); + } +}); diff --git a/packages/eslint-plugin-svelte/src/utils/eslint-core.ts b/packages/eslint-plugin-svelte/src/utils/eslint-core.ts index d78f293e7..5289ca5c4 100644 --- a/packages/eslint-plugin-svelte/src/utils/eslint-core.ts +++ b/packages/eslint-plugin-svelte/src/utils/eslint-core.ts @@ -6,6 +6,22 @@ import { Linter } from 'eslint'; import Module from 'module'; const require = Module.createRequire(import.meta.url); + +export function getProxyContent(context: RuleContext, overrides: any): RuleContext { + const cache: any = {}; + return new Proxy(context, { + get(_t, key) { + if (key in cache) { + return cache[key]; + } + if (key in overrides) { + return (cache[key] = overrides[key]); + } + return (context as any)[key]; + } + }); +} + /** * Define the wrapped core rule. */ @@ -73,11 +89,24 @@ export function buildProxyListener( } let ruleMap: Map | null = null; +let tsRuleMap: Map | null = null; /** * Get the core rule implementation from the rule name */ export function getCoreRule(ruleName: string): RuleModule { + if (ruleName.startsWith('@typescript-eslint/')) { + if (tsRuleMap == null) { + const rules = require('@typescript-eslint/eslint-plugin').rules; + for (const [name, rule] of Object.entries(rules)) { + if (tsRuleMap == null) { + tsRuleMap = new Map(); + } + tsRuleMap.set(`@typescript-eslint/${name}`, rule as RuleModule); + } + } + return tsRuleMap!.get(ruleName)!; + } try { const map: Map = ruleMap ? ruleMap diff --git a/packages/eslint-plugin-svelte/src/utils/rules.ts b/packages/eslint-plugin-svelte/src/utils/rules.ts index cb0cbe896..3a84cc58d 100644 --- a/packages/eslint-plugin-svelte/src/utils/rules.ts +++ b/packages/eslint-plugin-svelte/src/utils/rules.ts @@ -2,6 +2,7 @@ // This file has been automatically generated, // in order to update its content execute "pnpm run update" import type { RuleModule } from '../types.js'; +import typescriptEslintNoShadow from '../rules/@typescript-eslint/no-shadow.js'; import typescriptEslintNoUnnecessaryCondition from '../rules/@typescript-eslint/no-unnecessary-condition.js'; import blockLang from '../rules/block-lang.js'; import buttonHasType from '../rules/button-has-type.js'; @@ -73,6 +74,7 @@ import validEachKey from '../rules/valid-each-key.js'; import validPropNamesInKitPages from '../rules/valid-prop-names-in-kit-pages.js'; export const rules = [ + typescriptEslintNoShadow, typescriptEslintNoUnnecessaryCondition, blockLang, buttonHasType, diff --git a/packages/eslint-plugin-svelte/tests/fixtures/rules/@typescript-eslint/no-shadow/invalid/basic-errors.yaml b/packages/eslint-plugin-svelte/tests/fixtures/rules/@typescript-eslint/no-shadow/invalid/basic-errors.yaml new file mode 100644 index 000000000..8f4b845d8 --- /dev/null +++ b/packages/eslint-plugin-svelte/tests/fixtures/rules/@typescript-eslint/no-shadow/invalid/basic-errors.yaml @@ -0,0 +1,4 @@ +- message: "'x' is already declared in the upper scope on line 2 column 13." + line: 4 + column: 8 + suggestions: null diff --git a/packages/eslint-plugin-svelte/tests/fixtures/rules/@typescript-eslint/no-shadow/invalid/basic-input.svelte b/packages/eslint-plugin-svelte/tests/fixtures/rules/@typescript-eslint/no-shadow/invalid/basic-input.svelte new file mode 100644 index 000000000..0b867af18 --- /dev/null +++ b/packages/eslint-plugin-svelte/tests/fixtures/rules/@typescript-eslint/no-shadow/invalid/basic-input.svelte @@ -0,0 +1,7 @@ + diff --git a/packages/eslint-plugin-svelte/tests/fixtures/rules/@typescript-eslint/no-shadow/invalid/const-errors.yaml b/packages/eslint-plugin-svelte/tests/fixtures/rules/@typescript-eslint/no-shadow/invalid/const-errors.yaml new file mode 100644 index 000000000..a1ed736a7 --- /dev/null +++ b/packages/eslint-plugin-svelte/tests/fixtures/rules/@typescript-eslint/no-shadow/invalid/const-errors.yaml @@ -0,0 +1,4 @@ +- message: "'foo' is already declared in the upper scope on line 6 column 10." + line: 8 + column: 11 + suggestions: null diff --git a/packages/eslint-plugin-svelte/tests/fixtures/rules/@typescript-eslint/no-shadow/invalid/const-input.svelte b/packages/eslint-plugin-svelte/tests/fixtures/rules/@typescript-eslint/no-shadow/invalid/const-input.svelte new file mode 100644 index 000000000..837414743 --- /dev/null +++ b/packages/eslint-plugin-svelte/tests/fixtures/rules/@typescript-eslint/no-shadow/invalid/const-input.svelte @@ -0,0 +1,10 @@ + + + + {@const foo = 1} + + {@const foo = 2} + + diff --git a/packages/eslint-plugin-svelte/tests/fixtures/rules/@typescript-eslint/no-shadow/valid/basic-input.svelte b/packages/eslint-plugin-svelte/tests/fixtures/rules/@typescript-eslint/no-shadow/valid/basic-input.svelte new file mode 100644 index 000000000..c90809ca6 --- /dev/null +++ b/packages/eslint-plugin-svelte/tests/fixtures/rules/@typescript-eslint/no-shadow/valid/basic-input.svelte @@ -0,0 +1,10 @@ + diff --git a/packages/eslint-plugin-svelte/tests/fixtures/rules/@typescript-eslint/no-shadow/valid/snippet1-input.svelte b/packages/eslint-plugin-svelte/tests/fixtures/rules/@typescript-eslint/no-shadow/valid/snippet1-input.svelte new file mode 100644 index 000000000..e286d3982 --- /dev/null +++ b/packages/eslint-plugin-svelte/tests/fixtures/rules/@typescript-eslint/no-shadow/valid/snippet1-input.svelte @@ -0,0 +1,13 @@ + + + + {#snippet children()} + + {#snippet children()} + Hello! + {/snippet} + + {/snippet} + diff --git a/packages/eslint-plugin-svelte/tests/fixtures/rules/@typescript-eslint/no-shadow/valid/snippet1-requirements.json b/packages/eslint-plugin-svelte/tests/fixtures/rules/@typescript-eslint/no-shadow/valid/snippet1-requirements.json new file mode 100644 index 000000000..0192b1098 --- /dev/null +++ b/packages/eslint-plugin-svelte/tests/fixtures/rules/@typescript-eslint/no-shadow/valid/snippet1-requirements.json @@ -0,0 +1,3 @@ +{ + "svelte": ">=5.0.0-0" +} diff --git a/packages/eslint-plugin-svelte/tests/fixtures/rules/@typescript-eslint/no-shadow/valid/snippet2-input.svelte b/packages/eslint-plugin-svelte/tests/fixtures/rules/@typescript-eslint/no-shadow/valid/snippet2-input.svelte new file mode 100644 index 000000000..cd5cbdd07 --- /dev/null +++ b/packages/eslint-plugin-svelte/tests/fixtures/rules/@typescript-eslint/no-shadow/valid/snippet2-input.svelte @@ -0,0 +1,10 @@ + + + + {#snippet children()} + Hello! + {/snippet} + diff --git a/packages/eslint-plugin-svelte/tests/fixtures/rules/@typescript-eslint/no-shadow/valid/snippet2-requirements.json b/packages/eslint-plugin-svelte/tests/fixtures/rules/@typescript-eslint/no-shadow/valid/snippet2-requirements.json new file mode 100644 index 000000000..0192b1098 --- /dev/null +++ b/packages/eslint-plugin-svelte/tests/fixtures/rules/@typescript-eslint/no-shadow/valid/snippet2-requirements.json @@ -0,0 +1,3 @@ +{ + "svelte": ">=5.0.0-0" +} diff --git a/packages/eslint-plugin-svelte/tests/src/rules/@typescript-eslint/no-shadow.ts b/packages/eslint-plugin-svelte/tests/src/rules/@typescript-eslint/no-shadow.ts new file mode 100644 index 000000000..fe0f36495 --- /dev/null +++ b/packages/eslint-plugin-svelte/tests/src/rules/@typescript-eslint/no-shadow.ts @@ -0,0 +1,24 @@ +import { RuleTester } from '../../../utils/eslint-compat.js'; +import rule from '../../../../src/rules/@typescript-eslint/no-shadow.js'; +import { loadTestCases, RULES_PROJECT } from '../../../utils/utils.js'; + +const tester = new RuleTester({ + languageOptions: { + ecmaVersion: 2020, + sourceType: 'module', + parserOptions: { + parser: { + ts: '@typescript-eslint/parser', + js: 'espree' + }, + project: RULES_PROJECT, + disallowAutomaticSingleRunInference: true + } + } +}); + +tester.run( + '@typescript-eslint/no-shadow', + rule as any, + loadTestCases('@typescript-eslint/no-shadow') +);