eslint-plugin-kisszaya-fsd-plugin
Version:
Plugin to format code by fsd principles
89 lines (88 loc) • 3.6 kB
JavaScript
;
Object.defineProperty(exports, "__esModule", { value: true });
exports.layerImports = exports.MessageIds = void 0;
const utils_1 = require("@typescript-eslint/utils");
const schema_1 = require("./schema");
const helpers_1 = require("./helpers");
var MessageIds;
(function (MessageIds) {
MessageIds["ISSUE_LAYER_IMPORTS"] = "issue:layer-imports";
})(MessageIds || (exports.MessageIds = MessageIds = {}));
const createRule = utils_1.ESLintUtils.RuleCreator((name) => `https://example.com/rule/${name}`);
exports.layerImports = createRule({
name: "layer-imports",
meta: {
docs: {
description: "Modules on one layer can only interact with modules from the layers strictly below",
},
type: "problem",
messages: {
[MessageIds.ISSUE_LAYER_IMPORTS]: "Modules on one layer can only interact with modules from the layers strictly below",
},
schema: schema_1.SCHEMA,
},
defaultOptions: [],
create: (context) => {
const alias = context.options[0].alias || "";
const projectStructure = context.options[0].projectStructure;
const srcPath = context.options[0].srcPath || schema_1.ALIAS_START_PATH;
return {
ImportDeclaration(node) {
const importPath = node.source.value;
const filename = context.physicalFilename;
const normalizedFilename = (0, helpers_1.normalizePath)(filename);
if (!normalizedFilename.includes(srcPath)) {
return;
}
const checker = new LayerImportsChecker(alias, projectStructure, srcPath);
const isAbsolutePath = (0, helpers_1.isAbsolute)({
importPath,
alias,
projectStructure,
});
if (!isAbsolutePath) {
return;
}
if (checker.isLayerImportsViolated({ importPath, filename })) {
return context.report({
node,
messageId: MessageIds.ISSUE_LAYER_IMPORTS,
});
}
},
};
},
});
class LayerImportsChecker {
constructor(alias, projectStructure, srcPath) {
this.alias = alias;
this.srcPath = srcPath;
this.projectStructure = projectStructure;
}
isLayerImportsViolated({ importPath, filename, }) {
const importPathElems = (0, helpers_1.getAbsoluteImportPathElems)({
importPath,
alias: this.alias,
});
const filenameElems = (0, helpers_1.getFilenameElems)({ filename, srcPath: this.srcPath });
const importPathLayer = importPathElems[0];
const filenameLayer = filenameElems[0];
if (!importPathLayer ||
!filenameLayer ||
!(0, helpers_1.isLayer)({
path: importPathLayer,
projectStructure: this.projectStructure,
}) ||
!(0, helpers_1.isLayer)({ path: filenameLayer, projectStructure: this.projectStructure })) {
return false;
}
const layerKeys = Object.keys(this.projectStructure);
const importPathLayerIndex = layerKeys.findIndex((layer) => importPathLayer === layer);
const filenameLayerIndex = layerKeys.findIndex((layer) => filenameLayer === layer);
const isRuleViolated = importPathLayerIndex < filenameLayerIndex;
if (isRuleViolated) {
return true;
}
return false;
}
}