wp-shakedown 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 (116) hide show
  1. package/LICENSE +340 -0
  2. package/README.md +74 -2
  3. package/dist/baseline.d.ts +6 -0
  4. package/dist/baseline.js +41 -0
  5. package/dist/cli.d.ts +2 -0
  6. package/dist/cli.js +296 -0
  7. package/dist/diff.d.ts +8 -0
  8. package/dist/diff.js +26 -0
  9. package/dist/engines/config.d.ts +3 -0
  10. package/dist/engines/config.js +134 -0
  11. package/dist/engines/custom.d.ts +10 -0
  12. package/dist/engines/custom.js +286 -0
  13. package/dist/engines/eslint.d.ts +8 -0
  14. package/dist/engines/eslint.js +96 -0
  15. package/dist/engines/index.d.ts +2 -0
  16. package/dist/engines/index.js +14 -0
  17. package/dist/engines/integrity.d.ts +2 -0
  18. package/dist/engines/integrity.js +108 -0
  19. package/dist/engines/php-compat.d.ts +2 -0
  20. package/dist/engines/php-compat.js +26 -0
  21. package/dist/engines/php-lint.d.ts +6 -0
  22. package/dist/engines/php-lint.js +42 -0
  23. package/dist/engines/phpstan.d.ts +11 -0
  24. package/dist/engines/phpstan.js +103 -0
  25. package/dist/engines/stylelint.d.ts +4 -0
  26. package/dist/engines/stylelint.js +63 -0
  27. package/dist/engines/theme-check.d.ts +7 -0
  28. package/dist/engines/theme-check.js +109 -0
  29. package/dist/engines/theme-review.d.ts +24 -0
  30. package/dist/engines/theme-review.js +378 -0
  31. package/dist/engines/updates.d.ts +6 -0
  32. package/dist/engines/updates.js +78 -0
  33. package/dist/engines/vulnerabilities.d.ts +22 -0
  34. package/dist/engines/vulnerabilities.js +128 -0
  35. package/dist/engines/wp-json.d.ts +18 -0
  36. package/dist/engines/wp-json.js +134 -0
  37. package/dist/engines/wpcs.d.ts +7 -0
  38. package/dist/engines/wpcs.js +60 -0
  39. package/dist/exec.d.ts +12 -0
  40. package/dist/exec.js +19 -0
  41. package/dist/fingerprint.d.ts +10 -0
  42. package/dist/fingerprint.js +29 -0
  43. package/dist/health/install.d.ts +16 -0
  44. package/dist/health/install.js +68 -0
  45. package/dist/home.d.ts +2 -0
  46. package/dist/home.js +6 -0
  47. package/dist/hub.d.ts +32 -0
  48. package/dist/hub.js +99 -0
  49. package/dist/index.d.ts +42 -0
  50. package/dist/index.js +36 -0
  51. package/dist/js/files.d.ts +4 -0
  52. package/dist/js/files.js +47 -0
  53. package/dist/js/tools.d.ts +3 -0
  54. package/dist/js/tools.js +67 -0
  55. package/dist/mcp/server.d.ts +9 -0
  56. package/dist/mcp/server.js +91 -0
  57. package/dist/mcp/tools.d.ts +26 -0
  58. package/dist/mcp/tools.js +163 -0
  59. package/dist/net.d.ts +18 -0
  60. package/dist/net.js +68 -0
  61. package/dist/php/files.d.ts +3 -0
  62. package/dist/php/files.js +53 -0
  63. package/dist/php/php.d.ts +4 -0
  64. package/dist/php/php.js +25 -0
  65. package/dist/php/phpcs.d.ts +25 -0
  66. package/dist/php/phpcs.js +55 -0
  67. package/dist/php/tools.d.ts +3 -0
  68. package/dist/php/tools.js +66 -0
  69. package/dist/profiles.d.ts +4 -0
  70. package/dist/profiles.js +41 -0
  71. package/dist/progress.d.ts +3 -0
  72. package/dist/progress.js +13 -0
  73. package/dist/projects.d.ts +36 -0
  74. package/dist/projects.js +91 -0
  75. package/dist/report/escape.d.ts +1 -0
  76. package/dist/report/escape.js +4 -0
  77. package/dist/report/html.d.ts +2 -0
  78. package/dist/report/html.js +100 -0
  79. package/dist/report/json.d.ts +2 -0
  80. package/dist/report/json.js +3 -0
  81. package/dist/report/markdown.d.ts +5 -0
  82. package/dist/report/markdown.js +92 -0
  83. package/dist/report/sarif.d.ts +2 -0
  84. package/dist/report/sarif.js +44 -0
  85. package/dist/report/write.d.ts +9 -0
  86. package/dist/report/write.js +48 -0
  87. package/dist/runner.d.ts +14 -0
  88. package/dist/runner.js +166 -0
  89. package/dist/session.d.ts +22 -0
  90. package/dist/session.js +39 -0
  91. package/dist/target.d.ts +5 -0
  92. package/dist/target.js +114 -0
  93. package/dist/types.d.ts +165 -0
  94. package/dist/types.js +6 -0
  95. package/dist/ui/server.d.ts +13 -0
  96. package/dist/ui/server.js +458 -0
  97. package/dist/version.d.ts +1 -0
  98. package/dist/version.js +3 -0
  99. package/dist/versions.d.ts +9 -0
  100. package/dist/versions.js +35 -0
  101. package/js-tools/eslint.config.mjs +19 -0
  102. package/js-tools/package-lock.json +7004 -0
  103. package/js-tools/package.json +13 -0
  104. package/js-tools/stylelint.config.mjs +4 -0
  105. package/package.json +58 -4
  106. package/php-tools/composer.json +68 -0
  107. package/php-tools/composer.lock +889 -0
  108. package/php-tools/theme-check.php +239 -0
  109. package/ui/dist/assets/geist-cyrillic-ext-wght-normal-DjL33-gN.woff2 +0 -0
  110. package/ui/dist/assets/geist-cyrillic-wght-normal-BEAKL7Jp.woff2 +0 -0
  111. package/ui/dist/assets/geist-latin-ext-wght-normal-DC-KSUi6.woff2 +0 -0
  112. package/ui/dist/assets/geist-latin-wght-normal-BgDaEnEv.woff2 +0 -0
  113. package/ui/dist/assets/geist-vietnamese-wght-normal-6IgcOCM7.woff2 +0 -0
  114. package/ui/dist/assets/index-DXwdz_Wu.css +2 -0
  115. package/ui/dist/assets/index-V8IOqxHa.js +54 -0
  116. package/ui/dist/index.html +14 -0
