fumadocs-openapi 12.2.0 → 12.4.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 (59) hide show
  1. package/css/generated/shared.css +1 -1
  2. package/dist/.translations/index.d.ts +4 -4
  3. package/dist/.translations/keys.js +4 -4
  4. package/dist/operation.js +4 -4
  5. package/dist/packages/shared-api/dist/.translations/index.d.ts +1 -0
  6. package/dist/packages/shared-api/dist/.translations/keys.js +1 -0
  7. package/dist/packages/shared-api/dist/auto-anchor/index.js +54 -10
  8. package/dist/packages/shared-api/dist/components/accordion.js +3 -11
  9. package/dist/packages/shared-api/dist/components/collapsible.js +16 -0
  10. package/dist/packages/shared-api/dist/components/defaults.js +1 -1
  11. package/dist/packages/shared-api/dist/components/schema/client.d.ts +5 -0
  12. package/dist/packages/shared-api/dist/components/schema/client.js +408 -455
  13. package/dist/packages/shared-api/dist/components/select-tab.js +7 -12
  14. package/dist/playground/auth.d.ts +61 -7
  15. package/dist/playground/auth.js +192 -95
  16. package/dist/playground/fetcher.d.ts +1 -1
  17. package/dist/playground/index.d.ts +2 -2
  18. package/dist/playground/index.js +2 -2
  19. package/dist/playground/use-playground.d.ts +5 -3
  20. package/dist/playground/use-playground.js +22 -10
  21. package/dist/requests/generators/csharp.js +11 -21
  22. package/dist/requests/generators/curl.js +12 -14
  23. package/dist/requests/generators/go.js +22 -33
  24. package/dist/requests/generators/index.d.ts +1 -1
  25. package/dist/requests/generators/java.js +33 -37
  26. package/dist/requests/generators/javascript.js +13 -20
  27. package/dist/requests/generators/python.js +12 -17
  28. package/dist/requests/generators/rust.js +15 -20
  29. package/dist/requests/index.d.ts +1 -1
  30. package/dist/requests/media/adapter.d.ts +0 -1
  31. package/dist/requests/media/adapter.js +50 -42
  32. package/dist/requests/media/encode.d.ts +1 -1
  33. package/dist/requests/media/encode.js +1 -1
  34. package/dist/requests/string-utils.js +14 -6
  35. package/dist/ui/components/dialog.js +14 -0
  36. package/dist/ui/components/endpoint.js +11 -8
  37. package/dist/ui/components/heading.js +1 -1
  38. package/dist/ui/components/schema.js +1 -1
  39. package/dist/ui/{playground/components → components}/segmented.js +2 -2
  40. package/dist/ui/operation/index.js +262 -237
  41. package/dist/ui/operation/request-tabs.js +1 -1
  42. package/dist/ui/operation/response-tabs.js +1 -1
  43. package/dist/ui/operation/usage-tabs.js +1 -1
  44. package/dist/ui/playground/client.d.ts +1 -1
  45. package/dist/ui/playground/client.js +23 -19
  46. package/dist/ui/playground/components/fields.js +36 -15
  47. package/dist/ui/playground/components/oauth-panel.js +71 -21
  48. package/dist/ui/playground/components/request-panel.js +80 -94
  49. package/dist/ui/playground/components/response-panel.js +1 -1
  50. package/dist/ui/playground/components/result-display.js +1 -1
  51. package/dist/ui/playground/components/server-select.js +1 -1
  52. package/dist/utils/create-page.js +2 -2
  53. package/dist/utils/get-example-requests.js +1 -1
  54. package/dist/utils/use-server.d.ts +3 -3
  55. package/dist/utils/use-server.js +2 -2
  56. package/package.json +5 -5
  57. package/dist/packages/shared-api/dist/auto-anchor/client.js +0 -20
  58. package/dist/packages/shared-api/dist/components/popover.js +0 -23
  59. package/dist/packages/shared-api/dist/utils/merge-refs.js +0 -11
@@ -1,9 +1,8 @@
1
1
  "use client";
2
2
  import { cn } from "../utils/cn.js";
3
3
  import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "./select.js";
4
- import { anchorIdStartsWith } from "../auto-anchor/index.js";
5
- import { AnchorSection, useAnchorId } from "../auto-anchor/client.js";
6
- import { createContext, use, useEffect, useMemo, useState } from "react";
4
+ import { AnchorSection, useAnchorLink } from "../auto-anchor/index.js";
5
+ import { createContext, use, useMemo, useState } from "react";
7
6
  import { jsx, jsxs } from "react/jsx-runtime";
8
7
  //#region ../shared-api/dist/components/select-tab.js
9
8
  const Context = createContext(null);
@@ -19,16 +18,12 @@ function SelectTabs({ defaultValue, children }) {
19
18
  }
