@dcaldeira/tooling 0.0.0-stage → 0.2.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.
Files changed (56) hide show
  1. package/LICENSE +9 -0
  2. package/README.md +33 -2
  3. package/checks/a11y.mjs +206 -0
  4. package/checks/architecture.mjs +137 -0
  5. package/checks/audit.mjs +121 -0
  6. package/checks/bundle.mjs +126 -0
  7. package/checks/dependencies.mjs +277 -0
  8. package/checks/duplication.mjs +135 -0
  9. package/checks/lint-scss.mjs +363 -0
  10. package/checks/package.mjs +30 -0
  11. package/checks/playwright-summary.mjs +53 -0
  12. package/checks/sass.mjs +67 -0
  13. package/checks/scan-secrets.mjs +58 -0
  14. package/checks/shared.mjs +86 -0
  15. package/checks/style-property-order.json +498 -0
  16. package/checks/translations.mjs +55 -0
  17. package/checks/visual-compare.mjs +148 -0
  18. package/checks/visual-report-html.mjs +470 -0
  19. package/checks/visual-report.mjs +13 -0
  20. package/config.schema.json +977 -0
  21. package/configs/eslint.mjs +27 -0
  22. package/configs/knip.json +11 -0
  23. package/configs/playwright.mjs +15 -0
  24. package/configs/prettier.mjs +1 -0
  25. package/configs/tsconfig.json +16 -0
  26. package/configs/vitest.mjs +16 -0
  27. package/package.json +103 -4
  28. package/release/evidence.mjs +62 -0
  29. package/release/finalize.mjs +65 -0
  30. package/release/gh.mjs +25 -0
  31. package/release/github.mjs +64 -0
  32. package/release/prepare.mjs +30 -0
  33. package/runner/browsers.mjs +73 -0
  34. package/runner/cache.mjs +121 -0
  35. package/runner/ci-plan.mjs +54 -0
  36. package/runner/cli.mjs +251 -0
  37. package/runner/config.mjs +148 -0
  38. package/runner/docs-install.mjs +93 -0
  39. package/runner/execute.mjs +298 -0
  40. package/runner/generate.mjs +122 -0
  41. package/runner/git.mjs +122 -0
  42. package/runner/graph.mjs +250 -0
  43. package/runner/index.mjs +4 -0
  44. package/runner/insights.mjs +313 -0
  45. package/runner/provision.mjs +53 -0
  46. package/runner/repo-standard.mjs +104 -0
  47. package/runner/report.mjs +35 -0
  48. package/runner/serve-static.mjs +76 -0
  49. package/runner/setup.mjs +241 -0
  50. package/runner/summary.mjs +112 -0
  51. package/runner/watch.mjs +82 -0
  52. package/templates/ci.yml +25 -0
  53. package/templates/dependabot-merge.yml +13 -0
  54. package/templates/dependabot.yml +26 -0
  55. package/templates/pre-push +13 -0
  56. package/templates/release.yml +23 -0
