@djangocfg/ui-tools 2.1.284 → 2.1.286

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (71) hide show
  1. package/dist/DocsLayout-BCVU6TTX.cjs +2027 -0
  2. package/dist/DocsLayout-BCVU6TTX.cjs.map +1 -0
  3. package/dist/DocsLayout-ERETJLLV.mjs +2020 -0
  4. package/dist/DocsLayout-ERETJLLV.mjs.map +1 -0
  5. package/dist/{PlaygroundLayout-O52C6HK5.css → DocsLayout-MBFIB4NO.css} +1 -1
  6. package/dist/{PrettyCode.client-SGDGQTYT.cjs → PrettyCode.client-5GABIN2I.cjs} +57 -35
  7. package/dist/PrettyCode.client-5GABIN2I.cjs.map +1 -0
  8. package/dist/{PrettyCode.client-DW5LTG47.mjs → PrettyCode.client-IZTXXYHG.mjs} +57 -35
  9. package/dist/PrettyCode.client-IZTXXYHG.mjs.map +1 -0
  10. package/dist/chunk-IULI4XII.cjs +1129 -0
  11. package/dist/chunk-IULI4XII.cjs.map +1 -0
  12. package/dist/chunk-VZGQC3NG.mjs +1100 -0
  13. package/dist/chunk-VZGQC3NG.mjs.map +1 -0
  14. package/dist/index.cjs +88 -552
  15. package/dist/index.cjs.map +1 -1
  16. package/dist/index.d.cts +18 -6
  17. package/dist/index.d.ts +18 -6
  18. package/dist/index.mjs +25 -496
  19. package/dist/index.mjs.map +1 -1
  20. package/package.json +6 -6
  21. package/src/tools/OpenapiViewer/.claude/.sidecar/activity.jsonl +4 -0
  22. package/src/tools/OpenapiViewer/.claude/.sidecar/map_cache.json +30 -0
  23. package/src/tools/OpenapiViewer/.claude/.sidecar/usage.json +5 -0
  24. package/src/tools/OpenapiViewer/.claude/project-map.md +23 -0
  25. package/src/tools/OpenapiViewer/OpenapiViewer.story.tsx +28 -2
  26. package/src/tools/OpenapiViewer/README.md +104 -51
  27. package/src/tools/OpenapiViewer/components/DocsLayout/ApiIntroSection.tsx +64 -0
  28. package/src/tools/OpenapiViewer/components/DocsLayout/DocsView.tsx +137 -0
  29. package/src/tools/OpenapiViewer/components/DocsLayout/EndpointDoc.tsx +268 -0
  30. package/src/tools/OpenapiViewer/components/DocsLayout/SchemaCopyMenu.tsx +139 -0
  31. package/src/tools/OpenapiViewer/components/DocsLayout/Sidebar.tsx +211 -0
  32. package/src/tools/OpenapiViewer/components/DocsLayout/SlideInPlayground.tsx +101 -0
  33. package/src/tools/OpenapiViewer/components/DocsLayout/TryItSheet.tsx +57 -0
  34. package/src/tools/OpenapiViewer/components/DocsLayout/anchor.ts +11 -0
  35. package/src/tools/OpenapiViewer/components/DocsLayout/grouping.ts +71 -0
  36. package/src/tools/OpenapiViewer/components/DocsLayout/index.tsx +166 -0
  37. package/src/tools/OpenapiViewer/components/DocsLayout/schemaFields.ts +121 -0
  38. package/src/tools/OpenapiViewer/components/DocsLayout/sidebarLabel.ts +60 -0
  39. package/src/tools/OpenapiViewer/components/index.ts +5 -2
  40. package/src/tools/OpenapiViewer/components/shared/BodyFormEditor.tsx +422 -0
  41. package/src/tools/OpenapiViewer/components/shared/EndpointDraftSync.tsx +108 -0
  42. package/src/tools/OpenapiViewer/components/shared/EndpointResetButton.tsx +50 -0
  43. package/src/tools/OpenapiViewer/components/{PlaygroundLayout → shared}/RequestPanel.tsx +174 -87
  44. package/src/tools/OpenapiViewer/components/shared/SendButton.tsx +91 -0
  45. package/src/tools/OpenapiViewer/components/{PlaygroundLayout → shared}/ui.tsx +5 -4
  46. package/src/tools/OpenapiViewer/context/PlaygroundContext.tsx +82 -8
  47. package/src/tools/OpenapiViewer/hooks/useEndpointDraft.ts +142 -0
  48. package/src/tools/OpenapiViewer/hooks/useOpenApiSchema.ts +126 -13
  49. package/src/tools/OpenapiViewer/index.tsx +3 -7
  50. package/src/tools/OpenapiViewer/lazy.tsx +6 -27
  51. package/src/tools/OpenapiViewer/types.ts +44 -0
  52. package/src/tools/OpenapiViewer/utils/formatters.ts +2 -23
  53. package/src/tools/OpenapiViewer/utils/index.ts +3 -1
  54. package/src/tools/OpenapiViewer/utils/schemaExport.ts +206 -0
  55. package/src/tools/OpenapiViewer/utils/url.ts +202 -0
  56. package/src/tools/PrettyCode/PrettyCode.client.tsx +42 -8
  57. package/src/tools/PrettyCode/index.tsx +6 -0
  58. package/dist/PlaygroundLayout-DHUATCHB.cjs +0 -798
  59. package/dist/PlaygroundLayout-DHUATCHB.cjs.map +0 -1
  60. package/dist/PlaygroundLayout-NONWOVQR.mjs +0 -791
  61. package/dist/PlaygroundLayout-NONWOVQR.mjs.map +0 -1
  62. package/dist/PrettyCode.client-DW5LTG47.mjs.map +0 -1
  63. package/dist/PrettyCode.client-SGDGQTYT.cjs.map +0 -1
  64. package/dist/chunk-5FKE7OME.cjs +0 -369
  65. package/dist/chunk-5FKE7OME.cjs.map +0 -1
  66. package/dist/chunk-BKWDHJKF.mjs +0 -356
  67. package/dist/chunk-BKWDHJKF.mjs.map +0 -1
  68. package/src/tools/OpenapiViewer/components/PlaygroundLayout/EndpointList.tsx +0 -228
  69. package/src/tools/OpenapiViewer/components/PlaygroundLayout/index.tsx +0 -107
  70. /package/dist/{PlaygroundLayout-O52C6HK5.css.map → DocsLayout-MBFIB4NO.css.map} +0 -0
  71. /package/src/tools/OpenapiViewer/components/{PlaygroundLayout → shared}/ResponsePanel.tsx +0 -0
