- Each translation has a licence; FREE_BIBLE_TRANSLATION_IDS (KJV and the new Berean Standard Bible) is what the Hub and App 1.0 offer, and the CSV import refuses any other when told to, naming the publisher to ask. - The publishers' exact notices (NLT, ESV, AFR53, AFR83 corrected), an acknowledgement per translation, the Bible Society's disclaimer, publisher and permissionsUrl, FREE_QUOTE_VERSES and quotedVerses. AFR83 is named "Afrikaans 1983/1992-vertaling". - docs/BIBLE-PERMISSIONS.md: what each publisher allows, the status and the drafted permission requests. APP-1.0-PLAN decision 14, HANDOVER (with the Website 1.8.0 approach), VERSIONS, CHANGELOG. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
303 lines
15 KiB
TypeScript
303 lines
15 KiB
TypeScript
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;
|
|
}
|
|
|
|
/** The publisher's disclaimer shown with the copyright line, or null (Bible Society translations only). */
|
|
export function devotionalDisclaimer(passage: Pick<DevotionalPassage, "translation">): string | null {
|
|
return bibleTranslation(passage.translation).disclaimer;
|
|
}
|
|
|
|
/**
|
|
* Verses quoted per translation, for the free allowance (`FREE_QUOTE_VERSES`, counted across the
|
|
* whole App). A passage across chapters can't be counted (verse counts per chapter aren't kept)
|
|
* and goes in `uncounted`, so a warning can say the total is at least this.
|
|
*/
|
|
export function quotedVerses(passages: readonly Pick<DevotionalPassage, "location" | "translation">[]): {
|
|
verses: Partial<Record<BibleTranslationId, number>>;
|
|
uncounted: Partial<Record<BibleTranslationId, number>>;
|
|
} {
|
|
const verses: Partial<Record<BibleTranslationId, number>> = {};
|
|
const uncounted: Partial<Record<BibleTranslationId, number>> = {};
|
|
for (const p of passages) {
|
|
const n = passageVerseCount(p.location);
|
|
if (n === null) uncounted[p.translation] = (uncounted[p.translation] ?? 0) + 1;
|
|
else verses[p.translation] = (verses[p.translation] ?? 0) + n;
|
|
}
|
|
return { verses, uncounted };
|
|
}
|
|
|
|
// ─── 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;
|
|
/** The translations allowed (the Hub and App 1.0: `FREE_BIBLE_TRANSLATION_IDS`). Any by default. */
|
|
translations?: readonly BibleTranslationId[];
|
|
}
|
|
|
|
/**
|
|
* 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 ${(options.translations ?? BIBLE_TRANSLATION_IDS).join(", ")}` });
|
|
else if (translation && options.translations && !options.translations.includes(translation)) {
|
|
errors.push({ column: "translation", message: `${translation} needs ${bibleTranslation(translation).publisher ?? "the publisher"}'s permission; use ${options.translations.join(" or ")}` });
|
|
}
|
|
|
|
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: "BSB",
|
|
passage_text: "Love is patient, love is kind. It does not envy, it does not boast, it is not proud. It is not rude, it is not self-seeking, it is not easily angered, it keeps no account of wrongs. Love takes no pleasure in evil, but rejoices in the truth. It bears all things, believes all things, hopes all things, endures all things.",
|
|
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",
|
|
}]);
|