Merge branch 'feat/contracts-1.20'

This commit is contained in:
2026-11-30 09:54:45 +02:00
39 changed files with 2993 additions and 15 deletions
+33
View File
@@ -2,6 +2,39 @@
Each package and app has its own section and its own tags (`contracts@1.0.0`, `accounts@1.0.0`, …). Each package and app has its own section and its own tags (`contracts@1.0.0`, `accounts@1.0.0`, …).
## contracts@1.20.0 - 2026-11-30
The contracts for Church App 1.0.0 (docs/APP-1.0-PLAN.md §12), the first step of phase 6. Additive:
products on 1.19.0 keep working. Accounts refuses the two new requests (`INVALID_REQUEST`) until
Accounts 1.9.0 answers them.
- **`crosscode.devotional/1`** (`src/devotional.ts`): `devotionalSchema` (date, title, the passage
with its text and translation, body, prayer, author, `source` `crosscode` or `church`),
`devotionalsReplySchema` (the Hub's `GET /api/v2/devotionals?from=`, Cross Code's only),
`CROSSCODE_DEVOTIONALS_AHEAD_MONTHS` (3). **CSV import** shared by the Hub and the App:
`DEVOTIONAL_CSV_COLUMNS`, `parseCsv` (quotes, line breaks, BOM, `;` files), `checkDevotionalCsv`
(each row's errors by column, warnings, days already taken, a `latestDate` limit, dates twice in
the file), `devotionalCsv`, `DEVOTIONAL_CSV_TEMPLATE`.
- **Bible passages** (`src/bible.ts`): `BIBLE_TRANSLATIONS` (NLT, ESV, NIV, NKJV, KJV, AFR53, AFR83,
each with its YouVersion id and copyright line), `BIBLE_BOOKS` (USFM codes, English and Afrikaans
names, abbreviations, chapters), `parseBibleReference` ("Johannes 3:16–18", "1 Kor. 13:4-7",
"Rom 8:38-9:1", "Jude 3"), `formatBibleReference`, `passageVerseCount`, `youVersionUrl`,
`PASSAGE_WARN_VERSES` (25).
- **Identity requests:** `messaging.get` (the church's SMTP and WAWP settings for the App, secrets
sealed with the link's secret; `messagingGetReplySchema`) and the `messaging.changed` hint
Accounts sends back (`MESSAGING_CHANGED_PATH`); `whatsapp.optout` (a STOP received by any
product; `whatsappOptOutReplySchema`). `whatsapp_opted_out` (optional) in the profile that
`user.updated` and the sign-in claims carry.
- **App:** `APP_MODULES`; `hub.DEVOTIONALS_PATH` and its error codes; `agent.APP_DEMO_PROFILES`
(`acacia-hill`), `app` in `DEMO_PRODUCTS`, `SEED_APP_DEMO_MIN_AGENT` (1.7.0, not released yet).
- **Church export:** the `app` section (`exportAppSchema`: prayer wall rules, commitments as rules
with their skips, "I prayed" marks, campaigns, testimonies, prayer requests with their
moderation, emergency numbers, announcements, the church's own devotionals, simple events), and
`people[].roles` (optional) for a person with several roles.
- New samples: `devotionals-reply`, `messaging-get`, `messaging-get-reply`, `messaging-changed`,
`whatsapp-optout`, `whatsapp-optout-reply`, `church-export-app`. New JSON Schemas: `devotional`,
`devotionals-reply`, `messaging-get-reply`, `messaging-changed`, `whatsapp-optout-reply`.
## website@1.7.1 - 2026-11-28 ## website@1.7.1 - 2026-11-28
Move and zoom for ministries', leaders' and events' photos (1.7.0 had it in page sections only). Move and zoom for ministries', leaders' and events' photos (1.7.0 had it in page sections only).
@@ -323,6 +323,10 @@ async function handle(ctx: Ctx, provider: Provider, link: ProductLink, secret: s
await logRequest(ctx, link, r, 'people_checked_by_product', null, req, { checked: people.length, deleted: count('deleted'), unknown: count('unknown') }); await logRequest(ctx, link, r, 'people_checked_by_product', null, req, { checked: people.length, deleted: count('deleted'), unknown: count('unknown') });
return reply({ people }); return reply({ people });
} }
// contracts 1.20.0 (APP-1.0-PLAN §8): answered from Accounts 1.9.0.
case 'messaging.get':
case 'whatsapp.optout':
throw new RequestError(`This Accounts doesn't answer ${r.type} yet (Accounts 1.9.0 does).`, 'INVALID_REQUEST', 400);
case 'church.update': { case 'church.update': {
// The product checked the person's role (Accounts doesn't know the Website's); Accounts // The product checked the person's role (Accounts doesn't know the Website's); Accounts
// checks it's the Website, that the person signs in through it, and audits it as theirs. // checks it's the Website, that the person signs in through it, and audits it as theirs.
+9 -1
View File
@@ -14,7 +14,7 @@ separately below; the two often differ.
| Church Website | `crosscode-platform` (`apps/website`) | **1.7.1** | `website@1.7.1` | 2026-11-28 | | Church Website | `crosscode-platform` (`apps/website`) | **1.7.1** | `website@1.7.1` | 2026-11-28 |
| Accounts | `crosscode-platform` (`apps/accounts`) | **1.8.0** | `accounts@1.8.0` | 2026-11-26 | | Accounts | `crosscode-platform` (`apps/accounts`) | **1.8.0** | `accounts@1.8.0` | 2026-11-26 |
| Server agent | `crosscode-platform` (`apps/agent`) | **1.6.0** | `agent@1.6.0` | 2026-11-27 | | Server agent | `crosscode-platform` (`apps/agent`) | **1.6.0** | `agent@1.6.0` | 2026-11-27 |
| Contracts | `crosscode-platform` (`packages/contracts`) | **1.19.0** | `contracts@1.19.0` | 2026-11-27 | | Contracts | `crosscode-platform` (`packages/contracts`) | **1.20.0** | `contracts@1.20.0` | 2026-11-30 |
| Cross Code Hub | `events-hub` | **2.25.1** | `v2.25.1` | 2026-11-27 | | Cross Code Hub | `events-hub` | **2.25.1** | `v2.25.1` | 2026-11-27 |
| crosscode.co.za | `crosscode-site` | **1.9.1** | `v1.9.1` | 2026-11-27 | | crosscode.co.za | `crosscode-site` | **1.9.1** | `v1.9.1` | 2026-11-27 |
| `crosscode` script | `crosscode-platform` (`scripts/`) | `main` | none | 2026-11-27 (last change: an uninstall keeps the Website's backup snapshots shared, `rsync -aH`) | | `crosscode` script | `crosscode-platform` (`scripts/`) | `main` | none | 2026-11-27 (last change: an uninstall keeps the Website's backup snapshots shared, `rsync -aH`) |
@@ -38,6 +38,14 @@ need their own tags until something outside this repo depends on them.
## What each latest release was for ## What each latest release was for
- **Contracts 1.20.0 (2026-11-30):** the contracts for Church App 1.0.0 (APP-1.0-PLAN §12), the
first step of phase 6: `crosscode.devotional/1` and the devotionals CSV checks shared by the Hub
and the App, the Bible books and seven translations (YouVersion ids checked by Joshua),
`messaging.get` / `messaging.changed`, `whatsapp.optout` and `whatsapp_opted_out`, `APP_MODULES`,
the App's demo profile and the `app` part of the church export. Additive. Accounts refuses the
two new requests until 1.9.0. Checked: contracts tests (329), JSON Schemas up to date, the
workspace typecheck, Accounts' tests (80), the agent's tests. Nothing to deploy: the Hub vendors
it with 2.26.0, and the products take it with their next release.
- **Church Website 1.7.1 (2026-11-28):** Move and zoom for ministries', leaders' and events' - **Church Website 1.7.1 (2026-11-28):** Move and zoom for ministries', leaders' and events'
photos too (1.7.0 had it in page sections only), saved with the row (`framing`). One migration photos too (1.7.0 had it in page sections only), saved with the row (`framing`). One migration
(a nullable column on three tables). Checked: backend tests (136) and typecheck, frontend (a nullable column on three tables). Checked: backend tests (136) and typecheck, frontend
+1 -1
View File
@@ -23185,7 +23185,7 @@
}, },
"packages/contracts": { "packages/contracts": {
"name": "@crosscode/contracts", "name": "@crosscode/contracts",
"version": "1.19.0", "version": "1.20.0",
"license": "UNLICENSED", "license": "UNLICENSED",
"dependencies": { "dependencies": {
"zod": "^4.6.7" "zod": "^4.6.7"
+3 -1
View File
@@ -10,11 +10,13 @@ Events and the Hub, uses it, so the key fields are the same in every product's J
| Event feed | `crosscode.event-feed/1` | `GET /api/feed/v1/events?updatedSince=` and the `event.changed` webhook | `src/event.ts` | | Event feed | `crosscode.event-feed/1` | `GET /api/feed/v1/events?updatedSince=` and the `event.changed` webhook | `src/event.ts` |
| Church | `crosscode.church/1` | The church profile: name, branding, campuses, service times, contact details, product links | `src/church.ts` | | Church | `crosscode.church/1` | The church profile: name, branding, campuses, service times, contact details, product links | `src/church.ts` |
| Identity | `crosscode.identity/1` | Accounts' sign-in claims and back-channel calls (`user.updated`, `user.deleted`, `user.export`) and their replies | `src/identity.ts` | | Identity | `crosscode.identity/1` | Accounts' sign-in claims and back-channel calls (`user.updated`, `user.deleted`, `user.export`) and their replies | `src/identity.ts` |
| Identity requests | `crosscode.identity-request/1` | From 1.8.0: what a product asks of its Accounts at `POST /api/accounts/v1/requests`: moving its users in (`import.begin` / `batch` / `finish` / `abort`, secrets sealed with `sealLinkValue`) and `people.*` (ensure, update, reset 2FA, unlock, set active, news off); from 1.9.0 `messaging.*` (status, test, set Accounts' email and WhatsApp) | `src/identity-request.ts` | | Identity requests | `crosscode.identity-request/1` | From 1.8.0: what a product asks of its Accounts at `POST /api/accounts/v1/requests`: moving its users in (`import.begin` / `batch` / `finish` / `abort`, secrets sealed with `sealLinkValue`) and `people.*` (ensure, update, reset 2FA, unlock, set active, news off); from 1.9.0 `messaging.*` (status, test, set Accounts' email and WhatsApp); from 1.20.0 `messaging.get` (the church's settings for the App, with the `messaging.changed` hint back) and `whatsapp.optout` (a STOP, kept by Accounts for every product) | `src/identity-request.ts` |
| Sign-in return | — | The return-path check and OIDC `state` every product uses (ROADMAP-v3 §3) | `src/return-to.ts` | | Sign-in return | — | The return-path check and OIDC `state` every product uses (ROADMAP-v3 §3) | `src/return-to.ts` |
| Product link | `crosscode.link/1` | **Connect** under Settings → Linked products: the signed handshake that sets up a link's secret (`link.connect`, `link.connected`, `link.disconnect`) | `src/link.ts` | | Product link | `crosscode.link/1` | **Connect** under Settings → Linked products: the signed handshake that sets up a link's secret (`link.connect`, `link.connected`, `link.disconnect`) | `src/link.ts` |
| Hub protocol v2 | `protocolVersion: 2` | Register, heartbeat (stats per product), linked products, update requests, AI, licence token | `src/hub.ts` (exported as `hub`) | | Hub protocol v2 | `protocolVersion: 2` | Register, heartbeat (stats per product), linked products, update requests, AI, licence token | `src/hub.ts` (exported as `hub`) |
| Env template | `crosscode.env-template/1` | Each product's `.env` variables by layer; `missingRequired` and, from 1.6.0, `checkEnvValue` / `invalidValues` (values an app can't start with, e.g. `TRUST_PROXY=TRUE`), which the Hub checks before a job | `src/agent.ts` (exported as `agent`) | | Env template | `crosscode.env-template/1` | Each product's `.env` variables by layer; `missingRequired` and, from 1.6.0, `checkEnvValue` / `invalidValues` (values an app can't start with, e.g. `TRUST_PROXY=TRUE`), which the Hub checks before a job | `src/agent.ts` (exported as `agent`) |
| Devotional | `crosscode.devotional/1` | From 1.20.0: one day's devotional for the Church App (Cross Code's from the Hub at `GET /api/v2/devotionals`, or the church's own), the CSV import's columns and row checks (`checkDevotionalCsv`, `DEVOTIONAL_CSV_TEMPLATE`), shared by the Hub and the App | `src/devotional.ts` |
| Bible passages | — | From 1.20.0: the 66 books (USFM codes, English and Afrikaans names), the seven translations with their YouVersion ids and copyright lines, `parseBibleReference`, `formatBibleReference`, `youVersionUrl` | `src/bible.ts` |
| Signing | — | HMAC request signing for the Hub and for product links (Node only) | `src/signing.ts` (`@crosscode/contracts/signing`) | | Signing | — | HMAC request signing for the Hub and for product links (Node only) | `src/signing.ts` (`@crosscode/contracts/signing`) |
## Using it ## Using it
+1 -1
View File
@@ -1,6 +1,6 @@
{ {
"name": "@crosscode/contracts", "name": "@crosscode/contracts",
"version": "1.19.0", "version": "1.20.0",
"description": "The shared JSON formats used by every Cross Code product: zod schemas, JSON Schema, TypeScript types and sample payloads", "description": "The shared JSON formats used by every Cross Code product: zod schemas, JSON Schema, TypeScript types and sample payloads",
"license": "UNLICENSED", "license": "UNLICENSED",
"type": "commonjs", "type": "commonjs",
@@ -0,0 +1,131 @@
{
"schema": "crosscode.church-export/1",
"exportedAt": "2027-02-01T12:00:00.000Z",
"product": "app",
"productVersion": "1.0.0",
"church": { "name": "Acacia Hill Church", "timezone": "Africa/Johannesburg" },
"people": [
{
"ref": "p1",
"name": "Lindiwe Example",
"email": "lindiwe@example.com",
"phone": "+27825550101",
"role": "prayer-coordinator",
"roles": ["prayer-coordinator", "devotional-writer"],
"createdAt": "2026-12-10T08:00:00.000Z",
"consent": { "email": true, "whatsapp": true, "privacyNoticeAcceptedAt": "2026-12-10T08:00:00.000Z" }
},
{
"ref": "p2",
"name": "Pieter Example",
"email": "pieter@example.com",
"phone": null,
"role": "member",
"createdAt": "2026-12-12T19:20:00.000Z",
"consent": { "email": false, "whatsapp": null, "privacyNoticeAcceptedAt": "2026-12-12T19:20:00.000Z" }
}
],
"events": [],
"registrations": [],
"payments": [],
"checkIns": [],
"rosters": [],
"settings": { "name": "Acacia Hill Church" },
"files": [{ "path": "uploads/campaigns/21-days.jpg", "bytes": 214380 }],
"app": {
"modules": ["house-of-prayer", "prayer-requests", "announcements", "devotionals", "events"],
"prayerWall": { "slotMinutes": 60, "slotTarget": 1, "bookAheadMonths": 12, "recurringMaxMonths": 12, "cancelHours": 8, "contact": "Lindiwe, 082 555 0101" },
"commitments": [
{
"ref": "c1",
"personRef": "p2",
"startsAt": "2026-12-14T00:00:00.000Z",
"minutes": 120,
"repeats": "weekly",
"until": "2027-12-13",
"skipped": ["2026-12-28"],
"reminder": "1h",
"channel": "whatsapp",
"note": null,
"createdAt": "2026-12-12T19:30:00.000Z",
"stoppedAt": null
}
],
"prayed": [{ "personRef": "p2", "slotStartsAt": "2026-12-14T00:00:00.000Z", "at": "2026-12-14T02:05:00.000Z" }],
"campaigns": [
{ "ref": "k1", "title": "21 days of prayer", "description": "Every hour covered, together.", "image": "uploads/campaigns/21-days.jpg", "startsOn": "2027-01-05", "endsOn": "2027-01-25", "goal": "Every hour covered", "slotTarget": 2 }
],
"testimonies": [
{ "personRef": "p2", "campaignRef": "k1", "text": "My father came home from hospital.", "showName": true, "status": "shown", "createdAt": "2027-01-20T07:00:00.000Z" }
],
"prayerRequests": [
{
"ref": "q1",
"personRef": "p2",
"visibility": "members",
"showName": false,
"text": "Please pray for my exams this week.",
"status": "closed",
"prayedCount": 14,
"createdAt": "2027-01-10T06:00:00.000Z",
"closedAt": "2027-01-18T12:00:00.000Z",
"updates": [{ "text": "Answered! Thank you all.", "at": "2027-01-18T12:00:00.000Z" }],
"moderation": [
{ "action": "approved", "by": "Lindiwe Example", "reason": null, "at": "2027-01-10T07:10:00.000Z" },
{ "action": "closed", "by": null, "reason": null, "at": "2027-01-18T12:00:00.000Z" }
]
}
],
"safeguarding": {
"emergencyNumbers": [
{ "name": "Lifeline", "number": "0861 322 322" },
{ "name": "SADAG", "number": "0800 567 567" },
{ "name": "Childline", "number": "116" }
]
},
"announcements": [
{
"title": "21 days of prayer starts on 5 January",
"body": "Book your hour on the prayer wall.",
"image": null,
"button": { "label": "Book an hour", "url": "https://app.acaciahill.co.za/prayer" },
"campus": null,
"audience": "everyone",
"pinned": true,
"publishAt": "2026-12-20T06:00:00.000Z",
"endsAt": "2027-01-25T22:00:00.000Z",
"sent": { "email": true, "whatsapp": false }
}
],
"devotionalSource": "church",
"devotionals": [
{
"date": "2027-01-05",
"title": "God het eerste liefgehad",
"passage": {
"reference": "Johannes 3:16",
"location": { "book": "JHN", "chapter": 3, "verse": 16, "endChapter": 3, "endVerse": 16 },
"translation": "AFR53",
"text": "Want so lief het God die wêreld gehad, dat Hy sy eniggebore Seun gegee het, sodat elkeen wat in Hom glo, nie verlore mag gaan nie, maar die ewige lewe kan hê."
},
"body": "God het eerste liefgehad.",
"prayer": null,
"author": "Lindiwe Example",
"membersOnly": false
}
],
"events": [
{
"ref": "w1",
"title": "Prayer night",
"description": "An evening of worship and prayer.",
"startsAt": "2027-01-15T17:00:00.000Z",
"endsAt": "2027-01-15T19:00:00.000Z",
"location": "Acacia Hill Church hall",
"link": null,
"image": null,
"published": true
}
]
}
}
@@ -0,0 +1,42 @@
{
"schema": "crosscode.devotional/1",
"from": "2027-01-05",
"to": "2027-04-05",
"devotionals": [
{
"schema": "crosscode.devotional/1",
"id": "3b4c5d6e-7f8a-4b9c-8d0e-2f3a4b5c6d7e",
"source": "crosscode",
"date": "2027-01-05",
"title": "Love that never gives up",
"passage": {
"reference": "1 Corinthians 13:4–7",
"location": { "book": "1CO", "chapter": 13, "verse": 4, "endChapter": 13, "endVerse": 7 },
"translation": "NLT",
"text": "Love is patient and kind. Love is not jealous or boastful or proud or rude. It does not demand its own way. It is not irritable, and it keeps no record of being wronged. It does not rejoice about injustice but rejoices whenever the truth wins out. Love never gives up, never loses faith, is always hopeful, and endures through every circumstance."
},
"body": "Paul wrote these words to a church that was proud of its gifts.\n\nLove is the gift that makes the others worth having.",
"prayer": "Lord, teach me to love the way you love me.",
"author": "Cross Code",
"updatedAt": "2026-12-01T10:00:00.000Z"
},
{
"schema": "crosscode.devotional/1",
"id": "4c5d6e7f-8a9b-4c0d-9e1f-3a4b5c6d7e8f",
"source": "crosscode",
"date": "2027-01-06",
"title": "Die Here is my herder",
"passage": {
"reference": "Psalms 23:1–3",
"location": { "book": "PSA", "chapter": 23, "verse": 1, "endChapter": 23, "endVerse": 3 },
"translation": "AFR83",
"text": "Die Here is my herder, ek kom niks kort nie. Hy laat my rus in groen weivelde. Hy bring my by waters waar daar vrede is. Hy gee my nuwe krag. Hy lei my op die regte paaie tot eer van sy Naam."
},
"body": "Vandag herinner Dawid ons dat ons nie alleen loop nie.",
"prayer": null,
"author": null,
"updatedAt": "2026-12-01T10:00:00.000Z"
}
],
"generatedAt": "2027-01-05T00:30:00.000Z"
}
@@ -0,0 +1,7 @@
{
"schema": "crosscode.identity-request/1",
"type": "messaging.changed",
"occurredAt": "2026-12-03T09:15:00.000Z",
"email": false,
"whatsapp": true
}
@@ -0,0 +1,16 @@
{
"schema": "crosscode.identity-request/1",
"email": {
"host": "smtp.acaciahill.co.za",
"port": 587,
"secure": false,
"user": "hello@acaciahill.co.za",
"pass": "sealed1.DDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDD",
"from": "Acacia Hill Church <hello@acaciahill.co.za>"
},
"whatsapp": {
"accessToken": "sealed1.EEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEE",
"instanceId": "ACACIA01"
},
"updatedAt": "2026-12-02T07:30:00.000Z"
}
@@ -0,0 +1,6 @@
{
"schema": "crosscode.identity-request/1",
"requestId": "1f2a3b4c-5d6e-4f7a-8b9c-0d1e2f3a4b5c",
"actor": null,
"type": "messaging.get"
}
@@ -0,0 +1,4 @@
{
"schema": "crosscode.identity-request/1",
"accounts": 1
}
@@ -0,0 +1,9 @@
{
"schema": "crosscode.identity-request/1",
"requestId": "2a3b4c5d-6e7f-4a8b-9c0d-1e2f3a4b5c6d",
"actor": null,
"type": "whatsapp.optout",
"phone": "+27825550123",
"receivedAt": "2026-12-04T18:42:10.000Z",
"keyword": "STOP"
}
@@ -95,6 +95,9 @@
"email", "email",
"whatsapp" "whatsapp"
] ]
},
"whatsapp_opted_out": {
"type": "boolean"
} }
}, },
"required": [ "required": [
+8 -1
View File
@@ -823,7 +823,8 @@
"type": "string", "type": "string",
"enum": [ "enum": [
"events", "events",
"website" "website",
"app"
] ]
}, },
"profile": { "profile": {
@@ -849,6 +850,12 @@
"clean-modern", "clean-modern",
"clean-campus" "clean-campus"
] ]
},
{
"type": "string",
"enum": [
"acacia-hill"
]
} }
] ]
}, },
File diff suppressed because it is too large Load Diff
+215
View File
@@ -0,0 +1,215 @@
{
"$id": "https://c-git.crosscode.co.za/joshua/crosscode-platform/raw/branch/main/packages/contracts/schemas/devotional.json",
"$schema": "https://json-schema.org/draft/2020-12/schema",
"type": "object",
"properties": {
"date": {
"type": "string",
"format": "date",
"pattern": "^(?:(?:\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-(?:(?:0[13578]|1[02])-(?:0[1-9]|[12]\\d|3[01])|(?:0[469]|11)-(?:0[1-9]|[12]\\d|30)|(?:02)-(?:0[1-9]|1\\d|2[0-8])))$"
},
"title": {
"type": "string",
"minLength": 1,
"maxLength": 200
},
"passage": {
"type": "object",
"properties": {
"reference": {
"type": "string",
"minLength": 1,
"maxLength": 100
},
"location": {
"type": "object",
"properties": {
"book": {
"type": "string",
"enum": [
"GEN",
"EXO",
"LEV",
"NUM",
"DEU",
"JOS",
"JDG",
"RUT",
"1SA",
"2SA",
"1KI",
"2KI",
"1CH",
"2CH",
"EZR",
"NEH",
"EST",
"JOB",
"PSA",
"PRO",
"ECC",
"SNG",
"ISA",
"JER",
"LAM",
"EZK",
"DAN",
"HOS",
"JOL",
"AMO",
"OBA",
"JON",
"MIC",
"NAM",
"HAB",
"ZEP",
"HAG",
"ZEC",
"MAL",
"MAT",
"MRK",
"LUK",
"JHN",
"ACT",
"ROM",
"1CO",
"2CO",
"GAL",
"EPH",
"PHP",
"COL",
"1TH",
"2TH",
"1TI",
"2TI",
"TIT",
"PHM",
"HEB",
"JAS",
"1PE",
"2PE",
"1JN",
"2JN",
"3JN",
"JUD",
"REV"
]
},
"chapter": {
"type": "integer",
"minimum": 1,
"maximum": 150
},
"verse": {
"type": "integer",
"minimum": 1,
"maximum": 176
},
"endChapter": {
"type": "integer",
"minimum": 1,
"maximum": 150
},
"endVerse": {
"type": "integer",
"minimum": 1,
"maximum": 176
}
},
"required": [
"book",
"chapter",
"verse",
"endChapter",
"endVerse"
]
},
"translation": {
"type": "string",
"enum": [
"NLT",
"ESV",
"NIV",
"NKJV",
"KJV",
"AFR53",
"AFR83"
]
},
"text": {
"type": "string",
"minLength": 1,
"maxLength": 10000
}
},
"required": [
"reference",
"location",
"translation",
"text"
]
},
"body": {
"type": "string",
"minLength": 1,
"maxLength": 20000
},
"prayer": {
"anyOf": [
{
"type": "string",
"minLength": 1,
"maxLength": 5000
},
{
"type": "null"
}
]
},
"author": {
"anyOf": [
{
"type": "string",
"minLength": 1,
"maxLength": 200
},
{
"type": "null"
}
]
},
"schema": {
"type": "string",
"const": "crosscode.devotional/1"
},
"id": {
"type": "string",
"format": "uuid",
"pattern": "^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[1-8][0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12}|00000000-0000-0000-0000-000000000000|ffffffff-ffff-ffff-ffff-ffffffffffff)$"
},
"source": {
"type": "string",
"enum": [
"crosscode",
"church"
]
},
"updatedAt": {
"type": "string",
"format": "date-time",
"pattern": "^(?:(?:\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-(?:(?:0[13578]|1[02])-(?:0[1-9]|[12]\\d|3[01])|(?:0[469]|11)-(?:0[1-9]|[12]\\d|30)|(?:02)-(?:0[1-9]|1\\d|2[0-8])))T(?:(?:[01]\\d|2[0-3]):[0-5]\\d:[0-5]\\d(?:\\.\\d+)?(?:Z))$"
}
},
"required": [
"date",
"title",
"passage",
"body",
"prayer",
"author",
"schema",
"id",
"source",
"updatedAt"
]
}
@@ -0,0 +1,247 @@
{
"$id": "https://c-git.crosscode.co.za/joshua/crosscode-platform/raw/branch/main/packages/contracts/schemas/devotionals-reply.json",
"$schema": "https://json-schema.org/draft/2020-12/schema",
"type": "object",
"properties": {
"schema": {
"type": "string",
"const": "crosscode.devotional/1"
},
"from": {
"type": "string",
"format": "date",
"pattern": "^(?:(?:\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-(?:(?:0[13578]|1[02])-(?:0[1-9]|[12]\\d|3[01])|(?:0[469]|11)-(?:0[1-9]|[12]\\d|30)|(?:02)-(?:0[1-9]|1\\d|2[0-8])))$"
},
"to": {
"type": "string",
"format": "date",
"pattern": "^(?:(?:\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-(?:(?:0[13578]|1[02])-(?:0[1-9]|[12]\\d|3[01])|(?:0[469]|11)-(?:0[1-9]|[12]\\d|30)|(?:02)-(?:0[1-9]|1\\d|2[0-8])))$"
},
"devotionals": {
"maxItems": 100,
"type": "array",
"items": {
"type": "object",
"properties": {
"date": {
"type": "string",
"format": "date",
"pattern": "^(?:(?:\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-(?:(?:0[13578]|1[02])-(?:0[1-9]|[12]\\d|3[01])|(?:0[469]|11)-(?:0[1-9]|[12]\\d|30)|(?:02)-(?:0[1-9]|1\\d|2[0-8])))$"
},
"title": {
"type": "string",
"minLength": 1,
"maxLength": 200
},
"passage": {
"type": "object",
"properties": {
"reference": {
"type": "string",
"minLength": 1,
"maxLength": 100
},
"location": {
"type": "object",
"properties": {
"book": {
"type": "string",
"enum": [
"GEN",
"EXO",
"LEV",
"NUM",
"DEU",
"JOS",
"JDG",
"RUT",
"1SA",
"2SA",
"1KI",
"2KI",
"1CH",
"2CH",
"EZR",
"NEH",
"EST",
"JOB",
"PSA",
"PRO",
"ECC",
"SNG",
"ISA",
"JER",
"LAM",
"EZK",
"DAN",
"HOS",
"JOL",
"AMO",
"OBA",
"JON",
"MIC",
"NAM",
"HAB",
"ZEP",
"HAG",
"ZEC",
"MAL",
"MAT",
"MRK",
"LUK",
"JHN",
"ACT",
"ROM",
"1CO",
"2CO",
"GAL",
"EPH",
"PHP",
"COL",
"1TH",
"2TH",
"1TI",
"2TI",
"TIT",
"PHM",
"HEB",
"JAS",
"1PE",
"2PE",
"1JN",
"2JN",
"3JN",
"JUD",
"REV"
]
},
"chapter": {
"type": "integer",
"minimum": 1,
"maximum": 150
},
"verse": {
"type": "integer",
"minimum": 1,
"maximum": 176
},
"endChapter": {
"type": "integer",
"minimum": 1,
"maximum": 150
},
"endVerse": {
"type": "integer",
"minimum": 1,
"maximum": 176
}
},
"required": [
"book",
"chapter",
"verse",
"endChapter",
"endVerse"
]
},
"translation": {
"type": "string",
"enum": [
"NLT",
"ESV",
"NIV",
"NKJV",
"KJV",
"AFR53",
"AFR83"
]
},
"text": {
"type": "string",
"minLength": 1,
"maxLength": 10000
}
},
"required": [
"reference",
"location",
"translation",
"text"
]
},
"body": {
"type": "string",
"minLength": 1,
"maxLength": 20000
},
"prayer": {
"anyOf": [
{
"type": "string",
"minLength": 1,
"maxLength": 5000
},
{
"type": "null"
}
]
},
"author": {
"anyOf": [
{
"type": "string",
"minLength": 1,
"maxLength": 200
},
{
"type": "null"
}
]
},
"schema": {
"type": "string",
"const": "crosscode.devotional/1"
},
"id": {
"type": "string",
"format": "uuid",
"pattern": "^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[1-8][0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12}|00000000-0000-0000-0000-000000000000|ffffffff-ffff-ffff-ffff-ffffffffffff)$"
},
"source": {
"type": "string",
"const": "crosscode"
},
"updatedAt": {
"type": "string",
"format": "date-time",
"pattern": "^(?:(?:\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-(?:(?:0[13578]|1[02])-(?:0[1-9]|[12]\\d|3[01])|(?:0[469]|11)-(?:0[1-9]|[12]\\d|30)|(?:02)-(?:0[1-9]|1\\d|2[0-8])))T(?:(?:[01]\\d|2[0-3]):[0-5]\\d:[0-5]\\d(?:\\.\\d+)?(?:Z))$"
}
},
"required": [
"date",
"title",
"passage",
"body",
"prayer",
"author",
"schema",
"id",
"source",
"updatedAt"
]
}
},
"generatedAt": {
"type": "string",
"format": "date-time",
"pattern": "^(?:(?:\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-(?:(?:0[13578]|1[02])-(?:0[1-9]|[12]\\d|3[01])|(?:0[469]|11)-(?:0[1-9]|[12]\\d|30)|(?:02)-(?:0[1-9]|1\\d|2[0-8])))T(?:(?:[01]\\d|2[0-3]):[0-5]\\d:[0-5]\\d(?:\\.\\d+)?(?:Z))$"
}
},
"required": [
"schema",
"from",
"to",
"devotionals",
"generatedAt"
]
}
@@ -68,6 +68,9 @@
"whatsapp" "whatsapp"
] ]
}, },
"whatsapp_opted_out": {
"type": "boolean"
},
"schema": { "schema": {
"type": "string", "type": "string",
"const": "crosscode.identity/1" "const": "crosscode.identity/1"
@@ -1850,6 +1850,95 @@
"type", "type",
"church" "church"
] ]
},
{
"type": "object",
"properties": {
"schema": {
"type": "string",
"const": "crosscode.identity-request/1"
},
"requestId": {
"type": "string",
"format": "uuid",
"pattern": "^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[1-8][0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12}|00000000-0000-0000-0000-000000000000|ffffffff-ffff-ffff-ffff-ffffffffffff)$"
},
"actor": {
"anyOf": [
{
"type": "string",
"format": "uuid",
"pattern": "^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[1-8][0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12}|00000000-0000-0000-0000-000000000000|ffffffff-ffff-ffff-ffff-ffffffffffff)$"
},
{
"type": "null"
}
]
},
"type": {
"type": "string",
"const": "messaging.get"
}
},
"required": [
"schema",
"requestId",
"actor",
"type"
]
},
{
"type": "object",
"properties": {
"schema": {
"type": "string",
"const": "crosscode.identity-request/1"
},
"requestId": {
"type": "string",
"format": "uuid",
"pattern": "^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[1-8][0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12}|00000000-0000-0000-0000-000000000000|ffffffff-ffff-ffff-ffff-ffffffffffff)$"
},
"actor": {
"anyOf": [
{
"type": "string",
"format": "uuid",
"pattern": "^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[1-8][0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12}|00000000-0000-0000-0000-000000000000|ffffffff-ffff-ffff-ffff-ffffffffffff)$"
},
{
"type": "null"
}
]
},
"type": {
"type": "string",
"const": "whatsapp.optout"
},
"phone": {
"type": "string",
"pattern": "^\\+[1-9]\\d{6,14}$"
},
"receivedAt": {
"type": "string",
"format": "date-time",
"pattern": "^(?:(?:\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-(?:(?:0[13578]|1[02])-(?:0[1-9]|[12]\\d|3[01])|(?:0[469]|11)-(?:0[1-9]|[12]\\d|30)|(?:02)-(?:0[1-9]|1\\d|2[0-8])))T(?:(?:[01]\\d|2[0-3]):[0-5]\\d:[0-5]\\d(?:\\.\\d+)?(?:Z))$"
},
"keyword": {
"type": "string",
"minLength": 1,
"maxLength": 40
}
},
"required": [
"schema",
"requestId",
"actor",
"type",
"phone",
"receivedAt",
"keyword"
]
} }
] ]
} }
@@ -0,0 +1,33 @@
{
"$id": "https://c-git.crosscode.co.za/joshua/crosscode-platform/raw/branch/main/packages/contracts/schemas/messaging-changed.json",
"$schema": "https://json-schema.org/draft/2020-12/schema",
"type": "object",
"properties": {
"schema": {
"type": "string",
"const": "crosscode.identity-request/1"
},
"type": {
"type": "string",
"const": "messaging.changed"
},
"occurredAt": {
"type": "string",
"format": "date-time",
"pattern": "^(?:(?:\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-(?:(?:0[13578]|1[02])-(?:0[1-9]|[12]\\d|3[01])|(?:0[469]|11)-(?:0[1-9]|[12]\\d|30)|(?:02)-(?:0[1-9]|1\\d|2[0-8])))T(?:(?:[01]\\d|2[0-3]):[0-5]\\d:[0-5]\\d(?:\\.\\d+)?(?:Z))$"
},
"email": {
"type": "boolean"
},
"whatsapp": {
"type": "boolean"
}
},
"required": [
"schema",
"type",
"occurredAt",
"email",
"whatsapp"
]
}
@@ -0,0 +1,109 @@
{
"$id": "https://c-git.crosscode.co.za/joshua/crosscode-platform/raw/branch/main/packages/contracts/schemas/messaging-get-reply.json",
"$schema": "https://json-schema.org/draft/2020-12/schema",
"type": "object",
"properties": {
"schema": {
"type": "string",
"const": "crosscode.identity-request/1"
},
"email": {
"anyOf": [
{
"type": "object",
"properties": {
"host": {
"type": "string",
"minLength": 1,
"maxLength": 253
},
"port": {
"type": "integer",
"minimum": 1,
"maximum": 65535
},
"secure": {
"type": "boolean"
},
"user": {
"type": "string",
"maxLength": 254
},
"pass": {
"anyOf": [
{
"type": "string",
"maxLength": 4096,
"pattern": "^sealed1\\.[A-Za-z0-9_-]{40,}$"
},
{
"type": "null"
}
]
},
"from": {
"type": "string",
"minLength": 3,
"maxLength": 320
}
},
"required": [
"host",
"port",
"secure",
"user",
"pass",
"from"
]
},
{
"type": "null"
}
]
},
"whatsapp": {
"anyOf": [
{
"type": "object",
"properties": {
"accessToken": {
"type": "string",
"maxLength": 4096,
"pattern": "^sealed1\\.[A-Za-z0-9_-]{40,}$"
},
"instanceId": {
"type": "string",
"minLength": 1,
"maxLength": 200
}
},
"required": [
"accessToken",
"instanceId"
]
},
{
"type": "null"
}
]
},
"updatedAt": {
"anyOf": [
{
"type": "string",
"format": "date-time",
"pattern": "^(?:(?:\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-(?:(?:0[13578]|1[02])-(?:0[1-9]|[12]\\d|3[01])|(?:0[469]|11)-(?:0[1-9]|[12]\\d|30)|(?:02)-(?:0[1-9]|1\\d|2[0-8])))T(?:(?:[01]\\d|2[0-3]):[0-5]\\d:[0-5]\\d(?:\\.\\d+)?(?:Z))$"
},
{
"type": "null"
}
]
}
},
"required": [
"schema",
"email",
"whatsapp",
"updatedAt"
]
}
@@ -96,6 +96,9 @@
"email", "email",
"whatsapp" "whatsapp"
] ]
},
"whatsapp_opted_out": {
"type": "boolean"
} }
}, },
"required": [ "required": [
@@ -93,6 +93,9 @@
"email", "email",
"whatsapp" "whatsapp"
] ]
},
"whatsapp_opted_out": {
"type": "boolean"
} }
}, },
"required": [ "required": [
@@ -0,0 +1,20 @@
{
"$id": "https://c-git.crosscode.co.za/joshua/crosscode-platform/raw/branch/main/packages/contracts/schemas/whatsapp-optout-reply.json",
"$schema": "https://json-schema.org/draft/2020-12/schema",
"type": "object",
"properties": {
"schema": {
"type": "string",
"const": "crosscode.identity-request/1"
},
"accounts": {
"type": "integer",
"minimum": 0,
"maximum": 9007199254740991
}
},
"required": [
"schema",
"accounts"
]
}
@@ -71,6 +71,11 @@ function contracts(c) {
"people-remove-demo-reply": c.peopleRemoveDemoReplySchema, "people-remove-demo-reply": c.peopleRemoveDemoReplySchema,
"people-check-reply": c.peopleCheckReplySchema, "people-check-reply": c.peopleCheckReplySchema,
"church-update-reply": c.churchUpdateReplySchema, "church-update-reply": c.churchUpdateReplySchema,
"messaging-get-reply": c.messagingGetReplySchema,
"messaging-changed": c.messagingChangedSchema,
"whatsapp-optout-reply": c.whatsappOptOutReplySchema,
"devotional": c.devotionalSchema,
"devotionals-reply": c.devotionalsReplySchema,
}; };
} }
+19 -7
View File
@@ -72,13 +72,18 @@ export const WEBSITE_DEMO_PROFILES = [
export const websiteDemoProfileSchema = z.enum(WEBSITE_DEMO_PROFILES); export const websiteDemoProfileSchema = z.enum(WEBSITE_DEMO_PROFILES);
export type WebsiteDemoProfile = z.infer<typeof websiteDemoProfileSchema>; export type WebsiteDemoProfile = z.infer<typeof websiteDemoProfileSchema>;
/** The products with demo data (`seed-demo` jobs). */ /** The Church App's demo data sets (1.20.0): Acacia Hill, the demo church (APP-1.0-PLAN §12). */
export const DEMO_PRODUCTS = ["events", "website"] as const; export const APP_DEMO_PROFILES = ["acacia-hill"] as const;
export const appDemoProfileSchema = z.enum(APP_DEMO_PROFILES);
export type AppDemoProfile = z.infer<typeof appDemoProfileSchema>;
/** The products with demo data (`seed-demo` jobs). 1.20.0 adds `app`. */
export const DEMO_PRODUCTS = ["events", "website", "app"] as const;
export const demoProductSchema = z.enum(DEMO_PRODUCTS); export const demoProductSchema = z.enum(DEMO_PRODUCTS);
export type DemoProduct = z.infer<typeof demoProductSchema>; export type DemoProduct = z.infer<typeof demoProductSchema>;
/** Each demo product's profiles. */ /** Each demo product's profiles. */
export const DEMO_PROFILES_BY_PRODUCT: Record<DemoProduct, readonly string[]> = { events: DEMO_PROFILES, website: WEBSITE_DEMO_PROFILES }; export const DEMO_PROFILES_BY_PRODUCT: Record<DemoProduct, readonly string[]> = { events: DEMO_PROFILES, website: WEBSITE_DEMO_PROFILES, app: APP_DEMO_PROFILES };
/** The first agent that runs `seed-demo` jobs (an older one refuses the unknown type). */ /** The first agent that runs `seed-demo` jobs (an older one refuses the unknown type). */
export const SEED_DEMO_MIN_AGENT = "1.2.0"; export const SEED_DEMO_MIN_AGENT = "1.2.0";
@@ -86,6 +91,12 @@ export const SEED_DEMO_MIN_AGENT = "1.2.0";
/** The first agent that runs `seed-demo` jobs for the Website (`product: "website"`; an older one refuses the unknown key). */ /** The first agent that runs `seed-demo` jobs for the Website (`product: "website"`; an older one refuses the unknown key). */
export const SEED_WEBSITE_DEMO_MIN_AGENT = "1.6.0"; export const SEED_WEBSITE_DEMO_MIN_AGENT = "1.6.0";
/**
* The first agent that runs `seed-demo` jobs for the App (`product: "app"`; an older one passes no
* product to the script, so the Hub mustn't send it one). Agent 1.7.0 ships with App 1.0.0.
*/
export const SEED_APP_DEMO_MIN_AGENT = "1.7.0";
/** The first agent that runs `env-read` and `env-set` jobs (an older one refuses the unknown types). */ /** The first agent that runs `env-read` and `env-set` jobs (an older one refuses the unknown types). */
export const ENV_JOBS_MIN_AGENT = "1.3.0"; export const ENV_JOBS_MIN_AGENT = "1.3.0";
@@ -159,21 +170,22 @@ export const jobArgsSchemas = {
/** `crosscode restart <church> [product] --json` (PM2 reload) */ /** `crosscode restart <church> [product] --json` (PM2 reload) */
restart: z.strictObject({ church: shortNameSchema, product: productSchema.optional() }), restart: z.strictObject({ church: shortNameSchema, product: productSchema.optional() }),
/** /**
* `crosscode demo <church> [website] --profile <profile> [--admin-email <email>] --json`: replaces * `crosscode demo <church> [website|app] --profile <profile> [--admin-email <email>] --json`: replaces
* Cross Events' data (or, 1.19.0 with `product: "website"`, the Website's content) with a demo * Cross Events' data (or, 1.19.0 with `product: "website"`, the Website's content) with a demo
* set (a backup is taken first). The Hub only makes it for installs marked as demo sites. * set (a backup is taken first); 1.20.0 adds `product: "app"` (the App's prayer wall, campaign,
* testimonies, devotionals, announcements and events). The Hub only makes it for installs marked as demo sites.
* `adminEmail` (Events only): the account kept (default: the release's own choice). No `product` * `adminEmail` (Events only): the account kept (default: the release's own choice). No `product`
* is Events, so older Hubs' jobs mean what they did. * is Events, so older Hubs' jobs mean what they did.
*/ */
"seed-demo": z.strictObject({ "seed-demo": z.strictObject({
church: shortNameSchema, church: shortNameSchema,
product: demoProductSchema.optional(), product: demoProductSchema.optional(),
profile: z.union([demoProfileSchema, websiteDemoProfileSchema]), profile: z.union([demoProfileSchema, websiteDemoProfileSchema, appDemoProfileSchema]),
adminEmail: z.email().max(254).optional(), adminEmail: z.email().max(254).optional(),
}).superRefine((a, ctx) => { }).superRefine((a, ctx) => {
const product = a.product ?? "events"; const product = a.product ?? "events";
if (!DEMO_PROFILES_BY_PRODUCT[product].includes(a.profile)) ctx.addIssue({ code: "custom", path: ["profile"], message: `${a.profile} isn't a ${product} demo` }); if (!DEMO_PROFILES_BY_PRODUCT[product].includes(a.profile)) ctx.addIssue({ code: "custom", path: ["profile"], message: `${a.profile} isn't a ${product} demo` });
if (product === "website" && a.adminEmail) ctx.addIssue({ code: "custom", path: ["adminEmail"], message: "the Website's demo keeps every admin" }); if (product !== "events" && a.adminEmail) ctx.addIssue({ code: "custom", path: ["adminEmail"], message: `the ${product === "app" ? "App" : "Website"}'s demo keeps every admin` });
}), }),
/** /**
* `crosscode env <church> <product> --json`: the product's .env values, secrets hidden (only * `crosscode env <church> <product> --json`: the product's .env values, secrets hidden (only
+244
View File
@@ -0,0 +1,244 @@
import { z } from "zod";
/**
* Bible passages for the Church App's devotionals (contracts 1.20.0, docs/APP-1.0-PLAN.md §6,
* decisions 5 and 10): the books (USFM codes, as YouVersion uses them), the translations a
* devotional can quote, reading a reference someone typed ("John 3:16-18", "Johannes 3:16–18",
* "1 Kor 13:4-7"), and the "Read in YouVersion" link.
*
* Shared by the Hub and the App, so a CSV row the Hub accepts is one the App accepts.
*/
// ─── Translations ────────────────────────────────────────────────────────────
/**
* The translations a devotional can use. An id never changes once released; more can be added.
* `youVersionId` is the version's number on bible.com (`bible.com/bible/<id>/JHN.3.16.<abbr>`).
* `copyright` is shown under the verse wherever it's quoted. Check each publisher's terms for use
* in an app before Cross Code's devotionals go out (APP-1.0-PLAN, "Still open").
*/
export const BIBLE_TRANSLATIONS = [
{
id: "NLT", name: "New Living Translation", language: "en", youVersionId: 116,
copyright: "Scripture quotations are taken from the Holy Bible, New Living Translation, copyright © 1996, 2004, 2015 by Tyndale House Foundation. Used by permission of Tyndale House Publishers, Carol Stream, Illinois 60188. All rights reserved.",
},
{
id: "ESV", name: "English Standard Version", language: "en", youVersionId: 59,
copyright: "Scripture quotations are from the ESV® Bible (The Holy Bible, English Standard Version®), © 2001 by Crossway, a publishing ministry of Good News Publishers. Used by permission. All rights reserved.",
},
{
id: "NIV", name: "New International Version", language: "en", youVersionId: 111,
copyright: "Scripture quotations taken from The Holy Bible, New International Version® NIV®. Copyright © 1973, 1978, 1984, 2011 by Biblica, Inc.™ Used by permission. All rights reserved worldwide.",
},
{
id: "NKJV", name: "New King James Version", language: "en", youVersionId: 114,
copyright: "Scripture taken from the New King James Version®. Copyright © 1982 by Thomas Nelson. Used by permission. All rights reserved.",
},
{
id: "KJV", name: "King James Version", language: "en", youVersionId: 1,
copyright: "King James Version. Public domain.",
},
{
id: "AFR53", name: "Afrikaans 1933/1953-vertaling", language: "af", youVersionId: 5,
copyright: "Die Bybel in Afrikaans, 1933/1953-vertaling. © Bybelgenootskap van Suid-Afrika. Gebruik met toestemming.",
},
{
id: "AFR83", name: "Afrikaans 1983-vertaling", language: "af", youVersionId: 6,
copyright: "Die Bybel in Afrikaans, 1983-vertaling. © Bybelgenootskap van Suid-Afrika 1983. Gebruik met toestemming.",
},
] as const;
export type BibleTranslation = (typeof BIBLE_TRANSLATIONS)[number];
export const BIBLE_TRANSLATION_IDS = BIBLE_TRANSLATIONS.map((t) => t.id) as [BibleTranslation["id"], ...BibleTranslation["id"][]];
export const bibleTranslationIdSchema = z.enum(BIBLE_TRANSLATION_IDS);
export type BibleTranslationId = z.infer<typeof bibleTranslationIdSchema>;
export function bibleTranslation(id: BibleTranslationId): BibleTranslation {
return BIBLE_TRANSLATIONS.find((t) => t.id === id)!;
}
/** A passage longer than this gets a warning: quote the passage, not whole chapters (§6). */
export const PASSAGE_WARN_VERSES = 25;
// ─── Books ───────────────────────────────────────────────────────────────────
/**
* The 66 books in order: USFM code, English and Afrikaans names, chapters (English numbering) and
* the other names and abbreviations a reference may use. Matching ignores case, accents, dots and
* spaces, so "1 Kor.", "1kor" and "1 Korintiërs" are the same book.
*/
export const BIBLE_BOOKS = [
{ code: "GEN", en: "Genesis", af: "Genesis", chapters: 50, aliases: ["Gen", "Ge", "Gn"] },
{ code: "EXO", en: "Exodus", af: "Eksodus", chapters: 40, aliases: ["Exod", "Exo", "Ex", "Eks"] },
{ code: "LEV", en: "Leviticus", af: "Levitikus", chapters: 27, aliases: ["Lev", "Le", "Lv"] },
{ code: "NUM", en: "Numbers", af: "Numeri", chapters: 36, aliases: ["Num", "Nu", "Nm", "Nb"] },
{ code: "DEU", en: "Deuteronomy", af: "Deuteronomium", chapters: 34, aliases: ["Deut", "Deu", "Dt", "Dtn"] },
{ code: "JOS", en: "Joshua", af: "Josua", chapters: 24, aliases: ["Josh", "Jos", "Jsh"] },
{ code: "JDG", en: "Judges", af: "Rigters", chapters: 21, aliases: ["Judg", "Jdg", "Jdgs", "Rig"] },
{ code: "RUT", en: "Ruth", af: "Rut", chapters: 4, aliases: ["Rth", "Ru"] },
{ code: "1SA", en: "1 Samuel", af: "1 Samuel", chapters: 31, aliases: ["1 Sam", "1 Sa", "1Sm"] },
{ code: "2SA", en: "2 Samuel", af: "2 Samuel", chapters: 24, aliases: ["2 Sam", "2 Sa", "2Sm"] },
{ code: "1KI", en: "1 Kings", af: "1 Konings", chapters: 22, aliases: ["1 Kgs", "1 Ki", "1 Kon"] },
{ code: "2KI", en: "2 Kings", af: "2 Konings", chapters: 25, aliases: ["2 Kgs", "2 Ki", "2 Kon"] },
{ code: "1CH", en: "1 Chronicles", af: "1 Kronieke", chapters: 29, aliases: ["1 Chron", "1 Chr", "1 Ch", "1 Kron", "1 Kr"] },
{ code: "2CH", en: "2 Chronicles", af: "2 Kronieke", chapters: 36, aliases: ["2 Chron", "2 Chr", "2 Ch", "2 Kron", "2 Kr"] },
{ code: "EZR", en: "Ezra", af: "Esra", chapters: 10, aliases: ["Ezr", "Esr"] },
{ code: "NEH", en: "Nehemiah", af: "Nehemia", chapters: 13, aliases: ["Neh", "Ne"] },
{ code: "EST", en: "Esther", af: "Ester", chapters: 10, aliases: ["Esth", "Est", "Es"] },
{ code: "JOB", en: "Job", af: "Job", chapters: 42, aliases: ["Jb"] },
{ code: "PSA", en: "Psalms", af: "Psalms", chapters: 150, aliases: ["Psalm", "Ps", "Psa", "Pss", "Psalmen"] },
{ code: "PRO", en: "Proverbs", af: "Spreuke", chapters: 31, aliases: ["Prov", "Pro", "Prv", "Pr", "Spr"] },
{ code: "ECC", en: "Ecclesiastes", af: "Prediker", chapters: 12, aliases: ["Eccl", "Ecc", "Ec", "Qoh", "Pred", "Pr"] },
{ code: "SNG", en: "Song of Songs", af: "Hooglied", chapters: 8, aliases: ["Song of Solomon", "Song", "Sos", "Sng", "Hgl", "Hoogl"] },
{ code: "ISA", en: "Isaiah", af: "Jesaja", chapters: 66, aliases: ["Isa", "Is", "Jes"] },
{ code: "JER", en: "Jeremiah", af: "Jeremia", chapters: 52, aliases: ["Jer", "Je", "Jr"] },
{ code: "LAM", en: "Lamentations", af: "Klaagliedere", chapters: 5, aliases: ["Lam", "La", "Klaagl", "Kla"] },
{ code: "EZK", en: "Ezekiel", af: "Esegiël", chapters: 48, aliases: ["Ezek", "Eze", "Ezk", "Eseg", "Ese"] },
{ code: "DAN", en: "Daniel", af: "Daniël", chapters: 12, aliases: ["Dan", "Da", "Dn"] },
{ code: "HOS", en: "Hosea", af: "Hosea", chapters: 14, aliases: ["Hos", "Ho"] },
{ code: "JOL", en: "Joel", af: "Joël", chapters: 3, aliases: ["Joe", "Jl"] },
{ code: "AMO", en: "Amos", af: "Amos", chapters: 9, aliases: ["Am", "Amo"] },
{ code: "OBA", en: "Obadiah", af: "Obadja", chapters: 1, aliases: ["Obad", "Ob", "Oba"] },
{ code: "JON", en: "Jonah", af: "Jona", chapters: 4, aliases: ["Jnh", "Jon"] },
{ code: "MIC", en: "Micah", af: "Miga", chapters: 7, aliases: ["Mic", "Mi", "Mig"] },
{ code: "NAM", en: "Nahum", af: "Nahum", chapters: 3, aliases: ["Nah", "Na"] },
{ code: "HAB", en: "Habakkuk", af: "Habakuk", chapters: 3, aliases: ["Hab", "Hb"] },
{ code: "ZEP", en: "Zephaniah", af: "Sefanja", chapters: 3, aliases: ["Zeph", "Zep", "Zp", "Sef"] },
{ code: "HAG", en: "Haggai", af: "Haggai", chapters: 2, aliases: ["Hag", "Hg"] },
{ code: "ZEC", en: "Zechariah", af: "Sagaria", chapters: 14, aliases: ["Zech", "Zec", "Zc", "Sag"] },
{ code: "MAL", en: "Malachi", af: "Maleagi", chapters: 4, aliases: ["Mal", "Ml"] },
{ code: "MAT", en: "Matthew", af: "Matteus", chapters: 28, aliases: ["Matt", "Mat", "Mt", "Mattheus", "Matt."] },
{ code: "MRK", en: "Mark", af: "Markus", chapters: 16, aliases: ["Mrk", "Mar", "Mk", "Mr", "Mark."] },
{ code: "LUK", en: "Luke", af: "Lukas", chapters: 24, aliases: ["Luk", "Lk", "Lu"] },
{ code: "JHN", en: "John", af: "Johannes", chapters: 21, aliases: ["Jhn", "Jn", "Joh"] },
{ code: "ACT", en: "Acts", af: "Handelinge", chapters: 28, aliases: ["Act", "Ac", "Hand", "Hnd"] },
{ code: "ROM", en: "Romans", af: "Romeine", chapters: 16, aliases: ["Rom", "Ro", "Rm"] },
{ code: "1CO", en: "1 Corinthians", af: "1 Korintiërs", chapters: 16, aliases: ["1 Cor", "1 Co", "1 Kor", "1 Ko"] },
{ code: "2CO", en: "2 Corinthians", af: "2 Korintiërs", chapters: 13, aliases: ["2 Cor", "2 Co", "2 Kor", "2 Ko"] },
{ code: "GAL", en: "Galatians", af: "Galasiërs", chapters: 6, aliases: ["Gal", "Ga"] },
{ code: "EPH", en: "Ephesians", af: "Efesiërs", chapters: 6, aliases: ["Eph", "Ephes", "Ef"] },
{ code: "PHP", en: "Philippians", af: "Filippense", chapters: 4, aliases: ["Phil", "Php", "Pp", "Fil"] },
{ code: "COL", en: "Colossians", af: "Kolossense", chapters: 4, aliases: ["Col", "Co", "Kol"] },
{ code: "1TH", en: "1 Thessalonians", af: "1 Tessalonisense", chapters: 5, aliases: ["1 Thess", "1 Thes", "1 Th", "1 Tess", "1 Tes"] },
{ code: "2TH", en: "2 Thessalonians", af: "2 Tessalonisense", chapters: 3, aliases: ["2 Thess", "2 Thes", "2 Th", "2 Tess", "2 Tes"] },
{ code: "1TI", en: "1 Timothy", af: "1 Timoteus", chapters: 6, aliases: ["1 Tim", "1 Ti", "1 Tm"] },
{ code: "2TI", en: "2 Timothy", af: "2 Timoteus", chapters: 4, aliases: ["2 Tim", "2 Ti", "2 Tm"] },
{ code: "TIT", en: "Titus", af: "Titus", chapters: 3, aliases: ["Tit", "Ti"] },
{ code: "PHM", en: "Philemon", af: "Filemon", chapters: 1, aliases: ["Philem", "Phm", "Pm", "Filem", "Flm"] },
{ code: "HEB", en: "Hebrews", af: "Hebreërs", chapters: 13, aliases: ["Heb", "He"] },
{ code: "JAS", en: "James", af: "Jakobus", chapters: 5, aliases: ["Jas", "Jm", "Jak"] },
{ code: "1PE", en: "1 Peter", af: "1 Petrus", chapters: 5, aliases: ["1 Pet", "1 Pe", "1 Pt", "1 Petr"] },
{ code: "2PE", en: "2 Peter", af: "2 Petrus", chapters: 3, aliases: ["2 Pet", "2 Pe", "2 Pt", "2 Petr"] },
{ code: "1JN", en: "1 John", af: "1 Johannes", chapters: 5, aliases: ["1 Jn", "1 Jhn", "1 Joh"] },
{ code: "2JN", en: "2 John", af: "2 Johannes", chapters: 1, aliases: ["2 Jn", "2 Jhn", "2 Joh"] },
{ code: "3JN", en: "3 John", af: "3 Johannes", chapters: 1, aliases: ["3 Jn", "3 Jhn", "3 Joh"] },
{ code: "JUD", en: "Jude", af: "Judas", chapters: 1, aliases: ["Jud", "Jd"] },
{ code: "REV", en: "Revelation", af: "Openbaring", chapters: 22, aliases: ["Rev", "Re", "Rv", "Revelations", "Op", "Openb"] },
] as const;
export type BibleBook = (typeof BIBLE_BOOKS)[number];
export const BIBLE_BOOK_CODES = BIBLE_BOOKS.map((b) => b.code) as [BibleBook["code"], ...BibleBook["code"][]];
export const bibleBookCodeSchema = z.enum(BIBLE_BOOK_CODES);
export type BibleBookCode = z.infer<typeof bibleBookCodeSchema>;
export function bibleBook(code: BibleBookCode): BibleBook {
return BIBLE_BOOKS.find((b) => b.code === code)!;
}
/** "1 Korintiërs." → "1korintiers": lower case, no accents, dots or spaces. */
function bookKey(name: string): string {
return name.normalize("NFD").replace(/[̀-ͯ]/g, "").toLowerCase().replace(/[.\s]/g, "");
}
/**
* Name → book. An abbreviation two books share (`Pr`: Proverbs and Prediker, `Co`, `Ti`) goes to
* the first, so the full names always work and the common short forms mostly do.
*/
const BOOK_BY_KEY: ReadonlyMap<string, BibleBook> = (() => {
const map = new Map<string, BibleBook>();
for (const book of BIBLE_BOOKS) {
for (const name of [book.code, book.en, book.af, ...book.aliases]) {
const key = bookKey(name);
if (!map.has(key)) map.set(key, book);
}
}
return map;
})();
/** The book a name or abbreviation means, or null. */
export function findBibleBook(name: string): BibleBook | null {
return BOOK_BY_KEY.get(bookKey(name)) ?? null;
}
// ─── Passages ────────────────────────────────────────────────────────────────
/**
* Where a passage is: a book, a start verse and an end verse (the same chapter or a later one).
* A whole chapter isn't a passage here: devotionals quote the verses they're about (§6).
*/
export const passageLocationSchema = z.object({
book: bibleBookCodeSchema,
chapter: z.int().min(1).max(150),
verse: z.int().min(1).max(176),
endChapter: z.int().min(1).max(150),
endVerse: z.int().min(1).max(176),
}).refine((p) => p.endChapter > p.chapter || (p.endChapter === p.chapter && p.endVerse >= p.verse), "The passage ends before it starts")
.refine((p) => p.endChapter <= bibleBook(p.book).chapters, "The book has fewer chapters");
export type PassageLocation = z.infer<typeof passageLocationSchema>;
export type ParsedReference = { ok: true; passage: PassageLocation } | { ok: false; error: string };
/**
* Reads a reference as people type it: `John 3:16`, `John 3:16-18`, `Johannes 3:16–18`,
* `1 Kor. 13:4-7`, `Rom 8:38-9:1`, `Ps 23 1-3` (a space for the colon), `Jude 3` and `Jude 1:3`
* (one-chapter books). Dashes may be `-`, `–` or `—`; `.` or `,` are taken for the colon too.
*/
export function parseBibleReference(input: string): ParsedReference {
const text = input.trim().replace(/\s+/g, " ");
const match = /^((?:[1-3]\s?)?[^\d\s][^\d]*?)\s*(\d+)(?:(?:\s*[:.,]\s*|\s+)(\d+))?(?:\s*[-–—]\s*(\d+)(?:\s*[:.,]\s*(\d+))?)?$/.exec(text);
if (!match) return { ok: false, error: `"${input}" isn't a Bible reference (e.g. John 3:16-18)` };
const [, name = "", a = "", b, c, d] = match;
const book = findBibleBook(name);
if (!book) return { ok: false, error: `"${name.trim()}" isn't a book of the Bible` };
let chapter: number, verse: number, endChapter: number, endVerse: number;
if (b === undefined) {
// "Jude 3" / "Jude 3-5": a verse in a one-chapter book. "John 3" alone is a whole chapter.
if (book.chapters !== 1) return { ok: false, error: `Give the verses as well as the chapter (e.g. ${book.en} ${a}:1-12)` };
if (d !== undefined) return { ok: false, error: `"${input}" isn't a Bible reference (e.g. ${book.en} 1:3-5)` };
chapter = 1; verse = Number(a); endChapter = 1; endVerse = c === undefined ? verse : Number(c);
} else {
chapter = Number(a); verse = Number(b);
if (d !== undefined) { endChapter = Number(c); endVerse = Number(d); }
else { endChapter = chapter; endVerse = c === undefined ? verse : Number(c); }
}
if (chapter > book.chapters || endChapter > book.chapters) {
return { ok: false, error: `${book.en} has ${book.chapters} chapter${book.chapters === 1 ? "" : "s"}` };
}
const parsed = passageLocationSchema.safeParse({ book: book.code, chapter, verse, endChapter, endVerse });
if (!parsed.success) return { ok: false, error: parsed.error.issues[0]?.message ?? "Not a passage" };
return { ok: true, passage: parsed.data };
}
/** `John 3:16–18`, `Johannes 3:16`, `Romans 8:38–9:1`, in the translation's language. */
export function formatBibleReference(p: PassageLocation, language: "en" | "af" = "en"): string {
const book = bibleBook(p.book);
const start = `${language === "af" ? book.af : book.en} ${p.chapter}:${p.verse}`;
if (p.endChapter !== p.chapter) return `${start}–${p.endChapter}:${p.endVerse}`;
return p.endVerse === p.verse ? start : `${start}–${p.endVerse}`;
}
/** How many verses, when the passage stays in one chapter (null across chapters: verse counts per chapter aren't kept). */
export function passageVerseCount(p: PassageLocation): number | null {
return p.endChapter === p.chapter ? p.endVerse - p.verse + 1 : null;
}
/**
* "Read in YouVersion": `https://www.bible.com/bible/116/JHN.3.16-18.NLT`. YouVersion opens its
* app instead where it's installed. Across chapters it opens at the first verse's chapter.
*/
export function youVersionUrl(p: PassageLocation, translation: BibleTranslationId): string {
const t = bibleTranslation(translation);
const verses = p.endChapter === p.chapter && p.endVerse !== p.verse ? `${p.verse}-${p.endVerse}` : `${p.verse}`;
return `https://www.bible.com/bible/${t.youVersionId}/${p.book}.${p.chapter}.${verses}.${t.id}`;
}
+103 -1
View File
@@ -1,5 +1,6 @@
import { z } from "zod"; import { z } from "zod";
import { dateTimeSchema, productSchema, timezoneSchema, urlSchema } from "./common"; import { dateSchema, dateTimeSchema, productSchema, timezoneSchema, urlSchema } from "./common";
import { devotionalContentSchema, devotionalSourceSchema } from "./devotional";
import { websiteTemplateSchema } from "./style"; import { websiteTemplateSchema } from "./style";
/** /**
@@ -23,6 +24,8 @@ export const exportPersonSchema = z.object({
email: text(254).nullable(), email: text(254).nullable(),
phone: text(40).nullable(), phone: text(40).nullable(),
role: text(40), role: text(40),
/** 1.20.0: every role, where a product gives a person several (the App). `role` is the highest. */
roles: z.array(text(40)).optional(),
createdAt: when, createdAt: when,
consent: z.object({ email: z.boolean().nullable(), whatsapp: z.boolean().nullable(), privacyNoticeAcceptedAt: when }), consent: z.object({ email: z.boolean().nullable(), whatsapp: z.boolean().nullable(), privacyNoticeAcceptedAt: when }),
}); });
@@ -134,6 +137,103 @@ export const exportWebsiteSchema = z.object({
}); });
export type ExportWebsite = z.infer<typeof exportWebsiteSchema>; export type ExportWebsite = z.infer<typeof exportWebsiteSchema>;
// The App's part (contracts 1.20.0, APP-1.0-PLAN §11): the prayer wall's rules, commitments as
// the rules they are (not every occurrence), "I prayed" marks, campaigns, testimonies, prayer
// requests (the whole export is encrypted, AGENT-1.0-PLAN §9), announcements, the church's own
// devotionals (not Cross Code's) and simple events. Members' roles are in `people[].roles`.
export const exportAppCommitmentSchema = z.object({
ref: ref("c"),
personRef: ref("p").nullable(),
/** The first slot, and its length (several slots in a row are one commitment). */
startsAt: when,
minutes: z.int().positive().max(24 * 60),
repeats: z.enum(["once", "weekly", "daily"]),
/** The last day of a recurring commitment (null for a one-off). */
until: dateSchema.nullable(),
/** Occurrences skipped, by the date they'd have started (in the church's timezone). */
skipped: z.array(dateSchema),
reminder: z.enum(["none", "15m", "1h", "evening"]),
channel: z.enum(["email", "whatsapp", "both"]),
/** The member's own "where I'll pray" note. */
note: text(500).nullable(),
createdAt: when,
/** When it was stopped early (the slots opened up). */
stoppedAt: when,
});
export const exportAppCampaignSchema = z.object({
ref: ref("k"),
title: text(300),
description: text().nullable(),
image: uploadPath.nullable(),
startsOn: dateSchema,
endsOn: dateSchema,
goal: text(300).nullable(),
slotTarget: z.int().positive(),
});
export const exportAppPrayerRequestSchema = z.object({
ref: ref("q"),
/** Null for a fully anonymous request (P9). */
personRef: ref("p").nullable(),
visibility: z.enum(["team", "members"]),
showName: z.boolean(),
text: text(5000),
status: z.enum(["waiting", "shared", "team", "escalated", "removed", "closed"]),
prayedCount: z.int().nonnegative(),
createdAt: when,
closedAt: when,
updates: z.array(z.object({ text: text(5000), at: when })),
/** Approve, redact, remove, escalate, close: who and why (the audit, in plain terms). */
moderation: z.array(z.object({ action: z.enum(["approved", "redacted", "removed", "escalated", "closed"]), by: text(300).nullable(), reason: text(1000).nullable(), at: when })),
});
export const exportAppSchema = z.object({
modules: z.array(z.string().regex(/^[a-z][a-z0-9-]*$/)),
prayerWall: z.object({
slotMinutes: z.union([z.literal(15), z.literal(30), z.literal(60)]),
slotTarget: z.int().positive(),
bookAheadMonths: z.int().min(1).max(12),
recurringMaxMonths: z.int().min(1).max(12),
cancelHours: z.int().min(0).max(48),
/** Who members contact inside the cancel window. */
contact: text(500).nullable(),
}),
commitments: z.array(exportAppCommitmentSchema),
/** "I prayed" (self-reported), per slot. */
prayed: z.array(z.object({ personRef: ref("p").nullable(), slotStartsAt: when, at: when })),
campaigns: z.array(exportAppCampaignSchema),
testimonies: z.array(z.object({
personRef: ref("p").nullable(),
campaignRef: ref("k").nullable(),
text: text(5000),
showName: z.boolean(),
status: z.enum(["waiting", "shown", "removed"]),
createdAt: when,
})),
prayerRequests: z.array(exportAppPrayerRequestSchema),
safeguarding: z.object({ emergencyNumbers: z.array(z.object({ name: text(200), number: text(40) })) }),
announcements: z.array(z.object({
title: text(500),
body: text(),
image: uploadPath.nullable(),
button: z.object({ label: text(100), url: urlSchema }).nullable(),
campus: text(200).nullable(),
audience: z.enum(["everyone", "members"]),
pinned: z.boolean(),
publishAt: when,
endsAt: when,
sent: z.object({ email: z.boolean(), whatsapp: z.boolean() }),
})),
/** `crosscode`: the App showed Cross Code's devotionals (they aren't exported: they're Cross Code's). */
devotionalSource: devotionalSourceSchema,
/** The church's own devotionals. */
devotionals: z.array(devotionalContentSchema.extend({ membersOnly: z.boolean() })),
events: z.array(exportWebsiteEventSchema),
});
export type ExportApp = z.infer<typeof exportAppSchema>;
export const churchExportSchema = z.object({ export const churchExportSchema = z.object({
schema: z.literal("crosscode.church-export/1"), schema: z.literal("crosscode.church-export/1"),
exportedAt: dateTimeSchema, exportedAt: dateTimeSchema,
@@ -152,6 +252,8 @@ export const churchExportSchema = z.object({
files: z.array(z.object({ path: uploadPath, bytes: z.int().nonnegative() })), files: z.array(z.object({ path: uploadPath, bytes: z.int().nonnegative() })),
/** Only in the Website's export (contracts 1.17.0). Its editors are in `people`, with their roles. */ /** Only in the Website's export (contracts 1.17.0). Its editors are in `people`, with their roles. */
website: exportWebsiteSchema.optional(), website: exportWebsiteSchema.optional(),
/** Only in the App's export (contracts 1.20.0). */
app: exportAppSchema.optional(),
}); });
export type ChurchExport = z.infer<typeof churchExportSchema>; export type ChurchExport = z.infer<typeof churchExportSchema>;
+9
View File
@@ -16,6 +16,15 @@ export const EVENT_PRODUCTS = ["events", "website", "app"] as const;
export const eventProductSchema = z.enum(EVENT_PRODUCTS); export const eventProductSchema = z.enum(EVENT_PRODUCTS);
export type EventProduct = z.infer<typeof eventProductSchema>; export type EventProduct = z.infer<typeof eventProductSchema>;
/**
* The Church App's modules (contracts 1.20.0, APP-1.0-PLAN §2): each can be switched off. The App
* reports the ones that are on in its heartbeat (`hub.appStatsSchema.modules`, which takes any
* slug so a later module never breaks an older Hub).
*/
export const APP_MODULES = ["house-of-prayer", "prayer-requests", "announcements", "devotionals", "events"] as const;
export const appModuleSchema = z.enum(APP_MODULES);
export type AppModule = z.infer<typeof appModuleSchema>;
/** Ids are UUIDs everywhere: records, installs, licences, customers and account `sub`s. */ /** Ids are UUIDs everywhere: records, installs, licences, customers and account `sub`s. */
export const idSchema = z.uuid(); export const idSchema = z.uuid();
+273
View File
@@ -0,0 +1,273 @@
import { z } from "zod";
import { dateSchema, dateTimeSchema, idSchema } from "./common";
import { schemaName } from "./schema-name";
import {
BIBLE_TRANSLATION_IDS, PASSAGE_WARN_VERSES, bibleTranslation, bibleTranslationIdSchema, formatBibleReference,
parseBibleReference, passageLocationSchema, passageVerseCount, type BibleTranslationId,
} from "./bible";
/**
* `crosscode.devotional/1` (contracts 1.20.0, docs/APP-1.0-PLAN.md §6, decision 1): one day's
* devotional, the same whether Cross Code wrote it in the Hub or the church's Devotional writers
* wrote it in the App, so both show and send alike.
*
* Cross Code's reach an App set to "From Cross Code" from the Hub: `GET /api/v2/devotionals`
* (`hub.DEVOTIONALS_PATH`), once a night, the next 3 months (`devotionalsReplySchema`).
*
* Both write them by hand or import a CSV (`DEVOTIONAL_CSV_COLUMNS`, `checkDevotionalCsv`), with
* the same checks in the Hub and the App.
*/
export const DEVOTIONAL_SCHEMA = schemaName("devotional", 1);
/** Who wrote it: Cross Code (in the Hub) or the church (in the App). */
export const DEVOTIONAL_SOURCES = ["crosscode", "church"] as const;
export const devotionalSourceSchema = z.enum(DEVOTIONAL_SOURCES);
export type DevotionalSource = z.infer<typeof devotionalSourceSchema>;
/** How far ahead the Hub schedules Cross Code's devotionals, and how far ahead an App fetches them. */
export const CROSSCODE_DEVOTIONALS_AHEAD_MONTHS = 3;
export const DEVOTIONAL_LIMITS = { title: 200, reference: 100, passageText: 10_000, body: 20_000, prayer: 5_000, author: 200 } as const;
/**
* The passage a devotional is about: where it is, the translation, and its text as quoted (shown
* in full above the devotional, with the translation's copyright line). `reference` is how it's
* written for people (`formatBibleReference`, in the translation's language).
*/
export const devotionalPassageSchema = z.object({
reference: z.string().trim().min(1).max(DEVOTIONAL_LIMITS.reference),
location: passageLocationSchema,
translation: bibleTranslationIdSchema,
text: z.string().trim().min(1).max(DEVOTIONAL_LIMITS.passageText),
});
export type DevotionalPassage = z.infer<typeof devotionalPassageSchema>;
/** What a writer fills in (the Hub's and App's forms, and a CSV row). */
export const devotionalContentSchema = z.object({
/** The day it's for, in the church's timezone: it shows on Home from midnight. */
date: dateSchema,
title: z.string().trim().min(1).max(DEVOTIONAL_LIMITS.title),
passage: devotionalPassageSchema,
/** Markdown (sanitised when shown). */
body: z.string().trim().min(1).max(DEVOTIONAL_LIMITS.body),
prayer: z.string().trim().min(1).max(DEVOTIONAL_LIMITS.prayer).nullable(),
author: z.string().trim().min(1).max(DEVOTIONAL_LIMITS.author).nullable(),
});
export type DevotionalContent = z.infer<typeof devotionalContentSchema>;
export const devotionalSchema = devotionalContentSchema.extend({
schema: z.literal(DEVOTIONAL_SCHEMA),
id: idSchema,
source: devotionalSourceSchema,
updatedAt: dateTimeSchema,
});
export type Devotional = z.infer<typeof devotionalSchema>;
/**
* The Hub's answer to `GET /api/v2/devotionals?from=YYYY-MM-DD`: Cross Code's devotionals from
* `from` to `to` (3 months on), one per day at most, oldest first. The App replaces its copy of
* that range with them (a day missing from the list was removed in the Hub).
*/
export const devotionalsReplySchema = z.object({
schema: z.literal(DEVOTIONAL_SCHEMA),
from: dateSchema,
to: dateSchema,
devotionals: z.array(devotionalSchema.extend({ source: z.literal("crosscode") })).max(100),
generatedAt: dateTimeSchema,
});
export type DevotionalsReply = z.infer<typeof devotionalsReplySchema>;
/** The passage's copyright line, shown under the verse. */
export function devotionalCopyright(passage: Pick<DevotionalPassage, "translation">): string {
return bibleTranslation(passage.translation).copyright;
}
// ─── CSV import ──────────────────────────────────────────────────────────────
/** The columns, in this order in the template. A file may order them differently. */
export const DEVOTIONAL_CSV_COLUMNS = ["date", "title", "passage", "translation", "passage_text", "body", "prayer", "author"] as const;
export type DevotionalCsvColumn = (typeof DEVOTIONAL_CSV_COLUMNS)[number];
const REQUIRED_COLUMNS: readonly DevotionalCsvColumn[] = ["date", "title", "passage", "translation", "passage_text", "body"];
/** Rows per import (a year and a bit), and the file size the Hub and App accept. */
export const DEVOTIONAL_CSV_MAX_ROWS = 400;
export const DEVOTIONAL_CSV_MAX_BYTES = 2 * 1024 * 1024;
/**
* Reads CSV (RFC 4180: quoted fields, `""` for a quote, line breaks inside quotes), with or
* without a byte-order mark, CRLF or LF. A header with semicolons and no commas means the file
* uses `;` (Excel in some regions). Blank lines are skipped. Each row comes with its line number.
*/
export function parseCsv(text: string): { line: number; cells: string[] }[] {
const src = text.charCodeAt(0) === 0xfeff ? text.slice(1) : text;
const firstLine = src.slice(0, src.search(/\r?\n|$/));
const sep = firstLine.includes(";") && !firstLine.includes(",") ? ";" : ",";
const rows: { line: number; cells: string[] }[] = [];
let cells: string[] = [];
let cell = "";
let quoted = false;
let line = 1;
let rowLine = 1;
const endRow = () => {
cells.push(cell);
if (cells.length > 1 || cells[0]!.trim() !== "") rows.push({ line: rowLine, cells });
cells = []; cell = "";
};
for (let i = 0; i < src.length; i++) {
const ch = src[i]!;
if (quoted) {
if (ch === '"') {
if (src[i + 1] === '"') { cell += '"'; i++; } else quoted = false;
} else {
if (ch === "\n") line++;
cell += ch;
}
} else if (ch === '"' && cell === "") quoted = true;
else if (ch === sep) { cells.push(cell); cell = ""; }
else if (ch === "\r" && src[i + 1] === "\n") continue;
else if (ch === "\n" || ch === "\r") { endRow(); line++; rowLine = line; }
else cell += ch;
}
if (cell !== "" || cells.length > 0) endRow();
return rows;
}
export interface DevotionalCsvIssue { column: DevotionalCsvColumn | null; message: string }
export interface DevotionalCsvRow {
/** The row's line in the file (the header is line 1). */
line: number;
/** Null when the row has errors. */
devotional: DevotionalContent | null;
errors: DevotionalCsvIssue[];
/** Imported anyway, but shown in the preview (a long passage). */
warnings: DevotionalCsvIssue[];
/** The date already has a devotional: the importer chooses to replace or skip it. */
taken: boolean;
}
export interface DevotionalCsvResult {
/** Set when the file can't be read at all (no header, a required column missing, too big). */
fileError: string | null;
rows: DevotionalCsvRow[];
}
export interface DevotionalCsvOptions {
/** Dates that already have a devotional. */
taken?: Iterable<string>;
/** The last date allowed (the Hub: 3 months from today). Later dates are errors. */
latestDate?: string;
}
/**
* Checks a devotionals CSV for the import preview: the header, then every row (a real date,
* the required fields, a passage YouVersion can open, a known translation, the lengths, a date
* twice in the file, a date already filled). Never throws.
*/
export function checkDevotionalCsv(text: string, options: DevotionalCsvOptions = {}): DevotionalCsvResult {
if (text.length > DEVOTIONAL_CSV_MAX_BYTES) return { fileError: "The file is larger than 2 MB", rows: [] };
const all = parseCsv(text);
const header = all[0];
if (!header) return { fileError: "The file is empty", rows: [] };
const names = header.cells.map((c) => c.trim().toLowerCase());
const index = new Map<DevotionalCsvColumn, number>();
for (const column of DEVOTIONAL_CSV_COLUMNS) {
const i = names.indexOf(column);
if (i >= 0) index.set(column, i);
}
const missing = REQUIRED_COLUMNS.filter((c) => !index.has(c));
if (missing.length) return { fileError: `Missing column${missing.length === 1 ? "" : "s"}: ${missing.join(", ")} (the first row must be the column names)`, rows: [] };
const body = all.slice(1);
if (body.length === 0) return { fileError: "The file has no devotionals under the column names", rows: [] };
if (body.length > DEVOTIONAL_CSV_MAX_ROWS) return { fileError: `At most ${DEVOTIONAL_CSV_MAX_ROWS} devotionals per file (this one has ${body.length})`, rows: [] };
const taken = new Set(options.taken ?? []);
const seen = new Map<string, number>();
const rows = body.map(({ line, cells }): DevotionalCsvRow => {
const get = (c: DevotionalCsvColumn) => {
const i = index.get(c);
return i === undefined ? "" : (cells[i] ?? "").trim();
};
const errors: DevotionalCsvIssue[] = [];
const warnings: DevotionalCsvIssue[] = [];
const required = (c: DevotionalCsvColumn, label: string) => {
const v = get(c);
if (!v) errors.push({ column: c, message: `${label} is empty` });
return v;
};
const tooLong = (c: DevotionalCsvColumn, v: string, max: number, label: string) => {
if (v.length > max) errors.push({ column: c, message: `${label} is longer than ${max.toLocaleString("en-ZA")} characters` });
};
const date = required("date", "The date");
if (date && !dateSchema.safeParse(date).success) errors.push({ column: "date", message: `"${date}" isn't a date (use YYYY-MM-DD, e.g. 2027-01-05)` });
else if (date && options.latestDate && date > options.latestDate) errors.push({ column: "date", message: `${date} is more than ${CROSSCODE_DEVOTIONALS_AHEAD_MONTHS} months ahead (the last day is ${options.latestDate})` });
else if (date && seen.has(date)) errors.push({ column: "date", message: `${date} is also on line ${seen.get(date)}` });
if (date && !seen.has(date)) seen.set(date, line);
const title = required("title", "The title");
tooLong("title", title, DEVOTIONAL_LIMITS.title, "The title");
const translationText = required("translation", "The translation");
const translation = BIBLE_TRANSLATION_IDS.find((id) => id === translationText.toUpperCase().replace(/\s/g, "")) as BibleTranslationId | undefined;
if (translationText && !translation) errors.push({ column: "translation", message: `"${translationText}" isn't one of ${BIBLE_TRANSLATION_IDS.join(", ")}` });
const reference = required("passage", "The passage");
const parsed = reference ? parseBibleReference(reference) : null;
if (parsed && !parsed.ok) errors.push({ column: "passage", message: parsed.error });
if (parsed?.ok) {
const verses = passageVerseCount(parsed.passage);
if (verses !== null && verses > PASSAGE_WARN_VERSES) {
warnings.push({ column: "passage", message: `${verses} verses: quote the passage it's about, not whole chapters (publishers limit how much may be quoted)` });
}
}
const passageText = required("passage_text", "The passage's text");
tooLong("passage_text", passageText, DEVOTIONAL_LIMITS.passageText, "The passage's text");
const text = required("body", "The devotional");
tooLong("body", text, DEVOTIONAL_LIMITS.body, "The devotional");
const prayer = get("prayer");
tooLong("prayer", prayer, DEVOTIONAL_LIMITS.prayer, "The prayer");
const author = get("author");
tooLong("author", author, DEVOTIONAL_LIMITS.author, "The author");
const isTaken = !!date && taken.has(date);
if (errors.length || !parsed?.ok || !translation) return { line, devotional: null, errors, warnings, taken: isTaken };
const devotional: DevotionalContent = {
date, title,
passage: {
reference: formatBibleReference(parsed.passage, bibleTranslation(translation).language),
location: parsed.passage, translation, text: passageText,
},
body: text, prayer: prayer || null, author: author || null,
};
const check = devotionalContentSchema.safeParse(devotional);
if (!check.success) return { line, devotional: null, errors: check.error.issues.map((i) => ({ column: null, message: i.message })), warnings, taken: isTaken };
return { line, devotional: check.data, errors, warnings, taken: isTaken };
});
return { fileError: null, rows };
}
/** One field for a CSV file: quoted when it has a separator, quote or line break. */
function csvField(value: string): string {
return /[",;\r\n]/.test(value) ? `"${value.replace(/"/g, '""')}"` : value;
}
/** Builds a devotionals CSV (the template, or an export) with the columns in order and CRLF line ends. */
export function devotionalCsv(rows: Partial<Record<DevotionalCsvColumn, string>>[]): string {
const lines = [DEVOTIONAL_CSV_COLUMNS.join(","), ...rows.map((r) => DEVOTIONAL_CSV_COLUMNS.map((c) => csvField(r[c] ?? "")).join(","))];
return `${lines.join("\r\n")}\r\n`;
}
/** The template the Hub and the App offer for download: the columns and one example row. */
export const DEVOTIONAL_CSV_TEMPLATE = devotionalCsv([{
date: "2027-01-05",
title: "Love that never gives up",
passage: "1 Corinthians 13:4-7",
translation: "NLT",
passage_text: "Love is patient and kind. Love is not jealous or boastful or proud or rude. It does not demand its own way. It is not irritable, and it keeps no record of being wronged. It does not rejoice about injustice but rejoices whenever the truth wins out. Love never gives up, never loses faith, is always hopeful, and endures through every circumstance.",
body: "Paul wrote these words to a church that was proud of its gifts...\n\nA second paragraph after a blank line.",
prayer: "Lord, teach me to love the way you love me.",
author: "Cross Code",
}]);
+12
View File
@@ -222,6 +222,7 @@ export const websiteStatsSchema = z.object({
/** Church App. `activeMembers90d` is what the App tier is billed on. */ /** Church App. `activeMembers90d` is what the App tier is billed on. */
export const appStatsSchema = z.object({ export const appStatsSchema = z.object({
activeMembers90d: activeMemberBandSchema, activeMembers90d: activeMemberBandSchema,
/** The modules switched on (`APP_MODULES`; any slug, so a later module never breaks an older Hub). */
modules: z.array(z.string().regex(/^[a-z][a-z0-9-]*$/)), modules: z.array(z.string().regex(/^[a-z][a-z0-9-]*$/)),
prayer: z.object({ prayer: z.object({
/** Share of the last 7 days' hours with at least one commitment, 0–100. */ /** Share of the last 7 days' hours with at least one commitment, 0–100. */
@@ -324,6 +325,17 @@ export const storageRequestResponseSchema = z.object({
}); });
export type StorageRequestResponse = z.infer<typeof storageRequestResponseSchema>; export type StorageRequestResponse = z.infer<typeof storageRequestResponseSchema>;
// ---------------------------------------------------------------------------------------------
// Cross Code's devotionals (contracts 1.20.0, Hub 2.26.0, APP-1.0-PLAN §6): an App set to "From
// Cross Code" fetches the next 3 months once a night (and on "Sync now"), and keeps its copy, so a
// Hub outage changes nothing. `GET /api/v2/devotionals?from=YYYY-MM-DD` with
// `Authorization: Bearer <the install's licence token>`; App licences only (`403 NOT_AN_APP`),
// active or in grace (`403 LICENCE_INACTIVE`). The answer is a `devotionalsReplySchema`.
// ---------------------------------------------------------------------------------------------
export const DEVOTIONALS_PATH = "/api/v2/devotionals";
export const DEVOTIONALS_ERROR_CODES = ["NOT_AN_APP", "LICENCE_INACTIVE", "BAD_LICENCE", "INVALID_REQUEST"] as const;
// --------------------------------------------------------------------------------------------- // ---------------------------------------------------------------------------------------------
// AI (as v1; usage is recorded per product on the Hub, the cap stays per customer) // AI (as v1; usage is recorded per product on the Hub, the cap stays per customer)
// --------------------------------------------------------------------------------------------- // ---------------------------------------------------------------------------------------------
+72 -1
View File
@@ -16,7 +16,11 @@ import { churchObjectSchema, churchSchema } from "./church";
* (`sealLinkValue` in `@crosscode/contracts/signing`) on top of the request signature. * (`sealLinkValue` in `@crosscode/contracts/signing`) on top of the request signature.
* - **`messaging.*`** (1.9.0): whether Accounts can send email and WhatsApp (its sign-in codes and * - **`messaging.*`** (1.9.0): whether Accounts can send email and WhatsApp (its sign-in codes and
* links need them), and setting them up from a product: a test first, saved only if it worked. * links need them), and setting them up from a product: a test first, saved only if it worked.
* The SMTP password and WAWP access token are sealed with the link's secret. * The SMTP password and WAWP access token are sealed with the link's secret. 1.20.0 adds
* `messaging.get` (the App sends with the church's settings) and the `messaging.changed` hint
* back to the product.
* - **`whatsapp.optout`** (1.20.0): a STOP to the church's WhatsApp number, passed on to Accounts,
* which keeps the opt-out for every product.
* - **`people.*`**: what a product's admin can do to someone's account from the product (add a * - **`people.*`**: what a product's admin can do to someone's account from the product (add a
* person, change their name or email, reset 2FA, unlock, deactivate, news off from an * person, change their name or email, reset 2FA, unlock, deactivate, news off from an
* unsubscribe link). Accounts only acts on people the product knows (signed in through it or * unsubscribe link). Accounts only acts on people the product knows (signed in through it or
@@ -237,6 +241,32 @@ export const messagingTestSchema = base.extend({
/** Tests the settings given as messaging.test does, and saves each part only if its test worked. */ /** Tests the settings given as messaging.test does, and saves each part only if its test worked. */
export const messagingSetSchema = messagingTestSchema.extend({ type: z.literal("messaging.set") }); export const messagingSetSchema = messagingTestSchema.extend({ type: z.literal("messaging.set") });
/**
* 1.20.0 (APP-1.0-PLAN §8, decision 4): the church's email and WhatsApp settings, for a product
* that sends with them but never asks for its own (the Church App). One set per church: kept in
* Events or Accounts, copied to the others. The SMTP password and WAWP token come sealed with the
* link's secret. Accounts remembers who asked, and sends each a `messaging.changed` when they
* change (`MESSAGING_CHANGED_PATH`), so it fetches them again.
*/
export const messagingGetSchema = base.extend({ type: z.literal("messaging.get") });
/**
* 1.20.0 (APP-1.0-PLAN §8, decision 11): someone replied STOP to the church's WhatsApp number.
* Whichever product's webhook received it tells Accounts, which keeps the opt-out for every
* product: it sets `whatsapp_opted_out` on each account with that verified number and sends
* `user.updated` to every linked product. Only ever turns WhatsApp off; turning it back on is the
* person's own choice in Accounts. Accounts also keeps a number without an account, so an account
* made with it later starts opted out.
*/
export const whatsappOptOutSchema = base.extend({
type: z.literal("whatsapp.optout"),
phone: phoneSchema,
/** When the reply arrived. */
receivedAt: dateTimeSchema,
/** The word they sent (`STOP`, `UNSUBSCRIBE`, `STOPP`), for the audit. */
keyword: z.string().trim().min(1).max(40),
});
/** /**
* 1.9.0: use the product's look (name, logo, colours) on Accounts' pages. `overwrite: false` only * 1.9.0: use the product's look (name, logo, colours) on Accounts' pages. `overwrite: false` only
* fills what Accounts doesn't have yet; `true` replaces it (an admin pressing the button). * fills what Accounts doesn't have yet; `true` replaces it (an admin pressing the button).
@@ -277,6 +307,7 @@ export const identityRequestSchema = z.discriminatedUnion("type", [
importBeginSchema, importBatchSchema, importFinishSchema, importAbortSchema, importBeginSchema, importBatchSchema, importFinishSchema, importAbortSchema,
peopleEnsureSchema, peopleUpdateSchema, peopleResetTwoFactorSchema, peopleUnlockSchema, peopleSetActiveSchema, peopleNewsOffSchema, peopleEnsureSchema, peopleUpdateSchema, peopleResetTwoFactorSchema, peopleUnlockSchema, peopleSetActiveSchema, peopleNewsOffSchema,
peopleRemoveDemoSchema, peopleCheckSchema, messagingStatusSchema, messagingTestSchema, messagingSetSchema, churchBrandingSchema, churchUpdateSchema, peopleRemoveDemoSchema, peopleCheckSchema, messagingStatusSchema, messagingTestSchema, messagingSetSchema, churchBrandingSchema, churchUpdateSchema,
messagingGetSchema, whatsappOptOutSchema,
]); ]);
export type IdentityRequest = z.infer<typeof identityRequestSchema>; export type IdentityRequest = z.infer<typeof identityRequestSchema>;
export type IdentityRequestType = IdentityRequest["type"]; export type IdentityRequestType = IdentityRequest["type"];
@@ -356,6 +387,46 @@ export const messagingTestReplySchema = z.object({
}); });
export type MessagingTestReply = z.infer<typeof messagingTestReplySchema>; export type MessagingTestReply = z.infer<typeof messagingTestReplySchema>;
/**
* messaging.get: the settings, secrets sealed with the link's secret; null for a part that isn't
* set up (or doesn't work: `ready` false in messaging.status). `email.pass` null: the server
* takes no password. `updatedAt`: the last change to either part.
*/
export const messagingGetReplySchema = z.object({
schema: z.literal(IDENTITY_REQUEST_SCHEMA),
email: smtpSettingsSchema.nullable(),
whatsapp: wawpSettingsSchema.extend({ accessToken: sealedValueSchema }).nullable(),
updatedAt: dateTimeSchema.nullable(),
});
export type MessagingGetReply = z.infer<typeof messagingGetReplySchema>;
/** whatsapp.optout: how many accounts have the number (0 is fine: the number is kept anyway). */
export const whatsappOptOutReplySchema = z.object({
schema: z.literal(IDENTITY_REQUEST_SCHEMA),
accounts: z.int().nonnegative(),
});
export type WhatsappOptOutReply = z.infer<typeof whatsappOptOutReplySchema>;
// ─── Accounts → product: messaging.changed (1.20.0) ─────────────────────────
/** On the product's address. Signed with the link's secret (LINK_HEADERS). */
export const MESSAGING_CHANGED_PATH = "/api/accounts/v1/messaging-changed";
/**
* A hint, as `church.changed` is: the church's email or WhatsApp settings changed (in Accounts,
* or copied in from Events), so send `messaging.get` again. Sent to the products that asked for
* them. The product answers `{ ok: true }` (`okReplySchema`); Accounts retries otherwise.
*/
export const messagingChangedSchema = z.object({
schema: z.literal(IDENTITY_REQUEST_SCHEMA),
type: z.literal("messaging.changed"),
occurredAt: dateTimeSchema,
/** Which parts changed. */
email: z.boolean(),
whatsapp: z.boolean(),
});
export type MessagingChanged = z.infer<typeof messagingChangedSchema>;
/** church.update: the profile after the change. */ /** church.update: the profile after the change. */
export const churchUpdateReplySchema = z.object({ schema: z.literal(IDENTITY_REQUEST_SCHEMA), church: churchSchema }); export const churchUpdateReplySchema = z.object({ schema: z.literal(IDENTITY_REQUEST_SCHEMA), church: churchSchema });
export type ChurchUpdateReply = z.infer<typeof churchUpdateReplySchema>; export type ChurchUpdateReply = z.infer<typeof churchUpdateReplySchema>;
+6
View File
@@ -35,6 +35,12 @@ export const profileSchema = z.object({
phone_number_verified: z.boolean(), phone_number_verified: z.boolean(),
/** Whether the church may send this person news, per channel. */ /** Whether the church may send this person news, per channel. */
news_consent: newsConsentSchema, news_consent: newsConsentSchema,
/**
* 1.20.0: the person replied STOP to the church's WhatsApp number (APP-1.0-PLAN §8, decision
* 11). No product sends them WhatsApp of any kind, reminders included, until they turn it back
* on in Accounts. Accounts keeps it for every product. Absent (an older Accounts): false.
*/
whatsapp_opted_out: z.boolean().optional(),
}); });
export type Profile = z.infer<typeof profileSchema>; export type Profile = z.infer<typeof profileSchema>;
+2
View File
@@ -15,4 +15,6 @@ export * from "./oidc";
export * as hub from "./hub"; export * as hub from "./hub";
export * as agent from "./agent"; export * as agent from "./agent";
export * from "./church-export"; export * from "./church-export";
export * from "./bible";
export * from "./devotional";
export { canonicalJson } from "./canonical"; export { canonicalJson } from "./canonical";
+8 -1
View File
@@ -141,7 +141,7 @@ describe("exports", () => {
expect(() => decryptExport(file, encryptExport(zip).key)).toThrow(); expect(() => decryptExport(file, encryptExport(zip).key)).toThrow();
}); });
it.each(["church-export.json", "church-export-website.json"])("%s has no internal ids", (file) => { it.each(["church-export.json", "church-export-website.json", "church-export-app.json"])("%s has no internal ids", (file) => {
const data = sample(file); const data = sample(file);
expect(churchExportSchema.safeParse(data).success).toBe(true); expect(churchExportSchema.safeParse(data).success).toBe(true);
const keys: string[] = []; const keys: string[] = [];
@@ -174,6 +174,13 @@ describe("seed-demo jobs", () => {
expect(args({ church: "hope", product: "accounts", profile: "small" })).toBe(false); expect(args({ church: "hope", product: "accounts", profile: "small" })).toBe(false);
expect(agent.WEBSITE_DEMO_PROFILES).toHaveLength(8); expect(agent.WEBSITE_DEMO_PROFILES).toHaveLength(8);
}); });
it("1.20.0: an App demo names the product and takes only an App profile, without an admin email", () => {
expect(agent.DEMO_PRODUCTS).toContain("app");
expect(args({ church: "demo2", product: "app", profile: "acacia-hill" })).toBe(true);
expect(args({ church: "demo2", product: "app", profile: "bold-plant" })).toBe(false);
expect(args({ church: "demo2", profile: "acacia-hill" })).toBe(false);
expect(args({ church: "demo2", product: "app", profile: "acacia-hill", adminEmail: "jane@hope.test" })).toBe(false);
});
}); });
describe("env-read and env-set jobs (1.12.0)", () => { describe("env-read and env-set jobs (1.12.0)", () => {
+183
View File
@@ -0,0 +1,183 @@
import {
BIBLE_BOOKS, BIBLE_TRANSLATIONS, DEVOTIONAL_CSV_COLUMNS, DEVOTIONAL_CSV_TEMPLATE, checkDevotionalCsv, devotionalCsv,
devotionalsReplySchema, findBibleBook, formatBibleReference, parseBibleReference, parseCsv, passageVerseCount, youVersionUrl,
type PassageLocation,
} from "../src";
import { sample } from "./helpers";
const ok = (input: string): PassageLocation => {
const r = parseBibleReference(input);
if (!r.ok) throw new Error(`${input}: ${r.error}`);
return r.passage;
};
describe("Bible books and translations", () => {
it("has the 66 books with unique codes", () => {
expect(BIBLE_BOOKS).toHaveLength(66);
expect(new Set(BIBLE_BOOKS.map((b) => b.code)).size).toBe(66);
});
it("finds every book by its English and Afrikaans name and its code", () => {
for (const b of BIBLE_BOOKS) {
expect(findBibleBook(b.en)?.code).toBe(b.code);
expect(findBibleBook(b.af)?.code).toBe(b.code);
expect(findBibleBook(b.code)?.code).toBe(b.code);
}
});
it("ignores case, accents, dots and spaces", () => {
expect(findBibleBook("1 korintiers")?.code).toBe("1CO");
expect(findBibleBook("1Kor.")?.code).toBe("1CO");
expect(findBibleBook("ESEGIËL")?.code).toBe("EZK");
expect(findBibleBook("Ps")?.code).toBe("PSA");
expect(findBibleBook("Nowhere")).toBeNull();
});
it("has the seven translations, with unique ids and YouVersion numbers", () => {
expect(BIBLE_TRANSLATIONS.map((t) => t.id)).toEqual(["NLT", "ESV", "NIV", "NKJV", "KJV", "AFR53", "AFR83"]);
expect(new Set(BIBLE_TRANSLATIONS.map((t) => t.youVersionId)).size).toBe(7);
for (const t of BIBLE_TRANSLATIONS) expect(t.copyright.length).toBeGreaterThan(10);
});
});
describe("parseBibleReference", () => {
it.each([
["John 3:16", { book: "JHN", chapter: 3, verse: 16, endChapter: 3, endVerse: 16 }],
["John 3:16-18", { book: "JHN", chapter: 3, verse: 16, endChapter: 3, endVerse: 18 }],
["Johannes 3:16–18", { book: "JHN", chapter: 3, verse: 16, endChapter: 3, endVerse: 18 }],
["1 Kor. 13:4 - 7", { book: "1CO", chapter: 13, verse: 4, endChapter: 13, endVerse: 7 }],
["Rom 8:38-9:1", { book: "ROM", chapter: 8, verse: 38, endChapter: 9, endVerse: 1 }],
["Ps 23 1-3", { book: "PSA", chapter: 23, verse: 1, endChapter: 23, endVerse: 3 }],
["Psalm 23.1", { book: "PSA", chapter: 23, verse: 1, endChapter: 23, endVerse: 1 }],
["Jude 3", { book: "JUD", chapter: 1, verse: 3, endChapter: 1, endVerse: 3 }],
["Judas 3-5", { book: "JUD", chapter: 1, verse: 3, endChapter: 1, endVerse: 5 }],
["Jude 1:3", { book: "JUD", chapter: 1, verse: 3, endChapter: 1, endVerse: 3 }],
["Song of Songs 2:4", { book: "SNG", chapter: 2, verse: 4, endChapter: 2, endVerse: 4 }],
])("reads %s", (input, expected) => {
expect(ok(input)).toEqual(expected);
});
it.each([
["", "isn't a Bible reference"],
["John", "isn't a Bible reference"],
["John 3", "Give the verses"],
["John 316", "Give the verses"],
["Hezekiah 3:1", "isn't a book"],
["John 22:1", "John has 21 chapters"],
["John 3:18-16", "ends before it starts"],
["Rom 9:1-8:38", "ends before it starts"],
])("refuses %p", (input, message) => {
const r = parseBibleReference(input);
expect(r.ok).toBe(false);
if (!r.ok) expect(r.error).toContain(message);
});
it("formats in the translation's language", () => {
expect(formatBibleReference(ok("john 3:16-18"))).toBe("John 3:16–18");
expect(formatBibleReference(ok("John 3:16-18"), "af")).toBe("Johannes 3:16–18");
expect(formatBibleReference(ok("Rom 8:38-9:1"))).toBe("Romans 8:38–9:1");
expect(formatBibleReference(ok("Jude 3"))).toBe("Jude 1:3");
});
it("counts verses within a chapter only", () => {
expect(passageVerseCount(ok("1 Cor 13:4-7"))).toBe(4);
expect(passageVerseCount(ok("Rom 8:38-9:1"))).toBeNull();
});
it("builds the YouVersion link", () => {
expect(youVersionUrl(ok("John 3:16-18"), "NLT")).toBe("https://www.bible.com/bible/116/JHN.3.16-18.NLT");
expect(youVersionUrl(ok("Johannes 3:16"), "AFR83")).toBe("https://www.bible.com/bible/6/JHN.3.16.AFR83");
expect(youVersionUrl(ok("Rom 8:38-9:1"), "ESV")).toBe("https://www.bible.com/bible/59/ROM.8.38.ESV");
});
});
describe("parseCsv", () => {
it("reads quotes, doubled quotes, line breaks in quotes, CRLF and a BOM", () => {
const rows = parseCsv(String.fromCharCode(0xfeff) + 'a,b\r\n"x, y","say ""hi"""\r\n"two\nlines",z\r\n\r\nlast,row');
expect(rows).toEqual([
{ line: 1, cells: ["a", "b"] },
{ line: 2, cells: ["x, y", 'say "hi"'] },
{ line: 3, cells: ["two\nlines", "z"] },
{ line: 6, cells: ["last", "row"] },
]);
});
it("takes semicolons when the header has them and no commas", () => {
expect(parseCsv("a;b\n1,5;2\n")).toEqual([{ line: 1, cells: ["a", "b"] }, { line: 2, cells: ["1,5", "2"] }]);
});
});
describe("checkDevotionalCsv", () => {
const row = (over: Partial<Record<(typeof DEVOTIONAL_CSV_COLUMNS)[number], string>> = {}) => ({
date: "2027-01-05", title: "Love", passage: "1 Cor 13:4-7", translation: "NLT", passage_text: "Love is patient and kind.",
body: "Text.", prayer: "", author: "", ...over,
});
it("accepts the template", () => {
const r = checkDevotionalCsv(DEVOTIONAL_CSV_TEMPLATE);
expect(r.fileError).toBeNull();
expect(r.rows).toHaveLength(1);
expect(r.rows[0]!.errors).toEqual([]);
expect(r.rows[0]!.devotional?.passage).toMatchObject({ reference: "1 Corinthians 13:4–7", translation: "NLT" });
});
it("turns a good row into a devotional, in the translation's language, empty optional fields null", () => {
const r = checkDevotionalCsv(devotionalCsv([row({ passage: "Joh 3:16", translation: "afr83" })]));
expect(r.rows[0]!.devotional).toEqual({
date: "2027-01-05", title: "Love",
passage: { reference: "Johannes 3:16", location: { book: "JHN", chapter: 3, verse: 16, endChapter: 3, endVerse: 16 }, translation: "AFR83", text: "Love is patient and kind." },
body: "Text.", prayer: null, author: null,
});
});
it("reports each bad field with its column and line", () => {
const r = checkDevotionalCsv(devotionalCsv([
row({ date: "5 Jan 2027" }),
row({ date: "2027-01-06", title: "" }),
row({ date: "2027-01-07", passage: "Hezekiah 1:1" }),
row({ date: "2027-01-08", translation: "MSG" }),
row({ date: "2027-01-09", body: "x".repeat(20_001) }),
row({ date: "2027-01-06" }),
]));
const errors = r.rows.map((x) => ({ line: x.line, columns: x.errors.map((e) => e.column), ok: x.devotional !== null }));
expect(errors).toEqual([
{ line: 2, columns: ["date"], ok: false },
{ line: 3, columns: ["title"], ok: false },
{ line: 4, columns: ["passage"], ok: false },
{ line: 5, columns: ["translation"], ok: false },
{ line: 6, columns: ["body"], ok: false },
{ line: 7, columns: ["date"], ok: false },
]);
expect(r.rows[5]!.errors[0]!.message).toContain("also on line 3");
});
it("marks taken days, refuses days past the limit and warns on long passages", () => {
const r = checkDevotionalCsv(devotionalCsv([row(), row({ date: "2027-01-06", passage: "Ps 119:1-40" }), row({ date: "2027-05-01" })]), {
taken: ["2027-01-05"], latestDate: "2027-03-31",
});
expect(r.rows[0]).toMatchObject({ taken: true, errors: [] });
expect(r.rows[1]!.warnings[0]!.message).toContain("40 verses");
expect(r.rows[1]!.devotional).not.toBeNull();
expect(r.rows[2]!.errors[0]!.message).toContain("more than 3 months ahead");
});
it("refuses a file without the required columns, or without rows", () => {
expect(checkDevotionalCsv("").fileError).toBe("The file is empty");
expect(checkDevotionalCsv("date,title\n2027-01-05,Love\n").fileError).toContain("passage, translation, passage_text, body");
expect(checkDevotionalCsv(`${DEVOTIONAL_CSV_COLUMNS.join(",")}\n`).fileError).toContain("no devotionals");
});
it("takes columns in any order, and without the optional ones", () => {
const r = checkDevotionalCsv("body,passage_text,translation,passage,title,date\nText.,Words.,KJV,Gen 1:1,In the beginning,2027-02-01\n");
expect(r.rows[0]!.devotional).toMatchObject({ date: "2027-02-01", prayer: null, passage: { reference: "Genesis 1:1", translation: "KJV" } });
});
});
describe("devotionals reply", () => {
it("only carries Cross Code's devotionals", () => {
const reply = sample<{ devotionals: { source: string }[] }>("devotionals-reply.json");
expect(devotionalsReplySchema.safeParse(reply).success).toBe(true);
reply.devotionals[0]!.source = "church";
expect(devotionalsReplySchema.safeParse(reply).success).toBe(false);
});
});
@@ -57,6 +57,13 @@ const SAMPLE_SCHEMA: Record<string, string> = {
"people-check-reply.json": "people-check-reply", "people-check-reply.json": "people-check-reply",
"church-update.json": "identity-request", "church-update.json": "identity-request",
"church-update-reply.json": "church-update-reply", "church-update-reply.json": "church-update-reply",
"church-export-app.json": "church-export",
"messaging-get.json": "identity-request",
"messaging-get-reply.json": "messaging-get-reply",
"messaging-changed.json": "messaging-changed",
"whatsapp-optout.json": "identity-request",
"whatsapp-optout-reply.json": "whatsapp-optout-reply",
"devotionals-reply.json": "devotionals-reply",
}; };
describe("JSON Schema (schemas/)", () => { describe("JSON Schema (schemas/)", () => {
+8
View File
@@ -20,6 +20,7 @@ import {
peopleRemoveDemoReplySchema, peopleCheckReplySchema, churchUpdateReplySchema, peopleRemoveDemoReplySchema, peopleCheckReplySchema, churchUpdateReplySchema,
userDeletedReplySchema, userDeletedReplySchema,
userExportReplySchema, userExportReplySchema,
messagingGetReplySchema, messagingChangedSchema, whatsappOptOutReplySchema, devotionalsReplySchema,
} from "../src"; } from "../src";
import { SAMPLES, sample } from "./helpers"; import { SAMPLES, sample } from "./helpers";
@@ -66,6 +67,13 @@ const SCHEMAS: Record<string, z.ZodType> = {
"people-check-reply.json": peopleCheckReplySchema, "people-check-reply.json": peopleCheckReplySchema,
"church-update.json": identityRequestSchema, "church-update.json": identityRequestSchema,
"church-update-reply.json": churchUpdateReplySchema, "church-update-reply.json": churchUpdateReplySchema,
"church-export-app.json": churchExportSchema,
"messaging-get.json": identityRequestSchema,
"messaging-get-reply.json": messagingGetReplySchema,
"messaging-changed.json": messagingChangedSchema,
"whatsapp-optout.json": identityRequestSchema,
"whatsapp-optout-reply.json": whatsappOptOutReplySchema,
"devotionals-reply.json": devotionalsReplySchema,
}; };
describe("samples", () => { describe("samples", () => {