doccupine 0.0.133 → 0.0.134
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 +40 -1
- package/dist/index.d.ts +1 -1
- package/dist/index.js +274 -19
- package/dist/lib/config-manager.d.ts +8 -1
- package/dist/lib/config-manager.js +98 -4
- package/dist/lib/openapi-types.d.ts +120 -0
- package/dist/lib/openapi-types.js +14 -0
- package/dist/lib/openapi.d.ts +52 -0
- package/dist/lib/openapi.js +603 -0
- package/dist/lib/structures.js +28 -2
- package/dist/lib/types.d.ts +22 -0
- package/dist/lib/utils.d.ts +8 -0
- package/dist/lib/utils.js +14 -0
- package/dist/templates/app/api/playground/route.d.ts +1 -0
- package/dist/templates/app/api/playground/route.js +199 -0
- package/dist/templates/components/Docs.d.ts +1 -1
- package/dist/templates/components/Docs.js +11 -2
- package/dist/templates/components/SideBar.d.ts +1 -1
- package/dist/templates/components/SideBar.js +10 -0
- package/dist/templates/components/layout/Accordion.d.ts +1 -1
- package/dist/templates/components/layout/Accordion.js +3 -2
- package/dist/templates/components/layout/ActionBar.d.ts +1 -1
- package/dist/templates/components/layout/ActionBar.js +21 -14
- package/dist/templates/components/layout/ApiPlayground.d.ts +1 -0
- package/dist/templates/components/layout/ApiPlayground.js +1083 -0
- package/dist/templates/components/layout/ApiPlaygroundDemo.d.ts +1 -0
- package/dist/templates/components/layout/ApiPlaygroundDemo.js +81 -0
- package/dist/templates/components/layout/Code.d.ts +1 -1
- package/dist/templates/components/layout/Code.js +10 -22
- package/dist/templates/components/layout/CopyButton.d.ts +1 -0
- package/dist/templates/components/layout/CopyButton.js +68 -0
- package/dist/templates/components/layout/DocsComponents.d.ts +1 -1
- package/dist/templates/components/layout/DocsComponents.js +39 -0
- package/dist/templates/components/layout/Mermaid.d.ts +1 -1
- package/dist/templates/components/layout/Mermaid.js +21 -3
- package/dist/templates/components/layout/SharedStyles.d.ts +1 -1
- package/dist/templates/components/layout/SharedStyles.js +0 -4
- package/dist/templates/components/layout/Steps.d.ts +1 -1
- package/dist/templates/components/layout/Steps.js +0 -1
- package/dist/templates/components/layout/Update.d.ts +1 -1
- package/dist/templates/components/layout/Update.js +2 -1
- package/dist/templates/mdx/accordion.mdx.d.ts +1 -1
- package/dist/templates/mdx/accordion.mdx.js +19 -1
- package/dist/templates/mdx/ai-assistant.mdx.d.ts +1 -1
- package/dist/templates/mdx/ai-assistant.mdx.js +3 -2
- package/dist/templates/mdx/analytics.mdx.d.ts +1 -1
- package/dist/templates/mdx/analytics.mdx.js +2 -2
- package/dist/templates/mdx/api-playground.mdx.d.ts +1 -0
- package/dist/templates/mdx/api-playground.mdx.js +158 -0
- package/dist/templates/mdx/authentication.mdx.d.ts +1 -1
- package/dist/templates/mdx/authentication.mdx.js +3 -3
- 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/commands.mdx.d.ts +1 -1
- package/dist/templates/mdx/commands.mdx.js +3 -2
- package/dist/templates/mdx/components.mdx.d.ts +1 -1
- package/dist/templates/mdx/components.mdx.js +12 -9
- package/dist/templates/mdx/deployment-and-hosting.mdx.d.ts +1 -1
- package/dist/templates/mdx/deployment-and-hosting.mdx.js +4 -3
- package/dist/templates/mdx/fields.mdx.d.ts +1 -1
- package/dist/templates/mdx/fields.mdx.js +1 -1
- package/dist/templates/mdx/fonts.mdx.d.ts +1 -1
- package/dist/templates/mdx/fonts.mdx.js +2 -2
- package/dist/templates/mdx/footer-links.mdx.d.ts +1 -1
- package/dist/templates/mdx/footer-links.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/globals.mdx.d.ts +1 -1
- package/dist/templates/mdx/globals.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/media-and-assets.mdx.d.ts +1 -1
- package/dist/templates/mdx/media-and-assets.mdx.js +2 -2
- package/dist/templates/mdx/mermaid.mdx.d.ts +1 -1
- package/dist/templates/mdx/mermaid.mdx.js +1 -1
- package/dist/templates/mdx/model-context-protocol.mdx.d.ts +1 -1
- package/dist/templates/mdx/model-context-protocol.mdx.js +2 -2
- package/dist/templates/mdx/navigation.mdx.d.ts +1 -1
- package/dist/templates/mdx/navigation.mdx.js +22 -11
- package/dist/templates/mdx/platform/ai-assistant.mdx.d.ts +1 -1
- package/dist/templates/mdx/platform/ai-assistant.mdx.js +4 -3
- package/dist/templates/mdx/platform/analytics.mdx.d.ts +1 -1
- package/dist/templates/mdx/platform/analytics.mdx.js +2 -2
- package/dist/templates/mdx/platform/api-playground.mdx.d.ts +1 -0
- package/dist/templates/mdx/platform/api-playground.mdx.js +62 -0
- package/dist/templates/mdx/platform/billing.mdx.d.ts +1 -1
- package/dist/templates/mdx/platform/billing.mdx.js +1 -1
- package/dist/templates/mdx/platform/build-and-deploy.mdx.d.ts +1 -1
- package/dist/templates/mdx/platform/build-and-deploy.mdx.js +1 -1
- package/dist/templates/mdx/platform/creating-a-project.mdx.d.ts +1 -1
- package/dist/templates/mdx/platform/creating-a-project.mdx.js +12 -2
- package/dist/templates/mdx/platform/custom-domains.mdx.d.ts +1 -1
- package/dist/templates/mdx/platform/custom-domains.mdx.js +1 -1
- package/dist/templates/mdx/platform/fonts-settings.mdx.d.ts +1 -1
- package/dist/templates/mdx/platform/fonts-settings.mdx.js +1 -1
- package/dist/templates/mdx/platform/footer-links.mdx.d.ts +1 -0
- package/dist/templates/mdx/platform/footer-links.mdx.js +47 -0
- package/dist/templates/mdx/platform/import-from-github.mdx.d.ts +1 -0
- package/dist/templates/mdx/platform/import-from-github.mdx.js +91 -0
- package/dist/templates/mdx/platform/mcp.mdx.d.ts +1 -1
- package/dist/templates/mdx/platform/mcp.mdx.js +3 -3
- package/dist/templates/mdx/platform/project-settings.mdx.d.ts +1 -1
- package/dist/templates/mdx/platform/project-settings.mdx.js +1 -1
- package/dist/templates/mdx/platform/self-updating-docs.mdx.d.ts +1 -0
- package/dist/templates/mdx/platform/self-updating-docs.mdx.js +113 -0
- package/dist/templates/mdx/platform/team-members.mdx.d.ts +1 -1
- package/dist/templates/mdx/platform/team-members.mdx.js +1 -1
- package/dist/templates/mdx/sections.mdx.d.ts +1 -1
- package/dist/templates/mdx/sections.mdx.js +1 -1
- 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/theme.mdx.d.ts +1 -1
- package/dist/templates/mdx/theme.mdx.js +1 -1
- package/dist/templates/mdx/update.mdx.d.ts +1 -1
- package/dist/templates/mdx/update.mdx.js +1 -1
- package/dist/templates/mdx/what-is-doccupine.mdx.d.ts +1 -1
- package/dist/templates/mdx/what-is-doccupine.mdx.js +1 -1
- package/dist/templates/package.js +6 -6
- package/dist/templates/services/openapi/playgroundAllowlistStub.d.ts +1 -0
- package/dist/templates/services/openapi/playgroundAllowlistStub.js +4 -0
- package/dist/templates/types/openapi.d.ts +1 -0
- package/dist/templates/types/openapi.js +93 -0
- package/dist/templates/utils/apiAnchors.d.ts +1 -0
- package/dist/templates/utils/apiAnchors.js +39 -0
- package/dist/templates/utils/apiSnippets.d.ts +1 -0
- package/dist/templates/utils/apiSnippets.js +94 -0
- package/dist/templates/utils/orderNavItems.d.ts +1 -1
- package/dist/templates/utils/orderNavItems.js +3 -0
- package/dist/templates/utils/playgroundAllowlist.d.ts +1 -0
- package/dist/templates/utils/playgroundAllowlist.js +70 -0
- package/dist/templates/utils/ssrfGuard.d.ts +1 -0
- package/dist/templates/utils/ssrfGuard.js +217 -0
- package/package.json +3 -2
|
@@ -113,26 +113,33 @@ const StyledToggle = styled.button<{ theme: Theme; $isActive?: boolean }>\`
|
|
|
113
113
|
}
|
|
114
114
|
\`;
|
|
115
115
|
|
|
116
|
+
// The raw-content view renders a full-viewport textarea. That rule is scoped to
|
|
117
|
+
// the raw view (\`$raw\`) so it never leaks into textareas rendered inside page
|
|
118
|
+
// content - e.g. the API playground's request-body editor, which sits inside
|
|
119
|
+
// this same ActionBar in the normal (view) mode.
|
|
116
120
|
const StyledContent = styled.div<{
|
|
117
121
|
theme: Theme;
|
|
118
122
|
$hasSectionBar?: boolean;
|
|
123
|
+
$raw?: boolean;
|
|
119
124
|
}>\`
|
|
120
125
|
padding-top: 20px;
|
|
121
126
|
transition: all 0.3s ease;
|
|
122
127
|
|
|
123
|
-
|
|
124
|
-
|
|
125
|
-
|
|
126
|
-
|
|
127
|
-
|
|
128
|
-
|
|
129
|
-
|
|
130
|
-
|
|
131
|
-
|
|
132
|
-
|
|
133
|
-
|
|
134
|
-
|
|
135
|
-
|
|
128
|
+
\${({ $raw, $hasSectionBar }) =>
|
|
129
|
+
$raw &&
|
|
130
|
+
css\`
|
|
131
|
+
& textarea {
|
|
132
|
+
max-width: 640px;
|
|
133
|
+
margin: auto;
|
|
134
|
+
width: 100%;
|
|
135
|
+
height: 100%;
|
|
136
|
+
min-height: calc(100vh - \${$hasSectionBar ? 202 : 160}px);
|
|
137
|
+
|
|
138
|
+
\${mq("lg")} {
|
|
139
|
+
min-height: calc(100vh - 159px);
|
|
140
|
+
}
|
|
141
|
+
}
|
|
142
|
+
\`}
|
|
136
143
|
\`;
|
|
137
144
|
|
|
138
145
|
function ActionBar({ children, content }: ActionBarProps) {
|
|
@@ -181,7 +188,7 @@ function ActionBar({ children, content }: ActionBarProps) {
|
|
|
181
188
|
<StyledContent $hasSectionBar={hasSectionBar}>{children}</StyledContent>
|
|
182
189
|
)}
|
|
183
190
|
{!isView && (
|
|
184
|
-
<StyledContent $hasSectionBar={hasSectionBar}>
|
|
191
|
+
<StyledContent $hasSectionBar={hasSectionBar} $raw>
|
|
185
192
|
<Textarea defaultValue={content} $fullWidth />
|
|
186
193
|
</StyledContent>
|
|
187
194
|
)}
|
|
@@ -0,0 +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";
|