doccupine 0.0.139 → 0.0.140
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.
- package/dist/index.js +6 -7
- package/dist/lib/utils.d.ts +13 -0
- package/dist/lib/utils.js +22 -0
- package/dist/templates/app/api/rag/route.d.ts +1 -1
- package/dist/templates/app/api/rag/route.js +30 -5
- package/dist/templates/components/Chat.d.ts +1 -1
- package/dist/templates/components/Chat.js +69 -70
- package/dist/templates/components/Docs.d.ts +1 -1
- package/dist/templates/components/Docs.js +56 -13
- package/dist/templates/components/layout/ApiPlayground.d.ts +1 -1
- package/dist/templates/components/layout/ApiPlayground.js +4 -7
- package/dist/templates/components/layout/DocsComponents.d.ts +1 -1
- package/dist/templates/components/layout/DocsComponents.js +0 -12
- package/dist/templates/mdx/platform/build-and-deploy.mdx.d.ts +1 -1
- package/dist/templates/mdx/platform/build-and-deploy.mdx.js +1 -1
- package/dist/templates/package.js +1 -1
- package/package.json +1 -1
package/dist/index.js
CHANGED
|
@@ -4,13 +4,12 @@ import chokidar from "chokidar";
|
|
|
4
4
|
import fs from "fs-extra";
|
|
5
5
|
import path from "path";
|
|
6
6
|
import { fileURLToPath } from "url";
|
|
7
|
-
import matter from "gray-matter";
|
|
8
7
|
import chalk from "chalk";
|
|
9
8
|
import { appStructure, obsoleteFiles, startingDocsStructure, } from "./lib/structures.js";
|
|
10
9
|
import { rootLayoutTemplate, siteLayoutTemplate } from "./lib/layout.js";
|
|
11
10
|
import { ConfigManager, normalizeOpenApiConfig } from "./lib/config-manager.js";
|
|
12
11
|
import { OpenApiRegistry, DEFAULT_API_BASE_SLUG, buildEndpointDoc, } from "./lib/openapi.js";
|
|
13
|
-
import { findAvailablePort, generateSlug, getFullSlug, escapeTemplateContent, toJsStringLiteral, resolvePackageManager, } from "./lib/utils.js";
|
|
12
|
+
import { findAvailablePort, generateSlug, getFullSlug, escapeTemplateContent, toJsStringLiteral, resolvePackageManager, safeMatter, } from "./lib/utils.js";
|
|
14
13
|
import { generateMetadataBlock, generateRuntimeOnlyMetadataBlock, generateJsonLdScript, } from "./lib/metadata.js";
|
|
15
14
|
import { parseUpdateBlocks } from "./lib/rss.js";
|
|
16
15
|
import { nextConfigTemplate } from "./templates/next.config.js";
|
|
@@ -245,7 +244,7 @@ class MDXToNextJSGenerator {
|
|
|
245
244
|
for (const file of files) {
|
|
246
245
|
const fullPath = path.join(this.watchDir, file);
|
|
247
246
|
const content = await fs.readFile(fullPath, "utf8");
|
|
248
|
-
const { data: frontmatter } =
|
|
247
|
+
const { data: frontmatter } = safeMatter(content, file);
|
|
249
248
|
if (frontmatter.section) {
|
|
250
249
|
const label = frontmatter.section;
|
|
251
250
|
const order = frontmatter.sectionOrder || 0;
|
|
@@ -697,7 +696,7 @@ class MDXToNextJSGenerator {
|
|
|
697
696
|
async parseMDXFile(file) {
|
|
698
697
|
const fullPath = path.join(this.watchDir, file);
|
|
699
698
|
const content = await fs.readFile(fullPath, "utf8");
|
|
700
|
-
const { data: frontmatter } =
|
|
699
|
+
const { data: frontmatter } = safeMatter(content, file);
|
|
701
700
|
const { sectionSlug, pageSlug } = this.determineSectionForFile(file, frontmatter);
|
|
702
701
|
const fullSlug = getFullSlug(pageSlug, sectionSlug);
|
|
703
702
|
let lastModified;
|
|
@@ -773,7 +772,7 @@ class MDXToNextJSGenerator {
|
|
|
773
772
|
async writePageForFile(filePath) {
|
|
774
773
|
const fullPath = path.join(this.watchDir, filePath);
|
|
775
774
|
const content = await fs.readFile(fullPath, "utf8");
|
|
776
|
-
const { data: frontmatter, content: mdxContent } =
|
|
775
|
+
const { data: frontmatter, content: mdxContent } = safeMatter(content, filePath);
|
|
777
776
|
const { sectionSlug, pageSlug } = this.determineSectionForFile(filePath, frontmatter);
|
|
778
777
|
const fullSlug = getFullSlug(pageSlug, sectionSlug);
|
|
779
778
|
const isIndex = filePath === "index.mdx" || filePath === "./index.mdx";
|
|
@@ -1307,7 +1306,7 @@ export default function Page() {
|
|
|
1307
1306
|
if (file === "index.mdx" || file === "./index.mdx") {
|
|
1308
1307
|
const fullPath = path.join(this.watchDir, file);
|
|
1309
1308
|
const content = await fs.readFile(fullPath, "utf8");
|
|
1310
|
-
const { data: frontmatter, content: mdxContent } =
|
|
1309
|
+
const { data: frontmatter, content: mdxContent } = safeMatter(content, file);
|
|
1311
1310
|
indexMDX = {
|
|
1312
1311
|
content: mdxContent,
|
|
1313
1312
|
title: frontmatter.title || "Welcome",
|
|
@@ -1611,7 +1610,7 @@ export default function Page() {
|
|
|
1611
1610
|
}
|
|
1612
1611
|
const fullPath = path.join(this.watchDir, page.path);
|
|
1613
1612
|
const raw = await fs.readFile(fullPath, "utf8");
|
|
1614
|
-
const { content: body } =
|
|
1613
|
+
const { content: body } = safeMatter(raw, page.path);
|
|
1615
1614
|
return { ...page, body };
|
|
1616
1615
|
}
|
|
1617
1616
|
llmsManifestPath() {
|
package/dist/lib/utils.d.ts
CHANGED
|
@@ -18,6 +18,19 @@ export declare function findAvailablePort(startPort: number): Promise<number>;
|
|
|
18
18
|
export declare function generateSlug(filePath: string): string;
|
|
19
19
|
export declare function getFullSlug(pageSlug: string, sectionSlug: string): string;
|
|
20
20
|
export declare function escapeTemplateContent(content: string): string;
|
|
21
|
+
/**
|
|
22
|
+
* gray-matter that never throws: malformed YAML frontmatter is reported as a
|
|
23
|
+
* warning and the file is treated as having no frontmatter, so one typo in a
|
|
24
|
+
* `---` block can't abort a whole build or site-wide aggregation pass. The
|
|
25
|
+
* broken block is stripped from the body best-effort; an unterminated block
|
|
26
|
+
* passes through as-is and the generated app's MDX error panel absorbs it.
|
|
27
|
+
*/
|
|
28
|
+
export declare function safeMatter(raw: string, label?: string): {
|
|
29
|
+
data: {
|
|
30
|
+
[key: string]: any;
|
|
31
|
+
};
|
|
32
|
+
content: string;
|
|
33
|
+
};
|
|
21
34
|
/**
|
|
22
35
|
* Renders `value` as a JS string literal using the same quote Prettier would
|
|
23
36
|
* choose: double by default, switching to single when that needs fewer escapes
|
package/dist/lib/utils.js
CHANGED
|
@@ -2,6 +2,7 @@ import fs from "fs-extra";
|
|
|
2
2
|
import path from "path";
|
|
3
3
|
import { execSync } from "child_process";
|
|
4
4
|
import chalk from "chalk";
|
|
5
|
+
import matter from "gray-matter";
|
|
5
6
|
/**
|
|
6
7
|
* Locates a usable pnpm binary without relying solely on the caller's PATH.
|
|
7
8
|
* Standalone pnpm installs (e.g. ~/Library/pnpm) expose PNPM_HOME but only add
|
|
@@ -94,6 +95,27 @@ export function escapeTemplateContent(content) {
|
|
|
94
95
|
.replace(/`/g, "\\`")
|
|
95
96
|
.replace(/\$\{/g, "\\${");
|
|
96
97
|
}
|
|
98
|
+
/**
|
|
99
|
+
* gray-matter that never throws: malformed YAML frontmatter is reported as a
|
|
100
|
+
* warning and the file is treated as having no frontmatter, so one typo in a
|
|
101
|
+
* `---` block can't abort a whole build or site-wide aggregation pass. The
|
|
102
|
+
* broken block is stripped from the body best-effort; an unterminated block
|
|
103
|
+
* passes through as-is and the generated app's MDX error panel absorbs it.
|
|
104
|
+
*/
|
|
105
|
+
export function safeMatter(raw, label) {
|
|
106
|
+
try {
|
|
107
|
+
const { data, content } = matter(raw);
|
|
108
|
+
return { data, content };
|
|
109
|
+
}
|
|
110
|
+
catch (error) {
|
|
111
|
+
const where = label ? ` in ${label}` : "";
|
|
112
|
+
console.warn(chalk.yellow(`⚠️ Invalid frontmatter${where}; ignoring it.`), error instanceof Error ? error.message : error);
|
|
113
|
+
return {
|
|
114
|
+
data: {},
|
|
115
|
+
content: raw.replace(/^---\r?\n[\s\S]*?\r?\n---\r?\n?/, ""),
|
|
116
|
+
};
|
|
117
|
+
}
|
|
118
|
+
}
|
|
97
119
|
/**
|
|
98
120
|
* Renders `value` as a JS string literal using the same quote Prettier would
|
|
99
121
|
* choose: double by default, switching to single when that needs fewer escapes
|
|
@@ -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\";\n\nconst messageSchema = z.object({\n role: z.enum([\"user\", \"assistant\"]),\n content: z.string().max(4000),\n});\n\nconst ragSchema = z.object({\n question: z.string().min(1).max(2000),\n history: z.array(messageSchema).max(20).optional(),\n refresh: z.boolean().optional(),\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// 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 // Rate limit by IP\n const ip =\n req.headers.get(\"x-forwarded-for\")?.split(\",\")[0]?.trim() ?? \"unknown\";\n const { allowed, retryAfter } = rateLimit(ip);\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 req.json();\n } catch {\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, refresh } = parsed.data;\n\n let llmConfig;\n try {\n llmConfig = getLLMConfig();\n } catch (error: unknown) {\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\";\n\nconst messageSchema = z.object({\n role: z.enum([\"user\", \"assistant\"]),\n content: z.string().max(4000),\n});\n\nconst ragSchema = z.object({\n question: z.string().min(1).max(2000),\n history: z.array(messageSchema).max(20).optional(),\n refresh: z.boolean().optional(),\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 // Rate limit by IP\n const ip =\n req.headers.get(\"x-forwarded-for\")?.split(\",\")[0]?.trim() ?? \"unknown\";\n const { allowed, retryAfter } = rateLimit(ip);\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 req.json();\n } catch {\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, refresh } = 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\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 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(Boolean(refresh));\n\n // Use MCP search_docs tool to find relevant documentation\n const searchResults = await searchDocs(question, 6);\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);\n for await (const chunk of stream) {\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 safeEnqueue(`data: ${JSON.stringify({ type: \"done\" })}\\n\\n`);\n } catch (error: unknown) {\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 try {\n controller.close();\n } catch {\n // Already closed.\n }\n }\n },\n cancel() {\n streamClosed = true;\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() {\n const status = getIndexStatus();\n return NextResponse.json({\n ready: status.ready,\n chunks: status.chunkCount,\n reason: status.reason,\n });\n}\n";
|
|
@@ -50,6 +50,25 @@ Each context chunk includes a "URL:" line with the pre-computed page URL. Use it
|
|
|
50
50
|
## Greetings & Small Talk
|
|
51
51
|
If the user sends a greeting or non-documentation question, respond briefly and ask how you can help with the documentation.\`;
|
|
52
52
|
|
|
53
|
+
// Maps provider/stream failures to fixed visitor-safe messages. Raw provider
|
|
54
|
+
// errors can include API-key fragments, org ids, and billing URLs, so only
|
|
55
|
+
// these strings ever reach the client; the full error goes to the server log.
|
|
56
|
+
function friendlyLLMError(error: unknown): string {
|
|
57
|
+
const raw = error instanceof Error ? error.message : String(error);
|
|
58
|
+
if (/\\b401\\b|api.?key|authenticat|unauthorized/i.test(raw)) {
|
|
59
|
+
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.";
|
|
60
|
+
}
|
|
61
|
+
if (/\\b429\\b|quota|rate.?limit|billing/i.test(raw)) {
|
|
62
|
+
return "The assistant's model provider is rate limiting requests right now. Please try again in a moment.";
|
|
63
|
+
}
|
|
64
|
+
if (
|
|
65
|
+
/timed?.?out|ETIMEDOUT|ECONNRESET|ENOTFOUND|fetch failed|network/i.test(raw)
|
|
66
|
+
) {
|
|
67
|
+
return "The assistant could not reach its model provider. Please try again.";
|
|
68
|
+
}
|
|
69
|
+
return "The assistant hit an unexpected error. Please try again.";
|
|
70
|
+
}
|
|
71
|
+
|
|
53
72
|
// LangChain + the MCP SDK require the Node.js runtime (not edge).
|
|
54
73
|
export const runtime = "nodejs";
|
|
55
74
|
// Safety net for the streaming function (Vercel-only; ignored elsewhere).
|
|
@@ -90,9 +109,15 @@ export async function POST(req: Request) {
|
|
|
90
109
|
try {
|
|
91
110
|
llmConfig = getLLMConfig();
|
|
92
111
|
} catch (error: unknown) {
|
|
93
|
-
|
|
94
|
-
|
|
95
|
-
return NextResponse.json(
|
|
112
|
+
// Setup details (provider names, env var names) stay in the server log.
|
|
113
|
+
console.error("[doccupine] LLM configuration error:", error);
|
|
114
|
+
return NextResponse.json(
|
|
115
|
+
{
|
|
116
|
+
error:
|
|
117
|
+
"The AI assistant is not configured on this site. If you are the site owner, check the server logs.",
|
|
118
|
+
},
|
|
119
|
+
{ status: 500 },
|
|
120
|
+
);
|
|
96
121
|
}
|
|
97
122
|
|
|
98
123
|
const encoder = new TextEncoder();
|
|
@@ -189,9 +214,9 @@ export async function POST(req: Request) {
|
|
|
189
214
|
|
|
190
215
|
safeEnqueue(\`data: \${JSON.stringify({ type: "done" })}\\n\\n\`);
|
|
191
216
|
} catch (error: unknown) {
|
|
192
|
-
|
|
217
|
+
console.error("[doccupine] RAG stream error:", error);
|
|
193
218
|
safeEnqueue(
|
|
194
|
-
\`data: \${JSON.stringify({ type: "error", data:
|
|
219
|
+
\`data: \${JSON.stringify({ type: "error", data: friendlyLLMError(error) })}\\n\\n\`,
|
|
195
220
|
);
|
|
196
221
|
} finally {
|
|
197
222
|
if (heartbeat) clearInterval(heartbeat);
|
|
@@ -1 +1 @@
|
|
|
1
|
-
export declare const chatTemplate = "\"use client\";\nimport React, {\n createContext,\n useCallback,\n useContext,\n useEffect,\n useRef,\n useState,\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 } from \"@/app/theme\";\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 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 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 transition: all 0.3s ease;\n transform: translateX(0);\n background: ${({ theme }) => theme.colors.light};\n -webkit-overflow-scrolling: touch;\n opacity: 1;\n\n &::-webkit-scrollbar {\n display: none;\n }\n\n ${({ $isVisible }) =>\n !$isVisible &&\n css`\n transform: translateX(100%);\n opacity: 0;\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 transition: all 0.3s ease;\n transform: translateX(100%);\n opacity: 0;\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 `}\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<{ theme: Theme }>`\n overflow-x: auto;\n ${thinScrollbar};\n background: ${({ theme }) => theme.colors.error};\n color: ${({ theme }) => theme.colors.surface};\n padding: 10px;\n border-radius: 8px;\n margin: 20px 0;\n width: 100%;\n ${styledText};\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 endRef = useRef<HTMLDivElement | null>(null);\n\n useLockBodyScroll(isOpen);\n\n useEffect(() => {\n endRef.current?.scrollIntoView({ behavior: \"smooth\", block: \"end\" });\n }, [answer]);\n\n useEffect(() => {\n if (answer?.length > 0) {\n chatInputRef.current?.focus();\n }\n }, [answer, chatInputRef]);\n\n return (\n <>\n <StyledChat $isVisible={isOpen} data-markdown-ignore>\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 <strong>Error:</strong> {error}\n </StyledError>\n )}\n <div ref={endRef} />\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 </>\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) => void;\n closeChat: () => 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: () => {},\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 isOpenRef = useRef(isOpen);\n\n useEffect(() => {\n isOpenRef.current = isOpen;\n }, [isOpen]);\n\n // Open the assistant, seeding a greeting the first time and focusing the\n // input once the panel has slid in (matches the 0.3s panel transition).\n const openChat = useCallback(() => {\n setIsOpen(true);\n setAnswer((prev) =>\n prev.length === 0 ? [{ text: INITIAL_GREETING, answer: true }] : prev,\n );\n setTimeout(() => {\n chatInputRef.current?.focus();\n }, 350);\n }, []);\n\n const toggleChat = useCallback(() => {\n if (isOpenRef.current) {\n setIsOpen(false);\n } else {\n openChat();\n }\n }, [openChat]);\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(currentQuestion: string) {\n setQuestion(\"\");\n setIsOpen(true);\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: \")) {\n try {\n const data = JSON.parse(line.slice(6));\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 } catch (parseError) {\n if (\n parseError instanceof Error &&\n parseError.message !== \"Unknown error\"\n ) {\n console.error(\"Failed to parse SSE data:\", parseError);\n }\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(rawQuestion: string) {\n const trimmed = rawQuestion.trim();\n if (trimmed === \"\") return;\n if (loading) {\n openChat();\n setQuestion(trimmed);\n } else {\n void runQuestion(trimmed);\n }\n }\n\n function closeChat() {\n setIsOpen(false);\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 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 useRef,\n useState,\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 } 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 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 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 transition: all 0.3s ease;\n transform: translateX(0);\n background: ${({ theme }) => theme.colors.light};\n -webkit-overflow-scrolling: touch;\n opacity: 1;\n\n &::-webkit-scrollbar {\n display: none;\n }\n\n ${({ $isVisible }) =>\n !$isVisible &&\n css`\n transform: translateX(100%);\n opacity: 0;\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 transition: all 0.3s ease;\n transform: translateX(100%);\n opacity: 0;\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 `}\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 endRef = useRef<HTMLDivElement | null>(null);\n\n useLockBodyScroll(isOpen);\n\n useEffect(() => {\n endRef.current?.scrollIntoView({ behavior: \"smooth\", block: \"end\" });\n }, [answer]);\n\n useEffect(() => {\n if (answer?.length > 0) {\n chatInputRef.current?.focus();\n }\n }, [answer, chatInputRef]);\n\n return (\n <>\n <StyledChat $isVisible={isOpen} data-markdown-ignore>\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 <div ref={endRef} />\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 </>\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) => void;\n closeChat: () => 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: () => {},\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 isOpenRef = useRef(isOpen);\n\n useEffect(() => {\n isOpenRef.current = isOpen;\n }, [isOpen]);\n\n // Open the assistant, seeding a greeting the first time and focusing the\n // input once the panel has slid in (matches the 0.3s panel transition).\n const openChat = useCallback(() => {\n setIsOpen(true);\n setAnswer((prev) =>\n prev.length === 0 ? [{ text: INITIAL_GREETING, answer: true }] : prev,\n );\n setTimeout(() => {\n chatInputRef.current?.focus();\n }, 350);\n }, []);\n\n const toggleChat = useCallback(() => {\n if (isOpenRef.current) {\n setIsOpen(false);\n } else {\n openChat();\n }\n }, [openChat]);\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(currentQuestion: string) {\n setQuestion(\"\");\n setIsOpen(true);\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(rawQuestion: string) {\n const trimmed = rawQuestion.trim();\n if (trimmed === \"\") return;\n if (loading) {\n openChat();\n setQuestion(trimmed);\n } else {\n void runQuestion(trimmed);\n }\n }\n\n function closeChat() {\n setIsOpen(false);\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 resetChat,\n chatInputRef,\n }}\n >\n {children}\n </ChatContext.Provider>\n );\n};\n\nexport { Chat, ChtProvider, ChatContext, ChatButtonCTA };\n";
|
|
@@ -17,6 +17,7 @@ import { MDXRemote, MDXRemoteSerializeResult } from "next-mdx-remote";
|
|
|
17
17
|
import { serialize } from "next-mdx-remote/serialize";
|
|
18
18
|
import Link from "next/link";
|
|
19
19
|
import { mq, Theme } from "@/app/theme";
|
|
20
|
+
import { Callout } from "@/components/layout/Callout";
|
|
20
21
|
import { useLockBodyScroll } from "@/components/LockBodyScroll";
|
|
21
22
|
import { useMDXComponents as getMDXComponents } from "@/components/MDXComponents";
|
|
22
23
|
import {
|
|
@@ -470,16 +471,9 @@ const StyledGlowSmallButton = styled(StyledSmallButton)<{
|
|
|
470
471
|
\`}
|
|
471
472
|
\`;
|
|
472
473
|
|
|
473
|
-
const StyledError = styled.div
|
|
474
|
-
overflow-x: auto;
|
|
475
|
-
\${thinScrollbar};
|
|
476
|
-
background: \${({ theme }) => theme.colors.error};
|
|
477
|
-
color: \${({ theme }) => theme.colors.surface};
|
|
478
|
-
padding: 10px;
|
|
479
|
-
border-radius: 8px;
|
|
474
|
+
const StyledError = styled.div\`
|
|
480
475
|
margin: 20px 0;
|
|
481
476
|
width: 100%;
|
|
482
|
-
\${styledText};
|
|
483
477
|
\`;
|
|
484
478
|
|
|
485
479
|
const loadingDotAnimation = keyframes\`
|
|
@@ -888,7 +882,11 @@ function Chat() {
|
|
|
888
882
|
)}
|
|
889
883
|
{error && (
|
|
890
884
|
<StyledError>
|
|
891
|
-
<
|
|
885
|
+
<Callout type="danger">
|
|
886
|
+
<p>
|
|
887
|
+
<strong>Error:</strong> {error}
|
|
888
|
+
</p>
|
|
889
|
+
</Callout>
|
|
892
890
|
</StyledError>
|
|
893
891
|
)}
|
|
894
892
|
<div ref={endRef} />
|
|
@@ -1077,69 +1075,70 @@ const ChtProvider = ({ children, isChatActive }: ChatContextProviderProps) => {
|
|
|
1077
1075
|
buffer = parts.pop() ?? "";
|
|
1078
1076
|
|
|
1079
1077
|
for (const line of parts) {
|
|
1080
|
-
if (line.startsWith("data: "))
|
|
1078
|
+
if (!line.startsWith("data: ")) continue;
|
|
1079
|
+
|
|
1080
|
+
// Guard only the parse: a malformed frame is skipped, while the
|
|
1081
|
+
// server's error event below must throw past this loop to the
|
|
1082
|
+
// outer catch so it renders in the chat's error callout instead
|
|
1083
|
+
// of dying in a parse-error log.
|
|
1084
|
+
let data;
|
|
1085
|
+
try {
|
|
1086
|
+
data = JSON.parse(line.slice(6));
|
|
1087
|
+
} catch {
|
|
1088
|
+
console.error("Failed to parse SSE data:", line);
|
|
1089
|
+
continue;
|
|
1090
|
+
}
|
|
1091
|
+
|
|
1092
|
+
if (data.type === "metadata") {
|
|
1093
|
+
const allSources: Source[] = data.data?.sources ?? [];
|
|
1094
|
+
const seen = new Set<string>();
|
|
1095
|
+
sources = allSources.filter((s: Source) => {
|
|
1096
|
+
if (s.score < 0.4 || seen.has(s.uri)) return false;
|
|
1097
|
+
seen.add(s.uri);
|
|
1098
|
+
return true;
|
|
1099
|
+
});
|
|
1100
|
+
} else if (data.type === "content") {
|
|
1101
|
+
contentParts.push(data.data);
|
|
1102
|
+
const streamedContent = contentParts.join("");
|
|
1103
|
+
|
|
1104
|
+
setAnswer((prev) => {
|
|
1105
|
+
const newAnswers = [...prev];
|
|
1106
|
+
newAnswers[streamingAnswerIndex] = {
|
|
1107
|
+
text: streamedContent,
|
|
1108
|
+
answer: true,
|
|
1109
|
+
sources,
|
|
1110
|
+
};
|
|
1111
|
+
return newAnswers;
|
|
1112
|
+
});
|
|
1113
|
+
} else if (data.type === "error") {
|
|
1114
|
+
throw new Error(data.data);
|
|
1115
|
+
} else if (data.type === "done") {
|
|
1116
|
+
const streamedContent = contentParts.join("");
|
|
1117
|
+
let mdxSource: MDXRemoteSerializeResult | null = null;
|
|
1081
1118
|
try {
|
|
1082
|
-
|
|
1083
|
-
|
|
1084
|
-
|
|
1085
|
-
|
|
1086
|
-
|
|
1087
|
-
|
|
1088
|
-
|
|
1089
|
-
|
|
1090
|
-
|
|
1091
|
-
|
|
1092
|
-
|
|
1093
|
-
contentParts.push(data.data);
|
|
1094
|
-
const streamedContent = contentParts.join("");
|
|
1095
|
-
|
|
1096
|
-
setAnswer((prev) => {
|
|
1097
|
-
const newAnswers = [...prev];
|
|
1098
|
-
newAnswers[streamingAnswerIndex] = {
|
|
1099
|
-
text: streamedContent,
|
|
1100
|
-
answer: true,
|
|
1101
|
-
sources,
|
|
1102
|
-
};
|
|
1103
|
-
return newAnswers;
|
|
1104
|
-
});
|
|
1105
|
-
} else if (data.type === "error") {
|
|
1106
|
-
throw new Error(data.data);
|
|
1107
|
-
} else if (data.type === "done") {
|
|
1108
|
-
const streamedContent = contentParts.join("");
|
|
1109
|
-
let mdxSource: MDXRemoteSerializeResult | null = null;
|
|
1110
|
-
try {
|
|
1111
|
-
mdxSource = await serialize(streamedContent, {
|
|
1112
|
-
parseFrontmatter: false,
|
|
1113
|
-
mdxOptions: {
|
|
1114
|
-
remarkPlugins: [remarkGfm],
|
|
1115
|
-
rehypePlugins: [rehypeHighlight],
|
|
1116
|
-
format: "md",
|
|
1117
|
-
development: false,
|
|
1118
|
-
},
|
|
1119
|
-
});
|
|
1120
|
-
} catch (mdxError: unknown) {
|
|
1121
|
-
console.error("MDX serialization error:", mdxError);
|
|
1122
|
-
}
|
|
1123
|
-
|
|
1124
|
-
setAnswer((prev) => {
|
|
1125
|
-
const newAnswers = [...prev];
|
|
1126
|
-
newAnswers[streamingAnswerIndex] = {
|
|
1127
|
-
text: streamedContent,
|
|
1128
|
-
answer: true,
|
|
1129
|
-
mdx: mdxSource || undefined,
|
|
1130
|
-
sources,
|
|
1131
|
-
};
|
|
1132
|
-
return newAnswers;
|
|
1133
|
-
});
|
|
1134
|
-
}
|
|
1135
|
-
} catch (parseError) {
|
|
1136
|
-
if (
|
|
1137
|
-
parseError instanceof Error &&
|
|
1138
|
-
parseError.message !== "Unknown error"
|
|
1139
|
-
) {
|
|
1140
|
-
console.error("Failed to parse SSE data:", parseError);
|
|
1141
|
-
}
|
|
1119
|
+
mdxSource = await serialize(streamedContent, {
|
|
1120
|
+
parseFrontmatter: false,
|
|
1121
|
+
mdxOptions: {
|
|
1122
|
+
remarkPlugins: [remarkGfm],
|
|
1123
|
+
rehypePlugins: [rehypeHighlight],
|
|
1124
|
+
format: "md",
|
|
1125
|
+
development: false,
|
|
1126
|
+
},
|
|
1127
|
+
});
|
|
1128
|
+
} catch (mdxError: unknown) {
|
|
1129
|
+
console.error("MDX serialization error:", mdxError);
|
|
1142
1130
|
}
|
|
1131
|
+
|
|
1132
|
+
setAnswer((prev) => {
|
|
1133
|
+
const newAnswers = [...prev];
|
|
1134
|
+
newAnswers[streamingAnswerIndex] = {
|
|
1135
|
+
text: streamedContent,
|
|
1136
|
+
answer: true,
|
|
1137
|
+
mdx: mdxSource || undefined,
|
|
1138
|
+
sources,
|
|
1139
|
+
};
|
|
1140
|
+
return newAnswers;
|
|
1141
|
+
});
|
|
1143
1142
|
}
|
|
1144
1143
|
}
|
|
1145
1144
|
}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
export declare const docsTemplate = "import React from \"react\";\nimport { Flex } from \"cherry-styled-components\";\nimport {\n DocsContainer,\n StyledMarkdownContainer,\n
|
|
1
|
+
export declare const docsTemplate = "import React from \"react\";\nimport { Flex } from \"cherry-styled-components\";\nimport {\n DocsContainer,\n StyledMarkdownContainer,\n} from \"@/components/layout/DocsComponents\";\nimport { Callout } from \"@/components/layout/Callout\";\nimport { compileMDX } from \"next-mdx-remote/rsc\";\nimport remarkGfm from \"remark-gfm\";\nimport { useMDXComponents } from \"@/components/MDXComponents\";\nimport { createMermaidPre } from \"@/components/MermaidPre\";\nimport { DocsSideBar } from \"@/components/DocsSideBar\";\nimport { ActionBar } from \"@/components/layout/ActionBar\";\nimport { ApiPlaygroundDemo } from \"@/components/layout/ApiPlaygroundDemo\";\nimport { createSlugger } from \"@/components/layout/Slug\";\nimport { rehypeCodeMeta } from \"@/utils/rehypeCodeMeta\";\n\ninterface DocsProps {\n content: string;\n sourcePath?: string;\n // Path of this page's RSS feed; when set, the action bar shows an RSS\n // button linking to it.\n rssHref?: string;\n // Extra content rendered inside the markdown column, after the MDX body.\n // Used to place generated widgets (e.g. the API playground) inside the docs\n // content area rather than outside its layout.\n children?: React.ReactNode;\n}\n\ninterface Heading {\n id: string;\n text: string;\n level: number;\n}\n\nfunction extractHeadings(content: string): Heading[] {\n const contentWithoutCodeBlocks = content.replace(/```[\\s\\S]*?```/g, \"\");\n const entries: { text: string; level: number; position: number }[] = [];\n let match;\n\n // Markdown headings (# .. ######)\n const headingRegex = /^(#{1,6})\\s+(.+)$/gm;\n while ((match = headingRegex.exec(contentWithoutCodeBlocks)) !== null) {\n const level = match[1].length;\n const text = match[2].trim();\n entries.push({ text, level, position: match.index });\n }\n\n // <Update label=\"...\"> blocks surface their label as a top-level entry\n const updateRegex = /<Update\\b[^>]*?\\blabel=[\"']([^\"']+)[\"'][^>]*>/g;\n while ((match = updateRegex.exec(contentWithoutCodeBlocks)) !== null) {\n entries.push({ text: match[1].trim(), level: 1, position: match.index });\n }\n\n // Assign ids in document order with a shared slugger so repeated heading\n // text produces unique anchors (\"setup\", \"setup-1\", ...) that stay in sync\n // with the ids rendered by MDXComponents/Update.\n const slug = createSlugger();\n return entries\n .sort((a, b) => a.position - b.position)\n .map(({ text, level }) => ({ id: slug(text), text, level }));\n}\n\nfunction extractComponentNames(source: string): string[] {\n const stripped = source\n .replace(/```[\\s\\S]*?```/g, \"\")\n .replace(/`[^`]*`/g, \"\");\n const tagRegex = /<([A-Z][a-zA-Z0-9]*)/g;\n const names = new Set<string>();\n let match;\n while ((match = tagRegex.exec(stripped)) !== null) {\n names.add(match[1]);\n }\n return Array.from(names);\n}\n\nfunction MissingComponent({\n componentName,\n children: _children,\n}: {\n componentName: string;\n children?: React.ReactNode;\n}) {\n return (\n <Callout type=\"danger\">\n <p>Missing component: <{componentName} /></p>\n </Callout>\n );\n}\n\ninterface MdxBodyProps {\n source: string;\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n components: Record<string, React.ComponentType<any>>;\n sourcePath?: string;\n}\n\n// Compiles the MDX body inside a try/catch so an authoring mistake (an\n// orphaned closing tag, a stray {expression}) renders an inline error panel\n// instead of throwing during static prerender - a broken page must never\n// fail `next build` for the rest of the site.\nasync function MdxBody({ source, components, sourcePath }: MdxBodyProps) {\n try {\n const { content } = await compileMDX({\n source,\n options: {\n blockJS: false,\n mdxOptions: {\n remarkPlugins: [remarkGfm],\n rehypePlugins: [rehypeCodeMeta],\n },\n },\n components,\n });\n // JS expressions in the body only run when the compiled component\n // renders, which would escape this try/catch and still fail the build.\n // The compiled component is a plain sync function, so invoke it once\n // here to surface those errors (a {placeholder} typo, for example).\n if (typeof content.type === \"function\") {\n await (content.type as React.FC<unknown>)(content.props);\n }\n return content;\n } catch (error) {\n const message = error instanceof Error ? error.message : String(error);\n const where = sourcePath ? ` in ${sourcePath}` : \"\";\n console.error(`[doccupine] MDX error${where}:`, message);\n return (\n <Callout type=\"danger\">\n <p>\n <strong>This page has an MDX error{where}.</strong> The rest of the\n site still builds and renders. Fix the syntax below and save the file\n to rebuild this page.\n </p>\n <pre>{message}</pre>\n </Callout>\n );\n }\n}\n\nfunction Docs({ content, sourcePath, rssHref, children }: DocsProps) {\n const components = useMDXComponents({\n pre: createMermaidPre(sourcePath),\n ApiPlaygroundDemo,\n });\n\n const knownNames = Object.keys(components);\n const usedNames = extractComponentNames(content);\n const missingNames = usedNames.filter((name) => !knownNames.includes(name));\n\n // A <SidePanel> takes over the right rail, so the table of contents that\n // normally lives there is dropped for that page. extractComponentNames\n // ignores code blocks, so a panel shown only as a code sample never counts.\n const hasSidePanel = usedNames.includes(\"SidePanel\");\n const headings = hasSidePanel ? [] : extractHeadings(content);\n\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n const stubs: Record<string, React.ComponentType<any>> = {};\n for (const name of missingNames) {\n stubs[name] = ({ children }: { children?: React.ReactNode }) => (\n <MissingComponent componentName={name}>{children}</MissingComponent>\n );\n }\n\n const allComponents = { ...components, ...stubs };\n\n return (\n <>\n <DocsContainer>\n <ActionBar content={content} rssHref={rssHref}>\n <Flex $gap={20}>\n <StyledMarkdownContainer>\n {children}\n {content && (\n <MdxBody\n source={content}\n components={allComponents}\n sourcePath={sourcePath}\n />\n )}\n </StyledMarkdownContainer>\n </Flex>\n </ActionBar>\n </DocsContainer>\n {!hasSidePanel && <DocsSideBar headings={headings} />}\n </>\n );\n}\n\nexport { Docs };\n";
|
|
@@ -3,9 +3,9 @@ import { Flex } from "cherry-styled-components";
|
|
|
3
3
|
import {
|
|
4
4
|
DocsContainer,
|
|
5
5
|
StyledMarkdownContainer,
|
|
6
|
-
StyledMissingComponent,
|
|
7
6
|
} from "@/components/layout/DocsComponents";
|
|
8
|
-
import {
|
|
7
|
+
import { Callout } from "@/components/layout/Callout";
|
|
8
|
+
import { compileMDX } from "next-mdx-remote/rsc";
|
|
9
9
|
import remarkGfm from "remark-gfm";
|
|
10
10
|
import { useMDXComponents } from "@/components/MDXComponents";
|
|
11
11
|
import { createMermaidPre } from "@/components/MermaidPre";
|
|
@@ -82,12 +82,61 @@ function MissingComponent({
|
|
|
82
82
|
children?: React.ReactNode;
|
|
83
83
|
}) {
|
|
84
84
|
return (
|
|
85
|
-
<
|
|
86
|
-
Missing component: <{componentName} />
|
|
87
|
-
</
|
|
85
|
+
<Callout type="danger">
|
|
86
|
+
<p>Missing component: <{componentName} /></p>
|
|
87
|
+
</Callout>
|
|
88
88
|
);
|
|
89
89
|
}
|
|
90
90
|
|
|
91
|
+
interface MdxBodyProps {
|
|
92
|
+
source: string;
|
|
93
|
+
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
|
94
|
+
components: Record<string, React.ComponentType<any>>;
|
|
95
|
+
sourcePath?: string;
|
|
96
|
+
}
|
|
97
|
+
|
|
98
|
+
// Compiles the MDX body inside a try/catch so an authoring mistake (an
|
|
99
|
+
// orphaned closing tag, a stray {expression}) renders an inline error panel
|
|
100
|
+
// instead of throwing during static prerender - a broken page must never
|
|
101
|
+
// fail \`next build\` for the rest of the site.
|
|
102
|
+
async function MdxBody({ source, components, sourcePath }: MdxBodyProps) {
|
|
103
|
+
try {
|
|
104
|
+
const { content } = await compileMDX({
|
|
105
|
+
source,
|
|
106
|
+
options: {
|
|
107
|
+
blockJS: false,
|
|
108
|
+
mdxOptions: {
|
|
109
|
+
remarkPlugins: [remarkGfm],
|
|
110
|
+
rehypePlugins: [rehypeCodeMeta],
|
|
111
|
+
},
|
|
112
|
+
},
|
|
113
|
+
components,
|
|
114
|
+
});
|
|
115
|
+
// JS expressions in the body only run when the compiled component
|
|
116
|
+
// renders, which would escape this try/catch and still fail the build.
|
|
117
|
+
// The compiled component is a plain sync function, so invoke it once
|
|
118
|
+
// here to surface those errors (a {placeholder} typo, for example).
|
|
119
|
+
if (typeof content.type === "function") {
|
|
120
|
+
await (content.type as React.FC<unknown>)(content.props);
|
|
121
|
+
}
|
|
122
|
+
return content;
|
|
123
|
+
} catch (error) {
|
|
124
|
+
const message = error instanceof Error ? error.message : String(error);
|
|
125
|
+
const where = sourcePath ? \` in \${sourcePath}\` : "";
|
|
126
|
+
console.error(\`[doccupine] MDX error\${where}:\`, message);
|
|
127
|
+
return (
|
|
128
|
+
<Callout type="danger">
|
|
129
|
+
<p>
|
|
130
|
+
<strong>This page has an MDX error{where}.</strong> The rest of the
|
|
131
|
+
site still builds and renders. Fix the syntax below and save the file
|
|
132
|
+
to rebuild this page.
|
|
133
|
+
</p>
|
|
134
|
+
<pre>{message}</pre>
|
|
135
|
+
</Callout>
|
|
136
|
+
);
|
|
137
|
+
}
|
|
138
|
+
}
|
|
139
|
+
|
|
91
140
|
function Docs({ content, sourcePath, rssHref, children }: DocsProps) {
|
|
92
141
|
const components = useMDXComponents({
|
|
93
142
|
pre: createMermaidPre(sourcePath),
|
|
@@ -122,16 +171,10 @@ function Docs({ content, sourcePath, rssHref, children }: DocsProps) {
|
|
|
122
171
|
<StyledMarkdownContainer>
|
|
123
172
|
{children}
|
|
124
173
|
{content && (
|
|
125
|
-
<
|
|
174
|
+
<MdxBody
|
|
126
175
|
source={content}
|
|
127
|
-
options={{
|
|
128
|
-
blockJS: false,
|
|
129
|
-
mdxOptions: {
|
|
130
|
-
remarkPlugins: [remarkGfm],
|
|
131
|
-
rehypePlugins: [rehypeCodeMeta],
|
|
132
|
-
},
|
|
133
|
-
}}
|
|
134
176
|
components={allComponents}
|
|
177
|
+
sourcePath={sourcePath}
|
|
135
178
|
/>
|
|
136
179
|
)}
|
|
137
180
|
</StyledMarkdownContainer>
|
|
@@ -1 +1 @@
|
|
|
1
|
-
export declare const apiPlaygroundTemplate = "\"use client\";\nimport React, { useCallback, useMemo, useRef, useState } from \"react\";\nimport styled, { css } from \"styled-components\";\nimport {\n styledSmall,\n interactiveStyles,\n Input,\n Textarea,\n Modal,\n} from \"cherry-styled-components\";\nimport { mq, Theme } from \"@/app/theme\";\nimport { Code, CodeTabs } from \"@/components/layout/Code\";\nimport { Icon } from \"@/components/layout/Icon\";\nimport { Accordion } from \"@/components/layout/Accordion\";\nimport { Badge, httpMethodBadgeColor } from \"@/components/layout/Badge\";\nimport { CopyButton } from \"@/components/layout/CopyButton\";\nimport { Spinner } from \"@/components/Spinner\";\nimport { matchAllowlist, matchAllowlistIn } from \"@/utils/playgroundAllowlist\";\nimport type { AllowlistEntry } from \"@/utils/playgroundAllowlist\";\nimport { buildSnippets } from \"@/utils/apiSnippets\";\nimport type { SnippetLanguage } from \"@/utils/apiSnippets\";\nimport type {\n OperationDescriptor,\n ParameterDescriptor,\n ServerDescriptor,\n} from \"@/types/openapi\";\n\ninterface PlaygroundResponse {\n status: number;\n statusText: string;\n headers: Record<string, string>;\n contentType: string | null;\n bodyEncoding: \"utf8\" | \"base64\";\n body: string;\n truncated: boolean;\n byteLength: number;\n durationMs: number;\n}\n\ninterface BuiltRequest {\n url: string;\n headers: Record<string, string>;\n body: string | null;\n secretHeaderNames: string[];\n}\n\nexport interface ApiPlaygroundProps {\n operation: OperationDescriptor;\n defaultMode?: \"proxy\" | \"direct\";\n allowDirect?: boolean;\n // Extra client-side allowlist entries. The server proxy always enforces the\n // build-time allowlist regardless; this only relaxes the client pre-flight\n // (used by the docs demo to run in direct mode without a configured spec).\n allowlist?: AllowlistEntry[];\n snippetLanguages?: SnippetLanguage[];\n}\n\nfunction schemaTypeLabel(schema: unknown): string {\n if (schema && typeof schema === \"object\") {\n const record = schema as { type?: unknown; format?: unknown };\n if (typeof record.type === \"string\") {\n return typeof record.format === \"string\"\n ? record.type + \" (\" + record.format + \")\"\n : record.type;\n }\n }\n return \"string\";\n}\n\nfunction serverBase(server: ServerDescriptor | undefined): string {\n if (!server) return \"\";\n let url = server.url;\n const variables = server.variables;\n if (variables) {\n for (const key of Object.keys(variables)) {\n url = url.split(\"{\" + key + \"}\").join(variables[key].default);\n }\n }\n while (url.endsWith(\"/\")) url = url.slice(0, -1);\n return url;\n}\n\nfunction applyPathParams(\n template: string,\n values: Record<string, string>,\n): string {\n let result = template;\n for (const key of Object.keys(values)) {\n result = result\n .split(\"{\" + key + \"}\")\n .join(encodeURIComponent(values[key]));\n }\n return result;\n}\n\nfunction firstJsonExample(op: OperationDescriptor): {\n contentType: string;\n text: string;\n} | null {\n if (!op.requestBody || op.requestBody.content.length === 0) return null;\n const media =\n op.requestBody.content.find((m) => m.contentType.includes(\"json\")) ??\n op.requestBody.content[0];\n let text = \"\";\n if (media.example !== undefined) {\n try {\n text = JSON.stringify(media.example, null, 2);\n } catch {\n text = \"\";\n }\n }\n return { contentType: media.contentType, text };\n}\n\nfunction classifyResponse(\n contentType: string | null,\n): \"image\" | \"video\" | \"audio\" | \"text\" | \"binary\" {\n if (!contentType) return \"text\";\n const t = contentType.toLowerCase();\n if (t.startsWith(\"image/\") && !t.includes(\"svg\")) return \"image\";\n if (t.startsWith(\"video/\")) return \"video\";\n if (t.startsWith(\"audio/\")) return \"audio\";\n if (\n t.includes(\"json\") ||\n t.startsWith(\"text/\") ||\n t.includes(\"xml\") ||\n t.includes(\"svg\") ||\n t.includes(\"html\") ||\n t.includes(\"javascript\") ||\n t.includes(\"csv\")\n ) {\n return \"text\";\n }\n return \"binary\";\n}\n\nfunction codeLanguage(contentType: string | null): string {\n if (!contentType) return \"text\";\n const t = contentType.toLowerCase();\n if (t.includes(\"json\")) return \"json\";\n if (t.includes(\"html\")) return \"html\";\n if (t.includes(\"xml\") || t.includes(\"svg\")) return \"xml\";\n if (t.includes(\"javascript\")) return \"javascript\";\n return \"text\";\n}\n\nfunction prettyBody(contentType: string | null, body: string): string {\n if (contentType && contentType.toLowerCase().includes(\"json\")) {\n try {\n return JSON.stringify(JSON.parse(body), null, 2);\n } catch {\n return body;\n }\n }\n return body;\n}\n\nfunction bufferToBase64(buffer: ArrayBuffer): string {\n let binary = \"\";\n const bytes = new Uint8Array(buffer);\n const chunk = 0x8000;\n for (let i = 0; i < bytes.length; i += chunk) {\n binary += String.fromCharCode(...bytes.subarray(i, i + chunk));\n }\n return btoa(binary);\n}\n\nfunction renderPath(path: string): React.ReactNode {\n return path\n .split(/(\\{[^}]+\\})/g)\n .map((part, index) =>\n part.startsWith(\"{\") ? (\n <PathParam key={index}>{part}</PathParam>\n ) : (\n <span key={index}>{part}</span>\n ),\n );\n}\n\nconst LOCATIONS: ParameterDescriptor[\"in\"][] = [\n \"path\",\n \"query\",\n \"header\",\n \"cookie\",\n];\n\nconst LOCATION_TITLES: Record<string, string> = {\n path: \"Path\",\n query: \"Query\",\n header: \"Headers\",\n cookie: \"Cookies\",\n};\n\n/* ---------- compact bar ---------- */\n\nconst CompactBar = styled.div`\n display: flex;\n align-items: center;\n gap: 10px;\n margin: 0;\n padding: 8px 8px 8px 12px;\n border: solid 1px ${({ theme }: { theme: Theme }) => theme.colors.grayLight};\n border-radius: ${({ theme }: { theme: Theme }) => theme.spacing.radius.lg};\n background: ${({ theme }: { theme: Theme }) => theme.colors.light};\n`;\n\n// The method chip is Badge's mono+solid variation; only bar-layout metrics\n// are adjusted here.\nconst MethodBadge = styled(Badge)`\n flex-shrink: 0;\n padding: 0 4px;\n border: none;\n`;\n\nconst PathText = styled.span`\n flex: 1;\n min-width: 0;\n font-family: ${({ theme }: { theme: Theme }) => theme.fonts.mono};\n font-weight: 600;\n font-size: 14px;\n color: ${({ theme }: { theme: Theme }) => theme.colors.dark};\n overflow-x: auto;\n white-space: nowrap;\n &::-webkit-scrollbar {\n display: none;\n }\n`;\n\nconst PathParam = styled.span`\n font-family: ${({ theme }: { theme: Theme }) => theme.fonts.mono};\n background: ${({ theme }: { theme: Theme }) =>\n `color-mix(in srgb, ${theme.colors.primaryLight} 20%, transparent)`};\n color: ${({ theme }: { theme: Theme }) => theme.colors.dark};\n padding: 2px 4px;\n border-radius: ${({ theme }: { theme: Theme }) => theme.spacing.radius.xs};\n overflow-wrap: anywhere;\n`;\n\nconst AccentButton = styled.button<{ theme: Theme }>`\n cursor: pointer;\n display: inline-flex;\n align-items: center;\n gap: 6px;\n flex-shrink: 0;\n font-family: ${({ theme }: { theme: Theme }) => theme.fonts.text};\n font-weight: 600;\n font-size: 14px;\n color: ${({ theme }: { theme: Theme }) => theme.colors.surface};\n background: ${({ theme }: { theme: Theme }) => theme.colors.primary};\n border: none;\n padding: 8px 14px;\n border-radius: ${({ theme }: { theme: Theme }) => theme.spacing.radius.xs};\n ${interactiveStyles};\n\n & svg {\n color: ${({ theme }: { theme: Theme }) => theme.colors.surface};\n stroke: ${({ theme }: { theme: Theme }) => theme.colors.surface};\n }\n\n &:hover {\n background: ${({ theme }: { theme: Theme }) => theme.colors.primaryDark};\n }\n &:disabled {\n opacity: 0.6;\n cursor: default;\n }\n`;\n\n/* ---------- modal ---------- */\n\nconst DialogHeader = styled.div`\n display: flex;\n align-items: center;\n gap: 10px;\n flex-wrap: wrap;\n margin: 5px 0 0 0;\n`;\n\nconst PathBar = styled.div`\n flex: 1;\n min-width: 200px;\n display: flex;\n align-items: center;\n gap: 8px;\n padding: 8px 8px 8px 12px;\n border: solid 1px ${({ theme }: { theme: Theme }) => theme.colors.grayLight};\n border-radius: ${({ theme }: { theme: Theme }) => theme.spacing.radius.xs};\n background: ${({ theme }: { theme: Theme }) => theme.colors.light};\n`;\n\nconst DialogBody = styled.div`\n display: grid;\n grid-template-columns: 1fr;\n gap: 20px;\n padding: 0;\n margin: 20px 0 0 0;\n\n ${mq(\"lg\")} {\n grid-template-columns: 1fr 1fr;\n }\n`;\n\nconst Column = styled.div`\n display: flex;\n flex-direction: column;\n gap: 20px;\n min-width: 0;\n`;\n\nconst Description = styled.p`\n margin: 0;\n ${({ theme }: { theme: Theme }) => styledSmall(theme)};\n color: ${({ theme }: { theme: Theme }) => theme.colors.grayDark};\n`;\n\nconst Toolbar = styled.div`\n display: flex;\n align-items: center;\n gap: 8px;\n flex-wrap: wrap;\n`;\n\nconst Toggle = styled.button<{ theme: Theme; $active?: boolean }>`\n position: relative;\n cursor: pointer;\n text-decoration: none;\n font-size: ${({ theme }) => theme.fontSizes.small.lg};\n line-height: 1;\n color: ${({ theme }) => theme.colors.accent};\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: none;\n border-radius: ${({ theme }) => theme.spacing.radius.xs};\n ${interactiveStyles};\n\n ${({ $active, theme }) =>\n $active &&\n css`\n background: ${theme.colors.primary};\n color: ${theme.colors.surface};\n `}\n`;\n\n/* ---------- collapsible card ---------- */\n\nconst Card = styled.div`\n border: solid 1px ${({ theme }: { theme: Theme }) => theme.colors.grayLight};\n border-radius: ${({ theme }: { theme: Theme }) => theme.spacing.radius.lg};\n overflow: hidden;\n`;\n\nconst CardHead = styled.button`\n cursor: pointer;\n width: 100%;\n display: flex;\n align-items: center;\n justify-content: space-between;\n gap: 8px;\n padding: 12px 20px;\n border: none;\n background: transparent;\n color: ${({ theme }: { theme: Theme }) => theme.colors.dark};\n ${({ theme }: { theme: Theme }) => styledSmall(theme)};\n`;\n\nconst Inline = styled.span`\n display: inline-flex;\n align-items: center;\n gap: 8px;\n`;\n\nconst CardBody = styled.div`\n padding: 0 20px 20px;\n display: flex;\n flex-direction: column;\n gap: 16px;\n`;\n\n/* ---------- fields ---------- */\n\n// Wraps an accordion section's content and insets it, so full-width inputs'\n// focus rings (a 4px box-shadow) are not clipped by the accordion's own\n// overflow. Keeps the accordion component untouched.\nconst SectionInner = styled.div`\n display: flex;\n flex-direction: column;\n gap: 16px;\n padding: 4px;\n`;\n\nconst Field = styled.div`\n display: flex;\n flex-direction: column;\n gap: 6px;\n`;\n\nconst FieldHead = styled.div`\n display: flex;\n align-items: center;\n gap: 8px;\n flex-wrap: wrap;\n ${({ theme }: { theme: Theme }) => styledSmall(theme)};\n`;\n\nconst FieldName = styled.span`\n font-family: ${({ theme }: { theme: Theme }) => theme.fonts.mono};\n font-weight: 600;\n color: ${({ theme }: { theme: Theme }) => theme.colors.dark};\n`;\n\nconst TypeChip = styled.span`\n font-family: ${({ theme }: { theme: Theme }) => theme.fonts.mono};\n color: ${({ theme }: { theme: Theme }) => theme.colors.grayDark};\n background: ${({ theme }: { theme: Theme }) =>\n `color-mix(in srgb, ${theme.colors.gray} 15%, transparent)`};\n padding: 0 4px;\n border-radius: ${({ theme }: { theme: Theme }) => theme.spacing.radius.xs};\n`;\n\nconst RequiredChip = styled.span`\n font-family: ${({ theme }: { theme: Theme }) => theme.fonts.mono};\n color: ${({ theme }: { theme: Theme }) => theme.colors.error};\n`;\n\nconst FieldDesc = styled.p`\n margin: 0;\n width: 100%;\n ${({ theme }: { theme: Theme }) => styledSmall(theme)};\n color: ${({ theme }: { theme: Theme }) => theme.colors.gray};\n`;\n\n/* ---------- response ---------- */\n\nconst StatusPill = styled.span<{ theme: Theme; $ok: boolean }>`\n font-family: ${({ theme }) => theme.fonts.mono};\n font-weight: 700;\n color: ${({ theme }) => theme.colors.surface};\n background: ${({ theme, $ok }) =>\n $ok ? theme.colors.success : theme.colors.error};\n padding: 0 4px;\n border-radius: ${({ theme }) => theme.spacing.radius.xs};\n`;\n\nconst Meta = styled.span`\n ${({ theme }: { theme: Theme }) => styledSmall(theme)};\n color: ${({ theme }: { theme: Theme }) => theme.colors.gray};\n`;\n\nconst ErrorText = styled.p`\n margin: 0;\n ${({ theme }: { theme: Theme }) => styledSmall(theme)};\n color: ${({ theme }: { theme: Theme }) => theme.colors.error};\n`;\n\nconst Placeholder = styled.div`\n border: dashed 1px ${({ theme }: { theme: Theme }) => theme.colors.grayLight};\n border-radius: ${({ theme }: { theme: Theme }) => theme.spacing.radius.lg};\n padding: 24px;\n min-height: 120px;\n display: flex;\n align-items: center;\n justify-content: center;\n gap: 10px;\n text-align: center;\n ${({ theme }: { theme: Theme }) => styledSmall(theme)};\n color: ${({ theme }: { theme: Theme }) => theme.colors.gray};\n`;\n\n// Holds the response (or empty placeholder) and lets the loading spinner sit on\n// top of it, so a re-send keeps the previous content in place instead of\n// collapsing and jumping the layout.\nconst ResponseArea = styled.div`\n position: relative;\n`;\n\nconst LoadingOverlay = styled.div`\n position: absolute;\n inset: 0;\n z-index: 1;\n display: flex;\n align-items: center;\n justify-content: center;\n border: solid 1px ${({ theme }: { theme: Theme }) => theme.colors.grayLight};\n border-radius: ${({ theme }: { theme: Theme }) => theme.spacing.radius.lg};\n color: ${({ theme }: { theme: Theme }) => theme.colors.grayDark};\n background: ${({ theme }: { theme: Theme }) =>\n `color-mix(in srgb, ${theme.colors.light} 60%, transparent)`};\n backdrop-filter: blur(1px);\n`;\n\nconst ResponseMedia = styled.img`\n max-width: 100%;\n border-radius: ${({ theme }: { theme: Theme }) => theme.spacing.radius.xs};\n`;\n\nexport function ApiPlayground({\n operation,\n defaultMode = \"proxy\",\n allowDirect = true,\n allowlist,\n snippetLanguages = [\"curl\", \"javascript\", \"python\"],\n}: ApiPlaygroundProps) {\n const [open, setOpen] = useState(false);\n const [paramValues, setParamValues] = useState<Record<string, string>>({});\n const [authValues, setAuthValues] = useState<Record<string, string>>({});\n const initialBody = useMemo(() => firstJsonExample(operation), [operation]);\n const [bodyText, setBodyText] = useState(initialBody?.text ?? \"\");\n const [mode, setMode] = useState<\"proxy\" | \"direct\">(defaultMode);\n const [showSecrets, setShowSecrets] = useState(false);\n const [loading, setLoading] = useState(false);\n const [response, setResponse] = useState<PlaygroundResponse | null>(null);\n const [error, setError] = useState<string | null>(null);\n const [corsRetry, setCorsRetry] = useState(false);\n const abortRef = useRef<AbortController | null>(null);\n\n const paramKey = (p: ParameterDescriptor) => p.in + \":\" + p.name;\n\n const isAllowed = useCallback(\n (url: string) =>\n Boolean(\n matchAllowlist(url) ??\n (allowlist ? matchAllowlistIn(allowlist, url) : null),\n ),\n [allowlist],\n );\n\n const buildRequest = useCallback((): BuiltRequest => {\n const base = serverBase(operation.servers[0]);\n const pathValues: Record<string, string> = {};\n const queryParts: string[] = [];\n const headers: Record<string, string> = {};\n const secretHeaderNames: string[] = [];\n let cookie = \"\";\n\n for (const param of operation.parameters) {\n const value = paramValues[paramKey(param)];\n if (value === undefined || value === \"\") continue;\n if (param.in === \"path\") pathValues[param.name] = value;\n else if (param.in === \"query\")\n queryParts.push(\n encodeURIComponent(param.name) + \"=\" + encodeURIComponent(value),\n );\n else if (param.in === \"header\") headers[param.name] = value;\n else if (param.in === \"cookie\")\n cookie += (cookie ? \"; \" : \"\") + param.name + \"=\" + value;\n }\n\n for (const requirement of operation.security) {\n const scheme = requirement.scheme;\n if (!scheme) continue;\n if (scheme.type === \"apiKey\" && scheme.name) {\n const value = authValues[requirement.schemeName];\n if (!value) continue;\n if (scheme.in === \"header\") {\n headers[scheme.name] = value;\n secretHeaderNames.push(scheme.name);\n } else if (scheme.in === \"query\") {\n queryParts.push(\n encodeURIComponent(scheme.name) + \"=\" + encodeURIComponent(value),\n );\n } else if (scheme.in === \"cookie\") {\n cookie += (cookie ? \"; \" : \"\") + scheme.name + \"=\" + value;\n }\n } else if (scheme.type === \"http\" && scheme.scheme === \"basic\") {\n const user = authValues[requirement.schemeName + \":user\"] ?? \"\";\n const pass = authValues[requirement.schemeName + \":pass\"] ?? \"\";\n if (user || pass) {\n headers[\"Authorization\"] = \"Basic \" + btoa(user + \":\" + pass);\n secretHeaderNames.push(\"Authorization\");\n }\n } else {\n const token = authValues[requirement.schemeName];\n if (token) {\n headers[\"Authorization\"] = \"Bearer \" + token;\n secretHeaderNames.push(\"Authorization\");\n }\n }\n }\n\n if (cookie) headers[\"Cookie\"] = cookie;\n\n const hasBody =\n operation.requestBody !== undefined &&\n operation.method !== \"get\" &&\n operation.method !== \"head\" &&\n bodyText.trim() !== \"\";\n if (hasBody && !headers[\"Content-Type\"] && initialBody) {\n headers[\"Content-Type\"] = initialBody.contentType;\n }\n\n const query = queryParts.join(\"&\");\n const url =\n base +\n applyPathParams(operation.path, pathValues) +\n (query ? \"?\" + query : \"\");\n\n return { url, headers, body: hasBody ? bodyText : null, secretHeaderNames };\n }, [operation, paramValues, authValues, bodyText, initialBody]);\n\n const snippets = useMemo(() => {\n const built = buildRequest();\n const headers: Record<string, string> = { ...built.headers };\n if (!showSecrets) {\n for (const name of built.secretHeaderNames) {\n headers[name] = \"<YOUR_CREDENTIALS>\";\n }\n }\n return buildSnippets(\n {\n method: operation.method.toUpperCase(),\n url: built.url || operation.path,\n headers,\n body: built.body,\n },\n snippetLanguages,\n );\n }, [buildRequest, showSecrets, operation, snippetLanguages]);\n\n const sendProxy = useCallback(\n async (\n built: BuiltRequest,\n signal: AbortSignal,\n ): Promise<PlaygroundResponse> => {\n const res = await fetch(\"/api/playground\", {\n method: \"POST\",\n headers: { \"Content-Type\": \"application/json\" },\n signal,\n body: JSON.stringify({\n targetUrl: built.url,\n method: operation.method.toUpperCase(),\n headers: built.headers,\n body: built.body ?? undefined,\n bodyEncoding: \"utf8\",\n }),\n });\n const data = await res.json();\n if (!res.ok) {\n throw new Error(\n typeof data?.error === \"string\" ? data.error : \"Request failed\",\n );\n }\n return data as PlaygroundResponse;\n },\n [operation],\n );\n\n const sendDirect = useCallback(\n async (\n built: BuiltRequest,\n signal: AbortSignal,\n ): Promise<PlaygroundResponse> => {\n const start = Date.now();\n const res = await fetch(built.url, {\n method: operation.method.toUpperCase(),\n headers: built.headers,\n body: built.body ?? undefined,\n signal,\n });\n const buffer = await res.arrayBuffer();\n const contentType = res.headers.get(\"content-type\");\n const isText = classifyResponse(contentType) === \"text\";\n const headers: Record<string, string> = {};\n res.headers.forEach((value, key) => {\n headers[key] = value;\n });\n return {\n status: res.status,\n statusText: res.statusText,\n headers,\n contentType,\n bodyEncoding: isText ? \"utf8\" : \"base64\",\n body: isText\n ? new TextDecoder().decode(buffer)\n : bufferToBase64(buffer),\n truncated: false,\n byteLength: buffer.byteLength,\n durationMs: Date.now() - start,\n };\n },\n [operation],\n );\n\n const send = useCallback(async () => {\n setError(null);\n setCorsRetry(false);\n // Keep any previous response on screen; the loading overlay covers it so\n // the layout does not collapse and jump while the new request is in flight.\n\n const built = buildRequest();\n if (!built.url) {\n setError(\"No server URL is configured for this endpoint.\");\n return;\n }\n if (!isAllowed(built.url)) {\n setError(\"This endpoint's server is not in the allowed list.\");\n return;\n }\n if (\n mode === \"direct\" &&\n typeof window !== \"undefined\" &&\n window.location.protocol === \"https:\" &&\n built.url.startsWith(\"http:\")\n ) {\n setError(\n \"Browsers block HTTP requests from an HTTPS page. Use proxy mode.\",\n );\n return;\n }\n\n const controller = new AbortController();\n abortRef.current = controller;\n setLoading(true);\n try {\n const result =\n mode === \"direct\"\n ? await sendDirect(built, controller.signal)\n : await sendProxy(built, controller.signal);\n setResponse(result);\n } catch (err) {\n if (controller.signal.aborted) return;\n if (mode === \"direct\" && err instanceof TypeError) {\n setCorsRetry(true);\n setError(\n \"The browser blocked this cross-origin request (CORS). Run it server-side instead.\",\n );\n } else {\n setError(err instanceof Error ? err.message : \"Request failed\");\n }\n } finally {\n setLoading(false);\n abortRef.current = null;\n }\n }, [buildRequest, isAllowed, mode, sendDirect, sendProxy]);\n\n const retryViaProxy = useCallback(() => {\n setMode(\"proxy\");\n setCorsRetry(false);\n void send();\n }, [send]);\n\n const groupedParams = LOCATIONS.map((location) => ({\n location,\n params: operation.parameters.filter((p) => p.in === location),\n })).filter((group) => group.params.length > 0);\n // Only the first visible section starts expanded.\n const hasAuth = operation.security.length > 0;\n\n const responseKind = response ? classifyResponse(response.contentType) : null;\n const mediaSrc =\n response && responseKind && responseKind !== \"text\"\n ? \"data:\" +\n (response.contentType ?? \"application/octet-stream\") +\n \";base64,\" +\n response.body\n : \"\";\n\n const renderParamField = (param: ParameterDescriptor) => (\n <Field key={param.anchorId}>\n <FieldHead>\n <FieldName>{param.name}</FieldName>\n <TypeChip>{schemaTypeLabel(param.schema)}</TypeChip>\n {param.required ? <RequiredChip>required</RequiredChip> : null}\n </FieldHead>\n {param.description ? <FieldDesc>{param.description}</FieldDesc> : null}\n <Input\n $fullWidth\n type=\"text\"\n aria-label={param.name}\n placeholder={\n param.example !== undefined\n ? String(param.example)\n : \"enter \" + param.name\n }\n value={paramValues[paramKey(param)] ?? \"\"}\n onChange={(e) =>\n setParamValues((prev) => ({\n ...prev,\n [paramKey(param)]: e.target.value,\n }))\n }\n />\n </Field>\n );\n\n return (\n <>\n <CompactBar>\n <MethodBadge\n mono\n solid\n size=\"sm\"\n color={httpMethodBadgeColor(operation.method)}\n >\n {operation.method}\n </MethodBadge>\n <PathText>{renderPath(operation.path)}</PathText>\n <CopyButton\n text={operation.method.toUpperCase() + \" \" + operation.path}\n label=\"Copy endpoint\"\n size={16}\n />\n <AccentButton type=\"button\" onClick={() => setOpen(true)}>\n Try it\n <Icon name=\"play\" size={14} />\n </AccentButton>\n </CompactBar>\n\n <Modal\n $isOpen={open}\n $onClose={() => setOpen(false)}\n $width={1120}\n $title={\n operation.summary ??\n operation.method.toUpperCase() + \" \" + operation.path\n }\n >\n <DialogHeader>\n <PathBar>\n <MethodBadge\n mono\n solid\n size=\"sm\"\n color={httpMethodBadgeColor(operation.method)}\n >\n {operation.method}\n </MethodBadge>\n <PathText>{renderPath(operation.path)}</PathText>\n <AccentButton\n type=\"button\"\n onClick={() => void send()}\n disabled={loading}\n >\n Send\n {loading ? <Spinner size={14} /> : <Icon name=\"play\" size={14} />}\n </AccentButton>\n </PathBar>\n </DialogHeader>\n\n <DialogBody>\n <Column>\n {operation.description || operation.summary ? (\n <Description>\n {operation.description ?? operation.summary}\n </Description>\n ) : null}\n\n <Toolbar>\n {operation.servers.length > 0 ? (\n <Meta>{serverBase(operation.servers[0])}</Meta>\n ) : null}\n {allowDirect ? (\n <>\n <Toggle\n type=\"button\"\n $active={mode === \"proxy\"}\n onClick={() => setMode(\"proxy\")}\n >\n Proxy\n </Toggle>\n <Toggle\n type=\"button\"\n $active={mode === \"direct\"}\n onClick={() => setMode(\"direct\")}\n >\n Direct\n </Toggle>\n </>\n ) : null}\n <Toggle\n type=\"button\"\n $active={showSecrets}\n onClick={() => setShowSecrets((v) => !v)}\n >\n {showSecrets ? \"Hide secrets\" : \"Show secrets\"}\n </Toggle>\n </Toolbar>\n\n {operation.security.length > 0 ? (\n <Accordion title=\"Authorization\" defaultOpen>\n <SectionInner>\n {operation.security.map((requirement) => {\n const scheme = requirement.scheme;\n if (\n scheme &&\n scheme.type === \"http\" &&\n scheme.scheme === \"basic\"\n ) {\n return (\n <Field key={requirement.schemeName}>\n <FieldHead>\n <FieldName>{requirement.schemeName}</FieldName>\n <TypeChip>basic</TypeChip>\n </FieldHead>\n <Input\n $fullWidth\n type=\"text\"\n aria-label={requirement.schemeName + \" username\"}\n placeholder=\"username\"\n value={\n authValues[requirement.schemeName + \":user\"] ?? \"\"\n }\n onChange={(e) =>\n setAuthValues((prev) => ({\n ...prev,\n [requirement.schemeName + \":user\"]:\n e.target.value,\n }))\n }\n />\n <Input\n $fullWidth\n type={showSecrets ? \"text\" : \"password\"}\n aria-label={requirement.schemeName + \" password\"}\n placeholder=\"password\"\n value={\n authValues[requirement.schemeName + \":pass\"] ?? \"\"\n }\n onChange={(e) =>\n setAuthValues((prev) => ({\n ...prev,\n [requirement.schemeName + \":pass\"]:\n e.target.value,\n }))\n }\n />\n </Field>\n );\n }\n const chip =\n scheme?.type === \"apiKey\"\n ? \"apiKey\"\n : scheme?.scheme === \"bearer\"\n ? \"bearer\"\n : (scheme?.type ?? \"token\");\n return (\n <Field key={requirement.schemeName}>\n <FieldHead>\n <FieldName>{requirement.schemeName}</FieldName>\n <TypeChip>{chip}</TypeChip>\n <RequiredChip>required</RequiredChip>\n </FieldHead>\n <Input\n $fullWidth\n type={showSecrets ? \"text\" : \"password\"}\n aria-label={requirement.schemeName}\n placeholder={\n chip === \"bearer\"\n ? \"enter bearer token\"\n : \"enter value\"\n }\n value={authValues[requirement.schemeName] ?? \"\"}\n onChange={(e) =>\n setAuthValues((prev) => ({\n ...prev,\n [requirement.schemeName]: e.target.value,\n }))\n }\n />\n </Field>\n );\n })}\n </SectionInner>\n </Accordion>\n ) : null}\n\n {groupedParams.map((group, index) => (\n <Accordion\n key={group.location}\n title={LOCATION_TITLES[group.location]}\n defaultOpen={!hasAuth && index === 0}\n >\n <SectionInner>\n {group.params.map(renderParamField)}\n </SectionInner>\n </Accordion>\n ))}\n\n {operation.requestBody &&\n operation.method !== \"get\" &&\n operation.method !== \"head\" ? (\n <Accordion\n title=\"Body\"\n defaultOpen={!hasAuth && groupedParams.length === 0}\n >\n <SectionInner>\n <Textarea\n $fullWidth\n rows={8}\n aria-label=\"Request body\"\n spellCheck={false}\n value={bodyText}\n onChange={(e) => setBodyText(e.target.value)}\n />\n </SectionInner>\n </Accordion>\n ) : null}\n\n {error ? (\n <Field>\n <ErrorText>{error}</ErrorText>\n {corsRetry ? (\n <Toggle type=\"button\" onClick={retryViaProxy}>\n Retry via proxy\n </Toggle>\n ) : null}\n </Field>\n ) : null}\n </Column>\n\n <Column>\n <ResponseArea>\n {response ? (\n <Card>\n <CardHead as=\"div\">\n <Inline>\n <StatusPill\n $ok={response.status >= 200 && response.status < 400}\n >\n {response.status} {response.statusText}\n </StatusPill>\n <Meta>{response.durationMs}ms</Meta>\n <Meta>{response.byteLength} bytes</Meta>\n {response.truncated ? <Meta>(truncated)</Meta> : null}\n </Inline>\n </CardHead>\n <CardBody>\n {responseKind === \"image\" ? (\n <ResponseMedia src={mediaSrc} alt=\"Response\" />\n ) : responseKind === \"video\" ? (\n <video\n controls\n src={mediaSrc}\n style={{ maxWidth: \"100%\" }}\n />\n ) : responseKind === \"audio\" ? (\n <audio controls src={mediaSrc} />\n ) : responseKind === \"binary\" ? (\n <a href={mediaSrc} download>\n Download response ({response.byteLength} bytes)\n </a>\n ) : (\n <Code\n language={codeLanguage(response.contentType)}\n code={prettyBody(response.contentType, response.body)}\n />\n )}\n </CardBody>\n </Card>\n ) : (\n <Placeholder>\n Send the request to see the live response here.\n </Placeholder>\n )}\n {loading ? (\n <LoadingOverlay>\n <Spinner size={22} />\n </LoadingOverlay>\n ) : null}\n </ResponseArea>\n\n {snippets.length > 0 ? <CodeTabs tabs={snippets} /> : null}\n </Column>\n </DialogBody>\n </Modal>\n </>\n );\n}\n";
|
|
1
|
+
export declare const apiPlaygroundTemplate = "\"use client\";\nimport React, { useCallback, useMemo, useRef, useState } from \"react\";\nimport styled, { css } from \"styled-components\";\nimport {\n styledSmall,\n interactiveStyles,\n Input,\n Textarea,\n Modal,\n} from \"cherry-styled-components\";\nimport { mq, Theme } from \"@/app/theme\";\nimport { Code, CodeTabs } from \"@/components/layout/Code\";\nimport { Icon } from \"@/components/layout/Icon\";\nimport { Accordion } from \"@/components/layout/Accordion\";\nimport { Badge, httpMethodBadgeColor } from \"@/components/layout/Badge\";\nimport { Callout } from \"@/components/layout/Callout\";\nimport { CopyButton } from \"@/components/layout/CopyButton\";\nimport { Spinner } from \"@/components/Spinner\";\nimport { matchAllowlist, matchAllowlistIn } from \"@/utils/playgroundAllowlist\";\nimport type { AllowlistEntry } from \"@/utils/playgroundAllowlist\";\nimport { buildSnippets } from \"@/utils/apiSnippets\";\nimport type { SnippetLanguage } from \"@/utils/apiSnippets\";\nimport type {\n OperationDescriptor,\n ParameterDescriptor,\n ServerDescriptor,\n} from \"@/types/openapi\";\n\ninterface PlaygroundResponse {\n status: number;\n statusText: string;\n headers: Record<string, string>;\n contentType: string | null;\n bodyEncoding: \"utf8\" | \"base64\";\n body: string;\n truncated: boolean;\n byteLength: number;\n durationMs: number;\n}\n\ninterface BuiltRequest {\n url: string;\n headers: Record<string, string>;\n body: string | null;\n secretHeaderNames: string[];\n}\n\nexport interface ApiPlaygroundProps {\n operation: OperationDescriptor;\n defaultMode?: \"proxy\" | \"direct\";\n allowDirect?: boolean;\n // Extra client-side allowlist entries. The server proxy always enforces the\n // build-time allowlist regardless; this only relaxes the client pre-flight\n // (used by the docs demo to run in direct mode without a configured spec).\n allowlist?: AllowlistEntry[];\n snippetLanguages?: SnippetLanguage[];\n}\n\nfunction schemaTypeLabel(schema: unknown): string {\n if (schema && typeof schema === \"object\") {\n const record = schema as { type?: unknown; format?: unknown };\n if (typeof record.type === \"string\") {\n return typeof record.format === \"string\"\n ? record.type + \" (\" + record.format + \")\"\n : record.type;\n }\n }\n return \"string\";\n}\n\nfunction serverBase(server: ServerDescriptor | undefined): string {\n if (!server) return \"\";\n let url = server.url;\n const variables = server.variables;\n if (variables) {\n for (const key of Object.keys(variables)) {\n url = url.split(\"{\" + key + \"}\").join(variables[key].default);\n }\n }\n while (url.endsWith(\"/\")) url = url.slice(0, -1);\n return url;\n}\n\nfunction applyPathParams(\n template: string,\n values: Record<string, string>,\n): string {\n let result = template;\n for (const key of Object.keys(values)) {\n result = result\n .split(\"{\" + key + \"}\")\n .join(encodeURIComponent(values[key]));\n }\n return result;\n}\n\nfunction firstJsonExample(op: OperationDescriptor): {\n contentType: string;\n text: string;\n} | null {\n if (!op.requestBody || op.requestBody.content.length === 0) return null;\n const media =\n op.requestBody.content.find((m) => m.contentType.includes(\"json\")) ??\n op.requestBody.content[0];\n let text = \"\";\n if (media.example !== undefined) {\n try {\n text = JSON.stringify(media.example, null, 2);\n } catch {\n text = \"\";\n }\n }\n return { contentType: media.contentType, text };\n}\n\nfunction classifyResponse(\n contentType: string | null,\n): \"image\" | \"video\" | \"audio\" | \"text\" | \"binary\" {\n if (!contentType) return \"text\";\n const t = contentType.toLowerCase();\n if (t.startsWith(\"image/\") && !t.includes(\"svg\")) return \"image\";\n if (t.startsWith(\"video/\")) return \"video\";\n if (t.startsWith(\"audio/\")) return \"audio\";\n if (\n t.includes(\"json\") ||\n t.startsWith(\"text/\") ||\n t.includes(\"xml\") ||\n t.includes(\"svg\") ||\n t.includes(\"html\") ||\n t.includes(\"javascript\") ||\n t.includes(\"csv\")\n ) {\n return \"text\";\n }\n return \"binary\";\n}\n\nfunction codeLanguage(contentType: string | null): string {\n if (!contentType) return \"text\";\n const t = contentType.toLowerCase();\n if (t.includes(\"json\")) return \"json\";\n if (t.includes(\"html\")) return \"html\";\n if (t.includes(\"xml\") || t.includes(\"svg\")) return \"xml\";\n if (t.includes(\"javascript\")) return \"javascript\";\n return \"text\";\n}\n\nfunction prettyBody(contentType: string | null, body: string): string {\n if (contentType && contentType.toLowerCase().includes(\"json\")) {\n try {\n return JSON.stringify(JSON.parse(body), null, 2);\n } catch {\n return body;\n }\n }\n return body;\n}\n\nfunction bufferToBase64(buffer: ArrayBuffer): string {\n let binary = \"\";\n const bytes = new Uint8Array(buffer);\n const chunk = 0x8000;\n for (let i = 0; i < bytes.length; i += chunk) {\n binary += String.fromCharCode(...bytes.subarray(i, i + chunk));\n }\n return btoa(binary);\n}\n\nfunction renderPath(path: string): React.ReactNode {\n return path\n .split(/(\\{[^}]+\\})/g)\n .map((part, index) =>\n part.startsWith(\"{\") ? (\n <PathParam key={index}>{part}</PathParam>\n ) : (\n <span key={index}>{part}</span>\n ),\n );\n}\n\nconst LOCATIONS: ParameterDescriptor[\"in\"][] = [\n \"path\",\n \"query\",\n \"header\",\n \"cookie\",\n];\n\nconst LOCATION_TITLES: Record<string, string> = {\n path: \"Path\",\n query: \"Query\",\n header: \"Headers\",\n cookie: \"Cookies\",\n};\n\n/* ---------- compact bar ---------- */\n\nconst CompactBar = styled.div`\n display: flex;\n align-items: center;\n gap: 10px;\n margin: 0;\n padding: 8px 8px 8px 12px;\n border: solid 1px ${({ theme }: { theme: Theme }) => theme.colors.grayLight};\n border-radius: ${({ theme }: { theme: Theme }) => theme.spacing.radius.lg};\n background: ${({ theme }: { theme: Theme }) => theme.colors.light};\n`;\n\n// The method chip is Badge's mono+solid variation; only bar-layout metrics\n// are adjusted here.\nconst MethodBadge = styled(Badge)`\n flex-shrink: 0;\n padding: 0 4px;\n border: none;\n`;\n\nconst PathText = styled.span`\n flex: 1;\n min-width: 0;\n font-family: ${({ theme }: { theme: Theme }) => theme.fonts.mono};\n font-weight: 600;\n font-size: 14px;\n color: ${({ theme }: { theme: Theme }) => theme.colors.dark};\n overflow-x: auto;\n white-space: nowrap;\n &::-webkit-scrollbar {\n display: none;\n }\n`;\n\nconst PathParam = styled.span`\n font-family: ${({ theme }: { theme: Theme }) => theme.fonts.mono};\n background: ${({ theme }: { theme: Theme }) =>\n `color-mix(in srgb, ${theme.colors.primaryLight} 20%, transparent)`};\n color: ${({ theme }: { theme: Theme }) => theme.colors.dark};\n padding: 2px 4px;\n border-radius: ${({ theme }: { theme: Theme }) => theme.spacing.radius.xs};\n overflow-wrap: anywhere;\n`;\n\nconst AccentButton = styled.button<{ theme: Theme }>`\n cursor: pointer;\n display: inline-flex;\n align-items: center;\n gap: 6px;\n flex-shrink: 0;\n font-family: ${({ theme }: { theme: Theme }) => theme.fonts.text};\n font-weight: 600;\n font-size: 14px;\n color: ${({ theme }: { theme: Theme }) => theme.colors.surface};\n background: ${({ theme }: { theme: Theme }) => theme.colors.primary};\n border: none;\n padding: 8px 14px;\n border-radius: ${({ theme }: { theme: Theme }) => theme.spacing.radius.xs};\n ${interactiveStyles};\n\n & svg {\n color: ${({ theme }: { theme: Theme }) => theme.colors.surface};\n stroke: ${({ theme }: { theme: Theme }) => theme.colors.surface};\n }\n\n &:hover {\n background: ${({ theme }: { theme: Theme }) => theme.colors.primaryDark};\n }\n &:disabled {\n opacity: 0.6;\n cursor: default;\n }\n`;\n\n/* ---------- modal ---------- */\n\nconst DialogHeader = styled.div`\n display: flex;\n align-items: center;\n gap: 10px;\n flex-wrap: wrap;\n margin: 5px 0 0 0;\n`;\n\nconst PathBar = styled.div`\n flex: 1;\n min-width: 200px;\n display: flex;\n align-items: center;\n gap: 8px;\n padding: 8px 8px 8px 12px;\n border: solid 1px ${({ theme }: { theme: Theme }) => theme.colors.grayLight};\n border-radius: ${({ theme }: { theme: Theme }) => theme.spacing.radius.xs};\n background: ${({ theme }: { theme: Theme }) => theme.colors.light};\n`;\n\nconst DialogBody = styled.div`\n display: grid;\n grid-template-columns: 1fr;\n gap: 20px;\n padding: 0;\n margin: 20px 0 0 0;\n\n ${mq(\"lg\")} {\n grid-template-columns: 1fr 1fr;\n }\n`;\n\nconst Column = styled.div`\n display: flex;\n flex-direction: column;\n gap: 20px;\n min-width: 0;\n`;\n\nconst Description = styled.p`\n margin: 0;\n ${({ theme }: { theme: Theme }) => styledSmall(theme)};\n color: ${({ theme }: { theme: Theme }) => theme.colors.grayDark};\n`;\n\nconst Toolbar = styled.div`\n display: flex;\n align-items: center;\n gap: 8px;\n flex-wrap: wrap;\n`;\n\nconst Toggle = styled.button<{ theme: Theme; $active?: boolean }>`\n position: relative;\n cursor: pointer;\n text-decoration: none;\n font-size: ${({ theme }) => theme.fontSizes.small.lg};\n line-height: 1;\n color: ${({ theme }) => theme.colors.accent};\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: none;\n border-radius: ${({ theme }) => theme.spacing.radius.xs};\n ${interactiveStyles};\n\n ${({ $active, theme }) =>\n $active &&\n css`\n background: ${theme.colors.primary};\n color: ${theme.colors.surface};\n `}\n`;\n\n/* ---------- collapsible card ---------- */\n\nconst Card = styled.div`\n border: solid 1px ${({ theme }: { theme: Theme }) => theme.colors.grayLight};\n border-radius: ${({ theme }: { theme: Theme }) => theme.spacing.radius.lg};\n overflow: hidden;\n`;\n\nconst CardHead = styled.button`\n cursor: pointer;\n width: 100%;\n display: flex;\n align-items: center;\n justify-content: space-between;\n gap: 8px;\n padding: 12px 20px;\n border: none;\n background: transparent;\n color: ${({ theme }: { theme: Theme }) => theme.colors.dark};\n ${({ theme }: { theme: Theme }) => styledSmall(theme)};\n`;\n\nconst Inline = styled.span`\n display: inline-flex;\n align-items: center;\n gap: 8px;\n`;\n\nconst CardBody = styled.div`\n padding: 0 20px 20px;\n display: flex;\n flex-direction: column;\n gap: 16px;\n`;\n\n/* ---------- fields ---------- */\n\n// Wraps an accordion section's content and insets it, so full-width inputs'\n// focus rings (a 4px box-shadow) are not clipped by the accordion's own\n// overflow. Keeps the accordion component untouched.\nconst SectionInner = styled.div`\n display: flex;\n flex-direction: column;\n gap: 16px;\n padding: 4px;\n`;\n\nconst Field = styled.div`\n display: flex;\n flex-direction: column;\n gap: 6px;\n`;\n\nconst FieldHead = styled.div`\n display: flex;\n align-items: center;\n gap: 8px;\n flex-wrap: wrap;\n ${({ theme }: { theme: Theme }) => styledSmall(theme)};\n`;\n\nconst FieldName = styled.span`\n font-family: ${({ theme }: { theme: Theme }) => theme.fonts.mono};\n font-weight: 600;\n color: ${({ theme }: { theme: Theme }) => theme.colors.dark};\n`;\n\nconst TypeChip = styled.span`\n font-family: ${({ theme }: { theme: Theme }) => theme.fonts.mono};\n color: ${({ theme }: { theme: Theme }) => theme.colors.grayDark};\n background: ${({ theme }: { theme: Theme }) =>\n `color-mix(in srgb, ${theme.colors.gray} 15%, transparent)`};\n padding: 0 4px;\n border-radius: ${({ theme }: { theme: Theme }) => theme.spacing.radius.xs};\n`;\n\nconst RequiredChip = styled.span`\n font-family: ${({ theme }: { theme: Theme }) => theme.fonts.mono};\n color: ${({ theme }: { theme: Theme }) => theme.colors.error};\n`;\n\nconst FieldDesc = styled.p`\n margin: 0;\n width: 100%;\n ${({ theme }: { theme: Theme }) => styledSmall(theme)};\n color: ${({ theme }: { theme: Theme }) => theme.colors.gray};\n`;\n\n/* ---------- response ---------- */\n\nconst StatusPill = styled.span<{ theme: Theme; $ok: boolean }>`\n font-family: ${({ theme }) => theme.fonts.mono};\n font-weight: 700;\n color: ${({ theme }) => theme.colors.surface};\n background: ${({ theme, $ok }) =>\n $ok ? theme.colors.success : theme.colors.error};\n padding: 0 4px;\n border-radius: ${({ theme }) => theme.spacing.radius.xs};\n`;\n\nconst Meta = styled.span`\n ${({ theme }: { theme: Theme }) => styledSmall(theme)};\n color: ${({ theme }: { theme: Theme }) => theme.colors.gray};\n`;\n\nconst Placeholder = styled.div`\n border: dashed 1px ${({ theme }: { theme: Theme }) => theme.colors.grayLight};\n border-radius: ${({ theme }: { theme: Theme }) => theme.spacing.radius.lg};\n padding: 24px;\n min-height: 120px;\n display: flex;\n align-items: center;\n justify-content: center;\n gap: 10px;\n text-align: center;\n ${({ theme }: { theme: Theme }) => styledSmall(theme)};\n color: ${({ theme }: { theme: Theme }) => theme.colors.gray};\n`;\n\n// Holds the response (or empty placeholder) and lets the loading spinner sit on\n// top of it, so a re-send keeps the previous content in place instead of\n// collapsing and jumping the layout.\nconst ResponseArea = styled.div`\n position: relative;\n`;\n\nconst LoadingOverlay = styled.div`\n position: absolute;\n inset: 0;\n z-index: 1;\n display: flex;\n align-items: center;\n justify-content: center;\n border: solid 1px ${({ theme }: { theme: Theme }) => theme.colors.grayLight};\n border-radius: ${({ theme }: { theme: Theme }) => theme.spacing.radius.lg};\n color: ${({ theme }: { theme: Theme }) => theme.colors.grayDark};\n background: ${({ theme }: { theme: Theme }) =>\n `color-mix(in srgb, ${theme.colors.light} 60%, transparent)`};\n backdrop-filter: blur(1px);\n`;\n\nconst ResponseMedia = styled.img`\n max-width: 100%;\n border-radius: ${({ theme }: { theme: Theme }) => theme.spacing.radius.xs};\n`;\n\nexport function ApiPlayground({\n operation,\n defaultMode = \"proxy\",\n allowDirect = true,\n allowlist,\n snippetLanguages = [\"curl\", \"javascript\", \"python\"],\n}: ApiPlaygroundProps) {\n const [open, setOpen] = useState(false);\n const [paramValues, setParamValues] = useState<Record<string, string>>({});\n const [authValues, setAuthValues] = useState<Record<string, string>>({});\n const initialBody = useMemo(() => firstJsonExample(operation), [operation]);\n const [bodyText, setBodyText] = useState(initialBody?.text ?? \"\");\n const [mode, setMode] = useState<\"proxy\" | \"direct\">(defaultMode);\n const [showSecrets, setShowSecrets] = useState(false);\n const [loading, setLoading] = useState(false);\n const [response, setResponse] = useState<PlaygroundResponse | null>(null);\n const [error, setError] = useState<string | null>(null);\n const [corsRetry, setCorsRetry] = useState(false);\n const abortRef = useRef<AbortController | null>(null);\n\n const paramKey = (p: ParameterDescriptor) => p.in + \":\" + p.name;\n\n const isAllowed = useCallback(\n (url: string) =>\n Boolean(\n matchAllowlist(url) ??\n (allowlist ? matchAllowlistIn(allowlist, url) : null),\n ),\n [allowlist],\n );\n\n const buildRequest = useCallback((): BuiltRequest => {\n const base = serverBase(operation.servers[0]);\n const pathValues: Record<string, string> = {};\n const queryParts: string[] = [];\n const headers: Record<string, string> = {};\n const secretHeaderNames: string[] = [];\n let cookie = \"\";\n\n for (const param of operation.parameters) {\n const value = paramValues[paramKey(param)];\n if (value === undefined || value === \"\") continue;\n if (param.in === \"path\") pathValues[param.name] = value;\n else if (param.in === \"query\")\n queryParts.push(\n encodeURIComponent(param.name) + \"=\" + encodeURIComponent(value),\n );\n else if (param.in === \"header\") headers[param.name] = value;\n else if (param.in === \"cookie\")\n cookie += (cookie ? \"; \" : \"\") + param.name + \"=\" + value;\n }\n\n for (const requirement of operation.security) {\n const scheme = requirement.scheme;\n if (!scheme) continue;\n if (scheme.type === \"apiKey\" && scheme.name) {\n const value = authValues[requirement.schemeName];\n if (!value) continue;\n if (scheme.in === \"header\") {\n headers[scheme.name] = value;\n secretHeaderNames.push(scheme.name);\n } else if (scheme.in === \"query\") {\n queryParts.push(\n encodeURIComponent(scheme.name) + \"=\" + encodeURIComponent(value),\n );\n } else if (scheme.in === \"cookie\") {\n cookie += (cookie ? \"; \" : \"\") + scheme.name + \"=\" + value;\n }\n } else if (scheme.type === \"http\" && scheme.scheme === \"basic\") {\n const user = authValues[requirement.schemeName + \":user\"] ?? \"\";\n const pass = authValues[requirement.schemeName + \":pass\"] ?? \"\";\n if (user || pass) {\n headers[\"Authorization\"] = \"Basic \" + btoa(user + \":\" + pass);\n secretHeaderNames.push(\"Authorization\");\n }\n } else {\n const token = authValues[requirement.schemeName];\n if (token) {\n headers[\"Authorization\"] = \"Bearer \" + token;\n secretHeaderNames.push(\"Authorization\");\n }\n }\n }\n\n if (cookie) headers[\"Cookie\"] = cookie;\n\n const hasBody =\n operation.requestBody !== undefined &&\n operation.method !== \"get\" &&\n operation.method !== \"head\" &&\n bodyText.trim() !== \"\";\n if (hasBody && !headers[\"Content-Type\"] && initialBody) {\n headers[\"Content-Type\"] = initialBody.contentType;\n }\n\n const query = queryParts.join(\"&\");\n const url =\n base +\n applyPathParams(operation.path, pathValues) +\n (query ? \"?\" + query : \"\");\n\n return { url, headers, body: hasBody ? bodyText : null, secretHeaderNames };\n }, [operation, paramValues, authValues, bodyText, initialBody]);\n\n const snippets = useMemo(() => {\n const built = buildRequest();\n const headers: Record<string, string> = { ...built.headers };\n if (!showSecrets) {\n for (const name of built.secretHeaderNames) {\n headers[name] = \"<YOUR_CREDENTIALS>\";\n }\n }\n return buildSnippets(\n {\n method: operation.method.toUpperCase(),\n url: built.url || operation.path,\n headers,\n body: built.body,\n },\n snippetLanguages,\n );\n }, [buildRequest, showSecrets, operation, snippetLanguages]);\n\n const sendProxy = useCallback(\n async (\n built: BuiltRequest,\n signal: AbortSignal,\n ): Promise<PlaygroundResponse> => {\n const res = await fetch(\"/api/playground\", {\n method: \"POST\",\n headers: { \"Content-Type\": \"application/json\" },\n signal,\n body: JSON.stringify({\n targetUrl: built.url,\n method: operation.method.toUpperCase(),\n headers: built.headers,\n body: built.body ?? undefined,\n bodyEncoding: \"utf8\",\n }),\n });\n const data = await res.json();\n if (!res.ok) {\n throw new Error(\n typeof data?.error === \"string\" ? data.error : \"Request failed\",\n );\n }\n return data as PlaygroundResponse;\n },\n [operation],\n );\n\n const sendDirect = useCallback(\n async (\n built: BuiltRequest,\n signal: AbortSignal,\n ): Promise<PlaygroundResponse> => {\n const start = Date.now();\n const res = await fetch(built.url, {\n method: operation.method.toUpperCase(),\n headers: built.headers,\n body: built.body ?? undefined,\n signal,\n });\n const buffer = await res.arrayBuffer();\n const contentType = res.headers.get(\"content-type\");\n const isText = classifyResponse(contentType) === \"text\";\n const headers: Record<string, string> = {};\n res.headers.forEach((value, key) => {\n headers[key] = value;\n });\n return {\n status: res.status,\n statusText: res.statusText,\n headers,\n contentType,\n bodyEncoding: isText ? \"utf8\" : \"base64\",\n body: isText\n ? new TextDecoder().decode(buffer)\n : bufferToBase64(buffer),\n truncated: false,\n byteLength: buffer.byteLength,\n durationMs: Date.now() - start,\n };\n },\n [operation],\n );\n\n const send = useCallback(async () => {\n setError(null);\n setCorsRetry(false);\n // Keep any previous response on screen; the loading overlay covers it so\n // the layout does not collapse and jump while the new request is in flight.\n\n const built = buildRequest();\n if (!built.url) {\n setError(\"No server URL is configured for this endpoint.\");\n return;\n }\n if (!isAllowed(built.url)) {\n setError(\"This endpoint's server is not in the allowed list.\");\n return;\n }\n if (\n mode === \"direct\" &&\n typeof window !== \"undefined\" &&\n window.location.protocol === \"https:\" &&\n built.url.startsWith(\"http:\")\n ) {\n setError(\n \"Browsers block HTTP requests from an HTTPS page. Use proxy mode.\",\n );\n return;\n }\n\n const controller = new AbortController();\n abortRef.current = controller;\n setLoading(true);\n try {\n const result =\n mode === \"direct\"\n ? await sendDirect(built, controller.signal)\n : await sendProxy(built, controller.signal);\n setResponse(result);\n } catch (err) {\n if (controller.signal.aborted) return;\n if (mode === \"direct\" && err instanceof TypeError) {\n setCorsRetry(true);\n setError(\n \"The browser blocked this cross-origin request (CORS). Run it server-side instead.\",\n );\n } else {\n setError(err instanceof Error ? err.message : \"Request failed\");\n }\n } finally {\n setLoading(false);\n abortRef.current = null;\n }\n }, [buildRequest, isAllowed, mode, sendDirect, sendProxy]);\n\n const retryViaProxy = useCallback(() => {\n setMode(\"proxy\");\n setCorsRetry(false);\n void send();\n }, [send]);\n\n const groupedParams = LOCATIONS.map((location) => ({\n location,\n params: operation.parameters.filter((p) => p.in === location),\n })).filter((group) => group.params.length > 0);\n // Only the first visible section starts expanded.\n const hasAuth = operation.security.length > 0;\n\n const responseKind = response ? classifyResponse(response.contentType) : null;\n const mediaSrc =\n response && responseKind && responseKind !== \"text\"\n ? \"data:\" +\n (response.contentType ?? \"application/octet-stream\") +\n \";base64,\" +\n response.body\n : \"\";\n\n const renderParamField = (param: ParameterDescriptor) => (\n <Field key={param.anchorId}>\n <FieldHead>\n <FieldName>{param.name}</FieldName>\n <TypeChip>{schemaTypeLabel(param.schema)}</TypeChip>\n {param.required ? <RequiredChip>required</RequiredChip> : null}\n </FieldHead>\n {param.description ? <FieldDesc>{param.description}</FieldDesc> : null}\n <Input\n $fullWidth\n type=\"text\"\n aria-label={param.name}\n placeholder={\n param.example !== undefined\n ? String(param.example)\n : \"enter \" + param.name\n }\n value={paramValues[paramKey(param)] ?? \"\"}\n onChange={(e) =>\n setParamValues((prev) => ({\n ...prev,\n [paramKey(param)]: e.target.value,\n }))\n }\n />\n </Field>\n );\n\n return (\n <>\n <CompactBar>\n <MethodBadge\n mono\n solid\n size=\"sm\"\n color={httpMethodBadgeColor(operation.method)}\n >\n {operation.method}\n </MethodBadge>\n <PathText>{renderPath(operation.path)}</PathText>\n <CopyButton\n text={operation.method.toUpperCase() + \" \" + operation.path}\n label=\"Copy endpoint\"\n size={16}\n />\n <AccentButton type=\"button\" onClick={() => setOpen(true)}>\n Try it\n <Icon name=\"play\" size={14} />\n </AccentButton>\n </CompactBar>\n\n <Modal\n $isOpen={open}\n $onClose={() => setOpen(false)}\n $width={1120}\n $title={\n operation.summary ??\n operation.method.toUpperCase() + \" \" + operation.path\n }\n >\n <DialogHeader>\n <PathBar>\n <MethodBadge\n mono\n solid\n size=\"sm\"\n color={httpMethodBadgeColor(operation.method)}\n >\n {operation.method}\n </MethodBadge>\n <PathText>{renderPath(operation.path)}</PathText>\n <AccentButton\n type=\"button\"\n onClick={() => void send()}\n disabled={loading}\n >\n Send\n {loading ? <Spinner size={14} /> : <Icon name=\"play\" size={14} />}\n </AccentButton>\n </PathBar>\n </DialogHeader>\n\n <DialogBody>\n <Column>\n {operation.description || operation.summary ? (\n <Description>\n {operation.description ?? operation.summary}\n </Description>\n ) : null}\n\n <Toolbar>\n {operation.servers.length > 0 ? (\n <Meta>{serverBase(operation.servers[0])}</Meta>\n ) : null}\n {allowDirect ? (\n <>\n <Toggle\n type=\"button\"\n $active={mode === \"proxy\"}\n onClick={() => setMode(\"proxy\")}\n >\n Proxy\n </Toggle>\n <Toggle\n type=\"button\"\n $active={mode === \"direct\"}\n onClick={() => setMode(\"direct\")}\n >\n Direct\n </Toggle>\n </>\n ) : null}\n <Toggle\n type=\"button\"\n $active={showSecrets}\n onClick={() => setShowSecrets((v) => !v)}\n >\n {showSecrets ? \"Hide secrets\" : \"Show secrets\"}\n </Toggle>\n </Toolbar>\n\n {operation.security.length > 0 ? (\n <Accordion title=\"Authorization\" defaultOpen>\n <SectionInner>\n {operation.security.map((requirement) => {\n const scheme = requirement.scheme;\n if (\n scheme &&\n scheme.type === \"http\" &&\n scheme.scheme === \"basic\"\n ) {\n return (\n <Field key={requirement.schemeName}>\n <FieldHead>\n <FieldName>{requirement.schemeName}</FieldName>\n <TypeChip>basic</TypeChip>\n </FieldHead>\n <Input\n $fullWidth\n type=\"text\"\n aria-label={requirement.schemeName + \" username\"}\n placeholder=\"username\"\n value={\n authValues[requirement.schemeName + \":user\"] ?? \"\"\n }\n onChange={(e) =>\n setAuthValues((prev) => ({\n ...prev,\n [requirement.schemeName + \":user\"]:\n e.target.value,\n }))\n }\n />\n <Input\n $fullWidth\n type={showSecrets ? \"text\" : \"password\"}\n aria-label={requirement.schemeName + \" password\"}\n placeholder=\"password\"\n value={\n authValues[requirement.schemeName + \":pass\"] ?? \"\"\n }\n onChange={(e) =>\n setAuthValues((prev) => ({\n ...prev,\n [requirement.schemeName + \":pass\"]:\n e.target.value,\n }))\n }\n />\n </Field>\n );\n }\n const chip =\n scheme?.type === \"apiKey\"\n ? \"apiKey\"\n : scheme?.scheme === \"bearer\"\n ? \"bearer\"\n : (scheme?.type ?? \"token\");\n return (\n <Field key={requirement.schemeName}>\n <FieldHead>\n <FieldName>{requirement.schemeName}</FieldName>\n <TypeChip>{chip}</TypeChip>\n <RequiredChip>required</RequiredChip>\n </FieldHead>\n <Input\n $fullWidth\n type={showSecrets ? \"text\" : \"password\"}\n aria-label={requirement.schemeName}\n placeholder={\n chip === \"bearer\"\n ? \"enter bearer token\"\n : \"enter value\"\n }\n value={authValues[requirement.schemeName] ?? \"\"}\n onChange={(e) =>\n setAuthValues((prev) => ({\n ...prev,\n [requirement.schemeName]: e.target.value,\n }))\n }\n />\n </Field>\n );\n })}\n </SectionInner>\n </Accordion>\n ) : null}\n\n {groupedParams.map((group, index) => (\n <Accordion\n key={group.location}\n title={LOCATION_TITLES[group.location]}\n defaultOpen={!hasAuth && index === 0}\n >\n <SectionInner>\n {group.params.map(renderParamField)}\n </SectionInner>\n </Accordion>\n ))}\n\n {operation.requestBody &&\n operation.method !== \"get\" &&\n operation.method !== \"head\" ? (\n <Accordion\n title=\"Body\"\n defaultOpen={!hasAuth && groupedParams.length === 0}\n >\n <SectionInner>\n <Textarea\n $fullWidth\n rows={8}\n aria-label=\"Request body\"\n spellCheck={false}\n value={bodyText}\n onChange={(e) => setBodyText(e.target.value)}\n />\n </SectionInner>\n </Accordion>\n ) : null}\n\n {error ? (\n <Field>\n <Callout type=\"danger\">\n <p>{error}</p>\n </Callout>\n {corsRetry ? (\n <Toggle type=\"button\" onClick={retryViaProxy}>\n Retry via proxy\n </Toggle>\n ) : null}\n </Field>\n ) : null}\n </Column>\n\n <Column>\n <ResponseArea>\n {response ? (\n <Card>\n <CardHead as=\"div\">\n <Inline>\n <StatusPill\n $ok={response.status >= 200 && response.status < 400}\n >\n {response.status} {response.statusText}\n </StatusPill>\n <Meta>{response.durationMs}ms</Meta>\n <Meta>{response.byteLength} bytes</Meta>\n {response.truncated ? <Meta>(truncated)</Meta> : null}\n </Inline>\n </CardHead>\n <CardBody>\n {responseKind === \"image\" ? (\n <ResponseMedia src={mediaSrc} alt=\"Response\" />\n ) : responseKind === \"video\" ? (\n <video\n controls\n src={mediaSrc}\n style={{ maxWidth: \"100%\" }}\n />\n ) : responseKind === \"audio\" ? (\n <audio controls src={mediaSrc} />\n ) : responseKind === \"binary\" ? (\n <a href={mediaSrc} download>\n Download response ({response.byteLength} bytes)\n </a>\n ) : (\n <Code\n language={codeLanguage(response.contentType)}\n code={prettyBody(response.contentType, response.body)}\n />\n )}\n </CardBody>\n </Card>\n ) : (\n <Placeholder>\n Send the request to see the live response here.\n </Placeholder>\n )}\n {loading ? (\n <LoadingOverlay>\n <Spinner size={22} />\n </LoadingOverlay>\n ) : null}\n </ResponseArea>\n\n {snippets.length > 0 ? <CodeTabs tabs={snippets} /> : null}\n </Column>\n </DialogBody>\n </Modal>\n </>\n );\n}\n";
|
|
@@ -13,6 +13,7 @@ import { Code, CodeTabs } from "@/components/layout/Code";
|
|
|
13
13
|
import { Icon } from "@/components/layout/Icon";
|
|
14
14
|
import { Accordion } from "@/components/layout/Accordion";
|
|
15
15
|
import { Badge, httpMethodBadgeColor } from "@/components/layout/Badge";
|
|
16
|
+
import { Callout } from "@/components/layout/Callout";
|
|
16
17
|
import { CopyButton } from "@/components/layout/CopyButton";
|
|
17
18
|
import { Spinner } from "@/components/Spinner";
|
|
18
19
|
import { matchAllowlist, matchAllowlistIn } from "@/utils/playgroundAllowlist";
|
|
@@ -453,12 +454,6 @@ const Meta = styled.span\`
|
|
|
453
454
|
color: \${({ theme }: { theme: Theme }) => theme.colors.gray};
|
|
454
455
|
\`;
|
|
455
456
|
|
|
456
|
-
const ErrorText = styled.p\`
|
|
457
|
-
margin: 0;
|
|
458
|
-
\${({ theme }: { theme: Theme }) => styledSmall(theme)};
|
|
459
|
-
color: \${({ theme }: { theme: Theme }) => theme.colors.error};
|
|
460
|
-
\`;
|
|
461
|
-
|
|
462
457
|
const Placeholder = styled.div\`
|
|
463
458
|
border: dashed 1px \${({ theme }: { theme: Theme }) => theme.colors.grayLight};
|
|
464
459
|
border-radius: \${({ theme }: { theme: Theme }) => theme.spacing.radius.lg};
|
|
@@ -1004,7 +999,9 @@ export function ApiPlayground({
|
|
|
1004
999
|
|
|
1005
1000
|
{error ? (
|
|
1006
1001
|
<Field>
|
|
1007
|
-
<
|
|
1002
|
+
<Callout type="danger">
|
|
1003
|
+
<p>{error}</p>
|
|
1004
|
+
</Callout>
|
|
1008
1005
|
{corsRetry ? (
|
|
1009
1006
|
<Toggle type="button" onClick={retryViaProxy}>
|
|
1010
1007
|
Retry via proxy
|
|
@@ -1 +1 @@
|
|
|
1
|
-
export declare const docsComponentsTemplate = "\"use client\";\nimport React, { createContext, useContext } from \"react\";\nimport styled, { css } from \"styled-components\";\nimport {\n resetButton,\n styledSmall,\n styledStrong,\n styledText,\n} from \"cherry-styled-components\";\nimport Link from \"next/link\";\nimport { mq, Theme } from \"@/app/theme\";\nimport {\n focusModeColumn,\n focusModeHide,\n sidePanelOffset,\n styledAnchor,\n styledTable,\n stylesLists,\n} from \"@/components/layout/SharedStyled\";\nimport { Badge } from \"@/components/layout/Badge\";\nimport { ChatContext } from \"@/components/Chat\";\n\nconst SectionBarContext = createContext(false);\n\nfunction SectionBarProvider({\n hasSectionBar,\n children,\n}: {\n hasSectionBar: boolean;\n children: React.ReactNode;\n}) {\n return (\n <SectionBarContext.Provider value={hasSectionBar}>\n {children}\n </SectionBarContext.Provider>\n );\n}\n\ninterface DocsProps {\n children: React.ReactNode;\n}\n\nconst StyledDocsWrapper = styled.div<{ theme: Theme }>`\n position: relative;\n`;\n\nconst StyledDocsSidebar = styled.div<{ theme: Theme }>`\n clear: both;\n`;\n\n// The <main> landmark wraps only the article content: the sidebar, footer,\n// and nav render outside it so content extractors and assistive tech start at\n// the article.\nconst StyledDocsContainer = styled.main<{\n theme: Theme;\n $isChatOpen?: boolean;\n}>`\n position: relative;\n padding: 0 20px 100px 20px;\n width: 100%;\n ${({ theme }) => styledText(theme)};\n transition: all 0.3s ease;\n\n ${mq(\"lg\")} {\n padding: 0 300px 80px 300px;\n\n ${({ $isChatOpen }) =>\n $isChatOpen &&\n css`\n padding: 0 440px 80px 300px;\n `}\n }\n\n ${sidePanelOffset};\n ${({ $isChatOpen }) => !$isChatOpen && focusModeColumn};\n\n & p {\n color: ${({ theme }) => theme.colors.grayDark};\n hyphens: auto;\n }\n\n & pre {\n max-width: 100%;\n }\n\n ${styledAnchor};\n ${stylesLists};\n ${styledTable};\n\n & img,\n & video,\n & iframe {\n max-width: 100%;\n border-radius: ${({ theme }) => theme.spacing.radius.lg};\n }\n\n & code:not([class]),\n & kbd {\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 overflow-wrap: anywhere;\n }\n\n & .lucide {\n color: ${({ theme }) => theme.colors.primary};\n }\n\n & .aspect-video {\n aspect-ratio: 16 / 9;\n border-radius: ${({ theme }) => theme.spacing.radius.lg};\n }\n`;\n\nexport const StyledMarkdownContainer = styled.div`\n display: flex;\n flex-direction: column;\n gap: 20px;\n flex: 1;\n max-width: 640px;\n margin: auto;\n`;\n\ninterface Props {\n theme?: Theme;\n $isActive?: boolean;\n $isOpen?: boolean;\n $hasSectionBar?: boolean;\n}\n\nexport const StyledSidebar = styled.nav<Props>`\n position: fixed;\n overflow-y: auto;\n max-height: calc(\n 100dvh - ${({ $hasSectionBar }) => ($hasSectionBar ? 104 : 62)}px\n );\n width: 100%;\n z-index: 99;\n top: ${({ $hasSectionBar }) => ($hasSectionBar ? 104 : 62)}px;\n height: 100%;\n padding: 20px;\n opacity: 0;\n pointer-events: none;\n transition: all 0.3s ease;\n transform: translateY(30px);\n left: 0;\n background: ${({ theme }) => theme.colors.light};\n -webkit-overflow-scrolling: touch;\n display: flex;\n flex-direction: column;\n\n &::-webkit-scrollbar {\n display: none;\n }\n\n ${mq(\"lg\")} {\n border-right: solid 1px ${({ theme }) => theme.colors.grayLight};\n transition: none;\n max-height: 100dvh;\n width: 220px;\n background: transparent;\n padding: 82px 20px 20px 20px;\n opacity: 1;\n pointer-events: all;\n transform: translateY(0);\n background: ${({ theme }) =>\n `color-mix(in srgb, ${theme.colors.primaryLight} 5%, transparent)`};\n top: 0;\n width: 280px;\n }\n\n ${({ $isActive }) =>\n $isActive &&\n css`\n transform: translateY(0);\n opacity: 1;\n pointer-events: all;\n `}\n\n ${focusModeHide(\"left\")};\n`;\n\nexport const StyledSidebarFooter = styled.div`\n padding: 22px 20px;\n position: sticky;\n border-top: 1px solid ${({ theme }) => theme.colors.grayLight};\n background: ${({ theme }) =>\n `color-mix(in srgb, ${theme.colors.primaryLight} 5%, transparent)`};\n margin: 0 -20px -20px;\n bottom: -20px;\n backdrop-filter: blur(10px);\n\n ${mq(\"lg\")} {\n padding: 16px 20px;\n }\n`;\n\nexport const StyledIndexSidebar = styled.ul<{ theme: Theme }>`\n display: none;\n list-style: none;\n margin: 0;\n padding: 0;\n position: fixed;\n top: 0;\n right: 0;\n width: 280px;\n height: 100dvh;\n overflow-y: auto;\n z-index: 1;\n padding: 82px 20px 20px 20px;\n background: ${({ theme }) => theme.colors.light};\n border-left: solid 1px ${({ theme }) => theme.colors.grayLight};\n -webkit-overflow-scrolling: touch;\n\n &::-webkit-scrollbar {\n display: none;\n }\n\n ${mq(\"lg\")} {\n display: block;\n }\n\n & li {\n padding: 5px 0;\n }\n\n ${focusModeHide(\"right\")};\n`;\n\nexport const StyledIndexSidebarLabel = styled.span<{ theme: Theme }>`\n ${({ theme }) => styledSmall(theme)};\n color: ${({ theme }) => theme.colors.grayDark};\n`;\n\nexport const StyledIndexSidebarLi = styled.li<{\n theme: Theme;\n $isActive: boolean;\n}>`\n &::before {\n content: \"\";\n display: block;\n position: absolute;\n left: 0;\n height: 20px;\n width: 1px;\n background: transparent;\n transition: all 0.3s ease;\n }\n\n ${({ $isActive, theme }) =>\n $isActive &&\n css`\n &::before {\n background: ${theme.colors.primary};\n }\n `}\n`;\n\nexport const StyledIndexSidebarLink = styled.a<{\n theme: Theme;\n $isActive: boolean;\n}>`\n ${({ theme }) => styledSmall(theme)};\n color: ${({ theme, $isActive }) =>\n $isActive ? theme.colors.primary : theme.colors.dark};\n font-weight: ${({ $isActive }) => ($isActive ? \"600\" : \"400\")};\n text-decoration: none;\n transition: all 0.3s ease;\n\n &:hover {\n color: ${({ theme }) => theme.colors.primary};\n }\n`;\n\nexport const StyledSidebarList = styled.ul`\n list-style: none;\n margin: 0;\n padding: 0;\n\n &:last-of-type {\n margin-bottom: auto;\n }\n`;\n\nexport const StyledStrong = styled.strong<{ theme: Theme }>`\n font-weight: 600;\n ${({ theme }) => styledStrong(theme)};\n color: ${({ theme }) => theme.colors.accentStrong};\n display: inline-flex;\n align-items: center;\n gap: 8px;\n\n & svg {\n flex-shrink: 0;\n }\n`;\n\nexport const StyledSidebarListItem = styled.li`\n display: flex;\n gap: 10px;\n clear: both;\n`;\n\n// Shared appearance for every sidebar row - leaf links AND nested group\n// headers - so hover, active state, and the left rail read identically.\nconst sidebarRowStyles = css<Props>`\n text-decoration: none;\n font-size: ${({ theme }) => theme.fontSizes.small.lg};\n line-height: 1.6;\n color: ${({ theme }) => theme.colors.accentMuted};\n padding: 5px 0 5px 20px;\n display: flex;\n align-items: center;\n gap: 8px;\n flex: 1;\n min-width: 0;\n transition: all 0.3s ease;\n border-left: solid 1px ${({ theme }) => theme.colors.grayLight};\n\n & svg {\n flex-shrink: 0;\n }\n\n &:hover {\n color: ${({ theme }) => theme.colors.accent};\n border-color: ${({ theme }) => theme.colors.primary};\n }\n\n ${({ $isActive, theme }) =>\n $isActive &&\n css`\n color: ${theme.colors.accentStrong};\n border-color: ${theme.colors.primary};\n font-weight: 600;\n `};\n`;\n\n// The collapse chevron points right when closed and rotates to point down\n// when the group is open.\nconst sidebarChevron = css<Props>`\n & .lucide-chevron-right {\n margin-left: auto;\n transition: transform 0.3s ease;\n\n ${({ $isOpen }) =>\n $isOpen &&\n css`\n transform: rotate(90deg);\n `}\n }\n`;\n\nexport const StyledSidebarListItemLink = styled(Link)<Props>`\n ${sidebarRowStyles};\n`;\n\n// Compact HTTP-method label shown before a generated API endpoint link, colored\n// by verb so endpoints are scannable in the sidebar. Only rendered when a link\n// carries an `httpMethod` (endpoint pages do; hand-written pages do not).\n// The look is Badge's mono variation (tinted, solid when active); only\n// sidebar metrics are adjusted here.\nexport const StyledSidebarMethodTag = styled(Badge)`\n flex-shrink: 0;\n font-size: 9px;\n letter-spacing: 0.02em;\n padding: 1px 4px;\n border: none;\n`;\n\n// Nested navigation group. The header shares the link appearance/hover; a\n// non-navigable group is a single toggle button, while a group that is also a\n// page pairs a link with a chevron toggle. Children live in\n// StyledSidebarGroupContent, which animates open/closed via height 0 <-> auto\n// (enabled by interpolate-size in GlobalStyles, same as the Accordion).\nexport const StyledSidebarGroupButton = styled.button<Props>`\n ${resetButton};\n ${sidebarRowStyles};\n ${sidebarChevron};\n width: 100%;\n text-align: left;\n\n /* Buttons aren't covered by the global a:focus-visible ring, so this\n nav-row toggle carries its own copy of it. */\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\nexport const StyledSidebarGroupRow = styled.div<Props>`\n ${sidebarRowStyles};\n ${sidebarChevron};\n\n /* The row is a plain div, so it never matches :focus-visible itself. Ring the\n whole row when its inner link or chevron takes keyboard focus instead, to\n match the leaf-row focus treatment. */\n &:has(:focus-visible) {\n border-radius: ${({ theme }) => theme.spacing.radius.xs};\n box-shadow: 0 0 0 2px ${({ theme }) => theme.colors.primaryLight};\n }\n`;\n\nexport const StyledSidebarGroupLink = styled(Link)`\n display: flex;\n align-items: center;\n gap: 8px;\n flex: 1;\n min-width: 0;\n color: inherit;\n text-decoration: none;\n\n & svg {\n flex-shrink: 0;\n }\n\n /* Ring is drawn on the parent row via :has(:focus-visible); suppress the\n global a:focus-visible glow so it isn't drawn twice. */\n &:focus-visible {\n outline: none;\n box-shadow: none;\n }\n`;\n\nexport const StyledSidebarGroupChevron = styled.button`\n display: inline-flex;\n align-items: center;\n justify-content: center;\n flex-shrink: 0;\n padding: 0;\n border: 0;\n background: none;\n color: inherit;\n cursor: pointer;\n\n /* Ring is drawn on the parent row via :has(:focus-visible). */\n &:focus-visible {\n outline: none;\n }\n`;\n\nexport const StyledSidebarGroupContent = styled.ul<Props>`\n list-style: none;\n margin: 0;\n padding: 0;\n height: 0;\n overflow: clip;\n transition: all 0.3s ease;\n\n ${({ $isOpen }) =>\n $isOpen &&\n css`\n height: auto;\n `}\n`;\n\nexport const StyleMobileBar = styled.button<Props>`\n ${resetButton};\n position: fixed;\n z-index: 999;\n bottom: 0;\n right: 20px;\n font-size: ${({ theme }) => theme.fontSizes.strong.lg};\n line-height: ${({ theme }) => theme.fontSizes.strong.lg};\n box-shadow: ${({ theme }) => theme.shadows.sm};\n background: ${({ theme }) => theme.colors.primary};\n color: ${({ theme }) => theme.colors.surface};\n backdrop-filter: blur(10px);\n -webkit-backdrop-filter: blur(10px);\n padding: 10px;\n border-radius: 100px;\n margin: 0 0 20px 0;\n font-weight: 600;\n display: flex;\n justify-content: flex-start;\n width: auto;\n\n ${mq(\"lg\")} {\n display: none;\n }\n\n ${({ $isActive }) => $isActive && `position: fixed;`};\n`;\n\nexport const StyledMobileBurger = styled.span<Props>`\n display: block;\n margin: auto 0;\n width: 18px;\n height: 18px;\n position: relative;\n overflow: hidden;\n background: transparent;\n position: relative;\n transform: scale(0.8);\n\n &::before,\n &::after {\n content: \"\";\n display: block;\n position: absolute;\n width: 18px;\n height: 3px;\n border-radius: 3px;\n background: ${({ theme }) => theme.colors.surface};\n transition: all 0.3s ease;\n }\n\n &::before {\n top: 3px;\n }\n\n &::after {\n bottom: 3px;\n }\n\n ${({ $isActive }) =>\n $isActive &&\n css`\n &::before {\n transform: translateY(5px) rotate(45deg);\n }\n\n &::after {\n transform: translateY(-4px) rotate(-45deg);\n }\n `};\n`;\n\nexport const StyledMissingComponent = styled.div`\n background: ${({ theme }) => theme.colors.error};\n border-radius: ${({ theme }) => theme.spacing.radius.lg};\n padding: 20px;\n font-size: ${({ theme }) => theme.fontSizes.small.lg};\n color: ${({ theme }) => theme.colors.surface};\n font-weight: 600;\n display: flex;\n gap: 10px;\n align-items: center;\n`;\n\n// Visually hidden but present for crawlers and agents: points at llms.txt and\n// the .md mirrors. Rendered as the first element of the site layout.\nconst StyledLlmsDirective = styled.div`\n position: absolute;\n width: 1px;\n height: 1px;\n padding: 0;\n margin: -1px;\n overflow: hidden;\n clip: rect(0 0 0 0);\n white-space: nowrap;\n border: 0;\n`;\n\nfunction LlmsDirective() {\n return (\n <StyledLlmsDirective data-markdown-ignore>\n <a href=\"/llms.txt\">Documentation index for AI agents (llms.txt)</a>.\n Markdown versions of every page are available by appending .md to the page\n URL. The full corpus is at <a href=\"/llms-full.txt\">/llms-full.txt</a>.\n </StyledLlmsDirective>\n );\n}\n\ninterface DocsWrapperProps {\n children: React.ReactNode;\n}\n\nfunction DocsWrapper({ children }: DocsWrapperProps) {\n return <StyledDocsWrapper>{children}</StyledDocsWrapper>;\n}\n\nfunction DocsSidebar({ children }: DocsProps) {\n return <StyledDocsSidebar>{children}</StyledDocsSidebar>;\n}\n\nfunction DocsContainer({ children }: DocsProps) {\n const { isOpen } = useContext(ChatContext);\n\n return (\n <StyledDocsContainer $isChatOpen={isOpen}>{children}</StyledDocsContainer>\n );\n}\n\nexport {\n DocsWrapper,\n DocsSidebar,\n DocsContainer,\n LlmsDirective,\n SectionBarContext,\n SectionBarProvider,\n};\n";
|
|
1
|
+
export declare const docsComponentsTemplate = "\"use client\";\nimport React, { createContext, useContext } from \"react\";\nimport styled, { css } from \"styled-components\";\nimport {\n resetButton,\n styledSmall,\n styledStrong,\n styledText,\n} from \"cherry-styled-components\";\nimport Link from \"next/link\";\nimport { mq, Theme } from \"@/app/theme\";\nimport {\n focusModeColumn,\n focusModeHide,\n sidePanelOffset,\n styledAnchor,\n styledTable,\n stylesLists,\n} from \"@/components/layout/SharedStyled\";\nimport { Badge } from \"@/components/layout/Badge\";\nimport { ChatContext } from \"@/components/Chat\";\n\nconst SectionBarContext = createContext(false);\n\nfunction SectionBarProvider({\n hasSectionBar,\n children,\n}: {\n hasSectionBar: boolean;\n children: React.ReactNode;\n}) {\n return (\n <SectionBarContext.Provider value={hasSectionBar}>\n {children}\n </SectionBarContext.Provider>\n );\n}\n\ninterface DocsProps {\n children: React.ReactNode;\n}\n\nconst StyledDocsWrapper = styled.div<{ theme: Theme }>`\n position: relative;\n`;\n\nconst StyledDocsSidebar = styled.div<{ theme: Theme }>`\n clear: both;\n`;\n\n// The <main> landmark wraps only the article content: the sidebar, footer,\n// and nav render outside it so content extractors and assistive tech start at\n// the article.\nconst StyledDocsContainer = styled.main<{\n theme: Theme;\n $isChatOpen?: boolean;\n}>`\n position: relative;\n padding: 0 20px 100px 20px;\n width: 100%;\n ${({ theme }) => styledText(theme)};\n transition: all 0.3s ease;\n\n ${mq(\"lg\")} {\n padding: 0 300px 80px 300px;\n\n ${({ $isChatOpen }) =>\n $isChatOpen &&\n css`\n padding: 0 440px 80px 300px;\n `}\n }\n\n ${sidePanelOffset};\n ${({ $isChatOpen }) => !$isChatOpen && focusModeColumn};\n\n & p {\n color: ${({ theme }) => theme.colors.grayDark};\n hyphens: auto;\n }\n\n & pre {\n max-width: 100%;\n }\n\n ${styledAnchor};\n ${stylesLists};\n ${styledTable};\n\n & img,\n & video,\n & iframe {\n max-width: 100%;\n border-radius: ${({ theme }) => theme.spacing.radius.lg};\n }\n\n & code:not([class]),\n & kbd {\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 overflow-wrap: anywhere;\n }\n\n & .lucide {\n color: ${({ theme }) => theme.colors.primary};\n }\n\n & .aspect-video {\n aspect-ratio: 16 / 9;\n border-radius: ${({ theme }) => theme.spacing.radius.lg};\n }\n`;\n\nexport const StyledMarkdownContainer = styled.div`\n display: flex;\n flex-direction: column;\n gap: 20px;\n flex: 1;\n max-width: 640px;\n margin: auto;\n`;\n\ninterface Props {\n theme?: Theme;\n $isActive?: boolean;\n $isOpen?: boolean;\n $hasSectionBar?: boolean;\n}\n\nexport const StyledSidebar = styled.nav<Props>`\n position: fixed;\n overflow-y: auto;\n max-height: calc(\n 100dvh - ${({ $hasSectionBar }) => ($hasSectionBar ? 104 : 62)}px\n );\n width: 100%;\n z-index: 99;\n top: ${({ $hasSectionBar }) => ($hasSectionBar ? 104 : 62)}px;\n height: 100%;\n padding: 20px;\n opacity: 0;\n pointer-events: none;\n transition: all 0.3s ease;\n transform: translateY(30px);\n left: 0;\n background: ${({ theme }) => theme.colors.light};\n -webkit-overflow-scrolling: touch;\n display: flex;\n flex-direction: column;\n\n &::-webkit-scrollbar {\n display: none;\n }\n\n ${mq(\"lg\")} {\n border-right: solid 1px ${({ theme }) => theme.colors.grayLight};\n transition: none;\n max-height: 100dvh;\n width: 220px;\n background: transparent;\n padding: 82px 20px 20px 20px;\n opacity: 1;\n pointer-events: all;\n transform: translateY(0);\n background: ${({ theme }) =>\n `color-mix(in srgb, ${theme.colors.primaryLight} 5%, transparent)`};\n top: 0;\n width: 280px;\n }\n\n ${({ $isActive }) =>\n $isActive &&\n css`\n transform: translateY(0);\n opacity: 1;\n pointer-events: all;\n `}\n\n ${focusModeHide(\"left\")};\n`;\n\nexport const StyledSidebarFooter = styled.div`\n padding: 22px 20px;\n position: sticky;\n border-top: 1px solid ${({ theme }) => theme.colors.grayLight};\n background: ${({ theme }) =>\n `color-mix(in srgb, ${theme.colors.primaryLight} 5%, transparent)`};\n margin: 0 -20px -20px;\n bottom: -20px;\n backdrop-filter: blur(10px);\n\n ${mq(\"lg\")} {\n padding: 16px 20px;\n }\n`;\n\nexport const StyledIndexSidebar = styled.ul<{ theme: Theme }>`\n display: none;\n list-style: none;\n margin: 0;\n padding: 0;\n position: fixed;\n top: 0;\n right: 0;\n width: 280px;\n height: 100dvh;\n overflow-y: auto;\n z-index: 1;\n padding: 82px 20px 20px 20px;\n background: ${({ theme }) => theme.colors.light};\n border-left: solid 1px ${({ theme }) => theme.colors.grayLight};\n -webkit-overflow-scrolling: touch;\n\n &::-webkit-scrollbar {\n display: none;\n }\n\n ${mq(\"lg\")} {\n display: block;\n }\n\n & li {\n padding: 5px 0;\n }\n\n ${focusModeHide(\"right\")};\n`;\n\nexport const StyledIndexSidebarLabel = styled.span<{ theme: Theme }>`\n ${({ theme }) => styledSmall(theme)};\n color: ${({ theme }) => theme.colors.grayDark};\n`;\n\nexport const StyledIndexSidebarLi = styled.li<{\n theme: Theme;\n $isActive: boolean;\n}>`\n &::before {\n content: \"\";\n display: block;\n position: absolute;\n left: 0;\n height: 20px;\n width: 1px;\n background: transparent;\n transition: all 0.3s ease;\n }\n\n ${({ $isActive, theme }) =>\n $isActive &&\n css`\n &::before {\n background: ${theme.colors.primary};\n }\n `}\n`;\n\nexport const StyledIndexSidebarLink = styled.a<{\n theme: Theme;\n $isActive: boolean;\n}>`\n ${({ theme }) => styledSmall(theme)};\n color: ${({ theme, $isActive }) =>\n $isActive ? theme.colors.primary : theme.colors.dark};\n font-weight: ${({ $isActive }) => ($isActive ? \"600\" : \"400\")};\n text-decoration: none;\n transition: all 0.3s ease;\n\n &:hover {\n color: ${({ theme }) => theme.colors.primary};\n }\n`;\n\nexport const StyledSidebarList = styled.ul`\n list-style: none;\n margin: 0;\n padding: 0;\n\n &:last-of-type {\n margin-bottom: auto;\n }\n`;\n\nexport const StyledStrong = styled.strong<{ theme: Theme }>`\n font-weight: 600;\n ${({ theme }) => styledStrong(theme)};\n color: ${({ theme }) => theme.colors.accentStrong};\n display: inline-flex;\n align-items: center;\n gap: 8px;\n\n & svg {\n flex-shrink: 0;\n }\n`;\n\nexport const StyledSidebarListItem = styled.li`\n display: flex;\n gap: 10px;\n clear: both;\n`;\n\n// Shared appearance for every sidebar row - leaf links AND nested group\n// headers - so hover, active state, and the left rail read identically.\nconst sidebarRowStyles = css<Props>`\n text-decoration: none;\n font-size: ${({ theme }) => theme.fontSizes.small.lg};\n line-height: 1.6;\n color: ${({ theme }) => theme.colors.accentMuted};\n padding: 5px 0 5px 20px;\n display: flex;\n align-items: center;\n gap: 8px;\n flex: 1;\n min-width: 0;\n transition: all 0.3s ease;\n border-left: solid 1px ${({ theme }) => theme.colors.grayLight};\n\n & svg {\n flex-shrink: 0;\n }\n\n &:hover {\n color: ${({ theme }) => theme.colors.accent};\n border-color: ${({ theme }) => theme.colors.primary};\n }\n\n ${({ $isActive, theme }) =>\n $isActive &&\n css`\n color: ${theme.colors.accentStrong};\n border-color: ${theme.colors.primary};\n font-weight: 600;\n `};\n`;\n\n// The collapse chevron points right when closed and rotates to point down\n// when the group is open.\nconst sidebarChevron = css<Props>`\n & .lucide-chevron-right {\n margin-left: auto;\n transition: transform 0.3s ease;\n\n ${({ $isOpen }) =>\n $isOpen &&\n css`\n transform: rotate(90deg);\n `}\n }\n`;\n\nexport const StyledSidebarListItemLink = styled(Link)<Props>`\n ${sidebarRowStyles};\n`;\n\n// Compact HTTP-method label shown before a generated API endpoint link, colored\n// by verb so endpoints are scannable in the sidebar. Only rendered when a link\n// carries an `httpMethod` (endpoint pages do; hand-written pages do not).\n// The look is Badge's mono variation (tinted, solid when active); only\n// sidebar metrics are adjusted here.\nexport const StyledSidebarMethodTag = styled(Badge)`\n flex-shrink: 0;\n font-size: 9px;\n letter-spacing: 0.02em;\n padding: 1px 4px;\n border: none;\n`;\n\n// Nested navigation group. The header shares the link appearance/hover; a\n// non-navigable group is a single toggle button, while a group that is also a\n// page pairs a link with a chevron toggle. Children live in\n// StyledSidebarGroupContent, which animates open/closed via height 0 <-> auto\n// (enabled by interpolate-size in GlobalStyles, same as the Accordion).\nexport const StyledSidebarGroupButton = styled.button<Props>`\n ${resetButton};\n ${sidebarRowStyles};\n ${sidebarChevron};\n width: 100%;\n text-align: left;\n\n /* Buttons aren't covered by the global a:focus-visible ring, so this\n nav-row toggle carries its own copy of it. */\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\nexport const StyledSidebarGroupRow = styled.div<Props>`\n ${sidebarRowStyles};\n ${sidebarChevron};\n\n /* The row is a plain div, so it never matches :focus-visible itself. Ring the\n whole row when its inner link or chevron takes keyboard focus instead, to\n match the leaf-row focus treatment. */\n &:has(:focus-visible) {\n border-radius: ${({ theme }) => theme.spacing.radius.xs};\n box-shadow: 0 0 0 2px ${({ theme }) => theme.colors.primaryLight};\n }\n`;\n\nexport const StyledSidebarGroupLink = styled(Link)`\n display: flex;\n align-items: center;\n gap: 8px;\n flex: 1;\n min-width: 0;\n color: inherit;\n text-decoration: none;\n\n & svg {\n flex-shrink: 0;\n }\n\n /* Ring is drawn on the parent row via :has(:focus-visible); suppress the\n global a:focus-visible glow so it isn't drawn twice. */\n &:focus-visible {\n outline: none;\n box-shadow: none;\n }\n`;\n\nexport const StyledSidebarGroupChevron = styled.button`\n display: inline-flex;\n align-items: center;\n justify-content: center;\n flex-shrink: 0;\n padding: 0;\n border: 0;\n background: none;\n color: inherit;\n cursor: pointer;\n\n /* Ring is drawn on the parent row via :has(:focus-visible). */\n &:focus-visible {\n outline: none;\n }\n`;\n\nexport const StyledSidebarGroupContent = styled.ul<Props>`\n list-style: none;\n margin: 0;\n padding: 0;\n height: 0;\n overflow: clip;\n transition: all 0.3s ease;\n\n ${({ $isOpen }) =>\n $isOpen &&\n css`\n height: auto;\n `}\n`;\n\nexport const StyleMobileBar = styled.button<Props>`\n ${resetButton};\n position: fixed;\n z-index: 999;\n bottom: 0;\n right: 20px;\n font-size: ${({ theme }) => theme.fontSizes.strong.lg};\n line-height: ${({ theme }) => theme.fontSizes.strong.lg};\n box-shadow: ${({ theme }) => theme.shadows.sm};\n background: ${({ theme }) => theme.colors.primary};\n color: ${({ theme }) => theme.colors.surface};\n backdrop-filter: blur(10px);\n -webkit-backdrop-filter: blur(10px);\n padding: 10px;\n border-radius: 100px;\n margin: 0 0 20px 0;\n font-weight: 600;\n display: flex;\n justify-content: flex-start;\n width: auto;\n\n ${mq(\"lg\")} {\n display: none;\n }\n\n ${({ $isActive }) => $isActive && `position: fixed;`};\n`;\n\nexport const StyledMobileBurger = styled.span<Props>`\n display: block;\n margin: auto 0;\n width: 18px;\n height: 18px;\n position: relative;\n overflow: hidden;\n background: transparent;\n position: relative;\n transform: scale(0.8);\n\n &::before,\n &::after {\n content: \"\";\n display: block;\n position: absolute;\n width: 18px;\n height: 3px;\n border-radius: 3px;\n background: ${({ theme }) => theme.colors.surface};\n transition: all 0.3s ease;\n }\n\n &::before {\n top: 3px;\n }\n\n &::after {\n bottom: 3px;\n }\n\n ${({ $isActive }) =>\n $isActive &&\n css`\n &::before {\n transform: translateY(5px) rotate(45deg);\n }\n\n &::after {\n transform: translateY(-4px) rotate(-45deg);\n }\n `};\n`;\n\n// Visually hidden but present for crawlers and agents: points at llms.txt and\n// the .md mirrors. Rendered as the first element of the site layout.\nconst StyledLlmsDirective = styled.div`\n position: absolute;\n width: 1px;\n height: 1px;\n padding: 0;\n margin: -1px;\n overflow: hidden;\n clip: rect(0 0 0 0);\n white-space: nowrap;\n border: 0;\n`;\n\nfunction LlmsDirective() {\n return (\n <StyledLlmsDirective data-markdown-ignore>\n <a href=\"/llms.txt\">Documentation index for AI agents (llms.txt)</a>.\n Markdown versions of every page are available by appending .md to the page\n URL. The full corpus is at <a href=\"/llms-full.txt\">/llms-full.txt</a>.\n </StyledLlmsDirective>\n );\n}\n\ninterface DocsWrapperProps {\n children: React.ReactNode;\n}\n\nfunction DocsWrapper({ children }: DocsWrapperProps) {\n return <StyledDocsWrapper>{children}</StyledDocsWrapper>;\n}\n\nfunction DocsSidebar({ children }: DocsProps) {\n return <StyledDocsSidebar>{children}</StyledDocsSidebar>;\n}\n\nfunction DocsContainer({ children }: DocsProps) {\n const { isOpen } = useContext(ChatContext);\n\n return (\n <StyledDocsContainer $isChatOpen={isOpen}>{children}</StyledDocsContainer>\n );\n}\n\nexport {\n DocsWrapper,\n DocsSidebar,\n DocsContainer,\n LlmsDirective,\n SectionBarContext,\n SectionBarProvider,\n};\n";
|
|
@@ -529,18 +529,6 @@ export const StyledMobileBurger = styled.span<Props>\`
|
|
|
529
529
|
\`};
|
|
530
530
|
\`;
|
|
531
531
|
|
|
532
|
-
export const StyledMissingComponent = styled.div\`
|
|
533
|
-
background: \${({ theme }) => theme.colors.error};
|
|
534
|
-
border-radius: \${({ theme }) => theme.spacing.radius.lg};
|
|
535
|
-
padding: 20px;
|
|
536
|
-
font-size: \${({ theme }) => theme.fontSizes.small.lg};
|
|
537
|
-
color: \${({ theme }) => theme.colors.surface};
|
|
538
|
-
font-weight: 600;
|
|
539
|
-
display: flex;
|
|
540
|
-
gap: 10px;
|
|
541
|
-
align-items: center;
|
|
542
|
-
\`;
|
|
543
|
-
|
|
544
532
|
// Visually hidden but present for crawlers and agents: points at llms.txt and
|
|
545
533
|
// the .md mirrors. Rendered as the first element of the site layout.
|
|
546
534
|
const StyledLlmsDirective = styled.div\`
|
|
@@ -1 +1 @@
|
|
|
1
|
-
export declare const platformBuildAndDeployMdxTemplate = "---\ntitle: \"Build & Deploy\"\ndescription: \"Monitor your documentation site's build status and deployment history.\"\ndate: \"2026-02-19\"\ncategory: \"Infrastructure\"\ncategoryOrder: 4\ncategoryIcon: \"server\"\norder: 1\nsection: \"Platform\"\n---\n# Build & Deploy\n\nThe Build & Deploy page shows your documentation site's build and deployment history. Every time you publish changes or push to GitHub, a new deployment is created.\n\n## Deployment status\n\nThe project header always shows your current deployment status:\n\n- **Ready** - your site is live and up to date\n- **Building** - a new deployment is in progress\n- **Queued** - a deployment is waiting to start\n- **Error** - the build failed\n\n<Callout type=\"warning\">\n If a deployment fails, check the build logs for error details.
|
|
1
|
+
export declare const platformBuildAndDeployMdxTemplate = "---\ntitle: \"Build & Deploy\"\ndescription: \"Monitor your documentation site's build status and deployment history.\"\ndate: \"2026-02-19\"\ncategory: \"Infrastructure\"\ncategoryOrder: 4\ncategoryIcon: \"server\"\norder: 1\nsection: \"Platform\"\n---\n# Build & Deploy\n\nThe Build & Deploy page shows your documentation site's build and deployment history. Every time you publish changes or push to GitHub, a new deployment is created.\n\n## Deployment status\n\nThe project header always shows your current deployment status:\n\n- **Ready** - your site is live and up to date\n- **Building** - a new deployment is in progress\n- **Queued** - a deployment is waiting to start\n- **Error** - the build failed\n\n<Callout type=\"warning\">\n If a deployment fails, check the build logs for error details. Broken MDX does not fail the build - the affected page renders an inline error panel describing the syntax error while the rest of the site deploys - and invalid frontmatter is ignored with a warning in the build logs.\n</Callout>\n\n## Build logs\n\nClick on any deployment to view its build logs. These show the full output of the build process, making it easy to diagnose issues.\n\n## Deployment triggers\n\nDeployments are triggered in three ways:\n\n1. **Publishing from Doccupine** - clicking Publish in the project header\n2. **Pushing to GitHub** - pushing to the `main` branch of your repository triggers an automatic deploy via webhook\n3. **Configuration changes** - saving AI assistant settings triggers a redeploy since those are stored as environment variables\n\n## Visiting your site\n\nClick the **Visit** button in the project header to open your live documentation site in a new tab.";
|
|
@@ -22,7 +22,7 @@ The project header always shows your current deployment status:
|
|
|
22
22
|
- **Error** - the build failed
|
|
23
23
|
|
|
24
24
|
<Callout type="warning">
|
|
25
|
-
If a deployment fails, check the build logs for error details.
|
|
25
|
+
If a deployment fails, check the build logs for error details. Broken MDX does not fail the build - the affected page renders an inline error panel describing the syntax error while the rest of the site deploys - and invalid frontmatter is ignored with a warning in the build logs.
|
|
26
26
|
</Callout>
|
|
27
27
|
|
|
28
28
|
## Build logs
|
|
@@ -24,7 +24,7 @@ export const packageJsonTemplate = JSON.stringify({
|
|
|
24
24
|
minisearch: "^7.2.0",
|
|
25
25
|
next: "16.2.12",
|
|
26
26
|
"next-mdx-remote": "^6.0.0",
|
|
27
|
-
"posthog-js": "^1.407.
|
|
27
|
+
"posthog-js": "^1.407.8",
|
|
28
28
|
"posthog-node": "^5.46.1",
|
|
29
29
|
react: "19.2.8",
|
|
30
30
|
"react-dom": "19.2.8",
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "doccupine",
|
|
3
|
-
"version": "0.0.
|
|
3
|
+
"version": "0.0.140",
|
|
4
4
|
"description": "Free and open-source documentation platform. Write MDX, get a production-ready site with AI chat, built-in components, and an MCP server - in one command.",
|
|
5
5
|
"main": "dist/index.js",
|
|
6
6
|
"bin": {
|