Some checks failed
PR checks / checks (pull_request) Failing after 2m16s
The public demo (demo.runicgateway.com) is live, so the site's demo slot can be switched on. Two decisions of record, PLAN.md §15: - D82: /beta reads the demo's GET /api/v1/public/settings demo.logins on the server, caches it for a minute, and lists the published sign-ins with the next wipe. If the demo does not answer, /beta links to its sign-in page instead. Gate two reads as in place. - D83: a deep link into a game module's pages carries data-demo-game, and applyBrand.mjs fills it only for games in the new mounted demoGames list. The Rust features gain links into /rust and /rust/servers/demo. UO's stay hidden on a Rust demo. The public-demo not-built entry is removed, because its resolvedBy was met. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01E14m6SuuY6i1vASFeGDBeY
402 lines
18 KiB
JavaScript
402 lines
18 KiB
JavaScript
#!/usr/bin/env node
|
|
/**
|
|
* applyBrand.mjs — brand TEXT from the bind mount (PLAN.md §7)
|
|
*
|
|
* Runs immediately before the server, as part of `npm start`. For an empty mount — the
|
|
* stock deployment, and the common case — it reads two small files, finds nothing to do
|
|
* and exits. It is not a build step and it is not a template engine.
|
|
*
|
|
* ---------------------------------------------------------------------------------------
|
|
* THE PROBLEM THIS SOLVES
|
|
* ---------------------------------------------------------------------------------------
|
|
* §7 promises that renaming the product, changing the Discord invite or publishing a
|
|
* different contact address is the same class of change as swapping a logo: edit the file
|
|
* in the mount, restart, done. §6 prerenders every page. Those two are in direct conflict,
|
|
* because a value read at build time is baked into HTML that no mounted file can reach.
|
|
*
|
|
* Assets escape the conflict by being served per request from `/brand/*`. Text cannot: it
|
|
* is inside the markup.
|
|
*
|
|
* Three ways out were considered and the org lead chose this one (2026-08-20):
|
|
*
|
|
* 1. THIS — rewrite the built HTML at boot, before the server opens a socket. Every page
|
|
* stays prerendered, Pagefind still has static HTML to index in phase 10, and the docs
|
|
* are covered by the same pass as the marketing pages.
|
|
* 2. Mark the brand-bearing pages `prerender = false`. Simpler, but the footer is on
|
|
* every page, so "the handful" is the whole site — and the docs would have to stay
|
|
* static for search anyway, leaving them showing the stock name.
|
|
* 3. Accept text as build-time and amend §7. Cheapest, and it gives up the promise.
|
|
*
|
|
* ---------------------------------------------------------------------------------------
|
|
* WHY IT REWRITES FROM A RECORD RATHER THAN FROM THE DEFAULTS
|
|
* ---------------------------------------------------------------------------------------
|
|
* The obvious version of this script replaces the DEFAULT value with the mounted one. It
|
|
* works exactly once. The second time an operator edits the mount — renaming from "Foo" to
|
|
* "Bar" — the default no longer appears anywhere in the HTML, every replacement matches
|
|
* nothing, and the site silently keeps saying "Foo". The bug would surface as "the first
|
|
* change worked and the second did nothing", which is a miserable thing to debug.
|
|
*
|
|
* So the script records what it baked, in `dist/.brand-applied.json`, and the next run
|
|
* rewrites from that record to the new values. A fresh image has no record and starts from
|
|
* the defaults, which is the same thing said differently.
|
|
*
|
|
* ---------------------------------------------------------------------------------------
|
|
* WHAT MAKES PLAIN STRING REPLACEMENT SAFE HERE
|
|
* ---------------------------------------------------------------------------------------
|
|
* Not much, on its own — which is why `scripts/checkBrand.mjs` exists. It fails the build
|
|
* if any rewritable default is short enough to collide with ordinary markup or prose. The
|
|
* check is the mechanism; the eight-character minimum below is only its last line.
|
|
*
|
|
* Replacing the site name across the docs as well as the marketing pages is deliberate. If
|
|
* the product is renamed, prose that says "Runic Gateway" should say the new name too.
|
|
*/
|
|
|
|
import { readFileSync, writeFileSync, existsSync, readdirSync, statSync } from 'node:fs';
|
|
import { fileURLToPath } from 'node:url';
|
|
import path from 'node:path';
|
|
|
|
const ROOT = fileURLToPath(new URL('..', import.meta.url));
|
|
|
|
const DIST = process.env.BRAND_DIST || path.join(ROOT, 'dist');
|
|
const CLIENT = path.join(DIST, 'client');
|
|
const RECORD = path.join(DIST, '.brand-applied.json');
|
|
|
|
const MOUNT_DIR = process.env.BRAND_DIR || path.join(process.cwd(), 'brand');
|
|
const DEFAULT_DIR = process.env.BRAND_DEFAULT_DIR || path.join(process.cwd(), 'brand-default');
|
|
|
|
/**
|
|
* The fields that appear in markup as literal text, and may therefore be rewritten.
|
|
*
|
|
* `demoUrl` is not one of them and is handled separately below: its default is the empty
|
|
* string, and there is no such thing as replacing every occurrence of "".
|
|
*/
|
|
const TEXT_FIELDS = ['siteName', 'tagline', 'contactEmail', 'discordInvite', 'giteaOrg'];
|
|
|
|
/**
|
|
* Below this length a value is too likely to occur inside unrelated markup — a class name,
|
|
* an attribute, a word in a sentence — for a blind replacement to be safe. `checkBrand.mjs`
|
|
* enforces the same floor at build time, where the failure is cheap; this is the copy that
|
|
* runs in production, where being wrong means corrupted pages.
|
|
*/
|
|
const MIN_REWRITABLE_LENGTH = 8;
|
|
|
|
const REWRITABLE_EXTENSIONS = new Set(['.html', '.webmanifest']);
|
|
|
|
function readJson(file, label) {
|
|
try {
|
|
return JSON.parse(readFileSync(file, 'utf8'));
|
|
} catch (error) {
|
|
if (error.code === 'ENOENT') return null;
|
|
// A malformed mounted brand.json must not take the site down.
|
|
//
|
|
// The alternative — exit non-zero and let the container crash-loop — surfaces the typo
|
|
// immediately, and that is genuinely tempting. But an operator editing a mount is
|
|
// watching the logs, whereas the restart six months later that trips over the same file
|
|
// is unattended, and a marketing site that is up with stock branding beats one that is
|
|
// down with correct branding.
|
|
console.error(`\n[brand] ${label} is not valid JSON and will be IGNORED:\n ${file}\n ${error.message}\n`);
|
|
return null;
|
|
}
|
|
}
|
|
|
|
/** `$comment` keys are documentation for whoever opens the mounted copy, not fields. */
|
|
const fieldsOf = (object) =>
|
|
Object.fromEntries(Object.entries(object || {}).filter(([key]) => !key.startsWith('$')));
|
|
|
|
const defaults = fieldsOf(readJson(path.join(DEFAULT_DIR, 'brand.json'), 'the stock brand.json'));
|
|
const mounted = fieldsOf(readJson(path.join(MOUNT_DIR, 'brand.json'), 'the mounted brand.json'));
|
|
|
|
if (!Object.keys(defaults).length) {
|
|
console.error(
|
|
`\n[brand] no stock brand.json at ${path.join(DEFAULT_DIR, 'brand.json')}.\n` +
|
|
`brand-default/ is baked into the image and must always be complete (§7).\n`
|
|
);
|
|
process.exit(1);
|
|
}
|
|
|
|
for (const key of Object.keys(mounted)) {
|
|
if (!(key in defaults)) {
|
|
console.warn(`[brand] the mounted brand.json sets an unknown field "${key}" — ignoring it.`);
|
|
}
|
|
}
|
|
|
|
const resolved = { ...defaults, ...mounted };
|
|
const previous = { ...defaults, ...(fieldsOf(readJson(RECORD, 'the applied-brand record')) || {}) };
|
|
|
|
/* ---------------------------------------------------------------------------------------
|
|
Work out what actually changed
|
|
--------------------------------------------------------------------------------------- */
|
|
|
|
const escapeHtml = (value) =>
|
|
value.replace(/&/g, '&').replace(/</g, '<').replace(/>/g, '>').replace(/"/g, '"');
|
|
|
|
const replacements = [];
|
|
|
|
for (const field of TEXT_FIELDS) {
|
|
const from = previous[field];
|
|
const to = resolved[field];
|
|
if (typeof from !== 'string' || typeof to !== 'string' || from === to) continue;
|
|
|
|
if (from.length < MIN_REWRITABLE_LENGTH) {
|
|
console.error(
|
|
`[brand] refusing to rewrite "${field}": the value being replaced (${JSON.stringify(from)}) ` +
|
|
`is under ${MIN_REWRITABLE_LENGTH} characters and would match unrelated markup.`
|
|
);
|
|
continue;
|
|
}
|
|
|
|
replacements.push({ field, from, to });
|
|
// Astro escapes `&`, `<`, `>` and `"` when it writes a value into markup, so a Discord
|
|
// invite or a Gitea URL carrying a query string appears in the HTML in its escaped form.
|
|
// Adding the escaped pair rather than unescaping the document keeps this a string
|
|
// operation on bytes, with no parser to disagree with the browser's.
|
|
const escapedFrom = escapeHtml(from);
|
|
if (escapedFrom !== from) replacements.push({ field, from: escapedFrom, to: escapeHtml(to) });
|
|
}
|
|
|
|
/**
|
|
* The demo slot (§15 / D12) is a rendering decision rather than a piece of text, and this
|
|
* is the one place a string replacement can still express it.
|
|
*
|
|
* The markup contract, which phase 3 writes and this script relies on:
|
|
*
|
|
* <a class="demo-cta" href="" data-demo-url="">See it running</a>
|
|
*
|
|
* `global.css` hides `[data-demo-url='']`, so a stock build renders nothing. Setting
|
|
* `demoUrl` in the mount turns both empty attributes into the URL, which fills the link and
|
|
* reveals it in the same edit. Going back to an empty value reverses it, because the
|
|
* previous value is in the record.
|
|
*/
|
|
const demoFrom = previous.demoUrl || '';
|
|
const demoTo = resolved.demoUrl || '';
|
|
|
|
if (demoFrom !== demoTo) {
|
|
const attr = (value) => `href="${escapeHtml(value)}" data-demo-url="${escapeHtml(value)}"`;
|
|
replacements.push({ field: 'demoUrl', from: attr(demoFrom), to: attr(demoTo) });
|
|
}
|
|
|
|
/**
|
|
* The demo's DEEP links (§15 / D25), which `/features/` writes one of per capability that
|
|
* has a stable public route:
|
|
*
|
|
* <a class="demo-link" href="" data-demo-url="" data-demo-path="/uo/market">see it live</a>
|
|
*
|
|
* The slot above cannot express these. It is a literal string swap of a whole URL, so it
|
|
* can only ever put the demo's root in an `href` — and reversing it would not even find a
|
|
* deep link, whose `href` is the root plus a path and therefore matches no literal the
|
|
* script knows.
|
|
*
|
|
* This pass is a different shape on purpose: it does not replace a previous value, it
|
|
* RECOMPUTES both attributes from `data-demo-path`, which never changes. That makes it
|
|
* idempotent and exactly reversible, so it runs unconditionally in the loop below rather
|
|
* than only when the demo URL moved. `data-demo-url` is still filled with the bare root
|
|
* because `global.css` hides `[data-demo-url='']` — the visibility rule stays one rule for
|
|
* both kinds of link, and only the `href` differs.
|
|
*/
|
|
const DEEP_LINK = /href="[^"]*" data-demo-url="[^"]*" data-demo-path="([^"]*)"(?: data-demo-game="([^"]*)")?/g;
|
|
|
|
/**
|
|
* Which games the demo runs (D83). A deep link into a game module's pages carries that
|
|
* game's id in `data-demo-game`, and it is filled only when the mounted `demoGames` names
|
|
* it: the demo is a Rust deployment, and a `/uo/market` link into it is a 404. Core's own
|
|
* links (`/wiki`, `/site/events`) carry no game and follow `demoUrl` alone, because every
|
|
* deployment has them.
|
|
*
|
|
* An absent or malformed list means no game's links, not every game's. A demo whose games
|
|
* nobody named is one whose game links cannot be known to work.
|
|
*/
|
|
const gamesOf = (value) => (Array.isArray(value) ? value.filter((id) => typeof id === 'string') : []);
|
|
const gamesFrom = gamesOf(previous.demoGames);
|
|
const gamesTo = gamesOf(resolved.demoGames);
|
|
const gamesChanged = gamesFrom.join(',') !== gamesTo.join(',');
|
|
|
|
if ('demoGames' in mounted && !Array.isArray(mounted.demoGames)) {
|
|
console.warn('[brand] the mounted "demoGames" is not a list of game ids — no game links will show.');
|
|
}
|
|
|
|
const deepLinkTo = (demoPath, game) => {
|
|
const root = !game || gamesTo.includes(game) ? demoTo : '';
|
|
const href = root ? `${root.replace(/\/+$/, '')}${demoPath}` : '';
|
|
return (
|
|
`href="${escapeHtml(href)}" data-demo-url="${escapeHtml(root)}" ` +
|
|
`data-demo-path="${demoPath}"` +
|
|
(game === undefined ? '' : ` data-demo-game="${game}"`)
|
|
);
|
|
};
|
|
|
|
if (!replacements.length && !gamesChanged) {
|
|
console.log('[brand] mount matches what is already applied; nothing to rewrite.');
|
|
process.exit(0);
|
|
}
|
|
|
|
/* ---------------------------------------------------------------------------------------
|
|
Rewrite
|
|
--------------------------------------------------------------------------------------- */
|
|
|
|
if (!existsSync(CLIENT)) {
|
|
console.error(`\n[brand] no build to rewrite at ${CLIENT}. Run \`npm run build\` first.\n`);
|
|
process.exit(1);
|
|
}
|
|
|
|
function* walk(dir) {
|
|
for (const entry of readdirSync(dir, { withFileTypes: true })) {
|
|
const full = path.join(dir, entry.name);
|
|
if (entry.isDirectory()) yield* walk(full);
|
|
else if (REWRITABLE_EXTENSIONS.has(path.extname(entry.name))) yield full;
|
|
}
|
|
}
|
|
|
|
const counts = new Map(replacements.map((r) => [r.field, 0]));
|
|
counts.set('demoDeep', 0);
|
|
let filesTouched = 0;
|
|
|
|
/**
|
|
* The CSP (§6, D48) hashes every inline `<script>` and `<style>` in the build. This script
|
|
* runs after that hashing and rewrites the same files, so a brand value that happened to
|
|
* sit inside an inline block would change its bytes, invalidate its hash and get the block
|
|
* refused by the browser — with no error anywhere except a console nobody has open. The
|
|
* page would render perfectly and the script simply would not run.
|
|
*
|
|
* Nothing puts brand text in an inline script today, and the replacements are guarded by
|
|
* MIN_REWRITABLE_LENGTH so they are unlikely to collide by accident. "Unlikely" is not the
|
|
* standard for a failure this quiet, so the collision is checked rather than reasoned
|
|
* about: if a rewrite ever lands inside an inline block, this refuses to write that file
|
|
* and says so, and the page keeps its stock text instead of losing its behaviour.
|
|
*/
|
|
const INLINE_BLOCK = /<(script|style)(?![^>]*\bsrc\s*=)([^>]*)>([\s\S]*?)<\/\1>/g;
|
|
|
|
/**
|
|
* The structured-data block (D50) is a `<script>` that no browser executes and no CSP hash
|
|
* covers, so it is not one of the blocks this guard protects — and it MUST NOT be, because
|
|
* it contains the site's name. Treating it as a script would make the guard refuse to
|
|
* rewrite the homepage, which is §7 failing on the one page that matters most.
|
|
*/
|
|
const DATA_BLOCK = /type\s*=\s*["']application\/(ld\+json|json)["']/i;
|
|
|
|
const inlineRanges = (html) => {
|
|
const ranges = [];
|
|
INLINE_BLOCK.lastIndex = 0;
|
|
let match;
|
|
while ((match = INLINE_BLOCK.exec(html))) {
|
|
if (match[1] === 'script' && DATA_BLOCK.test(match[2])) continue;
|
|
// Where the block's CONTENT starts — measured back from the end of the whole match, so
|
|
// the opening tag's attributes cannot throw the offset off: `</script>` is the tag name
|
|
// plus three characters.
|
|
const closing = match[1].length + 3;
|
|
const start = match.index + match[0].length - closing - match[3].length;
|
|
ranges.push([start, start + match[3].length]);
|
|
}
|
|
return ranges;
|
|
};
|
|
const hitsInlineBlock = (html, needle) => {
|
|
if (!needle || !html.includes(needle)) return false;
|
|
const ranges = inlineRanges(html);
|
|
if (ranges.length === 0) return false;
|
|
for (let at = html.indexOf(needle); at !== -1; at = html.indexOf(needle, at + 1)) {
|
|
const end = at + needle.length;
|
|
if (ranges.some(([from, to]) => at < to && end > from)) return true;
|
|
}
|
|
return false;
|
|
};
|
|
const inlineCollisions = [];
|
|
|
|
for (const file of walk(CLIENT)) {
|
|
const before = readFileSync(file, 'utf8');
|
|
let after = before;
|
|
|
|
if (path.extname(file) === '.html') {
|
|
const colliding = replacements.filter(({ from }) => hitsInlineBlock(before, from));
|
|
if (colliding.length) {
|
|
inlineCollisions.push({
|
|
file: path.relative(CLIENT, file),
|
|
fields: [...new Set(colliding.map((c) => c.field))],
|
|
});
|
|
continue;
|
|
}
|
|
}
|
|
|
|
for (const { field, from, to } of replacements) {
|
|
if (!after.includes(from)) continue;
|
|
counts.set(field, counts.get(field) + after.split(from).length - 1);
|
|
after = after.split(from).join(to);
|
|
}
|
|
|
|
// After the literal swaps, never before: the plain-slot replacement also matches the
|
|
// first two attributes of a deep link, so it runs first and this pass corrects the
|
|
// `href` it just wrote. Recomputing rather than replacing is what makes that safe.
|
|
after = after.replace(DEEP_LINK, (whole, demoPath, game) => {
|
|
const rebuilt = deepLinkTo(demoPath, game);
|
|
if (rebuilt !== whole) counts.set('demoDeep', counts.get('demoDeep') + 1);
|
|
return rebuilt;
|
|
});
|
|
|
|
if (after !== before) {
|
|
writeFileSync(file, after);
|
|
filesTouched++;
|
|
}
|
|
}
|
|
|
|
writeFileSync(RECORD, `${JSON.stringify(resolved, null, 2)}\n`);
|
|
|
|
console.log(`[brand] applied the mounted brand to ${filesTouched} file(s):`);
|
|
for (const { field, from, to } of replacements) {
|
|
if (from.startsWith('href=')) continue; // the demo pair, reported once below
|
|
console.log(` ${field.padEnd(14)} ${JSON.stringify(from)} -> ${JSON.stringify(to)} (${counts.get(field)}x)`);
|
|
}
|
|
if (demoFrom !== demoTo) {
|
|
console.log(` ${'demoUrl'.padEnd(14)} ${demoTo ? `slot shown -> ${demoTo}` : 'slot hidden'} (${counts.get('demoUrl')}x)`);
|
|
}
|
|
if (counts.get('demoDeep')) {
|
|
console.log(
|
|
` ${'demoUrl deep'.padEnd(14)} ${demoTo ? `linked -> ${demoTo}/…` : 'links hidden'} (${counts.get('demoDeep')}x)`
|
|
);
|
|
}
|
|
if (gamesChanged) {
|
|
console.log(` ${'demoGames'.padEnd(14)} ${gamesTo.length ? gamesTo.join(', ') : 'no game links'}`);
|
|
}
|
|
|
|
if (inlineCollisions.length) {
|
|
console.error(
|
|
`\n[brand] ${inlineCollisions.length} file(s) were LEFT UNCHANGED: a brand value occurs ` +
|
|
`inside an inline <script> or <style>, and rewriting it would break that block's CSP ` +
|
|
`hash (§6, D48) — the page would render and the script would silently not run.\n`
|
|
);
|
|
for (const { file, fields } of inlineCollisions) {
|
|
console.error(` ! ${file} (${fields.join(', ')})`);
|
|
}
|
|
console.error(
|
|
`\n Those pages keep the stock text. Fix it by taking the brand value out of the inline\n` +
|
|
` block — move it into markup the CSP does not hash, or into /brand/theme.css.\n`
|
|
);
|
|
}
|
|
|
|
/* ---------------------------------------------------------------------------------------
|
|
Search
|
|
--------------------------------------------------------------------------------------- */
|
|
|
|
/**
|
|
* Pagefind builds its index from the built HTML at BUILD time, so everything above reaches
|
|
* the pages and none of it reaches the search results: a site renamed through the mount
|
|
* would answer a search for its own name with the stock one, and every result title would
|
|
* still carry the old suffix. Phase 2 recorded that and left it for this phase, when
|
|
* search became site-wide (D47).
|
|
*
|
|
* The fix is to re-index, which is cheap and needs nothing the container does not already
|
|
* have — Pagefind is what Starlight ran at build. It only runs when a rewrite actually
|
|
* happened, so the stock deployment, which is the common case, still pays nothing.
|
|
*/
|
|
if (filesTouched > 0) {
|
|
const pagefind = await import('pagefind');
|
|
try {
|
|
const { index } = await pagefind.createIndex();
|
|
const { page_count } = await index.addDirectory({ path: CLIENT });
|
|
await index.writeFiles({ outputPath: path.join(CLIENT, 'pagefind') });
|
|
console.log(`[brand] re-indexed ${page_count} page(s) for search so results agree with it.`);
|
|
} catch (error) {
|
|
// Search degrading to stale titles is not a reason to refuse to serve the site.
|
|
console.error(`[brand] could not rebuild the search index; it keeps the built one: ${error.message}`);
|
|
} finally {
|
|
await pagefind.close();
|
|
}
|
|
}
|