import fs from 'fs'; import path from 'path'; import { SiteConfig, PageConfig, ToolItem, AppItem, CategoryItem } from '@/types'; import { getEndpointById } from '../catalog/loader'; const CONTENT_DIR = path.join(process.cwd(), 'content'); const MANAGEMENT_DIR = path.join(process.cwd(), 'management'); // In-memory cache for speed and resilience let siteConfigCache: SiteConfig | null = null; let pagesCache = new Map(); let toolsCache = new Map(); let appsCache = new Map(); let categoriesCache = new Map(); function readJsonFile(filePath: string): T | null { try { if (!fs.existsSync(filePath)) return null; const raw = fs.readFileSync(filePath, 'utf8'); return JSON.parse(raw) as T; } catch (e) { console.error(`Failed to read/parse JSON from ${filePath}:`, e); return null; } } export function getSiteConfig(): SiteConfig { if (siteConfigCache) return siteConfigCache; const config = readJsonFile(path.join(CONTENT_DIR, 'site.config.json')); if (!config) { throw new Error('Crucial site.config.json missing or invalid'); } siteConfigCache = config; return config; } export function getPageConfig(slug: string): PageConfig | null { const normSlug = slug === '' || slug === '/' ? 'home' : slug.replace(/^\/+|\/+$/g, ''); // 1. Prioritize management/pages/[name]/page.config.json const mgmtPageFile = path.join(MANAGEMENT_DIR, 'pages', normSlug, 'page.config.json'); if (fs.existsSync(mgmtPageFile)) { const page = readJsonFile(mgmtPageFile); if (page) return page; } // 2. Fallback to content/pages/[name].json const filePath = path.join(CONTENT_DIR, 'pages', `${normSlug}.json`); return readJsonFile(filePath); } export function getAllTools(): ToolItem[] { toolsCache.clear(); // 1. Load baseline from content/collections/tools const toolsDir = path.join(CONTENT_DIR, 'collections', 'tools'); if (fs.existsSync(toolsDir)) { const files = fs.readdirSync(toolsDir).filter((f) => f.endsWith('.json')); for (const file of files) { const tool = readJsonFile(path.join(toolsDir, file)); if (tool && tool.status === 'published') { toolsCache.set(tool.slug, tool); } } } // 2. Layer management/pages/tools/[slug]/tool.config.json on top const mgmtToolsDir = path.join(MANAGEMENT_DIR, 'pages', 'tools'); if (fs.existsSync(mgmtToolsDir)) { const slugs = fs.readdirSync(mgmtToolsDir); for (const slug of slugs) { const configPath = path.join(mgmtToolsDir, slug, 'tool.config.json'); if (fs.existsSync(configPath)) { const mgmtTool = readJsonFile(configPath); if (mgmtTool && mgmtTool.status === 'published') { // Normalize media paths so before/after point to live management media if (mgmtTool.media?.before && mgmtTool.content?.examples?.[0]) { mgmtTool.content.examples[0].before = mgmtTool.media.before; } if (mgmtTool.media?.after && mgmtTool.content?.examples?.[0]) { mgmtTool.content.examples[0].after = mgmtTool.media.after; } const existing = toolsCache.get(mgmtTool.slug) || ({} as any); const merged: ToolItem = { ...existing, ...mgmtTool, content: { ...(existing.content || {}), ...(mgmtTool.content || {}), alternatingFeatures: mgmtTool.content?.alternatingFeatures || existing.content?.alternatingFeatures, }, pageType: mgmtTool.pageType || existing.pageType, showThumbnailsSection: mgmtTool.showThumbnailsSection !== undefined ? mgmtTool.showThumbnailsSection : existing.showThumbnailsSection, thumbnailPlacement: mgmtTool.thumbnailPlacement || existing.thumbnailPlacement, thumbnails: mgmtTool.thumbnails || existing.thumbnails, maskingConfig: mgmtTool.maskingConfig || existing.maskingConfig, twoImagesConfig: mgmtTool.twoImagesConfig || existing.twoImagesConfig, textToImageConfig: mgmtTool.textToImageConfig || existing.textToImageConfig, }; toolsCache.set(mgmtTool.slug, merged); } } } } return Array.from(toolsCache.values()); } export function getToolBySlug(slug: string): ToolItem | null { getAllTools(); return toolsCache.get(slug) || null; } export function getToolById(id: string): ToolItem | null { getAllTools(); for (const t of toolsCache.values()) { if (t.id === id) return t; } return null; } export function getAllApps(): AppItem[] { appsCache.clear(); // 1. Prioritize management/apps/[slug]/app.config.json const mgmtAppsDir = path.join(MANAGEMENT_DIR, 'apps'); if (fs.existsSync(mgmtAppsDir)) { const slugs = fs.readdirSync(mgmtAppsDir); const apps: AppItem[] = []; for (const slug of slugs) { const configPath = path.join(mgmtAppsDir, slug, 'app.config.json'); if (fs.existsSync(configPath)) { const app = readJsonFile(configPath); if (app && app.status === 'published') { apps.push(app); appsCache.set(app.slug, app); } } } if (apps.length > 0) return apps; } // 2. Fallback to content/collections/apps const appsDir = path.join(CONTENT_DIR, 'collections', 'apps'); if (fs.existsSync(appsDir)) { const files = fs.readdirSync(appsDir).filter((f) => f.endsWith('.json')); for (const file of files) { const app = readJsonFile(path.join(appsDir, file)); if (app && app.status === 'published') { appsCache.set(app.slug, app); } } } return Array.from(appsCache.values()); } export function getAppBySlug(slug: string): AppItem | null { getAllApps(); return appsCache.get(slug) || null; } export function getAppById(id: string): AppItem | null { getAllApps(); for (const a of appsCache.values()) { if (a.id === id) return a; } return null; } export function getAllCategories(): CategoryItem[] { if (categoriesCache.size > 0) return Array.from(categoriesCache.values()); const dir = path.join(CONTENT_DIR, 'collections', 'categories'); if (fs.existsSync(dir)) { const files = fs.readdirSync(dir).filter((f) => f.endsWith('.json')); for (const file of files) { const cat = readJsonFile(path.join(dir, file)); if (cat) { categoriesCache.set(cat.slug, cat); } } } return Array.from(categoriesCache.values()); } export function getTemplate(name: string): any { const mgmtPath = path.join(MANAGEMENT_DIR, 'templates', `${name}.json`); if (fs.existsSync(mgmtPath)) { return readJsonFile(mgmtPath); } const filePath = path.join(CONTENT_DIR, 'templates', `${name}.json`); return readJsonFile(filePath); } export function getLocaleDictionary(locale: string = 'en'): Record { const filePath = path.join(CONTENT_DIR, 'locales', `${locale}.json`); const data = readJsonFile<{ system: Record }>(filePath); return data?.system || {}; } export function checkIntegrity(): { valid: boolean; errors: string[] } { const errors: string[] = []; const tools = getAllTools(); const apps = getAllApps(); const appIds = new Set(apps.map((a) => a.id)); for (const tool of tools) { if (!appIds.has(tool.homeApp)) { errors.push(`Tool '${tool.id}' references missing homeApp '${tool.homeApp}'`); } const epId = tool.tryIt?.endpointRef?.id; if (epId && !getEndpointById(epId)) { errors.push(`Tool '${tool.id}' references missing endpoint '${epId}'`); } } return { valid: errors.length === 0, errors, }; }