/** * @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').ComponentUnknownProp} ComponentUnknownProp * @typedef {import('../../typings/eslint-plugin-vue/util-types/utils').ComponentProp} ComponentProp * @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 {import('../../typings/eslint-plugin-vue/util-types/utils').ComponentUnknownEmit} ComponentUnknownEmit * @typedef {import('../../typings/eslint-plugin-vue/util-types/utils').ComponentEmit} ComponentEmit */ /** * @typedef { {key: string | null, value: BlockStatement | null} } ComponentComputedProperty */ /** * @typedef { 'props' | 'asyncData' | '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 | null} */ function getCoreRule(name) { const map = ruleMap || (ruleMap = new (require('eslint').Linter)().getRules()) return map.get(name) || null } /** * @template {object} T * @param {T} target * @param {Partial[]} propsArray * @returns {T} */ function newProxy(target, ...propsArray) { const result = new Proxy( {}, { get(_object, key) { for (const props of propsArray) { if (key in props) { // @ts-expect-error return props[key] } } // @ts-expect-error return target[key] }, has(_object, key) { return key in target }, ownKeys(_object) { return Reflect.ownKeys(target) }, getPrototypeOf(_object) { return Reflect.getPrototypeOf(target) } } ) return /** @type {T} */ (result) } /** * 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 = newProxy( eslintSourceCode, { get tokensAndComments() { return getTokensAndComments() }, getNodeByRangeIndex }, tokenStore ) 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 = newProxy(exprContainer, { // @ts-expect-error type: 'ExpressionStatement' }) const scopeProgram = newProxy(programNode, { // @ts-expect-error body: [expStmt] }) 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 newProxy(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 newProxy(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, /** * @callback WrapCoreRuleCreate * @param {RuleContext} ruleContext * @param {WrapCoreRuleCreateContext} wrapContext * @returns {TemplateListener} * * @typedef {object} WrapCoreRuleCreateContext * @property {RuleListener} coreHandlers */ /** * @callback WrapCoreRulePreprocess * @param {RuleContext} ruleContext * @param {WrapCoreRulePreprocessContext} wrapContext * @returns {void} * * @typedef {object} WrapCoreRulePreprocessContext * @property { (override: Partial) => RuleContext } wrapContextToOverrideProperties Wrap the rule context object to override * @property { (visitor: TemplateListener) => void } defineVisitor Define template body visitor */ /** * 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 {WrapCoreRulePreprocess} [options.preprocess] Preprocess to calling create of core rule. * @param {WrapCoreRuleCreate} [options.create] If define, extend core rule. * @returns {RuleModule} The wrapped rule implementation. */ wrapCoreRule(coreRuleName, options) { const coreRule = getCoreRule(coreRuleName) if (!coreRule) { return { meta: { type: 'problem', docs: { url: `https://eslint.vuejs.org/rules/${coreRuleName}.html` } }, create(context) { return defineTemplateBodyVisitor(context, { "VElement[name='template'][parent.type='VDocumentFragment']"(node) { context.report({ node, message: `Failed to extend ESLint core rule "${coreRuleName}". You may be able to use this rule by upgrading the version of ESLint. If you cannot upgrade it, turn off this rule.` }) } }) } } } let description = coreRule.meta.docs.description if (description) { description += ' in `