From 716d47242a1014e58245a768a6e3eb0f566af794 Mon Sep 17 00:00:00 2001 From: Joshua Oosthuizen Date: Wed, 18 Nov 2026 12:58:50 +0200 Subject: [PATCH] Events 2.4.0 frontend, deploy and docs: Linked products, linked events, seo MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - Site settings → Linked products (Connect, Show events from, Publish my events), help, command palette. - Events from linked products on /events, the home and campus pages, and /events/linked// (markdown with HTML off, canonical to the origin, no JSON-LD, not in the sitemap). - Event page JSON-LD from @crosscode/seo; lib/eventSchema.ts removed. - Readiness check for linked products' sync; e2e spec with a fake Church Website (not run yet: needs the e2e Postgres). - crosscode: install and build the shared packages Events uses first (an older tag still builds as before); scripts/tests/events.bats. - Release notes, changelogs, handovers, hub-protocol.md, and the plan's "Changes while building". Co-Authored-By: Claude Opus 5.5 --- CHANGELOG.md | 27 +++ apps/events/CHANGELOG.md | 41 +++++ apps/events/WHATS-NEW.md | 10 ++ apps/events/backend/package.json | 1 + apps/events/backend/src/utils/readiness.js | 7 + .../backend/tests/linkedProducts.test.js | 34 ++++ apps/events/docs/HANDOVER.md | 20 +++ apps/events/e2e/linked-products.spec.ts | 163 +++++++++++++++++ .../frontend/src/app/campus/[slug]/page.tsx | 14 +- .../src/app/dashboard/admin/settings/page.tsx | 7 +- .../frontend/src/app/events/[id]/page.tsx | 25 ++- .../app/events/linked/[product]/[id]/page.tsx | 121 +++++++++++++ apps/events/frontend/src/app/events/page.tsx | 10 +- apps/events/frontend/src/app/page.tsx | 19 +- .../components/admin/LinkedProductsTab.tsx | 167 ++++++++++++++++++ .../src/components/events/EventsGrid.tsx | 22 ++- .../src/components/events/LinkedEventCard.tsx | 61 +++++++ .../src/content/help/site-settings.tsx | 23 ++- apps/events/frontend/src/lib/commandPages.ts | 2 +- apps/events/frontend/src/lib/eventSchema.ts | 85 --------- apps/events/frontend/src/lib/linkedEvents.ts | 39 ++++ docs/EVENTS-2.4-PLAN.md | 43 ++++- docs/HANDOVER.md | 9 +- docs/ROADMAP-v3.md | 2 +- docs/hub-protocol.md | 24 ++- package-lock.json | 1 + scripts/products/events.sh | 27 ++- scripts/tests/events.bats | 55 ++++++ 28 files changed, 929 insertions(+), 130 deletions(-) create mode 100644 apps/events/e2e/linked-products.spec.ts create mode 100644 apps/events/frontend/src/app/events/linked/[product]/[id]/page.tsx create mode 100644 apps/events/frontend/src/components/admin/LinkedProductsTab.tsx create mode 100644 apps/events/frontend/src/components/events/LinkedEventCard.tsx delete mode 100644 apps/events/frontend/src/lib/eventSchema.ts create mode 100644 apps/events/frontend/src/lib/linkedEvents.ts create mode 100644 scripts/tests/events.bats diff --git a/CHANGELOG.md b/CHANGELOG.md index f845542..a963621 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -2,6 +2,33 @@ Each package and app has its own section and its own tags (`contracts@1.0.0`, `accounts@1.0.0`, …). +## events@2.4.0, contracts@1.4.0 - unreleased + +Phase 2 (docs/EVENTS-2.4-PLAN.md): protocol v2, Linked products, the event feed and +`packages/seo`. With Hub 2.2.0 (events-hub). Not tagged yet: the e2e run and the VM test come first. + +### Events (2.4.0) + +- Protocol v2 with the site's own Ed25519 key, Settings → Linked products with Connect, the public + event feed (`/api/feed/v1/events`) and `event.changed`, and events from linked products on the + public pages. Details in `apps/events/CHANGELOG.md`. + +### Contracts (1.4.0) + +- `crosscode.link/1` (`link.connect`, `link.connected`, `link.disconnect`) with `signLink` / + `verifyLink`, PEM helpers, link secrets and nonces; `LINK_PATHS`, `FEED_PATHS`. +- The v2 heartbeat can carry `publicKey`; the reply's `publicKeyStatus` (`saved` / `matches` / + `mismatch`). +- `typesVersions` for `@crosscode/contracts/signing` (older `moduleResolution`). + +### packages/seo (new) + +- `eventJsonLd`, `churchJsonLd`, `canonicalUrl`, `pageMeta`, `jsonLdString` (ROADMAP-v3 §11). + +### Scripts + +- `crosscode` (Events): installs and builds the shared packages Events uses before it. + ## events@2.3.1 - 2026-11-18 - Next.js 16.4.6 (security advisories for 16.2.0–16.4.4; Events wasn't exposed). Also brings diff --git a/apps/events/CHANGELOG.md b/apps/events/CHANGELOG.md index 3405524..eec4252 100644 --- a/apps/events/CHANGELOG.md +++ b/apps/events/CHANGELOG.md @@ -5,6 +5,47 @@ All notable changes to this project are documented in this file. The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/), and this project follows [Semantic Versioning](https://semver.org/). +## [2.4.0] - unreleased + +Protocol v2, Linked products, the event feed and `packages/seo` (ROADMAP-v3 phase 2, +docs/EVENTS-2.4-PLAN.md). Needs Hub 2.2.0 for the move to protocol v2 (against an older Hub it keeps +working on v1 and Linked products stays empty). contracts 1.4.0. + +### Added + +- **Protocol v2** (`src/hub/client.js`): register and heartbeat send `product: "events"`; the site + makes an Ed25519 key pair once (`src/links/store.ts`, `hub_private_key` encrypted) and sends its + public key on the heartbeat until the Hub answers `publicKeyStatus: saved | matches`. Installs + registered with v1 move over without their licence key. The reply's `linkedProducts` is cached + (`hub_linked_products`). A Hub that refuses a v2 body gets the same heartbeat as v1, and v1 is + used for a day (`hub_v1_until`), so the licence always refreshes. Update requests and AI calls + stay v1. +- **Linked products** (Site settings → Linked products; `/api/v2/linked-products`): the church's + other products from the Hub, **Connect** / **Disconnect** (`crosscode.link/1` over + `POST /api/links/v1/connect` and `/disconnect`, both directions, Ed25519-signed and checked + against the Hub-listed key, replays refused via `LinkNonce`), per-link **Show events from** and + the site's **Publish my events** (`feed_publish`). Audit log: `product_link_connected`, + `product_link_disconnected`, `feed_publish_toggled`, `feed_show_toggled`. +- **The event feed** `GET /api/feed/v1/events?updatedSince=` (`crosscode.event-feed/1`, public, no + personal information) built from `FeedEntry` (`src/feed/entries.ts`): going live, closing and + selling out are changes even though no `Event` row changes; deactivated events go in `deleted`; + ended events drop out after 30 days without a tombstone. Refreshed by the `feed` job (every 5 + minutes), a few seconds after writes to events, tickets and registrations (`config/db.js`), and + before answering when older than a minute. Changes are announced with `event.changed` + (`LINK_HEADERS`, one retry after a minute; the 15-minute poll catches the rest). +- **Showing linked products' events** (`src/feed/sync.ts`, `ImportedEvent`): fetched every 15 + minutes (`feed-sync`) and on a valid `POST /api/feed/v1/changed` (`feed-sync-link` task); only + events whose origin matches the link; the last good copy stays when a source is down. Shown on + /events, the home page and campus pages, each with its page `/events/linked//` + (markdown with HTML off, canonical link to the origin, no JSON-LD, not in the sitemap). + `/api/v2/linked-events`. +- **`@crosscode/seo`** (`packages/seo`): the event page's JSON-LD now comes from + `crosscode.event/1` (`crosscodeEvent` and `priceRangeCents` on `/events/:id/full`); + `frontend/src/lib/eventSchema.ts` is gone. The price range now covers main tickets only (an add-on + used to set the lowest price). +- Readiness: "Events from linked products are up to date". +- `FEED_JOBS_ENABLED` (default `true`). Migration `20261120120000_linked_products`. + ## [2.3.1] - 2026-11-18 ### Security diff --git a/apps/events/WHATS-NEW.md b/apps/events/WHATS-NEW.md index c8f4b7f..6230187 100644 --- a/apps/events/WHATS-NEW.md +++ b/apps/events/WHATS-NEW.md @@ -12,6 +12,16 @@ Write for church admins, not developers: no environment variables, endpoints or developer log is CHANGELOG.md. A tagged version without a section here shows "No details given". --> +## 2.4.0 + +- **Ready for the Church Website and App.** When your church has them, your events can show on + them and theirs here, with registration and payments still in Cross Events. Nothing changes until + you have them: Site settings → Linked products then lists them, with a Connect button. +- **Publish my events** (on by default) shares your public events with your connected products, + exactly as they appear on your events page. Hidden events and anyone's details are never shared. +- **Better search results for your events**: Google gets each event's real dates, place and the + price range of its main tickets, from the same data every Cross Code product uses. + ## 2.3.1 - **Maintenance update.** An update to the framework the site is built on, with its latest security diff --git a/apps/events/backend/package.json b/apps/events/backend/package.json index 9ee8afa..0d20e55 100644 --- a/apps/events/backend/package.json +++ b/apps/events/backend/package.json @@ -49,6 +49,7 @@ "zod": "^4.6.7" }, "devDependencies": { + "@crosscode/seo": "*", "@types/express": "^5.0.6", "@types/jest": "^30.0.0", "@types/jsonwebtoken": "^9.0.10", diff --git a/apps/events/backend/src/utils/readiness.js b/apps/events/backend/src/utils/readiness.js index dc48056..66d0b15 100644 --- a/apps/events/backend/src/utils/readiness.js +++ b/apps/events/backend/src/utils/readiness.js @@ -91,6 +91,13 @@ async function readiness(now = new Date(), db = prisma) { lastBackup ? `Last backup ${new Date(lastBackup).toLocaleString('en-ZA')}` : 'No backups found on this server.', '/dashboard/admin/settings?tab=backups'); + // Linked products (2.4.0): a product whose events are shown here, but that hasn't answered for a day. + const shown = await (db.productLink?.findMany({ where: { showEvents: true }, select: { url: true, lastGoodAt: true, lastSyncError: true, connectedAt: true } }) ?? Promise.resolve([])).catch(() => []); + const stale = shown.filter(l => l.lastSyncError && now - new Date(l.lastGoodAt || l.connectedAt) > DAY); + add('linked_sync', 'Events from linked products are up to date', stale.length === 0, + stale.length ? `Not fetched for over a day: ${stale.map(l => l.url).join(', ')}. Their last events keep showing.` : `${shown.length} product${shown.length === 1 ? '' : 's'} fetched in the last day`, + '/dashboard/admin/settings?tab=linked', shown.length > 0); + const applicable = checks.filter(c => c.applies); const passed = applicable.filter(c => c.ok).length; return { score: applicable.length ? Math.round((passed / applicable.length) * 100) : 0, passed, total: applicable.length, checks }; diff --git a/apps/events/backend/tests/linkedProducts.test.js b/apps/events/backend/tests/linkedProducts.test.js index 584cc8c..28e2a7f 100644 --- a/apps/events/backend/tests/linkedProducts.test.js +++ b/apps/events/backend/tests/linkedProducts.test.js @@ -484,3 +484,37 @@ describe('protocol v2 heartbeat', () => { expect(await store.publicKeyStatus()).toBe('saved'); }); }); + +// ─── The event page's JSON-LD (@crosscode/seo, replacing frontend/src/lib/eventSchema.ts) ── + +describe('event JSON-LD from crosscode.event/1', () => { + test('matches what the event page sent before 2.4.0, with the price range from main tickets only', () => { + const { eventJsonLd } = require('@crosscode/seo'); + const row = eventRow({ id: '00000000-0000-4000-8000-0000000000aa' }); + const built = buildCrosscodeEvent(row, new Map(), ctx()); + // As the page calls it (events/[id]/page.tsx). + const ld = eventJsonLd({ ...built.event, description: row.description }, { + pageUrl: `https://events.hope.test/events/${row.id}`, + organizer: { name: 'Hope Family Church', url: 'https://events.hope.test' }, + priceRange: built.priceRangeCents, + offerUrl: `https://events.hope.test/register/${row.id}`, + validFrom: row.goLiveAt.toISOString(), + }); + expect(ld).toEqual({ + '@context': 'https://schema.org', + '@type': 'Event', + name: 'Youth Camp', + description: row.description, + startDate: row.startDate.toISOString(), + endDate: row.endDate.toISOString(), + eventStatus: 'https://schema.org/EventScheduled', + eventAttendanceMode: 'https://schema.org/OfflineEventAttendanceMode', + location: { '@type': 'Place', name: 'Camp Wartburg', address: 'Camp Wartburg' }, + image: ['https://events.hope.test/api/uploads/camp.jpg'], + url: `https://events.hope.test/events/${row.id}`, + organizer: { '@type': 'Organization', name: 'Hope Family Church', url: 'https://events.hope.test' }, + // Before 2.4.0 the add-on T-shirt (R120) made this 120.00–450.00. + offers: { '@type': 'AggregateOffer', lowPrice: '300.00', highPrice: '450.00', priceCurrency: 'ZAR', availability: 'https://schema.org/InStock', url: `https://events.hope.test/register/${row.id}`, validFrom: row.goLiveAt.toISOString() }, + }); + }); +}); diff --git a/apps/events/docs/HANDOVER.md b/apps/events/docs/HANDOVER.md index 8a83d62..9230d5c 100644 --- a/apps/events/docs/HANDOVER.md +++ b/apps/events/docs/HANDOVER.md @@ -145,6 +145,26 @@ Languages (Afrikaans, §10) and Wallet passes (§7) are removed from scope (2026 - `backend/src/hub/client.js` `connectFromEnv()`: a site the Hub installed registers by itself on first start from `HUB_LICENCE_KEY`. +## Where Linked products and the feed live (2.4.0) + +Plan and reasons: the root [EVENTS-2.4-PLAN.md](../../../docs/EVENTS-2.4-PLAN.md). + +- **Protocol v2**: `backend/src/hub/client.js` (`heartbeatBody`, the v1 fallback `hub_v1_until`). + The key pair and the Hub's list of the church's products: `backend/src/links/store.ts`. +- **Connect** (`crosscode.link/1`): `backend/src/links/connect.ts` (both directions), + `links/http.ts` (calls to siblings: public addresses only, like webhooks), `links/routes.ts` + (`/api/feed/v1/*`, `/api/links/v1/*`, mounted in `app.js` before the JSON parser). +- **The feed**: `backend/src/feed/build.ts` (an Event as `crosscode.event/1`, also for the event + page's JSON-LD), `feed/entries.ts` (`FeedEntry`, refresh, `changedSoon` from `config/db.js`), + `feed/notify.ts` (`event.changed`), `feed/sync.ts` (fetching linked products' events into + `ImportedEvent`). Jobs `feed`, `feed-sync`; task `feed-sync-link`. +- **Screens**: `frontend/src/components/admin/LinkedProductsTab.tsx` (Site settings → Linked + products), `components/events/LinkedEventCard.tsx`, `lib/linkedEvents.ts`, + `app/events/linked/[product]/[id]/page.tsx`. API: `backend/src/v2/resources/linkedProducts.ts`. +- **Tests**: `backend/tests/linkedProducts.test.js` (in-memory database: + `tests/support/fakeFeedDb.js`), `e2e/linked-products.spec.ts` (a fake Church Website on + localhost:5198). + ## Working on this repo - **Release routine:** branch `feat/` → commit → bump with diff --git a/apps/events/e2e/linked-products.spec.ts b/apps/events/e2e/linked-products.spec.ts new file mode 100644 index 0000000..c321e48 --- /dev/null +++ b/apps/events/e2e/linked-products.spec.ts @@ -0,0 +1,163 @@ +import http from "http"; +import path from "path"; +import crypto from "crypto"; +import { test, expect, loginAs, seed, API } from "./fixtures"; + +// Linked products and the event feed (2.4.0, docs/EVENTS-2.4-PLAN.md §8). A fake Church Website +// runs on localhost: the test tells the site the Hub listed it (as a heartbeat would), an admin +// connects it and shows its events, and its event appears on /events with its own page whose +// canonical link points back to the website. Also: this site's own feed, and its event JSON-LD. +/* eslint-disable @typescript-eslint/no-require-imports -- the backend's own modules, as prepare-db.js uses them */ +const backend = path.join(__dirname, "..", "backend"); +const { Client } = require(require.resolve("pg", { paths: [backend] })); +const { e2eDatabaseUrl } = require("./support/db-url"); +const signing = require(require.resolve("@crosscode/contracts/signing", { paths: [backend] })); +const { eventFeedSchema } = require(require.resolve("@crosscode/contracts", { paths: [backend] })); +/* eslint-enable @typescript-eslint/no-require-imports */ + +const WEBSITE_PORT = 5198; +const WEBSITE_URL = `http://localhost:${WEBSITE_PORT}`; +const WEBSITE_ID = "3b0f6a52-6c1e-4b7a-9d0e-2f1a8c4b7e02"; +const EVENTS_ID = "9a4c2f1e-7b3d-4e5a-8c6f-0d1e2f3a4b5c"; +const EVENT_ID = "6e5d4c3b-2a19-4807-b6f5-e4d3c2b1a090"; +const websiteKey = signing.generateEd25519(); +const websitePem = signing.ed25519PublicToPem(websiteKey.publicKey); + +async function sql>(text: string, values: unknown[] = []): Promise { + const client = new Client({ connectionString: e2eDatabaseUrl() }); + await client.connect(); + try { + return (await client.query(text, values)).rows as T[]; + } finally { + await client.end(); + } +} +const setSetting = (key: string, value: string) => + sql(`INSERT INTO "AppSetting" (key, value, "updatedAt") VALUES ($1, $2, now()) ON CONFLICT (key) DO UPDATE SET value = $2, "updatedAt" = now()`, [key, value]); + +function websiteEvent() { + const starts = new Date(Date.now() + 10 * 24 * 3600e3); + return { + schema: "crosscode.event/1", + id: EVENT_ID, + origin: { product: "website", installId: WEBSITE_ID, url: `${WEBSITE_URL}/events/carols-by-candlelight` }, + status: "published", + updatedAt: new Date().toISOString(), + title: "Carols by Candlelight", + summary: null, + description: "Bring a **blanket** and the family.\n\nNo booking needed.", + imageUrl: null, + timezone: "Africa/Johannesburg", + startsAt: starts.toISOString(), + endsAt: new Date(starts.getTime() + 2 * 3600e3).toISOString(), + allDay: false, + sessions: [], + location: { name: "Church lawn", address: null, onlineUrl: null }, + campus: null, + series: null, + tags: ["christmas"], + registration: { mode: "contact", url: null, status: "open", opensAt: null, closesAt: null, priceFrom: null }, + }; +} + +test.describe.serial("linked products and the event feed", () => { + let server: http.Server; + const connects: Record[] = []; + + test.beforeAll(async () => { + server = http.createServer((req, res) => { + let body = ""; + req.on("data", c => { body += c; }); + req.on("end", async () => { + const send = (status: number, json: unknown) => res.writeHead(status, { "Content-Type": "application/json" }).end(JSON.stringify(json)); + if (req.method === "POST" && req.url === "/api/links/v1/connect") { + const m = JSON.parse(body); + connects.push(m); + // The website checks Cross Events' message with the key the Hub listed for it. + const [row] = await sql<{ value: string }>(`SELECT value FROM "AppSetting" WHERE key = 'hub_public_key'`); + if (!row || !signing.verifyLink(m, row.value).ok) return send(401, { message: "Bad signature", code: "BAD_SIGNATURE" }); + return send(200, signing.signLink({ + schema: "crosscode.link/1", type: "link.connected", + from: { product: "website", installId: WEBSITE_ID, url: WEBSITE_URL }, to: { installId: EVENTS_ID }, + inReplyTo: m.nonce, issuedAt: new Date().toISOString(), nonce: crypto.randomBytes(18).toString("base64url"), + }, websiteKey.privateKeyPem)); + } + if (req.method === "GET" && req.url?.startsWith("/api/feed/v1/events")) { + return send(200, { schema: "crosscode.event-feed/1", generatedAt: new Date().toISOString(), events: [websiteEvent()], deleted: [] }); + } + if (req.method === "POST" && req.url === "/api/links/v1/disconnect") return send(200, { schema: "crosscode.link/1", type: "link.disconnected" }); + return send(404, { message: "Not here", code: "NOT_FOUND" }); + }); + }); + await new Promise(resolve => server.listen(WEBSITE_PORT, resolve)); + // What a v2 heartbeat would have stored: this site's Hub id and the church's other products. + await setSetting("hub_install_id", EVENTS_ID); + await setSetting("hub_linked_products", JSON.stringify([{ product: "website", installId: WEBSITE_ID, url: WEBSITE_URL, publicKey: websitePem }])); + }); + + test.afterAll(async () => { + await sql(`DELETE FROM "ProductLink"`); + await sql(`DELETE FROM "FeedEntry"`); + await sql(`DELETE FROM "AppSetting" WHERE key IN ('hub_install_id', 'hub_linked_products', 'feed_publish')`); + await new Promise(resolve => server.close(resolve)); + }); + + test("an admin connects the Church Website and shows its events", async ({ page }) => { + await loginAs(page, "admin"); + await page.goto("/dashboard/admin/settings?tab=linked"); + const row = page.getByTestId("linked-website"); + await expect(row).toContainText("Church Website"); + await expect(row).toContainText("Not connected"); + await row.getByRole("button", { name: "Connect" }).click(); + await expect(page.getByRole("status")).toContainText("Connected to Church Website."); + expect(connects).toHaveLength(1); + expect(connects[0]).toMatchObject({ type: "link.connect", from: { product: "events", installId: EVENTS_ID }, to: { installId: WEBSITE_ID } }); + + await row.getByLabel(/Show events from Church Website/).check(); + await expect(page.getByRole("status")).toContainText("events are fetched"); + await expect(row).toContainText("1 event"); + }); + + test("its event is on /events, with its own page pointing back to the website", async ({ page }) => { + await page.goto("/events"); + const card = page.getByTestId("linked-event-card").filter({ hasText: "Carols by Candlelight" }); + await expect(card).toContainText("From the Church Website"); + await card.getByRole("link", { name: "View details" }).click(); + + await expect(page).toHaveURL(new RegExp(`/events/linked/website/${EVENT_ID}$`)); + await expect(page.getByRole("heading", { level: 1 })).toHaveText("Carols by Candlelight"); + await expect(page.locator('link[rel="canonical"]')).toHaveAttribute("href", `${WEBSITE_URL}/events/carols-by-candlelight`); + await expect(page.locator("strong", { hasText: "blanket" })).toBeVisible(); + // HTML in the description is dropped, never run. + expect(await page.locator("main script").count()).toBe(0); + expect(await page.locator('script[type="application/ld+json"]').count()).toBe(0); + + const sitemap = await (await page.request.get("/sitemap.xml")).text(); + expect(sitemap).not.toContain("/events/linked/"); + }); + + test("this site's own feed and event JSON-LD", async ({ page, request }) => { + const res = await request.get(`${API}/api/feed/v1/events`); + expect(res.status()).toBe(200); + const feed = await res.json(); + expect(eventFeedSchema.safeParse(feed).success).toBe(true); + const ids = feed.events.map((e: { id: string }) => e.id); + expect(ids).toContain(seed().events.free); + expect(ids).not.toContain(EVENT_ID); + expect(JSON.stringify(feed)).not.toMatch(/@e2e\.test/); + + await page.goto(`/events/${seed().events.free}`); + const ld = JSON.parse(await page.locator('script[type="application/ld+json"]').innerText()); + expect(ld).toMatchObject({ "@context": "https://schema.org", "@type": "Event", url: expect.stringContaining(`/events/${seed().events.free}`) }); + }); + + test("disconnecting removes its events", async ({ page }) => { + await loginAs(page, "admin"); + await page.goto("/dashboard/admin/settings?tab=linked"); + page.once("dialog", d => d.accept()); + await page.getByTestId("linked-website").getByRole("button", { name: "Disconnect" }).click(); + await expect(page.getByRole("status")).toContainText("Disconnected from Church Website."); + await page.goto("/events"); + await expect(page.getByTestId("linked-event-card")).toHaveCount(0); + }); +}); diff --git a/apps/events/frontend/src/app/campus/[slug]/page.tsx b/apps/events/frontend/src/app/campus/[slug]/page.tsx index e4026e0..27dea19 100644 --- a/apps/events/frontend/src/app/campus/[slug]/page.tsx +++ b/apps/events/frontend/src/app/campus/[slug]/page.tsx @@ -4,6 +4,8 @@ import { notFound } from "next/navigation"; import { Navbar } from "@/components/layout/Navbar"; import { Footer } from "@/components/layout/Footer"; import { EventCard } from "@/components/events/EventCard"; +import { LinkedEventCard } from "@/components/events/LinkedEventCard"; +import { fetchLinkedEvents, mergeByStart } from "@/lib/linkedEvents"; import { ApiImage } from "@/components/shared/ApiImage"; import { apiFetchListForPrerender, ApiError } from "@/lib/api"; import { mapsSearchUrl } from "@/lib/maps"; @@ -42,13 +44,17 @@ export default async function CampusPage({ params }: { params: Promise<{ slug: s const campus = await loadCampus(slug); if (!campus) notFound(); - const events = await apiFetchListForPrerender(`/api/v2/event-listing?campus=${encodeURIComponent(campus.slug)}`, { nextOptions: { next: { revalidate } } }); + const [events, linked] = await Promise.all([ + apiFetchListForPrerender(`/api/v2/event-listing?campus=${encodeURIComponent(campus.slug)}`, { nextOptions: { next: { revalidate } } }), + fetchLinkedEvents(campus.slug), + ]); // A server component renders once per request (or revalidation): this is that render's time. // eslint-disable-next-line react-hooks/purity const now = Date.now(); const upcoming = (events || []) .filter(e => e.cashupStatus !== "closed" && new Date(e.endDate || e.startDate).getTime() > now) .sort((a, b) => new Date(a.nextSession?.startsAt || a.startDate).getTime() - new Date(b.nextSession?.startsAt || b.startDate).getTime()); + const items = mergeByStart(upcoming, linked, e => e.nextSession?.startsAt || e.startDate); return (
@@ -79,14 +85,16 @@ export default async function CampusPage({ params }: { params: Promise<{ slug: s

Upcoming events

Events at {campus.name}, and church-wide events for every campus.

- {upcoming.length === 0 ? ( + {items.length === 0 ? (

No upcoming events at {campus.name} right now — check back soon.

) : (
- {upcoming.map(event => )} + {items.map(item => item.kind === "own" + ? + : )}
)} diff --git a/apps/events/frontend/src/app/dashboard/admin/settings/page.tsx b/apps/events/frontend/src/app/dashboard/admin/settings/page.tsx index bd7aac9..b490095 100644 --- a/apps/events/frontend/src/app/dashboard/admin/settings/page.tsx +++ b/apps/events/frontend/src/app/dashboard/admin/settings/page.tsx @@ -8,7 +8,7 @@ import { ApiError, resolveToApiOrigin } from "@/lib/api"; import { apiV2Raw, apiV2Data } from "@/lib/apiV2"; import { useSiteSettings } from "@/contexts/SiteSettingsContext"; import { useDismissingState } from "@/hooks/useDismissingState"; -import { Building2, Palette, Bell, Mail, Scale, MessageCircle, CreditCard, DatabaseBackup, Timer, KeyRound, MapPinned, type LucideIcon, Webhook, Sparkles } from "lucide-react"; +import { Building2, Palette, Bell, Mail, Scale, MessageCircle, CreditCard, DatabaseBackup, Timer, KeyRound, MapPinned, type LucideIcon, Webhook, Sparkles, Link2 } from "lucide-react"; import { ColorPickerField } from "@/components/admin/ColorPickerField"; import { BrandingPreviewPanel } from "@/components/admin/BrandingPreviewPanel"; import { BackupsTab } from "@/components/admin/BackupsTab"; @@ -17,6 +17,7 @@ import { PaymentsTab } from "@/components/admin/PaymentsTab"; import { LicenceTab } from "@/components/admin/LicenceTab"; import { WebhooksTab } from "@/components/admin/WebhooksTab"; import { AiTab } from "@/components/admin/AiTab"; +import { LinkedProductsTab } from "@/components/admin/LinkedProductsTab"; import { CampusesTab } from "@/components/admin/CampusesTab"; import { extractDominantColors } from "@/lib/extractColors"; import { mapsSearchUrl } from "@/lib/maps"; @@ -25,7 +26,7 @@ import { BackLink } from "@/components/shared/BackLink"; import { uploadImage } from "@/lib/eventSetup"; import { useExternalEffect } from "@/lib/hooks"; -type TabId = "organisation" | "campuses" | "branding" | "notifications" | "email" | "legal" | "whatsapp" | "payments" | "webhooks" | "backups" | "jobs" | "licence" | "ai"; +type TabId = "organisation" | "campuses" | "branding" | "notifications" | "email" | "legal" | "whatsapp" | "payments" | "webhooks" | "linked" | "backups" | "jobs" | "licence" | "ai"; const TABS: { id: TabId; label: string; icon: LucideIcon }[] = [ { id: "organisation", label: "Organisation", icon: Building2 }, @@ -37,6 +38,7 @@ const TABS: { id: TabId; label: string; icon: LucideIcon }[] = [ { id: "whatsapp", label: "WhatsApp", icon: MessageCircle }, { id: "payments", label: "Payments", icon: CreditCard }, { id: "webhooks", label: "Webhooks", icon: Webhook }, + { id: "linked", label: "Linked products", icon: Link2 }, { id: "backups", label: "Backups", icon: DatabaseBackup }, { id: "jobs", label: "Background jobs", icon: Timer }, { id: "licence", label: "Licence", icon: KeyRound }, @@ -718,6 +720,7 @@ function SiteSettingsPageInner() { {/* ── Backups ───────────────────────────────────────────────────────── */} {activeTab === "backups" && } {activeTab === "webhooks" && } + {activeTab === "linked" && } {activeTab === "jobs" && } {activeTab === "licence" && } {activeTab === "ai" && } diff --git a/apps/events/frontend/src/app/events/[id]/page.tsx b/apps/events/frontend/src/app/events/[id]/page.tsx index 1e459e1..3afc649 100644 --- a/apps/events/frontend/src/app/events/[id]/page.tsx +++ b/apps/events/frontend/src/app/events/[id]/page.tsx @@ -54,6 +54,9 @@ type Event = { attendanceMode?: "whole" | "pick"; sessions?: EventSession[]; registrationClosesAt?: string; + // 2.4.0: the event as crosscode.event/1, what its schema.org JSON-LD is built from (@crosscode/seo). + crosscodeEvent?: CrosscodeEvent | null; + priceRangeCents?: { lowCents: number; highCents: number } | null; lateJoin?: LateJoinInfo | null; series?: EventSeriesRef | null; nextInSeries?: NextInSeries | null; @@ -69,7 +72,8 @@ import { isPickOption, latePrice, registrationClosesAt, scheduleSummary } from " import { SessionSchedule } from "@/components/events/SessionSchedule"; import { appUrl, appName } from "@/lib/siteConfig"; import { getServerSettings } from "@/lib/serverSettings"; -import { eventJsonLd, jsonLdString } from "@/lib/eventSchema"; +import { eventJsonLd, jsonLdString } from "@crosscode/seo"; +import type { CrosscodeEvent } from "@crosscode/contracts"; // Tiered low-stock threshold: larger events use a smaller percentage. // Math.round avoids Math.ceil inflating the threshold (e.g. ceil(1.5)=2 made @@ -188,16 +192,21 @@ export default async function EventDetailPage({ params }: { params: Promise<{ id const settings = await getServerSettings(); const siteUrl = appUrl.replace(/\/$/, ""); - const jsonLd = eventJsonLd(event, { - pageUrl: `${siteUrl}/events/${event.id}`, - imageUrl: event.picture ? resolveToApiOrigin(event.picture) : null, - organizerName: settings.org_name || appName, - siteUrl, - }); + // schema.org Event (Google's event results), from the same crosscode.event/1 the feed publishes. + // The description goes in as the plain text it is (the feed's copy is escaped for markdown). + const jsonLd = event.crosscodeEvent + ? eventJsonLd({ ...event.crosscodeEvent, description: event.description || null }, { + pageUrl: `${siteUrl}/events/${event.id}`, + organizer: { name: settings.org_name || appName, url: siteUrl }, + priceRange: event.priceRangeCents ?? undefined, + offerUrl: `${siteUrl}/register/${event.id}`, + validFrom: event.goLiveAt || null, + }) + : null; return (
- " in event text. */ -export function jsonLdString(data: unknown): string { - return JSON.stringify(data).replace(/ { + const query = campus ? `?campus=${encodeURIComponent(campus)}` : ""; + try { + return await apiFetchListForPrerender(`/api/v2/linked-events${query}`, { nextOptions: { next: { revalidate: 60 } } }); + } catch { + return []; + } +} + +/** This site's page for a linked event. */ +export const linkedEventPath = (e: LinkedEvent) => `/events/linked/${e.product}/${e.event.id}`; + +/** "From the Church Website". */ +export const fromLabel = (e: LinkedEvent) => `From the ${e.productName}`; + +/** Our events and linked ones in one list by start time. `startOf` gives our events' start. */ +export function mergeByStart(ours: T[], linked: LinkedEvent[], startOf: (e: T) => string): ({ kind: "own"; event: T } | { kind: "linked"; event: LinkedEvent })[] { + const all = [ + ...ours.map((event) => ({ kind: "own" as const, event, at: new Date(startOf(event)).getTime() })), + ...linked.map((event) => ({ kind: "linked" as const, event, at: new Date(event.event.startsAt).getTime() })), + ]; + return all.sort((a, b) => a.at - b.at).map((x) => (x.kind === "own" ? { kind: "own" as const, event: x.event } : { kind: "linked" as const, event: x.event })); +} diff --git a/docs/EVENTS-2.4-PLAN.md b/docs/EVENTS-2.4-PLAN.md index d637c0c..bfbc360 100644 --- a/docs/EVENTS-2.4-PLAN.md +++ b/docs/EVENTS-2.4-PLAN.md @@ -1,7 +1,10 @@ # Cross Events 2.4.0 — protocol v2, Linked products, the event feed and `packages/seo` Phase **2** of [ROADMAP-v3.md](./ROADMAP-v3.md) (§4, §5 "Sibling discovery", §9, §11; decisions -5, 20). Written 2026-11-18. **Not started.** +5, 20). Written 2026-11-18. **Built 2026-11-18** on branches (contracts 1.4.0 and Events 2.4.0 on +`feat/events-2.4` here, Hub 2.2.0 on `feat/link-public-key`, crosscode-site on +`feat/linked-products`); not tagged yet. The decisions below were taken as proposed. Where the +build differs from this plan, see [Changes while building](#changes-while-building). **What 2.4.0 is:** Cross Events becomes a full member of a church stack. It reports to the Hub as `product: "events"` (protocol v2), shows the church's other products under **Settings → Linked @@ -35,8 +38,9 @@ sample feeds (§8). It's ready for the Website (phase 4) without another Events 8. [What changes in each repo](#7-what-changes-in-each-repo) 9. [Testing](#8-testing) 10. [Releasing and rolling it out](#9-releasing-and-rolling-it-out) -11. [Decisions](#decisions) -12. [Still open](#still-open) +11. [Changes while building](#changes-while-building) +12. [Decisions](#decisions) +13. [Still open](#still-open) --- @@ -365,6 +369,39 @@ Order, each with its CHANGELOG entry and `npm run check` first: 4. crosscode-site `v1.4.0`, deployed. 5. Each church updated through the Hub (a scheduled update, ROLLOUT-1.0 §5). +## Changes while building + +1. **A different public key never fails the heartbeat** (§1 said `409 PUBLIC_KEY_MISMATCH`): the + heartbeat also refreshes the licence, so failing it could lock a church out after 30 days. The + Hub keeps the saved key, answers `publicKeyStatus: "mismatch"` and opens an alert on the + install; the site keeps sending its key until it gets `saved` or `matches`, so it's saved + right after Joshua clears the old one. Events shows the mismatch on Linked products. +2. **Update requests and AI calls stay on protocol 1** (every Hub accepts them); only register and + heartbeat move to v2. A Hub that refuses a v2 body (`UNSUPPORTED_PROTOCOL` or + `INVALID_REQUEST`) gets the same heartbeat again as v1, and v1 is used for a day. The v2 + health fills in what v1 could leave empty (`jobs`, `pendingMigrations`), and the body is + checked against the contract before it's sent. +3. **`event.changed` is tried once more after a minute, then left to the 15-minute poll** (§3 + said the webhooks' 1 min … 12 h schedule): retrying longer than the poll interval adds nothing. +4. **The feed is also refreshed before it's served** when the last refresh is over a minute old, + so it's right even with the jobs switched off (e2e, `FEED_JOBS_ENABLED=false`). +5. **Imported events must come from that link's install** (`origin.installId` and `product`), + so one product can't publish events as another. Others are skipped and counted. +6. **JSON-LD**: `organizer` stays an `Organization` (the snapshot rule allowed only additions); + `Church` JSON-LD is in `@crosscode/seo` for the Website. The price range is now from main + tickets only (before, an add-on such as a T-shirt could set the lowest price). The description + goes in as plain text, not the feed's markdown-escaped copy. +7. **The deploy builds the shared packages**: `scripts/products/events.sh` installs and builds + `packages/contracts` and `packages/seo` before Events when the checkout's Events uses them + (an older tag still builds as before; `scripts/tests/events.bats`). +8. **`FEED_JOBS_ENABLED`** (optional, default `true`) switches the `feed` and `feed-sync` jobs, + like the other job flags (in `.env.example` and SETTINGS.md, not the env templates). +9. The readiness check is on the existing readiness page; contracts 1.4.0 also adds + `FEED_PATHS` and `typesVersions` (so `@crosscode/contracts/signing` has types under the + Events backend's `moduleResolution: node`). +10. **Not run yet:** the e2e spec (`e2e/linked-products.spec.ts`, needs the e2e Postgres) and the + VM test (§8): this machine has neither Postgres nor WSL. Both before tagging. + ## Decisions Proposed in this plan, to confirm before building: diff --git a/docs/HANDOVER.md b/docs/HANDOVER.md index fa39f04..80ffbc9 100644 --- a/docs/HANDOVER.md +++ b/docs/HANDOVER.md @@ -28,7 +28,7 @@ for each phase and the rollout checklist ([ROLLOUT-1.0.md](./ROLLOUT-1.0.md)). | 1b | Cross Events 2.2.0: moved here as `apps/events`, the `crosscode` script | **Released** 2026-11-17 (`events@2.2.0`, with AI use in tokens and the backend under `/api`). **VM tested 2026-11-17** (EVENTS-2.2-PLAN §6, all passing after fixes). **Not rolled out:** servers still run `hope-events` `v2.1.1` until each install is adopted | | 1c | Cross Events 2.3.x: authenticator app 2FA (TOTP + recovery codes) | **Released** 2026-11-17 (`events@2.3.0`). **`events@2.3.1`** 2026-11-18: Next.js 16.4.6 (security advisories for 16.2.0–16.4.4), so roll out 2.3.1, not 2.3.0. crosscode-site `v1.3.0` lists it (merged and tagged, **not deployed**) | | 1d | Agent 1.0.x + Hub 2.1.x (+ contracts 1.3.0) | **Released** 2026-11-17 (`agent@1.0.0`, `contracts@1.3.0`, Hub `v2.1.0`). **VM tested** end to end (AGENT-1.0-PLAN §13: joins, installs behind frp, scheduled / batch / missed updates, uninstall with export and purge, forged and replayed jobs). 2026-11-18: **`agent@1.0.1`** (the agent answers status on the central server itself) and Hub **`v2.1.1`** (adopt passes the church's address; Link takes the short name as a name). **Not rolled out**: use agent 1.0.1 and Hub 2.1.1 | -| 2 | Cross Events 2.4.0: protocol v2, Linked products, event feed, `packages/seo` (+ contracts 1.4.0, Hub 2.2.0) | **Planned** 2026-11-18: [EVENTS-2.4-PLAN.md](./EVENTS-2.4-PLAN.md), with six decisions to confirm before building. Events keeps speaking protocol 1 until then | +| 2 | Cross Events 2.4.0: protocol v2, Linked products, event feed, `packages/seo` (+ contracts 1.4.0, Hub 2.2.0) | **Built** 2026-11-18 ([EVENTS-2.4-PLAN.md](./EVENTS-2.4-PLAN.md), decisions taken as proposed, "Changes while building" there): `feat/events-2.4` here, `feat/link-public-key` in events-hub, `feat/linked-products` in crosscode-site. Unit tests pass. **Not tagged:** the e2e spec and the VM test haven't run (no Postgres on the dev machine) | | 3–7 | Accounts 1.0.0 → Website 1.0.0 → Events 3.0.0 → App 1.0.0 → App 1.x | Not started | ## Next up @@ -40,10 +40,9 @@ for each phase and the rollout checklist ([ROLLOUT-1.0.md](./ROLLOUT-1.0.md)). onto the monorepo) → a throwaway New install to prove FASTPANEL, DNS and Let's Encrypt. 2. **Deploy crosscode-site `v1.3.0`** (secure sign-in in the features and the brochure). 3. **Archive `hope-events`** once every install reports 2.2.0 or later (EVENTS-2.2-PLAN §7). -4. **Cross Events 2.4.0** (phase 2): confirm the decisions in - [EVENTS-2.4-PLAN.md](./EVENTS-2.4-PLAN.md), then build it in its order (contracts 1.4.0 → - Hub 2.2.0 → Events 2.4.0 → crosscode-site 1.4.0). It can be built during the rollout; releasing - it needs Hub 2.2.0 deployed. +4. **Cross Events 2.4.0** (phase 2) is built on branches: run `npm run test:e2e` in `apps/events` + (with the e2e Postgres) and the VM test in EVENTS-2.4-PLAN §8, then merge and release in its + order (contracts 1.4.0 → Hub 2.2.0, deployed → Events 2.4.0 → crosscode-site 1.4.0). ## The VM test (2026-11-17) diff --git a/docs/ROADMAP-v3.md b/docs/ROADMAP-v3.md index ced4adf..545a42a 100644 --- a/docs/ROADMAP-v3.md +++ b/docs/ROADMAP-v3.md @@ -616,7 +616,7 @@ Planned in [AGENT-1.0-PLAN.md](./AGENT-1.0-PLAN.md). In short: | 1b | **Cross Events 2.2.0** | **Moves into the monorepo** as `apps/events`, with its git history (merged in, not copied); its packages become workspaces; the **`crosscode` script** (`deploy`, `status`, `install`, `adopt`; §8) replaces `scripts/deploy.sh` and `scripts/install.sh`; every install moved with `crosscode adopt`; `hope-events` archived. Planned with no feature changes; two small ones were added on 2026-11-17 (decided by Joshua): **AI use shown in tokens**, never rand, outside the Hub (needs Hub 2.0.1), and **everything the backend serves under `/api`**, so a site and its API share one address and one proxy rule. **Tagged 2026-11-17, before the VM testing; VM tested the same day** | Before more products, so every product is released and deployed the same way from the start | | 1c | **Cross Events 2.3.0** | **Authenticator app 2FA** (TOTP) next to email and WhatsApp, with recovery codes; admins can see which method each staff account uses. **Released 2026-11-17** (`events@2.3.0`) | Independent and useful now; the Accounts migration later carries it over | | 1d | **Agent 1.0.0 + Hub 2.1.0** (contracts 1.3.0) | **Server agent** on every server (polls only, signed jobs, runs the `crosscode` script); Hub: Servers page with stats and alerts, server configuration, frp port list, New install with a choice of server, scheduled / emergency / batch updates with notice to the church, uninstall with an encrypted JSON export, emailed reports. [AGENT-1.0-PLAN.md](./AGENT-1.0-PLAN.md). **Released 2026-11-17** after the VM test; rollout in [ROLLOUT-1.0.md](./ROLLOUT-1.0.md) | Right after 1b (it runs the `crosscode` script), so every new church from then on is installed from the Hub. Can run alongside 1c | -| 2 | **Cross Events 2.4.0** | Reports `product: "events"` (protocol v2), **Linked products**, the event feed (publish + show events from siblings), `packages/seo` (§11) with canonical links for imported events. **Planned 2026-11-18:** [EVENTS-2.4-PLAN.md](./EVENTS-2.4-PLAN.md) (also needs contracts 1.4.0 and Hub 2.2.0, for a public key in the v2 heartbeat) | Small; ready for when the Website exists | +| 2 | **Cross Events 2.4.0** | Reports `product: "events"` (protocol v2), **Linked products**, the event feed (publish + show events from siblings), `packages/seo` (§11) with canonical links for imported events. **Planned and built 2026-11-18:** [EVENTS-2.4-PLAN.md](./EVENTS-2.4-PLAN.md) (also needs contracts 1.4.0 and Hub 2.2.0, for a public key in the v2 heartbeat); not tagged yet | Small; ready for when the Website exists | | 3 | **Accounts 1.0.0** | OIDC provider, sign-in, 2FA (email, WhatsApp, authenticator app), password reset, consent and notice, export / delete fan-out, admin, install script | The Website is built on it from day one | | 4 | **Church Website 1.0.0** | Public site with the **four templates** (§6), admin, simple events + feed, SEO (§11), Hope Family Church as the first church, then a second test church on a different template to prove it repeats | More churches need a website than an app; it also covers the "website only" case | | 5 | **Cross Events 3.0.0** | Sign-in moves to Accounts; user migration keeping password hashes; migration guide | Breaking change, so a major version, after Accounts is proven on the Website | diff --git a/docs/hub-protocol.md b/docs/hub-protocol.md index 0fa23f9..ccc12e6 100644 --- a/docs/hub-protocol.md +++ b/docs/hub-protocol.md @@ -332,6 +332,24 @@ what's needed) until the church's install of that product runs that version or l **AI.** The monthly cap and markup are the church's, shared by all its installs: a call from any of them counts what all of them used this month. -**Moving an install to v2** (e.g. Cross Events 2.4.0): register again with `protocolVersion: 2`, -the product and a public key (same licence and address: same install id, new secret), then send v2 -heartbeats. Nothing on the Hub needs changing. +**Moving an install to v2** (e.g. Cross Events 2.4.0, Hub 2.2.0+): an install that registered with +v1 just starts sending v2 heartbeats, with its Ed25519 public key (PEM) in `publicKey`. It doesn't +need its licence key again (Cross Events never stored it). The heartbeat is already signed with the +install secret, so the Hub knows whose key it is. The reply says what happened in +`publicKeyStatus`: + +| `publicKeyStatus` | Meaning | +|-------------------|---------| +| `saved` | The Hub had no key for the install and saved this one; the church's other installs list it from their next heartbeat | +| `matches` | The Hub already has this key (line endings and surrounding whitespace don't count) | +| `mismatch` | The Hub has a **different** key and keeps it: an alert opens on the install, and Joshua can **Clear public key** on its page (two-factor again) when the server was restored or rebuilt; the next heartbeat then saves the new key | + +A key problem never fails the heartbeat: the licence keeps refreshing whatever happens to the key. +An install keeps sending `publicKey` until it gets `saved` or `matches`. A Hub before 2.2.0 ignores +the field (no `publicKeyStatus`), so the install isn't listed to its siblings until the Hub is +updated. Registering again with `protocolVersion: 2`, the product and a public key (same licence +and address: same install id, new secret) also works, as before. + +**Connecting two installs** (Settings → Linked products → Connect) is between the installs, not +through the Hub: `crosscode.link/1` in `@crosscode/contracts` (`src/link.ts`), with each side +checking the other against the `linkedProducts` it has cached from the Hub. diff --git a/package-lock.json b/package-lock.json index 33385a7..1c0ab05 100644 --- a/package-lock.json +++ b/package-lock.json @@ -90,6 +90,7 @@ "zod": "^4.6.7" }, "devDependencies": { + "@crosscode/seo": "*", "@types/express": "^5.0.6", "@types/jest": "^30.0.0", "@types/jsonwebtoken": "^9.0.10", diff --git a/scripts/products/events.sh b/scripts/products/events.sh index 9c7c144..c6b3f01 100644 --- a/scripts/products/events.sh +++ b/scripts/products/events.sh @@ -31,10 +31,27 @@ events_backup() { .catch(e => { console.error(" Backup failed: " + e.message); process.exit(1); });' } -# Only this app's workspaces, never the other products'. --include=dev: the TypeScript and Next -# builds need type and build packages even where NODE_ENV=production. +# The shared packages this checkout's Events uses (from 2.4.0: contracts and seo), built before it. +# Only the ones in the checkout, so going back to an older tag still installs and builds. +events_shared_packages() { + local p + for p in packages/contracts packages/seo; do + if [ -f "$1/$p/package.json" ] && grep -q "\"@crosscode/${p#packages/}\"" "$1/apps/events/backend/package.json" "$1/apps/events/frontend/package.json" 2>/dev/null; then + printf '%s\n' "$p" + fi + done +} + +# Only this app's workspaces (and the shared packages it uses), never the other products'. +# --include=dev: the TypeScript and Next builds need type and build packages even where +# NODE_ENV=production; --include-workspace-root for the packages' build tool (tsup). events_install_deps() { - run_as "$2" "$1" npm ci --include=dev --no-audit --no-fund -w apps/events/backend -w apps/events/frontend + local -a shared=() ws=() + local p + mapfile -t shared < <(events_shared_packages "$1") + for p in "${shared[@]}"; do ws+=(-w "$p"); done + if [ "${#shared[@]}" -gt 0 ]; then ws+=(--include-workspace-root); fi + run_as "$2" "$1" npm ci --include=dev --no-audit --no-fund "${ws[@]}" -w apps/events/backend -w apps/events/frontend } events_migrate() { @@ -47,6 +64,10 @@ events_pending_migrations() { } events_build() { + local p + while IFS= read -r p; do + run_as "$2" "$1/$p" npm run build || return 1 + done < <(events_shared_packages "$1") run_as "$2" "$(events_app "$1")/backend" npm run build && run_as "$2" "$(events_app "$1")/frontend" npm run build } diff --git a/scripts/tests/events.bats b/scripts/tests/events.bats new file mode 100644 index 0000000..48a8674 --- /dev/null +++ b/scripts/tests/events.bats @@ -0,0 +1,55 @@ +#!/usr/bin/env bats +# Cross Events' hooks that don't need a server: which shared packages a checkout builds first +# (contracts and seo from 2.4.0), and that an older checkout (2.3.x) builds without them. +# Run with `npm run test:scripts`. + +setup() { + # shellcheck source=../products/events.sh + source "$BATS_TEST_DIRNAME/../products/events.sh" + TMP="$BATS_TEST_TMPDIR" + CALLS="$TMP/calls" + : > "$CALLS" + # Record what would run, as the app user, instead of running it. + run_as() { local user="$1" dir="$2"; shift 2; echo "$user|${dir#"$TMP"/}|$*" >> "$CALLS"; } +} + +checkout() { + local dir="$TMP/$1"; shift + mkdir -p "$dir/apps/events/backend" "$dir/apps/events/frontend" "$dir/packages/contracts" "$dir/packages/seo" + echo '{"name":"@crosscode/contracts"}' > "$dir/packages/contracts/package.json" + echo '{"name":"@crosscode/seo"}' > "$dir/packages/seo/package.json" + printf '{"dependencies":{%s}}' "$1" > "$dir/apps/events/backend/package.json" + printf '{"dependencies":{%s}}' "$2" > "$dir/apps/events/frontend/package.json" +} + +@test "2.4.0: contracts and seo are installed and built before Events" { + checkout new '"@crosscode/contracts":"*"' '"@crosscode/contracts":"*","@crosscode/seo":"*"' + run events_shared_packages "$TMP/new" + [ "$output" = $'packages/contracts\npackages/seo' ] + + events_install_deps "$TMP/new" hope + grep -qx 'hope|new|npm ci --include=dev --no-audit --no-fund -w packages/contracts -w packages/seo --include-workspace-root -w apps/events/backend -w apps/events/frontend' "$CALLS" + + : > "$CALLS" + events_build "$TMP/new" hope + [ "$(cut -d'|' -f2 "$CALLS" | tr '\n' ' ')" = "new/packages/contracts new/packages/seo new/apps/events/backend new/apps/events/frontend " ] +} + +@test "2.3.x (no shared packages used): installed and built as before" { + checkout old '' '' + run events_shared_packages "$TMP/old" + [ -z "$output" ] + events_install_deps "$TMP/old" hope + grep -qx 'hope|old|npm ci --include=dev --no-audit --no-fund -w apps/events/backend -w apps/events/frontend' "$CALLS" + : > "$CALLS" + events_build "$TMP/old" hope + [ "$(cut -d'|' -f2 "$CALLS" | tr '\n' ' ')" = "old/apps/events/backend old/apps/events/frontend " ] +} + +@test "a failing package build stops before Events is built" { + checkout new '"@crosscode/contracts":"*"' '' + run_as() { echo "${2#"$TMP"/}" >> "$CALLS"; [[ "$2" != */packages/contracts ]]; } + run events_build "$TMP/new" hope + [ "$status" -ne 0 ] + [ "$(cat "$CALLS")" = "new/packages/contracts" ] +}