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.
Files changed (103) hide show
  1. package/LICENSE +340 -0
  2. package/README.md +62 -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 +139 -0
  7. package/dist/diff.d.ts +7 -0
  8. package/dist/diff.js +24 -0
  9. package/dist/engines/config.d.ts +3 -0
  10. package/dist/engines/config.js +133 -0
  11. package/dist/engines/eslint.d.ts +8 -0
  12. package/dist/engines/eslint.js +96 -0
  13. package/dist/engines/index.d.ts +2 -0
  14. package/dist/engines/index.js +12 -0
  15. package/dist/engines/integrity.d.ts +2 -0
  16. package/dist/engines/integrity.js +108 -0
  17. package/dist/engines/php-compat.d.ts +2 -0
  18. package/dist/engines/php-compat.js +26 -0
  19. package/dist/engines/php-lint.d.ts +6 -0
  20. package/dist/engines/php-lint.js +41 -0
  21. package/dist/engines/phpstan.d.ts +11 -0
  22. package/dist/engines/phpstan.js +102 -0
  23. package/dist/engines/stylelint.d.ts +4 -0
  24. package/dist/engines/stylelint.js +63 -0
  25. package/dist/engines/updates.d.ts +4 -0
  26. package/dist/engines/updates.js +72 -0
  27. package/dist/engines/vulnerabilities.d.ts +22 -0
  28. package/dist/engines/vulnerabilities.js +128 -0
  29. package/dist/engines/wp-json.d.ts +18 -0
  30. package/dist/engines/wp-json.js +133 -0
  31. package/dist/engines/wpcs.d.ts +7 -0
  32. package/dist/engines/wpcs.js +60 -0
  33. package/dist/exec.d.ts +12 -0
  34. package/dist/exec.js +19 -0
  35. package/dist/fingerprint.d.ts +10 -0
  36. package/dist/fingerprint.js +29 -0
  37. package/dist/health/install.d.ts +16 -0
  38. package/dist/health/install.js +68 -0
  39. package/dist/home.d.ts +2 -0
  40. package/dist/home.js +6 -0
  41. package/dist/index.d.ts +38 -0
  42. package/dist/index.js +32 -0
  43. package/dist/js/files.d.ts +4 -0
  44. package/dist/js/files.js +47 -0
  45. package/dist/js/tools.d.ts +3 -0
  46. package/dist/js/tools.js +67 -0
  47. package/dist/mcp/server.d.ts +9 -0
  48. package/dist/mcp/server.js +91 -0
  49. package/dist/mcp/tools.d.ts +26 -0
  50. package/dist/mcp/tools.js +149 -0
  51. package/dist/net.d.ts +18 -0
  52. package/dist/net.js +68 -0
  53. package/dist/php/files.d.ts +3 -0
  54. package/dist/php/files.js +53 -0
  55. package/dist/php/php.d.ts +4 -0
  56. package/dist/php/php.js +25 -0
  57. package/dist/php/phpcs.d.ts +25 -0
  58. package/dist/php/phpcs.js +55 -0
  59. package/dist/php/tools.d.ts +3 -0
  60. package/dist/php/tools.js +66 -0
  61. package/dist/progress.d.ts +3 -0
  62. package/dist/progress.js +13 -0
  63. package/dist/report/escape.d.ts +1 -0
  64. package/dist/report/escape.js +4 -0
  65. package/dist/report/html.d.ts +2 -0
  66. package/dist/report/html.js +100 -0
  67. package/dist/report/json.d.ts +2 -0
  68. package/dist/report/json.js +3 -0
  69. package/dist/report/markdown.d.ts +5 -0
  70. package/dist/report/markdown.js +92 -0
  71. package/dist/report/sarif.d.ts +2 -0
  72. package/dist/report/sarif.js +44 -0
  73. package/dist/report/write.d.ts +9 -0
  74. package/dist/report/write.js +48 -0
  75. package/dist/runner.d.ts +11 -0
  76. package/dist/runner.js +152 -0
  77. package/dist/session.d.ts +19 -0
  78. package/dist/session.js +31 -0
  79. package/dist/target.d.ts +5 -0
  80. package/dist/target.js +114 -0
  81. package/dist/types.d.ts +135 -0
  82. package/dist/types.js +4 -0
  83. package/dist/ui/server.d.ts +13 -0
  84. package/dist/ui/server.js +295 -0
  85. package/dist/version.d.ts +1 -0
  86. package/dist/version.js +3 -0
  87. package/dist/versions.d.ts +9 -0
  88. package/dist/versions.js +35 -0
  89. package/js-tools/eslint.config.mjs +19 -0
  90. package/js-tools/package-lock.json +7004 -0
  91. package/js-tools/package.json +13 -0
  92. package/js-tools/stylelint.config.mjs +4 -0
  93. package/package.json +57 -4
  94. package/php-tools/composer.json +40 -0
  95. package/php-tools/composer.lock +868 -0
  96. package/ui/dist/assets/geist-cyrillic-ext-wght-normal-DjL33-gN.woff2 +0 -0
  97. package/ui/dist/assets/geist-cyrillic-wght-normal-BEAKL7Jp.woff2 +0 -0
  98. package/ui/dist/assets/geist-latin-ext-wght-normal-DC-KSUi6.woff2 +0 -0
  99. package/ui/dist/assets/geist-latin-wght-normal-BgDaEnEv.woff2 +0 -0
  100. package/ui/dist/assets/geist-vietnamese-wght-normal-6IgcOCM7.woff2 +0 -0
  101. package/ui/dist/assets/index-7zN46ssH.js +54 -0
  102. package/ui/dist/assets/index-B1axZya5.css +2 -0
  103. package/ui/dist/index.html +14 -0
