Files
sites/scripts/import-theme.ts
CatoandClaude Opus 5.5 7317d154aa feat: contact forms — the first block with a server half, in the engine and in exports (#2)
* feat: import a sitekit repo, export a site as its own repo, compare any two renders

loki ADR-0001 build steps 4, 8 and 9 (tooling half).

- scripts/import-repo.ts + import-theme.ts: read a sitekit consumer's content
  module and globals.css into spec + theme + settings. Text tokens below
  WCAG AA move to the nearest passing shade, each change reported (camille:
  fg-muted 3.15→4.53:1, accent 3.94→4.54:1, nothing else).
- scripts/export-site.ts + export/template: a site bundle becomes a static
  Next repo with the exact sitekit the engine pins, the engine's own
  stylesheet and font copier (copied, one source), one git commit per
  version, and its own verify. Refuses a bundle it could not render, and
  never writes over a directory.
- scripts/compare-renders.mjs: render pages from two bases at 390/834/1440
  (with --map to fetch a real host from a local port) and exit 1 on any
  difference a visitor would notice.

Measured 2026-11-20: live camille repo vs the engine serving its imported
row, and the engine vs camille's export built to static files — no
differences on any page at any width.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* feat: a site's free address answers 308 to its verified own domain

The apex before www, path kept, method and body kept (308, as apps do).
Checked locally: camille.orangecat.ch/catering → 308 https://camille.example/catering
once the domain is verified, both hosts serve, the ask approves the domain,
and removing the row restores the free address.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* feat: contact forms — the first block with a server half, in the engine and in exports

loki ADR-0001 build step 11, block 1. sitekit's new `form` section posts to
/_sites/forms:

- src/lib/forms.ts (shared by the engine and every export): only a form that
  exists on the named page is read, only its own fields, length-capped; a
  filled honeypot answers "sent" and is dropped; the owner's mail is plain
  text with reply-to the visitor; problems are worded in the site's language.
- The engine route resolves the site by Host, never sends from the preview
  host, rate-limits five per visitor per site per ten minutes keyed on the
  LAST X-Forwarded-For hop (a forged first hop is still limited), mails
  settings.formTo through @bitbaum/mail-kit, and answers 303 with a RELATIVE
  Location (an absolute one built from req.url sent visitors to the loopback
  origin — caught locally, guarded by a test).
- Export: a site with a form becomes a small standalone server with the same
  forms.ts and route, mailing through the owner's own provider; a site
  without one stays static files.

Checked locally against camille with a form: every outcome (missing, bad
email, unknown form, honeypot, delivery failure without a mail key, sixth
message busy, forged first hop busy, preview never sends), the page notices,
390px layout (no sideways scroll, 44px button, honeypot off-screen), and
compare-renders engine vs export (server variant and static variant): no
differences.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* feat: booking requests through the same form route; pin sitekit with map, gallery and card actions

forms.ts checks date (YYYY-MM-DD), time (HH:MM) and people (1–50), words the
problems in the site's language, and puts them in the owner's mail. sitekit
is pinned to the kits commit that adds the gallery, map and card-action
blocks, so the engine renders them.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* chore: pin sitekit with the map control fix

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

---------

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-20 15:42:57 +01:00

212 lines
7.3 KiB
TypeScript

/**
* Read a sitekit consumer's `globals.css` (+ its generated `fonts.ts`) into a
* SiteTheme. Pure; `scripts/import-repo.ts` is the command around it.
*
* Only the light `@theme` block is read (the first one); a site with a dark
* scheme gets its `.dark`/media block read as `darkPalette` when present.
* Colours may be literal hex or `var(--primitive-…)` references to hex.
*
* Text tokens below WCAG AA are moved to the nearest shade that passes,
* because sitekit's theme schema refuses them: darker on a light page,
* lighter on a dark one. Every move is returned so it can be reported.
*/
import {
AA_TEXT,
contrastRatio,
siteThemeSchema,
SITE_FACES,
type SiteFace,
type SitePalette,
type SiteTheme,
} from '@bitbaum/sitekit';
export type ThemeChange = {
token: keyof SitePalette;
from: string;
to: string;
before: number;
after: number;
against: string;
};
const TOKENS: Record<keyof SitePalette, string> = {
surfacePage: 'color-surface-page',
surfaceRaised: 'color-surface-raised',
fgPrimary: 'color-fg-primary',
fgSecondary: 'color-fg-secondary',
fgTertiary: 'color-fg-tertiary',
fgMuted: 'color-fg-muted',
borderSubtle: 'color-border-subtle',
borderStrong: 'color-border-strong',
accent: 'color-accent',
statusPositive: 'color-status-positive',
statusWarning: 'color-status-warning',
statusNegative: 'color-status-negative',
};
/** Every `--name: value;` in a block of CSS, last one wins. */
export function declarations(css: string): Map<string, string> {
const out = new Map<string, string>();
for (const m of css.matchAll(/--([a-z0-9-]+)\s*:\s*([^;]+);/gi)) out.set(m[1]!, m[2]!.trim());
return out;
}
/** The body of the first `@theme { … }` block. */
export function themeBlock(css: string): string | null {
const start = css.search(/@theme\s*\{/);
if (start < 0) return null;
let depth = 0;
for (let i = css.indexOf('{', start); i < css.length; i++) {
if (css[i] === '{') depth++;
else if (css[i] === '}' && --depth === 0) return css.slice(css.indexOf('{', start) + 1, i);
}
return null;
}
function resolveColor(
value: string | undefined,
vars: Map<string, string>,
depth = 0,
): string | null {
if (!value || depth > 5) return null;
const v = value.trim();
if (/^#[0-9a-f]{6}$/i.test(v)) return v.toLowerCase();
if (/^#[0-9a-f]{3}$/i.test(v))
return ('#' + [...v.slice(1)].map((c) => c + c).join('')).toLowerCase();
const ref = /^var\(--([a-z0-9-]+)\)$/i.exec(v);
return ref ? resolveColor(vars.get(ref[1]!), vars, depth + 1) : null;
}
function hexToRgb(h: string): [number, number, number] {
return [1, 3, 5].map((i) => parseInt(h.slice(i, i + 2), 16)) as [number, number, number];
}
function rgbToHex(rgb: number[]): string {
return (
'#' +
rgb
.map((c) =>
Math.round(Math.max(0, Math.min(255, c)))
.toString(16)
.padStart(2, '0'),
)
.join('')
);
}
/**
* The closest colour to `color`, mixed toward black (or white), whose
* contrast against every background is at least `min`. Mixing in small steps
* keeps the hue; the first step that passes is the smallest change.
*/
export function nearestPassing(color: string, backgrounds: string[], min = AA_TEXT): string {
const ok = (c: string) => backgrounds.every((b) => contrastRatio(c, b) >= min);
if (ok(color)) return color;
const rgb = hexToRgb(color);
const lightBg = backgrounds.every(
(b) => contrastRatio(b, '#000000') > contrastRatio(b, '#ffffff'),
);
const target = lightBg ? 0 : 255;
for (let t = 0.01; t <= 1; t += 0.01) {
const c = rgbToHex(rgb.map((x) => x + (target - x) * t));
if (ok(c)) return c;
}
return lightBg ? '#000000' : '#ffffff';
}
/** Move every text token (and the accent behind a button label) to AA. */
export function fixPalette(p: SitePalette): { palette: SitePalette; changes: ThemeChange[] } {
const palette = { ...p };
const changes: ThemeChange[] = [];
const surfaces = [palette.surfacePage, palette.surfaceRaised];
for (const token of ['fgPrimary', 'fgSecondary', 'fgTertiary', 'fgMuted'] as const) {
const from = palette[token];
const to = nearestPassing(from, surfaces);
if (to !== from) {
const worst = (c: string) => Math.min(...surfaces.map((s) => contrastRatio(c, s)));
changes.push({
token,
from,
to,
before: worst(from),
after: worst(to),
against: 'page and raised surfaces',
});
palette[token] = to;
}
}
// The filled button's label is the page colour, so the accent moves, away from the page.
const from = palette.accent;
const to = nearestPassing(from, [palette.surfacePage]);
if (to !== from) {
changes.push({
token: 'accent',
from,
to,
before: contrastRatio(from, palette.surfacePage),
after: contrastRatio(to, palette.surfacePage),
against: 'the button label (page colour)',
});
palette.accent = to;
}
return { palette, changes };
}
/** `display=cormorant-garamond;…` and `body=dm-sans;…` from design-tokens' generated fonts.ts. */
export function facesFromFontsTs(fontsTs: string): { display?: string; body?: string } {
return {
display: /'display=([a-z0-9-]+)/.exec(fontsTs)?.[1],
body: /'body=([a-z0-9-]+)/.exec(fontsTs)?.[1],
};
}
function faceFor(stack: string | undefined, generated: string | undefined): SiteFace {
if (stack && /var\(--font-(display|body)\)/.test(stack) && generated && generated in SITE_FACES) {
return generated as SiteFace;
}
const s = (stack ?? '').toLowerCase();
for (const [id, css] of Object.entries(SITE_FACES)) {
const family = /'([^']+)'/.exec(css)?.[1]?.toLowerCase();
if (family && s.includes(family)) return id as SiteFace;
}
if (s.includes('georgia') || (s.includes('serif') && !s.includes('sans'))) return 'system-serif';
return 'system-sans';
}
export type ImportedTheme =
{ ok: true; theme: SiteTheme; changes: ThemeChange[] } | { ok: false; reason: string };
export function importTheme(css: string, fontsTs = ''): ImportedTheme {
const block = themeBlock(css);
if (!block) return { ok: false, reason: 'no @theme block in globals.css' };
const vars = declarations(block);
const raw = {} as SitePalette;
for (const [key, name] of Object.entries(TOKENS) as [keyof SitePalette, string][]) {
const color = resolveColor(vars.get(name), vars);
if (!color) return { ok: false, reason: `--${name} is missing or not a hex colour` };
raw[key] = color;
}
const { palette, changes } = fixPalette(raw);
const faces = facesFromFontsTs(fontsTs);
const shell = /^(\d+)rem$/.exec(vars.get('spacing-shell') ?? '')?.[1];
const candidate = {
palette,
type: {
heading: faceFor(vars.get('font-heading'), faces.display),
body: faceFor(vars.get('font-sans'), faces.body),
...(vars.get('tracking-display') ? { trackingDisplay: vars.get('tracking-display') } : {}),
...(vars.get('tracking-caps') ? { trackingCaps: vars.get('tracking-caps') } : {}),
},
...(shell ? { shellRem: Math.min(96, Math.max(48, Number(shell))) } : {}),
};
const parsed = siteThemeSchema.safeParse(candidate);
if (!parsed.success) {
return {
ok: false,
reason: parsed.error.issues.map((i) => `${i.path.join('.')}: ${i.message}`).join('; '),
};
}
return { ok: true, theme: parsed.data, changes };
}