wp-shakedown 0.0.0-stage → 0.1.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.
- package/LICENSE +340 -0
- package/README.md +62 -2
- package/dist/baseline.d.ts +6 -0
- package/dist/baseline.js +41 -0
- package/dist/cli.d.ts +2 -0
- package/dist/cli.js +139 -0
- package/dist/diff.d.ts +7 -0
- package/dist/diff.js +24 -0
- package/dist/engines/config.d.ts +3 -0
- package/dist/engines/config.js +133 -0
- package/dist/engines/eslint.d.ts +8 -0
- package/dist/engines/eslint.js +96 -0
- package/dist/engines/index.d.ts +2 -0
- package/dist/engines/index.js +12 -0
- package/dist/engines/integrity.d.ts +2 -0
- package/dist/engines/integrity.js +108 -0
- package/dist/engines/php-compat.d.ts +2 -0
- package/dist/engines/php-compat.js +26 -0
- package/dist/engines/php-lint.d.ts +6 -0
- package/dist/engines/php-lint.js +41 -0
- package/dist/engines/phpstan.d.ts +11 -0
- package/dist/engines/phpstan.js +102 -0
- package/dist/engines/stylelint.d.ts +4 -0
- package/dist/engines/stylelint.js +63 -0
- package/dist/engines/updates.d.ts +4 -0
- package/dist/engines/updates.js +72 -0
- package/dist/engines/vulnerabilities.d.ts +22 -0
- package/dist/engines/vulnerabilities.js +128 -0
- package/dist/engines/wp-json.d.ts +18 -0
- package/dist/engines/wp-json.js +133 -0
- package/dist/engines/wpcs.d.ts +7 -0
- package/dist/engines/wpcs.js +60 -0
- package/dist/exec.d.ts +12 -0
- package/dist/exec.js +19 -0
- package/dist/fingerprint.d.ts +10 -0
- package/dist/fingerprint.js +29 -0
- package/dist/health/install.d.ts +16 -0
- package/dist/health/install.js +68 -0
- package/dist/home.d.ts +2 -0
- package/dist/home.js +6 -0
- package/dist/index.d.ts +38 -0
- package/dist/index.js +32 -0
- package/dist/js/files.d.ts +4 -0
- package/dist/js/files.js +47 -0
- package/dist/js/tools.d.ts +3 -0
- package/dist/js/tools.js +67 -0
- package/dist/mcp/server.d.ts +9 -0
- package/dist/mcp/server.js +91 -0
- package/dist/mcp/tools.d.ts +26 -0
- package/dist/mcp/tools.js +149 -0
- package/dist/net.d.ts +18 -0
- package/dist/net.js +68 -0
- package/dist/php/files.d.ts +3 -0
- package/dist/php/files.js +53 -0
- package/dist/php/php.d.ts +4 -0
- package/dist/php/php.js +25 -0
- package/dist/php/phpcs.d.ts +25 -0
- package/dist/php/phpcs.js +55 -0
- package/dist/php/tools.d.ts +3 -0
- package/dist/php/tools.js +66 -0
- package/dist/progress.d.ts +3 -0
- package/dist/progress.js +13 -0
- package/dist/report/escape.d.ts +1 -0
- package/dist/report/escape.js +4 -0
- package/dist/report/html.d.ts +2 -0
- package/dist/report/html.js +100 -0
- package/dist/report/json.d.ts +2 -0
- package/dist/report/json.js +3 -0
- package/dist/report/markdown.d.ts +5 -0
- package/dist/report/markdown.js +92 -0
- package/dist/report/sarif.d.ts +2 -0
- package/dist/report/sarif.js +44 -0
- package/dist/report/write.d.ts +9 -0
- package/dist/report/write.js +48 -0
- package/dist/runner.d.ts +11 -0
- package/dist/runner.js +152 -0
- package/dist/session.d.ts +19 -0
- package/dist/session.js +31 -0
- package/dist/target.d.ts +5 -0
- package/dist/target.js +114 -0
- package/dist/types.d.ts +135 -0
- package/dist/types.js +4 -0
- package/dist/ui/server.d.ts +13 -0
- package/dist/ui/server.js +295 -0
- package/dist/version.d.ts +1 -0
- package/dist/version.js +3 -0
- package/dist/versions.d.ts +9 -0
- package/dist/versions.js +35 -0
- package/js-tools/eslint.config.mjs +19 -0
- package/js-tools/package-lock.json +7004 -0
- package/js-tools/package.json +13 -0
- package/js-tools/stylelint.config.mjs +4 -0
- package/package.json +57 -4
- package/php-tools/composer.json +40 -0
- package/php-tools/composer.lock +868 -0
- package/ui/dist/assets/geist-cyrillic-ext-wght-normal-DjL33-gN.woff2 +0 -0
- package/ui/dist/assets/geist-cyrillic-wght-normal-BEAKL7Jp.woff2 +0 -0
- package/ui/dist/assets/geist-latin-ext-wght-normal-DC-KSUi6.woff2 +0 -0
- package/ui/dist/assets/geist-latin-wght-normal-BgDaEnEv.woff2 +0 -0
- package/ui/dist/assets/geist-vietnamese-wght-normal-6IgcOCM7.woff2 +0 -0
- package/ui/dist/assets/index-7zN46ssH.js +54 -0
- package/ui/dist/assets/index-B1axZya5.css +2 -0
- package/ui/dist/index.html +14 -0
|
@@ -0,0 +1,55 @@
|
|
|
1
|
+
import { statSync } from 'node:fs';
|
|
2
|
+
import path from 'node:path';
|
|
3
|
+
import { exec } from '../exec.js';
|
|
4
|
+
import { phpBinary, phpVersion } from './php.js';
|
|
5
|
+
import { phpTools } from './tools.js';
|
|
6
|
+
export function parsePhpcs(json) {
|
|
7
|
+
const bad = new Error('PHPCS returned output that is not JSON.');
|
|
8
|
+
let data;
|
|
9
|
+
try {
|
|
10
|
+
data = JSON.parse(json);
|
|
11
|
+
}
|
|
12
|
+
catch {
|
|
13
|
+
throw bad;
|
|
14
|
+
}
|
|
15
|
+
if (!data || typeof data.files !== 'object' || data.files === null)
|
|
16
|
+
throw bad;
|
|
17
|
+
const out = [];
|
|
18
|
+
for (const [file, f] of Object.entries(data.files)) {
|
|
19
|
+
for (const m of f.messages ?? []) {
|
|
20
|
+
out.push({ file, line: m.line, column: m.column, source: m.source, message: m.message, type: m.type, fixable: m.fixable });
|
|
21
|
+
}
|
|
22
|
+
}
|
|
23
|
+
return out;
|
|
24
|
+
}
|
|
25
|
+
/**
|
|
26
|
+
* PHPCS matches --ignore against the absolute path, so a plain vendor pattern
|
|
27
|
+
* would drop every file of a target that itself sits below a vendor folder.
|
|
28
|
+
* The pattern is a regular expression anchored to the target. PHPCS turns a
|
|
29
|
+
* star into ".*" and splits on commas, so neither may appear unescaped.
|
|
30
|
+
*/
|
|
31
|
+
export function ignorePattern(base) {
|
|
32
|
+
const escaped = base.split(path.sep).join('/').replace(/[.+?^${}()|[\]\\]/g, '\\$&').replace(/,/g, '\\,');
|
|
33
|
+
return `^${escaped}/(.+/)?(vendor|node_modules)/`;
|
|
34
|
+
}
|
|
35
|
+
const firstLine = (s) => s.split('\n').map((l) => l.trim()).find(Boolean) ?? '';
|
|
36
|
+
export async function runPhpcs(opts) {
|
|
37
|
+
await phpVersion();
|
|
38
|
+
const tools = await phpTools(opts.note);
|
|
39
|
+
const isFile = statSync(opts.target.path).isFile();
|
|
40
|
+
const base = isFile ? path.dirname(opts.target.path) : opts.target.path;
|
|
41
|
+
const args = [
|
|
42
|
+
'-d', 'memory_limit=1G',
|
|
43
|
+
path.join(tools, 'vendor', 'bin', 'phpcs'),
|
|
44
|
+
'--report=json', '-q', '--no-colors', '--extensions=php',
|
|
45
|
+
...(isFile ? [] : [`--ignore=${ignorePattern(base)}`]),
|
|
46
|
+
`--basepath=${base}`,
|
|
47
|
+
`--standard=${typeof opts.standard === 'function' ? opts.standard(tools) : opts.standard}`,
|
|
48
|
+
...(opts.extra ?? []),
|
|
49
|
+
opts.target.path,
|
|
50
|
+
];
|
|
51
|
+
const r = await exec(phpBinary(), args, { cwd: base, ...(opts.signal ? { signal: opts.signal } : {}) });
|
|
52
|
+
if (r.code > 2)
|
|
53
|
+
throw new Error(`PHPCS stopped: ${firstLine(r.stdout) || firstLine(r.stderr)}`);
|
|
54
|
+
return parsePhpcs(r.stdout);
|
|
55
|
+
}
|
|
@@ -0,0 +1,66 @@
|
|
|
1
|
+
import { createHash } from 'node:crypto';
|
|
2
|
+
import { copyFileSync, existsSync, mkdirSync, readFileSync, renameSync, rmSync } from 'node:fs';
|
|
3
|
+
import path from 'node:path';
|
|
4
|
+
import { fileURLToPath } from 'node:url';
|
|
5
|
+
import { exec, NotFound } from '../exec.js';
|
|
6
|
+
import { home } from '../home.js';
|
|
7
|
+
import { EngineSkipped } from '../types.js';
|
|
8
|
+
import { phpVersion } from './php.js';
|
|
9
|
+
// Resolves to the package root from both src/php and dist/php.
|
|
10
|
+
const bundled = fileURLToPath(new URL('../../php-tools/', import.meta.url));
|
|
11
|
+
let cached;
|
|
12
|
+
export function resetToolsCache() {
|
|
13
|
+
cached = undefined;
|
|
14
|
+
}
|
|
15
|
+
const lastLine = (s) => s.split('\n').map((l) => l.trim()).filter(Boolean).pop() ?? '';
|
|
16
|
+
async function install(note) {
|
|
17
|
+
const hash = createHash('sha256').update(readFileSync(path.join(bundled, 'composer.lock'))).digest('hex').slice(0, 8);
|
|
18
|
+
const dir = path.join(home(), 'tools', `php-${hash}`);
|
|
19
|
+
if (existsSync(path.join(dir, 'vendor', 'bin', 'phpcs')))
|
|
20
|
+
return dir;
|
|
21
|
+
await phpVersion();
|
|
22
|
+
const composer = process.env.WP_SHAKEDOWN_COMPOSER || 'composer';
|
|
23
|
+
const noComposer = new EngineSkipped('Composer is not installed. wp-shakedown uses it once to fetch PHPCS and the WordPress standards. Get it from https://getcomposer.org or set WP_SHAKEDOWN_COMPOSER to its path.');
|
|
24
|
+
try {
|
|
25
|
+
if ((await exec(composer, ['--version'])).code !== 0)
|
|
26
|
+
throw noComposer;
|
|
27
|
+
}
|
|
28
|
+
catch (err) {
|
|
29
|
+
throw err instanceof NotFound ? noComposer : err;
|
|
30
|
+
}
|
|
31
|
+
note('Installing the PHP tools. This happens once.');
|
|
32
|
+
const tmp = `${dir}.tmp-${process.pid}`;
|
|
33
|
+
rmSync(tmp, { recursive: true, force: true });
|
|
34
|
+
mkdirSync(tmp, { recursive: true });
|
|
35
|
+
for (const f of ['composer.json', 'composer.lock'])
|
|
36
|
+
copyFileSync(path.join(bundled, f), path.join(tmp, f));
|
|
37
|
+
// shortcut: composer runs without a shell, so composer.bat on Windows is not found. Spawn through a shell there when Windows support is tested.
|
|
38
|
+
const r = await exec(composer, ['install', '--no-dev', '--no-interaction', '--no-progress', '--working-dir', tmp]);
|
|
39
|
+
if (r.code !== 0) {
|
|
40
|
+
rmSync(tmp, { recursive: true, force: true });
|
|
41
|
+
throw new Error(`Composer could not install the PHP tools: ${lastLine(r.stderr) || lastLine(r.stdout)}`);
|
|
42
|
+
}
|
|
43
|
+
try {
|
|
44
|
+
renameSync(tmp, dir);
|
|
45
|
+
}
|
|
46
|
+
catch {
|
|
47
|
+
// Another process installed the tools first.
|
|
48
|
+
rmSync(tmp, { recursive: true, force: true });
|
|
49
|
+
}
|
|
50
|
+
if (!existsSync(path.join(dir, 'vendor', 'bin', 'phpcs'))) {
|
|
51
|
+
throw new Error(`Composer finished, but PHPCS is not in "${dir}".`);
|
|
52
|
+
}
|
|
53
|
+
return dir;
|
|
54
|
+
}
|
|
55
|
+
/** The folder that holds vendor/bin/phpcs. Installs it on first use. */
|
|
56
|
+
export function phpTools(note) {
|
|
57
|
+
if (!cached) {
|
|
58
|
+
const p = install(note);
|
|
59
|
+
cached = p;
|
|
60
|
+
p.catch(() => {
|
|
61
|
+
if (cached === p)
|
|
62
|
+
cached = undefined;
|
|
63
|
+
});
|
|
64
|
+
}
|
|
65
|
+
return cached;
|
|
66
|
+
}
|
package/dist/progress.js
ADDED
|
@@ -0,0 +1,13 @@
|
|
|
1
|
+
/** One line of progress for the terminal, or undefined when the event needs none. */
|
|
2
|
+
export function progressLine(e) {
|
|
3
|
+
if (e.type === 'engine:note')
|
|
4
|
+
return ` ${e.engine}${e.unit ? ' ' + e.unit : ''}: ${e.message}`;
|
|
5
|
+
if (e.type !== 'engine:end')
|
|
6
|
+
return undefined;
|
|
7
|
+
const r = e.run;
|
|
8
|
+
const who = `${r.engine}${r.unit ? ' ' + r.unit : ''}`;
|
|
9
|
+
if (r.status === 'ok') {
|
|
10
|
+
return `ok ${who}: ${r.findings} ${r.findings === 1 ? 'finding' : 'findings'}, ${(r.durationMs / 1000).toFixed(1)}s`;
|
|
11
|
+
}
|
|
12
|
+
return `${r.status} ${who}: ${r.reason}`;
|
|
13
|
+
}
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
export declare function escapeHtml(s: string): string;
|
|
@@ -0,0 +1,100 @@
|
|
|
1
|
+
import { escapeHtml as e } from './escape.js';
|
|
2
|
+
import { groupName, noEngineLine, summaryLine } from './markdown.js';
|
|
3
|
+
const STYLE = `
|
|
4
|
+
:root { color-scheme: light dark; --bg: #fff; --fg: #1d2327; --muted: #646970; --line: #dcdcde; --accent: #2271b1; }
|
|
5
|
+
@media (prefers-color-scheme: dark) { :root { --bg: #14181c; --fg: #e4e7ea; --muted: #9aa3ab; --line: #333a41; --accent: #72aee6; } }
|
|
6
|
+
body { font: 16px/1.5 system-ui, -apple-system, "Segoe UI", Roboto, sans-serif; background: var(--bg); color: var(--fg); max-width: 60rem; margin: 2rem auto; padding: 0 1rem; }
|
|
7
|
+
h1, h2, h3 { line-height: 1.25; }
|
|
8
|
+
table { border-collapse: collapse; width: 100%; margin: 1rem 0; }
|
|
9
|
+
th, td { text-align: left; vertical-align: top; padding: 0.4rem 0.6rem; border-bottom: 1px solid var(--line); }
|
|
10
|
+
code { font-family: ui-monospace, SFMono-Regular, Menlo, monospace; font-size: 0.9em; }
|
|
11
|
+
a { color: var(--accent); }
|
|
12
|
+
.muted { color: var(--muted); }
|
|
13
|
+
`;
|
|
14
|
+
const oneLine = (s) => s.replace(/\s*\r?\n\s*/g, ' ');
|
|
15
|
+
function docsLink(docs) {
|
|
16
|
+
return /^https?:\/\//.test(docs) ? `<a href="${e(docs)}">${e(docs)}</a>` : e(docs);
|
|
17
|
+
}
|
|
18
|
+
function diffList(title, items) {
|
|
19
|
+
if (!items.length)
|
|
20
|
+
return '';
|
|
21
|
+
const li = items
|
|
22
|
+
.map((f) => `<li>${e(groupName(f))}: ${e(f.severity)} <code>${e(f.id)}</code>${f.location.line !== undefined ? ` line ${e(String(f.location.line))}` : ''}: ${e(oneLine(f.message))} (${e(f.engine)}: ${e(f.rule)})</li>`)
|
|
23
|
+
.join('\n');
|
|
24
|
+
return `<h3>${title}</h3>\n<ul>\n${li}\n</ul>\n`;
|
|
25
|
+
}
|
|
26
|
+
export function toHtml(result, diff) {
|
|
27
|
+
const t = result.target;
|
|
28
|
+
let body = `<h1>wp-shakedown report</h1>
|
|
29
|
+
<p>Target: ${e(t.kind)} "${e(t.name)}" at ${e(t.path)}<br>
|
|
30
|
+
Run: ${e(result.finishedAt)}, wp-shakedown ${e(result.tool.version)}</p>
|
|
31
|
+
<h2>Summary</h2>
|
|
32
|
+
<p>${e(summaryLine(result))}</p>
|
|
33
|
+
`;
|
|
34
|
+
if (result.engines.length === 0) {
|
|
35
|
+
body += `<p>${e(noEngineLine(result))}</p>\n`;
|
|
36
|
+
}
|
|
37
|
+
else {
|
|
38
|
+
const rows = result.engines
|
|
39
|
+
.map((r) => `<tr><td>${e(r.engine)}</td><td>${e(r.unit ?? '-')}</td><td>${e(r.status)}${r.reason ? e(`: ${r.reason}`) : ''}</td><td>${e(String(r.findings))}</td></tr>`)
|
|
40
|
+
.join('\n');
|
|
41
|
+
body += `<table>\n<thead><tr><th>Engine</th><th>Part</th><th>Status</th><th>Findings</th></tr></thead>\n<tbody>\n${rows}\n</tbody>\n</table>\n`;
|
|
42
|
+
}
|
|
43
|
+
if (diff) {
|
|
44
|
+
body += `<h2>Since the last run</h2>\n<p>${diff.fixed.length} fixed, ${diff.added.length} new, ${diff.open.length} still open.</p>\n`;
|
|
45
|
+
body += diffList('New:', diff.added) + diffList('Fixed:', diff.fixed);
|
|
46
|
+
}
|
|
47
|
+
body += '<h2>Findings</h2>\n';
|
|
48
|
+
const active = result.findings.filter((f) => !f.suppressed);
|
|
49
|
+
if (active.length === 0)
|
|
50
|
+
body += '<p>No findings.</p>\n';
|
|
51
|
+
const groups = new Map();
|
|
52
|
+
for (const f of active) {
|
|
53
|
+
const g = groups.get(groupName(f));
|
|
54
|
+
if (g)
|
|
55
|
+
g.push(f);
|
|
56
|
+
else
|
|
57
|
+
groups.set(groupName(f), [f]);
|
|
58
|
+
}
|
|
59
|
+
for (const [name, items] of groups) {
|
|
60
|
+
const rows = items
|
|
61
|
+
.map((f) => {
|
|
62
|
+
let msg = e(oneLine(f.message));
|
|
63
|
+
if (f.hint)
|
|
64
|
+
msg += `<br><span class="muted">Fix: ${e(oneLine(f.hint))}</span>`;
|
|
65
|
+
if (f.docs)
|
|
66
|
+
msg += `<br><span class="muted">Docs: ${docsLink(oneLine(f.docs))}</span>`;
|
|
67
|
+
return `<tr><td>${e(f.severity)}</td><td><code>${e(f.id)}</code></td><td>${e(String(f.location.line ?? ''))}</td><td>${msg}</td><td>${e(f.engine)}: ${e(f.rule)}</td></tr>`;
|
|
68
|
+
})
|
|
69
|
+
.join('\n');
|
|
70
|
+
body += `<h3>${e(name)}</h3>\n<table>\n<thead><tr><th>Severity</th><th>ID</th><th>Line</th><th>Message</th><th>Rule</th></tr></thead>\n<tbody>\n${rows}\n</tbody>\n</table>\n`;
|
|
71
|
+
}
|
|
72
|
+
const suppressed = result.findings.filter((f) => f.suppressed);
|
|
73
|
+
if (suppressed.length) {
|
|
74
|
+
const li = suppressed
|
|
75
|
+
.map((f) => `<li><code>${e(f.id)}</code> ${e(f.engine)}: ${e(f.rule)}. Reason: ${e(oneLine(f.suppressed.reason))}</li>`)
|
|
76
|
+
.join('\n');
|
|
77
|
+
body += `<h2>Suppressed</h2>\n<ul>\n${li}\n</ul>\n`;
|
|
78
|
+
}
|
|
79
|
+
if (result.staleBaseline.length) {
|
|
80
|
+
const li = result.staleBaseline.map((id) => `<li><code>${e(id)}</code></li>`).join('\n');
|
|
81
|
+
body += `<h2>Stale baseline entries</h2>\n<p>These baseline entries match nothing now. Remove them.</p>\n<ul>\n${li}\n</ul>\n`;
|
|
82
|
+
}
|
|
83
|
+
if (result.engines.length) {
|
|
84
|
+
const ids = [...new Set(result.engines.map((r) => r.engine))];
|
|
85
|
+
const li = ids.map((id) => `<li><code>${e(`wp-shakedown run "${t.path}" --engine ${id}`)}</code></li>`).join('\n');
|
|
86
|
+
body += `<h2>Run again</h2>\n<ul>\n${li}\n</ul>\n`;
|
|
87
|
+
}
|
|
88
|
+
return `<!doctype html>
|
|
89
|
+
<html lang="en">
|
|
90
|
+
<head>
|
|
91
|
+
<meta charset="utf-8">
|
|
92
|
+
<meta name="viewport" content="width=device-width, initial-scale=1">
|
|
93
|
+
<title>wp-shakedown report: ${e(t.name)}</title>
|
|
94
|
+
<style>${STYLE}</style>
|
|
95
|
+
</head>
|
|
96
|
+
<body>
|
|
97
|
+
${body}</body>
|
|
98
|
+
</html>
|
|
99
|
+
`;
|
|
100
|
+
}
|
|
@@ -0,0 +1,5 @@
|
|
|
1
|
+
import type { Finding, RunDiff, RunResult } from '../types.ts';
|
|
2
|
+
export declare function summaryLine(result: RunResult): string;
|
|
3
|
+
export declare function noEngineLine(result: RunResult): string;
|
|
4
|
+
export declare function groupName(f: Finding): string;
|
|
5
|
+
export declare function toMarkdown(result: RunResult, diff?: RunDiff): string;
|
|
@@ -0,0 +1,92 @@
|
|
|
1
|
+
const oneLine = (s) => s.replace(/\s*\r?\n\s*/g, ' ');
|
|
2
|
+
const cell = (s) => oneLine(s).replace(/\|/g, '\\|');
|
|
3
|
+
const plural = (n, one, many) => `${n} ${n === 1 ? one : many}`;
|
|
4
|
+
export function summaryLine(result) {
|
|
5
|
+
const s = result.summary;
|
|
6
|
+
const base = `${plural(s.error, 'error', 'errors')}, ${plural(s.warning, 'warning', 'warnings')}, ${plural(s.info, 'note', 'notes')}.`;
|
|
7
|
+
return s.suppressed > 0 ? `${base} ${s.suppressed} suppressed.` : base;
|
|
8
|
+
}
|
|
9
|
+
export function noEngineLine(result) {
|
|
10
|
+
const label = { theme: 'theme', plugin: 'plugin', install: 'WordPress folder', url: 'site URL' }[result.target.kind];
|
|
11
|
+
return `No engine ran. This version has no engine for a ${label} yet.`;
|
|
12
|
+
}
|
|
13
|
+
export function groupName(f) {
|
|
14
|
+
return f.location.file ?? f.location.url ?? '(no file)';
|
|
15
|
+
}
|
|
16
|
+
function findingText(f) {
|
|
17
|
+
const line = f.location.line !== undefined ? ` line ${f.location.line}` : '';
|
|
18
|
+
return `${f.severity} \`${f.id}\`${line}: ${oneLine(f.message)} (${f.engine}: ${f.rule})`;
|
|
19
|
+
}
|
|
20
|
+
export function toMarkdown(result, diff) {
|
|
21
|
+
const out = [];
|
|
22
|
+
out.push('# wp-shakedown report');
|
|
23
|
+
out.push(`- Target: ${result.target.kind} "${result.target.name}" at ${result.target.path}\n- Run: ${result.finishedAt}, wp-shakedown ${result.tool.version}`);
|
|
24
|
+
const summary = ['## Summary', summaryLine(result)];
|
|
25
|
+
if (result.engines.length === 0) {
|
|
26
|
+
summary.push(noEngineLine(result));
|
|
27
|
+
}
|
|
28
|
+
else {
|
|
29
|
+
const rows = result.engines.map((e) => `| ${cell(e.engine)} | ${cell(e.unit ?? '-')} | ${e.status}${e.reason ? cell(`: ${e.reason}`) : ''} | ${e.findings} |`);
|
|
30
|
+
summary.push(['| Engine | Part | Status | Findings |', '|---|---|---|---|', ...rows].join('\n'));
|
|
31
|
+
}
|
|
32
|
+
out.push(...summary);
|
|
33
|
+
if (diff) {
|
|
34
|
+
out.push('## Since the last run', `${diff.fixed.length} fixed, ${diff.added.length} new, ${diff.open.length} still open.`);
|
|
35
|
+
const list = (title, all) => {
|
|
36
|
+
const items = all.filter((f) => f.category !== 'standards');
|
|
37
|
+
if (items.length)
|
|
38
|
+
out.push(`${title}\n\n${items.map((f) => `- ${groupName(f)}: ${findingText(f)}`).join('\n')}`);
|
|
39
|
+
};
|
|
40
|
+
list('New:', diff.added);
|
|
41
|
+
list('Fixed:', diff.fixed);
|
|
42
|
+
}
|
|
43
|
+
out.push('## Findings');
|
|
44
|
+
const active = result.findings.filter((f) => !f.suppressed);
|
|
45
|
+
// A real theme has thousands of style findings. Listed one by one they bury the few that matter, so they are counted per rule below.
|
|
46
|
+
const detail = active.filter((f) => f.category !== 'standards');
|
|
47
|
+
const style = active.filter((f) => f.category === 'standards');
|
|
48
|
+
if (active.length === 0)
|
|
49
|
+
out.push('No findings.');
|
|
50
|
+
else if (detail.length === 0)
|
|
51
|
+
out.push('No findings apart from code style.');
|
|
52
|
+
const groups = new Map();
|
|
53
|
+
for (const f of detail) {
|
|
54
|
+
const g = groups.get(groupName(f));
|
|
55
|
+
if (g)
|
|
56
|
+
g.push(f);
|
|
57
|
+
else
|
|
58
|
+
groups.set(groupName(f), [f]);
|
|
59
|
+
}
|
|
60
|
+
for (const [name, items] of groups) {
|
|
61
|
+
const lines = items.map((f) => {
|
|
62
|
+
let s = `- ${findingText(f)}`;
|
|
63
|
+
if (f.hint)
|
|
64
|
+
s += `\n Fix: ${oneLine(f.hint)}`;
|
|
65
|
+
if (f.docs)
|
|
66
|
+
s += `\n Docs: ${oneLine(f.docs)}`;
|
|
67
|
+
return s;
|
|
68
|
+
});
|
|
69
|
+
out.push(`### ${name}`, lines.join('\n'));
|
|
70
|
+
}
|
|
71
|
+
if (style.length) {
|
|
72
|
+
const counts = new Map();
|
|
73
|
+
for (const f of style)
|
|
74
|
+
counts.set(`${f.engine}: ${f.rule}`, (counts.get(`${f.engine}: ${f.rule}`) ?? 0) + 1);
|
|
75
|
+
const rows = [...counts]
|
|
76
|
+
.sort((a, b) => b[1] - a[1] || (a[0] < b[0] ? -1 : 1))
|
|
77
|
+
.map(([rule, n]) => `| ${cell(rule)} | ${n} |`);
|
|
78
|
+
out.push('## Code style', `${plural(style.length, 'style finding', 'style findings')} in ${plural(counts.size, 'rule', 'rules')}. report.json lists each one with its file and line.`, ['| Rule | Findings |', '|---|---|', ...rows].join('\n'));
|
|
79
|
+
}
|
|
80
|
+
const suppressed = result.findings.filter((f) => f.suppressed);
|
|
81
|
+
if (suppressed.length) {
|
|
82
|
+
out.push('## Suppressed', suppressed.map((f) => `- \`${f.id}\` ${f.engine}: ${f.rule}. Reason: ${oneLine(f.suppressed.reason)}`).join('\n'));
|
|
83
|
+
}
|
|
84
|
+
if (result.staleBaseline.length) {
|
|
85
|
+
out.push('## Stale baseline entries', 'These baseline entries match nothing now. Remove them.', result.staleBaseline.map((id) => `- \`${id}\``).join('\n'));
|
|
86
|
+
}
|
|
87
|
+
if (result.engines.length) {
|
|
88
|
+
const ids = [...new Set(result.engines.map((e) => e.engine))];
|
|
89
|
+
out.push('## Run again', ids.map((id) => `- \`wp-shakedown run "${result.target.path}" --engine ${id}\``).join('\n'));
|
|
90
|
+
}
|
|
91
|
+
return out.join('\n\n') + '\n';
|
|
92
|
+
}
|
|
@@ -0,0 +1,44 @@
|
|
|
1
|
+
const LEVEL = { error: 'error', warning: 'warning', info: 'note' };
|
|
2
|
+
export function toSarif(result) {
|
|
3
|
+
const rules = new Map();
|
|
4
|
+
for (const f of result.findings) {
|
|
5
|
+
const id = `${f.engine}/${f.rule}`;
|
|
6
|
+
const rule = rules.get(id) ?? { id };
|
|
7
|
+
if (f.docs && !rule.helpUri)
|
|
8
|
+
rule.helpUri = f.docs;
|
|
9
|
+
rules.set(id, rule);
|
|
10
|
+
}
|
|
11
|
+
const results = result.findings.map((f) => {
|
|
12
|
+
// SARIF wants a URI, so a space in a file path has to be encoded.
|
|
13
|
+
const uri = f.location.file !== undefined ? encodeURI(f.location.file) : f.location.url;
|
|
14
|
+
const region = f.location.line !== undefined
|
|
15
|
+
? { startLine: f.location.line, ...(f.location.column !== undefined ? { startColumn: f.location.column } : {}) }
|
|
16
|
+
: undefined;
|
|
17
|
+
return {
|
|
18
|
+
ruleId: `${f.engine}/${f.rule}`,
|
|
19
|
+
level: LEVEL[f.severity],
|
|
20
|
+
message: { text: f.message },
|
|
21
|
+
partialFingerprints: { 'wpShakedown/v1': f.id },
|
|
22
|
+
...(uri !== undefined ? { locations: [{ physicalLocation: { artifactLocation: { uri }, ...(region ? { region } : {}) } }] } : {}),
|
|
23
|
+
...(f.suppressed ? { suppressions: [{ kind: 'external', justification: f.suppressed.reason }] } : {}),
|
|
24
|
+
};
|
|
25
|
+
});
|
|
26
|
+
const sarif = {
|
|
27
|
+
$schema: 'https://json.schemastore.org/sarif-2.1.0.json',
|
|
28
|
+
version: '2.1.0',
|
|
29
|
+
runs: [
|
|
30
|
+
{
|
|
31
|
+
tool: {
|
|
32
|
+
driver: {
|
|
33
|
+
name: 'wp-shakedown',
|
|
34
|
+
version: result.tool.version,
|
|
35
|
+
informationUri: 'https://github.com/alexposlushnyak/wp-shakedown',
|
|
36
|
+
rules: [...rules.values()],
|
|
37
|
+
},
|
|
38
|
+
},
|
|
39
|
+
results,
|
|
40
|
+
},
|
|
41
|
+
],
|
|
42
|
+
};
|
|
43
|
+
return JSON.stringify(sarif, null, 2) + '\n';
|
|
44
|
+
}
|
|
@@ -0,0 +1,9 @@
|
|
|
1
|
+
import type { RunDiff, RunResult, Target } from '../types.ts';
|
|
2
|
+
export declare function defaultReportDir(target: Target): string;
|
|
3
|
+
export declare function readPreviousRun(dir: string): RunResult | undefined;
|
|
4
|
+
/** Throws when the report folder is the target or inside it. Call it before a run, so a long run is not wasted. */
|
|
5
|
+
export declare function assertReportDir(target: {
|
|
6
|
+
kind: string;
|
|
7
|
+
path: string;
|
|
8
|
+
}, dir: string): void;
|
|
9
|
+
export declare function writeReports(result: RunResult, dir: string, diff?: RunDiff): string[];
|
|
@@ -0,0 +1,48 @@
|
|
|
1
|
+
import { createHash } from 'node:crypto';
|
|
2
|
+
import { mkdirSync, readFileSync, writeFileSync } from 'node:fs';
|
|
3
|
+
import path from 'node:path';
|
|
4
|
+
import { home } from '../home.js';
|
|
5
|
+
import { toHtml } from './html.js';
|
|
6
|
+
import { toJson } from './json.js';
|
|
7
|
+
import { toMarkdown } from './markdown.js';
|
|
8
|
+
import { toSarif } from './sarif.js';
|
|
9
|
+
export function defaultReportDir(target) {
|
|
10
|
+
const slug = target.name.toLowerCase().replace(/[^a-z0-9]+/g, '-').replace(/^-+|-+$/g, '').slice(0, 40).replace(/-+$/, '') || 'target';
|
|
11
|
+
const hash = createHash('sha256').update(target.path).digest('hex').slice(0, 8);
|
|
12
|
+
return path.join(home(), 'reports', `${slug}-${hash}`);
|
|
13
|
+
}
|
|
14
|
+
export function readPreviousRun(dir) {
|
|
15
|
+
try {
|
|
16
|
+
const data = JSON.parse(readFileSync(path.join(dir, 'report.json'), 'utf8'));
|
|
17
|
+
return data?.schema === 1 && Array.isArray(data.findings) && Array.isArray(data.engines) ? data : undefined;
|
|
18
|
+
}
|
|
19
|
+
catch {
|
|
20
|
+
return undefined;
|
|
21
|
+
}
|
|
22
|
+
}
|
|
23
|
+
/** Throws when the report folder is the target or inside it. Call it before a run, so a long run is not wasted. */
|
|
24
|
+
export function assertReportDir(target, dir) {
|
|
25
|
+
if (target.kind === 'url')
|
|
26
|
+
return;
|
|
27
|
+
// shortcut: compares the paths as given. A symlink that points into the target passes. Resolve real paths if that happens.
|
|
28
|
+
const rel = path.relative(target.path, path.resolve(dir));
|
|
29
|
+
if (rel === '' || (!rel.startsWith('..') && !path.isAbsolute(rel))) {
|
|
30
|
+
throw new Error(`The report folder "${dir}" is inside the target. wp-shakedown never writes into what it tests. Pass --out with a folder elsewhere.`);
|
|
31
|
+
}
|
|
32
|
+
}
|
|
33
|
+
export function writeReports(result, dir, diff) {
|
|
34
|
+
assertReportDir(result.target, dir);
|
|
35
|
+
const out = path.resolve(dir);
|
|
36
|
+
mkdirSync(out, { recursive: true });
|
|
37
|
+
const files = [
|
|
38
|
+
['report.md', toMarkdown(result, diff)],
|
|
39
|
+
['report.json', toJson(result)],
|
|
40
|
+
['report.sarif', toSarif(result)],
|
|
41
|
+
['report.html', toHtml(result, diff)],
|
|
42
|
+
];
|
|
43
|
+
return files.map(([name, text]) => {
|
|
44
|
+
const p = path.join(out, name);
|
|
45
|
+
writeFileSync(p, text);
|
|
46
|
+
return p;
|
|
47
|
+
});
|
|
48
|
+
}
|
package/dist/runner.d.ts
ADDED
|
@@ -0,0 +1,11 @@
|
|
|
1
|
+
import type { Baseline, Engine, RunEvent, RunResult, Severity, Target } from './types.ts';
|
|
2
|
+
export interface RunOptions {
|
|
3
|
+
engines: Engine[];
|
|
4
|
+
only?: string[];
|
|
5
|
+
baseline?: Baseline;
|
|
6
|
+
signal?: AbortSignal;
|
|
7
|
+
onEvent?: (e: RunEvent) => void;
|
|
8
|
+
now?: () => Date;
|
|
9
|
+
}
|
|
10
|
+
export declare function run(target: Target, opts: RunOptions): Promise<RunResult>;
|
|
11
|
+
export declare function exitCode(result: RunResult, failOn: Severity | 'never'): 0 | 1 | 2;
|
package/dist/runner.js
ADDED
|
@@ -0,0 +1,152 @@
|
|
|
1
|
+
import { statSync } from 'node:fs';
|
|
2
|
+
import path from 'node:path';
|
|
3
|
+
import { applyBaseline } from './baseline.js';
|
|
4
|
+
import { assignIds } from './fingerprint.js';
|
|
5
|
+
import { unitLabel } from './target.js';
|
|
6
|
+
import { VERSION } from './version.js';
|
|
7
|
+
import { EngineSkipped } from './types.js';
|
|
8
|
+
const posix = (p) => p.split('\\').join('/');
|
|
9
|
+
/** An absolute path inside base becomes relative to it. Anything else stays as given. */
|
|
10
|
+
function relInside(base, p) {
|
|
11
|
+
if (!path.isAbsolute(p))
|
|
12
|
+
return p;
|
|
13
|
+
const r = path.relative(base, p);
|
|
14
|
+
return r === '' || r.startsWith('..') || path.isAbsolute(r) ? p : r;
|
|
15
|
+
}
|
|
16
|
+
function normaliseFile(file, job, root) {
|
|
17
|
+
if (job.unit) {
|
|
18
|
+
const unitRel = path.relative(root.path, job.unit.path);
|
|
19
|
+
// A one-file plugin: every finding points at the plugin file itself.
|
|
20
|
+
if (statSync(job.unit.path, { throwIfNoEntry: false })?.isFile())
|
|
21
|
+
return posix(unitRel);
|
|
22
|
+
return posix(path.join(unitRel, relInside(job.target.path, file)));
|
|
23
|
+
}
|
|
24
|
+
return posix(relInside(job.target.path, file));
|
|
25
|
+
}
|
|
26
|
+
function sortKey(f) {
|
|
27
|
+
return [f.location.file ?? f.location.url ?? '', f.location.line ?? 0, f.location.column ?? 0, f.engine, f.rule];
|
|
28
|
+
}
|
|
29
|
+
function compare(a, b) {
|
|
30
|
+
const x = sortKey(a);
|
|
31
|
+
const y = sortKey(b);
|
|
32
|
+
return ((x[0] < y[0] ? -1 : x[0] > y[0] ? 1 : 0) ||
|
|
33
|
+
x[1] - y[1] ||
|
|
34
|
+
x[2] - y[2] ||
|
|
35
|
+
(x[3] < y[3] ? -1 : x[3] > y[3] ? 1 : 0) ||
|
|
36
|
+
(x[4] < y[4] ? -1 : x[4] > y[4] ? 1 : 0));
|
|
37
|
+
}
|
|
38
|
+
export async function run(target, opts) {
|
|
39
|
+
const known = opts.engines.map((e) => e.id);
|
|
40
|
+
for (const id of opts.only ?? []) {
|
|
41
|
+
if (!known.includes(id))
|
|
42
|
+
throw new Error(`Unknown engine "${id}". Known engines: ${known.join(', ') || 'none'}.`);
|
|
43
|
+
}
|
|
44
|
+
const active = opts.only ? opts.engines.filter((e) => opts.only.includes(e.id)) : opts.engines;
|
|
45
|
+
const now = opts.now ?? (() => new Date());
|
|
46
|
+
const emit = opts.onEvent ?? (() => { });
|
|
47
|
+
const jobs = active.filter((e) => e.kinds.includes(target.kind)).map((engine) => ({ engine, target }));
|
|
48
|
+
if (target.kind === 'install') {
|
|
49
|
+
for (const unit of target.units) {
|
|
50
|
+
for (const engine of active)
|
|
51
|
+
if (engine.kinds.includes(unit.kind))
|
|
52
|
+
jobs.push({ engine, target: unit, unit });
|
|
53
|
+
}
|
|
54
|
+
}
|
|
55
|
+
const startedAt = now().toISOString();
|
|
56
|
+
emit({
|
|
57
|
+
type: 'run:start',
|
|
58
|
+
target,
|
|
59
|
+
jobs: jobs.map((j) => ({ engine: j.engine.id, ...(j.unit ? { unit: unitLabel(j.unit) } : {}) })),
|
|
60
|
+
});
|
|
61
|
+
const engineRuns = [];
|
|
62
|
+
const raw = [];
|
|
63
|
+
// shortcut: engines run one at a time. Run them in parallel once real engines make a run slow.
|
|
64
|
+
for (const job of jobs) {
|
|
65
|
+
if (opts.signal?.aborted)
|
|
66
|
+
break;
|
|
67
|
+
const unit = job.unit ? unitLabel(job.unit) : undefined;
|
|
68
|
+
emit({ type: 'engine:start', engine: job.engine.id, ...(unit ? { unit } : {}) });
|
|
69
|
+
const t0 = performance.now();
|
|
70
|
+
let status = 'ok';
|
|
71
|
+
let reason;
|
|
72
|
+
let found = [];
|
|
73
|
+
try {
|
|
74
|
+
found = await job.engine.run({
|
|
75
|
+
target: job.target,
|
|
76
|
+
note: (message) => emit({ type: 'engine:note', engine: job.engine.id, ...(unit ? { unit } : {}), message }),
|
|
77
|
+
...(opts.signal ? { signal: opts.signal } : {}),
|
|
78
|
+
});
|
|
79
|
+
}
|
|
80
|
+
catch (err) {
|
|
81
|
+
if (err instanceof EngineSkipped)
|
|
82
|
+
status = 'skipped';
|
|
83
|
+
else
|
|
84
|
+
status = 'failed';
|
|
85
|
+
reason = err instanceof Error ? err.message : String(err);
|
|
86
|
+
}
|
|
87
|
+
const er = {
|
|
88
|
+
engine: job.engine.id,
|
|
89
|
+
...(unit ? { unit } : {}),
|
|
90
|
+
status,
|
|
91
|
+
durationMs: Math.round(performance.now() - t0),
|
|
92
|
+
findings: found.length,
|
|
93
|
+
...(reason !== undefined ? { reason } : {}),
|
|
94
|
+
};
|
|
95
|
+
engineRuns.push(er);
|
|
96
|
+
for (const f of found) {
|
|
97
|
+
const location = { ...f.location };
|
|
98
|
+
if (location.file !== undefined)
|
|
99
|
+
location.file = normaliseFile(location.file, job, target);
|
|
100
|
+
raw.push({
|
|
101
|
+
...f,
|
|
102
|
+
location,
|
|
103
|
+
engine: job.engine.id,
|
|
104
|
+
...(unit ? { unit } : {}),
|
|
105
|
+
rerun: `wp-shakedown run "${target.path}" --engine ${job.engine.id}`,
|
|
106
|
+
});
|
|
107
|
+
}
|
|
108
|
+
emit({ type: 'engine:end', run: er });
|
|
109
|
+
}
|
|
110
|
+
let findings = assignIds(raw).sort(compare);
|
|
111
|
+
let staleBaseline = [];
|
|
112
|
+
if (opts.baseline) {
|
|
113
|
+
const applied = applyBaseline(findings, opts.baseline);
|
|
114
|
+
findings = applied.findings;
|
|
115
|
+
// An entry is only stale when every engine ran. After a partial run it may belong to an engine that did not.
|
|
116
|
+
const complete = !opts.only && engineRuns.length === jobs.length && engineRuns.every((e) => e.status === 'ok');
|
|
117
|
+
staleBaseline = complete ? applied.stale : [];
|
|
118
|
+
}
|
|
119
|
+
const summary = { error: 0, warning: 0, info: 0, suppressed: 0 };
|
|
120
|
+
for (const f of findings) {
|
|
121
|
+
if (f.suppressed)
|
|
122
|
+
summary.suppressed++;
|
|
123
|
+
else
|
|
124
|
+
summary[f.severity]++;
|
|
125
|
+
}
|
|
126
|
+
const result = {
|
|
127
|
+
schema: 1,
|
|
128
|
+
tool: { name: 'wp-shakedown', version: VERSION },
|
|
129
|
+
target: {
|
|
130
|
+
kind: target.kind,
|
|
131
|
+
path: target.path,
|
|
132
|
+
name: target.name,
|
|
133
|
+
units: target.units.map((u) => ({ kind: u.kind, name: u.name, path: posix(path.relative(target.path, u.path)) })),
|
|
134
|
+
},
|
|
135
|
+
startedAt,
|
|
136
|
+
finishedAt: now().toISOString(),
|
|
137
|
+
engines: engineRuns,
|
|
138
|
+
findings,
|
|
139
|
+
summary,
|
|
140
|
+
staleBaseline,
|
|
141
|
+
};
|
|
142
|
+
emit({ type: 'run:end', result });
|
|
143
|
+
return result;
|
|
144
|
+
}
|
|
145
|
+
const RANK = { error: 3, warning: 2, info: 1 };
|
|
146
|
+
export function exitCode(result, failOn) {
|
|
147
|
+
if (result.engines.some((e) => e.status === 'failed'))
|
|
148
|
+
return 2;
|
|
149
|
+
if (failOn !== 'never' && result.findings.some((f) => !f.suppressed && RANK[f.severity] >= RANK[failOn]))
|
|
150
|
+
return 1;
|
|
151
|
+
return 0;
|
|
152
|
+
}
|
|
@@ -0,0 +1,19 @@
|
|
|
1
|
+
import type { Engine, RunDiff, RunEvent, RunResult } from './types.ts';
|
|
2
|
+
export interface SessionOptions {
|
|
3
|
+
input: string;
|
|
4
|
+
type?: 'theme' | 'plugin' | 'install';
|
|
5
|
+
only?: string[];
|
|
6
|
+
out?: string;
|
|
7
|
+
baselineFile?: string;
|
|
8
|
+
engines: Engine[];
|
|
9
|
+
onEvent?: (e: RunEvent) => void;
|
|
10
|
+
signal?: AbortSignal;
|
|
11
|
+
}
|
|
12
|
+
export interface SessionResult {
|
|
13
|
+
result: RunResult;
|
|
14
|
+
diff?: RunDiff;
|
|
15
|
+
files: string[];
|
|
16
|
+
dir: string;
|
|
17
|
+
}
|
|
18
|
+
/** The steps from a path to written reports. The command line and the local server share them. */
|
|
19
|
+
export declare function runSession(opts: SessionOptions): Promise<SessionResult>;
|