fumadocs-openapi 12.1.1 → 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 +62 -17
  3. package/dist/.translations/keys.js +62 -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 +5 -1
  8. package/dist/playground/auth.js +7 -2
  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 +149 -389
  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 +185 -168
  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
@@ -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;