20
19
  function SelectTab({ value, anchorSegments, ...props }) {
21
20
  const { value: currentValue, setValue } = use(Context);
22
- const id = useAnchorId(anchorSegments ?? false);
23
- useEffect(() => {
24
- if (id && anchorIdStartsWith(window.location.hash.slice(1), id)) setValue(value);
25
- }, [
26
- id,
27
- value,
28
- setValue
29
- ]);
21
+ const ref = useAnchorLink(anchorSegments ?? false, () => setValue(value));
30
22
  if (value !== currentValue) return;
31
- const content = /* @__PURE__ */ jsx("div", { ...props });
23
+ const content = /* @__PURE__ */ jsx("div", {
24
+ ref,
25
+ ...props
26
+ });
32
27
  return anchorSegments ? /* @__PURE__ */ jsx(AnchorSection, {
33
28
  segments: anchorSegments,
34
29
  children: content
@@ -1,5 +1,7 @@
1
+ import { RawRequestData } from "../requests/types.js";
1
2
  import { OAuth2SecurityScheme, OperationObject, SecuritySchemeObject } from "../types.js";
2
- import { ReactNode } from "react";
3
+ import { FC, ReactNode } from "react";
4
+ import { JsonSchema } from "@fumadocs/json-schema";
3
5
  import { DataEngine, FieldKey } from "@fumari/stf";
4
6
  //#region src/playground/auth.d.ts
5
7
  export type OAuthFlowType = keyof NonNullable<OAuth2SecurityScheme['flows']>;
@@ -22,14 +24,25 @@ export interface OAuthFlowInput {
22
24
  redirectUrl?: string;
23
25
  /** where the flow started, like an operation, restored when it returns to the page */
24
26
  origin?: string;
27
+ /**
28
+ * leave the page for `implicit` and `authorizationCode`, like the one of `useAuthRedirect()`, `finishOAuthFlow()` takes `data` when it returns.
29
+ *
30
+ * By default, `usePlaygroundAuth()` finishes them.
31
+ */
32
+ redirect?: (url: URL, data: unknown) => void;
25
33
  }
26
34
  /**
27
35
  * Run an OAuth flow and resolve its token.
28
36
  *
29
- * `implicit` and `authorizationCode` leave the page instead: the token is picked up on return,
30
- * in `usePlaygroundAuth().store`.
37
+ * `implicit` and `authorizationCode` leave the page instead, see `redirect`.
31
38
  */
32
- export declare function requestOAuthToken(scheme: OAuth2SecurityScheme, type: OAuthFlowType, { schemeId, scopes, clientId, clientSecret, username, password, clientAuth, serverUrl, redirectUrl, origin }: OAuthFlowInput): Promise<string | undefined>;
39
+ export declare function requestOAuthToken(scheme: OAuth2SecurityScheme, type: OAuthFlowType, { schemeId, scopes, clientId, clientSecret, username, password, clientAuth, serverUrl, redirectUrl, origin, redirect }: OAuthFlowInput): Promise<string | undefined>;
40
+ /**
41
+ * Finish an `implicit` or `authorizationCode` flow of `requestOAuthToken()` from the URL it returned to.
42
+ *
43
+ * @returns the token, `undefined` when the URL isn't returning from it
44
+ */
45
+ export declare function finishOAuthFlow(url: URL, data: unknown): Promise<string> | string | undefined;
33
46
  /** scheme name -> token info */
34
47
  type TokenStore = Record<string, TokenInfo | undefined>;
35
48
  type TokenInfo = {
@@ -54,12 +67,52 @@ interface AuthContextType {
54
67
  subscribe: (listener: TokenListener) => () => void;
55
68
  }
56
69
  export declare function usePlaygroundAuth(): AuthContextType;
70
+ /**
71
+ * Leave the page for a flow of field, like signing in, with the returned function.
72
+ *
73
+ * When the page loads again, the playground reopens, and `onReturn` gets the URL and `data` of flow.
74
+ */
75
+ export declare function useAuthRedirect(field: AuthField, onReturn?: (url: URL, data: unknown) => void): (url: string | URL, data?: unknown) => void;
57
76
  export interface AuthRequirement {
58
77
  /** id of the security scheme */
59
78
  id: string;
60
79
  scopes: string[];
61
80
  scheme: SecuritySchemeObject;
62
81
  }
82
+ /**
83
+ * How the playground handles a security scheme: its rows, and how its value authorizes requests.
84
+ *
85
+ * Omitted options come from the next provider of the scheme, and then the built-in one.
86
+ */
87
+ export interface AuthProvider {
88
+ /** the ID of security schemes it handles, or a function. Every scheme when omitted */
89
+ on?: string | ((item: AuthRequirement) => boolean);
90
+ /** the rows of field */
91
+ render?: FC<AuthRenderProps>;
92
+ /** write the value into request data, for sending and code usages */
93
+ onRequest?: (data: RawRequestData, value: unknown, field: AuthField) => void;
94
+ }
95
+ export interface AuthRenderProps {
96
+ field: AuthField;
97
+ /** a row editing the value, or its property at `path` */
98
+ Value: FC<{
99
+ name: string;
100
+ type?: string;
101
+ description?: string;
102
+ schema?: Exclude<JsonSchema, boolean>;
103
+ path?: string;
104
+ }>;
105
+ /** a row opening `component` in a panel */
106
+ Panel: FC<{
107
+ title: ReactNode;
108
+ component: FC<AuthPanelProps>;
109
+ }>;
110
+ }
111
+ export interface AuthPanelProps {
112
+ field: AuthField;
113
+ /** back to the request */
114
+ close: () => void;
115
+ }
63
116
  export interface AuthField {
64
117
  schemeId: string;
65
118
  scheme: SecuritySchemeObject;
@@ -69,8 +122,7 @@ export interface AuthField {
69
122
  /** `localStorage` key of its persisted value */
70
123
  storageKey: string;
71
124
  defaultValue: unknown;
72
- /** encode the value into request data, like the header of Basic auth */
73
- mapOutput?: (value: unknown) => unknown;
125
+ provider: AuthProvider;
74
126
  }
75
127
  export interface AuthFields {
76
128
  /** the security requirements of the operation, one of them authorizes the request */
@@ -88,11 +140,13 @@ export interface AuthFields {
88
140
  export interface AuthFieldsOptions {
89
141
  /** the operation to authorize, defaults to the security of the document */
90
142
  operation?: OperationObject;
143
+ /** handle security schemes, before the built-in providers */
144
+ providers?: AuthProvider[];
91
145
  /** customise the generated fields, like their default values */
92
146
  transform?: (fields: AuthField[]) => AuthField[];
93
147
  }
94
148
  /**
95
149
  * The auth fields of an API playground: the values it persists, and the request data they encode into.
96
150
  */
97
- export declare function useAuthFields(engine: DataEngine, { operation, transform }?: AuthFieldsOptions): AuthFields;
151
+ export declare function useAuthFields(engine: DataEngine, { operation, providers, transform }?: AuthFieldsOptions): AuthFields;
98
152
  //#endregion
@@ -1,43 +1,58 @@
1
1
  "use client";
2
2
  import { useQuery } from "../packages/shared-api/dist/utils/use-query.js";
3
+ import { useOperation } from "../operation.js";
3
4
  import { useOpenAPI } from "../utils/create-page.js";
4
5
  import { createContext, use, useCallback, useEffect, useEffectEvent, useMemo, useState } from "react";
5
- import { jsx } from "react/jsx-runtime";
6
+ import { Fragment as Fragment$1, jsx, jsxs } from "react/jsx-runtime";
6
7
  import { useListener } from "@fumari/stf";
7
- import { arrayStartsWith, objectGet, objectSet } from "@fumari/stf/lib/utils";
8
+ import { arrayStartsWith, objectGet } from "@fumari/stf/lib/utils";
8
9
  //#region src/playground/auth.tsx
9
- const pendingFlowKey = "fumadocs-openapi-oauth";
10
+ const pendingOAuthKey = "fumadocs-openapi-oauth";
11
+ const pendingFlowKey = "fumadocs-openapi-flow";
12
+ function readPendingFlow() {
13
+ const stored = sessionStorage.getItem(pendingFlowKey);
14
+ if (stored) return JSON.parse(stored);
15
+ }
16
+ function leavePage(url, redirectUrl, flow) {
17
+ if (flow) sessionStorage.setItem(pendingFlowKey, JSON.stringify(flow));
18
+ if (redirectUrl) document.cookie = `fumadocs-openapi-oauth=${encodeURIComponent(window.location.pathname)}; path=/`;
19
+ window.location.replace(url);
20
+ }
10
21
  /**
11
22
  * Run an OAuth flow and resolve its token.
12
23
  *
13
- * `implicit` and `authorizationCode` leave the page instead: the token is picked up on return,
14
- * in `usePlaygroundAuth().store`.
24
+ * `implicit` and `authorizationCode` leave the page instead, see `redirect`.
15
25
  */
16
- async function requestOAuthToken(scheme, type, { schemeId, scopes, clientId, clientSecret, username, password, clientAuth, serverUrl, redirectUrl, origin }) {
26
+ async function requestOAuthToken(scheme, type, { schemeId, scopes, clientId, clientSecret, username, password, clientAuth, serverUrl, redirectUrl, origin, redirect }) {
17
27
  const flows = scheme.flows ?? {};
18
28
  const scope = scopes.join(" ");
19
29
  if (type === "implicit" || type === "authorizationCode") {
20
30
  const flow = flows[type];
21
31
  if (!flow) return;
22
- const pending = {
32
+ const data = {
23
33
  state: crypto.getRandomValues(/* @__PURE__ */ new Uint32Array(4)).join(""),
24
- scheme: schemeId,
25
34
  client_id: clientId,
26
35
  client_secret: clientSecret,
27
36
  client_auth: clientAuth,
28
37
  redirect_uri: new URL(redirectUrl ?? window.location.pathname, window.location.origin).href,
29
- token_url: "tokenUrl" in flow ? new URL(flow.tokenUrl, serverUrl).href : void 0,
30
- origin
38
+ token_url: "tokenUrl" in flow ? new URL(flow.tokenUrl, serverUrl).href : void 0
31
39
  };
32
- sessionStorage.setItem(pendingFlowKey, JSON.stringify(pending));
33
- if (redirectUrl) document.cookie = `fumadocs-openapi-oauth=${encodeURIComponent(window.location.pathname)}; path=/`;
34
40
  const url = new URL(flow.authorizationUrl, serverUrl);
35
41
  url.searchParams.set("response_type", type === "implicit" ? "token" : "code");
36
42
  url.searchParams.set("client_id", clientId);
37
- url.searchParams.set("redirect_uri", pending.redirect_uri);
43
+ url.searchParams.set("redirect_uri", data.redirect_uri);
38
44
  url.searchParams.set("scope", scope);
39
- url.searchParams.set("state", pending.state);
40
- window.location.replace(url);
45
+ url.searchParams.set("state", data.state);
46
+ if (redirect) redirect(url, data);
47
+ else {
48
+ const pending = {
49
+ ...data,
50
+ scheme: schemeId,
51
+ origin
52
+ };
53
+ sessionStorage.setItem(pendingOAuthKey, JSON.stringify(pending));
54
+ leavePage(url, redirectUrl);
55
+ }
41
56
  return;
42
57
  }
43
58
  if (type !== "password" && type !== "clientCredentials") return;
@@ -55,6 +70,26 @@ async function requestOAuthToken(scheme, type, { schemeId, scopes, clientId, cli
55
70
  client_auth: clientAuth
56
71
  });
57
72
  }
73
+ /**
74
+ * Finish an `implicit` or `authorizationCode` flow of `requestOAuthToken()` from the URL it returned to.
75
+ *
76
+ * @returns the token, `undefined` when the URL isn't returning from it
77
+ */
78
+ function finishOAuthFlow(url, data) {
79
+ const flow = data;
80
+ const code = url.searchParams.get("code");
81
+ if (code && url.searchParams.get("state") === flow.state) {
82
+ const body = new URLSearchParams({
83
+ grant_type: "authorization_code",
84
+ code,
85
+ redirect_uri: flow.redirect_uri
86
+ });
87
+ return fetchToken(flow.token_url, body, flow);
88
+ }
89
+ const hash = new URLSearchParams(url.hash.slice(1));
90
+ const token = hash.get("access_token");
91
+ if (token && hash.get("state") === flow.state) return `${hash.get("token_type") ?? "Bearer"} ${token}`;
92
+ }
58
93
  async function fetchToken(tokenUrl, body, { client_id, client_secret, client_auth }) {
59
94
  const headers = { "Content-Type": "application/x-www-form-urlencoded" };
60
95
  if (client_auth === "header" && client_secret) headers.Authorization = `Basic ${btoa(`${encodeURIComponent(client_id)}:${encodeURIComponent(client_secret)}`)}`;
@@ -77,67 +112,65 @@ function usePlaygroundAuth() {
77
112
  if (!ctx) throw new Error("Component must be used under <OpenAPIProvider />");
78
113
  return ctx;
79
114
  }
80
- function AuthProvider({ children }) {
115
+ function PlaygroundAuthProvider({ children }) {
81
116
  const [store, setStore] = useState({});
82
117
  const [origin, setOrigin] = useState();
83
- const listeners = useMemo(() => /* @__PURE__ */ new Set(), []);
84
- const subscribe = useCallback((listener) => {
85
- listeners.add(listener);
86
- return () => {
87
- listeners.delete(listener);
118
+ const { subscribe, emit } = useMemo(() => {
119
+ const listeners = /* @__PURE__ */ new Set();
120
+ return {
121
+ subscribe(listener) {
122
+ listeners.add(listener);
123
+ return () => {
124
+ listeners.delete(listener);
125
+ };
126
+ },
127
+ emit(schemeId, token) {
128
+ for (const listener of listeners) listener(schemeId, token);
129
+ }
88
130
  };
89
- }, [listeners]);
90
- function save(schemeId, info) {
91
- setStore((s) => ({
92
- ...s,
93
- [schemeId]: info
94
- }));
95
- for (const listener of listeners) listener(schemeId, info.token);
96
- }
97
- const authCodeQuery = useQuery(async (code, flow) => {
98
- const token = await fetchToken(flow.token_url, new URLSearchParams({
99
- grant_type: "authorization_code",
100
- code,
101
- redirect_uri: flow.redirect_uri
102
- }), flow);
103
- save(flow.scheme, {
131
+ }, []);
132
+ const returnQuery = useQuery(async (flow, result) => {
133
+ setOrigin(flow.origin);
134
+ const token = await result;
135
+ const info = typeof result === "string" ? {
136
+ type: "implicit",
137
+ client_id: flow.client_id,
138
+ token
139
+ } : {
104
140
  type: "authorization_code",
105
141
  client_id: flow.client_id,
106
142
  client_secret: flow.client_secret,
107
143
  client_auth: flow.client_auth,
108
144
  token
109
- });
145
+ };
146
+ setStore((s) => ({
147
+ ...s,
148
+ [flow.scheme]: info
149
+ }));
150
+ emit(flow.scheme, token);
110
151
  });
111
- useEffect(() => {
112
- const stored = sessionStorage.getItem(pendingFlowKey);
152
+ const onMount = useEffectEvent(() => {
153
+ const stored = sessionStorage.getItem(pendingOAuthKey);
113
154
  if (!stored) return;
114
155
  const flow = JSON.parse(stored);
115
- const query = new URLSearchParams(window.location.search);
116
- const hash = new URLSearchParams(window.location.hash.slice(1));
117
- const code = query.get("code");
118
- const token = hash.get("access_token");
119
- if (code && query.get("state") === flow.state) authCodeQuery.start(code, flow);
120
- else if (token && hash.get("state") === flow.state) save(flow.scheme, {
121
- type: "implicit",
122
- client_id: flow.client_id,
123
- token: `${hash.get("token_type") ?? "Bearer"} ${token}`
124
- });
125
- else return;
126
- setOrigin(flow.origin);
127
- sessionStorage.removeItem(pendingFlowKey);
156
+ const result = finishOAuthFlow(new URL(window.location.href), flow);
157
+ if (result === void 0) return;
158
+ sessionStorage.removeItem(pendingOAuthKey);
128
159
  window.history.replaceState(null, "", window.location.pathname);
129
- }, []);
160
+ returnQuery.start(flow, result);
161
+ });
162
+ useEffect(() => onMount(), []);
130
163
  return /* @__PURE__ */ jsx(AuthContext, {
131
164
  value: useMemo(() => ({
132
165
  store,
133
- isLoading: authCodeQuery.isLoading,
134
- error: authCodeQuery.error,
166
+ isLoading: returnQuery.isLoading,
167
+ error: returnQuery.error,
135
168
  origin,
136
169
  subscribe
137
170
  }), [
138
171
  store,
139
- authCodeQuery.isLoading,
140
- authCodeQuery.error,
172
+ returnQuery.isLoading,
173
+ returnQuery.error,
141
174
  origin,
142
175
  subscribe
143
176
  ]),
@@ -145,9 +178,95 @@ function AuthProvider({ children }) {
145
178
  });
146
179
  }
147
180
  /**
181
+ * Leave the page for a flow of field, like signing in, with the returned function.
182
+ *
183
+ * When the page loads again, the playground reopens, and `onReturn` gets the URL and `data` of flow.
184
+ */
185
+ function useAuthRedirect(field, onReturn) {
186
+ const { oauthRedirectUrl } = useOpenAPI();
187
+ const { method, path } = useOperation();
188
+ const origin = `${method} ${path}`;
189
+ const onMount = useEffectEvent(() => {
190
+ if (!onReturn) return;
191
+ const flow = readPendingFlow();
192
+ if (flow?.scheme !== field.schemeId || flow.origin !== origin) return;
193
+ sessionStorage.removeItem(pendingFlowKey);
194
+ const url = new URL(window.location.href);
195
+ window.history.replaceState(null, "", window.location.pathname);
196
+ onReturn(url, flow.data);
197
+ });
198
+ useEffect(() => onMount(), []);
199
+ return (url, data) => leavePage(url, oauthRedirectUrl, {
200
+ scheme: field.schemeId,
201
+ origin,
202
+ data
203
+ });
204
+ }
205
+ const builtinProviders = [
206
+ {
207
+ on: ({ scheme }) => scheme.type === "http" && scheme.scheme === "basic",
208
+ render: ({ field, Value }) => /* @__PURE__ */ jsxs(Fragment$1, { children: [/* @__PURE__ */ jsx(Value, {
209
+ name: "username",
210
+ type: "basic",
211
+ description: field.scheme.description,
212
+ path: "username"
213
+ }), /* @__PURE__ */ jsx(Value, {
214
+ name: "password",
215
+ path: "password",
216
+ schema: {
217
+ type: "string",
218
+ format: "password"
219
+ }
220
+ })] }),
221
+ onRequest(data, value) {
222
+ const { username, password } = value;
223
+ data.header.Authorization = `Basic ${btoa(`${username}:${password}`)}`;
224
+ }
225
+ },
226
+ {
227
+ on: ({ scheme }) => scheme.type === "apiKey",
228
+ render: ({ field: { scheme }, Value }) => scheme.type === "apiKey" && /* @__PURE__ */ jsx(Value, {
229
+ name: scheme.name,
230
+ type: scheme.in,
231
+ description: scheme.description
232
+ }),
233
+ onRequest(data, value, { scheme }) {
234
+ if (scheme.type === "apiKey") data[scheme.in][scheme.name] = value;
235
+ }
236
+ },
237
+ {
238
+ render: ({ field, Value }) => /* @__PURE__ */ jsx(Value, {
239
+ name: "Authorization",
240
+ type: "header",
241
+ description: field.scheme.description
242
+ }),
243
+ onRequest(data, value) {
244
+ data.header.Authorization = value;
245
+ }
246
+ }
247
+ ];
248
+ function findProvider(providers = [], item) {
249
+ const match = ({ on }) => on === void 0 || (typeof on === "string" ? on === item.id : on(item));
250
+ let provider = builtinProviders.find(match);
251
+ for (let i = providers.length - 1; i >= 0; i--) if (match(providers[i])) provider = {
252
+ ...provider,
253
+ ...providers[i]
254
+ };
255
+ return provider;
256
+ }
257
+ function getDefaultValue(scheme) {
258
+ if (scheme.type === "apiKey") return "";
259
+ if (scheme.type !== "http" || !scheme.scheme) return "Bearer ";
260
+ if (scheme.scheme === "basic") return {
261
+ username: "",
262
+ password: ""
263
+ };
264
+ return `${scheme.scheme[0].toUpperCase()}${scheme.scheme.slice(1)} `;
265
+ }
266
+ /**
148
267
  * The auth fields of an API playground: the values it persists, and the request data they encode into.
149
268
  */
150
- function useAuthFields(engine, { operation, transform } = {}) {
269
+ function useAuthFields(engine, { operation, providers, transform } = {}) {
151
270
  const { subscribe } = usePlaygroundAuth();
152
271
  const { storageKeyPrefix, doc } = useOpenAPI();
153
272
  const { dereferenced, resolve } = doc;
@@ -182,48 +301,27 @@ function useAuthFields(engine, { operation, transform } = {}) {
182
301
  const requirement = selected === -1 ? null : requirements[selected];
183
302
  const fields = useMemo(() => {
184
303
  if (!requirement) return [];
185
- const out = requirement.map(({ id, scheme, scopes }) => {
186
- const shared = {
187
- schemeId: id,
188
- scheme,
189
- scopes,
190
- storageKey: `${storageKeyPrefix}auth-${id}`
191
- };
192
- if (scheme.type === "http" && scheme.scheme === "basic") return {
193
- ...shared,
194
- fieldName: ["header", "Authorization"],
195
- defaultValue: {
196
- username: "",
197
- password: ""
198
- },
199
- mapOutput(value) {
200
- if (!value || typeof value !== "object") return value;
201
- const { username = "", password = "" } = value;
202
- return `Basic ${btoa(`${username}:${password}`)}`;
203
- }
204
- };
205
- if (scheme.type === "apiKey") return {
206
- ...shared,
207
- fieldName: [scheme.in, scheme.name],
208
- defaultValue: ""
209
- };
210
- return {
211
- ...shared,
212
- fieldName: ["header", "Authorization"],
213
- defaultValue: scheme.type === "http" || scheme.type === "oauth2" ? "Bearer " : ""
214
- };
215
- });
304
+ const out = requirement.map((item) => ({
305
+ schemeId: item.id,
306
+ scheme: item.scheme,
307
+ scopes: item.scopes,
308
+ fieldName: ["auth", item.id],
309
+ storageKey: `${storageKeyPrefix}auth-${item.id}`,
310
+ defaultValue: getDefaultValue(item.scheme),
311
+ provider: findProvider(providers, item)
312
+ }));
216
313
  return transform ? transform(out) : out;
217
314
  }, [
218
315
  requirement,
219
316
  storageKeyPrefix,
317
+ providers,
220
318
  transform
221
319
  ]);
222
320
  useListener({
223
321
  stf: engine,
224
322
  onUpdate(key) {
225
323
  for (const field of fields) {
226
- if (!arrayStartsWith(field.fieldName, key)) continue;
324
+ if (!arrayStartsWith(key, field.fieldName) && !arrayStartsWith(field.fieldName, key)) continue;
227
325
  const value = engine.get(field.fieldName);
228
326
  if (value != null) localStorage.setItem(field.storageKey, JSON.stringify(value));
229
327
  }
@@ -249,10 +347,9 @@ function useAuthFields(engine, { operation, transform } = {}) {
249
347
  fields,
250
348
  mapValues: useCallback((values) => {
251
349
  const cloned = structuredClone(values);
252
- for (const field of fields) {
253
- if (!field.mapOutput) continue;
254
- objectSet(cloned, field.fieldName, field.mapOutput(objectGet(cloned, field.fieldName)));
255
- }
350
+ const data = cloned;
351
+ for (const field of fields) field.provider.onRequest(data, objectGet(data, field.fieldName), field);
352
+ delete data.auth;
256
353
  return cloned;
257
354
  }, [fields]),
258
355
  init: useCallback(() => {
@@ -274,4 +371,4 @@ function useAuthFields(engine, { operation, transform } = {}) {
274
371
  };
275
372
  }
276
373
  //#endregion
277
- export { AuthProvider, requestOAuthToken, useAuthFields, usePlaygroundAuth };
374
+ export { PlaygroundAuthProvider, finishOAuthFlow, readPendingFlow, requestOAuthToken, useAuthFields, useAuthRedirect, usePlaygroundAuth };
@@ -1,5 +1,5 @@
1
- import { MediaAdapter } from "../requests/media/adapter.js";
2
1
  import { RequestData } from "../requests/types.js";
2
+ import { MediaAdapter } from "../requests/media/adapter.js";
3
3
  import { Awaitable } from "../types.js";
4
4
  //#region src/playground/fetcher.d.ts
5
5
  export type FetchResult = FetchResponseResult | FetchErrorResult;
@@ -1,4 +1,4 @@
1
1
  import { BrowserFetcherOptions, FetchErrorResult, FetchResponseResult, FetchResult, Fetcher, createBrowserFetcher } from "./fetcher.js";
2
- import { AuthField, AuthRequirement, OAuthFlowType, requestOAuthToken, useAuthFields, usePlaygroundAuth } from "./auth.js";
2
+ import { AuthField, AuthPanelProps, AuthProvider, AuthRenderProps, AuthRequirement, OAuthFlowType, finishOAuthFlow, requestOAuthToken, useAuthFields, useAuthRedirect, usePlaygroundAuth } from "./auth.js";
3
3
  import { OAuthInput, Playground, PlaygroundAuth, PlaygroundOptions, PlaygroundResponse, RequestBodyInfo, usePlayground } from "./use-playground.js";
4
- export { type AuthField, type AuthRequirement, type BrowserFetcherOptions, type FetchErrorResult, type FetchResponseResult, type FetchResult, type Fetcher, type OAuthFlowType, type OAuthInput, type Playground, type PlaygroundAuth, type PlaygroundOptions, type PlaygroundResponse, type RequestBodyInfo, createBrowserFetcher, requestOAuthToken, useAuthFields, usePlayground, usePlaygroundAuth };
4
+ export { type AuthField, type AuthPanelProps, type AuthProvider, type AuthRenderProps, type AuthRequirement, type BrowserFetcherOptions, type FetchErrorResult, type FetchResponseResult, type FetchResult, type Fetcher, type OAuthFlowType, type OAuthInput, type Playground, type PlaygroundAuth, type PlaygroundOptions, type PlaygroundResponse, type RequestBodyInfo, createBrowserFetcher, finishOAuthFlow, requestOAuthToken, useAuthFields, useAuthRedirect, usePlayground, usePlaygroundAuth };
@@ -1,4 +1,4 @@
1
- import { requestOAuthToken, useAuthFields, usePlaygroundAuth } from "./auth.js";
1
+ import { finishOAuthFlow, requestOAuthToken, useAuthFields, useAuthRedirect, usePlaygroundAuth } from "./auth.js";
2
2
  import { createBrowserFetcher } from "./fetcher.js";
3
3
  import { usePlayground } from "./use-playground.js";
4
- export { createBrowserFetcher, requestOAuthToken, useAuthFields, usePlayground, usePlaygroundAuth };
4
+ export { createBrowserFetcher, finishOAuthFlow, requestOAuthToken, useAuthFields, useAuthRedirect, usePlayground, usePlaygroundAuth };
@@ -1,9 +1,11 @@
1
1
  import { BrowserFetcherOptions, FetchResult } from "./fetcher.js";
2
- import { AuthField, AuthRequirement, OAuthFlowInput, OAuthFlowType } from "./auth.js";
2
+ import { AuthField, AuthProvider, AuthRequirement, OAuthFlowInput, OAuthFlowType } from "./auth.js";
3
3
  import { JsonSchema } from "@fumadocs/json-schema";
4
4
  import { Stf } from "@fumari/stf";
5
5
  //#region src/playground/use-playground.d.ts
6
6
  export interface PlaygroundOptions {
7
+ /** handle security schemes, before the built-in providers */
8
+ authProviders?: AuthProvider[];
7
9
  /** customise the auth fields, like their default values */
8
10
  transformAuthInputs?: (fields: AuthField[]) => AuthField[];
9
11
  fetchOptions?: BrowserFetcherOptions;
@@ -27,7 +29,7 @@ export interface PlaygroundAuth {
27
29
  * `implicit` and `authorizationCode` leave the page without a token, `flowReturned` is set when they return.
28
30
  */
29
31
  authorize: (field: AuthField, input: OAuthInput) => Promise<string | undefined>;
30
- /** an OAuth flow started here has returned to the page */
32
+ /** a flow started here has returned to the page */
31
33
  flowReturned: boolean;
32
34
  }
33
35
  export interface OAuthInput extends Partial<Pick<OAuthFlowInput, 'clientId' | 'clientSecret' | 'username' | 'password' | 'clientAuth'>> {
@@ -58,5 +60,5 @@ export interface Playground {
58
60
  *
59
61
  * Edits are synced to the example request, so code usages follow them.
60
62
  */
61
- export declare function usePlayground({ transformAuthInputs, fetchOptions }?: PlaygroundOptions): Playground;
63
+ export declare function usePlayground({ authProviders, transformAuthInputs, fetchOptions }?: PlaygroundOptions): Playground;
62
64
  //#endregion
@@ -1,27 +1,34 @@
1
1
  "use client";
2
2
  import { pathnameFromRequest } from "../requests/generators/index.js";
3
- import { requestOAuthToken, useAuthFields, usePlaygroundAuth } from "./auth.js";
4
- import { useServer } from "../utils/use-server.js";
5
- import { useOpenAPI } from "../utils/create-page.js";
6
- import { getPreferredType } from "../utils/schema.js";
7
3
  import { encodeRequestData } from "../requests/media/encode.js";
4
+ import { getPreferredType } from "../utils/schema.js";
5
+ import { useServer } from "../utils/use-server.js";
8
6
  import { useExampleRequests, useOperation } from "../operation.js";
7
+ import { readPendingFlow, requestOAuthToken, useAuthFields, usePlaygroundAuth } from "./auth.js";
8
+ import { useOpenAPI } from "../utils/create-page.js";
9
9
  import { createBrowserFetcher } from "./fetcher.js";
10
- import { useEffect, useEffectEvent, useMemo, useState } from "react";
10
+ import { useEffect, useEffectEvent, useMemo, useState, useSyncExternalStore } from "react";
11
11
  import { useStf } from "@fumari/stf";
12
+ import { useOnChange } from "fumadocs-core/utils/use-on-change";
12
13
  //#region src/playground/use-playground.tsx
14
+ const subscribeNever = () => () => {};
13
15
  /**
14
16
  * The state of an API playground under `<OperationProvider />`: a form starting from the selected example request, its auth and the request it sends.
15
17
  *
16
18
  * Edits are synced to the example request, so code usages follow them.
17
19
  */
18
- function usePlayground({ transformAuthInputs, fetchOptions } = {}) {
20
+ function usePlayground({ authProviders, transformAuthInputs, fetchOptions } = {}) {
19
21
  const { mediaAdapters, proxyUrl, oauthRedirectUrl } = useOpenAPI();
20
22
  const { path, method, operation, parameters: groups, requestBody } = useOperation();
21
23
  const { items: examples, selected, update } = useExampleRequests();
22
24
  const { resolveUrl } = useServer();
23
25
  const origin = `${method} ${path}`;
24
- const flowReturned = usePlaygroundAuth().origin === origin;
26
+ const oauthOrigin = usePlaygroundAuth().origin;
27
+ const returnedScheme = useSyncExternalStore(subscribeNever, () => {
28
+ const flow = readPendingFlow();
29
+ if (flow?.origin === origin) return flow.scheme;
30
+ }, () => void 0);
31
+ const flowReturned = returnedScheme !== void 0 || oauthOrigin === origin;
25
32
  const [response, setResponse] = useState();
26
33
  const [isSending, setSending] = useState(false);
27
34
  let body;
@@ -46,16 +53,21 @@ function usePlayground({ transformAuthInputs, fetchOptions } = {}) {
46
53
  const engine = stf.dataEngine;
47
54
  const auth = useAuthFields(engine, {
48
55
  operation,
56
+ providers: authProviders,
49
57
  transform: transformAuthInputs
50
58
  });
51
59
  function getRequestData() {
52
- return {
53
- ...auth.mapValues(engine.getData()),
60
+ return auth.mapValues({
61
+ ...engine.getData(),
54
62
  method,
55
63
  bodyMediaType: body?.mediaType
56
- };
64
+ });
57
65
  }
58
66
  const syncExample = useEffectEvent(() => update(getRequestData()));
67
+ useOnChange(returnedScheme, (scheme) => {
68
+ const idx = auth.requirements.findIndex((req) => req.some((item) => item.id === scheme));
69
+ if (idx !== -1) auth.select(idx);
70
+ });
59
71
  useEffect(() => {
60
72
  if (engine.getData() !== defaultValues) engine.reset(defaultValues);
61
73
  }, [engine, defaultValues]);