doccupine 0.0.134 → 0.0.136
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 -9
- package/dist/index.js +282 -46
- package/dist/lib/metadata.d.ts +5 -0
- package/dist/lib/metadata.js +15 -4
- package/dist/lib/rss.d.ts +24 -0
- package/dist/lib/rss.js +137 -0
- package/dist/lib/structures.js +22 -2
- package/dist/templates/app/rssRoute.d.ts +11 -0
- package/dist/templates/app/rssRoute.js +30 -0
- package/dist/templates/components/Docs.d.ts +1 -1
- package/dist/templates/components/Docs.js +5 -2
- package/dist/templates/components/MDXComponents.d.ts +1 -1
- package/dist/templates/components/MDXComponents.js +29 -0
- package/dist/templates/components/SideBar.d.ts +1 -1
- package/dist/templates/components/SideBar.js +5 -2
- package/dist/templates/components/layout/ActionBar.d.ts +1 -1
- package/dist/templates/components/layout/ActionBar.js +44 -13
- package/dist/templates/components/layout/ApiPlayground.d.ts +1 -1
- package/dist/templates/components/layout/ApiPlayground.js +20 -28
- package/dist/templates/components/layout/Badge.d.ts +1 -0
- package/dist/templates/components/layout/Badge.js +455 -0
- package/dist/templates/components/layout/DocsComponents.d.ts +1 -1
- package/dist/templates/components/layout/DocsComponents.js +5 -30
- package/dist/templates/components/layout/Prompt.d.ts +1 -0
- package/dist/templates/components/layout/Prompt.js +149 -0
- package/dist/templates/components/layout/Tooltip.d.ts +1 -0
- package/dist/templates/components/layout/Tooltip.js +222 -0
- package/dist/templates/components/layout/Tree.d.ts +1 -0
- package/dist/templates/components/layout/Tree.js +322 -0
- package/dist/templates/components/layout/TreeData.d.ts +1 -0
- package/dist/templates/components/layout/TreeData.js +131 -0
- package/dist/templates/components/layout/Update.d.ts +1 -1
- package/dist/templates/components/layout/Update.js +3 -0
- package/dist/templates/lib/rss.d.ts +1 -0
- package/dist/templates/lib/rss.js +83 -0
- package/dist/templates/mdx/accordion.mdx.d.ts +1 -1
- package/dist/templates/mdx/accordion.mdx.js +1 -1
- package/dist/templates/mdx/api-playground.mdx.d.ts +1 -1
- package/dist/templates/mdx/api-playground.mdx.js +1 -1
- package/dist/templates/mdx/badges.mdx.d.ts +1 -0
- package/dist/templates/mdx/badges.mdx.js +237 -0
- package/dist/templates/mdx/buttons.mdx.d.ts +1 -1
- package/dist/templates/mdx/buttons.mdx.js +1 -1
- package/dist/templates/mdx/callouts.mdx.d.ts +1 -1
- package/dist/templates/mdx/callouts.mdx.js +1 -1
- package/dist/templates/mdx/cards.mdx.d.ts +1 -1
- package/dist/templates/mdx/cards.mdx.js +1 -1
- package/dist/templates/mdx/color-swatches.mdx.d.ts +1 -1
- package/dist/templates/mdx/color-swatches.mdx.js +1 -1
- package/dist/templates/mdx/columns.mdx.d.ts +1 -1
- package/dist/templates/mdx/columns.mdx.js +1 -1
- package/dist/templates/mdx/components.mdx.d.ts +1 -1
- package/dist/templates/mdx/components.mdx.js +14 -2
- package/dist/templates/mdx/fields.mdx.d.ts +1 -1
- package/dist/templates/mdx/fields.mdx.js +1 -1
- package/dist/templates/mdx/frames.mdx.d.ts +1 -1
- package/dist/templates/mdx/frames.mdx.js +1 -1
- package/dist/templates/mdx/icons.mdx.d.ts +1 -1
- package/dist/templates/mdx/icons.mdx.js +1 -1
- package/dist/templates/mdx/image-and-embeds.mdx.d.ts +1 -1
- package/dist/templates/mdx/image-and-embeds.mdx.js +1 -1
- package/dist/templates/mdx/images-and-embeds.mdx.d.ts +1 -0
- package/dist/templates/mdx/images-and-embeds.mdx.js +118 -0
- package/dist/templates/mdx/mermaid.mdx.d.ts +1 -1
- package/dist/templates/mdx/mermaid.mdx.js +1 -1
- package/dist/templates/mdx/navigation.mdx.d.ts +1 -1
- package/dist/templates/mdx/navigation.mdx.js +5 -1
- package/dist/templates/mdx/prompt.mdx.d.ts +1 -0
- package/dist/templates/mdx/prompt.mdx.js +69 -0
- package/dist/templates/mdx/steps.mdx.d.ts +1 -1
- package/dist/templates/mdx/steps.mdx.js +1 -1
- package/dist/templates/mdx/tabs.mdx.d.ts +1 -1
- package/dist/templates/mdx/tabs.mdx.js +1 -1
- package/dist/templates/mdx/tooltips.mdx.d.ts +1 -0
- package/dist/templates/mdx/tooltips.mdx.js +57 -0
- package/dist/templates/mdx/tree.mdx.d.ts +1 -0
- package/dist/templates/mdx/tree.mdx.js +158 -0
- package/dist/templates/mdx/update.mdx.d.ts +1 -1
- package/dist/templates/mdx/update.mdx.js +42 -2
- package/dist/templates/package.js +1 -1
- package/package.json +2 -2
- package/dist/templates/mdx/platform/external-links.mdx.d.ts +0 -1
- package/dist/templates/mdx/platform/external-links.mdx.js +0 -47
- package/dist/templates/utils/apiAnchors.d.ts +0 -1
- package/dist/templates/utils/apiAnchors.js +0 -39
|
@@ -14,6 +14,9 @@ import { StyledSmallButton } from "@/components/layout/SharedStyled";
|
|
|
14
14
|
interface ActionBarProps {
|
|
15
15
|
children: React.ReactNode;
|
|
16
16
|
content: string;
|
|
17
|
+
// When set, an RSS button linking to this page's feed renders next to the
|
|
18
|
+
// copy pill.
|
|
19
|
+
rssHref?: string;
|
|
17
20
|
}
|
|
18
21
|
|
|
19
22
|
const StyledActionBar = styled.div<{
|
|
@@ -55,6 +58,26 @@ const StyledCopyButton = styled(StyledSmallButton)<{
|
|
|
55
58
|
}
|
|
56
59
|
\`;
|
|
57
60
|
|
|
61
|
+
// StyledSmallButton carries a -6px right margin for edge alignment; inside
|
|
62
|
+
// the pill group that would eat into the gap, so it is neutralized here.
|
|
63
|
+
const StyledActionBarGroup = styled.div\`
|
|
64
|
+
display: flex;
|
|
65
|
+
gap: 12px;
|
|
66
|
+
|
|
67
|
+
& > * {
|
|
68
|
+
margin-right: 0;
|
|
69
|
+
}
|
|
70
|
+
\`;
|
|
71
|
+
|
|
72
|
+
const StyledRssLink = styled(StyledSmallButton)<{ theme: Theme }>\`
|
|
73
|
+
text-decoration: none;
|
|
74
|
+
color: \${({ theme }) => theme.colors.primary};
|
|
75
|
+
|
|
76
|
+
& svg.lucide {
|
|
77
|
+
color: \${({ theme }) => theme.colors.primary};
|
|
78
|
+
}
|
|
79
|
+
\`;
|
|
80
|
+
|
|
58
81
|
// Mirrors the geometry and interaction of Cherry's ThemeToggle so the two
|
|
59
82
|
// pills look identical side by side: interactiveStyles supplies the border
|
|
60
83
|
// highlight + focus/active rings (no scale effect), and the space-between
|
|
@@ -142,7 +165,7 @@ const StyledContent = styled.div<{
|
|
|
142
165
|
\`}
|
|
143
166
|
\`;
|
|
144
167
|
|
|
145
|
-
function ActionBar({ children, content }: ActionBarProps) {
|
|
168
|
+
function ActionBar({ children, content, rssHref }: ActionBarProps) {
|
|
146
169
|
const [isView, setIsView] = useState(true);
|
|
147
170
|
const [copied, setCopied] = useState(false);
|
|
148
171
|
const hasSectionBar = useContext(SectionBarContext);
|
|
@@ -160,19 +183,27 @@ function ActionBar({ children, content }: ActionBarProps) {
|
|
|
160
183
|
return (
|
|
161
184
|
<>
|
|
162
185
|
<StyledActionBar>
|
|
163
|
-
<
|
|
164
|
-
{copied
|
|
165
|
-
|
|
166
|
-
|
|
167
|
-
|
|
168
|
-
|
|
169
|
-
|
|
170
|
-
|
|
171
|
-
|
|
172
|
-
|
|
173
|
-
|
|
186
|
+
<StyledActionBarGroup>
|
|
187
|
+
<StyledCopyButton onClick={handleCopyContent} $copied={copied}>
|
|
188
|
+
{copied ? (
|
|
189
|
+
<>
|
|
190
|
+
<Icon name="check" size={16} />
|
|
191
|
+
Copied!
|
|
192
|
+
</>
|
|
193
|
+
) : (
|
|
194
|
+
<>
|
|
195
|
+
<Icon name="copy" size={16} />
|
|
196
|
+
Copy content
|
|
197
|
+
</>
|
|
198
|
+
)}
|
|
199
|
+
</StyledCopyButton>
|
|
200
|
+
{rssHref && (
|
|
201
|
+
<StyledRssLink as="a" href={rssHref} aria-label="RSS feed">
|
|
202
|
+
<Icon name="rss" size={16} />
|
|
203
|
+
RSS
|
|
204
|
+
</StyledRssLink>
|
|
174
205
|
)}
|
|
175
|
-
</
|
|
206
|
+
</StyledActionBarGroup>
|
|
176
207
|
<StyledActionBarContent>
|
|
177
208
|
<StyledToggle
|
|
178
209
|
onClick={() => setIsView(!isView)}
|
|
@@ -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 { 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\nconst METHOD_TOKENS: Record<string, keyof Theme[\"colors\"]> = {\n get: \"info\",\n post: \"success\",\n put: \"warning\",\n patch: \"warning\",\n delete: \"error\",\n head: \"gray\",\n options: \"gray\",\n trace: \"gray\",\n};\n\nfunction methodColor(theme: Theme, method: string): string {\n const token = METHOD_TOKENS[method.toLowerCase()] ?? \"gray\";\n return theme.colors[token];\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\nconst MethodBadge = styled.span<{ theme: Theme; $method: string }>`\n font-family: ${({ theme }) => theme.fonts.mono};\n font-weight: 700;\n font-size: 12px;\n letter-spacing: 0.04em;\n text-transform: uppercase;\n color: ${({ theme }) => theme.colors.surface};\n background: ${({ theme, $method }) => methodColor(theme, $method)};\n padding: 0 4px;\n border-radius: ${({ theme }) => theme.spacing.radius.xs};\n flex-shrink: 0;\n`;\n\nconst PathText = styled.span`\n flex: 1;\n min-width: 0;\n font-family: ${({ theme }: { theme: Theme }) => theme.fonts.mono};\n font-weight: 600;\n font-size: 14px;\n color: ${({ theme }: { theme: Theme }) => theme.colors.dark};\n overflow-x: auto;\n white-space: nowrap;\n &::-webkit-scrollbar {\n display: none;\n }\n`;\n\nconst PathParam = styled.span`\n font-family: ${({ theme }: { theme: Theme }) => theme.fonts.mono};\n background: ${({ theme }: { theme: Theme }) =>\n `color-mix(in srgb, ${theme.colors.primaryLight} 20%, transparent)`};\n color: ${({ theme }: { theme: Theme }) => theme.colors.dark};\n padding: 2px 4px;\n border-radius: ${({ theme }: { theme: Theme }) => theme.spacing.radius.xs};\n overflow-wrap: anywhere;\n`;\n\nconst AccentButton = styled.button<{ theme: Theme }>`\n cursor: pointer;\n display: inline-flex;\n align-items: center;\n gap: 6px;\n flex-shrink: 0;\n font-family: ${({ theme }: { theme: Theme }) => theme.fonts.text};\n font-weight: 600;\n font-size: 14px;\n color: ${({ theme }: { theme: Theme }) => theme.colors.surface};\n background: ${({ theme }: { theme: Theme }) => theme.colors.primary};\n border: none;\n padding: 8px 14px;\n border-radius: ${({ theme }: { theme: Theme }) => theme.spacing.radius.xs};\n ${interactiveStyles};\n\n & svg {\n color: ${({ theme }: { theme: Theme }) => theme.colors.surface};\n stroke: ${({ theme }: { theme: Theme }) => theme.colors.surface};\n }\n\n &:hover {\n background: ${({ theme }: { theme: Theme }) => theme.colors.primaryDark};\n }\n &:disabled {\n opacity: 0.6;\n cursor: default;\n }\n`;\n\n/* ---------- modal ---------- */\n\nconst DialogHeader = styled.div`\n display: flex;\n align-items: center;\n gap: 10px;\n flex-wrap: wrap;\n margin: 5px 0 0 0;\n`;\n\nconst PathBar = styled.div`\n flex: 1;\n min-width: 200px;\n display: flex;\n align-items: center;\n gap: 8px;\n padding: 8px 8px 8px 12px;\n border: solid 1px ${({ theme }: { theme: Theme }) => theme.colors.grayLight};\n border-radius: ${({ theme }: { theme: Theme }) => theme.spacing.radius.xs};\n background: ${({ theme }: { theme: Theme }) => theme.colors.light};\n`;\n\nconst DialogBody = styled.div`\n display: grid;\n grid-template-columns: 1fr;\n gap: 20px;\n padding: 0;\n margin: 20px 0 0 0;\n\n ${mq(\"lg\")} {\n grid-template-columns: 1fr 1fr;\n }\n`;\n\nconst Column = styled.div`\n display: flex;\n flex-direction: column;\n gap: 20px;\n min-width: 0;\n`;\n\nconst Description = styled.p`\n margin: 0;\n ${({ theme }: { theme: Theme }) => styledSmall(theme)};\n color: ${({ theme }: { theme: Theme }) => theme.colors.grayDark};\n`;\n\nconst Toolbar = styled.div`\n display: flex;\n align-items: center;\n gap: 8px;\n flex-wrap: wrap;\n`;\n\nconst Toggle = styled.button<{ theme: Theme; $active?: boolean }>`\n position: relative;\n cursor: pointer;\n text-decoration: none;\n font-size: ${({ theme }) => theme.fontSizes.small.lg};\n line-height: 1;\n color: ${({ theme }) => theme.colors.accent};\n display: flex;\n gap: 6px;\n transition: all 0.3s ease;\n font-weight: 600;\n white-space: nowrap;\n min-width: fit-content;\n background: ${({ theme }) =>\n `color-mix(in srgb, ${theme.colors.primaryLight} 10%, transparent)`};\n padding: 6px 8px;\n border: none;\n border-radius: ${({ theme }) => theme.spacing.radius.xs};\n ${interactiveStyles};\n\n ${({ $active, theme }) =>\n $active &&\n css`\n background: ${theme.colors.primary};\n color: ${theme.colors.surface};\n `}\n`;\n\n/* ---------- collapsible card ---------- */\n\nconst Card = styled.div`\n border: solid 1px ${({ theme }: { theme: Theme }) => theme.colors.grayLight};\n border-radius: ${({ theme }: { theme: Theme }) => theme.spacing.radius.lg};\n overflow: hidden;\n`;\n\nconst CardHead = styled.button`\n cursor: pointer;\n width: 100%;\n display: flex;\n align-items: center;\n justify-content: space-between;\n gap: 8px;\n padding: 12px 20px;\n border: none;\n background: transparent;\n color: ${({ theme }: { theme: Theme }) => theme.colors.dark};\n ${({ theme }: { theme: Theme }) => styledSmall(theme)};\n`;\n\nconst Inline = styled.span`\n display: inline-flex;\n align-items: center;\n gap: 8px;\n`;\n\nconst CardBody = styled.div`\n padding: 0 20px 20px;\n display: flex;\n flex-direction: column;\n gap: 16px;\n`;\n\n/* ---------- fields ---------- */\n\n// Wraps an accordion section's content and insets it, so full-width inputs'\n// focus rings (a 4px box-shadow) are not clipped by the accordion's own\n// overflow. Keeps the accordion component untouched.\nconst SectionInner = styled.div`\n display: flex;\n flex-direction: column;\n gap: 16px;\n padding: 4px;\n`;\n\nconst Field = styled.div`\n display: flex;\n flex-direction: column;\n gap: 6px;\n`;\n\nconst FieldHead = styled.div`\n display: flex;\n align-items: center;\n gap: 8px;\n flex-wrap: wrap;\n ${({ theme }: { theme: Theme }) => styledSmall(theme)};\n`;\n\nconst FieldName = styled.span`\n font-family: ${({ theme }: { theme: Theme }) => theme.fonts.mono};\n font-weight: 600;\n color: ${({ theme }: { theme: Theme }) => theme.colors.dark};\n`;\n\nconst TypeChip = styled.span`\n font-family: ${({ theme }: { theme: Theme }) => theme.fonts.mono};\n color: ${({ theme }: { theme: Theme }) => theme.colors.grayDark};\n background: ${({ theme }: { theme: Theme }) =>\n `color-mix(in srgb, ${theme.colors.gray} 15%, transparent)`};\n padding: 0 4px;\n border-radius: ${({ theme }: { theme: Theme }) => theme.spacing.radius.xs};\n`;\n\nconst RequiredChip = styled.span`\n font-family: ${({ theme }: { theme: Theme }) => theme.fonts.mono};\n color: ${({ theme }: { theme: Theme }) => theme.colors.error};\n`;\n\nconst FieldDesc = styled.p`\n margin: 0;\n width: 100%;\n ${({ theme }: { theme: Theme }) => styledSmall(theme)};\n color: ${({ theme }: { theme: Theme }) => theme.colors.gray};\n`;\n\n/* ---------- response ---------- */\n\nconst StatusPill = styled.span<{ theme: Theme; $ok: boolean }>`\n font-family: ${({ theme }) => theme.fonts.mono};\n font-weight: 700;\n color: ${({ theme }) => theme.colors.surface};\n background: ${({ theme, $ok }) =>\n $ok ? theme.colors.success : theme.colors.error};\n padding: 0 4px;\n border-radius: ${({ theme }) => theme.spacing.radius.xs};\n`;\n\nconst Meta = styled.span`\n ${({ theme }: { theme: Theme }) => styledSmall(theme)};\n color: ${({ theme }: { theme: Theme }) => theme.colors.gray};\n`;\n\nconst ErrorText = styled.p`\n margin: 0;\n ${({ theme }: { theme: Theme }) => styledSmall(theme)};\n color: ${({ theme }: { theme: Theme }) => theme.colors.error};\n`;\n\nconst Placeholder = styled.div`\n border: dashed 1px ${({ theme }: { theme: Theme }) => theme.colors.grayLight};\n border-radius: ${({ theme }: { theme: Theme }) => theme.spacing.radius.lg};\n padding: 24px;\n min-height: 120px;\n display: flex;\n align-items: center;\n justify-content: center;\n gap: 10px;\n text-align: center;\n ${({ theme }: { theme: Theme }) => styledSmall(theme)};\n color: ${({ theme }: { theme: Theme }) => theme.colors.gray};\n`;\n\n// Holds the response (or empty placeholder) and lets the loading spinner sit on\n// top of it, so a re-send keeps the previous content in place instead of\n// collapsing and jumping the layout.\nconst ResponseArea = styled.div`\n position: relative;\n`;\n\nconst LoadingOverlay = styled.div`\n position: absolute;\n inset: 0;\n z-index: 1;\n display: flex;\n align-items: center;\n justify-content: center;\n border: solid 1px ${({ theme }: { theme: Theme }) => theme.colors.grayLight};\n border-radius: ${({ theme }: { theme: Theme }) => theme.spacing.radius.lg};\n color: ${({ theme }: { theme: Theme }) => theme.colors.grayDark};\n background: ${({ theme }: { theme: Theme }) =>\n `color-mix(in srgb, ${theme.colors.light} 60%, transparent)`};\n backdrop-filter: blur(1px);\n`;\n\nconst ResponseMedia = styled.img`\n max-width: 100%;\n border-radius: ${({ theme }: { theme: Theme }) => theme.spacing.radius.xs};\n`;\n\nexport function ApiPlayground({\n operation,\n defaultMode = \"proxy\",\n allowDirect = true,\n allowlist,\n snippetLanguages = [\"curl\", \"javascript\", \"python\"],\n}: ApiPlaygroundProps) {\n const [open, setOpen] = useState(false);\n const [paramValues, setParamValues] = useState<Record<string, string>>({});\n const [authValues, setAuthValues] = useState<Record<string, string>>({});\n const initialBody = useMemo(() => firstJsonExample(operation), [operation]);\n const [bodyText, setBodyText] = useState(initialBody?.text ?? \"\");\n const [mode, setMode] = useState<\"proxy\" | \"direct\">(defaultMode);\n const [showSecrets, setShowSecrets] = useState(false);\n const [loading, setLoading] = useState(false);\n const [response, setResponse] = useState<PlaygroundResponse | null>(null);\n const [error, setError] = useState<string | null>(null);\n const [corsRetry, setCorsRetry] = useState(false);\n const abortRef = useRef<AbortController | null>(null);\n\n const paramKey = (p: ParameterDescriptor) => p.in + \":\" + p.name;\n\n const isAllowed = useCallback(\n (url: string) =>\n Boolean(\n matchAllowlist(url) ??\n (allowlist ? matchAllowlistIn(allowlist, url) : null),\n ),\n [allowlist],\n );\n\n const buildRequest = useCallback((): BuiltRequest => {\n const base = serverBase(operation.servers[0]);\n const pathValues: Record<string, string> = {};\n const queryParts: string[] = [];\n const headers: Record<string, string> = {};\n const secretHeaderNames: string[] = [];\n let cookie = \"\";\n\n for (const param of operation.parameters) {\n const value = paramValues[paramKey(param)];\n if (value === undefined || value === \"\") continue;\n if (param.in === \"path\") pathValues[param.name] = value;\n else if (param.in === \"query\")\n queryParts.push(\n encodeURIComponent(param.name) + \"=\" + encodeURIComponent(value),\n );\n else if (param.in === \"header\") headers[param.name] = value;\n else if (param.in === \"cookie\")\n cookie += (cookie ? \"; \" : \"\") + param.name + \"=\" + value;\n }\n\n for (const requirement of operation.security) {\n const scheme = requirement.scheme;\n if (!scheme) continue;\n if (scheme.type === \"apiKey\" && scheme.name) {\n const value = authValues[requirement.schemeName];\n if (!value) continue;\n if (scheme.in === \"header\") {\n headers[scheme.name] = value;\n secretHeaderNames.push(scheme.name);\n } else if (scheme.in === \"query\") {\n queryParts.push(\n encodeURIComponent(scheme.name) + \"=\" + encodeURIComponent(value),\n );\n } else if (scheme.in === \"cookie\") {\n cookie += (cookie ? \"; \" : \"\") + scheme.name + \"=\" + value;\n }\n } else if (scheme.type === \"http\" && scheme.scheme === \"basic\") {\n const user = authValues[requirement.schemeName + \":user\"] ?? \"\";\n const pass = authValues[requirement.schemeName + \":pass\"] ?? \"\";\n if (user || pass) {\n headers[\"Authorization\"] = \"Basic \" + btoa(user + \":\" + pass);\n secretHeaderNames.push(\"Authorization\");\n }\n } else {\n const token = authValues[requirement.schemeName];\n if (token) {\n headers[\"Authorization\"] = \"Bearer \" + token;\n secretHeaderNames.push(\"Authorization\");\n }\n }\n }\n\n if (cookie) headers[\"Cookie\"] = cookie;\n\n const hasBody =\n operation.requestBody !== undefined &&\n operation.method !== \"get\" &&\n operation.method !== \"head\" &&\n bodyText.trim() !== \"\";\n if (hasBody && !headers[\"Content-Type\"] && initialBody) {\n headers[\"Content-Type\"] = initialBody.contentType;\n }\n\n const query = queryParts.join(\"&\");\n const url =\n base +\n applyPathParams(operation.path, pathValues) +\n (query ? \"?\" + query : \"\");\n\n return { url, headers, body: hasBody ? bodyText : null, secretHeaderNames };\n }, [operation, paramValues, authValues, bodyText, initialBody]);\n\n const snippets = useMemo(() => {\n const built = buildRequest();\n const headers: Record<string, string> = { ...built.headers };\n if (!showSecrets) {\n for (const name of built.secretHeaderNames) {\n headers[name] = \"<YOUR_CREDENTIALS>\";\n }\n }\n return buildSnippets(\n {\n method: operation.method.toUpperCase(),\n url: built.url || operation.path,\n headers,\n body: built.body,\n },\n snippetLanguages,\n );\n }, [buildRequest, showSecrets, operation, snippetLanguages]);\n\n const sendProxy = useCallback(\n async (\n built: BuiltRequest,\n signal: AbortSignal,\n ): Promise<PlaygroundResponse> => {\n const res = await fetch(\"/api/playground\", {\n method: \"POST\",\n headers: { \"Content-Type\": \"application/json\" },\n signal,\n body: JSON.stringify({\n targetUrl: built.url,\n method: operation.method.toUpperCase(),\n headers: built.headers,\n body: built.body ?? undefined,\n bodyEncoding: \"utf8\",\n }),\n });\n const data = await res.json();\n if (!res.ok) {\n throw new Error(\n typeof data?.error === \"string\" ? data.error : \"Request failed\",\n );\n }\n return data as PlaygroundResponse;\n },\n [operation],\n );\n\n const sendDirect = useCallback(\n async (\n built: BuiltRequest,\n signal: AbortSignal,\n ): Promise<PlaygroundResponse> => {\n const start = Date.now();\n const res = await fetch(built.url, {\n method: operation.method.toUpperCase(),\n headers: built.headers,\n body: built.body ?? undefined,\n signal,\n });\n const buffer = await res.arrayBuffer();\n const contentType = res.headers.get(\"content-type\");\n const isText = classifyResponse(contentType) === \"text\";\n const headers: Record<string, string> = {};\n res.headers.forEach((value, key) => {\n headers[key] = value;\n });\n return {\n status: res.status,\n statusText: res.statusText,\n headers,\n contentType,\n bodyEncoding: isText ? \"utf8\" : \"base64\",\n body: isText\n ? new TextDecoder().decode(buffer)\n : bufferToBase64(buffer),\n truncated: false,\n byteLength: buffer.byteLength,\n durationMs: Date.now() - start,\n };\n },\n [operation],\n );\n\n const send = useCallback(async () => {\n setError(null);\n setCorsRetry(false);\n // Keep any previous response on screen; the loading overlay covers it so\n // the layout does not collapse and jump while the new request is in flight.\n\n const built = buildRequest();\n if (!built.url) {\n setError(\"No server URL is configured for this endpoint.\");\n return;\n }\n if (!isAllowed(built.url)) {\n setError(\"This endpoint's server is not in the allowed list.\");\n return;\n }\n if (\n mode === \"direct\" &&\n typeof window !== \"undefined\" &&\n window.location.protocol === \"https:\" &&\n built.url.startsWith(\"http:\")\n ) {\n setError(\n \"Browsers block HTTP requests from an HTTPS page. Use proxy mode.\",\n );\n return;\n }\n\n const controller = new AbortController();\n abortRef.current = controller;\n setLoading(true);\n try {\n const result =\n mode === \"direct\"\n ? await sendDirect(built, controller.signal)\n : await sendProxy(built, controller.signal);\n setResponse(result);\n } catch (err) {\n if (controller.signal.aborted) return;\n if (mode === \"direct\" && err instanceof TypeError) {\n setCorsRetry(true);\n setError(\n \"The browser blocked this cross-origin request (CORS). Run it server-side instead.\",\n );\n } else {\n setError(err instanceof Error ? err.message : \"Request failed\");\n }\n } finally {\n setLoading(false);\n abortRef.current = null;\n }\n }, [buildRequest, isAllowed, mode, sendDirect, sendProxy]);\n\n const retryViaProxy = useCallback(() => {\n setMode(\"proxy\");\n setCorsRetry(false);\n void send();\n }, [send]);\n\n const groupedParams = LOCATIONS.map((location) => ({\n location,\n params: operation.parameters.filter((p) => p.in === location),\n })).filter((group) => group.params.length > 0);\n // Only the first visible section starts expanded.\n const hasAuth = operation.security.length > 0;\n\n const responseKind = response ? classifyResponse(response.contentType) : null;\n const mediaSrc =\n response && responseKind && responseKind !== \"text\"\n ? \"data:\" +\n (response.contentType ?? \"application/octet-stream\") +\n \";base64,\" +\n response.body\n : \"\";\n\n const renderParamField = (param: ParameterDescriptor) => (\n <Field key={param.anchorId}>\n <FieldHead>\n <FieldName>{param.name}</FieldName>\n <TypeChip>{schemaTypeLabel(param.schema)}</TypeChip>\n {param.required ? <RequiredChip>required</RequiredChip> : null}\n </FieldHead>\n {param.description ? <FieldDesc>{param.description}</FieldDesc> : null}\n <Input\n $fullWidth\n type=\"text\"\n aria-label={param.name}\n placeholder={\n param.example !== undefined\n ? String(param.example)\n : \"enter \" + param.name\n }\n value={paramValues[paramKey(param)] ?? \"\"}\n onChange={(e) =>\n setParamValues((prev) => ({\n ...prev,\n [paramKey(param)]: e.target.value,\n }))\n }\n />\n </Field>\n );\n\n return (\n <>\n <CompactBar>\n <MethodBadge $method={operation.method}>{operation.method}</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 $method={operation.method}>\n {operation.method}\n </MethodBadge>\n <PathText>{renderPath(operation.path)}</PathText>\n <AccentButton\n type=\"button\"\n onClick={() => void send()}\n disabled={loading}\n >\n Send\n {loading ? <Spinner size={14} /> : <Icon name=\"play\" size={14} />}\n </AccentButton>\n </PathBar>\n </DialogHeader>\n\n <DialogBody>\n <Column>\n {operation.description || operation.summary ? (\n <Description>\n {operation.description ?? operation.summary}\n </Description>\n ) : null}\n\n <Toolbar>\n {operation.servers.length > 0 ? (\n <Meta>{serverBase(operation.servers[0])}</Meta>\n ) : null}\n {allowDirect ? (\n <>\n <Toggle\n type=\"button\"\n $active={mode === \"proxy\"}\n onClick={() => setMode(\"proxy\")}\n >\n Proxy\n </Toggle>\n <Toggle\n type=\"button\"\n $active={mode === \"direct\"}\n onClick={() => setMode(\"direct\")}\n >\n Direct\n </Toggle>\n </>\n ) : null}\n <Toggle\n type=\"button\"\n $active={showSecrets}\n onClick={() => setShowSecrets((v) => !v)}\n >\n {showSecrets ? \"Hide secrets\" : \"Show secrets\"}\n </Toggle>\n </Toolbar>\n\n {operation.security.length > 0 ? (\n <Accordion title=\"Authorization\" defaultOpen>\n <SectionInner>\n {operation.security.map((requirement) => {\n const scheme = requirement.scheme;\n if (\n scheme &&\n scheme.type === \"http\" &&\n scheme.scheme === \"basic\"\n ) {\n return (\n <Field key={requirement.schemeName}>\n <FieldHead>\n <FieldName>{requirement.schemeName}</FieldName>\n <TypeChip>basic</TypeChip>\n </FieldHead>\n <Input\n $fullWidth\n type=\"text\"\n aria-label={requirement.schemeName + \" username\"}\n placeholder=\"username\"\n value={\n authValues[requirement.schemeName + \":user\"] ?? \"\"\n }\n onChange={(e) =>\n setAuthValues((prev) => ({\n ...prev,\n [requirement.schemeName + \":user\"]:\n e.target.value,\n }))\n }\n />\n <Input\n $fullWidth\n type={showSecrets ? \"text\" : \"password\"}\n aria-label={requirement.schemeName + \" password\"}\n placeholder=\"password\"\n value={\n authValues[requirement.schemeName + \":pass\"] ?? \"\"\n }\n onChange={(e) =>\n setAuthValues((prev) => ({\n ...prev,\n [requirement.schemeName + \":pass\"]:\n e.target.value,\n }))\n }\n />\n </Field>\n );\n }\n const chip =\n scheme?.type === \"apiKey\"\n ? \"apiKey\"\n : scheme?.scheme === \"bearer\"\n ? \"bearer\"\n : (scheme?.type ?? \"token\");\n return (\n <Field key={requirement.schemeName}>\n <FieldHead>\n <FieldName>{requirement.schemeName}</FieldName>\n <TypeChip>{chip}</TypeChip>\n <RequiredChip>required</RequiredChip>\n </FieldHead>\n <Input\n $fullWidth\n type={showSecrets ? \"text\" : \"password\"}\n aria-label={requirement.schemeName}\n placeholder={\n chip === \"bearer\"\n ? \"enter bearer token\"\n : \"enter value\"\n }\n value={authValues[requirement.schemeName] ?? \"\"}\n onChange={(e) =>\n setAuthValues((prev) => ({\n ...prev,\n [requirement.schemeName]: e.target.value,\n }))\n }\n />\n </Field>\n );\n })}\n </SectionInner>\n </Accordion>\n ) : null}\n\n {groupedParams.map((group, index) => (\n <Accordion\n key={group.location}\n title={LOCATION_TITLES[group.location]}\n defaultOpen={!hasAuth && index === 0}\n >\n <SectionInner>\n {group.params.map(renderParamField)}\n </SectionInner>\n </Accordion>\n ))}\n\n {operation.requestBody &&\n operation.method !== \"get\" &&\n operation.method !== \"head\" ? (\n <Accordion\n title=\"Body\"\n defaultOpen={!hasAuth && groupedParams.length === 0}\n >\n <SectionInner>\n <Textarea\n $fullWidth\n rows={8}\n aria-label=\"Request body\"\n spellCheck={false}\n value={bodyText}\n onChange={(e) => setBodyText(e.target.value)}\n />\n </SectionInner>\n </Accordion>\n ) : null}\n\n {error ? (\n <Field>\n <ErrorText>{error}</ErrorText>\n {corsRetry ? (\n <Toggle type=\"button\" onClick={retryViaProxy}>\n Retry via proxy\n </Toggle>\n ) : null}\n </Field>\n ) : null}\n </Column>\n\n <Column>\n <ResponseArea>\n {response ? (\n <Card>\n <CardHead as=\"div\">\n <Inline>\n <StatusPill\n $ok={response.status >= 200 && response.status < 400}\n >\n {response.status} {response.statusText}\n </StatusPill>\n <Meta>{response.durationMs}ms</Meta>\n <Meta>{response.byteLength} bytes</Meta>\n {response.truncated ? <Meta>(truncated)</Meta> : null}\n </Inline>\n </CardHead>\n <CardBody>\n {responseKind === \"image\" ? (\n <ResponseMedia src={mediaSrc} alt=\"Response\" />\n ) : responseKind === \"video\" ? (\n <video\n controls\n src={mediaSrc}\n style={{ maxWidth: \"100%\" }}\n />\n ) : responseKind === \"audio\" ? (\n <audio controls src={mediaSrc} />\n ) : responseKind === \"binary\" ? (\n <a href={mediaSrc} download>\n Download response ({response.byteLength} bytes)\n </a>\n ) : (\n <Code\n language={codeLanguage(response.contentType)}\n code={prettyBody(response.contentType, response.body)}\n />\n )}\n </CardBody>\n </Card>\n ) : (\n <Placeholder>\n Send the request to see the live response here.\n </Placeholder>\n )}\n {loading ? (\n <LoadingOverlay>\n <Spinner size={22} />\n </LoadingOverlay>\n ) : null}\n </ResponseArea>\n\n {snippets.length > 0 ? <CodeTabs tabs={snippets} /> : null}\n </Column>\n </DialogBody>\n </Modal>\n </>\n );\n}\n";
|
|
1
|
+
export declare const apiPlaygroundTemplate = "\"use client\";\nimport React, { useCallback, useMemo, useRef, useState } from \"react\";\nimport styled, { css } from \"styled-components\";\nimport {\n styledSmall,\n interactiveStyles,\n Input,\n Textarea,\n Modal,\n} from \"cherry-styled-components\";\nimport { mq, Theme } from \"@/app/theme\";\nimport { Code, CodeTabs } from \"@/components/layout/Code\";\nimport { Icon } from \"@/components/layout/Icon\";\nimport { Accordion } from \"@/components/layout/Accordion\";\nimport { Badge, httpMethodBadgeColor } from \"@/components/layout/Badge\";\nimport { CopyButton } from \"@/components/layout/CopyButton\";\nimport { Spinner } from \"@/components/Spinner\";\nimport { matchAllowlist, matchAllowlistIn } from \"@/utils/playgroundAllowlist\";\nimport type { AllowlistEntry } from \"@/utils/playgroundAllowlist\";\nimport { buildSnippets } from \"@/utils/apiSnippets\";\nimport type { SnippetLanguage } from \"@/utils/apiSnippets\";\nimport type {\n OperationDescriptor,\n ParameterDescriptor,\n ServerDescriptor,\n} from \"@/types/openapi\";\n\ninterface PlaygroundResponse {\n status: number;\n statusText: string;\n headers: Record<string, string>;\n contentType: string | null;\n bodyEncoding: \"utf8\" | \"base64\";\n body: string;\n truncated: boolean;\n byteLength: number;\n durationMs: number;\n}\n\ninterface BuiltRequest {\n url: string;\n headers: Record<string, string>;\n body: string | null;\n secretHeaderNames: string[];\n}\n\nexport interface ApiPlaygroundProps {\n operation: OperationDescriptor;\n defaultMode?: \"proxy\" | \"direct\";\n allowDirect?: boolean;\n // Extra client-side allowlist entries. The server proxy always enforces the\n // build-time allowlist regardless; this only relaxes the client pre-flight\n // (used by the docs demo to run in direct mode without a configured spec).\n allowlist?: AllowlistEntry[];\n snippetLanguages?: SnippetLanguage[];\n}\n\nfunction schemaTypeLabel(schema: unknown): string {\n if (schema && typeof schema === \"object\") {\n const record = schema as { type?: unknown; format?: unknown };\n if (typeof record.type === \"string\") {\n return typeof record.format === \"string\"\n ? record.type + \" (\" + record.format + \")\"\n : record.type;\n }\n }\n return \"string\";\n}\n\nfunction serverBase(server: ServerDescriptor | undefined): string {\n if (!server) return \"\";\n let url = server.url;\n const variables = server.variables;\n if (variables) {\n for (const key of Object.keys(variables)) {\n url = url.split(\"{\" + key + \"}\").join(variables[key].default);\n }\n }\n while (url.endsWith(\"/\")) url = url.slice(0, -1);\n return url;\n}\n\nfunction applyPathParams(\n template: string,\n values: Record<string, string>,\n): string {\n let result = template;\n for (const key of Object.keys(values)) {\n result = result\n .split(\"{\" + key + \"}\")\n .join(encodeURIComponent(values[key]));\n }\n return result;\n}\n\nfunction firstJsonExample(op: OperationDescriptor): {\n contentType: string;\n text: string;\n} | null {\n if (!op.requestBody || op.requestBody.content.length === 0) return null;\n const media =\n op.requestBody.content.find((m) => m.contentType.includes(\"json\")) ??\n op.requestBody.content[0];\n let text = \"\";\n if (media.example !== undefined) {\n try {\n text = JSON.stringify(media.example, null, 2);\n } catch {\n text = \"\";\n }\n }\n return { contentType: media.contentType, text };\n}\n\nfunction classifyResponse(\n contentType: string | null,\n): \"image\" | \"video\" | \"audio\" | \"text\" | \"binary\" {\n if (!contentType) return \"text\";\n const t = contentType.toLowerCase();\n if (t.startsWith(\"image/\") && !t.includes(\"svg\")) return \"image\";\n if (t.startsWith(\"video/\")) return \"video\";\n if (t.startsWith(\"audio/\")) return \"audio\";\n if (\n t.includes(\"json\") ||\n t.startsWith(\"text/\") ||\n t.includes(\"xml\") ||\n t.includes(\"svg\") ||\n t.includes(\"html\") ||\n t.includes(\"javascript\") ||\n t.includes(\"csv\")\n ) {\n return \"text\";\n }\n return \"binary\";\n}\n\nfunction codeLanguage(contentType: string | null): string {\n if (!contentType) return \"text\";\n const t = contentType.toLowerCase();\n if (t.includes(\"json\")) return \"json\";\n if (t.includes(\"html\")) return \"html\";\n if (t.includes(\"xml\") || t.includes(\"svg\")) return \"xml\";\n if (t.includes(\"javascript\")) return \"javascript\";\n return \"text\";\n}\n\nfunction prettyBody(contentType: string | null, body: string): string {\n if (contentType && contentType.toLowerCase().includes(\"json\")) {\n try {\n return JSON.stringify(JSON.parse(body), null, 2);\n } catch {\n return body;\n }\n }\n return body;\n}\n\nfunction bufferToBase64(buffer: ArrayBuffer): string {\n let binary = \"\";\n const bytes = new Uint8Array(buffer);\n const chunk = 0x8000;\n for (let i = 0; i < bytes.length; i += chunk) {\n binary += String.fromCharCode(...bytes.subarray(i, i + chunk));\n }\n return btoa(binary);\n}\n\nfunction renderPath(path: string): React.ReactNode {\n return path\n .split(/(\\{[^}]+\\})/g)\n .map((part, index) =>\n part.startsWith(\"{\") ? (\n <PathParam key={index}>{part}</PathParam>\n ) : (\n <span key={index}>{part}</span>\n ),\n );\n}\n\nconst LOCATIONS: ParameterDescriptor[\"in\"][] = [\n \"path\",\n \"query\",\n \"header\",\n \"cookie\",\n];\n\nconst LOCATION_TITLES: Record<string, string> = {\n path: \"Path\",\n query: \"Query\",\n header: \"Headers\",\n cookie: \"Cookies\",\n};\n\n/* ---------- compact bar ---------- */\n\nconst CompactBar = styled.div`\n display: flex;\n align-items: center;\n gap: 10px;\n margin: 0;\n padding: 8px 8px 8px 12px;\n border: solid 1px ${({ theme }: { theme: Theme }) => theme.colors.grayLight};\n border-radius: ${({ theme }: { theme: Theme }) => theme.spacing.radius.lg};\n background: ${({ theme }: { theme: Theme }) => theme.colors.light};\n`;\n\n// The method chip is Badge's mono+solid variation; only bar-layout metrics\n// are adjusted here.\nconst MethodBadge = styled(Badge)`\n flex-shrink: 0;\n padding: 0 4px;\n border: none;\n`;\n\nconst PathText = styled.span`\n flex: 1;\n min-width: 0;\n font-family: ${({ theme }: { theme: Theme }) => theme.fonts.mono};\n font-weight: 600;\n font-size: 14px;\n color: ${({ theme }: { theme: Theme }) => theme.colors.dark};\n overflow-x: auto;\n white-space: nowrap;\n &::-webkit-scrollbar {\n display: none;\n }\n`;\n\nconst PathParam = styled.span`\n font-family: ${({ theme }: { theme: Theme }) => theme.fonts.mono};\n background: ${({ theme }: { theme: Theme }) =>\n `color-mix(in srgb, ${theme.colors.primaryLight} 20%, transparent)`};\n color: ${({ theme }: { theme: Theme }) => theme.colors.dark};\n padding: 2px 4px;\n border-radius: ${({ theme }: { theme: Theme }) => theme.spacing.radius.xs};\n overflow-wrap: anywhere;\n`;\n\nconst AccentButton = styled.button<{ theme: Theme }>`\n cursor: pointer;\n display: inline-flex;\n align-items: center;\n gap: 6px;\n flex-shrink: 0;\n font-family: ${({ theme }: { theme: Theme }) => theme.fonts.text};\n font-weight: 600;\n font-size: 14px;\n color: ${({ theme }: { theme: Theme }) => theme.colors.surface};\n background: ${({ theme }: { theme: Theme }) => theme.colors.primary};\n border: none;\n padding: 8px 14px;\n border-radius: ${({ theme }: { theme: Theme }) => theme.spacing.radius.xs};\n ${interactiveStyles};\n\n & svg {\n color: ${({ theme }: { theme: Theme }) => theme.colors.surface};\n stroke: ${({ theme }: { theme: Theme }) => theme.colors.surface};\n }\n\n &:hover {\n background: ${({ theme }: { theme: Theme }) => theme.colors.primaryDark};\n }\n &:disabled {\n opacity: 0.6;\n cursor: default;\n }\n`;\n\n/* ---------- modal ---------- */\n\nconst DialogHeader = styled.div`\n display: flex;\n align-items: center;\n gap: 10px;\n flex-wrap: wrap;\n margin: 5px 0 0 0;\n`;\n\nconst PathBar = styled.div`\n flex: 1;\n min-width: 200px;\n display: flex;\n align-items: center;\n gap: 8px;\n padding: 8px 8px 8px 12px;\n border: solid 1px ${({ theme }: { theme: Theme }) => theme.colors.grayLight};\n border-radius: ${({ theme }: { theme: Theme }) => theme.spacing.radius.xs};\n background: ${({ theme }: { theme: Theme }) => theme.colors.light};\n`;\n\nconst DialogBody = styled.div`\n display: grid;\n grid-template-columns: 1fr;\n gap: 20px;\n padding: 0;\n margin: 20px 0 0 0;\n\n ${mq(\"lg\")} {\n grid-template-columns: 1fr 1fr;\n }\n`;\n\nconst Column = styled.div`\n display: flex;\n flex-direction: column;\n gap: 20px;\n min-width: 0;\n`;\n\nconst Description = styled.p`\n margin: 0;\n ${({ theme }: { theme: Theme }) => styledSmall(theme)};\n color: ${({ theme }: { theme: Theme }) => theme.colors.grayDark};\n`;\n\nconst Toolbar = styled.div`\n display: flex;\n align-items: center;\n gap: 8px;\n flex-wrap: wrap;\n`;\n\nconst Toggle = styled.button<{ theme: Theme; $active?: boolean }>`\n position: relative;\n cursor: pointer;\n text-decoration: none;\n font-size: ${({ theme }) => theme.fontSizes.small.lg};\n line-height: 1;\n color: ${({ theme }) => theme.colors.accent};\n display: flex;\n gap: 6px;\n transition: all 0.3s ease;\n font-weight: 600;\n white-space: nowrap;\n min-width: fit-content;\n background: ${({ theme }) =>\n `color-mix(in srgb, ${theme.colors.primaryLight} 10%, transparent)`};\n padding: 6px 8px;\n border: none;\n border-radius: ${({ theme }) => theme.spacing.radius.xs};\n ${interactiveStyles};\n\n ${({ $active, theme }) =>\n $active &&\n css`\n background: ${theme.colors.primary};\n color: ${theme.colors.surface};\n `}\n`;\n\n/* ---------- collapsible card ---------- */\n\nconst Card = styled.div`\n border: solid 1px ${({ theme }: { theme: Theme }) => theme.colors.grayLight};\n border-radius: ${({ theme }: { theme: Theme }) => theme.spacing.radius.lg};\n overflow: hidden;\n`;\n\nconst CardHead = styled.button`\n cursor: pointer;\n width: 100%;\n display: flex;\n align-items: center;\n justify-content: space-between;\n gap: 8px;\n padding: 12px 20px;\n border: none;\n background: transparent;\n color: ${({ theme }: { theme: Theme }) => theme.colors.dark};\n ${({ theme }: { theme: Theme }) => styledSmall(theme)};\n`;\n\nconst Inline = styled.span`\n display: inline-flex;\n align-items: center;\n gap: 8px;\n`;\n\nconst CardBody = styled.div`\n padding: 0 20px 20px;\n display: flex;\n flex-direction: column;\n gap: 16px;\n`;\n\n/* ---------- fields ---------- */\n\n// Wraps an accordion section's content and insets it, so full-width inputs'\n// focus rings (a 4px box-shadow) are not clipped by the accordion's own\n// overflow. Keeps the accordion component untouched.\nconst SectionInner = styled.div`\n display: flex;\n flex-direction: column;\n gap: 16px;\n padding: 4px;\n`;\n\nconst Field = styled.div`\n display: flex;\n flex-direction: column;\n gap: 6px;\n`;\n\nconst FieldHead = styled.div`\n display: flex;\n align-items: center;\n gap: 8px;\n flex-wrap: wrap;\n ${({ theme }: { theme: Theme }) => styledSmall(theme)};\n`;\n\nconst FieldName = styled.span`\n font-family: ${({ theme }: { theme: Theme }) => theme.fonts.mono};\n font-weight: 600;\n color: ${({ theme }: { theme: Theme }) => theme.colors.dark};\n`;\n\nconst TypeChip = styled.span`\n font-family: ${({ theme }: { theme: Theme }) => theme.fonts.mono};\n color: ${({ theme }: { theme: Theme }) => theme.colors.grayDark};\n background: ${({ theme }: { theme: Theme }) =>\n `color-mix(in srgb, ${theme.colors.gray} 15%, transparent)`};\n padding: 0 4px;\n border-radius: ${({ theme }: { theme: Theme }) => theme.spacing.radius.xs};\n`;\n\nconst RequiredChip = styled.span`\n font-family: ${({ theme }: { theme: Theme }) => theme.fonts.mono};\n color: ${({ theme }: { theme: Theme }) => theme.colors.error};\n`;\n\nconst FieldDesc = styled.p`\n margin: 0;\n width: 100%;\n ${({ theme }: { theme: Theme }) => styledSmall(theme)};\n color: ${({ theme }: { theme: Theme }) => theme.colors.gray};\n`;\n\n/* ---------- response ---------- */\n\nconst StatusPill = styled.span<{ theme: Theme; $ok: boolean }>`\n font-family: ${({ theme }) => theme.fonts.mono};\n font-weight: 700;\n color: ${({ theme }) => theme.colors.surface};\n background: ${({ theme, $ok }) =>\n $ok ? theme.colors.success : theme.colors.error};\n padding: 0 4px;\n border-radius: ${({ theme }) => theme.spacing.radius.xs};\n`;\n\nconst Meta = styled.span`\n ${({ theme }: { theme: Theme }) => styledSmall(theme)};\n color: ${({ theme }: { theme: Theme }) => theme.colors.gray};\n`;\n\nconst ErrorText = styled.p`\n margin: 0;\n ${({ theme }: { theme: Theme }) => styledSmall(theme)};\n color: ${({ theme }: { theme: Theme }) => theme.colors.error};\n`;\n\nconst Placeholder = styled.div`\n border: dashed 1px ${({ theme }: { theme: Theme }) => theme.colors.grayLight};\n border-radius: ${({ theme }: { theme: Theme }) => theme.spacing.radius.lg};\n padding: 24px;\n min-height: 120px;\n display: flex;\n align-items: center;\n justify-content: center;\n gap: 10px;\n text-align: center;\n ${({ theme }: { theme: Theme }) => styledSmall(theme)};\n color: ${({ theme }: { theme: Theme }) => theme.colors.gray};\n`;\n\n// Holds the response (or empty placeholder) and lets the loading spinner sit on\n// top of it, so a re-send keeps the previous content in place instead of\n// collapsing and jumping the layout.\nconst ResponseArea = styled.div`\n position: relative;\n`;\n\nconst LoadingOverlay = styled.div`\n position: absolute;\n inset: 0;\n z-index: 1;\n display: flex;\n align-items: center;\n justify-content: center;\n border: solid 1px ${({ theme }: { theme: Theme }) => theme.colors.grayLight};\n border-radius: ${({ theme }: { theme: Theme }) => theme.spacing.radius.lg};\n color: ${({ theme }: { theme: Theme }) => theme.colors.grayDark};\n background: ${({ theme }: { theme: Theme }) =>\n `color-mix(in srgb, ${theme.colors.light} 60%, transparent)`};\n backdrop-filter: blur(1px);\n`;\n\nconst ResponseMedia = styled.img`\n max-width: 100%;\n border-radius: ${({ theme }: { theme: Theme }) => theme.spacing.radius.xs};\n`;\n\nexport function ApiPlayground({\n operation,\n defaultMode = \"proxy\",\n allowDirect = true,\n allowlist,\n snippetLanguages = [\"curl\", \"javascript\", \"python\"],\n}: ApiPlaygroundProps) {\n const [open, setOpen] = useState(false);\n const [paramValues, setParamValues] = useState<Record<string, string>>({});\n const [authValues, setAuthValues] = useState<Record<string, string>>({});\n const initialBody = useMemo(() => firstJsonExample(operation), [operation]);\n const [bodyText, setBodyText] = useState(initialBody?.text ?? \"\");\n const [mode, setMode] = useState<\"proxy\" | \"direct\">(defaultMode);\n const [showSecrets, setShowSecrets] = useState(false);\n const [loading, setLoading] = useState(false);\n const [response, setResponse] = useState<PlaygroundResponse | null>(null);\n const [error, setError] = useState<string | null>(null);\n const [corsRetry, setCorsRetry] = useState(false);\n const abortRef = useRef<AbortController | null>(null);\n\n const paramKey = (p: ParameterDescriptor) => p.in + \":\" + p.name;\n\n const isAllowed = useCallback(\n (url: string) =>\n Boolean(\n matchAllowlist(url) ??\n (allowlist ? matchAllowlistIn(allowlist, url) : null),\n ),\n [allowlist],\n );\n\n const buildRequest = useCallback((): BuiltRequest => {\n const base = serverBase(operation.servers[0]);\n const pathValues: Record<string, string> = {};\n const queryParts: string[] = [];\n const headers: Record<string, string> = {};\n const secretHeaderNames: string[] = [];\n let cookie = \"\";\n\n for (const param of operation.parameters) {\n const value = paramValues[paramKey(param)];\n if (value === undefined || value === \"\") continue;\n if (param.in === \"path\") pathValues[param.name] = value;\n else if (param.in === \"query\")\n queryParts.push(\n encodeURIComponent(param.name) + \"=\" + encodeURIComponent(value),\n );\n else if (param.in === \"header\") headers[param.name] = value;\n else if (param.in === \"cookie\")\n cookie += (cookie ? \"; \" : \"\") + param.name + \"=\" + value;\n }\n\n for (const requirement of operation.security) {\n const scheme = requirement.scheme;\n if (!scheme) continue;\n if (scheme.type === \"apiKey\" && scheme.name) {\n const value = authValues[requirement.schemeName];\n if (!value) continue;\n if (scheme.in === \"header\") {\n headers[scheme.name] = value;\n secretHeaderNames.push(scheme.name);\n } else if (scheme.in === \"query\") {\n queryParts.push(\n encodeURIComponent(scheme.name) + \"=\" + encodeURIComponent(value),\n );\n } else if (scheme.in === \"cookie\") {\n cookie += (cookie ? \"; \" : \"\") + scheme.name + \"=\" + value;\n }\n } else if (scheme.type === \"http\" && scheme.scheme === \"basic\") {\n const user = authValues[requirement.schemeName + \":user\"] ?? \"\";\n const pass = authValues[requirement.schemeName + \":pass\"] ?? \"\";\n if (user || pass) {\n headers[\"Authorization\"] = \"Basic \" + btoa(user + \":\" + pass);\n secretHeaderNames.push(\"Authorization\");\n }\n } else {\n const token = authValues[requirement.schemeName];\n if (token) {\n headers[\"Authorization\"] = \"Bearer \" + token;\n secretHeaderNames.push(\"Authorization\");\n }\n }\n }\n\n if (cookie) headers[\"Cookie\"] = cookie;\n\n const hasBody =\n operation.requestBody !== undefined &&\n operation.method !== \"get\" &&\n operation.method !== \"head\" &&\n bodyText.trim() !== \"\";\n if (hasBody && !headers[\"Content-Type\"] && initialBody) {\n headers[\"Content-Type\"] = initialBody.contentType;\n }\n\n const query = queryParts.join(\"&\");\n const url =\n base +\n applyPathParams(operation.path, pathValues) +\n (query ? \"?\" + query : \"\");\n\n return { url, headers, body: hasBody ? bodyText : null, secretHeaderNames };\n }, [operation, paramValues, authValues, bodyText, initialBody]);\n\n const snippets = useMemo(() => {\n const built = buildRequest();\n const headers: Record<string, string> = { ...built.headers };\n if (!showSecrets) {\n for (const name of built.secretHeaderNames) {\n headers[name] = \"<YOUR_CREDENTIALS>\";\n }\n }\n return buildSnippets(\n {\n method: operation.method.toUpperCase(),\n url: built.url || operation.path,\n headers,\n body: built.body,\n },\n snippetLanguages,\n );\n }, [buildRequest, showSecrets, operation, snippetLanguages]);\n\n const sendProxy = useCallback(\n async (\n built: BuiltRequest,\n signal: AbortSignal,\n ): Promise<PlaygroundResponse> => {\n const res = await fetch(\"/api/playground\", {\n method: \"POST\",\n headers: { \"Content-Type\": \"application/json\" },\n signal,\n body: JSON.stringify({\n targetUrl: built.url,\n method: operation.method.toUpperCase(),\n headers: built.headers,\n body: built.body ?? undefined,\n bodyEncoding: \"utf8\",\n }),\n });\n const data = await res.json();\n if (!res.ok) {\n throw new Error(\n typeof data?.error === \"string\" ? data.error : \"Request failed\",\n );\n }\n return data as PlaygroundResponse;\n },\n [operation],\n );\n\n const sendDirect = useCallback(\n async (\n built: BuiltRequest,\n signal: AbortSignal,\n ): Promise<PlaygroundResponse> => {\n const start = Date.now();\n const res = await fetch(built.url, {\n method: operation.method.toUpperCase(),\n headers: built.headers,\n body: built.body ?? undefined,\n signal,\n });\n const buffer = await res.arrayBuffer();\n const contentType = res.headers.get(\"content-type\");\n const isText = classifyResponse(contentType) === \"text\";\n const headers: Record<string, string> = {};\n res.headers.forEach((value, key) => {\n headers[key] = value;\n });\n return {\n status: res.status,\n statusText: res.statusText,\n headers,\n contentType,\n bodyEncoding: isText ? \"utf8\" : \"base64\",\n body: isText\n ? new TextDecoder().decode(buffer)\n : bufferToBase64(buffer),\n truncated: false,\n byteLength: buffer.byteLength,\n durationMs: Date.now() - start,\n };\n },\n [operation],\n );\n\n const send = useCallback(async () => {\n setError(null);\n setCorsRetry(false);\n // Keep any previous response on screen; the loading overlay covers it so\n // the layout does not collapse and jump while the new request is in flight.\n\n const built = buildRequest();\n if (!built.url) {\n setError(\"No server URL is configured for this endpoint.\");\n return;\n }\n if (!isAllowed(built.url)) {\n setError(\"This endpoint's server is not in the allowed list.\");\n return;\n }\n if (\n mode === \"direct\" &&\n typeof window !== \"undefined\" &&\n window.location.protocol === \"https:\" &&\n built.url.startsWith(\"http:\")\n ) {\n setError(\n \"Browsers block HTTP requests from an HTTPS page. Use proxy mode.\",\n );\n return;\n }\n\n const controller = new AbortController();\n abortRef.current = controller;\n setLoading(true);\n try {\n const result =\n mode === \"direct\"\n ? await sendDirect(built, controller.signal)\n : await sendProxy(built, controller.signal);\n setResponse(result);\n } catch (err) {\n if (controller.signal.aborted) return;\n if (mode === \"direct\" && err instanceof TypeError) {\n setCorsRetry(true);\n setError(\n \"The browser blocked this cross-origin request (CORS). Run it server-side instead.\",\n );\n } else {\n setError(err instanceof Error ? err.message : \"Request failed\");\n }\n } finally {\n setLoading(false);\n abortRef.current = null;\n }\n }, [buildRequest, isAllowed, mode, sendDirect, sendProxy]);\n\n const retryViaProxy = useCallback(() => {\n setMode(\"proxy\");\n setCorsRetry(false);\n void send();\n }, [send]);\n\n const groupedParams = LOCATIONS.map((location) => ({\n location,\n params: operation.parameters.filter((p) => p.in === location),\n })).filter((group) => group.params.length > 0);\n // Only the first visible section starts expanded.\n const hasAuth = operation.security.length > 0;\n\n const responseKind = response ? classifyResponse(response.contentType) : null;\n const mediaSrc =\n response && responseKind && responseKind !== \"text\"\n ? \"data:\" +\n (response.contentType ?? \"application/octet-stream\") +\n \";base64,\" +\n response.body\n : \"\";\n\n const renderParamField = (param: ParameterDescriptor) => (\n <Field key={param.anchorId}>\n <FieldHead>\n <FieldName>{param.name}</FieldName>\n <TypeChip>{schemaTypeLabel(param.schema)}</TypeChip>\n {param.required ? <RequiredChip>required</RequiredChip> : null}\n </FieldHead>\n {param.description ? <FieldDesc>{param.description}</FieldDesc> : null}\n <Input\n $fullWidth\n type=\"text\"\n aria-label={param.name}\n placeholder={\n param.example !== undefined\n ? String(param.example)\n : \"enter \" + param.name\n }\n value={paramValues[paramKey(param)] ?? \"\"}\n onChange={(e) =>\n setParamValues((prev) => ({\n ...prev,\n [paramKey(param)]: e.target.value,\n }))\n }\n />\n </Field>\n );\n\n return (\n <>\n <CompactBar>\n <MethodBadge\n mono\n solid\n size=\"sm\"\n color={httpMethodBadgeColor(operation.method)}\n >\n {operation.method}\n </MethodBadge>\n <PathText>{renderPath(operation.path)}</PathText>\n <CopyButton\n text={operation.method.toUpperCase() + \" \" + operation.path}\n label=\"Copy endpoint\"\n size={16}\n />\n <AccentButton type=\"button\" onClick={() => setOpen(true)}>\n Try it\n <Icon name=\"play\" size={14} />\n </AccentButton>\n </CompactBar>\n\n <Modal\n $isOpen={open}\n $onClose={() => setOpen(false)}\n $width={1120}\n $title={\n operation.summary ??\n operation.method.toUpperCase() + \" \" + operation.path\n }\n >\n <DialogHeader>\n <PathBar>\n <MethodBadge\n mono\n solid\n size=\"sm\"\n color={httpMethodBadgeColor(operation.method)}\n >\n {operation.method}\n </MethodBadge>\n <PathText>{renderPath(operation.path)}</PathText>\n <AccentButton\n type=\"button\"\n onClick={() => void send()}\n disabled={loading}\n >\n Send\n {loading ? <Spinner size={14} /> : <Icon name=\"play\" size={14} />}\n </AccentButton>\n </PathBar>\n </DialogHeader>\n\n <DialogBody>\n <Column>\n {operation.description || operation.summary ? (\n <Description>\n {operation.description ?? operation.summary}\n </Description>\n ) : null}\n\n <Toolbar>\n {operation.servers.length > 0 ? (\n <Meta>{serverBase(operation.servers[0])}</Meta>\n ) : null}\n {allowDirect ? (\n <>\n <Toggle\n type=\"button\"\n $active={mode === \"proxy\"}\n onClick={() => setMode(\"proxy\")}\n >\n Proxy\n </Toggle>\n <Toggle\n type=\"button\"\n $active={mode === \"direct\"}\n onClick={() => setMode(\"direct\")}\n >\n Direct\n </Toggle>\n </>\n ) : null}\n <Toggle\n type=\"button\"\n $active={showSecrets}\n onClick={() => setShowSecrets((v) => !v)}\n >\n {showSecrets ? \"Hide secrets\" : \"Show secrets\"}\n </Toggle>\n </Toolbar>\n\n {operation.security.length > 0 ? (\n <Accordion title=\"Authorization\" defaultOpen>\n <SectionInner>\n {operation.security.map((requirement) => {\n const scheme = requirement.scheme;\n if (\n scheme &&\n scheme.type === \"http\" &&\n scheme.scheme === \"basic\"\n ) {\n return (\n <Field key={requirement.schemeName}>\n <FieldHead>\n <FieldName>{requirement.schemeName}</FieldName>\n <TypeChip>basic</TypeChip>\n </FieldHead>\n <Input\n $fullWidth\n type=\"text\"\n aria-label={requirement.schemeName + \" username\"}\n placeholder=\"username\"\n value={\n authValues[requirement.schemeName + \":user\"] ?? \"\"\n }\n onChange={(e) =>\n setAuthValues((prev) => ({\n ...prev,\n [requirement.schemeName + \":user\"]:\n e.target.value,\n }))\n }\n />\n <Input\n $fullWidth\n type={showSecrets ? \"text\" : \"password\"}\n aria-label={requirement.schemeName + \" password\"}\n placeholder=\"password\"\n value={\n authValues[requirement.schemeName + \":pass\"] ?? \"\"\n }\n onChange={(e) =>\n setAuthValues((prev) => ({\n ...prev,\n [requirement.schemeName + \":pass\"]:\n e.target.value,\n }))\n }\n />\n </Field>\n );\n }\n const chip =\n scheme?.type === \"apiKey\"\n ? \"apiKey\"\n : scheme?.scheme === \"bearer\"\n ? \"bearer\"\n : (scheme?.type ?? \"token\");\n return (\n <Field key={requirement.schemeName}>\n <FieldHead>\n <FieldName>{requirement.schemeName}</FieldName>\n <TypeChip>{chip}</TypeChip>\n <RequiredChip>required</RequiredChip>\n </FieldHead>\n <Input\n $fullWidth\n type={showSecrets ? \"text\" : \"password\"}\n aria-label={requirement.schemeName}\n placeholder={\n chip === \"bearer\"\n ? \"enter bearer token\"\n : \"enter value\"\n }\n value={authValues[requirement.schemeName] ?? \"\"}\n onChange={(e) =>\n setAuthValues((prev) => ({\n ...prev,\n [requirement.schemeName]: e.target.value,\n }))\n }\n />\n </Field>\n );\n })}\n </SectionInner>\n </Accordion>\n ) : null}\n\n {groupedParams.map((group, index) => (\n <Accordion\n key={group.location}\n title={LOCATION_TITLES[group.location]}\n defaultOpen={!hasAuth && index === 0}\n >\n <SectionInner>\n {group.params.map(renderParamField)}\n </SectionInner>\n </Accordion>\n ))}\n\n {operation.requestBody &&\n operation.method !== \"get\" &&\n operation.method !== \"head\" ? (\n <Accordion\n title=\"Body\"\n defaultOpen={!hasAuth && groupedParams.length === 0}\n >\n <SectionInner>\n <Textarea\n $fullWidth\n rows={8}\n aria-label=\"Request body\"\n spellCheck={false}\n value={bodyText}\n onChange={(e) => setBodyText(e.target.value)}\n />\n </SectionInner>\n </Accordion>\n ) : null}\n\n {error ? (\n <Field>\n <ErrorText>{error}</ErrorText>\n {corsRetry ? (\n <Toggle type=\"button\" onClick={retryViaProxy}>\n Retry via proxy\n </Toggle>\n ) : null}\n </Field>\n ) : null}\n </Column>\n\n <Column>\n <ResponseArea>\n {response ? (\n <Card>\n <CardHead as=\"div\">\n <Inline>\n <StatusPill\n $ok={response.status >= 200 && response.status < 400}\n >\n {response.status} {response.statusText}\n </StatusPill>\n <Meta>{response.durationMs}ms</Meta>\n <Meta>{response.byteLength} bytes</Meta>\n {response.truncated ? <Meta>(truncated)</Meta> : null}\n </Inline>\n </CardHead>\n <CardBody>\n {responseKind === \"image\" ? (\n <ResponseMedia src={mediaSrc} alt=\"Response\" />\n ) : responseKind === \"video\" ? (\n <video\n controls\n src={mediaSrc}\n style={{ maxWidth: \"100%\" }}\n />\n ) : responseKind === \"audio\" ? (\n <audio controls src={mediaSrc} />\n ) : responseKind === \"binary\" ? (\n <a href={mediaSrc} download>\n Download response ({response.byteLength} bytes)\n </a>\n ) : (\n <Code\n language={codeLanguage(response.contentType)}\n code={prettyBody(response.contentType, response.body)}\n />\n )}\n </CardBody>\n </Card>\n ) : (\n <Placeholder>\n Send the request to see the live response here.\n </Placeholder>\n )}\n {loading ? (\n <LoadingOverlay>\n <Spinner size={22} />\n </LoadingOverlay>\n ) : null}\n </ResponseArea>\n\n {snippets.length > 0 ? <CodeTabs tabs={snippets} /> : null}\n </Column>\n </DialogBody>\n </Modal>\n </>\n );\n}\n";
|
|
@@ -12,6 +12,7 @@ import { mq, Theme } from "@/app/theme";
|
|
|
12
12
|
import { Code, CodeTabs } from "@/components/layout/Code";
|
|
13
13
|
import { Icon } from "@/components/layout/Icon";
|
|
14
14
|
import { Accordion } from "@/components/layout/Accordion";
|
|
15
|
+
import { Badge, httpMethodBadgeColor } from "@/components/layout/Badge";
|
|
15
16
|
import { CopyButton } from "@/components/layout/CopyButton";
|
|
16
17
|
import { Spinner } from "@/components/Spinner";
|
|
17
18
|
import { matchAllowlist, matchAllowlistIn } from "@/utils/playgroundAllowlist";
|
|
@@ -54,22 +55,6 @@ export interface ApiPlaygroundProps {
|
|
|
54
55
|
snippetLanguages?: SnippetLanguage[];
|
|
55
56
|
}
|
|
56
57
|
|
|
57
|
-
const METHOD_TOKENS: Record<string, keyof Theme["colors"]> = {
|
|
58
|
-
get: "info",
|
|
59
|
-
post: "success",
|
|
60
|
-
put: "warning",
|
|
61
|
-
patch: "warning",
|
|
62
|
-
delete: "error",
|
|
63
|
-
head: "gray",
|
|
64
|
-
options: "gray",
|
|
65
|
-
trace: "gray",
|
|
66
|
-
};
|
|
67
|
-
|
|
68
|
-
function methodColor(theme: Theme, method: string): string {
|
|
69
|
-
const token = METHOD_TOKENS[method.toLowerCase()] ?? "gray";
|
|
70
|
-
return theme.colors[token];
|
|
71
|
-
}
|
|
72
|
-
|
|
73
58
|
function schemaTypeLabel(schema: unknown): string {
|
|
74
59
|
if (schema && typeof schema === "object") {
|
|
75
60
|
const record = schema as { type?: unknown; format?: unknown };
|
|
@@ -219,17 +204,12 @@ const CompactBar = styled.div\`
|
|
|
219
204
|
background: \${({ theme }: { theme: Theme }) => theme.colors.light};
|
|
220
205
|
\`;
|
|
221
206
|
|
|
222
|
-
|
|
223
|
-
|
|
224
|
-
|
|
225
|
-
font-size: 12px;
|
|
226
|
-
letter-spacing: 0.04em;
|
|
227
|
-
text-transform: uppercase;
|
|
228
|
-
color: \${({ theme }) => theme.colors.surface};
|
|
229
|
-
background: \${({ theme, $method }) => methodColor(theme, $method)};
|
|
230
|
-
padding: 0 4px;
|
|
231
|
-
border-radius: \${({ theme }) => theme.spacing.radius.xs};
|
|
207
|
+
// The method chip is Badge's mono+solid variation; only bar-layout metrics
|
|
208
|
+
// are adjusted here.
|
|
209
|
+
const MethodBadge = styled(Badge)\`
|
|
232
210
|
flex-shrink: 0;
|
|
211
|
+
padding: 0 4px;
|
|
212
|
+
border: none;
|
|
233
213
|
\`;
|
|
234
214
|
|
|
235
215
|
const PathText = styled.span\`
|
|
@@ -812,7 +792,14 @@ export function ApiPlayground({
|
|
|
812
792
|
return (
|
|
813
793
|
<>
|
|
814
794
|
<CompactBar>
|
|
815
|
-
<MethodBadge
|
|
795
|
+
<MethodBadge
|
|
796
|
+
mono
|
|
797
|
+
solid
|
|
798
|
+
size="sm"
|
|
799
|
+
color={httpMethodBadgeColor(operation.method)}
|
|
800
|
+
>
|
|
801
|
+
{operation.method}
|
|
802
|
+
</MethodBadge>
|
|
816
803
|
<PathText>{renderPath(operation.path)}</PathText>
|
|
817
804
|
<CopyButton
|
|
818
805
|
text={operation.method.toUpperCase() + " " + operation.path}
|
|
@@ -836,7 +823,12 @@ export function ApiPlayground({
|
|
|
836
823
|
>
|
|
837
824
|
<DialogHeader>
|
|
838
825
|
<PathBar>
|
|
839
|
-
<MethodBadge
|
|
826
|
+
<MethodBadge
|
|
827
|
+
mono
|
|
828
|
+
solid
|
|
829
|
+
size="sm"
|
|
830
|
+
color={httpMethodBadgeColor(operation.method)}
|
|
831
|
+
>
|
|
840
832
|
{operation.method}
|
|
841
833
|
</MethodBadge>
|
|
842
834
|
<PathText>{renderPath(operation.path)}</PathText>
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
export declare const badgeTemplate = "\"use client\";\nimport styled, { css } from \"styled-components\";\nimport { Theme } from \"@/app/theme\";\nimport { Icon } from \"@/components/layout/Icon\";\n\ntype BadgeColor =\n | \"gray\"\n | \"blue\"\n | \"green\"\n | \"yellow\"\n | \"orange\"\n | \"red\"\n | \"purple\"\n | \"white\"\n | \"surface\"\n | \"white-destructive\"\n | \"surface-destructive\"\n | \"info\"\n | \"success\"\n | \"warning\"\n | \"error\";\n\ntype BadgeSize = \"xs\" | \"sm\" | \"md\" | \"lg\";\n\ntype BadgeShape = \"rounded\" | \"pill\";\n\n// The semantic colors read theme tokens instead of the fixed palette, so\n// they follow theme.json and the light/dark toggle. They are also what the\n// HTTP method chips use.\nconst THEME_TOKEN_COLORS = [\"info\", \"success\", \"warning\", \"error\"] as const;\n\ntype ThemeTokenColor = (typeof THEME_TOKEN_COLORS)[number];\n\ntype HexBadgeColor = Exclude<BadgeColor, ThemeTokenColor>;\n\nfunction isThemeTokenColor(color: BadgeColor): color is ThemeTokenColor {\n return (THEME_TOKEN_COLORS as readonly string[]).includes(color);\n}\n\n// Single source for verb -> badge color, shared by the sidebar method tags\n// and the API playground so every surface colors HTTP verbs identically.\nconst HTTP_METHOD_COLORS: Record<string, BadgeColor> = {\n get: \"info\",\n post: \"success\",\n put: \"warning\",\n patch: \"warning\",\n delete: \"error\",\n head: \"gray\",\n options: \"gray\",\n trace: \"gray\",\n};\n\nfunction httpMethodBadgeColor(method: string): BadgeColor {\n return HTTP_METHOD_COLORS[method.toLowerCase()] ?? \"gray\";\n}\n\ninterface BadgePalette {\n background: string;\n text: string;\n border: string;\n darkBackground: string;\n darkText: string;\n darkBorder: string;\n}\n\n// Strong fills for the hex palette; the white and surface variants have no\n// distinct solid form and fall back to their filled palette.\nconst SOLID_ACCENTS: Partial<Record<HexBadgeColor, string>> = {\n gray: \"#71717a\",\n blue: \"#3b82f6\",\n green: \"#22c55e\",\n yellow: \"#eab308\",\n orange: \"#f97316\",\n red: \"#ef4444\",\n purple: \"#a855f7\",\n};\n\n// Color tints are label-semantic and intentionally independent of theme.json\n// (same rationale as Callout's alert tints); only the surface and semantic\n// token variants read theme tokens, so they follow the active theme on both\n// modes. When both are set, solid wins over stroke.\nfunction badgePalette(\n theme: Theme,\n color: BadgeColor,\n stroke: boolean,\n solid: boolean,\n): BadgePalette {\n if (isThemeTokenColor(color)) {\n const token = theme.colors[color];\n if (solid) {\n return {\n background: token,\n text: theme.colors.surface,\n border: \"transparent\",\n darkBackground: token,\n darkText: theme.colors.surface,\n darkBorder: \"transparent\",\n };\n }\n if (stroke) {\n return {\n background: \"transparent\",\n text: token,\n border: token,\n darkBackground: \"transparent\",\n darkText: token,\n darkBorder: token,\n };\n }\n const tint = `color-mix(in srgb, ${token} 15%, transparent)`;\n return {\n background: tint,\n text: token,\n border: \"transparent\",\n darkBackground: tint,\n darkText: token,\n darkBorder: \"transparent\",\n };\n }\n\n const solidAccent = SOLID_ACCENTS[color];\n if (solid && solidAccent) {\n return {\n background: solidAccent,\n text: \"#ffffff\",\n border: \"transparent\",\n darkBackground: solidAccent,\n darkText: \"#ffffff\",\n darkBorder: \"transparent\",\n };\n }\n\n const surface = {\n background: theme.colors.surface,\n text: theme.colors.grayDark,\n border: theme.colors.grayLight,\n darkBackground: theme.colors.surface,\n darkText: theme.colors.grayDark,\n darkBorder: theme.colors.grayLight,\n };\n\n if (stroke && !solid) {\n const strokes: Record<HexBadgeColor, BadgePalette> = {\n gray: {\n background: \"transparent\",\n text: \"#52525b\",\n border: \"#a1a1aa\",\n darkBackground: \"transparent\",\n darkText: \"#d4d4d8\",\n darkBorder: \"#71717a\",\n },\n blue: {\n background: \"transparent\",\n text: \"#1d4ed8\",\n border: \"#3b82f6\",\n darkBackground: \"transparent\",\n darkText: \"#93c5fd\",\n darkBorder: \"#3b82f6\",\n },\n green: {\n background: \"transparent\",\n text: \"#15803d\",\n border: \"#22c55e\",\n darkBackground: \"transparent\",\n darkText: \"#86efac\",\n darkBorder: \"#22c55e\",\n },\n yellow: {\n background: \"transparent\",\n text: \"#a16207\",\n border: \"#eab308\",\n darkBackground: \"transparent\",\n darkText: \"#fde047\",\n darkBorder: \"#eab308\",\n },\n orange: {\n background: \"transparent\",\n text: \"#c2410c\",\n border: \"#f97316\",\n darkBackground: \"transparent\",\n darkText: \"#fdba74\",\n darkBorder: \"#f97316\",\n },\n red: {\n background: \"transparent\",\n text: \"#b91c1c\",\n border: \"#ef4444\",\n darkBackground: \"transparent\",\n darkText: \"#fca5a5\",\n darkBorder: \"#ef4444\",\n },\n purple: {\n background: \"transparent\",\n text: \"#7e22ce\",\n border: \"#a855f7\",\n darkBackground: \"transparent\",\n darkText: \"#d8b4fe\",\n darkBorder: \"#a855f7\",\n },\n white: {\n background: \"transparent\",\n text: \"#18181b\",\n border: \"#e4e4e7\",\n darkBackground: \"transparent\",\n darkText: \"#fafafa\",\n darkBorder: \"#3f3f46\",\n },\n surface: { ...surface, background: \"transparent\" },\n \"white-destructive\": {\n background: \"transparent\",\n text: \"#b91c1c\",\n border: \"#ef4444\",\n darkBackground: \"transparent\",\n darkText: \"#fca5a5\",\n darkBorder: \"#ef4444\",\n },\n \"surface-destructive\": {\n background: \"transparent\",\n text: \"#b91c1c\",\n border: \"#ef4444\",\n darkBackground: \"transparent\",\n darkText: \"#fca5a5\",\n darkBorder: \"#ef4444\",\n },\n };\n return strokes[color];\n }\n\n const filled: Record<HexBadgeColor, BadgePalette> = {\n gray: {\n background: \"#f4f4f5\",\n text: \"#3f3f46\",\n border: \"transparent\",\n darkBackground: \"#71717a33\",\n darkText: \"#d4d4d8\",\n darkBorder: \"transparent\",\n },\n blue: {\n background: \"#dbeafe\",\n text: \"#1e40af\",\n border: \"transparent\",\n darkBackground: \"#3b82f633\",\n darkText: \"#93c5fd\",\n darkBorder: \"transparent\",\n },\n green: {\n background: \"#dcfce7\",\n text: \"#166534\",\n border: \"transparent\",\n darkBackground: \"#22c55e33\",\n darkText: \"#86efac\",\n darkBorder: \"transparent\",\n },\n yellow: {\n background: \"#fef9c3\",\n text: \"#854d0e\",\n border: \"transparent\",\n darkBackground: \"#eab30833\",\n darkText: \"#fde047\",\n darkBorder: \"transparent\",\n },\n orange: {\n background: \"#ffedd5\",\n text: \"#9a3412\",\n border: \"transparent\",\n darkBackground: \"#f9731633\",\n darkText: \"#fdba74\",\n darkBorder: \"transparent\",\n },\n red: {\n background: \"#fee2e2\",\n text: \"#991b1b\",\n border: \"transparent\",\n darkBackground: \"#ef444433\",\n darkText: \"#fca5a5\",\n darkBorder: \"transparent\",\n },\n purple: {\n background: \"#f3e8ff\",\n text: \"#6b21a8\",\n border: \"transparent\",\n darkBackground: \"#a855f733\",\n darkText: \"#d8b4fe\",\n darkBorder: \"transparent\",\n },\n white: {\n background: \"#ffffff\",\n text: \"#18181b\",\n border: \"#e4e4e7\",\n darkBackground: \"#ffffff\",\n darkText: \"#18181b\",\n darkBorder: \"#e4e4e7\",\n },\n surface,\n \"white-destructive\": {\n background: \"#ffffff\",\n text: \"#b91c1c\",\n border: \"#fecaca\",\n darkBackground: \"#ffffff\",\n darkText: \"#b91c1c\",\n darkBorder: \"#fecaca\",\n },\n \"surface-destructive\": {\n ...surface,\n text: \"#b91c1c\",\n border: \"#fecaca\",\n darkText: \"#fca5a5\",\n darkBorder: \"#ef44444d\",\n },\n };\n return filled[color];\n}\n\nconst badgeSizes = {\n xs: css`\n font-size: 11px;\n line-height: 16px;\n padding: 1px 6px;\n gap: 3px;\n `,\n sm: css`\n font-size: 12px;\n line-height: 18px;\n padding: 2px 8px;\n gap: 4px;\n `,\n md: css`\n font-size: 13px;\n line-height: 20px;\n padding: 3px 10px;\n gap: 5px;\n `,\n lg: css`\n font-size: 14px;\n line-height: 22px;\n padding: 4px 12px;\n gap: 6px;\n `,\n};\n\nconst badgeIconSizes: Record<BadgeSize, number> = {\n xs: 10,\n sm: 12,\n md: 14,\n lg: 16,\n};\n\nconst StyledBadge = styled.span<{\n theme: Theme;\n $color: BadgeColor;\n $size: BadgeSize;\n $shape: BadgeShape;\n $stroke: boolean;\n $solid: boolean;\n $mono: boolean;\n $disabled: boolean;\n}>`\n display: inline-flex;\n align-items: center;\n vertical-align: middle;\n max-width: max-content;\n font-family: inherit;\n font-weight: 600;\n white-space: nowrap;\n\n & svg.lucide {\n flex-shrink: 0;\n color: inherit;\n }\n\n ${({ $size }) => badgeSizes[$size]}\n\n ${({ theme, $mono }) =>\n $mono &&\n css`\n font-family: ${theme.fonts.mono};\n font-weight: 700;\n text-transform: uppercase;\n letter-spacing: 0.04em;\n `}\n\n ${({ theme, $shape }) =>\n $shape === \"pill\"\n ? css`\n border-radius: 999px;\n `\n : css`\n border-radius: ${theme.spacing.radius.xs};\n `}\n\n ${({ theme, $color, $stroke, $solid }) => {\n const palette = badgePalette(theme, $color, $stroke, $solid);\n return css`\n background: ${palette.background};\n color: ${palette.text};\n border: solid 1px ${palette.border};\n\n :root.dark & {\n background: ${palette.darkBackground};\n color: ${palette.darkText};\n border-color: ${palette.darkBorder};\n }\n `;\n }}\n\n ${({ $disabled }) =>\n $disabled &&\n css`\n opacity: 0.5;\n `}\n`;\n\ninterface BadgeProps extends React.HTMLAttributes<HTMLSpanElement> {\n children: React.ReactNode;\n color?: BadgeColor;\n size?: BadgeSize;\n shape?: BadgeShape;\n icon?: string;\n stroke?: boolean;\n solid?: boolean;\n mono?: boolean;\n disabled?: boolean;\n}\n\nfunction Badge({\n children,\n color = \"gray\",\n size = \"md\",\n shape = \"rounded\",\n icon,\n stroke = false,\n solid = false,\n mono = false,\n disabled = false,\n className,\n}: BadgeProps) {\n return (\n <StyledBadge\n className={className}\n $color={color}\n $size={size}\n $shape={shape}\n $stroke={stroke}\n $solid={solid}\n $mono={mono}\n $disabled={disabled}\n >\n {icon ? <Icon name={icon} size={badgeIconSizes[size]} /> : null}\n {children}\n </StyledBadge>\n );\n}\n\nexport { Badge, httpMethodBadgeColor };\n";
|