wp-shakedown 0.1.0 → 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 (44) hide show
  1. package/README.md +15 -3
  2. package/dist/cli.js +160 -3
  3. package/dist/diff.d.ts +2 -1
  4. package/dist/diff.js +5 -3
  5. package/dist/engines/config.js +1 -0
  6. package/dist/engines/custom.d.ts +10 -0
  7. package/dist/engines/custom.js +286 -0
  8. package/dist/engines/index.js +3 -1
  9. package/dist/engines/php-lint.js +1 -0
  10. package/dist/engines/phpstan.js +1 -0
  11. package/dist/engines/theme-check.d.ts +7 -0
  12. package/dist/engines/theme-check.js +109 -0
  13. package/dist/engines/theme-review.d.ts +24 -0
  14. package/dist/engines/theme-review.js +378 -0
  15. package/dist/engines/updates.d.ts +2 -0
  16. package/dist/engines/updates.js +6 -0
  17. package/dist/engines/wp-json.js +1 -0
  18. package/dist/hub.d.ts +32 -0
  19. package/dist/hub.js +99 -0
  20. package/dist/index.d.ts +5 -1
  21. package/dist/index.js +5 -1
  22. package/dist/mcp/tools.js +16 -2
  23. package/dist/profiles.d.ts +4 -0
  24. package/dist/profiles.js +41 -0
  25. package/dist/projects.d.ts +36 -0
  26. package/dist/projects.js +91 -0
  27. package/dist/report/html.js +1 -1
  28. package/dist/report/markdown.js +1 -1
  29. package/dist/runner.d.ts +4 -1
  30. package/dist/runner.js +16 -2
  31. package/dist/session.d.ts +4 -1
  32. package/dist/session.js +10 -2
  33. package/dist/types.d.ts +30 -0
  34. package/dist/types.js +2 -0
  35. package/dist/ui/server.js +218 -55
  36. package/package.json +2 -1
  37. package/php-tools/composer.json +29 -1
  38. package/php-tools/composer.lock +22 -1
  39. package/php-tools/theme-check.php +239 -0
  40. package/ui/dist/assets/index-DXwdz_Wu.css +2 -0
  41. package/ui/dist/assets/index-V8IOqxHa.js +54 -0
  42. package/ui/dist/index.html +2 -2
  43. package/ui/dist/assets/index-7zN46ssH.js +0 -54
  44. package/ui/dist/assets/index-B1axZya5.css +0 -2
package/README.md CHANGED
@@ -1,4 +1,9 @@
1
- # wp-shakedown
1
+ <h1>
2
+ <picture>
3
+ <source media="(prefers-color-scheme: dark)" srcset=".github/assets/wordmark-on-dark.png">
4
+ <img alt="wp-shakedown" src=".github/assets/wordmark-on-light.png" width="360">
5
+ </picture>
6
+ </h1>
2
7
 
3
8
  wp-shakedown runs the usual WordPress checks on a theme, a plugin or a whole WordPress folder from one place and writes one report.
4
9
 
@@ -20,9 +25,11 @@ Testing WordPress work means running PHPCS, PHPStan, WP-CLI checks, Site Health
20
25
 
21
26
  | Target | Checks |
22
27
  |---|---|
23
- | Theme or plugin folder | Coding standards, static analysis, PHP compatibility, `theme.json` and `block.json`, JavaScript and CSS |
28
+ | Theme or plugin folder | Coding standards, static analysis at the deep level, PHP compatibility, `theme.json` and `block.json`, JavaScript and CSS. For a theme, the Theme Check rules of wordpress.org |
24
29
  | WordPress folder | The same code checks across every theme and plugin in it, plus file integrity, known vulnerabilities, outdated or abandoned software, and risky settings and files |
25
30
 
31
+ A profile runs only what one gate checks: `--profile wporg-theme`, `envato`, `wporg-plugin` or `site`. `--depth quick`, `standard` or `deep` sets how thorough the run is. You can add [checks of your own](docs/reference/checks.md).
32
+
26
33
  ## How you run it
27
34
 
28
35
  | From | Command |
@@ -40,7 +47,7 @@ All three use the same core.
40
47
 
41
48
  You do not install PHPCS, PHPStan, ESLint or Stylelint. The first run fetches pinned versions into `~/.wp-shakedown`.
42
49
 
43
- Version 0.1 is tested on macOS and Linux. Windows is not tested yet.
50
+ Version 0.2 is tested on macOS and Linux. Windows is not tested yet.
44
51
 
