fumadocs-openapi 12.1.0 → 12.2.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 +63 -17
  3. package/dist/.translations/keys.js +63 -17
  4. package/dist/operation.d.ts +6 -1
  5. package/dist/operation.js +2 -4
  6. package/dist/packages/shared-api/dist/components/select.js +8 -7
  7. package/dist/playground/auth.d.ts +13 -3
  8. package/dist/playground/auth.js +58 -46
  9. package/dist/playground/fetcher.d.ts +8 -0
  10. package/dist/playground/fetcher.js +30 -1
  11. package/dist/playground/index.d.ts +2 -1
  12. package/dist/playground/index.js +2 -1
  13. package/dist/playground/use-playground.d.ts +62 -0
  14. package/dist/playground/use-playground.js +140 -0
  15. package/dist/ui/components/endpoint.js +37 -0
  16. package/dist/ui/operation/index.js +6 -14
  17. package/dist/ui/playground/client.d.ts +9 -26
  18. package/dist/ui/playground/client.js +150 -390
  19. package/dist/ui/playground/components/fields.js +693 -0
  20. package/dist/ui/playground/components/oauth-panel.js +182 -0
  21. package/dist/ui/playground/components/request-panel.js +480 -0
  22. package/dist/ui/playground/components/response-panel.js +150 -0
  23. package/dist/ui/playground/components/result-display.d.ts +1 -0
  24. package/dist/ui/playground/components/result-display.js +187 -147
  25. package/dist/ui/playground/components/segmented.js +21 -0
  26. package/dist/ui/playground/components/server-select.js +100 -89
  27. package/dist/ui/playground/components/url-bar.js +96 -0
  28. package/dist/ui/playground/status-info.js +32 -45
  29. package/dist/utils/document/load.js +1 -1
  30. package/package.json +10 -10
  31. package/dist/packages/shared-api/dist/components/collapsible.d.ts +0 -7
  32. package/dist/packages/shared-api/dist/components/collapsible.js +0 -16
  33. package/dist/packages/shared-api/dist/components/dialog.js +0 -55
  34. package/dist/packages/shared-api/dist/components/input.js +0 -14
  35. package/dist/packages/shared-api/dist/components/label.js +0 -11
  36. package/dist/packages/shared-api/dist/components/playground/inputs.js +0 -439
  37. package/dist/ui/playground/components/oauth-dialog.js +0 -259
@@ -1,11 +1,10 @@
1
1
  "use client";
2
2
  import { useQuery } from "../packages/shared-api/dist/utils/use-query.js";
3
3
  import { useOpenAPI } from "../utils/create-page.js";
4
- import { createContext, use, useCallback, useEffect, useMemo, useState } from "react";
4
+ import { createContext, use, useCallback, useEffect, useEffectEvent, useMemo, useState } from "react";
5
5
  import { jsx } from "react/jsx-runtime";
6
6
  import { useListener } from "@fumari/stf";
7
7
  import { arrayStartsWith, objectGet, objectSet } from "@fumari/stf/lib/utils";
8
- import { useOnChange } from "fumadocs-core/utils/use-on-change";
9
8
  //#region src/playground/auth.tsx
10
9
  const pendingFlowKey = "fumadocs-openapi-oauth";
11
10
  /**
@@ -14,7 +13,7 @@ const pendingFlowKey = "fumadocs-openapi-oauth";
14
13
  * `implicit` and `authorizationCode` leave the page instead: the token is picked up on return,
15
14
  * in `usePlaygroundAuth().store`.
16
15
  */
