/** * API Route: 获取 json-render 组件提示词 * * 返回 catalog.prompt() 生成的提示词 * 前端可以在初始化时调用此 API 获取最新提示词 */ import { NextResponse } from 'next/server'; import { readFile } from 'fs/promises'; import { join } from 'path'; // 缓存提示词(5分钟过期) let cachedPrompt: string | null = null; let cacheTime: number = 0; const CACHE_TTL = 5 * 60 * 1000; // 5 分钟 export async function GET() { try { // 检查缓存 const now = Date.now(); if (cachedPrompt && (now - cacheTime) < CACHE_TTL) { return NextResponse.json({ success: true, prompt: cachedPrompt, cached: true, length: cachedPrompt.length, }); } // 读取预生成的提示词文件 const promptPath = join(process.cwd(), 'lib/catalog/generated-prompt.txt'); const prompt = await readFile(promptPath, 'utf-8'); // 更新缓存 cachedPrompt = prompt; cacheTime = now; return NextResponse.json({ success: true, prompt, cached: false, length: prompt.length, generatedAt: new Date().toISOString(), }); } catch (error) { console.error('Failed to read components prompt:', error); // 返回 fallback 提示词 const fallbackPrompt = generateFallbackPrompt(); return NextResponse.json({ success: false, prompt: fallbackPrompt, error: 'Failed to read generated prompt, using fallback', length: fallbackPrompt.length, }); } } /** * 生成 fallback 提示词(当文件读取失败时使用) */ function generateFallbackPrompt(): string { return `## 可用的 json-render 组件 你可以使用以下组件来展示结构化数据。 ### 基础组件 - card: 卡片容器 - stack: 弹性布局 - heading: 标题 (h1-h6) - text: 文本 - button: 按钮 - badge: 徽章 - code-block: 代码块 ### MCP 专用组件 - translation-result: 翻译结果 - novel-list: 小说列表 - chapter-reader: 章节阅读器 - tool-call: 工具调用状态 组件格式示例: \`\`\`json { "type": "card", "title": "标题", "children": [] } \`\`\` `; }