fumadocs-openapi 12.5.2 → 12.5.4

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 (62) hide show
  1. package/css/generated/shared.css +1 -1
  2. package/dist/.translations/index.d.ts +0 -32
  3. package/dist/.translations/keys.js +0 -32
  4. package/dist/_virtual/_rolldown/runtime.js +2 -11
  5. package/dist/generate-file.d.ts +2 -1
  6. package/dist/generate-file.js +15 -17
  7. package/dist/index.browser.d.ts +8 -3
  8. package/dist/index.browser.js +11 -1
  9. package/dist/index.d.ts +3 -3
  10. package/dist/index.js +2 -1
  11. package/dist/node_modules/.pnpm/{fast-content-type-parse@4.0.0 → fast-content-type-parse@4.0.1}/node_modules/fast-content-type-parse/index.js +1 -1
  12. package/dist/packages/shared-api/dist/.translations/index.d.ts +34 -4
  13. package/dist/packages/shared-api/dist/.translations/keys.js +34 -4
  14. package/dist/packages/shared-api/dist/codegen.d.ts +2 -6
  15. package/dist/packages/shared-api/dist/codegen.js +63 -1
  16. package/dist/packages/shared-api/dist/components/collapsible.js +2 -2
  17. package/dist/packages/shared-api/dist/components/copy-typescript.js +31 -0
  18. package/dist/packages/shared-api/dist/components/dialog.js +15 -1
  19. package/dist/packages/shared-api/dist/components/example.js +90 -16
  20. package/dist/packages/shared-api/dist/components/playground/fields.js +7 -7
  21. package/dist/packages/shared-api/dist/components/playground/json-editor.js +54 -0
  22. package/dist/packages/shared-api/dist/components/playground/panels.js +88 -5
  23. package/dist/packages/shared-api/dist/components/playground/result.js +187 -0
  24. package/dist/packages/shared-api/dist/components/schema/client.js +22 -0
  25. package/dist/packages/shared-api/dist/components/select-tab.js +8 -3
  26. package/dist/packages/shared-api/dist/components/select.js +2 -2
  27. package/dist/packages/shared-api/dist/source.d.ts +11 -0
  28. package/dist/packages/shared-api/dist/source.js +50 -0
  29. package/dist/packages/shared-api/dist/utils/cn.js +1 -2
  30. package/dist/packages/shared-api/dist/utils/document-cache.js +16 -0
  31. package/dist/playground/auth.d.ts +2 -1
  32. package/dist/playground/fetcher.js +1 -1
  33. package/dist/requests/generators/curl.js +6 -9
  34. package/dist/requests/generators/go.js +5 -5
  35. package/dist/requests/generators/index.d.ts +1 -1
  36. package/dist/requests/generators/rust.js +3 -2
  37. package/dist/requests/media/adapter.d.ts +2 -1
  38. package/dist/requests/media/adapter.js +16 -7
  39. package/dist/requests/media/resolve-adapter.js +15 -12
  40. package/dist/requests/string-utils.js +4 -32
  41. package/dist/server/index.d.ts +7 -8
  42. package/dist/server/index.js +28 -66
  43. package/dist/server/proxy.d.ts +2 -1
  44. package/dist/ui/base.js +2 -2
  45. package/dist/ui/index.d.ts +2 -2
  46. package/dist/ui/operation/index.js +5 -36
  47. package/dist/ui/operation/usage-tabs.js +45 -56
  48. package/dist/ui/playground/client.js +18 -50
  49. package/dist/ui/playground/components/{oauth-panel.js → auth.js} +19 -7
  50. package/dist/ui/playground/components/request-panel.js +3 -65
  51. package/dist/ui/playground/components/response-panel.js +7 -18
  52. package/dist/ui/playground/components/result-display.js +45 -166
  53. package/dist/ui/playground/components/url-bar.js +2 -19
  54. package/dist/utils/cn.js +1 -2
  55. package/dist/utils/create-page.d.ts +4 -6
  56. package/dist/utils/create-page.js +12 -8
  57. package/dist/utils/pages/builder.d.ts +4 -2
  58. package/dist/utils/pages/preset-auto.d.ts +2 -1
  59. package/dist/utils/pages/preset-auto.js +139 -148
  60. package/dist/utils/use-server.d.ts +2 -1
  61. package/package.json +17 -17
  62. package/dist/ui/playground/status-info.js +0 -39
