doccupine 0.0.143 → 0.0.145

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (66) hide show
  1. package/README.md +1 -1
  2. package/dist/cli.d.ts +6 -0
  3. package/dist/cli.js +130 -22
  4. package/dist/generator/api-reference-generator.d.ts +22 -0
  5. package/dist/generator/api-reference-generator.js +96 -0
  6. package/dist/generator/app-scaffolder.d.ts +18 -0
  7. package/dist/generator/app-scaffolder.js +49 -0
  8. package/dist/generator/generated-route-manager.d.ts +18 -0
  9. package/dist/generator/generated-route-manager.js +114 -0
  10. package/dist/generator/page-catalog.d.ts +21 -0
  11. package/dist/generator/page-catalog.js +75 -0
  12. package/dist/generator/page-renderer.d.ts +31 -0
  13. package/dist/generator/page-renderer.js +248 -0
  14. package/dist/generator/project-config-repository.d.ts +33 -0
  15. package/dist/generator/project-config-repository.js +191 -0
  16. package/dist/generator/public-asset-manager.d.ts +20 -0
  17. package/dist/generator/public-asset-manager.js +225 -0
  18. package/dist/generator/section-resolver.d.ts +13 -0
  19. package/dist/generator/section-resolver.js +150 -0
  20. package/dist/generator/secure-source-fs.d.ts +31 -0
  21. package/dist/generator/secure-source-fs.js +470 -0
  22. package/dist/generator/site-artifacts.d.ts +23 -0
  23. package/dist/generator/site-artifacts.js +156 -0
  24. package/dist/generator/watch-coordinator.d.ts +58 -0
  25. package/dist/generator/watch-coordinator.js +456 -0
  26. package/dist/lib/config-manager.d.ts +1 -0
  27. package/dist/lib/config-manager.js +194 -12
  28. package/dist/lib/generated-artifacts.d.ts +11 -2
  29. package/dist/lib/generated-artifacts.js +52 -7
  30. package/dist/lib/layout.d.ts +1 -17
  31. package/dist/lib/layout.js +5 -4
  32. package/dist/lib/openapi.d.ts +4 -0
  33. package/dist/lib/openapi.js +36 -4
  34. package/dist/lib/project-config.d.ts +3 -0
  35. package/dist/lib/project-config.js +110 -0
  36. package/dist/lib/types.d.ts +14 -1
  37. package/dist/mdx-to-nextjs-generator.d.ts +50 -34
  38. package/dist/mdx-to-nextjs-generator.js +760 -1740
  39. package/dist/templates/app/api/rag/route.d.ts +1 -1
  40. package/dist/templates/app/api/rag/route.js +2 -1
  41. package/dist/templates/components/Chat.d.ts +1 -1
  42. package/dist/templates/components/Chat.js +2 -1
  43. package/dist/templates/components/layout/Accordion.d.ts +1 -1
  44. package/dist/templates/components/layout/Accordion.js +2 -3
  45. package/dist/templates/mdx/api-playground.mdx.d.ts +1 -1
  46. package/dist/templates/mdx/api-playground.mdx.js +11 -2
  47. package/dist/templates/mdx/commands.mdx.d.ts +1 -1
  48. package/dist/templates/mdx/commands.mdx.js +26 -1
  49. package/dist/templates/mdx/media-and-assets.mdx.d.ts +1 -1
  50. package/dist/templates/mdx/media-and-assets.mdx.js +5 -0
  51. package/dist/templates/mdx/model-context-protocol.mdx.d.ts +1 -1
  52. package/dist/templates/mdx/model-context-protocol.mdx.js +2 -1
  53. package/dist/templates/mdx/platform/api-playground.mdx.d.ts +1 -1
  54. package/dist/templates/mdx/platform/api-playground.mdx.js +2 -2
  55. package/dist/templates/mdx/platform/publishing.mdx.d.ts +1 -1
  56. package/dist/templates/mdx/platform/publishing.mdx.js +3 -3
  57. package/dist/templates/mdx/space.mdx.d.ts +1 -1
  58. package/dist/templates/mdx/space.mdx.js +1 -5
  59. package/dist/templates/mdx/what-is-doccupine.mdx.d.ts +1 -1
  60. package/dist/templates/mdx/what-is-doccupine.mdx.js +8 -3
  61. package/dist/templates/next.config.js +2 -2
  62. package/dist/templates/package.js +3 -3
  63. package/dist/templates/proxy.js +1 -1
  64. package/dist/templates/services/mcp/server.d.ts +1 -1
  65. package/dist/templates/services/mcp/server.js +2 -12
  66. package/package.json +3 -3
@@ -1 +1 @@
1
- export declare const ragRoutesTemplate = "import { NextResponse } from \"next/server\";\nimport { z } from \"zod\";\nimport { getLLMConfig, createChatModel } from \"@/services/llm\";\nimport {\n searchDocs,\n ensureDocsIndex,\n getIndexStatus,\n} from \"@/services/mcp/server\";\nimport { rateLimit } from \"@/utils/rateLimit\";\nimport { config } from \"@/utils/config\";\nimport { isSiteRequestAuthorized } from \"@/lib/access\";\nimport { timingSafeEqual } from \"@/lib/siteGate\";\nimport { readJsonBody, RequestTooLargeError } from \"@/utils/requestBody\";\n\nconst MAX_RAG_REQUEST_BYTES = 32 * 1024;\n\nconst messageSchema = z\n .object({\n role: z.enum([\"user\", \"assistant\"]),\n content: z.string().max(4000),\n })\n .strict();\n\nconst ragSchema = z\n .object({\n question: z.string().min(1).max(2000),\n history: z.array(messageSchema).max(20).optional(),\n })\n .strict();\n\nfunction bearerToken(req: Request): string | null {\n const authorization = req.headers.get(\"authorization\");\n return authorization?.startsWith(\"Bearer \")\n ? authorization.slice(\"Bearer \".length)\n : null;\n}\n\nasync function isRagRequestAuthorized(req: Request): Promise<boolean> {\n const siteAuthorized = await isSiteRequestAuthorized();\n if (process.env.SITE_PASSWORD && siteAuthorized) return true;\n\n const apiKey = process.env.RAG_API_KEY;\n if (apiKey) {\n const token = bearerToken(req);\n return token !== null && timingSafeEqual(token, apiKey);\n }\n return siteAuthorized;\n}\n\nconst projectName = config.name || \"Doccupine\";\n\nconst systemContext = `You are AI Assistant, a documentation assistant for ${projectName}, Your name is ${projectName} AI Assistant.\n\n## Core Rules\n1. Answer ONLY from the provided context. Never fabricate information.\n2. If the answer isn't in the context, say so clearly and suggest relevant sections or pages the user might check.\n3. If the question is ambiguous, ask a brief clarifying question before answering.\n\n## Response Style\n- Be concise and direct. Lead with the answer, then provide details if needed.\n- Use code examples from the context when relevant.\n- Match the technical level of the user's question.\n\n## MDX/Code Formatting\nWhen including code blocks in your response:\n- Never nest fenced code blocks (triple backticks) inside other fenced code blocks.\n- If you need to show MDX source that itself contains code blocks, use indented code blocks or escape the inner backticks.\n- All output must be valid MDX that renders correctly.\n\n## Internal Links\nEach context chunk includes a \"URL:\" line with the pre-computed page URL. Use it directly when linking:\n- Format links as markdown: [Page Title](/slug/).\n- Never expose raw file paths like \"/app/.../page.tsx\" to the user.\n- Never include route group segments in parentheses, like \"(site)\", in any link - they are internal directory names and do not exist in real URLs. Use \"/code/\" not \"/(site)/code/\".\n- Do NOT add a \"Related Pages\" section at the end - sources are shown separately by the UI.\n\n## Greetings & Small Talk\nIf the user sends a greeting or non-documentation question, respond briefly and ask how you can help with the documentation.`;\n\n// Maps provider/stream failures to fixed visitor-safe messages. Raw provider\n// errors can include API-key fragments, org ids, and billing URLs, so only\n// these strings ever reach the client; the full error goes to the server log.\nfunction friendlyLLMError(error: unknown): string {\n const raw = error instanceof Error ? error.message : String(error);\n if (/\\b401\\b|api.?key|authenticat|unauthorized/i.test(raw)) {\n return \"The assistant's model provider rejected its API key. If you are the site owner, check the server logs and your API key configuration.\";\n }\n if (/\\b429\\b|quota|rate.?limit|billing/i.test(raw)) {\n return \"The assistant's model provider is rate limiting requests right now. Please try again in a moment.\";\n }\n if (\n /timed?.?out|ETIMEDOUT|ECONNRESET|ENOTFOUND|fetch failed|network/i.test(raw)\n ) {\n return \"The assistant could not reach its model provider. Please try again.\";\n }\n return \"The assistant hit an unexpected error. Please try again.\";\n}\n\n// LangChain + the MCP SDK require the Node.js runtime (not edge).\nexport const runtime = \"nodejs\";\n// Safety net for the streaming function (Vercel-only; ignored elsewhere).\n// The heartbeat below, not this value, is what prevents proxy 524 timeouts.\nexport const maxDuration = 60;\n\nexport async function POST(req: Request) {\n if (!(await isRagRequestAuthorized(req))) {\n return NextResponse.json({ error: \"Unauthorized\" }, { status: 401 });\n }\n\n const { allowed, retryAfter } = rateLimit(req);\n if (!allowed) {\n return NextResponse.json(\n { error: \"Too many requests\" },\n { status: 429, headers: { \"Retry-After\": String(retryAfter) } },\n );\n }\n\n // Validate the request up front so genuine client/config errors still return\n // real status codes before we commit to a 200 streaming response.\n let body: unknown;\n try {\n body = await readJsonBody(req, MAX_RAG_REQUEST_BYTES);\n } catch (error: unknown) {\n if (req.signal.aborted) throw error;\n if (error instanceof RequestTooLargeError) {\n return NextResponse.json(\n { error: \"Request body too large\" },\n { status: 413 },\n );\n }\n return NextResponse.json({ error: \"Invalid JSON body\" }, { status: 400 });\n }\n\n const parsed = ragSchema.safeParse(body);\n if (!parsed.success) {\n return NextResponse.json(\n { error: \"Invalid input\", details: parsed.error.issues },\n { status: 400 },\n );\n }\n const { question, history } = parsed.data;\n\n let llmConfig;\n try {\n llmConfig = getLLMConfig();\n } catch (error: unknown) {\n // Setup details (provider names, env var names) stay in the server log.\n console.error(\"[doccupine] LLM configuration error:\", error);\n return NextResponse.json(\n {\n error:\n \"The AI assistant is not configured on this site. If you are the site owner, check the server logs.\",\n },\n { status: 500 },\n );\n }\n\n const encoder = new TextEncoder();\n let heartbeat: ReturnType<typeof setInterval> | null = null;\n let streamClosed = false;\n const workController = new AbortController();\n const abortWork = () => workController.abort(req.signal.reason);\n req.signal.addEventListener(\"abort\", abortWork, { once: true });\n if (req.signal.aborted) abortWork();\n const { signal } = workController;\n\n // Return the streaming response immediately and do ALL slow work (indexing,\n // search, model streaming) inside start(). This flushes headers + a first\n // byte right away so edge proxies never hit their time-to-first-byte timeout.\n const readableStream = new ReadableStream({\n async start(controller) {\n const safeEnqueue = (payload: string) => {\n if (streamClosed) return;\n try {\n controller.enqueue(encoder.encode(payload));\n } catch {\n // Stream already closed or cancelled - stop emitting.\n streamClosed = true;\n workController.abort();\n if (heartbeat) clearInterval(heartbeat);\n }\n };\n\n // Keep the connection alive while the index and model warm up.\n heartbeat = setInterval(() => safeEnqueue(`: keep-alive\\n\\n`), 15000);\n\n try {\n // First byte, before any slow work - satisfies the proxy TTFB window.\n safeEnqueue(`: connected\\n\\n`);\n\n // Ensure docs are indexed (loads precomputed embeddings when present).\n await ensureDocsIndex(false, signal);\n signal.throwIfAborted();\n\n // Use MCP search_docs tool to find relevant documentation\n const searchResults = await searchDocs(question, 6, signal);\n signal.throwIfAborted();\n\n // Build context from search results\n const context = searchResults\n .map(({ chunk, score }) => {\n const slug = chunk.uri.replace(\"docs://\", \"\").replace(/^\\/+/, \"\");\n const url = slug ? `/${slug}/` : \"/\";\n return `File: ${chunk.path}\\nURL: ${url}\\nScore: ${score.toFixed(3)}\\n----\\n${chunk.text}`;\n })\n .join(\"\\n\\n================\\n\\n\");\n\n // Build metadata from MCP search results and send it before the answer.\n const indexStatus = getIndexStatus();\n const metadata = {\n sources: searchResults.map(({ chunk, score }) => ({\n id: chunk.id,\n path: chunk.path,\n uri: chunk.uri,\n score,\n })),\n chunkCount: indexStatus.chunkCount,\n };\n safeEnqueue(\n `data: ${JSON.stringify({ type: \"metadata\", data: metadata })}\\n\\n`,\n );\n\n // Assemble the prompt, including conversation history for multi-turn.\n const prompt: {\n role: \"system\" | \"user\" | \"assistant\";\n content: string;\n }[] = [\n {\n role: \"system\" as const,\n content: systemContext,\n },\n ];\n if (history && history.length > 0) {\n for (const msg of history) {\n prompt.push({\n role: msg.role,\n content: msg.content,\n });\n }\n }\n prompt.push({\n role: \"user\" as const,\n content: `Question: ${question}\\n\\nContext:\\n${context}`,\n });\n\n // Create chat model and stream the response.\n const llm = createChatModel(llmConfig);\n const stream = await llm.stream(prompt, { signal });\n for await (const chunk of stream) {\n signal.throwIfAborted();\n const content = chunk?.content || \"\";\n if (content) {\n safeEnqueue(\n `data: ${JSON.stringify({ type: \"content\", data: content })}\\n\\n`,\n );\n }\n }\n\n signal.throwIfAborted();\n safeEnqueue(`data: ${JSON.stringify({ type: \"done\" })}\\n\\n`);\n } catch (error: unknown) {\n if (signal.aborted) return;\n console.error(\"[doccupine] RAG stream error:\", error);\n safeEnqueue(\n `data: ${JSON.stringify({ type: \"error\", data: friendlyLLMError(error) })}\\n\\n`,\n );\n } finally {\n if (heartbeat) clearInterval(heartbeat);\n streamClosed = true;\n req.signal.removeEventListener(\"abort\", abortWork);\n try {\n controller.close();\n } catch {\n // Already closed.\n }\n }\n },\n cancel() {\n streamClosed = true;\n workController.abort();\n if (heartbeat) clearInterval(heartbeat);\n },\n });\n\n return new Response(readableStream, {\n headers: {\n \"Content-Type\": \"text/event-stream\",\n \"Cache-Control\": \"no-cache, no-transform\",\n },\n });\n}\n\nexport async function GET(req: Request) {\n if (!(await isRagRequestAuthorized(req))) {\n return NextResponse.json({ error: \"Unauthorized\" }, { status: 401 });\n }\n\n const status = getIndexStatus();\n return NextResponse.json({\n ready: status.ready,\n chunks: status.chunkCount,\n reason: status.reason,\n });\n}\n";
1
+ export declare const ragRoutesTemplate = "import { NextResponse } from \"next/server\";\nimport { z } from \"zod\";\nimport { getLLMConfig, createChatModel } from \"@/services/llm\";\nimport {\n searchDocs,\n ensureDocsIndex,\n getIndexStatus,\n} from \"@/services/mcp/server\";\nimport { rateLimit } from \"@/utils/rateLimit\";\nimport { config } from \"@/utils/config\";\nimport { isSiteRequestAuthorized } from \"@/lib/access\";\nimport { timingSafeEqual } from \"@/lib/siteGate\";\nimport { readJsonBody, RequestTooLargeError } from \"@/utils/requestBody\";\n\n// Covers the schema's worst-case UTF-8 payload while retaining a hard cap.\nconst MAX_RAG_REQUEST_BYTES = 512 * 1024;\n\nconst messageSchema = z\n .object({\n role: z.enum([\"user\", \"assistant\"]),\n content: z.string().max(4000),\n })\n .strict();\n\nconst ragSchema = z\n .object({\n question: z.string().min(1).max(2000),\n history: z.array(messageSchema).max(20).optional(),\n })\n .strict();\n\nfunction bearerToken(req: Request): string | null {\n const authorization = req.headers.get(\"authorization\");\n return authorization?.startsWith(\"Bearer \")\n ? authorization.slice(\"Bearer \".length)\n : null;\n}\n\nasync function isRagRequestAuthorized(req: Request): Promise<boolean> {\n const siteAuthorized = await isSiteRequestAuthorized();\n if (process.env.SITE_PASSWORD && siteAuthorized) return true;\n\n const apiKey = process.env.RAG_API_KEY;\n if (apiKey) {\n const token = bearerToken(req);\n return token !== null && timingSafeEqual(token, apiKey);\n }\n return siteAuthorized;\n}\n\nconst projectName = config.name || \"Doccupine\";\n\nconst systemContext = `You are AI Assistant, a documentation assistant for ${projectName}, Your name is ${projectName} AI Assistant.\n\n## Core Rules\n1. Answer ONLY from the provided context. Never fabricate information.\n2. If the answer isn't in the context, say so clearly and suggest relevant sections or pages the user might check.\n3. If the question is ambiguous, ask a brief clarifying question before answering.\n\n## Response Style\n- Be concise and direct. Lead with the answer, then provide details if needed.\n- Use code examples from the context when relevant.\n- Match the technical level of the user's question.\n\n## MDX/Code Formatting\nWhen including code blocks in your response:\n- Never nest fenced code blocks (triple backticks) inside other fenced code blocks.\n- If you need to show MDX source that itself contains code blocks, use indented code blocks or escape the inner backticks.\n- All output must be valid MDX that renders correctly.\n\n## Internal Links\nEach context chunk includes a \"URL:\" line with the pre-computed page URL. Use it directly when linking:\n- Format links as markdown: [Page Title](/slug/).\n- Never expose raw file paths like \"/app/.../page.tsx\" to the user.\n- Never include route group segments in parentheses, like \"(site)\", in any link - they are internal directory names and do not exist in real URLs. Use \"/code/\" not \"/(site)/code/\".\n- Do NOT add a \"Related Pages\" section at the end - sources are shown separately by the UI.\n\n## Greetings & Small Talk\nIf the user sends a greeting or non-documentation question, respond briefly and ask how you can help with the documentation.`;\n\n// Maps provider/stream failures to fixed visitor-safe messages. Raw provider\n// errors can include API-key fragments, org ids, and billing URLs, so only\n// these strings ever reach the client; the full error goes to the server log.\nfunction friendlyLLMError(error: unknown): string {\n const raw = error instanceof Error ? error.message : String(error);\n if (/\\b401\\b|api.?key|authenticat|unauthorized/i.test(raw)) {\n return \"The assistant's model provider rejected its API key. If you are the site owner, check the server logs and your API key configuration.\";\n }\n if (/\\b429\\b|quota|rate.?limit|billing/i.test(raw)) {\n return \"The assistant's model provider is rate limiting requests right now. Please try again in a moment.\";\n }\n if (\n /timed?.?out|ETIMEDOUT|ECONNRESET|ENOTFOUND|fetch failed|network/i.test(raw)\n ) {\n return \"The assistant could not reach its model provider. Please try again.\";\n }\n return \"The assistant hit an unexpected error. Please try again.\";\n}\n\n// LangChain + the MCP SDK require the Node.js runtime (not edge).\nexport const runtime = \"nodejs\";\n// Safety net for the streaming function (Vercel-only; ignored elsewhere).\n// The heartbeat below, not this value, is what prevents proxy 524 timeouts.\nexport const maxDuration = 60;\n\nexport async function POST(req: Request) {\n if (!(await isRagRequestAuthorized(req))) {\n return NextResponse.json({ error: \"Unauthorized\" }, { status: 401 });\n }\n\n const { allowed, retryAfter } = rateLimit(req);\n if (!allowed) {\n return NextResponse.json(\n { error: \"Too many requests\" },\n { status: 429, headers: { \"Retry-After\": String(retryAfter) } },\n );\n }\n\n // Validate the request up front so genuine client/config errors still return\n // real status codes before we commit to a 200 streaming response.\n let body: unknown;\n try {\n body = await readJsonBody(req, MAX_RAG_REQUEST_BYTES);\n } catch (error: unknown) {\n if (req.signal.aborted) throw error;\n if (error instanceof RequestTooLargeError) {\n return NextResponse.json(\n { error: \"Request body too large\" },\n { status: 413 },\n );\n }\n return NextResponse.json({ error: \"Invalid JSON body\" }, { status: 400 });\n }\n\n const parsed = ragSchema.safeParse(body);\n if (!parsed.success) {\n return NextResponse.json(\n { error: \"Invalid input\", details: parsed.error.issues },\n { status: 400 },\n );\n }\n const { question, history } = parsed.data;\n\n let llmConfig;\n try {\n llmConfig = getLLMConfig();\n } catch (error: unknown) {\n // Setup details (provider names, env var names) stay in the server log.\n console.error(\"[doccupine] LLM configuration error:\", error);\n return NextResponse.json(\n {\n error:\n \"The AI assistant is not configured on this site. If you are the site owner, check the server logs.\",\n },\n { status: 500 },\n );\n }\n\n const encoder = new TextEncoder();\n let heartbeat: ReturnType<typeof setInterval> | null = null;\n let streamClosed = false;\n const workController = new AbortController();\n const abortWork = () => workController.abort(req.signal.reason);\n req.signal.addEventListener(\"abort\", abortWork, { once: true });\n if (req.signal.aborted) abortWork();\n const { signal } = workController;\n\n // Return the streaming response immediately and do ALL slow work (indexing,\n // search, model streaming) inside start(). This flushes headers + a first\n // byte right away so edge proxies never hit their time-to-first-byte timeout.\n const readableStream = new ReadableStream({\n async start(controller) {\n const safeEnqueue = (payload: string) => {\n if (streamClosed) return;\n try {\n controller.enqueue(encoder.encode(payload));\n } catch {\n // Stream already closed or cancelled - stop emitting.\n streamClosed = true;\n workController.abort();\n if (heartbeat) clearInterval(heartbeat);\n }\n };\n\n // Keep the connection alive while the index and model warm up.\n heartbeat = setInterval(() => safeEnqueue(`: keep-alive\\n\\n`), 15000);\n\n try {\n // First byte, before any slow work - satisfies the proxy TTFB window.\n safeEnqueue(`: connected\\n\\n`);\n\n // Ensure docs are indexed (loads precomputed embeddings when present).\n await ensureDocsIndex(false, signal);\n signal.throwIfAborted();\n\n // Use MCP search_docs tool to find relevant documentation\n const searchResults = await searchDocs(question, 6, signal);\n signal.throwIfAborted();\n\n // Build context from search results\n const context = searchResults\n .map(({ chunk, score }) => {\n const slug = chunk.uri.replace(\"docs://\", \"\").replace(/^\\/+/, \"\");\n const url = slug ? `/${slug}/` : \"/\";\n return `File: ${chunk.path}\\nURL: ${url}\\nScore: ${score.toFixed(3)}\\n----\\n${chunk.text}`;\n })\n .join(\"\\n\\n================\\n\\n\");\n\n // Build metadata from MCP search results and send it before the answer.\n const indexStatus = getIndexStatus();\n const metadata = {\n sources: searchResults.map(({ chunk, score }) => ({\n id: chunk.id,\n path: chunk.path,\n uri: chunk.uri,\n score,\n })),\n chunkCount: indexStatus.chunkCount,\n };\n safeEnqueue(\n `data: ${JSON.stringify({ type: \"metadata\", data: metadata })}\\n\\n`,\n );\n\n // Assemble the prompt, including conversation history for multi-turn.\n const prompt: {\n role: \"system\" | \"user\" | \"assistant\";\n content: string;\n }[] = [\n {\n role: \"system\" as const,\n content: systemContext,\n },\n ];\n if (history && history.length > 0) {\n for (const msg of history) {\n prompt.push({\n role: msg.role,\n content: msg.content,\n });\n }\n }\n prompt.push({\n role: \"user\" as const,\n content: `Question: ${question}\\n\\nContext:\\n${context}`,\n });\n\n // Create chat model and stream the response.\n const llm = createChatModel(llmConfig);\n const stream = await llm.stream(prompt, { signal });\n for await (const chunk of stream) {\n signal.throwIfAborted();\n const content = chunk?.content || \"\";\n if (content) {\n safeEnqueue(\n `data: ${JSON.stringify({ type: \"content\", data: content })}\\n\\n`,\n );\n }\n }\n\n signal.throwIfAborted();\n safeEnqueue(`data: ${JSON.stringify({ type: \"done\" })}\\n\\n`);\n } catch (error: unknown) {\n if (signal.aborted) return;\n console.error(\"[doccupine] RAG stream error:\", error);\n safeEnqueue(\n `data: ${JSON.stringify({ type: \"error\", data: friendlyLLMError(error) })}\\n\\n`,\n );\n } finally {\n if (heartbeat) clearInterval(heartbeat);\n streamClosed = true;\n req.signal.removeEventListener(\"abort\", abortWork);\n try {\n controller.close();\n } catch {\n // Already closed.\n }\n }\n },\n cancel() {\n streamClosed = true;\n workController.abort();\n if (heartbeat) clearInterval(heartbeat);\n },\n });\n\n return new Response(readableStream, {\n headers: {\n \"Content-Type\": \"text/event-stream\",\n \"Cache-Control\": \"no-cache, no-transform\",\n },\n });\n}\n\nexport async function GET(req: Request) {\n if (!(await isRagRequestAuthorized(req))) {\n return NextResponse.json({ error: \"Unauthorized\" }, { status: 401 });\n }\n\n const status = getIndexStatus();\n return NextResponse.json({\n ready: status.ready,\n chunks: status.chunkCount,\n reason: status.reason,\n });\n}\n";
@@ -12,7 +12,8 @@ import { isSiteRequestAuthorized } from "@/lib/access";
12
12
  import { timingSafeEqual } from "@/lib/siteGate";
