Files
crosscode-platform/packages/contracts/src/event.ts
T
joshuaandClaude Opus 5.5 ea1575f716 Contracts: event, event feed, church, identity, sign-in return, Hub protocol v2
- crosscode.event/1 and crosscode.event-feed/1 (feed, event.changed
  webhook), with session and registration rules; parseEventFeed skips
  and reports bad events instead of failing the whole feed.
- crosscode.church/1: branding, campuses, service times, contact, links.
- crosscode.identity/1: sign-in claims and the user.updated /
  user.deleted / user.export back-channel calls and replies.
- Sign-in return helpers (isSafeReturnPath, encodeState/decodeState,
  isRegisteredRedirectUri) so every product returns people to the page
  they came from in the same safe way.
- Hub protocol v2: product on register/heartbeat, stats per product,
  install public key, linked products, customerId/product in licences.
- @crosscode/contracts/signing (Node only): the Hub's HMAC scheme.
- Samples for every contract in samples/, checked by the tests (120).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-04 09:47:40 +02:00

194 lines
8.2 KiB
TypeScript

import { z } from "zod";
import { dateTimeSchema, eventProductSchema, idSchema, moneySchema, slugSchema, timezoneSchema, urlSchema } from "./common";
import { schemaName } from "./schema-name";
/**
* `crosscode.event/1` — the event every product publishes and reads (ROADMAP-v3 §4).
*
* Rules the schema enforces:
* - `sessions` is empty for a single-date event; otherwise `startsAt` / `endsAt` are the first
* start and the last end of the (non-cancelled) sessions.
* - Only Cross Events (`origin.product: "events"`) takes registrations, so only it may use
* `registration.mode: "origin"` or a `registration.status` other than `open`.
* - Public events only: nothing in here is personal information.
*/
export const EVENT_SCHEMA = schemaName("event", 1);
export const EVENT_FEED_SCHEMA = schemaName("event-feed", 1);
export const REGISTRATION_MODES = ["origin", "external", "contact", "none"] as const;
export const REGISTRATION_STATUSES = ["open", "not_open", "closed", "full", "waitlist"] as const;
export const EVENT_STATUSES = ["published", "cancelled"] as const;
const textLine = (max: number) => z.string().trim().min(1).max(max);
export const eventOriginSchema = z.object({
/** The product that owns the event. Only it can edit it (ROADMAP-v3 §1, rule 4). */
product: eventProductSchema,
/** The Hub install id of the origin. */
installId: idSchema,
/** The event's public page at the origin; imported copies link here. */
url: urlSchema,
});
export const eventSessionSchema = z.object({
id: idSchema,
label: z.string().trim().max(200).nullable(),
startsAt: dateTimeSchema,
endsAt: dateTimeSchema,
/** Only when it differs from the event's location. */
location: z.string().trim().max(300).nullable(),
cancelled: z.boolean(),
});
export const eventLocationSchema = z.object({
name: z.string().trim().max(200).nullable(),
address: z.string().trim().max(500).nullable(),
onlineUrl: urlSchema.nullable(),
});
export const eventCampusSchema = z.object({ slug: slugSchema, name: textLine(200) });
export const eventSeriesSchema = z.object({ id: idSchema, name: textLine(200) });
export const eventRegistrationSchema = z.object({
/** `origin`: register at the origin (Events only) · `external`: a link · `contact`: instructions in the description · `none`. */
mode: z.enum(REGISTRATION_MODES),
/** Where to register: the origin's page (`origin`) or the external link (`external`). `null` otherwise. */
url: urlSchema.nullable(),
status: z.enum(REGISTRATION_STATUSES),
opensAt: dateTimeSchema.nullable(),
closesAt: dateTimeSchema.nullable(),
/** The lowest current price, or `null` for free / not applicable. */
priceFrom: moneySchema.nullable(),
});
const eventObject = z.object({
schema: z.literal(EVENT_SCHEMA),
/** The origin's id for the event. With `origin.product` it identifies the event everywhere. */
id: idSchema,
origin: eventOriginSchema,
status: z.enum(EVENT_STATUSES),
updatedAt: dateTimeSchema,
title: textLine(200),
summary: z.string().trim().max(300).nullable(),
/** Sanitised markdown. Consumers render it as markdown with HTML switched off. */
description: z.string().max(20000).nullable(),
imageUrl: urlSchema.nullable(),
timezone: timezoneSchema,
startsAt: dateTimeSchema,
endsAt: dateTimeSchema,
allDay: z.boolean(),
sessions: z.array(eventSessionSchema).max(500),
location: eventLocationSchema.nullable(),
/** `null` = all campuses, or campuses are switched off. */
campus: eventCampusSchema.nullable(),
series: eventSeriesSchema.nullable(),
tags: z.array(slugSchema).max(20),
registration: eventRegistrationSchema,
});
export const eventSchema = eventObject.superRefine((event, ctx) => {
const issue = (path: (string | number)[], message: string) => ctx.addIssue({ code: "custom", path, message });
if (Date.parse(event.endsAt) < Date.parse(event.startsAt)) issue(["endsAt"], "endsAt is before startsAt");
event.sessions.forEach((s, i) => {
if (Date.parse(s.endsAt) < Date.parse(s.startsAt)) issue(["sessions", i, "endsAt"], "Session ends before it starts");
});
const live = event.sessions.filter((s) => !s.cancelled);
if (live.length > 0) {
const first = Math.min(...live.map((s) => Date.parse(s.startsAt)));
const last = Math.max(...live.map((s) => Date.parse(s.endsAt)));
if (Date.parse(event.startsAt) !== first) issue(["startsAt"], "startsAt must be the first session's start");
if (Date.parse(event.endsAt) !== last) issue(["endsAt"], "endsAt must be the last session's end");
}
const { registration: r, origin } = event;
if (origin.product !== "events") {
if (r.mode === "origin") issue(["registration", "mode"], "Only Cross Events takes registrations (mode \"origin\")");
if (r.status !== "open") issue(["registration", "status"], "Only Cross Events sends a registration status other than \"open\"");
}
if ((r.mode === "origin" || r.mode === "external") && r.url === null) issue(["registration", "url"], `A "${r.mode}" registration needs a url`);
if ((r.mode === "contact" || r.mode === "none") && r.url !== null) issue(["registration", "url"], `A "${r.mode}" registration has no url`);
if (r.opensAt && r.closesAt && Date.parse(r.closesAt) < Date.parse(r.opensAt)) issue(["registration", "closesAt"], "closesAt is before opensAt");
});
export type CrosscodeEvent = z.infer<typeof eventSchema>;
export type EventSession = z.infer<typeof eventSessionSchema>;
export type EventRegistration = z.infer<typeof eventRegistrationSchema>;
/** An event that was unpublished or deleted at the origin since `updatedSince`. */
export const deletedEventSchema = z.object({
id: idSchema,
deletedAt: dateTimeSchema,
});
/**
* `GET /api/feed/v1/events?updatedSince=<ISO>` → `crosscode.event-feed/1`.
*
* `events` is checked one by one with {@link parseEventFeed}: a single bad event is skipped and
* reported, it never blocks the rest of the feed (ROADMAP-v3 §4, "one failing source never blocks
* another" applies within a feed too).
*/
export const eventFeedSchema = z.object({
schema: z.literal(EVENT_FEED_SCHEMA),
generatedAt: dateTimeSchema,
events: z.array(eventSchema),
deleted: z.array(deletedEventSchema),
});
export type EventFeed = z.infer<typeof eventFeedSchema>;
const feedEnvelopeSchema = eventFeedSchema.extend({ events: z.array(z.unknown()) });
export interface RejectedEvent {
index: number;
/** The event's id, when it had a readable one. */
id: string | null;
issues: z.core.$ZodIssue[];
}
export type ParseEventFeedResult =
| { ok: true; feed: EventFeed; rejected: RejectedEvent[] }
| { ok: false; error: z.ZodError };
/**
* Parses a feed response. The envelope must be valid; each event is checked on its own, and
* invalid ones are left out and listed in `rejected` so the consumer can log them.
*/
export function parseEventFeed(input: unknown): ParseEventFeedResult {
const envelope = feedEnvelopeSchema.safeParse(input);
if (!envelope.success) return { ok: false, error: envelope.error };
const events: CrosscodeEvent[] = [];
const rejected: RejectedEvent[] = [];
envelope.data.events.forEach((raw, index) => {
const parsed = eventSchema.safeParse(raw);
if (parsed.success) events.push(parsed.data);
else {
const id = typeof raw === "object" && raw !== null && typeof (raw as { id?: unknown }).id === "string" ? (raw as { id: string }).id : null;
rejected.push({ index, id, issues: parsed.error.issues });
}
});
return { ok: true, feed: { ...envelope.data, events }, rejected };
}
/**
* The `event.changed` webhook: the origin tells a linked consumer to fetch its feed now instead
* of waiting for the 15-minute poll. Signed with the link's secret (`LINK_HEADERS`). `eventIds`
* is a hint; the consumer always fetches `?updatedSince=` its last sync.
*/
export const eventChangedSchema = z.object({
schema: z.literal(EVENT_FEED_SCHEMA),
type: z.literal("event.changed"),
occurredAt: dateTimeSchema,
eventIds: z.array(idSchema).max(100),
});
export type EventChanged = z.infer<typeof eventChangedSchema>;
/** The key that identifies an event across products: `origin.product` + `id` (ROADMAP-v3 §4, "No duplicates"). */
export function eventKey(event: Pick<CrosscodeEvent, "id" | "origin">): string {
return `${event.origin.product}:${event.id}`;
}