/** * 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 * * 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 = {}) { 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 { 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; 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 '); process.exit(2); } exportSite(JSON.parse(readFileSync(bundlePath, 'utf8')) as Bundle, resolve(out)); console.log(`exported to ${resolve(out)} — pnpm install && pnpm run build`); }