For the crosscode-site screenshots of another church on each template. Test helper only, no Website release. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
105 lines
5.9 KiB
TypeScript
105 lines
5.9 KiB
TypeScript
/**
|
|
* The e2e backend (playwright.config.ts): the Website's backend on port 5310 with the in-memory
|
|
* database from the backend tests (no Postgres needed), or a real Postgres with E2E_DATABASE_URL
|
|
* (freshPostgres, below), and the demo church published. The pages run as a production build on
|
|
* 3310 and send /api here.
|
|
*
|
|
* Test helpers: POST /test/demo?template=<id> loads the demo church on that template (or
|
|
* ?profile=<id>, a demo profile);
|
|
* POST /test/design { variants?, style?, home? } changes the design and publishes again.
|
|
*/
|
|
import { execSync } from 'node:child_process';
|
|
import fs from 'node:fs';
|
|
import path from 'node:path';
|
|
import { fileURLToPath } from 'node:url';
|
|
import express from 'express';
|
|
import pg from 'pg';
|
|
import sharp from 'sharp';
|
|
import { PrismaPg } from '@prisma/adapter-pg';
|
|
import { agent, websiteTemplateSchema } from '@crosscode/contracts';
|
|
import { PrismaClient } from '../backend/src/generated/prisma/client.js';
|
|
import { createApp } from '../backend/src/app.js';
|
|
import { createCtx } from '../backend/src/context.js';
|
|
import { DEMO_PHOTO_DIR, loadDemo } from '../backend/src/demo/demoChurch.js';
|
|
import { loadConfig } from '../backend/src/lib/config.js';
|
|
import { hashToken } from '../backend/src/lib/crypto.js';
|
|
import { publish } from '../backend/src/site/snapshot.js';
|
|
import { memoryDb } from '../backend/tests/support/memoryDb.js';
|
|
|
|
const { Client } = pg;
|
|
const here = path.dirname(fileURLToPath(import.meta.url));
|
|
const uploads = path.join(here, '.uploads');
|
|
fs.mkdirSync(uploads, { recursive: true });
|
|
|
|
const db = process.env.E2E_DATABASE_URL ? await freshPostgres(process.env.E2E_DATABASE_URL) : memoryDb();
|
|
|
|
/**
|
|
* The real-Postgres run (WEBSITE-1.0-PLAN §13): `E2E_DATABASE_URL=postgresql://…/ccw_website_e2e npx
|
|
* playwright test`. The database is dropped and made again, the migrations applied with `prisma
|
|
* migrate deploy` (as `crosscode deploy` does), and the same suite runs on it. The name must end in
|
|
* `_e2e`, so a real site's database is never dropped.
|
|
*/
|
|
async function freshPostgres(url: string) {
|
|
const target = new URL(url);
|
|
const name = target.pathname.slice(1);
|
|
if (!/^[a-z0-9_]+_e2e$/.test(name)) throw new Error(`E2E_DATABASE_URL must name a database ending in _e2e (got "${name}").`);
|
|
const admin = new URL(url);
|
|
admin.pathname = '/postgres';
|
|
const pg = new Client({ connectionString: admin.toString() });
|
|
await pg.connect();
|
|
await pg.query(`DROP DATABASE IF EXISTS ${name} WITH (FORCE)`);
|
|
await pg.query(`CREATE DATABASE ${name}`);
|
|
await pg.end();
|
|
execSync('npx prisma migrate deploy', { cwd: path.join(here, '../backend'), env: { ...process.env, DATABASE_URL: url }, stdio: 'inherit' });
|
|
console.log(`[e2e] On Postgres: ${name}, migrations applied.`);
|
|
return new PrismaClient({ adapter: new PrismaPg({ connectionString: url }) });
|
|
}
|
|
// A frozen clock (a Monday morning), so the demo's dates, and so the screenshots, are the same every
|
|
// run (variants.spec.ts). E2E_NOW changes it.
|
|
const frozen = new Date(process.env.E2E_NOW ?? '2026-11-23T06:00:00Z');
|
|
// YouTube's thumbnails (site/thumbnails.ts) without the network: one of the demo's photos, as a
|
|
// JPEG the size of YouTube's, for every video.
|
|
const thumb = await sharp(path.join(DEMO_PHOTO_DIR, 'congregation-warm.webp')).resize(480, 360, { fit: 'cover' }).jpeg().toBuffer();
|
|
const fakeYoutube = async (url: string) => url.startsWith('https://i.ytimg.com/')
|
|
? new Response(new Uint8Array(thumb), { headers: { 'content-type': 'image/jpeg' } })
|
|
: new Response('not here', { status: 404 });
|
|
const ctx = createCtx(loadConfig({ WEBSITE_URL: 'http://localhost:3310', NODE_ENV: 'test', JOBS_ENABLED: 'false', HUB_URL: 'http://127.0.0.1:1', UPLOAD_DIR: uploads, TRUST_PROXY: 'true' }), db as never, { now: () => new Date(frozen), fetch: fakeYoutube });
|
|
await loadDemo(ctx, websiteTemplateSchema.parse(process.env.DEMO_TEMPLATE ?? 'heritage'), { uploadDir: uploads });
|
|
|
|
const app = express();
|
|
app.post('/test/demo', async (req, res) => {
|
|
// ?profile=<id>: one of the demo profiles (the crosscode-site screenshots of another church on
|
|
// a template); it keeps the church profile the template demo saved (Acacia Hill).
|
|
const profile = String(req.query.profile ?? '');
|
|
if (profile) {
|
|
if (!(agent.WEBSITE_DEMO_PROFILES as readonly string[]).includes(profile)) return res.status(400).json({ error: 'profile' });
|
|
await loadDemo(ctx, profile as agent.WebsiteDemoProfile, { uploadDir: uploads });
|
|
return res.json({ ok: true, profile });
|
|
}
|
|
const t = websiteTemplateSchema.safeParse(req.query.template);
|
|
if (!t.success) return res.status(400).json({ error: 'template' });
|
|
await loadDemo(ctx, t.data, { uploadDir: uploads });
|
|
return res.json({ ok: true, template: t.data });
|
|
});
|
|
app.post('/test/design', express.json(), async (req, res) => {
|
|
const d = (await db.siteDesign.findUnique({ where: { id: 1 } })) as { variants: object; style: object; home: unknown };
|
|
await db.siteDesign.update({ where: { id: 1 }, data: {
|
|
variants: { ...d.variants, ...(req.body.variants ?? {}) },
|
|
style: { ...d.style, ...(req.body.style ?? {}) },
|
|
home: req.body.home ?? d.home,
|
|
} });
|
|
const v = await publish(ctx, { id: 'e2e', role: 'system' });
|
|
res.json({ ok: true, version: v.number });
|
|
});
|
|
// A signed-in admin without Accounts: the role's user and a session; the spec sets the cookie.
|
|
app.post('/test/session', async (req, res) => {
|
|
const role = String(req.query.role ?? 'editor');
|
|
const id = `00000000-0000-4000-8000-${String(Math.floor(Math.random() * 1e12)).padStart(12, '0')}`;
|
|
const token = `e2e-${id}`;
|
|
await db.websiteUser.create({ data: { id, name: `Test ${role}`, email: `${id}@hope.test`, role: role as never } });
|
|
await db.session.create({ data: { tokenHash: hashToken(token), userId: id, expiresAt: new Date(Date.now() + 864e5) } });
|
|
res.json({ cookie: { name: 'ccw_session', value: token } });
|
|
});
|
|
app.use(createApp(ctx));
|
|
app.listen(5310, '127.0.0.1', () => console.log('[e2e] Website backend on 5310 with the demo church.'));
|