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:
Generated
+13
-1
@@ -911,6 +911,10 @@
|
|||||||
"resolved": "apps/events/frontend",
|
"resolved": "apps/events/frontend",
|
||||||
"link": true
|
"link": true
|
||||||
},
|
},
|
||||||
|
"node_modules/@crosscode/seo": {
|
||||||
|
"resolved": "packages/seo",
|
||||||
|
"link": true
|
||||||
|
},
|
||||||
"node_modules/@crosscode/ui": {
|
"node_modules/@crosscode/ui": {
|
||||||
"resolved": "packages/ui",
|
"resolved": "packages/ui",
|
||||||
"link": true
|
"link": true
|
||||||
@@ -19652,7 +19656,7 @@
|
|||||||
},
|
},
|
||||||
"packages/contracts": {
|
"packages/contracts": {
|
||||||
"name": "@crosscode/contracts",
|
"name": "@crosscode/contracts",
|
||||||
"version": "1.3.0",
|
"version": "1.4.0",
|
||||||
"license": "UNLICENSED",
|
"license": "UNLICENSED",
|
||||||
"dependencies": {
|
"dependencies": {
|
||||||
"zod": "^4.6.7"
|
"zod": "^4.6.7"
|
||||||
@@ -19686,6 +19690,14 @@
|
|||||||
"dev": true,
|
"dev": true,
|
||||||
"license": "MIT"
|
"license": "MIT"
|
||||||
},
|
},
|
||||||
|
"packages/seo": {
|
||||||
|
"name": "@crosscode/seo",
|
||||||
|
"version": "1.0.0",
|
||||||
|
"license": "UNLICENSED",
|
||||||
|
"dependencies": {
|
||||||
|
"@crosscode/contracts": "*"
|
||||||
|
}
|
||||||
|
},
|
||||||
"packages/ui": {
|
"packages/ui": {
|
||||||
"name": "@crosscode/ui",
|
"name": "@crosscode/ui",
|
||||||
"version": "0.0.0"
|
"version": "0.0.0"
|
||||||
|
|||||||
@@ -0,0 +1,16 @@
|
|||||||
|
# @crosscode/seo
|
||||||
|
|
||||||
|
The schema.org JSON-LD builders and meta helpers every public Cross Code site uses (ROADMAP-v3
|
||||||
|
§11), built on `@crosscode/contracts`. Events, the Church Website and the Church App produce the
|
||||||
|
same search data from the same `crosscode.event/1` and `crosscode.church/1`.
|
||||||
|
|
||||||
|
| Export | What |
|
||||||
|
|--------|------|
|
||||||
|
| `eventJsonLd(event, opts)` | `Event` from a `crosscode.event/1`: status, attendance mode, `Place` / `VirtualLocation`, `offers` from `registration` (a price range when the origin passes `priceRange`), sessions as `subEvent`. **Only the origin's page** carries it; an imported copy has a canonical link to the origin instead |
|
||||||
|
| `churchJsonLd(church, opts)` | `Church` from a `crosscode.church/1`: address, geo, phone, logo, service times, social links, campuses as `department` |
|
||||||
|
| `canonicalUrl(base, path)` | Absolute, without tracking parameters (`src`, `utm_*`, `fbclid`, …), `#…` or a trailing slash |
|
||||||
|
| `pageMeta({ title, description })` | Title and description as search engines show them (60 / 155 characters) and warnings for an editor |
|
||||||
|
| `jsonLdString(data)` | JSON for `<script type="application/ld+json">`, safe against `</script>` |
|
||||||
|
|
||||||
|
Pure functions, no framework. CommonJS and ESM like contracts. It's a workspace, versioned with
|
||||||
|
the apps that use it (it isn't tagged on its own).
|
||||||
@@ -0,0 +1,7 @@
|
|||||||
|
module.exports = {
|
||||||
|
testEnvironment: "node",
|
||||||
|
testMatch: ["<rootDir>/tests/**/*.test.ts"],
|
||||||
|
transform: { "^.+\\.ts$": ["ts-jest", { tsconfig: { module: "commonjs", moduleResolution: "node", isolatedModules: true } }] },
|
||||||
|
moduleFileExtensions: ["ts", "js", "json"],
|
||||||
|
modulePathIgnorePatterns: ["<rootDir>/dist/"],
|
||||||
|
};
|
||||||
@@ -0,0 +1,37 @@
|
|||||||
|
{
|
||||||
|
"name": "@crosscode/seo",
|
||||||
|
"version": "1.0.0",
|
||||||
|
"private": true,
|
||||||
|
"description": "schema.org JSON-LD and meta helpers every public Cross Code site uses, built on @crosscode/contracts (ROADMAP-v3 §11)",
|
||||||
|
"license": "UNLICENSED",
|
||||||
|
"type": "commonjs",
|
||||||
|
"main": "./dist/index.js",
|
||||||
|
"module": "./dist/index.mjs",
|
||||||
|
"types": "./dist/index.d.ts",
|
||||||
|
"exports": {
|
||||||
|
".": {
|
||||||
|
"import": {
|
||||||
|
"types": "./dist/index.d.mts",
|
||||||
|
"default": "./dist/index.mjs"
|
||||||
|
},
|
||||||
|
"require": {
|
||||||
|
"types": "./dist/index.d.ts",
|
||||||
|
"default": "./dist/index.js"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"./package.json": "./package.json"
|
||||||
|
},
|
||||||
|
"files": [
|
||||||
|
"dist",
|
||||||
|
"README.md"
|
||||||
|
],
|
||||||
|
"sideEffects": false,
|
||||||
|
"scripts": {
|
||||||
|
"build": "tsup",
|
||||||
|
"typecheck": "tsc -p tsconfig.json --noEmit",
|
||||||
|
"test": "jest"
|
||||||
|
},
|
||||||
|
"dependencies": {
|
||||||
|
"@crosscode/contracts": "*"
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -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 } : {}),
|
||||||
|
};
|
||||||
|
}),
|
||||||
|
}
|
||||||
|
: {}),
|
||||||
|
};
|
||||||
|
}
|
||||||
@@ -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 } : {}),
|
||||||
|
})),
|
||||||
|
}
|
||||||
|
: {}),
|
||||||
|
};
|
||||||
|
}
|
||||||
@@ -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";
|
||||||
@@ -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");
|
||||||
|
}
|
||||||
@@ -0,0 +1,141 @@
|
|||||||
|
import { readFileSync } from "node:fs";
|
||||||
|
import { join } from "node:path";
|
||||||
|
import { churchSchema, eventSchema, type Church, type CrosscodeEvent } from "@crosscode/contracts";
|
||||||
|
import { canonicalUrl, churchJsonLd, eventJsonLd, jsonLdString, pageMeta, truncate } from "../src";
|
||||||
|
|
||||||
|
const SAMPLES = join(__dirname, "..", "..", "contracts", "samples");
|
||||||
|
const sample = <T>(file: string): T => JSON.parse(readFileSync(join(SAMPLES, file), "utf8")) as T;
|
||||||
|
const event = () => eventSchema.parse(sample("event.json")) as CrosscodeEvent;
|
||||||
|
const simple = () => eventSchema.parse(sample("event-simple.json")) as CrosscodeEvent;
|
||||||
|
const church = () => churchSchema.parse(sample("church.json")) as Church;
|
||||||
|
|
||||||
|
describe("eventJsonLd", () => {
|
||||||
|
it("builds an Event from crosscode.event/1", () => {
|
||||||
|
const ld = eventJsonLd(event(), { organizer: { name: "Hope Family Church", url: "https://events.hopefamily.co.za" } });
|
||||||
|
expect(ld).toMatchObject({
|
||||||
|
"@context": "https://schema.org",
|
||||||
|
"@type": "Event",
|
||||||
|
name: "Youth Camp 2027",
|
||||||
|
startDate: "2027-03-14T06:00:00.000Z",
|
||||||
|
endDate: "2027-03-16T12:00:00.000Z",
|
||||||
|
eventStatus: "https://schema.org/EventScheduled",
|
||||||
|
eventAttendanceMode: "https://schema.org/OfflineEventAttendanceMode",
|
||||||
|
location: { "@type": "Place", name: "Camp Wartburg", address: "R103, Wartburg, KwaZulu-Natal" },
|
||||||
|
url: "https://events.hopefamily.co.za/events/youth-camp",
|
||||||
|
organizer: { "@type": "Organization", name: "Hope Family Church" },
|
||||||
|
offers: { "@type": "Offer", price: "450.00", priceCurrency: "ZAR", availability: "https://schema.org/InStock" },
|
||||||
|
});
|
||||||
|
expect((ld.subEvent as unknown[]).length).toBe(3);
|
||||||
|
});
|
||||||
|
|
||||||
|
it("gives a price range when the origin knows it", () => {
|
||||||
|
const ld = eventJsonLd(event(), { priceRange: { lowCents: 45000, highCents: 90000 } });
|
||||||
|
expect(ld.offers).toMatchObject({ "@type": "AggregateOffer", lowPrice: "450.00", highPrice: "900.00" });
|
||||||
|
});
|
||||||
|
|
||||||
|
it("marks full and waitlisted events sold out, and cancelled ones cancelled", () => {
|
||||||
|
const e = event();
|
||||||
|
e.registration.status = "full";
|
||||||
|
e.status = "cancelled";
|
||||||
|
const ld = eventJsonLd(e);
|
||||||
|
expect((ld.offers as Record<string, unknown>).availability).toBe("https://schema.org/SoldOut");
|
||||||
|
expect(ld.eventStatus).toBe("https://schema.org/EventCancelled");
|
||||||
|
});
|
||||||
|
|
||||||
|
it("has no offer for contact-only events, or for an external link without a price", () => {
|
||||||
|
const e = event();
|
||||||
|
e.registration = { mode: "contact", url: null, status: "open", opensAt: null, closesAt: null, priceFrom: null };
|
||||||
|
expect(eventJsonLd(e).offers).toBeUndefined();
|
||||||
|
e.registration = { mode: "external", url: "https://example.org/tickets", status: "open", opensAt: null, closesAt: null, priceFrom: null };
|
||||||
|
expect(eventJsonLd(e).offers).toBeUndefined();
|
||||||
|
});
|
||||||
|
|
||||||
|
it("offers a free origin registration at 0.00", () => {
|
||||||
|
const e = event();
|
||||||
|
e.registration.priceFrom = null;
|
||||||
|
expect(eventJsonLd(e).offers).toMatchObject({ "@type": "Offer", price: "0.00" });
|
||||||
|
});
|
||||||
|
|
||||||
|
it("describes online and mixed events", () => {
|
||||||
|
const e = event();
|
||||||
|
e.location = { name: null, address: null, onlineUrl: "https://youtube.com/live/x" };
|
||||||
|
expect(eventJsonLd(e)).toMatchObject({ eventAttendanceMode: "https://schema.org/OnlineEventAttendanceMode", location: { "@type": "VirtualLocation" } });
|
||||||
|
e.location = { name: "Main hall", address: null, onlineUrl: "https://youtube.com/live/x" };
|
||||||
|
const ld = eventJsonLd(e);
|
||||||
|
expect(ld.eventAttendanceMode).toBe("https://schema.org/MixedEventAttendanceMode");
|
||||||
|
expect(ld.location).toEqual([
|
||||||
|
{ "@type": "Place", name: "Main hall", address: "Main hall" },
|
||||||
|
{ "@type": "VirtualLocation", url: "https://youtube.com/live/x" },
|
||||||
|
]);
|
||||||
|
});
|
||||||
|
|
||||||
|
it("works for a simple event from another product", () => {
|
||||||
|
const ld = eventJsonLd(simple());
|
||||||
|
expect(ld["@type"]).toBe("Event");
|
||||||
|
expect(ld.subEvent).toBeUndefined();
|
||||||
|
});
|
||||||
|
|
||||||
|
it("leaves cancelled sessions out of the dates", () => {
|
||||||
|
const e = event();
|
||||||
|
e.sessions[1]!.cancelled = true;
|
||||||
|
expect((eventJsonLd(e).subEvent as unknown[]).length).toBe(2);
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
describe("churchJsonLd", () => {
|
||||||
|
it("builds a Church with address, geo, service times and social links", () => {
|
||||||
|
const ld = churchJsonLd(church());
|
||||||
|
expect(ld).toMatchObject({
|
||||||
|
"@type": "Church",
|
||||||
|
name: "Hope Family Church",
|
||||||
|
alternateName: "Hope Family",
|
||||||
|
url: "https://www.hopefamily.co.za",
|
||||||
|
logo: "https://www.hopefamily.co.za/uploads/logo.png",
|
||||||
|
email: "office@hopefamily.co.za",
|
||||||
|
telephone: "+27161234567",
|
||||||
|
address: { "@type": "PostalAddress", streetAddress: "12 Church Street", addressLocality: "Meyerton Central, Meyerton", postalCode: "1961", addressCountry: "ZA" },
|
||||||
|
geo: { latitude: -26.5559, longitude: 28.0141 },
|
||||||
|
sameAs: ["https://www.facebook.com/hopefamilychurch", "https://www.youtube.com/@hopefamilychurch"],
|
||||||
|
});
|
||||||
|
expect((ld.openingHoursSpecification as unknown[]).length).toBe(2);
|
||||||
|
expect(ld.department).toBeUndefined();
|
||||||
|
});
|
||||||
|
|
||||||
|
it("lists each campus when there are several", () => {
|
||||||
|
const c = church();
|
||||||
|
c.campuses.push({ slug: "vereeniging", name: "Vereeniging", address: null });
|
||||||
|
const ld = churchJsonLd(c);
|
||||||
|
expect(ld.department).toEqual([
|
||||||
|
expect.objectContaining({ name: "Hope Family Church Meyerton" }),
|
||||||
|
{ "@type": "Church", name: "Hope Family Church Vereeniging" },
|
||||||
|
]);
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
describe("meta", () => {
|
||||||
|
it.each([
|
||||||
|
["https://e.co.za", "/events/1?src=whatsapp&utm_source=fb", "https://e.co.za/events/1"],
|
||||||
|
["https://e.co.za/", "/events/1/", "https://e.co.za/events/1"],
|
||||||
|
["https://e.co.za", "/", "https://e.co.za/"],
|
||||||
|
["https://e.co.za", "/events?campus=b&page=2&gclid=x#top", "https://e.co.za/events?campus=b&page=2"],
|
||||||
|
])("canonicalUrl(%s, %s)", (base, path, expected) => {
|
||||||
|
expect(canonicalUrl(base, path)).toBe(expected);
|
||||||
|
});
|
||||||
|
|
||||||
|
it("truncates at a word boundary", () => {
|
||||||
|
expect(truncate("Three days of worship, teaching and adventure", 30)).toBe("Three days of worship…");
|
||||||
|
expect(truncate("short", 30)).toBe("short");
|
||||||
|
});
|
||||||
|
|
||||||
|
it("warns about missing and long titles and descriptions", () => {
|
||||||
|
expect(pageMeta({ title: "", description: "" }).warnings).toEqual(["title_missing", "description_missing"]);
|
||||||
|
const long = pageMeta({ title: "x".repeat(61), description: "word ".repeat(40) });
|
||||||
|
expect(long.warnings).toEqual(["title_too_long", "description_too_long"]);
|
||||||
|
expect(long.description.length).toBeLessThanOrEqual(155);
|
||||||
|
expect(pageMeta({ title: "Home", description: null, fallbackDescription: "Hope Family Church" }).description).toBe("Hope Family Church");
|
||||||
|
});
|
||||||
|
|
||||||
|
it("makes JSON-LD safe inside a script tag", () => {
|
||||||
|
expect(jsonLdString({ name: "</script><script>alert(1)</script>" })).not.toContain("</script>");
|
||||||
|
});
|
||||||
|
});
|
||||||
@@ -0,0 +1,8 @@
|
|||||||
|
{
|
||||||
|
"extends": "../../tsconfig.base.json",
|
||||||
|
"compilerOptions": {
|
||||||
|
"rootDir": ".",
|
||||||
|
"types": ["node", "jest"]
|
||||||
|
},
|
||||||
|
"include": ["src", "tests", "tsup.config.ts"]
|
||||||
|
}
|
||||||
@@ -0,0 +1,13 @@
|
|||||||
|
import { defineConfig } from "tsup";
|
||||||
|
|
||||||
|
// CommonJS for the Events backend, ESM for the Next.js apps, types for both (as contracts).
|
||||||
|
export default defineConfig({
|
||||||
|
entry: ["src/index.ts"],
|
||||||
|
format: ["cjs", "esm"],
|
||||||
|
dts: true,
|
||||||
|
sourcemap: true,
|
||||||
|
clean: true,
|
||||||
|
target: "es2022",
|
||||||
|
external: ["@crosscode/contracts"],
|
||||||
|
outExtension: ({ format }) => ({ js: format === "esm" ? ".mjs" : ".js" }),
|
||||||
|
});
|
||||||
Reference in New Issue
Block a user