/
index.js
95 lines (75 loc) · 2.34 KB
/
index.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
'use strict';
const valueParser = require('postcss-value-parser');
const isCustomProperty = require('../../utils/isCustomProperty');
const report = require('../../utils/report');
const ruleMessages = require('../../utils/ruleMessages');
const validateOptions = require('../../utils/validateOptions');
const declarationValueIndex = require('../../utils/declarationValueIndex');
const { isRegExp, isString } = require('../../utils/validateTypes');
const { isValueFunction } = require('../../utils/typeGuards');
const isStandardSyntaxProperty = require('../../utils/isStandardSyntaxProperty');
const ruleName = 'custom-property-pattern';
const messages = ruleMessages(ruleName, {
expected: (propName, pattern) => `Expected "${propName}" to match pattern "${pattern}"`,
});
const meta = {
url: 'https://stylelint.io/user-guide/rules/custom-property-pattern',
};
/** @type {import('stylelint').Rule} */
const rule = (primary) => {
return (root, result) => {
const validOptions = validateOptions(result, ruleName, {
actual: primary,
possible: [isRegExp, isString],
});
if (!validOptions) {
return;
}
const regexpPattern = isString(primary) ? new RegExp(primary) : primary;
/**
* @param {string} property
* @returns {boolean}
*/
function check(property) {
return (
!isStandardSyntaxProperty(property) ||
!isCustomProperty(property) ||
regexpPattern.test(property.slice(2))
);
}
root.walkDecls((decl) => {
const { prop, value } = decl;
const parsedValue = valueParser(value);
parsedValue.walk((node) => {
if (!isValueFunction(node)) return;
if (node.value.toLowerCase() !== 'var') return;
const { nodes } = node;
const firstNode = nodes[0];
if (!firstNode || check(firstNode.value)) return;
complain(declarationValueIndex(decl) + firstNode.sourceIndex, firstNode.value, decl);
});
if (check(prop)) return;
complain(0, prop, decl);
});
/**
* @param {number} index
* @param {string} propName
* @param {import('postcss').Declaration} decl
*/
function complain(index, propName, decl) {
report({
result,
ruleName,
message: messages.expected,
messageArgs: [propName, primary],
node: decl,
index,
endIndex: index + propName.length,
});
}
};
};
rule.ruleName = ruleName;
rule.messages = messages;
rule.meta = meta;
module.exports = rule;