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,67 @@
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
+ // Resolves to the package root from both src/js and dist/js.
9
+ const bundled = fileURLToPath(new URL('../../js-tools/', import.meta.url));
10
+ const FILES = ['package.json', 'package-lock.json', 'eslint.config.mjs', 'stylelint.config.mjs'];
11
+ let cached;
12
+ export function resetJsToolsCache() {
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');
18
+ for (const f of ['package-lock.json', 'eslint.config.mjs', 'stylelint.config.mjs'])
19
+ hash.update(readFileSync(path.join(bundled, f)));
20
+ const dir = path.join(home(), 'tools', `js-${hash.digest('hex').slice(0, 8)}`);
21
+ const ready = path.join(dir, 'node_modules', 'eslint', 'package.json');
22
+ if (existsSync(ready))
23
+ return dir;
24
+ const npm = process.env.WP_SHAKEDOWN_NPM || 'npm';
25
+ const noNpm = new EngineSkipped('npm was not found. wp-shakedown uses it once to fetch ESLint and Stylelint. Put npm on your PATH or set WP_SHAKEDOWN_NPM to its path.');
26
+ try {
27
+ if ((await exec(npm, ['--version'])).code !== 0)
28
+ throw noNpm;
29
+ }
30
+ catch (err) {
31
+ throw err instanceof NotFound ? noNpm : err;
32
+ }
33
+ note('Installing the JavaScript and CSS tools. This happens once.');
34
+ const tmp = `${dir}.tmp-${process.pid}`;
35
+ rmSync(tmp, { recursive: true, force: true });
36
+ mkdirSync(tmp, { recursive: true });
37
+ for (const f of FILES)
38
+ copyFileSync(path.join(bundled, f), path.join(tmp, f));
39
+ // shortcut: npm runs without a shell, so npm.cmd on Windows is not found. Spawn through a shell there when Windows support is tested.
40
+ const r = await exec(npm, ['ci', '--ignore-scripts', '--no-audit', '--no-fund'], { cwd: tmp });
41
+ if (r.code !== 0) {
42
+ rmSync(tmp, { recursive: true, force: true });
43
+ throw new Error(`npm could not install the JavaScript and CSS tools: ${lastLine(r.stderr) || lastLine(r.stdout)}`);
44
+ }
45
+ try {
46
+ renameSync(tmp, dir);
47
+ }
48
+ catch {
49
+ // Another process installed the tools first.
50
+ rmSync(tmp, { recursive: true, force: true });
51
+ }
52
+ if (!existsSync(ready))
53
+ throw new Error(`npm finished, but ESLint is not in "${dir}".`);
54
+ return dir;
55
+ }
56
+ /** The folder that holds node_modules with ESLint and Stylelint. Installs it on first use. */
57
+ export function jsTools(note) {
58
+ if (!cached) {
59
+ const p = install(note);
60
+ cached = p;
61
+ p.catch(() => {
62
+ if (cached === p)
63
+ cached = undefined;
64
+ });
65
+ }
66
+ return cached;
67
+ }
@@ -0,0 +1,9 @@
1
+ import type { Engine } from '../types.ts';
2
+ export interface McpOptions {
3
+ engines: Engine[];
4
+ input: NodeJS.ReadableStream;
5
+ output: NodeJS.WritableStream;
6
+ }
7
+ export declare function startMcp(opts: McpOptions): {
8
+ closed: Promise<void>;
9
+ };
@@ -0,0 +1,91 @@
1
+ import { createInterface } from 'node:readline';
2
+ import { Ajv } from 'ajv';
3
+ import { VERSION } from '../version.js';
4
+ import { tools } from './tools.js';
5
+ const VERSIONS = ['2025-11-25', '2025-06-18', '2025-03-26', '2024-11-05'];
6
+ const INSTRUCTIONS = 'Call run_checks with the folder of a theme, a plugin or a WordPress site. Fix the errors first. Call run_checks again to confirm that they are gone.';
7
+ const ajv = new Ajv({ strict: false, allErrors: true });
8
+ const validators = new Map(tools.map((t) => [t.name, ajv.compile(t.inputSchema)]));
9
+ export function startMcp(opts) {
10
+ const running = new Map();
11
+ const send = (m) => {
12
+ opts.output.write(JSON.stringify({ jsonrpc: '2.0', ...m }) + '\n');
13
+ };
14
+ const reply = (id, result) => send({ id, result });
15
+ const fail = (id, code, message) => send({ id, error: { code, message } });
16
+ const text = (s, isError = false) => ({ content: [{ type: 'text', text: s }], ...(isError ? { isError } : {}) });
17
+ async function call(id, params) {
18
+ const tool = tools.find((t) => t.name === params.name);
19
+ if (!tool)
20
+ return fail(id, -32602, `Unknown tool: ${params.name}`);
21
+ const args = (params.arguments ?? {});
22
+ const validate = validators.get(tool.name);
23
+ if (!validate(args))
24
+ return reply(id, text(`Invalid arguments: ${ajv.errorsText(validate.errors)}`, true));
25
+ const ac = new AbortController();
26
+ running.set(id, ac);
27
+ const token = params._meta?.progressToken;
28
+ const progress = (done, total, message) => {
29
+ if (token !== undefined)
30
+ send({ method: 'notifications/progress', params: { progressToken: token, progress: done, total, message } });
31
+ };
32
+ try {
33
+ reply(id, text(await tool.handler(args, { engines: opts.engines, signal: ac.signal, progress })));
34
+ }
35
+ catch (err) {
36
+ reply(id, text(err instanceof Error ? err.message : String(err), true));
37
+ }
38
+ finally {
39
+ running.delete(id);
40
+ }
41
+ }
42
+ function handle(m) {
43
+ if (m.id === undefined) {
44
+ if (m.method === 'notifications/cancelled')
45
+ running.get(m.params?.requestId)?.abort();
46
+ return;
47
+ }
48
+ const { id, params = {} } = m;
49
+ switch (m.method) {
50
+ case 'initialize':
51
+ return reply(id, {
52
+ protocolVersion: VERSIONS.includes(params.protocolVersion) ? params.protocolVersion : '2025-06-18',
53
+ capabilities: { tools: {} },
54
+ serverInfo: { name: 'wp-shakedown', version: VERSION },
55
+ instructions: INSTRUCTIONS,
56
+ });
57
+ case 'ping':
58
+ return reply(id, {});
59
+ case 'tools/list':
60
+ return reply(id, { tools: tools.map(({ name, title, description, inputSchema, annotations }) => ({ name, title, description, inputSchema, annotations })) });
61
+ case 'tools/call':
62
+ // Not awaited: the next line is read while the tool runs.
63
+ void call(id, params);
64
+ return;
65
+ default:
66
+ return fail(id, -32601, `Method not found: ${m.method}`);
67
+ }
68
+ }
69
+ const rl = createInterface({ input: opts.input });
70
+ rl.on('line', (line) => {
71
+ if (!line.trim())
72
+ return;
73
+ let data;
74
+ try {
75
+ data = JSON.parse(line);
76
+ }
77
+ catch {
78
+ return fail(null, -32700, 'Parse error');
79
+ }
80
+ for (const m of Array.isArray(data) ? data : [data]) {
81
+ if (m && typeof m === 'object')
82
+ handle(m);
83
+ }
84
+ });
85
+ const closed = new Promise((resolve) => rl.on('close', () => {
86
+ for (const ac of running.values())
87
+ ac.abort();
88
+ resolve();
89
+ }));
90
+ return { closed };
91
+ }
@@ -0,0 +1,26 @@
1
+ import type { Engine, Finding, Severity } from '../types.ts';
2
+ export interface ToolContext {
3
+ engines: Engine[];
4
+ signal: AbortSignal;
5
+ progress: (done: number, total: number, message: string) => void;
6
+ }
7
+ export interface Tool {
8
+ name: string;
9
+ title: string;
10
+ description: string;
11
+ inputSchema: object;
12
+ annotations: {
13
+ readOnlyHint: boolean;
14
+ };
15
+ handler: (args: Record<string, unknown>, ctx: ToolContext) => Promise<string>;
16
+ }
17
+ export interface FindingFilter {
18
+ severity?: Severity;
19
+ engine?: string;
20
+ category?: string;
21
+ file?: string;
22
+ id?: string;
23
+ include_style?: boolean;
24
+ }
25
+ export declare function selectFindings(findings: Finding[], f: FindingFilter): Finding[];
26
+ export declare const tools: Tool[];
@@ -0,0 +1,163 @@
1
+ import path from 'node:path';
2
+ import { defaultReportDir, readPreviousRun } from '../report/write.js';
3
+ import { toMarkdown } from '../report/markdown.js';
4
+ import { customEngines } from '../engines/custom.js';
5
+ import { profiles } from '../profiles.js';
6
+ import { runSession } from '../session.js';
7
+ import { detectTarget } from '../target.js';
8
+ const MAX_TEXT = 60000;
9
+ const schema = (properties, required) => ({
10
+ type: 'object',
11
+ properties,
12
+ required,
13
+ additionalProperties: false,
14
+ });
15
+ export function selectFindings(findings, f) {
16
+ const file = f.file?.toLowerCase();
17
+ return findings.filter((x) => {
18
+ if (x.suppressed)
19
+ return false;
20
+ if (x.category === 'standards' && !f.include_style && !f.id)
21
+ return false;
22
+ if (f.severity && x.severity !== f.severity)
23
+ return false;
24
+ if (f.engine && x.engine !== f.engine)
25
+ return false;
26
+ if (f.category && x.category !== f.category)
27
+ return false;
28
+ if (f.id && x.id !== f.id)
29
+ return false;
30
+ if (file && !(x.location.file ?? x.location.url ?? '').toLowerCase().includes(file))
31
+ return false;
32
+ return true;
33
+ });
34
+ }
35
+ let running = false;
36
+ export const tools = [
37
+ {
38
+ name: 'detect_target',
39
+ title: 'Detect a target',
40
+ description: 'Says what a folder is: a theme, a plugin or a WordPress site, and for a site which themes and plugins it holds.',
41
+ inputSchema: schema({ path: { type: 'string', description: 'Absolute path of the folder.' } }, ['path']),
42
+ annotations: { readOnlyHint: true },
43
+ handler: async (args) => {
44
+ const t = detectTarget(args.path);
45
+ const units = t.units.map(({ kind, name, path: p }) => ({ kind, name, path: path.relative(t.path, p).split(path.sep).join('/') }));
46
+ return JSON.stringify({ kind: t.kind, name: t.name, path: t.path, units }, null, 2);
47
+ },
48
+ },
49
+ {
50
+ name: 'list_engines',
51
+ title: 'List the engines',
52
+ description: 'Lists the checks wp-shakedown can run, with the ID to pass to run_checks.',
53
+ inputSchema: schema({}, []),
54
+ annotations: { readOnlyHint: true },
55
+ handler: async (_args, ctx) => JSON.stringify([...ctx.engines, ...customEngines()].map(({ id, title, kinds, depth, experimental }) => ({ id, title, kinds, depth: depth ?? 'standard', ...(experimental ? { experimental: true } : {}) })), null, 2),
56
+ },
57
+ {
58
+ name: 'run_checks',
59
+ title: 'Run the checks',
60
+ description: 'Runs the checks on a theme, a plugin or a WordPress site folder and returns the report as Markdown. Errors come first in importance. Code style findings are counted per rule and not listed. The run writes report files but never changes the target.',
61
+ inputSchema: schema({
62
+ path: { type: 'string', description: 'Absolute path of the folder to test.' },
63
+ engines: { type: 'array', items: { type: 'string' }, description: 'Engine IDs to run. Leave out to run all that fit.' },
64
+ profile: {
65
+ type: 'string',
66
+ enum: profiles.map((p) => p.id),
67
+ description: 'Run only the engines for one gate. ' + profiles.map((p) => `${p.id}: ${p.summary}`).join(' '),
68
+ },
69
+ depth: { type: 'string', enum: ['quick', 'standard', 'deep'], description: 'How thorough the run is. quick runs the fast checks, standard is the default, deep adds static analysis.' },
70
+ experimental: { type: 'boolean', description: 'Also run the experimental engines, such as theme-review.' },
71
+ type: { type: 'string', enum: ['theme', 'plugin', 'install'], description: 'Use only when detection is wrong.' },
72
+ }, ['path']),
73
+ annotations: { readOnlyHint: false },
74
+ handler: async (args, ctx) => {
75
+ if (running)
76
+ throw new Error('A run is in progress. Wait for it to finish.');
77
+ const only = args.engines;
78
+ const all = [...ctx.engines, ...customEngines()];
79
+ for (const id of only ?? []) {
80
+ if (!all.some((e) => e.id === id))
81
+ throw new Error(`Unknown engine "${id}". Call list_engines for the IDs.`);
82
+ }
83
+ running = true;
84
+ try {
85
+ let total = 0;
86
+ let done = 0;
87
+ const type = args.type;
88
+ const depth = args.depth;
89
+ const s = await runSession({
90
+ input: args.path,
91
+ ...(type ? { type } : {}),
92
+ ...(only?.length ? { only } : {}),
93
+ ...(args.profile ? { profile: args.profile } : {}),
94
+ ...(depth ? { depth } : {}),
95
+ ...(args.experimental ? { experimental: true } : {}),
96
+ engines: ctx.engines,
97
+ signal: ctx.signal,
98
+ onEvent: (e) => {
99
+ if (e.type === 'run:start')
100
+ total = e.jobs.length;
101
+ else if (e.type === 'engine:end') {
102
+ done++;
103
+ ctx.progress(done, total, `${e.run.engine}${e.run.unit ? ' ' + e.run.unit : ''}: ${e.run.status}`);
104
+ }
105
+ },
106
+ });
107
+ const text = toMarkdown(s.result, s.diff);
108
+ if (text.length > MAX_TEXT) {
109
+ const cut = text.lastIndexOf('\n', MAX_TEXT);
110
+ return `${text.slice(0, cut > 0 ? cut : MAX_TEXT)}\n\nThe report is cut here. The full report is at ${s.files[0]}. Call list_findings to page through the findings.`;
111
+ }
112
+ return `${text}\n\nReport file: ${s.files[0]}`;
113
+ }
114
+ finally {
115
+ running = false;
116
+ }
117
+ },
118
+ },
119
+ {
120
+ name: 'list_findings',
121
+ title: 'List findings of the last run',
122
+ description: 'Returns findings from the last run on a folder, filtered and paged, as JSON. Use it after run_checks when the report was cut or when you want one severity, engine or file.',
123
+ inputSchema: schema({
124
+ path: { type: 'string', description: 'Absolute path of the folder that was tested.' },
125
+ severity: { type: 'string', enum: ['error', 'warning', 'info'] },
126
+ engine: { type: 'string' },
127
+ category: { type: 'string' },
128
+ file: { type: 'string', description: 'Part of a file path.' },
129
+ id: { type: 'string', description: 'One finding ID.' },
130
+ include_style: { type: 'boolean', description: 'Also list code style findings. They are left out by default.' },
131
+ limit: { type: 'integer', minimum: 1, maximum: 200 },
132
+ offset: { type: 'integer', minimum: 0 },
133
+ }, ['path']),
134
+ annotations: { readOnlyHint: true },
135
+ handler: async (args) => {
136
+ const target = detectTarget(args.path);
137
+ const prev = readPreviousRun(defaultReportDir(target));
138
+ if (!prev)
139
+ throw new Error('No report for this folder yet. Call run_checks first.');
140
+ const selected = selectFindings(prev.findings, args);
141
+ const limit = args.limit ?? 50;
142
+ const offset = args.offset ?? 0;
143
+ const page = selected.slice(offset, offset + limit);
144
+ return JSON.stringify({
145
+ total: selected.length,
146
+ offset,
147
+ findings: page.map((x) => ({
148
+ id: x.id,
149
+ severity: x.severity,
150
+ category: x.category,
151
+ engine: x.engine,
152
+ rule: x.rule,
153
+ message: x.message,
154
+ file: x.location.file ?? x.location.url,
155
+ line: x.location.line,
156
+ hint: x.hint,
157
+ docs: x.docs,
158
+ unit: x.unit,
159
+ })),
160
+ }, null, 2);
161
+ },
162
+ },
163
+ ];
package/dist/net.d.ts ADDED
@@ -0,0 +1,18 @@
1
+ export declare class Unreachable extends Error {
2
+ }
3
+ /** Tests replace `net.fetch`. */
4
+ export declare const net: {
5
+ fetch: (url: string, init?: RequestInit) => Promise<Response>;
6
+ };
7
+ interface Cached {
8
+ status: 200 | 404;
9
+ data: unknown;
10
+ }
11
+ export interface GetJsonOptions {
12
+ ttlMs: number;
13
+ headers?: Record<string, string>;
14
+ signal?: AbortSignal;
15
+ }
16
+ /** GET a JSON document with a disk cache. A stale cache answers when the network does not. */
17
+ export declare function getJson(url: string, opts: GetJsonOptions): Promise<Cached>;
18
+ export {};
package/dist/net.js ADDED
@@ -0,0 +1,68 @@
1
+ import { createHash } from 'node:crypto';
2
+ import { mkdirSync, readFileSync, statSync, writeFileSync } from 'node:fs';
3
+ import path from 'node:path';
4
+ import { home } from './home.js';
5
+ export class Unreachable extends Error {
6
+ }
7
+ /** Tests replace `net.fetch`. */
8
+ export const net = { fetch: (url, init) => fetch(url, init) };
9
+ /** GET a JSON document with a disk cache. A stale cache answers when the network does not. */
10
+ export async function getJson(url, opts) {
11
+ const file = path.join(home(), 'cache', 'http', `${createHash('sha256').update(url).digest('hex').slice(0, 16)}.json`);
12
+ const read = () => {
13
+ try {
14
+ const c = JSON.parse(readFileSync(file, 'utf8'));
15
+ return c && (c.status === 200 || c.status === 404) ? c : undefined;
16
+ }
17
+ catch {
18
+ return undefined;
19
+ }
20
+ };
21
+ const store = (c) => {
22
+ mkdirSync(path.dirname(file), { recursive: true });
23
+ writeFileSync(file, JSON.stringify(c));
24
+ return c;
25
+ };
26
+ const stale = read();
27
+ if (stale && Date.now() - statSync(file).mtimeMs < opts.ttlMs)
28
+ return stale;
29
+ const host = new URL(url).host;
30
+ const timeout = AbortSignal.timeout(20000);
31
+ let res;
32
+ try {
33
+ res = await net.fetch(url, {
34
+ ...(opts.headers ? { headers: opts.headers } : {}),
35
+ signal: opts.signal ? AbortSignal.any([timeout, opts.signal]) : timeout,
36
+ });
37
+ }
38
+ catch {
39
+ // A network error falls back to the stale cache below.
40
+ }
41
+ if (res) {
42
+ if (res.status === 401 || res.status === 403)
43
+ throw new Unreachable(`${host} rejected the request (${res.status}).`);
44
+ if (res.status === 200 || res.status === 404) {
45
+ try {
46
+ const text = await res.text();
47
+ if (res.status === 200)
48
+ return store({ status: 200, data: JSON.parse(text) });
49
+ let data = null;
50
+ try {
51
+ data = JSON.parse(text);
52
+ }
53
+ catch {
54
+ // A 404 body that is not JSON counts as no data.
55
+ }
56
+ return store({ status: 404, data });
57
+ }
58
+ catch {
59
+ // A 200 body that does not parse falls back to the stale cache below.
60
+ }
61
+ }
62
+ if (res.status === 429 && !stale)
63
+ throw new Unreachable(`${host} asked to slow down (429).`);
64
+ }
65
+ if (stale)
66
+ return stale;
67
+ throw new Unreachable(`Cannot reach ${host}.`);
68
+ }
@@ -0,0 +1,3 @@
1
+ export declare function phpFiles(target: string): string[];
2
+ /** The "Requires PHP" header as major.minor, or undefined. */
3
+ export declare function requiresPhp(target: string): string | undefined;
@@ -0,0 +1,53 @@
1
+ import { closeSync, openSync, readdirSync, readSync, statSync } from 'node:fs';
2
+ import path from 'node:path';
3
+ export function phpFiles(target) {
4
+ if (statSync(target).isFile())
5
+ return [target];
6
+ const out = [];
7
+ const walk = (dir) => {
8
+ for (const e of readdirSync(dir, { withFileTypes: true })) {
9
+ const p = path.join(dir, e.name);
10
+ if (e.isDirectory()) {
11
+ if (e.name !== 'vendor' && e.name !== 'node_modules' && !e.name.startsWith('.'))
12
+ walk(p);
13
+ }
14
+ else if (e.isFile() && e.name.endsWith('.php'))
15
+ out.push(p);
16
+ }
17
+ };
18
+ walk(target);
19
+ return out.sort();
20
+ }
21
+ function head(file) {
22
+ let fd;
23
+ try {
24
+ fd = openSync(file, 'r');
25
+ const buf = Buffer.alloc(8192);
26
+ return buf.toString('utf8', 0, readSync(fd, buf, 0, 8192, 0));
27
+ }
28
+ catch {
29
+ return '';
30
+ }
31
+ finally {
32
+ if (fd !== undefined)
33
+ closeSync(fd);
34
+ }
35
+ }
36
+ /** The "Requires PHP" header as major.minor, or undefined. */
37
+ export function requiresPhp(target) {
38
+ let files;
39
+ if (statSync(target).isFile())
40
+ files = [target];
41
+ else {
42
+ const top = readdirSync(target, { withFileTypes: true });
43
+ const php = top.filter((e) => e.isFile() && e.name.endsWith('.php')).map((e) => e.name).sort();
44
+ files = ['style.css', ...php, 'readme.txt'].map((n) => path.join(target, n));
45
+ }
46
+ for (const f of files) {
47
+ const m = /^[ \t\/*#@]*Requires PHP:\s*(\d+)(\.\d+)?/im.exec(head(f));
48
+ // "Requires PHP: 8" means 8.0.
49
+ if (m)
50
+ return `${m[1]}${m[2] ?? '.0'}`;
51
+ }
52
+ return undefined;
53
+ }
@@ -0,0 +1,4 @@
1
+ export declare function phpBinary(): string;
2
+ export declare function resetPhpCache(): void;
3
+ /** The PHP version, for example "8.4.25". Looked up once per process. */
4
+ export declare function phpVersion(): Promise<string>;
@@ -0,0 +1,25 @@
1
+ import { exec, NotFound } from '../exec.js';
2
+ import { EngineSkipped } from '../types.js';
3
+ export function phpBinary() {
4
+ return process.env.WP_SHAKEDOWN_PHP || 'php';
5
+ }
6
+ let cached;
7
+ export function resetPhpCache() {
8
+ cached = undefined;
9
+ }
10
+ async function detect() {
11
+ const missing = new EngineSkipped('PHP is not installed. Put php on your PATH or set WP_SHAKEDOWN_PHP to its path.');
12
+ try {
13
+ const r = await exec(phpBinary(), ['-r', 'echo PHP_VERSION;']);
14
+ if (r.code !== 0)
15
+ throw missing;
16
+ return r.stdout.trim();
17
+ }
18
+ catch (err) {
19
+ throw err instanceof NotFound ? missing : err;
20
+ }
21
+ }
22
+ /** The PHP version, for example "8.4.25". Looked up once per process. */
23
+ export function phpVersion() {
24
+ return (cached ??= detect());
25
+ }
@@ -0,0 +1,25 @@
1
+ import type { Target } from '../types.ts';
2
+ export interface PhpcsMessage {
3
+ file: string;
4
+ line: number;
5
+ column: number;
6
+ source: string;
7
+ message: string;
8
+ type: 'ERROR' | 'WARNING';
9
+ fixable: boolean;
10
+ }
11
+ export declare function parsePhpcs(json: string): PhpcsMessage[];
12
+ /**
13
+ * PHPCS matches --ignore against the absolute path, so a plain vendor pattern
14
+ * would drop every file of a target that itself sits below a vendor folder.
15
+ * The pattern is a regular expression anchored to the target. PHPCS turns a
16
+ * star into ".*" and splits on commas, so neither may appear unescaped.
17
+ */
18
+ export declare function ignorePattern(base: string): string;
19
+ export declare function runPhpcs(opts: {
20
+ target: Target;
21
+ standard: string | ((tools: string) => string);
22
+ extra?: string[];
23
+ signal?: AbortSignal;
24
+ note: (m: string) => void;
25
+ }): Promise<PhpcsMessage[]>;
@@ -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,3 @@
1
+ export declare function resetToolsCache(): void;
2
+ /** The folder that holds vendor/bin/phpcs. Installs it on first use. */
3
+ export declare function phpTools(note: (m: string) => void): Promise<string>;