doccupine 0.0.145 → 0.0.147
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/README.md +11 -2
- package/dist/cli.d.ts +7 -0
- package/dist/cli.js +41 -0
- package/dist/generator/generated-page-publisher.d.ts +21 -0
- package/dist/generator/generated-page-publisher.js +124 -0
- package/dist/generator/generated-route-manager.d.ts +3 -0
- package/dist/generator/generated-route-manager.js +21 -8
- package/dist/generator/mdx-pass-builder.d.ts +31 -0
- package/dist/generator/mdx-pass-builder.js +45 -0
- package/dist/generator/mdx-reconciliation-coordinator.d.ts +83 -0
- package/dist/generator/mdx-reconciliation-coordinator.js +471 -0
- package/dist/generator/openapi-refresh-coordinator.d.ts +42 -0
- package/dist/generator/openapi-refresh-coordinator.js +211 -0
- package/dist/generator/page-renderer.js +18 -13
- package/dist/generator/section-index-generator.d.ts +10 -0
- package/dist/generator/section-index-generator.js +68 -0
- package/dist/generator/secure-source-fs.js +5 -4
- package/dist/generator/site-artifacts.js +2 -2
- package/dist/generator/watch-coordinator.d.ts +8 -0
- package/dist/generator/watch-coordinator.js +131 -53
- package/dist/index.js +8 -2
- package/dist/lib/layout.js +18 -10
- package/dist/lib/openapi-rendering.d.ts +17 -0
- package/dist/lib/openapi-rendering.js +193 -0
- package/dist/lib/openapi.d.ts +1 -7
- package/dist/lib/openapi.js +2 -192
- package/dist/lib/output-safety.js +10 -3
- package/dist/lib/structures.js +4 -0
- package/dist/lib/utils.d.ts +14 -0
- package/dist/lib/utils.js +30 -8
- package/dist/mdx-to-nextjs-generator.d.ts +7 -65
- package/dist/mdx-to-nextjs-generator.js +94 -783
- package/dist/templates/components/Chat.d.ts +1 -1
- package/dist/templates/components/Chat.js +20 -691
- package/dist/templates/components/ChatStyles.d.ts +1 -0
- package/dist/templates/components/ChatStyles.js +695 -0
- package/dist/templates/components/layout/ApiPlayground.d.ts +1 -1
- package/dist/templates/components/layout/ApiPlayground.js +14 -148
- package/dist/templates/mdx/platform/analytics.mdx.d.ts +1 -1
- package/dist/templates/mdx/platform/analytics.mdx.js +13 -0
- package/dist/templates/mdx/platform/fonts-settings.mdx.d.ts +1 -1
- package/dist/templates/mdx/platform/fonts-settings.mdx.js +16 -0
- package/dist/templates/mdx/platform/publishing.mdx.d.ts +1 -1
- package/dist/templates/mdx/platform/publishing.mdx.js +16 -1
- package/dist/templates/mdx/platform/self-updating-docs.mdx.d.ts +1 -1
- package/dist/templates/mdx/platform/self-updating-docs.mdx.js +17 -5
- package/dist/templates/package.js +3 -2
- package/dist/templates/prettierignore.d.ts +1 -1
- package/dist/templates/prettierignore.js +11 -0
- package/dist/templates/utils/apiPlayground.d.ts +1 -0
- package/dist/templates/utils/apiPlayground.js +149 -0
- package/dist/templates/utils/orderNavItems.d.ts +1 -1
- package/dist/templates/utils/orderNavItems.js +1 -1
- package/package.json +1 -1
|
@@ -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 { 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";
|
|
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 {\n LOCATIONS,\n LOCATION_TITLES,\n applyPathParams,\n bufferToBase64,\n classifyResponse,\n codeLanguage,\n firstJsonExample,\n prettyBody,\n schemaTypeLabel,\n serverBase,\n} from \"@/utils/apiPlayground\";\nimport type { BuiltRequest, PlaygroundResponse } from \"@/utils/apiPlayground\";\nimport type { OperationDescriptor, ParameterDescriptor } from \"@/types/openapi\";\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 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\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";
|
|
@@ -20,30 +20,20 @@ import { matchAllowlist, matchAllowlistIn } from "@/utils/playgroundAllowlist";
|
|
|
20
20
|
import type { AllowlistEntry } from "@/utils/playgroundAllowlist";
|
|
21
21
|
import { buildSnippets } from "@/utils/apiSnippets";
|
|
22
22
|
import type { SnippetLanguage } from "@/utils/apiSnippets";
|
|
23
|
-
import
|
|
24
|
-
|
|
25
|
-
|
|
26
|
-
|
|
27
|
-
|
|
28
|
-
|
|
29
|
-
|
|
30
|
-
|
|
31
|
-
|
|
32
|
-
|
|
33
|
-
|
|
34
|
-
|
|
35
|
-
|
|
36
|
-
|
|
37
|
-
byteLength: number;
|
|
38
|
-
durationMs: number;
|
|
39
|
-
}
|
|
40
|
-
|
|
41
|
-
interface BuiltRequest {
|
|
42
|
-
url: string;
|
|
43
|
-
headers: Record<string, string>;
|
|
44
|
-
body: string | null;
|
|
45
|
-
secretHeaderNames: string[];
|
|
46
|
-
}
|
|
23
|
+
import {
|
|
24
|
+
LOCATIONS,
|
|
25
|
+
LOCATION_TITLES,
|
|
26
|
+
applyPathParams,
|
|
27
|
+
bufferToBase64,
|
|
28
|
+
classifyResponse,
|
|
29
|
+
codeLanguage,
|
|
30
|
+
firstJsonExample,
|
|
31
|
+
prettyBody,
|
|
32
|
+
schemaTypeLabel,
|
|
33
|
+
serverBase,
|
|
34
|
+
} from "@/utils/apiPlayground";
|
|
35
|
+
import type { BuiltRequest, PlaygroundResponse } from "@/utils/apiPlayground";
|
|
36
|
+
import type { OperationDescriptor, ParameterDescriptor } from "@/types/openapi";
|
|
47
37
|
|
|
48
38
|
export interface ApiPlaygroundProps {
|
|
49
39
|
operation: OperationDescriptor;
|
|
@@ -56,116 +46,6 @@ export interface ApiPlaygroundProps {
|
|
|
56
46
|
snippetLanguages?: SnippetLanguage[];
|
|
57
47
|
}
|
|
58
48
|
|
|
59
|
-
function schemaTypeLabel(schema: unknown): string {
|
|
60
|
-
if (schema && typeof schema === "object") {
|
|
61
|
-
const record = schema as { type?: unknown; format?: unknown };
|
|
62
|
-
if (typeof record.type === "string") {
|
|
63
|
-
return typeof record.format === "string"
|
|
64
|
-
? record.type + " (" + record.format + ")"
|
|
65
|
-
: record.type;
|
|
66
|
-
}
|
|
67
|
-
}
|
|
68
|
-
return "string";
|
|
69
|
-
}
|
|
70
|
-
|
|
71
|
-
function serverBase(server: ServerDescriptor | undefined): string {
|
|
72
|
-
if (!server) return "";
|
|
73
|
-
let url = server.url;
|
|
74
|
-
const variables = server.variables;
|
|
75
|
-
if (variables) {
|
|
76
|
-
for (const key of Object.keys(variables)) {
|
|
77
|
-
url = url.split("{" + key + "}").join(variables[key].default);
|
|
78
|
-
}
|
|
79
|
-
}
|
|
80
|
-
while (url.endsWith("/")) url = url.slice(0, -1);
|
|
81
|
-
return url;
|
|
82
|
-
}
|
|
83
|
-
|
|
84
|
-
function applyPathParams(
|
|
85
|
-
template: string,
|
|
86
|
-
values: Record<string, string>,
|
|
87
|
-
): string {
|
|
88
|
-
let result = template;
|
|
89
|
-
for (const key of Object.keys(values)) {
|
|
90
|
-
result = result
|
|
91
|
-
.split("{" + key + "}")
|
|
92
|
-
.join(encodeURIComponent(values[key]));
|
|
93
|
-
}
|
|
94
|
-
return result;
|
|
95
|
-
}
|
|
96
|
-
|
|
97
|
-
function firstJsonExample(op: OperationDescriptor): {
|
|
98
|
-
contentType: string;
|
|
99
|
-
text: string;
|
|
100
|
-
} | null {
|
|
101
|
-
if (!op.requestBody || op.requestBody.content.length === 0) return null;
|
|
102
|
-
const media =
|
|
103
|
-
op.requestBody.content.find((m) => m.contentType.includes("json")) ??
|
|
104
|
-
op.requestBody.content[0];
|
|
105
|
-
let text = "";
|
|
106
|
-
if (media.example !== undefined) {
|
|
107
|
-
try {
|
|
108
|
-
text = JSON.stringify(media.example, null, 2);
|
|
109
|
-
} catch {
|
|
110
|
-
text = "";
|
|
111
|
-
}
|
|
112
|
-
}
|
|
113
|
-
return { contentType: media.contentType, text };
|
|
114
|
-
}
|
|
115
|
-
|
|
116
|
-
function classifyResponse(
|
|
117
|
-
contentType: string | null,
|
|
118
|
-
): "image" | "video" | "audio" | "text" | "binary" {
|
|
119
|
-
if (!contentType) return "text";
|
|
120
|
-
const t = contentType.toLowerCase();
|
|
121
|
-
if (t.startsWith("image/") && !t.includes("svg")) return "image";
|
|
122
|
-
if (t.startsWith("video/")) return "video";
|
|
123
|
-
if (t.startsWith("audio/")) return "audio";
|
|
124
|
-
if (
|
|
125
|
-
t.includes("json") ||
|
|
126
|
-
t.startsWith("text/") ||
|
|
127
|
-
t.includes("xml") ||
|
|
128
|
-
t.includes("svg") ||
|
|
129
|
-
t.includes("html") ||
|
|
130
|
-
t.includes("javascript") ||
|
|
131
|
-
t.includes("csv")
|
|
132
|
-
) {
|
|
133
|
-
return "text";
|
|
134
|
-
}
|
|
135
|
-
return "binary";
|
|
136
|
-
}
|
|
137
|
-
|
|
138
|
-
function codeLanguage(contentType: string | null): string {
|
|
139
|
-
if (!contentType) return "text";
|
|
140
|
-
const t = contentType.toLowerCase();
|
|
141
|
-
if (t.includes("json")) return "json";
|
|
142
|
-
if (t.includes("html")) return "html";
|
|
143
|
-
if (t.includes("xml") || t.includes("svg")) return "xml";
|
|
144
|
-
if (t.includes("javascript")) return "javascript";
|
|
145
|
-
return "text";
|
|
146
|
-
}
|
|
147
|
-
|
|
148
|
-
function prettyBody(contentType: string | null, body: string): string {
|
|
149
|
-
if (contentType && contentType.toLowerCase().includes("json")) {
|
|
150
|
-
try {
|
|
151
|
-
return JSON.stringify(JSON.parse(body), null, 2);
|
|
152
|
-
} catch {
|
|
153
|
-
return body;
|
|
154
|
-
}
|
|
155
|
-
}
|
|
156
|
-
return body;
|
|
157
|
-
}
|
|
158
|
-
|
|
159
|
-
function bufferToBase64(buffer: ArrayBuffer): string {
|
|
160
|
-
let binary = "";
|
|
161
|
-
const bytes = new Uint8Array(buffer);
|
|
162
|
-
const chunk = 0x8000;
|
|
163
|
-
for (let i = 0; i < bytes.length; i += chunk) {
|
|
164
|
-
binary += String.fromCharCode(...bytes.subarray(i, i + chunk));
|
|
165
|
-
}
|
|
166
|
-
return btoa(binary);
|
|
167
|
-
}
|
|
168
|
-
|
|
169
49
|
function renderPath(path: string): React.ReactNode {
|
|
170
50
|
return path
|
|
171
51
|
.split(/(\\{[^}]+\\})/g)
|
|
@@ -178,20 +58,6 @@ function renderPath(path: string): React.ReactNode {
|
|
|
178
58
|
);
|
|
179
59
|
}
|
|
180
60
|
|
|
181
|
-
const LOCATIONS: ParameterDescriptor["in"][] = [
|
|
182
|
-
"path",
|
|
183
|
-
"query",
|
|
184
|
-
"header",
|
|
185
|
-
"cookie",
|
|
186
|
-
];
|
|
187
|
-
|
|
188
|
-
const LOCATION_TITLES: Record<string, string> = {
|
|
189
|
-
path: "Path",
|
|
190
|
-
query: "Query",
|
|
191
|
-
header: "Headers",
|
|
192
|
-
cookie: "Cookies",
|
|
193
|
-
};
|
|
194
|
-
|
|
195
61
|
/* ---------- compact bar ---------- */
|
|
196
62
|
|
|
197
63
|
const CompactBar = styled.div\`
|
|
@@ -1 +1 @@
|
|
|
1
|
-
export declare const platformAnalyticsMdxTemplate = "---\ntitle: \"Analytics\"\ndescription: \"Enable PostHog analytics to track page views on your documentation site.\"\ndate: \"2026-02-24\"\ncategory: \"AI & Integrations\"\ncategoryOrder: 3\norder: 3\nsection: \"Platform\"\n---\n# Analytics\n\nThe Analytics settings page lets you add PostHog analytics to your documentation site. Page views are captured both in the browser and on your server, so readers running ad blockers are still counted. Browser traffic is proxied through your own domain; server-side events go from your server to PostHog directly.\n\n## Enabling analytics\n\nUse the **Enable Analytics** toggle to turn tracking on or off. When disabled, no tracking code is added to your site.\n\n## Configuration\n\n### PostHog Project API Key\n\nYour project API key from PostHog (starts with `phc_`). This is a public identifier and is safe to commit to your repository.\n\nTo find your key:\n\n1. Log in to [PostHog](https://posthog.com).\n2. Open your project settings.\n3. Copy the **Project API Key**.\n\n### Region\n\nSelect the PostHog cloud region that matches your project:\n\n- **US Cloud** - `us.i.posthog.com`\n- **EU Cloud** - `eu.i.posthog.com`\n\n## How it works\n\nAnalytics settings are stored in `analytics.json` at the root of your repository. Here's an example:\n\n```json\n{\n \"provider\": \"posthog\",\n \"posthog\": {\n \"key\": \"phc_your_project_api_key\",\n \"host\": \"https://us.i.posthog.com\"\n }\n}\n```\n\nWhen enabled, Doccupine routes all analytics traffic through your documentation domain using Next.js rewrites. Instead of sending data directly to PostHog (which ad blockers may intercept), requests go through `/ingest` on your own domain and are proxied to PostHog.\n\n<Callout type=\"note\">\n Changes to analytics settings are staged as pending changes. Click **Publish** to commit them to your repository and trigger a deploy.\n</Callout>\n\nSee the [Analytics](/analytics) page for the full configuration reference and additional details on the privacy proxy.";
|
|
1
|
+
export declare const platformAnalyticsMdxTemplate = "---\ntitle: \"Analytics\"\ndescription: \"Enable PostHog analytics to track page views on your documentation site.\"\ndate: \"2026-02-24\"\nupdated: \"2026-08-01\"\ncategory: \"AI & Integrations\"\ncategoryOrder: 3\norder: 3\nsection: \"Platform\"\n---\n# Analytics\n\nThe Analytics settings page lets you add PostHog analytics to your documentation site. Page views are captured both in the browser and on your server, so readers running ad blockers are still counted. Browser traffic is proxied through your own domain; server-side events go from your server to PostHog directly.\n\n## Enabling analytics\n\nUse the **Enable Analytics** toggle to turn tracking on or off. When disabled, no tracking code is added to your site.\n\nTurning analytics off stages a **deletion** of `analytics.json` rather than saving an empty configuration, so the file disappears from your repository on the next publish. Absence is what the generator reads as \"no analytics\". An empty `{}` left in place ends up disabled too, but it fails validation on every build and prints a warning as it goes.\n\n## Configuration\n\n### PostHog Project API Key\n\nYour project API key from PostHog (starts with `phc_`). This is a public identifier and is safe to commit to your repository.\n\nTo find your key:\n\n1. Log in to [PostHog](https://posthog.com).\n2. Open your project settings.\n3. Copy the **Project API Key**.\n\n### Region\n\nSelect the PostHog cloud region that matches your project:\n\n- **US Cloud** - `us.i.posthog.com`\n- **EU Cloud** - `eu.i.posthog.com`\n\nIf your repository already names a host outside that list, the selector shows it as **Custom** and keeps it, so a hand-authored value survives a round trip through the settings page instead of snapping back to US Cloud.\n\n## Validation\n\n`analytics.json` is checked against the same rules the generator uses, both when the settings page loads it and when you save. A configuration the generator would refuse shows an error here, rather than passing silently and leaving analytics off on the deployed site:\n\n- `provider` must be `\"posthog\"`.\n- `posthog.key` may contain only letters, numbers, underscores, and hyphens.\n- `posthog.host`, when present, must be an HTTP(S) URL with no credentials, query string, or fragment.\n\n## How it works\n\nAnalytics settings are stored in `analytics.json` at the root of your repository. Here's an example:\n\n```json\n{\n \"provider\": \"posthog\",\n \"posthog\": {\n \"key\": \"phc_your_project_api_key\",\n \"host\": \"https://us.i.posthog.com\"\n }\n}\n```\n\nWhen enabled, Doccupine routes all analytics traffic through your documentation domain using Next.js rewrites. Instead of sending data directly to PostHog (which ad blockers may intercept), requests go through `/ingest` on your own domain and are proxied to PostHog.\n\n<Callout type=\"note\">\n Changes to analytics settings are staged as pending changes. Click **Publish** to commit them to your repository and trigger a deploy.\n</Callout>\n\nSee the [Analytics](/analytics) page for the full configuration reference and additional details on the privacy proxy.";
|
|
@@ -2,6 +2,7 @@ export const platformAnalyticsMdxTemplate = `---
|
|
|
2
2
|
title: "Analytics"
|
|
3
3
|
description: "Enable PostHog analytics to track page views on your documentation site."
|
|
4
4
|
date: "2026-02-24"
|
|
5
|
+
updated: "2026-08-01"
|
|
5
6
|
category: "AI & Integrations"
|
|
6
7
|
categoryOrder: 3
|
|
7
8
|
order: 3
|
|
@@ -15,6 +16,8 @@ The Analytics settings page lets you add PostHog analytics to your documentation
|
|
|
15
16
|
|
|
16
17
|
Use the **Enable Analytics** toggle to turn tracking on or off. When disabled, no tracking code is added to your site.
|
|
17
18
|
|
|
19
|
+
Turning analytics off stages a **deletion** of \`analytics.json\` rather than saving an empty configuration, so the file disappears from your repository on the next publish. Absence is what the generator reads as "no analytics". An empty \`{}\` left in place ends up disabled too, but it fails validation on every build and prints a warning as it goes.
|
|
20
|
+
|
|
18
21
|
## Configuration
|
|
19
22
|
|
|
20
23
|
### PostHog Project API Key
|
|
@@ -34,6 +37,16 @@ Select the PostHog cloud region that matches your project:
|
|
|
34
37
|
- **US Cloud** - \`us.i.posthog.com\`
|
|
35
38
|
- **EU Cloud** - \`eu.i.posthog.com\`
|
|
36
39
|
|
|
40
|
+
If your repository already names a host outside that list, the selector shows it as **Custom** and keeps it, so a hand-authored value survives a round trip through the settings page instead of snapping back to US Cloud.
|
|
41
|
+
|
|
42
|
+
## Validation
|
|
43
|
+
|
|
44
|
+
\`analytics.json\` is checked against the same rules the generator uses, both when the settings page loads it and when you save. A configuration the generator would refuse shows an error here, rather than passing silently and leaving analytics off on the deployed site:
|
|
45
|
+
|
|
46
|
+
- \`provider\` must be \`"posthog"\`.
|
|
47
|
+
- \`posthog.key\` may contain only letters, numbers, underscores, and hyphens.
|
|
48
|
+
- \`posthog.host\`, when present, must be an HTTP(S) URL with no credentials, query string, or fragment.
|
|
49
|
+
|
|
37
50
|
## How it works
|
|
38
51
|
|
|
39
52
|
Analytics settings are stored in \`analytics.json\` at the root of your repository. Here's an example:
|
|
@@ -1 +1 @@
|
|
|
1
|
-
export declare const platformFontsSettingsMdxTemplate = "---\ntitle: \"Fonts Settings\"\ndescription: \"Configure custom typography with Google Fonts or local font files.\"\ndate: \"2026-02-19\"\ncategory: \"Configuration\"\ncategoryOrder: 2\norder: 3\nsection: \"Platform\"\n---\n# Fonts Settings\n\nThe Fonts settings page lets you customize your documentation site's typography using Google Fonts or locally uploaded font files.\n\n## Google Fonts\n\nSelect a font from the full Google Fonts library:\n\n1. Type a font name to search the library.\n2. Select the **weights** you need (e.g., 400 for regular, 700 for bold). You can select multiple weights.\n3. Choose **subsets** for language support (latin, cyrillic, greek, vietnamese, etc.).\n\n<Callout type=\"note\">\n Only include the weights and subsets you actually use. Each addition increases page load time.\n</Callout>\n\n## Local fonts\n\nUpload your own font files for complete typographic control:\n\n1. Click **Add Font Source** to add a font file entry.\n2. Upload a font file (WOFF2, WOFF, TTF, OTF, or EOT format).\n3. Set the **weight** (e.g., 400, 700) and **style** (normal or italic).\n4. Add more sources for additional weights and styles.\n\nWOFF2 is recommended for the best compression and browser support.\n\n## How it works\n\nFont settings are stored in `fonts.json` at the root of your repository. Here's an example using Google Fonts:\n\n```json\n{\n \"googleFont\": {\n \"fontName\": \"Inter\",\n \"subsets\": [\"latin\"],\n \"weight\": [\"400\", \"500\", \"600\", \"700\"]\n }\n}\n```\n\nSee the [Fonts](/fonts) page for the full configuration format, including local font support.";
|
|
1
|
+
export declare const platformFontsSettingsMdxTemplate = "---\ntitle: \"Fonts Settings\"\ndescription: \"Configure custom typography with Google Fonts or local font files.\"\ndate: \"2026-02-19\"\nupdated: \"2026-08-01\"\ncategory: \"Configuration\"\ncategoryOrder: 2\norder: 3\nsection: \"Platform\"\n---\n# Fonts Settings\n\nThe Fonts settings page lets you customize your documentation site's typography using Google Fonts or locally uploaded font files.\n\n## Enabling custom fonts\n\nUse the **Enable Custom Fonts** toggle to turn custom typography on or off. Turning it off stages a **deletion** of `fonts.json` rather than saving an empty configuration, so the file disappears from your repository on the next publish and the site falls back to its default typeface. Absence is what the generator reads as \"no custom fonts\". An empty `{}` left in place ends up disabled too, but it fails validation on every build and prints a warning as it goes.\n\n## Google Fonts\n\nSelect a font from the full Google Fonts library:\n\n1. Type a font name to search the library.\n2. Select the **weights** you need (e.g., 400 for regular, 700 for bold). You can select multiple weights.\n3. Choose **subsets** for language support (latin, cyrillic, greek, vietnamese, etc.).\n\n<Callout type=\"note\">\n Only include the weights and subsets you actually use. Each addition increases page load time.\n</Callout>\n\n## Local fonts\n\nUpload your own font files for complete typographic control:\n\n1. Click **Add Font Source** to add a font file entry.\n2. Upload a font file (WOFF2, WOFF, TTF, OTF, or EOT format).\n3. Set the **weight** (e.g., 400, 700) and **style** (normal or italic).\n4. Add more sources for additional weights and styles.\n\nWOFF2 is recommended for the best compression and browser support.\n\nA weight or style already in your `fonts.json` that is not one of the offered choices appears as **Custom (value)** and is kept, so a hand-authored entry survives a round trip through the settings page.\n\n## Validation\n\n`fonts.json` is checked against the same rules the generator uses, both when the settings page loads it and when you save. A configuration the generator would refuse shows an error here, rather than passing silently and leaving your site on its default typeface:\n\n- Exactly one of `googleFont` or `localFonts` must be defined, never both and never neither.\n- `googleFont.fontName` must be a valid identifier, because it becomes an import in the generated site.\n- `googleFont.subsets` must be an array of non-empty strings, and `googleFont.weight` a non-empty string or array of them.\n- `localFonts` must be a non-empty path, or an object whose `src` array holds at least one entry with a string `path`.\n\n## How it works\n\nFont settings are stored in `fonts.json` at the root of your repository. Here's an example using Google Fonts:\n\n```json\n{\n \"googleFont\": {\n \"fontName\": \"Inter\",\n \"subsets\": [\"latin\"],\n \"weight\": [\"400\", \"500\", \"600\", \"700\"]\n }\n}\n```\n\nSee the [Fonts](/fonts) page for the full configuration format, including local font support.";
|
|
@@ -2,6 +2,7 @@ export const platformFontsSettingsMdxTemplate = `---
|
|
|
2
2
|
title: "Fonts Settings"
|
|
3
3
|
description: "Configure custom typography with Google Fonts or local font files."
|
|
4
4
|
date: "2026-02-19"
|
|
5
|
+
updated: "2026-08-01"
|
|
5
6
|
category: "Configuration"
|
|
6
7
|
categoryOrder: 2
|
|
7
8
|
order: 3
|
|
@@ -11,6 +12,10 @@ section: "Platform"
|
|
|
11
12
|
|
|
12
13
|
The Fonts settings page lets you customize your documentation site's typography using Google Fonts or locally uploaded font files.
|
|
13
14
|
|
|
15
|
+
## Enabling custom fonts
|
|
16
|
+
|
|
17
|
+
Use the **Enable Custom Fonts** toggle to turn custom typography on or off. Turning it off stages a **deletion** of \`fonts.json\` rather than saving an empty configuration, so the file disappears from your repository on the next publish and the site falls back to its default typeface. Absence is what the generator reads as "no custom fonts". An empty \`{}\` left in place ends up disabled too, but it fails validation on every build and prints a warning as it goes.
|
|
18
|
+
|
|
14
19
|
## Google Fonts
|
|
15
20
|
|
|
16
21
|
Select a font from the full Google Fonts library:
|
|
@@ -34,6 +39,17 @@ Upload your own font files for complete typographic control:
|
|
|
34
39
|
|
|
35
40
|
WOFF2 is recommended for the best compression and browser support.
|
|
36
41
|
|
|
42
|
+
A weight or style already in your \`fonts.json\` that is not one of the offered choices appears as **Custom (value)** and is kept, so a hand-authored entry survives a round trip through the settings page.
|
|
43
|
+
|
|
44
|
+
## Validation
|
|
45
|
+
|
|
46
|
+
\`fonts.json\` is checked against the same rules the generator uses, both when the settings page loads it and when you save. A configuration the generator would refuse shows an error here, rather than passing silently and leaving your site on its default typeface:
|
|
47
|
+
|
|
48
|
+
- Exactly one of \`googleFont\` or \`localFonts\` must be defined, never both and never neither.
|
|
49
|
+
- \`googleFont.fontName\` must be a valid identifier, because it becomes an import in the generated site.
|
|
50
|
+
- \`googleFont.subsets\` must be an array of non-empty strings, and \`googleFont.weight\` a non-empty string or array of them.
|
|
51
|
+
- \`localFonts\` must be a non-empty path, or an object whose \`src\` array holds at least one entry with a string \`path\`.
|
|
52
|
+
|
|
37
53
|
## How it works
|
|
38
54
|
|
|
39
55
|
Font settings are stored in \`fonts.json\` at the root of your repository. Here's an example using Google Fonts:
|
|
@@ -1 +1 @@
|
|
|
1
|
-
export declare const platformPublishingMdxTemplate = "---\ntitle: \"Publishing Changes\"\ndescription: \"Commit your edits to GitHub and deploy your documentation site with one click.\"\ndate: \"2026-02-19\"\nupdated: \"2026-
|
|
1
|
+
export declare const platformPublishingMdxTemplate = "---\ntitle: \"Publishing Changes\"\ndescription: \"Commit your edits to GitHub and deploy your documentation site with one click.\"\ndate: \"2026-02-19\"\nupdated: \"2026-08-01\"\ncategory: \"Editing\"\ncategoryOrder: 1\norder: 1\nsection: \"Platform\"\n---\n# Publishing Changes\n\nWhen you edit files in Doccupine, your changes are staged as pending. Nothing goes live until you explicitly publish.\n\n## The publish workflow\n\n1. Make edits to your files using the file editor.\n2. Click the **Publish** button in the project header. It appears as soon as anything is staged, with a badge showing the number of pending changes.\n3. Review the change set in the publish modal. Each file expands into a diff of what you actually changed, line by line, against what is currently in your repository.\n4. Optionally tick **Custom commit message** and write your own. Without one, the message is built from the files you are committing, like `Update docs/guide.mdx`.\n5. Click **Deploy**.\n\nDoccupine then:\n\n- Commits all pending changes to your GitHub repository\n- Triggers a new deployment\n- Clears all pending changes from the staging area\n\n<Callout type=\"note\">\n The deployment status badge next to the project name updates as your site builds. It cycles through **Queued**, **Building**, and **Ready** (or **Error** if something went wrong).\n</Callout>\n\n## Checks before a publish\n\nA few kinds of mistake do not break one page, they stop the whole site from building. Doccupine checks for those before committing anything and refuses the publish with a message naming the file to fix, so you find out in the publish modal instead of in a failed deploy.\n\n### An OpenAPI source that will not be there\n\nIf `doccupine.json` names an OpenAPI spec, the root document and every recursively referenced local file must exist after the publish. Publish all of those files with the configuration change. Moving or deleting any document in the reference graph requires updating the relevant `$ref` or `openapi` path in the same change set.\n\n### Two pages on the same URL\n\nTwo files that resolve to the same route - `guide.mdx` and `guide/index.mdx`, for instance - are a duplicate page, and the build stops rather than guessing which one you meant. Rename or delete one of them.\n\n### Section names that become the same URL\n\nSection URLs come from section names, so \"API Reference\" and \"api-reference\" both become `/api-reference`. Pick one spelling and use it in the `section` field of both pages.\n\n<Callout type=\"note\">\n These checks look at the repository as it will be **after** your publish, so a file you are deleting in the same change set counts as gone. If a check cannot run - GitHub is unreachable, say - the publish goes ahead and the build remains the backstop.\n</Callout>\n\n## Discarding changes\n\nYou can throw away as much or as little as you like:\n\n- **A single line** - **Discard this line** on that line of the diff. The rest of the file stays staged. Line numbers do not drift as you go, so you can pick off several in a row. A deleted file has no lines to pick from, and a diff too large to show in full does not offer the control.\n- **A whole file** - **Discard this file's change** on its row in the change set returns the file to whatever is in your repository.\n- **Everything** - **Discard all**, above the change set, clears the staging area without committing anything.\n\nIf discarding leaves a file identical to what is already committed, it drops out of the change set on its own.\n\n<Callout type=\"note\">\n Discarding a line here counts as a hand edit, exactly like editing the page in the editor would. That matters if the page is tracked by [Agent Sync](/platform/self-updating-docs): a page you have touched by hand is always routed to review rather than being rewritten automatically.\n</Callout>\n\n## File status badges\n\nIn the publish modal, every row in the change set carries a badge for what happened to the file, alongside a count of the lines added and removed:\n\n- **created** - the file is new\n- **updated** - the file already exists and was edited\n- **deleted** - the file is being removed\n\nA file that [Agent Sync](/platform/self-updating-docs) staged carries an **agent** badge as well, so the agent's proposals are distinguishable from your own edits at a glance.\n\nIf the diffs cannot be loaded, the modal falls back to a plain file list whose badges read **mod**, **del**, or **bin** - the last for a binary asset such as an image or a font, which has no text diff to show.\n\n## Changes staged by Agent Sync\n\nAgent Sync stages the pages it writes into the same staging area your own edits go to, so a single publish commits both. The modal tells you when that is happening:\n\n- **A conversation is waiting for review** - a notice names how many. Publishing or discarding those files here also settles the agent conversation, exactly as reviewing it from Agent Sync would.\n- **A run is still writing** - the notice says so, and **Deploy**, **Discard all**, and the per-file and per-line discard controls stay disabled until the run finishes. Committing half-written pages, or pulling files out from under a run, would leave the conversation recording one decision and your repository holding another.\n\nDiscarding an agent's file reconciles its conversation: the proposal is dropped from the run and its file count shrinks. Discard everything a run wrote and the conversation records the change set as **discarded**, so the thread reads as a review decision rather than an abandoned run.\n\n<Callout type=\"note\">\n Cherry-picking is easier from Agent Sync itself. Its run view keeps the agent's original change set and offers **Restore discarded changes** to put back whatever you removed - here in the publish modal, a discard is final.\n</Callout>\n\n## Auto-deploy from GitHub\n\nIf you're using a user-connected GitHub repository and push changes directly (outside of Doccupine), the webhook triggers an automatic redeploy. This means you can use Doccupine's editor and Git-based workflows interchangeably.";
|
|
@@ -2,7 +2,7 @@ export const platformPublishingMdxTemplate = `---
|
|
|
2
2
|
title: "Publishing Changes"
|
|
3
3
|
description: "Commit your edits to GitHub and deploy your documentation site with one click."
|
|
4
4
|
date: "2026-02-19"
|
|
5
|
-
updated: "2026-
|
|
5
|
+
updated: "2026-08-01"
|
|
6
6
|
category: "Editing"
|
|
7
7
|
categoryOrder: 1
|
|
8
8
|
order: 1
|
|
@@ -72,8 +72,23 @@ In the publish modal, every row in the change set carries a badge for what happe
|
|
|
72
72
|
- **updated** - the file already exists and was edited
|
|
73
73
|
- **deleted** - the file is being removed
|
|
74
74
|
|
|
75
|
+
A file that [Agent Sync](/platform/self-updating-docs) staged carries an **agent** badge as well, so the agent's proposals are distinguishable from your own edits at a glance.
|
|
76
|
+
|
|
75
77
|
If the diffs cannot be loaded, the modal falls back to a plain file list whose badges read **mod**, **del**, or **bin** - the last for a binary asset such as an image or a font, which has no text diff to show.
|
|
76
78
|
|
|
79
|
+
## Changes staged by Agent Sync
|
|
80
|
+
|
|
81
|
+
Agent Sync stages the pages it writes into the same staging area your own edits go to, so a single publish commits both. The modal tells you when that is happening:
|
|
82
|
+
|
|
83
|
+
- **A conversation is waiting for review** - a notice names how many. Publishing or discarding those files here also settles the agent conversation, exactly as reviewing it from Agent Sync would.
|
|
84
|
+
- **A run is still writing** - the notice says so, and **Deploy**, **Discard all**, and the per-file and per-line discard controls stay disabled until the run finishes. Committing half-written pages, or pulling files out from under a run, would leave the conversation recording one decision and your repository holding another.
|
|
85
|
+
|
|
86
|
+
Discarding an agent's file reconciles its conversation: the proposal is dropped from the run and its file count shrinks. Discard everything a run wrote and the conversation records the change set as **discarded**, so the thread reads as a review decision rather than an abandoned run.
|
|
87
|
+
|
|
88
|
+
<Callout type="note">
|
|
89
|
+
Cherry-picking is easier from Agent Sync itself. Its run view keeps the agent's original change set and offers **Restore discarded changes** to put back whatever you removed - here in the publish modal, a discard is final.
|
|
90
|
+
</Callout>
|
|
91
|
+
|
|
77
92
|
## Auto-deploy from GitHub
|
|
78
93
|
|
|
79
94
|
If you're using a user-connected GitHub repository and push changes directly (outside of Doccupine), the webhook triggers an automatic redeploy. This means you can use Doccupine's editor and Git-based workflows interchangeably.`;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
export declare const platformSelfUpdatingDocsMdxTemplate = "---\ntitle: \"Agent Sync\"\ndescription: \"Agent Sync links documentation pages to the code they describe and rewrites them when that code changes, keeping your docs self-updating.\"\ndate: \"2026-07-24\"\nupdated: \"2026-07-30\"\ncategory: \"Editing\"\ncategoryOrder: 1\norder: 2\nsection: \"Platform\"\n---\n# Agent Sync\n\nDocumentation goes stale because code moves and nobody notices. **Agent Sync** closes that gap: every page can be linked to the source files it documents, pinned to the exact commit it was written from. When those files change, the page is flagged as **drifted** - and the agent can rewrite it for you.\n\nYou'll find it under **Agent Sync** in the project sidebar.\n\n## The four views\n\n| View | What it's for |\n| --------- | ----------------------------------------------------------------------------- |\n| **Agent** | Ask the agent to write or update documentation, and read its replies |\n| **Map** | Each page beside the sources it came from, with its sync state |\n| **Table** | The same information as a dense, sortable list |\n| **Drift** | The queue of pages whose sources have changed |\n\nA badge on the sidebar link counts the pages currently waiting for attention.\n\n## Asking the agent for docs\n\nThe **Agent** view is a chat. Describe what you want documented, choose a **source repository** and a **scope** - the whole repo, a folder, or a single file - and the agent researches the code, plans the pages, and writes them.\n\nReplies are threaded, so a follow-up builds on what came before:\n\n> Document the auth module - cover sessions, refresh tokens and the error codes.\n\n> Now do the same for the CLI.\n\nEach turn shows the steps the agent took, the pages it changed, the sources it read, and what the run cost. You can switch between conversations, rename them, or start a fresh one.\n\n<Callout type=\"note\">\n An empty result is a valid answer. If the docs already describe the code accurately, the agent will say so rather than rewriting pages for the sake of it.\n</Callout>\n\n## Linking pages to sources\n\nA page needs at least one source link before drift can be detected. There are three ways to create them:\n\n<Steps>\n <Step title=\"Automatically, as the agent writes\">\n Every page the agent produces records the files it was derived from. Sites created by [Import from GitHub](/platform/import-from-github) arrive fully linked.\n </Step>\n <Step title=\"Auto-link existing pages\">\n **Auto-link code** scans your existing pages, proposes matching files from every source repository, and lets you approve the links in one batch. It's a good way to bootstrap a hand-written site.\n </Step>\n <Step title=\"By hand\">\n Open an MDX page in the editor, select **Source links** in the toolbar, then choose a repository and match one file, a folder, or a path pattern. Hand-written pages can be tracked this way without ever having been generated.\n </Step>\n</Steps>\n\n## Auto-link existing pages\n\nUse **Auto-link code** in the Agent Sync header when you already have documentation but it is not connected to its source code yet.\n\n<Steps>\n <Step title=\"Start the scan\">\n Select **Auto-link code**. Doccupine reads the committed Markdown and MDX pages in your docs repository that do not have source links yet, then compares them with file paths from all your source repositories. Pending editor changes are not included until they are published.\n </Step>\n <Step title=\"Review the suggestions\">\n Suggestions are grouped by page. A strong match means the page names or references the file, so it starts selected. A weaker name match is left unselected for you to confirm. You can change any checkbox, and existing source links are never replaced.\n </Step>\n <Step title=\"Link the selected files\">\n Select **Link selected (N)**. Each approved file is recorded against the page and pinned to the repository's current commit. The page appears as **In sync** in the Map and Table views; Auto-link does not rewrite, commit, or publish the documentation.\n </Step>\n</Steps>\n\nThe normal scan is deterministic and uses no AI credit. **AI auto-select** is optional: it asks the configured AI model to refine the offered matches, uses AI credit, and only changes which checkboxes are selected. You still review the result and select **Link selected (N)** to save it.\n\n<Callout type=\"note\">\n Auto-link skips pages that already have at least one source link. To add another file, folder, or pattern to one of those pages, open the page's **Source links** panel in the editor and link it manually.\n</Callout>\n\nIf the scan finds an OpenAPI specification and your `doccupine.json` does not configure one yet, it also offers **Add to doccupine.json (N)**. This stages the configuration and, when needed, a copy of the specification as pending changes. Review and publish those changes through the normal publishing flow.\n\n## How drift is detected\n\nDoccupine watches your source repositories two ways:\n\n- **Push webhook** - instant, and used whenever Doccupine can install a hook on the repository. Your project's own repository always has one.\n- **Background check** - every 30 minutes, for repositories you don't administer.\n\nThe Source repositories manager shows which one each repo is using, as an **Instant** or **~30 min** badge.\n\n## Review or publish automatically\n\nWhen a linked source changes, what happens next depends on the page:\n\n| Page setting | On drift |\n| -------------------------------- | ---------------------------------------------------------------- |\n| Default | Flagged for review - you trigger the update |\n| **Auto-update** on | The agent rewrites the page and publishes it |\n| Edited by a human | **Always** flagged for review, whatever else is set |\n\nEach row on the Map and Table views has an **Auto-update this page when its source changes** toggle, so you can let routine reference pages look after themselves while a carefully worded overview page always waits for you.\n\nFor anything in review, **Review update** opens the change set - the same diff view as [publishing](/platform/publishing) - and **Update from source** asks the agent to regenerate that one page on demand.\n\n<Callout type=\"warning\">\n Your edits are never overwritten. Doccupine compares the page's content against what the agent last wrote, so a page you've touched by hand is detected and routed to review - even if auto-update is on. Reformatting, line-ending changes, and blank-line churn don't count as edits.\n</Callout>\n\n## Source repositories\n\nYour project's own repository is always a source, so a repo that holds both code and docs needs no setup at all.\n\nFor a multi-repo setup, add the other repositories from Agent Sync:\n\n<Steps>\n <Step title=\"Open Source repositories\">\n Select **Source repositories** in the Agent Sync header. Your project's repository appears first with a **Default** badge and cannot be removed.\n </Step>\n <Step title=\"Choose another repository\">\n Project owners and editors can select **Add repository**, then search the GitHub repositories they own, collaborate on, or can access through an organization. If GitHub is not connected yet, select **Connect GitHub**, finish authorization, then reopen the manager.\n </Step>\n <Step title=\"Check its connection\">\n Selecting a repository adds it immediately. **Instant** means Doccupine installed a push webhook; **~30 min** means it will check for source changes on a schedule instead. Both modes support the agent, manual source links, Auto-link code, and drift tracking.\n </Step>\n</Steps>\n\nOnce connected, the repository appears in the Agent view's **Source repository** selector and anywhere you create a source link.\n\n<Callout type=\"note\">\n Removing a repository never deletes your documentation pages. If pages still link to it, Doccupine tells you how many are affected and asks again before removing those source links. The pages remain, but they stop tracking changes from that repository.\n</Callout>\n\n## Notifications\n\nDoccupine emails the project owner when pages are ready to review, and when pages have been updated and published. You're notified once per project when pages first drift - a later change to the same page won't email you again until you've dealt with it.\n\n## What it costs\n\nAgent runs use your project's AI credit. Doccupine keeps that spend predictable:\n\n- Automatic regeneration only ever happens for pages you've explicitly set to auto-update. A page waiting for review costs nothing when its source changes.\n- Drift that changes no lines - a merge or a rename that leaves the tracked file's content alone - never triggers a run.\n- Every run has a ceiling on pages and spend.\n- Only one run happens at a time per project.\n\nSee [AI Assistant](/platform/ai-assistant) for how AI is configured and budgeted.\n\n## In the editor\n\nYou don't have to leave the editor to use any of this. The toolbar has a source status button showing whether the open page is in sync, drifted, or unlinked - and why it would need review - and the side panel lets you ask the agent for a block of MDX to drop straight in at your cursor.";
|
|
1
|
+
export declare const platformSelfUpdatingDocsMdxTemplate = "---\ntitle: \"Agent Sync\"\ndescription: \"Agent Sync links documentation pages to the code they describe and rewrites them when that code changes, keeping your docs self-updating.\"\ndate: \"2026-07-24\"\nupdated: \"2026-08-01\"\ncategory: \"Editing\"\ncategoryOrder: 1\norder: 2\nsection: \"Platform\"\n---\n# Agent Sync\n\nDocumentation goes stale because code moves and nobody notices. **Agent Sync** closes that gap: every page can be linked to the source files it documents, pinned to the exact commit it was written from. When those files change, the page is flagged as **drifted** - and the agent can rewrite it for you.\n\nYou'll find it under **Agent Sync** in the project sidebar.\n\n## The four views\n\n| View | What it's for |\n| --------- | ----------------------------------------------------------------------------- |\n| **Agent** | Ask questions about your code, or ask the agent to write and update pages |\n| **Map** | Each page beside the sources it came from, with its sync state |\n| **Table** | The same information as a dense, sortable list |\n| **Drift** | The queue of pages whose sources have changed |\n\nA badge on the sidebar link counts the pages currently waiting for attention.\n\n## Asking the agent for docs\n\nThe **Agent** view is a chat. Choose a **source repository** and a **scope** - the whole repo, a folder, or a single file - then either ask a question or ask for a change.\n\n**Questions are answered in the chat.** Ask what a module does, which pages cover a feature, or whether a guide still matches the code, and the agent reads the source and replies without touching your documentation:\n\n> Which pages would break if we renamed the refresh-token endpoint?\n\n**Asking for a change starts a run.** The agent researches the code, plans the pages, and writes them:\n\n> Document the auth module - cover sessions, refresh tokens and the error codes.\n\n> Update the buttons page so it matches the current component.\n\nReplies are threaded, so a follow-up builds on what came before - and agreeing to something the agent suggested is enough to start the work, without repeating yourself:\n\n> Now do the same for the CLI.\n\nA turn that changes documentation shows the steps the agent took, the pages it changed, the sources it read, and what the run cost. You can switch between conversations, rename them, or start a fresh one.\n\nA run commits itself only when every page it wrote is set to auto-update and untouched by hand. Anything else is staged alongside your own edits and waits, and you can settle it from the conversation or from the project's [Publish](/platform/publishing) modal - either way, the other side is kept in step.\n\n<Callout type=\"note\">\n An empty result is a valid answer. If the docs already describe the code accurately, the agent will say so rather than rewriting pages for the sake of it.\n</Callout>\n\n## Linking pages to sources\n\nA page needs at least one source link before drift can be detected. There are three ways to create them:\n\n<Steps>\n <Step title=\"Automatically, as the agent writes\">\n Every page the agent produces records the files it was derived from. Sites created by [Import from GitHub](/platform/import-from-github) arrive fully linked.\n </Step>\n <Step title=\"Auto-link existing pages\">\n **Auto-link code** scans your existing pages, proposes matching files from every source repository, and lets you approve the links in one batch. It's a good way to bootstrap a hand-written site.\n </Step>\n <Step title=\"By hand\">\n Open an MDX page in the editor, select **Source links** in the toolbar, then choose a repository and match one file, a folder, or a path pattern. Hand-written pages can be tracked this way without ever having been generated.\n </Step>\n</Steps>\n\n## Auto-link existing pages\n\nUse **Auto-link code** in the Agent Sync header when you already have documentation but it is not connected to its source code yet.\n\n<Steps>\n <Step title=\"Start the scan\">\n Select **Auto-link code**. Doccupine reads the committed Markdown and MDX pages in your docs repository that do not have source links yet, then compares them with file paths from all your source repositories. Pending editor changes are not included until they are published.\n </Step>\n <Step title=\"Review the suggestions\">\n Suggestions are grouped by page. A strong match means the page names or references the file, so it starts selected. A weaker name match is left unselected for you to confirm. You can change any checkbox, and existing source links are never replaced.\n </Step>\n <Step title=\"Link the selected files\">\n Select **Link selected (N)**. Each approved file is recorded against the page and pinned to the repository's current commit. The page appears as **In sync** in the Map and Table views; Auto-link does not rewrite, commit, or publish the documentation.\n </Step>\n</Steps>\n\nThe normal scan is deterministic and uses no AI credit. **AI auto-select** is optional: it asks the configured AI model to refine the offered matches, uses AI credit, and only changes which checkboxes are selected. You still review the result and select **Link selected (N)** to save it.\n\n<Callout type=\"note\">\n Auto-link skips pages that already have at least one source link. To add another file, folder, or pattern to one of those pages, open the page's **Source links** panel in the editor and link it manually.\n</Callout>\n\nIf the scan finds an OpenAPI specification and your `doccupine.json` does not configure one yet, it also offers **Add to doccupine.json (N)**. This stages the configuration and, when needed, a copy of the specification as pending changes. Review and publish those changes through the normal publishing flow.\n\n## How drift is detected\n\nDoccupine watches your source repositories two ways:\n\n- **Push webhook** - instant, and used whenever Doccupine can install a hook on the repository. Your project's own repository always has one.\n- **Background check** - every 30 minutes, for repositories you don't administer.\n\nThe Source repositories manager shows which one each repo is using, as an **Instant** or **~30 min** badge.\n\n## Review or publish automatically\n\nWhen a linked source changes, what happens next depends on the page:\n\n| Page setting | On drift |\n| -------------------------------- | ---------------------------------------------------------------- |\n| Default | Flagged for review - you trigger the update |\n| **Auto-update** on | The agent rewrites the page and publishes it |\n| Edited by a human | **Always** flagged for review, whatever else is set |\n\nEach row on the Map and Table views has an **Auto-update this page when its source changes** toggle, so you can let routine reference pages look after themselves while a carefully worded overview page always waits for you.\n\nThe same settings decide what happens to a run you started yourself from the Agent view - auto-update is not only about drift. What differs is that a run writes one change set and commits or stages it as a unit: if any page in it resolves to review, the whole set waits. Publishing half a coherent change and leaving the rest behind would be worse than waiting for you.\n\nFor anything in review, **Review update** opens the change set - the same diff view as [publishing](/platform/publishing) - and **Update from source** asks the agent to regenerate that one page on demand.\n\n<Callout type=\"warning\">\n Your edits are never overwritten. Doccupine compares the page's content against what the agent last wrote, so a page you've touched by hand is detected and routed to review - even if auto-update is on. Reformatting, line-ending changes, and blank-line churn don't count as edits.\n</Callout>\n\n## Source repositories\n\nYour project's own repository is always a source, so a repo that holds both code and docs needs no setup at all.\n\nFor a multi-repo setup, add the other repositories from Agent Sync:\n\n<Steps>\n <Step title=\"Open Source repositories\">\n Select **Source repositories** in the Agent Sync header. Your project's repository appears first with a **Default** badge and cannot be removed.\n </Step>\n <Step title=\"Choose another repository\">\n Project owners and editors can select **Add repository**, then search the GitHub repositories they own, collaborate on, or can access through an organization. If GitHub is not connected yet, select **Connect GitHub**, finish authorization, then reopen the manager.\n </Step>\n <Step title=\"Check its connection\">\n Selecting a repository adds it immediately. **Instant** means Doccupine installed a push webhook; **~30 min** means it will check for source changes on a schedule instead. Both modes support the agent, manual source links, Auto-link code, and drift tracking.\n </Step>\n</Steps>\n\nOnce connected, the repository appears in the Agent view's **Source repository** selector and anywhere you create a source link.\n\n<Callout type=\"note\">\n Removing a repository never deletes your documentation pages. If pages still link to it, Doccupine tells you how many are affected and asks again before removing those source links. The pages remain, but they stop tracking changes from that repository.\n</Callout>\n\n## Notifications\n\nDoccupine emails the project owner when pages are ready to review, and when pages have been updated and published. You're notified once per project when pages first drift - a later change to the same page won't email you again until you've dealt with it.\n\n## What it costs\n\nAgent runs use your project's AI credit. Doccupine keeps that spend predictable:\n\n- Automatic regeneration only ever happens for pages you've explicitly set to auto-update. A page waiting for review costs nothing when its source changes.\n- Drift that changes no lines - a merge or a rename that leaves the tracked file's content alone - never triggers a run.\n- Every run has a ceiling on pages and spend.\n- Only one run happens at a time per project.\n\nSee [AI Assistant](/platform/ai-assistant) for how AI is configured and budgeted.\n\n## In the editor\n\nYou don't have to leave the editor to use any of this. The toolbar has a source status button showing whether the open page is in sync, drifted, or unlinked - and why it would need review - and the side panel lets you ask the agent for a block of MDX to drop straight in at your cursor.";
|