@@ -0,0 +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
+ // 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).`);
@@ -0,0 +1,30 @@
1
+ import { existsSync, mkdtempSync, readdirSync, rmSync, statSync } from 'node:fs';
2
+ import { tmpdir } from 'node:os';
3
+ import { join } from 'node:path';
4
+ import { pathToFileURL } from 'node:url';
5
+ import { inside } from '../runner/config.mjs';
6
+ import { invoke } from '../runner/execute.mjs';
7
+
8
+ export async function checkPackage(root, requiredFiles, run = invoke) {
9
+ if (!requiredFiles.length) throw new Error('Specify required package build files');
10
+ const missing = requiredFiles.filter((file) => {
11
+ const path = inside(root, file);
12
+ return !existsSync(path) || !statSync(path).isFile();
13
+ });
14
+ if (missing.length) throw new Error(`Package build is missing: ${missing.join(', ')}`);
15
+ const destination = mkdtempSync(join(tmpdir(), 'tooling-pack-'));
16
+ try {
17
+ const result = await run(['npm', 'pack', '--ignore-scripts', '--pack-destination', destination], root, { quiet: true });
18
+ if (result.status !== 'passed') throw new Error('Package packing failed');
19
+ const archives = readdirSync(destination).filter((file) => file.endsWith('.tgz'));
20
+ if (archives.length !== 1) throw new Error('Package smoke check did not produce exactly one archive');
21
+ return archives[0];
22
+ } finally {
23
+ rmSync(destination, { recursive: true, force: true });
24
+ }
25
+ }
26
+
27
+ if (process.argv[1] && import.meta.url === pathToFileURL(process.argv[1]).href) {
28
+ const archive = await checkPackage(process.cwd(), process.argv.slice(2));
29
+ console.log(`Package smoke check passed (${archive}).`);
30
+ }
@@ -0,0 +1,53 @@
1
+ import { existsSync, readFileSync } from 'node:fs';
2
+ import { pathToFileURL } from 'node:url';
3
+
4
+ const cell = (text) => String(text).replaceAll('|', '&#124;').replace(/[\r\n]+/g, ' ');
5
+
6
+ export function playwrightSummary(data, { artifact = 'visual-diffs', report = 'playwright-report/index.html' } = {}) {
7
+ const failures = [];
8
+
9
+ const collect = (suite, path = []) => {
10
+ const titles = suite.title ? [...path, suite.title] : path;
11
+
12
+ for (const spec of suite.specs ?? []) {
13
+ if (spec.ok) continue;
14
+ const projects = [
15
+ ...new Set((spec.tests ?? []).map((test) => test.projectName)),
16
+ ];
17
+ failures.push({
18
+ name: [...titles, spec.title].join(' › '),
19
+ projects: projects.join(', '),
20
+ });
21
+ }
22
+ for (const child of suite.suites ?? []) collect(child, titles);
23
+ };
24
+
25
+ for (const suite of data.suites ?? [])
26
+ collect(suite);
27
+
28
+ if (failures.length === 0) return '';
29
+
30
+ const rows = failures
31
+ .map(({ name, projects }) => `| ${cell(name)} | ${cell(projects)} |`)
32
+ .join('\n');
33
+
34
+ return [
35
+ '## Visual differences',
36
+ '',
37
+ `${failures.length} snapshot test(s) differ from their baseline.`,
38
+ '',
39
+ `Download the **${cell(artifact)}** artifact and open \`${cell(report)}\` for expected, actual and diff images. Fix the regression or update and review the intended baselines.`,
40
+ '',
41
+ '| Test | Project |',
42
+ '| --- | --- |',
43
+ rows,
44
+ '',
45
+ ].join('\n');
46
+
47
+ }
48
+
49
+ if (process.argv[1] && import.meta.url === pathToFileURL(process.argv[1]).href) {
50
+ const [resultsPath = 'test-results/results.json', artifact, report] = process.argv.slice(2);
51
+ if (existsSync(resultsPath))
52
+ process.stdout.write(playwrightSummary(JSON.parse(readFileSync(resultsPath, 'utf8')), { artifact, report }));
53
+ }
@@ -0,0 +1,67 @@
1
+ import { readdirSync, readFileSync } from 'node:fs';
2
+ import { createRequire } from 'node:module';
3
+ import { join, relative } from 'node:path';
4
+ import { pathToFileURL } from 'node:url';
5
+ import scss from 'postcss-scss';
6
+ import { inside, loadConfig } from '../runner/config.mjs';
7
+ import { matches } from '../runner/graph.mjs';
8
+
9
+ export function importantViolations(source, file, exceptions = []) {
10
+ const tree = scss.parse(source, { from: file });
11
+ if (exceptions.some((pattern) => matches(file, pattern))) return [];
12
+ const failures = [];
13
+ tree.walkDecls((declaration) => {
14
+ if (declaration.important)
15
+ failures.push(`${file}:${declaration.source?.start?.line ?? 1}: avoid !important; use tokens or cascade structure`);
16
+ });
17
+ return failures;
18
+ }
19
+
20
+ export async function checkSass(root, options, { compile } = {}) {
21
+ if (!options?.entrypoints?.length) throw new Error('Configure sass.entrypoints');
22
+ const source = inside(root, options.source ?? 'src');
23
+ const includes = options.include ?? ['**/*.scss'];
24
+ const excludes = options.exclude ?? [];
25
+ const files = [];
26
+ const walk = (directory) => {
27
+ for (const entry of readdirSync(directory, { withFileTypes: true }).sort((a, b) => a.name.localeCompare(b.name))) {
28
+ const path = join(directory, entry.name);
29
+ const file = relative(root, path).replaceAll('\\', '/');
30
+ if (excludes.some((pattern) => matches(file, pattern))) continue;
31
+ if (entry.isSymbolicLink()) throw new Error(`Sass source must not contain symlinks: ${file}`);
32
+ if (entry.isDirectory()) walk(path);
33
+ else if (entry.isFile() && includes.some((pattern) => matches(file, pattern))) files.push(path);
34
+ }
35
+ };
36
+ walk(source);
37
+ if (!files.length) throw new Error('No SCSS files matched sass.include');
38
+ const entrypoints = options.entrypoints.map((file) => inside(root, file));
39
+ const compiler = compile ?? createRequire(join(root, 'package.json'))('sass').compileAsync;
40
+ const failures = [];
41
+ for (const file of entrypoints) {
42
+ try {
43
+ await compiler(file, { style: 'compressed' });
44
+ } catch (error) {
45
+ failures.push(`${relative(root, file)}: Sass compilation failed: ${error.message}`);
46
+ }
47
+ }
48
+ for (const path of files) {
49
+ const file = relative(root, path).replaceAll('\\', '/');
50
+ try {
51
+ failures.push(...importantViolations(readFileSync(path, 'utf8'), file, options.importantExceptions));
52
+ } catch (error) {
53
+ failures.push(`${file}:${error.line ?? 1}: SCSS parsing failed: ${error.reason ?? error.message}`);
54
+ }
55
+ }
56
+ return { files: files.length, entrypoints: entrypoints.length, failures };
57
+ }
58
+
59
+ if (process.argv[1] && import.meta.url === pathToFileURL(process.argv[1]).href) {
60
+ const root = process.env.TOOLING_ROOT ?? process.cwd();
61
+ const { config } = loadConfig(root);
62
+ const result = await checkSass(root, config.sass);
63
+ if (result.failures.length) {
64
+ console.error(result.failures.join('\n'));
65
+ process.exitCode = 1;
66
+ } else console.log(`Sass checks passed (${result.files} files, ${result.entrypoints} entrypoints).`);
67
+ }
@@ -0,0 +1,58 @@
1
+ #!/usr/bin/env node
2
+ import { lstatSync, readFileSync } from 'node:fs';
3
+ import { join } from 'node:path';
4
+ import { pathToFileURL } from 'node:url';
5
+ import { git } from '../runner/git.mjs';
6
+ import { rootDirectory, writeDetails } from './shared.mjs';
7
+
8
+ const patterns = [
9
+ [/-----BEGIN (RSA |EC |OPENSSH )?PRIVATE KEY-----/, 'private key'],
10
+ [/sk_live_[0-9a-zA-Z]{20,}/, 'live secret key'],
11
+ [/AKIA[0-9A-Z]{16}/, 'AWS access key'],
12
+ [/VAPID_PRIVATE_KEY\s*=\s*['"]?[A-Za-z0-9_-]{40,}/, 'VAPID private key'],
13
+ ];
14
+
15
+ export function secretLabels(text) {
16
+ const labels = patterns.filter(([pattern]) => pattern.test(text)).map(([, label]) => label);
17
+ for (const match of text.matchAll(/\beyJ[A-Za-z0-9_-]*\.([A-Za-z0-9_-]+)\.[A-Za-z0-9_-]+/g)) {
18
+ try {
19
+ const payload = JSON.parse(Buffer.from(match[1], 'base64url').toString('utf8'));
20
+ if (payload.role === 'service_role') labels.push('Supabase service-role JWT');
21
+ } catch {
22
+ // Ordinary dotted strings and malformed tokens are not service-role JWTs.
23
+ }
24
+ }
25
+ return [...new Set(labels)];
26
+ }
27
+
28
+ export function scanSecrets(root) {
29
+ const files = [...new Set(
30
+ git(root, 'ls-files', '--cached', '--others', '--exclude-standard', '-z').split('\0'),
31
+ )].filter((file) => file && !/\.(?:png|jpe?g|gif|webp|ico|wasm|woff2?|pdf|zip)$/i.test(file));
32
+ const hits = [];
33
+ let scanned = 0;
34
+ for (const file of files) {
35
+ let text;
36
+ try {
37
+ const path = join(root, file);
38
+ if (!lstatSync(path).isFile()) continue;
39
+ text = readFileSync(path, 'utf8');
40
+ } catch (error) {
41
+ if (error.code === 'ENOENT') continue;
42
+ throw error;
43
+ }
44
+ if (text.includes('\0')) continue;
45
+ scanned++;
46
+ for (const label of secretLabels(text)) hits.push({ file, label });
47
+ }
48
+ return { scanned, hits };
49
+ }
50
+
51
+ if (process.argv[1] && import.meta.url === pathToFileURL(process.argv[1]).href) {
52
+ const result = scanSecrets(rootDirectory());
53
+ writeDetails({ secrets: result });
54
+ if (result.hits.length) {
55
+ console.error(`Possible secrets committed:\n${result.hits.map(({ file, label }) => `${file}: ${label}`).join('\n')}`);
56
+ process.exitCode = 1;
57
+ } else console.log(`Secret scan passed (${result.scanned} files).`);
58
+ }
@@ -0,0 +1,86 @@
1
+ import { createRequire } from 'node:module';
2
+ import { existsSync, mkdirSync, readFileSync, writeFileSync } from 'node:fs';
3
+ import { join, dirname } from 'node:path';
4
+ import { git } from '../runner/git.mjs';
5
+ import { matches } from '../runner/graph.mjs';
6
+
7
+ export const rootDirectory = () => process.env.TOOLING_ROOT ?? process.cwd();
8
+ export function peer(name, cwd = process.cwd()) {
9
+ try {
10
+ return createRequire(join(cwd, 'package.json'))(name);
11
+ } catch (error) {
12
+ throw new Error(`Install ${name} in this project to enable this check`, { cause: error });
13
+ }
14
+ }
15
+ export function sourceFiles(root, patterns, exclude = []) {
16
+ return [
17
+ ...new Set(
18
+ git(root, 'ls-files', '--cached', '--others', '--exclude-standard', '-z').split('\0'),
19
+ ),
20
+ ].filter(
21
+ (file) =>
22
+ file &&
23
+ existsSync(join(root, file)) &&
24
+ patterns.some((pattern) => matches(file, pattern)) &&
25
+ !exclude.some((pattern) => matches(file, pattern)),
26
+ );
27
+ }
28
+ export function writeDetails(value) {
29
+ const directory = process.env.TOOLING_REPORT_DIR;
30
+ const id = process.env.TOOLING_CHECK_ID;
31
+ if (!directory || !id) return;
32
+ mkdirSync(directory, { recursive: true });
33
+ writeFileSync(join(directory, `${id}.details.json`), JSON.stringify(value, null, 2) + '\n');
34
+ }
35
+ export function compilerOptions(ts, root, configPath = 'tsconfig.json') {
36
+ const path = join(root, configPath);
37
+ if (!existsSync(path))
38
+ return {
39
+ allowJs: true,
40
+ moduleResolution: ts.ModuleResolutionKind.Bundler,
41
+ module: ts.ModuleKind.ESNext,
42
+ };
43
+ const read = ts.readConfigFile(path, ts.sys.readFile);
44
+ if (read.error) throw new Error(ts.flattenDiagnosticMessageText(read.error.messageText, '\n'));
45
+ const parsed = ts.parseJsonConfigFileContent(read.config, ts.sys, dirname(path), undefined, path);
46
+ const errors = parsed.errors.filter((error) => ![18002, 18003].includes(error.code));
47
+ if (errors.length)
48
+ throw new Error(
49
+ errors.map((error) => ts.flattenDiagnosticMessageText(error.messageText, '\n')).join('\n'),
50
+ );
51
+ return parsed.options;
52
+ }
53
+ export function importsIn(ts, file) {
54
+ const ast = ts.createSourceFile(file, readFileSync(file, 'utf8'), ts.ScriptTarget.Latest, true);
55
+ if (ast.parseDiagnostics.length)
56
+ throw new Error(
57
+ `${file}: ${ts.flattenDiagnosticMessageText(ast.parseDiagnostics[0].messageText, '\n')}`,
58
+ );
59
+ const imports = [];
60
+ function visit(node) {
61
+ let value;
62
+ if (ts.isImportDeclaration(node) || ts.isExportDeclaration(node)) value = node.moduleSpecifier;
63
+ else if (
64
+ ts.isImportEqualsDeclaration(node) &&
65
+ ts.isExternalModuleReference(node.moduleReference)
66
+ )
67
+ value = node.moduleReference.expression;
68
+ else if (
69
+ ts.isCallExpression(node) &&
70
+ (node.expression.kind === ts.SyntaxKind.ImportKeyword ||
71
+ (ts.isIdentifier(node.expression) && node.expression.text === 'require')) &&
72
+ node.arguments.length === 1
73
+ )
74
+ value = node.arguments[0];
75
+ else if (ts.isImportTypeNode(node) && ts.isLiteralTypeNode(node.argument))
76
+ value = node.argument.literal;
77
+ if (value && ts.isStringLiteralLike(value))
78
+ imports.push({
79
+ specifier: value.text,
80
+ line: ast.getLineAndCharacterOfPosition(value.getStart(ast)).line + 1,
81
+ });
82
+ ts.forEachChild(node, visit);
83
+ }
84
+ visit(ast);
85
+ return imports;
86
+ }