eslint-plugin-vue
Version:
Official ESLint plugin for Vue.js
80 lines (79 loc) • 2.97 kB
JavaScript
const require_runtime = require("../_virtual/_rolldown/runtime.js");
const require_index = require("../utils/index.js");
let node_path = require("node:path");
node_path = require_runtime.__toESM(node_path);
// lib/rules/require-name-property.ts
/**
* @fileoverview Require a name property in Vue components
* @author LukeeeeBennett
*/
const { getVueComponentDefinitionType } = require_index.default;
/**
* Get the text of the empty indentation part of the line which the given token is on.
* @param sourceCode the source code object
* @param token the token to get the indentation text of the line which the token is on
* @returns The text of indentation part.
*/
function getLineEmptyIndent(sourceCode, token) {
const LT_CHAR = /[\n\r\u{2028}\u{2029}]/u;
const EMPTY_CHAR = /\s/;
const text = sourceCode.text;
let i = token.range[0] - 1;
while (i >= 0 && !LT_CHAR.test(text[i])) i -= 1;
let j = i;
while (EMPTY_CHAR.test(text[j])) j += 1;
return text.slice(i + 1, j);
}
function isNameProperty(node) {
return node.type === "Property" && require_index.default.getStaticPropertyName(node) === "name" && !node.computed;
}
var require_name_property_default = {
meta: {
type: "suggestion",
docs: {
description: "require a name property in Vue components",
categories: void 0,
url: "https://eslint.vuejs.org/rules/require-name-property.html"
},
fixable: null,
hasSuggestions: true,
schema: [],
messages: {
missingName: "Required name property is not set.",
addName: "Add name property to component."
}
},
create(context) {
if (require_index.default.isScriptSetup(context)) return {};
return require_index.default.executeOnVue(context, (component, type) => {
if (type === "definition") {
if (getVueComponentDefinitionType(context, component) === "mixin") return;
}
if (component.properties.some(isNameProperty)) return;
context.report({
node: component,
messageId: "missingName",
suggest: [{
messageId: "addName",
fix(fixer) {
const extension = node_path.default.extname(context.filename);
const filename = node_path.default.basename(context.filename, extension);
const sourceCode = context.sourceCode;
if (component.properties.length > 0) {
const indentText = getLineEmptyIndent(sourceCode, sourceCode.getFirstToken(component.properties[0]));
return fixer.insertTextBefore(component.properties[0], `name: '${filename}',\n${indentText}`);
}
const firstToken = sourceCode.getFirstToken(component);
const lastToken = sourceCode.getLastToken(component);
if (firstToken.value === "{" && lastToken.value === "}") {
const indentText = getLineEmptyIndent(sourceCode, firstToken);
return fixer.replaceTextRange([firstToken.range[1], lastToken.range[0]], `\n${indentText} name: '${filename}'\n${indentText}`);
}
return null;
}
}]
});
});
}
};
exports.default = require_name_property_default;