17
- async function requestOAuthToken(scheme, type, { schemeId, scopes, clientId, clientSecret, username, password, clientAuth, serverUrl, redirectUrl }) {
16
+ async function requestOAuthToken(scheme, type, { schemeId, scopes, clientId, clientSecret, username, password, clientAuth, serverUrl, redirectUrl, origin }) {
18
17
  const flows = scheme.flows ?? {};
19
18
  const scope = scopes.join(" ");
20
19
  if (type === "implicit" || type === "authorizationCode") {
@@ -25,8 +24,10 @@ async function requestOAuthToken(scheme, type, { schemeId, scopes, clientId, cli
25
24
  scheme: schemeId,
26
25
  client_id: clientId,
27
26
  client_secret: clientSecret,
27
+ client_auth: clientAuth,
28
28
  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
29
+ token_url: "tokenUrl" in flow ? new URL(flow.tokenUrl, serverUrl).href : void 0,
30
+ origin
30
31
  };
31
32
  sessionStorage.setItem(pendingFlowKey, JSON.stringify(pending));
32
33
  if (redirectUrl) document.cookie = `fumadocs-openapi-oauth=${encodeURIComponent(window.location.pathname)}; path=/`;
@@ -42,27 +43,28 @@ async function requestOAuthToken(scheme, type, { schemeId, scopes, clientId, cli
42
43
  if (type !== "password" && type !== "clientCredentials") return;
43
44
  const flow = flows[type];
44
45
  if (!flow) return;
45
- const headers = {};
46
46
  const body = new URLSearchParams({ scope });
47
47
  if (type === "password") {
48
48
  body.set("grant_type", "password");
49
49
  body.set("username", username);
50
50
  body.set("password", password);
51
51
  } else body.set("grant_type", "client_credentials");
52
- if (clientAuth === "header") headers.Authorization = `Basic ${btoa(`${encodeURIComponent(clientId)}:${encodeURIComponent(clientSecret)}`)}`;
52
+ return fetchToken(new URL(flow.tokenUrl, serverUrl).href, body, {
53
+ client_id: clientId,
54
+ client_secret: clientSecret,
55
+ client_auth: clientAuth
56
+ });
57
+ }
58
+ async function fetchToken(tokenUrl, body, { client_id, client_secret, client_auth }) {
59
+ const headers = { "Content-Type": "application/x-www-form-urlencoded" };
60
+ if (client_auth === "header" && client_secret) headers.Authorization = `Basic ${btoa(`${encodeURIComponent(client_id)}:${encodeURIComponent(client_secret)}`)}`;
53
61
  else {
54
- if (clientId) body.set("client_id", clientId);
55
- if (clientSecret) body.set("client_secret", clientSecret);
62
+ if (client_id) body.set("client_id", client_id);
63
+ if (client_secret) body.set("client_secret", client_secret);
56
64
  }
57
- return fetchToken(new URL(flow.tokenUrl, serverUrl).href, body, headers);
58
- }
59
- async function fetchToken(tokenUrl, body, headers = {}) {
60
65
  const res = await fetch(tokenUrl, {
61
66
  method: "POST",
62
- headers: {
63
- ...headers,
64
- "Content-Type": "application/x-www-form-urlencoded"
65
- },
67
+ headers,
66
68
  body
67
69
  });
68
70
  if (!res.ok) throw new Error(await res.text());
@@ -77,23 +79,34 @@ function usePlaygroundAuth() {
77
79
  }
78
80
  function AuthProvider({ children }) {
79
81
  const [store, setStore] = useState({});
82
+ 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);
88
+ };
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
+ }
80
97
  const authCodeQuery = useQuery(async (code, flow) => {
81
98
  const token = await fetchToken(flow.token_url, new URLSearchParams({
82
99
  grant_type: "authorization_code",
83
100
  code,
84
- redirect_uri: flow.redirect_uri,
101
+ redirect_uri: flow.redirect_uri
102
+ }), flow);
103
+ save(flow.scheme, {
104
+ type: "authorization_code",
85
105
  client_id: flow.client_id,
86
- client_secret: flow.client_secret
87
- }));
88
- setStore((s) => ({
89
- ...s,
90
- [flow.scheme]: {
91
- type: "authorization_code",
92
- client_id: flow.client_id,
93
- client_secret: flow.client_secret,
94
- token
95
- }
96
- }));
106
+ client_secret: flow.client_secret,
107
+ client_auth: flow.client_auth,
108
+ token
109
+ });
97
110
  });
98
111
  useEffect(() => {
99
112
  const stored = sessionStorage.getItem(pendingFlowKey);
@@ -104,28 +117,29 @@ function AuthProvider({ children }) {
104
117
  const code = query.get("code");
105
118
  const token = hash.get("access_token");
106
119
  if (code && query.get("state") === flow.state) authCodeQuery.start(code, flow);
107
- else if (token && hash.get("state") === flow.state) setStore((s) => ({
108
- ...s,
109
- [flow.scheme]: {
110
- type: "implicit",
111
- client_id: flow.client_id,
112
- token: `${hash.get("token_type") ?? "Bearer"} ${token}`
113
- }
114
- }));
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
+ });
115
125
  else return;
126
+ setOrigin(flow.origin);
116
127
  sessionStorage.removeItem(pendingFlowKey);
117
128
  window.history.replaceState(null, "", window.location.pathname);
118
129
  }, []);
