@djangocfg/ui-tools 2.1.390 → 2.1.394

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 (184) hide show
  1. package/README.md +7 -10
  2. package/dist/chunk-PAWJFY3S.mjs +6 -0
  3. package/dist/{chunk-N2XQF2OL.mjs.map → chunk-PAWJFY3S.mjs.map} +1 -1
  4. package/dist/chunk-PK6SKIKE.cjs +8 -0
  5. package/dist/{chunk-OLISEQHS.cjs.map → chunk-PK6SKIKE.cjs.map} +1 -1
  6. package/dist/file-icon/index.cjs +6 -6
  7. package/dist/file-icon/index.d.cts +1 -1
  8. package/dist/file-icon/index.d.ts +1 -1
  9. package/dist/file-icon/index.mjs +1 -1
  10. package/dist/tree/index.cjs +1372 -143
  11. package/dist/tree/index.cjs.map +1 -1
  12. package/dist/tree/index.d.cts +2 -2
  13. package/dist/tree/index.d.ts +2 -2
  14. package/dist/tree/index.mjs +1322 -3
  15. package/dist/tree/index.mjs.map +1 -1
  16. package/dist/{types-CevSbyfD.d.cts → types-B_zhyAqR.d.cts} +1 -1
  17. package/dist/{types-CevSbyfD.d.ts → types-B_zhyAqR.d.ts} +1 -1
  18. package/package.json +6 -14
  19. package/src/tools/AudioPlayer/README.md +4 -4
  20. package/src/tools/Chat/README.md +6 -6
  21. package/src/tools/CronScheduler/index.tsx +1 -1
  22. package/src/tools/CronScheduler/lazy.tsx +1 -1
  23. package/src/tools/ImageViewer/README.md +1 -1
  24. package/src/tools/JsonForm/README.md +2 -2
  25. package/src/tools/MarkdownEditor/README.md +3 -3
  26. package/src/tools/MarkdownMessage/README.md +2 -2
  27. package/src/tools/OpenapiViewer/components/DocsLayout/grouping.ts +5 -1
  28. package/src/tools/PrettyCode/lazy.tsx +6 -0
  29. package/src/tools/SpeechRecognition/README.md +1 -1
  30. package/dist/ChatRoot-EFNXQXXN.cjs +0 -15
  31. package/dist/ChatRoot-EFNXQXXN.cjs.map +0 -1
  32. package/dist/ChatRoot-FITF5RVP.mjs +0 -6
  33. package/dist/ChatRoot-FITF5RVP.mjs.map +0 -1
  34. package/dist/ChatRoot-PNNGQCYF.css +0 -7
  35. package/dist/ChatRoot-PNNGQCYF.css.map +0 -1
  36. package/dist/CronScheduler.client-DLMXCPAJ.mjs +0 -67
  37. package/dist/CronScheduler.client-DLMXCPAJ.mjs.map +0 -1
  38. package/dist/CronScheduler.client-WEJF4PWQ.cjs +0 -72
  39. package/dist/CronScheduler.client-WEJF4PWQ.cjs.map +0 -1
  40. package/dist/DictationField-AS2F33WI.cjs +0 -13
  41. package/dist/DictationField-AS2F33WI.cjs.map +0 -1
  42. package/dist/DictationField-WPONUCYE.mjs +0 -4
  43. package/dist/DictationField-WPONUCYE.mjs.map +0 -1
  44. package/dist/DocsLayout-EKASBSP7.mjs +0 -3448
  45. package/dist/DocsLayout-EKASBSP7.mjs.map +0 -1
  46. package/dist/DocsLayout-MBFIB4NO.css +0 -7
  47. package/dist/DocsLayout-MBFIB4NO.css.map +0 -1
  48. package/dist/DocsLayout-OURFYWQE.cjs +0 -3455
  49. package/dist/DocsLayout-OURFYWQE.cjs.map +0 -1
  50. package/dist/JsonSchemaForm-DD7CLRIG.cjs +0 -13
  51. package/dist/JsonSchemaForm-DD7CLRIG.cjs.map +0 -1
  52. package/dist/JsonSchemaForm-XKUIVELK.mjs +0 -4
  53. package/dist/JsonSchemaForm-XKUIVELK.mjs.map +0 -1
  54. package/dist/JsonTree-43PQAJKY.mjs +0 -5
  55. package/dist/JsonTree-43PQAJKY.mjs.map +0 -1
  56. package/dist/JsonTree-MLET23ZA.css +0 -7
  57. package/dist/JsonTree-MLET23ZA.css.map +0 -1
  58. package/dist/JsonTree-X6W5YEVY.cjs +0 -11
  59. package/dist/JsonTree-X6W5YEVY.cjs.map +0 -1
  60. package/dist/LottiePlayer.client-2S7ISJ2S.cjs +0 -168
  61. package/dist/LottiePlayer.client-2S7ISJ2S.cjs.map +0 -1
  62. package/dist/LottiePlayer.client-5LDSSJWS.mjs +0 -161
  63. package/dist/LottiePlayer.client-5LDSSJWS.mjs.map +0 -1
  64. package/dist/MapContainer-AKIPABJK.mjs +0 -4
  65. package/dist/MapContainer-AKIPABJK.mjs.map +0 -1
  66. package/dist/MapContainer-STVDMC36.cjs +0 -17
  67. package/dist/MapContainer-STVDMC36.cjs.map +0 -1
  68. package/dist/Mermaid.client-DDXWXZXY.css +0 -7
  69. package/dist/Mermaid.client-DDXWXZXY.css.map +0 -1
  70. package/dist/Mermaid.client-NL4SVR7F.mjs +0 -481
  71. package/dist/Mermaid.client-NL4SVR7F.mjs.map +0 -1
  72. package/dist/Mermaid.client-NNTI6DFX.cjs +0 -487
  73. package/dist/Mermaid.client-NNTI6DFX.cjs.map +0 -1
  74. package/dist/Player-BRV7XTWR.mjs +0 -4
  75. package/dist/Player-BRV7XTWR.mjs.map +0 -1
  76. package/dist/Player-PM7F7DD7.cjs +0 -13
  77. package/dist/Player-PM7F7DD7.cjs.map +0 -1
  78. package/dist/Player-ZGQKKOWI.css +0 -66
  79. package/dist/Player-ZGQKKOWI.css.map +0 -1
  80. package/dist/PrettyCode.client-GWFAIVFN.css +0 -7
  81. package/dist/PrettyCode.client-GWFAIVFN.css.map +0 -1
  82. package/dist/PrettyCode.client-KOHDVPPN.cjs +0 -285
  83. package/dist/PrettyCode.client-KOHDVPPN.cjs.map +0 -1
  84. package/dist/PrettyCode.client-ZGYGKE7G.mjs +0 -283
  85. package/dist/PrettyCode.client-ZGYGKE7G.mjs.map +0 -1
  86. package/dist/TreeRoot-5COOOSWG.mjs +0 -4
  87. package/dist/TreeRoot-5COOOSWG.mjs.map +0 -1
  88. package/dist/TreeRoot-AABP2J6Y.cjs +0 -19
  89. package/dist/TreeRoot-AABP2J6Y.cjs.map +0 -1
  90. package/dist/chunk-2NG4SXEP.mjs +0 -743
  91. package/dist/chunk-2NG4SXEP.mjs.map +0 -1
  92. package/dist/chunk-4LFB7I5K.cjs +0 -1387
  93. package/dist/chunk-4LFB7I5K.cjs.map +0 -1
  94. package/dist/chunk-5D2OCOPQ.cjs +0 -222
  95. package/dist/chunk-5D2OCOPQ.cjs.map +0 -1
  96. package/dist/chunk-5I5QNGUG.cjs +0 -611
  97. package/dist/chunk-5I5QNGUG.cjs.map +0 -1
  98. package/dist/chunk-6ZX2G25W.mjs +0 -1361
  99. package/dist/chunk-6ZX2G25W.mjs.map +0 -1
  100. package/dist/chunk-76NNDZH6.cjs +0 -1061
  101. package/dist/chunk-76NNDZH6.cjs.map +0 -1
  102. package/dist/chunk-7CWGZPO3.mjs +0 -214
  103. package/dist/chunk-7CWGZPO3.mjs.map +0 -1
  104. package/dist/chunk-7EYHNP3E.cjs +0 -965
  105. package/dist/chunk-7EYHNP3E.cjs.map +0 -1
  106. package/dist/chunk-7IYXZUJO.cjs +0 -769
  107. package/dist/chunk-7IYXZUJO.cjs.map +0 -1
  108. package/dist/chunk-ADEN3UA4.cjs +0 -892
  109. package/dist/chunk-ADEN3UA4.cjs.map +0 -1
  110. package/dist/chunk-B6IR5KSC.mjs +0 -59
  111. package/dist/chunk-B6IR5KSC.mjs.map +0 -1
  112. package/dist/chunk-C6GXVH5J.mjs +0 -338
  113. package/dist/chunk-C6GXVH5J.mjs.map +0 -1
  114. package/dist/chunk-DMX7W4XZ.mjs +0 -1113
  115. package/dist/chunk-DMX7W4XZ.mjs.map +0 -1
  116. package/dist/chunk-ECONRHIG.mjs +0 -212
  117. package/dist/chunk-ECONRHIG.mjs.map +0 -1
  118. package/dist/chunk-FEN5S772.cjs +0 -1227
  119. package/dist/chunk-FEN5S772.cjs.map +0 -1
  120. package/dist/chunk-FP2RLYQZ.cjs +0 -187
  121. package/dist/chunk-FP2RLYQZ.cjs.map +0 -1
  122. package/dist/chunk-FVVF7VCD.cjs +0 -1325
  123. package/dist/chunk-FVVF7VCD.cjs.map +0 -1
  124. package/dist/chunk-GYIO7W7M.mjs +0 -1197
  125. package/dist/chunk-GYIO7W7M.mjs.map +0 -1
  126. package/dist/chunk-KNDLV4PI.cjs +0 -1356
  127. package/dist/chunk-KNDLV4PI.cjs.map +0 -1
  128. package/dist/chunk-KNEQRUBA.mjs +0 -181
  129. package/dist/chunk-KNEQRUBA.mjs.map +0 -1
  130. package/dist/chunk-N2XQF2OL.mjs +0 -14
  131. package/dist/chunk-N4MZYNR4.mjs +0 -1342
  132. package/dist/chunk-N4MZYNR4.mjs.map +0 -1
  133. package/dist/chunk-NTVBIIUD.mjs +0 -1439
  134. package/dist/chunk-NTVBIIUD.mjs.map +0 -1
  135. package/dist/chunk-OBRSGM64.mjs +0 -607
  136. package/dist/chunk-OBRSGM64.mjs.map +0 -1
  137. package/dist/chunk-ODO4GMW7.mjs +0 -79
  138. package/dist/chunk-ODO4GMW7.mjs.map +0 -1
  139. package/dist/chunk-OLISEQHS.cjs +0 -18
  140. package/dist/chunk-PVAX67JG.mjs +0 -1041
  141. package/dist/chunk-PVAX67JG.mjs.map +0 -1
  142. package/dist/chunk-QJ6GTUCO.cjs +0 -81
  143. package/dist/chunk-QJ6GTUCO.cjs.map +0 -1
  144. package/dist/chunk-T3MWM23F.cjs +0 -214
  145. package/dist/chunk-T3MWM23F.cjs.map +0 -1
  146. package/dist/chunk-TBSHZO5R.cjs +0 -1134
  147. package/dist/chunk-TBSHZO5R.cjs.map +0 -1
  148. package/dist/chunk-UNCS5V5F.mjs +0 -887
  149. package/dist/chunk-UNCS5V5F.mjs.map +0 -1
  150. package/dist/chunk-VWQ5WOIL.mjs +0 -2059
  151. package/dist/chunk-VWQ5WOIL.mjs.map +0 -1
  152. package/dist/chunk-W75B7Y6C.cjs +0 -1478
  153. package/dist/chunk-W75B7Y6C.cjs.map +0 -1
  154. package/dist/chunk-Y6UTOBF6.mjs +0 -938
  155. package/dist/chunk-Y6UTOBF6.mjs.map +0 -1
  156. package/dist/chunk-YDPDTOSP.cjs +0 -2061
  157. package/dist/chunk-YDPDTOSP.cjs.map +0 -1
  158. package/dist/chunk-YW5IVWHQ.cjs +0 -346
  159. package/dist/chunk-YW5IVWHQ.cjs.map +0 -1
  160. package/dist/chunk-YXZ6GU7H.cjs +0 -63
  161. package/dist/chunk-YXZ6GU7H.cjs.map +0 -1
  162. package/dist/chunk-ZL7FH4NW.mjs +0 -1274
  163. package/dist/chunk-ZL7FH4NW.mjs.map +0 -1
  164. package/dist/components-EHOGXATG.cjs +0 -22
  165. package/dist/components-EHOGXATG.cjs.map +0 -1
  166. package/dist/components-MQ6DR7TX.cjs +0 -26
  167. package/dist/components-MQ6DR7TX.cjs.map +0 -1
  168. package/dist/components-XRX7QGLB.mjs +0 -5
  169. package/dist/components-XRX7QGLB.mjs.map +0 -1
  170. package/dist/components-YATKRWLH.mjs +0 -5
  171. package/dist/components-YATKRWLH.mjs.map +0 -1
  172. package/dist/index.cjs +0 -3674
  173. package/dist/index.cjs.map +0 -1
  174. package/dist/index.css +0 -234
  175. package/dist/index.css.map +0 -1
  176. package/dist/index.d.cts +0 -4929
  177. package/dist/index.d.ts +0 -4929
  178. package/dist/index.mjs +0 -2912
  179. package/dist/index.mjs.map +0 -1
  180. package/dist/launcher-5Y42OBSN.mjs +0 -6
  181. package/dist/launcher-5Y42OBSN.mjs.map +0 -1
  182. package/dist/launcher-PMW2YB24.cjs +0 -59
  183. package/dist/launcher-PMW2YB24.cjs.map +0 -1
  184. package/src/index.ts +0 -157
