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,39 +1,29 @@
1
- import { doubleQuote } from "../string-utils.js";
2
- import { resolveMediaAdapter } from "../media/resolve-adapter.js";
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 headers = { ...data.header };
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(from) {
19
- imports.add(from);
20
- }
15
+ addImport: (name) => imports.add(name)
21
16
  });
22
- for (const specifier of imports) s.push(`using ${specifier};`);
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 headerLines = [];
27
- function addHeader(key, value) {
28
- headerLines.push(`client.DefaultRequestHeaders.Add("${key}", ${doubleQuote(value)});`);
29
- }
30
- for (const k in headers) addHeader(k, headers[k].value);
31
- if (Object.keys(data.cookie).length > 0) addHeader("cookie", Object.entries(data.cookie).map(([key, param]) => `${key}=${param.value}`).join("; "));
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 { doubleQuote, indent, inputToString, singleQuote } from "../string-utils.js";
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()} "${data.url}"`);
10
- for (const header in data.header) {
11
- const value = `${header}: ${data.header[header].value}`;
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}=${doubleQuote(inputToString(value))}`);
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 = singleQuote(inputToString(data.body, data.bodyMediaType));
23
- s.push(`-H "Content-Type: ${data.bodyMediaType}"`);
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.flatMap((v, i) => indent(v, i > 0 ? 1 : 0)).join(" \\\n");
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 { resolveMediaAdapter } from "../media/resolve-adapter.js";
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
- "net/http",
11
- "io/ioutil"
12
- ];
13
- const headers = /* @__PURE__ */ new Map();
14
- const variables = /* @__PURE__ */ new Map();
15
- variables.set("url", doubleQuote(data.url));
16
- for (const header in data.header) headers.set(header, doubleQuote(data.header[header].value));
17
- const cookies = Object.entries(data.cookie);
18
- if (cookies.length > 0) headers.set("Cookie", doubleQuote(cookies.map(([k, param]) => `${k}=${param.value}`).join("; ")));
19
- let body;
20
- if (data.body && data.bodyMediaType) {
21
- const adapter = resolveMediaAdapter(data.bodyMediaType, mediaAdapters);
22
- headers.set("Content-Type", `"${data.bodyMediaType}"`);
23
- body = adapter?.generateExample(data, {
24
- lang: "go",
25
- addImport(from) {
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(imports.map((v) => `"${v}"`).join("\n"))}
31
+ ${indent(Array.from(imports, (name) => `"${name}"`).join("\n"))}
34
32
  )
35
33
 
36
34
  func main() {
37
- ${Array.from(variables.entries()).map(([k, v]) => indent(`${k} := ${v}`)).join("\n")}
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 { resolveMediaAdapter } from "../media/resolve-adapter.js";
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
- let body;
19
- if (data.body && data.bodyMediaType) body = resolveMediaAdapter(data.bodyMediaType, mediaAdapters)?.generateExample(data, {
15
+ const multipart = data.bodyMediaType === "multipart/form-data";
16
+ const body = multipart ? multipartBody(data.body) : generateBodyExample(data, mediaAdapters, {
20
17
  lang: "java",
21
- addImport(specifier) {
22
- imports.add(specifier);
23
- }
18
+ addImport: (name) => imports.add(name)
24
19
  });
25
- for (const value of imports.values()) s.push(`import ${value};`);
26
- s.push("");
27
- if (body) s.push(body);
28
- s.push("HttpClient client = HttpClient.newBuilder()");
29
- s.push(indent(".connectTimeout(Duration.ofSeconds(10))"));
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 arg = body ? "body" : "";
42
- s.push(indent(`.${data.method.toUpperCase()}(${arg})`));
43
- s.push(indent(".build();"));
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("try {");
46
- s.push(indent("HttpResponse<String> response = client.send(requestBuilder.build(), BodyHandlers.ofString());"));
47
- s.push(indent("System.out.println(\"Status code: \" + response.statusCode());"));
48
- s.push(indent("System.out.println(\"Response body: \" + response.body());"));
49
- s.push("} catch (Exception e) {");
50
- s.push(indent("e.printStackTrace();"));
51
- s.push("}");
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 { resolveMediaAdapter } from "../media/resolve-adapter.js";
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 options = /* @__PURE__ */ new Map();
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.unshift(`import { ${name} } from "${from}"`);
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.set("body", "body");
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(${params.join(", ")})`);
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 { resolveMediaAdapter } from "../media/resolve-adapter.js";
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 headers = {};
9
- const imports = /* @__PURE__ */ new Set();
8
+ const imports = /* @__PURE__ */ new Set(["requests"]);
9
+ const body = generateBodyExample(data, mediaAdapters, { lang: "python" });
10
10
  const params = [`"${data.method.toUpperCase()}"`, "url"];
11
- let body;
12
- imports.add("requests");
13
- if (data.body && data.bodyMediaType) {
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
- body = adapter?.generateExample(data, { lang: "python" });
17
- if (body) params.push("data = body");
15
+ params.push("data = body");
18
16
  }
19
- for (const [k, v] of Object.entries(data.header)) headers[k] = v.value;
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 inputCookies = Object.entries(data.cookie);
22
- if (inputCookies.length > 0) {
23
- const cookies = {};
24
- for (const [k, v] of inputCookies) cookies[k] = v.value;
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 { resolveMediaAdapter } from "../media/resolve-adapter.js";
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 headers = /* @__PURE__ */ new Map();
9
- for (const header in data.header) headers.set(header, doubleQuote(data.header[header].value));
10
- const cookies = Object.entries(data.cookie);
11
- if (cookies.length > 0) headers.set("Cookie", doubleQuote(cookies.map(([k, param]) => `${k}=${param.value}`).join("; ")));
12
- let body;
13
- if (data.body && data.bodyMediaType) {
14
- const adapter = resolveMediaAdapter(data.bodyMediaType, mediaAdapters);
15
- headers.set("Content-Type", `"${data.bodyMediaType}"`);
16
- body = adapter?.generateExample(data, { lang: "rust" });
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 = "${data.url}";
24
- ${body ? indent(body) + "\n" : ""}
22
+ let url = ${doubleQuote(data.url)};
23
+ ${body ? `${indent(body)}\n` : ""}
25
24
  let res = client
26
- .${data.method.toLowerCase()}(url)
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(())
@@ -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 };
@@ -1,4 +1,3 @@
1
- import { resolveMediaAdapter } from "./resolve-adapter.js";
2
1
  //#region src/requests/media/adapter.d.ts
3
2
  interface BaseContext {
4
3
  /**
@@ -1,6 +1,6 @@
1
1
  import { __toESM } from "../../_virtual/_rolldown/runtime.js";
2
2
  import { require_js2xml } from "../../node_modules/.pnpm/xml-js@1.6.11/node_modules/xml-js/lib/js2xml.js";
3
- import { backtickQuote, inputToString, rustRawStringLiteral, tripleDoubleQuote } from "../string-utils.js";
3
+ import { backtickQuote, goRawStringLiteral, inputToString, rustRawStringLiteral, tripleDoubleQuote } from "../string-utils.js";
4
4
  import { resolveMediaAdapter } from "./resolve-adapter.js";
5
5
  //#region src/requests/media/adapter.ts
6
6
  var import_js2xml = /* @__PURE__ */ __toESM(require_js2xml(), 1);
@@ -68,30 +68,37 @@ const defaultAdapters = {
68
68
  return formData;
69
69
  },
70
70
  generateExample(data, ctx) {
71
- if (ctx.lang === "python") return `body = ${JSON.stringify(data.body, null, 2)}`;
72
71
  const s = [];
73
- if (ctx.lang === "js") {
74
- s.push(`const body = new FormData();`);
75
- for (const [key, value] of Object.entries(data.body)) s.push(`body.set(${key}, ${JSON.stringify(inputToString(value))})`);
76
- }
77
- if (ctx.lang === "go") {
78
- const { addImport } = ctx;
79
- addImport("mime/multipart");
80
- addImport("bytes");
81
- s.push("body := new(bytes.Buffer)");
82
- s.push("mp := multipart.NewWriter(payload)");
83
- for (const [key, value] of Object.entries(data.body)) {
84
- if (!value) continue;
85
- const escaped = backtickQuote(inputToString(value, "application/json"));
86
- s.push(`mp.WriteField("${key}", ${escaped})`);
72
+ const fields = [];
73
+ for (const [key, value] of Object.entries(data.body)) if (value != null) fields.push([JSON.stringify(key), inputToString(value)]);
74
+ switch (ctx.lang) {
75
+ case "js":
76
+ s.push("const body = new FormData();");
77
+ for (const [key, value] of fields) s.push(`body.set(${key}, ${JSON.stringify(value)})`);
78
+ break;
79
+ case "python":
80
+ s.push("body = {");
81
+ for (const [key, value] of fields) s.push(` ${key}: (None, ${JSON.stringify(value)}),`);
82
+ s.push("}");
83
+ break;
84
+ case "go": {
85
+ const { addImport } = ctx;
86
+ addImport("bytes");
87
+ addImport("mime/multipart");
88
+ s.push("body := new(bytes.Buffer)", "mp := multipart.NewWriter(body)");
89
+ for (const [key, value] of fields) s.push(`mp.WriteField(${key}, ${JSON.stringify(value)})`);
90
+ s.push("mp.Close()");
91
+ break;
87
92
  }
93
+ case "csharp":
94
+ s.push("var body = new MultipartFormDataContent();");
95
+ for (const [key, value] of fields) s.push(`body.Add(new StringContent(${JSON.stringify(value)}), ${key});`);
96
+ break;
97
+ case "rust":
98
+ s.push("let body = reqwest::multipart::Form::new()");
99
+ for (const [key, value] of fields) s.push(` .text(${key}, ${JSON.stringify(value)})`);
100
+ s[s.length - 1] += ";";
88
101
  }
89
- if (ctx.lang === "java") {
90
- const { addImport } = ctx;
91
- addImport("java.net.http.HttpRequest.BodyPublishers");
92
- s.push(`var body = BodyPublishers.ofByteArray(new byte[] { ... });`);
93
- }
94
- if (ctx.lang === "csharp") s.push(`var body = new MultipartFormDataContent();`);
95
102
  if (s.length > 0) return s.join("\n");
96
103
  }
97
104
  },
@@ -102,27 +109,28 @@ const defaultAdapters = {
102
109
  generateExample() {}
103
110
  }
104
111
  };
112
+ /**
113
+ * Generate the code that inits a `body` variable for the request body, `undefined` when unsupported.
114
+ */
115
+ function generateBodyExample(data, adapters, ctx) {
116
+ if (!data.body || !data.bodyMediaType) return;
117
+ return resolveMediaAdapter(data.bodyMediaType, adapters)?.generateExample(data, ctx);
118
+ }
105
119
  function str(init, mediaType, ctx) {
106
- if (ctx.lang === "js") {
107
- if (mediaType === "application/json") return `const body = JSON.stringify(${JSON.stringify(init, null, 2)})`;
108
- return `const body = ${backtickQuote(inputToString(init, mediaType))}`;
109
- }
110
- if (ctx.lang === "python") return `body = ${tripleDoubleQuote(inputToString(init, mediaType))}`;
111
- if (ctx.lang === "go") {
112
- const { addImport } = ctx;
113
- addImport("strings");
114
- return `body := strings.NewReader(${backtickQuote(inputToString(init, mediaType))})`;
115
- }
116
- if (ctx.lang === "java") {
117
- const { addImport } = ctx;
118
- addImport("java.net.http.HttpRequest.BodyPublishers");
119
- return `var body = BodyPublishers.ofString(${tripleDoubleQuote(inputToString(init, mediaType))});`;
120
- }
121
- if (ctx.lang === "csharp") {
122
- const input = `\n${inputToString(init, mediaType)}\n`;
123
- return `var body = new StringContent(${tripleDoubleQuote(input)}, Encoding.UTF8, "${mediaType}");`;
120
+ if (ctx.lang === "js" && mediaType === "application/json") return `const body = JSON.stringify(${JSON.stringify(init, null, 2)})`;
121
+ const text = inputToString(init, mediaType);
122
+ switch (ctx.lang) {
123
+ case "js": return `const body = ${backtickQuote(text)}`;
124
+ case "python": return `body = ${tripleDoubleQuote(text)}`;
125
+ case "go":
126
+ ctx.addImport("strings");
127
+ return `body := strings.NewReader(${goRawStringLiteral(text)})`;
128
+ case "java":
129
+ ctx.addImport("java.net.http.HttpRequest.BodyPublishers");
130
+ return `var body = BodyPublishers.ofString(${tripleDoubleQuote(`\n${text}`)});`;
131
+ case "csharp": return `var body = new StringContent("""\n${text}\n""", Encoding.UTF8, "${mediaType}");`;
132
+ case "rust": return `let body = ${rustRawStringLiteral(text)};`;
124
133
  }
125
- if (ctx.lang === "rust") return `let body = ${rustRawStringLiteral(inputToString(init, mediaType))};`;
126
134
  }
127
135
  //#endregion
128
- export { defaultAdapters, resolveMediaAdapter };
136
+ export { defaultAdapters, generateBodyExample };
@@ -1,5 +1,5 @@
1
- import { MediaAdapter } from "./adapter.js";
2
1
  import { RawRequestData, RequestData } from "../types.js";
2
+ import { MediaAdapter } from "./adapter.js";
3
3
  import { ParameterObject } from "../../types.js";
4
4
  //#region src/requests/media/encode.d.ts
5
5
  export interface EncodedParameter {
@@ -75,7 +75,7 @@ function serializePathParameter(field, value, output) {
75
75
  case "matrix": {
76
76
  const specifier = `;${name}=`;
77
77
  if (Array.isArray(value)) {
78
- output[field.name] = { value: explode ? `${specifier}${value.join(",")}` : `${specifier}${value.join(specifier)}` };
78
+ output[field.name] = { value: explode ? `${specifier}${value.join(specifier)}` : `${specifier}${value.join(",")}` };
79
79
  break;
80
80
  }
81
81
  if (typeof value === "object") {
@@ -21,10 +21,12 @@ function inputToString(value, format = "application/json") {
21
21
  });
22
22
  }
23
23
  /**
24
- * Returns the input string wrapped in single quotes, escaping internal single quotes and backslashes.
24
+ * Returns the value of a `Cookie` header with the given cookies.
25
25
  */
26
- function singleQuote(str) {
27
- return `'${str.replace(/\\/g, "\\\\").replace(/'/g, "\\'")}'`;
26
+ function cookieString(cookies) {
27
+ let out = "";
28
+ for (const k in cookies) out += `${out ? "; " : ""}${k}=${cookies[k].value}`;
29
+ return out;
28
30
  }
29
31
  /**
30
32
  * Returns the input string wrapped in double quotes, escaping internal double quotes and backslashes.
@@ -40,10 +42,16 @@ function tripleDoubleQuote(str) {
40
42
  return `"""${str.replace(/\\/g, "\\\\").replace(/"""/g, "\\\"\\\"\\\"")}"""`;
41
43
  }
42
44
  /**
43
- * Returns the input string wrapped in backticks, escaping internal backticks and backslashes.
45
+ * Returns the input string wrapped in a JavaScript template literal, escaping internal backticks, backslashes and `${`.
44
46
  */
45
47
  function backtickQuote(str) {
46
- return `\`${str.replace(/\\/g, "\\\\").replace(/`/g, "\\`")}\``;
48
+ return `\`${str.replace(/[\\`]|\$\{/g, "\\$&")}\``;
49
+ }
50
+ /**
51
+ * Returns the input string wrapped inside a Go raw string literal, where backticks can't be escaped and are concatenated instead.
52
+ */
53
+ function goRawStringLiteral(str) {
54
+ return `\`${str.replaceAll("`", "` + \"`\" + `")}\``;
47
55
  }
