Files
portfolio/scripts/build.mjs
T
2026-11-10 13:54:19 +01:00

31 lines
1.6 KiB
JavaScript

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';
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/');