eslint-plugin-sitecore-jss
Version:
An ESLint plugin to enforce correct usage of Sitecore JSS components
76 lines • 3.49 kB
JavaScript
;
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
const utils_1 = require("@typescript-eslint/utils");
const type_checking_1 = __importDefault(require("./utils/type-checking"));
const { getType, isFileField } = type_checking_1.default;
exports.default = {
defaultOptions: [],
meta: {
type: "problem",
docs: {
description: "Ensure `<File>` is used instead of raw `<a>` for `FileField`.",
recommended: "recommended",
},
messages: {
useFileComponent: "Use `<File field={{fieldName}} />` instead of `<a>` for Sitecore file fields.",
},
fixable: "code",
schema: [],
},
create(context) {
const parserServices = utils_1.ESLintUtils.getParserServices(context);
if (!parserServices || !parserServices.program)
return {};
const checker = parserServices.program.getTypeChecker();
return {
JSXOpeningElement(node) {
if (node.name.type !== utils_1.AST_NODE_TYPES.JSXIdentifier ||
node.name.name !== "a")
return;
// Find the `href` attribute
const hrefAttr = node.attributes.find((attr) => attr.type === utils_1.AST_NODE_TYPES.JSXAttribute &&
attr.name.type === utils_1.AST_NODE_TYPES.JSXIdentifier &&
attr.name.name === "href");
if (!(hrefAttr === null || hrefAttr === void 0 ? void 0 : hrefAttr.value) ||
hrefAttr.value.type !== utils_1.AST_NODE_TYPES.JSXExpressionContainer)
return;
const expression = hrefAttr.value.expression;
if (expression.type !== utils_1.AST_NODE_TYPES.MemberExpression)
return;
const tsNode = parserServices.esTreeNodeToTSNodeMap.get(expression.object);
if (!tsNode) {
console.warn("⚠️ TypeScript Node not found.");
return;
}
const type = getType(tsNode, checker);
if (isFileField(type)) {
let fieldName = expression;
// Step back to remove ".value" if it exists
while (fieldName.type === utils_1.AST_NODE_TYPES.MemberExpression) {
if (fieldName.property.type === utils_1.AST_NODE_TYPES.Identifier &&
(fieldName.property.name === "value" ||
fieldName.property.name === "src")) {
fieldName = fieldName.object;
}
else {
break;
}
}
const fieldNameText = context.getSourceCode().getText(fieldName);
context.report({
node,
messageId: "useFileComponent",
data: { fieldName: fieldNameText },
fix(fixer) {
return fixer.replaceText(node.parent, `<File field={${fieldNameText}} />`);
},
});
}
},
};
},
};
//# sourceMappingURL=enforce-file-component.js.map