fumadocs-openapi 12.3.0 → 12.4.1
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.
- package/css/generated/shared.css +1 -1
- package/dist/.translations/index.d.ts +3 -1
- package/dist/.translations/keys.js +3 -1
- package/dist/operation.js +4 -4
- package/dist/packages/shared-api/dist/components/defaults.js +1 -1
- package/dist/playground/auth.d.ts +61 -7
- package/dist/playground/auth.js +192 -95
- package/dist/playground/fetcher.d.ts +1 -1
- package/dist/playground/index.d.ts +2 -2
- package/dist/playground/index.js +2 -2
- package/dist/playground/use-playground.d.ts +5 -3
- package/dist/playground/use-playground.js +22 -10
- package/dist/requests/generators/csharp.js +11 -21
- package/dist/requests/generators/curl.js +12 -14
- package/dist/requests/generators/go.js +22 -33
- package/dist/requests/generators/index.d.ts +1 -1
- package/dist/requests/generators/java.js +33 -37
- package/dist/requests/generators/javascript.js +13 -20
- package/dist/requests/generators/python.js +12 -17
- package/dist/requests/generators/rust.js +15 -20
- package/dist/requests/index.d.ts +1 -1
- package/dist/requests/media/adapter.d.ts +0 -1
- package/dist/requests/media/adapter.js +50 -42
- package/dist/requests/media/encode.d.ts +1 -1
- package/dist/requests/media/encode.js +1 -1
- package/dist/requests/string-utils.js +14 -6
- package/dist/ui/operation/index.js +1 -1
- package/dist/ui/operation/request-tabs.js +1 -1
- package/dist/ui/operation/response-tabs.js +1 -1
- package/dist/ui/operation/usage-tabs.js +1 -1
- package/dist/ui/playground/client.d.ts +1 -1
- package/dist/ui/playground/client.js +18 -15
- package/dist/ui/playground/components/fields.js +35 -14
- package/dist/ui/playground/components/oauth-panel.js +71 -21
- package/dist/ui/playground/components/request-panel.js +79 -93
- package/dist/utils/create-page.js +2 -2
- package/dist/utils/get-example-requests.js +1 -1
- package/dist/utils/pages/to-text.js +1 -1
- package/dist/utils/use-server.d.ts +3 -3
- package/dist/utils/use-server.js +2 -2
- package/package.json +3 -3
|
@@ -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 };
|
package/dist/playground/index.js
CHANGED
|
@@ -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
|
-
/**
|
|
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
|
|
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
|
-
...
|
|
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]);
|
|
@@ -1,39 +1,29 @@
|
|
|
1
|
-
import { doubleQuote } from "../string-utils.js";
|
|
2
|
-
import {
|
|
1
|
+
import { cookieString, doubleQuote } from "../string-utils.js";
|
|
2
|
+
import { generateBodyExample } from "../media/adapter.js";
|
|
3
3
|
//#region src/requests/generators/csharp.ts
|
|
4
4
|
const csharp = {
|
|
5
5
|
label: "C#",
|
|
6
6
|
lang: "csharp",
|
|
7
7
|
generate(data, { mediaAdapters }) {
|
|
8
|
-
const s = [];
|
|
9
8
|
const imports = /* @__PURE__ */ new Set([
|
|
10
9
|
"System",
|
|
11
10
|
"System.Net.Http",
|
|
12
11
|
"System.Text"
|
|
13
12
|
]);
|
|
14
|
-
const
|
|
15
|
-
let body;
|
|
16
|
-
if (data.body && data.bodyMediaType) body = resolveMediaAdapter(data.bodyMediaType, mediaAdapters)?.generateExample(data, {
|
|
13
|
+
const body = generateBodyExample(data, mediaAdapters, {
|
|
17
14
|
lang: "csharp",
|
|
18
|
-
addImport(
|
|
19
|
-
imports.add(from);
|
|
20
|
-
}
|
|
15
|
+
addImport: (name) => imports.add(name)
|
|
21
16
|
});
|
|
22
|
-
|
|
17
|
+
const s = Array.from(imports, (name) => `using ${name};`);
|
|
23
18
|
s.push("");
|
|
24
19
|
if (body) s.push(body, "");
|
|
25
20
|
s.push("var client = new HttpClient();");
|
|
26
|
-
const
|
|
27
|
-
|
|
28
|
-
|
|
29
|
-
|
|
30
|
-
|
|
31
|
-
|
|
32
|
-
s.push(...headerLines);
|
|
33
|
-
const method = data.method[0].toUpperCase() + data.method.slice(1).toLowerCase() + "Async";
|
|
34
|
-
if (body) s.push(`var response = await client.${method}("${data.url}", body);`);
|
|
35
|
-
else s.push(`var response = await client.${method}("${data.url}");`);
|
|
36
|
-
s.push("var responseBody = await response.Content.ReadAsStringAsync();");
|
|
21
|
+
for (const k in data.header) s.push(`client.DefaultRequestHeaders.Add(${doubleQuote(k)}, ${doubleQuote(data.header[k].value)});`);
|
|
22
|
+
const cookie = cookieString(data.cookie);
|
|
23
|
+
if (cookie) s.push(`client.DefaultRequestHeaders.Add("cookie", ${doubleQuote(cookie)});`);
|
|
24
|
+
const method = data.method[0].toUpperCase() + data.method.slice(1).toLowerCase();
|
|
25
|
+
const content = body ? " { Content = body }" : "";
|
|
26
|
+
s.push(`var request = new HttpRequestMessage(HttpMethod.${method}, ${doubleQuote(data.url)})${content};`, "var response = await client.SendAsync(request);", "var responseBody = await response.Content.ReadAsStringAsync();");
|
|
37
27
|
return s.join("\n");
|
|
38
28
|
}
|
|
39
29
|
};
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import {
|
|
1
|
+
import { inputToString } from "../string-utils.js";
|
|
2
2
|
import { resolveMediaAdapter } from "../media/resolve-adapter.js";
|
|
3
3
|
//#region src/requests/generators/curl.ts
|
|
4
4
|
const curl = {
|
|
@@ -6,25 +6,23 @@ const curl = {
|
|
|
6
6
|
lang: "bash",
|
|
7
7
|
generate(data, { mediaAdapters }) {
|
|
8
8
|
const s = [];
|
|
9
|
-
s.push(`curl -X ${data.method.toUpperCase()}
|
|
10
|
-
for (const header in data.header) {
|
|
11
|
-
|
|
12
|
-
s.push(`-H "${value}"`);
|
|
13
|
-
}
|
|
14
|
-
for (const k in data.cookie) {
|
|
15
|
-
const param = data.cookie[k];
|
|
16
|
-
s.push(`--cookie ${doubleQuote(`${k}=${param.value}`)}`);
|
|
17
|
-
}
|
|
9
|
+
s.push(`curl -X ${data.method.toUpperCase()} ${shellQuote(data.url)}`);
|
|
10
|
+
for (const header in data.header) s.push(`-H ${shellQuote(`${header}: ${data.header[header].value}`)}`);
|
|
11
|
+
for (const k in data.cookie) s.push(`--cookie ${shellQuote(`${k}=${data.cookie[k].value}`)}`);
|
|
18
12
|
if (data.body && data.bodyMediaType === "multipart/form-data") {
|
|
19
13
|
if (typeof data.body !== "object") throw new Error("[CURL] request body must be an object.");
|
|
20
|
-
for (const [key, value] of Object.entries(data.body)) s.push(`-F ${key}=${
|
|
14
|
+
for (const [key, value] of Object.entries(data.body)) s.push(`-F ${shellQuote(`${key}=${inputToString(value)}`)}`);
|
|
21
15
|
} else if (data.body && data.bodyMediaType && resolveMediaAdapter(data.bodyMediaType, mediaAdapters)) {
|
|
22
|
-
const escaped =
|
|
23
|
-
s.push(`-H
|
|
16
|
+
const escaped = shellQuote(inputToString(data.body, data.bodyMediaType));
|
|
17
|
+
s.push(`-H 'Content-Type: ${data.bodyMediaType}'`);
|
|
24
18
|
s.push(`-d ${escaped}`);
|
|
25
19
|
}
|
|
26
|
-
return s.
|
|
20
|
+
return s.join(" \\\n ");
|
|
27
21
|
}
|
|
28
22
|
};
|
|
23
|
+
/** single quotes keep the string literal, each `'` closes them to add an escaped quote */
|
|
24
|
+
function shellQuote(str) {
|
|
25
|
+
return `'${str.replaceAll("'", `'\\''`)}'`;
|
|
26
|
+
}
|
|
29
27
|
//#endregion
|
|
30
28
|
export { curl };
|
|
@@ -1,49 +1,38 @@
|
|
|
1
|
-
import { doubleQuote, indent } from "../string-utils.js";
|
|
2
|
-
import {
|
|
1
|
+
import { cookieString, doubleQuote, indent } from "../string-utils.js";
|
|
2
|
+
import { generateBodyExample } from "../media/adapter.js";
|
|
3
3
|
//#region src/requests/generators/go.ts
|
|
4
4
|
const go = {
|
|
5
5
|
label: "Go",
|
|
6
6
|
lang: "go",
|
|
7
7
|
generate(data, { mediaAdapters }) {
|
|
8
|
-
const imports = [
|
|
8
|
+
const imports = /* @__PURE__ */ new Set([
|
|
9
9
|
"fmt",
|
|
10
|
-
"
|
|
11
|
-
"
|
|
12
|
-
];
|
|
13
|
-
const
|
|
14
|
-
|
|
15
|
-
|
|
16
|
-
|
|
17
|
-
const
|
|
18
|
-
if (
|
|
19
|
-
|
|
20
|
-
|
|
21
|
-
|
|
22
|
-
|
|
23
|
-
|
|
24
|
-
|
|
25
|
-
|
|
26
|
-
imports.push(from);
|
|
27
|
-
}
|
|
28
|
-
});
|
|
10
|
+
"io",
|
|
11
|
+
"net/http"
|
|
12
|
+
]);
|
|
13
|
+
const body = generateBodyExample(data, mediaAdapters, {
|
|
14
|
+
lang: "go",
|
|
15
|
+
addImport: (name) => imports.add(name)
|
|
16
|
+
});
|
|
17
|
+
const s = [`url := ${doubleQuote(data.url)}`];
|
|
18
|
+
if (body) s.push(body);
|
|
19
|
+
s.push(`req, _ := http.NewRequest("${data.method.toUpperCase()}", url, ${body ? "body" : "nil"})`);
|
|
20
|
+
for (const k in data.header) s.push(`req.Header.Add(${doubleQuote(k)}, ${doubleQuote(data.header[k].value)})`);
|
|
21
|
+
const cookie = cookieString(data.cookie);
|
|
22
|
+
if (cookie) s.push(`req.Header.Add("Cookie", ${doubleQuote(cookie)})`);
|
|
23
|
+
if (body) {
|
|
24
|
+
const type = data.bodyMediaType === "multipart/form-data" ? "mp.FormDataContentType()" : doubleQuote(data.bodyMediaType);
|
|
25
|
+
s.push(`req.Header.Add("Content-Type", ${type})`);
|
|
29
26
|
}
|
|
27
|
+
s.push("res, _ := http.DefaultClient.Do(req)", "defer res.Body.Close()", "resBody, _ := io.ReadAll(res.Body)", "", "fmt.Println(res)", "fmt.Println(string(resBody))");
|
|
30
28
|
return `package main
|
|
31
29
|
|
|
32
30
|
import (
|
|
33
|
-
${indent(
|
|
31
|
+
${indent(Array.from(imports, (name) => `"${name}"`).join("\n"))}
|
|
34
32
|
)
|
|
35
33
|
|
|
36
34
|
func main() {
|
|
37
|
-
${
|
|
38
|
-
${body ? indent(body) : ""}
|
|
39
|
-
req, _ := http.NewRequest("${data.method.toUpperCase()}", url, ${body ? "body" : "nil"})
|
|
40
|
-
${indent(Array.from(headers.entries()).map(([key, value]) => `req.Header.Add("${key}", ${value})`).join("\n"))}
|
|
41
|
-
res, _ := http.DefaultClient.Do(req)
|
|
42
|
-
defer res.Body.Close()
|
|
43
|
-
body, _ := ioutil.ReadAll(res.Body)
|
|
44
|
-
|
|
45
|
-
fmt.Println(res)
|
|
46
|
-
fmt.Println(string(body))
|
|
35
|
+
${indent(s.join("\n"))}
|
|
47
36
|
}`;
|
|
48
37
|
}
|
|
49
38
|
};
|
|
@@ -1,5 +1,5 @@
|
|
|
1
|
-
import { MediaAdapter } from "../media/adapter.js";
|
|
2
1
|
import { RequestData } from "../types.js";
|
|
2
|
+
import { MediaAdapter } from "../media/adapter.js";
|
|
3
3
|
import { CodeUsageGenerator as CodeUsageGenerator$1, CodeUsageGeneratorRegistry as CodeUsageGeneratorRegistry$1, InlineCodeUsageGenerator as InlineCodeUsageGenerator$1, codegen_d_exports } from "../../packages/shared-api/dist/codegen.js";
|
|
4
4
|
//#region src/requests/generators/index.d.ts
|
|
5
5
|
export declare function pathnameFromRequest(pathname: string, { path, query }: RequestData): string;
|
|
@@ -1,56 +1,52 @@
|
|
|
1
|
-
import { doubleQuote, indent } from "../string-utils.js";
|
|
2
|
-
import {
|
|
1
|
+
import { cookieString, doubleQuote, indent, inputToString } from "../string-utils.js";
|
|
2
|
+
import { generateBodyExample } from "../media/adapter.js";
|
|
3
3
|
//#region src/requests/generators/java.ts
|
|
4
|
+
const boundary = "form-data-boundary";
|
|
4
5
|
const java = {
|
|
5
6
|
label: "Java",
|
|
6
7
|
lang: "java",
|
|
7
8
|
generate(data, { mediaAdapters }) {
|
|
8
|
-
const s = [];
|
|
9
|
-
const headers = { ...data.header };
|
|
10
9
|
const imports = /* @__PURE__ */ new Set([
|
|
11
10
|
"java.net.URI",
|
|
12
11
|
"java.net.http.HttpClient",
|
|
13
12
|
"java.net.http.HttpRequest",
|
|
14
|
-
"java.net.http.HttpResponse"
|
|
15
|
-
"java.net.http.HttpResponse.BodyHandlers",
|
|
16
|
-
"java.time.Duration"
|
|
13
|
+
"java.net.http.HttpResponse"
|
|
17
14
|
]);
|
|
18
|
-
|
|
19
|
-
|
|
15
|
+
const multipart = data.bodyMediaType === "multipart/form-data";
|
|
16
|
+
const body = multipart ? multipartBody(data.body) : generateBodyExample(data, mediaAdapters, {
|
|
20
17
|
lang: "java",
|
|
21
|
-
addImport(
|
|
22
|
-
imports.add(specifier);
|
|
23
|
-
}
|
|
18
|
+
addImport: (name) => imports.add(name)
|
|
24
19
|
});
|
|
25
|
-
|
|
26
|
-
|
|
27
|
-
if (body)
|
|
28
|
-
|
|
29
|
-
|
|
30
|
-
s.push(indent(".build();"));
|
|
31
|
-
s.push("");
|
|
32
|
-
s.push("HttpRequest.Builder requestBuilder = HttpRequest.newBuilder()");
|
|
33
|
-
s.push(indent(`.uri(URI.create(${doubleQuote(data.url)}))`));
|
|
34
|
-
for (const [key, param] of Object.entries(headers)) s.push(indent(`.header(${doubleQuote(key)}, ${doubleQuote(param.value)})`));
|
|
35
|
-
if (data.bodyMediaType) s.push(indent(`.header("Content-Type", "${data.bodyMediaType}")`));
|
|
36
|
-
const cookies = Object.entries(data.cookie);
|
|
37
|
-
if (cookies.length > 0) {
|
|
38
|
-
const cookieString = cookies.map(([key, param]) => `${key}=${param.value}`).join("; ");
|
|
39
|
-
s.push(indent(`.header("Cookie", ${doubleQuote(cookieString)})`));
|
|
20
|
+
const request = [`.uri(URI.create(${doubleQuote(data.url)}))`];
|
|
21
|
+
for (const k in data.header) request.push(`.header(${doubleQuote(k)}, ${doubleQuote(data.header[k].value)})`);
|
|
22
|
+
if (body) {
|
|
23
|
+
const type = multipart ? `multipart/form-data; boundary=${boundary}` : data.bodyMediaType;
|
|
24
|
+
request.push(`.header("Content-Type", ${doubleQuote(type)})`);
|
|
40
25
|
}
|
|
41
|
-
const
|
|
42
|
-
|
|
43
|
-
|
|
26
|
+
const cookie = cookieString(data.cookie);
|
|
27
|
+
if (cookie) request.push(`.header("Cookie", ${doubleQuote(cookie)})`);
|
|
28
|
+
request.push(`.method("${data.method.toUpperCase()}", ${body ? "body" : "HttpRequest.BodyPublishers.noBody()"})`, ".build();");
|
|
29
|
+
const s = Array.from(imports, (name) => `import ${name};`);
|
|
44
30
|
s.push("");
|
|
45
|
-
s.push(
|
|
46
|
-
s.push(
|
|
47
|
-
|
|
48
|
-
|
|
49
|
-
|
|
50
|
-
|
|
51
|
-
|
|
31
|
+
if (body) s.push(body);
|
|
32
|
+
s.push("HttpClient client = HttpClient.newHttpClient();", "HttpRequest request = HttpRequest.newBuilder()", indent(request.join("\n")), "", `try {
|
|
33
|
+
HttpResponse<String> response = client.send(request, HttpResponse.BodyHandlers.ofString());
|
|
34
|
+
System.out.println("Status code: " + response.statusCode());
|
|
35
|
+
System.out.println("Response body: " + response.body());
|
|
36
|
+
} catch (Exception e) {
|
|
37
|
+
e.printStackTrace();
|
|
38
|
+
}`);
|
|
52
39
|
return s.join("\n");
|
|
53
40
|
}
|
|
54
41
|
};
|
|
42
|
+
function multipartBody(body) {
|
|
43
|
+
if (!body) return;
|
|
44
|
+
let text = "";
|
|
45
|
+
for (const [key, value] of Object.entries(body)) {
|
|
46
|
+
if (value == null) continue;
|
|
47
|
+
text += `--${boundary}\r\nContent-Disposition: form-data; name=${JSON.stringify(key)}\r\n\r\n${inputToString(value)}\r\n`;
|
|
48
|
+
}
|
|
49
|
+
return `var body = HttpRequest.BodyPublishers.ofString(${JSON.stringify(`${text}--${boundary}--\r\n`)});`;
|
|
50
|
+
}
|
|
55
51
|
//#endregion
|
|
56
52
|
export { java };
|
|
@@ -1,36 +1,29 @@
|
|
|
1
|
-
import { doubleQuote, indent } from "../string-utils.js";
|
|
2
|
-
import {
|
|
1
|
+
import { cookieString, doubleQuote, indent } from "../string-utils.js";
|
|
2
|
+
import { generateBodyExample } from "../media/adapter.js";
|
|
3
3
|
//#region src/requests/generators/javascript.ts
|
|
4
4
|
const javascript = {
|
|
5
5
|
label: "JavaScript",
|
|
6
6
|
lang: "js",
|
|
7
7
|
generate(data, { mediaAdapters }) {
|
|
8
8
|
const s = [];
|
|
9
|
-
const
|
|
10
|
-
const headers = {};
|
|
11
|
-
options.set("method", `"${data.method.toUpperCase()}"`);
|
|
12
|
-
if (data.bodyMediaType) headers["Content-Type"] = data.bodyMediaType;
|
|
13
|
-
for (const [k, v] of Object.entries(data.header)) headers[k] = v.value;
|
|
14
|
-
const cookies = Object.entries(data.cookie);
|
|
15
|
-
if (cookies.length > 0) headers["cookie"] = cookies.map(([key, param]) => `${key}=${param.value}`).join("; ");
|
|
16
|
-
if (Object.keys(headers).length > 0) options.set("headers", JSON.stringify(headers, null, 2));
|
|
17
|
-
let body;
|
|
18
|
-
if (data.body && data.bodyMediaType) body = resolveMediaAdapter(data.bodyMediaType, mediaAdapters)?.generateExample(data, {
|
|
9
|
+
const body = generateBodyExample(data, mediaAdapters, {
|
|
19
10
|
lang: "js",
|
|
20
11
|
addImport(from, name) {
|
|
21
|
-
s.
|
|
12
|
+
s.push(`import { ${name} } from "${from}"`);
|
|
22
13
|
}
|
|
23
14
|
});
|
|
15
|
+
const headers = {};
|
|
16
|
+
if (body && data.bodyMediaType !== "multipart/form-data") headers["Content-Type"] = data.bodyMediaType;
|
|
17
|
+
for (const k in data.header) headers[k] = data.header[k].value;
|
|
18
|
+
const cookie = cookieString(data.cookie);
|
|
19
|
+
if (cookie) headers.cookie = cookie;
|
|
20
|
+
const options = [`method: "${data.method.toUpperCase()}"`];
|
|
21
|
+
if (Object.keys(headers).length > 0) options.push(`headers: ${JSON.stringify(headers, null, 2)}`);
|
|
24
22
|
if (body) {
|
|
25
23
|
s.push(body);
|
|
26
|
-
options.
|
|
27
|
-
}
|
|
28
|
-
const params = [doubleQuote(data.url)];
|
|
29
|
-
if (options.size > 0) {
|
|
30
|
-
const str = Array.from(options.entries()).map(([k, v]) => indent(k === v ? k : `${k}: ${v}`)).join(",\n");
|
|
31
|
-
params.push(`{\n${str}\n}`);
|
|
24
|
+
options.push("body");
|
|
32
25
|
}
|
|
33
|
-
s.push(`fetch(${
|
|
26
|
+
s.push(`fetch(${doubleQuote(data.url)}, {\n${indent(options.join(",\n"))}\n})`);
|
|
34
27
|
return s.join("\n\n");
|
|
35
28
|
}
|
|
36
29
|
};
|
|
@@ -1,30 +1,25 @@
|
|
|
1
1
|
import { doubleQuote } from "../string-utils.js";
|
|
2
|
-
import {
|
|
2
|
+
import { generateBodyExample } from "../media/adapter.js";
|
|
3
3
|
//#region src/requests/generators/python.ts
|
|
4
4
|
const python = {
|
|
5
5
|
label: "Python",
|
|
6
6
|
lang: "python",
|
|
7
7
|
generate(data, { mediaAdapters }) {
|
|
8
|
-
const
|
|
9
|
-
const
|
|
8
|
+
const imports = /* @__PURE__ */ new Set(["requests"]);
|
|
9
|
+
const body = generateBodyExample(data, mediaAdapters, { lang: "python" });
|
|
10
10
|
const params = [`"${data.method.toUpperCase()}"`, "url"];
|
|
11
|
-
|
|
12
|
-
|
|
13
|
-
if (
|
|
14
|
-
const adapter = resolveMediaAdapter(data.bodyMediaType, mediaAdapters);
|
|
11
|
+
const headers = {};
|
|
12
|
+
if (body && data.bodyMediaType === "multipart/form-data") params.push("files = body");
|
|
13
|
+
else if (body) {
|
|
15
14
|
headers["Content-Type"] = data.bodyMediaType;
|
|
16
|
-
|
|
17
|
-
if (body) params.push("data = body");
|
|
15
|
+
params.push("data = body");
|
|
18
16
|
}
|
|
19
|
-
for (const
|
|
17
|
+
for (const k in data.header) headers[k] = data.header[k].value;
|
|
20
18
|
if (Object.keys(headers).length > 0) params.push(`headers = ${generatePythonObject(headers, imports)}`);
|
|
21
|
-
const
|
|
22
|
-
|
|
23
|
-
|
|
24
|
-
|
|
25
|
-
params.push(`cookies = ${generatePythonObject(cookies, imports)}`);
|
|
26
|
-
}
|
|
27
|
-
return `${Array.from(imports).map((name) => "import " + name).join("\n")}
|
|
19
|
+
const cookies = {};
|
|
20
|
+
for (const k in data.cookie) cookies[k] = data.cookie[k].value;
|
|
21
|
+
if (Object.keys(cookies).length > 0) params.push(`cookies = ${generatePythonObject(cookies, imports)}`);
|
|
22
|
+
return `${Array.from(imports, (name) => `import ${name}`).join("\n")}
|
|
28
23
|
|
|
29
24
|
url = ${doubleQuote(data.url)}
|
|
30
25
|
${body ?? ""}
|
|
@@ -1,33 +1,28 @@
|
|
|
1
|
-
import { doubleQuote, indent } from "../string-utils.js";
|
|
2
|
-
import {
|
|
1
|
+
import { cookieString, doubleQuote, indent } from "../string-utils.js";
|
|
2
|
+
import { generateBodyExample } from "../media/adapter.js";
|
|
3
3
|
//#region src/requests/generators/rust.ts
|
|
4
4
|
const rust = {
|
|
5
5
|
label: "Rust",
|
|
6
6
|
lang: "rust",
|
|
7
7
|
generate(data, { mediaAdapters }) {
|
|
8
|
-
const
|
|
9
|
-
|
|
10
|
-
const
|
|
11
|
-
|
|
12
|
-
|
|
13
|
-
if (
|
|
14
|
-
|
|
15
|
-
|
|
16
|
-
|
|
17
|
-
}
|
|
18
|
-
return `use reqwest::{Result, Client};
|
|
8
|
+
const body = generateBodyExample(data, mediaAdapters, { lang: "rust" });
|
|
9
|
+
const request = [`.request(Method::${data.method.toUpperCase()}, url)`];
|
|
10
|
+
for (const k in data.header) request.push(`.header(${doubleQuote(k)}, ${doubleQuote(data.header[k].value)})`);
|
|
11
|
+
const cookie = cookieString(data.cookie);
|
|
12
|
+
if (cookie) request.push(`.header("Cookie", ${doubleQuote(cookie)})`);
|
|
13
|
+
if (body && data.bodyMediaType === "multipart/form-data") request.push(".multipart(body)");
|
|
14
|
+
else if (body) request.push(`.header("Content-Type", ${doubleQuote(data.bodyMediaType)})`, ".body(body)");
|
|
15
|
+
request.push(".send()", ".await?", ".text()", ".await?;");
|
|
16
|
+
return `use reqwest::{Client, Method, Result};
|
|
19
17
|
|
|
18
|
+
#[tokio::main]
|
|
20
19
|
async fn main() -> Result<()> {
|
|
21
20
|
let client = Client::new();
|
|
22
21
|
|
|
23
|
-
let url =
|
|
24
|
-
${body ? indent(body)
|
|
22
|
+
let url = ${doubleQuote(data.url)};
|
|
23
|
+
${body ? `${indent(body)}\n` : ""}
|
|
25
24
|
let res = client
|
|
26
|
-
|
|
27
|
-
${headers.size <= 0 ? "" : indent(Array.from(headers.entries()).map(([key, value]) => ` .header("${key}", ${value})`).join("\n")) + "\n"}${body ? " .body(body)\n" : ""} .send()
|
|
28
|
-
.await?
|
|
29
|
-
.text()
|
|
30
|
-
.await?;
|
|
25
|
+
${indent(request.join("\n"), 2)}
|
|
31
26
|
|
|
32
27
|
println!("{}", res);
|
|
33
28
|
Ok(())
|
package/dist/requests/index.d.ts
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { resolveMediaAdapter } from "./media/resolve-adapter.js";
|
|
2
1
|
import { EncodedParameter, EncodedParameterMultiple, encodeRequestData } from "./media/encode.js";
|
|
3
2
|
import { RawRequestData, RequestData } from "./types.js";
|
|
3
|
+
import { resolveMediaAdapter } from "./media/resolve-adapter.js";
|
|
4
4
|
export { type EncodedParameter, type EncodedParameterMultiple, type RawRequestData, type RequestData, encodeRequestData, resolveMediaAdapter };
|