@@ -1,938 +0,0 @@
1
- import { __name } from './chunk-N2XQF2OL.mjs';
2
- import consola2 from 'consola';
3
- import React, { createContext, useContext, useReducer, useRef, useEffect, useCallback } from 'react';
4
- import { useSessionStorage } from '@djangocfg/ui-core/hooks';
5
- import { sample } from 'openapi-sampler';
6
- import { jsx } from 'react/jsx-runtime';
7
-
8
- // src/tools/OpenapiViewer/utils/apiKeyManager.ts
9
- function findApiKeyById(apiKeys, keyId) {
10
- return apiKeys.find((key) => key.id === keyId) || null;
11
- }
12
- __name(findApiKeyById, "findApiKeyById");
13
-
14
- // src/tools/OpenapiViewer/utils/codeSamples.ts
15
- var CODE_SAMPLE_TARGETS = [
16
- { id: "curl", label: "cURL", prism: "bash" },
17
- { id: "fetch", label: "JavaScript", prism: "javascript" },
18
- { id: "axios", label: "Node (axios)", prism: "javascript" },
19
- { id: "python", label: "Python", prism: "python" },
20
- { id: "go", label: "Go", prism: "go" },
21
- { id: "php", label: "PHP", prism: "php" },
22
- { id: "ruby", label: "Ruby", prism: "ruby" },
23
- { id: "java", label: "Java", prism: "java" }
24
- ];
25
- function goRawString(s) {
26
- return s.includes("`") ? JSON.stringify(s) : `\`${s}\``;
27
- }
28
- __name(goRawString, "goRawString");
29
- function rubyHeredoc(s) {
30
- return `<<~JSON
31
- ${s}
32
- JSON`;
33
- }
34
- __name(rubyHeredoc, "rubyHeredoc");
35
- function phpHeredoc(s) {
36
- return `<<<JSON
37
- ${s}
38
- JSON`;
39
- }
40
- __name(phpHeredoc, "phpHeredoc");
41
- function javaTextBlock(s) {
42
- if (s.includes('"""')) return JSON.stringify(s);
43
- return `"""
44
- ${s}
45
- """`;
46
- }
47
- __name(javaTextBlock, "javaTextBlock");
48
- function fullUrl(har) {
49
- if (!har.queryString.length) return har.url;
50
- const qs = har.queryString.map((p) => `${encodeURIComponent(p.name)}=${encodeURIComponent(p.value)}`).join("&");
51
- const sep = har.url.includes("?") ? "&" : "?";
52
- return `${har.url}${sep}${qs}`;
53
- }
54
- __name(fullUrl, "fullUrl");
55
- function shellEscape(value) {
56
- return `'${value.replace(/'/g, `'\\''`)}'`;
57
- }
58
- __name(shellEscape, "shellEscape");
59
- function renderCurl(har) {
60
- const lines = [`curl -X ${har.method} ${shellEscape(fullUrl(har))}`];
61
- for (const h of har.headers) {
62
- lines.push(` -H ${shellEscape(`${h.name}: ${h.value}`)}`);
63
- }
64
- if (har.postData?.text) {
65
- lines.push(` -d ${shellEscape(har.postData.text)}`);
66
- }
67
- return lines.join(" \\\n");
68
- }
69
- __name(renderCurl, "renderCurl");
70
- function jsHeadersLiteral(har, indent) {
71
- if (!har.headers.length) return "{}";
72
- const entries = har.headers.map((h) => `${indent} ${JSON.stringify(h.name)}: ${JSON.stringify(h.value)}`).join(",\n");
73
- return `{
74
- ${entries},
75
- ${indent}}`;
76
- }
77
- __name(jsHeadersLiteral, "jsHeadersLiteral");
78
- function jsTemplateLiteral(s) {
79
- if (/[`$]/.test(s)) return JSON.stringify(s);
80
- return `\`${s}\``;
81
- }
82
- __name(jsTemplateLiteral, "jsTemplateLiteral");
83
- function renderFetch(har) {
84
- const url = fullUrl(har);
85
- const options = [` method: ${JSON.stringify(har.method)}`];
86
- if (har.headers.length) {
87
- options.push(` headers: ${jsHeadersLiteral(har, " ")}`);
88
- }
89
- if (har.postData?.text) {
90
- options.push(` body: ${jsTemplateLiteral(har.postData.text)}`);
91
- }
92
- return `const response = await fetch(${JSON.stringify(url)}, {
93
- ${options.join(",\n")},
94
- });
95
- const data = await response.json();`;
96
- }
97
- __name(renderFetch, "renderFetch");
98
- function renderAxios(har) {
99
- const url = fullUrl(har);
100
- const config = [
101
- ` method: ${JSON.stringify(har.method.toLowerCase())}`,
102
- ` url: ${JSON.stringify(url)}`
103
- ];
104
- if (har.headers.length) {
105
- config.push(` headers: ${jsHeadersLiteral(har, " ")}`);
106
- }
107
- if (har.postData?.text) {
108
- config.push(` data: ${har.postData.text}`);
109
- }
110
- return `import axios from 'axios';
111
-
112
- const { data } = await axios({
113
- ${config.join(",\n")},
114
- });`;
115
- }
116
- __name(renderAxios, "renderAxios");
117
- function renderPython(har) {
118
- const lines = [`import requests`, ``];
119
- lines.push(`url = ${JSON.stringify(fullUrl(har))}`);
120
- if (har.headers.length) {
121
- const headerEntries = har.headers.map((h) => ` ${JSON.stringify(h.name)}: ${JSON.stringify(h.value)}`).join(",\n");
122
- lines.push(`headers = {
123
- ${headerEntries},
124
- }`);
125
- }
126
- if (har.postData?.text) {
127
- lines.push(`payload = ${har.postData.text}`);
128
- }
129
- const args = [`url`];
130
- if (har.headers.length) args.push(`headers=headers`);
131
- if (har.postData?.text) args.push(`json=payload`);
132
- lines.push(``, `response = requests.${har.method.toLowerCase()}(${args.join(", ")})`);
133
- lines.push(`data = response.json()`);
134
- return lines.join("\n");
135
- }
136
- __name(renderPython, "renderPython");
137
- function renderGo(har) {
138
- const url = fullUrl(har);
139
- const lines = [
140
- `package main`,
141
- ``,
142
- `import (`,
143
- ` "fmt"`,
144
- ` "io"`
145
- ];
146
- if (har.postData?.text) lines.push(` "strings"`);
147
- lines.push(` "net/http"`);
148
- lines.push(`)`, ``, `func main() {`);
149
- if (har.postData?.text) {
150
- lines.push(` payload := strings.NewReader(${goRawString(har.postData.text)})`);
151
- lines.push(` req, _ := http.NewRequest(${JSON.stringify(har.method)}, ${JSON.stringify(url)}, payload)`);
152
- } else {
153
- lines.push(` req, _ := http.NewRequest(${JSON.stringify(har.method)}, ${JSON.stringify(url)}, nil)`);
154
- }
155
- for (const h of har.headers) {
156
- lines.push(` req.Header.Add(${JSON.stringify(h.name)}, ${JSON.stringify(h.value)})`);
157
- }
158
- lines.push(
159
- ``,
160
- ` res, _ := http.DefaultClient.Do(req)`,
161
- ` defer res.Body.Close()`,
162
- ` body, _ := io.ReadAll(res.Body)`,
163
- ` fmt.Println(string(body))`,
164
- `}`
165
- );
166
- return lines.join("\n");
167
- }
168
- __name(renderGo, "renderGo");
169
- function renderPhp(har) {
170
- const lines = [`<?php`, ``, `$curl = curl_init();`, ``, `curl_setopt_array($curl, [`];
171
- lines.push(` CURLOPT_URL => ${JSON.stringify(fullUrl(har))},`);
172
- lines.push(` CURLOPT_RETURNTRANSFER => true,`);
173
- lines.push(` CURLOPT_CUSTOMREQUEST => ${JSON.stringify(har.method)},`);
174
- if (har.postData?.text) {
175
- lines.push(` CURLOPT_POSTFIELDS => ${phpHeredoc(har.postData.text)},`);
176
- }
177
- if (har.headers.length) {
178
- const headerList = har.headers.map((h) => ` ${JSON.stringify(`${h.name}: ${h.value}`)}`).join(",\n");
179
- lines.push(` CURLOPT_HTTPHEADER => [
180
- ${headerList},
181
- ],`);
182
- }
183
- lines.push(`]);`, ``, `$response = curl_exec($curl);`, `curl_close($curl);`, `echo $response;`);
184
- return lines.join("\n");
185
- }
186
- __name(renderPhp, "renderPhp");
187
- function renderRuby(har) {
188
- const lines = [
189
- `require 'net/http'`,
190
- `require 'uri'`,
191
- `require 'json'`,
192
- ``,
193
- `uri = URI(${JSON.stringify(fullUrl(har))})`,
194
- `http = Net::HTTP.new(uri.host, uri.port)`,
195
- `http.use_ssl = uri.scheme == 'https'`,
196
- ``
197
- ];
198
- const methodClass = har.method.charAt(0) + har.method.slice(1).toLowerCase();
199
- lines.push(`request = Net::HTTP::${methodClass}.new(uri)`);
200
- for (const h of har.headers) {
201
- lines.push(`request[${JSON.stringify(h.name)}] = ${JSON.stringify(h.value)}`);
202
- }
203
- if (har.postData?.text) {
204
- lines.push(`request.body = ${rubyHeredoc(har.postData.text)}`);
205
- }
206
- lines.push(``, `response = http.request(request)`, `puts response.body`);
207
- return lines.join("\n");
208
- }
209
- __name(renderRuby, "renderRuby");
210
- function renderJava(har) {
211
- const lines = [
212
- `OkHttpClient client = new OkHttpClient();`,
213
- ``
214
- ];
215
- if (har.postData?.text) {
216
- lines.push(
217
- `MediaType mediaType = MediaType.parse("application/json");`,
218
- `RequestBody body = RequestBody.create(mediaType, ${javaTextBlock(har.postData.text)});`,
219
- ``
220
- );
221
- }
222
- lines.push(`Request request = new Request.Builder()`);
223
- lines.push(` .url(${JSON.stringify(fullUrl(har))})`);
224
- if (har.postData?.text) {
225
- lines.push(` .method(${JSON.stringify(har.method)}, body)`);
226
- } else {
227
- lines.push(` .method(${JSON.stringify(har.method)}, null)`);
228
- }
229
- for (const h of har.headers) {
230
- lines.push(` .addHeader(${JSON.stringify(h.name)}, ${JSON.stringify(h.value)})`);
231
- }
232
- lines.push(` .build();`, ``, `Response response = client.newCall(request).execute();`);
233
- return lines.join("\n");
234
- }
235
- __name(renderJava, "renderJava");
236
- var RENDERERS = {
237
- curl: renderCurl,
238
- fetch: renderFetch,
239
- axios: renderAxios,
240
- python: renderPython,
241
- go: renderGo,
242
- php: renderPhp,
243
- ruby: renderRuby,
244
- java: renderJava
245
- };
246
- function renderSnippet(har, targetId) {
247
- const renderer = RENDERERS[targetId];
248
- if (!renderer) return null;
249
- try {
250
- return renderer(har);
251
- } catch {
252
- return null;
253
- }
254
- }
255
- __name(renderSnippet, "renderSnippet");
256
-
257
- // src/tools/OpenapiViewer/utils/operationToHar.ts
258
- function buildUrl(endpoint, parameters, baseUrl) {
259
- const pathParamNames = new Set(
260
- (endpoint.parameters ?? []).filter((p) => endpoint.path.includes(`{${p.name}}`)).map((p) => p.name)
261
- );
262
- let path = endpoint.path;
263
- for (const name of pathParamNames) {
264
- const value = parameters[name];
265
- if (value === void 0 || value === "") continue;
266
- path = path.replaceAll(`{${name}}`, encodeURIComponent(value));
267
- }
268
- const queryString = [];
269
- for (const param of endpoint.parameters ?? []) {
270
- if (pathParamNames.has(param.name)) continue;
271
- const value = parameters[param.name];
272
- if (value === void 0 || value === "") continue;
273
- queryString.push({ name: param.name, value });
274
- }
275
- const url = baseUrl ? `${baseUrl.replace(/\/+$/, "")}${path.startsWith("/") ? path : `/${path}`}` : path;
276
- return { url, queryString };
277
- }
278
- __name(buildUrl, "buildUrl");
279
- function buildHarRequest(input) {
280
- const { endpoint, body, parameters = {}, headers = {}, baseUrl } = input;
281
- const { url, queryString } = buildUrl(endpoint, parameters, baseUrl);
282
- const hasBody = Boolean(body && body.trim().length > 0);
283
- const bodyMime = hasBody ? "application/json" : void 0;
284
- const mergedHeaders = {};
285
- if (hasBody && bodyMime) mergedHeaders["Content-Type"] = bodyMime;
286
- mergedHeaders["Accept"] = "application/json";
287
- for (const [k, v] of Object.entries(headers)) {
288
- if (v === void 0 || v === "") continue;
289
- mergedHeaders[k] = v;
290
- }
291
- const har = {
292
- method: endpoint.method.toUpperCase(),
293
- url,
294
- httpVersion: "HTTP/1.1",
295
- headers: Object.entries(mergedHeaders).map(([name, value]) => ({ name, value })),
296
- queryString,
297
- cookies: [],
298
- headersSize: -1,
299
- bodySize: hasBody ? new TextEncoder().encode(body).length : 0
300
- };
301
- if (hasBody && bodyMime) {
302
- har.postData = { mimeType: bodyMime, text: body };
303
- }
304
- return har;
305
- }
306
- __name(buildHarRequest, "buildHarRequest");
307
-
308
- // src/tools/OpenapiViewer/utils/versionManager.ts
309
- var API_VERSIONS = [
310
- {
311
- id: "v1",
312
- name: "v1",
313
- description: "Current stable version",
314
- isDefault: true
315
- }
316
- ];
317
- var detectEndpointVersion = /* @__PURE__ */ __name((path) => {
318
- const versionMatch = path.match(/\/api\/[^/]+\/(v\d+)\//);
319
- if (versionMatch && versionMatch[1]) {
320
- return versionMatch[1];
321
- }
322
- return "v1";
323
- }, "detectEndpointVersion");
324
- var isEndpointInVersion = /* @__PURE__ */ __name((endpoint, version) => {
325
- const endpointVersion = detectEndpointVersion(endpoint.path);
326
- return endpointVersion === version;
327
- }, "isEndpointInVersion");
328
- var deduplicateEndpoints = /* @__PURE__ */ __name((endpoints, preferredVersion) => {
329
- const endpointMap = /* @__PURE__ */ new Map();
330
- const groupedEndpoints = /* @__PURE__ */ new Map();
331
- endpoints.forEach((endpoint) => {
332
- const normalizedPath = normalizeEndpointPath(endpoint.path);
333
- if (!groupedEndpoints.has(normalizedPath)) {
334
- groupedEndpoints.set(normalizedPath, []);
335
- }
336
- groupedEndpoints.get(normalizedPath).push(endpoint);
337
- });
338
- groupedEndpoints.forEach((endpointGroup, normalizedPath) => {
339
- let selectedEndpoint = null;
340
- const versionEndpoint = endpointGroup.find((ep) => isEndpointInVersion(ep, preferredVersion));
341
- if (versionEndpoint) {
342
- selectedEndpoint = versionEndpoint;
343
- } else if (endpointGroup.length > 0) {
344
- selectedEndpoint = endpointGroup[0] || null;
345
- }
346
- if (selectedEndpoint) {
347
- endpointMap.set(normalizedPath, selectedEndpoint);
348
- }
349
- });
350
- return Array.from(endpointMap.values());
351
- }, "deduplicateEndpoints");
352
- var normalizeEndpointPath = /* @__PURE__ */ __name((path) => {
353
- return path.replace(/\/v\d+\//, "/");
354
- }, "normalizeEndpointPath");
355
- var getDefaultVersion = /* @__PURE__ */ __name(() => {
356
- const defaultVersion = API_VERSIONS.find((v) => v.isDefault);
357
- if (defaultVersion) {
358
- return defaultVersion;
359
- }
360
- if (API_VERSIONS.length > 0 && API_VERSIONS[0]) {
361
- return API_VERSIONS[0];
362
- }
363
- throw new Error("No API versions defined");
364
- }, "getDefaultVersion");
365
-
366
- // src/tools/OpenapiViewer/utils/formatters.ts
367
- var isValidJson = /* @__PURE__ */ __name((str) => {
368
- if (!str || typeof str !== "string") return false;
369
- try {
370
- JSON.parse(str);
371
- return true;
372
- } catch {
373
- return false;
374
- }
375
- }, "isValidJson");
376
- var parseRequestHeaders = /* @__PURE__ */ __name((headersString) => {
377
- if (!headersString || typeof headersString !== "string") {
378
- return { "Content-Type": "application/json" };
379
- }
380
- try {
381
- const parsed = JSON.parse(headersString);
382
- return typeof parsed === "object" && parsed !== null ? parsed : { "Content-Type": "application/json" };
383
- } catch {
384
- return { "Content-Type": "application/json" };
385
- }
386
- }, "parseRequestHeaders");
387
- function sampleSchema(schema, options = {}, spec) {
388
- if (!schema) return null;
389
- try {
390
- return sample(schema, options, spec);
391
- } catch (err) {
392
- consola2.warn("[OpenapiViewer] sampleSchema failed:", err, { schema });
393
- return null;
394
- }
395
- }
396
- __name(sampleSchema, "sampleSchema");
397
- function sampleSchemaJson(schema, options = {}, spec) {
398
- const value = sampleSchema(schema, options, spec);
399
- if (value === null || value === void 0) return void 0;
400
- try {
401
- return JSON.stringify(value, null, 2);
402
- } catch {
403
- return void 0;
404
- }
405
- }
406
- __name(sampleSchemaJson, "sampleSchemaJson");
407
-
408
- // src/tools/OpenapiViewer/utils/url.ts
409
- var PATH_PARAM_RE = /\{([^{}]+)\}/g;
410
- function extractPathPlaceholders(template) {
411
- const seen = /* @__PURE__ */ new Set();
412
- const out = [];
413
- for (const match of template.matchAll(PATH_PARAM_RE)) {
414
- const name = match[1];
415
- if (!seen.has(name)) {
416
- seen.add(name);
417
- out.push(name);
418
- }
419
- }
420
- return out;
421
- }
422
- __name(extractPathPlaceholders, "extractPathPlaceholders");
423
- function substitutePath(template, values) {
424
- return template.replace(PATH_PARAM_RE, (whole, name) => {
425
- const v = values[name];
426
- return v && v.trim() !== "" ? encodeURIComponent(v) : whole;
427
- });
428
- }
429
- __name(substitutePath, "substitutePath");
430
- function unfilledPlaceholders(template, values) {
431
- return extractPathPlaceholders(template).filter(
432
- (name) => !(values[name] ?? "").trim()
433
- );
434
- }
435
- __name(unfilledPlaceholders, "unfilledPlaceholders");
436
- function appendQuery(url, values, pathTemplate) {
437
- const pathNames = new Set(extractPathPlaceholders(pathTemplate));
438
- const queryEntries = Object.entries(values).filter(
439
- ([name, value]) => !pathNames.has(name) && value && value.trim() !== ""
440
- );
441
- if (queryEntries.length === 0) return url;
442
- const [base, existingQuery = ""] = url.split("?", 2);
443
- const params = new URLSearchParams(existingQuery);
444
- for (const [k, v] of queryEntries) params.set(k, v);
445
- const qs = params.toString();
446
- return qs ? `${base}?${qs}` : base ?? url;
447
- }
448
- __name(appendQuery, "appendQuery");
449
- function resolveAbsolute(url) {
450
- if (!url) return url;
451
- if (/^https?:\/\//i.test(url)) return url;
452
- if (typeof window === "undefined") return url;
453
- if (url.startsWith("//")) return `${window.location.protocol}${url}`;
454
- if (url.startsWith("/")) return `${window.location.origin}${url}`;
455
- return url;
456
- }
457
- __name(resolveAbsolute, "resolveAbsolute");
458
- function relativePath(url) {
459
- try {
460
- return new URL(url).pathname.replace(/%7B/gi, "{").replace(/%7D/gi, "}");
461
- } catch {
462
- return url;
463
- }
464
- }
465
- __name(relativePath, "relativePath");
466
- function joinUrl(...parts) {
467
- const filtered = parts.filter((p) => p !== void 0 && p !== null && p !== "");
468
- return filtered.map((p, i) => {
469
- const s = String(p);
470
- if (i === 0) return s.replace(/\/+$/, "");
471
- const stripped = s.replace(/^\/+/, "");
472
- if (i === filtered.length - 1) return stripped;
473
- return stripped.replace(/\/+$/, "");
474
- }).filter((p) => p !== "").join("/");
475
- }
476
- __name(joinUrl, "joinUrl");
477
- function resolveBaseUrl(sources) {
478
- return sources.schemaSource || sources.config || sources.fromServers || "";
479
- }
480
- __name(resolveBaseUrl, "resolveBaseUrl");
481
- var _UrlBuilder = class _UrlBuilder {
482
- constructor(endpoint, parameters) {
483
- this.endpoint = endpoint;
484
- this.parameters = parameters;
485
- }
486
- /** What ``fetch()`` receives: substituted path + query string. Origin
487
- * is whatever the endpoint template already had (relative paths
488
- * stay relative so the browser resolves them against the page). */
489
- build() {
490
- const substituted = substitutePath(this.endpoint.path, this.parameters);
491
- return appendQuery(substituted, this.parameters, this.endpoint.path);
492
- }
493
- /** Same as ``build()`` but guaranteed absolute — for curl snippets
494
- * and anywhere the URL leaves the browser context. */
495
- buildAbsolute() {
496
- return resolveAbsolute(this.build());
497
- }
498
- /** Names of required path/query params still empty. */
499
- missingRequired() {
500
- if (!this.endpoint.parameters) return [];
501
- return this.endpoint.parameters.filter((p) => p.required && !(this.parameters[p.name] ?? "").trim()).map((p) => p.name);
502
- }
503
- /** Placeholders in the template with no matching value. Usually a
504
- * superset of ``missingRequired`` — catches schemas that forgot
505
- * to flag a path param as required. */
506
- unfilledPlaceholders() {
507
- return unfilledPlaceholders(this.endpoint.path, this.parameters);
508
- }
509
- };
510
- __name(_UrlBuilder, "UrlBuilder");
511
- var UrlBuilder = _UrlBuilder;
512
-
513
- // src/tools/OpenapiViewer/utils/schemaExport.ts
514
- function dereferenceSchema(schema, maxDepth = 10) {
515
- const root = schema;
516
- function resolveRef(ref) {
517
- if (!ref.startsWith("#/")) return null;
518
- const parts = ref.slice(2).split("/");
519
- let node = root;
520
- for (const part of parts) {
521
- if (node && typeof node === "object" && part in node) {
522
- node = node[part];
523
- } else {
524
- return null;
525
- }
526
- }
527
- return node;
528
- }
529
- __name(resolveRef, "resolveRef");
530
- function walk(value, depth) {
531
- if (depth > maxDepth) return value;
532
- if (Array.isArray(value)) return value.map((v) => walk(v, depth + 1));
533
- if (value && typeof value === "object") {
534
- const obj = value;
535
- if (typeof obj.$ref === "string") {
536
- const resolved = resolveRef(obj.$ref);
537
- if (resolved === null) return obj;
538
- return walk(resolved, depth + 1);
539
- }
540
- const out = {};
541
- for (const [k, v] of Object.entries(obj)) out[k] = walk(v, depth + 1);
542
- return out;
543
- }
544
- return value;
545
- }
546
- __name(walk, "walk");
547
- return walk(schema, 0);
548
- }
549
- __name(dereferenceSchema, "dereferenceSchema");
550
- var NOISY_KEYS = /* @__PURE__ */ new Set(["xml", "example", "examples", "externalDocs"]);
551
- var MAX_DESCRIPTION_LEN = 500;
552
- function pruneForCompact(value) {
553
- if (Array.isArray(value)) return value.map(pruneForCompact);
554
- if (value && typeof value === "object") {
555
- const out = {};
556
- for (const [k, v] of Object.entries(value)) {
557
- if (NOISY_KEYS.has(k)) continue;
558
- if (k === "description" && typeof v === "string" && v.length > MAX_DESCRIPTION_LEN) {
559
- out[k] = v.slice(0, MAX_DESCRIPTION_LEN).trimEnd() + "\u2026";
560
- continue;
561
- }
562
- out[k] = pruneForCompact(v);
563
- }
564
- return out;
565
- }
566
- return value;
567
- }
568
- __name(pruneForCompact, "pruneForCompact");
569
- function withResolvedBaseUrl(schema, baseUrl) {
570
- if (!baseUrl) return schema;
571
- return { ...schema, servers: [{ url: baseUrl }] };
572
- }
573
- __name(withResolvedBaseUrl, "withResolvedBaseUrl");
574
- function toRawJson(schema, baseUrl) {
575
- return JSON.stringify(withResolvedBaseUrl(schema, baseUrl), null, 2);
576
- }
577
- __name(toRawJson, "toRawJson");
578
- function toCompactJson(schema, baseUrl) {
579
- const resolved = dereferenceSchema(withResolvedBaseUrl(schema, baseUrl));
580
- const pruned = pruneForCompact(resolved);
581
- return JSON.stringify(pruned);
582
- }
583
- __name(toCompactJson, "toCompactJson");
584
- function endpointToMarkdown(ep) {
585
- const lines = [];
586
- lines.push(`### ${ep.method} ${ep.path}`);
587
- if (ep.description) lines.push(ep.description);
588
- const pathParams = ep.parameters?.filter((p) => ep.path.includes(`{${p.name}}`)) ?? [];
589
- const queryParams = ep.parameters?.filter((p) => !ep.path.includes(`{${p.name}}`)) ?? [];
590
- if (pathParams.length > 0) {
591
- lines.push("", "**Path parameters**");
592
- for (const p of pathParams) {
593
- const req = p.required ? " (required)" : "";
594
- const desc = p.description ? ` \u2014 ${p.description}` : "";
595
- lines.push(`- \`${p.name}\`: ${p.type}${req}${desc}`);
596
- }
597
- }
598
- if (queryParams.length > 0) {
599
- lines.push("", "**Query parameters**");
600
- for (const p of queryParams) {
601
- const req = p.required ? " (required)" : "";
602
- const desc = p.description ? ` \u2014 ${p.description}` : "";
603
- lines.push(`- \`${p.name}\`: ${p.type}${req}${desc}`);
604
- }
605
- }
606
- if (ep.requestBody) {
607
- const desc = ep.requestBody.description ? ` \u2014 ${ep.requestBody.description}` : "";
608
- lines.push("", `**Request body:** ${ep.requestBody.type}${desc}`);
609
- }
610
- if (ep.responses && ep.responses.length > 0) {
611
- lines.push("", "**Responses**");
612
- for (const r of ep.responses) {
613
- lines.push(`- \`${r.code}\` \u2014 ${r.description}`);
614
- }
615
- }
616
- return lines.join("\n");
617
- }
618
- __name(endpointToMarkdown, "endpointToMarkdown");
619
- function toMarkdown(schema, endpoints, baseUrl) {
620
- const lines = [];
621
- const info = schema.info;
622
- const resolvedBase = resolveBaseUrl({
623
- config: baseUrl,
624
- fromServers: schema.servers?.[0]?.url
625
- });
626
- lines.push(`# ${info?.title ?? "API"}${info?.version ? ` (v${info.version})` : ""}`);
627
- if (resolvedBase) lines.push("", `**Base URL:** \`${resolvedBase}\``);
628
- if (info?.description) lines.push("", info.description.trim());
629
- const grouped = /* @__PURE__ */ new Map();
630
- for (const ep of endpoints) {
631
- const arr = grouped.get(ep.category) ?? [];
632
- arr.push(ep);
633
- grouped.set(ep.category, arr);
634
- }
635
- const categories = Array.from(grouped.keys()).sort((a, b) => {
636
- if (a === "Other") return 1;
637
- if (b === "Other") return -1;
638
- return a.localeCompare(b);
639
- });
640
- for (const category of categories) {
641
- lines.push("", `## ${category}`);
642
- const list = grouped.get(category);
643
- for (const ep of list) {
644
- const displayPath = relativePath(ep.path);
645
- const sub = endpointToMarkdown({ ...ep, path: displayPath });
646
- lines.push("", sub);
647
- }
648
- }
649
- return lines.join("\n");
650
- }
651
- __name(toMarkdown, "toMarkdown");
652
- function formatBytes(s) {
653
- const bytes = new Blob([s]).size;
654
- if (bytes < 1024) return `${bytes} B`;
655
- if (bytes < 1024 * 1024) return `${(bytes / 1024).toFixed(1)} KB`;
656
- return `${(bytes / 1024 / 1024).toFixed(2)} MB`;
657
- }
658
- __name(formatBytes, "formatBytes");
659
- var AUTH_KEY_STORAGE = "openapi-playground:auth:apiKeyId";
660
- var AUTH_BEARER_STORAGE = "openapi-playground:auth:bearer";
661
- var createInitialState = /* @__PURE__ */ __name(() => ({
662
- currentStep: "endpoints",
663
- steps: ["endpoints", "request", "response"],
664
- selectedEndpoint: null,
665
- selectedCategory: "All",
666
- searchTerm: "",
667
- selectedVersion: getDefaultVersion().id,
668
- requestUrl: "",
669
- requestMethod: "GET",
670
- requestHeaders: '{\n "Content-Type": "application/json"\n}',
671
- requestBody: "",
672
- selectedApiKey: null,
673
- manualApiToken: "",
674
- parameters: {},
675
- response: null,
676
- loading: false,
677
- sidebarOpen: false,
678
- activeSchemaId: null
679
- }), "createInitialState");
680
- function reducer(state, action) {
681
- switch (action.type) {
682
- case "SET_STEP":
683
- return { ...state, currentStep: action.step };
684
- case "NEXT_STEP": {
685
- const i = state.steps.indexOf(state.currentStep);
686
- return i < state.steps.length - 1 ? { ...state, currentStep: state.steps[i + 1] } : state;
687
- }
688
- case "PREV_STEP": {
689
- const i = state.steps.indexOf(state.currentStep);
690
- return i > 0 ? { ...state, currentStep: state.steps[i - 1] } : state;
691
- }
692
- case "SELECT_ENDPOINT": {
693
- if (!action.endpoint) return { ...state, selectedEndpoint: null };
694
- const same = state.selectedEndpoint?.method === action.endpoint.method && state.selectedEndpoint?.path === action.endpoint.path;
695
- const exampleBody = action.endpoint.requestBody?.example ?? "";
696
- return {
697
- ...state,
698
- selectedEndpoint: action.endpoint,
699
- requestMethod: action.endpoint.method,
700
- requestUrl: action.endpoint.path,
701
- parameters: same ? state.parameters : {},
702
- requestBody: same ? state.requestBody : exampleBody,
703
- // Switching to a different endpoint: the previous response no
704
- // longer belongs here. Clear it so the playground panel collapses
705
- // back to single-column until the user sends a new request.
706
- response: same ? state.response : null,
707
- currentStep: "request"
708
- };
709
- }
710
- case "SET_CATEGORY":
711
- return { ...state, selectedCategory: action.category };
712
- case "SET_SEARCH":
713
- return { ...state, searchTerm: action.term };
714
- case "SET_VERSION":
715
- return { ...state, selectedVersion: action.version };
716
- case "SET_REQUEST_URL":
717
- return { ...state, requestUrl: action.url };
718
- case "SET_REQUEST_METHOD":
719
- return { ...state, requestMethod: action.method };
720
- case "SET_REQUEST_HEADERS":
721
- return { ...state, requestHeaders: action.headers };
722
- case "SET_REQUEST_BODY":
723
- return { ...state, requestBody: action.body };
724
- case "SET_API_KEY":
725
- return { ...state, selectedApiKey: action.apiKeyId };
726
- case "SET_MANUAL_TOKEN":
727
- return { ...state, manualApiToken: action.token };
728
- case "SET_PARAMETERS":
729
- return { ...state, parameters: action.parameters };
730
- case "SET_RESPONSE":
731
- return { ...state, response: action.response };
732
- case "SET_LOADING":
733
- return { ...state, loading: action.loading };
734
- case "REQUEST_START":
735
- return { ...state, loading: true, response: null };
736
- case "REQUEST_SUCCESS":
737
- return { ...state, loading: false, response: action.response, currentStep: "response" };
738
- case "REQUEST_ERROR":
739
- return { ...state, loading: false, response: action.response };
740
- case "SET_SIDEBAR":
741
- return { ...state, sidebarOpen: action.open };
742
- case "SET_ACTIVE_SCHEMA_ID":
743
- return { ...state, activeSchemaId: action.id };
744
- case "SYNC_API_KEY_HEADER":
745
- return { ...state, requestHeaders: action.headers };
746
- case "CLEAR_API_KEY_SELECTION":
747
- return { ...state, selectedApiKey: null };
748
- case "SYNC_URL":
749
- return { ...state, requestUrl: action.url };
750
- case "RESET":
751
- return createInitialState();
752
- default:
753
- return state;
754
- }
755
- }
756
- __name(reducer, "reducer");
757
- var PlaygroundContext = createContext(void 0);
758
- var usePlaygroundContext = /* @__PURE__ */ __name(() => {
759
- const context = useContext(PlaygroundContext);
760
- if (!context) throw new Error("usePlaygroundContext must be used within a PlaygroundProvider");
761
- return context;
762
- }, "usePlaygroundContext");
763
- var PlaygroundProvider = /* @__PURE__ */ __name(({ children, config }) => {
764
- const [state, dispatch] = useReducer(reducer, void 0, createInitialState);
765
- const abortControllerRef = useRef(null);
766
- const apiKeys = React.useMemo(
767
- () => config.apiKeys ?? [],
768
- [config.apiKeys]
769
- );
770
- const isLoadingApiKeys = config.apiKeysLoading ?? false;
771
- const [storedApiKeyId, setStoredApiKeyId] = useSessionStorage(
772
- AUTH_KEY_STORAGE,
773
- null
774
- );
775
- const [storedBearer, setStoredBearer] = useSessionStorage(
776
- AUTH_BEARER_STORAGE,
777
- ""
778
- );
779
- const hasHydratedAuthRef = useRef(false);
780
- useEffect(() => {
781
- if (hasHydratedAuthRef.current) return;
782
- hasHydratedAuthRef.current = true;
783
- if (storedApiKeyId) dispatch({ type: "SET_API_KEY", apiKeyId: storedApiKeyId });
784
- if (storedBearer) dispatch({ type: "SET_MANUAL_TOKEN", token: storedBearer });
785
- }, []);
786
- useEffect(() => {
787
- if (!hasHydratedAuthRef.current) return;
788
- setStoredApiKeyId(state.selectedApiKey);
789
- }, [state.selectedApiKey, setStoredApiKeyId]);
790
- useEffect(() => {
791
- if (!hasHydratedAuthRef.current) return;
792
- setStoredBearer(state.manualApiToken);
793
- }, [state.manualApiToken, setStoredBearer]);
794
- useEffect(() => {
795
- if (!hasHydratedAuthRef.current) return;
796
- if (!isLoadingApiKeys && apiKeys.length > 0 && !state.selectedApiKey && !storedApiKeyId) {
797
- dispatch({ type: "SET_API_KEY", apiKeyId: apiKeys[0]?.id || null });
798
- }
799
- }, [apiKeys, isLoadingApiKeys, state.selectedApiKey, storedApiKeyId]);
800
- useEffect(() => {
801
- try {
802
- const headers = parseRequestHeaders(state.requestHeaders);
803
- if (state.selectedApiKey) {
804
- const apiKey = apiKeys.find((k) => k.id === state.selectedApiKey);
805
- if (!apiKey) {
806
- dispatch({ type: "CLEAR_API_KEY_SELECTION" });
807
- return;
808
- }
809
- const keyValue = apiKey.secret || apiKey.id;
810
- if (headers["X-API-Key"] !== keyValue) {
811
- headers["X-API-Key"] = keyValue;
812
- dispatch({ type: "SYNC_API_KEY_HEADER", headers: JSON.stringify(headers, null, 2) });
813
- }
814
- } else if (headers["X-API-Key"]) {
815
- delete headers["X-API-Key"];
816
- dispatch({ type: "SYNC_API_KEY_HEADER", headers: JSON.stringify(headers, null, 2) });
817
- }
818
- } catch (error) {
819
- consola2.error("Error updating headers:", error);
820
- }
821
- }, [state.selectedApiKey, apiKeys]);
822
- useEffect(() => {
823
- if (!state.selectedEndpoint) return;
824
- const updated = new UrlBuilder(state.selectedEndpoint, state.parameters).build();
825
- if (updated !== state.requestUrl) {
826
- dispatch({ type: "SYNC_URL", url: updated });
827
- }
828
- }, [state.parameters, state.selectedEndpoint]);
829
- const setCurrentStep = useCallback((step) => dispatch({ type: "SET_STEP", step }), []);
830
- const goToNextStep = useCallback(() => dispatch({ type: "NEXT_STEP" }), []);
831
- const goToPreviousStep = useCallback(() => dispatch({ type: "PREV_STEP" }), []);
832
- const setSelectedEndpoint = useCallback((endpoint) => dispatch({ type: "SELECT_ENDPOINT", endpoint }), []);
833
- const setSelectedCategory = useCallback((category) => dispatch({ type: "SET_CATEGORY", category }), []);
834
- const setSearchTerm = useCallback((term) => dispatch({ type: "SET_SEARCH", term }), []);
835
- const setSelectedVersion = useCallback((version) => dispatch({ type: "SET_VERSION", version }), []);
836
- const setRequestUrl = useCallback((url) => dispatch({ type: "SET_REQUEST_URL", url }), []);
837
- const setRequestMethod = useCallback((method) => dispatch({ type: "SET_REQUEST_METHOD", method }), []);
838
- const setRequestHeaders = useCallback((headers) => dispatch({ type: "SET_REQUEST_HEADERS", headers }), []);
839
- const setRequestBody = useCallback((body) => dispatch({ type: "SET_REQUEST_BODY", body }), []);
840
- const setSelectedApiKey = useCallback((apiKeyId) => dispatch({ type: "SET_API_KEY", apiKeyId }), []);
841
- const setManualApiToken = useCallback((token) => dispatch({ type: "SET_MANUAL_TOKEN", token }), []);
842
- const setParameters = useCallback((parameters) => dispatch({ type: "SET_PARAMETERS", parameters }), []);
843
- const setResponse = useCallback((response) => dispatch({ type: "SET_RESPONSE", response }), []);
844
- const setLoading = useCallback((loading) => dispatch({ type: "SET_LOADING", loading }), []);
845
- const setSidebarOpen = useCallback((open) => dispatch({ type: "SET_SIDEBAR", open }), []);
846
- const setActiveSchemaId = useCallback((id) => dispatch({ type: "SET_ACTIVE_SCHEMA_ID", id }), []);
847
- const clearAll = useCallback(() => dispatch({ type: "RESET" }), []);
848
- const sendRequest = useCallback(async () => {
849
- if (!state.requestUrl) {
850
- consola2.error("No URL provided");
851
- return;
852
- }
853
- abortControllerRef.current?.abort();
854
- const controller = new AbortController();
855
- abortControllerRef.current = controller;
856
- dispatch({ type: "REQUEST_START" });
857
- const startTime = Date.now();
858
- try {
859
- const headers = parseRequestHeaders(state.requestHeaders);
860
- let bearerToken = null;
861
- if (state.manualApiToken) {
862
- bearerToken = state.manualApiToken;
863
- } else if (typeof window !== "undefined") {
864
- bearerToken = window.localStorage.getItem("auth_token");
865
- }
866
- if (bearerToken) headers["Authorization"] = `Bearer ${bearerToken}`;
867
- const requestOptions = {
868
- method: state.requestMethod,
869
- headers,
870
- signal: controller.signal
871
- };
872
- if (state.requestBody && state.requestMethod !== "GET") {
873
- requestOptions.body = state.requestBody;
874
- }
875
- const response = await fetch(state.requestUrl, requestOptions);
876
- const duration = Date.now() - startTime;
877
- const responseText = await response.text();
878
- let responseData;
879
- try {
880
- responseData = JSON.parse(responseText);
881
- } catch {
882
- responseData = responseText;
883
- }
884
- dispatch({
885
- type: "REQUEST_SUCCESS",
886
- response: {
887
- status: response.status,
888
- statusText: response.statusText,
889
- headers: Object.fromEntries(response.headers.entries()),
890
- data: responseData,
891
- duration
892
- }
893
- });
894
- consola2.success(`${state.requestMethod} ${state.requestUrl} \u2192 ${response.status} (${duration}ms)`);
895
- } catch (error) {
896
- if (error instanceof DOMException && error.name === "AbortError") return;
897
- consola2.error("Request failed:", error);
898
- dispatch({
899
- type: "REQUEST_ERROR",
900
- response: {
901
- error: error instanceof Error ? error.message : "Request failed",
902
- duration: Date.now() - startTime
903
- }
904
- });
905
- }
906
- }, [state.requestUrl, state.requestHeaders, state.manualApiToken, state.requestMethod, state.requestBody]);
907
- const contextValue = {
908
- state,
909
- config,
910
- apiKeys,
911
- apiKeysLoading: isLoadingApiKeys,
912
- setCurrentStep,
913
- goToNextStep,
914
- goToPreviousStep,
915
- setSelectedEndpoint,
916
- setSelectedCategory,
917
- setSearchTerm,
918
- setSelectedVersion,
919
- setRequestUrl,
920
- setRequestMethod,
921
- setRequestHeaders,
922
- setRequestBody,
923
- setSelectedApiKey,
924
- setManualApiToken,
925
- setParameters,
926
- setResponse,
927
- setLoading,
928
- setSidebarOpen,
929
- setActiveSchemaId,
930
- clearAll,
931
- sendRequest
932
- };
933
- return /* @__PURE__ */ jsx(PlaygroundContext.Provider, { value: contextValue, children });
934
- }, "PlaygroundProvider");
935
-
936
- export { CODE_SAMPLE_TARGETS, PlaygroundProvider, UrlBuilder, buildHarRequest, deduplicateEndpoints, dereferenceSchema, endpointToMarkdown, findApiKeyById, formatBytes, isValidJson, joinUrl, parseRequestHeaders, relativePath, renderSnippet, resolveAbsolute, resolveBaseUrl, sampleSchemaJson, toCompactJson, toMarkdown, toRawJson, usePlaygroundContext };
937
- //# sourceMappingURL=chunk-Y6UTOBF6.mjs.map
938
- //# sourceMappingURL=chunk-Y6UTOBF6.mjs.map