13
13
  import { readJsonBody, RequestTooLargeError } from "@/utils/requestBody";
14
14
 
15
- const MAX_RAG_REQUEST_BYTES = 32 * 1024;
15
+ // Covers the schema's worst-case UTF-8 payload while retaining a hard cap.
16
+ const MAX_RAG_REQUEST_BYTES = 512 * 1024;
16
17
 
17
18
  const messageSchema = z
18
19
  .object({
@@ -1 +1 @@
1
- export declare const chatTemplate = "\"use client\";\nimport React, {\n createContext,\n useCallback,\n useContext,\n useEffect,\n useLayoutEffect,\n useRef,\n useState,\n useSyncExternalStore,\n} from \"react\";\nimport styled, { css, keyframes } from \"styled-components\";\nimport { Button, IconButton } from \"cherry-styled-components\";\nimport { ArrowUp, LoaderPinwheel, RotateCcw, Sparkles, X } from \"lucide-react\";\nimport remarkGfm from \"remark-gfm\";\nimport rehypeHighlight from \"rehype-highlight\";\nimport { MDXRemote, MDXRemoteSerializeResult } from \"next-mdx-remote\";\nimport { serialize } from \"next-mdx-remote/serialize\";\nimport Link from \"next/link\";\nimport { mq, theme, Theme } from \"@/app/theme\";\nimport { Callout } from \"@/components/layout/Callout\";\nimport { useLockBodyScroll } from \"@/components/LockBodyScroll\";\nimport { useMDXComponents as getMDXComponents } from \"@/components/MDXComponents\";\nimport {\n styledAnchor,\n styledTable,\n stylesLists,\n StyledSmallButton,\n interactiveStyles,\n thinScrollbar,\n} from \"@/components/layout/SharedStyled\";\n\nconst mdxComponents = getMDXComponents({});\n\nconst MOBILE_CHAT_QUERY = `(max-width: ${theme.breakpoints.lg - 1}px)`;\n\nfunction subscribeToMobileChat(callback: () => void) {\n const mediaQuery = window.matchMedia(MOBILE_CHAT_QUERY);\n mediaQuery.addEventListener(\"change\", callback);\n return () => mediaQuery.removeEventListener(\"change\", callback);\n}\n\nfunction getMobileChatSnapshot() {\n return window.matchMedia(MOBILE_CHAT_QUERY).matches;\n}\n\nfunction useIsMobileChat() {\n return useSyncExternalStore(\n subscribeToMobileChat,\n getMobileChatSnapshot,\n () => false,\n );\n}\n\nconst styledText = css<{ theme: Theme }>`\n font-size: ${({ theme }) => theme.fontSizes.text.xs};\n line-height: ${({ theme }) => theme.lineHeights.text.xs};\n\n ${mq(\"lg\")} {\n font-size: ${({ theme }) => theme.fontSizes.small.lg};\n line-height: ${({ theme }) => theme.lineHeights.small.lg};\n }\n`;\n\nconst StyledChatSurface = styled.div<{ $isVisible: boolean }>`\n position: fixed;\n inset: 0;\n z-index: 1000;\n pointer-events: none;\n\n & > * {\n pointer-events: auto;\n }\n\n ${({ $isVisible }) =>\n !$isVisible &&\n css`\n visibility: hidden;\n\n & > * {\n pointer-events: none;\n }\n `}\n`;\n\nconst StyledChat = styled.div<{ theme: Theme; $isVisible: boolean }>`\n margin: 0;\n position: fixed;\n top: 0;\n right: 0;\n width: 100%;\n height: calc(100dvh - 90px);\n overflow-y: scroll;\n overflow-x: hidden;\n z-index: 1000;\n padding: 0 20px;\n /* See StyledChatForm: visibility snaps open and is delayed on close, so the\n panel is focusable as soon as it opens. */\n transition:\n transform 0.3s ease,\n opacity 0.3s ease,\n visibility 0s linear 0s;\n transform: translateX(0);\n background: ${({ theme }) => theme.colors.light};\n -webkit-overflow-scrolling: touch;\n opacity: 1;\n visibility: visible;\n\n &::-webkit-scrollbar {\n display: none;\n }\n\n ${({ $isVisible }) =>\n !$isVisible &&\n css`\n transform: translateX(100%);\n opacity: 0;\n visibility: hidden;\n transition-delay: 0s, 0s, 0.3s;\n `}\n\n @media (prefers-reduced-motion: reduce) {\n transition: none;\n }\n\n ${mq(\"lg\")} {\n width: 420px;\n border-left: solid 1px ${({ theme }) => theme.colors.grayLight};\n }\n`;\n\nconst loadingAnimation = keyframes`\n 0% {\n transform: rotate(0deg);\n }\n 100% {\n transform: rotate(360deg);\n }\n`;\n\nconst rotateGradient = keyframes`\n 0% {\n --gradient-angle: 0deg;\n }\n 100% {\n --gradient-angle: 360deg;\n }\n`;\n\nconst pulseGlow = keyframes`\n 0%, 100% {\n opacity: 0.5;\n filter: blur(16px);\n }\n 50% {\n opacity: 1;\n filter: blur(22px);\n }\n`;\n\nconst sparkleFloat = keyframes`\n 0%, 100% {\n opacity: 0;\n transform: translateY(0) scale(0);\n }\n 50% {\n opacity: 0.9;\n transform: translateY(-20px) scale(1);\n }\n`;\n\nconst shimmer = keyframes`\n 0% {\n background-position: 0% center;\n }\n 50% {\n background-position: 100% center;\n }\n 100% {\n background-position: 0% center;\n }\n`;\n\nconst StyledRainbowInputWrapper = styled.div<{\n theme: Theme;\n $isActive: boolean;\n}>`\n @property --gradient-angle {\n syntax: \"<angle>\";\n initial-value: 0deg;\n inherits: false;\n }\n\n position: relative;\n flex: 1;\n\n &::before {\n content: \"\";\n position: absolute;\n inset: -2px;\n border-radius: 14px;\n background: conic-gradient(\n from var(--gradient-angle),\n #cc5555,\n #d9a745,\n #3ab0cc,\n #cc7fc2,\n #4380cc,\n #4c1fa3,\n #cc5555\n );\n opacity: 0;\n transition: opacity 0.4s cubic-bezier(0.4, 0, 0.2, 1);\n animation: ${rotateGradient} 3s linear infinite;\n z-index: 0;\n }\n\n &::after {\n content: \"\";\n position: absolute;\n inset: -10px;\n border-radius: 20px;\n background: conic-gradient(\n from var(--gradient-angle),\n #ff6b6b66,\n #feca5766,\n #48dbfb66,\n #ff9ff366,\n #54a0ff66,\n #5f27cd66,\n #ff6b6b66\n );\n opacity: 0;\n transition: opacity 0.4s cubic-bezier(0.4, 0, 0.2, 1);\n animation:\n ${rotateGradient} 3s linear infinite,\n ${pulseGlow} 2s ease-in-out infinite;\n z-index: -1;\n pointer-events: none;\n }\n\n &:hover::before,\n &:focus-within::before {\n opacity: 1;\n }\n\n &:hover::after,\n &:focus-within::after {\n opacity: 1;\n }\n\n ${({ $isActive }) =>\n $isActive &&\n css`\n &::before {\n opacity: 1;\n }\n &::after {\n opacity: 1;\n }\n `}\n`;\n\nconst StyledSparkleContainer = styled.div<{ $isActive: boolean }>`\n position: absolute;\n inset: -30px;\n pointer-events: none;\n overflow: hidden;\n border-radius: 30px;\n z-index: -2;\n opacity: 0;\n transition: opacity 0.4s ease;\n\n ${({ $isActive }) =>\n $isActive &&\n css`\n opacity: 1;\n `}\n`;\n\nconst StyledSparkle = styled.div<{\n $color: string;\n $left: number;\n $top: number;\n $delay: number;\n}>`\n position: absolute;\n width: 4px;\n height: 4px;\n border-radius: 50%;\n background: ${({ $color }) => $color};\n box-shadow: 0 0 6px ${({ $color }) => $color};\n left: ${({ $left }) => $left}%;\n top: ${({ $top }) => $top}%;\n animation: ${sparkleFloat} 2s ease-in-out infinite;\n animation-delay: ${({ $delay }) => $delay}s;\n`;\n\nconst StyledRainbowInput = styled.input<{ theme: Theme }>`\n position: relative;\n z-index: 1;\n width: 100%;\n background: ${({ theme }) => theme.colors.light};\n border: 1px solid ${({ theme }) => theme.colors.grayLight};\n border-radius: 12px;\n padding: 12px 18px;\n font-size: ${({ theme }) => theme.fontSizes.text.lg};\n font-family: inherit;\n color: ${({ theme }) => theme.colors.dark};\n outline: none;\n transition:\n border-color 0.3s ease,\n box-shadow 0.3s ease;\n\n ${mq(\"lg\")} {\n font-size: ${({ theme }) => theme.fontSizes.small.lg};\n }\n\n &::placeholder {\n color: ${({ theme }) =>\n `color-mix(in srgb, ${theme.colors.dark} 40%, transparent)`};\n transition: color 0.3s ease;\n }\n\n &:focus::placeholder {\n color: ${({ theme }) =>\n `color-mix(in srgb, ${theme.colors.dark} 60%, transparent)`};\n }\n\n &:focus {\n border-color: transparent;\n }\n`;\n\nconst StyledRainbowButton = styled(Button)<{\n theme: Theme;\n $hasContent: boolean;\n}>`\n padding-top: 10px;\n padding-bottom: 10px;\n position: relative;\n overflow: hidden;\n transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1) !important;\n color: ${({ theme }) => theme.colors.surface};\n\n &::before {\n content: \"\";\n position: absolute;\n inset: 0;\n background: linear-gradient(\n 135deg,\n #ff6b6b,\n #feca57,\n #48dbfb,\n #ff9ff3,\n #54a0ff\n );\n background-size: 300% 300%;\n opacity: 0;\n transition: opacity 0.3s ease;\n z-index: 0;\n animation: ${shimmer} 3s linear infinite;\n width: 200%;\n }\n\n ${({ $hasContent }) =>\n $hasContent &&\n css`\n &::before {\n opacity: 1;\n }\n `}\n\n &:hover::before {\n opacity: 1;\n }\n\n &:hover {\n transform: scale(1.05);\n }\n\n &:active {\n transform: scale(0.95);\n }\n\n & svg {\n position: relative;\n z-index: 1;\n transition: transform 0.3s ease;\n }\n\n &:disabled,\n &:disabled:hover {\n background: ${({ theme }) => theme.colors.primaryDark};\n transform: none;\n box-shadow: none;\n\n &::before {\n opacity: 0;\n }\n }\n`;\n\nconst StyledChatForm = styled.form<{ theme: Theme; $isVisible: boolean }>`\n display: flex;\n gap: 10px;\n justify-content: center;\n align-items: center;\n background: ${({ theme }) => theme.colors.light};\n padding: 20px;\n position: fixed;\n bottom: 0;\n right: 0;\n z-index: 1000;\n width: 100%;\n border-top: solid 1px ${({ theme }) => theme.colors.grayLight};\n /* visibility is animatable, so transitioning \"all\" keeps this hidden for the\n whole slide-in - long enough for the focus() that follows opening to be a\n silent no-op. Snap it on open (transition-delay below) and delay it on\n close so the slide-out stays visible while it animates. */\n transition:\n transform 0.3s ease,\n opacity 0.3s ease,\n visibility 0s linear 0.3s;\n transform: translateX(100%);\n opacity: 0;\n visibility: hidden;\n\n ${mq(\"lg\")} {\n width: 420px;\n border-left: solid 1px ${({ theme }) => theme.colors.grayLight};\n }\n\n ${({ $isVisible }) =>\n $isVisible &&\n css`\n opacity: 1;\n transform: translateX(0);\n visibility: visible;\n transition-delay: 0s;\n `}\n\n @media (prefers-reduced-motion: reduce) {\n transition: none;\n }\n\n & .loading {\n animation: ${loadingAnimation} 1s linear infinite;\n }\n`;\n\nconst StyledGlowSmallButton = styled(StyledSmallButton)<{\n theme: Theme;\n $hasContent: boolean;\n}>`\n @property --gradient-angle {\n syntax: \"<angle>\";\n initial-value: 0deg;\n inherits: false;\n }\n\n position: relative;\n isolation: isolate;\n margin-right: 0;\n background: ${({ theme }) => theme.colors.light};\n padding: 0;\n\n &::before {\n content: \"\";\n inset: -2px;\n border-radius: 8px;\n background: conic-gradient(\n from var(--gradient-angle),\n #cc5555,\n #d9a745,\n #3ab0cc,\n #cc7fc2,\n #4380cc,\n #4c1fa3,\n #cc5555\n );\n opacity: 0;\n transition: opacity 0.4s cubic-bezier(0.4, 0, 0.2, 1);\n animation: ${rotateGradient} 3s linear infinite;\n z-index: -1;\n position: absolute;\n top: -2px;\n left: -2px;\n width: calc(100% + 4px);\n height: calc(100% + 4px);\n }\n\n &::after {\n content: \"\";\n position: absolute;\n inset: -8px;\n border-radius: 14px;\n background: conic-gradient(\n from var(--gradient-angle),\n #ff6b6b66,\n #feca5766,\n #48dbfb66,\n #ff9ff366,\n #54a0ff66,\n #5f27cd66,\n #ff6b6b66\n );\n opacity: 0;\n transition: opacity 0.4s cubic-bezier(0.4, 0, 0.2, 1);\n animation:\n ${rotateGradient} 3s linear infinite,\n ${pulseGlow} 2s ease-in-out infinite;\n z-index: -2;\n pointer-events: none;\n }\n\n &:hover::before,\n &:hover::after {\n opacity: 1;\n }\n\n & span {\n padding: 6px 8px;\n display: flex;\n background: ${({ theme }) => theme.colors.light};\n border-radius: ${({ theme }) => theme.spacing.radius.xs};\n gap: 6px;\n }\n\n ${({ $hasContent }) =>\n $hasContent &&\n css`\n &::before {\n opacity: 1;\n }\n &::after {\n opacity: 1;\n }\n `}\n`;\n\nconst StyledError = styled.div`\n margin: 20px 0;\n width: 100%;\n`;\n\nconst loadingDotAnimation = keyframes`\n 0% {\n opacity: 0;\n }\n 50% {\n opacity: 1;\n }\n 100% {\n opacity: 0;\n }\n`;\n\nconst StyledLoading = styled.div<{ theme: Theme }>`\n overflow-x: auto;\n ${thinScrollbar};\n margin: 20px 0;\n width: 100%;\n font-weight: 600;\n ${styledText};\n color: ${({ theme }) => theme.colors.dark};\n\n & span {\n &:nth-child(1) {\n animation: ${loadingDotAnimation} 1s ease infinite;\n }\n &:nth-child(2) {\n animation: ${loadingDotAnimation} 1s ease infinite;\n animation-delay: 0.2s;\n }\n &:nth-child(3) {\n animation: ${loadingDotAnimation} 1s ease infinite;\n animation-delay: 0.4s;\n }\n }\n`;\n\nconst StyledAnswer = styled.div<{ theme: Theme; $isAnswer: boolean }>`\n overflow-x: auto;\n ${thinScrollbar};\n background: ${({ theme }) => theme.colors.primary};\n color: ${({ theme }) => theme.colors.surface};\n padding: 9px 14px;\n border-radius: 16px 16px 4px 16px;\n margin: 20px 0 20px auto;\n width: fit-content;\n max-width: min(560px, 88%);\n font-weight: 500;\n white-space: pre-wrap;\n overflow-wrap: anywhere;\n ${styledText};\n\n & p {\n ${styledText};\n }\n\n ${({ $isAnswer }) =>\n $isAnswer &&\n css`\n background: transparent;\n color: ${({ theme }) => theme.colors.dark};\n padding: 0;\n width: 100%;\n max-width: 100%;\n margin: 20px 0;\n border-radius: 0;\n font-weight: inherit;\n white-space: normal;\n `}\n\n & code:not([class]) {\n background: ${({ theme }) =>\n `color-mix(in srgb, ${theme.colors.primaryLight} 20%, transparent)`};\n color: ${({ theme }) => theme.colors.dark};\n padding: 2px 4px;\n border-radius: ${({ theme }) => theme.spacing.radius.xs};\n white-space: pre;\n }\n\n ${styledAnchor};\n ${stylesLists};\n ${styledTable};\n\n & pre,\n & .hljs {\n margin: 10px 0;\n }\n\n & .code-wrapper pre {\n margin: 0;\n ${styledText};\n }\n\n & > *:first-child {\n margin-top: 0;\n }\n\n & > *:last-child {\n margin-bottom: 0;\n\n & > *:last-child {\n margin-bottom: 0;\n }\n }\n\n & ul,\n & ol {\n & li {\n ${styledText};\n }\n }\n\n & img,\n & video,\n & iframe {\n max-width: 100%;\n border-radius: ${({ theme }) => theme.spacing.radius.lg};\n margin: 10px 0;\n display: block;\n }\n\n & h1,\n & h2,\n & h3,\n & h4,\n & h5,\n & h6 {\n margin: 10px 0;\n padding: 0;\n }\n`;\n\nconst StyledSources = styled.div`\n display: flex;\n gap: 16px;\n flex-wrap: wrap;\n margin: -5px 0 20px;\n`;\n\nconst StyledSourceLink = styled(Link)<{ theme: Theme }>`\n position: relative;\n text-decoration: none;\n font-size: ${({ theme }) => theme.fontSizes.small.lg};\n line-height: 1;\n color: ${({ theme }) => theme.colors.primary};\n display: flex;\n gap: 6px;\n transition: all 0.3s ease;\n font-weight: 600;\n white-space: nowrap;\n min-width: fit-content;\n background: ${({ theme }) =>\n `color-mix(in srgb, ${theme.colors.primaryLight} 10%, transparent)`};\n padding: 6px 8px;\n border-radius: ${({ theme }) => theme.spacing.radius.xs};\n ${interactiveStyles};\n\n & * {\n margin: auto 0;\n }\n\n &:hover {\n color: ${({ theme }) => theme.colors.accent};\n }\n`;\n\nconst StyledChatTitle = styled.div<{ theme: Theme }>`\n display: flex;\n flex-wrap: nowrap;\n justify-content: space-between;\n position: sticky;\n margin: 0 -20px;\n padding: 16px 20px;\n height: 62px;\n top: 0;\n background: ${({ theme }) => theme.colors.light};\n border-bottom: solid 1px ${({ theme }) => theme.colors.grayLight};\n z-index: 1000;\n`;\n\nconst StyledChatTitleIconWrapper = styled.span<{ theme: Theme }>`\n display: flex;\n align-items: center;\n gap: 12px;\n color: ${({ theme }) => theme.colors.dark};\n`;\n\ntype Source = {\n id: string;\n path: string;\n uri: string;\n score: number;\n};\n\ntype Answer = {\n text: string;\n answer?: boolean;\n mdx?: MDXRemoteSerializeResult;\n sources?: Source[];\n};\n\nconst SPARKLE_COLORS = [\n \"#ff6b6b\",\n \"#feca57\",\n \"#48dbfb\",\n \"#ff9ff3\",\n \"#54a0ff\",\n \"#5f27cd\",\n];\n\n// Deterministic sparkle positions to avoid hydration mismatch\nconst SPARKLE_POSITIONS = [\n { left: 8, top: 35 },\n { left: 17, top: 55 },\n { left: 26, top: 28 },\n { left: 35, top: 68 },\n { left: 44, top: 42 },\n { left: 53, top: 75 },\n { left: 62, top: 32 },\n { left: 71, top: 58 },\n { left: 80, top: 45 },\n { left: 89, top: 65 },\n];\n\ninterface RainbowInputProps {\n id?: string;\n value: string;\n onChange: (e: React.ChangeEvent<HTMLInputElement>) => void;\n placeholder?: string;\n autoComplete?: string;\n \"aria-label\"?: string;\n inputRef?: React.Ref<HTMLInputElement>;\n}\n\nfunction RainbowInput({\n id,\n value,\n onChange,\n placeholder,\n autoComplete,\n \"aria-label\": ariaLabel,\n inputRef,\n}: RainbowInputProps) {\n const [isFocused, setIsFocused] = useState(false);\n const [isHovered, setIsHovered] = useState(false);\n const isActive = isFocused || isHovered;\n\n const sparkles = SPARKLE_POSITIONS.map((pos, i) => ({\n color: SPARKLE_COLORS[i % SPARKLE_COLORS.length],\n left: pos.left,\n top: pos.top,\n delay: i * 0.12,\n }));\n\n return (\n <StyledRainbowInputWrapper\n $isActive={isActive}\n onMouseEnter={() => setIsHovered(true)}\n onMouseLeave={() => setIsHovered(false)}\n >\n <StyledSparkleContainer $isActive={isActive}>\n {sparkles.map((sparkle, i) => (\n <StyledSparkle\n key={i}\n $color={sparkle.color}\n $left={sparkle.left}\n $top={sparkle.top}\n $delay={sparkle.delay}\n />\n ))}\n </StyledSparkleContainer>\n <StyledRainbowInput\n ref={inputRef}\n id={id}\n value={value}\n onChange={onChange}\n placeholder={placeholder}\n autoComplete={autoComplete}\n aria-label={ariaLabel}\n onFocus={() => setIsFocused(true)}\n onBlur={() => setIsFocused(false)}\n />\n </StyledRainbowInputWrapper>\n );\n}\n\nfunction ChatButtonCTA() {\n const { toggleChat, isOpen } = useContext(ChatContext);\n\n return (\n <StyledGlowSmallButton\n onClick={toggleChat}\n aria-label=\"Ask AI Assistant\"\n $hasContent={isOpen}\n type=\"button\"\n >\n <span>\n <Sparkles size={16} />\n Ask AI\n </span>\n </StyledGlowSmallButton>\n );\n}\n\nfunction Chat() {\n const {\n isOpen,\n question,\n setQuestion,\n loading,\n error,\n answer,\n ask,\n closeChat,\n resetChat,\n chatInputRef,\n } = useContext(ChatContext);\n const chatSurfaceRef = useRef<HTMLDivElement | null>(null);\n const chatScrollRef = useRef<HTMLDivElement | null>(null);\n const scrollFrameRef = useRef<number | null>(null);\n const shouldAutoScrollRef = useRef(true);\n const loadingRef = useRef(loading);\n const isMobileChat = useIsMobileChat();\n const isMobileModal = isOpen && isMobileChat;\n\n useLockBodyScroll(isOpen);\n\n useEffect(() => {\n loadingRef.current = loading;\n }, [loading]);\n\n useLayoutEffect(() => {\n if (isOpen) {\n shouldAutoScrollRef.current = true;\n return;\n }\n\n if (scrollFrameRef.current !== null) {\n cancelAnimationFrame(scrollFrameRef.current);\n scrollFrameRef.current = null;\n }\n }, [isOpen]);\n\n useEffect(() => {\n if (!isOpen || !shouldAutoScrollRef.current) return;\n if (scrollFrameRef.current !== null) return;\n\n scrollFrameRef.current = requestAnimationFrame(() => {\n scrollFrameRef.current = null;\n const scrollContainer = chatScrollRef.current;\n if (!scrollContainer || !shouldAutoScrollRef.current) return;\n const reduceMotion = window.matchMedia(\n \"(prefers-reduced-motion: reduce)\",\n ).matches;\n scrollContainer.scrollTo({\n top: scrollContainer.scrollHeight,\n behavior: reduceMotion || loadingRef.current ? \"auto\" : \"smooth\",\n });\n });\n }, [answer, isOpen, loading]);\n\n useEffect(() => {\n return () => {\n if (scrollFrameRef.current !== null) {\n cancelAnimationFrame(scrollFrameRef.current);\n }\n };\n }, []);\n\n useEffect(() => {\n if (!isMobileModal || !chatSurfaceRef.current) return;\n\n const surface = chatSurfaceRef.current;\n const inertSiblings: Array<{\n element: HTMLElement;\n wasInert: boolean;\n }> = [];\n let current: HTMLElement = surface;\n\n while (current.parentElement) {\n const parent = current.parentElement;\n for (const sibling of Array.from(parent.children)) {\n if (sibling === current || !(sibling instanceof HTMLElement)) continue;\n inertSiblings.push({ element: sibling, wasInert: sibling.inert });\n sibling.inert = true;\n }\n if (parent === document.body) break;\n current = parent;\n }\n\n const containFocus = (event: FocusEvent) => {\n if (event.target instanceof Node && !surface.contains(event.target)) {\n chatInputRef.current?.focus();\n }\n };\n\n document.addEventListener(\"focusin\", containFocus);\n chatInputRef.current?.focus();\n\n return () => {\n document.removeEventListener(\"focusin\", containFocus);\n for (const { element, wasInert } of inertSiblings) {\n element.inert = wasInert;\n }\n };\n }, [chatInputRef, isMobileModal]);\n\n const handleChatScroll = () => {\n const scrollContainer = chatScrollRef.current;\n if (!scrollContainer) return;\n const distanceFromBottom =\n scrollContainer.scrollHeight -\n scrollContainer.scrollTop -\n scrollContainer.clientHeight;\n shouldAutoScrollRef.current =\n distanceFromBottom <= scrollContainer.clientHeight * 0.15;\n };\n\n const handleSurfaceKeyDown = (event: React.KeyboardEvent<HTMLDivElement>) => {\n if (event.key === \"Escape\" && isMobileModal) {\n event.preventDefault();\n event.stopPropagation();\n closeChat();\n return;\n }\n\n if (event.key !== \"Tab\" || !isMobileModal) return;\n const focusable = Array.from(\n chatSurfaceRef.current?.querySelectorAll<HTMLElement>(\n 'a[href], button:not([disabled]), input:not([disabled]), [tabindex]:not([tabindex=\"-1\"])',\n ) ?? [],\n ).filter(\n (element) =>\n element.offsetParent !== null &&\n element.getAttribute(\"aria-hidden\") !== \"true\",\n );\n if (focusable.length === 0) {\n event.preventDefault();\n return;\n }\n const first = focusable[0];\n const last = focusable[focusable.length - 1];\n if (event.shiftKey && document.activeElement === first) {\n event.preventDefault();\n last.focus();\n } else if (!event.shiftKey && document.activeElement === last) {\n event.preventDefault();\n first.focus();\n }\n };\n\n return (\n <StyledChatSurface\n ref={chatSurfaceRef}\n $isVisible={isOpen}\n inert={!isOpen}\n aria-hidden={!isOpen}\n role={isMobileModal ? \"dialog\" : \"complementary\"}\n aria-modal={isMobileModal ? \"true\" : undefined}\n aria-label=\"AI Assistant\"\n data-chat-surface\n data-markdown-ignore\n onKeyDownCapture={handleSurfaceKeyDown}\n >\n <StyledChat\n ref={chatScrollRef}\n $isVisible={isOpen}\n onScroll={handleChatScroll}\n >\n <StyledChatTitle>\n <StyledChatTitleIconWrapper>\n <Sparkles />\n <h3>AI Assistant</h3>\n </StyledChatTitleIconWrapper>\n <StyledChatTitleIconWrapper>\n <IconButton\n onClick={resetChat}\n aria-label=\"Reset chat history\"\n title=\"Reset chat history\"\n >\n <RotateCcw />\n </IconButton>\n <IconButton\n onClick={() => closeChat()}\n aria-label=\"Close chat\"\n title=\"Close chat\"\n >\n <X />\n </IconButton>\n </StyledChatTitleIconWrapper>\n </StyledChatTitle>\n {answer &&\n answer.map((a, i) => (\n <React.Fragment key={i}>\n <StyledAnswer $isAnswer={a.answer ?? false}>\n {a.answer && a.mdx ? (\n <MDXRemote {...a.mdx} components={mdxComponents} />\n ) : (\n a.text\n )}\n </StyledAnswer>\n {a.answer && a.sources && a.sources.length > 0 && (\n <StyledSources>\n {a.sources.map((src) => {\n const slug = src.uri\n .replace(\"docs://\", \"\")\n .replace(/^\\/+/, \"\");\n const href = slug ? `/${slug}/` : \"/\";\n const label = slug\n ? slug\n .split(\"/\")\n .pop()!\n .replace(/-/g, \" \")\n .replace(/\\b\\w/g, (c: string) => c.toUpperCase())\n : \"Home\";\n return (\n <StyledSourceLink\n key={src.id}\n href={href}\n onClick={() => {\n if (window.innerWidth <= 992) {\n closeChat();\n }\n }}\n >\n {label}\n </StyledSourceLink>\n );\n })}\n </StyledSources>\n )}\n </React.Fragment>\n ))}\n {loading && !answer[answer.length - 1]?.answer && (\n <StyledLoading>\n Answering<span>.</span>\n <span>.</span>\n <span>.</span>\n </StyledLoading>\n )}\n {error && (\n <StyledError>\n <Callout type=\"danger\">\n <p>\n <strong>Error:</strong> {error}\n </p>\n </Callout>\n </StyledError>\n )}\n </StyledChat>\n\n <StyledChatForm onSubmit={ask} $isVisible={isOpen} data-markdown-ignore>\n <RainbowInput\n id=\"chat-bottom-input\"\n inputRef={chatInputRef}\n value={question}\n onChange={(e) => setQuestion(e.target.value)}\n placeholder=\"Ask AI Assistant...\"\n autoComplete=\"off\"\n aria-label=\"Ask a follow-up question\"\n />\n <StyledRainbowButton\n type=\"submit\"\n disabled={loading || question.trim() === \"\"}\n $hasContent={question.trim().length > 0}\n aria-label={loading ? \"Loading response\" : \"Submit question\"}\n >\n {loading ? <LoaderPinwheel className=\"loading\" /> : <ArrowUp />}\n </StyledRainbowButton>\n </StyledChatForm>\n </StyledChatSurface>\n );\n}\n\nconst ChatContext = createContext<{\n isOpen: boolean;\n setIsOpen: (isOpen: boolean) => void;\n toggleChat: () => void;\n isChatActive: boolean;\n question: string;\n setQuestion: (q: string) => void;\n loading: boolean;\n error: string | null;\n answer: Answer[];\n setAnswer: (answers: Answer[]) => void;\n ask: (e: React.FormEvent) => void;\n askAssistant: (question: string, returnFocusTo?: HTMLElement | null) => void;\n closeChat: (restoreFocus?: boolean) => HTMLElement | null;\n registerSearchClose: (\n closeSearch: (restoreFocus?: boolean) => HTMLElement | null,\n ) => () => void;\n resetChat: () => void;\n chatInputRef: React.RefObject<HTMLInputElement | null>;\n}>({\n isOpen: false,\n setIsOpen: () => {},\n toggleChat: () => {},\n isChatActive: false,\n question: \"\",\n setQuestion: () => {},\n loading: false,\n error: null,\n answer: [],\n setAnswer: () => {},\n ask: () => {},\n askAssistant: () => {},\n closeChat: () => null,\n registerSearchClose: () => () => {},\n resetChat: () => {},\n chatInputRef: { current: null },\n});\n\ninterface ChatContextProviderProps {\n children: React.ReactNode;\n isChatActive: boolean;\n}\n\nconst INITIAL_GREETING = \"Hey there, how can I assist you?\";\n\nconst ChtProvider = ({ children, isChatActive }: ChatContextProviderProps) => {\n const [isOpen, setIsOpen] = useState(false);\n const [question, setQuestion] = useState(\"\");\n const [loading, setLoading] = useState(false);\n const [error, setError] = useState<string | null>(null);\n const [answer, setAnswer] = useState<Answer[]>([]);\n const abortRef = useRef<AbortController | null>(null);\n const chatInputRef = useRef<HTMLInputElement | null>(null);\n const focusTimeoutRef = useRef<ReturnType<typeof setTimeout> | null>(null);\n const restoreFocusTimeoutRef = useRef<ReturnType<typeof setTimeout> | null>(\n null,\n );\n const pendingRestoreFocusRef = useRef<HTMLElement | null>(null);\n const openerRef = useRef<HTMLElement | null>(null);\n const closeSearchRef = useRef<\n ((restoreFocus?: boolean) => HTMLElement | null) | null\n >(null);\n const isOpenRef = useRef(isOpen);\n\n useEffect(() => {\n isOpenRef.current = isOpen;\n }, [isOpen]);\n\n const showChat = useCallback((returnFocusTo?: HTMLElement | null) => {\n const previousOverlayOpener = closeSearchRef.current?.(false) ?? null;\n const pendingChatOpener = pendingRestoreFocusRef.current;\n if (restoreFocusTimeoutRef.current) {\n clearTimeout(restoreFocusTimeoutRef.current);\n restoreFocusTimeoutRef.current = null;\n }\n pendingRestoreFocusRef.current = null;\n if (!isOpenRef.current) {\n const activeElement = document.activeElement;\n openerRef.current =\n returnFocusTo?.isConnected === true\n ? returnFocusTo\n : previousOverlayOpener?.isConnected === true\n ? previousOverlayOpener\n : pendingChatOpener?.isConnected === true\n ? pendingChatOpener\n : activeElement instanceof HTMLElement &&\n activeElement !== document.body\n ? activeElement\n : null;\n }\n isOpenRef.current = true;\n setIsOpen(true);\n if (focusTimeoutRef.current) clearTimeout(focusTimeoutRef.current);\n focusTimeoutRef.current = setTimeout(() => {\n focusTimeoutRef.current = null;\n chatInputRef.current?.focus();\n }, 0);\n }, []);\n\n // Open the assistant and seed its greeting on the first visit. The opener is\n // captured before the mobile dialog makes the rest of the page inert.\n const openChat = useCallback(() => {\n showChat();\n setAnswer((prev) =>\n prev.length === 0 ? [{ text: INITIAL_GREETING, answer: true }] : prev,\n );\n }, [showChat]);\n\n const closeChat = useCallback((restoreFocus = true) => {\n const pendingOpener = pendingRestoreFocusRef.current;\n if (!restoreFocus && restoreFocusTimeoutRef.current) {\n clearTimeout(restoreFocusTimeoutRef.current);\n restoreFocusTimeoutRef.current = null;\n pendingRestoreFocusRef.current = null;\n }\n if (!isOpenRef.current) return pendingOpener;\n if (focusTimeoutRef.current) {\n clearTimeout(focusTimeoutRef.current);\n focusTimeoutRef.current = null;\n }\n const activeElement = document.activeElement;\n if (\n activeElement instanceof HTMLElement &&\n activeElement.closest(\"[data-chat-surface]\")\n ) {\n activeElement.blur();\n }\n const opener = openerRef.current;\n openerRef.current = null;\n isOpenRef.current = false;\n setIsOpen(false);\n if (restoreFocusTimeoutRef.current) {\n clearTimeout(restoreFocusTimeoutRef.current);\n }\n if (restoreFocus) {\n pendingRestoreFocusRef.current = opener;\n restoreFocusTimeoutRef.current = setTimeout(() => {\n const focusTarget = pendingRestoreFocusRef.current;\n restoreFocusTimeoutRef.current = null;\n pendingRestoreFocusRef.current = null;\n if (focusTarget?.isConnected) focusTarget.focus();\n }, 0);\n } else {\n pendingRestoreFocusRef.current = null;\n }\n return opener;\n }, []);\n\n const registerSearchClose = useCallback(\n (closeSearch: (restoreFocus?: boolean) => HTMLElement | null) => {\n closeSearchRef.current = closeSearch;\n return () => {\n if (closeSearchRef.current === closeSearch) {\n closeSearchRef.current = null;\n }\n };\n },\n [],\n );\n\n const toggleChat = useCallback(() => {\n if (isOpenRef.current) {\n closeChat();\n } else {\n openChat();\n }\n }, [closeChat, openChat]);\n\n useEffect(() => {\n return () => {\n if (focusTimeoutRef.current) clearTimeout(focusTimeoutRef.current);\n if (restoreFocusTimeoutRef.current) {\n clearTimeout(restoreFocusTimeoutRef.current);\n }\n };\n }, []);\n\n // Global Cmd/Ctrl+I toggles the assistant, but only when chat is enabled.\n useEffect(() => {\n if (!isChatActive) return;\n function handleKeyDown(e: KeyboardEvent) {\n if ((e.metaKey || e.ctrlKey) && e.key.toLowerCase() === \"i\") {\n e.preventDefault();\n toggleChat();\n }\n }\n document.addEventListener(\"keydown\", handleKeyDown);\n return () => document.removeEventListener(\"keydown\", handleKeyDown);\n }, [isChatActive, toggleChat]);\n\n async function runQuestion(\n currentQuestion: string,\n returnFocusTo?: HTMLElement | null,\n ) {\n setQuestion(\"\");\n showChat(returnFocusTo);\n setLoading(true);\n setError(null);\n\n const base =\n answer.length > 0 ? answer : [{ text: INITIAL_GREETING, answer: true }];\n const mergedQuestions = [...base, { text: currentQuestion, answer: false }];\n\n setAnswer(mergedQuestions);\n\n const controller = new AbortController();\n abortRef.current = controller;\n\n try {\n const history = answer\n .filter((a) => a.text.trim() !== \"\")\n .map((a) => ({\n role: a.answer ? (\"assistant\" as const) : (\"user\" as const),\n content: a.text,\n }));\n\n const res = await fetch(\"/api/rag\", {\n method: \"POST\",\n headers: { \"Content-Type\": \"application/json\" },\n body: JSON.stringify({ question: currentQuestion, history }),\n signal: controller.signal,\n });\n\n if (!res.ok) {\n // The body may be a proxy/gateway HTML error page (e.g. Cloudflare\n // 524), not our JSON - never blindly JSON.parse it.\n const contentType = res.headers.get(\"content-type\") || \"\";\n let message = \"Request failed\";\n if (contentType.includes(\"application/json\")) {\n try {\n const errorData = await res.json();\n message = errorData.error || message;\n } catch {\n // Non-JSON despite the header - fall through to the default.\n }\n } else if ([502, 503, 504, 524].includes(res.status)) {\n message = \"The assistant took too long to respond. Please try again.\";\n }\n throw new Error(message);\n }\n\n const reader = res.body?.getReader();\n const decoder = new TextDecoder();\n const contentParts: string[] = [];\n let sources: Source[] = [];\n if (!reader) {\n throw new Error(\"Failed to get response reader\");\n }\n\n // Don't insert the answer bubble yet - an empty bubble renders a blank\n // gap above the \"Answering...\" loader. The bubble is created on the first\n // streamed token (or the done event) instead, so the loader stays put\n // until real text appears.\n const streamingAnswerIndex = mergedQuestions.length;\n\n let buffer = \"\";\n while (true) {\n const { done, value } = await reader.read();\n if (done) break;\n\n buffer += decoder.decode(value, { stream: true });\n const parts = buffer.split(\"\\n\");\n buffer = parts.pop() ?? \"\";\n\n for (const line of parts) {\n if (!line.startsWith(\"data: \")) continue;\n\n // Guard only the parse: a malformed frame is skipped, while the\n // server's error event below must throw past this loop to the\n // outer catch so it renders in the chat's error callout instead\n // of dying in a parse-error log.\n let data;\n try {\n data = JSON.parse(line.slice(6));\n } catch {\n console.error(\"Failed to parse SSE data:\", line);\n continue;\n }\n\n if (data.type === \"metadata\") {\n const allSources: Source[] = data.data?.sources ?? [];\n const seen = new Set<string>();\n sources = allSources.filter((s: Source) => {\n if (s.score < 0.4 || seen.has(s.uri)) return false;\n seen.add(s.uri);\n return true;\n });\n } else if (data.type === \"content\") {\n contentParts.push(data.data);\n const streamedContent = contentParts.join(\"\");\n\n setAnswer((prev) => {\n const newAnswers = [...prev];\n newAnswers[streamingAnswerIndex] = {\n text: streamedContent,\n answer: true,\n sources,\n };\n return newAnswers;\n });\n } else if (data.type === \"error\") {\n throw new Error(data.data);\n } else if (data.type === \"done\") {\n const streamedContent = contentParts.join(\"\");\n let mdxSource: MDXRemoteSerializeResult | null = null;\n try {\n mdxSource = await serialize(streamedContent, {\n parseFrontmatter: false,\n mdxOptions: {\n remarkPlugins: [remarkGfm],\n rehypePlugins: [rehypeHighlight],\n format: \"md\",\n development: false,\n },\n });\n } catch (mdxError: unknown) {\n console.error(\"MDX serialization error:\", mdxError);\n }\n\n setAnswer((prev) => {\n const newAnswers = [...prev];\n newAnswers[streamingAnswerIndex] = {\n text: streamedContent,\n answer: true,\n mdx: mdxSource || undefined,\n sources,\n };\n return newAnswers;\n });\n }\n }\n }\n } catch (err: unknown) {\n if (err instanceof DOMException && err.name === \"AbortError\") return;\n setError(err instanceof Error ? err.message : \"Unknown error\");\n } finally {\n abortRef.current = null;\n setLoading(false);\n }\n }\n\n async function ask(e: React.FormEvent) {\n e.preventDefault();\n if (loading || question.trim() === \"\") return;\n await runQuestion(question);\n }\n\n // Bridge from the search modal: hand the typed query to the assistant. If a\n // response is already streaming (loading), we can't submit yet - open the\n // panel and pre-fill the input so the user can send it the moment the\n // current answer finishes. Otherwise submit it right away.\n function askAssistant(\n rawQuestion: string,\n returnFocusTo?: HTMLElement | null,\n ) {\n const trimmed = rawQuestion.trim();\n if (trimmed === \"\") return;\n if (loading) {\n showChat(returnFocusTo);\n setQuestion(trimmed);\n } else {\n void runQuestion(trimmed, returnFocusTo);\n }\n }\n\n function resetChat() {\n abortRef.current?.abort();\n setLoading(false);\n setError(null);\n setAnswer([{ text: INITIAL_GREETING, answer: true }]);\n }\n\n return (\n <ChatContext.Provider\n value={{\n isOpen,\n setIsOpen,\n toggleChat,\n isChatActive,\n question,\n setQuestion,\n loading,\n error,\n answer,\n setAnswer,\n ask,\n askAssistant,\n closeChat,\n registerSearchClose,\n resetChat,\n chatInputRef,\n }}\n >\n {children}\n </ChatContext.Provider>\n );\n};\n\nexport { Chat, ChtProvider, ChatContext, ChatButtonCTA };\n";
1
+ export declare const chatTemplate = "\"use client\";\nimport React, {\n createContext,\n useCallback,\n useContext,\n useEffect,\n useLayoutEffect,\n useRef,\n useState,\n useSyncExternalStore,\n} from \"react\";\nimport styled, { css, keyframes } from \"styled-components\";\nimport { Button, IconButton } from \"cherry-styled-components\";\nimport { ArrowUp, LoaderPinwheel, RotateCcw, Sparkles, X } from \"lucide-react\";\nimport remarkGfm from \"remark-gfm\";\nimport rehypeHighlight from \"rehype-highlight\";\nimport { MDXRemote, MDXRemoteSerializeResult } from \"next-mdx-remote\";\nimport { serialize } from \"next-mdx-remote/serialize\";\nimport Link from \"next/link\";\nimport { mq, theme, Theme } from \"@/app/theme\";\nimport { Callout } from \"@/components/layout/Callout\";\nimport { useLockBodyScroll } from \"@/components/LockBodyScroll\";\nimport { useMDXComponents as getMDXComponents } from \"@/components/MDXComponents\";\nimport {\n styledAnchor,\n styledTable,\n stylesLists,\n StyledSmallButton,\n interactiveStyles,\n thinScrollbar,\n} from \"@/components/layout/SharedStyled\";\n\nconst mdxComponents = getMDXComponents({});\n\nconst MOBILE_CHAT_QUERY = `(max-width: ${theme.breakpoints.lg - 1}px)`;\n\nfunction subscribeToMobileChat(callback: () => void) {\n const mediaQuery = window.matchMedia(MOBILE_CHAT_QUERY);\n mediaQuery.addEventListener(\"change\", callback);\n return () => mediaQuery.removeEventListener(\"change\", callback);\n}\n\nfunction getMobileChatSnapshot() {\n return window.matchMedia(MOBILE_CHAT_QUERY).matches;\n}\n\nfunction useIsMobileChat() {\n return useSyncExternalStore(\n subscribeToMobileChat,\n getMobileChatSnapshot,\n () => false,\n );\n}\n\nconst styledText = css<{ theme: Theme }>`\n font-size: ${({ theme }) => theme.fontSizes.text.xs};\n line-height: ${({ theme }) => theme.lineHeights.text.xs};\n\n ${mq(\"lg\")} {\n font-size: ${({ theme }) => theme.fontSizes.small.lg};\n line-height: ${({ theme }) => theme.lineHeights.small.lg};\n }\n`;\n\nconst StyledChatSurface = styled.div<{ $isVisible: boolean }>`\n position: fixed;\n inset: 0;\n z-index: 1000;\n pointer-events: none;\n\n & > * {\n pointer-events: auto;\n }\n\n ${({ $isVisible }) =>\n !$isVisible &&\n css`\n visibility: hidden;\n\n & > * {\n pointer-events: none;\n }\n `}\n`;\n\nconst StyledChat = styled.div<{ theme: Theme; $isVisible: boolean }>`\n margin: 0;\n position: fixed;\n top: 0;\n right: 0;\n width: 100%;\n height: calc(100dvh - 90px);\n overflow-y: scroll;\n overflow-x: hidden;\n z-index: 1000;\n padding: 0 20px;\n /* See StyledChatForm: visibility snaps open and is delayed on close, so the\n panel is focusable as soon as it opens. */\n transition:\n transform 0.3s ease,\n opacity 0.3s ease,\n visibility 0s linear 0s;\n transform: translateX(0);\n background: ${({ theme }) => theme.colors.light};\n -webkit-overflow-scrolling: touch;\n opacity: 1;\n visibility: visible;\n\n &::-webkit-scrollbar {\n display: none;\n }\n\n ${({ $isVisible }) =>\n !$isVisible &&\n css`\n transform: translateX(100%);\n opacity: 0;\n visibility: hidden;\n transition-delay: 0s, 0s, 0.3s;\n `}\n\n @media (prefers-reduced-motion: reduce) {\n transition: none;\n }\n\n ${mq(\"lg\")} {\n width: 420px;\n border-left: solid 1px ${({ theme }) => theme.colors.grayLight};\n }\n`;\n\nconst loadingAnimation = keyframes`\n 0% {\n transform: rotate(0deg);\n }\n 100% {\n transform: rotate(360deg);\n }\n`;\n\nconst rotateGradient = keyframes`\n 0% {\n --gradient-angle: 0deg;\n }\n 100% {\n --gradient-angle: 360deg;\n }\n`;\n\nconst pulseGlow = keyframes`\n 0%, 100% {\n opacity: 0.5;\n filter: blur(16px);\n }\n 50% {\n opacity: 1;\n filter: blur(22px);\n }\n`;\n\nconst sparkleFloat = keyframes`\n 0%, 100% {\n opacity: 0;\n transform: translateY(0) scale(0);\n }\n 50% {\n opacity: 0.9;\n transform: translateY(-20px) scale(1);\n }\n`;\n\nconst shimmer = keyframes`\n 0% {\n background-position: 0% center;\n }\n 50% {\n background-position: 100% center;\n }\n 100% {\n background-position: 0% center;\n }\n`;\n\nconst StyledRainbowInputWrapper = styled.div<{\n theme: Theme;\n $isActive: boolean;\n}>`\n @property --gradient-angle {\n syntax: \"<angle>\";\n initial-value: 0deg;\n inherits: false;\n }\n\n position: relative;\n flex: 1;\n\n &::before {\n content: \"\";\n position: absolute;\n inset: -2px;\n border-radius: 14px;\n background: conic-gradient(\n from var(--gradient-angle),\n #cc5555,\n #d9a745,\n #3ab0cc,\n #cc7fc2,\n #4380cc,\n #4c1fa3,\n #cc5555\n );\n opacity: 0;\n transition: opacity 0.4s cubic-bezier(0.4, 0, 0.2, 1);\n animation: ${rotateGradient} 3s linear infinite;\n z-index: 0;\n }\n\n &::after {\n content: \"\";\n position: absolute;\n inset: -10px;\n border-radius: 20px;\n background: conic-gradient(\n from var(--gradient-angle),\n #ff6b6b66,\n #feca5766,\n #48dbfb66,\n #ff9ff366,\n #54a0ff66,\n #5f27cd66,\n #ff6b6b66\n );\n opacity: 0;\n transition: opacity 0.4s cubic-bezier(0.4, 0, 0.2, 1);\n animation:\n ${rotateGradient} 3s linear infinite,\n ${pulseGlow} 2s ease-in-out infinite;\n z-index: -1;\n pointer-events: none;\n }\n\n &:hover::before,\n &:focus-within::before {\n opacity: 1;\n }\n\n &:hover::after,\n &:focus-within::after {\n opacity: 1;\n }\n\n ${({ $isActive }) =>\n $isActive &&\n css`\n &::before {\n opacity: 1;\n }\n &::after {\n opacity: 1;\n }\n `}\n`;\n\nconst StyledSparkleContainer = styled.div<{ $isActive: boolean }>`\n position: absolute;\n inset: -30px;\n pointer-events: none;\n overflow: hidden;\n border-radius: 30px;\n z-index: -2;\n opacity: 0;\n transition: opacity 0.4s ease;\n\n ${({ $isActive }) =>\n $isActive &&\n css`\n opacity: 1;\n `}\n`;\n\nconst StyledSparkle = styled.div<{\n $color: string;\n $left: number;\n $top: number;\n $delay: number;\n}>`\n position: absolute;\n width: 4px;\n height: 4px;\n border-radius: 50%;\n background: ${({ $color }) => $color};\n box-shadow: 0 0 6px ${({ $color }) => $color};\n left: ${({ $left }) => $left}%;\n top: ${({ $top }) => $top}%;\n animation: ${sparkleFloat} 2s ease-in-out infinite;\n animation-delay: ${({ $delay }) => $delay}s;\n`;\n\nconst StyledRainbowInput = styled.input<{ theme: Theme }>`\n position: relative;\n z-index: 1;\n width: 100%;\n background: ${({ theme }) => theme.colors.light};\n border: 1px solid ${({ theme }) => theme.colors.grayLight};\n border-radius: 12px;\n padding: 12px 18px;\n font-size: ${({ theme }) => theme.fontSizes.text.lg};\n font-family: inherit;\n color: ${({ theme }) => theme.colors.dark};\n outline: none;\n transition:\n border-color 0.3s ease,\n box-shadow 0.3s ease;\n\n ${mq(\"lg\")} {\n font-size: ${({ theme }) => theme.fontSizes.small.lg};\n }\n\n &::placeholder {\n color: ${({ theme }) =>\n `color-mix(in srgb, ${theme.colors.dark} 40%, transparent)`};\n transition: color 0.3s ease;\n }\n\n &:focus::placeholder {\n color: ${({ theme }) =>\n `color-mix(in srgb, ${theme.colors.dark} 60%, transparent)`};\n }\n\n &:focus {\n border-color: transparent;\n }\n`;\n\nconst StyledRainbowButton = styled(Button)<{\n theme: Theme;\n $hasContent: boolean;\n}>`\n padding-top: 10px;\n padding-bottom: 10px;\n position: relative;\n overflow: hidden;\n transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1) !important;\n color: ${({ theme }) => theme.colors.surface};\n\n &::before {\n content: \"\";\n position: absolute;\n inset: 0;\n background: linear-gradient(\n 135deg,\n #ff6b6b,\n #feca57,\n #48dbfb,\n #ff9ff3,\n #54a0ff\n );\n background-size: 300% 300%;\n opacity: 0;\n transition: opacity 0.3s ease;\n z-index: 0;\n animation: ${shimmer} 3s linear infinite;\n width: 200%;\n }\n\n ${({ $hasContent }) =>\n $hasContent &&\n css`\n &::before {\n opacity: 1;\n }\n `}\n\n &:hover::before {\n opacity: 1;\n }\n\n &:hover {\n transform: scale(1.05);\n }\n\n &:active {\n transform: scale(0.95);\n }\n\n & svg {\n position: relative;\n z-index: 1;\n transition: transform 0.3s ease;\n }\n\n &:disabled,\n &:disabled:hover {\n background: ${({ theme }) => theme.colors.primaryDark};\n transform: none;\n box-shadow: none;\n\n &::before {\n opacity: 0;\n }\n }\n`;\n\nconst StyledChatForm = styled.form<{ theme: Theme; $isVisible: boolean }>`\n display: flex;\n gap: 10px;\n justify-content: center;\n align-items: center;\n background: ${({ theme }) => theme.colors.light};\n padding: 20px;\n position: fixed;\n bottom: 0;\n right: 0;\n z-index: 1000;\n width: 100%;\n border-top: solid 1px ${({ theme }) => theme.colors.grayLight};\n /* visibility is animatable, so transitioning \"all\" keeps this hidden for the\n whole slide-in - long enough for the focus() that follows opening to be a\n silent no-op. Snap it on open (transition-delay below) and delay it on\n close so the slide-out stays visible while it animates. */\n transition:\n transform 0.3s ease,\n opacity 0.3s ease,\n visibility 0s linear 0.3s;\n transform: translateX(100%);\n opacity: 0;\n visibility: hidden;\n\n ${mq(\"lg\")} {\n width: 420px;\n border-left: solid 1px ${({ theme }) => theme.colors.grayLight};\n }\n\n ${({ $isVisible }) =>\n $isVisible &&\n css`\n opacity: 1;\n transform: translateX(0);\n visibility: visible;\n transition-delay: 0s;\n `}\n\n @media (prefers-reduced-motion: reduce) {\n transition: none;\n }\n\n & .loading {\n animation: ${loadingAnimation} 1s linear infinite;\n }\n`;\n\nconst StyledGlowSmallButton = styled(StyledSmallButton)<{\n theme: Theme;\n $hasContent: boolean;\n}>`\n @property --gradient-angle {\n syntax: \"<angle>\";\n initial-value: 0deg;\n inherits: false;\n }\n\n position: relative;\n isolation: isolate;\n margin-right: 0;\n background: ${({ theme }) => theme.colors.light};\n padding: 0;\n\n &::before {\n content: \"\";\n inset: -2px;\n border-radius: 8px;\n background: conic-gradient(\n from var(--gradient-angle),\n #cc5555,\n #d9a745,\n #3ab0cc,\n #cc7fc2,\n #4380cc,\n #4c1fa3,\n #cc5555\n );\n opacity: 0;\n transition: opacity 0.4s cubic-bezier(0.4, 0, 0.2, 1);\n animation: ${rotateGradient} 3s linear infinite;\n z-index: -1;\n position: absolute;\n top: -2px;\n left: -2px;\n width: calc(100% + 4px);\n height: calc(100% + 4px);\n }\n\n &::after {\n content: \"\";\n position: absolute;\n inset: -8px;\n border-radius: 14px;\n background: conic-gradient(\n from var(--gradient-angle),\n #ff6b6b66,\n #feca5766,\n #48dbfb66,\n #ff9ff366,\n #54a0ff66,\n #5f27cd66,\n #ff6b6b66\n );\n opacity: 0;\n transition: opacity 0.4s cubic-bezier(0.4, 0, 0.2, 1);\n animation:\n ${rotateGradient} 3s linear infinite,\n ${pulseGlow} 2s ease-in-out infinite;\n z-index: -2;\n pointer-events: none;\n }\n\n &:hover::before,\n &:hover::after {\n opacity: 1;\n }\n\n & span {\n padding: 6px 8px;\n display: flex;\n background: ${({ theme }) => theme.colors.light};\n border-radius: ${({ theme }) => theme.spacing.radius.xs};\n gap: 6px;\n }\n\n ${({ $hasContent }) =>\n $hasContent &&\n css`\n &::before {\n opacity: 1;\n }\n &::after {\n opacity: 1;\n }\n `}\n`;\n\nconst StyledError = styled.div`\n margin: 20px 0;\n width: 100%;\n`;\n\nconst loadingDotAnimation = keyframes`\n 0% {\n opacity: 0;\n }\n 50% {\n opacity: 1;\n }\n 100% {\n opacity: 0;\n }\n`;\n\nconst StyledLoading = styled.div<{ theme: Theme }>`\n overflow-x: auto;\n ${thinScrollbar};\n margin: 20px 0;\n width: 100%;\n font-weight: 600;\n ${styledText};\n color: ${({ theme }) => theme.colors.dark};\n\n & span {\n &:nth-child(1) {\n animation: ${loadingDotAnimation} 1s ease infinite;\n }\n &:nth-child(2) {\n animation: ${loadingDotAnimation} 1s ease infinite;\n animation-delay: 0.2s;\n }\n &:nth-child(3) {\n animation: ${loadingDotAnimation} 1s ease infinite;\n animation-delay: 0.4s;\n }\n }\n`;\n\nconst StyledAnswer = styled.div<{ theme: Theme; $isAnswer: boolean }>`\n overflow-x: auto;\n ${thinScrollbar};\n background: ${({ theme }) => theme.colors.primary};\n color: ${({ theme }) => theme.colors.surface};\n padding: 9px 14px;\n border-radius: 16px 16px 4px 16px;\n margin: 20px 0 20px auto;\n width: fit-content;\n max-width: min(560px, 88%);\n font-weight: 500;\n white-space: pre-wrap;\n overflow-wrap: anywhere;\n ${styledText};\n\n & p {\n ${styledText};\n }\n\n ${({ $isAnswer }) =>\n $isAnswer &&\n css`\n background: transparent;\n color: ${({ theme }) => theme.colors.dark};\n padding: 0;\n width: 100%;\n max-width: 100%;\n margin: 20px 0;\n border-radius: 0;\n font-weight: inherit;\n white-space: normal;\n `}\n\n & code:not([class]) {\n background: ${({ theme }) =>\n `color-mix(in srgb, ${theme.colors.primaryLight} 20%, transparent)`};\n color: ${({ theme }) => theme.colors.dark};\n padding: 2px 4px;\n border-radius: ${({ theme }) => theme.spacing.radius.xs};\n white-space: pre;\n }\n\n ${styledAnchor};\n ${stylesLists};\n ${styledTable};\n\n & pre,\n & .hljs {\n margin: 10px 0;\n }\n\n & .code-wrapper pre {\n margin: 0;\n ${styledText};\n }\n\n & > *:first-child {\n margin-top: 0;\n }\n\n & > *:last-child {\n margin-bottom: 0;\n\n & > *:last-child {\n margin-bottom: 0;\n }\n }\n\n & ul,\n & ol {\n & li {\n ${styledText};\n }\n }\n\n & img,\n & video,\n & iframe {\n max-width: 100%;\n border-radius: ${({ theme }) => theme.spacing.radius.lg};\n margin: 10px 0;\n display: block;\n }\n\n & h1,\n & h2,\n & h3,\n & h4,\n & h5,\n & h6 {\n margin: 10px 0;\n padding: 0;\n }\n`;\n\nconst StyledSources = styled.div`\n display: flex;\n gap: 16px;\n flex-wrap: wrap;\n margin: -5px 0 20px;\n`;\n\nconst StyledSourceLink = styled(Link)<{ theme: Theme }>`\n position: relative;\n text-decoration: none;\n font-size: ${({ theme }) => theme.fontSizes.small.lg};\n line-height: 1;\n color: ${({ theme }) => theme.colors.primary};\n display: flex;\n gap: 6px;\n transition: all 0.3s ease;\n font-weight: 600;\n white-space: nowrap;\n min-width: fit-content;\n background: ${({ theme }) =>\n `color-mix(in srgb, ${theme.colors.primaryLight} 10%, transparent)`};\n padding: 6px 8px;\n border-radius: ${({ theme }) => theme.spacing.radius.xs};\n ${interactiveStyles};\n\n & * {\n margin: auto 0;\n }\n\n &:hover {\n color: ${({ theme }) => theme.colors.accent};\n }\n`;\n\nconst StyledChatTitle = styled.div<{ theme: Theme }>`\n display: flex;\n flex-wrap: nowrap;\n justify-content: space-between;\n position: sticky;\n margin: 0 -20px;\n padding: 16px 20px;\n height: 62px;\n top: 0;\n background: ${({ theme }) => theme.colors.light};\n border-bottom: solid 1px ${({ theme }) => theme.colors.grayLight};\n z-index: 1000;\n`;\n\nconst StyledChatTitleIconWrapper = styled.span<{ theme: Theme }>`\n display: flex;\n align-items: center;\n gap: 12px;\n color: ${({ theme }) => theme.colors.dark};\n`;\n\ntype Source = {\n id: string;\n path: string;\n uri: string;\n score: number;\n};\n\ntype Answer = {\n text: string;\n answer?: boolean;\n mdx?: MDXRemoteSerializeResult;\n sources?: Source[];\n};\n\nconst SPARKLE_COLORS = [\n \"#ff6b6b\",\n \"#feca57\",\n \"#48dbfb\",\n \"#ff9ff3\",\n \"#54a0ff\",\n \"#5f27cd\",\n];\n\n// Deterministic sparkle positions to avoid hydration mismatch\nconst SPARKLE_POSITIONS = [\n { left: 8, top: 35 },\n { left: 17, top: 55 },\n { left: 26, top: 28 },\n { left: 35, top: 68 },\n { left: 44, top: 42 },\n { left: 53, top: 75 },\n { left: 62, top: 32 },\n { left: 71, top: 58 },\n { left: 80, top: 45 },\n { left: 89, top: 65 },\n];\n\ninterface RainbowInputProps {\n id?: string;\n value: string;\n onChange: (e: React.ChangeEvent<HTMLInputElement>) => void;\n placeholder?: string;\n autoComplete?: string;\n \"aria-label\"?: string;\n inputRef?: React.Ref<HTMLInputElement>;\n}\n\nfunction RainbowInput({\n id,\n value,\n onChange,\n placeholder,\n autoComplete,\n \"aria-label\": ariaLabel,\n inputRef,\n}: RainbowInputProps) {\n const [isFocused, setIsFocused] = useState(false);\n const [isHovered, setIsHovered] = useState(false);\n const isActive = isFocused || isHovered;\n\n const sparkles = SPARKLE_POSITIONS.map((pos, i) => ({\n color: SPARKLE_COLORS[i % SPARKLE_COLORS.length],\n left: pos.left,\n top: pos.top,\n delay: i * 0.12,\n }));\n\n return (\n <StyledRainbowInputWrapper\n $isActive={isActive}\n onMouseEnter={() => setIsHovered(true)}\n onMouseLeave={() => setIsHovered(false)}\n >\n <StyledSparkleContainer $isActive={isActive}>\n {sparkles.map((sparkle, i) => (\n <StyledSparkle\n key={i}\n $color={sparkle.color}\n $left={sparkle.left}\n $top={sparkle.top}\n $delay={sparkle.delay}\n />\n ))}\n </StyledSparkleContainer>\n <StyledRainbowInput\n ref={inputRef}\n id={id}\n value={value}\n onChange={onChange}\n placeholder={placeholder}\n autoComplete={autoComplete}\n aria-label={ariaLabel}\n onFocus={() => setIsFocused(true)}\n onBlur={() => setIsFocused(false)}\n />\n </StyledRainbowInputWrapper>\n );\n}\n\nfunction ChatButtonCTA() {\n const { toggleChat, isOpen } = useContext(ChatContext);\n\n return (\n <StyledGlowSmallButton\n onClick={toggleChat}\n aria-label=\"Ask AI Assistant\"\n $hasContent={isOpen}\n type=\"button\"\n >\n <span>\n <Sparkles size={16} />\n Ask AI\n </span>\n </StyledGlowSmallButton>\n );\n}\n\nfunction Chat() {\n const {\n isOpen,\n question,\n setQuestion,\n loading,\n error,\n answer,\n ask,\n closeChat,\n resetChat,\n chatInputRef,\n } = useContext(ChatContext);\n const chatSurfaceRef = useRef<HTMLDivElement | null>(null);\n const chatScrollRef = useRef<HTMLDivElement | null>(null);\n const scrollFrameRef = useRef<number | null>(null);\n const shouldAutoScrollRef = useRef(true);\n const loadingRef = useRef(loading);\n const isMobileChat = useIsMobileChat();\n const isMobileModal = isOpen && isMobileChat;\n\n useLockBodyScroll(isOpen);\n\n useEffect(() => {\n loadingRef.current = loading;\n }, [loading]);\n\n useLayoutEffect(() => {\n if (isOpen) {\n shouldAutoScrollRef.current = true;\n return;\n }\n\n if (scrollFrameRef.current !== null) {\n cancelAnimationFrame(scrollFrameRef.current);\n scrollFrameRef.current = null;\n }\n }, [isOpen]);\n\n useEffect(() => {\n if (!isOpen || !shouldAutoScrollRef.current) return;\n if (scrollFrameRef.current !== null) return;\n\n scrollFrameRef.current = requestAnimationFrame(() => {\n scrollFrameRef.current = null;\n const scrollContainer = chatScrollRef.current;\n if (!scrollContainer || !shouldAutoScrollRef.current) return;\n const reduceMotion = window.matchMedia(\n \"(prefers-reduced-motion: reduce)\",\n ).matches;\n scrollContainer.scrollTo({\n top: scrollContainer.scrollHeight,\n behavior: reduceMotion || loadingRef.current ? \"auto\" : \"smooth\",\n });\n });\n }, [answer, isOpen, loading]);\n\n useEffect(() => {\n return () => {\n if (scrollFrameRef.current !== null) {\n cancelAnimationFrame(scrollFrameRef.current);\n }\n };\n }, []);\n\n useEffect(() => {\n if (!isMobileModal || !chatSurfaceRef.current) return;\n\n const surface = chatSurfaceRef.current;\n const inertSiblings: Array<{\n element: HTMLElement;\n wasInert: boolean;\n }> = [];\n let current: HTMLElement = surface;\n\n while (current.parentElement) {\n const parent = current.parentElement;\n for (const sibling of Array.from(parent.children)) {\n if (sibling === current || !(sibling instanceof HTMLElement)) continue;\n inertSiblings.push({ element: sibling, wasInert: sibling.inert });\n sibling.inert = true;\n }\n if (parent === document.body) break;\n current = parent;\n }\n\n const containFocus = (event: FocusEvent) => {\n if (event.target instanceof Node && !surface.contains(event.target)) {\n chatInputRef.current?.focus();\n }\n };\n\n document.addEventListener(\"focusin\", containFocus);\n chatInputRef.current?.focus();\n\n return () => {\n document.removeEventListener(\"focusin\", containFocus);\n for (const { element, wasInert } of inertSiblings) {\n element.inert = wasInert;\n }\n };\n }, [chatInputRef, isMobileModal]);\n\n const handleChatScroll = () => {\n const scrollContainer = chatScrollRef.current;\n if (!scrollContainer) return;\n const distanceFromBottom =\n scrollContainer.scrollHeight -\n scrollContainer.scrollTop -\n scrollContainer.clientHeight;\n shouldAutoScrollRef.current =\n distanceFromBottom <= scrollContainer.clientHeight * 0.15;\n };\n\n const handleSurfaceKeyDown = (event: React.KeyboardEvent<HTMLDivElement>) => {\n if (event.key === \"Escape\" && isMobileModal) {\n event.preventDefault();\n event.stopPropagation();\n closeChat();\n return;\n }\n\n if (event.key !== \"Tab\" || !isMobileModal) return;\n const focusable = Array.from(\n chatSurfaceRef.current?.querySelectorAll<HTMLElement>(\n 'a[href], button:not([disabled]), input:not([disabled]), [tabindex]:not([tabindex=\"-1\"])',\n ) ?? [],\n ).filter(\n (element) =>\n element.offsetParent !== null &&\n element.getAttribute(\"aria-hidden\") !== \"true\",\n );\n if (focusable.length === 0) {\n event.preventDefault();\n return;\n }\n const first = focusable[0];\n const last = focusable[focusable.length - 1];\n if (event.shiftKey && document.activeElement === first) {\n event.preventDefault();\n last.focus();\n } else if (!event.shiftKey && document.activeElement === last) {\n event.preventDefault();\n first.focus();\n }\n };\n\n return (\n <StyledChatSurface\n ref={chatSurfaceRef}\n $isVisible={isOpen}\n inert={!isOpen}\n aria-hidden={!isOpen}\n role={isMobileModal ? \"dialog\" : \"complementary\"}\n aria-modal={isMobileModal ? \"true\" : undefined}\n aria-label=\"AI Assistant\"\n data-chat-surface\n data-markdown-ignore\n onKeyDownCapture={handleSurfaceKeyDown}\n >\n <StyledChat\n ref={chatScrollRef}\n $isVisible={isOpen}\n onScroll={handleChatScroll}\n >\n <StyledChatTitle>\n <StyledChatTitleIconWrapper>\n <Sparkles />\n <h3>AI Assistant</h3>\n </StyledChatTitleIconWrapper>\n <StyledChatTitleIconWrapper>\n <IconButton\n onClick={resetChat}\n aria-label=\"Reset chat history\"\n title=\"Reset chat history\"\n >\n <RotateCcw />\n </IconButton>\n <IconButton\n onClick={() => closeChat()}\n aria-label=\"Close chat\"\n title=\"Close chat\"\n >\n <X />\n </IconButton>\n </StyledChatTitleIconWrapper>\n </StyledChatTitle>\n {answer &&\n answer.map((a, i) => (\n <React.Fragment key={i}>\n <StyledAnswer $isAnswer={a.answer ?? false}>\n {a.answer && a.mdx ? (\n <MDXRemote {...a.mdx} components={mdxComponents} />\n ) : (\n a.text\n )}\n </StyledAnswer>\n {a.answer && a.sources && a.sources.length > 0 && (\n <StyledSources>\n {a.sources.map((src) => {\n const slug = src.uri\n .replace(\"docs://\", \"\")\n .replace(/^\\/+/, \"\");\n const href = slug ? `/${slug}/` : \"/\";\n const label = slug\n ? slug\n .split(\"/\")\n .pop()!\n .replace(/-/g, \" \")\n .replace(/\\b\\w/g, (c: string) => c.toUpperCase())\n : \"Home\";\n return (\n <StyledSourceLink\n key={src.id}\n href={href}\n onClick={() => {\n if (window.innerWidth <= 992) {\n closeChat();\n }\n }}\n >\n {label}\n </StyledSourceLink>\n );\n })}\n </StyledSources>\n )}\n </React.Fragment>\n ))}\n {loading && !answer[answer.length - 1]?.answer && (\n <StyledLoading>\n Answering<span>.</span>\n <span>.</span>\n <span>.</span>\n </StyledLoading>\n )}\n {error && (\n <StyledError>\n <Callout type=\"danger\">\n <p>\n <strong>Error:</strong> {error}\n </p>\n </Callout>\n </StyledError>\n )}\n </StyledChat>\n\n <StyledChatForm onSubmit={ask} $isVisible={isOpen} data-markdown-ignore>\n <RainbowInput\n id=\"chat-bottom-input\"\n inputRef={chatInputRef}\n value={question}\n onChange={(e) => setQuestion(e.target.value)}\n placeholder=\"Ask AI Assistant...\"\n autoComplete=\"off\"\n aria-label=\"Ask a follow-up question\"\n />\n <StyledRainbowButton\n type=\"submit\"\n disabled={loading || question.trim() === \"\"}\n $hasContent={question.trim().length > 0}\n aria-label={loading ? \"Loading response\" : \"Submit question\"}\n >\n {loading ? <LoaderPinwheel className=\"loading\" /> : <ArrowUp />}\n </StyledRainbowButton>\n </StyledChatForm>\n </StyledChatSurface>\n );\n}\n\nconst ChatContext = createContext<{\n isOpen: boolean;\n setIsOpen: (isOpen: boolean) => void;\n toggleChat: () => void;\n isChatActive: boolean;\n question: string;\n setQuestion: (q: string) => void;\n loading: boolean;\n error: string | null;\n answer: Answer[];\n setAnswer: (answers: Answer[]) => void;\n ask: (e: React.FormEvent) => void;\n askAssistant: (question: string, returnFocusTo?: HTMLElement | null) => void;\n closeChat: (restoreFocus?: boolean) => HTMLElement | null;\n registerSearchClose: (\n closeSearch: (restoreFocus?: boolean) => HTMLElement | null,\n ) => () => void;\n resetChat: () => void;\n chatInputRef: React.RefObject<HTMLInputElement | null>;\n}>({\n isOpen: false,\n setIsOpen: () => {},\n toggleChat: () => {},\n isChatActive: false,\n question: \"\",\n setQuestion: () => {},\n loading: false,\n error: null,\n answer: [],\n setAnswer: () => {},\n ask: () => {},\n askAssistant: () => {},\n closeChat: () => null,\n registerSearchClose: () => () => {},\n resetChat: () => {},\n chatInputRef: { current: null },\n});\n\ninterface ChatContextProviderProps {\n children: React.ReactNode;\n isChatActive: boolean;\n}\n\nconst INITIAL_GREETING = \"Hey there, how can I assist you?\";\n\nconst ChtProvider = ({ children, isChatActive }: ChatContextProviderProps) => {\n const [isOpen, setIsOpen] = useState(false);\n const [question, setQuestion] = useState(\"\");\n const [loading, setLoading] = useState(false);\n const [error, setError] = useState<string | null>(null);\n const [answer, setAnswer] = useState<Answer[]>([]);\n const abortRef = useRef<AbortController | null>(null);\n const chatInputRef = useRef<HTMLInputElement | null>(null);\n const focusTimeoutRef = useRef<ReturnType<typeof setTimeout> | null>(null);\n const restoreFocusTimeoutRef = useRef<ReturnType<typeof setTimeout> | null>(\n null,\n );\n const pendingRestoreFocusRef = useRef<HTMLElement | null>(null);\n const openerRef = useRef<HTMLElement | null>(null);\n const closeSearchRef = useRef<\n ((restoreFocus?: boolean) => HTMLElement | null) | null\n >(null);\n const isOpenRef = useRef(isOpen);\n\n useEffect(() => {\n isOpenRef.current = isOpen;\n }, [isOpen]);\n\n const showChat = useCallback((returnFocusTo?: HTMLElement | null) => {\n const previousOverlayOpener = closeSearchRef.current?.(false) ?? null;\n const pendingChatOpener = pendingRestoreFocusRef.current;\n if (restoreFocusTimeoutRef.current) {\n clearTimeout(restoreFocusTimeoutRef.current);\n restoreFocusTimeoutRef.current = null;\n }\n pendingRestoreFocusRef.current = null;\n if (!isOpenRef.current) {\n const activeElement = document.activeElement;\n openerRef.current =\n returnFocusTo?.isConnected === true\n ? returnFocusTo\n : previousOverlayOpener?.isConnected === true\n ? previousOverlayOpener\n : pendingChatOpener?.isConnected === true\n ? pendingChatOpener\n : activeElement instanceof HTMLElement &&\n activeElement !== document.body\n ? activeElement\n : null;\n }\n isOpenRef.current = true;\n setIsOpen(true);\n if (focusTimeoutRef.current) clearTimeout(focusTimeoutRef.current);\n focusTimeoutRef.current = setTimeout(() => {\n focusTimeoutRef.current = null;\n chatInputRef.current?.focus();\n }, 0);\n }, []);\n\n // Open the assistant and seed its greeting on the first visit. The opener is\n // captured before the mobile dialog makes the rest of the page inert.\n const openChat = useCallback(() => {\n showChat();\n setAnswer((prev) =>\n prev.length === 0 ? [{ text: INITIAL_GREETING, answer: true }] : prev,\n );\n }, [showChat]);\n\n const closeChat = useCallback((restoreFocus = true) => {\n const pendingOpener = pendingRestoreFocusRef.current;\n if (!restoreFocus && restoreFocusTimeoutRef.current) {\n clearTimeout(restoreFocusTimeoutRef.current);\n restoreFocusTimeoutRef.current = null;\n pendingRestoreFocusRef.current = null;\n }\n if (!isOpenRef.current) return pendingOpener;\n if (focusTimeoutRef.current) {\n clearTimeout(focusTimeoutRef.current);\n focusTimeoutRef.current = null;\n }\n const activeElement = document.activeElement;\n if (\n activeElement instanceof HTMLElement &&\n activeElement.closest(\"[data-chat-surface]\")\n ) {\n activeElement.blur();\n }\n const opener = openerRef.current;\n openerRef.current = null;\n isOpenRef.current = false;\n setIsOpen(false);\n if (restoreFocusTimeoutRef.current) {\n clearTimeout(restoreFocusTimeoutRef.current);\n }\n if (restoreFocus) {\n pendingRestoreFocusRef.current = opener;\n restoreFocusTimeoutRef.current = setTimeout(() => {\n const focusTarget = pendingRestoreFocusRef.current;\n restoreFocusTimeoutRef.current = null;\n pendingRestoreFocusRef.current = null;\n if (focusTarget?.isConnected) focusTarget.focus();\n }, 0);\n } else {\n pendingRestoreFocusRef.current = null;\n }\n return opener;\n }, []);\n\n const registerSearchClose = useCallback(\n (closeSearch: (restoreFocus?: boolean) => HTMLElement | null) => {\n closeSearchRef.current = closeSearch;\n return () => {\n if (closeSearchRef.current === closeSearch) {\n closeSearchRef.current = null;\n }\n };\n },\n [],\n );\n\n const toggleChat = useCallback(() => {\n if (isOpenRef.current) {\n closeChat();\n } else {\n openChat();\n }\n }, [closeChat, openChat]);\n\n useEffect(() => {\n return () => {\n if (focusTimeoutRef.current) clearTimeout(focusTimeoutRef.current);\n if (restoreFocusTimeoutRef.current) {\n clearTimeout(restoreFocusTimeoutRef.current);\n }\n };\n }, []);\n\n // Global Cmd/Ctrl+I toggles the assistant, but only when chat is enabled.\n useEffect(() => {\n if (!isChatActive) return;\n function handleKeyDown(e: KeyboardEvent) {\n if ((e.metaKey || e.ctrlKey) && e.key.toLowerCase() === \"i\") {\n e.preventDefault();\n toggleChat();\n }\n }\n document.addEventListener(\"keydown\", handleKeyDown);\n return () => document.removeEventListener(\"keydown\", handleKeyDown);\n }, [isChatActive, toggleChat]);\n\n async function runQuestion(\n currentQuestion: string,\n returnFocusTo?: HTMLElement | null,\n ) {\n setQuestion(\"\");\n showChat(returnFocusTo);\n setLoading(true);\n setError(null);\n\n const base =\n answer.length > 0 ? answer : [{ text: INITIAL_GREETING, answer: true }];\n const mergedQuestions = [...base, { text: currentQuestion, answer: false }];\n\n setAnswer(mergedQuestions);\n\n const controller = new AbortController();\n abortRef.current = controller;\n\n try {\n const history = answer\n .filter((a) => a.text.trim() !== \"\")\n .slice(-20)\n .map((a) => ({\n role: a.answer ? (\"assistant\" as const) : (\"user\" as const),\n content: a.text.slice(0, 4000),\n }));\n\n const res = await fetch(\"/api/rag\", {\n method: \"POST\",\n headers: { \"Content-Type\": \"application/json\" },\n body: JSON.stringify({ question: currentQuestion, history }),\n signal: controller.signal,\n });\n\n if (!res.ok) {\n // The body may be a proxy/gateway HTML error page (e.g. Cloudflare\n // 524), not our JSON - never blindly JSON.parse it.\n const contentType = res.headers.get(\"content-type\") || \"\";\n let message = \"Request failed\";\n if (contentType.includes(\"application/json\")) {\n try {\n const errorData = await res.json();\n message = errorData.error || message;\n } catch {\n // Non-JSON despite the header - fall through to the default.\n }\n } else if ([502, 503, 504, 524].includes(res.status)) {\n message = \"The assistant took too long to respond. Please try again.\";\n }\n throw new Error(message);\n }\n\n const reader = res.body?.getReader();\n const decoder = new TextDecoder();\n const contentParts: string[] = [];\n let sources: Source[] = [];\n if (!reader) {\n throw new Error(\"Failed to get response reader\");\n }\n\n // Don't insert the answer bubble yet - an empty bubble renders a blank\n // gap above the \"Answering...\" loader. The bubble is created on the first\n // streamed token (or the done event) instead, so the loader stays put\n // until real text appears.\n const streamingAnswerIndex = mergedQuestions.length;\n\n let buffer = \"\";\n while (true) {\n const { done, value } = await reader.read();\n if (done) break;\n\n buffer += decoder.decode(value, { stream: true });\n const parts = buffer.split(\"\\n\");\n buffer = parts.pop() ?? \"\";\n\n for (const line of parts) {\n if (!line.startsWith(\"data: \")) continue;\n\n // Guard only the parse: a malformed frame is skipped, while the\n // server's error event below must throw past this loop to the\n // outer catch so it renders in the chat's error callout instead\n // of dying in a parse-error log.\n let data;\n try {\n data = JSON.parse(line.slice(6));\n } catch {\n console.error(\"Failed to parse SSE data:\", line);\n continue;\n }\n\n if (data.type === \"metadata\") {\n const allSources: Source[] = data.data?.sources ?? [];\n const seen = new Set<string>();\n sources = allSources.filter((s: Source) => {\n if (s.score < 0.4 || seen.has(s.uri)) return false;\n seen.add(s.uri);\n return true;\n });\n } else if (data.type === \"content\") {\n contentParts.push(data.data);\n const streamedContent = contentParts.join(\"\");\n\n setAnswer((prev) => {\n const newAnswers = [...prev];\n newAnswers[streamingAnswerIndex] = {\n text: streamedContent,\n answer: true,\n sources,\n };\n return newAnswers;\n });\n } else if (data.type === \"error\") {\n throw new Error(data.data);\n } else if (data.type === \"done\") {\n const streamedContent = contentParts.join(\"\");\n let mdxSource: MDXRemoteSerializeResult | null = null;\n try {\n mdxSource = await serialize(streamedContent, {\n parseFrontmatter: false,\n mdxOptions: {\n remarkPlugins: [remarkGfm],\n rehypePlugins: [rehypeHighlight],\n format: \"md\",\n development: false,\n },\n });\n } catch (mdxError: unknown) {\n console.error(\"MDX serialization error:\", mdxError);\n }\n\n setAnswer((prev) => {\n const newAnswers = [...prev];\n newAnswers[streamingAnswerIndex] = {\n text: streamedContent,\n answer: true,\n mdx: mdxSource || undefined,\n sources,\n };\n return newAnswers;\n });\n }\n }\n }\n } catch (err: unknown) {\n if (err instanceof DOMException && err.name === \"AbortError\") return;\n setError(err instanceof Error ? err.message : \"Unknown error\");\n } finally {\n abortRef.current = null;\n setLoading(false);\n }\n }\n\n async function ask(e: React.FormEvent) {\n e.preventDefault();\n if (loading || question.trim() === \"\") return;\n await runQuestion(question);\n }\n\n // Bridge from the search modal: hand the typed query to the assistant. If a\n // response is already streaming (loading), we can't submit yet - open the\n // panel and pre-fill the input so the user can send it the moment the\n // current answer finishes. Otherwise submit it right away.\n function askAssistant(\n rawQuestion: string,\n returnFocusTo?: HTMLElement | null,\n ) {\n const trimmed = rawQuestion.trim();\n if (trimmed === \"\") return;\n if (loading) {\n showChat(returnFocusTo);\n setQuestion(trimmed);\n } else {\n void runQuestion(trimmed, returnFocusTo);\n }\n }\n\n function resetChat() {\n abortRef.current?.abort();\n setLoading(false);\n setError(null);\n setAnswer([{ text: INITIAL_GREETING, answer: true }]);\n }\n\n return (\n <ChatContext.Provider\n value={{\n isOpen,\n setIsOpen,\n toggleChat,\n isChatActive,\n question,\n setQuestion,\n loading,\n error,\n answer,\n setAnswer,\n ask,\n askAssistant,\n closeChat,\n registerSearchClose,\n resetChat,\n chatInputRef,\n }}\n >\n {children}\n </ChatContext.Provider>\n );\n};\n\nexport { Chat, ChtProvider, ChatContext, ChatButtonCTA };\n";
@@ -1329,9 +1329,10 @@ const ChtProvider = ({ children, isChatActive }: ChatContextProviderProps) => {
1329
1329
  try {
1330
1330
  const history = answer
1331
1331
  .filter((a) => a.text.trim() !== "")
1332
+ .slice(-20)
1332
1333
  .map((a) => ({
1333
1334
  role: a.answer ? ("assistant" as const) : ("user" as const),
1334
- content: a.text,
1335
+ content: a.text.slice(0, 4000),
1335
1336
  }));
1336
1337
 
1337
1338
  const res = await fetch("/api/rag", {
@@ -1 +1 @@
1
- export declare const accordionTemplate = "\"use client\";\nimport { useId, useState } from \"react\";\nimport styled, { css } from \"styled-components\";\nimport { Button, resetButton, styledText } from \"cherry-styled-components\";\nimport { Theme } from \"@/app/theme\";\nimport { Icon } from \"@/components/layout/Icon\";\n\nconst StyledAccordion = styled.div<{ theme: Theme }>`\n background: ${({ theme }) => theme.colors.light};\n border: solid 1px ${({ theme }) => theme.colors.grayLight};\n border-radius: ${({ theme }) => theme.spacing.radius.lg};\n padding: 20px;\n margin: 0;\n ${({ theme }) => styledText(theme)};\n width: 100%;\n`;\n\nconst StyledAccordionTitle = styled(Button)<{\n theme: Theme;\n $isOpen: boolean;\n}>`\n ${resetButton};\n appearance: none;\n display: block;\n width: 100%;\n border: none;\n background: none;\n text-align: left;\n font: inherit;\n cursor: pointer;\n margin: 0;\n padding: 0 40px 0 0;\n ${({ theme }) => styledText(theme)};\n font-weight: 700;\n color: ${({ theme }) => theme.colors.primary};\n transition: color 0.3s ease;\n position: relative;\n\n &:hover {\n color: ${({ theme }) => theme.colors.primaryDark};\n }\n\n &:focus-visible {\n outline: none;\n border-radius: ${({ theme }) => theme.spacing.radius.xs};\n box-shadow: 0 0 0 2px ${({ theme }) => theme.colors.primaryLight};\n }\n\n & .lucide-chevron-down {\n position: absolute;\n top: 50%;\n transform: translateY(-50%);\n right: 0;\n transition: transform 0.3s ease;\n\n ${({ $isOpen }) =>\n $isOpen &&\n css`\n transform: translateY(-50%) rotate(180deg);\n `}\n }\n`;\n\nconst StyledAccordionContent = styled.div<{ theme: Theme; $isOpen: boolean }>`\n ${({ theme }) => styledText(theme)};\n color: ${({ theme }) => theme.colors.grayDark};\n height: 0;\n overflow: clip;\n transition: all 0.3s ease;\n display: flex;\n flex-direction: column;\n gap: 20px;\n flex-wrap: wrap;\n flex: 1;\n\n ${({ $isOpen }) =>\n $isOpen &&\n css`\n margin: 20px 0 0;\n height: auto;\n `}\n\n @media (prefers-reduced-motion: reduce) {\n transition: none;\n }\n`;\n\ninterface AccordionProps extends React.HTMLAttributes<HTMLDivElement> {\n children: React.ReactNode;\n title: string;\n defaultOpen?: boolean;\n}\n\nfunction Accordion({ children, title, defaultOpen = false }: AccordionProps) {\n const [isOpen, setIsOpen] = useState(defaultOpen);\n const contentId = useId();\n const titleId = useId();\n\n return (\n <StyledAccordion>\n <StyledAccordionTitle\n id={titleId}\n type=\"button\"\n onClick={() => setIsOpen(!isOpen)}\n $isOpen={isOpen}\n aria-expanded={isOpen}\n aria-controls={contentId}\n >\n {title} <Icon name=\"ChevronDown\" />\n </StyledAccordionTitle>\n <StyledAccordionContent\n id={contentId}\n role=\"region\"\n aria-labelledby={titleId}\n aria-hidden={!isOpen}\n inert={!isOpen}\n $isOpen={isOpen}\n >\n {children}\n </StyledAccordionContent>\n </StyledAccordion>\n );\n}\n\nexport { Accordion };\n";
1
+ export declare const accordionTemplate = "\"use client\";\nimport { useId, useState } from \"react\";\nimport styled, { css } from \"styled-components\";\nimport { styledText } from \"cherry-styled-components\";\nimport { Theme } from \"@/app/theme\";\nimport { Icon } from \"@/components/layout/Icon\";\n\nconst StyledAccordion = styled.div<{ theme: Theme }>`\n background: ${({ theme }) => theme.colors.light};\n border: solid 1px ${({ theme }) => theme.colors.grayLight};\n border-radius: ${({ theme }) => theme.spacing.radius.lg};\n padding: 20px;\n margin: 0;\n ${({ theme }) => styledText(theme)};\n width: 100%;\n`;\n\nconst StyledAccordionTitle = styled.button<{\n theme: Theme;\n $isOpen: boolean;\n}>`\n appearance: none;\n display: block;\n width: 100%;\n border: none;\n background: none;\n text-align: left;\n font: inherit;\n cursor: pointer;\n margin: 0;\n padding: 0 40px 0 0;\n ${({ theme }) => styledText(theme)};\n font-weight: 700;\n color: ${({ theme }) => theme.colors.primary};\n transition: color 0.3s ease;\n position: relative;\n\n &:hover {\n color: ${({ theme }) => theme.colors.primaryDark};\n }\n\n &:focus-visible {\n outline: none;\n border-radius: ${({ theme }) => theme.spacing.radius.xs};\n box-shadow: 0 0 0 2px ${({ theme }) => theme.colors.primaryLight};\n }\n\n & .lucide-chevron-down {\n position: absolute;\n top: 50%;\n transform: translateY(-50%);\n right: 0;\n transition: transform 0.3s ease;\n\n ${({ $isOpen }) =>\n $isOpen &&\n css`\n transform: translateY(-50%) rotate(180deg);\n `}\n }\n`;\n\nconst StyledAccordionContent = styled.div<{ theme: Theme; $isOpen: boolean }>`\n ${({ theme }) => styledText(theme)};\n color: ${({ theme }) => theme.colors.grayDark};\n height: 0;\n overflow: clip;\n transition: all 0.3s ease;\n display: flex;\n flex-direction: column;\n gap: 20px;\n flex-wrap: wrap;\n flex: 1;\n\n ${({ $isOpen }) =>\n $isOpen &&\n css`\n margin: 20px 0 0;\n height: auto;\n `}\n\n @media (prefers-reduced-motion: reduce) {\n transition: none;\n }\n`;\n\ninterface AccordionProps extends React.HTMLAttributes<HTMLDivElement> {\n children: React.ReactNode;\n title: string;\n defaultOpen?: boolean;\n}\n\nfunction Accordion({ children, title, defaultOpen = false }: AccordionProps) {\n const [isOpen, setIsOpen] = useState(defaultOpen);\n const contentId = useId();\n const titleId = useId();\n\n return (\n <StyledAccordion>\n <StyledAccordionTitle\n id={titleId}\n type=\"button\"\n onClick={() => setIsOpen(!isOpen)}\n $isOpen={isOpen}\n aria-expanded={isOpen}\n aria-controls={contentId}\n >\n {title} <Icon name=\"ChevronDown\" />\n </StyledAccordionTitle>\n <StyledAccordionContent\n id={contentId}\n role=\"region\"\n aria-labelledby={titleId}\n aria-hidden={!isOpen}\n inert={!isOpen}\n $isOpen={isOpen}\n >\n {children}\n </StyledAccordionContent>\n </StyledAccordion>\n );\n}\n\nexport { Accordion };\n";
@@ -1,7 +1,7 @@
1
1
  export const accordionTemplate = `"use client";
2
2
  import { useId, useState } from "react";
3
3
  import styled, { css } from "styled-components";
4
- import { Button, resetButton, styledText } from "cherry-styled-components";
4
+ import { styledText } from "cherry-styled-components";
5
5
  import { Theme } from "@/app/theme";
6
6
  import { Icon } from "@/components/layout/Icon";
7
7
 
@@ -15,11 +15,10 @@ const StyledAccordion = styled.div<{ theme: Theme }>\`
15
15
  width: 100%;
16
16
  \`;
17
17
 
18
- const StyledAccordionTitle = styled(Button)<{
18
+ const StyledAccordionTitle = styled.button<{
19
19
  theme: Theme;
20
20
  $isOpen: boolean;
21
21
  }>\`
22
- \${resetButton};
23
22
  appearance: none;
24
23
  display: block;
25
24
  width: 100%;
@@ -1 +1 @@
1
- export declare const apiPlaygroundMdxTemplate = "---\ntitle: \"API Playground\"\ndescription: \"Turn an OpenAPI document into an interactive API reference where readers send real requests and see live responses, right inside your docs.\"\ndate: \"2026-07-25\"\ncategory: \"Components\"\ncategoryOrder: 1\norder: 20\n---\n# API Playground\n\nPoint Doccupine at an OpenAPI document and it generates a complete, interactive API reference: one page per endpoint, grouped by tag in the sidebar, each with a \"Send request\" panel that makes real calls and shows the live response - plus copy-pasteable code snippets.\n\n<Callout type=\"note\">\nThe playground is driven entirely by your OpenAPI document. There is nothing to wire up by hand - add one line of config and every endpoint becomes a documented, runnable page.\n</Callout>\n\n## Try it\n\nPress **Try it** below to open the playground, tweak the request body, and send a real request to a live API - right from these docs.\n\n<ApiPlaygroundDemo />\n\n## Enabling the playground\n\n<Steps>\n <Step title=\"Add an openapi path to doccupine.json.\">\n Point at a local `.json`, `.yaml`, or `.yml` OpenAPI 3.0 or 3.1 document.\n\n```json\n{\n \"watchDir\": \"docs\",\n \"outputDir\": \"nextjs-app\",\n \"openapi\": \"openapi.yaml\"\n}\n```\n </Step>\n <Step title=\"Run Doccupine.\">\n On the next build (or live, while watching) Doccupine parses the document and writes an endpoint page for each operation. Local `$ref` files must stay inside the configured spec's directory, use `.json`, `.yaml`, or `.yml`, and cannot be dotfiles or live inside dot-directories.\n </Step>\n <Step title=\"Open the API Reference section.\">\n Endpoints appear in the sidebar grouped by their OpenAPI tag. Editing the spec regenerates the pages automatically.\n </Step>\n</Steps>\n\n## Example spec\n\nDo not have a document yet? This `openapi.yaml` points at [JSONPlaceholder](https://jsonplaceholder.typicode.com), a free public test API, so it works end to end - save it, set `openapi` to it, and the generated pages can send real requests:\n\n```yaml\nopenapi: 3.1.0\ninfo:\n title: JSONPlaceholder\n version: 1.0.0\nservers:\n - url: https://jsonplaceholder.typicode.com\ntags:\n - name: Todos\n - name: Posts\npaths:\n /todos/{id}:\n get:\n summary: Get a to-do\n tags: [Todos]\n parameters:\n - name: id\n in: path\n required: true\n schema:\n type: integer\n responses:\n \"200\":\n description: Just a demo of a to-do item\n /posts:\n post:\n summary: Create a post\n tags: [Posts]\n requestBody:\n required: true\n content:\n application/json:\n example:\n title: Hello\n body: Sent from the docs\n userId: 1\n responses:\n \"201\":\n description: Just a demo of the created post\n```\n\nEach part maps to something in the playground: `servers` sets the request target - and the only host the proxy will call - `tags` group endpoints in the sidebar, and `parameters` and `requestBody` become the inputs (adding a `securitySchemes` entry would produce authentication fields). Doccupine reads OpenAPI 3.0 and 3.1; see the [OpenAPI specification](https://spec.openapis.org) for the full format.\n\n## What gets generated\n\nThe generated `/api-reference` index lists every operation with a direct link, grouped by API and tag. Each operation also gets its own page under `/api-reference/{tag}/{operation}`, showing:\n\n<Field value=\"Parameters\" type=\"path, query, header, cookie\">\nEach parameter is rendered with its name, type, and whether it is required, grouped into a collapsible section with an input to fill in.\n</Field>\n\n<Field value=\"Request body\" type=\"editable\">\nA JSON editor prefilled from the schema's example, ready to tweak and send.\n</Field>\n\n<Field value=\"Authentication\" type=\"from securitySchemes\">\nInputs for the endpoint's security schemes - API keys, bearer tokens, or basic auth - generated from the document.\n</Field>\n\n<Field value=\"Response\" type=\"live\">\nThe real status, timing, and body from your API, rendered to match its content type.\n</Field>\n\n## Embedding a single endpoint\n\nTo mix prose and a live endpoint on a hand-written page, reference an operation from the page's frontmatter with `openapi`. Use `METHOD /path` or an `operationId`:\n\n```mdx\n---\ntitle: \"Create a post\"\nopenapi: \"POST /posts\"\n---\n\nPosts are created for a user. The playground above is fully live - fill in the\nbody and send a real request.\n```\n\nDoccupine renders that endpoint's playground above your prose. If the reference does not match any operation in your document, the page still renders its prose and a warning is logged.\n\n## Running requests\n\nRequests run one of two ways, and readers can switch between them:\n\n<Callout type=\"note\">\n**Proxy (default).** The request is forwarded server-side, so it works even when the target API blocks cross-origin browser calls. **Direct.** The browser calls the API itself - useful when the API allows CORS and you want requests to never leave the reader's machine.\n</Callout>\n\nThe proxy is deliberately locked down. It only forwards to servers declared in your OpenAPI document and refuses private, internal, metadata, and reserved network addresses, including IPv4 destinations represented through IPv6 translation ranges. An explicitly declared loopback server such as `http://localhost:4000` is available only outside production for local development and tests; production always blocks loopback and every other private target even when the spec declares one. Request URLs, headers, and bodies are never logged, so API keys a reader enters are not written anywhere. On a [password-protected site](/authentication), the proxy also requires the visitor's unlocked session, so it cannot be called anonymously.\n\nProxy requests are rate limited per trusted client address on recognized hosting platforms. Unknown and self-hosted proxy setups share one fallback bucket rather than trusting spoofable forwarding headers; use your trusted edge or a shared rate-limit store when those deployments need accurate per-client limits.\n\n<Callout type=\"warning\">\nKeys and tokens a reader types are used only to make the request. Turn on \"Show secrets\" to reveal them in the generated code snippets; they are redacted by default.\n</Callout>\n\n## Responses and snippets\n\nResponses render to match their type: images and video play inline, everything else is shown as a formatted, syntax-highlighted body. Alongside the response, the playground generates ready-to-run **cURL**, **JavaScript**, and **Python** snippets for the exact request you built.\n\n## Documenting more than one API\n\nPass an array to document several APIs at once. Each spec becomes its own namespaced section:\n\n```json\n{\n \"openapi\": [\n { \"name\": \"public\", \"file\": \"specs/public.yaml\" },\n { \"name\": \"admin\", \"file\": \"specs/admin.yaml\" }\n ]\n}\n```\n";
1
+ export declare const apiPlaygroundMdxTemplate = "---\ntitle: \"API Playground\"\ndescription: \"Turn an OpenAPI document into an interactive API reference where readers send real requests and see live responses, right inside your docs.\"\ndate: \"2026-07-25\"\nupdated: \"2026-07-31\"\ncategory: \"Components\"\ncategoryOrder: 1\norder: 20\n---\n# API Playground\n\nPoint Doccupine at an OpenAPI document and it generates a complete, interactive API reference: one page per endpoint, grouped by tag in the sidebar, each with a \"Send request\" panel that makes real calls and shows the live response - plus copy-pasteable code snippets.\n\n<Callout type=\"note\">\nThe playground is driven entirely by your OpenAPI document. There is nothing to wire up by hand - add one line of config and every endpoint becomes a documented, runnable page.\n</Callout>\n\n## Try it\n\nPress **Try it** below to open the playground, tweak the request body, and send a real request to a live API - right from these docs.\n\n<ApiPlaygroundDemo />\n\n## Enabling the playground\n\n<Steps>\n <Step title=\"Add an openapi path to doccupine.json.\">\n Point at a local `.json`, `.yaml`, or `.yml` OpenAPI 3.0 or 3.1 document.\n\n```json\n{\n \"watchDir\": \"docs\",\n \"outputDir\": \"nextjs-app\",\n \"openapi\": \"openapi.yaml\"\n}\n```\n </Step>\n <Step title=\"Run Doccupine.\">\n Doccupine reads the root document and its recursive local `$ref` dependencies as one stable snapshot, then writes an endpoint page for each operation. The root must resolve inside the project, while referenced files must stay beneath the root spec's directory, use `.json`, `.yaml`, or `.yml`, and cannot be dotfiles or live inside dot-directories. Remote references and symlink escapes are rejected.\n </Step>\n <Step title=\"Open the API Reference section.\">\n Endpoints appear in the sidebar grouped by their OpenAPI tag. In watch mode, editing the root spec or any discovered local `$ref` file regenerates the reference automatically. Adding or retargeting a reference updates the watched dependency set after the refresh succeeds.\n </Step>\n</Steps>\n\n<Callout type=\"info\">\n OpenAPI refreshes preserve the last successful reference. A malformed or partially saved spec, a missing reference, or a generation failure does not replace the active pages, request allowlist, navigation, MCP content, or watcher.\n</Callout>\n\n## Example spec\n\nDo not have a document yet? This `openapi.yaml` points at [JSONPlaceholder](https://jsonplaceholder.typicode.com), a free public test API, so it works end to end - save it, set `openapi` to it, and the generated pages can send real requests:\n\n```yaml\nopenapi: 3.1.0\ninfo:\n title: JSONPlaceholder\n version: 1.0.0\nservers:\n - url: https://jsonplaceholder.typicode.com\ntags:\n - name: Todos\n - name: Posts\npaths:\n /todos/{id}:\n get:\n summary: Get a to-do\n tags: [Todos]\n parameters:\n - name: id\n in: path\n required: true\n schema:\n type: integer\n responses:\n \"200\":\n description: Just a demo of a to-do item\n /posts:\n post:\n summary: Create a post\n tags: [Posts]\n requestBody:\n required: true\n content:\n application/json:\n example:\n title: Hello\n body: Sent from the docs\n userId: 1\n responses:\n \"201\":\n description: Just a demo of the created post\n```\n\nEach part maps to something in the playground: `servers` sets the request target - and the only host the proxy will call - `tags` group endpoints in the sidebar, and `parameters` and `requestBody` become the inputs (adding a `securitySchemes` entry would produce authentication fields). Doccupine reads OpenAPI 3.0 and 3.1; see the [OpenAPI specification](https://spec.openapis.org) for the full format.\n\n## What gets generated\n\nThe generated `/api-reference` index lists every operation with a direct link, grouped by API and tag. Each operation also gets its own page under `/api-reference/{tag}/{operation}`, showing:\n\n<Callout type=\"note\">\n A hand-written MDX page takes precedence when it resolves to the same route as a generated OpenAPI page. Moving or deleting that MDX source returns the route to OpenAPI on the next successful refresh.\n</Callout>\n\n<Field value=\"Parameters\" type=\"path, query, header, cookie\">\nEach parameter is rendered with its name, type, and whether it is required, grouped into a collapsible section with an input to fill in.\n</Field>\n\n<Field value=\"Request body\" type=\"editable\">\nA JSON editor prefilled from the schema's example, ready to tweak and send.\n</Field>\n\n<Field value=\"Authentication\" type=\"from securitySchemes\">\nInputs for the endpoint's security schemes - API keys, bearer tokens, or basic auth - generated from the document.\n</Field>\n\n<Field value=\"Response\" type=\"live\">\nThe real status, timing, and body from your API, rendered to match its content type.\n</Field>\n\n## Embedding a single endpoint\n\nTo mix prose and a live endpoint on a hand-written page, reference an operation from the page's frontmatter with `openapi`. Use `METHOD /path` or an `operationId`:\n\n```mdx\n---\ntitle: \"Create a post\"\nopenapi: \"POST /posts\"\n---\n\nPosts are created for a user. The playground above is fully live - fill in the\nbody and send a real request.\n```\n\nDoccupine renders that endpoint's playground above your prose. If the reference does not match any operation in your document, the page still renders its prose and a warning is logged.\n\n## Running requests\n\nRequests run one of two ways, and readers can switch between them:\n\n<Callout type=\"note\">\n**Proxy (default).** The request is forwarded server-side, so it works even when the target API blocks cross-origin browser calls. **Direct.** The browser calls the API itself - useful when the API allows CORS and you want requests to never leave the reader's machine.\n</Callout>\n\nThe proxy is deliberately locked down. It only forwards to servers declared in your OpenAPI document and refuses private, internal, metadata, and reserved network addresses, including IPv4 destinations represented through IPv6 translation ranges. An explicitly declared loopback server such as `http://localhost:4000` is available only outside production for local development and tests; production always blocks loopback and every other private target even when the spec declares one. Request URLs, headers, and bodies are never logged, so API keys a reader enters are not written anywhere. On a [password-protected site](/authentication), the proxy also requires the visitor's unlocked session, so it cannot be called anonymously.\n\nProxy requests are rate limited per trusted client address on recognized hosting platforms. Unknown and self-hosted proxy setups share one fallback bucket rather than trusting spoofable forwarding headers; use your trusted edge or a shared rate-limit store when those deployments need accurate per-client limits.\n\n<Callout type=\"warning\">\nKeys and tokens a reader types are used only to make the request. Turn on \"Show secrets\" to reveal them in the generated code snippets; they are redacted by default.\n</Callout>\n\n## Responses and snippets\n\nResponses render to match their type: images and video play inline, everything else is shown as a formatted, syntax-highlighted body. Alongside the response, the playground generates ready-to-run **cURL**, **JavaScript**, and **Python** snippets for the exact request you built.\n\n## Documenting more than one API\n\nPass an array to document several APIs at once. Each spec becomes its own namespaced section:\n\n```json\n{\n \"openapi\": [\n { \"name\": \"public\", \"file\": \"specs/public.yaml\" },\n { \"name\": \"admin\", \"file\": \"specs/admin.yaml\" }\n ]\n}\n```\n";
@@ -2,6 +2,7 @@ export const apiPlaygroundMdxTemplate = `---
2
2
  title: "API Playground"
3
3
  description: "Turn an OpenAPI document into an interactive API reference where readers send real requests and see live responses, right inside your docs."
4
4
  date: "2026-07-25"
5
+ updated: "2026-07-31"
5
6
  category: "Components"
6
7
  categoryOrder: 1
7
8
  order: 20
@@ -35,13 +36,17 @@ Press **Try it** below to open the playground, tweak the request body, and send
35
36
  \`\`\`
36
37
  </Step>
37
38
  <Step title="Run Doccupine.">
38
- On the next build (or live, while watching) Doccupine parses the document and writes an endpoint page for each operation. Local \`$ref\` files must stay inside the configured spec's directory, use \`.json\`, \`.yaml\`, or \`.yml\`, and cannot be dotfiles or live inside dot-directories.
39
+ Doccupine reads the root document and its recursive local \`$ref\` dependencies as one stable snapshot, then writes an endpoint page for each operation. The root must resolve inside the project, while referenced files must stay beneath the root spec's directory, use \`.json\`, \`.yaml\`, or \`.yml\`, and cannot be dotfiles or live inside dot-directories. Remote references and symlink escapes are rejected.
39
40
  </Step>
40
41
  <Step title="Open the API Reference section.">
41
- Endpoints appear in the sidebar grouped by their OpenAPI tag. Editing the spec regenerates the pages automatically.
42
+ Endpoints appear in the sidebar grouped by their OpenAPI tag. In watch mode, editing the root spec or any discovered local \`$ref\` file regenerates the reference automatically. Adding or retargeting a reference updates the watched dependency set after the refresh succeeds.
42
43
  </Step>
43
44
  </Steps>
44
45
 
46
+ <Callout type="info">
47
+ OpenAPI refreshes preserve the last successful reference. A malformed or partially saved spec, a missing reference, or a generation failure does not replace the active pages, request allowlist, navigation, MCP content, or watcher.
48
+ </Callout>
49
+
45
50
  ## Example spec
46
51
 
47
52
  Do not have a document yet? This \`openapi.yaml\` points at [JSONPlaceholder](https://jsonplaceholder.typicode.com), a free public test API, so it works end to end - save it, set \`openapi\` to it, and the generated pages can send real requests:
@@ -93,6 +98,10 @@ Each part maps to something in the playground: \`servers\` sets the request targ
93
98
 
94
99
  The generated \`/api-reference\` index lists every operation with a direct link, grouped by API and tag. Each operation also gets its own page under \`/api-reference/{tag}/{operation}\`, showing:
95
100
 
101
+ <Callout type="note">
102
+ A hand-written MDX page takes precedence when it resolves to the same route as a generated OpenAPI page. Moving or deleting that MDX source returns the route to OpenAPI on the next successful refresh.
103
+ </Callout>
104
+
96
105
  <Field value="Parameters" type="path, query, header, cookie">
97
106
  Each parameter is rendered with its name, type, and whether it is required, grouped into a collapsible section with an input to fill in.
98
107
  </Field>
@@ -1 +1 @@
1
- export declare const commandsMdxTemplate = "---\ntitle: \"Commands\"\ndescription: \"In this page, you can find all the commands available in Doccupine CLI.\"\ndate: \"2026-02-19\"\ncategory: \"Getting Started\"\ncategoryOrder: 0\norder: 2\n---\n# Commands\n\nIn this page, you can find all the commands available in Doccupine CLI.\n\n## Run Doccupine CLI\n\nCreate a new directory for your project and navigate to it in your terminal. Run the following command to create a new Doccupine project:\n\n```bash\nnpx doccupine\n```\n\nOnce you run the command, Doccupine will ask you to select a directory to store your MDX files. Choose the directory where you want to create your documentation files.\nAfter selecting the directory, Doccupine will ask you to enter the name of the directory for the generated website. Enter the name of the directory where you want to create your website.\nFinally, Doccupine will ask for an optional path to an OpenAPI document. Leave it blank to skip, or point it at a `.yaml`, `.yml`, or `.json` spec to generate an interactive [API Playground](/api-playground) from your API.\n\nThis will start the development server on port 3000. Open your browser and navigate to http://localhost:3000 to view your documentation.\n\n## Options\n\n| Flag | Description |\n| -------------------------- | --------------------------------------------------------------------------- |\n| `--port <port>` | Port for the dev server (default: `3000`). Auto-increments if taken. |\n| `--verbose` | Show all Next.js output including compilation details. |\n| `--reset` | Re-prompt for watch/output directories and the OpenAPI spec path. |\n| `--skip-install` | Always skip dependency installation before starting the development server. |\n| `--package-manager <name>` | Use `pnpm` or `npm` for the generated app instead of auto-detection. |\n\n<Callout type=\"warning\">\n The watch and output directories must not overlap. The output directory must be empty, contain only local metadata such as `.DS_Store` or `.env.local`, or already be owned by Doccupine. This prevents the generator from overwriting another project. If an older `doccupine.json` no longer validates, run `doccupine config --reset`. Generation also reports a validation error, instead of letting one page overwrite another, when two source files resolve to the same route.\n</Callout>\n\nStarter documentation is created only when the selected source directory contains no MDX files. Existing pages are never replaced just because `index.mdx` is missing. Frontmatter must use the normal YAML `---` delimiter; language-tagged executable frontmatter is rejected.\n\nDoccupine records generated route and Markdown-mirror ownership in `.doccupine-artifacts.json` inside the generated app. Watch-mode renames and deletes use that registry rather than guessing routes from filenames, so section moves remove only files owned by the changed source.\n\n## Dependency installation\n\nThe first run installs the generated app's dependencies. After that, Doccupine records a fingerprint of the generated `package.json` and the package manager in `.doccupine-install` and reinstalls only when that fingerprint changes or `node_modules` is missing - later runs start the dev server straight away. Pass `--skip-install` to skip the check entirely, for example when you manage dependencies yourself.\n\n## Verbose mode\n\n```bash\nnpx doccupine --verbose\n```\n\n<Callout type=\"note\">\n This will show Next.js output in the terminal, providing detailed logs useful for debugging during development.\n</Callout>\n\n## Generate the website\n\n```bash\nnpx doccupine build\n```\n\nYou can also use the equivalent `npx doccupine generate` command. These commands scaffold the Next.js app from your MDX files without installing dependencies or starting the development server. To produce a production build, install dependencies and run the generated app's `build` script.\n\n## Show current configuration\n\n```bash\nnpx doccupine config --show\n```\n\nThis will show the current configuration for Doccupine.\n\n## Reset configuration\n\n```bash\nnpx doccupine config --reset\n```\n\nThis will reset the current configuration for Doccupine.";
1
+ export declare const commandsMdxTemplate = "---\ntitle: \"Commands\"\ndescription: \"In this page, you can find all the commands available in Doccupine CLI.\"\ndate: \"2026-02-19\"\nupdated: \"2026-07-31\"\ncategory: \"Getting Started\"\ncategoryOrder: 0\norder: 2\n---\n# Commands\n\nIn this page, you can find all the commands available in Doccupine CLI.\n\n## Run Doccupine CLI\n\nCreate a new directory for your project and navigate to it in your terminal. Run the following command to create a new Doccupine project:\n\n```bash\nnpx doccupine\n```\n\nOnce you run the command, Doccupine will ask you to select a directory to store your MDX files. Choose the directory where you want to create your documentation files.\nAfter selecting the directory, Doccupine will ask you to enter the name of the directory for the generated website. Enter the name of the directory where you want to create your website.\nFinally, Doccupine will ask for an optional path to an OpenAPI document. Leave it blank to skip, or point it at a `.yaml`, `.yml`, or `.json` spec to generate an interactive [API Playground](/api-playground) from your API.\n\nThis will start the development server on port 3000. Open your browser and navigate to http://localhost:3000 to view your documentation.\n\n## Options\n\n| Flag | Description |\n| -------------------------- | --------------------------------------------------------------------------- |\n| `--port <port>` | Port for the dev server (default: `3000`). Auto-increments if taken. |\n| `--verbose` | Show all Next.js output including compilation details. |\n| `--reset` | Re-prompt for watch/output directories and the OpenAPI spec path. |\n| `--skip-install` | Always skip dependency installation before starting the development server. |\n| `--package-manager <name>` | Use `pnpm` or `npm` for the generated app instead of auto-detection. |\n\n<Callout type=\"warning\">\n The watch and output directories must not overlap. The output directory must be empty, contain only local metadata such as `.DS_Store` or `.env.local`, or already be owned by Doccupine. This prevents the generator from overwriting another project. If an older `doccupine.json` no longer validates, run `doccupine config --reset`. Generation also reports a validation error, instead of letting one page overwrite another, when two source files resolve to the same route.\n</Callout>\n\nStarter documentation is created only when the selected source directory contains no MDX files. Existing pages are never replaced just because `index.mdx` is missing. Frontmatter must use the normal YAML `---` delimiter; language-tagged executable frontmatter is rejected.\n\nDoccupine marks its output directory with `.doccupine-generated.json` and records generated route, Markdown-mirror, and copied public-file ownership in `.doccupine-artifacts.json`. Treat both files as internal generator state. A fresh run recreates `app`, and later refreshes may rewrite other registered template paths, so keep durable changes in source MDX, project-root JSON files, and `public`.\n\n## Watch mode\n\nThe default command watches MDX files, supported project-root JSON configuration, `fonts.json`, `analytics.json`, `doccupine.json`, public assets, and configured OpenAPI documents with their discovered local `$ref` files. Changes are processed serially. Once every watcher is ready, Doccupine compares the current sources with the versions used during initial generation and reconciles edits made while startup was still running.\n\n## Route collisions and recovery\n\nTwo MDX sources cannot generate the same route. For example, `guide.mdx` and `guide/index.mdx` both resolve to `/guide`. A one-time build stops before either source can overwrite the other.\n\nDuring watch mode, a collision keeps the last successfully generated page and site metadata in place. After you move, rename, or delete one of the colliding sources, Doccupine retries the blocked sources and any other MDX changes that could not be applied while the collision existed. A restart or manual resave is not required.\n\n<Callout type=\"info\">\n Failed watch refreshes keep or restore the last successful pages, route ownership, inferred sections, sitemap, and LLMS/MCP content. A new page with no successful version stays absent until it can be generated safely.\n</Callout>\n\n## Reloading doccupine.json\n\nChanging the `openapi` field is applied live after the complete candidate reference validates and generates successfully. Invalid JSON, invalid configuration, a missing spec, or a failed generation keeps the current OpenAPI reference and watcher active. Changes to `watchDir`, `outputDir`, `port`, or `packageManager` require restarting Doccupine.\n\n## File-system safety\n\nDoccupine does not follow symlinked MDX files or nested directories beneath `watchDir`. Project-root configuration and public assets must also use real files and directories, and the `public` root cannot be a symlink. A stable symlink used as the `watchDir` root is supported, but links inside it are rejected.\n\nThe output directory must be a real directory, and generated paths cannot contain symlinks. OpenAPI root specs must resolve inside the project, while local references must remain inside the root spec's directory. These checks prevent generated reads, writes, and removals from being redirected elsewhere.\n\n## Dependency installation\n\nThe first run installs the generated app's dependencies. After that, Doccupine records a fingerprint of the generated `package.json` and the package manager in `.doccupine-install` and reinstalls only when that fingerprint changes or `node_modules` is missing - later runs start the dev server straight away. Pass `--skip-install` to skip the check entirely, for example when you manage dependencies yourself.\n\n## Verbose mode\n\n```bash\nnpx doccupine --verbose\n```\n\n<Callout type=\"note\">\n This will show Next.js output in the terminal, providing detailed logs useful for debugging during development.\n</Callout>\n\n## Generate the website\n\n```bash\nnpx doccupine build\n```\n\nYou can also use the equivalent `npx doccupine generate` command. These commands scaffold the Next.js app from your MDX files without installing dependencies or starting the development server. To produce a production build, install dependencies and run the generated app's `build` script.\n\n## Show current configuration\n\n```bash\nnpx doccupine config --show\n```\n\nThis will show the current configuration for Doccupine.\n\n## Reset configuration\n\n```bash\nnpx doccupine config --reset\n```\n\nThis will reset the current configuration for Doccupine.";
@@ -2,6 +2,7 @@ export const commandsMdxTemplate = `---
2
2
  title: "Commands"
3
3
  description: "In this page, you can find all the commands available in Doccupine CLI."
4
4
  date: "2026-02-19"
5
+ updated: "2026-07-31"
5
6
  category: "Getting Started"
6
7
  categoryOrder: 0
7
8
  order: 2
@@ -40,7 +41,31 @@ This will start the development server on port 3000. Open your browser and navig
40
41
 
41
42
  Starter documentation is created only when the selected source directory contains no MDX files. Existing pages are never replaced just because \`index.mdx\` is missing. Frontmatter must use the normal YAML \`---\` delimiter; language-tagged executable frontmatter is rejected.
42
43
 
43
- Doccupine records generated route and Markdown-mirror ownership in \`.doccupine-artifacts.json\` inside the generated app. Watch-mode renames and deletes use that registry rather than guessing routes from filenames, so section moves remove only files owned by the changed source.
44
+ Doccupine marks its output directory with \`.doccupine-generated.json\` and records generated route, Markdown-mirror, and copied public-file ownership in \`.doccupine-artifacts.json\`. Treat both files as internal generator state. A fresh run recreates \`app\`, and later refreshes may rewrite other registered template paths, so keep durable changes in source MDX, project-root JSON files, and \`public\`.
45
+
46
+ ## Watch mode
47
+
48
+ The default command watches MDX files, supported project-root JSON configuration, \`fonts.json\`, \`analytics.json\`, \`doccupine.json\`, public assets, and configured OpenAPI documents with their discovered local \`$ref\` files. Changes are processed serially. Once every watcher is ready, Doccupine compares the current sources with the versions used during initial generation and reconciles edits made while startup was still running.
49
+
50
+ ## Route collisions and recovery
51
+
52
+ Two MDX sources cannot generate the same route. For example, \`guide.mdx\` and \`guide/index.mdx\` both resolve to \`/guide\`. A one-time build stops before either source can overwrite the other.
53
+
54
+ During watch mode, a collision keeps the last successfully generated page and site metadata in place. After you move, rename, or delete one of the colliding sources, Doccupine retries the blocked sources and any other MDX changes that could not be applied while the collision existed. A restart or manual resave is not required.
55
+
56
+ <Callout type="info">
57
+ Failed watch refreshes keep or restore the last successful pages, route ownership, inferred sections, sitemap, and LLMS/MCP content. A new page with no successful version stays absent until it can be generated safely.
58
+ </Callout>
59
+
60
+ ## Reloading doccupine.json
61
+
62
+ Changing the \`openapi\` field is applied live after the complete candidate reference validates and generates successfully. Invalid JSON, invalid configuration, a missing spec, or a failed generation keeps the current OpenAPI reference and watcher active. Changes to \`watchDir\`, \`outputDir\`, \`port\`, or \`packageManager\` require restarting Doccupine.
63
+
64
+ ## File-system safety
65
+
66
+ Doccupine does not follow symlinked MDX files or nested directories beneath \`watchDir\`. Project-root configuration and public assets must also use real files and directories, and the \`public\` root cannot be a symlink. A stable symlink used as the \`watchDir\` root is supported, but links inside it are rejected.
67
+
68
+ The output directory must be a real directory, and generated paths cannot contain symlinks. OpenAPI root specs must resolve inside the project, while local references must remain inside the root spec's directory. These checks prevent generated reads, writes, and removals from being redirected elsewhere.
44
69
 
45
70
  ## Dependency installation
46
71
 
@@ -1 +1 @@
1
- export declare const mediaAndAssetsMdxTemplate = "---\ntitle: \"Media and assets\"\ndescription: \"Serve static files like images, favicons, fonts, and Open Graph previews from the public directory.\"\ndate: \"2026-02-19\"\ncategory: \"Configuration\"\ncategoryOrder: 2\norder: 7\n---\n# Media and assets\n\nDoccupine watches a `public` directory in your project root (the same directory where you execute `npx doccupine`) and copies its contents into the generated Next.js `public` directory. Use it to serve static files such as favicons, Open Graph preview images, custom fonts, or any other media your documentation needs.\n\n## The public directory\n\nCreate a `public` directory at your project root. Any file you place inside is automatically synced to the generated site and served from the root URL path.\n\n```text\nmy-docs/\n\u251C\u2500\u2500 public/\n\u2502 \u251C\u2500\u2500 favicon.ico\n\u2502 \u251C\u2500\u2500 og-image.png\n\u2502 \u251C\u2500\u2500 logo.svg\n\u2502 \u2514\u2500\u2500 fonts/\n\u2502 \u2514\u2500\u2500 custom-font.woff2\n\u251C\u2500\u2500 docs/\n\u2502 \u2514\u2500\u2500 index.mdx\n\u251C\u2500\u2500 config.json\n\u2514\u2500\u2500 theme.json\n```\n\n## How assets are served\n\nFiles in the `public` directory are available at the root of your deployed domain. The path inside `public` maps directly to the URL path.\n\n| File | URL |\n| -------------------------------- | ------------------------------------------------- |\n| `public/favicon.ico` | `https://your-domain.com/favicon.ico` |\n| `public/og-image.png` | `https://your-domain.com/og-image.png` |\n| `public/logo.svg` | `https://your-domain.com/logo.svg` |\n| `public/fonts/custom-font.woff2` | `https://your-domain.com/fonts/custom-font.woff2` |\n\n## Common use cases\n\n### Favicon\n\nDrop a `favicon.ico` into the `public` directory. Browsers pick it up automatically from the root path.\n\n```text\npublic/favicon.ico \u2192 https://your-domain.com/favicon.ico\n```\n\n### Open Graph preview image\n\nAdd an image for link previews on social media. Reference it in your `config.json` so Doccupine sets the correct meta tags.\n\n```text\npublic/og-image.png \u2192 https://your-domain.com/og-image.png\n```\n\n### Custom fonts\n\nPlace font files in `public` and reference them from your `fonts.json`. See the **Fonts** page for full configuration details.\n\n```text\npublic/fonts/custom-font.woff2 \u2192 https://your-domain.com/fonts/custom-font.woff2\n```\n\n### Images and other media\n\nAny image or file you want to reference in your MDX pages can live in `public`. Use a root-relative path in your content:\n\n```mdx\n![Architecture diagram](/architecture.png)\n```\n\n## Live syncing\n\n<Callout type=\"info\">\n Doccupine watches the `public` directory for changes while running. When you add, update, or remove a file, the generated site is updated automatically.\n</Callout>\n\n## Tips\n\n- **Keep it flat**: For a small number of files, placing them directly in `public` keeps paths short and simple.\n- **Use subdirectories for organization**: For larger projects, group assets into directories like `public/fonts`, `public/images`, or `public/icons`.\n- **Mind file size**: Optimize images before adding them to keep deployment size and load times low.\n- **Consistent naming**: Use lowercase, hyphen-separated filenames (e.g., `og-image.png`) for predictable URLs.";
1
+ export declare const mediaAndAssetsMdxTemplate = "---\ntitle: \"Media and assets\"\ndescription: \"Serve static files like images, favicons, fonts, and Open Graph previews from the public directory.\"\ndate: \"2026-02-19\"\nupdated: \"2026-07-31\"\ncategory: \"Configuration\"\ncategoryOrder: 2\norder: 7\n---\n# Media and assets\n\nDoccupine watches a `public` directory in your project root (the same directory where you execute `npx doccupine`) and copies its contents into the generated Next.js `public` directory. Use it to serve static files such as favicons, Open Graph preview images, custom fonts, or any other media your documentation needs.\n\n## The public directory\n\nCreate a `public` directory at your project root. Any file you place inside is automatically synced to the generated site and served from the root URL path.\n\n```text\nmy-docs/\n\u251C\u2500\u2500 public/\n\u2502 \u251C\u2500\u2500 favicon.ico\n\u2502 \u251C\u2500\u2500 og-image.png\n\u2502 \u251C\u2500\u2500 logo.svg\n\u2502 \u2514\u2500\u2500 fonts/\n\u2502 \u2514\u2500\u2500 custom-font.woff2\n\u251C\u2500\u2500 docs/\n\u2502 \u2514\u2500\u2500 index.mdx\n\u251C\u2500\u2500 config.json\n\u2514\u2500\u2500 theme.json\n```\n\n## How assets are served\n\nFiles in the `public` directory are available at the root of your deployed domain. The path inside `public` maps directly to the URL path.\n\n| File | URL |\n| -------------------------------- | ------------------------------------------------- |\n| `public/favicon.ico` | `https://your-domain.com/favicon.ico` |\n| `public/og-image.png` | `https://your-domain.com/og-image.png` |\n| `public/logo.svg` | `https://your-domain.com/logo.svg` |\n| `public/fonts/custom-font.woff2` | `https://your-domain.com/fonts/custom-font.woff2` |\n\n## Common use cases\n\n### Favicon\n\nDrop a `favicon.ico` into the `public` directory. Browsers pick it up automatically from the root path.\n\n```text\npublic/favicon.ico \u2192 https://your-domain.com/favicon.ico\n```\n\n### Open Graph preview image\n\nAdd an image for link previews on social media. Reference it in your `config.json` so Doccupine sets the correct meta tags.\n\n```text\npublic/og-image.png \u2192 https://your-domain.com/og-image.png\n```\n\n### Custom fonts\n\nPlace font files in `public` and reference them from your `fonts.json`. See the **Fonts** page for full configuration details.\n\n```text\npublic/fonts/custom-font.woff2 \u2192 https://your-domain.com/fonts/custom-font.woff2\n```\n\n### Images and other media\n\nAny image or file you want to reference in your MDX pages can live in `public`. Use a root-relative path in your content:\n\n```mdx\n![Architecture diagram](/architecture.png)\n```\n\n## Live syncing\n\n<Callout type=\"info\">\n Doccupine watches the `public` directory for changes while running. When you add, update, or remove a file, the generated site is updated automatically.\n</Callout>\n\n<Callout type=\"warning\">\n The `public` directory and everything beneath it must use real files and directories. Doccupine rejects symlinks instead of following or copying them, including links whose targets are inside the project.\n</Callout>\n\n## Tips\n\n- **Keep it flat**: For a small number of files, placing them directly in `public` keeps paths short and simple.\n- **Use subdirectories for organization**: For larger projects, group assets into directories like `public/fonts`, `public/images`, or `public/icons`.\n- **Mind file size**: Optimize images before adding them to keep deployment size and load times low.\n- **Consistent naming**: Use lowercase, hyphen-separated filenames (e.g., `og-image.png`) for predictable URLs.";
@@ -2,6 +2,7 @@ export const mediaAndAssetsMdxTemplate = `---
2
2
  title: "Media and assets"
3
3
  description: "Serve static files like images, favicons, fonts, and Open Graph previews from the public directory."
4
4
  date: "2026-02-19"
5
+ updated: "2026-07-31"
5
6
  category: "Configuration"
6
7
  categoryOrder: 2
7
8
  order: 7
@@ -79,6 +80,10 @@ Any image or file you want to reference in your MDX pages can live in \`public\`
79
80
  Doccupine watches the \`public\` directory for changes while running. When you add, update, or remove a file, the generated site is updated automatically.
80
81
  </Callout>
81
82
 
83
+ <Callout type="warning">
84
+ The \`public\` directory and everything beneath it must use real files and directories. Doccupine rejects symlinks instead of following or copying them, including links whose targets are inside the project.
85
+ </Callout>
86
+
82
87
  ## Tips
83
88
 
84
89
  - **Keep it flat**: For a small number of files, placing them directly in \`public\` keeps paths short and simple.