45
52
  ## Documentation
46
53
 
@@ -49,6 +56,7 @@ Version 0.1 is tested on macOS and Linux. Windows is not tested yet.
49
56
  - [Local web page](docs/reference/ui.md)
50
57
  - [MCP server](docs/reference/mcp.md)
51
58
  - [Engines](docs/reference/engines.md)
59
+ - [Profiles](docs/reference/profiles.md)
52
60
  - [Report format](docs/reference/report.md)
53
61
  - [Architecture](docs/explanation/architecture.md)
54
62
  - [Decision records](docs/adr/README.md)
@@ -61,3 +69,7 @@ AI agents write most of this project and the maintainer reviews their work. The
61
69
  ## License
62
70
 
63
71
  [GPL-2.0-or-later](LICENSE). The tool is free and has no paid tier.
72
+
73
+ ## Credits
74
+
75
+ Made by [alexposlushnyak](https://github.com/alexposlushnyak). Backed by [jkdevstudio](https://jkdevstudio.com), a studio that builds WordPress themes.
package/dist/cli.js CHANGED
@@ -4,6 +4,9 @@ import { statSync } from 'node:fs';
4
4
  import path from 'node:path';
5
5
  import { parseArgs } from 'node:util';
6
6
  import { engines } from './engines/index.js';
7
+ import { profiles } from './profiles.js';
8
+ import { hubExitCode, hubLines, projectTable, runMany } from './hub.js';
9
+ import { addProject, listProjects, removeProject } from './projects.js';
7
10
  import { progressLine } from './progress.js';
8
11
  import { noEngineLine, summaryLine } from './report/markdown.js';
9
12
  import { exitCode } from './runner.js';
@@ -11,19 +14,29 @@ import { runSession } from './session.js';
11
14
  import { startMcp } from './mcp/server.js';
12
15
  import { startUi } from './ui/server.js';
13
16
  import { VERSION } from './version.js';
17
+ const profileList = `${profiles.slice(0, -1).map((p) => p.id).join(', ')} or ${profiles[profiles.length - 1].id}`;
14
18
  const HELP = `wp-shakedown ${VERSION}
15
19
 
16
20
  Usage:
17
- wp-shakedown run <path> [options]
21
+ wp-shakedown run <path>... [options]
22
+ wp-shakedown run --all [options]
23
+ wp-shakedown add <path>...
24
+ wp-shakedown remove <project>...
25
+ wp-shakedown list
18
26
  wp-shakedown ui [path] [options]
19
27
  wp-shakedown mcp
20
28
 
21
29
  Options:
22
30
  --type <kind> Treat the path as a theme, plugin or install
23
31
  --engine <id> Run only this engine. Repeat for more than one
32
+ --profile <id> Run the engines for one gate: ${profileList}
33
+ --depth <level> How thorough the run is: quick, standard or deep. The default is standard
34
+ --experimental Also run the experimental engines
24
35
  --out <dir> Write the report here
25
36
  --baseline <file> Use this baseline file
26
37
  --fail-on <level> Exit 1 at this severity: error, warning, info or never
38
+ --all Run every project on the list
39
+ --jobs <n> How many projects run at once. The default is 3
27
40
  --port <n> Port for the ui command. The default is a free port
28
41
  --no-open Do not open the browser
29
42
  -h, --help Show this help
@@ -31,6 +44,95 @@ Options:
31
44
 
32
45
  Exit codes: 0 clean, 1 findings at or above --fail-on, 2 the run itself failed.
33
46
  `;
47
+ function add(paths) {
48
+ if (paths.length === 0) {
49
+ console.error('wp-shakedown: Give a folder to add, for example: wp-shakedown add ./my-theme');
50
+ return 2;
51
+ }
52
+ const labels = { theme: 'theme', plugin: 'plugin', install: 'WordPress folder', url: 'site URL' };
53
+ let code = 0;
54
+ for (const p of paths) {
55
+ try {
56
+ const { project, added } = addProject(p);
57
+ console.log(added ? `Added the ${labels[project.kind]} "${project.name}".` : `"${project.name}" is already on the list.`);
58
+ }
59
+ catch (err) {
60
+ console.error(`wp-shakedown: ${err instanceof Error ? err.message : String(err)}`);
61
+ code = 2;
62
+ }
63
+ }
64
+ return code;
65
+ }
66
+ function remove(keys) {
67
+ if (keys.length === 0) {
68
+ console.error('wp-shakedown: Name a project to remove. wp-shakedown list shows them.');
69
+ return 2;
70
+ }
71
+ let code = 0;
72
+ for (const k of keys) {
73
+ if (removeProject(k))
74
+ console.log(`Removed "${k}". Its reports stay.`);
75
+ else {
76
+ console.error(`wp-shakedown: No project fits "${k}".`);
77
+ code = 2;
78
+ }
79
+ }
80
+ return code;
81
+ }
82
+ function list() {
83
+ const projects = listProjects();
84
+ console.log(projects.length === 0 ? 'No projects yet. Add one with: wp-shakedown add <path>' : projectTable(projects));
85
+ return 0;
86
+ }
87
+ async function runHub(inputs, jobs, f) {
88
+ const ac = new AbortController();
89
+ const onSigint = () => ac.abort();
90
+ process.once('SIGINT', onSigint);
91
+ const live = process.stderr.isTTY;
92
+ let drawn = 0;
93
+ let timer;
94
+ const draw = (rows) => {
95
+ timer = undefined;
96
+ const lines = hubLines(rows, process.stderr.columns || 80);
97
+ process.stderr.write((drawn ? `\x1b[${drawn}A` : '') + lines.map((l) => `\x1b[2K${l}\n`).join(''));
98
+ drawn = lines.length;
99
+ };
100
+ let latest = [];
101
+ const rows = await runMany(inputs, {
102
+ jobs,
103
+ session: {
104
+ engines,
105
+ signal: ac.signal,
106
+ ...(f.type ? { type: f.type } : {}),
107
+ ...(f.only ? { only: f.only } : {}),
108
+ ...(f.profile ? { profile: f.profile } : {}),
109
+ ...(f.experimental ? { experimental: true } : {}),
110
+ ...(f.depth ? { depth: f.depth } : {}),
111
+ },
112
+ onChange: (all, row, event) => {
113
+ latest = all;
114
+ if (live)
115
+ timer ??= setTimeout(() => draw(latest), 100);
116
+ else if (event) {
117
+ const line = progressLine(event);
118
+ if (line)
119
+ console.error(`[${row.name}] ${line}`);
120
+ }
121
+ else if (row.state === 'failed')
122
+ console.error(`[${row.name}] failed: ${row.error}`);
123
+ },
124
+ });
125
+ process.off('SIGINT', onSigint);
126
+ if (live) {
127
+ if (timer)
128
+ clearTimeout(timer);
129
+ draw(rows);
130
+ }
131
+ for (const r of rows) {
132
+ console.log(r.state === 'done' ? `${r.name}: ${summaryLine(r.result)} Report: ${r.reportFile}` : `${r.name}: failed: ${r.error}`);
133
+ }
134
+ return hubExitCode(rows, f.failOn);
135
+ }
34
136
  function openBrowser(url) {
35
137
  const [cmd, args] = process.platform === 'darwin' ? ['open', [url]] : process.platform === 'win32' ? ['cmd', ['/c', 'start', '""', url]] : ['xdg-open', [url]];
36
138
  try {
@@ -52,6 +154,14 @@ async function ui(input, portText, noOpen) {
52
154
  const startDir = path.resolve(input ?? process.cwd());
53
155
  if (!statSync(startDir, { throwIfNoEntry: false })?.isDirectory())
54
156
  throw new Error(`"${input}" is not a folder.`);
157
+ if (input !== undefined) {
158
+ try {
159
+ addProject(startDir);
160
+ }
161
+ catch {
162
+ // A folder that is not a theme, a plugin or a WordPress folder is only the place to start browsing.
163
+ }
164
+ }
55
165
  const server = await startUi({ engines, startDir, ...(port !== undefined ? { port } : {}) });
56
166
  // Listen for the signal before printing the address. Whoever reads that line may send the signal at once.
57
167
  const stopped = new Promise((resolve) => {
@@ -74,9 +184,14 @@ async function main(argv) {
74
184
  options: {
75
185
  type: { type: 'string' },
76
186
  engine: { type: 'string', multiple: true },
187
+ profile: { type: 'string' },
188
+ depth: { type: 'string' },
189
+ experimental: { type: 'boolean' },
77
190
  out: { type: 'string' },
78
191
  baseline: { type: 'string' },
79
192
  'fail-on': { type: 'string' },
193
+ all: { type: 'boolean' },
194
+ jobs: { type: 'string' },
80
195
  port: { type: 'string' },
81
196
  'no-open': { type: 'boolean' },
82
197
  help: { type: 'boolean', short: 'h' },
@@ -92,6 +207,12 @@ async function main(argv) {
92
207
  return 0;
93
208
  }
94
209
  const [command, input] = positionals;
210
+ if (command === 'add')
211
+ return add(positionals.slice(1));
212
+ if (command === 'remove')
213
+ return remove(positionals.slice(1));
214
+ if (command === 'list')
215
+ return list();
95
216
  if (command === 'mcp') {
96
217
  await startMcp({ engines, input: process.stdin, output: process.stdout }).closed;
97
218
  return 0;
@@ -100,20 +221,56 @@ async function main(argv) {
100
221
  return await ui(input, values.port, values['no-open'] ?? false);
101
222
  if (command !== 'run')
102
223
  throw new Error(`Unknown command "${command}". Run wp-shakedown --help.`);
103
- if (!input)
224
+ const paths = positionals.slice(1);
225
+ const all = values.all ?? false;
226
+ if (all && paths.length > 0)
227
+ throw new Error('Use --all or paths, not both.');
228
+ if (!all && paths.length === 0)
104
229
  throw new Error('Give a folder to test, for example: wp-shakedown run ./my-theme');
230
+ let jobs = 3;
231
+ if (values.jobs !== undefined) {
232
+ jobs = Number(values.jobs);
233
+ if (!/^\d+$/.test(values.jobs) || jobs < 1 || jobs > 8)
234
+ throw new Error('--jobs must be a number from 1 to 8.');
235
+ }
236
+ const many = all || paths.length > 1;
237
+ if (many && values.out)
238
+ throw new Error('--out works with one path.');
239
+ if (many && values.baseline)
240
+ throw new Error('--baseline works with one path.');
105
241
  const type = values.type;
106
242
  if (type !== undefined && type !== 'theme' && type !== 'plugin' && type !== 'install') {
107
243
  throw new Error('--type must be theme, plugin or install.');
108
244
  }
245
+ const depth = values.depth;
246
+ if (depth !== undefined && depth !== 'quick' && depth !== 'standard' && depth !== 'deep') {
247
+ throw new Error('--depth must be quick, standard or deep.');
248
+ }
109
249
  const failOn = values['fail-on'] ?? 'error';
110
250
  if (failOn !== 'error' && failOn !== 'warning' && failOn !== 'info' && failOn !== 'never') {
111
251
  throw new Error('--fail-on must be error, warning, info or never.');
112
252
  }
253
+ if (many) {
254
+ // The same folder twice would write one report folder from two runs.
255
+ const targets = all ? listProjects().filter((p) => p.kind).map((p) => p.path) : [...new Set(paths.map((p) => path.resolve(p)))];
256
+ if (targets.length === 0)
257
+ throw new Error('No projects yet. Add one with: wp-shakedown add <path>');
258
+ return await runHub(targets, jobs, {
259
+ ...(type ? { type } : {}),
260
+ ...(values.engine ? { only: values.engine } : {}),
261
+ ...(values.profile ? { profile: values.profile } : {}),
262
+ ...(depth ? { depth } : {}),
263
+ ...(values.experimental ? { experimental: true } : {}),
264
+ failOn: failOn,
265
+ });
266
+ }
113
267
  const { result, diff, files } = await runSession({
114
- input,
268
+ input: input,
115
269
  ...(type ? { type } : {}),
116
270
  ...(values.engine ? { only: values.engine } : {}),
271
+ ...(values.profile ? { profile: values.profile } : {}),
272
+ ...(depth ? { depth } : {}),
273
+ ...(values.experimental ? { experimental: true } : {}),
117
274
  ...(values.out ? { out: values.out } : {}),
118
275
  ...(values.baseline ? { baselineFile: values.baseline } : {}),
119
276
  engines,
package/dist/diff.d.ts CHANGED
@@ -2,6 +2,7 @@ import type { RunDiff, RunResult } from './types.ts';
2
2
  /**
3
3
  * Compares only what the same engine checked in both runs. A run with --engine,
4
4
  * or one where an engine was skipped, would otherwise report the findings of
5
- * every engine that did not run as fixed.
5
+ * every engine that did not run as fixed. The same goes for an engine that ran
6
+ * another variant of its tool, such as Theme Check under the envato profile.
6
7
  */
7
8
  export declare function diffRuns(previous: RunResult, current: RunResult): RunDiff;
package/dist/diff.js CHANGED
@@ -1,16 +1,18 @@
1
1
  const key = (engine, unit) => `${engine}\n${unit ?? ''}`;
2
- const ranOk = (r) => new Set(r.engines.filter((e) => e.status === 'ok').map((e) => key(e.engine, e.unit)));
2
+ /** What ran well, with the variant of the tool it ran. */
3
+ const ranOk = (r) => new Map(r.engines.filter((e) => e.status === 'ok').map((e) => [key(e.engine, e.unit), e.variant ?? '']));
3
4
  /**
4
5
  * Compares only what the same engine checked in both runs. A run with --engine,
5
6
  * or one where an engine was skipped, would otherwise report the findings of
6
- * every engine that did not run as fixed.
7
+ * every engine that did not run as fixed. The same goes for an engine that ran
8
+ * another variant of its tool, such as Theme Check under the envato profile.
7
9
  */
8
10
  export function diffRuns(previous, current) {
9
11
  const before = ranOk(previous);
10
12
  const now = ranOk(current);
11
13
  const compared = (f) => {
12
14
  const k = key(f.engine, f.unit);
13
- return !f.suppressed && before.has(k) && now.has(k);
15
+ return !f.suppressed && before.has(k) && before.get(k) === now.get(k);
14
16
  };
15
17
  const prev = previous.findings.filter(compared);
16
18
  const cur = current.findings.filter(compared);
@@ -89,6 +89,7 @@ export const config = {
89
89
  id: 'config',
90
90
  title: 'Configuration and risky files',
91
91
  kinds: ['install'],
92
+ depth: 'quick',
92
93
  async run({ target, note }) {
93
94
  const root = target.path;
94
95
  const out = [];
@@ -0,0 +1,10 @@
1
+ import type { Engine, Target } from '../types.ts';
2
+ /** Turns a glob into a RegExp that matches a POSIX relative path. Supports **, *, ? and {a,b}. */
3
+ export declare function globToRegExp(glob: string): RegExp;
4
+ /** The files of the target as POSIX paths relative to its folder. */
5
+ export declare function walk(target: Target): {
6
+ root: string;
7
+ files: string[];
8
+ };
9
+ /** The checks in <home>/checks as engines. With a target, only the checks whose `paths` fit it. */
10
+ export declare function customEngines(target?: Target): Engine[];
@@ -0,0 +1,286 @@
1
+ import { spawn } from 'node:child_process';
2
+ import { existsSync, readdirSync, readFileSync, statSync } from 'node:fs';
3
+ import path from 'node:path';
4
+ import { Ajv } from 'ajv';
5
+ import { home } from '../home.js';
6
+ import { DEPTHS, EngineSkipped } from '../types.js';
7
+ const esc = (s) => s.replace(/[.*+?^${}()|[\]\\\/]/g, '\\$&');
8
+ /** Turns a glob into a RegExp that matches a POSIX relative path. Supports **, *, ? and {a,b}. */
9
+ export function globToRegExp(glob) {
10
+ let out = '';
11
+ for (let i = 0; i < glob.length; i++) {
12
+ const c = glob[i];
13
+ if (c === '*') {
14
+ if (glob[i + 1] === '*') {
15
+ if (glob[i + 2] === '/') {
16
+ out += '(?:.*/)?';
17
+ i += 2;
18
+ }
19
+ else {
20
+ out += '.*';
21
+ i += 1;
22
+ }
23
+ }
24
+ else
25
+ out += '[^/]*';
26
+ }
27
+ else if (c === '?')
28
+ out += '[^/]';
29
+ else if (c === '{' && glob.indexOf('}', i) > i) {
30
+ const end = glob.indexOf('}', i);
31
+ out += `(?:${glob.slice(i + 1, end).split(',').map(esc).join('|')})`;
32
+ i = end;
33
+ }
34
+ else
35
+ out += esc(c);
36
+ }
37
+ return new RegExp(`^${out}$`);
38
+ }
39
+ const CATEGORIES = ['security', 'compatibility', 'standards', 'correctness', 'performance', 'accessibility', 'i18n', 'health', 'other'];
40
+ const strings = (extra = {}) => ({ type: 'array', items: { type: 'string' }, ...extra });
41
+ const globs = { oneOf: [{ type: 'string' }, strings({ minItems: 1 })] };
42
+ const common = {
43
+ title: { type: 'string' },
44
+ kinds: { type: 'array', items: { enum: ['theme', 'plugin', 'install'] }, minItems: 1 },
45
+ paths: strings({ minItems: 1 }),
46
+ depth: { enum: [...DEPTHS] },
47
+ severity: { enum: ['error', 'warning', 'info'] },
48
+ category: { enum: CATEGORIES },
49
+ message: { type: 'string' },
50
+ hint: { type: 'string' },
51
+ onError: { enum: ['fail', 'skip', 'warn'] },
52
+ };
53
+ const schemaFor = (type, properties, extra = {}) => ({
54
+ type: 'object',
55
+ properties: { type: { const: type }, ...common, ...properties },
56
+ required: ['type'],
57
+ additionalProperties: false,
58
+ ...extra,
59
+ });
60
+ const ajv = new Ajv({ strict: false });
61
+ const validators = {
62
+ pattern: ajv.compile(schemaFor('pattern', { files: globs, forbid: { type: 'string' }, require: { type: 'string' }, flags: { type: 'string' } }, { required: ['type', 'files', 'message'], oneOf: [{ required: ['forbid'], not: { required: ['require'] } }, { required: ['require'], not: { required: ['forbid'] } }] })),
63
+ files: ajv.compile(schemaFor('files', { require: strings(), forbid: strings() }, { anyOf: [{ required: ['require'] }, { required: ['forbid'] }] })),
64
+ command: ajv.compile(schemaFor('command', { run: { type: 'string' }, expectExit: { type: 'integer' }, timeoutSeconds: { type: 'number', exclusiveMinimum: 0 } }, { required: ['type', 'run'] })),
65
+ none: ajv.compile({ type: 'object', properties: { type: { enum: ['pattern', 'files', 'command'] } }, required: ['type'] }),
66
+ };
67
+ /** The check itself cannot run. This is not a finding about the target. */
68
+ class CheckError extends Error {
69
+ }
70
+ const posix = (p) => p.split(path.sep).join('/');
71
+ const list = (v) => (v === undefined ? [] : Array.isArray(v) ? v : [v]);
72
+ const MAX_FILE = 2 * 1024 * 1024;
73
+ /** The files of the target as POSIX paths relative to its folder. */
74
+ export function walk(target) {
75
+ if (statSync(target.path).isFile())
76
+ return { root: path.dirname(target.path), files: [path.basename(target.path)] };
77
+ const files = [];
78
+ const visit = (dir) => {
79
+ for (const e of readdirSync(dir, { withFileTypes: true })) {
80
+ if (e.name.startsWith('.'))
81
+ continue;
82
+ const full = path.join(dir, e.name);
83
+ if (e.isDirectory()) {
84
+ if (e.name !== 'node_modules' && e.name !== 'vendor')
85
+ visit(full);
86
+ }
87
+ else if (e.isFile())
88
+ files.push(posix(path.relative(target.path, full)));
89
+ }
90
+ };
91
+ visit(target.path);
92
+ return { root: target.path, files: files.sort() };
93
+ }
94
+ function runCommand(check, target, cwd, signal) {
95
+ const seconds = check.timeoutSeconds ?? 120;
96
+ return new Promise((resolve, reject) => {
97
+ let output = '';
98
+ let timedOut = false;
99
+ // The shell gets its own process group, so a stop reaches the commands the shell started and not only the shell.
100
+ const group = process.platform !== 'win32';
101
+ const child = spawn(check.run, { shell: true, cwd, env: { ...process.env, WP_SHAKEDOWN_TARGET: target.path }, detached: group });
102
+ const stop = () => {
103
+ try {
104
+ if (group && child.pid)
105
+ process.kill(-child.pid, 'SIGKILL');
106
+ else
107
+ child.kill();
108
+ }
109
+ catch {
110
+ // It already ended.
111
+ }
112
+ };
113
+ const onAbort = () => {
114
+ stop();
115
+ reject(signal.reason instanceof Error ? signal.reason : new Error('The run was stopped.'));
116
+ };
117
+ if (signal?.aborted)
118
+ onAbort();
119
+ signal?.addEventListener('abort', onAbort, { once: true });
120
+ // Reject at the timeout without waiting for the pipes to close. A grandchild can keep them open.
121
+ const timer = setTimeout(() => {
122
+ timedOut = true;
123
+ stop();
124
+ reject(new CheckError(`The command did not finish in ${seconds} seconds.`));
125
+ }, seconds * 1000);
126
+ child.stdout.setEncoding('utf8').on('data', (d) => (output += d));
127
+ child.stderr.setEncoding('utf8').on('data', (d) => (output += d));
128
+ const done = () => {
129
+ clearTimeout(timer);
130
+ signal?.removeEventListener('abort', onAbort);
131
+ };
132
+ child.on('error', (err) => {
133
+ done();
134
+ reject(new CheckError(`The command could not start: ${err.message}.`));
135
+ });
136
+ child.on('close', (code) => {
137
+ done();
138
+ if (timedOut || signal?.aborted)
139
+ return;
140
+ const n = code ?? 1;
141
+ if (n === 126 || n === 127)
142
+ return reject(new CheckError(`The command was not found or could not run (exit code ${n}).`));
143
+ resolve({ code: n, output });
144
+ });
145
+ });
146
+ }
147
+ async function runCheck(name, check, target, signal) {
148
+ const title = check.title ?? name;
149
+ const make = (message, location, hint = check.hint) => ({
150
+ rule: name,
151
+ severity: check.severity ?? 'error',
152
+ category: check.category ?? 'other',
153
+ message,
154
+ location,
155
+ ...(hint ? { hint } : {}),
156
+ });
157
+ if (check.type === 'command') {
158
+ const cwd = statSync(target.path).isFile() ? path.dirname(target.path) : target.path;
159
+ const { code, output } = await runCommand(check, target, cwd, signal);
160
+ if (code === (check.expectExit ?? 0))
161
+ return [];
162
+ const tail = output.split(/\r?\n/).filter((l) => l.trim() !== '').slice(-10).join('\n').slice(-1000);
163
+ const hint = check.hint ?? (tail || undefined);
164
+ return [make(check.message ?? `${title} failed with exit code ${code}.`, {}, hint)];
165
+ }
166
+ const { root, files } = walk(target);
167
+ if (check.type === 'files') {
168
+ const out = [];
169
+ for (const g of list(check.require)) {
170
+ const re = globToRegExp(g);
171
+ if (!files.some((f) => re.test(f)))
172
+ out.push(make(check.message ?? `Nothing matches "${g}".`, {}));
173
+ }
174
+ for (const g of list(check.forbid)) {
175
+ const re = globToRegExp(g);
176
+ for (const f of files)
177
+ if (re.test(f))
178
+ out.push(make(check.message ?? 'This file must not be here.', { file: f }));
179
+ }
180
+ return out;
181
+ }
182
+ let re;
183
+ try {
184
+ re = new RegExp((check.forbid ?? check.require), check.flags ?? '');
185
+ }
186
+ catch (err) {
187
+ throw new CheckError(`The pattern is not a valid regular expression: ${err instanceof Error ? err.message : String(err)}.`);
188
+ }
189
+ const wanted = list(check.files).map(globToRegExp);
190
+ const out = [];
191
+ let matched = false;
192
+ for (const f of files) {
193
+ if (!wanted.some((w) => w.test(f)))
194
+ continue;
195
+ const full = path.join(root, f);
196
+ if (statSync(full).size > MAX_FILE)
197
+ continue;
198
+ const text = readFileSync(full, 'utf8');
199
+ if (check.require !== undefined) {
200
+ re.lastIndex = 0;
201
+ if (re.test(text))
202
+ matched = true;
203
+ continue;
204
+ }
205
+ text.split(/\r?\n/).forEach((line, i) => {
206
+ re.lastIndex = 0;
207
+ if (re.test(line))
208
+ out.push(make(check.message, { file: f, line: i + 1 }));
209
+ });
210
+ }
211
+ if (check.require !== undefined && !matched)
212
+ out.push(make(check.message, {}));
213
+ return out;
214
+ }
215
+ function failing(name, reason) {
216
+ return {
217
+ id: `custom:${name}`,
218
+ title: name,
219
+ kinds: ['theme', 'plugin', 'install'],
220
+ depth: 'quick',
221
+ async run() {
222
+ throw new Error(`The check file ${name}.json is not valid: ${reason}.`);
223
+ },
224
+ };
225
+ }
226
+ function toEngine(name, check) {
227
+ return {
228
+ id: `custom:${name}`,
229
+ title: check.title ?? name,
230
+ kinds: check.kinds ?? ['theme', 'plugin'],
231
+ depth: check.depth ?? 'standard',
232
+ async run({ target, signal }) {
233
+ try {
234
+ return await runCheck(name, check, target, signal);
235
+ }
236
+ catch (err) {
237
+ if (!(err instanceof CheckError))
238
+ throw err;
239
+ const how = check.onError ?? 'fail';
240
+ if (how === 'skip')
241
+ throw new EngineSkipped(err.message);
242
+ if (how === 'warn') {
243
+ return [{ rule: name, severity: 'warning', category: 'other', message: `The check could not run: ${err.message}`, location: {} }];
244
+ }
245
+ throw new Error(err.message);
246
+ }
247
+ },
248
+ };
249
+ }
250
+ /** The checks in <home>/checks as engines. With a target, only the checks whose `paths` fit it. */
251
+ export function customEngines(target) {
252
+ const dir = path.join(home(), 'checks');
253
+ if (!existsSync(dir))
254
+ return [];
255
+ const names = readdirSync(dir)
256
+ .filter((n) => /^[a-z0-9][a-z0-9-]*\.json$/.test(n))
257
+ .sort();
258
+ const out = [];
259
+ for (const file of names) {
260
+ const name = file.slice(0, -'.json'.length);
261
+ let data;
262
+ try {
263
+ data = JSON.parse(readFileSync(path.join(dir, file), 'utf8'));
264
+ }
265
+ catch {
266
+ out.push(failing(name, 'it is not JSON'));
267
+ continue;
268
+ }
269
+ const type = data?.type;
270
+ const validate = validators[typeof type === 'string' && type in validators && type !== 'none' ? type : 'none'];
271
+ if (!validate(data)) {
272
+ const e = validate.errors[0];
273
+ const unknown = e.keyword === 'additionalProperties' ? e.params.additionalProperty : undefined;
274
+ out.push(failing(name, unknown ? `it has a field the format does not know, "${unknown}"` : `${e.instancePath || 'the file'} ${e.message}`));
275
+ continue;
276
+ }
277
+ const check = data;
278
+ if (target && check.paths) {
279
+ const p = posix(target.path);
280
+ if (!check.paths.some((g) => globToRegExp(g).test(p)))
281
+ continue;
282
+ }
283
+ out.push(toEngine(name, check));
284
+ }
285
+ return out;
286
+ }
@@ -5,8 +5,10 @@ import { phpCompat } from './php-compat.js';
5
5
  import { phpLint } from './php-lint.js';
6
6
  import { phpstan } from './phpstan.js';
7
7
  import { stylelint } from './stylelint.js';
8
+ import { themeCheck } from './theme-check.js';
9
+ import { themeReview } from './theme-review.js';
8
10
  import { updates } from './updates.js';
9
11
  import { vulnerabilities } from './vulnerabilities.js';
10
12
  import { wpJson } from './wp-json.js';
11
13
  import { wpcs } from './wpcs.js';
12
- export const engines = [phpLint, wpcs, phpCompat, phpstan, wpJson, eslint, stylelint, integrity, updates, vulnerabilities, config];
14
+ export const engines = [phpLint, themeCheck, themeReview, wpcs, phpCompat, phpstan, wpJson, eslint, stylelint, integrity, updates, vulnerabilities, config];
@@ -11,6 +11,7 @@ export const phpLint = {
11
11
  id: 'php-lint',
12
12
  title: 'PHP syntax',
13
13
  kinds: ['theme', 'plugin'],
14
+ depth: 'quick',
14
15
  async run({ target, signal, note }) {
15
16
  note(`Checking syntax with PHP ${await phpVersion()}.`);
16
17
  const base = statSync(target.path).isFile() ? path.dirname(target.path) : target.path;
@@ -57,6 +57,7 @@ export const phpstan = {
57
57
  id: 'phpstan',
58
58
  title: 'PHPStan',
59
59
  kinds: ['theme', 'plugin'],
60
+ depth: 'deep',
60
61
  async run({ target, signal, note }) {
61
62
  await phpVersion();
62
63
  const tools = await phpTools(note);
@@ -0,0 +1,7 @@
1
+ import type { Engine, RawFinding } from '../types.ts';
2
+ export interface ThemeCheckMessage {
3
+ check: string;
4
+ html: string;
5
+ }
6
+ export declare function toFindings(messages: ThemeCheckMessage[], isFile: (rel: string) => boolean): RawFinding[];
7
+ export declare const themeCheck: Engine;