@@ -0,0 +1,1100 @@
1
+ import { __name } from './chunk-CGILA3WO.mjs';
2
+ import React3, { lazy, createContext, useState, useMemo, useCallback, Suspense, useContext, useReducer, useRef, useEffect } from 'react';
3
+ import '@djangocfg/ui-core/styles/palette';
4
+ import { jsx, jsxs, Fragment } from 'react/jsx-runtime';
5
+ import ReactMarkdown from 'react-markdown';
6
+ import remarkGfm from 'remark-gfm';
7
+ import { CopyButton } from '@djangocfg/ui-core/components';
8
+ import { useSessionStorage, useResolvedTheme } from '@djangocfg/ui-core/hooks';
9
+ import consola from 'consola';
10
+
11
+ var MermaidClient = lazy(() => import('./Mermaid.client-XFQ74OYN.mjs'));
12
+ var LoadingFallback = /* @__PURE__ */ __name(() => /* @__PURE__ */ jsx("div", { className: "flex justify-center items-center min-h-[100px]", children: /* @__PURE__ */ jsx("div", { className: "animate-spin rounded-full h-6 w-6 border-b-2 border-primary" }) }), "LoadingFallback");
13
+ var Mermaid = /* @__PURE__ */ __name((props) => {
14
+ return /* @__PURE__ */ jsx(Suspense, { fallback: /* @__PURE__ */ jsx(LoadingFallback, {}), children: /* @__PURE__ */ jsx(MermaidClient, { ...props }) });
15
+ }, "Mermaid");
16
+ var Mermaid_default = Mermaid;
17
+ var PrettyCodeClient = lazy(() => import('./PrettyCode.client-IZTXXYHG.mjs'));
18
+ var LoadingFallback2 = /* @__PURE__ */ __name(() => /* @__PURE__ */ jsx("div", { className: "relative rounded-sm border border-border overflow-hidden bg-muted dark:bg-zinc-900", children: /* @__PURE__ */ jsx("div", { className: "p-4", children: /* @__PURE__ */ jsxs("div", { className: "flex items-center gap-2", children: [
19
+ /* @__PURE__ */ jsx("div", { className: "animate-pulse h-4 w-4 rounded-full bg-muted-foreground/20" }),
20
+ /* @__PURE__ */ jsx("span", { className: "text-xs text-muted-foreground", children: "Loading code..." })
21
+ ] }) }) }), "LoadingFallback");
22
+ var PrettyCode = /* @__PURE__ */ __name((props) => {
23
+ return /* @__PURE__ */ jsx(Suspense, { fallback: /* @__PURE__ */ jsx(LoadingFallback2, {}), children: /* @__PURE__ */ jsx(PrettyCodeClient, { ...props }) });
24
+ }, "PrettyCode");
25
+ var PrettyCode_default = PrettyCode;
26
+ function smartTruncate(content, maxLength) {
27
+ if (content.length <= maxLength) {
28
+ return content;
29
+ }
30
+ let breakPoint = maxLength;
31
+ while (breakPoint > maxLength - 50 && breakPoint > 0) {
32
+ const char = content[breakPoint];
33
+ if (char === " " || char === "\n" || char === " ") {
34
+ break;
35
+ }
36
+ breakPoint--;
37
+ }
38
+ if (breakPoint <= maxLength - 50) {
39
+ breakPoint = maxLength;
40
+ }
41
+ let truncated = content.slice(0, breakPoint).trimEnd();
42
+ truncated = fixUnclosedMarkdown(truncated);
43
+ return truncated;
44
+ }
45
+ __name(smartTruncate, "smartTruncate");
46
+ function truncateByLines(content, maxLines) {
47
+ const lines = content.split("\n");
48
+ if (lines.length <= maxLines) {
49
+ return content;
50
+ }
51
+ let truncated = lines.slice(0, maxLines).join("\n").trimEnd();
52
+ truncated = fixUnclosedMarkdown(truncated);
53
+ return truncated;
54
+ }
55
+ __name(truncateByLines, "truncateByLines");
56
+ function fixUnclosedMarkdown(content) {
57
+ let result = content;
58
+ const countOccurrences = /* @__PURE__ */ __name((str, marker) => {
59
+ const escaped = marker.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
60
+ const matches = str.match(new RegExp(escaped, "g"));
61
+ return matches ? matches.length : 0;
62
+ }, "countOccurrences");
63
+ const boldCount = countOccurrences(result, "**");
64
+ if (boldCount % 2 !== 0) {
65
+ result += "**";
66
+ }
67
+ const withoutBold = result.replace(/\*\*/g, "");
68
+ const italicCount = countOccurrences(withoutBold, "*");
69
+ if (italicCount % 2 !== 0) {
70
+ result += "*";
71
+ }
72
+ const codeCount = countOccurrences(result, "`");
73
+ const tripleCount = countOccurrences(result, "```");
74
+ const singleCodeCount = codeCount - tripleCount * 3;
75
+ if (singleCodeCount % 2 !== 0) {
76
+ result += "`";
77
+ }
78
+ if (tripleCount % 2 !== 0) {
79
+ result += "\n```";
80
+ }
81
+ const strikeCount = countOccurrences(result, "~~");
82
+ if (strikeCount % 2 !== 0) {
83
+ result += "~~";
84
+ }
85
+ const underlineBoldCount = countOccurrences(result, "__");
86
+ if (underlineBoldCount % 2 !== 0) {
87
+ result += "__";
88
+ }
89
+ const withoutUnderlineBold = result.replace(/__/g, "");
90
+ const underlineItalicCount = countOccurrences(withoutUnderlineBold, "_");
91
+ if (underlineItalicCount % 2 !== 0) {
92
+ result += "_";
93
+ }
94
+ return result;
95
+ }
96
+ __name(fixUnclosedMarkdown, "fixUnclosedMarkdown");
97
+ function useCollapsibleContent(content, options = {}) {
98
+ const { maxLength, maxLines, defaultExpanded = false } = options;
99
+ const [isCollapsed, setIsCollapsed] = useState(!defaultExpanded);
100
+ const originalLength = content.length;
101
+ const originalLineCount = content.split("\n").length;
102
+ const { shouldCollapse, truncatedContent } = useMemo(() => {
103
+ if (maxLength === void 0 && maxLines === void 0) {
104
+ return { shouldCollapse: false, truncatedContent: content };
105
+ }
106
+ let needsCollapse = false;
107
+ let result = content;
108
+ if (maxLines !== void 0 && originalLineCount > maxLines) {
109
+ needsCollapse = true;
110
+ result = truncateByLines(result, maxLines);
111
+ }
112
+ if (maxLength !== void 0 && result.length > maxLength) {
113
+ needsCollapse = true;
114
+ result = smartTruncate(result, maxLength);
115
+ }
116
+ return { shouldCollapse: needsCollapse, truncatedContent: result };
117
+ }, [content, maxLength, maxLines, originalLineCount]);
118
+ const displayContent = useMemo(() => {
119
+ if (!shouldCollapse || !isCollapsed) {
120
+ return content;
121
+ }
122
+ return truncatedContent;
123
+ }, [content, truncatedContent, shouldCollapse, isCollapsed]);
124
+ const toggleCollapsed = useCallback(() => {
125
+ setIsCollapsed((prev) => !prev);
126
+ }, []);
127
+ const setCollapsed = useCallback((collapsed) => {
128
+ setIsCollapsed(collapsed);
129
+ }, []);
130
+ return {
131
+ isCollapsed,
132
+ toggleCollapsed,
133
+ setCollapsed,
134
+ displayContent,
135
+ shouldCollapse,
136
+ originalLength,
137
+ originalLineCount
138
+ };
139
+ }
140
+ __name(useCollapsibleContent, "useCollapsibleContent");
141
+ var extractTextFromChildren = /* @__PURE__ */ __name((children) => {
142
+ if (typeof children === "string") {
143
+ return children;
144
+ }
145
+ if (typeof children === "number") {
146
+ return String(children);
147
+ }
148
+ if (React3.isValidElement(children)) {
149
+ const props = children.props;
150
+ return extractTextFromChildren(props.children);
151
+ }
152
+ if (Array.isArray(children)) {
153
+ return children.map(extractTextFromChildren).join("");
154
+ }
155
+ return "";
156
+ }, "extractTextFromChildren");
157
+ var CodeBlock = /* @__PURE__ */ __name(({ code, language, isUser, isCompact = false }) => {
158
+ const theme = useResolvedTheme();
159
+ return /* @__PURE__ */ jsxs("div", { className: "relative group my-3", children: [
160
+ /* @__PURE__ */ jsx(
161
+ CopyButton,
162
+ {
163
+ value: code,
164
+ variant: "ghost",
165
+ className: `
166
+ absolute top-2 right-2 z-10 opacity-0 group-hover:opacity-100 transition-opacity
167
+ h-8 w-8
168
+ ${isUser ? "hover:bg-white/20 text-white" : "hover:bg-muted-foreground/20 text-muted-foreground hover:text-foreground"}
169
+ `,
170
+ title: "Copy code"
171
+ }
172
+ ),
173
+ /* @__PURE__ */ jsx(
174
+ PrettyCode_default,
175
+ {
176
+ data: code,
177
+ language,
178
+ className: isCompact ? "text-xs" : "text-sm",
179
+ customBg: isUser ? "bg-white/10" : "bg-muted dark:bg-muted",
180
+ mode: theme,
181
+ isCompact
182
+ }
183
+ )
184
+ ] });
185
+ }, "CodeBlock");
186
+ var createMarkdownComponents = /* @__PURE__ */ __name((isUser = false, isCompact = false) => {
187
+ const textSize = isCompact ? "text-xs" : "text-sm";
188
+ const headingBase = isCompact ? "text-sm" : "text-base";
189
+ const headingSm = isCompact ? "text-xs" : "text-sm";
190
+ return {
191
+ // Headings - scaled for chat context
192
+ h1: /* @__PURE__ */ __name(({ children }) => /* @__PURE__ */ jsx("h1", { className: `${headingBase} font-bold mb-2 mt-3 first:mt-0`, children }), "h1"),
193
+ h2: /* @__PURE__ */ __name(({ children }) => /* @__PURE__ */ jsx("h2", { className: `${headingSm} font-bold mb-2 mt-3 first:mt-0`, children }), "h2"),
194
+ h3: /* @__PURE__ */ __name(({ children }) => /* @__PURE__ */ jsx("h3", { className: `${headingSm} font-semibold mb-1 mt-2 first:mt-0`, children }), "h3"),
195
+ h4: /* @__PURE__ */ __name(({ children }) => /* @__PURE__ */ jsx("h4", { className: `${headingSm} font-semibold mb-1 mt-2 first:mt-0`, children }), "h4"),
196
+ h5: /* @__PURE__ */ __name(({ children }) => /* @__PURE__ */ jsx("h5", { className: `${headingSm} font-medium mb-1 mt-2 first:mt-0`, children }), "h5"),
197
+ h6: /* @__PURE__ */ __name(({ children }) => /* @__PURE__ */ jsx("h6", { className: `${headingSm} font-medium mb-1 mt-2 first:mt-0`, children }), "h6"),
198
+ // Paragraphs - optimized for chat readability
199
+ p: /* @__PURE__ */ __name(({ children }) => /* @__PURE__ */ jsx("p", { className: `${textSize} mb-4 last:mb-0 leading-7 break-words font-light`, children }), "p"),
200
+ // Lists - compact
201
+ ul: /* @__PURE__ */ __name(({ children }) => /* @__PURE__ */ jsx("ul", { className: `list-disc list-inside mb-2 space-y-1 ${textSize}`, children }), "ul"),
202
+ ol: /* @__PURE__ */ __name(({ children }) => /* @__PURE__ */ jsx("ol", { className: `list-decimal list-inside mb-2 space-y-1 ${textSize}`, children }), "ol"),
203
+ li: /* @__PURE__ */ __name(({ children }) => /* @__PURE__ */ jsx("li", { className: "break-words", children }), "li"),
204
+ // Links - appropriate for chat context
205
+ a: /* @__PURE__ */ __name(({ href, children }) => /* @__PURE__ */ jsx(
206
+ "a",
207
+ {
208
+ href,
209
+ className: `${textSize} ${isUser ? "text-white/90 underline hover:text-white" : "text-primary underline hover:text-primary/80"} transition-colors break-all`,
210
+ target: href?.startsWith("http") ? "_blank" : void 0,
211
+ rel: href?.startsWith("http") ? "noopener noreferrer" : void 0,
212
+ children
213
+ }
214
+ ), "a"),
215
+ // Code blocks - using CodeBlock component with copy functionality
216
+ pre: /* @__PURE__ */ __name(({ children }) => {
217
+ let codeContent = "";
218
+ let language = "plaintext";
219
+ if (React3.isValidElement(children)) {
220
+ const child = children;
221
+ if (child.type === "code" || typeof child.type === "function" && child.type.name === "code") {
222
+ const codeProps = child.props;
223
+ const rawClassName = codeProps.className;
224
+ language = rawClassName?.replace(/language-/, "").trim() || "plaintext";
225
+ codeContent = extractTextFromChildren(codeProps.children).trim();
226
+ } else {
227
+ codeContent = extractTextFromChildren(children).trim();
228
+ }
229
+ } else {
230
+ codeContent = extractTextFromChildren(children).trim();
231
+ }
232
+ if (!codeContent) {
233
+ return /* @__PURE__ */ jsx("div", { className: "my-3 p-3 bg-muted rounded text-sm text-muted-foreground", children: "No content available" });
234
+ }
235
+ if (language === "mermaid") {
236
+ return /* @__PURE__ */ jsx("div", { className: "my-3 max-w-full overflow-x-auto", children: /* @__PURE__ */ jsx(Mermaid_default, { chart: codeContent, className: "max-w-[600px] mx-auto", isCompact }) });
237
+ }
238
+ try {
239
+ return /* @__PURE__ */ jsx(CodeBlock, { code: codeContent, language, isUser, isCompact });
240
+ } catch (error) {
241
+ console.warn("CodeBlock failed, using fallback:", error);
242
+ return /* @__PURE__ */ jsxs("div", { className: "relative group my-3", children: [
243
+ /* @__PURE__ */ jsx(
244
+ CopyButton,
245
+ {
246
+ value: codeContent,
247
+ variant: "ghost",
248
+ className: `
249
+ absolute top-2 right-2 z-10 opacity-0 group-hover:opacity-100 transition-opacity
250
+ h-8 w-8
251
+ ${isUser ? "hover:bg-white/20 text-white" : "hover:bg-muted-foreground/20 text-muted-foreground hover:text-foreground"}
252
+ `,
253
+ title: "Copy code"
254
+ }
255
+ ),
256
+ /* @__PURE__ */ jsx("pre", { className: `
257
+ p-3 rounded text-xs font-mono overflow-x-auto
258
+ ${isUser ? "bg-white/10 text-white" : "bg-muted text-foreground"}
259
+ `, children: /* @__PURE__ */ jsx("code", { children: codeContent }) })
260
+ ] });
261
+ }
262
+ }, "pre"),
263
+ // Inline code
264
+ code: /* @__PURE__ */ __name(({ children, className }) => {
265
+ if (className?.includes("language-")) {
266
+ return /* @__PURE__ */ jsx("code", { className, children });
267
+ }
268
+ const codeContent = extractTextFromChildren(children);
269
+ return /* @__PURE__ */ jsx("code", { className: "px-1.5 py-0.5 rounded text-xs font-mono bg-muted text-foreground break-all", children: codeContent });
270
+ }, "code"),
271
+ // Blockquotes
272
+ blockquote: /* @__PURE__ */ __name(({ children }) => /* @__PURE__ */ jsx("blockquote", { className: `${textSize} border-l-2 border-border pl-3 my-2 italic text-muted-foreground break-words`, children }), "blockquote"),
273
+ // Tables - compact for chat
274
+ table: /* @__PURE__ */ __name(({ children }) => /* @__PURE__ */ jsx("div", { className: "overflow-x-auto my-3", children: /* @__PURE__ */ jsx("table", { className: `min-w-full ${textSize} border-collapse`, children }) }), "table"),
275
+ thead: /* @__PURE__ */ __name(({ children }) => /* @__PURE__ */ jsx("thead", { className: "bg-muted/50", children }), "thead"),
276
+ tbody: /* @__PURE__ */ __name(({ children }) => /* @__PURE__ */ jsx("tbody", { children }), "tbody"),
277
+ tr: /* @__PURE__ */ __name(({ children }) => /* @__PURE__ */ jsx("tr", { className: "border-b border-border/50", children }), "tr"),
278
+ th: /* @__PURE__ */ __name(({ children }) => /* @__PURE__ */ jsx("th", { className: "px-2 py-1 text-left font-medium break-words", children }), "th"),
279
+ td: /* @__PURE__ */ __name(({ children }) => /* @__PURE__ */ jsx("td", { className: "px-2 py-1 break-words", children }), "td"),
280
+ // Horizontal rule
281
+ hr: /* @__PURE__ */ __name(() => /* @__PURE__ */ jsx("hr", { className: "my-3 border-0 h-px bg-border" }), "hr"),
282
+ // Strong and emphasis
283
+ strong: /* @__PURE__ */ __name(({ children }) => /* @__PURE__ */ jsx("strong", { className: "font-semibold", children }), "strong"),
284
+ em: /* @__PURE__ */ __name(({ children }) => /* @__PURE__ */ jsx("em", { className: "italic", children }), "em")
285
+ };
286
+ }, "createMarkdownComponents");
287
+ var hasMarkdownSyntax = /* @__PURE__ */ __name((text) => {
288
+ if (text.trim().includes("\n")) {
289
+ return true;
290
+ }
291
+ const markdownPatterns = [
292
+ /^#{1,6}\s/m,
293
+ // Headers
294
+ /\*\*[^*]+\*\*/,
295
+ // Bold
296
+ /\*[^*]+\*/,
297
+ // Italic
298
+ /__[^_]+__/,
299
+ // Bold (underscore)
300
+ /_[^_]+_/,
301
+ // Italic (underscore)
302
+ /\[.+\]\(.+\)/,
303
+ // Links
304
+ /!\[.*\]\(.+\)/,
305
+ // Images
306
+ /```[\s\S]*```/,
307
+ // Code blocks
308
+ /`[^`]+`/,
309
+ // Inline code
310
+ /^\s*[-*+]\s/m,
311
+ // Unordered lists
312
+ /^\s*\d+\.\s/m,
313
+ // Ordered lists
314
+ /^\s*>/m,
315
+ // Blockquotes
316
+ /\|.+\|/,
317
+ // Tables
318
+ /^---+$/m,
319
+ // Horizontal rules
320
+ /~~[^~]+~~/
321
+ // Strikethrough
322
+ ];
323
+ return markdownPatterns.some((pattern) => pattern.test(text));
324
+ }, "hasMarkdownSyntax");
325
+ var CollapseToggle = /* @__PURE__ */ __name(({
326
+ isCollapsed,
327
+ onClick,
328
+ readMoreLabel,
329
+ showLessLabel,
330
+ isUser,
331
+ isCompact
332
+ }) => {
333
+ const textSize = isCompact ? "text-xs" : "text-sm";
334
+ return /* @__PURE__ */ jsx(
335
+ "button",
336
+ {
337
+ type: "button",
338
+ onClick,
339
+ className: `
340
+ ${textSize} font-medium cursor-pointer
341
+ transition-colors duration-200
342
+ ${isUser ? "text-white/80 hover:text-white" : "text-primary hover:text-primary/80"}
343
+ inline-flex items-center gap-1
344
+ mt-1
345
+ `,
346
+ children: isCollapsed ? /* @__PURE__ */ jsxs(Fragment, { children: [
347
+ readMoreLabel,
348
+ /* @__PURE__ */ jsx(
349
+ "svg",
350
+ {
351
+ className: "w-3 h-3",
352
+ fill: "none",
353
+ stroke: "currentColor",
354
+ viewBox: "0 0 24 24",
355
+ children: /* @__PURE__ */ jsx(
356
+ "path",
357
+ {
358
+ strokeLinecap: "round",
359
+ strokeLinejoin: "round",
360
+ strokeWidth: 2,
361
+ d: "M19 9l-7 7-7-7"
362
+ }
363
+ )
364
+ }
365
+ )
366
+ ] }) : /* @__PURE__ */ jsxs(Fragment, { children: [
367
+ showLessLabel,
368
+ /* @__PURE__ */ jsx(
369
+ "svg",
370
+ {
371
+ className: "w-3 h-3",
372
+ fill: "none",
373
+ stroke: "currentColor",
374
+ viewBox: "0 0 24 24",
375
+ children: /* @__PURE__ */ jsx(
376
+ "path",
377
+ {
378
+ strokeLinecap: "round",
379
+ strokeLinejoin: "round",
380
+ strokeWidth: 2,
381
+ d: "M5 15l7-7 7 7"
382
+ }
383
+ )
384
+ }
385
+ )
386
+ ] })
387
+ }
388
+ );
389
+ }, "CollapseToggle");
390
+ var MarkdownMessage = /* @__PURE__ */ __name(({
391
+ content,
392
+ className = "",
393
+ isUser = false,
394
+ isCompact = false,
395
+ collapsible = false,
396
+ maxLength,
397
+ maxLines,
398
+ readMoreLabel = "Read more...",
399
+ showLessLabel = "Show less",
400
+ defaultExpanded = false,
401
+ onCollapseChange
402
+ }) => {
403
+ const trimmedContent = content.trim();
404
+ const collapsibleOptions = React3.useMemo(() => {
405
+ if (!collapsible) return {};
406
+ const effectiveMaxLength = maxLength ?? 1e3;
407
+ const effectiveMaxLines = maxLines ?? 10;
408
+ return { maxLength: effectiveMaxLength, maxLines: effectiveMaxLines, defaultExpanded };
409
+ }, [collapsible, maxLength, maxLines, defaultExpanded]);
410
+ const {
411
+ isCollapsed,
412
+ toggleCollapsed,
413
+ displayContent,
414
+ shouldCollapse
415
+ } = useCollapsibleContent(
416
+ trimmedContent,
417
+ collapsible ? collapsibleOptions : {}
418
+ );
419
+ React3.useEffect(() => {
420
+ if (collapsible && shouldCollapse && onCollapseChange) {
421
+ onCollapseChange(isCollapsed);
422
+ }
423
+ }, [isCollapsed, collapsible, shouldCollapse, onCollapseChange]);
424
+ const components = React3.useMemo(() => createMarkdownComponents(isUser, isCompact), [isUser, isCompact]);
425
+ const textSizeClass = isCompact ? "text-xs" : "text-sm";
426
+ const proseClass = isCompact ? "prose-xs" : "prose-sm";
427
+ const isPlainText = !hasMarkdownSyntax(displayContent);
428
+ if (isPlainText) {
429
+ return /* @__PURE__ */ jsxs("span", { className: `${textSizeClass} leading-7 break-words whitespace-pre-line font-light ${className}`, children: [
430
+ displayContent,
431
+ collapsible && shouldCollapse && /* @__PURE__ */ jsxs(Fragment, { children: [
432
+ isCollapsed && "... ",
433
+ /* @__PURE__ */ jsx(
434
+ CollapseToggle,
435
+ {
436
+ isCollapsed,
437
+ onClick: toggleCollapsed,
438
+ readMoreLabel,
439
+ showLessLabel,
440
+ isUser,
441
+ isCompact
442
+ }
443
+ )
444
+ ] })
445
+ ] });
446
+ }
447
+ return /* @__PURE__ */ jsxs("div", { className, children: [
448
+ /* @__PURE__ */ jsx(
449
+ "div",
450
+ {
451
+ className: `
452
+ prose ${proseClass} max-w-none break-words overflow-hidden ${textSizeClass}
453
+ ${isUser ? "prose-invert" : "dark:prose-invert"}
454
+ [&>*]:leading-7
455
+ `,
456
+ style: {
457
+ // Inherit colors from parent - fixes issues with external CSS variables
458
+ "--tw-prose-body": "inherit",
459
+ "--tw-prose-headings": "inherit",
460
+ "--tw-prose-bold": "inherit",
461
+ "--tw-prose-links": "inherit",
462
+ color: "inherit"
463
+ },
464
+ children: /* @__PURE__ */ jsx(
465
+ ReactMarkdown,
466
+ {
467
+ remarkPlugins: [remarkGfm],
468
+ components,
469
+ children: displayContent
470
+ }
471
+ )
472
+ }
473
+ ),
474
+ collapsible && shouldCollapse && /* @__PURE__ */ jsx(
475
+ CollapseToggle,
476
+ {
477
+ isCollapsed,
478
+ onClick: toggleCollapsed,
479
+ readMoreLabel,
480
+ showLessLabel,
481
+ isUser,
482
+ isCompact
483
+ }
484
+ )
485
+ ] });
486
+ }, "MarkdownMessage");
487
+
488
+ // src/tools/OpenapiViewer/utils/apiKeyManager.ts
489
+ function findApiKeyById(apiKeys, keyId) {
490
+ return apiKeys.find((key) => key.id === keyId) || null;
491
+ }
492
+ __name(findApiKeyById, "findApiKeyById");
493
+
494
+ // src/tools/OpenapiViewer/utils/versionManager.ts
495
+ var API_VERSIONS = [
496
+ {
497
+ id: "v1",
498
+ name: "v1",
499
+ description: "Current stable version",
500
+ isDefault: true
501
+ }
502
+ ];
503
+ var detectEndpointVersion = /* @__PURE__ */ __name((path) => {
504
+ const versionMatch = path.match(/\/api\/[^/]+\/(v\d+)\//);
505
+ if (versionMatch && versionMatch[1]) {
506
+ return versionMatch[1];
507
+ }
508
+ return "v1";
509
+ }, "detectEndpointVersion");
510
+ var isEndpointInVersion = /* @__PURE__ */ __name((endpoint, version) => {
511
+ const endpointVersion = detectEndpointVersion(endpoint.path);
512
+ return endpointVersion === version;
513
+ }, "isEndpointInVersion");
514
+ var deduplicateEndpoints = /* @__PURE__ */ __name((endpoints, preferredVersion) => {
515
+ const endpointMap = /* @__PURE__ */ new Map();
516
+ const groupedEndpoints = /* @__PURE__ */ new Map();
517
+ endpoints.forEach((endpoint) => {
518
+ const normalizedPath = normalizeEndpointPath(endpoint.path);
519
+ if (!groupedEndpoints.has(normalizedPath)) {
520
+ groupedEndpoints.set(normalizedPath, []);
521
+ }
522
+ groupedEndpoints.get(normalizedPath).push(endpoint);
523
+ });
524
+ groupedEndpoints.forEach((endpointGroup, normalizedPath) => {
525
+ let selectedEndpoint = null;
526
+ const versionEndpoint = endpointGroup.find((ep) => isEndpointInVersion(ep, preferredVersion));
527
+ if (versionEndpoint) {
528
+ selectedEndpoint = versionEndpoint;
529
+ } else if (endpointGroup.length > 0) {
530
+ selectedEndpoint = endpointGroup[0] || null;
531
+ }
532
+ if (selectedEndpoint) {
533
+ endpointMap.set(normalizedPath, selectedEndpoint);
534
+ }
535
+ });
536
+ return Array.from(endpointMap.values());
537
+ }, "deduplicateEndpoints");
538
+ var normalizeEndpointPath = /* @__PURE__ */ __name((path) => {
539
+ return path.replace(/\/v\d+\//, "/");
540
+ }, "normalizeEndpointPath");
541
+ var getDefaultVersion = /* @__PURE__ */ __name(() => {
542
+ const defaultVersion = API_VERSIONS.find((v) => v.isDefault);
543
+ if (defaultVersion) {
544
+ return defaultVersion;
545
+ }
546
+ if (API_VERSIONS.length > 0 && API_VERSIONS[0]) {
547
+ return API_VERSIONS[0];
548
+ }
549
+ throw new Error("No API versions defined");
550
+ }, "getDefaultVersion");
551
+
552
+ // src/tools/OpenapiViewer/utils/formatters.ts
553
+ var isValidJson = /* @__PURE__ */ __name((str) => {
554
+ if (!str || typeof str !== "string") return false;
555
+ try {
556
+ JSON.parse(str);
557
+ return true;
558
+ } catch {
559
+ return false;
560
+ }
561
+ }, "isValidJson");
562
+ var parseRequestHeaders = /* @__PURE__ */ __name((headersString) => {
563
+ if (!headersString || typeof headersString !== "string") {
564
+ return { "Content-Type": "application/json" };
565
+ }
566
+ try {
567
+ const parsed = JSON.parse(headersString);
568
+ return typeof parsed === "object" && parsed !== null ? parsed : { "Content-Type": "application/json" };
569
+ } catch {
570
+ return { "Content-Type": "application/json" };
571
+ }
572
+ }, "parseRequestHeaders");
573
+
574
+ // src/tools/OpenapiViewer/utils/url.ts
575
+ var PATH_PARAM_RE = /\{([^{}]+)\}/g;
576
+ function extractPathPlaceholders(template) {
577
+ const seen = /* @__PURE__ */ new Set();
578
+ const out = [];
579
+ for (const match of template.matchAll(PATH_PARAM_RE)) {
580
+ const name = match[1];
581
+ if (!seen.has(name)) {
582
+ seen.add(name);
583
+ out.push(name);
584
+ }
585
+ }
586
+ return out;
587
+ }
588
+ __name(extractPathPlaceholders, "extractPathPlaceholders");
589
+ function substitutePath(template, values) {
590
+ return template.replace(PATH_PARAM_RE, (whole, name) => {
591
+ const v = values[name];
592
+ return v && v.trim() !== "" ? encodeURIComponent(v) : whole;
593
+ });
594
+ }
595
+ __name(substitutePath, "substitutePath");
596
+ function unfilledPlaceholders(template, values) {
597
+ return extractPathPlaceholders(template).filter(
598
+ (name) => !(values[name] ?? "").trim()
599
+ );
600
+ }
601
+ __name(unfilledPlaceholders, "unfilledPlaceholders");
602
+ function appendQuery(url, values, pathTemplate) {
603
+ const pathNames = new Set(extractPathPlaceholders(pathTemplate));
604
+ const queryEntries = Object.entries(values).filter(
605
+ ([name, value]) => !pathNames.has(name) && value && value.trim() !== ""
606
+ );
607
+ if (queryEntries.length === 0) return url;
608
+ const [base, existingQuery = ""] = url.split("?", 2);
609
+ const params = new URLSearchParams(existingQuery);
610
+ for (const [k, v] of queryEntries) params.set(k, v);
611
+ const qs = params.toString();
612
+ return qs ? `${base}?${qs}` : base ?? url;
613
+ }
614
+ __name(appendQuery, "appendQuery");
615
+ function resolveAbsolute(url) {
616
+ if (!url) return url;
617
+ if (/^https?:\/\//i.test(url)) return url;
618
+ if (typeof window === "undefined") return url;
619
+ if (url.startsWith("//")) return `${window.location.protocol}${url}`;
620
+ if (url.startsWith("/")) return `${window.location.origin}${url}`;
621
+ return url;
622
+ }
623
+ __name(resolveAbsolute, "resolveAbsolute");
624
+ function relativePath(url) {
625
+ try {
626
+ return new URL(url).pathname;
627
+ } catch {
628
+ return url;
629
+ }
630
+ }
631
+ __name(relativePath, "relativePath");
632
+ function joinUrl(...parts) {
633
+ return parts.filter((p) => p !== void 0 && p !== null && p !== "").map((p, i) => {
634
+ if (i === 0) return String(p).replace(/\/+$/, "");
635
+ return String(p).replace(/^\/+|\/+$/g, "");
636
+ }).filter((p) => p !== "").join("/");
637
+ }
638
+ __name(joinUrl, "joinUrl");
639
+ function resolveBaseUrl(sources) {
640
+ return sources.schemaSource || sources.config || sources.fromServers || "";
641
+ }
642
+ __name(resolveBaseUrl, "resolveBaseUrl");
643
+ var _UrlBuilder = class _UrlBuilder {
644
+ constructor(endpoint, parameters) {
645
+ this.endpoint = endpoint;
646
+ this.parameters = parameters;
647
+ }
648
+ /** What ``fetch()`` receives: substituted path + query string. Origin
649
+ * is whatever the endpoint template already had (relative paths
650
+ * stay relative so the browser resolves them against the page). */
651
+ build() {
652
+ const substituted = substitutePath(this.endpoint.path, this.parameters);
653
+ return appendQuery(substituted, this.parameters, this.endpoint.path);
654
+ }
655
+ /** Same as ``build()`` but guaranteed absolute — for curl snippets
656
+ * and anywhere the URL leaves the browser context. */
657
+ buildAbsolute() {
658
+ return resolveAbsolute(this.build());
659
+ }
660
+ /** Names of required path/query params still empty. */
661
+ missingRequired() {
662
+ if (!this.endpoint.parameters) return [];
663
+ return this.endpoint.parameters.filter((p) => p.required && !(this.parameters[p.name] ?? "").trim()).map((p) => p.name);
664
+ }
665
+ /** Placeholders in the template with no matching value. Usually a
666
+ * superset of ``missingRequired`` — catches schemas that forgot
667
+ * to flag a path param as required. */
668
+ unfilledPlaceholders() {
669
+ return unfilledPlaceholders(this.endpoint.path, this.parameters);
670
+ }
671
+ };
672
+ __name(_UrlBuilder, "UrlBuilder");
673
+ var UrlBuilder = _UrlBuilder;
674
+
675
+ // src/tools/OpenapiViewer/utils/schemaExport.ts
676
+ function dereferenceSchema(schema, maxDepth = 10) {
677
+ const root = schema;
678
+ function resolveRef(ref) {
679
+ if (!ref.startsWith("#/")) return null;
680
+ const parts = ref.slice(2).split("/");
681
+ let node = root;
682
+ for (const part of parts) {
683
+ if (node && typeof node === "object" && part in node) {
684
+ node = node[part];
685
+ } else {
686
+ return null;
687
+ }
688
+ }
689
+ return node;
690
+ }
691
+ __name(resolveRef, "resolveRef");
692
+ function walk(value, depth) {
693
+ if (depth > maxDepth) return value;
694
+ if (Array.isArray(value)) return value.map((v) => walk(v, depth + 1));
695
+ if (value && typeof value === "object") {
696
+ const obj = value;
697
+ if (typeof obj.$ref === "string") {
698
+ const resolved = resolveRef(obj.$ref);
699
+ if (resolved === null) return obj;
700
+ return walk(resolved, depth + 1);
701
+ }
702
+ const out = {};
703
+ for (const [k, v] of Object.entries(obj)) out[k] = walk(v, depth + 1);
704
+ return out;
705
+ }
706
+ return value;
707
+ }
708
+ __name(walk, "walk");
709
+ return walk(schema, 0);
710
+ }
711
+ __name(dereferenceSchema, "dereferenceSchema");
712
+ var NOISY_KEYS = /* @__PURE__ */ new Set(["xml", "example", "examples", "externalDocs"]);
713
+ var MAX_DESCRIPTION_LEN = 500;
714
+ function pruneForCompact(value) {
715
+ if (Array.isArray(value)) return value.map(pruneForCompact);
716
+ if (value && typeof value === "object") {
717
+ const out = {};
718
+ for (const [k, v] of Object.entries(value)) {
719
+ if (NOISY_KEYS.has(k)) continue;
720
+ if (k === "description" && typeof v === "string" && v.length > MAX_DESCRIPTION_LEN) {
721
+ out[k] = v.slice(0, MAX_DESCRIPTION_LEN).trimEnd() + "\u2026";
722
+ continue;
723
+ }
724
+ out[k] = pruneForCompact(v);
725
+ }
726
+ return out;
727
+ }
728
+ return value;
729
+ }
730
+ __name(pruneForCompact, "pruneForCompact");
731
+ function withResolvedBaseUrl(schema, baseUrl) {
732
+ if (!baseUrl) return schema;
733
+ return { ...schema, servers: [{ url: baseUrl }] };
734
+ }
735
+ __name(withResolvedBaseUrl, "withResolvedBaseUrl");
736
+ function toRawJson(schema, baseUrl) {
737
+ return JSON.stringify(withResolvedBaseUrl(schema, baseUrl), null, 2);
738
+ }
739
+ __name(toRawJson, "toRawJson");
740
+ function toCompactJson(schema, baseUrl) {
741
+ const resolved = dereferenceSchema(withResolvedBaseUrl(schema, baseUrl));
742
+ const pruned = pruneForCompact(resolved);
743
+ return JSON.stringify(pruned);
744
+ }
745
+ __name(toCompactJson, "toCompactJson");
746
+ function endpointToMarkdown(ep) {
747
+ const lines = [];
748
+ lines.push(`### ${ep.method} ${ep.path}`);
749
+ if (ep.description) lines.push(ep.description);
750
+ const pathParams = ep.parameters?.filter((p) => ep.path.includes(`{${p.name}}`)) ?? [];
751
+ const queryParams = ep.parameters?.filter((p) => !ep.path.includes(`{${p.name}}`)) ?? [];
752
+ if (pathParams.length > 0) {
753
+ lines.push("", "**Path parameters**");
754
+ for (const p of pathParams) {
755
+ const req = p.required ? " (required)" : "";
756
+ const desc = p.description ? ` \u2014 ${p.description}` : "";
757
+ lines.push(`- \`${p.name}\`: ${p.type}${req}${desc}`);
758
+ }
759
+ }
760
+ if (queryParams.length > 0) {
761
+ lines.push("", "**Query parameters**");
762
+ for (const p of queryParams) {
763
+ const req = p.required ? " (required)" : "";
764
+ const desc = p.description ? ` \u2014 ${p.description}` : "";
765
+ lines.push(`- \`${p.name}\`: ${p.type}${req}${desc}`);
766
+ }
767
+ }
768
+ if (ep.requestBody) {
769
+ const desc = ep.requestBody.description ? ` \u2014 ${ep.requestBody.description}` : "";
770
+ lines.push("", `**Request body:** ${ep.requestBody.type}${desc}`);
771
+ }
772
+ if (ep.responses && ep.responses.length > 0) {
773
+ lines.push("", "**Responses**");
774
+ for (const r of ep.responses) {
775
+ lines.push(`- \`${r.code}\` \u2014 ${r.description}`);
776
+ }
777
+ }
778
+ return lines.join("\n");
779
+ }
780
+ __name(endpointToMarkdown, "endpointToMarkdown");
781
+ function toMarkdown(schema, endpoints, baseUrl) {
782
+ const lines = [];
783
+ const info = schema.info;
784
+ const resolvedBase = resolveBaseUrl({
785
+ config: baseUrl,
786
+ fromServers: schema.servers?.[0]?.url
787
+ });
788
+ lines.push(`# ${info?.title ?? "API"}${info?.version ? ` (v${info.version})` : ""}`);
789
+ if (resolvedBase) lines.push("", `**Base URL:** \`${resolvedBase}\``);
790
+ if (info?.description) lines.push("", info.description.trim());
791
+ const grouped = /* @__PURE__ */ new Map();
792
+ for (const ep of endpoints) {
793
+ const arr = grouped.get(ep.category) ?? [];
794
+ arr.push(ep);
795
+ grouped.set(ep.category, arr);
796
+ }
797
+ const categories = Array.from(grouped.keys()).sort((a, b) => {
798
+ if (a === "Other") return 1;
799
+ if (b === "Other") return -1;
800
+ return a.localeCompare(b);
801
+ });
802
+ for (const category of categories) {
803
+ lines.push("", `## ${category}`);
804
+ const list = grouped.get(category);
805
+ for (const ep of list) {
806
+ const displayPath = relativePath(ep.path);
807
+ const sub = endpointToMarkdown({ ...ep, path: displayPath });
808
+ lines.push("", sub);
809
+ }
810
+ }
811
+ return lines.join("\n");
812
+ }
813
+ __name(toMarkdown, "toMarkdown");
814
+ function formatBytes(s) {
815
+ const bytes = new Blob([s]).size;
816
+ if (bytes < 1024) return `${bytes} B`;
817
+ if (bytes < 1024 * 1024) return `${(bytes / 1024).toFixed(1)} KB`;
818
+ return `${(bytes / 1024 / 1024).toFixed(2)} MB`;
819
+ }
820
+ __name(formatBytes, "formatBytes");
821
+ var AUTH_KEY_STORAGE = "openapi-playground:auth:apiKeyId";
822
+ var AUTH_BEARER_STORAGE = "openapi-playground:auth:bearer";
823
+ var createInitialState = /* @__PURE__ */ __name(() => ({
824
+ currentStep: "endpoints",
825
+ steps: ["endpoints", "request", "response"],
826
+ selectedEndpoint: null,
827
+ selectedCategory: "All",
828
+ searchTerm: "",
829
+ selectedVersion: getDefaultVersion().id,
830
+ requestUrl: "",
831
+ requestMethod: "GET",
832
+ requestHeaders: '{\n "Content-Type": "application/json"\n}',
833
+ requestBody: "",
834
+ selectedApiKey: null,
835
+ manualApiToken: "",
836
+ parameters: {},
837
+ response: null,
838
+ loading: false,
839
+ sidebarOpen: false,
840
+ activeSchemaId: null
841
+ }), "createInitialState");
842
+ function reducer(state, action) {
843
+ switch (action.type) {
844
+ case "SET_STEP":
845
+ return { ...state, currentStep: action.step };
846
+ case "NEXT_STEP": {
847
+ const i = state.steps.indexOf(state.currentStep);
848
+ return i < state.steps.length - 1 ? { ...state, currentStep: state.steps[i + 1] } : state;
849
+ }
850
+ case "PREV_STEP": {
851
+ const i = state.steps.indexOf(state.currentStep);
852
+ return i > 0 ? { ...state, currentStep: state.steps[i - 1] } : state;
853
+ }
854
+ case "SELECT_ENDPOINT": {
855
+ if (!action.endpoint) return { ...state, selectedEndpoint: null };
856
+ const same = state.selectedEndpoint?.method === action.endpoint.method && state.selectedEndpoint?.path === action.endpoint.path;
857
+ const exampleBody = action.endpoint.requestBody?.example ?? "";
858
+ return {
859
+ ...state,
860
+ selectedEndpoint: action.endpoint,
861
+ requestMethod: action.endpoint.method,
862
+ requestUrl: action.endpoint.path,
863
+ parameters: same ? state.parameters : {},
864
+ requestBody: same ? state.requestBody : exampleBody,
865
+ // Switching to a different endpoint: the previous response no
866
+ // longer belongs here. Clear it so the playground panel collapses
867
+ // back to single-column until the user sends a new request.
868
+ response: same ? state.response : null,
869
+ currentStep: "request"
870
+ };
871
+ }
872
+ case "SET_CATEGORY":
873
+ return { ...state, selectedCategory: action.category };
874
+ case "SET_SEARCH":
875
+ return { ...state, searchTerm: action.term };
876
+ case "SET_VERSION":
877
+ return { ...state, selectedVersion: action.version };
878
+ case "SET_REQUEST_URL":
879
+ return { ...state, requestUrl: action.url };
880
+ case "SET_REQUEST_METHOD":
881
+ return { ...state, requestMethod: action.method };
882
+ case "SET_REQUEST_HEADERS":
883
+ return { ...state, requestHeaders: action.headers };
884
+ case "SET_REQUEST_BODY":
885
+ return { ...state, requestBody: action.body };
886
+ case "SET_API_KEY":
887
+ return { ...state, selectedApiKey: action.apiKeyId };
888
+ case "SET_MANUAL_TOKEN":
889
+ return { ...state, manualApiToken: action.token };
890
+ case "SET_PARAMETERS":
891
+ return { ...state, parameters: action.parameters };
892
+ case "SET_RESPONSE":
893
+ return { ...state, response: action.response };
894
+ case "SET_LOADING":
895
+ return { ...state, loading: action.loading };
896
+ case "REQUEST_START":
897
+ return { ...state, loading: true, response: null };
898
+ case "REQUEST_SUCCESS":
899
+ return { ...state, loading: false, response: action.response, currentStep: "response" };
900
+ case "REQUEST_ERROR":
901
+ return { ...state, loading: false, response: action.response };
902
+ case "SET_SIDEBAR":
903
+ return { ...state, sidebarOpen: action.open };
904
+ case "SET_ACTIVE_SCHEMA_ID":
905
+ return { ...state, activeSchemaId: action.id };
906
+ case "SYNC_API_KEY_HEADER":
907
+ return { ...state, requestHeaders: action.headers };
908
+ case "CLEAR_API_KEY_SELECTION":
909
+ return { ...state, selectedApiKey: null };
910
+ case "SYNC_URL":
911
+ return { ...state, requestUrl: action.url };
912
+ case "RESET":
913
+ return createInitialState();
914
+ default:
915
+ return state;
916
+ }
917
+ }
918
+ __name(reducer, "reducer");
919
+ var PlaygroundContext = createContext(void 0);
920
+ var usePlaygroundContext = /* @__PURE__ */ __name(() => {
921
+ const context = useContext(PlaygroundContext);
922
+ if (!context) throw new Error("usePlaygroundContext must be used within a PlaygroundProvider");
923
+ return context;
924
+ }, "usePlaygroundContext");
925
+ var PlaygroundProvider = /* @__PURE__ */ __name(({ children, config }) => {
926
+ const [state, dispatch] = useReducer(reducer, void 0, createInitialState);
927
+ const abortControllerRef = useRef(null);
928
+ const apiKeys = React3.useMemo(
929
+ () => config.apiKeys ?? [],
930
+ [config.apiKeys]
931
+ );
932
+ const isLoadingApiKeys = config.apiKeysLoading ?? false;
933
+ const [storedApiKeyId, setStoredApiKeyId] = useSessionStorage(
934
+ AUTH_KEY_STORAGE,
935
+ null
936
+ );
937
+ const [storedBearer, setStoredBearer] = useSessionStorage(
938
+ AUTH_BEARER_STORAGE,
939
+ ""
940
+ );
941
+ const hasHydratedAuthRef = useRef(false);
942
+ useEffect(() => {
943
+ if (hasHydratedAuthRef.current) return;
944
+ hasHydratedAuthRef.current = true;
945
+ if (storedApiKeyId) dispatch({ type: "SET_API_KEY", apiKeyId: storedApiKeyId });
946
+ if (storedBearer) dispatch({ type: "SET_MANUAL_TOKEN", token: storedBearer });
947
+ }, []);
948
+ useEffect(() => {
949
+ if (!hasHydratedAuthRef.current) return;
950
+ setStoredApiKeyId(state.selectedApiKey);
951
+ }, [state.selectedApiKey, setStoredApiKeyId]);
952
+ useEffect(() => {
953
+ if (!hasHydratedAuthRef.current) return;
954
+ setStoredBearer(state.manualApiToken);
955
+ }, [state.manualApiToken, setStoredBearer]);
956
+ useEffect(() => {
957
+ if (!hasHydratedAuthRef.current) return;
958
+ if (!isLoadingApiKeys && apiKeys.length > 0 && !state.selectedApiKey && !storedApiKeyId) {
959
+ dispatch({ type: "SET_API_KEY", apiKeyId: apiKeys[0]?.id || null });
960
+ }
961
+ }, [apiKeys, isLoadingApiKeys, state.selectedApiKey, storedApiKeyId]);
962
+ useEffect(() => {
963
+ try {
964
+ const headers = parseRequestHeaders(state.requestHeaders);
965
+ if (state.selectedApiKey) {
966
+ const apiKey = apiKeys.find((k) => k.id === state.selectedApiKey);
967
+ if (!apiKey) {
968
+ dispatch({ type: "CLEAR_API_KEY_SELECTION" });
969
+ return;
970
+ }
971
+ const keyValue = apiKey.secret || apiKey.id;
972
+ if (headers["X-API-Key"] !== keyValue) {
973
+ headers["X-API-Key"] = keyValue;
974
+ dispatch({ type: "SYNC_API_KEY_HEADER", headers: JSON.stringify(headers, null, 2) });
975
+ }
976
+ } else if (headers["X-API-Key"]) {
977
+ delete headers["X-API-Key"];
978
+ dispatch({ type: "SYNC_API_KEY_HEADER", headers: JSON.stringify(headers, null, 2) });
979
+ }
980
+ } catch (error) {
981
+ consola.error("Error updating headers:", error);
982
+ }
983
+ }, [state.selectedApiKey, apiKeys]);
984
+ useEffect(() => {
985
+ if (!state.selectedEndpoint) return;
986
+ const updated = new UrlBuilder(state.selectedEndpoint, state.parameters).build();
987
+ if (updated !== state.requestUrl) {
988
+ dispatch({ type: "SYNC_URL", url: updated });
989
+ }
990
+ }, [state.parameters, state.selectedEndpoint]);
991
+ const setCurrentStep = useCallback((step) => dispatch({ type: "SET_STEP", step }), []);
992
+ const goToNextStep = useCallback(() => dispatch({ type: "NEXT_STEP" }), []);
993
+ const goToPreviousStep = useCallback(() => dispatch({ type: "PREV_STEP" }), []);
994
+ const setSelectedEndpoint = useCallback((endpoint) => dispatch({ type: "SELECT_ENDPOINT", endpoint }), []);
995
+ const setSelectedCategory = useCallback((category) => dispatch({ type: "SET_CATEGORY", category }), []);
996
+ const setSearchTerm = useCallback((term) => dispatch({ type: "SET_SEARCH", term }), []);
997
+ const setSelectedVersion = useCallback((version) => dispatch({ type: "SET_VERSION", version }), []);
998
+ const setRequestUrl = useCallback((url) => dispatch({ type: "SET_REQUEST_URL", url }), []);
999
+ const setRequestMethod = useCallback((method) => dispatch({ type: "SET_REQUEST_METHOD", method }), []);
1000
+ const setRequestHeaders = useCallback((headers) => dispatch({ type: "SET_REQUEST_HEADERS", headers }), []);
1001
+ const setRequestBody = useCallback((body) => dispatch({ type: "SET_REQUEST_BODY", body }), []);
1002
+ const setSelectedApiKey = useCallback((apiKeyId) => dispatch({ type: "SET_API_KEY", apiKeyId }), []);
1003
+ const setManualApiToken = useCallback((token) => dispatch({ type: "SET_MANUAL_TOKEN", token }), []);
1004
+ const setParameters = useCallback((parameters) => dispatch({ type: "SET_PARAMETERS", parameters }), []);
1005
+ const setResponse = useCallback((response) => dispatch({ type: "SET_RESPONSE", response }), []);
1006
+ const setLoading = useCallback((loading) => dispatch({ type: "SET_LOADING", loading }), []);
1007
+ const setSidebarOpen = useCallback((open) => dispatch({ type: "SET_SIDEBAR", open }), []);
1008
+ const setActiveSchemaId = useCallback((id) => dispatch({ type: "SET_ACTIVE_SCHEMA_ID", id }), []);
1009
+ const clearAll = useCallback(() => dispatch({ type: "RESET" }), []);
1010
+ const sendRequest = useCallback(async () => {
1011
+ if (!state.requestUrl) {
1012
+ consola.error("No URL provided");
1013
+ return;
1014
+ }
1015
+ abortControllerRef.current?.abort();
1016
+ const controller = new AbortController();
1017
+ abortControllerRef.current = controller;
1018
+ dispatch({ type: "REQUEST_START" });
1019
+ const startTime = Date.now();
1020
+ try {
1021
+ const headers = parseRequestHeaders(state.requestHeaders);
1022
+ let bearerToken = null;
1023
+ if (state.manualApiToken) {
1024
+ bearerToken = state.manualApiToken;
1025
+ } else if (typeof window !== "undefined") {
1026
+ bearerToken = window.localStorage.getItem("auth_token");
1027
+ }
1028
+ if (bearerToken) headers["Authorization"] = `Bearer ${bearerToken}`;
1029
+ const requestOptions = {
1030
+ method: state.requestMethod,
1031
+ headers,
1032
+ signal: controller.signal
1033
+ };
1034
+ if (state.requestBody && state.requestMethod !== "GET") {
1035
+ requestOptions.body = state.requestBody;
1036
+ }
1037
+ const response = await fetch(state.requestUrl, requestOptions);
1038
+ const duration = Date.now() - startTime;
1039
+ const responseText = await response.text();
1040
+ let responseData;
1041
+ try {
1042
+ responseData = JSON.parse(responseText);
1043
+ } catch {
1044
+ responseData = responseText;
1045
+ }
1046
+ dispatch({
1047
+ type: "REQUEST_SUCCESS",
1048
+ response: {
1049
+ status: response.status,
1050
+ statusText: response.statusText,
1051
+ headers: Object.fromEntries(response.headers.entries()),
1052
+ data: responseData,
1053
+ duration
1054
+ }
1055
+ });
1056
+ consola.success(`${state.requestMethod} ${state.requestUrl} \u2192 ${response.status} (${duration}ms)`);
1057
+ } catch (error) {
1058
+ if (error instanceof DOMException && error.name === "AbortError") return;
1059
+ consola.error("Request failed:", error);
1060
+ dispatch({
1061
+ type: "REQUEST_ERROR",
1062
+ response: {
1063
+ error: error instanceof Error ? error.message : "Request failed",
1064
+ duration: Date.now() - startTime
1065
+ }
1066
+ });
1067
+ }
1068
+ }, [state.requestUrl, state.requestHeaders, state.manualApiToken, state.requestMethod, state.requestBody]);
1069
+ const contextValue = {
1070
+ state,
1071
+ config,
1072
+ apiKeys,
1073
+ apiKeysLoading: isLoadingApiKeys,
1074
+ setCurrentStep,
1075
+ goToNextStep,
1076
+ goToPreviousStep,
1077
+ setSelectedEndpoint,
1078
+ setSelectedCategory,
1079
+ setSearchTerm,
1080
+ setSelectedVersion,
1081
+ setRequestUrl,
1082
+ setRequestMethod,
1083
+ setRequestHeaders,
1084
+ setRequestBody,
1085
+ setSelectedApiKey,
1086
+ setManualApiToken,
1087
+ setParameters,
1088
+ setResponse,
1089
+ setLoading,
1090
+ setSidebarOpen,
1091
+ setActiveSchemaId,
1092
+ clearAll,
1093
+ sendRequest
1094
+ };
1095
+ return /* @__PURE__ */ jsx(PlaygroundContext.Provider, { value: contextValue, children });
1096
+ }, "PlaygroundProvider");
1097
+
1098
+ export { MarkdownMessage, Mermaid_default, PlaygroundProvider, PrettyCode_default, UrlBuilder, deduplicateEndpoints, dereferenceSchema, endpointToMarkdown, findApiKeyById, formatBytes, isValidJson, joinUrl, parseRequestHeaders, relativePath, resolveAbsolute, resolveBaseUrl, toCompactJson, toMarkdown, toRawJson, useCollapsibleContent, usePlaygroundContext };
1099
+ //# sourceMappingURL=chunk-VZGQC3NG.mjs.map
1100
+ //# sourceMappingURL=chunk-VZGQC3NG.mjs.map