47 lines
2.0 KiB
JavaScript
47 lines
2.0 KiB
JavaScript
// Post-build step (NFR-9): renders the static landing text into dist/index.html so crawlers see
|
|
// it without JavaScript. The client (createRoot in src/main.tsx) replaces it on load.
|
|
import { build } from 'vite';
|
|
import { readFile, writeFile, rm } from 'node:fs/promises';
|
|
import { pathToFileURL } from 'node:url';
|
|
import path from 'node:path';
|
|
|
|
const root = process.cwd();
|
|
const ssrDir = path.join(root, 'node_modules', '.prerender');
|
|
const htmlPath = path.join(root, 'dist', 'index.html');
|
|
|
|
await build({
|
|
logLevel: 'warn',
|
|
build: {
|
|
ssr: path.join(root, 'src/prerender/entry-server.tsx'),
|
|
outDir: ssrDir,
|
|
emptyOutDir: true,
|
|
rollupOptions: { output: { entryFileNames: 'entry-server.mjs', format: 'esm' } },
|
|
},
|
|
});
|
|
|
|
const { render } = await import(pathToFileURL(path.join(ssrDir, 'entry-server.mjs')).href);
|
|
// The hero marks the region the CMS host may replace; React cannot write comments, so the component renders
|
|
// <i data-cms-marker="CMS:HERO-HTML"> placeholders that become <!--CMS:HERO-HTML--> here. Without a host they are
|
|
// plain comments and nothing changes for the visitor.
|
|
const markerPattern = /<i\s[^>]*data-cms-marker="([^"]+)"[^>]*><\/i>/g;
|
|
const rendered = render();
|
|
const markup = rendered.replace(markerPattern, (_all, name) => `<!--${name}-->`);
|
|
const expectedMarkers = ['<!--CMS:HERO-HTML-->', '<!--/CMS:HERO-HTML-->'];
|
|
for (const marker of expectedMarkers) {
|
|
if (markup.split(marker).length !== 2 || /data-cms-marker/.test(markup)) {
|
|
throw new Error(`prerender: expected exactly one ${marker} in the static landing`);
|
|
}
|
|
}
|
|
|
|
const html = await readFile(htmlPath, 'utf8');
|
|
const placeholder = '<div id="root"></div>';
|
|
if (!html.includes(placeholder)) {
|
|
throw new Error(`prerender: ${placeholder} not found in dist/index.html`);
|
|
}
|
|
await writeFile(
|
|
htmlPath,
|
|
html.replace(placeholder, () => `<div id="root">${markup}</div>`),
|
|
);
|
|
await rm(ssrDir, { recursive: true, force: true });
|
|
console.log(`prerender: ${markup.length} bytes of static HTML injected into dist/index.html`);
|