@dcaldeira/tooling 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.
- package/README.md +34 -34
- package/checks/a11y.mjs +206 -206
- package/checks/architecture.mjs +137 -137
- package/checks/audit.mjs +121 -121
- package/checks/bundle.mjs +126 -126
- package/checks/dependencies.mjs +277 -277
- package/checks/duplication.mjs +135 -0
- package/checks/lint-scss.mjs +363 -349
- package/checks/package.mjs +30 -30
- package/checks/playwright-summary.mjs +53 -53
- package/checks/sass.mjs +67 -67
- package/checks/scan-secrets.mjs +58 -58
- package/checks/shared.mjs +86 -86
- package/checks/translations.mjs +55 -55
- package/checks/visual-compare.mjs +148 -148
- package/checks/visual-report-html.mjs +470 -470
- package/checks/visual-report.mjs +13 -13
- package/config.schema.json +977 -927
- package/configs/eslint.mjs +27 -27
- package/configs/knip.json +11 -11
- package/configs/playwright.mjs +15 -15
- package/configs/vitest.mjs +16 -16
- package/package.json +105 -105
- package/release/finalize.mjs +65 -65
- package/release/github.mjs +64 -64
- package/release/prepare.mjs +30 -30
- package/runner/browsers.mjs +73 -73
- package/runner/cache.mjs +121 -121
- package/runner/ci-plan.mjs +54 -54
- package/runner/cli.mjs +250 -248
- package/runner/config.mjs +148 -148
- package/runner/docs-install.mjs +93 -93
- package/runner/execute.mjs +298 -286
- package/runner/generate.mjs +122 -122
- package/runner/git.mjs +122 -122
- package/runner/graph.mjs +250 -243
- package/runner/insights.mjs +313 -313
- package/runner/provision.mjs +53 -53
- package/runner/repo-standard.mjs +104 -0
- package/runner/report.mjs +35 -35
- package/runner/serve-static.mjs +76 -76
- package/runner/setup.mjs +241 -237
- package/runner/summary.mjs +112 -112
- package/runner/watch.mjs +82 -82
- package/templates/ci.yml +25 -25
- package/templates/dependabot-merge.yml +13 -13
- package/templates/dependabot.yml +26 -26
- package/templates/pre-push +13 -13
- package/templates/release.yml +23 -23
package/runner/provision.mjs
CHANGED
|
@@ -1,53 +1,53 @@
|
|
|
1
|
-
#!/usr/bin/env node
|
|
2
|
-
import { chmodSync, mkdirSync, readFileSync, writeFileSync, appendFileSync } from 'node:fs';
|
|
3
|
-
import { join, resolve } from 'node:path';
|
|
4
|
-
import { invoke } from './execute.mjs';
|
|
5
|
-
|
|
6
|
-
const selection = JSON.parse(readFileSync(process.argv[2], 'utf8'));
|
|
7
|
-
const selected = selection.checks.filter((c) => !c.excluded);
|
|
8
|
-
const ids = selected.map((c) => c.kind ?? c.id);
|
|
9
|
-
const tools = new Set(selected.flatMap((c) => c.tools ?? []));
|
|
10
|
-
const root = process.cwd();
|
|
11
|
-
const bin = resolve('.tooling/bin');
|
|
12
|
-
mkdirSync(bin, { recursive: true });
|
|
13
|
-
async function requirePass(command) {
|
|
14
|
-
const result = await invoke(command, root);
|
|
15
|
-
if (result.status !== 'passed')
|
|
16
|
-
throw new Error(`Prerequisite installation failed: ${command.join(' ')}`);
|
|
17
|
-
}
|
|
18
|
-
if (process.platform !== 'linux')
|
|
19
|
-
throw new Error('CI prerequisite provisioning requires Linux; use WSL or a container');
|
|
20
|
-
if (ids.includes('database')) {
|
|
21
|
-
await requirePass(['sudo', 'apt-get', 'update']);
|
|
22
|
-
await requirePass(['sudo', 'apt-get', 'install', '-y', 'postgresql-16', 'postgresql-16-pgtap']);
|
|
23
|
-
if (process.env.GITHUB_ENV)
|
|
24
|
-
appendFileSync(process.env.GITHUB_ENV, 'PG_BIN=/usr/lib/postgresql/16/bin\n');
|
|
25
|
-
}
|
|
26
|
-
for (const [name, image] of [
|
|
27
|
-
['actionlint', 'rhysd/actionlint:1.7.7'],
|
|
28
|
-
['gitleaks', 'zricethezav/gitleaks:v8.24.3'],
|
|
29
|
-
['deno', 'denoland/deno:2.5.6'],
|
|
30
|
-
]) {
|
|
31
|
-
if (!tools.has(name)) continue;
|
|
32
|
-
await requirePass(['docker', 'pull', image]);
|
|
33
|
-
const path = join(bin, name);
|
|
34
|
-
writeFileSync(path, `#!/bin/sh\nexec docker run --rm -v "$PWD:/repo" -w /repo ${image} "$@"\n`);
|
|
35
|
-
chmodSync(path, 0o755);
|
|
36
|
-
}
|
|
37
|
-
if (tools.has('lhci')) {
|
|
38
|
-
await requirePass([
|
|
39
|
-
'npm',
|
|
40
|
-
'install',
|
|
41
|
-
'--prefix',
|
|
42
|
-
'.tooling/tools',
|
|
43
|
-
'--no-save',
|
|
44
|
-
'@lhci/cli@0.15.1',
|
|
45
|
-
]);
|
|
46
|
-
const path = join(bin, 'lhci');
|
|
47
|
-
writeFileSync(
|
|
48
|
-
path,
|
|
49
|
-
`#!/bin/sh\nexec node "${resolve('.tooling/tools/node_modules/@lhci/cli/src/cli.js')}" "$@"\n`,
|
|
50
|
-
);
|
|
51
|
-
chmodSync(path, 0o755);
|
|
52
|
-
}
|
|
53
|
-
if (process.env.GITHUB_PATH) appendFileSync(process.env.GITHUB_PATH, `${bin}\n`);
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
import { chmodSync, mkdirSync, readFileSync, writeFileSync, appendFileSync } from 'node:fs';
|
|
3
|
+
import { join, resolve } from 'node:path';
|
|
4
|
+
import { invoke } from './execute.mjs';
|
|
5
|
+
|
|
6
|
+
const selection = JSON.parse(readFileSync(process.argv[2], 'utf8'));
|
|
7
|
+
const selected = selection.checks.filter((c) => !c.excluded);
|
|
8
|
+
const ids = selected.map((c) => c.kind ?? c.id);
|
|
9
|
+
const tools = new Set(selected.flatMap((c) => c.tools ?? []));
|
|
10
|
+
const root = process.cwd();
|
|
11
|
+
const bin = resolve('.tooling/bin');
|
|
12
|
+
mkdirSync(bin, { recursive: true });
|
|
13
|
+
async function requirePass(command) {
|
|
14
|
+
const result = await invoke(command, root);
|
|
15
|
+
if (result.status !== 'passed')
|
|
16
|
+
throw new Error(`Prerequisite installation failed: ${command.join(' ')}`);
|
|
17
|
+
}
|
|
18
|
+
if (process.platform !== 'linux')
|
|
19
|
+
throw new Error('CI prerequisite provisioning requires Linux; use WSL or a container');
|
|
20
|
+
if (ids.includes('database')) {
|
|
21
|
+
await requirePass(['sudo', 'apt-get', 'update']);
|
|
22
|
+
await requirePass(['sudo', 'apt-get', 'install', '-y', 'postgresql-16', 'postgresql-16-pgtap']);
|
|
23
|
+
if (process.env.GITHUB_ENV)
|
|
24
|
+
appendFileSync(process.env.GITHUB_ENV, 'PG_BIN=/usr/lib/postgresql/16/bin\n');
|
|
25
|
+
}
|
|
26
|
+
for (const [name, image] of [
|
|
27
|
+
['actionlint', 'rhysd/actionlint:1.7.7'],
|
|
28
|
+
['gitleaks', 'zricethezav/gitleaks:v8.24.3'],
|
|
29
|
+
['deno', 'denoland/deno:2.5.6'],
|
|
30
|
+
]) {
|
|
31
|
+
if (!tools.has(name)) continue;
|
|
32
|
+
await requirePass(['docker', 'pull', image]);
|
|
33
|
+
const path = join(bin, name);
|
|
34
|
+
writeFileSync(path, `#!/bin/sh\nexec docker run --rm -v "$PWD:/repo" -w /repo ${image} "$@"\n`);
|
|
35
|
+
chmodSync(path, 0o755);
|
|
36
|
+
}
|
|
37
|
+
if (tools.has('lhci')) {
|
|
38
|
+
await requirePass([
|
|
39
|
+
'npm',
|
|
40
|
+
'install',
|
|
41
|
+
'--prefix',
|
|
42
|
+
'.tooling/tools',
|
|
43
|
+
'--no-save',
|
|
44
|
+
'@lhci/cli@0.15.1',
|
|
45
|
+
]);
|
|
46
|
+
const path = join(bin, 'lhci');
|
|
47
|
+
writeFileSync(
|
|
48
|
+
path,
|
|
49
|
+
`#!/bin/sh\nexec node "${resolve('.tooling/tools/node_modules/@lhci/cli/src/cli.js')}" "$@"\n`,
|
|
50
|
+
);
|
|
51
|
+
chmodSync(path, 0o755);
|
|
52
|
+
}
|
|
53
|
+
if (process.env.GITHUB_PATH) appendFileSync(process.env.GITHUB_PATH, `${bin}\n`);
|
|
@@ -0,0 +1,104 @@
|
|
|
1
|
+
import { existsSync, lstatSync, readdirSync, readFileSync } from 'node:fs';
|
|
2
|
+
import { join } from 'node:path';
|
|
3
|
+
|
|
4
|
+
const REQUIRED_SECTIONS = ['Repository', 'Layout', 'Commands', 'Constraints'];
|
|
5
|
+
// Plugin set from the core plugin's repo-standard skill. Personal plugins (caveman) stay out.
|
|
6
|
+
const PLUGINS = ['core@dcaldeira', 'mattpocock-skills@mattpocock'];
|
|
7
|
+
const FRONTEND_PLUGINS = ['ui-ux-pro-max@ui-ux-pro-max-skill', 'taste-skill@taste-skill'];
|
|
8
|
+
const FRONTEND_DEPS = ['react', 'react-native', 'vite', 'next', 'expo'];
|
|
9
|
+
|
|
10
|
+
const read = (path) => (existsSync(path) ? readFileSync(path, 'utf8') : undefined);
|
|
11
|
+
const json = (path) => {
|
|
12
|
+
try {
|
|
13
|
+
return JSON.parse(read(path) ?? 'null');
|
|
14
|
+
} catch {
|
|
15
|
+
return null;
|
|
16
|
+
}
|
|
17
|
+
};
|
|
18
|
+
const subdirs = (path) => {
|
|
19
|
+
try {
|
|
20
|
+
return readdirSync(path, { withFileTypes: true })
|
|
21
|
+
.filter((entry) => entry.isDirectory() && entry.name !== 'node_modules')
|
|
22
|
+
.map((entry) => join(path, entry.name));
|
|
23
|
+
} catch {
|
|
24
|
+
return [];
|
|
25
|
+
}
|
|
26
|
+
};
|
|
27
|
+
|
|
28
|
+
/**
|
|
29
|
+
* True when the root, a workspace, any top-level folder or `apps/*`/`packages/*` depends on a
|
|
30
|
+
* frontend framework. Keep in sync with `detectStack` in claude/hooks/lib/detect.mjs (a test
|
|
31
|
+
* compares them).
|
|
32
|
+
*/
|
|
33
|
+
export function hasFrontend(root) {
|
|
34
|
+
const rootManifest = json(join(root, 'package.json'));
|
|
35
|
+
const patterns = [
|
|
36
|
+
...(Array.isArray(rootManifest?.workspaces)
|
|
37
|
+
? rootManifest.workspaces
|
|
38
|
+
: (rootManifest?.workspaces?.packages ?? [])),
|
|
39
|
+
'*',
|
|
40
|
+
'apps/*',
|
|
41
|
+
'packages/*',
|
|
42
|
+
];
|
|
43
|
+
const dirs = patterns.flatMap((pattern) =>
|
|
44
|
+
pattern.endsWith('*') ? subdirs(join(root, pattern.slice(0, -1))) : [join(root, pattern)],
|
|
45
|
+
);
|
|
46
|
+
return [rootManifest, ...dirs.map((dir) => json(join(dir, 'package.json')))].some((manifest) =>
|
|
47
|
+
FRONTEND_DEPS.some(
|
|
48
|
+
(dep) =>
|
|
49
|
+
manifest?.dependencies?.[dep] ||
|
|
50
|
+
manifest?.devDependencies?.[dep] ||
|
|
51
|
+
manifest?.peerDependencies?.[dep],
|
|
52
|
+
),
|
|
53
|
+
);
|
|
54
|
+
}
|
|
55
|
+
const exists = (path) => {
|
|
56
|
+
try {
|
|
57
|
+
lstatSync(path);
|
|
58
|
+
return true;
|
|
59
|
+
} catch {
|
|
60
|
+
return false;
|
|
61
|
+
}
|
|
62
|
+
};
|
|
63
|
+
|
|
64
|
+
/** Findings for the shared repo standard (opt-in through `repoStandard: true`). */
|
|
65
|
+
export function repoStandardFindings(root) {
|
|
66
|
+
const findings = [];
|
|
67
|
+
const fail = (message) =>
|
|
68
|
+
findings.push({ status: 'failed', message: `repo standard: ${message}` });
|
|
69
|
+
|
|
70
|
+
const agents = read(join(root, 'AGENTS.md'));
|
|
71
|
+
if (agents === undefined) fail('add AGENTS.md');
|
|
72
|
+
else {
|
|
73
|
+
const headings = new Set([...agents.matchAll(/^##\s+(.+?)\s*$/gm)].map((match) => match[1]));
|
|
74
|
+
for (const section of REQUIRED_SECTIONS)
|
|
75
|
+
if (!headings.has(section)) fail(`AGENTS.md needs a "## ${section}" section`);
|
|
76
|
+
}
|
|
77
|
+
|
|
78
|
+
const claude = read(join(root, 'CLAUDE.md'));
|
|
79
|
+
if (claude?.trim() !== '@AGENTS.md') fail('CLAUDE.md must contain only @AGENTS.md');
|
|
80
|
+
|
|
81
|
+
for (const [name, text] of [
|
|
82
|
+
['AGENTS.md', agents],
|
|
83
|
+
['CLAUDE.md', claude],
|
|
84
|
+
])
|
|
85
|
+
if (text && /(^|[\s`(/])\.ai[/\\]/m.test(text))
|
|
86
|
+
fail(`${name} still references the old .ai/ kit`);
|
|
87
|
+
if (exists(join(root, '.ai'))) fail('remove the .ai kit link');
|
|
88
|
+
if (exists(join(root, 'ai-memory')))
|
|
89
|
+
fail('move what is still useful out of ai-memory/ and delete it');
|
|
90
|
+
|
|
91
|
+
let settings;
|
|
92
|
+
try {
|
|
93
|
+
settings = JSON.parse(read(join(root, '.claude', 'settings.json')) ?? 'null');
|
|
94
|
+
} catch {
|
|
95
|
+
fail('.claude/settings.json is not valid JSON');
|
|
96
|
+
}
|
|
97
|
+
if (settings !== undefined)
|
|
98
|
+
for (const plugin of [...PLUGINS, ...(hasFrontend(root) ? FRONTEND_PLUGINS : [])])
|
|
99
|
+
if (settings?.enabledPlugins?.[plugin] !== true)
|
|
100
|
+
fail(`.claude/settings.json must enable ${plugin}`);
|
|
101
|
+
|
|
102
|
+
if (!findings.length) findings.push({ status: 'passed', message: 'Repo standard is met' });
|
|
103
|
+
return findings;
|
|
104
|
+
}
|
package/runner/report.mjs
CHANGED
|
@@ -1,35 +1,35 @@
|
|
|
1
|
-
import { existsSync, mkdirSync, writeFileSync } from 'node:fs';
|
|
2
|
-
import { join } from 'node:path';
|
|
3
|
-
import { markdownSummary } from './summary.mjs';
|
|
4
|
-
|
|
5
|
-
const escape = (value) =>
|
|
6
|
-
String(value ?? '').replace(
|
|
7
|
-
/[&<>"']/g,
|
|
8
|
-
(c) => ({ '&': '&', '<': '<', '>': '>', '"': '"', "'": ''' })[c],
|
|
9
|
-
);
|
|
10
|
-
export function writeReport(directory, report) {
|
|
11
|
-
mkdirSync(directory, { recursive: true });
|
|
12
|
-
writeFileSync(join(directory, 'summary.json'), `${JSON.stringify(report, null, 2)}\n`);
|
|
13
|
-
writeFileSync(join(directory, 'summary.md'), markdownSummary(report));
|
|
14
|
-
const rows = report.results
|
|
15
|
-
.map(
|
|
16
|
-
(r) =>
|
|
17
|
-
`<tr><td>${escape(r.id)}</td><td>${escape(r.status)}</td><td>${escape(r.reason)}</td><td>${((r.milliseconds ?? 0) / 1000).toFixed(2)}s</td></tr>`,
|
|
18
|
-
)
|
|
19
|
-
.join('');
|
|
20
|
-
const browserLinks = report.results
|
|
21
|
-
.filter(
|
|
22
|
-
(result) =>
|
|
23
|
-
['e2e', 'visual'].includes(result.kind ?? result.id) &&
|
|
24
|
-
existsSync(join(directory, result.id, 'index.html')),
|
|
25
|
-
)
|
|
26
|
-
.map(
|
|
27
|
-
(result) =>
|
|
28
|
-
`<a href="${encodeURIComponent(result.id)}/index.html">${escape(result.id)} report</a>`,
|
|
29
|
-
)
|
|
30
|
-
.join(' · ');
|
|
31
|
-
writeFileSync(
|
|
32
|
-
join(directory, 'index.html'),
|
|
33
|
-
`<!doctype html><html lang="en"><meta charset="utf-8"><meta name="viewport" content="width=device-width"><title>Repository checks</title><style>body{font:16px system-ui;max-width:1100px;margin:3rem auto;padding:0 1rem;color:#172033}table{width:100%;border-collapse:collapse}td,th{padding:.8rem;text-align:left;border-bottom:1px solid #ccd3df}code{overflow-wrap:anywhere}</style><h1>${report.complete ? 'Validation passed' : 'Validation incomplete or failed'}</h1><p>${escape(report.profile)} · ${escape(report.groups.join(', '))}</p><p>Commit: <code>${escape(report.commit)}</code></p><p>Tooling: ${escape(report.version)}</p><table><thead><tr><th>Check</th><th>Result</th><th>Details</th><th>Duration</th></tr></thead><tbody>${rows}</tbody></table><p><a href="summary.json" download>Download JSON</a>${browserLinks ? ` · ${browserLinks}` : ''}</p></html>`,
|
|
34
|
-
);
|
|
35
|
-
}
|
|
1
|
+
import { existsSync, mkdirSync, writeFileSync } from 'node:fs';
|
|
2
|
+
import { join } from 'node:path';
|
|
3
|
+
import { markdownSummary } from './summary.mjs';
|
|
4
|
+
|
|
5
|
+
const escape = (value) =>
|
|
6
|
+
String(value ?? '').replace(
|
|
7
|
+
/[&<>"']/g,
|
|
8
|
+
(c) => ({ '&': '&', '<': '<', '>': '>', '"': '"', "'": ''' })[c],
|
|
9
|
+
);
|
|
10
|
+
export function writeReport(directory, report) {
|
|
11
|
+
mkdirSync(directory, { recursive: true });
|
|
12
|
+
writeFileSync(join(directory, 'summary.json'), `${JSON.stringify(report, null, 2)}\n`);
|
|
13
|
+
writeFileSync(join(directory, 'summary.md'), markdownSummary(report));
|
|
14
|
+
const rows = report.results
|
|
15
|
+
.map(
|
|
16
|
+
(r) =>
|
|
17
|
+
`<tr><td>${escape(r.id)}</td><td>${escape(r.status)}</td><td>${escape(r.reason)}</td><td>${((r.milliseconds ?? 0) / 1000).toFixed(2)}s</td></tr>`,
|
|
18
|
+
)
|
|
19
|
+
.join('');
|
|
20
|
+
const browserLinks = report.results
|
|
21
|
+
.filter(
|
|
22
|
+
(result) =>
|
|
23
|
+
['e2e', 'visual'].includes(result.kind ?? result.id) &&
|
|
24
|
+
existsSync(join(directory, result.id, 'index.html')),
|
|
25
|
+
)
|
|
26
|
+
.map(
|
|
27
|
+
(result) =>
|
|
28
|
+
`<a href="${encodeURIComponent(result.id)}/index.html">${escape(result.id)} report</a>`,
|
|
29
|
+
)
|
|
30
|
+
.join(' · ');
|
|
31
|
+
writeFileSync(
|
|
32
|
+
join(directory, 'index.html'),
|
|
33
|
+
`<!doctype html><html lang="en"><meta charset="utf-8"><meta name="viewport" content="width=device-width"><title>Repository checks</title><style>body{font:16px system-ui;max-width:1100px;margin:3rem auto;padding:0 1rem;color:#172033}table{width:100%;border-collapse:collapse}td,th{padding:.8rem;text-align:left;border-bottom:1px solid #ccd3df}code{overflow-wrap:anywhere}</style><h1>${report.complete ? 'Validation passed' : 'Validation incomplete or failed'}</h1><p>${escape(report.profile)} · ${escape(report.groups.join(', '))}</p><p>Commit: <code>${escape(report.commit)}</code></p><p>Tooling: ${escape(report.version)}</p><table><thead><tr><th>Check</th><th>Result</th><th>Details</th><th>Duration</th></tr></thead><tbody>${rows}</tbody></table><p><a href="summary.json" download>Download JSON</a>${browserLinks ? ` · ${browserLinks}` : ''}</p></html>`,
|
|
34
|
+
);
|
|
35
|
+
}
|
package/runner/serve-static.mjs
CHANGED
|
@@ -1,76 +1,76 @@
|
|
|
1
|
-
import { createReadStream, realpathSync, statSync } from 'node:fs';
|
|
2
|
-
import { createServer } from 'node:http';
|
|
3
|
-
import { extname, isAbsolute, relative, resolve } from 'node:path';
|
|
4
|
-
import { pathToFileURL } from 'node:url';
|
|
5
|
-
|
|
6
|
-
const types = {
|
|
7
|
-
'.html': 'text/html; charset=utf-8',
|
|
8
|
-
'.js': 'text/javascript; charset=utf-8',
|
|
9
|
-
'.mjs': 'text/javascript; charset=utf-8',
|
|
10
|
-
'.css': 'text/css; charset=utf-8',
|
|
11
|
-
'.json': 'application/json; charset=utf-8',
|
|
12
|
-
'.svg': 'image/svg+xml',
|
|
13
|
-
'.woff2': 'font/woff2',
|
|
14
|
-
'.woff': 'font/woff',
|
|
15
|
-
'.png': 'image/png',
|
|
16
|
-
'.webp': 'image/webp',
|
|
17
|
-
'.ico': 'image/x-icon',
|
|
18
|
-
'.wasm': 'application/wasm',
|
|
19
|
-
};
|
|
20
|
-
const contained = (root, target) => {
|
|
21
|
-
const path = relative(root, target);
|
|
22
|
-
return path !== '..' && !path.startsWith('../') && !path.startsWith('..\\') && !isAbsolute(path);
|
|
23
|
-
};
|
|
24
|
-
|
|
25
|
-
export function staticServer(directory) {
|
|
26
|
-
const root = realpathSync(directory);
|
|
27
|
-
return createServer((request, response) => {
|
|
28
|
-
if (!['GET', 'HEAD'].includes(request.method)) {
|
|
29
|
-
response.writeHead(405, { Allow: 'GET, HEAD' }).end();
|
|
30
|
-
return;
|
|
31
|
-
}
|
|
32
|
-
let path;
|
|
33
|
-
try {
|
|
34
|
-
path = decodeURIComponent(new URL(request.url ?? '/', 'http://localhost').pathname);
|
|
35
|
-
} catch {
|
|
36
|
-
response.writeHead(400).end();
|
|
37
|
-
return;
|
|
38
|
-
}
|
|
39
|
-
let target = resolve(root, '.' + path);
|
|
40
|
-
if (!contained(root, target)) {
|
|
41
|
-
response.writeHead(403).end();
|
|
42
|
-
return;
|
|
43
|
-
}
|
|
44
|
-
try {
|
|
45
|
-
if (statSync(target).isDirectory()) target = resolve(target, 'index.html');
|
|
46
|
-
target = realpathSync(target);
|
|
47
|
-
if (!contained(root, target)) {
|
|
48
|
-
response.writeHead(403).end();
|
|
49
|
-
return;
|
|
50
|
-
}
|
|
51
|
-
if (!statSync(target).isFile()) {
|
|
52
|
-
response.writeHead(404).end();
|
|
53
|
-
return;
|
|
54
|
-
}
|
|
55
|
-
} catch {
|
|
56
|
-
response.writeHead(404).end();
|
|
57
|
-
return;
|
|
58
|
-
}
|
|
59
|
-
response.writeHead(200, { 'content-type': types[extname(target)] ?? 'application/octet-stream' });
|
|
60
|
-
if (request.method === 'HEAD') response.end();
|
|
61
|
-
else createReadStream(target).on('error', () => response.destroy()).pipe(response);
|
|
62
|
-
});
|
|
63
|
-
}
|
|
64
|
-
|
|
65
|
-
if (process.argv[1] && import.meta.url === pathToFileURL(process.argv[1]).href) {
|
|
66
|
-
const [directory, port = '6217', required = 'index.html'] = process.argv.slice(2);
|
|
67
|
-
if (!directory || process.argv.length > 5 || !/^\d+$/.test(port) || Number(port) < 1 || Number(port) > 65535)
|
|
68
|
-
throw new Error('Usage: serve-static.mjs <directory> [port] [required-file]');
|
|
69
|
-
const root = realpathSync(directory);
|
|
70
|
-
const entry = realpathSync(resolve(root, required));
|
|
71
|
-
if (!contained(root, entry) || !statSync(entry).isFile())
|
|
72
|
-
throw new Error('Required build entry is outside the served directory or is not a file');
|
|
73
|
-
staticServer(root).listen(Number(port), '127.0.0.1', () => {
|
|
74
|
-
console.log(`Serving ${root} on http://127.0.0.1:${port}`);
|
|
75
|
-
});
|
|
76
|
-
}
|
|
1
|
+
import { createReadStream, realpathSync, statSync } from 'node:fs';
|
|
2
|
+
import { createServer } from 'node:http';
|
|
3
|
+
import { extname, isAbsolute, relative, resolve } from 'node:path';
|
|
4
|
+
import { pathToFileURL } from 'node:url';
|
|
5
|
+
|
|
6
|
+
const types = {
|
|
7
|
+
'.html': 'text/html; charset=utf-8',
|
|
8
|
+
'.js': 'text/javascript; charset=utf-8',
|
|
9
|
+
'.mjs': 'text/javascript; charset=utf-8',
|
|
10
|
+
'.css': 'text/css; charset=utf-8',
|
|
11
|
+
'.json': 'application/json; charset=utf-8',
|
|
12
|
+
'.svg': 'image/svg+xml',
|
|
13
|
+
'.woff2': 'font/woff2',
|
|
14
|
+
'.woff': 'font/woff',
|
|
15
|
+
'.png': 'image/png',
|
|
16
|
+
'.webp': 'image/webp',
|
|
17
|
+
'.ico': 'image/x-icon',
|
|
18
|
+
'.wasm': 'application/wasm',
|
|
19
|
+
};
|
|
20
|
+
const contained = (root, target) => {
|
|
21
|
+
const path = relative(root, target);
|
|
22
|
+
return path !== '..' && !path.startsWith('../') && !path.startsWith('..\\') && !isAbsolute(path);
|
|
23
|
+
};
|
|
24
|
+
|
|
25
|
+
export function staticServer(directory) {
|
|
26
|
+
const root = realpathSync(directory);
|
|
27
|
+
return createServer((request, response) => {
|
|
28
|
+
if (!['GET', 'HEAD'].includes(request.method)) {
|
|
29
|
+
response.writeHead(405, { Allow: 'GET, HEAD' }).end();
|
|
30
|
+
return;
|
|
31
|
+
}
|
|
32
|
+
let path;
|
|
33
|
+
try {
|
|
34
|
+
path = decodeURIComponent(new URL(request.url ?? '/', 'http://localhost').pathname);
|
|
35
|
+
} catch {
|
|
36
|
+
response.writeHead(400).end();
|
|
37
|
+
return;
|
|
38
|
+
}
|
|
39
|
+
let target = resolve(root, '.' + path);
|
|
40
|
+
if (!contained(root, target)) {
|
|
41
|
+
response.writeHead(403).end();
|
|
42
|
+
return;
|
|
43
|
+
}
|
|
44
|
+
try {
|
|
45
|
+
if (statSync(target).isDirectory()) target = resolve(target, 'index.html');
|
|
46
|
+
target = realpathSync(target);
|
|
47
|
+
if (!contained(root, target)) {
|
|
48
|
+
response.writeHead(403).end();
|
|
49
|
+
return;
|
|
50
|
+
}
|
|
51
|
+
if (!statSync(target).isFile()) {
|
|
52
|
+
response.writeHead(404).end();
|
|
53
|
+
return;
|
|
54
|
+
}
|
|
55
|
+
} catch {
|
|
56
|
+
response.writeHead(404).end();
|
|
57
|
+
return;
|
|
58
|
+
}
|
|
59
|
+
response.writeHead(200, { 'content-type': types[extname(target)] ?? 'application/octet-stream' });
|
|
60
|
+
if (request.method === 'HEAD') response.end();
|
|
61
|
+
else createReadStream(target).on('error', () => response.destroy()).pipe(response);
|
|
62
|
+
});
|
|
63
|
+
}
|
|
64
|
+
|
|
65
|
+
if (process.argv[1] && import.meta.url === pathToFileURL(process.argv[1]).href) {
|
|
66
|
+
const [directory, port = '6217', required = 'index.html'] = process.argv.slice(2);
|
|
67
|
+
if (!directory || process.argv.length > 5 || !/^\d+$/.test(port) || Number(port) < 1 || Number(port) > 65535)
|
|
68
|
+
throw new Error('Usage: serve-static.mjs <directory> [port] [required-file]');
|
|
69
|
+
const root = realpathSync(directory);
|
|
70
|
+
const entry = realpathSync(resolve(root, required));
|
|
71
|
+
if (!contained(root, entry) || !statSync(entry).isFile())
|
|
72
|
+
throw new Error('Required build entry is outside the served directory or is not a file');
|
|
73
|
+
staticServer(root).listen(Number(port), '127.0.0.1', () => {
|
|
74
|
+
console.log(`Serving ${root} on http://127.0.0.1:${port}`);
|
|
75
|
+
});
|
|
76
|
+
}
|