packages/seo: schema.org JSON-LD and meta helpers on @crosscode/contracts

eventJsonLd (crosscode.event/1), churchJsonLd (crosscode.church/1),
canonicalUrl, pageMeta and jsonLdString (ROADMAP-v3 §11).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
2026-11-18 12:01:20 +02:00
co-authored by Claude Opus 5.5
parent 4952e2cb0f
commit 390b80e56e
11 changed files with 496 additions and 1 deletions
+78
View File
@@ -0,0 +1,78 @@
import type { Address, Church } from "@crosscode/contracts";
/**
* schema.org `Church` JSON-LD (an `Organization` and a `Place`) from a `crosscode.church/1`, for
* a church's home and contact pages, so it shows up in local search and maps (ROADMAP-v3 §11).
*/
type JsonLd = Record<string, unknown>;
const DAYS: Record<string, string> = {
monday: "Monday",
tuesday: "Tuesday",
wednesday: "Wednesday",
thursday: "Thursday",
friday: "Friday",
saturday: "Saturday",
sunday: "Sunday",
};
function postalAddress(a: Address): JsonLd {
return {
"@type": "PostalAddress",
streetAddress: [a.line1, a.line2].filter(Boolean).join(", "),
...(a.suburb || a.city ? { addressLocality: a.suburb ? `${a.suburb}, ${a.city}` : a.city } : {}),
...(a.province ? { addressRegion: a.province } : {}),
...(a.postalCode ? { postalCode: a.postalCode } : {}),
addressCountry: a.country,
};
}
function geo(a: Address | null | undefined): JsonLd | undefined {
return a?.geo ? { "@type": "GeoCoordinates", latitude: a.geo.lat, longitude: a.geo.lng } : undefined;
}
export interface ChurchJsonLdOptions {
/** The page's own address (the church's home page by default: `links.website`). */
url?: string;
}
export function churchJsonLd(church: Church, opts: ChurchJsonLdOptions = {}): JsonLd {
// The church's main address: its contact address, else its only (or first) campus's.
const main = church.contact.address ?? church.campuses.find((c) => c.address)?.address ?? null;
const url = opts.url ?? church.links.website ?? church.links.events ?? undefined;
const mainGeo = geo(main);
const services = church.serviceTimes.filter((s) => !s.campus || church.campuses.length <= 1);
return {
"@context": "https://schema.org",
"@type": "Church",
name: church.name,
...(church.shortName ? { alternateName: church.shortName } : {}),
...(url ? { url } : {}),
...(church.branding.logoUrl ? { logo: church.branding.logoUrl, image: church.branding.logoUrl } : {}),
...(church.contact.email ? { email: church.contact.email } : {}),
...(church.contact.phone ? { telephone: church.contact.phone } : {}),
...(main ? { address: postalAddress(main) } : {}),
...(mainGeo ? { geo: mainGeo } : {}),
...(church.social.length > 0 ? { sameAs: church.social.map((s) => s.url) } : {}),
// Service times: when the doors are open, as Google reads it for a place.
...(services.length > 0
? { openingHoursSpecification: services.map((s) => ({ "@type": "OpeningHoursSpecification", dayOfWeek: `https://schema.org/${DAYS[s.day]}`, opens: s.time, ...(s.label ? { name: s.label } : {}) })) }
: {}),
// Several campuses: each one a place of its own.
...(church.campuses.length > 1
? {
department: church.campuses.map((c) => {
const g = geo(c.address);
return {
"@type": "Church",
name: `${church.name} ${c.name}`,
...(c.address ? { address: postalAddress(c.address) } : {}),
...(g ? { geo: g } : {}),
};
}),
}
: {}),
};
}
+114
View File
@@ -0,0 +1,114 @@
import type { CrosscodeEvent } from "@crosscode/contracts";
/**
* schema.org `Event` JSON-LD from a `crosscode.event/1`, the same for every product (ROADMAP-v3
* §11), so Google can show the event with its date, venue and ticket link. Checked with
* https://search.google.com/test/rich-results.
*
* Only the **origin** of an event puts this on its page. An imported copy has a canonical link to
* the origin instead and no JSON-LD, so search engines see one event, not one per product.
*/
export interface Organizer {
name: string;
url: string;
}
export interface EventJsonLdOptions {
/** The page this JSON-LD is on. Defaults to `event.origin.url`. */
pageUrl?: string;
/** The church (or the site's organisation) running the event. */
organizer?: Organizer;
/**
* The origin's own price range, in cents. `crosscode.event/1` only carries the lowest price,
* but the origin knows the highest too, and Google shows a range (`AggregateOffer`).
*/
priceRange?: { lowCents: number; highCents: number };
/** Where the ticket offer points. Defaults to `registration.url`. */
offerUrl?: string;
/** When tickets went (or go) on sale. Defaults to `registration.opensAt`. */
validFrom?: string | null;
}
type JsonLd = Record<string, unknown>;
const SCHEMA = "https://schema.org/";
const rand = (cents: number) => (cents / 100).toFixed(2);
function attendanceMode(event: CrosscodeEvent): string {
const online = Boolean(event.location?.onlineUrl);
const inPerson = Boolean(event.location?.name || event.location?.address);
if (online && inPerson) return `${SCHEMA}MixedEventAttendanceMode`;
if (online) return `${SCHEMA}OnlineEventAttendanceMode`;
return `${SCHEMA}OfflineEventAttendanceMode`;
}
function location(event: CrosscodeEvent): JsonLd | JsonLd[] | undefined {
const l = event.location;
if (!l) return undefined;
const places: JsonLd[] = [];
if (l.name || l.address) {
// Google wants an address; an event with only a place name uses the name for both.
places.push({ "@type": "Place", name: l.name ?? l.address, address: l.address ?? l.name });
}
if (l.onlineUrl) places.push({ "@type": "VirtualLocation", url: l.onlineUrl });
if (places.length === 0) return undefined;
return places.length === 1 ? places[0] : places;
}
function offers(event: CrosscodeEvent, opts: EventJsonLdOptions): JsonLd | undefined {
const r = event.registration;
// Contact-only and no-registration events have no tickets to offer.
if (r.mode === "contact" || r.mode === "none") return undefined;
// An external link without a price has nothing Google can show as an offer.
if (r.mode === "external" && !r.priceFrom && !opts.priceRange) return undefined;
const low = opts.priceRange?.lowCents ?? r.priceFrom?.amountCents ?? 0;
const high = opts.priceRange?.highCents ?? low;
const soldOut = r.status === "full" || r.status === "waitlist";
const validFrom = opts.validFrom === undefined ? r.opensAt : opts.validFrom;
const url = opts.offerUrl ?? r.url;
return {
"@type": low === high ? "Offer" : "AggregateOffer",
...(low === high ? { price: rand(low) } : { lowPrice: rand(low), highPrice: rand(high) }),
priceCurrency: r.priceFrom?.currency ?? "ZAR",
availability: soldOut ? `${SCHEMA}SoldOut` : `${SCHEMA}InStock`,
...(url ? { url } : {}),
...(validFrom ? { validFrom: new Date(validFrom).toISOString() } : {}),
};
}
export function eventJsonLd(event: CrosscodeEvent, opts: EventJsonLdOptions = {}): JsonLd {
const live = event.sessions.filter((s) => !s.cancelled);
const offer = offers(event, opts);
const place = location(event);
return {
"@context": "https://schema.org",
"@type": "Event",
name: event.title,
...(event.description ? { description: event.description.slice(0, 5000) } : event.summary ? { description: event.summary } : {}),
startDate: new Date(event.startsAt).toISOString(),
endDate: new Date(event.endsAt).toISOString(),
eventStatus: event.status === "cancelled" ? `${SCHEMA}EventCancelled` : `${SCHEMA}EventScheduled`,
eventAttendanceMode: attendanceMode(event),
...(place ? { location: place } : {}),
...(event.imageUrl ? { image: [event.imageUrl] } : {}),
url: opts.pageUrl ?? event.origin.url,
...(opts.organizer ? { organizer: { "@type": "Organization", name: opts.organizer.name, url: opts.organizer.url } } : {}),
...(offer ? { offers: offer } : {}),
// A multi-day event: each date as a sub-event, so Google can list the dates.
...(live.length > 1
? {
subEvent: live.map((s) => ({
"@type": "Event",
name: s.label ? `${event.title}: ${s.label}` : event.title,
startDate: new Date(s.startsAt).toISOString(),
endDate: new Date(s.endsAt).toISOString(),
...(s.location ? { location: { "@type": "Place", name: s.location, address: s.location } } : place ? { location: place } : {}),
})),
}
: {}),
};
}
+8
View File
@@ -0,0 +1,8 @@
/**
* @crosscode/seo — the schema.org JSON-LD builders and meta helpers every public Cross Code site
* uses (ROADMAP-v3 §11), built on `@crosscode/contracts` so Events, the Website and the App
* produce the same data from the same `crosscode.event/1` and `crosscode.church/1`.
*/
export * from "./event";
export * from "./church";
export * from "./meta";
+61
View File
@@ -0,0 +1,61 @@
/**
* Meta helpers every public Cross Code site uses (ROADMAP-v3 §11, "The baseline").
*/
/** Query parameters that only track where a visitor came from; never part of a canonical URL. */
const TRACKING = /^(utm_[a-z_]+|src|fbclid|gclid|gbraid|wbraid|msclkid|mc_cid|mc_eid|ref)$/i;
/**
* The canonical address of a page: absolute, without tracking parameters or a `#…`, and without
* a trailing slash (except the home page).
*/
export function canonicalUrl(base: string, path = "/"): string {
const url = new URL(path, base.endsWith("/") ? base : `${base}/`);
for (const key of [...url.searchParams.keys()]) if (TRACKING.test(key)) url.searchParams.delete(key);
url.hash = "";
if (url.pathname.length > 1) url.pathname = url.pathname.replace(/\/+$/, "");
url.searchParams.sort();
return url.toString();
}
export const TITLE_MAX = 60;
export const DESCRIPTION_MAX = 155;
/** Cuts text at a word boundary to `max` characters, with an ellipsis when it was cut. */
export function truncate(text: string, max: number): string {
const clean = text.replace(/\s+/g, " ").trim();
if (clean.length <= max) return clean;
const cut = clean.slice(0, max - 1);
const space = cut.lastIndexOf(" ");
return `${(space > max * 0.6 ? cut.slice(0, space) : cut).replace(/[\s,.;:–-]+$/, "")}…`;
}
export type MetaWarning = "title_missing" | "title_too_long" | "description_missing" | "description_too_long";
export interface PageMeta {
title: string;
description: string;
/** What an editor should fix (the Website's SEO panel shows these). */
warnings: MetaWarning[];
}
/** A page's title and description as search engines will show them, with warnings. */
export function pageMeta(input: { title?: string | null; description?: string | null; fallbackDescription?: string }): PageMeta {
const title = (input.title ?? "").replace(/\s+/g, " ").trim();
const raw = (input.description ?? "").trim();
const warnings: MetaWarning[] = [];
if (!title) warnings.push("title_missing");
else if (title.length > TITLE_MAX) warnings.push("title_too_long");
if (!raw) warnings.push("description_missing");
else if (raw.replace(/\s+/g, " ").length > DESCRIPTION_MAX) warnings.push("description_too_long");
return {
title,
description: truncate(raw || input.fallbackDescription || "", DESCRIPTION_MAX),
warnings,
};
}
/** JSON for a `<script type="application/ld+json">`, safe against `</script>` in the text. */
export function jsonLdString(data: unknown): string {
return JSON.stringify(data).replace(/</g, "\\u003c");
}