Files
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

186 lines
6.9 KiB
TypeScript

/**
* Export a data site as its own repository that renders identically
* (loki ADR-0001 D7). The one hard step on the customer path, so it is a
* command from day one, not a promise.
*
* pnpm exec tsx scripts/export-site.ts <bundle.json> <out dir>
*
* A bundle is what Loki hands over for one site:
* { slug, noindex, publishedN, versions: [{ n, spec, theme, settings, note, createdAt }] }
*
* What makes "identical" true by construction rather than by care: the export
* renders the same `SiteDocument` from the same sitekit (pinned exactly as
* this engine pins it), with this engine's own stylesheet and font copier,
* copied in rather than rewritten. What makes it checkable: `scripts/
* compare-renders.mjs` renders both and must find nothing different.
*
* What does not leave: the Loki widget, access codes, anything of OrangeCat.
*/
import { execFileSync } from 'node:child_process';
import { cpSync, existsSync, mkdirSync, readFileSync, writeFileSync } from 'node:fs';
import { dirname, join, resolve } from 'node:path';
import { fileURLToPath } from 'node:url';
import { siteSettingsSchema, siteSpecSchema, siteThemeSchema } from '@bitbaum/sitekit';
const ROOT = resolve(dirname(fileURLToPath(import.meta.url)), '..');
const TEMPLATE = join(ROOT, 'export', 'template');
/** Laid over the template when the site has a form: a server route and config. */
const TEMPLATE_FORMS = join(ROOT, 'export', 'template-forms');
type Version = {
n: number;
spec: unknown;
theme: unknown;
settings: unknown;
note?: string | null;
createdAt: string;
};
export type Bundle = { slug: string; noindex: boolean; publishedN: number; versions: Version[] };
/** Files the export shares with the engine — copied, so there is one source. */
const SHARED: Array<[string, string]> = [
['src/app/globals.css', 'src/app/globals.css'],
['src/lib/fonts.ts', 'src/fonts.ts'],
['src/lib/forms.ts', 'src/lib/forms.ts'],
['scripts/copy-fonts.mjs', 'scripts/copy-fonts.mjs'],
['postcss.config.mjs', 'postcss.config.mjs'],
['next-env.d.ts', 'next-env.d.ts'],
['pnpm-workspace.yaml', 'pnpm-workspace.yaml'],
['.nvmrc', '.nvmrc'],
];
function git(dir: string, args: string[], env: Record<string, string> = {}) {
execFileSync('git', ['-C', dir, ...args], {
stdio: 'pipe',
env: {
...process.env,
...env,
GIT_DIR: undefined,
GIT_WORK_TREE: undefined,
} as NodeJS.ProcessEnv,
});
}
function fill(text: string, vars: Record<string, string>): string {
return text.replace(/\{\{([A-Z_]+)\}\}/g, (_, k: string) => {
if (!(k in vars)) throw new Error(`template variable ${k} has no value`);
return vars[k]!;
});
}
export function checkBundle(b: Bundle): string[] {
const errors: string[] = [];
if (!/^[a-z0-9]([a-z0-9-]{0,61}[a-z0-9])?$/.test(b.slug)) errors.push('slug');
if (!b.versions.length) errors.push('no versions');
if (!b.versions.some((v) => v.n === b.publishedN)) errors.push(`no version ${b.publishedN}`);
for (const v of b.versions) {
if (!siteSpecSchema.safeParse(v.spec).success) errors.push(`version ${v.n}: spec`);
if (v.theme != null && !siteThemeSchema.safeParse(v.theme).success)
errors.push(`version ${v.n}: theme`);
if (!siteSettingsSchema.safeParse(v.settings ?? {}).success)
errors.push(`version ${v.n}: settings`);
}
return errors;
}
export function exportSite(bundle: Bundle, out: string): void {
const errors = checkBundle(bundle);
if (errors.length) throw new Error(`bundle refused: ${errors.join(', ')}`);
if (existsSync(out)) throw new Error(`${out} exists — export into a new directory`);
const engine = JSON.parse(readFileSync(join(ROOT, 'package.json'), 'utf8'));
const deps = engine.dependencies as Record<string, string>;
const versions = [...bundle.versions].sort((a, b) => a.n - b.n);
const published = versions.find((v) => v.n === bundle.publishedN)!;
const name = siteSpecSchema.parse(published.spec).chrome.name;
const vars = {
NAME: name,
SLUG: bundle.slug,
SITEKIT: deps['@bitbaum/sitekit']!,
DESIGN_TOKENS: deps['@bitbaum/design-tokens']!,
NEXT: deps.next!,
REACT: deps.react!,
MAILKIT: deps['@bitbaum/mail-kit']!,
LIMITKIT: deps.limitkit!,
};
const hasForms = siteSpecSchema
.parse(published.spec)
.pages.some((p) => p.sections.some((s) => s.kind === 'form'));
mkdirSync(out, { recursive: true });
cpSync(TEMPLATE, out, { recursive: true });
if (hasForms) cpSync(TEMPLATE_FORMS, out, { recursive: true });
for (const f of ['README.md', 'package.json']) {
writeFileSync(join(out, f), fill(readFileSync(join(out, f), 'utf8'), vars));
}
cpSync(join(out, 'gitignore.txt'), join(out, '.gitignore'));
execFileSync('rm', [join(out, 'gitignore.txt')]);
for (const [from, to] of SHARED) {
mkdirSync(dirname(join(out, to)), { recursive: true });
cpSync(join(ROOT, from), join(out, to));
}
writeFileSync(
join(out, 'src', 'forms-enabled.ts'),
`/** Whether this site has a form (and so is served by a small server rather than static files). */\nexport const FORMS = ${hasForms};\n`,
);
mkdirSync(join(out, 'site', 'versions'), { recursive: true });
// History: one commit per version, dated when it was made, so the site's
// history leaves with it. The last commit leaves the published one current.
git(out, ['init', '-q', '-b', 'main']);
const current = (v: Version) => ({
spec: v.spec,
theme: v.theme ?? null,
settings: v.settings ?? {},
noindex: bundle.noindex,
});
const write = (v: Version) => {
writeFileSync(
join(out, 'site', 'versions', `${v.n}.json`),
JSON.stringify(current(v), null, 2) + '\n',
);
writeFileSync(join(out, 'site', 'current.json'), JSON.stringify(current(v), null, 2) + '\n');
};
const commit = (message: string, when: string) => {
git(out, ['add', '-A']);
git(
out,
[
'-c',
'user.name=bitbaum sites',
'-c',
'user.email=sites@orangecat.ch',
'commit',
'-q',
'-m',
message,
],
{
GIT_AUTHOR_DATE: when,
GIT_COMMITTER_DATE: when,
},
);
};
for (const v of versions) {
write(v);
commit(`site: version ${v.n}${v.note ? ` — ${v.note}` : ''}`, v.createdAt);
}
if (versions[versions.length - 1]!.n !== published.n) {
writeFileSync(
join(out, 'site', 'current.json'),
JSON.stringify(current(published), null, 2) + '\n',
);
commit(`site: version ${published.n} is the published one`, new Date().toISOString());
}
}
if (process.argv[1] && resolve(process.argv[1]) === fileURLToPath(import.meta.url)) {
const [bundlePath, out] = process.argv.slice(2);
if (!bundlePath || !out) {
console.error('usage: export-site.ts <bundle.json> <out dir>');
process.exit(2);
}
exportSite(JSON.parse(readFileSync(bundlePath, 'utf8')) as Bundle, resolve(out));
console.log(`exported to ${resolve(out)} — pnpm install && pnpm run build`);
}