@dcaldeira/tooling 0.1.0 → 0.2.1

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.
Files changed (49) hide show
  1. package/README.md +34 -34
  2. package/checks/a11y.mjs +206 -206
  3. package/checks/architecture.mjs +137 -137
  4. package/checks/audit.mjs +121 -121
  5. package/checks/bundle.mjs +128 -126
  6. package/checks/dependencies.mjs +277 -277
  7. package/checks/duplication.mjs +135 -0
  8. package/checks/lint-scss.mjs +363 -349
  9. package/checks/package.mjs +30 -30
  10. package/checks/playwright-summary.mjs +53 -53
  11. package/checks/sass.mjs +67 -67
  12. package/checks/scan-secrets.mjs +58 -58
  13. package/checks/shared.mjs +86 -86
  14. package/checks/translations.mjs +55 -55
  15. package/checks/visual-compare.mjs +148 -148
  16. package/checks/visual-report-html.mjs +470 -470
  17. package/checks/visual-report.mjs +13 -13
  18. package/config.schema.json +999 -927
  19. package/configs/eslint.mjs +27 -27
  20. package/configs/knip.json +11 -11
  21. package/configs/playwright.mjs +15 -15
  22. package/configs/vitest.mjs +16 -16
  23. package/package.json +105 -105
  24. package/release/finalize.mjs +65 -65
  25. package/release/github.mjs +64 -64
  26. package/release/prepare.mjs +30 -30
  27. package/runner/browsers.mjs +73 -73
  28. package/runner/cache.mjs +121 -121
  29. package/runner/ci-plan.mjs +54 -54
  30. package/runner/cli.mjs +250 -248
  31. package/runner/config.mjs +148 -148
  32. package/runner/docs-install.mjs +93 -93
  33. package/runner/execute.mjs +298 -286
  34. package/runner/generate.mjs +122 -122
  35. package/runner/git.mjs +122 -122
  36. package/runner/graph.mjs +250 -243
  37. package/runner/insights.mjs +313 -313
  38. package/runner/provision.mjs +53 -53
  39. package/runner/repo-standard.mjs +104 -0
  40. package/runner/report.mjs +35 -35
  41. package/runner/serve-static.mjs +76 -76
  42. package/runner/setup.mjs +241 -237
  43. package/runner/summary.mjs +112 -112
  44. package/runner/watch.mjs +82 -82
  45. package/templates/ci.yml +25 -25
  46. package/templates/dependabot-merge.yml +13 -13
  47. package/templates/dependabot.yml +26 -26
  48. package/templates/pre-push +13 -13
  49. package/templates/release.yml +23 -23
