UNPKG

tslint-etc

Version:
55 lines (54 loc) 2.05 kB
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.Rule = void 0; const Lint = require("tslint"); class Rule extends Lint.Rules.AbstractRule { apply(sourceFile) { return this.applyWithWalker(new Walker(sourceFile, this.getOptions())); } } exports.Rule = Rule; Rule.metadata = { description: "Disallows the use of banned imports.", options: { type: "object", }, optionsDescription: Lint.Utils.dedent ` An object containing keys that are regular expressions and values that are either booleans or strings containing the explanation for the ban.`, requiresTypeInfo: false, ruleName: "ban-imports", type: "functionality", typescriptOnly: false, }; Rule.FAILURE_STRING = "Import is banned"; class Walker extends Lint.RuleWalker { constructor(sourceFile, rawOptions) { super(sourceFile, rawOptions); this._bans = []; const [options] = this.getOptions(); if (options) { Object.entries(options).forEach(([key, value]) => { if (value !== false) { this._bans.push({ explanation: typeof value === "string" ? value : "", regExp: new RegExp(key), }); } }); } } visitImportDeclaration(node) { const { _bans } = this; const moduleSpecifier = node.moduleSpecifier.getText().replace(/['"]/g, ""); for (let b = 0, length = _bans.length; b < length; ++b) { const ban = _bans[b]; if (ban.regExp.test(moduleSpecifier)) { const explanation = ban.explanation ? `: ${ban.explanation}` : ""; const failure = `${Rule.FAILURE_STRING}: '${moduleSpecifier}' matches ${ban.regExp.toString()}${explanation}`; this.addFailureAtNode(node.moduleSpecifier, failure); } } super.visitImportDeclaration(node); } }