NGU-Web/server/src/pageMeta.js
Zaldimmar f1edaaf92a Let superadmins change the whole colour palette
Panel -> Site settings -> Colours: any colour token, with a light and a
dark value (migration 041). The server writes the overrides into each
page's head in the same cascade layers as index.css, so a light-only
change leaves dark mode alone. Values must be #rrggbb (a table CHECK),
and saving refuses a palette that puts any text under 4.5:1 in either
mode, through a new descriptor hook, check(db, id), run inside the
save's transaction.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-09-28 23:26:35 -05:00

513 lines
20 KiB
JavaScript

/* ═══════════════════════════════════════════════════════════════
PAGE METADATA
What a page's HTML should say about it before any JavaScript
runs: title, description, preview image, canonical address,
whether search engines may index it, and structured data. Link
previews (Facebook, iMessage, Slack, Discord, X) never run the
app's JavaScript, so this is the only way a shared event shows
the event rather than the site's defaults.
routes/pages.js puts it into the built index.html for each
request, and serves /sitemap.xml from the same rules.
── Where it comes from ──
/site.json (SITE_CONFIG): the site's name, address, default
description and image, icons, and each static page's title and
description. Laid over it: Panel → Site settings (the
site_settings table, 035), where anything set wins and anything
blank falls back to site.json. siteFor(db) does the merge. The
pages read the same merged values (renderPage writes them into
the HTML as window.__NGU_SITE__, see src/lib/site.ts), so a
heading and its search title can't drift.
The database: records' names, taglines, first paragraphs and
images. A blank site description falls back to the front page's
subhead.
── Rules ──
published, listed indexed, in the sitemap
published, unlisted noindex: reachable by link, not by search
unpublished, missing 404 and noindex, with the site defaults
/admin noindex
Image paths resolve like src/lib/media.ts does: a bare filename
is in the uploads directory, anything starting with / or a scheme
is used as it is.
An SVG isn't used as a preview image (the big sites won't show
one), so it falls back to the site default.
═══════════════════════════════════════════════════════════════ */
import { readFileSync, statSync } from "node:fs";
import path from "node:path";
import { fileURLToPath } from "node:url";
import { loadBlocks, paragraphs } from "./shape.js";
import { themeCss } from "./theme.js";
const here = path.dirname(fileURLToPath(import.meta.url));
export const SITE_CONFIG = path.resolve(process.env.SITE_CONFIG ?? path.join(here, "../../site.json"));
const DESCRIPTION_CHARS = 160;
/* Where a bare filename lives: record images are uploads, whatever
kind they are. Mirrors src/lib/media.ts. */
const UPLOADS = "/uploads";
/* ── site.json, reread when it changes ─────────────────────── */
let cached = { mtime: 0, site: null };
export function loadSite() {
const mtime = statSync(SITE_CONFIG).mtimeMs;
if (cached.site && cached.mtime === mtime) return cached.site;
const site = JSON.parse(readFileSync(SITE_CONFIG, "utf8"));
cached = { mtime, site };
return site;
}
const origin = (site) => (site.url ?? "").replace(/\/$/, "");
/* site.json with the admin's Site settings laid over it: a value set
there wins, a blank one falls back. indexing 'on' / 'off' overrides
robots.index for this database only. Page overrides apply only to
pages site.json knows. */
export function siteFor(db) {
const base = loadSite();
const row = db.prepare(`SELECT * FROM site_settings WHERE id = 'site'`).get() ?? {};
const pages = { ...(base.pages ?? {}) };
const overrides = db
.prepare(`SELECT path, title, description FROM site_setting_pages WHERE settings_id = 'site'`)
.all();
for (const page of overrides) {
const known = pages[page.path];
if (!known) continue;
pages[page.path] = {
title: page.title || known.title,
description: page.description || known.description,
};
}
return {
...base,
title: row.site_name || base.title,
description: row.description || base.description,
openGraph: { ...base.openGraph, image: row.preview_image || base.openGraph?.image },
icons: {
...base.icons,
icon: row.favicon || base.icons?.icon,
apple: row.apple_touch_icon || base.icons?.apple,
},
robots: {
...base.robots,
index: row.indexing ? row.indexing === "on" : base.robots?.index !== false,
},
privacyEmail: row.privacy_email || base.privacyEmail || "",
// The admin's colours (theme.js): only #rrggbb values and fixed
// text, so safe inside <style>.
themeCss: themeCss(db),
pages,
};
}
/* What the browser app reads for headings and titles. */
const forBrowser = (site) => ({ title: site.title, pages: site.pages, privacyEmail: site.privacyEmail });
/* robots.txt for this database's setting, as the build writes it. */
export function robotsTxt(site) {
if (site.robots?.index === false) return "User-agent: *\nDisallow: /\n";
return (
"User-agent: *\nDisallow: /admin\nDisallow: /api\n" +
(site.url ? `\nSitemap: ${origin(site)}/sitemap.xml\n` : "")
);
}
/* ── Helpers ───────────────────────────────────────────────── */
/* Text as a description: the formatting marks content blocks allow
(**bold**, *italic*, [text](url)) taken out, whitespace folded,
cut on a word near DESCRIPTION_CHARS. */
export function plainText(text) {
if (!text) return null;
const flat = String(text)
.replace(/\[([^\]]+)\]\([^)]*\)/g, "$1")
.replace(/\*\*(.+?)\*\*/g, "$1")
.replace(/\*(.+?)\*/g, "$1")
.replace(/\s+/g, " ")
.trim();
if (!flat) return null;
if (flat.length <= DESCRIPTION_CHARS) return flat;
const cut = flat.slice(0, DESCRIPTION_CHARS);
const space = cut.lastIndexOf(" ");
return `${(space > DESCRIPTION_CHARS / 2 ? cut.slice(0, space) : cut).trimEnd()}…`;
}
const first = (...values) => values.find((v) => v != null && String(v).trim() !== "") ?? null;
function imageUrl(site, file, kind) {
if (!file || /\.svg(\?|#|$)/i.test(file)) return null;
// A record's bare filename is an upload; the site's own default
// image (kind null) is a path from the site's root.
const pathOrUrl = /^(https?:|\/)/.test(file) ? file : kind ? `${UPLOADS}/${file}` : `/${file}`;
return /^https?:/.test(pathOrUrl) ? pathOrUrl : `${origin(site)}${pathOrUrl}`;
}
function firstParagraph(db, ownerKind, id, slot) {
return paragraphs(loadBlocks(db, ownerKind, [id], slot).get(id) ?? [])[0] ?? null;
}
/* ── One page ──────────────────────────────────────────────── */
const ORG_ROUTES = { region: "/regions", chapter: "/chapters", partner: "/partners", national: "/organizations" };
function defaults(site, db, pathname) {
const home = db.prepare(`SELECT headline, subhead FROM front_page WHERE id = 'home'`).get();
return {
status: 200,
title: site.title,
description: plainText(first(site.description, home?.subhead)),
image: imageUrl(site, site.openGraph?.image, null),
canonical: `${origin(site)}${pathname === "/" ? "/" : pathname}`,
type: "website",
noindex: false,
jsonLd: null,
site,
};
}
function notFound(meta) {
return { ...meta, status: 404, noindex: true, title: `Page not found | ${meta.title}` };
}
/* Title for a record page: "Name | Site". */
const titled = (site, name) => `${name} | ${site.title}`;
function eventMeta(site, db, id, meta) {
const row = db.prepare(`SELECT * FROM v_events WHERE id = ? AND is_published = 1`).get(id);
if (!row) return notFound(meta);
const when = [row.date_label, row.location_label].filter(Boolean).join(" · ");
const image =
imageUrl(site, row.card_image, "eventBackground") ??
imageUrl(site, row.event_logo, "eventLogo") ??
imageUrl(site, row.effective_org_logo, "organization") ??
meta.image;
const description = plainText(first(row.tagline, firstParagraph(db, "event", id, "card"), when, row.theme));
const place = row.is_online
? { "@type": "VirtualLocation", url: meta.canonical }
: {
"@type": "Place",
name: first(row.venue, row.location_label, row.locality),
address: {
"@type": "PostalAddress",
streetAddress: row.address ?? undefined,
addressLocality: row.locality ?? undefined,
addressRegion: row.state_code ?? undefined,
addressCountry: row.country ?? undefined,
},
};
return {
...meta,
title: titled(site, row.title),
description,
image,
noindex: row.is_listed !== 1,
jsonLd: row.starts_on
? {
"@context": "https://schema.org",
"@type": "Event",
name: row.title,
description: description ?? undefined,
startDate: row.starts_on,
endDate: row.ends_on ?? undefined,
eventStatus:
row.effective_status === "cancelled"
? "https://schema.org/EventCancelled"
: "https://schema.org/EventScheduled",
eventAttendanceMode: row.is_online
? "https://schema.org/OnlineEventAttendanceMode"
: "https://schema.org/OfflineEventAttendanceMode",
location: place,
image: image ? [image] : undefined,
organizer: row.host_name ? { "@type": "Organization", name: row.host_name } : undefined,
url: meta.canonical,
}
: null,
};
}
function organizationMeta(site, db, id, kind, meta) {
const row = db.prepare(`SELECT * FROM organizations WHERE id = ? AND is_published = 1`).get(id);
// /regions/x must be a region: the same slug under the wrong route
// is a page the site doesn't have.
if (!row || (kind && row.kind !== kind)) return notFound(meta);
return {
...meta,
title: titled(site, row.name),
description: plainText(first(row.tagline, firstParagraph(db, "organization", id, "card"))),
image: imageUrl(site, row.logo, "organization") ?? meta.image,
canonical: `${origin(site)}${ORG_ROUTES[row.kind] ?? "/organizations"}/${row.id}`,
noindex: row.is_listed !== 1,
};
}
function teamMeta(site, db, id, meta) {
const row = db
.prepare(
`SELECT t.* FROM teams t
JOIN organizations o ON o.id = t.org_id AND o.is_published = 1
WHERE t.id = ? AND t.is_published = 1`,
)
.get(id);
if (!row) return notFound(meta);
return {
...meta,
title: titled(site, row.name),
description: plainText(first(row.tagline, firstParagraph(db, "team", id, "card"))),
image: imageUrl(site, row.logo, "team") ?? meta.image,
noindex: row.is_listed !== 1,
};
}
function awardMeta(site, db, id, meta) {
const row = db.prepare(`SELECT * FROM awards WHERE id = ? AND is_published = 1`).get(id);
if (!row) return notFound(meta);
return {
...meta,
title: titled(site, row.name),
description: plainText(row.description),
image: imageUrl(site, row.logo, "award") ?? meta.image,
noindex: row.is_listed !== 1,
};
}
function personMeta(site, db, id, meta) {
const row = db.prepare(`SELECT * FROM people WHERE id = ? AND is_published = 1`).get(id);
if (!row) return notFound(meta);
return {
...meta,
title: titled(site, row.display_name),
description: plainText(first(row.tagline, row.bio, firstParagraph(db, "person", id, "card"))),
image: imageUrl(site, row.photo, "person") ?? meta.image,
type: "profile",
noindex: row.is_listed !== 1,
};
}
function blogMeta(site, db, id, meta) {
const row = db.prepare(`SELECT * FROM blog_posts WHERE id = ? AND is_published = 1`).get(id);
if (!row) return notFound(meta);
const authors = db
.prepare(
`SELECT p.display_name AS name
FROM blog_post_authors a
JOIN people p ON p.id = a.person_id AND p.is_published = 1
WHERE a.post_id = ? ORDER BY a.sort_order`,
)
.all(id)
.map((a) => a.name);
if (row.guest_author) authors.push(row.guest_author);
const description = plainText(first(row.excerpt, firstParagraph(db, "blog_post", id, "body")));
const image = imageUrl(site, row.cover_image, "blog") ?? meta.image;
return {
...meta,
title: titled(site, row.title),
description,
image,
type: "article",
noindex: row.is_listed !== 1,
jsonLd: {
"@context": "https://schema.org",
"@type": "BlogPosting",
headline: row.title,
description: description ?? undefined,
datePublished: row.published_on ?? undefined,
dateModified: row.updated_at ? row.updated_at.replace(" ", "T") + "Z" : undefined,
author: authors.length ? authors.map((name) => ({ "@type": "Person", name })) : undefined,
image: image ? [image] : undefined,
publisher: { "@type": "Organization", name: site.title, url: `${origin(site)}/` },
mainEntityOfPage: meta.canonical,
},
};
}
/* The metadata for one request path. */
export function metaFor(db, rawPath) {
const site = siteFor(db);
// Canonical form: no trailing slash (but "/" itself), no query.
const pathname = rawPath.split(/[?#]/)[0].replace(/(.)\/+$/, "$1") || "/";
const meta = defaults(site, db, pathname);
if (pathname === "/") {
return {
...meta,
jsonLd: {
"@context": "https://schema.org",
"@type": "Organization",
name: site.title,
url: `${origin(site)}/`,
logo: meta.image ?? undefined,
},
};
}
if (/^\/admin(\/|$)/.test(pathname)) return { ...meta, title: `Admin | ${site.title}`, noindex: true };
const page = site.pages?.[pathname];
if (page) {
return { ...meta, title: titled(site, page.title), description: plainText(page.description) ?? meta.description };
}
const match = pathname.match(/^\/(events|regions|chapters|partners|organizations|teams|awards|people|blog)\/([^/]+)$/);
if (!match) return notFound(meta);
const [, base, rawId] = match;
let id;
try {
id = decodeURIComponent(rawId);
} catch {
return notFound(meta);
}
switch (base) {
case "events":
return eventMeta(site, db, id, meta);
case "regions":
return organizationMeta(site, db, id, "region", meta);
case "chapters":
return organizationMeta(site, db, id, "chapter", meta);
case "partners":
return organizationMeta(site, db, id, "partner", meta);
case "organizations":
return organizationMeta(site, db, id, null, meta);
case "teams":
return teamMeta(site, db, id, meta);
case "awards":
return awardMeta(site, db, id, meta);
case "people":
return personMeta(site, db, id, meta);
case "blog":
return blogMeta(site, db, id, meta);
}
return notFound(meta);
}
/* ── Into the HTML ─────────────────────────────────────────── */
const escapeHtml = (value) =>
String(value)
.replace(/&/g, "&amp;")
.replace(/"/g, "&quot;")
.replace(/</g, "&lt;")
.replace(/>/g, "&gt;");
/* The tags the build put in (vite.config.ts's site plugin) that this
replaces, so a page never says two different things. */
const REPLACED = [
/<title>[\s\S]*?<\/title>\s*/i,
/<meta\s+(?:name|property)="(?:description|robots|og:[^"]+|twitter:[^"]+)"[^>]*>\s*/gi,
/<link\s+rel="canonical"[^>]*>\s*/gi,
/<script\s+type="application\/ld\+json"[^>]*>[\s\S]*?<\/script>\s*/gi,
/<link\s+rel="(?:icon|apple-touch-icon)"[^>]*>\s*/gi,
];
/* A value for a <script>: JSON with "<" escaped, so nothing in it
can end the element early. */
const scriptJson = (value) => JSON.stringify(value).replace(/</g, "\\u003c");
export function renderPage(html, meta) {
const site = meta.site;
let out = html;
for (const pattern of REPLACED) out = out.replace(pattern, "");
const tags = [
`<title>${escapeHtml(meta.title)}</title>`,
meta.description && `<meta name="description" content="${escapeHtml(meta.description)}">`,
meta.noindex && `<meta name="robots" content="noindex">`,
meta.status === 200 && `<link rel="canonical" href="${escapeHtml(meta.canonical)}">`,
`<meta property="og:site_name" content="${escapeHtml(site.title)}">`,
`<meta property="og:type" content="${meta.type}">`,
`<meta property="og:title" content="${escapeHtml(meta.title)}">`,
meta.description && `<meta property="og:description" content="${escapeHtml(meta.description)}">`,
meta.status === 200 && `<meta property="og:url" content="${escapeHtml(meta.canonical)}">`,
meta.image && `<meta property="og:image" content="${escapeHtml(meta.image)}">`,
`<meta name="twitter:card" content="${meta.image ? "summary_large_image" : "summary"}">`,
meta.image && `<meta name="twitter:image" content="${escapeHtml(meta.image)}">`,
// "</" can't appear inside the script, or the browser would
// end the element there.
site.icons?.icon && `<link rel="icon" href="${escapeHtml(site.icons.icon)}">`,
site.icons?.apple && `<link rel="apple-touch-icon" href="${escapeHtml(site.icons.apple)}">`,
meta.jsonLd && `<script type="application/ld+json">${scriptJson(meta.jsonLd)}</script>`,
// Read by src/lib/site.ts before the app's module runs (a plain
// script in the head runs during parsing; modules wait).
`<script>window.__NGU_SITE__ = ${scriptJson(forBrowser(site))}</script>`,
site.themeCss && `<style id="site-colors">${site.themeCss}</style>`,
].filter(Boolean);
// A blocked site (Site settings indexing off, or site.json's
// robots.index false) stays blocked on every page, whatever the
// record says.
if (site.robots?.index === false && !meta.noindex) {
tags.splice(2, 0, `<meta name="robots" content="noindex, nofollow">`);
}
// A function, so a $& or $` in record text isn't read as a pattern.
return out.replace(/<\/head>/i, () => ` ${tags.join("\n ")}\n </head>`);
}
/* ── Sitemap ───────────────────────────────────────────────── */
export function sitemap(db) {
const site = siteFor(db);
const base = origin(site);
const day = (value) => (value ? String(value).slice(0, 10) : null);
const entries = [
{ loc: "/" },
...Object.keys(site.pages ?? {}).map((loc) => ({ loc })),
...db
.prepare(`SELECT id, updated_at FROM events WHERE is_published = 1 AND is_listed = 1`)
.all()
.map((r) => ({ loc: `/events/${r.id}`, lastmod: day(r.updated_at) })),
...db
.prepare(`SELECT id, kind, updated_at FROM organizations WHERE is_published = 1 AND is_listed = 1`)
.all()
.map((r) => ({ loc: `${ORG_ROUTES[r.kind] ?? "/organizations"}/${r.id}`, lastmod: day(r.updated_at) })),
...db
.prepare(
`SELECT t.id, t.updated_at FROM teams t
JOIN organizations o ON o.id = t.org_id AND o.is_published = 1
WHERE t.is_published = 1 AND t.is_listed = 1`,
)
.all()
.map((r) => ({ loc: `/teams/${r.id}`, lastmod: day(r.updated_at) })),
...db
.prepare(`SELECT id FROM awards WHERE is_published = 1 AND is_listed = 1`)
.all()
.map((r) => ({ loc: `/awards/${r.id}` })),
...db
.prepare(`SELECT id, updated_at FROM people WHERE is_published = 1 AND is_listed = 1`)
.all()
.map((r) => ({ loc: `/people/${r.id}`, lastmod: day(r.updated_at) })),
...db
.prepare(`SELECT id, updated_at FROM blog_posts WHERE is_published = 1 AND is_listed = 1`)
.all()
.map((r) => ({ loc: `/blog/${r.id}`, lastmod: day(r.updated_at) })),
];
const xml = entries
.map(
(e) =>
` <url><loc>${escapeHtml(base + e.loc.split("/").map(encodeURIComponent).join("/"))}</loc>` +
(e.lastmod ? `<lastmod>${e.lastmod}</lastmod>` : "") +
`</url>`,
)
.join("\n");
return `<?xml version="1.0" encoding="UTF-8"?>\n<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">\n${xml}\n</urlset>\n`;
}