pnpm-test/eslint/eslint-pinia.cjs

74 lines
2.1 KiB
JavaScript

"use strict";
const storeIds = new Map();
module.exports = {
meta: {
type: "problem",
docs: {
description: "Disallow duplicate Pinia defineStore ids",
},
schema: [],
messages: {
duplicate: "Pinia store id '{{id}}' is already defined in {{file}}.",
},
},
create(context) {
const filename = context.getFilename();
function reportIfDuplicate(id, node) {
const existingFile = storeIds.get(id);
if (existingFile === filename) {
return;
}
if (existingFile) {
context.report({
node,
messageId: "duplicate",
data: {
id,
file: existingFile,
},
});
return;
}
storeIds.set(id, filename);
}
return {
CallExpression(node) {
if (
node.callee.type === "Identifier" &&
node.callee.name === "defineStore" &&
node.arguments.length > 0
) {
const firstArg = node.arguments[0];
if (firstArg.type === "Literal" && typeof firstArg.value === "string") {
reportIfDuplicate(firstArg.value, firstArg);
}
if (firstArg.type === "ObjectExpression") {
const idProp = firstArg.properties.find(
(p) =>
p.type === "Property" &&
p.key.type === "Identifier" &&
p.key.name === "id" &&
p.value.type === "Literal" &&
typeof p.value.value === "string"
);
if (idProp) {
reportIfDuplicate(idProp.value.value, idProp.value);
}
}
}
},
};
},
};