scaling-swarms / backend /scripts /sync-template-layout.mjs
tfrere's picture
tfrere HF Staff
Cursor
build: mirror the research-article-template page layout
e5e073b
Raw History Blame Contribute Delete
6.32 kB
#!/usr/bin/env node
// Mirror the research-article-template page layout into the editor:
// - the grid tokens and layout stylesheets go to frontend/src/styles/template-layout/
// (loaded by the editor and inlined by the publisher), with @custom-media
// resolved because neither Vite nor the publisher runs PostCSS;
// - the paper hero styles are lifted from HeroPaper.astro's <style> block;
// - the layout scripts (TOC, heading anchors, sidenotes, meta columns, debug
// grid on ?grid) are bundled into one IIFE inlined in every published page.
//
// node scripts/sync-template-layout.mjs [templateDir] # write
// node scripts/sync-template-layout.mjs [templateDir] --check # fail if stale
//
// templateDir defaults to $TEMPLATE_DIR, then ../research-article-template
// next to this repo.
import { readFile, writeFile, mkdir } from 'node:fs/promises';
import { existsSync } from 'node:fs';
import { execFileSync } from 'node:child_process';
import { dirname, join, resolve } from 'node:path';
import { fileURLToPath } from 'node:url';
import { build } from 'esbuild';
const backendDir = resolve(dirname(fileURLToPath(import.meta.url)), '..');
const repoDir = resolve(backendDir, '..');
const args = process.argv.slice(2);
const checkOnly = args.includes('--check');
const templateDir = resolve(
args.find((a) => !a.startsWith('--')) || process.env.TEMPLATE_DIR || join(repoDir, '..', 'research-article-template'),
);
const appDir = join(templateDir, 'app', 'src');
if (!existsSync(join(appDir, 'styles', '_grid.css'))) {
console.error(`No new-layout template found at ${templateDir} (missing app/src/styles/_grid.css).`);
process.exit(1);
}
let revision = 'unknown';
try {
revision = execFileSync('git', ['-C', templateDir, 'rev-parse', '--short', 'HEAD'], { encoding: 'utf8' }).trim();
} catch {
// Not a git checkout: the header just says "unknown".
}
const read = (rel) => readFile(join(appDir, rel), 'utf8');
const customMedia = new Map();
for (const m of (await read('styles/_variables.css')).matchAll(/@custom-media\s+(--[\w-]+)\s+(\([^;]+\))\s*;/g)) {
customMedia.set(m[1], m[2]);
}
const resolveMedia = (css) => {
let out = css;
for (const [name, query] of customMedia) out = out.replaceAll(`(${name})`, query);
const left = out.match(/\(--bp-[\w-]+\)/);
if (left) throw new Error(`Unresolved custom media ${left[0]}`);
return out;
};
const cssHeader = (source) => [
'/* GENERATED FILE - do not edit by hand.',
` Source: research-article-template@${revision} app/src/${source}`,
' Regenerate with `npm run sync:template-layout` in backend/. */',
'',
'',
].join('\n');
const STYLES = {
'_grid.css': 'styles/_grid.css',
'_layout.css': 'styles/_layout.css',
'_hero.css': 'styles/layout/_hero.css',
'_toc.css': 'styles/layout/_toc.css',
'_headings.css': 'styles/layout/_headings.css',
'_sidenote.css': 'styles/layout/_sidenote.css',
'_footer.css': 'styles/layout/_footer.css',
};
const stylesOut = 'frontend/src/styles/template-layout';
const outputs = {};
for (const [name, source] of Object.entries(STYLES)) {
outputs[`${stylesOut}/${name}`] = cssHeader(source) + resolveMedia(await read(source)).trimEnd() + '\n';
}
const heroPaper = (await read('components/HeroPaper.astro')).match(/<style>([\s\S]*?)<\/style>/);
if (!heroPaper) throw new Error('HeroPaper.astro has no <style> block');
const heroPaperCss = heroPaper[1]
.replace(/:global\(([^)]*)\)/g, '$1')
.split('\n')
.map((line) => line.replace(/^ {2}/, ''))
.join('\n')
.trim();
outputs[`${stylesOut}/_hero-paper.css`] =
cssHeader('components/HeroPaper.astro (<style>)') + resolveMedia(heroPaperCss) + '\n';
const heroUtils = await read('components/heroUtils.ts');
const linkIcons = heroUtils.match(/export const LINK_ICONS[\s\S]*?\n};\n/);
const getLinkIcon = heroUtils.match(/export function getLinkIcon[\s\S]*?\n}\n/);
if (!linkIcons || !getLinkIcon) throw new Error('heroUtils.ts: LINK_ICONS / getLinkIcon not found');
outputs['backend/src/shared/link-icons.generated.ts'] = [
'// GENERATED FILE - do not edit by hand.',
`// Source: research-article-template@${revision} app/src/components/heroUtils.ts`,
'// Regenerate with `npm run sync:template-layout` in backend/.',
'',
linkIcons[0],
getLinkIcon[0],
].join('\n');
const entry = `
import { initHeadingAnchors } from "./heading-anchors";
import { initToc } from "./toc";
import { initSidenotes } from "./sidenotes";
import { initMeta } from "./meta";
initHeadingAnchors();
initToc();
initSidenotes();
initMeta();
const params = new URLSearchParams(location.search);
if ((params.has("grid") && params.get("grid") !== "0") || params.get("debug") === "grid") {
import("./debug-grid").then((m) => m.toggleDebugGrid(true));
}
`;
const bundle = await build({
stdin: { contents: entry, resolveDir: join(appDir, 'scripts', 'layout'), loader: 'ts', sourcefile: 'layout-entry.ts' },
bundle: true,
format: 'iife',
target: 'es2020',
minify: true,
write: false,
logLevel: 'silent',
});
const runtimeJs = bundle.outputFiles[0].text.trim();
outputs['backend/src/publisher/layout-runtime.generated.ts'] = [
'// GENERATED FILE - do not edit by hand.',
`// Source: research-article-template@${revision} app/src/scripts/layout/{toc,heading-anchors,sidenotes,meta,debug-grid}.ts`,
'// Regenerate with `npm run sync:template-layout` in backend/.',
'',
`export const LAYOUT_RUNTIME_JS = ${JSON.stringify(runtimeJs)};`,
'',
].join('\n');
// The revision header changes on every template commit; compare the bodies so
// --check only fails on real drift.
const body = (s) => s.replace(/research-article-template@\S+/g, '');
let stale = 0;
await mkdir(join(repoDir, stylesOut), { recursive: true });
for (const [rel, content] of Object.entries(outputs)) {
const target = join(repoDir, rel);
const current = existsSync(target) ? await readFile(target, 'utf8') : null;
if (current !== null && body(current) === body(content)) continue;
stale++;
if (checkOnly) console.error(`stale: ${rel} (run npm run sync:template-layout)`);
else {
await writeFile(target, content);
console.log(`wrote ${rel}`);
}
}
if (checkOnly && stale) process.exit(1);
if (!stale) console.log(`template layout already in sync with research-article-template@${revision}.`);