119
130
  return /* @__PURE__ */ jsx(AuthContext, {
120
131
  value: useMemo(() => ({
121
132
  store,
122
- updatedSchemeId: Object.keys(store)[0] ?? null,
123
133
  isLoading: authCodeQuery.isLoading,
124
- error: authCodeQuery.error
134
+ error: authCodeQuery.error,
135
+ origin,
136
+ subscribe
125
137
  }), [
126
138
  store,
127
139
  authCodeQuery.isLoading,
128
- authCodeQuery.error
140
+ authCodeQuery.error,
141
+ origin,
142
+ subscribe
129
143
  ]),
130
144
  children
131
145
  });
@@ -134,7 +148,7 @@ function AuthProvider({ children }) {
134
148
  * The auth fields of an API playground: the values it persists, and the request data they encode into.
135
149
  */
136
150
  function useAuthFields(engine, { operation, transform } = {}) {
137
- const auth = usePlaygroundAuth();
151
+ const { subscribe } = usePlaygroundAuth();
138
152
  const { storageKeyPrefix, doc } = useOpenAPI();
139
153
  const { dereferenced, resolve } = doc;
140
154
  const schemes = dereferenced.components?.securitySchemes;
@@ -215,21 +229,19 @@ function useAuthFields(engine, { operation, transform } = {}) {
215
229
  }
216
230
  }
217
231
  });
