fumadocs-openapi 12.4.2 → 12.5.0

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 (37) hide show
  1. package/css/generated/shared.css +1 -1
  2. package/dist/.translations/index.d.ts +12 -1
  3. package/dist/.translations/keys.js +12 -1
  4. package/dist/generate-file.js +3 -1
  5. package/dist/index.browser.d.ts +2 -2
  6. package/dist/index.d.ts +3 -2
  7. package/dist/operation.js +2 -2
  8. package/dist/packages/shared-api/dist/codegen.js +1 -3
  9. package/dist/packages/shared-api/dist/components/schema/client.js +1 -1
  10. package/dist/playground/auth.d.ts +84 -30
  11. package/dist/playground/auth.js +250 -150
  12. package/dist/playground/fetcher.js +11 -6
  13. package/dist/playground/index.d.ts +2 -2
  14. package/dist/playground/index.js +2 -2
  15. package/dist/playground/use-playground.d.ts +3 -3
  16. package/dist/playground/use-playground.js +46 -31
  17. package/dist/requests/generators/python.d.ts +0 -1
  18. package/dist/requests/generators/python.js +1 -1
  19. package/dist/server/index.d.ts +2 -9
  20. package/dist/server/index.js +0 -4
  21. package/dist/server/proxy.d.ts +5 -4
  22. package/dist/server/proxy.js +105 -25
  23. package/dist/types/openapi.d.ts +7 -2
  24. package/dist/types.d.ts +1 -0
  25. package/dist/ui/operation/index.js +48 -27
  26. package/dist/ui/operation/usage-tabs.js +251 -34
  27. package/dist/ui/playground/client.js +8 -4
  28. package/dist/ui/playground/components/oauth-panel.js +150 -39
  29. package/dist/ui/playground/components/request-panel.js +18 -3
  30. package/dist/ui/playground/components/response-panel.js +53 -90
  31. package/dist/utils/create-page.d.ts +1 -1
  32. package/dist/utils/pages/to-static-data.d.ts +12 -0
  33. package/dist/utils/use-server.js +1 -1
  34. package/package.json +7 -6
  35. package/dist/packages/shared-api/dist/components/accordion.js +0 -63
  36. package/dist/ui/operation/request-tabs.js +0 -92
  37. package/dist/ui/operation/response-tabs.js +0 -53
@@ -1,42 +1,42 @@
1
1
  "use client";
2
- import { useCodeUsage, useExampleRequests, useOperation } from "../../operation.js";
3
- import { useRenderContext } from "../../utils/create-page.js";
2
+ import { useCodeUsage, useExampleRequests, useOperation, useResponseExamples } from "../../operation.js";
3
+ import { useOpenAPI, useRenderContext } from "../../utils/create-page.js";
4
+ import { MethodLabel } from "../components/method-label.js";
4
5
  import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "../../packages/shared-api/dist/components/select.js";
5
6
  import { ClientCodeBlock } from "../components/codeblock.js";
6
- import { ResponseTabs } from "./response-tabs.js";
7
- import { jsx, jsxs } from "react/jsx-runtime";
8
- import { CodeBlockTab, CodeBlockTabs, CodeBlockTabsList, CodeBlockTabsTrigger } from "fumadocs-ui/components/codeblock";
7
+ import { Markdown } from "../components/markdown.js";
8
+ import { cn } from "../../utils/cn.js";
9
+ import { useState, useSyncExternalStore } from "react";
10
+ import { getRaw } from "@scalar/json-magic/magic-proxy";
11
+ import { Fragment as Fragment$1, jsx, jsxs } from "react/jsx-runtime";
12
+ import { useTranslations } from "@fuma-translate/react";
13
+ import { Switch } from "@base-ui/react/switch";
9
14
  //#region src/ui/operation/usage-tabs.tsx
