index.js 1.8 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374
  1. 'use strict';
  2. const mediaParser = require('postcss-media-query-parser').default;
  3. const report = require('../../utils/report');
  4. const ruleMessages = require('../../utils/ruleMessages');
  5. const validateOptions = require('../../utils/validateOptions');
  6. const valueParser = require('postcss-value-parser');
  7. const ruleName = 'no-duplicate-at-import-rules';
  8. const messages = ruleMessages(ruleName, {
  9. rejected: (atImport) => `Unexpected duplicate @import rule ${atImport}`,
  10. });
  11. const meta = {
  12. url: 'https://stylelint.io/user-guide/rules/list/no-duplicate-at-import-rules',
  13. };
  14. /** @type {import('stylelint').Rule} */
  15. const rule = (primary) => {
  16. return (root, result) => {
  17. const validOptions = validateOptions(result, ruleName, { actual: primary });
  18. if (!validOptions) {
  19. return;
  20. }
  21. /** @type {Record<string, string[]>} */
  22. const imports = {};
  23. root.walkAtRules(/^import$/i, (atRule) => {
  24. const [firstParam, ...restParams] = valueParser(atRule.params).nodes;
  25. if (!firstParam) {
  26. return;
  27. }
  28. // extract uri from url() if exists
  29. const uri =
  30. firstParam.type === 'function' && firstParam.value === 'url'
  31. ? firstParam.nodes[0].value
  32. : firstParam.value;
  33. // extract media queries if any
  34. const media = (mediaParser(valueParser.stringify(restParams)).nodes || [])
  35. .map((n) => n.value.replace(/\s/g, ''))
  36. .filter((n) => n.length);
  37. const isDuplicate = media.length
  38. ? imports[uri] && media.some((q) => imports[uri].includes(q))
  39. : imports[uri];
  40. if (isDuplicate) {
  41. report({
  42. message: messages.rejected(uri),
  43. node: atRule,
  44. result,
  45. ruleName,
  46. });
  47. return;
  48. }
  49. if (!imports[uri]) imports[uri] = [];
  50. imports[uri] = imports[uri].concat(media);
  51. });
  52. };
  53. };
  54. rule.ruleName = ruleName;
  55. rule.messages = messages;
  56. rule.meta = meta;
  57. module.exports = rule;