@projectwallace/css-analyzer 9.4.0 → 9.5.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,268 @@
1
+ import { n as unquote, r as KeywordSet } from "./string-utils-olNNcOlY.js";
2
+ import { ATTRIBUTE_SELECTOR, CLASS_SELECTOR, COMBINATOR, ID_SELECTOR, NTH_OF_SELECTOR, NTH_SELECTOR, PSEUDO_CLASS_SELECTOR, PSEUDO_ELEMENT_SELECTOR, SELECTOR, SELECTOR_LIST, SKIP, TYPE_SELECTOR, str_equals, str_starts_with, walk } from "@projectwallace/css-parser";
3
+ import { parse_selector } from "@projectwallace/css-parser/parse-selector";
4
+ //#region src/selectors/utils.ts
5
+ const PSEUDO_FUNCTIONS = new KeywordSet([
6
+ "nth-child",
7
+ "where",
8
+ "not",
9
+ "is",
10
+ "has",
11
+ "nth-last-child",
12
+ "matches",
13
+ "-webkit-any",
14
+ "-moz-any"
15
+ ]);
16
+ function isPrefixed(selector, on_selector) {
17
+ walk(selector, function(node) {
18
+ if (node.type === PSEUDO_ELEMENT_SELECTOR || node.type === PSEUDO_CLASS_SELECTOR || node.type === TYPE_SELECTOR) {
19
+ if (node.is_vendor_prefixed) {
20
+ let prefix = "";
21
+ if (node.type === PSEUDO_CLASS_SELECTOR) prefix = ":";
22
+ else if (node.type === PSEUDO_ELEMENT_SELECTOR) prefix = "::";
23
+ on_selector(prefix + (node.name || node.text));
24
+ }
25
+ }
26
+ });
27
+ }
28
+ /**
29
+ * Check if a Wallace selector is an accessibility selector (has aria-* or role attribute)
30
+ */
31
+ function isAccessibility(selector, on_selector) {
32
+ function normalize(node) {
33
+ let clone = node.clone();
34
+ if (clone.value) return "[" + clone.name?.toLowerCase() + clone.attr_operator + "\"" + unquote(clone.value.toString()) + "\"]";
35
+ return "[" + clone.name?.toLowerCase() + "]";
36
+ }
37
+ walk(selector, function(node) {
38
+ if (node.type === ATTRIBUTE_SELECTOR) {
39
+ const name = node.name || "";
40
+ if (str_equals("role", name) || str_starts_with(name, "aria-")) on_selector(normalize(node));
41
+ }
42
+ });
43
+ }
44
+ /**
45
+ * Get the Complexity for a Wallace Selector Node
46
+ * @param selector - Wallace CSSNode for a Selector
47
+ * @return The numeric complexity of the Selector
48
+ */
49
+ function getComplexity(selector) {
50
+ let complexity = 0;
51
+ function findSelectors(node, complexities) {
52
+ walk(node, function(n) {
53
+ if (n.type === SELECTOR) complexities.push(getComplexity(n));
54
+ });
55
+ }
56
+ walk(selector, function(node) {
57
+ const type = node.type;
58
+ if (type === SELECTOR) return;
59
+ if (type === NTH_SELECTOR) {
60
+ if (node.text && node.text.trim()) complexity++;
61
+ return;
62
+ }
63
+ complexity++;
64
+ if (type === PSEUDO_ELEMENT_SELECTOR || type === TYPE_SELECTOR || type === PSEUDO_CLASS_SELECTOR) {
65
+ if (node.is_vendor_prefixed) complexity++;
66
+ }
67
+ if (type === ATTRIBUTE_SELECTOR) {
68
+ if (node.value) complexity++;
69
+ return SKIP;
70
+ }
71
+ if (type === PSEUDO_CLASS_SELECTOR) {
72
+ const name = node.name || "";
73
+ if (PSEUDO_FUNCTIONS.has(name.toLowerCase())) {
74
+ const childComplexities = [];
75
+ if (node.has_children) for (const child of node) if (child.type === SELECTOR) childComplexities.push(getComplexity(child));
76
+ else findSelectors(child, childComplexities);
77
+ if (childComplexities.length > 0) {
78
+ for (const c of childComplexities) complexity += c;
79
+ return SKIP;
80
+ }
81
+ }
82
+ }
83
+ });
84
+ return complexity;
85
+ }
86
+ /**
87
+ * Walk a selector node and trigger a callback every time a Combinator was found
88
+ */
89
+ function getCombinators(selector, onMatch) {
90
+ walk(selector, function(node) {
91
+ if (node.type === COMBINATOR) onMatch({
92
+ name: node.name?.trim() === "" ? " " : node.name,
93
+ loc: {
94
+ offset: node.start,
95
+ line: node.line,
96
+ column: node.column,
97
+ length: 1
98
+ }
99
+ });
100
+ });
101
+ }
102
+ //#endregion
103
+ //#region src/selectors/specificity.ts
104
+ /**
105
+ * @returns 0 if s1 equals s2, a negative number if s1 is lower than s2, or a positive number if s1 higher than s2
106
+ */
107
+ function compare(s1, s2) {
108
+ if (s1[0] === s2[0]) {
109
+ if (s1[1] === s2[1]) return s1[2] - s2[2];
110
+ return s1[1] - s2[1];
111
+ }
112
+ return s1[0] - s2[0];
113
+ }
114
+ function max(list) {
115
+ return list.sort(compare).at(-1);
116
+ }
117
+ const calculateForAST = (selectorAST) => {
118
+ let a = 0;
119
+ let b = 0;
120
+ let c = 0;
121
+ let current = selectorAST.first_child;
122
+ while (current) {
123
+ switch (current.type) {
124
+ case ID_SELECTOR:
125
+ a += 1;
126
+ break;
127
+ case ATTRIBUTE_SELECTOR:
128
+ case CLASS_SELECTOR:
129
+ b += 1;
130
+ break;
131
+ case PSEUDO_CLASS_SELECTOR:
132
+ switch (current.name?.toLowerCase()) {
133
+ case "where": break;
134
+ case "-webkit-any":
135
+ case "any":
136
+ if (current.first_child) b += 1;
137
+ break;
138
+ case "-moz-any":
139
+ case "is":
140
+ case "matches":
141
+ case "not":
142
+ case "has":
143
+ if (current.has_children) {
144
+ const childSelectorList = current.first_child;
145
+ if (childSelectorList?.type === SELECTOR_LIST) {
146
+ const max1 = max(calculate(childSelectorList));
147
+ a += max1[0];
148
+ b += max1[1];
149
+ c += max1[2];
150
+ }
151
+ }
152
+ break;
153
+ case "nth-child":
154
+ case "nth-last-child":
155
+ b += 1;
156
+ const nthOf = current.first_child;
157
+ if (nthOf?.type === NTH_OF_SELECTOR && nthOf.selector) {
158
+ const max2 = max(calculate(nthOf.selector));
159
+ a += max2[0];
160
+ b += max2[1];
161
+ c += max2[2];
162
+ }
163
+ break;
164
+ case "host-context":
165
+ case "host":
166
+ b += 1;
167
+ const childSelector = current.first_child?.first_child;
168
+ if (childSelector?.type === SELECTOR) {
169
+ let childPart = childSelector.first_child;
170
+ while (childPart) {
171
+ if (childPart.type === COMBINATOR) break;
172
+ const partSpecificity = calculateForAST({
173
+ type_name: "Selector",
174
+ first_child: childPart,
175
+ has_children: true
176
+ });
177
+ a += partSpecificity[0] ?? 0;
178
+ b += partSpecificity[1] ?? 0;
179
+ c += partSpecificity[2] ?? 0;
180
+ childPart = childPart.next_sibling;
181
+ }
182
+ }
183
+ break;
184
+ case "after":
185
+ case "before":
186
+ case "first-letter":
187
+ case "first-line":
188
+ c += 1;
189
+ break;
190
+ default:
191
+ b += 1;
192
+ break;
193
+ }
194
+ break;
195
+ case PSEUDO_ELEMENT_SELECTOR:
196
+ switch (current.name?.toLowerCase()) {
197
+ case "slotted":
198
+ c += 1;
199
+ const childSelector = current.first_child?.first_child;
200
+ if (childSelector?.type === SELECTOR) {
201
+ let childPart = childSelector.first_child;
202
+ while (childPart) {
203
+ if (childPart.type === COMBINATOR) break;
204
+ const partSpecificity = calculateForAST({
205
+ type_name: "Selector",
206
+ first_child: childPart,
207
+ has_children: true
208
+ });
209
+ a += partSpecificity[0] ?? 0;
210
+ b += partSpecificity[1] ?? 0;
211
+ c += partSpecificity[2] ?? 0;
212
+ childPart = childPart.next_sibling;
213
+ }
214
+ }
215
+ break;
216
+ case "view-transition-group":
217
+ case "view-transition-image-pair":
218
+ case "view-transition-old":
219
+ case "view-transition-new":
220
+ if (current.first_child?.text === "*") break;
221
+ c += 1;
222
+ break;
223
+ default:
224
+ c += 1;
225
+ break;
226
+ }
227
+ break;
228
+ case TYPE_SELECTOR:
229
+ let typeSelector = current.name ?? "";
230
+ if (typeSelector.includes("|")) typeSelector = typeSelector.split("|")[1] ?? "";
231
+ if (typeSelector !== "*") c += 1;
232
+ break;
233
+ default: break;
234
+ }
235
+ current = current.next_sibling;
236
+ }
237
+ return [
238
+ a,
239
+ b,
240
+ c
241
+ ];
242
+ };
243
+ const convertToAST = (source) => {
244
+ if (typeof source === "string") try {
245
+ return parse_selector(source);
246
+ } catch (e) {
247
+ const message = e instanceof Error ? e.message : String(e);
248
+ throw new TypeError(`Could not convert passed in source '${source}' to SelectorList: ${message}`);
249
+ }
250
+ if (source instanceof Object) {
251
+ if (source.type === SELECTOR_LIST) return source;
252
+ throw new TypeError(`Passed in source is an Object but no AST / AST of the type SelectorList`);
253
+ }
254
+ throw new TypeError(`Passed in source is not a String nor an Object. I don't know what to do with it.`);
255
+ };
256
+ const calculate = (selector) => {
257
+ if (!selector) return [];
258
+ const ast = convertToAST(selector);
259
+ const specificities = [];
260
+ let selectorNode = ast.first_child;
261
+ while (selectorNode) {
262
+ specificities.push(calculateForAST(selectorNode));
263
+ selectorNode = selectorNode.next_sibling;
264
+ }
265
+ return specificities;
266
+ };
267
+ //#endregion
268
+ export { getComplexity as a, getCombinators as i, calculateForAST as n, isAccessibility as o, compare as r, isPrefixed as s, calculate as t };
@@ -0,0 +1,49 @@
1
+ import "@projectwallace/css-parser";
2
+ //#region src/keyword-set.ts
3
+ /**
4
+ * @description A Set-like construct to search CSS keywords in a case-insensitive way
5
+ */
6
+ var KeywordSet = class {
7
+ set;
8
+ constructor(items) {
9
+ /** @type {Set<string>} */
10
+ this.set = new Set(items);
11
+ }
12
+ has(item) {
13
+ return this.set.has(item.toLowerCase());
14
+ }
15
+ };
16
+ //#endregion
17
+ //#region src/string-utils.ts
18
+ function unquote(str) {
19
+ return str.replaceAll(/(?:^['"])|(?:['"]$)/g, "");
20
+ }
21
+ /**
22
+ * Case-insensitive compare two character codes
23
+ * @see https://github.com/csstree/csstree/blob/41f276e8862d8223eeaa01a3d113ab70bb13d2d9/lib/tokenizer/utils.js#L22
24
+ */
25
+ function compareChar(referenceCode, testCode) {
26
+ if (testCode >= 65 && testCode <= 90) testCode = testCode | 32;
27
+ return referenceCode === testCode;
28
+ }
29
+ /**
30
+ * Case-insensitive testing whether a string ends with a given substring
31
+ *
32
+ * @example
33
+ * endsWith('test', 'my-test') // true
34
+ * endsWith('test', 'est') // false
35
+ *
36
+ * @param base e.g. '-webkit-transform'
37
+ * @param maybe e.g. 'transform'
38
+ * @returns true if `test` ends with `base`, false otherwise
39
+ */
40
+ function endsWith(base, maybe) {
41
+ if (base === maybe) return true;
42
+ let len = maybe.length;
43
+ let offset = len - base.length;
44
+ if (offset < 0) return false;
45
+ for (let i = len - 1; i >= offset; i--) if (compareChar(base.charCodeAt(i - offset), maybe.charCodeAt(i)) === false) return false;
46
+ return true;
47
+ }
48
+ //#endregion
49
+ export { unquote as n, KeywordSet as r, endsWith as t };
@@ -0,0 +1,54 @@
1
+ import { CSSNode } from "@projectwallace/css-parser";
2
+
3
+ //#region src/collection.d.ts
4
+ type Location = {
5
+ line: number;
6
+ column: number;
7
+ offset: number;
8
+ length: number;
9
+ };
10
+ type UniqueWithLocations = Record<string, Location[]>;
11
+ type CollectionCount<WithLocations extends boolean = false> = {
12
+ total: number;
13
+ totalUnique: number;
14
+ unique: Record<string, number>;
15
+ uniquenessRatio: number;
16
+ } & (WithLocations extends true ? {
17
+ uniqueWithLocations: UniqueWithLocations;
18
+ } : {
19
+ uniqueWithLocations?: undefined;
20
+ });
21
+ //#endregion
22
+ //#region src/selectors/specificity.d.ts
23
+ type Specificity = [number, number, number];
24
+ /**
25
+ * @returns 0 if s1 equals s2, a negative number if s1 is lower than s2, or a positive number if s1 higher than s2
26
+ */
27
+ declare function compare(s1: Specificity, s2: Specificity): number;
28
+ declare const calculateForAST: (selectorAST: CSSNode) => Specificity;
29
+ declare const calculate: (selector: string | CSSNode) => Specificity[];
30
+ //#endregion
31
+ //#region src/selectors/utils.d.ts
32
+ declare function isPrefixed(selector: CSSNode, on_selector: (prefix: string) => void): void;
33
+ /**
34
+ * Check if a Wallace selector is an accessibility selector (has aria-* or role attribute)
35
+ */
36
+ declare function isAccessibility(selector: CSSNode, on_selector: (a11y_selector: string) => void): void;
37
+ /**
38
+ * Get the Complexity for a Wallace Selector Node
39
+ * @param selector - Wallace CSSNode for a Selector
40
+ * @return The numeric complexity of the Selector
41
+ */
42
+ declare function getComplexity(selector: CSSNode): number;
43
+ /**
44
+ * Walk a selector node and trigger a callback every time a Combinator was found
45
+ */
46
+ declare function getCombinators(selector: CSSNode, onMatch: ({
47
+ name,
48
+ loc
49
+ }: {
50
+ name: string;
51
+ loc: Location;
52
+ }) => void): void;
53
+ //#endregion
54
+ export { calculate as a, CollectionCount as c, isPrefixed as i, Location as l, getComplexity as n, calculateForAST as o, isAccessibility as r, compare as s, getCombinators as t, UniqueWithLocations as u };
@@ -0,0 +1,7 @@
1
+ import { a as namedColors, i as colorKeywords, n as keywords, o as systemColors, r as colorFunctions, t as isValueReset } from "../values-Dw53soqy.js";
2
+ import { CSSNode } from "@projectwallace/css-parser";
3
+
4
+ //#region src/values/browserhacks.d.ts
5
+ declare function isIe9Hack(node: CSSNode): boolean;
6
+ //#endregion
7
+ export { colorFunctions, colorKeywords, isIe9Hack, isValueReset, keywords, namedColors, systemColors };
@@ -0,0 +1,3 @@
1
+ import "../string-utils-olNNcOlY.js";
2
+ import { a as colorKeywords, i as colorFunctions, n as isValueReset, o as namedColors, r as keywords, s as systemColors, t as isIe9Hack } from "../browserhacks-eP_e1D5u.js";
3
+ export { colorFunctions, colorKeywords, isIe9Hack, isValueReset, keywords, namedColors, systemColors };
@@ -0,0 +1,26 @@
1
+ import { CSSNode } from "@projectwallace/css-parser";
2
+
3
+ //#region src/keyword-set.d.ts
4
+ /**
5
+ * @description A Set-like construct to search CSS keywords in a case-insensitive way
6
+ */
7
+ declare class KeywordSet {
8
+ set: Set<string>;
9
+ constructor(items: Lowercase<string>[]);
10
+ has(item: string): boolean;
11
+ }
12
+ //#endregion
13
+ //#region src/values/colors.d.ts
14
+ declare const namedColors: KeywordSet;
15
+ declare const systemColors: KeywordSet;
16
+ declare const colorFunctions: KeywordSet;
17
+ declare const colorKeywords: KeywordSet;
18
+ //#endregion
19
+ //#region src/values/values.d.ts
20
+ declare const keywords: KeywordSet;
21
+ /**
22
+ * Test whether a value is a reset (0, 0px, -0.0e0 etc.)
23
+ */
24
+ declare function isValueReset(node: CSSNode): boolean;
25
+ //#endregion
26
+ export { namedColors as a, colorKeywords as i, keywords as n, systemColors as o, colorFunctions as r, KeywordSet as s, isValueReset as t };
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "@projectwallace/css-analyzer",
3
3
  "description": "The best CSS analyzer out there. Check design tokens, complexity, specificity, performance and more.",
4
- "version": "9.4.0",
4
+ "version": "9.5.0",
5
5
  "author": "Bart Veneman",
6
6
  "repository": {
7
7
  "type": "git",
@@ -17,8 +17,22 @@
17
17
  "main": "./dist/index.js",
18
18
  "types": "./dist/index.d.ts",
19
19
  "exports": {
20
- "types": "./dist/index.d.ts",
21
- "default": "./dist/index.js"
20
+ ".": {
21
+ "types": "./dist/index.d.ts",
22
+ "default": "./dist/index.js"
23
+ },
24
+ "./selectors": {
25
+ "types": "./dist/selectors/index.d.ts",
26
+ "default": "./dist/selectors/index.js"
27
+ },
28
+ "./atrules": {
29
+ "types": "./dist/atrules/index.d.ts",
30
+ "default": "./dist/atrules/index.js"
31
+ },
32
+ "./values": {
33
+ "types": "./dist/values/index.d.ts",
34
+ "default": "./dist/values/index.js"
35
+ }
22
36
  },
23
37
  "engines": {
24
38
  "node": ">=18.0.0"
@@ -54,7 +68,7 @@
54
68
  "devDependencies": {
55
69
  "@codecov/rollup-plugin": "^1.9.1",
56
70
  "@vitest/coverage-v8": "^4.0.18",
57
- "knip": "^5.83.1",
71
+ "knip": "^6.0.4",
58
72
  "oxlint": "^1.43.0",
59
73
  "prettier": "^3.6.2",
60
74
  "publint": "^0.3.17",