15
+ /** a code block filling its card */
16
+ const cardCodeBlock = {
17
+ className: "flex min-h-0 flex-col rounded-none border-0 bg-transparent shadow-none",
18
+ viewportProps: { className: "min-h-0" }
19
+ };
20
+ /** a code block under its caption */
21
+ const captionedCodeBlock = {
22
+ ...cardCodeBlock,
23
+ viewportProps: { className: "min-h-0 pt-2" }
24
+ };
10
25
  function UsageTabs() {
11
26
  const ctx = useRenderContext();
27
+ const t = useTranslations({ note: "operation page" });
12
28
  const { operation, codeUsages } = useOperation();
13
- let usageTabs;
14
- if (ctx.content?.renderAPIExampleUsageTabs) usageTabs = ctx.content.renderAPIExampleUsageTabs(codeUsages, ctx);
15
- else {
16
- const items = Array.from(codeUsages.map());
17
- usageTabs = items.length > 0 && /* @__PURE__ */ jsxs(CodeBlockTabs, {
18
- groupId: "fumadocs_openapi_requests",
19
- defaultValue: items[0][0],
20
- children: [/* @__PURE__ */ jsx(CodeBlockTabsList, { children: items.map(([id, item]) => /* @__PURE__ */ jsx(CodeBlockTabsTrigger, {
21
- value: id,
22
- children: item.label ?? item.lang
23
- }, id)) }), items.map(([id, item]) => /* @__PURE__ */ jsx(CodeBlockTab, {
24
- value: id,
25
- children: /* @__PURE__ */ jsx(UsageTab, {
26
- id,
27
- lang: item.lang
28
- })
29
- }, id))]
30
- });
31
- }
32
29
  const slots = {
33
30
  selector: operation["x-exclusiveCodeSample"] ? null : /* @__PURE__ */ jsx(UsageTabsSelector, {}),
34
- usageTabs,
31
+ usageTabs: ctx.content?.renderAPIExampleUsageTabs ? ctx.content.renderAPIExampleUsageTabs(codeUsages, ctx) : /* @__PURE__ */ jsx(CodeUsages, {
32
+ title: t("Example Request"),
33
+ className: "mb-4 flex min-h-0 flex-col overflow-hidden rounded-xl border bg-fd-card"
34
+ }),
35
35
  responseTabs: /* @__PURE__ */ jsx(ResponseTabs, {})
36
36
  };
37
37
  if (ctx.content?.renderAPIExampleLayout) return ctx.content.renderAPIExampleLayout(slots, ctx);
38
38
  return /* @__PURE__ */ jsxs("div", {
39
- className: "prose-no-margin",
39
+ className: "flex min-h-0 flex-col prose-no-margin",
40
40
  children: [
41
41
  slots.selector,
42
42
  slots.usageTabs,
@@ -65,7 +65,7 @@ function UsageTabsSelector() {
65
65
  value: selected,
66
66
  onValueChange: (v) => v !== null && select(v),
67
67
  children: [/* @__PURE__ */ jsx(SelectTrigger, {
68
- className: "not-prose mb-2",
68
+ className: "not-prose mb-4 rounded-xl bg-fd-card px-3",
69
69
  children: /* @__PURE__ */ jsx(SelectValue, {})
70
70
  }), /* @__PURE__ */ jsx(SelectContent, { children: options.map((item) => /* @__PURE__ */ jsx(SelectItem, {
71
71
  value: item.value,
@@ -73,13 +73,230 @@ function UsageTabsSelector() {
73
73
  }, item.value)) })]
74
74
  });
75
75
  }
76
- function UsageTab({ id, lang }) {
77
- const code = useCodeUsage(id);
78
- if (!code) return null;
79
- return /* @__PURE__ */ jsx(ClientCodeBlock, {
80
- lang,
81
- code
76
+ function ExampleHeader({ title, children }) {
77
+ return /* @__PURE__ */ jsxs("div", {
78
+ className: "flex h-10 shrink-0 items-center gap-2 border-b ps-4 pe-1.5 text-[0.8125rem] font-medium",
79
+ children: [/* @__PURE__ */ jsx("span", {
80
+ className: "me-auto truncate",
81
+ children: title
82
+ }), children]
83
+ });
84
+ }
85
+ function ExampleSelect({ items, value, onValueChange, className }) {
86
+ return /* @__PURE__ */ jsxs(Select, {
87
+ items,
88
+ value,
89
+ onValueChange: (v) => v !== null && onValueChange(v),
90
+ children: [/* @__PURE__ */ jsx(SelectTrigger, {
91
+ className: cn("h-7 w-fit max-w-1/2 shrink-0 gap-1.5 border-0 bg-transparent px-2 py-0 text-[0.8125rem] font-medium text-fd-muted-foreground hover:text-fd-accent-foreground focus:ring-0 focus-visible:ring-2 data-popup-open:bg-fd-accent data-popup-open:text-fd-accent-foreground", className),
92
+ children: /* @__PURE__ */ jsx(SelectValue, { className: "min-w-0 truncate" })
93
+ }), /* @__PURE__ */ jsx(SelectContent, {
94
+ align: "end",
95
+ children: items.map((item) => /* @__PURE__ */ jsx(SelectItem, {
96
+ value: item.value,
97
+ className: "text-[0.8125rem]",
98
+ children: item.label
99
+ }, item.value))
100
+ })]
101
+ });
102
+ }
103
+ const storageKey = "fumadocs_openapi_requests";
104
+ const listeners = /* @__PURE__ */ new Set();
105
+ function subscribe(listener) {
106
+ listeners.add(listener);
107
+ return () => {
108
+ listeners.delete(listener);
109
+ };
110
+ }
111
+ function select(id) {
112
+ sessionStorage.setItem(storageKey, id);
113
+ for (const listener of listeners) listener();
114
+ }
115
+ /** the code usages of the selected example request, with a select of their languages */
116
+ function CodeUsages({ title, className, viewportClassName }) {
117
+ const generators = useOperation().codeUsages.map();
118
+ const selected = useSyncExternalStore(subscribe, () => sessionStorage.getItem(storageKey), () => null);
119
+ const id = selected !== null && generators.has(selected) ? selected : generators.keys().next().value;
120
+ const code = useCodeUsage(id ?? "");
121
+ if (id === void 0) return null;
122
+ const items = Array.from(generators, ([value, item]) => ({
123
+ value,
124
+ label: item.label ?? item.lang
125
+ }));
126
+ return /* @__PURE__ */ jsxs("div", {
127
+ className,
128
+ children: [/* @__PURE__ */ jsx(ExampleHeader, {
129
+ title,
130
+ children: items.length > 1 ? /* @__PURE__ */ jsx(ExampleSelect, {
131
+ items,
132
+ value: id,
133
+ onValueChange: select
134
+ }) : /* @__PURE__ */ jsx("span", {
135
+ className: "px-2 text-fd-muted-foreground",
136
+ children: items[0].label
137
+ })
138
+ }), code && /* @__PURE__ */ jsx(ClientCodeBlock, {
139
+ lang: generators.get(id).lang,
140
+ code,
141
+ codeblock: {
142
+ ...cardCodeBlock,
143
+ viewportProps: { className: cn(cardCodeBlock.viewportProps.className, viewportClassName) }
144
+ }
145
+ })]
146
+ });
147
+ }
148
+ function ResponseTabs() {
149
+ const ctx = useRenderContext();
150
+ const tabs = useResponseExamples();
151
+ if (tabs.length === 0) return null;
152
+ if (ctx.content?.renderResponseTabs) return ctx.content.renderResponseTabs({ tabs }, ctx);
153
+ return /* @__PURE__ */ jsx(ResponseTabsDefaultContent, { tabs });
154
+ }
155
+ function ResponseTabsDefaultContent({ tabs }) {
156
+ const t = useTranslations({ note: "operation page" });
157
+ const { resolve } = useOpenAPI().doc;
158
+ const [code, setCode] = useState(tabs[0].code);
159
+ const [index, setIndex] = useState(0);
160
+ const [showSchema, setShowSchema] = useState(false);
161
+ const tab = tabs.find((item) => item.code === code) ?? tabs[0];
162
+ const examples = tab.examples ?? [];
163
+ const example = examples.at(index);
164
+ const schema = tab.mediaType ? resolve(tab.response.content?.[tab.mediaType])?.schema : void 0;
165
+ let body;
166
+ if (showSchema && schema !== void 0) body = /* @__PURE__ */ jsx(ClientCodeBlock, {
167
+ lang: "json",
168
+ code: JSON.stringify(resolve(schema), (_, value) => getRaw(value), 2),
169
+ codeblock: cardCodeBlock
170
+ });
171
+ else if (example) {
172
+ const captioned = examples.length > 1 || example.description !== void 0;
173
+ body = /* @__PURE__ */ jsxs(Fragment$1, { children: [captioned && /* @__PURE__ */ jsxs("div", {
174
+ className: "shrink-0 px-4 pt-2.5",
175
+ children: [examples.length > 1 && /* @__PURE__ */ jsx(ExampleSelect, {
176
+ items: examples.map((item, i) => ({
177
+ value: String(i),
178
+ label: item.label
179
+ })),
180
+ value: String(index),
181
+ onValueChange: (v) => setIndex(Number(v)),
182
+ className: "-ms-2"
183
+ }), example.description && /* @__PURE__ */ jsx("div", {
184
+ className: "prose prose-xs prose-no-margin text-fd-muted-foreground",
185
+ children: /* @__PURE__ */ jsx(Markdown, { md: example.description })
186
+ })]
187
+ }), /* @__PURE__ */ jsx(ClientCodeBlock, {
188
+ lang: "json",
189
+ code: JSON.stringify(example.sample, null, 2),
190
+ codeblock: captioned ? captionedCodeBlock : cardCodeBlock
191
+ })] });
192
+ } else body = /* @__PURE__ */ jsx("div", {
193
+ className: "px-4 py-3 text-sm text-fd-muted-foreground",
194
+ children: t("Empty")
195
+ });
196
+ return /* @__PURE__ */ jsxs("div", {
197
+ className: "mb-4 flex min-h-0 flex-col overflow-hidden rounded-xl border bg-fd-card",
198
+ children: [/* @__PURE__ */ jsxs(ExampleHeader, {
199
+ title: t("Example Response"),
200
+ children: [schema !== void 0 && /* @__PURE__ */ jsxs("label", {
201
+ className: "flex shrink-0 items-center gap-2 text-fd-muted-foreground",
202
+ children: [t("Schema"), /* @__PURE__ */ jsx(Switch.Root, {
203
+ checked: showSchema,
204
+ onCheckedChange: setShowSchema,
205
+ className: "inline-flex h-4 w-7 shrink-0 items-center rounded-full bg-fd-accent p-0.5 transition-colors focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-fd-ring data-checked:bg-fd-primary motion-reduce:transition-none",
206
+ children: /* @__PURE__ */ jsx(Switch.Thumb, { className: "size-3 rounded-full bg-fd-muted-foreground transition-[translate,background-color] duration-200 ease-[cubic-bezier(0.16,1,0.3,1)] data-checked:translate-x-3 data-checked:bg-fd-primary-foreground motion-reduce:transition-none" })
207
+ })]
208
+ }), /* @__PURE__ */ jsx(ExampleSelect, {
209
+ items: tabs.map((item) => ({
210
+ value: item.code,
211
+ label: item.code
212
+ })),
213
+ value: tab.code,
214
+ onValueChange: (v) => {
215
+ setCode(v);
216
+ setIndex(0);
217
+ }
218
+ })]
219
+ }), body]
220
+ });
221
+ }
222
+ /** the example requests of a webhook */
223
+ function RequestTabs() {
224
+ const ctx = useRenderContext();
225
+ const { path, method, operation, pathItem } = useOperation();
226
+ const { items } = useExampleRequests();
227
+ if (!operation.requestBody) return null;
228
+ if (ctx.content?.renderRequestTabs) return ctx.content.renderRequestTabs({
229
+ items,
230
+ route: path,
231
+ method,
232
+ pathItem,
233
+ operation
234
+ }, ctx);
235
+ return /* @__PURE__ */ jsx(RequestTabsDefaultContent, {});
236
+ }
237
+ function RequestTabsDefaultContent() {
238
+ const t = useTranslations({ note: "operation page" });
239
+ const { items, selected, select } = useExampleRequests();
240
+ const item = items.find((item) => item.id === selected) ?? items[0];
241
+ const requestData = item.data;
242
+ const displayNames = {
243
+ body: t("Request Body"),
244
+ cookie: t("Cookie Parameters"),
245
+ header: t("Header Parameters"),
246
+ query: t("Query Parameters"),
247
+ path: t("Path Parameters")
248
+ };
249
+ return /* @__PURE__ */ jsxs("div", {
250
+ className: "flex min-h-0 flex-col overflow-hidden rounded-xl border bg-fd-card",
251
+ children: [
252
+ /* @__PURE__ */ jsx(ExampleHeader, {
253
+ title: t("Example Requests"),
254
+ children: items.length > 1 && /* @__PURE__ */ jsx(ExampleSelect, {
255
+ items: items.map((item) => ({
256
+ value: item.id,
257
+ label: item.id === "_default" ? t("Default") : item.name
258
+ })),
259
+ value: item.id,
260
+ onValueChange: select
261
+ })
262
+ }),
263
+ /* @__PURE__ */ jsxs("div", {
264
+ className: "shrink-0 px-4 py-3 text-[0.8125rem]",
265
+ children: [
266
+ /* @__PURE__ */ jsx(MethodLabel, {
267
+ className: "me-2 text-xs",
268
+ children: requestData.method
269
+ }),
270
+ /* @__PURE__ */ jsx("span", {
271
+ className: "font-mono",
272
+ children: item.pathname
273
+ }),
274
+ item.description && /* @__PURE__ */ jsx("div", {
275
+ className: "prose prose-xs prose-no-margin mt-1 text-fd-muted-foreground",
276
+ children: /* @__PURE__ */ jsx(Markdown, { md: item.description })
277
+ })
278
+ ]
279
+ }),
280
+ Object.entries(displayNames).map(([k, v]) => {
281
+ const data = requestData[k];
282
+ if (!data || Object.keys(data).length === 0) return;
283
+ return /* @__PURE__ */ jsxs("div", {
284
+ className: "flex min-h-0 flex-col border-t",
285
+ children: [/* @__PURE__ */ jsxs("div", {
286
+ className: "flex shrink-0 px-4 pt-3 text-xs font-medium text-fd-muted-foreground",
287
+ children: [v, k === "body" && /* @__PURE__ */ jsx("span", {
288
+ className: "ms-auto font-mono font-normal",
289
+ children: requestData.bodyMediaType
290
+ })]
291
+ }), /* @__PURE__ */ jsx(ClientCodeBlock, {
292
+ lang: "json",
293
+ code: JSON.stringify(data, null, 2),
294
+ codeblock: captionedCodeBlock
295
+ })]
296
+ }, k);
297
+ })
298
+ ]
82
299
  });
83
300
  }
84
301
  //#endregion
85
- export { UsageTabs };
302
+ export { CodeUsages, ExampleSelect, RequestTabs, UsageTabs };
@@ -10,29 +10,33 @@ import { EndpointBar } from "../components/endpoint.js";
10
10
  import { DialogPopup } from "../components/dialog.js";
11
11
  import { SchemaProvider } from "../../packages/shared-api/dist/components/playground/schema.js";
12
12
  import { UrlBar } from "./components/url-bar.js";
13
- import { RequestPanel } from "./components/request-panel.js";
13
+ import { RequestPanel, mutualTLSProvider } from "./components/request-panel.js";
14
14
  import { oauthPanelProvider } from "./components/oauth-panel.js";
15
15
  import { ResponsePanel } from "./components/response-panel.js";
16
16
  import { useMemo, useState } from "react";
17
17
  import { jsx, jsxs } from "react/jsx-runtime";
18
18
  import { StfProvider, useFieldValue } from "@fumari/stf";
19
19
  import { useTranslations } from "@fuma-translate/react";
20
- import { useOnChange } from "fumadocs-core/utils/use-on-change";
21
20
  import { Play, X } from "lucide-react";
22
21
  import { buttonVariants } from "fumadocs-ui/components/ui/button";
23
22
  import { Dialog } from "@base-ui/react/dialog";
23
+ import { useOnChange } from "fumadocs-core/utils/use-on-change";
24
24
  //#region src/ui/playground/client.tsx
25
25
  function PlaygroundClient({ writeOnly = true, readOnly = false, authProviders, transformAuthInputs, fetchOptions, components, renderParameterField, renderBodyField, ...rest }) {
26
26
  const t = useTranslations({ note: "playground" });
27
27
  const { doc } = useOpenAPI();
28
28
  const { path, method, operation } = useOperation();
29
- const providers = useMemo(() => [...authProviders ?? [], oauthPanelProvider], [authProviders]);
29
+ const providers = useMemo(() => [
30
+ ...authProviders ?? [],
31
+ oauthPanelProvider,
32
+ mutualTLSProvider
33
+ ], [authProviders]);
30
34
  const playground = usePlayground({
31
35
  authProviders: providers,
32
36
  transformAuthInputs,
33
37
  fetchOptions
34
38
  });
35
- const [open, setOpen] = useState(false);
39
+ const [open, setOpen] = useState(playground.auth.flowReturned);
36
40
  useOnChange(playground.auth.flowReturned, (returned) => {
37
41
  if (returned) setOpen(true);
38
42
  });
@@ -1,21 +1,24 @@
1
1
  "use client";
2
- import { useQuery } from "../../../packages/shared-api/dist/utils/use-query.js";
3
2
  import { useServer } from "../../../utils/use-server.js";
4
- import { finishOAuthFlow, requestOAuthToken, useAuthRedirect } from "../../../playground/auth.js";
3
+ import { useQuery } from "../../../packages/shared-api/dist/utils/use-query.js";
4
+ import { finishOAuthFlow, requestOAuthToken, useAuthRedirect, useOpenIdConnectFlows } from "../../../playground/auth.js";
5
5
  import { useOpenAPI } from "../../../utils/create-page.js";
6
6
  import { Markdown } from "../../components/markdown.js";
7
7
  import { cn } from "../../../utils/cn.js";
8
+ import { iconButtonClassName } from "./result-display.js";
8
9
  import { Spinner } from "../../../packages/shared-api/dist/components/spinner.js";
9
10
  import { CheckRow, SelectRow, TextRow, ValueRow } from "./fields.js";
10
- import { useState } from "react";
11
+ import { Suspense, useEffect, useRef, useState } from "react";
11
12
  import { Fragment as Fragment$1, jsx, jsxs } from "react/jsx-runtime";
12
13
  import { StfProvider, useDataEngine, useStf } from "@fumari/stf";
13
14
  import { useTranslations } from "@fuma-translate/react";
15
+ import { Check, Copy, ExternalLink } from "lucide-react";
14
16
  import { buttonVariants } from "fumadocs-ui/components/ui/button";
17
+ import { useCopyButton } from "fumadocs-ui/utils/use-copy-button";
15
18
  //#region src/ui/playground/components/oauth-panel.tsx
16
- /** OAuth 2.0 schemes, authorized in a panel */
19
+ /** OAuth 2.0 and OpenID Connect schemes, authorized in a panel */
17
20
  const oauthPanelProvider = {
18
- on: ({ scheme }) => scheme.type === "oauth2",
21
+ on: ({ scheme }) => scheme.type === "oauth2" || scheme.type === "openIdConnect",
19
22
  render: function OAuthRows({ field, Value, Panel }) {
20
23
  const t = useTranslations({ note: "playground" });
21
24
  const engine = useDataEngine();
@@ -53,19 +56,61 @@ const oauthPanelProvider = {
53
56
  ] });
54
57
  }
55
58
  };
56
- /** obtain the access token of an OAuth 2.0 scheme */
59
+ /** obtain the access token of an OAuth 2.0 or OpenID Connect scheme */
57
60
  function OAuthPanel({ field, close }) {
61
+ const t = useTranslations({ note: "OAuth dialog" });
62
+ const { scheme } = field;
63
+ return /* @__PURE__ */ jsxs(Fragment$1, { children: [scheme.description && /* @__PURE__ */ jsx("div", {
64
+ className: "border-b px-4 py-2.5 text-xs text-fd-muted-foreground [&_a]:underline",
65
+ children: /* @__PURE__ */ jsx(Markdown, { md: scheme.description })
66
+ }), scheme.type === "openIdConnect" ? /* @__PURE__ */ jsx(Suspense, {
67
+ fallback: /* @__PURE__ */ jsxs("p", {
68
+ className: "flex items-center gap-1.5 border-b px-4 py-2.5 text-xs text-fd-muted-foreground",
69
+ children: [/* @__PURE__ */ jsx(Spinner, { className: "size-3" }), t("Loading the OpenID Connect configuration...")]
70
+ }),
71
+ children: /* @__PURE__ */ jsx(OpenIdConnectForm, {
72
+ field,
73
+ configUrl: scheme.openIdConnectUrl,
74
+ close
75
+ })
76
+ }) : /* @__PURE__ */ jsx(OAuthForm, {
77
+ field,
78
+ flows: scheme.type === "oauth2" && scheme.flows || {},
79
+ close
80
+ })] });
81
+ }
82
+ /** the flows of OpenID Connect schemes come from their configuration */
83
+ function OpenIdConnectForm({ configUrl, ...props }) {
84
+ const t = useTranslations({ note: "OAuth dialog" });
85
+ const { flows, error } = useOpenIdConnectFlows(configUrl);
86
+ if (flows) return /* @__PURE__ */ jsx(OAuthForm, {
87
+ ...props,
88
+ flows
89
+ });
90
+ return /* @__PURE__ */ jsxs("div", {
91
+ className: "border-b px-4 py-2.5 text-xs",
92
+ children: [/* @__PURE__ */ jsx("p", {
93
+ className: "font-medium text-red-400",
94
+ children: t("Failed to load the OpenID Connect configuration")
95
+ }), /* @__PURE__ */ jsx("p", {
96
+ className: "text-fd-muted-foreground",
97
+ children: String(error)
98
+ })]
99
+ });
100
+ }
101
+ function OAuthForm({ field, flows, close }) {
58
102
  const t = useTranslations({ note: "OAuth dialog" });
59
103
  const engine = useDataEngine();
60
104
  const redirect = useAuthRedirect(field);
61
- const { oauthRedirectUrl } = useOpenAPI();
105
+ const { oauthRedirectUrl, proxyUrl, storageKeyPrefix } = useOpenAPI();
106
+ const storageKey = `${storageKeyPrefix}oauth-${field.schemeId}`;
62
107
  const { resolveUrl } = useServer();
63
- const scheme = field.scheme;
64
- const flows = scheme.flows ?? {};
65
108
  const [type, setType] = useState(() => Object.keys(flows)[0]);
66
109
  const [clientAuth, setClientAuth] = useState("header");
67
110
  const [scopes, setScopes] = useState(() => new Set(field.scopes));
68
- const stf = useStf({});
111
+ const [userCode, setUserCode] = useState();
112
+ const controllerRef = useRef(null);
113
+ const stf = useStf({ defaultValues: () => JSON.parse(localStorage.getItem(storageKey) ?? "{}") });
69
114
  const flowInfo = {
70
115
  authorizationCode: {
71
116
  name: t("Authorization code"),
@@ -89,30 +134,44 @@ function OAuthPanel({ field, close }) {
89
134
  }
90
135
  };
91
136
  const flow = flows[type];
92
- const supported = type !== "deviceAuthorization";
93
137
  const redirects = type === "authorizationCode" || type === "implicit";
94
- const hasSecret = type === "authorizationCode" || type === "clientCredentials" || type === "password";
95
138
  const serverUrl = resolveUrl();
96
139
  const scopeOptions = { ...flow?.scopes };
97
140
  for (const scope of field.scopes) scopeOptions[scope] ??= "";
98
141
  const query = useQuery(async () => {
99
142
  const credentials = stf.dataEngine.getData();
100
- const token = await requestOAuthToken(scheme, type, {
101
- schemeId: field.schemeId,
102
- scopes: Array.from(scopes),
103
- clientId: credentials.client_id ?? "",
104
- clientSecret: credentials.client_secret ?? "",
105
- username: credentials.username ?? "",
106
- password: credentials.password ?? "",
107
- clientAuth,
108
- serverUrl,
109
- redirectUrl: oauthRedirectUrl,
110
- redirect
111
- });
112
- if (!token) return;
113
- engine.update(field.fieldName, token);
114
- close();
143
+ localStorage.setItem(storageKey, JSON.stringify({ clientId: credentials.clientId }));
144
+ const controller = controllerRef.current = new AbortController();
145
+ try {
146
+ const token = await requestOAuthToken(field.scheme, type, {
147
+ ...credentials,
148
+ schemeId: field.schemeId,
149
+ scopes: Array.from(scopes),
150
+ clientAuth,
151
+ serverUrl,
152
+ redirectUrl: oauthRedirectUrl,
153
+ proxyUrl,
154
+ redirect,
155
+ onUserCode: setUserCode,
156
+ signal: controller.signal
157
+ });
158
+ if (!token) return;
159
+ engine.update(field.fieldName, token);
160
+ close();
161
+ } catch (e) {
162
+ if (!controller.signal.aborted) throw e;
163
+ } finally {
164
+ setUserCode(void 0);
165
+ }
115
166
  });
167
+ useEffect(() => () => controllerRef.current?.abort(), []);
168
+ if (userCode) return /* @__PURE__ */ jsx(DeviceVerification, {
169
+ code: userCode,
170
+ onCancel: () => controllerRef.current?.abort()
171
+ });
172
+ let note;
173
+ if (redirects) note = t("You will be redirected to authorize, then back to this page.");
174
+ else if (type === "deviceAuthorization") note = t("You will get a code to enter on the verification page.");
116
175
  return /* @__PURE__ */ jsx(StfProvider, {
117
176
  value: stf,
118
177
  children: /* @__PURE__ */ jsxs("form", {
@@ -122,10 +181,6 @@ function OAuthPanel({ field, close }) {
122
181
  query.start();
123
182
  },
124
183
  children: [
125
- scheme.description && /* @__PURE__ */ jsx("div", {
126
- className: "border-b px-4 py-2.5 text-xs text-fd-muted-foreground [&_a]:underline",
127
- children: /* @__PURE__ */ jsx(Markdown, { md: scheme.description })
128
- }),
129
184
  /* @__PURE__ */ jsx(SelectRow, {
130
185
  name: "flow",
131
186
  value: type,
@@ -136,18 +191,18 @@ function OAuthPanel({ field, close }) {
136
191
  description: flowInfo[key].description
137
192
  }))
138
193
  }),
139
- supported && /* @__PURE__ */ jsx(ValueRow, {
194
+ /* @__PURE__ */ jsx(ValueRow, {
140
195
  name: "client_id",
141
196
  required: type !== "password",
142
197
  description: t("The client ID of your OAuth application."),
143
- fieldName: ["client_id"],
198
+ fieldName: ["clientId"],
144
199
  field: { type: "string" }
145
200
  }),
146
- hasSecret && /* @__PURE__ */ jsx(ValueRow, {
201
+ type !== "implicit" && /* @__PURE__ */ jsx(ValueRow, {
147
202
  name: "client_secret",
148
- required: type !== "password",
203
+ required: type === "clientCredentials",
149
204
  description: t("The client secret of your OAuth application."),
150
- fieldName: ["client_secret"],
205
+ fieldName: ["clientSecret"],
151
206
  field: {
152
207
  type: "string",
153
208
  format: "password"
@@ -167,7 +222,7 @@ function OAuthPanel({ field, close }) {
167
222
  format: "password"
168
223
  }
169
224
  })] }),
170
- hasSecret && /* @__PURE__ */ jsx(SelectRow, {
225
+ type !== "implicit" && /* @__PURE__ */ jsx(SelectRow, {
171
226
  name: "client_auth",
172
227
  value: clientAuth,
173
228
  onValueChange: (v) => setClientAuth(v),
@@ -185,6 +240,10 @@ function OAuthPanel({ field, close }) {
185
240
  name: "authorization_url",
186
241
  children: new URL(flow.authorizationUrl, serverUrl).href
187
242
  }),
243
+ flow && "deviceAuthorizationUrl" in flow && flow.deviceAuthorizationUrl && /* @__PURE__ */ jsx(TextRow, {
244
+ name: "device_authorization_url",
245
+ children: new URL(flow.deviceAuthorizationUrl, serverUrl).href
246
+ }),
188
247
  flow && "tokenUrl" in flow && flow.tokenUrl && /* @__PURE__ */ jsx(TextRow, {
189
248
  name: "token_url",
190
249
  children: new URL(flow.tokenUrl, serverUrl).href
@@ -213,10 +272,10 @@ function OAuthPanel({ field, close }) {
213
272
  className: "flex items-center gap-3 px-4 py-3",
214
273
  children: [/* @__PURE__ */ jsx("p", {
215
274
  className: cn("min-w-0 flex-1 text-xs", query.error ? "text-red-400" : "text-fd-muted-foreground"),
216
- children: query.error ? String(query.error) : !supported ? t("Unsupported") : redirects && t("You will be redirected to authorize, then back to this page.")
275
+ children: query.error ? String(query.error) : note
217
276
  }), /* @__PURE__ */ jsxs("button", {
218
277
  type: "submit",
219
- disabled: !supported || query.isLoading,
278
+ disabled: query.isLoading,
220
279
  className: cn(buttonVariants({
221
280
  variant: "primary",
222
281
  size: "sm"
@@ -228,5 +287,57 @@ function OAuthPanel({ field, close }) {
228
287
  })
229
288
  });
230
289
  }
290
+ /** the code of a device authorization, until users enter it */
291
+ function DeviceVerification({ code, onCancel }) {
292
+ const t = useTranslations({ note: "OAuth dialog" });
293
+ const tPlayground = useTranslations({ note: "playground" });
294
+ const [isCopied, onCopy] = useCopyButton(() => navigator.clipboard.writeText(code.userCode));
295
+ return /* @__PURE__ */ jsxs(Fragment$1, { children: [/* @__PURE__ */ jsxs("div", {
296
+ className: "flex flex-col items-center gap-4 border-b px-4 py-8 text-center starting:opacity-0 motion-safe:transition-[opacity,translate] motion-safe:duration-300 motion-safe:starting:translate-y-1",
297
+ children: [
298
+ /* @__PURE__ */ jsx("p", {
299
+ className: "text-xs text-fd-muted-foreground",
300
+ children: t("Enter this code on the verification page.")
301
+ }),
302
+ /* @__PURE__ */ jsxs("div", {
303
+ className: "flex items-center gap-1 rounded-lg border bg-fd-secondary py-1 ps-4 pe-1",
304
+ children: [/* @__PURE__ */ jsx("code", {
305
+ className: "font-mono text-xl font-medium tracking-widest select-all",
306
+ children: code.userCode
307
+ }), /* @__PURE__ */ jsx("button", {
308
+ type: "button",
309
+ "aria-label": isCopied ? tPlayground("Copied", { note: "aria-label" }) : tPlayground("Copy", { note: "aria-label" }),
310
+ onClick: onCopy,
311
+ className: iconButtonClassName,
312
+ children: isCopied ? /* @__PURE__ */ jsx(Check, {}) : /* @__PURE__ */ jsx(Copy, {})
313
+ })]
314
+ }),
315
+ /* @__PURE__ */ jsxs("a", {
316
+ href: code.verificationUriComplete ?? code.verificationUri,
317
+ target: "_blank",
318
+ rel: "noreferrer",
319
+ className: cn(buttonVariants({
320
+ variant: "primary",
321
+ size: "sm"
322
+ }), "gap-1.5 px-3"),
323
+ children: [t("Open verification page"), /* @__PURE__ */ jsx(ExternalLink, { className: "size-3.5" })]
324
+ })
325
+ ]
326
+ }), /* @__PURE__ */ jsxs("div", {
327
+ className: "flex items-center gap-3 px-4 py-3",
328
+ children: [/* @__PURE__ */ jsxs("p", {
329
+ className: "flex min-w-0 flex-1 items-center gap-1.5 text-xs text-fd-muted-foreground",
330
+ children: [/* @__PURE__ */ jsx(Spinner, { className: "size-3" }), t("Waiting for authorization...")]
331
+ }), /* @__PURE__ */ jsx("button", {
332
+ type: "button",
333
+ onClick: onCancel,
334
+ className: cn(buttonVariants({
335
+ variant: "secondary",
336
+ size: "sm"
337
+ }), "shrink-0 px-3"),
338
+ children: t("Cancel")
339
+ })]
340
+ })] });
341
+ }
231
342
  //#endregion
232
343
  export { oauthPanelProvider };