r
This commit is contained in:
1 parent
76a4db6a9e
commit
783c95b797
21 files changed
+1245
-46
No files matched your search
+27
-6
@@ -1,9 +1,30 @@
|
||||
import { mkdir, copyFile } from 'node:fs/promises';
|
||||
import { writeFile } from 'node:fs/promises';
|
||||
import { mkdir, copyFile, writeFile, realpath, lstat, rm, rename } from 'node:fs/promises';
|
||||
import { fileURLToPath } from 'node:url';
|
||||
import { resolve, dirname } from 'node:path';
|
||||
import { compileContent } from './content.mjs';
|
||||
await writeFile(new URL('../content.js', import.meta.url), await compileContent());
|
||||
await mkdir('dist', { recursive: true });
|
||||
for (const file of ['index.html', 'styles.css', 'app.js', 'content.js', 'favicon.svg']) {
|
||||
await copyFile(file, `dist/${file}`);
|
||||
const root = await realpath(fileURLToPath(new URL('../', import.meta.url)));
|
||||
const output = resolve(root, 'dist');
|
||||
const staging = resolve(root, '.dist-staging');
|
||||
// Never recursively remove a redirected directory or a path outside this repository.
|
||||
async function verifyTarget(target) {
|
||||
if (dirname(target) !== root || !['dist', '.dist-staging'].some(name => target === resolve(root, name))) throw new Error('Unsafe build target');
|
||||
const stat = await lstat(target).catch(error => { if (error.code !== 'ENOENT') throw error; });
|
||||
if (stat && (stat.isSymbolicLink() || !stat.isDirectory() || await realpath(target) !== target)) throw new Error('Build target must be a real repository directory');
|
||||
}
|
||||
const content = await compileContent();
|
||||
await verifyTarget(output);
|
||||
await verifyTarget(staging);
|
||||
// Exclusive creation prevents concurrent builds from sharing staging output.
|
||||
await mkdir(staging);
|
||||
try {
|
||||
for (const file of ['index.html', 'styles.css', 'app.js', 'favicon.svg']) await copyFile(resolve(root, file), resolve(staging, file));
|
||||
await writeFile(resolve(staging, 'content.js'), content);
|
||||
await writeFile(resolve(root, 'content.js'), content);
|
||||
await verifyTarget(output);
|
||||
await rm(output, { recursive: true, force: true });
|
||||
await rename(staging, output);
|
||||
} finally {
|
||||
await verifyTarget(staging);
|
||||
await rm(staging, { recursive: true, force: true });
|
||||
}
|
||||
console.log('Built static site in dist/');
|
||||
+43
-3
@@ -4,6 +4,36 @@ import { pathToFileURL } from 'node:url';
|
||||
const root = new URL('../', import.meta.url);
|
||||
const readJSON = async path => JSON.parse(await readFile(new URL(path, root), 'utf8'));
|
||||
const pairs = ['kind', 'title', 'name', 'intro', 'context', 'implementation', 'decisions'];
|
||||
const require = (ok, message) => { if (!ok) throw new Error(message); };
|
||||
const pair = value => Array.isArray(value) && value.length === 2 && value.every(v => typeof v === 'string' && v.trim());
|
||||
const keys = (value, expected) => value !== null && typeof value === 'object' && !Array.isArray(value) && Object.keys(value).length === expected.length && expected.every(k => Object.hasOwn(value, k));
|
||||
const safeHTTPS = value => {
|
||||
if (typeof value !== 'string' || /[\s\\<>"']/.test(value)) return false;
|
||||
try {
|
||||
const url = new URL(value);
|
||||
return value.startsWith('https://') && url.protocol === 'https:' && !!url.hostname && !url.username && !url.password;
|
||||
} catch { return false; }
|
||||
};
|
||||
export function validateSettings(settings) {
|
||||
require(keys(settings, ['profile', 'revision', 'processes']), 'settings: expected only profile, revision and processes');
|
||||
const p = settings.profile;
|
||||
require(keys(p, ['name', 'github', 'gitea', 'school', 'qualification', 'reviewed']), 'profile: invalid structure');
|
||||
require(typeof p.name === 'string' && p.name.trim(), 'profile.name: required text');
|
||||
require(typeof p.reviewed === 'string' && /^\d{4}-\d{2}-\d{2}$/.test(p.reviewed) && Number.isFinite(Date.parse(p.reviewed)) && new Date(p.reviewed).toISOString().slice(0, 10) === p.reviewed, 'profile.reviewed: expected a valid ISO date');
|
||||
for (const key of ['github', 'gitea', 'school', 'qualification']) require(safeHTTPS(p[key]), `profile.${key}: expected a safe HTTPS URL`);
|
||||
require(/^https:\/\/github\.com\/[A-Za-z0-9_-]+$/.test(p.github), 'profile.github: expected a GitHub profile');
|
||||
require(/^https:\/\/codealvin\.xyz\/[A-Za-z0-9_-]+$/.test(p.gitea), 'profile.gitea: expected a Gitea profile');
|
||||
require(/^https:\/\/github\.com\/[A-Za-z0-9_-]+\/[A-Za-z0-9_.-]+$/.test(p.school) && !['.', '..'].includes(p.school.split('/').pop()), 'profile.school: expected a GitHub repository');
|
||||
require(typeof settings.revision === 'string' && /^[a-f0-9]{40}$/.test(settings.revision), 'revision: expected a full lowercase commit SHA');
|
||||
require(Array.isArray(settings.processes), 'processes: expected an array');
|
||||
const codes = new Set();
|
||||
for (const process of settings.processes) {
|
||||
require(keys(process, ['code', 'title', 'description']), 'process: invalid structure');
|
||||
require(typeof process.code === 'string' && /^B[1-9]\d*-K[1-9]\d*-W[1-9]\d*$/.test(process.code) && !codes.has(process.code), 'process.code: invalid or duplicate code');
|
||||
codes.add(process.code);
|
||||
require(pair(process.title) && pair(process.description), 'process: provide Dutch and English title and description');
|
||||
}
|
||||
}
|
||||
export function validateProjects(projects, processes) {
|
||||
const ids = new Set();
|
||||
const codes = new Set(processes.map(p => p.code));
|
||||
@@ -18,7 +48,12 @@ export function validateProjects(projects, processes) {
|
||||
for (const key of ['number', 'challenge']) require(typeof p[key] === 'string' && p[key].trim(), `${p.id}.${key}: required text`);
|
||||
for (const key of ['stack', 'nodes']) require(Array.isArray(p[key]) && p[key].length > 0 && p[key].every(v => typeof v === 'string' && v.trim()), `${p.id}.${key}: provide text entries`);
|
||||
require(p.nodes.length === 3, `${p.id}.nodes: provide three diagram labels`);
|
||||
require(path(p.path), `${p.id}.path: provide a repository-relative path`);
|
||||
if (p.repository !== undefined) {
|
||||
const r = p.repository;
|
||||
require(r && /^https:\/\/(github\.com|codealvin\.xyz)\/[A-Za-z0-9_.-]+\/[A-Za-z0-9_.-]+$/.test(r.url) && /^[a-f0-9]{40}$/.test(r.revision) && ['github', 'gitea'].includes(r.forge) && (r.forge === 'github') === r.url.startsWith('https://github.com/'), `${p.id}.repository: provide a supported repository and pinned commit`);
|
||||
}
|
||||
require(path(p.path) || (p.repository && p.path === ''), `${p.id}.path: provide a repository-relative path`);
|
||||
require(p.setting === undefined || pair(p.setting), `${p.id}.setting: provide Dutch and English text`);
|
||||
require(mapping(p.codes), `${p.id}.codes: unknown process code`);
|
||||
require(Array.isArray(p.evidence), `${p.id}.evidence: expected an array`);
|
||||
for (const e of p.evidence) {
|
||||
@@ -28,13 +63,18 @@ export function validateProjects(projects, processes) {
|
||||
}
|
||||
export async function compileContent() {
|
||||
const settings = await readJSON('content/settings.json');
|
||||
validateSettings(settings);
|
||||
const files = (await readdir(new URL('content/projects/', root))).filter(f => f.endsWith('.json')).sort();
|
||||
const projects = await Promise.all(files.map(f => readJSON(`content/projects/${f}`)));
|
||||
projects.sort((a, b) => a.number.localeCompare(b.number, undefined, { numeric: true }));
|
||||
validateProjects(projects, settings.processes);
|
||||
return '// Generated from content/ by npm run content. Edit the JSON source files.\n' +
|
||||
Object.entries({ ...settings, projects }).map(([key, value]) => `export const ${key} = ${JSON.stringify(value, null, 2)};`).join('\n') +
|
||||
'\nexport const source = (path, directory = false) => `${profile.school}/${directory ? "tree" : "blob"}/${revision}/${path.split("/").map(encodeURIComponent).join("/")}`;\n';
|
||||
Object.entries({ profile: settings.profile, revision: settings.revision, processes: settings.processes, projects }).map(([key, value]) => `export const ${key} = ${JSON.stringify(value, null, 2)};`).join('\n') +
|
||||
'\nexport const source = (path, directory = false, project = {}) => {\n' +
|
||||
' const repo = project.repository || { url: profile.school, revision, forge: "github" };\n' +
|
||||
' const view = repo.forge === "gitea" ? "src/commit" : (directory ? "tree" : "blob");\n' +
|
||||
' return `${repo.url}/${view}/${repo.revision}${path ? "/" + path.split("/").map(encodeURIComponent).join("/") : ""}`;\n' +
|
||||
'};\n';
|
||||
}
|
||||
if (process.argv[1] && import.meta.url === pathToFileURL(process.argv[1]).href) {
|
||||
const [command, id] = process.argv.slice(2);
|
||||
|
||||
+7
-3
@@ -4,12 +4,16 @@ import { compileContent } from './content.mjs';
|
||||
const port = Number(process.env.PORT || 4173);
|
||||
const files = new Map([['/', 'index.html'], ['/index.html', 'index.html'], ['/styles.css', 'styles.css'], ['/app.js', 'app.js'], ['/content.js', 'content.js'], ['/favicon.svg', 'favicon.svg']]);
|
||||
const mime = { html: 'text/html', css: 'text/css', js: 'text/javascript', svg: 'image/svg+xml' };
|
||||
createServer(async (req, res) => {
|
||||
const file = files.get(new URL(req.url, 'http://localhost').pathname);
|
||||
const server = createServer(async (req, res) => {
|
||||
let pathname;
|
||||
try { pathname = new URL(req.url, 'http://localhost').pathname; }
|
||||
catch { res.writeHead(400); return res.end('Bad request'); }
|
||||
const file = files.get(pathname);
|
||||
if (!file) { res.writeHead(404); return res.end('Not found'); }
|
||||
try {
|
||||
const body = file === 'content.js' ? await compileContent() : await readFile(new URL(`../${file}`, import.meta.url));
|
||||
res.writeHead(200, { 'Content-Type': `${mime[file.split('.').pop()]}; charset=utf-8`, 'Cache-Control': 'no-cache', 'X-Content-Type-Options': 'nosniff' });
|
||||
res.end(body);
|
||||
} catch { res.writeHead(500); res.end('Unable to read file'); }
|
||||
}).listen(port, '127.0.0.1', () => console.log(`Local: http://127.0.0.1:${port}`));
|
||||
}).listen(port, '127.0.0.1', () => console.log(`Local: http://127.0.0.1:${server.address().port}`));
|
||||
|
||||
Reference in new issue
Block a user