48
56
  /**
49
57
  * Returns the input string wrapped inside a Rust string literal,
@@ -59,4 +67,4 @@ function indent(code, tab = 1) {
59
67
  return code.split("\n").map((v) => v.length === 0 ? v : p + v).join("\n");
60
68
  }
61
69
  //#endregion
62
- export { backtickQuote, doubleQuote, indent, inputToString, rustRawStringLiteral, singleQuote, tripleDoubleQuote };
70
+ export { backtickQuote, cookieString, doubleQuote, goRawStringLiteral, indent, inputToString, rustRawStringLiteral, tripleDoubleQuote };
@@ -0,0 +1,14 @@
1
+ "use client";
2
+ import { cn } from "../../utils/cn.js";
3
+ import { jsx, jsxs } from "react/jsx-runtime";
4
+ import { Dialog } from "@base-ui/react/dialog";
5
+ //#region src/ui/components/dialog.tsx
6
+ /** the popup of a dialog, a window on larger screens and the full screen on smaller ones */
7
+ function DialogPopup({ className, children }) {
8
+ return /* @__PURE__ */ jsxs(Dialog.Portal, { children: [/* @__PURE__ */ jsx(Dialog.Backdrop, { className: "fixed inset-0 z-50 bg-black/40 backdrop-blur-xs transition-opacity duration-200 data-ending-style:opacity-0 data-starting-style:opacity-0" }), /* @__PURE__ */ jsx(Dialog.Popup, {
9
+ className: cn("fixed inset-0 z-50 flex flex-col overflow-hidden bg-fd-background text-fd-foreground outline-none transition-[opacity,scale] duration-200 ease-[cubic-bezier(0.16,1,0.3,1)] data-ending-style:scale-[0.98] data-ending-style:opacity-0 data-ending-style:duration-150 data-starting-style:scale-[0.98] data-starting-style:opacity-0 motion-reduce:transition-opacity sm:inset-auto sm:top-1/2 sm:left-1/2 sm:-translate-x-1/2 sm:-translate-y-1/2 sm:rounded-2xl sm:border sm:shadow-2xl", className),
10
+ children
11
+ })] });
12
+ }
13
+ //#endregion
14
+ export { DialogPopup };