feat: add journals

This commit is contained in:
gosangam
2026-05-03 21:02:41 +05:30
parent 89106efc98
commit 35d1d14f37
47 changed files with 11365 additions and 37 deletions
+299
View File
@@ -0,0 +1,299 @@
/**
* Data access layer for Bhagavāner Kathā (BK).
*
* Reads from MongoDB via Prisma, same as the rest of the app.
* BK is a simple prose book with no volume structure and no intro segments —
* just 2 chapters directly. We use volume=0 as the sentinel for "no volumes".
*
* When the DB isn't seeded yet, falls back to reading local JSON files
* from lib/jsons/books/bk/.
*
* Collections used:
* - book_meta (via Prisma BookMeta model)
* - prose_chapters (via Prisma ProseChapter model)
*/
import { prisma } from "@/lib/db";
import type { JsonValue } from "@prisma/client/runtime/library";
import fs from "fs";
import path from "path";
// ---------------------------------------------------------------------------
// Constants
// ---------------------------------------------------------------------------
/** Volume sentinel for books without volumes. */
const NO_VOLUME = 0;
const BOOK = "bk";
const BK_JSON_DIR = path.join(process.cwd(), "lib", "jsons", "books", "bk");
// ---------------------------------------------------------------------------
// Types
// ---------------------------------------------------------------------------
export type BkMeta = {
book: string;
title: string;
author: string;
year?: number | null;
description: string;
totalChapters: number;
chapters: BkChapterEntry[];
};
export type BkChapterEntry = {
number: number;
title: string;
};
export type BkChapter = {
book: string;
chapter: number | null;
title: string;
type: string;
slug?: string;
paragraphs: string[];
};
/** Union type used in sidebar / table-of-contents navigation. */
export type BkSidebarItem = {
/** URL-safe slug: "1", "2" */
slug: string;
/** Human-readable label for the sidebar */
label: string;
/** "chapter" */
type: string;
/** Chapter number */
chapter: number | null;
};
// ---------------------------------------------------------------------------
// HTML sanitisation (mirrors lib/api.ts)
// ---------------------------------------------------------------------------
function sanitizeHtml(html: string): string {
let clean = html.replace(/<script[\s>][\s\S]*?<\/script>/gi, "");
clean = clean.replace(/<style[\s>][\s\S]*?<\/style>/gi, "");
clean = clean.replace(/<iframe[\s>][\s\S]*?<\/iframe>/gi, "");
clean = clean.replace(
/<\/?(?:script|style|iframe|object|embed|form|input|textarea|select|button)[^>]*>/gi,
"",
);
clean = clean.replace(/\s+on\w+\s*=\s*(?:"[^"]*"|'[^']*'|[^\s>]+)/gi, "");
clean = clean.replace(/href\s*=\s*"javascript:[^"]*"/gi, 'href=""');
clean = clean.replace(/href\s*=\s*'javascript:[^']*'/gi, "href=''");
return clean;
}
/** Normalize paragraphs — handles both native arrays and stringified JSON. */
function normalizeParagraphs(paragraphs: string[] | JsonValue): string[] {
let result: string[];
if (typeof paragraphs === "string") {
try {
const parsed = JSON.parse(paragraphs);
result = Array.isArray(parsed) ? parsed : [paragraphs];
} catch {
result = [paragraphs];
}
} else if (Array.isArray(paragraphs)) {
result = paragraphs as string[];
} else {
result = [];
}
return result.map(sanitizeHtml);
}
// ---------------------------------------------------------------------------
// Local JSON helpers (fallback when DB is not seeded)
// ---------------------------------------------------------------------------
function readLocalJson<T>(filePath: string): T | null {
if (!fs.existsSync(filePath)) return null;
try {
return JSON.parse(fs.readFileSync(filePath, "utf-8")) as T;
} catch {
return null;
}
}
function getLocalChapter(chapterNum: number): BkChapter | null {
const filePath = path.join(
BK_JSON_DIR,
"chapters",
String(chapterNum).padStart(2, "0") + ".json",
);
return readLocalJson<BkChapter>(filePath);
}
// ---------------------------------------------------------------------------
// Book meta
// ---------------------------------------------------------------------------
/**
* Book-level metadata (title, author, chapter list, etc.)
*/
export async function getBkMeta(): Promise<BkMeta | null> {
const meta = await prisma.bookMeta.findUnique({ where: { book: BOOK } });
if (meta) return meta.data as unknown as BkMeta;
// Fallback to local JSON
const introPath = path.join(BK_JSON_DIR, "intro.json");
return readLocalJson<BkMeta>(introPath);
}
// ---------------------------------------------------------------------------
// Chapters
// ---------------------------------------------------------------------------
/**
* A numbered chapter (1–2).
*/
export async function getBkChapter(
chapterNum: number,
): Promise<BkChapter | null> {
if (chapterNum < 1 || chapterNum > 2 || !Number.isInteger(chapterNum)) {
return null;
}
const doc = await prisma.proseChapter.findUnique({
where: {
book_volume_slug: {
book: BOOK,
volume: NO_VOLUME,
slug: String(chapterNum),
},
},
});
if (doc) {
return {
book: doc.book,
chapter: doc.chapter,
title: doc.title,
type: doc.type,
slug: doc.slug,
paragraphs: normalizeParagraphs(doc.paragraphs),
};
}
// Fallback to local JSON
const local = getLocalChapter(chapterNum);
if (!local) return null;
return {
...local,
paragraphs: local.paragraphs.map(sanitizeHtml),
};
}
// ---------------------------------------------------------------------------
// Unified content accessor
// ---------------------------------------------------------------------------
/**
* Get content by URL slug.
*
* "1" … "2" → chapter
*/
export async function getBkContent(
slug: string,
): Promise<BkChapter | null> {
const num = Number(slug);
if (!Number.isNaN(num) && Number.isInteger(num) && num >= 1 && num <= 2) {
return getBkChapter(num);
}
return null;
}
// ---------------------------------------------------------------------------
// Sidebar navigation
// ---------------------------------------------------------------------------
/**
* Build the full sidebar navigation list.
*
* Order: chapters 1–2 (no intro segments)
*/
export async function getBkSidebarItems(): Promise<BkSidebarItem[]> {
const [meta, allDocs] = await Promise.all([
getBkMeta(),
prisma.proseChapter.findMany({
where: { book: BOOK, volume: NO_VOLUME },
orderBy: { order: "asc" },
select: {
slug: true,
title: true,
type: true,
chapter: true,
order: true,
},
}),
]);
// If we got DB results, build from those
if (meta && allDocs.length > 0) {
return buildSidebarFromDocs(meta);
}
// Fallback: build from local JSON
return buildSidebarFromLocal(meta);
}
function buildSidebarFromDocs(meta: BkMeta): BkSidebarItem[] {
const items: BkSidebarItem[] = [];
// Chapters 1–2 (use meta.chapters for consistent title/ordering)
for (const ch of meta.chapters) {
items.push({
slug: String(ch.number),
label: `Chapter ${ch.number}: ${ch.title}`,
type: "chapter",
chapter: ch.number,
});
}
return items;
}
function buildSidebarFromLocal(meta: BkMeta | null): BkSidebarItem[] {
const items: BkSidebarItem[] = [];
// Chapters from meta or scan local chapter JSONs
if (meta && meta.chapters) {
for (const ch of meta.chapters) {
items.push({
slug: String(ch.number),
label: `Chapter ${ch.number}: ${ch.title}`,
type: "chapter",
chapter: ch.number,
});
}
} else {
// Fallback: scan local chapter JSONs
const chaptersDir = path.join(BK_JSON_DIR, "chapters");
if (fs.existsSync(chaptersDir)) {
const files = fs
.readdirSync(chaptersDir)
.filter((f) => f.endsWith(".json"))
.sort();
for (const file of files) {
const ch = readLocalJson<BkChapter>(path.join(chaptersDir, file));
if (ch) {
const num = ch.chapter ?? parseInt(file.replace(".json", ""), 10);
items.push({
slug: String(num),
label: `Chapter ${num}: ${ch.title}`,
type: "chapter",
chapter: num,
});
}
}
}
}
return items;
}
+299
View File
@@ -0,0 +1,299 @@
/**
* Data access layer for Śrī Caitanya-bhāgavata Commentary (CBHC).
*
* Reads from MongoDB via Prisma, same as the rest of the app.
* CBHC is a simple prose book with no volume structure and no intro segments —
* just 4 chapters directly. We use volume=0 as the sentinel for "no volumes".
*
* When the DB isn't seeded yet, falls back to reading local JSON files
* from lib/jsons/books/cbhc/.
*
* Collections used:
* - book_meta (via Prisma BookMeta model)
* - prose_chapters (via Prisma ProseChapter model)
*/
import { prisma } from "@/lib/db";
import type { JsonValue } from "@prisma/client/runtime/library";
import fs from "fs";
import path from "path";
// ---------------------------------------------------------------------------
// Constants
// ---------------------------------------------------------------------------
/** Volume sentinel for books without volumes. */
const NO_VOLUME = 0;
const BOOK = "cbhc";
const CBHC_JSON_DIR = path.join(process.cwd(), "lib", "jsons", "books", "cbhc");
// ---------------------------------------------------------------------------
// Types
// ---------------------------------------------------------------------------
export type CbhcMeta = {
book: string;
title: string;
author: string;
year?: number | null;
description: string;
totalChapters: number;
chapters: CbhcChapterEntry[];
};
export type CbhcChapterEntry = {
number: number;
title: string;
};
export type CbhcChapter = {
book: string;
chapter: number | null;
title: string;
type: string;
slug?: string;
paragraphs: string[];
};
/** Union type used in sidebar / table-of-contents navigation. */
export type CbhcSidebarItem = {
/** URL-safe slug: "1", "2", "3", "4" */
slug: string;
/** Human-readable label for the sidebar */
label: string;
/** "chapter" */
type: string;
/** Chapter number */
chapter: number | null;
};
// ---------------------------------------------------------------------------
// HTML sanitisation (mirrors lib/api.ts)
// ---------------------------------------------------------------------------
function sanitizeHtml(html: string): string {
let clean = html.replace(/<script[\s>][\s\S]*?<\/script>/gi, "");
clean = clean.replace(/<style[\s>][\s\S]*?<\/style>/gi, "");
clean = clean.replace(/<iframe[\s>][\s\S]*?<\/iframe>/gi, "");
clean = clean.replace(
/<\/?(?:script|style|iframe|object|embed|form|input|textarea|select|button)[^>]*>/gi,
"",
);
clean = clean.replace(/\s+on\w+\s*=\s*(?:"[^"]*"|'[^']*'|[^\s>]+)/gi, "");
clean = clean.replace(/href\s*=\s*"javascript:[^"]*"/gi, 'href=""');
clean = clean.replace(/href\s*=\s*'javascript:[^']*'/gi, "href=''");
return clean;
}
/** Normalize paragraphs — handles both native arrays and stringified JSON. */
function normalizeParagraphs(paragraphs: string[] | JsonValue): string[] {
let result: string[];
if (typeof paragraphs === "string") {
try {
const parsed = JSON.parse(paragraphs);
result = Array.isArray(parsed) ? parsed : [paragraphs];
} catch {
result = [paragraphs];
}
} else if (Array.isArray(paragraphs)) {
result = paragraphs as string[];
} else {
result = [];
}
return result.map(sanitizeHtml);
}
// ---------------------------------------------------------------------------
// Local JSON helpers (fallback when DB is not seeded)
// ---------------------------------------------------------------------------
function readLocalJson<T>(filePath: string): T | null {
if (!fs.existsSync(filePath)) return null;
try {
return JSON.parse(fs.readFileSync(filePath, "utf-8")) as T;
} catch {
return null;
}
}
function getLocalChapter(chapterNum: number): CbhcChapter | null {
const filePath = path.join(
CBHC_JSON_DIR,
"chapters",
String(chapterNum).padStart(2, "0") + ".json",
);
return readLocalJson<CbhcChapter>(filePath);
}
// ---------------------------------------------------------------------------
// Book meta
// ---------------------------------------------------------------------------
/**
* Book-level metadata (title, author, chapter list, etc.)
*/
export async function getCbhcMeta(): Promise<CbhcMeta | null> {
const meta = await prisma.bookMeta.findUnique({ where: { book: BOOK } });
if (meta) return meta.data as unknown as CbhcMeta;
// Fallback to local JSON
const introPath = path.join(CBHC_JSON_DIR, "intro.json");
return readLocalJson<CbhcMeta>(introPath);
}
// ---------------------------------------------------------------------------
// Chapters
// ---------------------------------------------------------------------------
/**
* A numbered chapter (1–4).
*/
export async function getCbhcChapter(
chapterNum: number,
): Promise<CbhcChapter | null> {
if (chapterNum < 1 || chapterNum > 4 || !Number.isInteger(chapterNum)) {
return null;
}
const doc = await prisma.proseChapter.findUnique({
where: {
book_volume_slug: {
book: BOOK,
volume: NO_VOLUME,
slug: String(chapterNum),
},
},
});
if (doc) {
return {
book: doc.book,
chapter: doc.chapter,
title: doc.title,
type: doc.type,
slug: doc.slug,
paragraphs: normalizeParagraphs(doc.paragraphs),
};
}
// Fallback to local JSON
const local = getLocalChapter(chapterNum);
if (!local) return null;
return {
...local,
paragraphs: local.paragraphs.map(sanitizeHtml),
};
}
// ---------------------------------------------------------------------------
// Unified content accessor
// ---------------------------------------------------------------------------
/**
* Get content by URL slug.
*
* "1" … "4" → chapter
*/
export async function getCbhcContent(
slug: string,
): Promise<CbhcChapter | null> {
const num = Number(slug);
if (!Number.isNaN(num) && Number.isInteger(num) && num >= 1 && num <= 4) {
return getCbhcChapter(num);
}
return null;
}
// ---------------------------------------------------------------------------
// Sidebar navigation
// ---------------------------------------------------------------------------
/**
* Build the full sidebar navigation list.
*
* Order: chapters 1–4 (no intro segments)
*/
export async function getCbhcSidebarItems(): Promise<CbhcSidebarItem[]> {
const [meta, allDocs] = await Promise.all([
getCbhcMeta(),
prisma.proseChapter.findMany({
where: { book: BOOK, volume: NO_VOLUME },
orderBy: { order: "asc" },
select: {
slug: true,
title: true,
type: true,
chapter: true,
order: true,
},
}),
]);
// If we got DB results, build from those
if (meta && allDocs.length > 0) {
return buildSidebarFromDocs(meta);
}
// Fallback: build from local JSON
return buildSidebarFromLocal(meta);
}
function buildSidebarFromDocs(meta: CbhcMeta): CbhcSidebarItem[] {
const items: CbhcSidebarItem[] = [];
// Chapters 1–4 (use meta.chapters for consistent title/ordering)
for (const ch of meta.chapters) {
items.push({
slug: String(ch.number),
label: `Chapter ${ch.number}: ${ch.title}`,
type: "chapter",
chapter: ch.number,
});
}
return items;
}
function buildSidebarFromLocal(meta: CbhcMeta | null): CbhcSidebarItem[] {
const items: CbhcSidebarItem[] = [];
// Chapters from meta or scan local chapter JSONs
if (meta && meta.chapters) {
for (const ch of meta.chapters) {
items.push({
slug: String(ch.number),
label: `Chapter ${ch.number}: ${ch.title}`,
type: "chapter",
chapter: ch.number,
});
}
} else {
// Fallback: scan local chapter JSONs
const chaptersDir = path.join(CBHC_JSON_DIR, "chapters");
if (fs.existsSync(chaptersDir)) {
const files = fs
.readdirSync(chaptersDir)
.filter((f) => f.endsWith(".json"))
.sort();
for (const file of files) {
const ch = readLocalJson<CbhcChapter>(path.join(chaptersDir, file));
if (ch) {
const num = ch.chapter ?? parseInt(file.replace(".json", ""), 10);
items.push({
slug: String(num),
label: `Chapter ${num}: ${ch.title}`,
type: "chapter",
chapter: num,
});
}
}
}
}
return items;
}
+289
View File
@@ -0,0 +1,289 @@
/**
* Data access layer for Journals.
*
* Uses dedicated Prisma models:
* - JournalMeta (collection: journal_meta)
* - JournalChapter (collection: journal_chapters)
*/
import { prisma } from "@/lib/db";
import type { JsonValue } from "@prisma/client/runtime/library";
import fs from "fs";
import path from "path";
const LOCAL_JSON_DIR = path.join(process.cwd(), "lib", "jsons", "journals");
// Types
export type JournalMetaData = {
book: string;
title: string;
author: string;
year: number | null;
description: string | null;
totalChapters: number;
chapters: JournalChapterEntry[];
};
export type JournalSubChapter = { slug: string; title: string };
export type JournalMonthGroup = {
title: string;
subChapters: JournalSubChapter[];
};
export type JournalChapterGroup = {
title: string;
subChapters: (JournalSubChapter | JournalMonthGroup)[];
};
export type JournalChapterEntry =
| JournalSubChapter
| JournalMonthGroup
| JournalChapterGroup;
export type JournalChapterData = {
book: string;
chapter: number;
title: string;
type: string;
paragraphs: string[];
};
export type JournalSummary = {
book: string;
title: string;
author: string;
year: number | null;
description: string | null;
totalChapters: number;
};
export type JournalSidebarItem = {
slug: string;
label: string;
type: string;
chapter: number;
};
// HTML sanitisation
function sanitizeHtml(html: string): string {
let clean = html.replace(/<script[\s>][\s\S]*?<\/script>/gi, "");
clean = clean.replace(/<style[\s>][\s\S]*?<\/style>/gi, "");
clean = clean.replace(/<iframe[\s>][\s\S]*?<\/iframe>/gi, "");
clean = clean.replace(
/<\/?(?:script|style|iframe|object|embed|form|input|textarea|select|button)[^>]*>/gi,
"",
);
clean = clean.replace(/\s+on\w+\s*=\s*(?:"[^"]*"|'[^']*'|[^\s>]+)/gi, "");
clean = clean.replace(/href\s*=\s*"javascript:[^"]*"/gi, 'href=""');
clean = clean.replace(/href\s*=\s*'javascript:[^']*'/gi, "href=''");
return clean;
}
function normalizeParagraphs(paragraphs: string[] | JsonValue): string[] {
let result: string[];
if (typeof paragraphs === "string") {
try {
const parsed = JSON.parse(paragraphs);
result = Array.isArray(parsed) ? parsed : [paragraphs];
} catch {
result = [paragraphs];
}
} else if (Array.isArray(paragraphs)) {
result = paragraphs as string[];
} else {
result = [];
}
return result.map(sanitizeHtml);
}
// Local JSON fallback helpers
function findLocalDirForBook(bookCode: string): string | null {
if (!fs.existsSync(LOCAL_JSON_DIR)) return null;
const entries = fs.readdirSync(LOCAL_JSON_DIR);
for (const entry of entries) {
const introPath = path.join(LOCAL_JSON_DIR, entry, "intro.json");
if (fs.existsSync(introPath)) {
try {
const intro = JSON.parse(fs.readFileSync(introPath, "utf-8"));
if (intro.book === bookCode) return entry;
} catch {
/* skip */
}
}
}
return null;
}
function readLocalJson<T>(filePath: string): T | null {
try {
if (!fs.existsSync(filePath)) return null;
return JSON.parse(fs.readFileSync(filePath, "utf-8")) as T;
} catch {
return null;
}
}
function getAllLocalMetas(): JournalMetaData[] {
if (!fs.existsSync(LOCAL_JSON_DIR)) return [];
const entries = fs.readdirSync(LOCAL_JSON_DIR).sort();
const metas: JournalMetaData[] = [];
for (const entry of entries) {
const introPath = path.join(LOCAL_JSON_DIR, entry, "intro.json");
const intro = readLocalJson<JournalMetaData>(introPath);
if (intro) metas.push(intro);
}
return metas;
}
function getLocalMeta(bookCode: string): JournalMetaData | null {
const dir = findLocalDirForBook(bookCode);
if (!dir) return null;
return readLocalJson<JournalMetaData>(
path.join(LOCAL_JSON_DIR, dir, "intro.json"),
);
}
function getLocalChapterBySlug(
bookCode: string,
slug: string,
): JournalChapterData | null {
const dir = findLocalDirForBook(bookCode);
if (!dir) return null;
// Try slug directly as filename (e.g. "preface.json", "apr-3.json")
const filePath = path.join(LOCAL_JSON_DIR, dir, "chapters", `${slug}.json`);
const data = readLocalJson<JournalChapterData>(filePath);
if (!data) return null;
return { ...data, paragraphs: data.paragraphs.map(sanitizeHtml) };
}
// Public API
export async function getAllJournals(): Promise<JournalSummary[]> {
try {
const results = await prisma.journalMeta.findMany({
orderBy: { book: "asc" },
});
if (results.length > 0) {
return results.map((row) => {
const data = row.data as unknown as JournalMetaData;
return {
book: row.book,
title: data.title,
author: data.author,
year: data.year ?? null,
description: data.description ?? null,
totalChapters: data.totalChapters,
};
});
}
} catch {
/* fall through */
}
const localMetas = getAllLocalMetas();
return localMetas.map((meta) => ({
book: meta.book,
title: meta.title,
author: meta.author,
year: meta.year ?? null,
description: meta.description ?? null,
totalChapters: meta.totalChapters,
}));
}
export async function getJournalMeta(
bookCode: string,
): Promise<JournalMetaData | null> {
try {
const row = await prisma.journalMeta.findUnique({
where: { book: bookCode },
});
if (row) return row.data as unknown as JournalMetaData;
} catch {
/* fall through */
}
return getLocalMeta(bookCode);
}
export async function getJournalChapterBySlug(
bookCode: string,
slug: string,
): Promise<JournalChapterData | null> {
if (!slug) return null;
try {
const doc = await prisma.journalChapter.findUnique({
where: { book_slug: { book: bookCode, slug } },
});
if (doc)
return {
book: doc.book,
chapter: doc.chapter,
title: doc.title,
type: doc.type,
paragraphs: normalizeParagraphs(doc.paragraphs),
};
} catch {
/* fall through */
}
return getLocalChapterBySlug(bookCode, slug);
}
export async function getJournalContent(
bookCode: string,
slug: string,
): Promise<JournalChapterData | null> {
return getJournalChapterBySlug(bookCode, slug);
}
function isSubChapter(ch: JournalChapterEntry): ch is JournalSubChapter {
return "slug" in ch && !("subChapters" in ch);
}
function hasSubChapters(
ch: JournalChapterEntry,
): ch is JournalMonthGroup | JournalChapterGroup {
return "subChapters" in ch && Array.isArray(ch.subChapters);
}
export async function getJournalSidebarItems(
bookCode: string,
): Promise<JournalSidebarItem[]> {
const meta = await getJournalMeta(bookCode);
if (!meta) return [];
const items: JournalSidebarItem[] = [];
function addEntry(entry: JournalChapterEntry) {
if (isSubChapter(entry)) {
items.push({
slug: entry.slug,
label: entry.title,
type: "chapter",
chapter: 0,
});
} else if (hasSubChapters(entry)) {
// Group heading (place name or month name)
items.push({
slug: "",
label: entry.title,
type: "heading",
chapter: 0,
});
for (const sc of entry.subChapters) {
addEntry(sc);
}
}
}
for (const ch of meta.chapters) {
addEntry(ch);
}
return items;
}
export function bookCodeToSlug(bookCode: string): string {
return bookCode;
}
export function slugToBookCode(slug: string): string {
return slug;
}
+430
View File
@@ -0,0 +1,430 @@
/**
* Data access layer for Message of Godhead (MOG).
*
* Reads from MongoDB via Prisma, same as the rest of the app.
* MOG is a prose book with no volume structure —
* we use volume=0 as the sentinel for "no volumes".
*
* When the DB isn't seeded yet, falls back to reading local JSON files
* from lib/jsons/books/mog/.
*
* Collections used:
* - book_meta (via Prisma BookMeta model)
* - prose_chapters (via Prisma ProseChapter model)
*/
import { prisma } from "@/lib/db";
import type { JsonValue } from "@prisma/client/runtime/library";
import fs from "fs";
import path from "path";
// ---------------------------------------------------------------------------
// Constants
// ---------------------------------------------------------------------------
/** Volume sentinel for books without volumes. */
const NO_VOLUME = 0;
const BOOK = "mog";
const MOG_JSON_DIR = path.join(process.cwd(), "lib", "jsons", "books", "mog");
// ---------------------------------------------------------------------------
// Types
// ---------------------------------------------------------------------------
export type MogMeta = {
book: string;
title: string;
author: string;
year?: number;
description: string;
totalChapters: number;
chapters: MogChapterEntry[];
};
export type MogChapterEntry = {
number: number;
title: string;
};
export type MogIntroSegment = {
slug: string;
title: string;
type: string;
book: string;
order: number;
paragraphs: string[];
};
export type MogChapter = {
book: string;
chapter: number | null;
title: string;
type: string;
slug?: string;
paragraphs: string[];
};
/** Union type used in sidebar / table-of-contents navigation. */
export type MogSidebarItem = {
/** URL-safe slug: "intro-front-pages", "1", "2", "3" */
slug: string;
/** Human-readable label for the sidebar */
label: string;
/** "intro-segment" | "chapter" */
type: string;
/** Chapter number, or null for non-chapter items */
chapter: number | null;
};
// ---------------------------------------------------------------------------
// HTML sanitisation (mirrors lib/api.ts)
// ---------------------------------------------------------------------------
function sanitizeHtml(html: string): string {
let clean = html.replace(/<script[\s>][\s\S]*?<\/script>/gi, "");
clean = clean.replace(/<style[\s>][\s\S]*?<\/style>/gi, "");
clean = clean.replace(/<iframe[\s>][\s\S]*?<\/iframe>/gi, "");
clean = clean.replace(
/<\/?(?:script|style|iframe|object|embed|form|input|textarea|select|button)[^>]*>/gi,
"",
);
clean = clean.replace(/\s+on\w+\s*=\s*(?:"[^"]*"|'[^']*'|[^\s>]+)/gi, "");
clean = clean.replace(/href\s*=\s*"javascript:[^"]*"/gi, 'href=""');
clean = clean.replace(/href\s*=\s*'javascript:[^']*'/gi, "href=''");
return clean;
}
/** Normalize paragraphs — handles both native arrays and stringified JSON. */
function normalizeParagraphs(paragraphs: string[] | JsonValue): string[] {
let result: string[];
if (typeof paragraphs === "string") {
try {
const parsed = JSON.parse(paragraphs);
result = Array.isArray(parsed) ? parsed : [paragraphs];
} catch {
result = [paragraphs];
}
} else if (Array.isArray(paragraphs)) {
result = paragraphs as string[];
} else {
result = [];
}
return result.map(sanitizeHtml);
}
// ---------------------------------------------------------------------------
// Local JSON helpers (fallback when DB is not seeded)
// ---------------------------------------------------------------------------
function readLocalJson<T>(filePath: string): T | null {
if (!fs.existsSync(filePath)) return null;
try {
return JSON.parse(fs.readFileSync(filePath, "utf-8")) as T;
} catch {
return null;
}
}
function getLocalIntroSegments(): MogIntroSegment[] {
const introDir = path.join(MOG_JSON_DIR, "intro");
if (!fs.existsSync(introDir)) return [];
const results: MogIntroSegment[] = [];
const files = ["front-pages.json"];
for (const file of files) {
const filePath = path.join(introDir, file);
const seg = readLocalJson<MogIntroSegment>(filePath);
if (seg) results.push(seg);
}
return results.sort((a, b) => (a.order ?? 0) - (b.order ?? 0));
}
function getLocalIntroSegment(rawSlug: string): MogIntroSegment | null {
const filePath = path.join(MOG_JSON_DIR, "intro", `${rawSlug}.json`);
return readLocalJson<MogIntroSegment>(filePath);
}
function getLocalChapter(chapterNum: number): MogChapter | null {
const filePath = path.join(
MOG_JSON_DIR,
"chapters",
String(chapterNum).padStart(2, "0") + ".json",
);
return readLocalJson<MogChapter>(filePath);
}
// ---------------------------------------------------------------------------
// Book meta
// ---------------------------------------------------------------------------
/**
* Book-level metadata (title, author, chapter list, etc.)
*/
export async function getMogMeta(): Promise<MogMeta | null> {
const meta = await prisma.bookMeta.findUnique({ where: { book: BOOK } });
if (meta) return meta.data as unknown as MogMeta;
// Fallback to local JSON
const introPath = path.join(MOG_JSON_DIR, "intro.json");
return readLocalJson<MogMeta>(introPath);
}
// ---------------------------------------------------------------------------
// Intro segments
// ---------------------------------------------------------------------------
/**
* All intro segments, ordered by their `order` field.
*/
export async function getMogIntroSegments(): Promise<MogIntroSegment[]> {
const results = await prisma.proseChapter.findMany({
where: { book: BOOK, volume: NO_VOLUME, type: "intro-segment" },
orderBy: { order: "asc" },
});
if (results.length > 0) {
return results.map((doc) => ({
slug: doc.slug,
title: doc.title,
type: doc.type,
book: doc.book,
order: doc.order,
paragraphs: normalizeParagraphs(doc.paragraphs),
}));
}
// Fallback to local JSON
return getLocalIntroSegments();
}
/**
* A single intro segment by slug.
* Accepts both "intro-front-pages" (URL slug) and "front-pages" (raw slug).
*/
export async function getMogIntroSegment(
slug: string,
): Promise<MogIntroSegment | null> {
// DB stores with "intro-" prefix; accept either form
const dbSlug = slug.startsWith("intro-") ? slug : `intro-${slug}`;
const rawSlug = slug.startsWith("intro-") ? slug.replace(/^intro-/, "") : slug;
const doc = await prisma.proseChapter.findUnique({
where: {
book_volume_slug: { book: BOOK, volume: NO_VOLUME, slug: dbSlug },
},
});
if (doc) {
return {
slug: doc.slug,
title: doc.title,
type: doc.type,
book: doc.book,
order: doc.order,
paragraphs: normalizeParagraphs(doc.paragraphs),
};
}
// Fallback to local JSON
const local = getLocalIntroSegment(rawSlug);
if (!local) return null;
return {
...local,
slug: dbSlug,
paragraphs: local.paragraphs.map(sanitizeHtml),
};
}
// ---------------------------------------------------------------------------
// Chapters
// ---------------------------------------------------------------------------
/**
* A numbered chapter (1–3).
*/
export async function getMogChapter(
chapterNum: number,
): Promise<MogChapter | null> {
if (chapterNum < 1 || chapterNum > 3 || !Number.isInteger(chapterNum)) {
return null;
}
const doc = await prisma.proseChapter.findUnique({
where: {
book_volume_slug: {
book: BOOK,
volume: NO_VOLUME,
slug: String(chapterNum),
},
},
});
if (doc) {
return {
book: doc.book,
chapter: doc.chapter,
title: doc.title,
type: doc.type,
slug: doc.slug,
paragraphs: normalizeParagraphs(doc.paragraphs),
};
}
// Fallback to local JSON
const local = getLocalChapter(chapterNum);
if (!local) return null;
return {
...local,
paragraphs: local.paragraphs.map(sanitizeHtml),
};
}
// ---------------------------------------------------------------------------
// Unified content accessor
// ---------------------------------------------------------------------------
/**
* Get content by URL slug.
*
* "intro-front-pages" → intro segment
* "1" … "3" → chapter
*/
export async function getMogContent(
slug: string,
): Promise<MogChapter | MogIntroSegment | null> {
if (slug.startsWith("intro-")) {
return getMogIntroSegment(slug);
}
const num = Number(slug);
if (!Number.isNaN(num) && Number.isInteger(num) && num >= 1 && num <= 3) {
return getMogChapter(num);
}
return null;
}
// ---------------------------------------------------------------------------
// Sidebar navigation
// ---------------------------------------------------------------------------
/**
* Build the full sidebar navigation list.
*
* Order: front-pages → chapters 1–3
*/
export async function getMogSidebarItems(): Promise<MogSidebarItem[]> {
const [meta, allDocs] = await Promise.all([
getMogMeta(),
prisma.proseChapter.findMany({
where: { book: BOOK, volume: NO_VOLUME },
orderBy: { order: "asc" },
select: {
slug: true,
title: true,
type: true,
chapter: true,
order: true,
},
}),
]);
// If we got DB results, build from those
if (meta && allDocs.length > 0) {
return buildSidebarFromDocs(meta, allDocs);
}
// Fallback: build from local JSON
return buildSidebarFromLocal(meta);
}
function buildSidebarFromDocs(
meta: MogMeta,
allDocs: {
slug: string;
title: string;
type: string;
chapter: number | null;
order: number | null;
}[],
): MogSidebarItem[] {
const items: MogSidebarItem[] = [];
// Intro segments (front-pages)
for (const doc of allDocs) {
if (doc.type === "intro-segment") {
items.push({
slug: doc.slug,
label: doc.title,
type: "intro-segment",
chapter: null,
});
}
}
// Chapters 1–3 (use meta.chapters for consistent title/ordering)
for (const ch of meta.chapters) {
items.push({
slug: String(ch.number),
label: `${ch.number}. ${ch.title}`,
type: "chapter",
chapter: ch.number,
});
}
return items;
}
function buildSidebarFromLocal(meta: MogMeta | null): MogSidebarItem[] {
const items: MogSidebarItem[] = [];
// Local intro segments (front matter)
const introSegs = getLocalIntroSegments();
for (const seg of introSegs) {
items.push({
slug: `intro-${seg.slug}`,
label: seg.title,
type: "intro-segment",
chapter: null,
});
}
// Chapters from meta or scan local chapter JSONs
if (meta && meta.chapters) {
for (const ch of meta.chapters) {
items.push({
slug: String(ch.number),
label: `${ch.number}. ${ch.title}`,
type: "chapter",
chapter: ch.number,
});
}
} else {
// Fallback: scan local chapter JSONs
const chaptersDir = path.join(MOG_JSON_DIR, "chapters");
if (fs.existsSync(chaptersDir)) {
const files = fs
.readdirSync(chaptersDir)
.filter((f) => f.endsWith(".json"))
.sort();
for (const file of files) {
const ch = readLocalJson<MogChapter>(path.join(chaptersDir, file));
if (ch) {
const num = ch.chapter ?? parseInt(file.replace(".json", ""), 10);
items.push({
slug: String(num),
label: `${num}. ${ch.title}`,
type: "chapter",
chapter: num,
});
}
}
}
}
return items;
}
+327
View File
@@ -0,0 +1,327 @@
/**
* Data access layer for Other Documents.
*
* Uses dedicated Prisma models:
* - OtherDocumentMeta (collection: other_document_meta)
* - OtherDocumentChapter (collection: other_document_chapters)
*
* Falls back to reading local JSON files from
* lib/jsons/other-documents/<slug>/ when the database is unavailable.
*
* Book codes are plain slugs (e.g. "analysis-bg", "real-peace-formula").
*/
import { prisma } from "@/lib/db";
import type { JsonValue } from "@prisma/client/runtime/library";
import fs from "fs";
import path from "path";
// ---------------------------------------------------------------------------
// Constants
// ---------------------------------------------------------------------------
const LOCAL_JSON_DIR = path.join(
process.cwd(),
"lib",
"jsons",
"other-documents",
);
// ---------------------------------------------------------------------------
// Types
// ---------------------------------------------------------------------------
export type OtherDocumentMetaData = {
book: string;
title: string;
author: string;
year: number | null;
description: string | null;
totalChapters: number;
chapters: OtherDocumentChapterEntry[];
};
export type OtherDocumentChapterEntry = {
number: number;
title: string;
};
export type OtherDocumentChapterData = {
book: string;
chapter: number;
title: string;
type: string;
paragraphs: string[];
};
/** Lightweight summary for the top-level index page. */
export type OtherDocumentSummary = {
book: string;
title: string;
author: string;
year: number | null;
description: string | null;
totalChapters: number;
};
/** Used in sidebar / table-of-contents navigation. */
export type OtherDocumentSidebarItem = {
slug: string;
label: string;
type: string;
chapter: number;
};
// ---------------------------------------------------------------------------
// HTML sanitisation (same pattern used across all readers)
// ---------------------------------------------------------------------------
function sanitizeHtml(html: string): string {
let clean = html.replace(/<script[\s>][\s\S]*?<\/script>/gi, "");
clean = clean.replace(/<style[\s>][\s\S]*?<\/style>/gi, "");
clean = clean.replace(/<iframe[\s>][\s\S]*?<\/iframe>/gi, "");
clean = clean.replace(
/<\/?(?:script|style|iframe|object|embed|form|input|textarea|select|button)[^>]*>/gi,
"",
);
clean = clean.replace(/\s+on\w+\s*=\s*(?:"[^"]*"|'[^']*'|[^\s>]+)/gi, "");
clean = clean.replace(/href\s*=\s*"javascript:[^"]*"/gi, 'href=""');
clean = clean.replace(/href\s*=\s*'javascript:[^']*'/gi, "href=''");
return clean;
}
function normalizeParagraphs(paragraphs: string[] | JsonValue): string[] {
let result: string[];
if (typeof paragraphs === "string") {
try {
const parsed = JSON.parse(paragraphs);
result = Array.isArray(parsed) ? parsed : [paragraphs];
} catch {
result = [paragraphs];
}
} else if (Array.isArray(paragraphs)) {
result = paragraphs as string[];
} else {
result = [];
}
return result.map(sanitizeHtml);
}
// ---------------------------------------------------------------------------
// Helpers: local JSON fallback
// ---------------------------------------------------------------------------
function findLocalDirForBook(bookCode: string): string | null {
if (!fs.existsSync(LOCAL_JSON_DIR)) return null;
const entries = fs.readdirSync(LOCAL_JSON_DIR);
for (const entry of entries) {
const introPath = path.join(LOCAL_JSON_DIR, entry, "intro.json");
if (fs.existsSync(introPath)) {
try {
const intro = JSON.parse(fs.readFileSync(introPath, "utf-8"));
if (intro.book === bookCode) return entry;
} catch {
// skip
}
}
}
return null;
}
function readLocalJson<T>(filePath: string): T | null {
try {
if (!fs.existsSync(filePath)) return null;
return JSON.parse(fs.readFileSync(filePath, "utf-8")) as T;
} catch {
return null;
}
}
function getAllLocalMetas(): OtherDocumentMetaData[] {
if (!fs.existsSync(LOCAL_JSON_DIR)) return [];
const entries = fs.readdirSync(LOCAL_JSON_DIR).sort();
const metas: OtherDocumentMetaData[] = [];
for (const entry of entries) {
const introPath = path.join(LOCAL_JSON_DIR, entry, "intro.json");
const intro = readLocalJson<OtherDocumentMetaData>(introPath);
if (intro) metas.push(intro);
}
return metas;
}
function getLocalMeta(bookCode: string): OtherDocumentMetaData | null {
const dir = findLocalDirForBook(bookCode);
if (!dir) return null;
return readLocalJson<OtherDocumentMetaData>(
path.join(LOCAL_JSON_DIR, dir, "intro.json"),
);
}
function getLocalChapter(
bookCode: string,
chapterNum: number,
): OtherDocumentChapterData | null {
const dir = findLocalDirForBook(bookCode);
if (!dir) return null;
const filePath = path.join(
LOCAL_JSON_DIR,
dir,
"chapters",
String(chapterNum).padStart(2, "0") + ".json",
);
const data = readLocalJson<OtherDocumentChapterData>(filePath);
if (!data) return null;
return {
...data,
paragraphs: data.paragraphs.map(sanitizeHtml),
};
}
// ---------------------------------------------------------------------------
// Public API
// ---------------------------------------------------------------------------
/**
* List all other documents (lightweight summaries for the index page).
*/
export async function getAllOtherDocuments(): Promise<OtherDocumentSummary[]> {
try {
const results = await prisma.otherDocumentMeta.findMany({
orderBy: { book: "asc" },
});
if (results.length > 0) {
return results.map((row) => {
const data = row.data as unknown as OtherDocumentMetaData;
return {
book: row.book,
title: data.title,
author: data.author,
year: data.year ?? null,
description: data.description ?? null,
totalChapters: data.totalChapters,
};
});
}
} catch {
// fall through to local JSON
}
const localMetas = getAllLocalMetas();
return localMetas.map((meta) => ({
book: meta.book,
title: meta.title,
author: meta.author,
year: meta.year ?? null,
description: meta.description ?? null,
totalChapters: meta.totalChapters,
}));
}
/**
* Get metadata for a single other document by book code.
*/
export async function getOtherDocumentMeta(
bookCode: string,
): Promise<OtherDocumentMetaData | null> {
try {
const row = await prisma.otherDocumentMeta.findUnique({
where: { book: bookCode },
});
if (row) {
return row.data as unknown as OtherDocumentMetaData;
}
} catch {
// fall through to local JSON
}
return getLocalMeta(bookCode);
}
/**
* Get a single chapter from an other document.
*/
export async function getOtherDocumentChapter(
bookCode: string,
chapterNum: number,
): Promise<OtherDocumentChapterData | null> {
if (chapterNum < 1 || !Number.isInteger(chapterNum)) return null;
try {
const doc = await prisma.otherDocumentChapter.findUnique({
where: {
book_slug: {
book: bookCode,
slug: String(chapterNum),
},
},
});
if (doc) {
return {
book: doc.book,
chapter: doc.chapter,
title: doc.title,
type: doc.type,
paragraphs: normalizeParagraphs(doc.paragraphs),
};
}
} catch {
// fall through to local JSON
}
return getLocalChapter(bookCode, chapterNum);
}
/**
* Unified content accessor — get content by URL slug.
*/
export async function getOtherDocumentContent(
bookCode: string,
slug: string,
): Promise<OtherDocumentChapterData | null> {
const num = Number(slug);
if (Number.isNaN(num) || !Number.isInteger(num) || num < 1) return null;
return getOtherDocumentChapter(bookCode, num);
}
/**
* Build the sidebar navigation list for an other document.
*/
export async function getOtherDocumentSidebarItems(
bookCode: string,
): Promise<OtherDocumentSidebarItem[]> {
const meta = await getOtherDocumentMeta(bookCode);
if (!meta) return [];
return meta.chapters.map((ch) => ({
slug: String(ch.number),
label: `${ch.number}. ${ch.title}`,
type: "chapter",
chapter: ch.number,
}));
}
/**
* Derive the URL slug from a book code.
*/
export function bookCodeToSlug(bookCode: string): string {
return bookCode;
}
/**
* Derive the book code from a URL slug.
*/
export function slugToBookCode(slug: string): string {
return slug;
}
+306
View File
@@ -0,0 +1,306 @@
/**
* Data access layer for Prayers of King Kulaśekhara (PK).
*
* Reads from MongoDB via Prisma, same as the rest of the app.
* PK is a prose book with no volume structure and no intro segments —
* we use volume=0 as the sentinel for "no volumes".
*
* When the DB isn't seeded yet, falls back to reading local JSON files
* from lib/jsons/books/pk/.
*
* Collections used:
* - book_meta (via Prisma BookMeta model)
* - prose_chapters (via Prisma ProseChapter model)
*/
import { prisma } from "@/lib/db";
import type { JsonValue } from "@prisma/client/runtime/library";
import fs from "fs";
import path from "path";
// ---------------------------------------------------------------------------
// Constants
// ---------------------------------------------------------------------------
/** Volume sentinel for books without volumes. */
const NO_VOLUME = 0;
const BOOK = "pk";
const PK_JSON_DIR = path.join(process.cwd(), "lib", "jsons", "books", "pk");
// ---------------------------------------------------------------------------
// Types
// ---------------------------------------------------------------------------
export type PkMeta = {
book: string;
title: string;
author: string;
year?: number;
description: string;
totalChapters: number;
chapters: PkChapterEntry[];
};
export type PkChapterEntry = {
number: number;
title: string;
};
export type PkChapter = {
book: string;
chapter: number | null;
title: string;
type: string;
slug?: string;
paragraphs: string[];
};
/** Union type used in sidebar / table-of-contents navigation. */
export type PkSidebarItem = {
/** URL-safe slug: "1", "2", … "6" */
slug: string;
/** Human-readable label for the sidebar */
label: string;
/** "chapter" */
type: string;
/** Chapter number */
chapter: number | null;
};
// ---------------------------------------------------------------------------
// HTML sanitisation (mirrors lib/api.ts)
// ---------------------------------------------------------------------------
function sanitizeHtml(html: string): string {
let clean = html.replace(/<script[\s>][\s\S]*?<\/script>/gi, "");
clean = clean.replace(/<style[\s>][\s\S]*?<\/style>/gi, "");
clean = clean.replace(/<iframe[\s>][\s\S]*?<\/iframe>/gi, "");
clean = clean.replace(
/<\/?(?:script|style|iframe|object|embed|form|input|textarea|select|button)[^>]*>/gi,
"",
);
clean = clean.replace(/\s+on\w+\s*=\s*(?:"[^"]*"|'[^']*'|[^\s>]+)/gi, "");
clean = clean.replace(/href\s*=\s*"javascript:[^"]*"/gi, 'href=""');
clean = clean.replace(/href\s*=\s*'javascript:[^']*'/gi, "href=''");
return clean;
}
/** Normalize paragraphs — handles both native arrays and stringified JSON. */
function normalizeParagraphs(paragraphs: string[] | JsonValue): string[] {
let result: string[];
if (typeof paragraphs === "string") {
try {
const parsed = JSON.parse(paragraphs);
result = Array.isArray(parsed) ? parsed : [paragraphs];
} catch {
result = [paragraphs];
}
} else if (Array.isArray(paragraphs)) {
result = paragraphs as string[];
} else {
result = [];
}
return result.map(sanitizeHtml);
}
// ---------------------------------------------------------------------------
// Local JSON helpers (fallback when DB is not seeded)
// ---------------------------------------------------------------------------
function readLocalJson<T>(filePath: string): T | null {
if (!fs.existsSync(filePath)) return null;
try {
return JSON.parse(fs.readFileSync(filePath, "utf-8")) as T;
} catch {
return null;
}
}
function getLocalChapter(chapterNum: number): PkChapter | null {
const filePath = path.join(
PK_JSON_DIR,
"chapters",
String(chapterNum).padStart(2, "0") + ".json",
);
return readLocalJson<PkChapter>(filePath);
}
// ---------------------------------------------------------------------------
// Book meta
// ---------------------------------------------------------------------------
/**
* Book-level metadata (title, author, chapter list, etc.)
*/
export async function getPkMeta(): Promise<PkMeta | null> {
const meta = await prisma.bookMeta.findUnique({ where: { book: BOOK } });
if (meta) return meta.data as unknown as PkMeta;
// Fallback to local JSON
const introPath = path.join(PK_JSON_DIR, "intro.json");
return readLocalJson<PkMeta>(introPath);
}
// ---------------------------------------------------------------------------
// Chapters
// ---------------------------------------------------------------------------
/**
* A numbered chapter (1–6).
*/
export async function getPkChapter(
chapterNum: number,
): Promise<PkChapter | null> {
if (chapterNum < 1 || chapterNum > 6 || !Number.isInteger(chapterNum)) {
return null;
}
const doc = await prisma.proseChapter.findUnique({
where: {
book_volume_slug: {
book: BOOK,
volume: NO_VOLUME,
slug: String(chapterNum),
},
},
});
if (doc) {
return {
book: doc.book,
chapter: doc.chapter,
title: doc.title,
type: doc.type,
slug: doc.slug,
paragraphs: normalizeParagraphs(doc.paragraphs),
};
}
// Fallback to local JSON
const local = getLocalChapter(chapterNum);
if (!local) return null;
return {
...local,
paragraphs: local.paragraphs.map(sanitizeHtml),
};
}
// ---------------------------------------------------------------------------
// Unified content accessor
// ---------------------------------------------------------------------------
/**
* Get content by URL slug.
*
* "1" … "6" → chapter
*/
export async function getPkContent(slug: string): Promise<PkChapter | null> {
const num = Number(slug);
if (!Number.isNaN(num) && Number.isInteger(num) && num >= 1 && num <= 6) {
return getPkChapter(num);
}
return null;
}
// ---------------------------------------------------------------------------
// Sidebar navigation
// ---------------------------------------------------------------------------
/**
* Build the full sidebar navigation list.
*
* Order: chapters 1–6 (no intro segments for PK)
*/
export async function getPkSidebarItems(): Promise<PkSidebarItem[]> {
const [meta, allDocs] = await Promise.all([
getPkMeta(),
prisma.proseChapter.findMany({
where: { book: BOOK, volume: NO_VOLUME },
orderBy: { order: "asc" },
select: {
slug: true,
title: true,
type: true,
chapter: true,
order: true,
},
}),
]);
// If we got DB results, build from those
if (meta && allDocs.length > 0) {
return buildSidebarFromDocs(meta, allDocs);
}
// Fallback: build from local JSON
return buildSidebarFromLocal(meta);
}
function buildSidebarFromDocs(
meta: PkMeta,
_allDocs: {
slug: string;
title: string;
type: string;
chapter: number | null;
order: number | null;
}[],
): PkSidebarItem[] {
const items: PkSidebarItem[] = [];
// Chapters 1–6 (use meta.chapters for consistent title/ordering)
for (const ch of meta.chapters) {
items.push({
slug: String(ch.number),
label: `${ch.number}. ${ch.title}`,
type: "chapter",
chapter: ch.number,
});
}
return items;
}
function buildSidebarFromLocal(meta: PkMeta | null): PkSidebarItem[] {
const items: PkSidebarItem[] = [];
// Chapters from meta or scan local chapter JSONs
if (meta && meta.chapters) {
for (const ch of meta.chapters) {
items.push({
slug: String(ch.number),
label: `${ch.number}. ${ch.title}`,
type: "chapter",
chapter: ch.number,
});
}
} else {
// Fallback: scan local chapter JSONs
const chaptersDir = path.join(PK_JSON_DIR, "chapters");
if (fs.existsSync(chaptersDir)) {
const files = fs
.readdirSync(chaptersDir)
.filter((f) => f.endsWith(".json"))
.sort();
for (const file of files) {
const ch = readLocalJson<PkChapter>(path.join(chaptersDir, file));
if (ch) {
const num = ch.chapter ?? parseInt(file.replace(".json", ""), 10);
items.push({
slug: String(num),
label: `${num}. ${ch.title}`,
type: "chapter",
chapter: num,
});
}
}
}
}
return items;
}
+167
View File
@@ -0,0 +1,167 @@
/**
* Data access layer for Vaiśiṣṭyāṣṭakam (VA).
*
* Reads from MongoDB via Prisma.
* VA is a poetic work with 8 chapters (Vaiśiṣṭyas) and no intro segments.
*
* Collections used:
* - book_meta (via Prisma BookMeta model)
* - prose_chapters (via Prisma ProseChapter model)
*/
import { prisma } from "@/lib/db";
import type { JsonValue } from "@prisma/client/runtime/library";
// ---------------------------------------------------------------------------
// Constants
// ---------------------------------------------------------------------------
const BOOK = "va";
/** Volume sentinel for books without volumes. */
const NO_VOLUME = 0;
// ---------------------------------------------------------------------------
// Types
// ---------------------------------------------------------------------------
export type VaMeta = {
book: string;
title: string;
author: string;
year: number;
description: string;
totalChapters: number;
chapters: VaChapterEntry[];
};
export type VaChapterEntry = {
number: number;
title: string;
};
export type VaChapter = {
book: string;
chapter: number | null;
title: string;
type: string;
slug?: string;
paragraphs: string[];
};
/** Used in sidebar / table-of-contents navigation. */
export type VaSidebarItem = {
slug: string;
label: string;
type: string;
chapter: number | null;
};
// ---------------------------------------------------------------------------
// HTML sanitisation
// ---------------------------------------------------------------------------
function sanitizeHtml(html: string): string {
let clean = html.replace(/<script[\s>][\s\S]*?<\/script>/gi, "");
clean = clean.replace(/<style[\s>][\s\S]*?<\/style>/gi, "");
clean = clean.replace(/<iframe[\s>][\s\S]*?<\/iframe>/gi, "");
clean = clean.replace(
/<\/?(?:script|style|iframe|object|embed|form|input|textarea|select|button)[^>]*>/gi,
"",
);
clean = clean.replace(/\s+on\w+\s*=\s*(?:"[^"]*"|'[^']*'|[^\s>]+)/gi, "");
clean = clean.replace(/href\s*=\s*"javascript:[^"]*"/gi, 'href=""');
clean = clean.replace(/href\s*=\s*'javascript:[^']*'/gi, "href=''");
return clean;
}
function normalizeParagraphs(paragraphs: string[] | JsonValue): string[] {
let result: string[];
if (typeof paragraphs === "string") {
try {
const parsed = JSON.parse(paragraphs);
result = Array.isArray(parsed) ? parsed : [paragraphs];
} catch {
result = [paragraphs];
}
} else if (Array.isArray(paragraphs)) {
result = paragraphs as string[];
} else {
result = [];
}
return result.map(sanitizeHtml);
}
// ---------------------------------------------------------------------------
// Book meta
// ---------------------------------------------------------------------------
export async function getVaMeta(): Promise<VaMeta | null> {
const meta = await prisma.bookMeta.findUnique({ where: { book: BOOK } });
if (!meta) return null;
return meta.data as unknown as VaMeta;
}
// ---------------------------------------------------------------------------
// Chapters
// ---------------------------------------------------------------------------
export async function getVaChapter(
chapterNum: number,
): Promise<VaChapter | null> {
if (chapterNum < 1 || chapterNum > 8 || !Number.isInteger(chapterNum)) {
return null;
}
const doc = await prisma.proseChapter.findUnique({
where: {
book_volume_slug: {
book: BOOK,
volume: NO_VOLUME,
slug: String(chapterNum),
},
},
});
if (!doc) return null;
return {
book: doc.book,
chapter: doc.chapter,
title: doc.title,
type: doc.type,
slug: doc.slug,
paragraphs: normalizeParagraphs(doc.paragraphs),
};
}
// ---------------------------------------------------------------------------
// Unified content accessor
// ---------------------------------------------------------------------------
export async function getVaContent(
slug: string,
): Promise<VaChapter | null> {
const num = Number(slug);
if (!Number.isNaN(num) && Number.isInteger(num) && num >= 1 && num <= 8) {
return getVaChapter(num);
}
return null;
}
// ---------------------------------------------------------------------------
// Sidebar navigation
// ---------------------------------------------------------------------------
export async function getVaSidebarItems(): Promise<VaSidebarItem[]> {
const meta = await getVaMeta();
if (!meta) return [];
return meta.chapters.map((ch) => ({
slug: String(ch.number),
label: `${ch.number}. ${ch.title}`,
type: "chapter",
chapter: ch.number,
}));
}