Compare commits

..
Author SHA1 Message Date
joshua 79121bc447 Merge branch 'feat/website-skeleton' 2026-11-25 08:41:11 +02:00
joshuaandClaude Opus 5.5 36ceb358b8 feat(website): apps/website skeleton
Backend (Express + Prisma, ES modules, as Accounts): /api/health and
/api/v1/site/status (Coming soon until the first publish), the content
model and its first migration, and the confirmed section variants per
template (WEBSITE-1.0-PLAN §3, decision 16) with the template switch
rules, with tests. Frontend (Next.js 16): Coming soon page, admin
placeholder, robots.txt. env.template.json, PM2 example, CHANGELOG and
WHATS-NEW. Root workspaces and lint updated.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-25 08:41:11 +02:00
joshua a3a158faa8 Merge branch 'docs/website-section-variants' 2026-11-25 08:13:22 +02:00
45 changed files with 1617 additions and 12 deletions
+2
View File
@@ -0,0 +1,2 @@
# this install's PM2 config (made from ecosystem.config.example.cjs by the crosscode script)
/ecosystem.config.cjs
+10
View File
@@ -0,0 +1,10 @@
# Changelog — Church Website
## [Unreleased]
### Added
- The app's skeleton (WEBSITE-1.0-PLAN §1): an Express + Prisma backend with `/api/health` and
`/api/v1/site/status` (Coming soon until the first publish), the content model and its first
migration, the section variants per template (§3, decision 16) with the template switch rules, and
a Next.js frontend with the Coming soon page, an admin placeholder and `robots.txt`.
+18 -1
View File
@@ -1,3 +1,20 @@
# Church Website
Placeholder: the church's public website and its admin. Built in phase 5 of ROADMAP-v3 (see §6 there).
The church's public website and its admin (ROADMAP-v3 §6, phase 5; plan and decisions in
[docs/WEBSITE-1.0-PLAN.md](../../docs/WEBSITE-1.0-PLAN.md)). Served at `www.<church's address>` (or
`<church>.crosscode.co.za`), with the admin at `/admin`, signed in through the church's Accounts.
The church picks one of four templates (Heritage, Bold, Community, Clean) and makes it its own with
section variants and style settings. Changes are drafts until an editor previews the whole site and
presses Publish; until the first publish visitors see Coming soon.
**State:** skeleton (2026-11-25). Not released; `website@1.0.0` is tagged when the plan is built.
- `backend/`: Express + Prisma (ES modules), as Accounts. `npm run dev`, `npm test` (Node's test
runner through tsx), `npm run build`. The content model is in `prisma/schema.prisma`; the section
variants per template (plan §3, decision 16) in `src/site/variants.ts`.
- `frontend/`: Next.js 16. The public site (server-rendered from the latest published version) and
the admin.
Local development: Postgres in `backend/.env` (`DATABASE_URL`, `WEBSITE_URL=http://localhost:3300`),
`npx prisma migrate deploy`, then `npm run dev` in both folders (the frontend runs on 3300 and sends
/api to the backend on 5300).
+4
View File
@@ -0,0 +1,4 @@
# What's new in the Church Website
What each version changes for the church, in plain language (read by the Hub like Cross Events'
WHATS-NEW.md; a section shows once its version is tagged).
+7
View File
@@ -0,0 +1,7 @@
node_modules/
dist/
src/generated/
.env
uploads/
exports/
/backups/
+39
View File
@@ -0,0 +1,39 @@
{
"name": "@crosscode/website-backend",
"version": "0.1.0",
"description": "Church Website: the public site's content API, the admin API, publishing and uploads",
"private": true,
"type": "module",
"main": "dist/index.js",
"scripts": {
"start": "node dist/index.js",
"dev": "tsx watch src/index.ts",
"build": "tsc -p tsconfig.build.json && node -e \"require('fs').writeFileSync('dist/build.json', JSON.stringify({ version: require('./package.json').version, builtAt: new Date().toISOString() }))\"",
"typecheck": "tsc -p tsconfig.json --noEmit",
"test": "node --import tsx --test --test-reporter=spec \"tests/**/*.test.ts\"",
"postinstall": "prisma generate",
"prisma:generate": "prisma generate",
"prisma:deploy": "prisma migrate deploy && prisma generate",
"prisma:status": "prisma migrate status"
},
"dependencies": {
"@crosscode/contracts": "*",
"@prisma/adapter-pg": "^7.10.1",
"@prisma/client": "^7.10.1",
"dotenv": "^16.3.1",
"express": "^5.3.0",
"zod": "^4.6.7"
},
"devDependencies": {
"@types/express": "^5.0.6",
"@types/node": "^20.19.43",
"@types/supertest": "^7.2.1",
"prisma": "^7.10.1",
"supertest": "^7.3.1",
"tsx": "^4.23.15",
"typescript": "^5.9.3"
},
"engines": {
"node": ">=22"
}
}
+10
View File
@@ -0,0 +1,10 @@
// Prisma CLI config (migrate, generate). Prisma 7 doesn't load .env or read the URL from the schema.
import 'dotenv/config';
import { defineConfig } from 'prisma/config';
export default defineConfig({
schema: 'prisma/schema.prisma',
migrations: { path: 'prisma/migrations' },
// process.env, so `prisma generate` works on a machine with no DATABASE_URL (it never connects).
datasource: { url: process.env.DATABASE_URL ?? '' },
});
@@ -0,0 +1,289 @@
-- Church Website 1.0.0: the first schema (docs/WEBSITE-1.0-PLAN.md §1, §2, §4).
-- CreateSchema
CREATE SCHEMA IF NOT EXISTS "public";
-- CreateEnum
CREATE TYPE "WebsiteRole" AS ENUM ('owner', 'admin', 'editor', 'ministry_leader', 'viewer');
-- CreateEnum
CREATE TYPE "PageKind" AS ENUM ('home', 'visit', 'about', 'leadership', 'ministries', 'events', 'messages', 'give', 'contact', 'terms', 'safeguarding', 'custom');
-- CreateEnum
CREATE TYPE "MessageSource" AS ENUM ('youtube_feed', 'youtube', 'spotify');
-- CreateTable
CREATE TABLE "SiteDesign" (
"id" INTEGER NOT NULL DEFAULT 1,
"template" TEXT NOT NULL,
"variants" JSONB NOT NULL,
"home" JSONB NOT NULL,
"style" JSONB NOT NULL,
"updatedAt" TIMESTAMP(3) NOT NULL,
"updatedBy" TEXT,
CONSTRAINT "SiteDesign_pkey" PRIMARY KEY ("id")
);
-- CreateTable
CREATE TABLE "Page" (
"id" TEXT NOT NULL,
"kind" "PageKind" NOT NULL,
"slug" TEXT NOT NULL,
"title" TEXT NOT NULL,
"seoTitle" TEXT,
"description" TEXT,
"navLabel" TEXT,
"inNav" BOOLEAN NOT NULL DEFAULT true,
"position" INTEGER NOT NULL DEFAULT 0,
"imageId" TEXT,
"archivedAt" TIMESTAMP(3),
"updatedAt" TIMESTAMP(3) NOT NULL,
"updatedBy" TEXT,
CONSTRAINT "Page_pkey" PRIMARY KEY ("id")
);
-- CreateTable
CREATE TABLE "Section" (
"id" TEXT NOT NULL,
"pageId" TEXT NOT NULL,
"type" TEXT NOT NULL,
"variant" TEXT,
"position" INTEGER NOT NULL DEFAULT 0,
"hidden" BOOLEAN NOT NULL DEFAULT false,
"data" JSONB NOT NULL,
"updatedAt" TIMESTAMP(3) NOT NULL,
"updatedBy" TEXT,
CONSTRAINT "Section_pkey" PRIMARY KEY ("id")
);
-- CreateTable
CREATE TABLE "Ministry" (
"id" TEXT NOT NULL,
"slug" TEXT NOT NULL,
"name" TEXT NOT NULL,
"summary" TEXT,
"body" TEXT,
"imageId" TEXT,
"position" INTEGER NOT NULL DEFAULT 0,
"archivedAt" TIMESTAMP(3),
"updatedAt" TIMESTAMP(3) NOT NULL,
"updatedBy" TEXT,
CONSTRAINT "Ministry_pkey" PRIMARY KEY ("id")
);
-- CreateTable
CREATE TABLE "Leader" (
"id" TEXT NOT NULL,
"name" TEXT NOT NULL,
"role" TEXT,
"bio" TEXT,
"photoId" TEXT,
"position" INTEGER NOT NULL DEFAULT 0,
"archivedAt" TIMESTAMP(3),
"updatedAt" TIMESTAMP(3) NOT NULL,
"updatedBy" TEXT,
CONSTRAINT "Leader_pkey" PRIMARY KEY ("id")
);
-- CreateTable
CREATE TABLE "MessageSeries" (
"id" TEXT NOT NULL,
"slug" TEXT NOT NULL,
"title" TEXT NOT NULL,
"summary" TEXT,
"imageId" TEXT,
"createdAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
CONSTRAINT "MessageSeries_pkey" PRIMARY KEY ("id")
);
-- CreateTable
CREATE TABLE "Message" (
"id" TEXT NOT NULL,
"slug" TEXT NOT NULL,
"title" TEXT NOT NULL,
"date" TIMESTAMP(3) NOT NULL,
"source" "MessageSource" NOT NULL,
"mediaUrl" TEXT NOT NULL,
"externalId" TEXT,
"thumbnailUrl" TEXT,
"speaker" TEXT,
"passage" TEXT,
"notes" TEXT,
"seriesId" TEXT,
"hidden" BOOLEAN NOT NULL DEFAULT false,
"publishedAt" TIMESTAMP(3),
"updatedAt" TIMESTAMP(3) NOT NULL,
"updatedBy" TEXT,
CONSTRAINT "Message_pkey" PRIMARY KEY ("id")
);
-- CreateTable
CREATE TABLE "SimpleEvent" (
"id" TEXT NOT NULL,
"slug" TEXT NOT NULL,
"title" TEXT NOT NULL,
"startsAt" TIMESTAMP(3) NOT NULL,
"endsAt" TIMESTAMP(3),
"allDay" BOOLEAN NOT NULL DEFAULT false,
"timezone" TEXT NOT NULL DEFAULT 'Africa/Johannesburg',
"location" TEXT,
"description" TEXT,
"imageId" TEXT,
"link" TEXT,
"cancelled" BOOLEAN NOT NULL DEFAULT false,
"publishedAt" TIMESTAMP(3),
"updatedAt" TIMESTAMP(3) NOT NULL,
"updatedBy" TEXT,
CONSTRAINT "SimpleEvent_pkey" PRIMARY KEY ("id")
);
-- CreateTable
CREATE TABLE "ImportedEvent" (
"id" TEXT NOT NULL,
"originProduct" TEXT NOT NULL,
"originId" TEXT NOT NULL,
"startsAt" TIMESTAMP(3) NOT NULL,
"data" JSONB NOT NULL,
"syncedAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
CONSTRAINT "ImportedEvent_pkey" PRIMARY KEY ("id")
);
-- CreateTable
CREATE TABLE "MediaAsset" (
"id" TEXT NOT NULL,
"filename" TEXT NOT NULL,
"mime" TEXT NOT NULL,
"bytes" INTEGER NOT NULL,
"width" INTEGER,
"height" INTEGER,
"alt" TEXT NOT NULL DEFAULT '',
"sizes" JSONB,
"uploadedBy" TEXT,
"createdAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
CONSTRAINT "MediaAsset_pkey" PRIMARY KEY ("id")
);
-- CreateTable
CREATE TABLE "SiteVersion" (
"id" TEXT NOT NULL,
"number" INTEGER NOT NULL,
"snapshot" JSONB NOT NULL,
"note" TEXT,
"publishedBy" TEXT NOT NULL,
"publishedAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
CONSTRAINT "SiteVersion_pkey" PRIMARY KEY ("id")
);
-- CreateTable
CREATE TABLE "PreviewLink" (
"id" TEXT NOT NULL,
"tokenHash" TEXT NOT NULL,
"createdBy" TEXT NOT NULL,
"createdAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
"expiresAt" TIMESTAMP(3) NOT NULL,
"revokedAt" TIMESTAMP(3),
CONSTRAINT "PreviewLink_pkey" PRIMARY KEY ("id")
);
-- CreateTable
CREATE TABLE "WebsiteUser" (
"id" TEXT NOT NULL,
"email" TEXT NOT NULL,
"name" TEXT NOT NULL,
"role" "WebsiteRole" NOT NULL,
"ministryId" TEXT,
"lastSignInAt" TIMESTAMP(3),
"createdAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
CONSTRAINT "WebsiteUser_pkey" PRIMARY KEY ("id")
);
-- CreateTable
CREATE TABLE "AuditLog" (
"id" TEXT NOT NULL,
"actorId" TEXT,
"actorRole" TEXT NOT NULL,
"action" TEXT NOT NULL,
"targetType" TEXT NOT NULL,
"targetId" TEXT,
"metadata" JSONB,
"ip" TEXT,
"createdAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
CONSTRAINT "AuditLog_pkey" PRIMARY KEY ("id")
);
-- CreateTable
CREATE TABLE "AppSetting" (
"key" TEXT NOT NULL,
"value" TEXT NOT NULL,
"updatedAt" TIMESTAMP(3) NOT NULL,
CONSTRAINT "AppSetting_pkey" PRIMARY KEY ("key")
);
-- CreateIndex
CREATE UNIQUE INDEX "Page_slug_key" ON "Page"("slug");
-- CreateIndex
CREATE INDEX "Page_kind_idx" ON "Page"("kind");
-- CreateIndex
CREATE INDEX "Section_pageId_position_idx" ON "Section"("pageId", "position");
-- CreateIndex
CREATE UNIQUE INDEX "Ministry_slug_key" ON "Ministry"("slug");
-- CreateIndex
CREATE UNIQUE INDEX "MessageSeries_slug_key" ON "MessageSeries"("slug");
-- CreateIndex
CREATE UNIQUE INDEX "Message_slug_key" ON "Message"("slug");
-- CreateIndex
CREATE UNIQUE INDEX "Message_externalId_key" ON "Message"("externalId");
-- CreateIndex
CREATE INDEX "Message_date_idx" ON "Message"("date");
-- CreateIndex
CREATE UNIQUE INDEX "SimpleEvent_slug_key" ON "SimpleEvent"("slug");
-- CreateIndex
CREATE INDEX "SimpleEvent_startsAt_idx" ON "SimpleEvent"("startsAt");
-- CreateIndex
CREATE INDEX "ImportedEvent_startsAt_idx" ON "ImportedEvent"("startsAt");
-- CreateIndex
CREATE UNIQUE INDEX "ImportedEvent_originProduct_originId_key" ON "ImportedEvent"("originProduct", "originId");
-- CreateIndex
CREATE UNIQUE INDEX "SiteVersion_number_key" ON "SiteVersion"("number");
-- CreateIndex
CREATE UNIQUE INDEX "PreviewLink_tokenHash_key" ON "PreviewLink"("tokenHash");
-- CreateIndex
CREATE INDEX "AuditLog_createdAt_idx" ON "AuditLog"("createdAt");
-- AddForeignKey
ALTER TABLE "Section" ADD CONSTRAINT "Section_pageId_fkey" FOREIGN KEY ("pageId") REFERENCES "Page"("id") ON DELETE CASCADE ON UPDATE CASCADE;
-- AddForeignKey
ALTER TABLE "Message" ADD CONSTRAINT "Message_seriesId_fkey" FOREIGN KEY ("seriesId") REFERENCES "MessageSeries"("id") ON DELETE SET NULL ON UPDATE CASCADE;
-- AddForeignKey
ALTER TABLE "WebsiteUser" ADD CONSTRAINT "WebsiteUser_ministryId_fkey" FOREIGN KEY ("ministryId") REFERENCES "Ministry"("id") ON DELETE SET NULL ON UPDATE CASCADE;
@@ -0,0 +1,3 @@
# Please do not edit this file manually
# It should be added in your version-control system (e.g., Git)
provider = "postgresql"
+262
View File
@@ -0,0 +1,262 @@
// Church Website 1.0.0 (docs/WEBSITE-1.0-PLAN.md). One database per church.
//
// The content tables are the **working copy** the admin edits (§4). Publishing writes an immutable
// snapshot of them to SiteVersion; visitors always see the latest SiteVersion, the preview sees the
// working copy. Shared facts (name, logo, colours, service times, contact, the brand style) are the
// church profile's, in Accounts (§2), and are never stored here.
generator client {
provider = "prisma-client"
// Its own output, so hoisted clients of other apps never overwrite it (EVENTS-2.2-PLAN §2).
output = "../src/generated/prisma"
moduleFormat = "esm"
importFileExtension = "js"
}
datasource db {
provider = "postgresql"
}
/// Website roles (§10). Held here, per product: an Events role gives nothing in the Website.
enum WebsiteRole {
owner
admin
editor
ministry_leader
viewer
}
enum PageKind {
home
visit
about
leadership
ministries
events
messages
give
contact
terms
safeguarding
custom
}
enum MessageSource {
youtube_feed
youtube
spotify
}
/// The site's design in the working copy (one row, id 1): template, section variants, homepage
/// order and the Website-only style settings (src/site/variants.ts). Fonts and corners are shared.
model SiteDesign {
id Int @id @default(1)
template String
variants Json
home Json
style Json
updatedAt DateTime @updatedAt
updatedBy String?
}
/// A page: the fixed ones (§6) and custom pages built from blocks.
model Page {
id String @id @default(uuid())
kind PageKind
slug String @unique
title String
/// Per-page SEO (ROADMAP-v3 §11); null uses the generated one.
seoTitle String?
description String?
navLabel String?
inNav Boolean @default(true)
position Int @default(0)
imageId String?
archivedAt DateTime?
updatedAt DateTime @updatedAt
updatedBy String?
sections Section[]
@@index([kind])
}
/// A section or block on a page. `data` is validated with the zod schema for its `type`; `variant`
/// is one of that type's ids. Content is never tied to a template (§2).
model Section {
id String @id @default(uuid())
pageId String
page Page @relation(fields: [pageId], references: [id], onDelete: Cascade)
type String
variant String?
position Int @default(0)
hidden Boolean @default(false)
data Json
updatedAt DateTime @updatedAt
updatedBy String?
@@index([pageId, position])
}
model Ministry {
id String @id @default(uuid())
slug String @unique
name String
summary String?
body String?
imageId String?
position Int @default(0)
archivedAt DateTime?
updatedAt DateTime @updatedAt
updatedBy String?
leaders WebsiteUser[]
}
model Leader {
id String @id @default(uuid())
name String
role String?
bio String?
photoId String?
position Int @default(0)
archivedAt DateTime?
updatedAt DateTime @updatedAt
updatedBy String?
}
model MessageSeries {
id String @id @default(uuid())
slug String @unique
title String
summary String?
imageId String?
createdAt DateTime @default(now())
messages Message[]
}
/// A message (sermon), from the YouTube feed or added by hand (§7). Published on its own, not with
/// the site's Publish (decision 9). Audio and video are linked, never uploaded.
model Message {
id String @id @default(uuid())
slug String @unique
title String
date DateTime
source MessageSource
mediaUrl String
/// The YouTube video id or Spotify episode id: one message per video, whichever way it came in.
externalId String? @unique
thumbnailUrl String?
speaker String?
passage String?
notes String?
seriesId String?
series MessageSeries? @relation(fields: [seriesId], references: [id], onDelete: SetNull)
hidden Boolean @default(false)
publishedAt DateTime?
updatedAt DateTime @updatedAt
updatedBy String?
@@index([date])
}
/// A simple event made in the Website (§8). Registrations and payments are only Cross Events'.
model SimpleEvent {
id String @id @default(uuid())
slug String @unique
title String
startsAt DateTime
endsAt DateTime?
allDay Boolean @default(false)
timezone String @default("Africa/Johannesburg")
location String?
description String?
imageId String?
link String?
cancelled Boolean @default(false)
publishedAt DateTime?
updatedAt DateTime @updatedAt
updatedBy String?
@@index([startsAt])
}
/// A read-only copy of a sibling's event from the feed (crosscode.event/1, ROADMAP-v3 §4).
model ImportedEvent {
id String @id @default(uuid())
originProduct String
originId String
startsAt DateTime
data Json
syncedAt DateTime @default(now())
@@unique([originProduct, originId])
@@index([startsAt])
}
/// An upload: counted towards storage (§10) until neither the working copy nor the last 10
/// published versions use it.
model MediaAsset {
id String @id @default(uuid())
filename String
mime String
bytes Int
width Int?
height Int?
alt String @default("")
/// The resized files (WebP and JPEG per width) and their sizes, counted with `bytes`.
sizes Json?
uploadedBy String?
createdAt DateTime @default(now())
}
/// A published version: an immutable snapshot of the working copy (§4). Restore copies one back.
model SiteVersion {
id String @id @default(uuid())
number Int @unique
snapshot Json
note String?
publishedBy String
publishedAt DateTime @default(now())
}
/// A shared preview link (§4): the token is stored hashed, expires after 7 days or when revoked.
model PreviewLink {
id String @id @default(uuid())
tokenHash String @unique
createdBy String
createdAt DateTime @default(now())
expiresAt DateTime
revokedAt DateTime?
}
/// Someone who can use the admin: keyed by their account's `sub` from Accounts.
model WebsiteUser {
id String @id
email String
name String
role WebsiteRole
/// A Ministry leader edits only their own ministry.
ministryId String?
ministry Ministry? @relation(fields: [ministryId], references: [id], onDelete: SetNull)
lastSignInAt DateTime?
createdAt DateTime @default(now())
}
model AuditLog {
id String @id @default(uuid())
actorId String?
actorRole String
action String
targetType String
targetId String?
metadata Json?
ip String?
createdAt DateTime @default(now())
@@index([createdAt])
}
model AppSetting {
key String @id
value String
updatedAt DateTime @updatedAt
}
+57
View File
@@ -0,0 +1,57 @@
/**
* The Express app (docs/WEBSITE-1.0-PLAN.md §1). Everything is under /api, so the site and its API
* share one address (as Events and Accounts): nginx sends /api to this backend and the rest to Next.js.
*
* /api/health version and database, for monitoring, `crosscode deploy` and the Hub
* /api/v1/site/… the public site (what visitors see: the latest published version)
*
* To come (§1): /api/v1/admin/… (content, publish, preview links), /api/uploads/…, the event feed
* (/api/links/v1/*, as Events 2.4) and the Hub client.
*/
import express from 'express';
import type { Ctx } from './context.js';
import { handle, sendError } from './http.js';
import { appVersion } from './lib/version.js';
import { siteStatus } from './site/status.js';
async function dbUp(ctx: Ctx): Promise<boolean> {
try {
await ctx.db.$queryRaw`SELECT 1`;
return true;
} catch {
return false;
}
}
export function createApp(ctx: Ctx) {
const app = express();
app.disable('x-powered-by');
if (ctx.config.trustProxySetting !== false) app.set('trust proxy', ctx.config.trustProxySetting);
app.use((_req, res, next) => {
res.setHeader('X-Content-Type-Options', 'nosniff');
res.setHeader('Referrer-Policy', 'strict-origin-when-cross-origin');
// The API is never a page of its own in search results; the public pages are (ROADMAP-v3 §11).
res.setHeader('X-Robots-Tag', 'noindex');
next();
});
app.get('/api/health', async (_req, res) => {
const db = await dbUp(ctx);
res.status(db ? 200 : 503).json({ status: db ? 'ok' : 'error', product: 'website', version: appVersion(), db });
});
const site = express.Router();
site.get('/status', handle(() => siteStatus(ctx)));
app.use('/api/v1/site', site);
app.use('/api', (_req, res) => {
res.status(404).json({ error: { code: 'NOT_FOUND', message: 'There is no such API endpoint.' } });
});
app.use((err: unknown, _req: express.Request, res: express.Response, next: express.NextFunction) => {
if (res.headersSent) return next(err);
return sendError(res, err);
});
return app;
}
+18
View File
@@ -0,0 +1,18 @@
/**
* Everything a request handler or job needs, passed in rather than imported, so tests can run the
* app against a stand-in database.
*/
import type { PrismaClient } from './generated/prisma/client.js';
import type { Config } from './lib/config.js';
export type Db = PrismaClient;
export type Ctx = {
config: Config;
db: Db;
now: () => Date;
};
export function createCtx(config: Config, db: Db, opts: { now?: () => Date } = {}): Ctx {
return { config, db, now: opts.now ?? (() => new Date()) };
}
+26
View File
@@ -0,0 +1,26 @@
/**
* Shared bits for the API: errors as `{ error: { code, message, fields? } }` (as Accounts and
* Events' /api/v2) and async handlers.
*/
import type { Request, RequestHandler, Response } from 'express';
export class ApiError extends Error {
constructor(public status: number, public code: string, message: string, public fields?: Record<string, string>) {
super(message);
}
}
/** Known errors carry a status and code; anything else is a 500. */
export function sendError(res: Response, e: unknown) {
if (e instanceof ApiError) {
return res.status(e.status).json({ error: { code: e.code, message: e.message, ...(e.fields ? { fields: e.fields } : {}) } });
}
console.error('[api]', e);
return res.status(500).json({ error: { code: 'INTERNAL', message: 'Something went wrong. Please try again.' } });
}
export const handle = (fn: (req: Request, res: Response) => Promise<unknown>): RequestHandler => (req, res) => {
fn(req, res).then((out) => {
if (out !== undefined && !res.headersSent) res.json(out);
}).catch((e) => sendError(res, e));
};
+33
View File
@@ -0,0 +1,33 @@
/**
* Starts the Church Website's backend: database and HTTP server. Jobs (YouTube feed, storage count,
* sitemap, feed sync) and the Hub client come with their features (docs/WEBSITE-1.0-PLAN.md §1).
*/
import 'dotenv/config';
import { PrismaPg } from '@prisma/adapter-pg';
import { PrismaClient } from './generated/prisma/client.js';
import { createApp } from './app.js';
import { createCtx } from './context.js';
import { loadConfig } from './lib/config.js';
async function main() {
const config = loadConfig();
const url = process.env.DATABASE_URL;
if (!url) throw new Error('DATABASE_URL isn\'t set.');
const db = new PrismaClient({ adapter: new PrismaPg({ connectionString: url, connectionTimeoutMillis: 5000 }) });
const ctx = createCtx(config, db);
const app = createApp(ctx);
const server = app.listen(config.port, () => console.log(`[website] Listening on ${config.port} (${config.publicUrl}).`));
const stop = async () => {
server.close();
await db.$disconnect();
process.exit(0);
};
process.on('SIGTERM', stop);
process.on('SIGINT', stop);
}
main().catch((e) => {
console.error('[website] Failed to start:', e);
process.exit(1);
});
+55
View File
@@ -0,0 +1,55 @@
/**
* The server's settings, from the environment (`.env`, built from `env.template.json`). Read once;
* tests pass their own with `loadConfig({...})`.
*/
export type TrustProxy = false | number | string | string[];
export type Config = {
/** The public address, e.g. https://www.hopefamily.co.za (no trailing slash). */
publicUrl: string;
port: number;
/** Signs preview links and cookies, encrypts stored secrets. Generated on the server, never sent anywhere. */
secret: string;
production: boolean;
/** Express's "trust proxy" (TRUST_PROXY, read as Accounts reads it), or false when off. */
trustProxySetting: TrustProxy;
hubUrl: string;
hubLicenceKey: string | null;
hubPublicKey: string | null;
timezone: string;
jobsEnabled: boolean;
/** Where uploads go; default backend/uploads. */
uploadDir: string | null;
};
const bool = (v: string | undefined, def: boolean) => (v === undefined || v === '' ? def : String(v).toLowerCase() === 'true');
/** As Accounts' trustProxyFrom: `loopback`, a hop count, addresses, `true` (one hop) or `false`. */
export function trustProxyFrom(v: string | undefined, production: boolean): TrustProxy {
const raw = (v ?? '').trim();
if (raw === '') return production ? 1 : false;
const lower = raw.toLowerCase();
if (lower === 'true') return 1;
if (lower === 'false') return false;
if (/^\d+$/.test(raw)) return Number(raw) || false;
return raw.includes(',') ? raw.split(',').map((s) => s.trim()).filter(Boolean) : raw;
}
export function loadConfig(env: Record<string, string | undefined> = process.env): Config {
const production = env.NODE_ENV === 'production';
const secret = env.WEBSITE_SECRET || '';
if (production && secret.length < 32) throw new Error('WEBSITE_SECRET must be set (at least 32 characters) in production.');
return {
publicUrl: String(env.WEBSITE_URL || 'http://localhost:3300').replace(/\/+$/, ''),
port: Number(env.PORT || 5300),
secret: secret || 'development-only-secret-change-me-0123456789',
production,
trustProxySetting: trustProxyFrom(env.TRUST_PROXY, production),
hubUrl: String(env.HUB_URL || 'https://hub.crosscode.co.za').replace(/\/+$/, ''),
hubLicenceKey: env.HUB_LICENCE_KEY?.trim() || null,
hubPublicKey: env.HUB_PUBLIC_KEY?.trim() || null,
timezone: env.APP_TIMEZONE || 'Africa/Johannesburg',
jobsEnabled: bool(env.JOBS_ENABLED, true),
uploadDir: env.UPLOAD_DIR?.trim() || null,
};
}
+22
View File
@@ -0,0 +1,22 @@
/**
* The running version, from the backend's package.json (src/lib → ../../package.json in development,
* dist/lib → ../../package.json when built), so /api/health tells `crosscode deploy` the truth
* however the process was started (PM2 doesn't set npm_package_version).
*/
import fs from 'node:fs';
import path from 'node:path';
import { fileURLToPath } from 'node:url';
let cached: string | null = null;
export function appVersion(): string {
if (!cached) {
try {
const file = path.resolve(path.dirname(fileURLToPath(import.meta.url)), '..', '..', 'package.json');
cached = (JSON.parse(fs.readFileSync(file, 'utf8')) as { version: string }).version;
} catch {
cached = '0.0.0';
}
}
return cached;
}
+18
View File
@@ -0,0 +1,18 @@
/**
* What the public site shows right now: Coming soon until the first publish (§5, decision 3), then
* the latest published version. After the first publish there's no going back to Coming soon.
*/
import { WEBSITE_TEMPLATES, type WebsiteTemplate } from '@crosscode/contracts';
import type { Ctx } from '../context.js';
export type SiteStatus =
| { mode: 'coming-soon' }
| { mode: 'published'; version: number; publishedAt: string; template: WebsiteTemplate | null };
export async function siteStatus(ctx: Ctx): Promise<SiteStatus> {
const latest = await ctx.db.siteVersion.findFirst({ orderBy: { number: 'desc' }, select: { number: true, publishedAt: true, snapshot: true } });
if (!latest) return { mode: 'coming-soon' };
const t = (latest.snapshot as { design?: { template?: unknown } } | null)?.design?.template;
const template = (WEBSITE_TEMPLATES as readonly unknown[]).includes(t) ? (t as WebsiteTemplate) : null;
return { mode: 'published', version: latest.number, publishedAt: latest.publishedAt.toISOString(), template };
}
+202
View File
@@ -0,0 +1,202 @@
/**
* Section variants per template (docs/WEBSITE-1.0-PLAN.md §3, "Section variants per template",
* decision 16, confirmed 2026-11-25).
*
* Every template draws every variant, so nothing is ever unavailable and a template switch never
* needs a fallback. A template only sets which variant each section starts with, which ones it
* recommends, its header options, its homepage order and its style defaults.
*
* The ids are stored on each section (`hero.variant = "photo"`), so **an id never changes or goes
* away** once released, like the font pairing ids in `@crosscode/contracts`.
*/
import { z } from 'zod';
import type { Corners, WebsiteTemplate } from '@crosscode/contracts';
/** The homepage section types and their variant ids. */
export const SECTION_VARIANTS = {
hero: ['photo', 'video', 'collage', 'split', 'text'],
serviceTimes: ['panel', 'strip', 'map'],
welcome: ['text', 'image-text', 'pastor'],
ministries: ['cards', 'list', 'bands'],
team: ['faces', 'list', 'featured'],
events: ['cards', 'list', 'calendar'],
latestMessage: ['video', 'card', 'compact'],
invitation: ['banner', 'centred', 'image'],
} as const;
export type SectionType = keyof typeof SECTION_VARIANTS;
export type Variant<S extends SectionType = SectionType> = (typeof SECTION_VARIANTS)[S][number];
export const SECTION_TYPES = Object.keys(SECTION_VARIANTS) as [SectionType, ...SectionType[]];
export const sectionTypeSchema = z.enum(SECTION_TYPES);
/** Whether `variant` is one of `section`'s ids. */
export function isVariant<S extends SectionType>(section: S, variant: string): variant is Variant<S> {
return (SECTION_VARIANTS[section] as readonly string[]).includes(variant);
}
/** Per section: the default first, then the other recommended variants. */
type Recommendations = { [S in SectionType]: readonly [Variant<S>, ...Variant<S>[]] };
export const TEMPLATE_VARIANTS: Record<WebsiteTemplate, Recommendations> = {
heritage: {
hero: ['photo', 'split', 'text'],
serviceTimes: ['panel', 'map'],
welcome: ['pastor', 'text'],
ministries: ['list', 'cards'],
team: ['featured', 'faces'],
events: ['list', 'calendar'],
latestMessage: ['card', 'video'],
invitation: ['centred', 'banner'],
},
bold: {
hero: ['video', 'photo', 'split'],
serviceTimes: ['strip', 'map'],
welcome: ['image-text', 'pastor'],
ministries: ['bands', 'cards'],
team: ['faces', 'featured'],
events: ['cards', 'calendar'],
latestMessage: ['video', 'card'],
invitation: ['image', 'banner'],
},
community: {
hero: ['collage', 'photo', 'split'],
serviceTimes: ['map', 'panel'],
welcome: ['pastor', 'image-text'],
ministries: ['cards', 'bands'],
team: ['faces', 'featured'],
events: ['cards', 'calendar'],
latestMessage: ['card', 'video'],
invitation: ['banner', 'image'],
},
clean: {
hero: ['text', 'split', 'photo'],
serviceTimes: ['strip', 'panel'],
welcome: ['text', 'image-text'],
ministries: ['list', 'cards'],
team: ['list', 'faces'],
events: ['list', 'calendar'],
latestMessage: ['compact', 'card'],
invitation: ['centred', 'banner'],
},
};
export function defaultVariant<S extends SectionType>(template: WebsiteTemplate, section: S): Variant<S> {
return (TEMPLATE_VARIANTS[template][section] as readonly Variant<S>[])[0]!;
}
export function isRecommended(template: WebsiteTemplate, section: SectionType, variant: string): boolean {
return (TEMPLATE_VARIANTS[template][section] as readonly string[]).includes(variant);
}
/** The "Header" style setting: each template's options, default first. */
export const TEMPLATE_HEADERS = {
heritage: ['centred', 'centred-top-bar'],
bold: ['transparent', 'solid'],
community: ['logo-left-button', 'logo-left-tinted'],
clean: ['small', 'small-menu'],
} as const satisfies Record<WebsiteTemplate, readonly [string, ...string[]]>;
/**
* The transparent header only sits over a photo, video or collage hero; on any other first section
* it's drawn solid, so it never puts white text on white.
*/
export function headerIsTransparent(template: WebsiteTemplate, header: string, heroVariant: Variant<'hero'> | null): boolean {
return template === 'bold' && header === 'transparent' && heroVariant !== null && ['photo', 'video', 'collage'].includes(heroVariant);
}
/** A homepage entry: the section and whether it shows. */
export type HomeEntry = { section: SectionType; hidden: boolean };
const order = (shown: SectionType[], hidden: SectionType[] = []): HomeEntry[] => [
...shown.map((section) => ({ section, hidden: false })),
...hidden.map((section) => ({ section, hidden: true })),
];
/** The default homepage order (the church can reorder, hide and show). Every section is listed once. */
export const TEMPLATE_HOME_ORDER: Record<WebsiteTemplate, HomeEntry[]> = {
heritage: order(['hero', 'serviceTimes', 'welcome', 'latestMessage', 'ministries', 'team', 'events', 'invitation']),
bold: order(['hero', 'serviceTimes', 'welcome', 'events', 'latestMessage', 'ministries', 'invitation'], ['team']),
community: order(['hero', 'welcome', 'serviceTimes', 'ministries', 'team', 'events', 'latestMessage', 'invitation']),
clean: order(['hero', 'serviceTimes', 'welcome', 'events', 'latestMessage', 'invitation'], ['ministries', 'team']),
};
/** The Website-only style settings (§3, "Style settings"). Fonts and corners are the church's, shared. */
export const SECTION_COLOURS = ['light', 'tinted', 'mixed'] as const;
export const SPACINGS = ['airy', 'compact'] as const;
export const BUTTONS = ['solid', 'outline', 'pill'] as const;
export const IMAGE_TREATMENTS = ['natural', 'mono', 'duotone'] as const;
export type SiteStyle = {
sectionColour: (typeof SECTION_COLOURS)[number];
spacing: (typeof SPACINGS)[number];
buttons: (typeof BUTTONS)[number];
images: (typeof IMAGE_TREATMENTS)[number];
header: string;
};
export const TEMPLATE_STYLE: Record<WebsiteTemplate, SiteStyle & { suggestedCorners: Corners }> = {
heritage: { sectionColour: 'light', spacing: 'airy', buttons: 'outline', images: 'natural', header: 'centred', suggestedCorners: 'sharp' },
bold: { sectionColour: 'mixed', spacing: 'compact', buttons: 'solid', images: 'natural', header: 'transparent', suggestedCorners: 'sharp' },
community: { sectionColour: 'tinted', spacing: 'airy', buttons: 'pill', images: 'natural', header: 'logo-left-button', suggestedCorners: 'round' },
clean: { sectionColour: 'light', spacing: 'airy', buttons: 'outline', images: 'natural', header: 'small', suggestedCorners: 'soft' },
};
const STYLE_KEYS = ['sectionColour', 'spacing', 'buttons', 'images', 'header'] as const;
/** The site's design: what a template switch changes. Content is never part of it. */
export type SiteDesign = {
template: WebsiteTemplate;
variants: { [S in SectionType]: Variant<S> };
home: HomeEntry[];
style: SiteStyle;
};
/** A fresh site on `template`: every default. */
export function defaultDesign(template: WebsiteTemplate): SiteDesign {
const variants = Object.fromEntries(SECTION_TYPES.map((s) => [s, defaultVariant(template, s)])) as SiteDesign['variants'];
const { suggestedCorners: _c, ...style } = TEMPLATE_STYLE[template];
return { template, variants, home: TEMPLATE_HOME_ORDER[template].map((e) => ({ ...e })), style };
}
export type DesignChange = { what: string; from: string; to: string };
const sameOrder = (a: HomeEntry[], b: HomeEntry[]) =>
a.length === b.length && a.every((e, i) => e.section === b[i]!.section && e.hidden === b[i]!.hidden);
/**
* Switching template (§3, "Switching template"): anything still on the old template's default
* moves to the new template's default; anything the church chose stays. Returns the new design and
* what moved, for the Publish screen ("Hero: Collage → Text only, Clean's default").
*/
export function switchTemplate(current: SiteDesign, to: WebsiteTemplate): { design: SiteDesign; changes: DesignChange[] } {
if (current.template === to) return { design: current, changes: [] };
const from = current.template;
const target = defaultDesign(to);
const changes: DesignChange[] = [{ what: 'template', from, to }];
const variants = { ...current.variants } as Record<SectionType, string>;
for (const s of SECTION_TYPES) {
const next = target.variants[s];
if (current.variants[s] === defaultVariant(from, s) && next !== current.variants[s]) {
changes.push({ what: `${s}.variant`, from: current.variants[s], to: next });
variants[s] = next;
}
}
const homeUntouched = sameOrder(current.home, TEMPLATE_HOME_ORDER[from]);
const home = homeUntouched ? target.home : current.home.map((e) => ({ ...e }));
if (homeUntouched && !sameOrder(current.home, target.home)) changes.push({ what: 'home', from: `${from} order`, to: `${to} order` });
const style = { ...current.style };
const oldStyle = TEMPLATE_STYLE[from];
for (const k of STYLE_KEYS) {
// A header from the old template's options means nothing in the new one, so it always moves.
const untouched = current.style[k] === oldStyle[k] || (k === 'header' && !(TEMPLATE_HEADERS[to] as readonly string[]).includes(current.style.header));
if (untouched && current.style[k] !== target.style[k]) {
changes.push({ what: `style.${k}`, from: current.style[k], to: target.style[k] });
(style as Record<string, string>)[k] = target.style[k];
}
}
return { design: { template: to, variants: variants as SiteDesign['variants'], home, style }, changes };
}
+73
View File
@@ -0,0 +1,73 @@
import { describe, it } from 'node:test';
import assert from 'node:assert/strict';
import request from 'supertest';
import { createApp } from '../src/app.js';
import { createCtx, type Db } from '../src/context.js';
import { loadConfig } from '../src/lib/config.js';
import { appVersion } from '../src/lib/version.js';
type Version = { number: number; publishedAt: Date; snapshot: unknown };
/** Just what the app uses so far: a ping and the latest published version. */
function fakeDb(opts: { up?: boolean; versions?: Version[] } = {}): Db {
const versions = opts.versions ?? [];
return {
$queryRaw: async () => {
if (opts.up === false) throw new Error('down');
return [{ '?column?': 1 }];
},
siteVersion: {
findFirst: async () => [...versions].sort((a, b) => b.number - a.number)[0] ?? null,
},
} as unknown as Db;
}
const app = (db: Db) => createApp(createCtx(loadConfig({}), db));
describe('the app', () => {
it('answers /api/health with the product and version', async () => {
const res = await request(app(fakeDb())).get('/api/health');
assert.equal(res.status, 200);
assert.deepEqual(res.body, { status: 'ok', product: 'website', version: appVersion(), db: true });
});
it('says 503 when the database is down', async () => {
const res = await request(app(fakeDb({ up: false }))).get('/api/health');
assert.equal(res.status, 503);
assert.equal(res.body.db, false);
});
it('shows Coming soon until the first publish', async () => {
const res = await request(app(fakeDb())).get('/api/v1/site/status');
assert.deepEqual(res.body, { mode: 'coming-soon' });
});
it('shows the latest published version after it', async () => {
const at = new Date('2026-12-01T08:00:00Z');
const res = await request(app(fakeDb({ versions: [
{ number: 1, publishedAt: new Date('2026-11-30T08:00:00Z'), snapshot: { design: { template: 'heritage' } } },
{ number: 2, publishedAt: at, snapshot: { design: { template: 'clean' } } },
] }))).get('/api/v1/site/status');
assert.deepEqual(res.body, { mode: 'published', version: 2, publishedAt: at.toISOString(), template: 'clean' });
});
it('answers unknown API paths with a JSON 404 and keeps the API out of search', async () => {
const res = await request(app(fakeDb())).get('/api/nothing');
assert.equal(res.status, 404);
assert.equal(res.body.error.code, 'NOT_FOUND');
assert.equal(res.headers['x-robots-tag'], 'noindex');
assert.equal(res.headers['x-powered-by'], undefined);
});
});
describe('config', () => {
it('refuses production without a secret', () => {
assert.throws(() => loadConfig({ NODE_ENV: 'production' }), /WEBSITE_SECRET/);
});
it('defaults to the development ports', () => {
const c = loadConfig({});
assert.equal(c.port, 5300);
assert.equal(c.publicUrl, 'http://localhost:3300');
});
});
+103
View File
@@ -0,0 +1,103 @@
import { describe, it } from 'node:test';
import assert from 'node:assert/strict';
import { WEBSITE_TEMPLATES } from '@crosscode/contracts';
import {
SECTION_TYPES, SECTION_VARIANTS, TEMPLATE_HEADERS, TEMPLATE_HOME_ORDER, TEMPLATE_STYLE, TEMPLATE_VARIANTS,
defaultDesign, defaultVariant, headerIsTransparent, isRecommended, isVariant, switchTemplate,
} from '../src/site/variants.js';
describe('section variants (WEBSITE-1.0-PLAN §3, decision 16)', () => {
it('has the 26 confirmed variant ids', () => {
assert.equal(Object.values(SECTION_VARIANTS).flat().length, 26);
assert.deepEqual(SECTION_VARIANTS.hero, ['photo', 'video', 'collage', 'split', 'text']);
});
it('every template recommends only real variants, without repeats, with a default for every section', () => {
for (const t of WEBSITE_TEMPLATES) {
for (const s of SECTION_TYPES) {
const rec = TEMPLATE_VARIANTS[t][s] as readonly string[];
assert.ok(rec.length >= 2, `${t}.${s}`);
assert.equal(new Set(rec).size, rec.length, `${t}.${s} repeats`);
for (const v of rec) assert.ok(isVariant(s, v), `${t}.${s}: ${v}`);
}
}
});
it('has the confirmed defaults', () => {
assert.equal(defaultVariant('heritage', 'hero'), 'photo');
assert.equal(defaultVariant('bold', 'hero'), 'video');
assert.equal(defaultVariant('community', 'hero'), 'collage');
assert.equal(defaultVariant('clean', 'hero'), 'text');
assert.equal(defaultVariant('clean', 'latestMessage'), 'compact');
assert.ok(isRecommended('heritage', 'team', 'faces'));
assert.ok(!isRecommended('heritage', 'team', 'list'));
});
it('lists every section once in each homepage order; Bold hides Team, Clean hides Ministries and Team', () => {
for (const t of WEBSITE_TEMPLATES) {
assert.deepEqual([...TEMPLATE_HOME_ORDER[t].map((e) => e.section)].sort(), [...SECTION_TYPES].sort(), t);
}
const hidden = (t: keyof typeof TEMPLATE_HOME_ORDER) => TEMPLATE_HOME_ORDER[t].filter((e) => e.hidden).map((e) => e.section);
assert.deepEqual(hidden('heritage'), []);
assert.deepEqual(hidden('bold'), ['team']);
assert.deepEqual(hidden('community'), []);
assert.deepEqual(hidden('clean'), ['ministries', 'team']);
});
it("each template's default header is the first of its options", () => {
for (const t of WEBSITE_TEMPLATES) assert.equal(TEMPLATE_STYLE[t].header, TEMPLATE_HEADERS[t][0]);
});
it('suggests the confirmed corners', () => {
assert.deepEqual(WEBSITE_TEMPLATES.map((t) => TEMPLATE_STYLE[t].suggestedCorners), ['sharp', 'sharp', 'round', 'soft']);
});
it('only makes the header transparent over a photo, video or collage hero', () => {
assert.ok(headerIsTransparent('bold', 'transparent', 'video'));
assert.ok(!headerIsTransparent('bold', 'transparent', 'text'));
assert.ok(!headerIsTransparent('bold', 'transparent', 'split'));
assert.ok(!headerIsTransparent('bold', 'solid', 'photo'));
assert.ok(!headerIsTransparent('bold', 'transparent', null));
});
});
describe('switching template', () => {
it('moves an untouched site to every default of the new template', () => {
const { design, changes } = switchTemplate(defaultDesign('community'), 'clean');
assert.deepEqual(design, defaultDesign('clean'));
assert.ok(changes.some((c) => c.what === 'hero.variant' && c.from === 'collage' && c.to === 'text'));
assert.ok(changes.some((c) => c.what === 'home'));
assert.equal(changes[0]!.what, 'template');
});
it("keeps the church's own choices", () => {
const start = defaultDesign('heritage');
start.variants.hero = 'video';
start.style.buttons = 'pill';
start.home = [...start.home].reverse();
const { design, changes } = switchTemplate(start, 'clean');
assert.equal(design.template, 'clean');
assert.equal(design.variants.hero, 'video');
assert.equal(design.style.buttons, 'pill');
assert.deepEqual(design.home, start.home);
assert.equal(design.variants.team, 'list', 'an untouched section still moves');
assert.ok(!changes.some((c) => c.what === 'hero.variant' || c.what === 'home' || c.what === 'style.buttons'));
});
it("moves a header the new template doesn't have", () => {
const start = defaultDesign('bold');
start.style.header = 'solid';
const { design } = switchTemplate(start, 'heritage');
assert.equal(design.style.header, 'centred');
});
it('changes nothing when the template stays', () => {
const d = defaultDesign('bold');
assert.deepEqual(switchTemplate(d, 'bold'), { design: d, changes: [] });
});
it('round-trips an untouched site', () => {
const there = switchTemplate(defaultDesign('heritage'), 'bold').design;
assert.deepEqual(switchTemplate(there, 'heritage').design, defaultDesign('heritage'));
});
});
+5
View File
@@ -0,0 +1,5 @@
{
"extends": "./tsconfig.json",
"compilerOptions": { "rootDir": "src", "outDir": "dist" },
"include": ["src"]
}
+21
View File
@@ -0,0 +1,21 @@
{
// ES modules throughout, as Accounts (docs/WEBSITE-1.0-PLAN.md §1).
"compilerOptions": {
"target": "ES2023",
"module": "nodenext",
"moduleResolution": "nodenext",
"lib": ["ES2023"],
"strict": true,
"noImplicitOverride": true,
"noFallthroughCasesInSwitch": true,
"esModuleInterop": true,
"resolveJsonModule": true,
"skipLibCheck": true,
"forceConsistentCasingInFileNames": true,
"sourceMap": true,
"rootDir": ".",
"outDir": "dist",
"types": ["node"]
},
"include": ["src", "tests", "scripts", "prisma.config.ts"]
}
+22
View File
@@ -0,0 +1,22 @@
// PM2 config template. Each install keeps its own copy as ecosystem.config.cjs (not in git, so
// deploys never change it); crosscode creates it from this file the first time with the church's
// PM2 names and ports.
module.exports = {
apps: [
{
name: 'website-backend',
cwd: __dirname + '/backend',
script: 'dist/index.js',
env: { NODE_ENV: 'production' },
max_memory_restart: '400M',
},
{
name: 'website-frontend',
cwd: __dirname + '/frontend',
script: 'npm',
args: 'start -- -p 3300',
env: { NODE_ENV: 'production' },
max_memory_restart: '400M',
},
],
};
+22
View File
@@ -0,0 +1,22 @@
{
"schema": "crosscode.env-template/1",
"product": "website",
"files": {
"backend/.env": [
{ "name": "NODE_ENV", "layer": "generated", "required": true, "description": "production" },
{ "name": "PORT", "layer": "install", "from": "{apiPort}", "required": true, "description": "The backend's port (from the Hub's port list)" },
{ "name": "DATABASE_URL", "layer": "generated", "required": true, "description": "Made on the server with a new password; never leaves it" },
{ "name": "WEBSITE_SECRET", "layer": "generated", "required": true, "description": "Signs preview links and cookies, encrypts stored secrets: never change it" },
{ "name": "WEBSITE_URL", "layer": "install", "from": "https://{domain}", "required": true, "description": "The public address (www. or the Cross Code address)" },
{ "name": "TRUST_PROXY", "layer": "server", "required": true, "description": "Behind frp: loopback" },
{ "name": "APP_TIMEZONE", "layer": "install", "default": "Africa/Johannesburg" },
{ "name": "HUB_URL", "layer": "defaults", "default": "https://hub.crosscode.co.za" },
{ "name": "HUB_PUBLIC_KEY", "layer": "defaults", "description": "Only for a Hub other than production" },
{ "name": "HUB_LICENCE_KEY", "layer": "install", "description": "A Hub install registers by itself with this (CCW-…)" },
{ "name": "JOBS_ENABLED", "layer": "defaults", "default": "true" }
],
"frontend/.env.production": [
{ "name": "WEBSITE_API_URL", "layer": "install", "from": "http://127.0.0.1:{apiPort}", "required": true, "description": "Where the pages reach the backend on this server" }
]
}
}
+4
View File
@@ -0,0 +1,4 @@
node_modules/
.next/
next-env.d.ts
.env*
+9
View File
@@ -0,0 +1,9 @@
<!-- BEGIN:nextjs-agent-rules -->
## This is NOT the Next.js you know
This version has breaking changes — APIs, conventions, and file structure may all differ from your training data. Read the relevant guide in `node_modules/next/dist/docs/` (resolved from this file's directory; in monorepos the `next` package may not be visible from the repo root) before writing any code. Heed deprecation notices.
This block is written and re-added by `next dev` — verify at `node_modules/next/dist/server/lib/generate-agent-files.js`. Removing it from a diff only re-creates the uncommitted change; committing it with your work keeps the tree clean.
<!-- END:nextjs-agent-rules -->
+10
View File
@@ -0,0 +1,10 @@
import { defineConfig, globalIgnores } from "eslint/config";
import nextVitals from "eslint-config-next/core-web-vitals";
import nextTs from "eslint-config-next/typescript";
// Next.js 16's own flat configs, as Accounts. Run with `npm run lint`.
export default defineConfig([
...nextVitals,
...nextTs,
globalIgnores([".next/**", "out/**", "next-env.d.ts"]),
]);
+29
View File
@@ -0,0 +1,29 @@
import type { NextConfig } from "next";
// Everything under /api is the backend (docs/WEBSITE-1.0-PLAN.md §1). On a server nginx sends it
// there; in development (and when Next is reached directly) this rewrite does.
const api = (process.env.WEBSITE_API_URL || "http://127.0.0.1:5300").replace(/\/+$/, "");
const nextConfig: NextConfig = {
poweredByHeader: false,
transpilePackages: ["@crosscode/ui"],
async rewrites() {
return [{ source: "/api/:path*", destination: `${api}/api/:path*` }];
},
async headers() {
// The public site is indexed (ROADMAP-v3 §11); the admin and shared previews never are.
const common = [
{ key: "Referrer-Policy", value: "strict-origin-when-cross-origin" },
{ key: "X-Content-Type-Options", value: "nosniff" },
];
const noindex = { key: "X-Robots-Tag", value: "noindex, nofollow" };
return [
{ source: "/:path*", headers: common },
{ source: "/admin/:path*", headers: [noindex] },
{ source: "/admin", headers: [noindex] },
{ source: "/preview/:path*", headers: [noindex] },
];
},
};
export default nextConfig;
+32
View File
@@ -0,0 +1,32 @@
{
"name": "@crosscode/website-frontend",
"version": "0.1.0",
"private": true,
"description": "Church Website: the church's public site in its template, and the admin",
"scripts": {
"dev": "next dev -p 3300",
"build": "next build",
"start": "next start",
"lint": "eslint src",
"typecheck": "tsc --noEmit"
},
"dependencies": {
"@crosscode/contracts": "*",
"@crosscode/ui": "*",
"next": "^16.4.6",
"react": "^19.3.1",
"react-dom": "^19.3.1"
},
"devDependencies": {
"@eslint/eslintrc": "^3",
"@types/node": "^20",
"@types/react": "^19.3.0",
"@types/react-dom": "^19.3.0",
"autoprefixer": "^10.4.21",
"eslint": "^10.13.0",
"eslint-config-next": "^16.4.6",
"postcss": "^8.5.6",
"tailwindcss": "3.4",
"typescript": "^5"
}
}
+1
View File
@@ -0,0 +1 @@
module.exports = { plugins: { tailwindcss: {}, autoprefixer: {} } };
@@ -0,0 +1,13 @@
import type { Metadata } from "next";
export const metadata: Metadata = { title: "Admin", robots: { index: false, follow: false } };
// The admin (docs/WEBSITE-1.0-PLAN.md §10), signed in through the church's Accounts, comes next.
export default function Admin() {
return (
<main className="mx-auto max-w-xl px-4 py-16">
<h1 className="text-2xl font-semibold">Website admin</h1>
<p className="mt-2 text-gray-600">Not built yet.</p>
</main>
);
}
+20
View File
@@ -0,0 +1,20 @@
@tailwind base;
@tailwind components;
@tailwind utilities;
/* Defaults until the church profile's colour is set (layout.tsx overrides them per request). */
:root {
--brand: 31 78 121;
--brand-dark: 21 55 85;
}
body {
@apply bg-white text-gray-900 antialiased;
/* The church's font pairing (@crosscode/ui fonts.css); the template's default until it picks one. */
font-family: var(--cc-font-body, ui-sans-serif, system-ui, sans-serif);
}
h1, h2, h3 {
font-family: var(--cc-font-heading, inherit);
font-variation-settings: var(--cc-heading-variation, normal);
}
+18
View File
@@ -0,0 +1,18 @@
import type { Metadata } from "next";
import "@crosscode/ui/fonts.css";
import "./globals.css";
import { brandAttributes } from "@crosscode/ui";
// The church's name, colours, fonts and corners come from its profile in Accounts once the Website
// is linked (docs/WEBSITE-1.0-PLAN.md §2); until then, plain defaults.
export const metadata: Metadata = {
title: { default: "Church Website", template: "%s" },
};
export default function RootLayout({ children }: { children: React.ReactNode }) {
return (
<html lang="en-ZA" {...brandAttributes(null)}>
<body>{children}</body>
</html>
);
}
+31
View File
@@ -0,0 +1,31 @@
import type { Metadata } from "next";
import { loadStatus } from "@/lib/site";
// Rendered per request from the backend's status; the published site is cached once it exists (§1).
export const dynamic = "force-dynamic";
export async function generateMetadata(): Promise<Metadata> {
const status = await loadStatus();
// Coming soon is a real page (HTTP 200) but never indexed (§5, decision 14).
return status.mode === "coming-soon" ? { title: "Coming soon", robots: { index: false, follow: true } } : { title: "Home" };
}
export default async function Home() {
const status = await loadStatus();
if (status.mode === "coming-soon") {
// The full Coming soon page (logo, service times, contact, links to Events) comes with the
// church profile (§5).
return (
<main className="mx-auto flex min-h-screen max-w-xl flex-col items-center justify-center gap-4 px-4 text-center">
<h1 className="text-3xl font-semibold text-brand">Coming soon</h1>
<p className="text-gray-600">Our new website is on its way.</p>
</main>
);
}
return (
<main className="mx-auto max-w-3xl px-4 py-16">
<h1 className="text-3xl font-semibold">Welcome</h1>
<p className="mt-2 text-gray-600">Published version {status.version}. The templates come next (§3).</p>
</main>
);
}
+7
View File
@@ -0,0 +1,7 @@
import type { MetadataRoute } from "next";
// The public site is indexed; the admin, previews and API never are (ROADMAP-v3 §11). The sitemap
// comes with the published pages.
export default function robots(): MetadataRoute.Robots {
return { rules: [{ userAgent: "*", allow: "/", disallow: ["/admin", "/preview", "/api"] }] };
}
+16
View File
@@ -0,0 +1,16 @@
/** What the public site shows right now, from the backend (src/site/status.ts there). */
export type SiteStatus =
| { mode: "coming-soon" }
| { mode: "published"; version: number; publishedAt: string; template: string | null };
const api = (process.env.WEBSITE_API_URL || "http://127.0.0.1:5300").replace(/\/+$/, "");
export async function loadStatus(): Promise<SiteStatus> {
try {
const res = await fetch(`${api}/api/v1/site/status`, { next: { revalidate: 30 } });
if (res.ok) return (await res.json()) as SiteStatus;
} catch {
// The backend is starting or down: Coming soon is the safe thing to show.
}
return { mode: "coming-soon" };
}
+13
View File
@@ -0,0 +1,13 @@
/** @type {import('tailwindcss').Config} */
// The church's colours are CSS variables set per request in layout.tsx (from the church profile).
module.exports = {
content: ["./src/**/*.{ts,tsx}", "../../../packages/ui/src/**/*.{ts,tsx}"],
theme: {
extend: {
colors: {
brand: { DEFAULT: "rgb(var(--brand) / <alpha-value>)", dark: "rgb(var(--brand-dark) / <alpha-value>)" },
},
},
},
plugins: [],
};
+21
View File
@@ -0,0 +1,21 @@
{
"compilerOptions": {
"target": "ES2020",
"lib": ["dom", "dom.iterable", "esnext"],
"allowJs": false,
"skipLibCheck": true,
"strict": true,
"noEmit": true,
"esModuleInterop": true,
"module": "esnext",
"moduleResolution": "bundler",
"resolveJsonModule": true,
"isolatedModules": true,
"jsx": "react-jsx",
"incremental": true,
"plugins": [{ "name": "next" }],
"paths": { "@/*": ["./src/*"] }
},
"include": ["next-env.d.ts", "**/*.ts", "**/*.tsx", ".next/types/**/*.ts", ".next/dev/types/**/*.ts"],
"exclude": ["node_modules"]
}
+1 -1
View File
@@ -2,5 +2,5 @@
"name": "@crosscode/website",
"version": "0.0.0",
"private": true,
"description": "Placeholder: Church Website, built in phase 5 (ROADMAP-v3 §6)"
"description": "Church Website (ROADMAP-v3 §6, phase 5): backend/ and frontend/ are the workspaces"
}
+1 -1
View File
@@ -102,7 +102,7 @@ out").
[WEBSITE-1.0-PLAN.md](./WEBSITE-1.0-PLAN.md): decisions all confirmed 2026-11-21. Font pairings
confirmed 2026-11-24 (§3). Order: ~~contracts 1.17.0~~ → ~~Accounts 1.7.0~~ (both released 2026-11-24; Accounts
ships with contracts because it answers the new `church.update`) → ~~Events 3.7.0~~ (shared fonts and footer; released 2026-11-24) → ~~Hub 2.21.0~~ (released
and deployed 2026-11-25; the plan said 2.13.0) → **`website@1.0.0`** → Hope Family Church → a second
and deployed 2026-11-25; the plan said 2.13.0) → **`website@1.0.0`** (skeleton in `apps/website` 2026-11-25: backend, frontend, content model, the section variants in `src/site/variants.ts`) → Hope Family Church → a second
church → crosscode-site 1.7.0.
Done (confirmed by Joshua 2026-11-25): `hope-events` is archived, and every FastPanel site set up
before Hub 2.10.0, and the Hub's own site, has `location ^~ /api/`.
+1 -1
View File
@@ -29,7 +29,7 @@ on each run, so merging to `main` and pushing releases it. Its changes are liste
| `@crosscode/auth-client` | `packages/auth-client` | 1.1.0 (released with Events 3.0.0 and Accounts 1.1.0) |
| `@crosscode/seo` | `packages/seo` | 1.0.0 (released with Events 2.4.0) |
| `@crosscode/ui` | `packages/ui` | 0.3.0 (fonts, `ChurchFooter`; 0.2.0 with Accounts 1.7.0, 0.3.0 with Events 3.7.0) |
| Website | `apps/website` | 0.0.0 (phase 5, being built: contracts 1.17.0 released) |
| Website | `apps/website` | 0.1.0 (phase 5, being built: skeleton 2026-11-25; backend and frontend workspaces) |
| App | `apps/app` | 0.0.0 (not started, phase 6) |
These shared packages ship inside the apps that use them, from the same checkout, so they don't
+1 -1
View File
@@ -2,7 +2,7 @@
Phase **5** of [ROADMAP-v3.md](./ROADMAP-v3.md) (§6, §9, §10, §11; decisions 19, 20, 40–47).
Written 2026-11-21. **All decisions confirmed by Joshua on 2026-11-21** (12 changed: a full
storage stops uploads). Not started.
storage stops uploads). **Being built:** the skeleton is in `apps/website` (2026-11-25).
**Updated 2026-11-24:** the Hub release is **2.21.0**, not 2.13.0 (the Hub reached 2.20.0 on
2026-11-23 with other work). The 8 font pairings in §3 ("Font pairings") were **confirmed by Joshua
+2 -2
View File
@@ -18,6 +18,6 @@ export default defineConfig([
},
},
// Cross Events keeps its own lint (frontend/eslint.config.mjs, tsc for the backend) for now.
// The Accounts frontend has its own Next lint (apps/accounts/frontend/eslint.config.mjs); Prisma's client is generated.
globalIgnores(["**/node_modules/**", "**/dist/**", "**/coverage/**", "**/schemas/**", "apps/events/**", "apps/accounts/frontend/**", "**/src/generated/**", "**/.next/**"]),
// The Accounts and Website frontends have their own Next lint (apps/*/frontend/eslint.config.mjs); Prisma's client is generated.
globalIgnores(["**/node_modules/**", "**/dist/**", "**/coverage/**", "**/schemas/**", "apps/events/**", "apps/accounts/frontend/**", "apps/website/frontend/**", "**/src/generated/**", "**/.next/**"]),
]);
+62 -4
View File
@@ -12,10 +12,13 @@
"apps/*",
"!apps/events",
"!apps/accounts",
"!apps/website",
"apps/events/backend",
"apps/events/frontend",
"apps/accounts/backend",
"apps/accounts/frontend"
"apps/accounts/frontend",
"apps/website/backend",
"apps/website/frontend"
],
"devDependencies": {
"@axe-core/playwright": "^4.14.0",
@@ -348,7 +351,58 @@
},
"apps/website": {
"name": "@crosscode/website",
"version": "0.0.0"
"version": "0.0.0",
"dev": true,
"optional": true,
"peer": true
},
"apps/website/backend": {
"name": "@crosscode/website-backend",
"version": "0.1.0",
"hasInstallScript": true,
"dependencies": {
"@crosscode/contracts": "*",
"@prisma/adapter-pg": "^7.10.1",
"@prisma/client": "^7.10.1",
"dotenv": "^16.3.1",
"express": "^5.3.0",
"zod": "^4.6.7"
},
"devDependencies": {
"@types/express": "^5.0.6",
"@types/node": "^20.19.43",
"@types/supertest": "^7.2.1",
"prisma": "^7.10.1",
"supertest": "^7.3.1",
"tsx": "^4.23.15",
"typescript": "^5.9.3"
},
"engines": {
"node": ">=22"
}
},
"apps/website/frontend": {
"name": "@crosscode/website-frontend",
"version": "0.1.0",
"dependencies": {
"@crosscode/contracts": "*",
"@crosscode/ui": "*",
"next": "^16.4.6",
"react": "^19.3.1",
"react-dom": "^19.3.1"
},
"devDependencies": {
"@eslint/eslintrc": "^3",
"@types/node": "^20",
"@types/react": "^19.3.0",
"@types/react-dom": "^19.3.0",
"autoprefixer": "^10.4.21",
"eslint": "^10.13.0",
"eslint-config-next": "^16.4.6",
"postcss": "^8.5.6",
"tailwindcss": "3.4",
"typescript": "^5"
}
},
"node_modules/@alloc/quick-lru": {
"version": "5.3.0",
@@ -1020,8 +1074,12 @@
"resolved": "packages/ui",
"link": true
},
"node_modules/@crosscode/website": {
"resolved": "apps/website",
"node_modules/@crosscode/website-backend": {
"resolved": "apps/website/backend",
"link": true
},
"node_modules/@crosscode/website-frontend": {
"resolved": "apps/website/frontend",
"link": true
},
"node_modules/@date-fns/tz": {
+4 -1
View File
@@ -8,10 +8,13 @@
"apps/*",
"!apps/events",
"!apps/accounts",
"!apps/website",
"apps/events/backend",
"apps/events/frontend",
"apps/accounts/backend",
"apps/accounts/frontend"
"apps/accounts/frontend",
"apps/website/backend",
"apps/website/frontend"
],
"scripts": {
"build": "npm run build --workspaces --if-present",