/** * @author Toru Nagashima * @copyright 2017 Toru Nagashima. All rights reserved. * See LICENSE file in root directory for full license. */ 'use strict' /** * @typedef {import('eslint').Rule.RuleModule} RuleModule * @typedef {import('estree').Position} Position * @typedef {import('eslint').Rule.CodePath} CodePath * @typedef {import('eslint').Rule.CodePathSegment} CodePathSegment */ /** * @typedef {import('../../typings/eslint-plugin-vue/util-types/utils').ComponentArrayProp} ComponentArrayProp * @typedef {import('../../typings/eslint-plugin-vue/util-types/utils').ComponentObjectProp} ComponentObjectProp * @typedef {import('../../typings/eslint-plugin-vue/util-types/utils').ComponentTypeProp} ComponentTypeProp * @typedef {import('../../typings/eslint-plugin-vue/util-types/utils').ComponentArrayEmit} ComponentArrayEmit * @typedef {import('../../typings/eslint-plugin-vue/util-types/utils').ComponentObjectEmit} ComponentObjectEmit * @typedef {import('../../typings/eslint-plugin-vue/util-types/utils').ComponentTypeEmit} ComponentTypeEmit */ /** * @typedef { {key: string | null, value: BlockStatement | null} } ComponentComputedProperty */ /** * @typedef { 'props' | 'data' | 'computed' | 'setup' | 'watch' | 'methods' | 'provide' | 'inject' | 'expose' } GroupName * @typedef { { type: 'array', name: string, groupName: GroupName, node: Literal | TemplateLiteral } } ComponentArrayPropertyData * @typedef { { type: 'object', name: string, groupName: GroupName, node: Identifier | Literal | TemplateLiteral, property: Property } } ComponentObjectPropertyData * @typedef { ComponentArrayPropertyData | ComponentObjectPropertyData } ComponentPropertyData */ /** * @typedef {import('../../typings/eslint-plugin-vue/util-types/utils').VueObjectType} VueObjectType * @typedef {import('../../typings/eslint-plugin-vue/util-types/utils').VueObjectData} VueObjectData * @typedef {import('../../typings/eslint-plugin-vue/util-types/utils').VueVisitor} VueVisitor * @typedef {import('../../typings/eslint-plugin-vue/util-types/utils').ScriptSetupVisitor} ScriptSetupVisitor */ // ------------------------------------------------------------------------------ // Helpers // ------------------------------------------------------------------------------ const HTML_ELEMENT_NAMES = new Set(require('./html-elements.json')) const SVG_ELEMENT_NAMES = new Set(require('./svg-elements.json')) const VOID_ELEMENT_NAMES = new Set(require('./void-elements.json')) const VUE2_BUILTIN_COMPONENT_NAMES = new Set( require('./vue2-builtin-components') ) const VUE3_BUILTIN_COMPONENT_NAMES = new Set( require('./vue3-builtin-components') ) const path = require('path') const vueEslintParser = require('vue-eslint-parser') const { traverseNodes, getFallbackKeys } = vueEslintParser.AST const { findVariable } = require('eslint-utils') const { getComponentPropsFromTypeDefine, getComponentEmitsFromTypeDefine, isTypeNode } = require('./ts-ast-utils') /** * @type { WeakMap } */ const componentComments = new WeakMap() /** @type { Map | null } */ let ruleMap = null /** * Get the core rule implementation from the rule name * @param {string} name * @returns {RuleModule} */ function getCoreRule(name) { const map = ruleMap || (ruleMap = new (require('eslint').Linter)().getRules()) return map.get(name) || require(`eslint/lib/rules/${name}`) } /** * Wrap the rule context object to override methods which access to tokens (such as getTokenAfter). * @param {RuleContext} context The rule context object. * @param {ParserServices.TokenStore} tokenStore The token store object for template. * @param {Object} options The option of this rule. * @param {boolean} [options.applyDocument] If `true`, apply check to document fragment. * @returns {RuleContext} */ function wrapContextToOverrideTokenMethods(context, tokenStore, options) { const eslintSourceCode = context.getSourceCode() const rootNode = options.applyDocument ? context.parserServices.getDocumentFragment && context.parserServices.getDocumentFragment() : eslintSourceCode.ast.templateBody /** @type {Token[] | null} */ let tokensAndComments = null function getTokensAndComments() { if (tokensAndComments) { return tokensAndComments } tokensAndComments = rootNode ? tokenStore.getTokens(rootNode, { includeComments: true }) : [] return tokensAndComments } /** @param {number} index */ function getNodeByRangeIndex(index) { if (!rootNode) { return eslintSourceCode.ast } /** @type {ASTNode} */ let result = eslintSourceCode.ast /** @type {ASTNode[]} */ const skipNodes = [] let breakFlag = false traverseNodes(rootNode, { enterNode(node, parent) { if (breakFlag) { return } if (skipNodes[0] === parent) { skipNodes.unshift(node) return } if (node.range[0] <= index && index < node.range[1]) { result = node } else { skipNodes.unshift(node) } }, leaveNode(node) { if (breakFlag) { return } if (result === node) { breakFlag = true } else if (skipNodes[0] === node) { skipNodes.shift() } } }) return result } const sourceCode = new Proxy(Object.assign({}, eslintSourceCode), { get(_object, key) { if (key === 'tokensAndComments') { return getTokensAndComments() } if (key === 'getNodeByRangeIndex') { return getNodeByRangeIndex } // @ts-expect-error return key in tokenStore ? tokenStore[key] : eslintSourceCode[key] } }) const containerScopes = new WeakMap() /** * @param {ASTNode} node */ function getContainerScope(node) { const exprContainer = getVExpressionContainer(node) if (!exprContainer) { return null } const cache = containerScopes.get(exprContainer) if (cache) { return cache } const programNode = eslintSourceCode.ast const parserOptions = context.parserOptions || {} const ecmaFeatures = parserOptions.ecmaFeatures || {} const ecmaVersion = parserOptions.ecmaVersion || 2020 const sourceType = programNode.sourceType try { const eslintScope = createRequire(require.resolve('eslint'))( 'eslint-scope' ) const expStmt = new Proxy(exprContainer, { get(_object, key) { if (key === 'type') { return 'ExpressionStatement' } // @ts-expect-error return exprContainer[key] } }) const scopeProgram = new Proxy(programNode, { get(_object, key) { if (key === 'body') { return [expStmt] } // @ts-expect-error return programNode[key] } }) const scope = eslintScope.analyze(scopeProgram, { ignoreEval: true, nodejsScope: false, impliedStrict: ecmaFeatures.impliedStrict, ecmaVersion, sourceType, fallback: getFallbackKeys }) containerScopes.set(exprContainer, scope) return scope } catch (e) { // ignore // console.log(e) } return null } return { // @ts-expect-error __proto__: context, getSourceCode() { return sourceCode }, getDeclaredVariables(node) { const scope = getContainerScope(node) if (scope) { return scope.getDeclaredVariables(node) } return context.getDeclaredVariables(node) } } } /** * Wrap the rule context object to override report method to skip the dynamic argument. * @param {RuleContext} context The rule context object. * @returns {RuleContext} */ function wrapContextToOverrideReportMethodToSkipDynamicArgument(context) { const sourceCode = context.getSourceCode() const templateBody = sourceCode.ast.templateBody if (!templateBody) { return context } /** @type {Range[]} */ const directiveKeyRanges = [] const traverseNodes = vueEslintParser.AST.traverseNodes traverseNodes(templateBody, { enterNode(node, parent) { if ( parent && parent.type === 'VDirectiveKey' && node.type === 'VExpressionContainer' ) { directiveKeyRanges.push(node.range) } }, leaveNode() {} }) return { // @ts-expect-error __proto__: context, report(descriptor, ...args) { let range = null if (descriptor.loc) { const startLoc = descriptor.loc.start || descriptor.loc const endLoc = descriptor.loc.end || startLoc range = [ sourceCode.getIndexFromLoc(startLoc), sourceCode.getIndexFromLoc(endLoc) ] } else if (descriptor.node) { range = descriptor.node.range } if (range) { for (const directiveKeyRange of directiveKeyRanges) { if ( range[0] < directiveKeyRange[1] && directiveKeyRange[0] < range[1] ) { return } } } context.report(descriptor, ...args) } } } // ------------------------------------------------------------------------------ // Exports // ------------------------------------------------------------------------------ module.exports = { /** * Register the given visitor to parser services. * If the parser service of `vue-eslint-parser` was not found, * this generates a warning. * * @param {RuleContext} context The rule context to use parser services. * @param {TemplateListener} templateBodyVisitor The visitor to traverse the template body. * @param {RuleListener} [scriptVisitor] The visitor to traverse the script. * @param { { templateBodyTriggerSelector: "Program" | "Program:exit" } } [options] The options. * @returns {RuleListener} The merged visitor. */ defineTemplateBodyVisitor, /** * Register the given visitor to parser services. * If the parser service of `vue-eslint-parser` was not found, * this generates a warning. * * @param {RuleContext} context The rule context to use parser services. * @param {TemplateListener} documentVisitor The visitor to traverse the document. * @param { { triggerSelector: "Program" | "Program:exit" } } [options] The options. * @returns {RuleListener} The merged visitor. */ defineDocumentVisitor, /** * Wrap a given core rule to apply it to Vue.js template. * @param {string} coreRuleName The name of the core rule implementation to wrap. * @param {Object} [options] The option of this rule. * @param {string[]} [options.categories] The categories of this rule. * @param {boolean} [options.skipDynamicArguments] If `true`, skip validation within dynamic arguments. * @param {boolean} [options.skipDynamicArgumentsReport] If `true`, skip report within dynamic arguments. * @param {boolean} [options.applyDocument] If `true`, apply check to document fragment. * @param { (context: RuleContext, options: { coreHandlers: RuleListener }) => TemplateListener } [options.create] If define, extend core rule. * @returns {RuleModule} The wrapped rule implementation. */ wrapCoreRule(coreRuleName, options) { const coreRule = getCoreRule(coreRuleName) const { categories, skipDynamicArguments, skipDynamicArgumentsReport, applyDocument, create } = options || {} return { create(context) { const tokenStore = context.parserServices.getTemplateBodyTokenStore && context.parserServices.getTemplateBodyTokenStore() // The `context.getSourceCode()` cannot access the tokens of templates. // So override the methods which access to tokens by the `tokenStore`. if (tokenStore) { context = wrapContextToOverrideTokenMethods(context, tokenStore, { applyDocument }) } if (skipDynamicArgumentsReport) { context = wrapContextToOverrideReportMethodToSkipDynamicArgument(context) } // Move `Program` handlers to `VElement[parent.type!='VElement']` const coreHandlers = coreRule.create(context) const handlers = /** @type {TemplateListener} */ ( Object.assign({}, coreHandlers) ) if (handlers.Program) { handlers[ applyDocument ? 'VDocumentFragment' : "VElement[parent.type!='VElement']" ] = /** @type {any} */ (handlers.Program) delete handlers.Program } if (handlers['Program:exit']) { handlers[ applyDocument ? 'VDocumentFragment:exit' : "VElement[parent.type!='VElement']:exit" ] = /** @type {any} */ (handlers['Program:exit']) delete handlers['Program:exit'] } if (skipDynamicArguments) { let withinDynamicArguments = false for (const name of Object.keys(handlers)) { const original = handlers[name] /** @param {any[]} args */ handlers[name] = (...args) => { if (withinDynamicArguments) return // @ts-expect-error original(...args) } } handlers['VDirectiveKey > VExpressionContainer'] = () => { withinDynamicArguments = true } handlers['VDirectiveKey > VExpressionContainer:exit'] = () => { withinDynamicArguments = false } } if (create) { compositingVisitors(handlers, create(context, { coreHandlers })) } if (applyDocument) { // Apply the handlers to document. return defineDocumentVisitor(context, handlers) } // Apply the handlers to templates. return defineTemplateBodyVisitor(context, handlers) }, meta: Object.assign({}, coreRule.meta, { docs: Object.assign({}, coreRule.meta.docs, { category: null, categories, url: `https://eslint.vuejs.org/rules/${path.basename( coreRule.meta.docs.url || '' )}.html`, extensionRule: true, coreRuleUrl: coreRule.meta.docs.url }) }) } }, /** * Checks whether the given value is defined. * @template T * @param {T | null | undefined} v * @returns {v is T} */ isDef, /** * Get the previous sibling element of the given element. * @param {VElement} node The element node to get the previous sibling element. * @returns {VElement|null} The previous sibling element. */ prevSibling(node) { let prevElement = null for (const siblingNode of (node.parent && node.parent.children) || []) { if (siblingNode === node) { return prevElement } if (siblingNode.type === 'VElement') { prevElement = siblingNode } } return null }, /** * Check whether the given directive attribute has their empty value (`=""`). * @param {VDirective} node The directive attribute node to check. * @param {RuleContext} context The rule context to use parser services. * @returns {boolean} `true` if the directive attribute has their empty value (`=""`). */ isEmptyValueDirective(node, context) { if (node.value == null) { return false } if (node.value.expression != null) { return false } let valueText = context.getSourceCode().getText(node.value) if ( (valueText[0] === '"' || valueText[0] === "'") && valueText[0] === valueText[valueText.length - 1] ) { // quoted valueText = valueText.slice(1, -1) } if (!valueText) { // empty return true } return false }, /** * Check whether the given directive attribute has their empty expression value (e.g. `=" "`, `="/* */"`). * @param {VDirective} node The directive attribute node to check. * @param {RuleContext} context The rule context to use parser services. * @returns {boolean} `true` if the directive attribute has their empty expression value. */ isEmptyExpressionValueDirective(node, context) { if (node.value == null) { return false } if (node.value.expression != null) { return false } const valueNode = node.value const tokenStore = context.parserServices.getTemplateBodyTokenStore() let quote1 = null let quote2 = null // `node.value` may be only comments, so cannot get the correct tokens with `tokenStore.getTokens(node.value)`. for (const token of tokenStore.getTokens(node)) { if (token.range[1] <= valueNode.range[0]) { continue } if (valueNode.range[1] <= token.range[0]) { // empty return true } if ( !quote1 && token.type === 'Punctuator' && (token.value === '"' || token.value === "'") ) { quote1 = token continue } if ( !quote2 && quote1 && token.type === 'Punctuator' && token.value === quote1.value ) { quote2 = token continue } // not empty return false } // empty return true }, /** * Get the attribute which has the given name. * @param {VElement} node The start tag node to check. * @param {string} name The attribute name to check. * @param {string} [value] The attribute value to check. * @returns {VAttribute | null} The found attribute. */ getAttribute, /** * Check whether the given start tag has specific directive. * @param {VElement} node The start tag node to check. * @param {string} name The attribute name to check. * @param {string} [value] The attribute value to check. * @returns {boolean} `true` if the start tag has the attribute. */ hasAttribute, /** * Get the directive list which has the given name. * @param {VElement | VStartTag} node The start tag node to check. * @param {string} name The directive name to check. * @returns {VDirective[]} The array of `v-slot` directives. */ getDirectives, /** * Get the directive which has the given name. * @param {VElement} node The start tag node to check. * @param {string} name The directive name to check. * @param {string} [argument] The directive argument to check. * @returns {VDirective | null} The found directive. */ getDirective, /** * Check whether the given start tag has specific directive. * @param {VElement} node The start tag node to check. * @param {string} name The directive name to check. * @param {string} [argument] The directive argument to check. * @returns {boolean} `true` if the start tag has the directive. */ hasDirective, /** * Returns the list of all registered components * @param {ObjectExpression} componentObject * @returns { { node: Property, name: string }[] } Array of ASTNodes */ getRegisteredComponents(componentObject) { const componentsNode = componentObject.properties.find( /** * @param {ESNode} p * @returns {p is (Property & { key: Identifier & {name: 'components'}, value: ObjectExpression })} */ (p) => { return ( p.type === 'Property' && getStaticPropertyName(p) === 'components' && p.value.type === 'ObjectExpression' ) } ) if (!componentsNode) { return [] } return componentsNode.value.properties .filter(isProperty) .map((node) => { const name = getStaticPropertyName(node) return name ? { node, name } : null }) .filter(isDef) }, /** * Check whether the previous sibling element has `if` or `else-if` directive. * @param {VElement} node The element node to check. * @returns {boolean} `true` if the previous sibling element has `if` or `else-if` directive. */ prevElementHasIf(node) { const prev = this.prevSibling(node) return ( prev != null && prev.startTag.attributes.some( (a) => a.directive && (a.key.name.name === 'if' || a.key.name.name === 'else-if') ) ) }, /** * Returns a generator with all child element v-if chains of the given element. * @param {VElement} node The element node to check. * @returns {IterableIterator} */ *iterateChildElementsChains(node) { let vIf = false /** @type {VElement[]} */ let elementChain = [] for (const childNode of node.children) { if (childNode.type === 'VElement') { let connected if (hasDirective(childNode, 'if')) { connected = false vIf = true } else if (hasDirective(childNode, 'else-if')) { connected = vIf vIf = true } else if (hasDirective(childNode, 'else')) { connected = vIf vIf = false } else { connected = false vIf = false } if (connected) { elementChain.push(childNode) } else { if (elementChain.length) { yield elementChain } elementChain = [childNode] } } else if (childNode.type !== 'VText' || childNode.value.trim() !== '') { vIf = false } } if (elementChain.length) { yield elementChain } }, /** * Check whether the given node is a custom component or not. * @param {VElement} node The start tag node to check. * @returns {boolean} `true` if the node is a custom component. */ isCustomComponent(node) { return ( (this.isHtmlElementNode(node) && !this.isHtmlWellKnownElementName(node.rawName)) || (this.isSvgElementNode(node) && !this.isSvgWellKnownElementName(node.rawName)) || hasAttribute(node, 'is') || hasDirective(node, 'bind', 'is') || hasDirective(node, 'is') ) }, /** * Check whether the given node is a HTML element or not. * @param {VElement} node The node to check. * @returns {boolean} `true` if the node is a HTML element. */ isHtmlElementNode(node) { return node.namespace === vueEslintParser.AST.NS.HTML }, /** * Check whether the given node is a SVG element or not. * @param {VElement} node The node to check. * @returns {boolean} `true` if the name is a SVG element. */ isSvgElementNode(node) { return node.namespace === vueEslintParser.AST.NS.SVG }, /** * Check whether the given name is a MathML element or not. * @param {VElement} node The node to check. * @returns {boolean} `true` if the node is a MathML element. */ isMathMLElementNode(node) { return node.namespace === vueEslintParser.AST.NS.MathML }, /** * Check whether the given name is an well-known element or not. * @param {string} name The name to check. * @returns {boolean} `true` if the name is an well-known element name. */ isHtmlWellKnownElementName(name) { return HTML_ELEMENT_NAMES.has(name) }, /** * Check whether the given name is an well-known SVG element or not. * @param {string} name The name to check. * @returns {boolean} `true` if the name is an well-known SVG element name. */ isSvgWellKnownElementName(name) { return SVG_ELEMENT_NAMES.has(name) }, /** * Check whether the given name is a void element name or not. * @param {string} name The name to check. * @returns {boolean} `true` if the name is a void element name. */ isHtmlVoidElementName(name) { return VOID_ELEMENT_NAMES.has(name) }, /** * Check whether the given name is Vue builtin component name or not. * @param {string} name The name to check. * @returns {boolean} `true` if the name is a builtin component name */ isBuiltInComponentName(name) { return ( VUE3_BUILTIN_COMPONENT_NAMES.has(name) || VUE2_BUILTIN_COMPONENT_NAMES.has(name) ) }, /** * Check whether the given name is Vue builtin directive name or not. * @param {string} name The name to check. * @returns {boolean} `true` if the name is a builtin Directive name */ isBuiltInDirectiveName(name) { return ( name === 'bind' || name === 'on' || name === 'text' || name === 'html' || name === 'show' || name === 'if' || name === 'else' || name === 'else-if' || name === 'for' || name === 'model' || name === 'slot' || name === 'pre' || name === 'cloak' || name === 'once' || name === 'memo' || name === 'is' ) }, /** * Gets the property name of a given node. * @param {Property|AssignmentProperty|MethodDefinition|MemberExpression} node - The node to get. * @return {string|null} The property name if static. Otherwise, null. */ getStaticPropertyName, /** * Gets the string of a given node. * @param {Literal|TemplateLiteral} node - The node to get. * @return {string|null} The string if static. Otherwise, null. */ getStringLiteralValue, /** * Get all props by looking at all component's properties * @param {ObjectExpression} componentObject Object with component definition * @return {(ComponentArrayProp | ComponentObjectProp)[]} Array of component props in format: [{key?: String, value?: ASTNode, node: ASTNod}] */ getComponentProps(componentObject) { const propsNode = componentObject.properties.find( /** * @param {ESNode} p * @returns {p is (Property & { key: Identifier & {name: 'props'}, value: ObjectExpression | ArrayExpression })} */ (p) => { return ( p.type === 'Property' && getStaticPropertyName(p) === 'props' && (p.value.type === 'ObjectExpression' || p.value.type === 'ArrayExpression') ) } ) if (!propsNode) { return [] } return getComponentPropsFromDefine(propsNode.value) }, /** * Get all emits by looking at all component's properties * @param {ObjectExpression} componentObject Object with component definition * @return {(ComponentArrayEmit | ComponentObjectEmit)[]} Array of component emits in format: [{key?: String, value?: ASTNode, node: ASTNod}] */ getComponentEmits(componentObject) { const emitsNode = componentObject.properties.find( /** * @param {ESNode} p * @returns {p is (Property & { key: Identifier & {name: 'emits'}, value: ObjectExpression | ArrayExpression })} */ (p) => { return ( p.type === 'Property' && getStaticPropertyName(p) === 'emits' && (p.value.type === 'ObjectExpression' || p.value.type === 'ArrayExpression') ) } ) if (!emitsNode) { return [] } return getComponentEmitsFromDefine(emitsNode.value) }, /** * Get all computed properties by looking at all component's properties * @param {ObjectExpression} componentObject Object with component definition * @return {ComponentComputedProperty[]} Array of computed properties in format: [{key: String, value: ASTNode}] */ getComputedProperties(componentObject) { const computedPropertiesNode = componentObject.properties.find( /** * @param {ESNode} p * @returns {p is (Property & { key: Identifier & {name: 'computed'}, value: ObjectExpression })} */ (p) => { return ( p.type === 'Property' && getStaticPropertyName(p) === 'computed' && p.value.type === 'ObjectExpression' ) } ) if (!computedPropertiesNode) { return [] } return computedPropertiesNode.value.properties .filter(isProperty) .map((cp) => { const key = getStaticPropertyName(cp) /** @type {Expression} */ const propValue = skipTSAsExpression(cp.value) /** @type {BlockStatement | null} */ let value = null if (propValue.type === 'FunctionExpression') { value = propValue.body } else if (propValue.type === 'ObjectExpression') { const get = /** @type {(Property & { value: FunctionExpression }) | null} */ ( findProperty( propValue, 'get', (p) => p.value.type === 'FunctionExpression' ) ) value = get ? get.value.body : null } return { key, value } }) }, /** * Get getter body from computed function * @param {CallExpression} callExpression call of computed function * @return {FunctionExpression | ArrowFunctionExpression | null} getter function */ getGetterBodyFromComputedFunction(callExpression) { if (callExpression.arguments.length <= 0) { return null } const arg = callExpression.arguments[0] if ( arg.type === 'FunctionExpression' || arg.type === 'ArrowFunctionExpression' ) { return arg } if (arg.type === 'ObjectExpression') { const getProperty = /** @type {(Property & { value: FunctionExpression | ArrowFunctionExpression }) | null} */ ( findProperty( arg, 'get', (p) => p.value.type === 'FunctionExpression' || p.value.type === 'ArrowFunctionExpression' ) ) return getProperty ? getProperty.value : null } return null }, isVueFile, /** * Checks whether the current file is uses `