/** * OpenStax source provider for grounded teaching content. * * Uses the OpenStax CMS (Wagtail) API to search for relevant textbook chapters, * then fetches page content from the public reader (openstax.org/books/{slug}/pages/{page}). * * All OpenStax CC BY textbooks are licensed under Creative Commons Attribution 4.0. * OpenStax is a nonprofit initiative by Rice University providing free, peer-reviewed textbooks. * * API docs: https://github.com/openstax/cnx-archive/blob/master/docs/content_api_doc.md * Book list: https://openstax.org/apps/cms/api/v2/pages/?type=books.Book&fields=title,slug */ const OPENSTAX_CMS_API = "https://openstax.org/apps/cms/api/v2/pages"; const OPENSTAX_BOOKS_BASE = "https://openstax.org/books"; const USER_AGENT = "RotNot/1.0 (educational app; contact: github.com/CuriosityQuantified/rotnot)"; export interface OpenStaxBook { id: number; title: string; slug: string; url: string; } export interface OpenStaxSection { bookTitle: string; bookSlug: string; sectionTitle: string; sectionSlug: string; url: string; excerpt: string; } /** * Maps Feynman topic domains to relevant OpenStax book slugs. * Prefers latest editions (2e, 3e). All listed books are CC BY 4.0. */ const DOMAIN_BOOK_MAP: Record = { Physics: ["college-physics-2e", "university-physics-volume-1", "university-physics-volume-2", "university-physics-volume-3"], Biology: ["biology-2e", "concepts-biology", "microbiology", "anatomy-and-physiology-2e"], Chemistry: ["chemistry-2e", "chemistry-atoms-first-2e", "organic-chemistry"], Economics: ["principles-economics-3e", "principles-microeconomics-3e", "principles-macroeconomics-3e"], Psychology: ["psychology-2e", "introduction-sociology-3e"], Mathematics: ["calculus-volume-1", "calculus-volume-2", "calculus-volume-3", "introductory-statistics-2e", "prealgebra-2e"], CS: ["introduction-computer-science"], History: ["us-history", "world-history-volume-1", "world-history-volume-2"], Philosophy: ["introduction-philosophy", "introduction-logic-critical-thinking"], }; /** * Search the OpenStax CMS for books matching a query. * Uses the Wagtail API `search` parameter on Book page types. * Returns up to `limit` results (default 3). */ export async function searchOpenStaxBooks( query: string, limit: number = 3, ): Promise { const params = new URLSearchParams({ type: "books.Book", fields: "title,slug", format: "json", limit: String(limit), search: query, }); const response = await fetch(`${OPENSTAX_CMS_API}?${params}`, { headers: { "User-Agent": USER_AGENT }, }); if (!response.ok) { throw new Error(`OpenStax book search failed: ${response.status} ${response.statusText}`); } const data = await response.json(); const items = data?.items ?? []; return items.map((item: { id: number; title: string; meta: { slug: string; html_url: string } }) => ({ id: item.id, title: item.title, slug: item.meta.slug, url: item.meta.html_url || `https://openstax.org/details/books/${item.meta.slug}`, })); } /** * Fetch text content from an OpenStax book page URL. * Strips HTML to return clean, readable text. * Returns null if the page is not accessible or empty. */ export async function fetchOpenStaxPageContent( bookSlug: string, pageSlug: string, maxChars: number = 4000, ): Promise<{ title: string; content: string; url: string } | null> { const url = `${OPENSTAX_BOOKS_BASE}/${bookSlug}/pages/${pageSlug}`; const response = await fetch(url, { headers: { "User-Agent": USER_AGENT }, }); if (!response.ok) { return null; } const html = await response.text(); // Extract page title from tag const titleMatch = html.match(/<title[^>]*>([^<]+)</); const rawTitle = titleMatch ? titleMatch[1] : pageSlug; // Clean up title: "1.1 Physics: Definitions - Physics | OpenStax" → "1.1 Physics: Definitions" const title = rawTitle.replace(/\s*[-–|].*OpenStax.*$/i, "").replace(/\s*[-–|]\s*$/, "").trim(); // Extract main content — OpenStax wraps content in data-type="page" or class with page content // We'll extract text from the main content area, stripping HTML let content = extractMainContent(html); // Truncate to maxChars if (content.length > maxChars) { content = content.slice(0, maxChars) + "…"; } if (content.length < 100) { return null; // too little content } return { title, content, url }; } /** * Search OpenStax for content relevant to a Feynman topic. * Uses domain-based book selection + keyword matching in page slugs. * * Returns up to `maxResults` section excerpts. */ export async function fetchOpenStaxSources( topicName: string, domain?: string, maxResults: number = 2, ): Promise<OpenStaxSection[]> { const sections: OpenStaxSection[] = []; // Step 1: Determine candidate books const candidateSlugs = domain ? (DOMAIN_BOOK_MAP[domain] ?? []) : []; // Step 2: Also try CMS search for additional coverage let searchBooks: OpenStaxBook[] = []; try { // Extract key terms from the topic for a focused search const searchTerms = extractSearchTerms(topicName); searchBooks = await searchOpenStaxBooks(searchTerms, 3); } catch { // Search failure is non-critical } // Combine: domain-mapped books first, then search results const allSlugs = [...new Set([ ...candidateSlugs, ...searchBooks.map((b) => b.slug), ])]; if (allSlugs.length === 0) { return []; } // Step 3: For each candidate book, try to find a relevant page // We generate plausible page slugs from the topic name const pageSlugs = generatePageSlugs(topicName); for (const bookSlug of allSlugs) { if (sections.length >= maxResults) break; for (const pageSlug of pageSlugs) { if (sections.length >= maxResults) break; const page = await fetchOpenStaxPageContent(bookSlug, pageSlug); if (page && page.content.length >= 200) { sections.push({ bookTitle: searchBooks.find((b) => b.slug === bookSlug)?.title ?? formatSlugAsTitle(bookSlug), bookSlug, sectionTitle: page.title, sectionSlug: pageSlug, url: page.url, excerpt: page.content, }); break; // Found content in this book, move to next } } } return sections; } /** * Extract key search terms from a topic name. * Removes common filler words to improve CMS search quality. */ export function extractSearchTerms(topic: string): string { const stopWords = new Set([ "how", "what", "why", "the", "a", "an", "and", "or", "of", "in", "to", "is", "are", "was", "were", "works", "work", "does", "do", "between", "its", "it", "that", "this", "for", "with", "from", "three", "two", ]); return topic .toLowerCase() .replace(/['']/g, "'") .replace(/[^\w\s'-]/g, " ") .split(/\s+/) .filter((w) => !stopWords.has(w) && w.length > 1) .slice(0, 4) // CMS search works best with fewer terms .join(" "); } /** * Generate plausible OpenStax page slugs from a topic name. * OpenStax uses slugs like "1-1-physics-definitions-and-applications". * Since we can't know the chapter number, we generate the keyword portion * and also try the topic index page. */ export function generatePageSlugs(topicName: string): string[] { // Convert topic to slug format: lowercase, spaces to hyphens, strip non-alphanumeric const baseSlug = topicName .toLowerCase() .replace(/['']/g, "") .replace(/[^\w\s-]/g, "") .replace(/\s+/g, "-") .replace(/-+/g, "-") .replace(/^-|-$/g, ""); // Also extract key concepts for shorter slug attempts const keyTerms = extractSearchTerms(topicName) .replace(/['']/g, "") .replace(/\s+/g, "-"); const slugs = new Set<string>(); // Full topic as slug slugs.add(baseSlug); // Key terms as slug if (keyTerms && keyTerms !== baseSlug) { slugs.add(keyTerms); } // First 2-3 key words (common OpenStax pattern) const words = baseSlug.split("-").filter((w) => w.length > 2); if (words.length > 3) { slugs.add(words.slice(0, 3).join("-")); } if (words.length > 2) { slugs.add(words.slice(0, 2).join("-")); } return Array.from(slugs); } /** * Extract main content text from an OpenStax HTML page. * Strips HTML tags, teacher support blocks, and navigation chrome. */ function extractMainContent(html: string): string { // Remove script and style tags entirely let cleaned = html .replace(/<script[^>]*>[\s\S]*?<\/script>/gi, "") .replace(/<style[^>]*>[\s\S]*?<\/style>/gi, "") .replace(/<nav[^>]*>[\s\S]*?<\/nav>/gi, "") .replace(/<header[^>]*>[\s\S]*?<\/header>/gi, "") .replace(/<footer[^>]*>[\s\S]*?<\/footer>/gi, ""); // Remove Teacher Support sections (OpenStax K-12 content includes these) cleaned = cleaned.replace(/<[^>]*class="[^"]*teacher[^"]*"[^>]*>[\s\S]*?(?=<\/(?:div|section)>)/gi, ""); // Strip all HTML tags cleaned = cleaned .replace(/<[^>]+>/g, " ") .replace(/ /g, " ") .replace(/&/g, "&") .replace(/</g, "<") .replace(/>/g, ">") .replace(/"/g, '"') .replace(/'/g, "'") .replace(/'/g, "'") .replace(/\s+/g, " ") .trim(); // Remove common noise patterns cleaned = cleaned .replace(/Want to cite, share, or modify this book\?.*$/i, "") .replace(/Citation\/Attribution.*$/i, "") .replace(/This book may not be used in the training.*$/i, "") .replace(/Order a print copy.*$/i, ""); return cleaned.trim(); } /** * Format a book slug into a readable title. * "college-physics-2e" → "College Physics 2e" */ function formatSlugAsTitle(slug: string): string { return slug .split("-") .map((word) => { if (word.match(/^\d/)) return word; // numbers/editions like "2e" return word.charAt(0).toUpperCase() + word.slice(1); }) .join(" "); }