UNPKG

@dnb/eufemia

Version:

DNB Eufemia Design System UI Library

85 lines (84 loc) 2.65 kB
"use strict"; var _push = _interopRequireDefault(require("core-js-pure/stable/instance/push.js")); function _interopRequireDefault(e) { return e && e.__esModule ? e : { default: e }; } const stylelint = require('stylelint'); const RULE_NAME = 'eufemia/no-unused-use'; const messages = stylelint.utils.ruleMessages(RULE_NAME, { unusedUse: (namespace, path) => `Unexpected unused @use "${path}" with namespace "${namespace}". Either use the namespace or remove the @use statement.` }); const meta = { url: 'https://github.com/dnbexperience/eufemia' }; const getExplicitNamespace = params => { const match = params.match(/^(['"]).*?\1\s+as\s+(\S+)\s*;?\s*$/); if (!match) { return null; } const namespace = match[2].replace(/;$/, ''); if (namespace === '*') { return null; } return namespace; }; const getModulePath = params => { const match = params.match(/^(['"])(.*?)\1/); return match ? match[2] : params; }; const isNamespaceUsed = (root, namespace) => { const pattern = `${namespace}.`; let found = false; root.walk(node => { if (found) { return; } const textToSearch = []; if (node.type === 'decl') { (0, _push.default)(textToSearch).call(textToSearch, node.prop, node.value); } else if (node.type === 'atrule') { if (node.name !== 'use' && node.name !== 'forward') { (0, _push.default)(textToSearch).call(textToSearch, node.params); } } else if (node.type === 'rule') { (0, _push.default)(textToSearch).call(textToSearch, node.selector); } for (const text of textToSearch) { if (text && text.includes(pattern)) { found = true; return; } } }); return found; }; const ruleFunction = primary => { return (root, result) => { const validOptions = stylelint.utils.validateOptions(result, RULE_NAME, { actual: primary }); if (!validOptions) { return; } root.walkAtRules('use', atRule => { const namespace = getExplicitNamespace(atRule.params); if (!namespace) { return; } if (!isNamespaceUsed(root, namespace)) { const modulePath = getModulePath(atRule.params); stylelint.utils.report({ message: messages.unusedUse(namespace, modulePath), node: atRule, result, ruleName: RULE_NAME }); } }); }; }; ruleFunction.ruleName = RULE_NAME; ruleFunction.messages = messages; ruleFunction.meta = meta; module.exports = stylelint.createPlugin(RULE_NAME, ruleFunction); module.exports.ruleName = RULE_NAME; module.exports.messages = messages; //# sourceMappingURL=no-unused-use.js.map