/** * The demo church (WEBSITE-1.0-PLAN §11, "Demo church"): a fictional church, fictional people and * stock photos (models, not anyone from a church), loaded into a template for development, the * Hub's demo sites and the crosscode-site screenshots. `npm run demo -- --template bold`. * * 1.3.0: also the eight demo profiles (seeds.ts, `npm run demo -- --profile bold-plant`), which * keep the church's own profile (Accounts' organisation settings), the site settings, the site * icon and the admins, and name the church in the copy. A template alone (development, e2e) is * still Acacia Hill, profile and all, exactly as before. * * 1.8.0: a demo scenario (`--scenario`, APP-1.0-PLAN §12) loads a profile as part of the same * church in every product: the leaders are the scenario's people (`@crosscode/demo`), and with a * linked Cross Events the site shows Events' events through the feed instead of making its own. * * It replaces the Website's content (never the admins), so the script refuses on a site that has * been published unless told otherwise. */ import fs from 'node:fs'; import os from 'node:os'; import path from 'node:path'; import { fileURLToPath } from 'node:url'; import { CHURCH_SCHEMA, WEBSITE_TEMPLATES, type agent, type Church, type WebsiteTemplate } from '@crosscode/contracts'; import type { Ctx } from '../context.js'; import { churchProfile } from '../church/profile.js'; import { demoChurch, demoParts, demoPeople } from '@crosscode/demo'; import { markRemoved, notifyLinks, syncLink, type SyncResult } from '../feed/feed.js'; import type { SectionData } from '../site/sections.js'; import { publish } from '../site/snapshot.js'; import { TEMPLATE_HEADERS, TEMPLATE_VARIANTS, SECTION_TYPES, defaultDesign, type SiteDesign } from '../site/variants.js'; import { MAX_WIDTH, WIDTHS, processImage, type Sizes } from '../admin/media.js'; import { DEMO_SEEDS, type DemoPhotos, type DemoSeed, type ProfileSeed } from './seeds.js'; export const DEMO_COLOURS = { primary: '#1d5c63', accent: '#e0a458' }; export function demoProfile(publicUrl: string): Church { return { schema: CHURCH_SCHEMA, customerId: '00000000-0000-4000-8000-000000000001', updatedAt: '2026-11-25T08:00:00.000Z', name: 'Acacia Hill Church', shortName: 'Acacia Hill', timezone: 'Africa/Johannesburg', locale: 'en-ZA', branding: { logoUrl: null, iconUrl: null, colours: DEMO_COLOURS, style: { fontPairing: null, corners: null } }, campuses: [], serviceTimes: [ { day: 'sunday', time: '08:30', label: 'Early service', campus: null, note: null }, { day: 'sunday', time: '10:00', label: 'Family service', campus: null, note: 'Kids church during the service' }, { day: 'wednesday', time: '18:30', label: 'Midweek prayer', campus: null, note: null }, ], contact: { email: 'hello@acaciahill.example', phone: '+27125550123', whatsapp: '+27825550123', address: { line1: '12 Acacia Avenue', line2: null, suburb: 'Westridge', city: 'Pretoria', province: 'Gauteng', postalCode: '0181', country: 'ZA', geo: { lat: -25.7461, lng: 28.1881 } }, }, social: [ { network: 'facebook', url: 'https://www.facebook.com/acaciahill.example' }, { network: 'youtube', url: 'https://www.youtube.com/@acaciahill.example' }, ], links: { website: publicUrl, events: null, app: null, accounts: 'https://accounts.acaciahill.example' }, } as Church; } /** * 1.8.0: a scenario's church as a profile, for a scenario loaded on a site that has no profile at * all (Accounts normally has it first and the site reads it from there). */ export function scenarioProfile(publicUrl: string, scenario: agent.DemoScenarioKey): Church { const p = demoChurch(scenario).profile; const base = demoProfile(publicUrl); return { ...base, name: p.name, shortName: p.shortName, timezone: p.timezone, locale: p.locale, campuses: p.campuses, serviceTimes: p.serviceTimes, social: p.social, branding: { ...base.branding, colours: p.colours, style: p.style }, contact: { ...p.contact, phone: null, whatsapp: null }, links: { ...base.links, accounts: `https://example.com/accounts/${demoChurch(scenario).slug}` }, } as Church; } /** * 1.8.0: a profile's seed with the scenario's people as its leaders (`scenarioTeam`), the pastor * first, each with the portrait chosen for them. */ export function scenarioSeed(seed: ProfileSeed, scenario: agent.DemoScenarioKey): DemoSeed { const parts = demoParts(scenario); const leads = demoPeople(scenario).filter((p) => parts.has(p.email)); const team = seed.scenarioTeam.map(([part, role, photo]) => { const person = leads.find((p) => parts.get(p.email)!.includes(part)); if (!person) throw new Error(`The ${scenario} scenario has no one who is ${part}.`); return { name: person.name, role, photo }; }); return { ...seed, leaders: team.map((l) => [l.name, l.role]), photos: { ...seed.photos, pastor: team[0]!.photo, team: [team[1]!.photo, team[2]!.photo, team[3]!.photo] }, }; } /** Hills, a sun and a path in the church's colours (SVG): what stands in for a demo photo that is missing. */ export function illustration(seed: number, w = 1600, h = 1000, colours: { primary: string; accent: string } = DEMO_COLOURS): string { const hues = [colours.primary, colours.accent, '#7fb7be', '#f3e3c3', '#284b52']; const c = (i: number) => hues[(seed + i) % hues.length]; const y = (f: number) => Math.round(h * f); return ` `; } type Ids = Record; const HEX = /^#[0-9a-f]{6}$/i; export const defaultUploadDir = () => path.resolve(path.dirname(fileURLToPath(import.meta.url)), '..', '..', 'uploads'); /** * The demo's photos (Unsplash, free to use: credits in demo-photos/photos.json and CREDITS.md). * Stock photos of models standing in for the fictional churches' people and places. */ export const DEMO_PHOTO_DIR = path.resolve(path.dirname(fileURLToPath(import.meta.url)), '..', '..', 'demo-photos'); type DemoPhoto = { file: string; alt: string; width: number; height: number }; let photoList: Record | null = null; export function demoPhotos(): Record { if (!photoList) { try { photoList = JSON.parse(fs.readFileSync(path.join(DEMO_PHOTO_DIR, 'photos.json'), 'utf8')) as Record; } catch { photoList = {}; } } return photoList; } /** * One demo photo as a media asset, in the responsive sizes a real upload gets. The processed files * stay in `/demo/` (the demo replaces rows, not files), so a later demo reuses them. * Without the photo (a checkout without demo-photos/), the illustration stands in. */ async function demoAsset(ctx: Ctx, uploadDir: string, key: string, alt: string, fallbackSeed: number, colours: { primary: string; accent: string }): Promise { const photo = demoPhotos()[key]; const source = photo && path.join(DEMO_PHOTO_DIR, photo.file); if (!source || !fs.existsSync(source)) { const filename = `demo/${key}.svg`; const svg = illustration(fallbackSeed, 1600, 1000, colours); fs.writeFileSync(path.join(uploadDir, filename), svg); const row = await ctx.db.mediaAsset.create({ data: { filename, mime: 'image/svg+xml', bytes: Buffer.byteLength(svg), width: 1600, height: 1000, alt } }); return row.id; } const width = Math.min(photo.width, MAX_WIDTH); const height = Math.round((photo.height * width) / photo.width); const sizes: Sizes = WIDTHS.filter((w) => w < width).map((w) => ({ w, webp: `${key}-${w}.webp`, jpg: `${key}-${w}.jpg` })); const names = [`${key}.webp`, ...sizes.flatMap((s) => [s.webp, s.jpg])]; // Made once per machine (in the temp folder, by the photo's size, so a replaced photo is made // again) and copied: the e2e and the tests load the demo many times. const made = path.join(os.tmpdir(), 'crosscode-website-demo', `${key}-${fs.statSync(source).size}`); if (!names.every((f) => fs.existsSync(path.join(made, f)))) { // Made in a folder of its own and renamed into place, so a demo loading at the same time // never copies a half-written file. const making = `${made}.${process.pid}.${Math.random().toString(36).slice(2)}`; fs.mkdirSync(making, { recursive: true }); await processImage(fs.readFileSync(source), { ext: 'webp', mime: 'image/webp' }, path.join(making, key)); try { fs.renameSync(making, made); } catch { fs.rmSync(making, { recursive: true, force: true }); } } for (const f of names) { const to = path.join(uploadDir, 'demo', f); if (!fs.existsSync(to)) fs.copyFileSync(path.join(made, f), to); } const bytes = names.reduce((t, f) => t + fs.statSync(path.join(uploadDir, 'demo', f)).size, 0); const row = await ctx.db.mediaAsset.create({ data: { filename: `demo/${key}.webp`, mime: 'image/webp', bytes, width, height, alt, sizes: sizes as never } }); return row.id; } /** The demo's pictures by slot (hero, collage2, collage3, welcome, pastor, invite, and the four ministries). */ async function demoMedia(ctx: Ctx, uploadDir: string, photos: DemoPhotos, pastorName: string, team: string[], colours: { primary: string; accent: string }, withEvents: boolean): Promise { const slots: [string, string, string | null][] = [ ['hero', photos.hero, null], ['collage2', photos.collage[0], null], ['collage3', photos.collage[1], null], ['welcome', photos.welcome, null], ['pastor', photos.pastor, pastorName], ['invite', photos.invite, null], ...photos.ministries.map((p, i) => [`ministry${i}`, p, null] as [string, string, string | null]), ...photos.team.map((p, i) => [`team${i}`, p, team[i] ?? null] as [string, string, string | null]), ...photos.messages.map((p, i) => [`message${i}`, p, null] as [string, string, string | null]), ...(withEvents ? photos.events : []).map((p, i) => [`event${i}`, p, null] as [string, string, string | null]), ]; fs.mkdirSync(path.join(uploadDir, 'demo'), { recursive: true }); const ids: Ids = {}; const byPhoto = new Map(); let n = 0; for (const [slot, key, alt] of slots) { // A photo used twice (a profile may) is one asset; the pastor's always gets their name. const id = !alt && byPhoto.get(key) || await demoAsset(ctx, uploadDir, key, alt ?? demoPhotos()[key]?.alt ?? 'Illustration', n, colours); if (!alt) byPhoto.set(key, id); ids[slot] = id; n++; } return ids; } /** The development demo church (Acacia Hill), on any template: what a template alone loads. */ const CLASSIC: Omit & { pastorName: string; ctaText: string; descriptions: Record } = { id: 'classic', label: 'Acacia Hill (development)', alternate: false, hero: { headline: 'A home for everyone on the hill', subline: 'Sundays at 08:30 and 10:00 in Westridge, Pretoria. Come as you are.', button: { label: 'Plan your visit', href: '/visit' } }, serviceNote: 'Kids church runs during the 10:00 service. Parking on Acacia Avenue and behind the hall.', welcome: { heading: 'Welcome to Acacia Hill', mission: 'Loving God, loving our neighbours, from Westridge to the nations.', body: 'We are a family of ordinary people who have found good news in Jesus. Whether you have followed him for years or are just curious, there is a seat for you here, and coffee after the service.', quote: 'We would love to meet you. Come and say hello at the welcome table.', }, ministriesIntro: 'There is something for every age and stage.', teamIntro: null, invitation: { heading: 'We saved you a seat', text: 'New here? Let us know you are coming and we will meet you at the door.', button: { label: 'Plan your visit', href: '/visit' } }, visit: { expect: 'Services last about an hour and a quarter. We sing together, pray, and hear a message from the Bible. Dress is casual.', kids: 'Kids church (ages 3 to 12) runs during the 10:00 service. Sign your children in at the kids desk in the hall.', cta: 'Questions before you come?', }, ctaText: 'Send us a WhatsApp and we will get back to you.', about: { story: 'Acacia Hill began in 1998 as a Bible study in a lounge in Westridge. Today we are a church of all ages that meets in the old school hall on Acacia Avenue.', quote: 'Love one another. As I have loved you, so you must love one another.', by: 'John 13:34' }, give: 'Thank you for giving. You can give by EFT to Acacia Hill Church (demo details only: this is not a real account).', ministries: [ ['kids', 'Kids church', 'Ages 3 to 12, every Sunday at 10:00.'], ['youth', 'Youth', 'High schoolers, Friday nights at 18:30.'], ['worship', 'Worship', 'Musicians and sound, rehearsing on Thursdays.'], ['care', 'Care and prayer', 'Meals, visits and prayer for anyone who needs it.'], ], leaders: [['Thandi Mokoena', 'Lead pastor'], ['Pieter van Wyk', 'Associate pastor'], ['Lerato Dlamini', 'Kids and families'], ['Johan Botha', 'Worship']], pastorName: 'Pastor Thandi Mokoena', series: ['hope-for-today', 'Hope for today'], messages: [['hope-that-holds', 'A hope that holds', 3, 'Psalm 23'], ['bread-for-the-road', 'Bread for the road', 10, 'Psalm 23'], ['the-good-shepherd', 'The good shepherd', 17, 'Psalm 23']], events: [ ['family-picnic', 'Family picnic', 6, 'Bring a blanket and something to share. Games for the kids.'], ['carols-by-candlelight', 'Carols by candlelight', 20, 'Our Christmas carol service on the lawn.'], ['new-here-lunch', 'New here lunch', 34, 'Meet the pastors over lunch after the 10:00 service.'], ], venue: 'Acacia Hill Church', descriptions: { home: 'Acacia Hill Church in Westridge, Pretoria: Sundays at 08:30 and 10:00. Come as you are.', visit: 'What to expect on your first Sunday at Acacia Hill Church.', about: 'Our story, what we believe and what we value.', ministries: 'Kids, youth, worship, care and prayer at Acacia Hill.', leadership: 'The team who lead Acacia Hill Church.', events: 'What is coming up at Acacia Hill Church.', messages: 'Sunday messages from Acacia Hill Church.', give: 'How to give to Acacia Hill Church.', contact: 'Find Acacia Hill Church in Westridge, Pretoria.', }, photos: { hero: 'acacia-sunrise', collage: ['congregation-warm', 'coffee-friends'], welcome: 'welcome-hug', pastor: 'pastor-thandi', invite: 'church-light', ministries: ['kids-craft', 'youth-group', 'band-small', 'prayer-group'], team: ['team-pieter', 'team-lerato', 'team-johan'], messages: ['open-bible', 'mic-audience', 'pulpit'], events: ['friends-picnic', 'candles', 'meal-friends'] }, }; /** A demo profile's design: the template's defaults, or (alternate) its second recommendations and header. */ export function seedDesign(template: WebsiteTemplate, alternate: boolean): SiteDesign { const design = defaultDesign(template); if (!alternate) return design; const variants = Object.fromEntries(SECTION_TYPES.map((s) => { const options = TEMPLATE_VARIANTS[template][s] as readonly string[]; return [s, options[1] ?? options[0]!]; })) as SiteDesign['variants']; const headers = TEMPLATE_HEADERS[template] as readonly string[]; return { ...design, variants, style: { ...design.style, header: headers[1] ?? headers[0]! } }; } export const isDemoTemplate = (v: string): v is WebsiteTemplate => (WEBSITE_TEMPLATES as readonly string[]).includes(v); /** * Replaces the content with a demo, then publishes it. `what`: a template (the Acacia Hill church, * its profile saved too) or a demo profile (keeps the church's profile; Acacia Hill's is saved * only on a site that has none at all, so the site still has a name). * * `scenario` (1.8.0): part of loading that demo scenario, whose church the profile is (the same * name: the script refuses any other). The leaders are the scenario's people, and with a linked * Cross Events the site makes no events of its own: it shows Events' through the feed. */ export async function loadDemo(ctx: Ctx, what: WebsiteTemplate | agent.WebsiteDemoProfile, opts: { uploadDir?: string; publishedBy?: string; scenario?: agent.DemoScenarioKey } = {}) { const db = ctx.db; const uploadDir = opts.uploadDir ?? ctx.config.uploadDir ?? defaultUploadDir(); const classic = isDemoTemplate(what); const scenario = opts.scenario ?? null; if (scenario && scenario !== what) throw new Error(`The ${scenario} scenario loads the ${scenario} profile, not ${what}.`); const seed: DemoSeed = classic ? { ...CLASSIC, template: what } : scenario ? scenarioSeed(DEMO_SEEDS[what], scenario) : DEMO_SEEDS[what]; const extra = classic ? CLASSIC : null; // A scenario's events are Cross Events' when the church has it: shown through the feed, never copied. const eventsLink = scenario ? await db.productLink.findFirst({ where: { product: 'events' } }) : null; // The church: Acacia Hill for a template; else whoever the site belongs to (in a scenario, // Accounts has the scenario's church by now). let church = classic ? null : await churchProfile(ctx); if (!church) { church = scenario ? scenarioProfile(ctx.config.publicUrl, scenario) : demoProfile(ctx.config.publicUrl); await ctx.settings.set('church_profile_local', JSON.stringify(church)); } const name = church.name; const short = church.shortName || church.name; const city = church.contact?.address?.city || church.contact?.address?.suburb || 'town'; const t = (s: string) => s.replaceAll('{name}', name).replaceAll('{short}', short).replaceAll('{city}', city); const brand = church.branding?.colours; const colours = classic || !brand?.primary || !HEX.test(brand.primary) ? DEMO_COLOURS : { primary: brand.primary, accent: brand.accent && HEX.test(brand.accent) ? brand.accent : DEMO_COLOURS.accent }; // The site icon is a setting, so its picture stays; every other picture goes with the content. const faviconId = classic ? null : await ctx.settings.get('favicon_media_id'); // 1.6.1: the published events that go are listed in the feed's `deleted`, so linked products // (Cross Events) drop their copies instead of showing them beside the new ones. const gone = (await db.simpleEvent.findMany({ where: { publishedAt: { not: null } }, select: { id: true } })).map((e) => e.id); for (const id of gone) await markRemoved(ctx, id, true); for (const m of ['section', 'page', 'ministry', 'leader', 'message', 'messageSeries', 'simpleEvent', 'siteVersion', 'siteDesign', 'slugHistory', 'previewLink'] as const) { await (db[m] as unknown as { deleteMany: (a?: object) => Promise }).deleteMany({}); } await db.mediaAsset.deleteMany(faviconId ? { where: { NOT: { id: faviconId } } } : undefined); const [pastorName] = seed.leaders[0]!; const ministryNames = seed.ministries.map(([, n]) => t(n)); const speaker = extra?.pastorName ?? pastorName; const img = await demoMedia(ctx, uploadDir, seed.photos, speaker, seed.leaders.slice(1).map(([name]) => name), colours, !eventsLink); const design = classic ? defaultDesign(seed.template) : seedDesign(seed.template, seed.alternate); await db.siteDesign.create({ data: { id: 1, template: seed.template, variants: design.variants as never, home: design.home as never, style: design.style as never } }); const home: SectionData = { hero: { headline: t(seed.hero.headline), subline: t(seed.hero.subline), images: [img.hero!, img.collage2!, img.collage3!], videoId: null, button: seed.hero.button }, serviceTimes: { heading: 'Join us this Sunday', note: t(seed.serviceNote) }, welcome: { heading: t(seed.welcome.heading), mission: t(seed.welcome.mission), body: t(seed.welcome.body), imageId: img.welcome!, pastor: { name: speaker, role: seed.leaders[0]![1], quote: t(seed.welcome.quote), photoId: img.pastor! }, }, ministries: { heading: 'Find your place', intro: t(seed.ministriesIntro) }, team: { heading: 'Our team', intro: seed.teamIntro ? t(seed.teamIntro) : null }, events: { heading: 'Coming up', count: 3 }, latestMessage: { heading: 'Latest message' }, invitation: { heading: t(seed.invitation.heading), text: t(seed.invitation.text), button: seed.invitation.button, imageId: img.invite! }, }; const d = (kind: string, fallback: string) => extra?.descriptions[kind] ?? t(fallback); const pages: { kind: string; slug: string; title: string; position: number; description: string; sections: { type: string; variant?: string; data: unknown }[] }[] = [ { kind: 'home', slug: 'home', title: 'Home', position: 0, description: d('home', `${seed.hero.subline}`), sections: Object.entries(home).map(([type, data]) => ({ type, data })) }, { kind: 'visit', slug: 'visit', title: 'Plan your visit', position: 1, description: d('visit', 'What to expect on your first Sunday at {name}.'), sections: [ { type: 'text', data: { heading: 'What to expect', body: t(seed.visit.expect) } }, { type: 'image-text', variant: 'image-text', data: { heading: 'Bringing children', body: t(seed.visit.kids), imageId: img.ministry0, button: null } }, { type: 'cta', data: { heading: t(seed.visit.cta), text: extra?.ctaText ?? 'Send us a message and we will get back to you.', button: { label: 'Contact us', href: '/contact' } } }, ], }, { kind: 'about', slug: 'about', title: 'About us', position: 2, description: d('about', 'Our story, what we believe and what we value.'), sections: [ { type: 'text', data: { heading: 'Our story', body: t(seed.about.story) } }, { type: 'quote', data: { quote: seed.about.quote, by: seed.about.by } }, ], }, { kind: 'ministries', slug: 'ministries', title: 'Ministries', position: 3, description: d('ministries', `${ministryNames.join(', ')} at {short}.`), sections: [] }, { kind: 'leadership', slug: 'leadership', title: 'Leadership', position: 4, description: d('leadership', 'The team who lead {name}.'), sections: [] }, { kind: 'events', slug: 'events', title: 'Events', position: 5, description: d('events', 'What is coming up at {name}.'), sections: [] }, { kind: 'messages', slug: 'messages', title: 'Messages', position: 6, description: d('messages', 'Sunday messages from {name}.'), sections: [] }, { kind: 'give', slug: 'give', title: 'Give', position: 7, description: d('give', 'How to give to {name}.'), sections: [ { type: 'text', data: { heading: 'Giving', body: t(seed.give) } }, ], }, { kind: 'contact', slug: 'contact', title: 'Contact', position: 8, description: d('contact', 'Find {name} in {city}.'), sections: [] }, ]; for (const p of pages) { const page = await db.page.create({ data: { kind: p.kind as never, slug: p.slug, title: p.title, position: p.position, description: p.description } }); let i = 0; for (const s of p.sections) await db.section.create({ data: { pageId: page.id, type: s.type, variant: s.variant ?? null, position: i++, data: s.data as never } }); } let n = 0; for (const [slug, , summary] of seed.ministries) await db.ministry.create({ data: { slug, name: ministryNames[n]!, summary: t(summary), imageId: img[`ministry${n}`]!, position: n++ } }); n = 0; for (const [leader, role] of seed.leaders) await db.leader.create({ data: { name: leader, role, photoId: n === 0 ? img.pastor! : img[`team${n - 1}`] ?? null, position: n++ } }); const now = ctx.now(); const day = 864e5; const series = await db.messageSeries.create({ data: { slug: seed.series[0], title: seed.series[1] } }); // Each message shows a photo (its video is a stand-in), at the 960 px size a card needs. n = 0; for (const [slug, title, ago, passage] of seed.messages) { const photo = await db.mediaAsset.findUnique({ where: { id: img[`message${n++}`]! } }); const sizes = (photo?.sizes ?? []) as Sizes; const file = sizes.find((s) => s.w === 960)?.webp; const thumbnailUrl = photo ? `/api/uploads/${file ? `demo/${file}` : photo.filename}` : null; await db.message.create({ data: { slug, title, date: new Date(now.getTime() - ago * day), source: 'youtube', mediaUrl: 'https://www.youtube.com/watch?v=aqz-KE-bpKQ', thumbnailUrl, speaker, passage, seriesId: series.id, publishedAt: now } }); } n = 0; const made: string[] = []; for (const [slug, title, inDays, description] of eventsLink ? [] : seed.events) { const startsAt = new Date(Math.floor((now.getTime() + inDays * day) / day) * day + 8 * 3600e3); made.push((await db.simpleEvent.create({ data: { slug, title, startsAt, endsAt: new Date(startsAt.getTime() + 3 * 3600e3), location: t(seed.venue), description: t(description), imageId: img[`event${n++}`] ?? null, publishedAt: now } })).id); } const version = await publish(ctx, { id: opts.publishedBy ?? 'demo', role: 'system' }, classic ? `Demo church on ${seed.template}` : `Demo: ${seed.label}`); // Linked products fetch the feed now, not at their next poll (one try; the poll catches up). await notifyLinks(ctx, [...gone, ...made]).catch(() => {}); let eventsSync: SyncResult | null = null; if (eventsLink) { // Show Events' events (the scenario loaded them just before), the whole list at once. const link = await db.productLink.update({ where: { installId: eventsLink.installId }, data: { showEvents: true } }); eventsSync = await syncLink(ctx, link, { full: true }); } return { ...version, eventsSync }; }