@@ -0,0 +1,134 @@
1
+ import { existsSync, readdirSync, readFileSync, statSync } from 'node:fs';
2
+ import path from 'node:path';
3
+ import { Ajv } from 'ajv';
4
+ import { getJson, Unreachable } from '../net.js';
5
+ import { EngineSkipped } from '../types.js';
6
+ export function jsonFiles(target) {
7
+ if (statSync(target.path).isFile())
8
+ return [];
9
+ const out = [];
10
+ const walk = (dir, visit) => {
11
+ for (const e of readdirSync(dir, { withFileTypes: true })) {
12
+ const p = path.join(dir, e.name);
13
+ if (e.isDirectory()) {
14
+ if (e.name !== 'vendor' && e.name !== 'node_modules' && !e.name.startsWith('.'))
15
+ walk(p, visit);
16
+ }
17
+ else if (e.isFile())
18
+ visit(p, e.name);
19
+ }
20
+ };
21
+ if (target.kind === 'theme') {
22
+ const top = path.join(target.path, 'theme.json');
23
+ if (existsSync(top))
24
+ out.push({ file: top, kind: 'theme' });
25
+ const styles = path.join(target.path, 'styles');
26
+ if (existsSync(styles) && statSync(styles).isDirectory()) {
27
+ walk(styles, (p, n) => {
28
+ if (n.endsWith('.json'))
29
+ out.push({ file: p, kind: 'theme' });
30
+ });
31
+ }
32
+ }
33
+ walk(target.path, (p, n) => {
34
+ if (n === 'block.json')
35
+ out.push({ file: p, kind: 'block' });
36
+ });
37
+ return out.sort((a, b) => (a.file < b.file ? -1 : a.file > b.file ? 1 : 0));
38
+ }
39
+ export function schemaUrl(kind, declared) {
40
+ if (typeof declared === 'string') {
41
+ const m = /^https:\/\/schemas\.wp\.org\/(?:trunk|wp\/\d+\.\d+)\/(theme|block)\.json$/.exec(declared);
42
+ if (m && m[1] === kind)
43
+ return declared;
44
+ }
45
+ return `https://schemas.wp.org/trunk/${kind}.json`;
46
+ }
47
+ const WEEK = 7 * 24 * 3600 * 1000;
48
+ export async function loadSchema(url) {
49
+ const skip = new EngineSkipped(`Cannot download ${url}. The engine needs the schema once and then works offline for a week.`);
50
+ try {
51
+ const r = await getJson(url, { ttlMs: WEEK });
52
+ if (r.status === 200 && r.data && typeof r.data === 'object')
53
+ return r.data;
54
+ }
55
+ catch (err) {
56
+ if (!(err instanceof Unreachable))
57
+ throw err;
58
+ }
59
+ throw skip;
60
+ }
61
+ const ajv = new Ajv({ strict: false, allErrors: true, validateFormats: false });
62
+ const validators = new WeakMap();
63
+ const SKIP = new Set(['if', 'then', 'else', 'anyOf', 'oneOf', 'allOf', 'not']);
64
+ export function validate(schema, data) {
65
+ let v = validators.get(schema);
66
+ if (!v)
67
+ validators.set(schema, (v = ajv.compile(schema)));
68
+ v(data);
69
+ const seen = new Set();
70
+ const out = [];
71
+ for (const e of v.errors ?? []) {
72
+ if (SKIP.has(e.keyword))
73
+ continue;
74
+ // A name that propertyNames rejects also produces errors about the name itself. The propertyNames error says it all.
75
+ if ('propertyName' in e && e.keyword !== 'propertyNames')
76
+ continue;
77
+ const where = e.instancePath || '/';
78
+ let message = `${where}: ${e.message}`;
79
+ // The WordPress schemas reject an unknown name with additionalProperties in some places and with propertyNames in others.
80
+ if (e.keyword === 'additionalProperties')
81
+ message = `${where}: "${e.params.additionalProperty}" is not a known property`;
82
+ if (e.keyword === 'propertyNames')
83
+ message = `${where}: "${e.params.propertyName}" is not a known property`;
84
+ if (e.keyword === 'enum')
85
+ message += `: ${e.params.allowedValues.slice(0, 8).join(', ')}`;
86
+ const rule = `schema.${e.keyword}`;
87
+ const key = `${rule}\n${message}`;
88
+ if (seen.has(key))
89
+ continue;
90
+ seen.add(key);
91
+ out.push({ rule, message });
92
+ }
93
+ return out.slice(0, 50);
94
+ }
95
+ export function syntaxFinding(err) {
96
+ const message = err instanceof Error ? err.message : String(err);
97
+ const m = /\(line (\d+) column \d+\)/.exec(message);
98
+ return { message, ...(m ? { line: Number(m[1]) } : {}) };
99
+ }
100
+ export const wpJson = {
101
+ id: 'wp-json',
102
+ title: 'theme.json and block.json',
103
+ kinds: ['theme', 'plugin'],
104
+ depth: 'quick',
105
+ async run({ target, signal }) {
106
+ const files = jsonFiles(target);
107
+ const out = [];
108
+ const schemas = new Map();
109
+ for (const { file, kind } of files) {
110
+ if (signal?.aborted)
111
+ break;
112
+ const rel = path.relative(target.path, file).split(path.sep).join('/');
113
+ let data;
114
+ try {
115
+ data = JSON.parse(readFileSync(file, 'utf8'));
116
+ }
117
+ catch (err) {
118
+ const s = syntaxFinding(err);
119
+ out.push({ rule: 'json.syntax', severity: 'error', category: 'correctness', message: s.message, location: { file: rel, ...(s.line ? { line: s.line } : {}) } });
120
+ continue;
121
+ }
122
+ const url = schemaUrl(kind, data?.$schema);
123
+ let pending = schemas.get(url);
124
+ if (!pending)
125
+ schemas.set(url, (pending = loadSchema(url)));
126
+ const schema = await pending;
127
+ for (const v of validate(schema, data)) {
128
+ // shortcut: no line number. Mapping a JSON path to a line needs a position-aware parser. Add one when people ask where in the file.
129
+ out.push({ rule: v.rule, severity: 'warning', category: 'correctness', message: v.message, location: { file: rel } });
130
+ }
131
+ }
132
+ return out;
133
+ },
134
+ };
@@ -0,0 +1,7 @@
1
+ import type { PhpcsMessage } from '../php/phpcs.ts';
2
+ import type { Category, Engine, RawFinding } from '../types.ts';
3
+ export declare function categorise(source: string): Category;
4
+ export declare function toFinding(m: PhpcsMessage): RawFinding;
5
+ /** The WordPress-Extra rules plus the Plugin Check review rules, as a ruleset file in the tools folder. */
6
+ export declare function pluginRuleset(tools: string): string;
7
+ export declare const wpcs: Engine;
@@ -0,0 +1,60 @@
1
+ import { existsSync, statSync, writeFileSync } from 'node:fs';
2
+ import path from 'node:path';
3
+ import { runPhpcs } from '../php/phpcs.js';
4
+ const RULES = [
5
+ [/^PluginCheck\.Security\./, 'security'],
6
+ [/^PluginCheck\.CodeAnalysis\./, 'correctness'],
7
+ [/^WordPress\.PHP\.YodaConditions/, 'standards'],
8
+ [/^WordPress\.Security\./, 'security'],
9
+ [/^WordPress\.DB\.PreparedSQL/, 'security'],
10
+ [/^WordPress\.WP\.I18n\./, 'i18n'],
11
+ [/^WordPress\.DB\.(DirectDatabaseQuery|SlowDBQuery)/, 'performance'],
12
+ [/^WordPress\.(WP|PHP|DB|DateTime|CodeAnalysis|Utils)\./, 'correctness'],
13
+ [/^(Generic\.PHP\.(Syntax|BacktickOperator|DiscourageGoto|ForbiddenFunctions)|Squiz\.PHP\.(Eval|DiscouragedFunctions)|Generic\.CodeAnalysis\.|Generic\.PHP\.(DisallowShortOpenTag|DisallowAlternativePHPTags)|Generic\.Files\.ByteOrderMark)/, 'correctness'],
14
+ ];
15
+ export function categorise(source) {
16
+ return RULES.find(([re]) => re.test(source))?.[1] ?? 'standards';
17
+ }
18
+ export function toFinding(m) {
19
+ const category = categorise(m.source);
20
+ const error = m.type === 'ERROR';
21
+ const severity = category === 'standards' ? (error ? 'warning' : 'info') : error ? 'error' : 'warning';
22
+ return {
23
+ rule: m.source,
24
+ severity,
25
+ category,
26
+ message: m.message,
27
+ location: { file: m.file, line: m.line, column: m.column },
28
+ ...(m.fixable ? { hint: 'phpcbf can fix this.' } : {}),
29
+ };
30
+ }
31
+ const PLUGIN_RULESET = `<?xml version="1.0"?>
32
+ <ruleset name="wp-shakedown plugin">
33
+ <rule ref="WordPress-Extra"/>
34
+ <rule ref="./vendor/plugin-check/phpcs-sniffs/phpcs-rulesets/plugin-review.xml"/>
35
+ </ruleset>
36
+ `;
37
+ /** The WordPress-Extra rules plus the Plugin Check review rules, as a ruleset file in the tools folder. */
38
+ export function pluginRuleset(tools) {
39
+ const file = path.join(tools, 'wp-shakedown-plugin.xml');
40
+ if (!existsSync(file))
41
+ writeFileSync(file, PLUGIN_RULESET);
42
+ return file;
43
+ }
44
+ const RULESETS = ['.phpcs.xml', 'phpcs.xml', '.phpcs.xml.dist', 'phpcs.xml.dist'];
45
+ export const wpcs = {
46
+ id: 'wpcs',
47
+ title: 'WordPress Coding Standards',
48
+ kinds: ['theme', 'plugin'],
49
+ async run({ target, signal, note }) {
50
+ let standard = target.kind === 'plugin' ? pluginRuleset : 'WordPress-Extra';
51
+ if (statSync(target.path).isDirectory()) {
52
+ const name = RULESETS.find((n) => existsSync(path.join(target.path, n)));
53
+ if (name) {
54
+ standard = path.join(target.path, name);
55
+ note(`Using the project ruleset ${name}.`);
56
+ }
57
+ }
58
+ return (await runPhpcs({ target, standard, ...(signal ? { signal } : {}), note })).map(toFinding);
59
+ },
60
+ };
package/dist/exec.d.ts ADDED
@@ -0,0 +1,12 @@
1
+ export interface ExecResult {
2
+ code: number;
3
+ stdout: string;
4
+ stderr: string;
5
+ }
6
+ /** Thrown when the command does not exist. */
7
+ export declare class NotFound extends Error {
8
+ }
9
+ export declare function exec(cmd: string, args: string[], opts?: {
10
+ cwd?: string;
11
+ signal?: AbortSignal;
12
+ }): Promise<ExecResult>;
package/dist/exec.js ADDED
@@ -0,0 +1,19 @@
1
+ import { spawn } from 'node:child_process';
2
+ /** Thrown when the command does not exist. */
3
+ export class NotFound extends Error {
4
+ }
5
+ export function exec(cmd, args, opts = {}) {
6
+ return new Promise((resolve, reject) => {
7
+ const child = spawn(cmd, args, {
8
+ ...(opts.cwd ? { cwd: opts.cwd } : {}),
9
+ ...(opts.signal ? { signal: opts.signal } : {}),
10
+ stdio: ['ignore', 'pipe', 'pipe'],
11
+ });
12
+ let stdout = '';
13
+ let stderr = '';
14
+ child.stdout.setEncoding('utf8').on('data', (d) => (stdout += d));
15
+ child.stderr.setEncoding('utf8').on('data', (d) => (stderr += d));
16
+ child.on('error', (err) => reject(err.code === 'ENOENT' ? new NotFound(`${cmd} was not found.`) : err));
17
+ child.on('close', (code) => resolve({ code: code ?? 1, stdout, stderr }));
18
+ });
19
+ }
@@ -0,0 +1,10 @@
1
+ import type { Location } from './types.ts';
2
+ export declare function assignIds<T extends {
3
+ engine: string;
4
+ unit?: string;
5
+ rule: string;
6
+ message: string;
7
+ location: Location;
8
+ }>(items: T[]): (T & {
9
+ id: string;
10
+ })[];
@@ -0,0 +1,29 @@
1
+ import { createHash } from 'node:crypto';
2
+ const sha = (s) => createHash('sha256').update(s).digest('hex').slice(0, 12);
3
+ export function assignIds(items) {
4
+ const groups = new Map();
5
+ items.forEach((f, i) => {
6
+ const key = JSON.stringify([
7
+ f.engine,
8
+ f.rule,
9
+ f.unit ?? '',
10
+ f.location.file ?? f.location.url ?? '',
11
+ f.location.selector ?? '',
12
+ f.message,
13
+ ]);
14
+ const g = groups.get(key);
15
+ if (g)
16
+ g.push(i);
17
+ else
18
+ groups.set(key, [i]);
19
+ });
20
+ const ids = [];
21
+ for (const [key, idx] of groups) {
22
+ idx.sort((a, b) => (items[a].location.line ?? 0) - (items[b].location.line ?? 0) ||
23
+ (items[a].location.column ?? 0) - (items[b].location.column ?? 0));
24
+ idx.forEach((i, n) => {
25
+ ids[i] = n === 0 ? sha(key) : sha(`${key}#${n + 1}`);
26
+ });
27
+ }
28
+ return items.map((f, i) => ({ ...f, id: ids[i] }));
29
+ }
@@ -0,0 +1,16 @@
1
+ import type { Target } from '../types.ts';
2
+ export declare function coreVersion(root: string): {
3
+ version: string;
4
+ locale: string;
5
+ } | undefined;
6
+ export interface Package {
7
+ kind: 'plugin' | 'theme';
8
+ slug: string;
9
+ name: string;
10
+ version?: string;
11
+ path: string;
12
+ file: string;
13
+ }
14
+ export declare function packages(target: Target): Package[];
15
+ /** Turns a lost connection into a skipped engine. */
16
+ export declare function skipOnNetwork<T>(work: () => Promise<T>): Promise<T>;
@@ -0,0 +1,68 @@
1
+ import { readdirSync, readFileSync, statSync } from 'node:fs';
2
+ import path from 'node:path';
3
+ import { Unreachable } from '../net.js';
4
+ import { EngineSkipped } from '../types.js';
5
+ export function coreVersion(root) {
6
+ let text;
7
+ try {
8
+ text = readFileSync(path.join(root, 'wp-includes', 'version.php'), 'utf8');
9
+ }
10
+ catch {
11
+ return undefined;
12
+ }
13
+ const version = /\$wp_version\s*=\s*'([^']+)'/.exec(text)?.[1];
14
+ if (!version)
15
+ return undefined;
16
+ return { version, locale: /\$wp_local_package\s*=\s*'([^']+)'/.exec(text)?.[1] ?? 'en_US' };
17
+ }
18
+ const PLUGIN_HEAD = /^[ \t\/*#@]*Plugin Name:/im;
19
+ const VERSION_HEAD = /^[ \t\/*#@]*Version:\s*(.+)$/im;
20
+ function head(file) {
21
+ try {
22
+ return readFileSync(file).subarray(0, 8192).toString('utf8');
23
+ }
24
+ catch {
25
+ return '';
26
+ }
27
+ }
28
+ function pluginMain(dir) {
29
+ let names;
30
+ try {
31
+ names = readdirSync(dir).filter((n) => n.endsWith('.php')).sort();
32
+ }
33
+ catch {
34
+ return undefined;
35
+ }
36
+ for (const n of names) {
37
+ const f = path.join(dir, n);
38
+ if (statSync(f, { throwIfNoEntry: false })?.isFile() && PLUGIN_HEAD.test(head(f)))
39
+ return f;
40
+ }
41
+ return undefined;
42
+ }
43
+ export function packages(target) {
44
+ return target.units.map((u) => {
45
+ const isFile = statSync(u.path, { throwIfNoEntry: false })?.isFile() ?? false;
46
+ const main = u.kind === 'theme' ? path.join(u.path, 'style.css') : isFile ? u.path : pluginMain(u.path);
47
+ const version = main ? VERSION_HEAD.exec(head(main))?.[1]?.replace(/\*\/\s*$/, '').trim() || undefined : undefined;
48
+ return {
49
+ kind: u.kind,
50
+ slug: path.basename(u.path).replace(/\.php$/, ''),
51
+ name: u.name,
52
+ ...(version ? { version } : {}),
53
+ path: u.path,
54
+ file: path.relative(target.path, main ?? u.path).split(path.sep).join('/'),
55
+ };
56
+ });
57
+ }
58
+ /** Turns a lost connection into a skipped engine. */
59
+ export async function skipOnNetwork(work) {
60
+ try {
61
+ return await work();
62
+ }
63
+ catch (err) {
64
+ if (err instanceof Unreachable)
65
+ throw new EngineSkipped(`${err.message} This engine needs the network.`);
66
+ throw err;
67
+ }
68
+ }
package/dist/home.d.ts ADDED
@@ -0,0 +1,2 @@
1
+ /** The folder where wp-shakedown keeps reports and downloaded tools. */
2
+ export declare function home(): string;
package/dist/home.js ADDED
@@ -0,0 +1,6 @@
1
+ import os from 'node:os';
2
+ import path from 'node:path';
3
+ /** The folder where wp-shakedown keeps reports and downloaded tools. */
4
+ export function home() {
5
+ return process.env.WP_SHAKEDOWN_HOME || path.join(os.homedir(), '.wp-shakedown');
6
+ }
package/dist/hub.d.ts ADDED
@@ -0,0 +1,32 @@
1
+ import type { Project } from './projects.ts';
2
+ import type { SessionOptions } from './session.ts';
3
+ import type { RunEvent, RunResult, Severity } from './types.ts';
4
+ export interface HubRow {
5
+ /** The target name once the run has started, the base name of the path before. */
6
+ name: string;
7
+ path: string;
8
+ /** failed: the run itself threw. */
9
+ state: 'waiting' | 'running' | 'done' | 'failed';
10
+ /** Jobs of the run, 0 before it starts. */
11
+ total: number;
12
+ /** Engines finished so far. */
13
+ done: number;
14
+ /** "wpcs" or "wpcs theme:twentytwenty" while an engine runs. */
15
+ current?: string;
16
+ result?: RunResult;
17
+ reportFile?: string;
18
+ error?: string;
19
+ }
20
+ export interface HubOptions {
21
+ jobs: number;
22
+ session: Omit<SessionOptions, 'input' | 'onEvent'>;
23
+ onChange?: (rows: HubRow[], changed: HubRow, event?: RunEvent) => void;
24
+ }
25
+ /** Runs the sessions with at most `jobs` at a time. One run that throws makes that row failed and nothing more. */
26
+ export declare function runMany(inputs: string[], opts: HubOptions): Promise<HubRow[]>;
27
+ /** One line per row for the live view. */
28
+ export declare function hubLines(rows: HubRow[], width: number): string[];
29
+ /** 2 when a run failed or any run's exit code is 2, else 1 when any is 1, else 0. */
30
+ export declare function hubExitCode(rows: HubRow[], failOn: Severity | 'never'): 0 | 1 | 2;
31
+ /** The text table of the project list: a header row and one row per project, columns padded with spaces. */
32
+ export declare function projectTable(projects: Project[]): string;
package/dist/hub.js ADDED
@@ -0,0 +1,99 @@
1
+ import path from 'node:path';
2
+ import { summaryLine } from './report/markdown.js';
3
+ import { exitCode } from './runner.js';
4
+ import { runSession } from './session.js';
5
+ /** Runs the sessions with at most `jobs` at a time. One run that throws makes that row failed and nothing more. */
6
+ export async function runMany(inputs, opts) {
7
+ const rows = inputs.map((p) => ({ name: path.basename(path.resolve(p)), path: p, state: 'waiting', total: 0, done: 0 }));
8
+ const change = (row, event) => opts.onChange?.(rows, row, event);
9
+ let next = 0;
10
+ const worker = async () => {
11
+ while (next < rows.length) {
12
+ const i = next++;
13
+ const row = rows[i];
14
+ row.state = 'running';
15
+ change(row);
16
+ try {
17
+ const s = await runSession({
18
+ ...opts.session,
19
+ input: inputs[i],
20
+ onEvent: (e) => {
21
+ if (e.type === 'run:start') {
22
+ row.name = e.target.name;
23
+ row.total = e.jobs.length;
24
+ }
25
+ else if (e.type === 'engine:start') {
26
+ row.current = `${e.engine}${e.unit ? ' ' + e.unit : ''}`;
27
+ }
28
+ else if (e.type === 'engine:end') {
29
+ row.done++;
30
+ delete row.current;
31
+ }
32
+ change(row, e);
33
+ },
34
+ });
35
+ row.state = 'done';
36
+ row.result = s.result;
37
+ row.name = s.result.target.name;
38
+ if (s.files[0])
39
+ row.reportFile = s.files[0];
40
+ }
41
+ catch (err) {
42
+ row.state = 'failed';
43
+ row.error = err instanceof Error ? err.message : String(err);
44
+ }
45
+ delete row.current;
46
+ change(row);
47
+ }
48
+ };
49
+ await Promise.all(Array.from({ length: Math.max(1, Math.min(opts.jobs, rows.length)) }, worker));
50
+ return rows;
51
+ }
52
+ /** One line per row for the live view. */
53
+ export function hubLines(rows, width) {
54
+ const pad = Math.max(0, ...rows.map((r) => r.name.length));
55
+ return rows.map((r) => {
56
+ const name = r.name.padEnd(pad);
57
+ let text;
58
+ if (r.state === 'waiting')
59
+ text = ` ${name} waiting`;
60
+ else if (r.state === 'running')
61
+ text = ` ${name} ${r.done}/${r.total}${r.current ? ' ' + r.current : ''}`;
62
+ else if (r.state === 'failed')
63
+ text = ` ${name} failed: ${r.error}`;
64
+ else {
65
+ const failed = r.result.engines.filter((e) => e.status === 'failed').length;
66
+ text = ` ${name} ${summaryLine(r.result)}${failed ? ` ${failed} ${failed === 1 ? 'engine' : 'engines'} failed.` : ''}`;
67
+ }
68
+ return text.slice(0, width);
69
+ });
70
+ }
71
+ /** 2 when a run failed or any run's exit code is 2, else 1 when any is 1, else 0. */
72
+ export function hubExitCode(rows, failOn) {
73
+ let code = 0;
74
+ for (const r of rows) {
75
+ const c = r.state === 'done' && r.result ? exitCode(r.result, failOn) : 2;
76
+ if (c > code)
77
+ code = c;
78
+ }
79
+ return code;
80
+ }
81
+ const pad2 = (n) => String(n).padStart(2, '0');
82
+ function localTime(iso) {
83
+ const d = new Date(iso);
84
+ return `${d.getFullYear()}-${pad2(d.getMonth() + 1)}-${pad2(d.getDate())} ${pad2(d.getHours())}:${pad2(d.getMinutes())}`;
85
+ }
86
+ /** The text table of the project list: a header row and one row per project, columns padded with spaces. */
87
+ export function projectTable(projects) {
88
+ const kinds = { theme: 'theme', plugin: 'plugin', install: 'WordPress folder', url: 'site URL' };
89
+ const rows = [
90
+ ['ID', 'Name', 'Kind', 'Last run', 'Errors', 'Warnings', 'Notes', 'Path'],
91
+ ...projects.map((p) => {
92
+ const counts = p.last ? [p.last.summary.error, p.last.summary.warning, p.last.summary.info].map(String) : ['-', '-', '-'];
93
+ const when = p.problem ?? (p.last ? localTime(p.last.finishedAt) : 'never');
94
+ return [p.id, p.name, p.kind ? kinds[p.kind] : '-', when, ...(p.problem ? ['-', '-', '-'] : counts), p.path];
95
+ }),
96
+ ];
97
+ const widths = rows[0].map((_, c) => Math.max(...rows.map((r) => r[c].length)));
98
+ return rows.map((r) => r.map((cell, c) => (c === r.length - 1 ? cell : cell.padEnd(widths[c]))).join(' ').trimEnd()).join('\n');
99
+ }
@@ -0,0 +1,42 @@
1
+ export type * from './types.ts';
2
+ export { SEVERITIES, DEPTHS, EngineSkipped } from './types.ts';
3
+ export { detectTarget, unitLabel } from './target.ts';
4
+ export { run, exitCode } from './runner.ts';
5
+ export type { RunOptions } from './runner.ts';
6
+ export { runSession } from './session.ts';
7
+ export type { SessionOptions, SessionResult } from './session.ts';
8
+ export { startMcp } from './mcp/server.ts';
9
+ export type { McpOptions } from './mcp/server.ts';
10
+ export { tools, selectFindings } from './mcp/tools.ts';
11
+ export type { Tool, ToolContext } from './mcp/tools.ts';
12
+ export { startUi } from './ui/server.ts';
13
+ export type { UiServer } from './ui/server.ts';
14
+ export { loadBaseline, applyBaseline } from './baseline.ts';
15
+ export { diffRuns } from './diff.ts';
16
+ export { assignIds } from './fingerprint.ts';
17
+ export { toMarkdown } from './report/markdown.ts';
18
+ export { toJson } from './report/json.ts';
19
+ export { toSarif } from './report/sarif.ts';
20
+ export { toHtml } from './report/html.ts';
21
+ export { assertReportDir, defaultReportDir, readPreviousRun, writeReports } from './report/write.ts';
22
+ export { engines } from './engines/index.ts';
23
+ export { customEngines, globToRegExp } from './engines/custom.ts';
24
+ export { profiles, profileEngines } from './profiles.ts';
25
+ export { home } from './home.ts';
26
+ export { phpLint } from './engines/php-lint.ts';
27
+ export { themeCheck } from './engines/theme-check.ts';
28
+ export { themeReview } from './engines/theme-review.ts';
29
+ export { wpcs } from './engines/wpcs.ts';
30
+ export { phpCompat } from './engines/php-compat.ts';
31
+ export { phpstan } from './engines/phpstan.ts';
32
+ export { wpJson } from './engines/wp-json.ts';
33
+ export { eslint } from './engines/eslint.ts';
34
+ export { stylelint } from './engines/stylelint.ts';
35
+ export { integrity } from './engines/integrity.ts';
36
+ export { updates } from './engines/updates.ts';
37
+ export { vulnerabilities } from './engines/vulnerabilities.ts';
38
+ export { config } from './engines/config.ts';
39
+ export { compareVersions } from './versions.ts';
40
+ export { getJson } from './net.ts';
41
+ export { progressLine } from './progress.ts';
42
+ export { VERSION } from './version.ts';
package/dist/index.js ADDED
@@ -0,0 +1,36 @@
1
+ export { SEVERITIES, DEPTHS, EngineSkipped } from './types.js';
2
+ export { detectTarget, unitLabel } from './target.js';
3
+ export { run, exitCode } from './runner.js';
4
+ export { runSession } from './session.js';
5
+ export { startMcp } from './mcp/server.js';
6
+ export { tools, selectFindings } from './mcp/tools.js';
7
+ export { startUi } from './ui/server.js';
8
+ export { loadBaseline, applyBaseline } from './baseline.js';
9
+ export { diffRuns } from './diff.js';
10
+ export { assignIds } from './fingerprint.js';
11
+ export { toMarkdown } from './report/markdown.js';
12
+ export { toJson } from './report/json.js';
13
+ export { toSarif } from './report/sarif.js';
14
+ export { toHtml } from './report/html.js';
15
+ export { assertReportDir, defaultReportDir, readPreviousRun, writeReports } from './report/write.js';
16
+ export { engines } from './engines/index.js';
17
+ export { customEngines, globToRegExp } from './engines/custom.js';
18
+ export { profiles, profileEngines } from './profiles.js';
19
+ export { home } from './home.js';
20
+ export { phpLint } from './engines/php-lint.js';
21
+ export { themeCheck } from './engines/theme-check.js';
22
+ export { themeReview } from './engines/theme-review.js';
23
+ export { wpcs } from './engines/wpcs.js';
24
+ export { phpCompat } from './engines/php-compat.js';
25
+ export { phpstan } from './engines/phpstan.js';
26
+ export { wpJson } from './engines/wp-json.js';
27
+ export { eslint } from './engines/eslint.js';
28
+ export { stylelint } from './engines/stylelint.js';
29
+ export { integrity } from './engines/integrity.js';
30
+ export { updates } from './engines/updates.js';
31
+ export { vulnerabilities } from './engines/vulnerabilities.js';
32
+ export { config } from './engines/config.js';
33
+ export { compareVersions } from './versions.js';
34
+ export { getJson } from './net.js';
35
+ export { progressLine } from './progress.js';
36
+ export { VERSION } from './version.js';
@@ -0,0 +1,4 @@
1
+ /** Absolute paths of the files under `root` that end with one of `exts`, sorted. Minified files and skipped folders are left out. */
2
+ export declare function sourceFiles(root: string, exts: string[]): string[];
3
+ /** True for built output: a very long line near the top, a source map comment, or a sibling .map file. */
4
+ export declare function isGenerated(file: string): boolean;
@@ -0,0 +1,47 @@
1
+ import { closeSync, existsSync, openSync, readdirSync, readSync, statSync } from 'node:fs';
2
+ import path from 'node:path';
3
+ const SKIP = new Set(['node_modules', 'vendor', 'bower_components', 'build', 'dist']);
4
+ /** Absolute paths of the files under `root` that end with one of `exts`, sorted. Minified files and skipped folders are left out. */
5
+ export function sourceFiles(root, exts) {
6
+ const out = [];
7
+ const walk = (dir) => {
8
+ for (const e of readdirSync(dir, { withFileTypes: true })) {
9
+ const full = path.join(dir, e.name);
10
+ if (e.isDirectory()) {
11
+ if (!SKIP.has(e.name) && !e.name.startsWith('.'))
12
+ walk(full);
13
+ }
14
+ else if (e.isFile() && exts.some((x) => e.name.endsWith(x)) && !/\.min\.(js|css)$/.test(e.name)) {
15
+ out.push(full);
16
+ }
17
+ }
18
+ };
19
+ if (statSync(root).isDirectory())
20
+ walk(root);
21
+ return out.sort();
22
+ }
23
+ /** True for built output: a very long line near the top, a source map comment, or a sibling .map file. */
24
+ export function isGenerated(file) {
25
+ try {
26
+ if (existsSync(`${file}.map`))
27
+ return true;
28
+ const fd = openSync(file, 'r');
29
+ try {
30
+ const size = statSync(file).size;
31
+ const head = Buffer.alloc(Math.min(4096, size));
32
+ readSync(fd, head, 0, head.length, 0);
33
+ if (head.toString('utf8').split('\n').some((l) => l.length > 500))
34
+ return true;
35
+ const len = Math.min(512, size);
36
+ const tail = Buffer.alloc(len);
37
+ readSync(fd, tail, 0, len, size - len);
38
+ return tail.toString('utf8').includes('sourceMappingURL=');
39
+ }
40
+ finally {
41
+ closeSync(fd);
42
+ }
43
+ }
44
+ catch {
45
+ return false;
46
+ }
47
+ }
@@ -0,0 +1,3 @@
1
+ export declare function resetJsToolsCache(): void;
2
+ /** The folder that holds node_modules with ESLint and Stylelint. Installs it on first use. */
3
+ export declare function jsTools(note: (m: string) => void): Promise<string>;