@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,104 @@
1
+ import { existsSync, lstatSync, readdirSync, readFileSync } from 'node:fs';
2
+ import { join } from 'node:path';
3
+
4
+ const REQUIRED_SECTIONS = ['Repository', 'Layout', 'Commands', 'Constraints'];
5
+ // Plugin set from the core plugin's repo-standard skill. Personal plugins (caveman) stay out.
6
+ const PLUGINS = ['core@dcaldeira', 'mattpocock-skills@mattpocock'];
7
+ const FRONTEND_PLUGINS = ['ui-ux-pro-max@ui-ux-pro-max-skill', 'taste-skill@taste-skill'];
8
+ const FRONTEND_DEPS = ['react', 'react-native', 'vite', 'next', 'expo'];
9
+
10
+ const read = (path) => (existsSync(path) ? readFileSync(path, 'utf8') : undefined);
11
+ const json = (path) => {
12
+ try {
13
+ return JSON.parse(read(path) ?? 'null');
14
+ } catch {
15
+ return null;
16
+ }
17
+ };
18
+ const subdirs = (path) => {
19
+ try {
20
+ return readdirSync(path, { withFileTypes: true })
21
+ .filter((entry) => entry.isDirectory() && entry.name !== 'node_modules')
22
+ .map((entry) => join(path, entry.name));
23
+ } catch {
24
+ return [];
25
+ }
26
+ };
27
+
28
+ /**
29
+ * True when the root, a workspace, any top-level folder or `apps/*`/`packages/*` depends on a
30
+ * frontend framework. Keep in sync with `detectStack` in claude/hooks/lib/detect.mjs (a test
31
+ * compares them).
32
+ */
33
+ export function hasFrontend(root) {
34
+ const rootManifest = json(join(root, 'package.json'));
35
+ const patterns = [
36
+ ...(Array.isArray(rootManifest?.workspaces)
37
+ ? rootManifest.workspaces
38
+ : (rootManifest?.workspaces?.packages ?? [])),
39
+ '*',
40
+ 'apps/*',
41
+ 'packages/*',
42
+ ];
43
+ const dirs = patterns.flatMap((pattern) =>
44
+ pattern.endsWith('*') ? subdirs(join(root, pattern.slice(0, -1))) : [join(root, pattern)],
45
+ );
46
+ return [rootManifest, ...dirs.map((dir) => json(join(dir, 'package.json')))].some((manifest) =>
47
+ FRONTEND_DEPS.some(
48
+ (dep) =>
49
+ manifest?.dependencies?.[dep] ||
50
+ manifest?.devDependencies?.[dep] ||
51
+ manifest?.peerDependencies?.[dep],
52
+ ),
53
+ );
54
+ }
55
+ const exists = (path) => {
56
+ try {
57
+ lstatSync(path);
58
+ return true;
59
+ } catch {
60
+ return false;
61
+ }
62
+ };
63
+
64
+ /** Findings for the shared repo standard (opt-in through `repoStandard: true`). */
65
+ export function repoStandardFindings(root) {
66
+ const findings = [];
67
+ const fail = (message) =>
68
+ findings.push({ status: 'failed', message: `repo standard: ${message}` });
69
+
70
+ const agents = read(join(root, 'AGENTS.md'));
71
+ if (agents === undefined) fail('add AGENTS.md');
72
+ else {
73
+ const headings = new Set([...agents.matchAll(/^##\s+(.+?)\s*$/gm)].map((match) => match[1]));
74
+ for (const section of REQUIRED_SECTIONS)
75
+ if (!headings.has(section)) fail(`AGENTS.md needs a "## ${section}" section`);
76
+ }
77
+
78
+ const claude = read(join(root, 'CLAUDE.md'));
79
+ if (claude?.trim() !== '@AGENTS.md') fail('CLAUDE.md must contain only @AGENTS.md');
80
+
81
+ for (const [name, text] of [
82
+ ['AGENTS.md', agents],
83
+ ['CLAUDE.md', claude],
84
+ ])
85
+ if (text && /(^|[\s`(/])\.ai[/\\]/m.test(text))
86
+ fail(`${name} still references the old .ai/ kit`);
87
+ if (exists(join(root, '.ai'))) fail('remove the .ai kit link');
88
+ if (exists(join(root, 'ai-memory')))
89
+ fail('move what is still useful out of ai-memory/ and delete it');
90
+
91
+ let settings;
92
+ try {
93
+ settings = JSON.parse(read(join(root, '.claude', 'settings.json')) ?? 'null');
94
+ } catch {
95
+ fail('.claude/settings.json is not valid JSON');
96
+ }
97
+ if (settings !== undefined)
98
+ for (const plugin of [...PLUGINS, ...(hasFrontend(root) ? FRONTEND_PLUGINS : [])])
99
+ if (settings?.enabledPlugins?.[plugin] !== true)
100
+ fail(`.claude/settings.json must enable ${plugin}`);
101
+
102
+ if (!findings.length) findings.push({ status: 'passed', message: 'Repo standard is met' });
103
+ return findings;
104
+ }
@@ -0,0 +1,35 @@
1
+ import { existsSync, mkdirSync, writeFileSync } from 'node:fs';
2
+ import { join } from 'node:path';
3
+ import { markdownSummary } from './summary.mjs';
4
+
5
+ const escape = (value) =>
6
+ String(value ?? '').replace(
7
+ /[&<>"']/g,
8
+ (c) => ({ '&': '&amp;', '<': '&lt;', '>': '&gt;', '"': '&quot;', "'": '&#39;' })[c],
9
+ );
10
+ export function writeReport(directory, report) {
11
+ mkdirSync(directory, { recursive: true });
12
+ writeFileSync(join(directory, 'summary.json'), `${JSON.stringify(report, null, 2)}\n`);
13
+ writeFileSync(join(directory, 'summary.md'), markdownSummary(report));
14
+ const rows = report.results
15
+ .map(
16
+ (r) =>
17
+ `<tr><td>${escape(r.id)}</td><td>${escape(r.status)}</td><td>${escape(r.reason)}</td><td>${((r.milliseconds ?? 0) / 1000).toFixed(2)}s</td></tr>`,
18
+ )
19
+ .join('');
20
+ const browserLinks = report.results
21
+ .filter(
22
+ (result) =>
23
+ ['e2e', 'visual'].includes(result.kind ?? result.id) &&
24
+ existsSync(join(directory, result.id, 'index.html')),
25
+ )
26
+ .map(
27
+ (result) =>
28
+ `<a href="${encodeURIComponent(result.id)}/index.html">${escape(result.id)} report</a>`,
29
+ )
30
+ .join(' &middot; ');
31
+ writeFileSync(
32
+ join(directory, 'index.html'),
33
+ `<!doctype html><html lang="en"><meta charset="utf-8"><meta name="viewport" content="width=device-width"><title>Repository checks</title><style>body{font:16px system-ui;max-width:1100px;margin:3rem auto;padding:0 1rem;color:#172033}table{width:100%;border-collapse:collapse}td,th{padding:.8rem;text-align:left;border-bottom:1px solid #ccd3df}code{overflow-wrap:anywhere}</style><h1>${report.complete ? 'Validation passed' : 'Validation incomplete or failed'}</h1><p>${escape(report.profile)} &middot; ${escape(report.groups.join(', '))}</p><p>Commit: <code>${escape(report.commit)}</code></p><p>Tooling: ${escape(report.version)}</p><table><thead><tr><th>Check</th><th>Result</th><th>Details</th><th>Duration</th></tr></thead><tbody>${rows}</tbody></table><p><a href="summary.json" download>Download JSON</a>${browserLinks ? ` &middot; ${browserLinks}` : ''}</p></html>`,
34
+ );
35
+ }
@@ -0,0 +1,76 @@
1
+ import { createReadStream, realpathSync, statSync } from 'node:fs';
2
+ import { createServer } from 'node:http';
3
+ import { extname, isAbsolute, relative, resolve } from 'node:path';
4
+ import { pathToFileURL } from 'node:url';
5
+
6
+ const types = {
7
+ '.html': 'text/html; charset=utf-8',
8
+ '.js': 'text/javascript; charset=utf-8',
9
+ '.mjs': 'text/javascript; charset=utf-8',
10
+ '.css': 'text/css; charset=utf-8',
11
+ '.json': 'application/json; charset=utf-8',
12
+ '.svg': 'image/svg+xml',
13
+ '.woff2': 'font/woff2',
14
+ '.woff': 'font/woff',
15
+ '.png': 'image/png',
16
+ '.webp': 'image/webp',
17
+ '.ico': 'image/x-icon',
18
+ '.wasm': 'application/wasm',
19
+ };
20
+ const contained = (root, target) => {
21
+ const path = relative(root, target);
22
+ return path !== '..' && !path.startsWith('../') && !path.startsWith('..\\') && !isAbsolute(path);
23
+ };
24
+
25
+ export function staticServer(directory) {
26
+ const root = realpathSync(directory);
27
+ return createServer((request, response) => {
28
+ if (!['GET', 'HEAD'].includes(request.method)) {
29
+ response.writeHead(405, { Allow: 'GET, HEAD' }).end();
30
+ return;
31
+ }
32
+ let path;
33
+ try {
34
+ path = decodeURIComponent(new URL(request.url ?? '/', 'http://localhost').pathname);
35
+ } catch {
36
+ response.writeHead(400).end();
37
+ return;
38
+ }
39
+ let target = resolve(root, '.' + path);
40
+ if (!contained(root, target)) {
41
+ response.writeHead(403).end();
42
+ return;
43
+ }
44
+ try {
45
+ if (statSync(target).isDirectory()) target = resolve(target, 'index.html');
46
+ target = realpathSync(target);
47
+ if (!contained(root, target)) {
48
+ response.writeHead(403).end();
49
+ return;
50
+ }
51
+ if (!statSync(target).isFile()) {
52
+ response.writeHead(404).end();
53
+ return;
54
+ }
55
+ } catch {
56
+ response.writeHead(404).end();
57
+ return;
58
+ }
59
+ response.writeHead(200, { 'content-type': types[extname(target)] ?? 'application/octet-stream' });
60
+ if (request.method === 'HEAD') response.end();
61
+ else createReadStream(target).on('error', () => response.destroy()).pipe(response);
62
+ });
63
+ }
64
+
65
+ if (process.argv[1] && import.meta.url === pathToFileURL(process.argv[1]).href) {
66
+ const [directory, port = '6217', required = 'index.html'] = process.argv.slice(2);
67
+ if (!directory || process.argv.length > 5 || !/^\d+$/.test(port) || Number(port) < 1 || Number(port) > 65535)
68
+ throw new Error('Usage: serve-static.mjs <directory> [port] [required-file]');
69
+ const root = realpathSync(directory);
70
+ const entry = realpathSync(resolve(root, required));
71
+ if (!contained(root, entry) || !statSync(entry).isFile())
72
+ throw new Error('Required build entry is outside the served directory or is not a file');
73
+ staticServer(root).listen(Number(port), '127.0.0.1', () => {
74
+ console.log(`Serving ${root} on http://127.0.0.1:${port}`);
75
+ });
76
+ }
@@ -0,0 +1,241 @@
1
+ import { chmodSync, existsSync, mkdirSync, readFileSync, writeFileSync } from 'node:fs';
2
+ import { dirname, join } from 'node:path';
3
+ import { inside, loadConfig, validateConfig } from './config.mjs';
4
+ import { builtins, plan } from './graph.mjs';
5
+ import { executable, packageManifest } from './execute.mjs';
6
+ import { git } from './git.mjs';
7
+ import { repoStandardFindings } from './repo-standard.mjs';
8
+
9
+ const manifest = JSON.parse(readFileSync(new URL('../package.json', import.meta.url), 'utf8'));
10
+ const readJSON = (path) => JSON.parse(readFileSync(path, 'utf8'));
11
+ const json = (value) => JSON.stringify(value, null, 2) + '\n';
12
+
13
+ export function starterConfig({ preset = 'react-vite', app = 'frontend', scripts = {} } = {}) {
14
+ if (!['react-vite', 'workspace'].includes(preset))
15
+ throw new Error('Preset must be react-vite or workspace');
16
+ if (!/^[\w-]+(?:\/[\w-]+)*$/.test(app))
17
+ throw new Error('App must be a repository-relative directory');
18
+ const workspace = preset === 'workspace';
19
+ const cwd = workspace ? app : '.';
20
+ const enabled = ['format', 'lint', 'types', 'unit', 'build'];
21
+ const checks = Object.fromEntries(
22
+ Object.keys(builtins).map((id) => [id, enabled.includes(id) ? {} : false]),
23
+ );
24
+ const adapters = { lint: 'lint', types: 'typecheck', unit: 'test:coverage', build: 'build' };
25
+ for (const id of ['lint', 'types', 'unit', 'build']) {
26
+ checks[id].cwd = cwd;
27
+ if (workspace) checks[id].workspaces = ['app'];
28
+ if (scripts[adapters[id]]) checks[id].command = ['npm', 'run', adapters[id]];
29
+ }
30
+ const config = {
31
+ $schema: './node_modules/@dcaldeira/tooling/config.schema.json',
32
+ schemaVersion: 1,
33
+ execution: { concurrency: 2 },
34
+ ...(workspace
35
+ ? {
36
+ paths: { app: [`${app}/src/**`, 'shared/src/**'] },
37
+ workspaces: {
38
+ app: { paths: [`${app}/**`], dependsOn: ['shared'] },
39
+ shared: { paths: ['shared/**'] },
40
+ },
41
+ }
42
+ : {}),
43
+ checks,
44
+ };
45
+ validateConfig(config);
46
+ return config;
47
+ }
48
+
49
+ export function initialize(root, { preset = 'react-vite', app = 'frontend', toolingSha } = {}) {
50
+ if (toolingSha && !/^[a-f\d]{40}$/.test(toolingSha))
51
+ throw new Error('--tooling-sha must be a full 40-character commit SHA');
52
+ const packagePath = join(root, 'package.json');
53
+ const pkg = readJSON(packagePath);
54
+ const appPackage =
55
+ preset === 'workspace' ? readJSON(join(inside(root, app), 'package.json')) : pkg;
56
+ const config = starterConfig({ preset, app, scripts: appPackage.scripts });
57
+ const aliases = {
58
+ 'check:dev': 'tooling --profile=dev --changed',
59
+ 'check:push': 'tooling --profile=push --changed --bail',
60
+ 'ci:local': 'tooling --profile=ci --all',
61
+ };
62
+ for (const [key, value] of Object.entries(aliases)) {
63
+ if (pkg.scripts?.[key] && pkg.scripts[key] !== value)
64
+ throw new Error(`Existing script ${key}; adapt it before initializing`);
65
+ }
66
+ const files = new Map([['tooling.config.json', json(config)]]);
67
+ const template = (name) =>
68
+ readFileSync(new URL(`../templates/${name}`, import.meta.url), 'utf8').replaceAll(
69
+ 'REPLACE_WITH_TOOLING_COMMIT_SHA',
70
+ toolingSha ?? 'REPLACE_WITH_TOOLING_COMMIT_SHA',
71
+ );
72
+ files.set('.github/workflows/ci.yml', template('ci.yml'));
73
+ files.set('.github/workflows/dependabot-merge.yml', template('dependabot-merge.yml'));
74
+ files.set('.github/dependabot.yml', template('dependabot.yml'));
75
+ files.set('.githooks/pre-push', template('pre-push'));
76
+ files.set(
77
+ 'prettier.config.mjs',
78
+ "export { default } from '@dcaldeira/tooling/configs/prettier.mjs';\n",
79
+ );
80
+ files.set('.nvmrc', '22.23.1\n');
81
+ // Preserve existing formatter configuration and Node version files.
82
+ if (
83
+ [
84
+ 'prettier.config.mjs',
85
+ 'prettier.config.js',
86
+ 'prettier.config.cjs',
87
+ '.prettierrc',
88
+ '.prettierrc.json',
89
+ '.prettierrc.yml',
90
+ '.prettierrc.yaml',
91
+ '.prettierrc.js',
92
+ '.prettierrc.cjs',
93
+ '.prettierrc.toml',
94
+ ].some((name) => existsSync(join(root, name))) ||
95
+ pkg.prettier
96
+ )
97
+ files.delete('prettier.config.mjs');
98
+ if (files.has('prettier.config.mjs'))
99
+ files.set(
100
+ '.github/workflows/ci.yml',
101
+ files
102
+ .get('.github/workflows/ci.yml')
103
+ .replace(' with:\n', ' with:\n lightweight-docs: true\n'),
104
+ );
105
+ if (existsSync(join(root, '.nvmrc'))) files.delete('.nvmrc');
106
+ for (const path of files.keys())
107
+ if (existsSync(join(root, path))) throw new Error(`Refusing to overwrite ${path}`);
108
+ for (const name of ['.gitignore', '.prettierignore']) {
109
+ const path = join(root, name);
110
+ let text = existsSync(path) ? readFileSync(path, 'utf8') : '';
111
+ for (const entry of [
112
+ 'node_modules/',
113
+ 'debug.log',
114
+ '.tooling/',
115
+ 'dist/',
116
+ 'coverage/',
117
+ 'playwright-report/',
118
+ 'test-results/',
119
+ '*.tsbuildinfo',
120
+ ]) {
121
+ if (!text.split(/\r?\n/).includes(entry))
122
+ text += `${text && !text.endsWith('\n') ? '\n' : ''}${entry}\n`;
123
+ }
124
+ files.set(name, text);
125
+ }
126
+ pkg.scripts = { ...pkg.scripts, ...aliases };
127
+ pkg.devDependencies = { ...pkg.devDependencies, [manifest.name]: manifest.version };
128
+ files.set('package.json', json(pkg));
129
+ for (const [path, text] of files) {
130
+ const target = join(root, path);
131
+ mkdirSync(dirname(target), { recursive: true });
132
+ writeFileSync(target, text);
133
+ }
134
+ chmodSync(join(root, '.githooks/pre-push'), 0o755);
135
+ return [...files.keys()];
136
+ }
137
+
138
+ export function diagnose(root, configPath) {
139
+ const findings = [];
140
+ const add = (status, message) => findings.push({ status, message });
141
+ let config;
142
+ try {
143
+ config = loadConfig(root, configPath).config;
144
+ add('passed', 'Configuration is valid');
145
+ } catch (error) {
146
+ add('failed', error.message);
147
+ return findings;
148
+ }
149
+ let selection;
150
+ try {
151
+ selection = plan(config, { profile: 'ci' });
152
+ add('passed', 'Check dependencies form a valid graph');
153
+ } catch (error) {
154
+ add('failed', error.message);
155
+ return findings;
156
+ }
157
+ if (!existsSync(join(root, 'package-lock.json')))
158
+ add('failed', 'Run npm install and commit package-lock.json');
159
+ if (!existsSync(join(root, '.nvmrc'))) add('failed', 'Add .nvmrc for the shared workflow');
160
+ try {
161
+ git(root, 'rev-parse', '--verify', 'HEAD');
162
+ if (git(root, 'config', '--get', 'core.hooksPath') !== '.githooks')
163
+ add('failed', 'Enable the hook: git config core.hooksPath .githooks');
164
+ } catch {
165
+ add('failed', 'Initialize Git, commit the project and enable .githooks');
166
+ }
167
+ for (const check of selection.checks) {
168
+ const cwd = inside(root, check.cwd ?? '.');
169
+ if (!existsSync(cwd)) {
170
+ add('failed', `${check.id}: missing directory ${check.cwd}`);
171
+ continue;
172
+ }
173
+ const commands = [check.command, check.devCommand, check.devAllCommand].filter(Array.isArray);
174
+ const tools = new Set([...commands.map((command) => command[0]), ...(check.tools ?? [])]);
175
+ for (const tool of tools)
176
+ if (!executable(cwd, tool))
177
+ add('failed', `${check.id}: missing ${tool} in ${check.cwd ?? '.'}`);
178
+ for (const command of commands) {
179
+ if (
180
+ command[0] === 'node' &&
181
+ command[1]?.endsWith('.mjs') &&
182
+ !existsSync(join(cwd, command[1])) &&
183
+ !existsSync(command[1])
184
+ )
185
+ add('failed', `${check.id}: missing script ${command[1]}`);
186
+ if (command[0] === 'npm' && command[1] === 'run') {
187
+ const pkgPath = join(cwd, 'package.json');
188
+ if (!existsSync(pkgPath) || !readJSON(pkgPath).scripts?.[command[2]])
189
+ add('failed', `${check.id}: missing npm script ${command[2]}`);
190
+ }
191
+ }
192
+ if (check.platforms && !check.platforms.includes(process.platform))
193
+ add('notice', `${check.id}: use ${check.platforms.join('/')} for canonical validation`);
194
+ if ((check.kind ?? check.id) === 'styles' && !packageManifest(root, 'postcss-scss'))
195
+ add('failed', 'styles: install postcss-scss and its postcss peer at the consumer root');
196
+ if (
197
+ ['architecture', 'dependency-consistency'].includes(check.kind ?? check.id) &&
198
+ !packageManifest(cwd, 'typescript')
199
+ )
200
+ add('failed', `${check.id}: install TypeScript for import analysis`);
201
+ if ((check.kind ?? check.id) === 'a11y') {
202
+ if (!config.a11y?.routes?.length)
203
+ add('failed', `${check.id}: configure a11y.baseURL and routes`);
204
+ for (const name of ['@playwright/test', '@axe-core/playwright'])
205
+ if (!packageManifest(cwd, name)) add('failed', `${check.id}: install ${name}`);
206
+ }
207
+ if (
208
+ (check.kind ?? check.id) === 'unit' &&
209
+ commands.some((command) => command.includes('--coverage')) &&
210
+ !packageManifest(cwd, '@vitest/coverage-v8')
211
+ )
212
+ add('failed', 'unit: install @vitest/coverage-v8 matching your Vitest version');
213
+ }
214
+ if (config.repoStandard) findings.push(...repoStandardFindings(root));
215
+ for (const name of ['ci.yml', 'dependabot-merge.yml']) {
216
+ const path = join(root, '.github/workflows', name);
217
+ if (!existsSync(path)) add('failed', `Missing .github/workflows/${name}`);
218
+ else if (readFileSync(path, 'utf8').includes('REPLACE_WITH_TOOLING_COMMIT_SHA'))
219
+ add('failed', `Pin .github/workflows/${name} to the tooling commit SHA`);
220
+ }
221
+ return findings;
222
+ }
223
+
224
+ export async function setupCommand(command, root, options) {
225
+ if (command === 'init') {
226
+ const paths = initialize(root, {
227
+ preset: options.preset,
228
+ app: options.app,
229
+ toolingSha: options['tooling-sha'],
230
+ });
231
+ console.log(
232
+ `Created/adapted: ${paths.join(', ')}\nRun npm install, install the peer tools for your enabled checks, then tooling doctor.\nEnable the hook: git config core.hooksPath .githooks\nPin the workflow SHA if you did not pass --tooling-sha.`,
233
+ );
234
+ return 0;
235
+ }
236
+ const findings = options['repo-standard']
237
+ ? repoStandardFindings(root)
238
+ : diagnose(root, options.config);
239
+ for (const finding of findings) console.log(`${finding.status}: ${finding.message}`);
240
+ return findings.some((finding) => finding.status === 'failed') ? 1 : 0;
241
+ }
@@ -0,0 +1,112 @@
1
+ import { appendFileSync, existsSync, readFileSync, writeFileSync } from 'node:fs';
2
+ import { join } from 'node:path';
3
+ import { pathToFileURL } from 'node:url';
4
+
5
+ const text = (value) =>
6
+ String(value ?? '')
7
+ .replace(/[\r\n]+/g, ' ')
8
+ .replaceAll('&', '&amp;')
9
+ .replaceAll('<', '&lt;')
10
+ .replaceAll('>', '&gt;')
11
+ .replaceAll('|', '&#124;')
12
+ .replaceAll('`', '&#96;')
13
+ .replace(/([\[\]()*_!\\])/g, '\\$1')
14
+ .slice(0, 600);
15
+ const seconds = (value) => `${((value ?? 0) / 1000).toFixed(2)}s`;
16
+
17
+ export function markdownSummary(report, { artifactURL } = {}) {
18
+ const lines = [
19
+ `## Validation ${report.complete ? 'passed' : 'incomplete or failed'}`,
20
+ '',
21
+ `Profile: **${text(report.profile)}** · Scope: ${report.groups.map(text).join(', ')} · Duration: ${seconds(report.wallMilliseconds)}`,
22
+ `Selected checks: **${report.results.length}** · Cache hits: **${report.results.filter((check) => check.cached).length}**`,
23
+ '',
24
+ ];
25
+ if (report.affectedWorkspaces?.length)
26
+ lines.push(`Affected workspaces: ${report.affectedWorkspaces.map(text).join(', ')}`, '');
27
+ lines.push('| Check | Result | Reused | Time | Details |', '| --- | --- | --- | --- | --- |');
28
+ for (const check of report.results)
29
+ lines.push(
30
+ `| ${text(check.id)} | ${text(check.status)} | ${check.cached ? 'yes' : 'no'} | ${seconds(check.milliseconds)} | ${text(check.reason)} |`,
31
+ );
32
+ const metrics = report.metrics ?? {};
33
+ if (metrics.bundle)
34
+ lines.push(
35
+ '',
36
+ `Initial JavaScript: **${Number(metrics.bundle.initialKB).toFixed(1)} KB gzip**${report.performance?.bundleDeltaKB == null ? '' : ` (${report.performance.bundleDeltaKB >= 0 ? '+' : ''}${report.performance.bundleDeltaKB.toFixed(1)} KB against the previous comparable run)`}.`,
37
+ );
38
+ if (metrics.coverage)
39
+ lines.push(
40
+ '',
41
+ `Coverage: ${Object.entries(metrics.coverage)
42
+ .map(([key, value]) => `${text(key)} **${value.toFixed(1)}%**`)
43
+ .join(' · ')}.`,
44
+ );
45
+ if (metrics.browser)
46
+ lines.push(
47
+ '',
48
+ `Browser tests: ${metrics.browser.passed} passed · ${metrics.browser.failed} failed · ${metrics.browser.flaky} flaky · ${metrics.browser.skipped} skipped.`,
49
+ );
50
+ if (metrics.a11y)
51
+ lines.push(
52
+ '',
53
+ `Accessibility: ${metrics.a11y.pages} rendered pages · ${metrics.a11y.violations} blocking violations · ${metrics.a11y.errors} scan errors.`,
54
+ );
55
+ if (metrics.architecture)
56
+ lines.push(
57
+ '',
58
+ `Architecture: ${metrics.architecture.files} source files · ${metrics.architecture.issues} violations.`,
59
+ );
60
+ if (metrics.dependencies)
61
+ lines.push(
62
+ '',
63
+ `Dependencies: ${metrics.dependencies.packages} manifests · ${metrics.dependencies.issues} errors · ${metrics.dependencies.duplicates} duplicate-version notices.`,
64
+ );
65
+ if (report.performance?.previousMs !== null && report.performance?.previousMs !== undefined)
66
+ lines.push(
67
+ '',
68
+ `Previous comparable median: ${seconds(report.performance.previousMs)}. Current change: ${report.performance.deltaMs >= 0 ? '+' : ''}${seconds(report.performance.deltaMs)}.`,
69
+ );
70
+ for (const regression of report.performance?.regressions ?? [])
71
+ lines.push(
72
+ '',
73
+ `Slower check: **${text(regression.id)}**, ${seconds(regression.currentMs)} against ${seconds(regression.previousMs)} median.`,
74
+ );
75
+ if (metrics.slowTests?.length) {
76
+ lines.push('', '### Slowest reported tests', '', '| Test | Time |', '| --- | --- |');
77
+ for (const test of metrics.slowTests.slice(0, 10))
78
+ lines.push(`| ${text(test.name)} | ${seconds(test.milliseconds)} |`);
79
+ }
80
+ const visual = report.results.filter(
81
+ (check) =>
82
+ (check.kind ?? check.id) === 'visual' && !['excluded', 'unavailable'].includes(check.status),
83
+ );
84
+ if (visual.length)
85
+ lines.push(
86
+ '',
87
+ `Visual results: ${visual.map((check) => `${text(check.id)} (${text(check.status)})`).join(', ')}. Expected, actual and diff images are in the browser reports.`,
88
+ );
89
+ if (artifactURL) {
90
+ const url = new URL(artifactURL);
91
+ if (!['https:', 'http:'].includes(url.protocol))
92
+ throw new Error('Artifact URL must use HTTP or HTTPS');
93
+ lines.push('', `[Download validation reports and visual differences](<${url.href}>)`);
94
+ }
95
+ lines.push('', `Commit: ${text(report.commit)} · Tooling: ${text(report.version)}`, '');
96
+ return lines.join('\n');
97
+ }
98
+
99
+ if (process.argv[1] && import.meta.url === pathToFileURL(process.argv[1]).href) {
100
+ const directory = process.argv[2] ?? '.tooling/report';
101
+ const path = join(directory, 'summary.json');
102
+ const markdown = existsSync(path)
103
+ ? markdownSummary(JSON.parse(readFileSync(path, 'utf8')), {
104
+ artifactURL: process.env.TOOLING_ARTIFACT_URL,
105
+ })
106
+ : process.env.TOOLING_EMPTY_PLAN === 'true'
107
+ ? '## Validation passed\n\nNo checks apply to this change. Installation and validation were skipped.\n'
108
+ : '## Validation stopped before a report was produced\n\nSee the failed workflow step for the prerequisite or planning error.\n';
109
+ if (existsSync(directory)) writeFileSync(join(directory, 'summary.md'), markdown);
110
+ if (process.env.GITHUB_STEP_SUMMARY) appendFileSync(process.env.GITHUB_STEP_SUMMARY, markdown);
111
+ else console.log(markdown);
112
+ }
@@ -0,0 +1,82 @@
1
+ import { watch } from 'node:fs';
2
+ import { execFileSync } from 'node:child_process';
3
+ import { relative, resolve } from 'node:path';
4
+
5
+ export function relevantChanges(root, files, inputs = []) {
6
+ const declared = new Set(
7
+ inputs.map((file) => relative(root, resolve(root, file)).replaceAll('\\', '/')),
8
+ );
9
+ const candidates = [...new Set(files.map((file) => file.replaceAll('\\', '/')))].filter(
10
+ (file) => {
11
+ if (declared.has(file)) return true;
12
+ if (file.startsWith('.git/')) return file === '.git/HEAD' || file.startsWith('.git/refs/');
13
+ return !file.split('/').some((part) => ['node_modules', '.tooling'].includes(part));
14
+ },
15
+ );
16
+ if (!candidates.length) return [];
17
+ let ignored = '';
18
+ try {
19
+ ignored = execFileSync('git', ['check-ignore', '-z', '--stdin'], {
20
+ cwd: root,
21
+ input: candidates.join('\0') + '\0',
22
+ encoding: 'utf8',
23
+ stdio: ['pipe', 'pipe', 'pipe'],
24
+ });
25
+ } catch (error) {
26
+ if (error.status !== 1) throw error;
27
+ ignored = error.stdout ?? '';
28
+ }
29
+ const excluded = new Set(ignored.split('\0'));
30
+ return candidates.filter(
31
+ (file) => declared.has(file) || file.startsWith('.git/') || !excluded.has(file),
32
+ );
33
+ }
34
+
35
+ // Only validate after filesystem events; snapshots remain authoritative inside each validation.
36
+ export function watchChanges(root, run, { inputs = () => [], signal, debounce = 350 } = {}) {
37
+ return new Promise((resolveDone, reject) => {
38
+ let timer,
39
+ active,
40
+ closed = false;
41
+ const pending = new Set();
42
+ const finish = (error) => {
43
+ if (closed) return;
44
+ closed = true;
45
+ clearTimeout(timer);
46
+ watcher.close();
47
+ signal?.removeEventListener('abort', abort);
48
+ Promise.resolve(active).then(() => (error ? reject(error) : resolveDone()), reject);
49
+ };
50
+ const schedule = () => {
51
+ clearTimeout(timer);
52
+ if (!closed) timer = setTimeout(drain, debounce);
53
+ };
54
+ const drain = async () => {
55
+ if (closed || active) return;
56
+ try {
57
+ const files = [...pending];
58
+ pending.clear();
59
+ if (!files.includes('*') && !relevantChanges(root, files, inputs()).length) return;
60
+ active = Promise.resolve().then(run);
61
+ await active;
62
+ } catch (error) {
63
+ finish(error);
64
+ } finally {
65
+ active = undefined;
66
+ if (pending.size) schedule();
67
+ }
68
+ };
69
+ const watcher = watch(root, { recursive: true }, (_event, filename) => {
70
+ pending.add(filename?.toString() ?? '*');
71
+ schedule();
72
+ });
73
+ watcher.on('error', finish);
74
+ const abort = () => finish();
75
+ signal?.addEventListener('abort', abort, { once: true });
76
+ if (signal?.aborted) finish();
77
+ else {
78
+ pending.add('*');
79
+ schedule();
80
+ }
81
+ });
82
+ }
@@ -0,0 +1,25 @@
1
+ name: CI
2
+ on:
3
+ pull_request:
4
+ types: [opened, synchronize, reopened, ready_for_review, edited]
5
+ schedule:
6
+ - cron: '0 8 * * 1'
7
+ workflow_dispatch:
8
+ inputs:
9
+ pull-request-number:
10
+ description: Release PR to route after trusted generation
11
+ type: string
12
+ default: ''
13
+ permissions:
14
+ contents: read
15
+ pull-requests: read
16
+ actions: read
17
+ concurrency:
18
+ group: ci-${{ github.event.pull_request.number || inputs.pull-request-number || github.ref }}
19
+ cancel-in-progress: true
20
+ jobs:
21
+ CI:
22
+ uses: DuarteCaldeira/tooling/.github/workflows/ci.yml@REPLACE_WITH_TOOLING_COMMIT_SHA
23
+ with:
24
+ tooling-sha: REPLACE_WITH_TOOLING_COMMIT_SHA
25
+ pull-request-number: ${{ inputs.pull-request-number || '' }}