@@ -1,349 +1,363 @@
1
- #!/usr/bin/env node
2
- import { readdirSync, readFileSync, writeFileSync } from 'node:fs';
3
- import { basename, join, relative } from 'node:path';
4
- import { loadConfig, inside } from '../runner/config.mjs';
5
- import { matches } from '../runner/graph.mjs';
6
- import scss from 'postcss-scss';
7
-
8
- const repo = process.env.TOOLING_ROOT ?? process.cwd();
9
- const { config } = loadConfig(repo);
10
- const options = config.styles ?? {};
11
- const ORDER = JSON.parse(
12
- readFileSync(new URL('./style-property-order.json', import.meta.url), 'utf8'),
13
- );
14
- const RANK = new Map(ORDER.map((name, index) => [name, index]));
15
-
16
- const BEM =
17
- /^[a-z][a-z0-9]*(-[a-z0-9]+)*(__[a-z][a-z0-9]*(-[a-z0-9]+)*)?(--[a-z][a-z0-9]*(-[a-z0-9]+)*)?$/;
18
- const rookie = options.preset === 'rookie';
19
- const rules = { bem: rookie, componentName: rookie, palette: rookie, ...options.rules };
20
- const COLOUR_FREE = /[/\\](_palette|themes)[/\\]/;
21
- const MAX_DEPTH = options.maxDepth ?? 3;
22
- const CONTROL = new Set(['for', 'each', 'while', 'if', 'else']);
23
- const MAX_SPECIFICITY = options.maxSpecificity ?? [0, 4, 2];
24
- const LENGTH_UNITS = 'px|em|rem|ex|ch|vw|vh|vmin|vmax|cm|mm|in|pt|pc|q';
25
- const NAMED_COLOURS = new Set(
26
- 'aliceblue antiquewhite aqua aquamarine azure beige bisque black blanchedalmond blue blueviolet brown burlywood cadetblue chartreuse chocolate coral cornflowerblue cornsilk crimson cyan darkblue darkcyan darkgoldenrod darkgray darkgreen darkgrey darkkhaki darkmagenta darkolivegreen darkorange darkorchid darkred darksalmon darkseagreen darkslateblue darkslategray darkslategrey darkturquoise darkviolet deeppink deepskyblue dimgray dimgrey dodgerblue firebrick floralwhite forestgreen fuchsia gainsboro ghostwhite gold goldenrod gray green greenyellow grey honeydew hotpink indianred indigo ivory khaki lavender lavenderblush lawngreen lemonchiffon lightblue lightcoral lightcyan lightgoldenrodyellow lightgray lightgreen lightgrey lightpink lightsalmon lightseagreen lightskyblue lightslategray lightslategrey lightsteelblue lightyellow lime limegreen linen magenta maroon mediumaquamarine mediumblue mediumorchid mediumpurple mediumseagreen mediumslateblue mediumspringgreen mediumturquoise mediumvioletred midnightblue mintcream mistyrose moccasin navajowhite navy oldlace olive olivedrab orange orangered orchid palegoldenrod palegreen paleturquoise palevioletred papayawhip peachpuff peru pink plum powderblue purple rebeccapurple red rosybrown royalblue saddlebrown salmon sandybrown seagreen seashell sienna silver skyblue slateblue slategray slategrey snow springgreen steelblue tan teal thistle tomato turquoise violet wheat white whitesmoke yellow yellowgreen'.split(
27
- ' ',
28
- ),
29
- );
30
- const COLOUR_PROPS =
31
- /^(color|background(-color|-image)?|border(-[a-z]+)*-color|border(-top|-right|-bottom|-left)?|outline(-color)?|fill|stroke|box-shadow|text-shadow|caret-color|accent-color|text-decoration(-color)?|column-rule(-color)?)$/;
32
-
33
- const files = (dir) =>
34
- readdirSync(dir, { withFileTypes: true }).flatMap((entry) => {
35
- const path = join(dir, entry.name);
36
- if (entry.isDirectory()) return files(path);
37
- return entry.isFile() && path.endsWith('.scss') ? [path] : [];
38
- });
39
-
40
- const stripValue = (value) =>
41
- value
42
- .replace(/\/\*[\s\S]*?\*\//g, '')
43
- .replace(/(['"])(?:\\.|(?!\1).)*\1/g, '""')
44
- .replace(/#\{[^}]*\}/g, 'x');
45
-
46
- const unprefixed = (prop) => prop.replace(/^-(webkit|moz|ms|o)-/, '');
47
-
48
- const specificity = (selector) => {
49
- const s = [0, 0, 0];
50
- const clean = selector.replace(/\[[^\]]*\]/g, () => {
51
- s[1] += 1;
52
- return '';
53
- });
54
- for (const match of clean.matchAll(
55
- /(#[\w-]+)|(\.[\w-]+)|(::?[\w-]+)(\([^)]*\))?|([a-zA-Z][\w-]*)/g,
56
- )) {
57
- if (match[1]) s[0] += 1;
58
- else if (match[2]) s[1] += 1;
59
- else if (match[3]) {
60
- const name = match[3].replace(/^:+/, '');
61
- if (
62
- match[3].startsWith('::') ||
63
- ['before', 'after', 'first-line', 'first-letter'].includes(name)
64
- )
65
- s[2] += 1;
66
- else if (name === 'where' || name === 'global') continue;
67
- else if (['is', 'not', 'has'].includes(name)) {
68
- const inner = (match[4] ?? '').slice(1, -1).split(',').map(specificity);
69
- const top = inner.sort((a, b) => b[0] - a[0] || b[1] - a[1] || b[2] - a[2])[0] ?? [0, 0, 0];
70
- s[0] += top[0];
71
- s[1] += top[1];
72
- s[2] += top[2];
73
- } else s[1] += 1;
74
- } else if (match[5]) s[2] += 1;
75
- }
76
- return s;
77
- };
78
- const tooSpecific = (s) =>
79
- s[0] > MAX_SPECIFICITY[0] ||
80
- (s[0] === MAX_SPECIFICITY[0] &&
81
- (s[1] > MAX_SPECIFICITY[1] || (s[1] === MAX_SPECIFICITY[1] && s[2] > MAX_SPECIFICITY[2])));
82
-
83
- const splitList = (selector) => {
84
- const out = [];
85
- let depth = 0;
86
- let start = 0;
87
- for (let i = 0; i < selector.length; i += 1) {
88
- const c = selector[i];
89
- if (c === '(' || c === '[') depth += 1;
90
- else if (c === ')' || c === ']') depth -= 1;
91
- else if (c === ',' && depth === 0) {
92
- out.push(selector.slice(start, i).trim());
93
- start = i + 1;
94
- }
95
- }
96
- out.push(selector.slice(start).trim());
97
- return out.filter(Boolean);
98
- };
99
-
100
- const resolve = (selector, parents) =>
101
- parents.length === 0
102
- ? splitList(selector)
103
- : splitList(selector).flatMap((child) =>
104
- parents.map((parent) =>
105
- child.includes('&') ? child.replaceAll('&', parent) : `${parent} ${child}`,
106
- ),
107
- );
108
-
109
- /* An at-rule straight under the root (a mixin, a media query) and Sass control flow are not levels. */
110
- const nestingDepth = (node, level = 0) => {
111
- const parent = node.parent;
112
- if (!parent || parent.type === 'root') return level;
113
- if (parent.type === 'atrule' && parent.parent?.type === 'root') return level;
114
- if (parent.type === 'atrule' && CONTROL.has(parent.name)) return nestingDepth(parent, level);
115
- return nestingDepth(parent, level + 1);
116
- };
117
-
118
- const line = (node) => node.source?.start?.line ?? 0;
119
- const endLine = (node) => node.source?.end?.line ?? line(node);
120
- const blankBefore = (node) => /\n[ \t\r]*\n/.test(node.raws.before ?? '');
121
-
122
- const lintFile = (file, fix) => {
123
- const source = readFileSync(file, 'utf8');
124
- const problems = [];
125
- const root = scss.parse(source, { from: file });
126
- const colourFree =
127
- !rules.palette ||
128
- COLOUR_FREE.test(file) ||
129
- (options.colourTokenPaths ?? []).some((pattern) => matches(relative(repo, file), pattern));
130
- const moduleBlock =
131
- rules.componentName && /\.module\.scss$/.test(file)
132
- ? basename(file, '.module.scss')
133
- .replace(/(?<!^)(?=[A-Z])/g, '-')
134
- .toLowerCase()
135
- : null;
136
- const disabled = new Map();
137
- root.walkComments((c) => {
138
- const m = /lint-scss-disable-next-line\s+([\w-]+)/.exec(c.text);
139
- if (m) disabled.set(`${endLine(c) + 1}:${m[1]}`, true);
140
- });
141
- const report = (node, rule, message) => {
142
- if (disabled.has(`${line(node)}:${rule}`)) return;
143
- problems.push({ line: line(node), rule, message });
144
- };
145
-
146
- const visit = (parent, selectors, depth) => {
147
- const kids = parent.nodes ?? [];
148
- kids.forEach((node, index) => {
149
- const prev = kids[index - 1];
150
- const first = index === 0;
151
- const nested = parent.type !== 'root';
152
-
153
- if (node.type === 'comment') {
154
- const sameLine = prev && endLine(prev) === line(node);
155
- const afterComment = prev?.type === 'comment';
156
- if (
157
- !sameLine &&
158
- !afterComment &&
159
- !first &&
160
- !blankBefore(node) &&
161
- !/lint-scss|stylelint/.test(node.text)
162
- )
163
- report(node, 'comment-empty-line-before', 'Expected an empty line before the comment');
164
- if (!sameLine && first && nested && blankBefore(node))
165
- report(
166
- node,
167
- 'comment-empty-line-before',
168
- 'Unexpected empty line before the first comment',
169
- );
170
- }
171
-
172
- if (
173
- node.type === 'rule' &&
174
- parent.name !== 'keyframes' &&
175
- !/keyframes$/.test(parent.name ?? '')
176
- ) {
177
- const own = resolve(node.selector, selectors);
178
- const multi = endLine(node) > line(node);
179
- const afterComment = prev?.type === 'comment';
180
- if (first && nested && blankBefore(node))
181
- report(node, 'rule-empty-line-before', 'Unexpected empty line before the first rule');
182
- else if (!first && multi && !afterComment && !blankBefore(node))
183
- report(node, 'rule-empty-line-before', 'Expected an empty line before the rule');
184
- if (nestingDepth(node) > MAX_DEPTH)
185
- report(node, 'max-nesting-depth', `Nesting deeper than ${MAX_DEPTH} levels`);
186
- if (!node.nodes?.length) report(node, 'block-no-empty', 'Empty block');
187
- for (const sel of own) {
188
- if (!sel.includes('#{') && !sel.includes('%')) {
189
- const bare = sel.replace(/:global\([^)]*\)/g, '').replace(/\[[^\]]*\]/g, '');
190
- for (const m of bare.matchAll(/\.(-?[\w-]+)/g))
191
- if (rules.bem && !BEM.test(m[1]))
192
- report(
193
- node,
194
- 'selector-class-pattern',
195
- `Use BEM: .block, .block__element, .block--modifier, in kebab-case: .${m[1]}`,
196
- );
197
- for (const m of bare.matchAll(/\.([a-z][a-z0-9]*(?:-[a-z0-9]+)*)(?:__|--|(?![\w-]))/g))
198
- if (moduleBlock && m[1] !== moduleBlock)
199
- report(
200
- node,
201
- 'block-name-matches-component',
202
- `The block is named after the component: .${moduleBlock}, not .${m[1]}`,
203
- );
204
- }
205
- if (!sel.includes('#{') && tooSpecific(specificity(sel)))
206
- report(
207
- node,
208
- 'selector-max-specificity',
209
- `Specificity of "${sel}" is above ${MAX_SPECIFICITY.join(',')}`,
210
- );
211
- }
212
- visit(node, own, depth + 1);
213
- return;
214
- }
215
-
216
- if (node.type === 'atrule') {
217
- const blockless = !node.nodes;
218
- const afterComment = prev?.type === 'comment';
219
- const prevBlockless = prev?.type === 'atrule' && !prev.nodes;
220
- if (node.name !== 'else') {
221
- if (first && nested && blankBefore(node))
222
- report(node, 'at-rule-empty-line-before', `Unexpected empty line before @${node.name}`);
223
- else if (!first && !afterComment) {
224
- if (blockless && prevBlockless && blankBefore(node))
225
- report(
226
- node,
227
- 'at-rule-empty-line-before',
228
- `Unexpected empty line before @${node.name}`,
229
- );
230
- else if (!(blockless && prevBlockless) && !blankBefore(node))
231
- report(
232
- node,
233
- 'at-rule-empty-line-before',
234
- `Expected an empty line before @${node.name}`,
235
- );
236
- }
237
- }
238
- if (node.nodes) {
239
- if (nestingDepth(node) > MAX_DEPTH && node.name !== 'keyframes')
240
- report(node, 'max-nesting-depth', `Nesting deeper than ${MAX_DEPTH} levels`);
241
- if (!node.nodes.length) report(node, 'block-no-empty', 'Empty block');
242
- visit(node, selectors, node.name === 'keyframes' ? depth : depth + 1);
243
- }
244
- return;
245
- }
246
-
247
- if (node.type === 'decl') {
248
- const value = stripValue(node.value);
249
- if (!colourFree) {
250
- if (
251
- /#[0-9a-fA-F]{3,8}\b/.test(value) &&
252
- !node.prop.startsWith('$') &&
253
- !node.prop.startsWith('--')
254
- )
255
- report(node, 'color-no-hex', 'Raw hex colour: use a palette token');
256
- if (/\b(rgba?|hsla?)\(/i.test(value))
257
- report(node, 'function-disallowed-list', 'Use a palette token, not rgb()/hsl()');
258
- if (COLOUR_PROPS.test(node.prop)) {
259
- for (const word of value.match(/(?<![\w$#.-])[a-zA-Z][a-zA-Z0-9-]*(?![\w(-])/g) ?? [])
260
- if (NAMED_COLOURS.has(word.toLowerCase()))
261
- report(node, 'color-named', `Named colour "${word}": use a palette token`);
262
- }
263
- }
264
- if (!node.prop.startsWith('--') && !node.prop.startsWith('$')) {
265
- const zero = new RegExp(`(?<![\\w.#$-])0(${LENGTH_UNITS})\\b`, 'i');
266
- if (zero.test(value) && !/calc\(/.test(value))
267
- report(node, 'length-zero-no-unit', 'Unexpected unit on a zero length');
268
- }
269
- }
270
- });
271
-
272
- const decls = kids.filter((n) => n.type === 'decl');
273
- const seen = new Map();
274
- decls.forEach((d, i) => {
275
- if (d.prop.startsWith('$') || d.prop.startsWith('--')) return;
276
- const before = seen.get(d.prop);
277
- const consecutive = before !== undefined && decls[i - 1] === decls[before];
278
- if (before !== undefined && !(consecutive && decls[before].value !== d.value))
279
- report(d, 'declaration-block-no-duplicate-properties', `Duplicate property ${d.prop}`);
280
- seen.set(d.prop, i);
281
- });
282
-
283
- let run = [];
284
- const flush = () => {
285
- const known = run.filter((d) => RANK.has(unprefixed(d.prop)));
286
- const sorted = [...known].sort(
287
- (a, b) => RANK.get(unprefixed(a.prop)) - RANK.get(unprefixed(b.prop)),
288
- );
289
- known.forEach((d, i) => {
290
- if (
291
- d !== sorted[i] &&
292
- !known
293
- .slice(0, i)
294
- .every((p) => RANK.get(unprefixed(p.prop)) <= RANK.get(unprefixed(d.prop)))
295
- ) {
296
- const before = known
297
- .slice(0, i)
298
- .find((p) => RANK.get(unprefixed(p.prop)) > RANK.get(unprefixed(d.prop)));
299
- report(
300
- d,
301
- 'order/properties-order',
302
- `Expected "${d.prop}" to come before "${before.prop}"`,
303
- );
304
- }
305
- });
306
- if (fix && known.some((d, i) => d !== sorted[i])) {
307
- const slots = known.map((d) => ({ before: d.raws.before }));
308
- const nodes = run.slice();
309
- const positions = known.map((d) => nodes.indexOf(d));
310
- const holders = positions.map((p) => nodes[p]);
311
- sorted.forEach((d, i) => {
312
- holders[i].replaceWith(d.clone({ raws: { ...d.raws, before: slots[i].before } }));
313
- });
314
- }
315
- run = [];
316
- };
317
- for (const node of kids) {
318
- if (node.type === 'decl') run.push(node);
319
- else if (node.type !== 'comment') flush();
320
- }
321
- flush();
322
- };
323
- visit(root, [], 0);
324
-
325
- if (fix) {
326
- const out = root.toString();
327
- if (out !== source) writeFileSync(file, out);
328
- }
329
- return problems;
330
- };
331
-
332
- const fix = process.argv.includes('--fix');
333
- const given = process.argv.slice(2).filter((a) => !a.startsWith('--'));
334
- const targets = given.length ? given : files(inside(repo, options.source ?? 'src'));
335
- let total = 0;
336
- for (const file of targets) {
337
- const problems = fix ? (lintFile(file, true), lintFile(file, false)) : lintFile(file, false);
338
- for (const p of problems.sort((a, b) => a.line - b.line)) {
339
- console.error(
340
- `${relative(repo, file).replaceAll('\\', '/')}:${p.line} ${p.message} (${p.rule})`,
341
- );
342
- total += 1;
343
- }
344
- }
345
- if (total) {
346
- console.error(`\n${total} SCSS problem${total === 1 ? '' : 's'}.`);
347
- process.exit(1);
348
- }
349
- console.log(`SCSS lint passed (${targets.length} files).`);
1
+ #!/usr/bin/env node
2
+ import { readdirSync, readFileSync, writeFileSync } from 'node:fs';
3
+ import { basename, join, relative } from 'node:path';
4
+ import { loadConfig, inside } from '../runner/config.mjs';
5
+ import { matches } from '../runner/graph.mjs';
6
+ import scss from 'postcss-scss';
7
+
8
+ const repo = process.env.TOOLING_ROOT ?? process.cwd();
9
+ const { config } = loadConfig(repo);
10
+ const options = config.styles ?? {};
11
+ const ORDER = JSON.parse(
12
+ readFileSync(new URL('./style-property-order.json', import.meta.url), 'utf8'),
13
+ );
14
+ const RANK = new Map(ORDER.map((name, index) => [name, index]));
15
+
16
+ const BEM =
17
+ /^[a-z][a-z0-9]*(-[a-z0-9]+)*(__[a-z][a-z0-9]*(-[a-z0-9]+)*)?(--[a-z][a-z0-9]*(-[a-z0-9]+)*)?$/;
18
+ const rookie = options.preset === 'rookie';
19
+ const rules = { bem: rookie, componentName: rookie, palette: rookie, ...options.rules };
20
+ const COLOUR_FREE = /[/\\](_palette|themes)[/\\]/;
21
+ // Flex layout a `Stack`-style primitive already expresses. Grid stays allowed (areas, templates).
22
+ const LAYOUT_PROPS =
23
+ /^(display|gap|row-gap|column-gap|flex-direction|flex-wrap|justify-content|align-items)$/;
24
+ const LAYOUT_VALUE = (prop, value) => prop !== 'display' || /^\s*(inline-)?flex\s*$/.test(value);
25
+ const MAX_DEPTH = options.maxDepth ?? 3;
26
+ const CONTROL = new Set(['for', 'each', 'while', 'if', 'else']);
27
+ const MAX_SPECIFICITY = options.maxSpecificity ?? [0, 4, 2];
28
+ const LENGTH_UNITS = 'px|em|rem|ex|ch|vw|vh|vmin|vmax|cm|mm|in|pt|pc|q';
29
+ const NAMED_COLOURS = new Set(
30
+ 'aliceblue antiquewhite aqua aquamarine azure beige bisque black blanchedalmond blue blueviolet brown burlywood cadetblue chartreuse chocolate coral cornflowerblue cornsilk crimson cyan darkblue darkcyan darkgoldenrod darkgray darkgreen darkgrey darkkhaki darkmagenta darkolivegreen darkorange darkorchid darkred darksalmon darkseagreen darkslateblue darkslategray darkslategrey darkturquoise darkviolet deeppink deepskyblue dimgray dimgrey dodgerblue firebrick floralwhite forestgreen fuchsia gainsboro ghostwhite gold goldenrod gray green greenyellow grey honeydew hotpink indianred indigo ivory khaki lavender lavenderblush lawngreen lemonchiffon lightblue lightcoral lightcyan lightgoldenrodyellow lightgray lightgreen lightgrey lightpink lightsalmon lightseagreen lightskyblue lightslategray lightslategrey lightsteelblue lightyellow lime limegreen linen magenta maroon mediumaquamarine mediumblue mediumorchid mediumpurple mediumseagreen mediumslateblue mediumspringgreen mediumturquoise mediumvioletred midnightblue mintcream mistyrose moccasin navajowhite navy oldlace olive olivedrab orange orangered orchid palegoldenrod palegreen paleturquoise palevioletred papayawhip peachpuff peru pink plum powderblue purple rebeccapurple red rosybrown royalblue saddlebrown salmon sandybrown seagreen seashell sienna silver skyblue slateblue slategray slategrey snow springgreen steelblue tan teal thistle tomato turquoise violet wheat white whitesmoke yellow yellowgreen'.split(
31
+ ' ',
32
+ ),
33
+ );
34
+ const COLOUR_PROPS =
35
+ /^(color|background(-color|-image)?|border(-[a-z]+)*-color|border(-top|-right|-bottom|-left)?|outline(-color)?|fill|stroke|box-shadow|text-shadow|caret-color|accent-color|text-decoration(-color)?|column-rule(-color)?)$/;
36
+
37
+ const files = (dir) =>
38
+ readdirSync(dir, { withFileTypes: true }).flatMap((entry) => {
39
+ const path = join(dir, entry.name);
40
+ if (entry.isDirectory()) return files(path);
41
+ return entry.isFile() && path.endsWith('.scss') ? [path] : [];
42
+ });
43
+
44
+ const stripValue = (value) =>
45
+ value
46
+ .replace(/\/\*[\s\S]*?\*\//g, '')
47
+ .replace(/(['"])(?:\\.|(?!\1).)*\1/g, '""')
48
+ .replace(/#\{[^}]*\}/g, 'x');
49
+
50
+ const unprefixed = (prop) => prop.replace(/^-(webkit|moz|ms|o)-/, '');
51
+
52
+ const specificity = (selector) => {
53
+ const s = [0, 0, 0];
54
+ const clean = selector.replace(/\[[^\]]*\]/g, () => {
55
+ s[1] += 1;
56
+ return '';
57
+ });
58
+ for (const match of clean.matchAll(
59
+ /(#[\w-]+)|(\.[\w-]+)|(::?[\w-]+)(\([^)]*\))?|([a-zA-Z][\w-]*)/g,
60
+ )) {
61
+ if (match[1]) s[0] += 1;
62
+ else if (match[2]) s[1] += 1;
63
+ else if (match[3]) {
64
+ const name = match[3].replace(/^:+/, '');
65
+ if (
66
+ match[3].startsWith('::') ||
67
+ ['before', 'after', 'first-line', 'first-letter'].includes(name)
68
+ )
69
+ s[2] += 1;
70
+ else if (name === 'where' || name === 'global') continue;
71
+ else if (['is', 'not', 'has'].includes(name)) {
72
+ const inner = (match[4] ?? '').slice(1, -1).split(',').map(specificity);
73
+ const top = inner.sort((a, b) => b[0] - a[0] || b[1] - a[1] || b[2] - a[2])[0] ?? [0, 0, 0];
74
+ s[0] += top[0];
75
+ s[1] += top[1];
76
+ s[2] += top[2];
77
+ } else s[1] += 1;
78
+ } else if (match[5]) s[2] += 1;
79
+ }
80
+ return s;
81
+ };
82
+ const tooSpecific = (s) =>
83
+ s[0] > MAX_SPECIFICITY[0] ||
84
+ (s[0] === MAX_SPECIFICITY[0] &&
85
+ (s[1] > MAX_SPECIFICITY[1] || (s[1] === MAX_SPECIFICITY[1] && s[2] > MAX_SPECIFICITY[2])));
86
+
87
+ const splitList = (selector) => {
88
+ const out = [];
89
+ let depth = 0;
90
+ let start = 0;
91
+ for (let i = 0; i < selector.length; i += 1) {
92
+ const c = selector[i];
93
+ if (c === '(' || c === '[') depth += 1;
94
+ else if (c === ')' || c === ']') depth -= 1;
95
+ else if (c === ',' && depth === 0) {
96
+ out.push(selector.slice(start, i).trim());
97
+ start = i + 1;
98
+ }
99
+ }
100
+ out.push(selector.slice(start).trim());
101
+ return out.filter(Boolean);
102
+ };
103
+
104
+ const resolve = (selector, parents) =>
105
+ parents.length === 0
106
+ ? splitList(selector)
107
+ : splitList(selector).flatMap((child) =>
108
+ parents.map((parent) =>
109
+ child.includes('&') ? child.replaceAll('&', parent) : `${parent} ${child}`,
110
+ ),
111
+ );
112
+
113
+ /* An at-rule straight under the root (a mixin, a media query) and Sass control flow are not levels. */
114
+ const nestingDepth = (node, level = 0) => {
115
+ const parent = node.parent;
116
+ if (!parent || parent.type === 'root') return level;
117
+ if (parent.type === 'atrule' && parent.parent?.type === 'root') return level;
118
+ if (parent.type === 'atrule' && CONTROL.has(parent.name)) return nestingDepth(parent, level);
119
+ return nestingDepth(parent, level + 1);
120
+ };
121
+
122
+ const line = (node) => node.source?.start?.line ?? 0;
123
+ const endLine = (node) => node.source?.end?.line ?? line(node);
124
+ const blankBefore = (node) => /\n[ \t\r]*\n/.test(node.raws.before ?? '');
125
+
126
+ const lintFile = (file, fix) => {
127
+ const source = readFileSync(file, 'utf8');
128
+ const problems = [];
129
+ const root = scss.parse(source, { from: file });
130
+ const colourFree =
131
+ !rules.palette ||
132
+ COLOUR_FREE.test(file) ||
133
+ (options.colourTokenPaths ?? []).some((pattern) => matches(relative(repo, file), pattern));
134
+ const moduleBlock =
135
+ rules.componentName && /\.module\.scss$/.test(file)
136
+ ? basename(file, '.module.scss')
137
+ .replace(/(?<!^)(?=[A-Z])/g, '-')
138
+ .toLowerCase()
139
+ : null;
140
+ const layoutChecked =
141
+ rules.layoutCss &&
142
+ /\.module\.scss$/.test(file) &&
143
+ !(options.layoutPaths ?? []).some((pattern) => matches(relative(repo, file), pattern));
144
+ const disabled = new Map();
145
+ root.walkComments((c) => {
146
+ const m = /lint-scss-disable-next-line\s+([\w-]+)/.exec(c.text);
147
+ if (m) disabled.set(`${endLine(c) + 1}:${m[1]}`, true);
148
+ });
149
+ const report = (node, rule, message) => {
150
+ if (disabled.has(`${line(node)}:${rule}`)) return;
151
+ problems.push({ line: line(node), rule, message });
152
+ };
153
+
154
+ const visit = (parent, selectors, depth) => {
155
+ const kids = parent.nodes ?? [];
156
+ kids.forEach((node, index) => {
157
+ const prev = kids[index - 1];
158
+ const first = index === 0;
159
+ const nested = parent.type !== 'root';
160
+
161
+ if (node.type === 'comment') {
162
+ const sameLine = prev && endLine(prev) === line(node);
163
+ const afterComment = prev?.type === 'comment';
164
+ if (
165
+ !sameLine &&
166
+ !afterComment &&
167
+ !first &&
168
+ !blankBefore(node) &&
169
+ !/lint-scss|stylelint/.test(node.text)
170
+ )
171
+ report(node, 'comment-empty-line-before', 'Expected an empty line before the comment');
172
+ if (!sameLine && first && nested && blankBefore(node))
173
+ report(
174
+ node,
175
+ 'comment-empty-line-before',
176
+ 'Unexpected empty line before the first comment',
177
+ );
178
+ }
179
+
180
+ if (
181
+ node.type === 'rule' &&
182
+ parent.name !== 'keyframes' &&
183
+ !/keyframes$/.test(parent.name ?? '')
184
+ ) {
185
+ const own = resolve(node.selector, selectors);
186
+ const multi = endLine(node) > line(node);
187
+ const afterComment = prev?.type === 'comment';
188
+ if (first && nested && blankBefore(node))
189
+ report(node, 'rule-empty-line-before', 'Unexpected empty line before the first rule');
190
+ else if (!first && multi && !afterComment && !blankBefore(node))
191
+ report(node, 'rule-empty-line-before', 'Expected an empty line before the rule');
192
+ if (nestingDepth(node) > MAX_DEPTH)
193
+ report(node, 'max-nesting-depth', `Nesting deeper than ${MAX_DEPTH} levels`);
194
+ if (!node.nodes?.length) report(node, 'block-no-empty', 'Empty block');
195
+ for (const sel of own) {
196
+ if (!sel.includes('#{') && !sel.includes('%')) {
197
+ const bare = sel.replace(/:global\([^)]*\)/g, '').replace(/\[[^\]]*\]/g, '');
198
+ for (const m of bare.matchAll(/\.(-?[\w-]+)/g))
199
+ if (rules.bem && !BEM.test(m[1]))
200
+ report(
201
+ node,
202
+ 'selector-class-pattern',
203
+ `Use BEM: .block, .block__element, .block--modifier, in kebab-case: .${m[1]}`,
204
+ );
205
+ for (const m of bare.matchAll(/\.([a-z][a-z0-9]*(?:-[a-z0-9]+)*)(?:__|--|(?![\w-]))/g))
206
+ if (moduleBlock && m[1] !== moduleBlock)
207
+ report(
208
+ node,
209
+ 'block-name-matches-component',
210
+ `The block is named after the component: .${moduleBlock}, not .${m[1]}`,
211
+ );
212
+ }
213
+ if (!sel.includes('#{') && tooSpecific(specificity(sel)))
214
+ report(
215
+ node,
216
+ 'selector-max-specificity',
217
+ `Specificity of "${sel}" is above ${MAX_SPECIFICITY.join(',')}`,
218
+ );
219
+ }
220
+ visit(node, own, depth + 1);
221
+ return;
222
+ }
223
+
224
+ if (node.type === 'atrule') {
225
+ const blockless = !node.nodes;
226
+ const afterComment = prev?.type === 'comment';
227
+ const prevBlockless = prev?.type === 'atrule' && !prev.nodes;
228
+ if (node.name !== 'else') {
229
+ if (first && nested && blankBefore(node))
230
+ report(node, 'at-rule-empty-line-before', `Unexpected empty line before @${node.name}`);
231
+ else if (!first && !afterComment) {
232
+ if (blockless && prevBlockless && blankBefore(node))
233
+ report(
234
+ node,
235
+ 'at-rule-empty-line-before',
236
+ `Unexpected empty line before @${node.name}`,
237
+ );
238
+ else if (!(blockless && prevBlockless) && !blankBefore(node))
239
+ report(
240
+ node,
241
+ 'at-rule-empty-line-before',
242
+ `Expected an empty line before @${node.name}`,
243
+ );
244
+ }
245
+ }
246
+ if (node.nodes) {
247
+ if (nestingDepth(node) > MAX_DEPTH && node.name !== 'keyframes')
248
+ report(node, 'max-nesting-depth', `Nesting deeper than ${MAX_DEPTH} levels`);
249
+ if (!node.nodes.length) report(node, 'block-no-empty', 'Empty block');
250
+ visit(node, selectors, node.name === 'keyframes' ? depth : depth + 1);
251
+ }
252
+ return;
253
+ }
254
+
255
+ if (node.type === 'decl') {
256
+ const value = stripValue(node.value);
257
+ if (layoutChecked && LAYOUT_PROPS.test(node.prop) && LAYOUT_VALUE(node.prop, value))
258
+ report(
259
+ node,
260
+ 'layout-css',
261
+ `${node.prop}: ${node.value} in a component module: use the layout primitive (Stack) props, or move it to a shared layout component listed in styles.layoutPaths`,
262
+ );
263
+ if (!colourFree) {
264
+ if (
265
+ /#[0-9a-fA-F]{3,8}\b/.test(value) &&
266
+ !node.prop.startsWith('$') &&
267
+ !node.prop.startsWith('--')
268
+ )
269
+ report(node, 'color-no-hex', 'Raw hex colour: use a palette token');
270
+ if (/\b(rgba?|hsla?)\(/i.test(value))
271
+ report(node, 'function-disallowed-list', 'Use a palette token, not rgb()/hsl()');
272
+ if (COLOUR_PROPS.test(node.prop)) {
273
+ for (const word of value.match(/(?<![\w$#.-])[a-zA-Z][a-zA-Z0-9-]*(?![\w(-])/g) ?? [])
274
+ if (NAMED_COLOURS.has(word.toLowerCase()))
275
+ report(node, 'color-named', `Named colour "${word}": use a palette token`);
276
+ }
277
+ }
278
+ if (!node.prop.startsWith('--') && !node.prop.startsWith('$')) {
279
+ const zero = new RegExp(`(?<![\\w.#$-])0(${LENGTH_UNITS})\\b`, 'i');
280
+ if (zero.test(value) && !/calc\(/.test(value))
281
+ report(node, 'length-zero-no-unit', 'Unexpected unit on a zero length');
282
+ }
283
+ }
284
+ });
285
+
286
+ const decls = kids.filter((n) => n.type === 'decl');
287
+ const seen = new Map();
288
+ decls.forEach((d, i) => {
289
+ if (d.prop.startsWith('$') || d.prop.startsWith('--')) return;
290
+ const before = seen.get(d.prop);
291
+ const consecutive = before !== undefined && decls[i - 1] === decls[before];
292
+ if (before !== undefined && !(consecutive && decls[before].value !== d.value))
293
+ report(d, 'declaration-block-no-duplicate-properties', `Duplicate property ${d.prop}`);
294
+ seen.set(d.prop, i);
295
+ });
296
+
297
+ let run = [];
298
+ const flush = () => {
299
+ const known = run.filter((d) => RANK.has(unprefixed(d.prop)));
300
+ const sorted = [...known].sort(
301
+ (a, b) => RANK.get(unprefixed(a.prop)) - RANK.get(unprefixed(b.prop)),
302
+ );
303
+ known.forEach((d, i) => {
304
+ if (
305
+ d !== sorted[i] &&
306
+ !known
307
+ .slice(0, i)
308
+ .every((p) => RANK.get(unprefixed(p.prop)) <= RANK.get(unprefixed(d.prop)))
309
+ ) {
310
+ const before = known
311
+ .slice(0, i)
312
+ .find((p) => RANK.get(unprefixed(p.prop)) > RANK.get(unprefixed(d.prop)));
313
+ report(
314
+ d,
315
+ 'order/properties-order',
316
+ `Expected "${d.prop}" to come before "${before.prop}"`,
317
+ );
318
+ }
319
+ });
320
+ if (fix && known.some((d, i) => d !== sorted[i])) {
321
+ const slots = known.map((d) => ({ before: d.raws.before }));
322
+ const nodes = run.slice();
323
+ const positions = known.map((d) => nodes.indexOf(d));
324
+ const holders = positions.map((p) => nodes[p]);
325
+ sorted.forEach((d, i) => {
326
+ holders[i].replaceWith(d.clone({ raws: { ...d.raws, before: slots[i].before } }));
327
+ });
328
+ }
329
+ run = [];
330
+ };
331
+ for (const node of kids) {
332
+ if (node.type === 'decl') run.push(node);
333
+ else if (node.type !== 'comment') flush();
334
+ }
335
+ flush();
336
+ };
337
+ visit(root, [], 0);
338
+
339
+ if (fix) {
340
+ const out = root.toString();
341
+ if (out !== source) writeFileSync(file, out);
342
+ }
343
+ return problems;
344
+ };
345
+
346
+ const fix = process.argv.includes('--fix');
347
+ const given = process.argv.slice(2).filter((a) => !a.startsWith('--'));
348
+ const targets = given.length ? given : files(inside(repo, options.source ?? 'src'));
349
+ let total = 0;
350
+ for (const file of targets) {
351
+ const problems = fix ? (lintFile(file, true), lintFile(file, false)) : lintFile(file, false);
352
+ for (const p of problems.sort((a, b) => a.line - b.line)) {
353
+ console.error(
354
+ `${relative(repo, file).replaceAll('\\', '/')}:${p.line} ${p.message} (${p.rule})`,
355
+ );
356
+ total += 1;
357
+ }
358
+ }
359
+ if (total) {
360
+ console.error(`\n${total} SCSS problem${total === 1 ? '' : 's'}.`);
361
+ process.exit(1);
362
+ }
363
+ console.log(`SCSS lint passed (${targets.length} files).`);