Files
AndreaSlopFotografie/web/config/externalizeInlineScripts.ts
T
SluijsensandClaude Sonnet 5.5 ad0b114828 Hero from the CMS: markers HERO-HTML and HERO-PRELOAD, hero key in the data block, picture per ratio, baked fallback
The prerendered hero is plain HTML between the markers (first photo, h1, buttons), the slider takes over after hydration with the hero of the host block, the API or the build. The head preload is added to the finished HTML. Hero texts move into nl.json. The stand-in host and the e2e tests cover the hero.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-16 16:48:00 +01:00

365 lines
12 KiB
TypeScript

// Stap na `vite build` die de inline scripts van Start in dist/client naar
// bestanden verplaatst en de uitvoer controleert.
//
// Waarom (BR-BLD-12): de CSP staat alleen script-src 'self' en Umami toe, en
// Start zet inline scripts in elke geprerenderde pagina. Zonder deze stap
// blokkeert de browser ze. De CSP blijft ongewijzigd.
//
// Alles wordt eerst in het geheugen gepland (planExternalization, puur). Pas
// als er geen enkele overtreding is, schrijft de runner: eerst de
// scriptbestanden, daarna de aangepaste HTML (BR-SCR-12, SECURITY-15). Een
// mislukte controle laat dist/client dus ongemoeid.
import {
mkdirSync,
readFileSync,
readdirSync,
statSync,
writeFileSync,
} from 'node:fs';
import { dirname, join, parse, resolve } from 'node:path';
import { fileURLToPath } from 'node:url';
import { emailAddress } from '../src/lib/emailAddress.ts';
import { siteUrl } from '../src/seo.ts';
import siteContent from '../src/content/siteContent.ts';
import { sitemapXml } from '../src/sitemap.ts';
import sitePages, { pageList } from '../src/sitePages.ts';
import {
ScriptError,
externalizeInlineScripts,
findExecutableInlineScripts,
} from './inlineScripts.ts';
import { injectHeroPreload } from './heroPreload.ts';
import { NOT_FOUND_FILE, pageFile } from './pageFiles.ts';
export type ViolationCode =
| 'NO_HTML'
| 'PAGE_MISSING'
| 'NOT_FOUND_PAGE_MISSING'
| 'UNEXPECTED_HTML'
| 'NO_SCRIPTS_MOVED'
| 'EXECUTABLE_REMAINS'
| 'UNSUPPORTED_SCRIPT'
| 'UNTERMINATED_SCRIPT'
| 'COLLISION'
| 'EMAIL_IN_OUTPUT'
| 'SITEMAP_MISSING'
| 'SITEMAP_DIFFERS'
| 'SOURCE_MAP_PRESENT'
| 'BUILD_PATH_LEAK';
export interface Violation {
file: string;
code: ViolationCode;
// Nooit een scriptinhoud en nooit het e-mailadres (BR-SCR-21)
detail: string;
}
export interface ExpectedFileSet {
// Paginapad uit het register naar zijn bestand
pages: Map<string, string>;
notFound: string;
}
export interface PlanContext {
expected: ExpectedFileSet;
// Het samengestelde adres, of null als de delen ongeldig zijn
address: string | null;
sitemap: string;
// De repositorywortel in alle schrijfwijzen die in tekst kunnen staan
rootPaths: string[];
}
export interface OutputPlan {
// Relatief pad naar nieuwe inhoud
writes: Map<string, string>;
violations: Violation[];
}
// De twee functies van de scriptstap als parameter, zodat de verdediging
// EXECUTABLE_REMAINS getest kan worden: met de echte functies kan ze niet
// optreden (BR-SCR-11).
export interface ScriptStep {
externalize: typeof externalizeInlineScripts;
find: typeof findExecutableInlineScripts;
}
const defaultScriptStep: ScriptStep = {
externalize: externalizeInlineScripts,
find: findExecutableInlineScripts,
};
const ASSETS_DIR = 'assets';
const SITEMAP_FILE = 'sitemap.xml';
const MOVED_REFERENCE = /src="\/assets\/inline-[0-9a-f]{12}\.js"/;
// Hoe een '@' in een bestand kan staan zonder dat het adres leesbaar is:
// platte tekst, URL-codering, JavaScript-escapes en HTML-entiteiten
const AT_ENCODINGS = [
'@',
'%40',
'\\u0040',
'\\u{40}',
'\\x40',
'&#64;',
'&#x40;',
'&commat;',
];
// Staat het adres in een van de schrijfwijzen in de tekst? Hoofdletterongevoelig.
export function containsAddress(text: string, address: string): boolean {
const at = address.indexOf('@');
if (at === -1) return false;
const haystack = text.toLowerCase();
const user = address.slice(0, at).toLowerCase();
const domain = address.slice(at + 1).toLowerCase();
return AT_ENCODINGS.some((encoding) =>
haystack.includes(`${user}${encoding}${domain}`),
);
}
const isHtml = (file: string) => file.endsWith('.html');
// Een ScriptError heeft het bericht `CODE: detail`; de runner zet er zelf de
// code en het bestand voor
const detailOf = (error: ScriptError) =>
error.message.slice(error.code.length + 2);
export function formatViolation({ file, code, detail }: Violation): string {
return `${file}: ${code}: ${detail}`;
}
// De beslissingen van de runner zonder bestandssysteem. `files` bevat alle
// tekstbestanden (en eventuele .map-bestanden) onder dist/client op relatief
// pad met voorwaartse slashes.
export function planExternalization(
files: ReadonlyMap<string, string>,
context: PlanContext,
scripts: ScriptStep = defaultScriptStep,
): OutputPlan {
const violations: Violation[] = [];
const writes = new Map<string, string>();
const add = (file: string, code: ViolationCode, detail: string) =>
violations.push({ file, code, detail });
const htmlFiles = [...files.keys()].filter(isHtml).sort();
const expectedFiles = new Set([
...context.expected.pages.values(),
context.expected.notFound,
]);
if (htmlFiles.length === 0) {
// De ontbrekende pagina's afzonderlijk melden zou alleen herhalen
add('.', 'NO_HTML', 'geen .html-bestand in de uitvoermap');
} else {
for (const [path, file] of context.expected.pages) {
if (!files.has(file)) {
add(file, 'PAGE_MISSING', `pagina ${path} ontbreekt`);
}
}
if (!files.has(context.expected.notFound)) {
add(
context.expected.notFound,
'NOT_FOUND_PAGE_MISSING',
'de 404-pagina ontbreekt',
);
}
}
for (const file of htmlFiles) {
if (!expectedFiles.has(file)) {
add(
file,
'UNEXPECTED_HTML',
'html-bestand dat niet bij het register hoort',
);
}
}
for (const file of htmlFiles) {
if (!expectedFiles.has(file)) continue;
const html = files.get(file)!;
let result;
try {
result = scripts.externalize(injectHeroPreload(html));
} catch (error) {
if (!(error instanceof ScriptError)) throw error;
add(file, error.code, detailOf(error));
continue;
}
const remaining = scripts.find(result.html).length;
if (remaining > 0) {
add(
file,
'EXECUTABLE_REMAINS',
`${remaining} uitvoerbaar inline script blijft over`,
);
}
// Een al verwerkte pagina telt mee, dus twee keer draaien mag
if (!MOVED_REFERENCE.test(result.html)) {
add(
file,
'NO_SCRIPTS_MOVED',
'geen verwijzing naar een verplaatst inline script',
);
}
for (const { fileName, body } of result.moved) {
const path = `${ASSETS_DIR}/${fileName}`;
const existing = writes.get(path) ?? files.get(path);
if (existing !== undefined && existing !== body) {
add(path, 'COLLISION', 'bestaat al met andere inhoud');
} else if (existing === undefined) {
writes.set(path, body);
}
}
if (result.html !== html) writes.set(file, result.html);
}
// De uitvoer zoals hij na het schrijven is: ook de verplaatste scripts
const finalFiles = new Map(files);
for (const [path, content] of writes) finalFiles.set(path, content);
for (const [file, content] of finalFiles) {
if (file.endsWith('.map')) {
add(file, 'SOURCE_MAP_PRESENT', 'sourcemap in de uitvoer');
}
if (context.address && containsAddress(content, context.address)) {
add(file, 'EMAIL_IN_OUTPUT', 'e-mailadres in de uitvoer');
}
if (context.rootPaths.some((root) => content.includes(root))) {
add(file, 'BUILD_PATH_LEAK', 'pad van de repository in de uitvoer');
}
}
const sitemap = files.get(SITEMAP_FILE);
if (sitemap === undefined) {
add(SITEMAP_FILE, 'SITEMAP_MISSING', 'bestand ontbreekt');
} else if (sitemap !== context.sitemap) {
add(
SITEMAP_FILE,
'SITEMAP_DIFFERS',
'inhoud wijkt af van het pagina-register',
);
}
return { writes, violations };
}
// Alleen deze bestanden worden gelezen en op adres en pad doorzocht
const TEXT_EXTENSIONS = [
'.html',
'.js',
'.css',
'.xml',
'.txt',
'.json',
'.webmanifest',
'.map',
];
function readOutput(clientDir: string): Map<string, string> {
const files = new Map<string, string>();
const entries = readdirSync(clientDir, {
recursive: true,
encoding: 'utf8',
})
.map((entry) => entry.replaceAll('\\', '/'))
.filter((entry) => TEXT_EXTENSIONS.some((ext) => entry.endsWith(ext)))
.sort();
for (const entry of entries) {
const path = join(clientDir, entry);
if (statSync(path).isFile())
files.set(entry, readFileSync(path, 'utf8'));
}
return files;
}
// De repositorywortel in de schrijfwijzen waarin hij in tekst kan staan:
// met / , met \ en met verdubbelde \ zoals in een JSON- of JS-string
function rootPathsOf(root: string): string[] {
// De wortel van het bestandssysteem zou alles als lek aanmerken
if (parse(root).root === root) return [];
return [
...new Set([
root,
root.replaceAll('\\', '/'),
root.replaceAll('/', '\\'),
root.replaceAll('/', '\\').replaceAll('\\', '\\\\'),
]),
];
}
function contextFor(clientDir: string): PlanContext {
return {
expected: {
pages: new Map(
Object.keys(sitePages).map((path) => [path, pageFile(path)]),
),
notFound: NOT_FOUND_FILE,
},
address: emailAddress(siteContent.email),
sitemap: sitemapXml(pageList(sitePages), siteUrl),
rootPaths: rootPathsOf(resolve(clientDir, '../..')),
};
}
export interface RunResult {
exitCode: 0 | 1;
violations: Violation[];
written: string[];
}
interface Log {
log: (message: string) => void;
error: (message: string) => void;
}
// Leest de map, plant, en schrijft alleen zonder overtredingen. Geeft de
// exitcode terug in plaats van hem te zetten, zodat tests hem kunnen lezen.
export function externalizeOutput(
clientDir: string,
out: Log = console,
): RunResult {
const context = contextFor(clientDir);
const { writes, violations } = planExternalization(
readOutput(clientDir),
context,
);
if (violations.length > 0) {
for (const violation of violations) {
out.error(formatViolation(violation));
}
return { exitCode: 1, violations, written: [] };
}
// Scriptbestanden eerst: een afgebroken run laat nooit HTML achter die
// naar een bestand verwijst dat niet bestaat
const paths = [...writes.keys()].sort(
(a, b) => Number(isHtml(a)) - Number(isHtml(b)),
);
for (const path of paths) {
const target = join(clientDir, path);
mkdirSync(dirname(target), { recursive: true });
writeFileSync(target, writes.get(path)!, 'utf8');
}
const moved = paths.filter((path) => !isHtml(path)).length;
out.log(
`Inline scripts verplaatst: ${context.expected.pages.size + 1} pagina's gecontroleerd, ${moved} scripts verplaatst, ${paths.length} bestanden geschreven`,
);
return { exitCode: 0, violations, written: paths };
}
// Draait alleen als het bestand zelf wordt gestart (pnpm build), niet als een
// test het importeert. Optioneel argument: de map, standaard dist/client.
if (
process.argv[1] &&
resolve(process.argv[1]) === fileURLToPath(import.meta.url)
) {
process.exitCode = externalizeOutput(
resolve(process.argv[2] ?? 'dist/client'),
).exitCode;
}