@@ -0,0 +1,187 @@
1
+ "use client";
2
+ import { cn } from "../../utils/cn.js";
3
+ import { Segmented, SegmentedList, SegmentedPanel } from "../segmented.js";
4
+ import { PanelHeader, iconButtonClassName } from "./panels.js";
5
+ import { Fragment, useState } from "react";
6
+ import { Fragment as Fragment$1, jsx, jsxs } from "react/jsx-runtime";
7
+ import { useTranslations } from "@fuma-translate/react";
8
+ import { X } from "lucide-react";
9
+ //#region ../shared-api/dist/components/playground/result.js
10
+ function ClearButton({ onClick, className }) {
11
+ const t = useTranslations({ note: "playground result display" });
12
+ return /* @__PURE__ */ jsx("button", {
13
+ type: "button",
14
+ "aria-label": t("Clear"),
15
+ title: t("Clear"),
16
+ className: cn(iconButtonClassName, className),
17
+ onClick,
18
+ children: /* @__PURE__ */ jsx(X, {})
19
+ });
20
+ }
21
+ /** a request without response, like a network error */
22
+ function RequestError({ message, url, onClear, ...rest }) {
23
+ const t = useTranslations({ note: "playground result display" });
24
+ return /* @__PURE__ */ jsxs("div", {
25
+ ...rest,
26
+ className: cn("flex min-h-0 flex-1 flex-col", rest.className),
27
+ children: [/* @__PURE__ */ jsxs(PanelHeader, { children: [
28
+ /* @__PURE__ */ jsx("span", { className: "size-2 shrink-0 rounded-full bg-red-500" }),
29
+ /* @__PURE__ */ jsx("span", {
30
+ className: "text-[0.8125rem] font-medium",
31
+ children: t("Request Failed")
32
+ }),
33
+ /* @__PURE__ */ jsx(ClearButton, {
34
+ onClick: onClear,
35
+ className: "ms-auto"
36
+ })
37
+ ] }), /* @__PURE__ */ jsxs("div", {
38
+ className: "flex flex-col gap-3 overflow-auto p-4 text-sm",
39
+ children: [
40
+ /* @__PURE__ */ jsx("p", { children: message }),
41
+ /* @__PURE__ */ jsx("p", {
42
+ className: "font-mono text-xs break-all text-fd-muted-foreground",
43
+ children: url
44
+ }),
45
+ /* @__PURE__ */ jsx("p", {
46
+ className: "rounded-lg border bg-fd-secondary p-3 text-xs text-fd-muted-foreground",
47
+ children: t("Check the server URL. If the API does not allow cross-origin requests from this site, a proxy is needed.")
48
+ })
49
+ ]
50
+ })]
51
+ });
52
+ }
53
+ function formatDuration(ms) {
54
+ return ms < 1e3 ? `${Math.round(ms)} ms` : `${(ms / 1e3).toFixed(2)} s`;
55
+ }
56
+ function formatSize(bytes) {
57
+ if (bytes < 1024) return `${bytes} B`;
58
+ if (bytes < 1048576) return `${(bytes / 1024).toFixed(1)} kB`;
59
+ return `${(bytes / 1024 / 1024).toFixed(1)} MB`;
60
+ }
61
+ function useStatusInfo(status) {
62
+ const t = useTranslations({ note: "playground status info" });
63
+ const descriptions = {
64
+ 200: t("OK"),
65
+ 201: t("Created"),
66
+ 202: t("Accepted"),
67
+ 204: t("No Content"),
68
+ 301: t("Moved Permanently"),
69
+ 302: t("Found"),
70
+ 304: t("Not Modified"),
71
+ 400: t("Bad Request"),
72
+ 401: t("Unauthorized"),
73
+ 403: t("Forbidden"),
74
+ 404: t("Not Found"),
75
+ 405: t("Method Not Allowed"),
76
+ 409: t("Conflict"),
77
+ 422: t("Unprocessable Content"),
78
+ 429: t("Too Many Requests"),
79
+ 500: t("Internal Server Error"),
80
+ 502: t("Bad Gateway"),
81
+ 503: t("Service Unavailable")
82
+ };
83
+ if (status >= 200 && status < 300) return {
84
+ color: "bg-green-500",
85
+ description: descriptions[status] ?? t("Successful")
86
+ };
87
+ if (status >= 300 && status < 400) return {
88
+ color: "bg-blue-500",
89
+ description: descriptions[status] ?? t("Redirect")
90
+ };
91
+ return {
92
+ color: status >= 400 && status < 500 ? "bg-amber-500" : "bg-red-500",
93
+ description: descriptions[status] ?? t("Error")
94
+ };
95
+ }
96
+ /** the response of a request, with `children` as its body */
97
+ function ResponseView({ status, duration, size, url, headers, warning = false, actions, onClear, children, ...rest }) {
98
+ const t = useTranslations({ note: "playground result display" });
99
+ const statusInfo = useStatusInfo(status);
100
+ const [view, setView] = useState("body");
101
+ return /* @__PURE__ */ jsx("div", {
102
+ ...rest,
103
+ className: cn("flex min-h-0 flex-1 flex-col", rest.className),
104
+ children: /* @__PURE__ */ jsxs(Segmented, {
105
+ value: view,
106
+ onValueChange: setView,
107
+ className: "flex min-h-0 flex-1 flex-col",
108
+ children: [
109
+ /* @__PURE__ */ jsxs(PanelHeader, { children: [
110
+ /* @__PURE__ */ jsx("span", { className: cn("size-2 shrink-0 rounded-full motion-safe:transition-transform motion-safe:duration-300 motion-safe:starting:scale-0", warning ? "bg-amber-500" : statusInfo.color) }),
111
+ /* @__PURE__ */ jsxs("p", {
112
+ className: "min-w-0 truncate text-[0.8125rem] font-medium",
113
+ children: [
114
+ /* @__PURE__ */ jsx("span", {
115
+ className: "tabular-nums",
116
+ children: status
117
+ }),
118
+ " ",
119
+ /* @__PURE__ */ jsx("span", {
120
+ className: "font-normal text-fd-muted-foreground",
121
+ children: statusInfo.description
122
+ })
123
+ ]
124
+ }),
125
+ /* @__PURE__ */ jsxs("p", {
126
+ className: "hidden shrink-0 text-xs text-fd-muted-foreground tabular-nums @md:block",
127
+ children: [
128
+ formatDuration(duration),
129
+ " · ",
130
+ formatSize(size)
131
+ ]
132
+ }),
133
+ headers && /* @__PURE__ */ jsx(SegmentedList, {
134
+ className: "ms-auto shrink-0",
135
+ items: [{
136
+ value: "body",
137
+ label: t("Body")
138
+ }, {
139
+ value: "headers",
140
+ label: /* @__PURE__ */ jsxs(Fragment$1, { children: [t("Headers"), /* @__PURE__ */ jsx("span", {
141
+ className: "text-fd-muted-foreground tabular-nums",
142
+ children: headers.length
143
+ })] })
144
+ }]
145
+ }),
146
+ /* @__PURE__ */ jsxs("div", {
147
+ className: cn("flex shrink-0 items-center", !headers && "ms-auto"),
148
+ children: [actions, /* @__PURE__ */ jsx(ClearButton, { onClick: onClear })]
149
+ })
150
+ ] }),
151
+ /* @__PURE__ */ jsx(SegmentedPanel, {
152
+ value: "body",
153
+ className: "min-h-0 flex-1 overflow-auto",
154
+ children: size > 0 ? children : /* @__PURE__ */ jsxs("div", {
155
+ className: "flex h-full flex-col items-center justify-center gap-1 p-6 text-center",
156
+ children: [/* @__PURE__ */ jsx("p", {
157
+ className: "text-4xl font-light tracking-tight tabular-nums",
158
+ children: status
159
+ }), /* @__PURE__ */ jsx("p", {
160
+ className: "text-sm text-fd-muted-foreground",
161
+ children: t("Empty response body")
162
+ })]
163
+ })
164
+ }),
165
+ headers && /* @__PURE__ */ jsxs(SegmentedPanel, {
166
+ value: "headers",
167
+ className: "min-h-0 flex-1 overflow-auto",
168
+ children: [/* @__PURE__ */ jsx("p", {
169
+ className: "border-b px-4 py-2.5 font-mono text-xs break-all text-fd-muted-foreground",
170
+ children: url
171
+ }), /* @__PURE__ */ jsx("dl", {
172
+ className: "grid grid-cols-[minmax(0,2fr)_minmax(0,3fr)] font-mono text-xs",
173
+ children: headers.map(([name, value]) => /* @__PURE__ */ jsxs(Fragment, { children: [/* @__PURE__ */ jsx("dt", {
174
+ className: "truncate border-b py-2 ps-4 pe-2 text-fd-muted-foreground",
175
+ children: name
176
+ }), /* @__PURE__ */ jsx("dd", {
177
+ className: "border-b border-s px-3 py-2 break-all",
178
+ children: value
179
+ })] }, name))
180
+ })]
181
+ })
182
+ ]
183
+ })
184
+ });
185
+ }
186
+ //#endregion
187
+ export { RequestError, ResponseView };
@@ -433,6 +433,7 @@ function SchemaDescription({ schema: { description, infoTags = [] }, className }
433
433
  className: "flex flex-wrap gap-1.5",
434
434
  children: infoTags.map((tag, i) => {
435
435
  if ("node" in tag) return /* @__PURE__ */ jsx(Fragment, { children: tag.node }, i);
436
+ if ("open" in tag) return /* @__PURE__ */ jsx(OpenTag, { ...tag }, i);
436
437
  if ("list" in tag) return /* @__PURE__ */ jsxs("div", {
437
438
  className: "not-prose flex w-full flex-wrap items-center gap-1.5 text-xs",
438
439
  children: [tag.label, tag.list.map((item, j) => /* @__PURE__ */ jsx("code", {
@@ -461,5 +462,26 @@ function SchemaDescription({ schema: { description, infoTags = [] }, className }
461
462
  })]
462
463
  });
463
464
  }
465
+ /** a tag opening a schema, like the type of a property */
466
+ function OpenTag({ label, value, open: { name, $ref } }) {
467
+ const { open, isExpanded } = use(TypeContext);
468
+ return /* @__PURE__ */ jsxs("button", {
469
+ type: "button",
470
+ "aria-expanded": isExpanded?.(name, $ref),
471
+ onClick: () => open(name, $ref),
472
+ className: cn(tagClassName, "group/open inline-flex max-w-full items-center gap-1.5 text-start transition-colors hover:bg-fd-accent hover:text-fd-accent-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-fd-ring aria-expanded:bg-fd-accent"),
473
+ children: [
474
+ /* @__PURE__ */ jsx("span", {
475
+ className: "not-prose shrink-0 text-fd-muted-foreground",
476
+ children: label
477
+ }),
478
+ value && /* @__PURE__ */ jsx("code", {
479
+ className: "not-prose min-w-0 truncate",
480
+ children: value
481
+ }),
482
+ /* @__PURE__ */ jsx(ChevronRightIcon, { className: "size-3 shrink-0 text-fd-muted-foreground transition-transform duration-200 group-hover/open:translate-x-0.5 motion-reduce:transition-none" })
483
+ ]
484
+ });
485
+ }
464
486
  //#endregion
465
487
  export { SchemaUI };
@@ -29,16 +29,21 @@ function SelectTab({ value, anchorSegments, ...props }) {
29
29
  children: content
30
30
  }) : content;
31
31
  }
32
- function SelectTabTrigger({ items, className, placeholder, ...props }) {
32
+ /** selects the tab shown in a card, like a media type, a single item is a plain label */
33
+ function SelectTabTrigger({ items, className, ...props }) {
33
34
  const { value, setValue } = use(Context);
35
+ if (items.length === 1) return /* @__PURE__ */ jsx("span", {
36
+ className: "min-w-0 px-1.5 font-medium",
37
+ children: items[0].label
38
+ });
34
39
  return /* @__PURE__ */ jsxs(Select, {
35
40
  items,
36
41
  value,
37
42
  onValueChange: setValue,
38
43
  children: [/* @__PURE__ */ jsx(SelectTrigger, {
39
- className: cn("not-prose w-fit min-w-0 *:min-w-0", className),
44
+ className: cn("not-prose h-7 w-auto min-w-0 gap-1 border-0 bg-transparent px-1.5 py-0 text-[0.8125rem] font-medium *:min-w-0 hover:bg-fd-accent hover:text-fd-accent-foreground focus:ring-0 focus-visible:ring-2 focus-visible:ring-inset data-popup-open:bg-fd-accent", className),
40
45
  ...props,
41
- children: /* @__PURE__ */ jsx(SelectValue, { placeholder })
46
+ children: /* @__PURE__ */ jsx(SelectValue, {})
42
47
  }), /* @__PURE__ */ jsx(SelectContent, { children: items.map(({ label, value }) => /* @__PURE__ */ jsx(SelectItem, {
43
48
  value,
44
49
  children: label
@@ -4,7 +4,7 @@ import { jsx, jsxs } from "react/jsx-runtime";
4
4
  import { Check, ChevronDown } from "lucide-react";
5
5
  import { Select } from "@base-ui/react/select";
6
6
  //#region ../shared-api/dist/components/select.js
7
- const Select$1 = Select.Root;
7
+ const Select$2 = Select.Root;
8
8
  Select.Group;
9
9
  const SelectValue = Select.Value;
10
10
  function SelectTrigger({ className, children, ref, ...props }) {
@@ -72,4 +72,4 @@ function SelectItem({ className, children, description, ref, ...props }) {
72
72
  });
73
73
  }
74
74
  //#endregion
75
- export { Select$1 as Select, SelectContent, SelectItem, SelectScrollDownButton, SelectScrollUpButton, SelectTrigger, SelectValue };
75
+ export { Select$2 as Select, SelectContent, SelectItem, SelectScrollDownButton, SelectScrollUpButton, SelectTrigger, SelectValue };
@@ -0,0 +1,11 @@
1
+ import { MetaData, PageData } from "fumadocs-core/source";
2
+ //#region ../shared-api/dist/source.d.ts
3
+ //#region src/source.d.ts
4
+ export interface SourceOptions {
5
+ baseDir?: string;
6
+ /** Generate `meta.json` files */
7
+ meta?: boolean | {
8
+ folderStyle?: 'folder' | 'separator';
9
+ };
10
+ }
11
+ //#endregion
@@ -0,0 +1,50 @@
1
+ import * as path from "node:path";
2
+ import { PathUtils } from "fumadocs-core/source";
3
+ //#region ../shared-api/dist/source.js
4
+ /** convert output entries into virtual files for `loader()` */
5
+ function toVirtualFiles(entries, { baseDir = "", meta = false }, toPage) {
6
+ const { folderStyle = "folder" } = typeof meta === "object" ? meta : {};
7
+ const files = [];
8
+ function scan(entries, parent) {
9
+ for (const entry of entries) {
10
+ if (entry.type === "group") {
11
+ scan(entry.entries, entry);
12
+ continue;
13
+ }
14
+ files.push({
15
+ type: "page",
16
+ path: path.join(baseDir, entry.path),
17
+ data: toPage(entry),
18
+ locale: "$"
19
+ });
20
+ }
21
+ if (!meta) return;
22
+ const pages = getMetaPages(entries, parent, folderStyle);
23
+ if (pages.length === 0) return;
24
+ files.push({
25
+ type: "meta",
26
+ path: path.join(baseDir, parent?.path ?? "", "meta.json"),
27
+ data: {
28
+ title: parent?.info.title,
29
+ description: parent?.info.description,
30
+ pages
31
+ },
32
+ locale: "$"
33
+ });
34
+ }
35
+ scan(entries);
36
+ return files;
37
+ }
38
+ /** the `pages` of `meta.json` in the folder of `parent`, for its entries */
39
+ function getMetaPages(entries, parent, folderStyle) {
40
+ const pages = [];
41
+ for (const entry of entries) {
42
+ const relativePath = PathUtils.slash(parent ? path.relative(parent.path, entry.path) : entry.path);
43
+ if (entry.type !== "group") pages.push(relativePath.slice(0, -path.extname(entry.path).length));
44
+ else if (folderStyle === "folder") pages.push(relativePath);
45
+ else pages.push(`---${entry.info.title}---`, `...${relativePath}`);
46
+ }
47
+ return pages;
48
+ }
49
+ //#endregion
50
+ export { getMetaPages, toVirtualFiles };
@@ -1,2 +1 @@
1
- import { cn } from "cn";
2
- export { cn };
1
+ export { cn } from "cn";
@@ -0,0 +1,16 @@
1
+ //#region ../shared-api/dist/utils/document-cache.js
2
+ /** Browsers load each document once per session, servers cache documents themselves. */
3
+ function createDocumentCache() {
4
+ const cache = /* @__PURE__ */ new Map();
5
+ return (id, load) => {
6
+ if (typeof window === "undefined") return load(id);
7
+ let promise = cache.get(id);
8
+ if (!promise) {
9
+ cache.set(id, promise = load(id));
10
+ promise.catch(() => cache.delete(id));
11
+ }
12
+ return promise;
13
+ };
14
+ }
15
+ //#endregion
16
+ export { createDocumentCache };
@@ -203,4 +203,5 @@ export interface AuthFieldsOptions {
203
203
  * The auth fields of an API playground: the values it persists, and the request data they encode into.
204
204
  */
205
205
  export declare function useAuthFields(engine: DataEngine, { operation, providers, transform }?: AuthFieldsOptions): AuthFields;
206
- //#endregion
206
+ //#endregion
207
+ export {};
@@ -1,5 +1,5 @@
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
+ import { require_fast_content_type_parse } from "../node_modules/.pnpm/fast-content-type-parse@4.0.1/node_modules/fast-content-type-parse/index.js";
3
3
  //#region src/playground/fetcher.ts
4
4
  var import_fast_content_type_parse = require_fast_content_type_parse();
5
5
  /**
@@ -1,5 +1,6 @@
1
+ import { shellQuote } from "../../packages/shared-api/dist/codegen.js";
1
2
  import { inputToString } from "../string-utils.js";
2
- import { resolveMediaAdapter } from "../media/resolve-adapter.js";
3
+ import { resolveMediaType } from "../media/resolve-adapter.js";
3
4
  //#region src/requests/generators/curl.ts
4
5
  const curl = {
5
6
  label: "cURL",
@@ -9,20 +10,16 @@ const curl = {
9
10
  s.push(`curl -X ${data.method.toUpperCase()} ${shellQuote(data.url)}`);
10
11
  for (const header in data.header) s.push(`-H ${shellQuote(`${header}: ${data.header[header].value}`)}`);
11
12
  for (const k in data.cookie) s.push(`--cookie ${shellQuote(`${k}=${data.cookie[k].value}`)}`);
12
- if (data.body && data.bodyMediaType === "multipart/form-data") {
13
+ const type = data.bodyMediaType && resolveMediaType(data.bodyMediaType, mediaAdapters);
14
+ if (data.body && type === "multipart/form-data") {
13
15
  if (typeof data.body !== "object") throw new Error("[CURL] request body must be an object.");
14
16
  for (const [key, value] of Object.entries(data.body)) s.push(`-F ${shellQuote(`${key}=${inputToString(value)}`)}`);
15
- } else if (data.body && data.bodyMediaType && resolveMediaAdapter(data.bodyMediaType, mediaAdapters)) {
16
- const escaped = shellQuote(inputToString(data.body, data.bodyMediaType));
17
+ } else if (data.body && type) {
17
18
  s.push(`-H 'Content-Type: ${data.bodyMediaType}'`);
18
- s.push(`-d ${escaped}`);
19
+ s.push(`-d ${shellQuote(inputToString(data.body, type))}`);
19
20
  }
20
21
  return s.join(" \\\n ");
21
22
  }
22
23
  };
23
- /** single quotes keep the string literal, each `'` closes them to add an escaped quote */
24
- function shellQuote(str) {
25
- return `'${str.replaceAll("'", `'\\''`)}'`;
26
- }
27
24
  //#endregion
28
25
  export { curl };
@@ -14,14 +14,13 @@ const go = {
14
14
  lang: "go",
15
15
  addImport: (name) => imports.add(name)
16
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"})`);
17
+ const multipart = data.bodyMediaType === "multipart/form-data";
18
+ const s = [`req, _ := http.NewRequest("${data.method.toUpperCase()}", url, ${body ? "body" : "nil"})`];
20
19
  for (const k in data.header) s.push(`req.Header.Add(${doubleQuote(k)}, ${doubleQuote(data.header[k].value)})`);
21
20
  const cookie = cookieString(data.cookie);
22
21
  if (cookie) s.push(`req.Header.Add("Cookie", ${doubleQuote(cookie)})`);
23
22
  if (body) {
24
- const type = data.bodyMediaType === "multipart/form-data" ? "mp.FormDataContentType()" : doubleQuote(data.bodyMediaType);
23
+ const type = multipart ? "mp.FormDataContentType()" : doubleQuote(data.bodyMediaType);
25
24
  s.push(`req.Header.Add("Content-Type", ${type})`);
26
25
  }
27
26
  s.push("res, _ := http.DefaultClient.Do(req)", "defer res.Body.Close()", "resBody, _ := io.ReadAll(res.Body)", "", "fmt.Println(res)", "fmt.Println(string(resBody))");
@@ -32,7 +31,8 @@ ${indent(Array.from(imports, (name) => `"${name}"`).join("\n"))}
32
31
  )
33
32
 
34
33
  func main() {
35
- ${indent(s.join("\n"))}
34
+ url := ${doubleQuote(data.url)}
35
+ ${body ? `${multipart ? indent(body) : ` ${body}`}\n` : ""}${indent(s.join("\n"))}
36
36
  }`;
37
37
  }
38
38
  };
@@ -1,6 +1,6 @@
1
1
  import { RequestData } from "../types.js";
2
2
  import { MediaAdapter } from "../media/adapter.js";
3
- import { CodeUsageGenerator as CodeUsageGenerator$1, CodeUsageGeneratorRegistry as CodeUsageGeneratorRegistry$1, InlineCodeUsageGenerator as InlineCodeUsageGenerator$1, codegen_d_exports } from "../../packages/shared-api/dist/codegen.js";
3
+ import { CodeUsageGenerator as CodeUsageGenerator$1, CodeUsageGeneratorRegistry as CodeUsageGeneratorRegistry$1, InlineCodeUsageGenerator as InlineCodeUsageGenerator$1 } 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;
6
6
  export type CodeUsageGeneratorRegistry = CodeUsageGeneratorRegistry$1<RequestData & {
@@ -6,11 +6,12 @@ const rust = {
6
6
  lang: "rust",
7
7
  generate(data, { mediaAdapters }) {
8
8
  const body = generateBodyExample(data, mediaAdapters, { lang: "rust" });
9
+ const multipart = data.bodyMediaType === "multipart/form-data";
9
10
  const request = [`.request(Method::${data.method.toUpperCase()}, url)`];
10
11
  for (const k in data.header) request.push(`.header(${doubleQuote(k)}, ${doubleQuote(data.header[k].value)})`);
11
12
  const cookie = cookieString(data.cookie);
12
13
  if (cookie) request.push(`.header("Cookie", ${doubleQuote(cookie)})`);
13
- if (body && data.bodyMediaType === "multipart/form-data") request.push(".multipart(body)");
14
+ if (body && multipart) request.push(".multipart(body)");
14
15
  else if (body) request.push(`.header("Content-Type", ${doubleQuote(data.bodyMediaType)})`, ".body(body)");
15
16
  request.push(".send()", ".await?", ".text()", ".await?;");
16
17
  return `use reqwest::{Client, Method, Result};
@@ -20,7 +21,7 @@ async fn main() -> Result<()> {
20
21
  let client = Client::new();
21
22
 
22
23
  let url = ${doubleQuote(data.url)};
23
- ${body ? `${indent(body)}\n` : ""}
24
+ ${body ? `${multipart ? indent(body) : ` ${body}`}\n` : ""}
24
25
  let res = client
25
26
  ${indent(request.join("\n"), 2)}
26
27
 
@@ -46,4 +46,5 @@ export interface MediaAdapter {
46
46
  body: unknown;
47
47
  }, ctx: MediaContext) => string | undefined;
48
48
  }
49
- //#endregion
49
+ //#endregion
50
+ export {};
@@ -1,6 +1,7 @@
1
1
  import { __toESM } from "../../_virtual/_rolldown/runtime.js";
2
+ import { csharpRawString, goString, javaTextBlock, jsTemplateLiteral, pythonString, rustString } from "../../packages/shared-api/dist/codegen.js";
2
3
  import { require_js2xml } from "../../node_modules/.pnpm/xml-js@1.6.11/node_modules/xml-js/lib/js2xml.js";
3
- import { backtickQuote, goRawStringLiteral, inputToString, rustRawStringLiteral, tripleDoubleQuote } from "../string-utils.js";
4
+ import { inputToString } from "../string-utils.js";
4
5
  import { resolveMediaAdapter } from "./resolve-adapter.js";
5
6
  //#region src/requests/media/adapter.ts
6
7
  var import_js2xml = /* @__PURE__ */ __toESM(require_js2xml(), 1);
@@ -33,6 +34,14 @@ const defaultAdapters = {
33
34
  return str(data.body, "application/x-ndjson", ctx);
34
35
  }
35
36
  },
37
+ "text/plain": {
38
+ encode(data) {
39
+ return inputToString(data.body, "text/plain");
40
+ },
41
+ generateExample(data, ctx) {
42
+ return str(data.body, "text/plain", ctx);
43
+ }
44
+ },
36
45
  "application/x-www-form-urlencoded": {
37
46
  encode(data) {
38
47
  if (typeof data.body !== "object") throw new Error(`Input value must be object, received: ${typeof data.body}`);
@@ -120,16 +129,16 @@ function str(init, mediaType, ctx) {
120
129
  if (ctx.lang === "js" && mediaType === "application/json") return `const body = JSON.stringify(${JSON.stringify(init, null, 2)})`;
121
130
  const text = inputToString(init, mediaType);
122
131
  switch (ctx.lang) {
123
- case "js": return `const body = ${backtickQuote(text)}`;
124
- case "python": return `body = ${tripleDoubleQuote(text)}`;
132
+ case "js": return `const body = ${jsTemplateLiteral(text)}`;
133
+ case "python": return `body = ${pythonString(text)}`;
125
134
  case "go":
126
135
  ctx.addImport("strings");
127
- return `body := strings.NewReader(${goRawStringLiteral(text)})`;
136
+ return `body := strings.NewReader(${goString(text)})`;
128
137
  case "java":
129
138
  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)};`;
139
+ return `var body = BodyPublishers.ofString(${javaTextBlock(text)});`;
140
+ case "csharp": return `var body = new StringContent(${csharpRawString(text)}, Encoding.UTF8, "${mediaType}");`;
141
+ case "rust": return `let body = ${rustString(text)};`;
133
142
  }
134
143
  }
135
144
  //#endregion
@@ -1,6 +1,18 @@
1
1
  //#region src/requests/media/resolve-adapter.ts
2
2
  const VariantMediaTypeRegex = /^(?<dir>[a-zA-Z0-9._-]+)\/(?<content>[a-zA-Z0-9._-]+)\+(?<variant>[a-zA-Z0-9._-]+)$/;
3
3
  /**
4
+ * Resolve the media type of the adapter for a given media type, like `application/json` for `+json` variants.
5
+ */
6
+ function resolveMediaType(mediaType, adapters) {
7
+ const normalized = mediaType.split(";", 2)[0].trim().toLowerCase();
8
+ if (normalized in adapters) return normalized;
9
+ const match = VariantMediaTypeRegex.exec(normalized);
10
+ if (match?.groups) {
11
+ const baseType = `${match.groups.dir}/${match.groups.variant}`;
12
+ if (baseType in adapters) return baseType;
13
+ }
14
+ }
15
+ /**
4
16
  * Resolve a media adapter for a given media type.
5
17
  * Supports exact matches and pattern matching (e.g., +json suffix).
6
18
  *
@@ -9,17 +21,8 @@ const VariantMediaTypeRegex = /^(?<dir>[a-zA-Z0-9._-]+)\/(?<content>[a-zA-Z0-9._
9
21
  * @returns The resolved adapter or undefined if not found
10
22
  */
11
23
  function resolveMediaAdapter(mediaType, adapters) {
12
- const normalized = mediaType.split(";", 2)[0].trim().toLowerCase();
13
- if (normalized in adapters) return adapters[normalized];
14
- const match = VariantMediaTypeRegex.exec(normalized);
15
- if (match?.groups) {
16
- const baseType = `${match.groups.dir}/${match.groups.variant}`;
17
- if (baseType in adapters) return adapters[baseType];
18
- }
19
- if (normalized === "text/plain") {
20
- console.warn("there is no defined behaviour for encoding form values into \"text/plain\", using JSON encoder for now.");
21
- return adapters["application/json"];
22
- }
24
+ const type = resolveMediaType(mediaType, adapters);
25
+ if (type) return adapters[type];
23
26
  }
24
27
  //#endregion
25
- export { resolveMediaAdapter };
28
+ export { resolveMediaAdapter, resolveMediaType };
@@ -3,11 +3,10 @@ import { require_js2xml } from "../node_modules/.pnpm/xml-js@1.6.11/node_modules
3
3
  //#region src/requests/string-utils.ts
4
4
  var import_js2xml = /* @__PURE__ */ __toESM(require_js2xml(), 1);
5
5
  /**
6
- * Convert input value to hardcoded string (with quotes)
6
+ * The text of a body value in the format of a media type, strings are already serialized.
7
7
  */
8
8
  function inputToString(value, format = "application/json") {
9
9
  if (typeof value === "string") return value;
10
- if (format === "application/json") return JSON.stringify(value, null, 2);
11
10
  if (format === "application/x-ndjson") return Array.isArray(value) ? value.map((v) => JSON.stringify(v)).join("\n") : JSON.stringify(value, null, 2);
12
11
  if (format === "application/x-www-form-urlencoded") {
13
12
  const params = new URLSearchParams();
@@ -15,10 +14,11 @@ function inputToString(value, format = "application/json") {
15
14
  for (const key in value) if (value[key]) params.set(key, String(value[key]));
16
15
  return params.toString();
17
16
  }
18
- return (0, import_js2xml.default)(value, {
17
+ if (format === "application/xml") return (0, import_js2xml.default)(value, {
19
18
  compact: true,
20
19
  spaces: 2
21
20
  });
21
+ return JSON.stringify(value, null, 2);
22
22
  }
23
23
  /**
24
24
  * Returns the value of a `Cookie` header with the given cookies.
@@ -40,37 +40,9 @@ function doubleQuote(str) {
40
40
  function jsxString(str) {
41
41
  return str.includes("\"") ? `{${JSON.stringify(str)}}` : `"${str}"`;
42
42
  }
43
- /**
44
- * Returns the input string wrapped in Python triple double-quotes,
45
- * escaping embedded triple quotes and backslashes.
46
- */
47
- function tripleDoubleQuote(str) {
48
- return `"""${str.replace(/\\/g, "\\\\").replace(/"""/g, "\\\"\\\"\\\"")}"""`;
49
- }
50
- /**
51
- * Returns the input string wrapped in a JavaScript template literal, escaping internal backticks, backslashes and `${`.
52
- */
53
- function backtickQuote(str) {
54
- return `\`${str.replace(/[\\`]|\$\{/g, "\\$&")}\``;
55
- }
56
- /**
57
- * Returns the input string wrapped inside a Go raw string literal, where backticks can't be escaped and are concatenated instead.
58
- */
59
- function goRawStringLiteral(str) {
60
- return `\`${str.replaceAll("`", "` + \"`\" + `")}\``;
61
- }
62
- /**
63
- * Returns the input string wrapped inside a Rust string literal,
64
- * with increasing number of # to escape `"#`
65
- */
66
- function rustRawStringLiteral(str) {
67
- let hashes = "#";
68
- while (str.includes(`"${hashes}`)) hashes += "#";
69
- return `r${hashes}"${str}"${hashes}`;
70
- }
71
43
  function indent(code, tab = 1) {
72
44
  const p = " ".repeat(tab);
73
45
  return code.split("\n").map((v) => v.length === 0 ? v : p + v).join("\n");
74
46
  }
75
47
  //#endregion
76
- export { backtickQuote, cookieString, doubleQuote, goRawStringLiteral, indent, inputToString, jsxString, rustRawStringLiteral, tripleDoubleQuote };
48
+ export { cookieString, doubleQuote, indent, inputToString, jsxString };