eslint-plugin-vue
Version:
Official ESLint plugin for Vue.js
351 lines (350 loc) • 15.9 kB
JavaScript
const require_index = require("../utils/index.js");
const require_vue_reserved = require("../utils/vue-reserved.json.js");
const require_regexp = require("../utils/regexp.js");
const require_index$1 = require("../utils/style-variables/index.js");
const require_property_references = require("../utils/property-references.js");
let _eslint_community_eslint_utils = require("@eslint-community/eslint-utils");
// lib/rules/no-undef-properties.ts
const GROUP_PROPERTY = "props";
const GROUP_ASYNC_DATA = "asyncData";
const GROUP_DATA = "data";
const GROUP_COMPUTED_PROPERTY = "computed";
const GROUP_METHODS = "methods";
const GROUP_SETUP = "setup";
const GROUP_WATCHER = "watch";
const GROUP_EXPOSE = "expose";
const GROUP_INJECT = "inject";
function getObjectPropertyMap(object) {
const props = /* @__PURE__ */ new Map();
for (const p of object.properties) {
if (p.type !== "Property") return null;
const name = require_index.default.getStaticPropertyName(p);
if (name == null) return null;
props.set(name, p);
}
return props;
}
function getPropertyDataFromObjectProperty(property) {
if (property == null) return null;
const propertyMap = property.value.type === "ObjectExpression" ? getObjectPropertyMap(property.value) : null;
return {
hasNestProperty: Boolean(propertyMap),
get(name) {
return propertyMap ? getPropertyDataFromObjectProperty(propertyMap.get(name)) : null;
}
};
}
var no_undef_properties_default = {
meta: {
type: "suggestion",
docs: {
description: "disallow undefined properties",
categories: void 0,
url: "https://eslint.vuejs.org/rules/no-undef-properties.html"
},
fixable: null,
schema: [{
type: "object",
properties: { ignores: {
type: "array",
items: { type: "string" },
uniqueItems: true
} },
additionalProperties: false
}],
messages: {
undef: "'{{name}}' is not defined.",
undefProps: "'{{name}}' is not defined in props."
}
},
create(context) {
const { ignores = [String.raw`/^\$/`] } = context.options[0] || {};
const isIgnored = require_regexp.toRegExpGroupMatcher(ignores);
const propertyReferenceExtractor = require_property_references.definePropertyReferenceExtractor(context);
const programNode = context.sourceCode.ast;
/**
* Property names identified as defined via a Vuex or Pinia helpers
*/
const propertiesDefinedByStoreHelpers = /* @__PURE__ */ new Set();
/**
* Collect property names defined by a Vuex or Pinia `map*` helper call.
*/
function addPropertiesDefinedByStoreHelper(node) {
if (node.callee.type !== "Identifier") return;
let groupName = null;
if (/^mapMutations|mapActions$/u.test(node.callee.name)) groupName = GROUP_METHODS;
else if (/^mapState|mapGetters|mapWritableState$/u.test(node.callee.name)) groupName = GROUP_COMPUTED_PROPERTY;
if (!groupName || node.arguments.length === 0) return;
const arg = node.arguments.length === 2 ? node.arguments[1] : node.arguments[0];
if (arg.type === "ObjectExpression") for (const prop of arg.properties) {
const name = prop.type === "SpreadElement" ? null : require_index.default.getStaticPropertyName(prop);
if (name) propertiesDefinedByStoreHelpers.add(name);
}
else if (arg.type === "ArrayExpression") for (const element of arg.elements) {
if (!element || !require_index.default.isStringLiteral(element)) continue;
const name = require_index.default.getStringLiteralValue(element);
if (name) propertiesDefinedByStoreHelpers.add(name);
}
}
let reactiveApiNodes = null;
function getReactiveApiNodes() {
if (reactiveApiNodes) return reactiveApiNodes;
const tracker = new _eslint_community_eslint_utils.ReferenceTracker(context.sourceCode.scopeManager.scopes[0]);
const reactive = /* @__PURE__ */ new Set();
const toRefs = /* @__PURE__ */ new Set();
const references = require_index.default.iterateReferencesTraceMap(tracker, {
reactive: { [_eslint_community_eslint_utils.ReferenceTracker.CALL]: true },
toRefs: { [_eslint_community_eslint_utils.ReferenceTracker.CALL]: true }
});
for (const { node, path } of references) if (path.at(-1) === "reactive") reactive.add(node);
else toRefs.add(node);
reactiveApiNodes = {
reactive,
toRefs
};
return reactiveApiNodes;
}
/**
* Resolve `toRefs(reactive({...}))`, or `toRefs(x)` where `x` is a `const`
* initialized with `reactive({...})`, to the object literal passed to `reactive`.
*/
function getReactiveObjectFromToRefs(node) {
if (node.type !== "CallExpression" || !getReactiveApiNodes().toRefs.has(node)) return null;
let arg = node.arguments[0];
if (arg && arg.type === "Identifier") {
const variable = require_index.default.findVariableByIdentifier(context, arg);
if (!variable || variable.defs.length !== 1) return null;
const def = variable.defs[0];
if (def.type !== "Variable" || def.parent.kind !== "const" || !def.node.init) return null;
arg = def.node.init;
}
if (!arg || arg.type !== "CallExpression" || !getReactiveApiNodes().reactive.has(arg)) return null;
const reactiveArg = arg.arguments[0];
return reactiveArg && reactiveArg.type === "ObjectExpression" ? reactiveArg : null;
}
function* iterateSetupReturnObjects(node) {
const setup = require_index.default.findProperty(node, GROUP_SETUP);
if (!setup || setup.value.type !== "FunctionExpression" && setup.value.type !== "ArrowFunctionExpression") return;
const body = setup.value.body;
if (body.type === "ObjectExpression") {
yield body;
return;
}
if (body.type !== "BlockStatement") return;
for (const statement of body.body) if (statement.type === "ReturnStatement" && statement.argument && statement.argument.type === "ObjectExpression") yield statement.argument;
}
function* iterateSpreadToRefsNames(node) {
for (const property of node.properties) {
const reactiveObject = property.type === "SpreadElement" ? getReactiveObjectFromToRefs(property.argument) : null;
if (!reactiveObject) continue;
for (const p of reactiveObject.properties) {
const name = p.type === "Property" && require_index.default.getStaticPropertyName(p);
if (name) yield name;
}
}
}
/**
* Iterate names defined by `...toRefs(reactive({...}))` spreads in the `setup()` return object.
*/
function* iterateSetupToRefsNames(node) {
for (const returned of iterateSetupReturnObjects(node)) yield* iterateSpreadToRefsNames(returned);
}
function isScriptSetupProgram(node) {
return node === programNode;
}
/** Vue component context */
class VueComponentContext {
defineProperties = /* @__PURE__ */ new Map();
reported = /* @__PURE__ */ new Set();
hasUnknownProperty = false;
/**
* Report
*/
verifyReferences(references, options) {
if (this.hasUnknownProperty) return;
const report = this.report.bind(this);
verifyUndefProperties(this.defineProperties, references, null);
function verifyUndefProperties(defineProperties, references, pathName) {
if (!references) return;
for (const [refName, { nodes }] of references.allProperties()) {
const referencePathName = pathName ? `${pathName}.${refName}` : refName;
const prop = defineProperties.get && defineProperties.get(refName);
if (prop) {
if (options && options.isProps && !prop.isProps) {
report(nodes[0], referencePathName, "undefProps");
continue;
}
} else {
report(nodes[0], referencePathName, "undef");
continue;
}
if (prop.hasNestProperty) verifyUndefProperties(prop, references.getNest(refName), referencePathName);
}
}
}
/**
* Report
*/
report(node, name, messageId = "undef") {
if (require_vue_reserved.default.includes(name) || isIgnored(name) || propertiesDefinedByStoreHelpers.has(name) || this.reported.has(node) || this.reported.has(name)) return;
this.reported.add(node);
this.reported.add(name);
context.report({
node,
messageId,
data: { name }
});
}
markAsHasUnknownProperty() {
this.hasUnknownProperty = true;
}
}
const vueComponentContextMap = /* @__PURE__ */ new Map();
function getVueComponentContext(node) {
let ctx = vueComponentContextMap.get(node);
if (!ctx) {
ctx = new VueComponentContext();
vueComponentContextMap.set(node, ctx);
}
return ctx;
}
function getVueComponentContextForTemplate() {
const keys = [...vueComponentContextMap.keys()];
const exported = keys.find(isScriptSetupProgram) || keys.find(require_index.default.isInExportDefault);
return exported && vueComponentContextMap.get(exported);
}
function getParentProperty(node) {
if (!node.parent || node.parent.type !== "Property" || node.parent.value !== node) return null;
const property = node.parent;
return require_index.default.isProperty(property) ? property : null;
}
const scriptVisitor = require_index.default.compositingVisitors({ Program() {
if (!require_index.default.isScriptSetup(context)) return;
const ctx = getVueComponentContext(programNode);
const globalScope = context.sourceCode.scopeManager.globalScope;
if (!globalScope) return;
for (const variable of globalScope.variables) ctx.defineProperties.set(variable.name, {});
const moduleScope = globalScope.childScopes.find((scope) => scope.type === "module");
const moduleVariables = moduleScope && moduleScope.variables || [];
for (const variable of moduleVariables) ctx.defineProperties.set(variable.name, {});
} }, require_index.default.defineScriptSetupVisitor(context, {
onDefinePropsEnter(node, props) {
const ctx = getVueComponentContext(programNode);
for (const prop of props) {
if (prop.type === "unknown") {
ctx.markAsHasUnknownProperty();
return;
}
if (!prop.propName) continue;
ctx.defineProperties.set(prop.propName, { isProps: true });
}
let target = node;
if (target.parent && target.parent.type === "CallExpression" && target.parent.arguments[0] === target && target.parent.callee.type === "Identifier" && target.parent.callee.name === "withDefaults") target = target.parent;
if (!target.parent || target.parent.type !== "VariableDeclarator" || target.parent.init !== target) return;
const pattern = target.parent.id;
const propertyReferences = propertyReferenceExtractor.extractFromPattern(pattern);
ctx.verifyReferences(propertyReferences);
},
onDefineModelEnter(_node, model) {
getVueComponentContext(programNode).defineProperties.set(model.name.modelName, { isProps: true });
}
}), require_index.default.defineVueVisitor(context, {
CallExpression(node) {
addPropertiesDefinedByStoreHelper(node);
},
onVueObjectEnter(node) {
const ctx = getVueComponentContext(node);
for (const groupName of [GROUP_COMPUTED_PROPERTY, GROUP_METHODS]) {
const group = require_index.default.findProperty(node, groupName);
if (!group) continue;
const values = group.value.type === "ObjectExpression" ? group.value.properties.map((p) => p.type === "SpreadElement" ? p.argument : null) : [group.value];
for (const value of values) if (value && value.type === "CallExpression") addPropertiesDefinedByStoreHelper(value);
}
const properties = require_index.default.iterateProperties(node, /* @__PURE__ */ new Set([
GROUP_PROPERTY,
GROUP_ASYNC_DATA,
GROUP_DATA,
GROUP_COMPUTED_PROPERTY,
GROUP_SETUP,
GROUP_METHODS,
GROUP_INJECT
]));
for (const prop of properties) {
const propertyMap = (prop.groupName === GROUP_DATA || prop.groupName === GROUP_ASYNC_DATA) && prop.type === "object" && prop.property.value.type === "ObjectExpression" ? getObjectPropertyMap(prop.property.value) : null;
ctx.defineProperties.set(prop.name, {
hasNestProperty: Boolean(propertyMap),
isProps: prop.groupName === GROUP_PROPERTY,
get(name) {
return propertyMap ? getPropertyDataFromObjectProperty(propertyMap.get(name)) : null;
}
});
}
for (const name of iterateSetupToRefsNames(node)) if (!ctx.defineProperties.has(name)) ctx.defineProperties.set(name, {});
const watchersAndExposes = require_index.default.iterateProperties(node, /* @__PURE__ */ new Set([GROUP_WATCHER, GROUP_EXPOSE]));
for (const watcherOrExpose of watchersAndExposes) if (watcherOrExpose.groupName === GROUP_WATCHER) {
const watcher = watcherOrExpose;
ctx.verifyReferences(propertyReferenceExtractor.extractFromPath(watcher.name, watcher.node));
if (watcher.type === "object") {
const property = watcher.property;
if (property.kind === "init") for (const handlerValueNode of require_index.default.iterateWatchHandlerValues(property)) ctx.verifyReferences(propertyReferenceExtractor.extractFromNameLiteral(handlerValueNode));
}
} else if (watcherOrExpose.groupName === GROUP_EXPOSE) {
const expose = watcherOrExpose;
ctx.verifyReferences(propertyReferenceExtractor.extractFromName(expose.name, expose.node));
}
},
"ObjectExpression > Property > :function[params.length>0]"(node, vueData) {
const property = getParentProperty(node);
if (!property) return;
let isProps = false;
if (property.parent === vueData.node) {
if (require_index.default.getStaticPropertyName(property) !== "data") return;
isProps = true;
} else {
const parentProperty = getParentProperty(property.parent);
if (!parentProperty) return;
if (parentProperty.parent === vueData.node) {
if (require_index.default.getStaticPropertyName(parentProperty) !== "computed") return;
} else {
const parentParentProperty = getParentProperty(parentProperty.parent);
if (!parentParentProperty) return;
if (parentParentProperty.parent === vueData.node) {
if (require_index.default.getStaticPropertyName(parentParentProperty) !== "computed" || require_index.default.getStaticPropertyName(property) !== "get") return;
} else return;
}
}
const propertyReferences = propertyReferenceExtractor.extractFromFunctionParam(node, 0);
getVueComponentContext(vueData.node).verifyReferences(propertyReferences, { isProps });
},
onSetupFunctionEnter(node, vueData) {
const propertyReferences = propertyReferenceExtractor.extractFromFunctionParam(node, 0);
getVueComponentContext(vueData.node).verifyReferences(propertyReferences, { isProps: true });
},
onRenderFunctionEnter(node, vueData) {
const ctx = getVueComponentContext(vueData.node);
const propertyReferences = propertyReferenceExtractor.extractFromFunctionParam(node, 0);
ctx.verifyReferences(propertyReferences);
if (!vueData.functional) return;
const propertyReferencesForV2 = propertyReferenceExtractor.extractFromFunctionParam(node, 1);
ctx.verifyReferences(propertyReferencesForV2.getNest("props"), { isProps: true });
},
"ThisExpression, Identifier"(node, vueData) {
if (!require_index.default.isThis(node, context)) return;
const ctx = getVueComponentContext(vueData.node);
const propertyReferences = propertyReferenceExtractor.extractFromExpression(node, false);
ctx.verifyReferences(propertyReferences);
}
}), { "Program:exit"() {
const ctx = getVueComponentContextForTemplate();
if (!ctx) return;
const styleVars = require_index$1.getStyleVariablesContext(context);
if (styleVars) ctx.verifyReferences(propertyReferenceExtractor.extractFromStyleVariablesContext(styleVars));
} });
return require_index.default.defineTemplateBodyVisitor(context, { VExpressionContainer(node) {
const ctx = getVueComponentContextForTemplate();
if (!ctx) return;
ctx.verifyReferences(propertyReferenceExtractor.extractFromVExpressionContainer(node, { ignoreGlobals: true }));
} }, scriptVisitor);
}
};
exports.default = no_undef_properties_default;