@@ -0,0 +1,31 @@
1
+ import { existsSync } from 'node:fs';
2
+ import path from 'node:path';
3
+ import { loadBaseline } from './baseline.js';
4
+ import { diffRuns } from './diff.js';
5
+ import { assertReportDir, defaultReportDir, readPreviousRun, writeReports } from './report/write.js';
6
+ import { run } from './runner.js';
7
+ import { detectTarget } from './target.js';
8
+ /** The steps from a path to written reports. The command line and the local server share them. */
9
+ export async function runSession(opts) {
10
+ const target = detectTarget(opts.input, opts.type ? { type: opts.type } : {});
11
+ let baselineFile = opts.baselineFile;
12
+ if (!baselineFile && target.kind !== 'url') {
13
+ const candidate = path.join(target.path, 'wp-shakedown-baseline.json');
14
+ if (existsSync(candidate))
15
+ baselineFile = candidate;
16
+ }
17
+ const baseline = baselineFile ? loadBaseline(baselineFile) : undefined;
18
+ const dir = opts.out ?? defaultReportDir(target);
19
+ assertReportDir(target, dir);
20
+ const previous = readPreviousRun(dir);
21
+ const result = await run(target, {
22
+ engines: opts.engines,
23
+ ...(opts.only ? { only: opts.only } : {}),
24
+ ...(baseline ? { baseline } : {}),
25
+ ...(opts.onEvent ? { onEvent: opts.onEvent } : {}),
26
+ ...(opts.signal ? { signal: opts.signal } : {}),
27
+ });
28
+ const diff = previous ? diffRuns(previous, result) : undefined;
29
+ const files = writeReports(result, dir, diff);
30
+ return { result, ...(diff ? { diff } : {}), files, dir };
31
+ }
@@ -0,0 +1,5 @@
1
+ import type { Target } from './types.ts';
2
+ export declare function detectTarget(input: string, opts?: {
3
+ type?: 'theme' | 'plugin' | 'install';
4
+ }): Target;
5
+ export declare function unitLabel(unit: Target): string;
package/dist/target.js ADDED
@@ -0,0 +1,114 @@
1
+ import { existsSync, readdirSync, readFileSync, statSync, openSync, readSync, closeSync } from 'node:fs';
2
+ import path from 'node:path';
3
+ const THEME_RE = /^[ \t\/*#@]*Theme Name:\s*(.+)$/im;
4
+ const PLUGIN_RE = /^[ \t\/*#@]*Plugin Name:\s*(.+)$/im;
5
+ function head(file) {
6
+ const fd = openSync(file, 'r');
7
+ try {
8
+ const buf = Buffer.alloc(8192);
9
+ const n = readSync(fd, buf, 0, 8192, 0);
10
+ return buf.subarray(0, n).toString('utf8');
11
+ }
12
+ finally {
13
+ closeSync(fd);
14
+ }
15
+ }
16
+ function isDir(p) {
17
+ try {
18
+ return statSync(p).isDirectory();
19
+ }
20
+ catch {
21
+ return false;
22
+ }
23
+ }
24
+ function isFile(p) {
25
+ try {
26
+ return statSync(p).isFile();
27
+ }
28
+ catch {
29
+ return false;
30
+ }
31
+ }
32
+ /** The header value, without the comment end of a one-line header. */
33
+ function headerValue(re, file) {
34
+ return re.exec(head(file))?.[1]?.replace(/\*\/\s*$/, '').trim() || undefined;
35
+ }
36
+ function themeName(dir) {
37
+ const css = path.join(dir, 'style.css');
38
+ if (!isFile(css))
39
+ return undefined;
40
+ return headerValue(THEME_RE, css);
41
+ }
42
+ function visible(dir) {
43
+ try {
44
+ return readdirSync(dir).filter((n) => !n.startsWith('.')).sort();
45
+ }
46
+ catch {
47
+ return [];
48
+ }
49
+ }
50
+ /** First top-level PHP file with a Plugin Name header, in sorted order. */
51
+ function pluginName(dir) {
52
+ for (const n of visible(dir)) {
53
+ const f = path.join(dir, n);
54
+ if (!n.endsWith('.php') || !isFile(f))
55
+ continue;
56
+ const name = headerValue(PLUGIN_RE, f);
57
+ if (name)
58
+ return name;
59
+ }
60
+ return undefined;
61
+ }
62
+ function discoverUnits(root) {
63
+ const units = [];
64
+ // shortcut: reads wp-content at the install root and skips mu-plugins. Read WP_CONTENT_DIR from wp-config.php when someone has a relocated content folder.
65
+ const themes = path.join(root, 'wp-content', 'themes');
66
+ for (const n of visible(themes)) {
67
+ const p = path.join(themes, n);
68
+ if (!isDir(p))
69
+ continue;
70
+ units.push({ kind: 'theme', path: p, name: themeName(p) ?? n, units: [] });
71
+ }
72
+ const plugins = path.join(root, 'wp-content', 'plugins');
73
+ for (const n of visible(plugins)) {
74
+ const p = path.join(plugins, n);
75
+ if (isDir(p)) {
76
+ units.push({ kind: 'plugin', path: p, name: pluginName(p) ?? n, units: [] });
77
+ }
78
+ else if (n.endsWith('.php') && isFile(p)) {
79
+ const name = headerValue(PLUGIN_RE, p);
80
+ if (name)
81
+ units.push({ kind: 'plugin', path: p, name, units: [] });
82
+ }
83
+ }
84
+ return units;
85
+ }
86
+ export function detectTarget(input, opts = {}) {
87
+ if (/^https?:\/\//.test(input)) {
88
+ return { kind: 'url', path: input, name: new URL(input).host, units: [] };
89
+ }
90
+ const abs = path.resolve(input);
91
+ if (!isDir(abs))
92
+ throw new Error(`"${input}" is not a folder.`);
93
+ const base = path.basename(abs);
94
+ let kind = opts.type;
95
+ let name;
96
+ if (!kind) {
97
+ if (existsSync(path.join(abs, 'wp-includes', 'version.php')))
98
+ kind = 'install';
99
+ else if ((name = themeName(abs)))
100
+ kind = 'theme';
101
+ else if ((name = pluginName(abs)))
102
+ kind = 'plugin';
103
+ else {
104
+ throw new Error(`Cannot tell what "${input}" is. It has no wp-includes/version.php, no style.css with a Theme Name header and no PHP file with a Plugin Name header. Pass --type theme, --type plugin or --type install.`);
105
+ }
106
+ }
107
+ if (kind === 'install')
108
+ return { kind, path: abs, name: base, units: discoverUnits(abs) };
109
+ name ??= kind === 'theme' ? themeName(abs) : pluginName(abs);
110
+ return { kind, path: abs, name: name ?? base, units: [] };
111
+ }
112
+ export function unitLabel(unit) {
113
+ return `${unit.kind}:${path.basename(unit.path).replace(/\.php$/, '')}`;
114
+ }
@@ -0,0 +1,135 @@
1
+ export declare const SEVERITIES: readonly ['error', 'warning', 'info'];
2
+ export type Severity = (typeof SEVERITIES)[number];
3
+ export type Category = 'security' | 'compatibility' | 'standards' | 'correctness' | 'performance' | 'accessibility' | 'i18n' | 'health' | 'other';
4
+ export type TargetKind = 'theme' | 'plugin' | 'install' | 'url';
5
+ export interface Target {
6
+ kind: TargetKind;
7
+ /** Absolute path of the folder. A one-file plugin has the path of its PHP file. A 'url' target has the URL. */
8
+ path: string;
9
+ /** Name from the theme or plugin header, the folder name otherwise. */
10
+ name: string;
11
+ /** Themes and plugins found inside an install. Empty for every other kind. */
12
+ units: Target[];
13
+ }
14
+ export interface Location {
15
+ /** POSIX path relative to the root target. */
16
+ file?: string;
17
+ line?: number;
18
+ column?: number;
19
+ url?: string;
20
+ selector?: string;
21
+ }
22
+ /** What an engine returns. `location.file` is relative to the target the engine was given. */
23
+ export interface RawFinding {
24
+ rule: string;
25
+ severity: Severity;
26
+ category: Category;
27
+ message: string;
28
+ location: Location;
29
+ hint?: string;
30
+ docs?: string;
31
+ }
32
+ export interface Finding extends RawFinding {
33
+ /** Stable between runs. The line is not part of it, so edits above a finding keep its ID. */
34
+ id: string;
35
+ engine: string;
36
+ /** Set when the finding belongs to a theme or plugin inside an install, as `theme:<folder>` or `plugin:<folder>`. */
37
+ unit?: string;
38
+ /** Command that runs the engine that produced this finding again. */
39
+ rerun: string;
40
+ suppressed?: {
41
+ reason: string;
42
+ };
43
+ }
44
+ export interface EngineContext {
45
+ target: Target;
46
+ signal?: AbortSignal;
47
+ /** Tells the user something while the engine runs, for example that tools are being installed. */
48
+ note(message: string): void;
49
+ }
50
+ export interface Engine {
51
+ id: string;
52
+ title: string;
53
+ kinds: readonly TargetKind[];
54
+ run(ctx: EngineContext): Promise<RawFinding[]>;
55
+ }
56
+ /** An engine throws this when it cannot run here, for example when PHP is missing. The run continues. */
57
+ export declare class EngineSkipped extends Error {
58
+ }
59
+ export type EngineStatus = 'ok' | 'skipped' | 'failed';
60
+ export interface EngineRun {
61
+ engine: string;
62
+ unit?: string;
63
+ status: EngineStatus;
64
+ durationMs: number;
65
+ findings: number;
66
+ /** Why the engine was skipped or how it failed. */
67
+ reason?: string;
68
+ }
69
+ export interface Summary {
70
+ error: number;
71
+ warning: number;
72
+ info: number;
73
+ suppressed: number;
74
+ }
75
+ export interface RunResult {
76
+ schema: 1;
77
+ tool: {
78
+ name: 'wp-shakedown';
79
+ version: string;
80
+ };
81
+ target: {
82
+ kind: TargetKind;
83
+ path: string;
84
+ name: string;
85
+ /** `path` here is relative to the root target. */
86
+ units: {
87
+ kind: TargetKind;
88
+ name: string;
89
+ path: string;
90
+ }[];
91
+ };
92
+ startedAt: string;
93
+ finishedAt: string;
94
+ engines: EngineRun[];
95
+ findings: Finding[];
96
+ summary: Summary;
97
+ /** Baseline entries that matched no finding in this run. */
98
+ staleBaseline: string[];
99
+ }
100
+ export type RunEvent = {
101
+ type: 'run:start';
102
+ target: Target;
103
+ jobs: {
104
+ engine: string;
105
+ unit?: string;
106
+ }[];
107
+ } | {
108
+ type: 'engine:start';
109
+ engine: string;
110
+ unit?: string;
111
+ } | {
112
+ type: 'engine:note';
113
+ engine: string;
114
+ unit?: string;
115
+ message: string;
116
+ } | {
117
+ type: 'engine:end';
118
+ run: EngineRun;
119
+ } | {
120
+ type: 'run:end';
121
+ result: RunResult;
122
+ };
123
+ export interface BaselineEntry {
124
+ id: string;
125
+ reason: string;
126
+ }
127
+ export interface Baseline {
128
+ schema: 1;
129
+ entries: BaselineEntry[];
130
+ }
131
+ export interface RunDiff {
132
+ fixed: Finding[];
133
+ added: Finding[];
134
+ open: Finding[];
135
+ }
package/dist/types.js ADDED
@@ -0,0 +1,4 @@
1
+ export const SEVERITIES = ['error', 'warning', 'info'];
2
+ /** An engine throws this when it cannot run here, for example when PHP is missing. The run continues. */
3
+ export class EngineSkipped extends Error {
4
+ }
@@ -0,0 +1,13 @@
1
+ import type { Engine } from '../types.ts';
2
+ export interface UiServer {
3
+ url: string;
4
+ port: number;
5
+ token: string;
6
+ close(): Promise<void>;
7
+ }
8
+ export declare function startUi(opts: {
9
+ engines: Engine[];
10
+ port?: number;
11
+ startDir?: string;
12
+ token?: string;
13
+ }): Promise<UiServer>;
@@ -0,0 +1,295 @@
1
+ import { randomBytes, timingSafeEqual } from 'node:crypto';
2
+ import { readFileSync, readdirSync, statSync } from 'node:fs';
3
+ import http from 'node:http';
4
+ import os from 'node:os';
5
+ import path from 'node:path';
6
+ import { fileURLToPath } from 'node:url';
7
+ import { runSession } from '../session.js';
8
+ import { detectTarget } from '../target.js';
9
+ import { VERSION } from '../version.js';
10
+ // The page is a Vite build. Its files are index.html and the hashed files in assets/.
11
+ const UI_DIR = fileURLToPath(new URL('../../ui/dist/', import.meta.url));
12
+ const TYPES = {
13
+ '.html': 'text/html; charset=utf-8',
14
+ '.js': 'text/javascript; charset=utf-8',
15
+ '.css': 'text/css; charset=utf-8',
16
+ '.woff2': 'font/woff2',
17
+ '.svg': 'image/svg+xml',
18
+ };
19
+ /** The file for a route, or undefined. Only index.html and a plain file name under /assets/ are served, so a URL cannot walk out of the folder. */
20
+ function staticFile(route) {
21
+ if (route === '/' || route === '/index.html')
22
+ return 'index.html';
23
+ const m = /^\/assets\/([A-Za-z0-9._-]+)$/.exec(route);
24
+ return m && !m[1].startsWith('.') && TYPES[path.extname(m[1])] ? path.join('assets', m[1]) : undefined;
25
+ }
26
+ const HEADERS = {
27
+ 'Cache-Control': 'no-store',
28
+ 'X-Content-Type-Options': 'nosniff',
29
+ 'Referrer-Policy': 'no-referrer',
30
+ 'Content-Security-Policy': "default-src 'none'; script-src 'self'; style-src 'self' 'unsafe-inline'; font-src 'self'; connect-src 'self'; img-src 'self' data:; base-uri 'none'; form-action 'none'",
31
+ };
32
+ const MAX_BODY = 65536;
33
+ function toWire(e) {
34
+ if (e.type === 'run:start') {
35
+ const { kind, name, path: p, units } = e.target;
36
+ return { type: e.type, target: { kind, name, path: p, units: units.length }, jobs: e.jobs };
37
+ }
38
+ if (e.type === 'run:end')
39
+ return { type: e.type, summary: e.result.summary, finishedAt: e.result.finishedAt };
40
+ return e;
41
+ }
42
+ function same(a, b) {
43
+ const x = Buffer.from(a);
44
+ const y = Buffer.from(b);
45
+ return x.length === y.length && timingSafeEqual(x, y);
46
+ }
47
+ export function startUi(opts) {
48
+ const token = opts.token ?? randomBytes(24).toString('base64url');
49
+ const startDir = path.resolve(opts.startDir ?? process.cwd());
50
+ let port = 0;
51
+ let controller;
52
+ let events = [];
53
+ let last;
54
+ const clients = new Set();
55
+ const send = (res, status, body) => {
56
+ res.writeHead(status, { ...HEADERS, 'Content-Type': 'application/json; charset=utf-8' });
57
+ res.end(JSON.stringify(body));
58
+ };
59
+ const sse = (res, name, data) => {
60
+ res.write(`event: ${name}\ndata: ${JSON.stringify(data)}\n\n`);
61
+ };
62
+ const push = (e) => {
63
+ events.push(e);
64
+ for (const c of clients)
65
+ sse(c, 'run', e);
66
+ };
67
+ function readBody(req) {
68
+ return new Promise((resolve) => {
69
+ const chunks = [];
70
+ let size = 0;
71
+ req.on('data', (c) => {
72
+ size += c.length;
73
+ if (size > MAX_BODY) {
74
+ resolve(undefined);
75
+ req.removeAllListeners('data');
76
+ req.resume();
77
+ }
78
+ else
79
+ chunks.push(c);
80
+ });
81
+ req.on('end', () => resolve(Buffer.concat(chunks).toString('utf8')));
82
+ req.on('error', () => resolve(undefined));
83
+ });
84
+ }
85
+ function start(input, type, only) {
86
+ const ctl = new AbortController();
87
+ controller = ctl;
88
+ events = [];
89
+ let ended = false;
90
+ runSession({
91
+ input,
92
+ ...(type ? { type } : {}),
93
+ ...(only ? { only } : {}),
94
+ engines: opts.engines,
95
+ signal: ctl.signal,
96
+ onEvent: (e) => {
97
+ // A stopped run reports one message, not a partial result.
98
+ if (e.type === 'run:end' && ctl.signal.aborted)
99
+ return;
100
+ if (e.type === 'run:end')
101
+ ended = true;
102
+ push(toWire(e));
103
+ },
104
+ })
105
+ .then((s) => {
106
+ if (!ctl.signal.aborted)
107
+ last = s;
108
+ })
109
+ .catch((err) => {
110
+ if (!ctl.signal.aborted)
111
+ push({ type: 'run:error', message: err instanceof Error ? err.message : String(err) });
112
+ })
113
+ .finally(() => {
114
+ if (ctl.signal.aborted && !ended)
115
+ push({ type: 'run:error', message: 'The run was stopped.' });
116
+ if (controller === ctl)
117
+ controller = undefined;
118
+ });
119
+ }
120
+ const handle = async (req, res) => {
121
+ const url = new URL(req.url ?? '/', `http://127.0.0.1:${port}`);
122
+ const route = url.pathname;
123
+ const method = req.method ?? 'GET';
124
+ if (!route.startsWith('/api/')) {
125
+ const file = staticFile(route);
126
+ if (!file || method !== 'GET')
127
+ return send(res, file ? 405 : 404, { error: file ? 'Method not allowed.' : 'Not found.' });
128
+ try {
129
+ const body = readFileSync(path.join(UI_DIR, file));
130
+ res.writeHead(200, { ...HEADERS, 'Content-Type': TYPES[path.extname(file)] });
131
+ res.end(body);
132
+ }
133
+ catch {
134
+ send(res, 404, { error: 'Not found.' });
135
+ }
136
+ return;
137
+ }
138
+ if (req.headers.host !== `127.0.0.1:${port}` && req.headers.host !== `localhost:${port}`) {
139
+ return send(res, 403, { error: 'Bad host.' });
140
+ }
141
+ const origin = req.headers.origin;
142
+ if (origin !== undefined && origin !== `http://127.0.0.1:${port}` && origin !== `http://localhost:${port}`) {
143
+ return send(res, 403, { error: 'Bad origin.' });
144
+ }
145
+ const given = req.headers['x-shakedown-token'] ?? url.searchParams.get('t') ?? '';
146
+ if (!same(Array.isArray(given) ? (given[0] ?? '') : given, token)) {
147
+ return send(res, 401, { error: 'Missing or wrong token.' });
148
+ }
149
+ const methods = {
150
+ '/api/state': 'GET',
151
+ '/api/dirs': 'GET',
152
+ '/api/detect': 'GET',
153
+ '/api/run': 'POST',
154
+ '/api/cancel': 'POST',
155
+ '/api/report': 'GET',
156
+ '/api/events': 'GET',
157
+ };
158
+ const want = methods[route];
159
+ if (!want)
160
+ return send(res, 404, { error: 'Not found.' });
161
+ if (method !== want)
162
+ return send(res, 405, { error: 'Method not allowed.' });
163
+ switch (route) {
164
+ case '/api/state':
165
+ return send(res, 200, {
166
+ version: VERSION,
167
+ home: os.homedir(),
168
+ startDir,
169
+ engines: opts.engines.map(({ id, title, kinds }) => ({ id, title, kinds })),
170
+ running: controller !== undefined,
171
+ });
172
+ case '/api/dirs': {
173
+ const given = url.searchParams.get('path');
174
+ const p = given ?? startDir;
175
+ if (!path.isAbsolute(p))
176
+ return send(res, 400, { error: 'Give an absolute path.' });
177
+ if (!statSync(p, { throwIfNoEntry: false })?.isDirectory())
178
+ return send(res, 400, { error: `"${p}" is not a folder.` });
179
+ let names;
180
+ try {
181
+ names = readdirSync(p);
182
+ }
183
+ catch {
184
+ return send(res, 400, { error: `Cannot read "${p}".` });
185
+ }
186
+ const dirs = names
187
+ .filter((n) => !n.startsWith('.'))
188
+ .filter((n) => statSync(path.join(p, n), { throwIfNoEntry: false })?.isDirectory())
189
+ .sort((a, b) => a.localeCompare(b, undefined, { sensitivity: 'base' }))
190
+ .map((name) => ({ name, path: path.join(p, name) }));
191
+ const parent = path.dirname(p);
192
+ return send(res, 200, { path: p, parent: parent === p ? null : parent, dirs });
193
+ }
194
+ case '/api/detect': {
195
+ try {
196
+ const t = detectTarget(url.searchParams.get('path') ?? '');
197
+ return send(res, 200, {
198
+ kind: t.kind,
199
+ name: t.name,
200
+ path: t.path,
201
+ units: t.units.map((u) => ({ kind: u.kind, name: u.name, path: path.relative(t.path, u.path).split(path.sep).join('/') })),
202
+ });
203
+ }
204
+ catch (err) {
205
+ return send(res, 400, { error: err instanceof Error ? err.message : String(err) });
206
+ }
207
+ }
208
+ case '/api/run': {
209
+ if (!(req.headers['content-type'] ?? '').startsWith('application/json'))
210
+ return send(res, 415, { error: 'Send JSON.' });
211
+ const text = await readBody(req);
212
+ if (text === undefined) {
213
+ res.setHeader('Connection', 'close');
214
+ return send(res, 413, { error: 'The request is too large.' });
215
+ }
216
+ const body = (() => {
217
+ try {
218
+ return JSON.parse(text);
219
+ }
220
+ catch {
221
+ return null; // answered as a missing path
222
+ }
223
+ })();
224
+ if (!body || typeof body.path !== 'string' || body.path === '')
225
+ return send(res, 400, { error: 'Send a path.' });
226
+ if (controller)
227
+ return send(res, 409, { error: 'A run is in progress.' });
228
+ const type = body.type === 'theme' || body.type === 'plugin' || body.type === 'install' ? body.type : undefined;
229
+ const ids = Array.isArray(body.engines) ? body.engines.filter((x) => typeof x === 'string') : [];
230
+ try {
231
+ detectTarget(body.path, type ? { type } : {});
232
+ }
233
+ catch (err) {
234
+ return send(res, 400, { error: err instanceof Error ? err.message : String(err) });
235
+ }
236
+ for (const id of ids) {
237
+ if (!opts.engines.some((e) => e.id === id))
238
+ return send(res, 400, { error: `Unknown engine "${id}".` });
239
+ }
240
+ start(body.path, type, ids.length > 0 ? ids : undefined);
241
+ return send(res, 202, { ok: true });
242
+ }
243
+ case '/api/cancel':
244
+ controller?.abort();
245
+ return send(res, 200, { ok: true });
246
+ case '/api/report': {
247
+ if (!last)
248
+ return send(res, 404, { error: 'No report yet.' });
249
+ const { result, diff, files, dir } = last;
250
+ return send(res, 200, { result, ...(diff ? { diff } : {}), files, dir });
251
+ }
252
+ default: {
253
+ res.writeHead(200, {
254
+ ...HEADERS,
255
+ 'Content-Type': 'text/event-stream; charset=utf-8',
256
+ Connection: 'keep-alive',
257
+ });
258
+ sse(res, 'snapshot', { running: controller !== undefined, events });
259
+ clients.add(res);
260
+ const ping = setInterval(() => res.write(': ping\n\n'), 25000);
261
+ res.on('close', () => {
262
+ clearInterval(ping);
263
+ clients.delete(res);
264
+ });
265
+ }
266
+ }
267
+ };
268
+ const server = http.createServer((req, res) => {
269
+ handle(req, res).catch(() => {
270
+ if (!res.headersSent)
271
+ send(res, 500, { error: 'Something went wrong.' });
272
+ else
273
+ res.end();
274
+ });
275
+ });
276
+ return new Promise((resolve, reject) => {
277
+ server.once('error', reject);
278
+ server.listen(opts.port ?? 0, '127.0.0.1', () => {
279
+ port = server.address().port;
280
+ resolve({
281
+ url: `http://127.0.0.1:${port}/?t=${token}`,
282
+ port,
283
+ token,
284
+ close: () => new Promise((done) => {
285
+ controller?.abort();
286
+ for (const c of clients)
287
+ c.end();
288
+ clients.clear();
289
+ server.close(() => done());
290
+ server.closeAllConnections();
291
+ }),
292
+ });
293
+ });
294
+ });
295
+ }
@@ -0,0 +1 @@
1
+ export declare const VERSION: string;
@@ -0,0 +1,3 @@
1
+ import { createRequire } from 'node:module';
2
+ const require = createRequire(import.meta.url);
3
+ export const VERSION = require('../package.json').version;
@@ -0,0 +1,9 @@
1
+ /** Negative, zero or positive. A numeric part beats a text part, so 1.0-beta is older than 1.0. */
2
+ export declare function compareVersions(a: string, b: string): number;
3
+ export interface VersionRange {
4
+ min?: string | null;
5
+ minInclusive?: boolean;
6
+ max?: string | null;
7
+ maxInclusive?: boolean;
8
+ }
9
+ export declare function inRange(version: string, r: VersionRange): boolean;
@@ -0,0 +1,35 @@
1
+ const isNum = (s) => /^\d+$/.test(s);
2
+ /** Negative, zero or positive. A numeric part beats a text part, so 1.0-beta is older than 1.0. */
3
+ export function compareVersions(a, b) {
4
+ const x = a.trim().toLowerCase().split(/[.\-+_]/);
5
+ const y = b.trim().toLowerCase().split(/[.\-+_]/);
6
+ for (let i = 0; i < Math.max(x.length, y.length); i++) {
7
+ const p = x[i] ?? '0';
8
+ const q = y[i] ?? '0';
9
+ if (isNum(p) && isNum(q)) {
10
+ if (Number(p) !== Number(q))
11
+ return Number(p) - Number(q);
12
+ }
13
+ else if (isNum(p) !== isNum(q)) {
14
+ return isNum(p) ? 1 : -1;
15
+ }
16
+ else if (p !== q) {
17
+ return p < q ? -1 : 1;
18
+ }
19
+ }
20
+ return 0;
21
+ }
22
+ const bound = (v) => !!v && v !== '*';
23
+ export function inRange(version, r) {
24
+ if (bound(r.min)) {
25
+ const c = compareVersions(version, r.min);
26
+ if (c < 0 || (c === 0 && !r.minInclusive))
27
+ return false;
28
+ }
29
+ if (bound(r.max)) {
30
+ const c = compareVersions(version, r.max);
31
+ if (c > 0 || (c === 0 && !r.maxInclusive))
32
+ return false;
33
+ }
34
+ return true;
35
+ }
@@ -0,0 +1,19 @@
1
+ import wordpress from '@wordpress/eslint-plugin';
2
+ import globals from 'globals';
3
+
4
+ export default [
5
+ { ignores: [ '**/node_modules/**', '**/vendor/**', '**/bower_components/**', '**/build/**', '**/dist/**', '**/*.min.js' ] },
6
+ ...wordpress.configs.recommended,
7
+ // ESLint only lints the extensions a config names. Without this entry a .jsx file is skipped without a word.
8
+ { files: [ '**/*.jsx' ] },
9
+ {
10
+ languageOptions: {
11
+ globals: { ...globals.browser, ...globals.jquery, wp: 'readonly', ajaxurl: 'readonly', _: 'readonly', Backbone: 'readonly' },
12
+ },
13
+ rules: {
14
+ 'prettier/prettier': 'off',
15
+ 'import/no-extraneous-dependencies': 'off',
16
+ 'import/no-unresolved': 'off',
17
+ },
18
+ },
19
+ ];