218
- useOnChange(auth.updatedSchemeId, () => {
219
- const { updatedSchemeId } = auth;
220
- if (!updatedSchemeId) return;
221
- const { token } = auth.store[updatedSchemeId];
222
- const field = fields.find((field) => field.schemeId === updatedSchemeId);
232
+ const onToken = useEffectEvent((schemeId, token) => {
233
+ const field = fields.find((field) => field.schemeId === schemeId);
223
234
  if (field) {
224
235
  engine.update(field.fieldName, token);
225
236
  return;
226
237
  }
227
- const idx = requirements.findIndex((req) => req.some((item) => item.id === updatedSchemeId));
238
+ const idx = requirements.findIndex((req) => req.some((item) => item.id === schemeId));
228
239
  if (idx !== -1) {
229
- localStorage.setItem(`${storageKeyPrefix}auth-${updatedSchemeId}`, JSON.stringify(token));
240
+ localStorage.setItem(`${storageKeyPrefix}auth-${schemeId}`, JSON.stringify(token));
230
241
  select(idx);
231
242
  }
232
243
  });
244
+ useEffect(() => subscribe(onToken), [subscribe]);
233
245
  return {
234
246
  requirements,
235
247
  selected,
@@ -14,6 +14,14 @@ export interface FetchResponseResult {
14
14
  status: number;
15
15
  headers: Headers;
16
16
  body: ArrayBuffer;
17
+ /** how long the request took, in milliseconds */
18
+ duration: number;
19
+ /** the media type of `Content-Type` like `application/json` */
20
+ mediaType?: string;
21
+ /** the file name from `Content-Disposition`, without directories */
22
+ fileName?: string;
23
+ /** decode the body with the charset of `Content-Type`, UTF-8 by default */
24
+ text: () => string;
17
25
  }
18
26
  export interface Fetcher {
19
27
  /**
@@ -1,5 +1,7 @@
1
1
  import { resolveMediaAdapter } from "../requests/media/resolve-adapter.js";
2
+ import { require_fast_content_type_parse } from "../node_modules/.pnpm/fast-content-type-parse@4.0.0/node_modules/fast-content-type-parse/index.js";
2
3
  //#region src/playground/fetcher.ts
4
+ var import_fast_content_type_parse = require_fast_content_type_parse();
3
5
  function createBrowserFetcher(adapters, { proxyUrl, proxyForwardCookie = true, requestTimeout = 10, onRequestInit } = {}) {
4
6
  return { async fetch(url, data) {
5
7
  let requestUrl = new URL(url, document.baseURI);
@@ -39,13 +41,25 @@ function createBrowserFetcher(adapters, { proxyUrl, proxyForwardCookie = true, r
39
41
  document.cookie = segs.join("; ");
40
42
  }
41
43
  if (onRequestInit) requestInit = await onRequestInit(requestInit);
44
+ const start = performance.now();
42
45
  return fetch(requestUrl, requestInit).then(async (res) => {
46
+ const body = await res.arrayBuffer();
47
+ const { type, parameters } = (0, import_fast_content_type_parse.safeParse)(res.headers.get("Content-Type") ?? "");
43
48
  return {
44
49
  type: "response",
45
50
  url: res.url,
46
51
  status: res.status,
47
52
  headers: res.headers,
48
- body: await res.arrayBuffer()
53
+ body,
54
+ duration: performance.now() - start,
55
+ mediaType: type || void 0,
56
+ fileName: getFileName(res.headers),
57
+ text() {
58
+ try {
59
+ if (parameters.charset) return new TextDecoder(parameters.charset).decode(body);
60
+ } catch {}
61
+ return new TextDecoder().decode(body);
62
+ }
49
63
  };
50
64
  }).catch((e) => {
51
65
  return {
@@ -56,5 +70,20 @@ function createBrowserFetcher(adapters, { proxyUrl, proxyForwardCookie = true, r
56
70
  });
57
71
  } };
58
72
  }
73
+ /** prefers `filename*` (RFC 6266) */
74
+ function getFileName(headers) {
75
+ const disposition = headers.get("Content-Disposition");
76
+ if (!disposition) return;
77
+ const extended = /(?:^|;)\s*filename\*\s*=\s*[^']*'[^']*'([^\s;"]+)/i.exec(disposition);
78
+ let name;
79
+ if (extended) try {
80
+ name = decodeURIComponent(extended[1]);
81
+ } catch {}
82
+ if (!name) {
83
+ const match = /(?:^|;)\s*filename\s*=\s*(?:"((?:\\.|[^"\\])*)"|([^\s;]+))/i.exec(disposition);
84
+ name = match?.[1]?.replace(/\\(.)/g, "$1") ?? match?.[2];
85
+ }
86
+ return name?.replace(/^.*[/\\]/, "") || void 0;
87
+ }
59
88
  //#endregion
60
89
  export { createBrowserFetcher };
@@ -1,3 +1,4 @@
1
1
  import { BrowserFetcherOptions, FetchErrorResult, FetchResponseResult, FetchResult, Fetcher, createBrowserFetcher } from "./fetcher.js";
2
2
  import { AuthField, AuthRequirement, OAuthFlowType, requestOAuthToken, useAuthFields, usePlaygroundAuth } from "./auth.js";
3
- export { type AuthField, type AuthRequirement, type BrowserFetcherOptions, type FetchErrorResult, type FetchResponseResult, type FetchResult, type Fetcher, type OAuthFlowType, createBrowserFetcher, requestOAuthToken, useAuthFields, usePlaygroundAuth };
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 };
@@ -1,3 +1,4 @@
1
1
  import { requestOAuthToken, useAuthFields, usePlaygroundAuth } from "./auth.js";
2
2
  import { createBrowserFetcher } from "./fetcher.js";
3
- export { createBrowserFetcher, requestOAuthToken, useAuthFields, usePlaygroundAuth };
3
+ import { usePlayground } from "./use-playground.js";
4
+ export { createBrowserFetcher, requestOAuthToken, useAuthFields, usePlayground, usePlaygroundAuth };
@@ -0,0 +1,62 @@
1
+ import { BrowserFetcherOptions, FetchResult } from "./fetcher.js";
2
+ import { AuthField, AuthRequirement, OAuthFlowInput, OAuthFlowType } from "./auth.js";
3
+ import { JsonSchema } from "@fumadocs/json-schema";
4
+ import { Stf } from "@fumari/stf";
5
+ //#region src/playground/use-playground.d.ts
6
+ export interface PlaygroundOptions {
7
+ /** customise the auth fields, like their default values */
8
+ transformAuthInputs?: (fields: AuthField[]) => AuthField[];
9
+ fetchOptions?: BrowserFetcherOptions;
10
+ }
11
+ export interface RequestBodyInfo {
12
+ /** the preferred one of its media types */
13
+ mediaType: string;
14
+ schema: JsonSchema;
15
+ }
16
+ export interface PlaygroundAuth {
17
+ /** the security requirements of the operation, one of them authorizes the request */
18
+ requirements: AuthRequirement[][];
19
+ /** index of the selected requirement, `-1` when the operation needs no authorization */
20
+ selected: number;
21
+ select: (index: number) => void;
22
+ /** the fields of the selected requirement */
23
+ fields: AuthField[];
24
+ /**
25
+ * Obtain the access token of an OAuth 2.0 field, and write it into the field.
26
+ *
27
+ * `implicit` and `authorizationCode` leave the page without a token, `flowReturned` is set when they return.
28
+ */
29
+ authorize: (field: AuthField, input: OAuthInput) => Promise<string | undefined>;
30
+ /** an OAuth flow started here has returned to the page */
31
+ flowReturned: boolean;
32
+ }
33
+ export interface OAuthInput extends Partial<Pick<OAuthFlowInput, 'clientId' | 'clientSecret' | 'username' | 'password' | 'clientAuth'>> {
34
+ type: OAuthFlowType;
35
+ /** defaults to the scopes required by the operation */
36
+ scopes?: string[];
37
+ }
38
+ export interface PlaygroundResponse {
39
+ /** unique among the responses of a playground */
40
+ id: number;
41
+ result: FetchResult;
42
+ }
43
+ export interface Playground {
44
+ /** the form, holding the `path`, `query`, `header`, `cookie` and `body` of request */
45
+ stf: Stf;
46
+ /** the request body edited in the form */
47
+ body?: RequestBodyInfo;
48
+ auth: PlaygroundAuth;
49
+ /** send the request of form */
50
+ send: () => Promise<void>;
51
+ isSending: boolean;
52
+ /** the response of last request */
53
+ response?: PlaygroundResponse;
54
+ clearResponse: () => void;
55
+ }
56
+ /**
57
+ * The state of an API playground under `<OperationProvider />`: a form starting from the selected example request, its auth and the request it sends.
58
+ *
59
+ * Edits are synced to the example request, so code usages follow them.
60
+ */
61
+ export declare function usePlayground({ transformAuthInputs, fetchOptions }?: PlaygroundOptions): Playground;
62
+ //#endregion
@@ -0,0 +1,140 @@
1
+ "use client";
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
+ import { encodeRequestData } from "../requests/media/encode.js";
8
+ import { useExampleRequests, useOperation } from "../operation.js";
9
+ import { createBrowserFetcher } from "./fetcher.js";
10
+ import { useEffect, useEffectEvent, useMemo, useState } from "react";
11
+ import { useStf } from "@fumari/stf";
12
+ //#region src/playground/use-playground.tsx
13
+ /**
14
+ * The state of an API playground under `<OperationProvider />`: a form starting from the selected example request, its auth and the request it sends.
15
+ *
16
+ * Edits are synced to the example request, so code usages follow them.
17
+ */
18
+ function usePlayground({ transformAuthInputs, fetchOptions } = {}) {
19
+ const { mediaAdapters, proxyUrl, oauthRedirectUrl } = useOpenAPI();
20
+ const { path, method, operation, parameters: groups, requestBody } = useOperation();
21
+ const { items: examples, selected, update } = useExampleRequests();
22
+ const { resolveUrl } = useServer();
23
+ const origin = `${method} ${path}`;
24
+ const flowReturned = usePlaygroundAuth().origin === origin;
25
+ const [response, setResponse] = useState();
26
+ const [isSending, setSending] = useState(false);
27
+ let body;
28
+ if (requestBody) {
29
+ const mediaType = getPreferredType(requestBody.content);
30
+ body = {
31
+ mediaType,
32
+ schema: requestBody.content[mediaType].schema ?? true
33
+ };
34
+ }
35
+ const defaultValues = useMemo(() => {
36
+ const data = examples.find((example) => example.id === selected)?.data;
37
+ return {
38
+ path: data?.path ?? {},
39
+ query: data?.query ?? {},
40
+ header: data?.header ?? {},
41
+ cookie: data?.cookie ?? {},
42
+ body: data?.body ?? {}
43
+ };
44
+ }, [examples, selected]);
45
+ const stf = useStf({ defaultValues });
46
+ const engine = stf.dataEngine;
47
+ const auth = useAuthFields(engine, {
48
+ operation,
49
+ transform: transformAuthInputs
50
+ });
51
+ function getRequestData() {
52
+ return {
53
+ ...auth.mapValues(engine.getData()),
54
+ method,
55
+ bodyMediaType: body?.mediaType
56
+ };
57
+ }
58
+ const syncExample = useEffectEvent(() => update(getRequestData()));
59
+ useEffect(() => {
60
+ if (engine.getData() !== defaultValues) engine.reset(defaultValues);
61
+ }, [engine, defaultValues]);
62
+ const initAuth = auth.init;
63
+ useEffect(() => {
64
+ const reset = initAuth();
65
+ syncExample();
66
+ let timer;
67
+ const listener = { onUpdate() {
68
+ window.clearTimeout(timer);
69
+ timer = window.setTimeout(syncExample, 400);
70
+ } };
71
+ engine.listen(listener);
72
+ return () => {
73
+ engine.unlisten(listener);
74
+ window.clearTimeout(timer);
75
+ reset();
76
+ };
77
+ }, [
78
+ engine,
79
+ defaultValues,
80
+ initAuth
81
+ ]);
82
+ return {
83
+ stf,
84
+ body,
85
+ auth: {
86
+ requirements: auth.requirements,
87
+ selected: auth.selected,
88
+ select: auth.select,
89
+ fields: auth.fields,
90
+ async authorize(field, { type, scopes = field.scopes, clientAuth = "header", ...input }) {
91
+ const token = await requestOAuthToken(field.scheme, type, {
92
+ clientId: input.clientId ?? "",
93
+ clientSecret: input.clientSecret ?? "",
94
+ username: input.username ?? "",
95
+ password: input.password ?? "",
96
+ scopes,
97
+ clientAuth,
98
+ schemeId: field.schemeId,
99
+ serverUrl: resolveUrl(),
100
+ redirectUrl: oauthRedirectUrl,
101
+ origin
102
+ });
103
+ if (token) engine.update(field.fieldName, token);
104
+ return token;
105
+ },
106
+ flowReturned
107
+ },
108
+ isSending,
109
+ response,
110
+ async send() {
111
+ if (isSending) return;
112
+ setSending(true);
113
+ const parameters = groups.flatMap((group) => group.items);
114
+ let result;
115
+ try {
116
+ const data = encodeRequestData(getRequestData(), mediaAdapters, parameters);
117
+ result = await createBrowserFetcher(mediaAdapters, {
118
+ proxyUrl,
119
+ ...fetchOptions
120
+ }).fetch(resolveUrl(pathnameFromRequest(path, data)), data);
121
+ } catch (e) {
122
+ result = {
123
+ type: "client_error",
124
+ url: path,
125
+ message: String(e)
126
+ };
127
+ }
128
+ setResponse((prev) => ({
129
+ id: (prev?.id ?? 0) + 1,
130
+ result
131
+ }));
132
+ setSending(false);
133
+ },
134
+ clearResponse() {
135
+ setResponse(void 0);
136
+ }
137
+ };
138
+ }
139
+ //#endregion
140
+ export { usePlayground };
@@ -0,0 +1,37 @@
1
+ import { MethodLabel } from "./method-label.js";
2
+ import { cn } from "../../utils/cn.js";
3
+ import { Fragment } from "react";
4
+ import { jsx, jsxs } from "react/jsx-runtime";
5
+ //#region src/ui/components/endpoint.tsx
6
+ function EndpointBar({ method, route, deprecated = false, children, ...props }) {
7
+ return /* @__PURE__ */ jsxs("div", {
8
+ ...props,
9
+ className: cn("not-prose flex min-h-11 items-center gap-3 rounded-xl border bg-fd-card p-1.5 ps-3.5 text-sm text-fd-card-foreground", props.className),
10
+ children: [
11
+ /* @__PURE__ */ jsx(MethodLabel, {
12
+ className: "text-xs",
13
+ children: method
14
+ }),
15
+ /* @__PURE__ */ jsx(Route, {
16
+ route,
17
+ className: cn("flex-1", deprecated && "line-through")
18
+ }),
19
+ children
20
+ ]
21
+ });
22
+ }
23
+ function Route({ route, ...props }) {
24
+ return /* @__PURE__ */ jsx("div", {
25
+ ...props,
26
+ className: cn("flex min-w-0 items-center overflow-x-auto font-mono text-[0.8125rem] text-nowrap [scrollbar-width:none]", props.className),
27
+ children: route.split("/").map((part, index) => /* @__PURE__ */ jsxs(Fragment, { children: [index > 0 && /* @__PURE__ */ jsx("span", {
28
+ className: "text-fd-muted-foreground",
29
+ children: "/"
30
+ }), part.startsWith("{") && part.endsWith("}") ? /* @__PURE__ */ jsx("span", {
31
+ className: "rounded-md bg-fd-primary/10 px-1 text-fd-primary",
32
+ children: part
33
+ }) : part] }, index))
34
+ });
35
+ }
36
+ //#endregion
37
+ export { EndpointBar };
@@ -12,6 +12,7 @@ import { RequestTabs } from "./request-tabs.js";
12
12
  import { cn } from "../../utils/cn.js";
13
13
  import { SelectTab, SelectTabTrigger, SelectTabs } from "../../packages/shared-api/dist/components/select-tab.js";
14
14
  import { Heading } from "../components/heading.js";
15
+ import { EndpointBar } from "../components/endpoint.js";
15
16
  import PlaygroundClient from "../playground/client.js";
16
17
  import { Fragment } from "react";
17
18
  import { Fragment as Fragment$1, jsx, jsxs } from "react/jsx-runtime";
@@ -234,20 +235,11 @@ function OperationContent({ showTitle, showDescription, headingLevel = 2 }) {
234
235
  method,
235
236
  operation,
236
237
  pathItem
237
- }) : /* @__PURE__ */ jsx(PlaygroundClient, {
238
- ...options,
239
- writeOnly: true,
240
- readOnly: false
241
- });
242
- } else apiPlayground = /* @__PURE__ */ jsxs("div", {
243
- className: "flex flex-row items-center gap-2.5 p-3 rounded-xl border bg-fd-card text-fd-card-foreground not-prose",
244
- children: [/* @__PURE__ */ jsx(MethodLabel, {
245
- className: "text-xs",
246
- children: method
247
- }), /* @__PURE__ */ jsx("code", {
248
- className: cn("flex-1 overflow-auto text-nowrap text-[0.8125rem] text-fd-muted-foreground", operation.deprecated && "line-through"),
249
- children: path
250
- })]
238
+ }) : /* @__PURE__ */ jsx(PlaygroundClient, { ...options });
239
+ } else apiPlayground = /* @__PURE__ */ jsx(EndpointBar, {
240
+ method,
241
+ route: path,
242
+ deprecated: operation.deprecated
251
243
  });
252
244
  const slots = {
253
245
  header: headNode,
@@ -1,12 +1,16 @@
1
1
  import { ParameterObject } from "../../types.js";
2
- import { BrowserFetcherOptions } from "../../playground/fetcher.js";
3
2
  import { DefaultResultDisplay, ResultDisplayProps } from "./components/result-display.js";
4
- import { Collapsible } from "../../packages/shared-api/dist/components/collapsible.js";
5
- import { AuthField } from "../../playground/auth.js";
3
+ import { PlaygroundOptions, RequestBodyInfo } from "../../playground/use-playground.js";
6
4
  import { ComponentProps, FC, ReactNode } from "react";
7
- import { JsonSchema } from "@fumadocs/json-schema";
8
5
  import { FieldKey } from "@fumari/stf";
9
6
  //#region src/ui/playground/client.d.ts
7
+ export interface PlaygroundClientProps extends ComponentProps<'div'>, PlaygroundClientOptions {
8
+ /** @deprecated it defaults to `true` for requests */
9
+ writeOnly?: boolean;
10
+ /** @deprecated it defaults to `false` for requests */
11
+ readOnly?: boolean;
12
+ }
13
+ /** @deprecated use `usePlayground().stf` for the form */
10
14
  export interface FormValues extends Record<string, unknown> {
11
15
  path: Record<string, unknown>;
12
16
  query: Record<string, unknown>;
@@ -14,23 +18,9 @@ export interface FormValues extends Record<string, unknown> {
14
18
  cookie: Record<string, unknown>;
15
19
  body: unknown;
16
20
  }
17
- export interface PlaygroundClientProps extends Omit<ComponentProps<'form'>, 'method'>, PlaygroundClientOptions {
18
- writeOnly: boolean;
19
- readOnly: boolean;
20
- }
21
- export interface CollapsiblePanelProps extends Omit<ComponentProps<typeof Collapsible>, 'title'> {
22
- 'data-type': 'authorization' | 'body' | ParamType;
23
- title: ReactNode;
24
- }
25
- export interface PlaygroundClientOptions {
26
- /**
27
- * transform fields for auth-specific parameters (e.g. header)
28
- */
29
- transformAuthInputs?: (fields: AuthField[]) => AuthField[];
30
- fetchOptions?: BrowserFetcherOptions;
21
+ export interface PlaygroundClientOptions extends PlaygroundOptions {
31
22
  components?: {
32
23
  ResultDisplay?: FC<ResultDisplayProps>;
33
- CollapsiblePanel?: FC<CollapsiblePanelProps>;
34
24
  };
35
25
  /**
36
26
  * render the parameter inputs of API endpoint.
@@ -48,14 +38,7 @@ export interface PlaygroundClientOptions {
48
38
  */
49
39
  renderBodyField?: (fieldName: 'body', info: RequestBodyInfo) => ReactNode;
50
40
  }
51
- interface RequestBodyInfo {
52
- schema: JsonSchema;
53
- mediaType: string;
54
- }
55
41
  export default function PlaygroundClient({ writeOnly, readOnly, transformAuthInputs, fetchOptions, components, renderParameterField, renderBodyField, ...rest }: PlaygroundClientProps): import("react").JSX.Element;
56
- declare const ParamTypes: readonly ['path', 'header', 'cookie', 'query'];
57
- type ParamType = (typeof ParamTypes)[number];
58
- export declare function DefaultCollapsiblePanel({ title, children, ...props }: CollapsiblePanelProps): import("react").JSX.Element;
59
42
  export declare const Custom: {
60
43
  useController(fieldName: FieldKey, options?: {
61
44
  defaultValue?: unknown;