@orpc/openapi 2.0.0-beta.47 → 2.0.0-beta.49

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 (93) hide show
  1. package/README.md +6 -7
  2. package/dist/adapters/aws-lambda/index.d.ts +10 -22
  3. package/dist/adapters/aws-lambda/index.js +1 -0
  4. package/dist/adapters/aws-lambda/openapi-handler.d.ts +18 -0
  5. package/dist/adapters/aws-lambda/openapi-handler.js +18 -0
  6. package/dist/adapters/fastify/index.d.ts +1 -23
  7. package/dist/adapters/fastify/index.js +1 -0
  8. package/dist/adapters/fastify/openapi-handler.d.ts +15 -0
  9. package/dist/adapters/fastify/openapi-handler.js +15 -0
  10. package/dist/adapters/fetch/index.d.ts +2 -37
  11. package/dist/adapters/fetch/index.js +2 -0
  12. package/dist/adapters/fetch/openapi-handler.d.ts +15 -0
  13. package/dist/adapters/fetch/openapi-handler.js +15 -0
  14. package/dist/adapters/fetch/openapi-link.d.ts +21 -0
  15. package/dist/adapters/fetch/openapi-link.js +20 -0
  16. package/dist/adapters/node/index.d.ts +1 -23
  17. package/dist/adapters/node/index.js +1 -0
  18. package/dist/adapters/node/openapi-handler.d.ts +15 -0
  19. package/dist/adapters/node/openapi-handler.js +15 -0
  20. package/dist/adapters/standard/index.d.ts +3 -56
  21. package/dist/adapters/standard/index.js +3 -0
  22. package/dist/adapters/standard/openapi-handler-codec.d.ts +62 -0
  23. package/dist/adapters/standard/openapi-handler-codec.js +220 -0
  24. package/dist/adapters/standard/{index.d.mts → openapi-link-codec.d.ts} +25 -19
  25. package/dist/adapters/standard/openapi-link-codec.js +405 -0
  26. package/dist/adapters/standard/openapi-matcher.d.ts +29 -0
  27. package/dist/adapters/standard/openapi-matcher.js +108 -0
  28. package/dist/adapters/standard/utils.d.ts +4 -0
  29. package/dist/adapters/standard/utils.js +47 -0
  30. package/dist/bracket-notation.d.ts +26 -0
  31. package/dist/bracket-notation.js +185 -0
  32. package/dist/client-factory.d.ts +24 -0
  33. package/dist/client-factory.js +13 -0
  34. package/dist/constants.d.ts +4 -0
  35. package/dist/constants.js +4 -0
  36. package/dist/extensions/route.d.ts +3 -7
  37. package/dist/extensions/route.js +12 -0
  38. package/dist/helpers/{index.d.mts → form-data.d.ts} +2 -4
  39. package/dist/helpers/form-data.js +90 -0
  40. package/dist/helpers/index.d.ts +1 -59
  41. package/dist/helpers/index.js +1 -0
  42. package/dist/index.d.ts +12 -165
  43. package/dist/index.js +11 -0
  44. package/dist/{shared/openapi.zGZlCOwp.d.mts → meta.d.ts} +14 -18
  45. package/dist/meta.js +84 -0
  46. package/dist/openapi-generator-components.d.ts +31 -0
  47. package/dist/openapi-generator-components.js +275 -0
  48. package/dist/openapi-generator-operation.d.ts +34 -0
  49. package/dist/openapi-generator-operation.js +469 -0
  50. package/dist/openapi-generator.d.ts +92 -0
  51. package/dist/openapi-generator.js +147 -0
  52. package/dist/openapi-json-serializer.d.ts +79 -0
  53. package/dist/openapi-json-serializer.js +260 -0
  54. package/dist/openapi-serializer.d.ts +43 -0
  55. package/dist/openapi-serializer.js +93 -0
  56. package/dist/plugins/index.d.ts +1 -121
  57. package/dist/plugins/index.js +1 -0
  58. package/dist/plugins/{index.d.mts → openapi-reference.d.ts} +15 -21
  59. package/dist/plugins/openapi-reference.js +187 -0
  60. package/dist/router-utils.d.ts +20 -0
  61. package/dist/router-utils.js +36 -0
  62. package/dist/types.d.ts +31 -0
  63. package/dist/types.js +1 -0
  64. package/dist/utils.d.ts +14 -0
  65. package/dist/utils.js +47 -0
  66. package/package.json +69 -71
  67. package/dist/adapters/aws-lambda/index.d.mts +0 -27
  68. package/dist/adapters/aws-lambda/index.mjs +0 -21
  69. package/dist/adapters/fastify/index.d.mts +0 -23
  70. package/dist/adapters/fastify/index.mjs +0 -21
  71. package/dist/adapters/fetch/index.d.mts +0 -37
  72. package/dist/adapters/fetch/index.mjs +0 -34
  73. package/dist/adapters/node/index.d.mts +0 -23
  74. package/dist/adapters/node/index.mjs +0 -21
  75. package/dist/adapters/standard/index.mjs +0 -12
  76. package/dist/extensions/route.d.mts +0 -41
  77. package/dist/extensions/route.mjs +0 -14
  78. package/dist/helpers/index.mjs +0 -39
  79. package/dist/index.d.mts +0 -166
  80. package/dist/index.mjs +0 -780
  81. package/dist/plugins/index.mjs +0 -167
  82. package/dist/shared/openapi.B9PQzqBn.mjs +0 -49
  83. package/dist/shared/openapi.CQkXu1nY.mjs +0 -366
  84. package/dist/shared/openapi.Covi8zVE.d.mts +0 -33
  85. package/dist/shared/openapi.Covi8zVE.d.ts +0 -33
  86. package/dist/shared/openapi.DfmCR1pB.d.mts +0 -94
  87. package/dist/shared/openapi.DtEVcxuW.mjs +0 -149
  88. package/dist/shared/openapi.E3ZBiweM.mjs +0 -353
  89. package/dist/shared/openapi.Y4K_-I5W.d.ts +0 -94
  90. package/dist/shared/openapi.YMRD3b4R.d.mts +0 -157
  91. package/dist/shared/openapi.YMRD3b4R.d.ts +0 -157
  92. package/dist/shared/openapi.g7ucL05o.mjs +0 -410
  93. package/dist/shared/openapi.zGZlCOwp.d.ts +0 -329
@@ -1,167 +0,0 @@
1
- import { toArray, matchesHttpPath, mergeHttpPath, value, getTracer, stringifyJSON } from '@orpc/shared';
2
-
3
- class OpenAPIReferenceHandlerPlugin {
4
- name = "~openapi-reference";
5
- spec;
6
- allow;
7
- specPath;
8
- provider;
9
- providerConfig;
10
- providerScriptUrl;
11
- providerCssUrl;
12
- docsPath;
13
- docsTitle;
14
- docsHead;
15
- constructor(options) {
16
- this.spec = options.spec;
17
- this.allow = options.allow;
18
- this.specPath = options.specPath ?? "/spec.json";
19
- this.provider = options.provider ?? "scalar";
20
- this.providerConfig = options.providerConfig;
21
- this.providerScriptUrl = options.providerScriptUrl;
22
- this.providerCssUrl = options.providerCssUrl;
23
- this.docsTitle = options.docsTitle;
24
- this.docsPath = options.docsPath ?? "/";
25
- this.docsHead = options.docsHead ?? "";
26
- }
27
- init(options) {
28
- return {
29
- ...options,
30
- routingInterceptors: [
31
- // Run after user-provided routing interceptors so they can capture the ui/spec responses
32
- ...toArray(options.routingInterceptors),
33
- async ({ next, ...routingInterceptorOptions }) => {
34
- const result = await next();
35
- if (result.matched || routingInterceptorOptions.request.method !== "GET") {
36
- return result;
37
- }
38
- const isSpecPath = matchesHttpPath(
39
- routingInterceptorOptions.request.url,
40
- routingInterceptorOptions.prefix ? mergeHttpPath(routingInterceptorOptions.prefix, this.specPath) : this.specPath
41
- );
42
- const isDocsPath = matchesHttpPath(
43
- routingInterceptorOptions.request.url,
44
- routingInterceptorOptions.prefix ? mergeHttpPath(routingInterceptorOptions.prefix, this.docsPath) : this.docsPath
45
- );
46
- if (!isSpecPath && !isDocsPath) {
47
- return result;
48
- }
49
- if (await value(this.allow, routingInterceptorOptions) === false) {
50
- return result;
51
- }
52
- const span = getTracer()?.getActiveSpan();
53
- const spec = await value(this.spec, routingInterceptorOptions);
54
- if (isSpecPath) {
55
- span?.updateName(`${routingInterceptorOptions.request.method} ${routingInterceptorOptions.request.url} (openapi spec)`);
56
- const specFile = new File([stringifyJSON(spec)], `${spec.info.title}.json`, {
57
- type: "application/json"
58
- });
59
- return { matched: true, response: { status: 200, headers: {}, body: specFile } };
60
- }
61
- span?.updateName(`${routingInterceptorOptions.request.method} ${routingInterceptorOptions.request.url} (${this.provider} ui)`);
62
- const docsTitle = await value(this.docsTitle, routingInterceptorOptions) ?? spec.info.title;
63
- const docsHead = await value(this.docsHead, routingInterceptorOptions);
64
- let html;
65
- if (this.provider === "swagger") {
66
- const scriptUrl = this.providerScriptUrl ?? "https://unpkg.com/swagger-ui-dist/swagger-ui-bundle.js";
67
- const cssUrl = this.providerCssUrl ?? "https://unpkg.com/swagger-ui-dist/swagger-ui.css";
68
- const config = {
69
- dom_id: "#app",
70
- spec,
71
- deepLinking: true,
72
- presets: ["SwaggerUIBundle.presets.apis"],
73
- plugins: ["SwaggerUIBundle.plugins.DownloadUrl"],
74
- ...this.providerConfig
75
- };
76
- html = `
77
- <!doctype html>
78
- <html>
79
- <head>
80
- <meta charset="utf-8" />
81
- <meta name="viewport" content="width=device-width, initial-scale=1" />
82
- <title>${escapeHtmlEntities(docsTitle)}</title>
83
- <link rel="stylesheet" type="text/css" href="${escapeHtmlEntities(cssUrl)}" />
84
- ${docsHead}
85
- </head>
86
- <body>
87
- <div id="app"></div>
88
-
89
- <script src="${escapeHtmlEntities(scriptUrl)}"><\/script>
90
-
91
- <!-- IMPORTANT: assign to a variable first to prevent ), ( in values breaking the call expression. -->
92
- <!-- IMPORTANT: escapeJsonForHtml ensures <, > cannot terminate the <\/script> tag prematurely. -->
93
- <!-- IMPORTANT: resolve presets/plugins global paths at runtime, never unquote them in the JSON, which also holds the spec. -->
94
- <script>
95
- const swaggerConfig = ${escapeJsonForHtml(config)}
96
-
97
- window.onload = () => {
98
- for (const key of ['presets', 'plugins']) {
99
- swaggerConfig[key] &&= swaggerConfig[key].map(path => path.split('.').reduce((value, name) => value?.[name], window))
100
- }
101
-
102
- window.ui = SwaggerUIBundle(swaggerConfig)
103
- }
104
- <\/script>
105
- </body>
106
- </html>
107
- `;
108
- } else {
109
- const scriptUrl = this.providerScriptUrl ?? "https://cdn.jsdelivr.net/npm/@scalar/api-reference";
110
- const cssUrl = this.providerCssUrl;
111
- const config = {
112
- content: stringifyJSON(spec),
113
- ...this.providerConfig
114
- };
115
- html = `
116
- <!doctype html>
117
- <html>
118
- <head>
119
- <meta charset="utf-8" />
120
- <meta name="viewport" content="width=device-width, initial-scale=1" />
121
- <title>${escapeHtmlEntities(docsTitle)}</title>
122
- ${cssUrl ? `<link rel="stylesheet" type="text/css" href="${escapeHtmlEntities(cssUrl)}" />` : ""}
123
- ${docsHead}
124
- </head>
125
- <body>
126
- <div id="app"></div>
127
-
128
- <script src="${escapeHtmlEntities(scriptUrl)}"><\/script>
129
-
130
- <!-- IMPORTANT: assign to a variable first to prevent ), ( in values breaking the call expression. -->
131
- <!-- IMPORTANT: escapeJsonForHtml ensures <, > cannot terminate the <\/script> tag prematurely. -->
132
- <script>
133
- const scalarConfig = ${escapeJsonForHtml(config)}
134
-
135
- Scalar.createApiReference('#app', scalarConfig)
136
- <\/script>
137
- </body>
138
- </html>
139
- `;
140
- }
141
- const htmlBlob = new Blob([html], {
142
- type: "text/html"
143
- });
144
- return {
145
- matched: true,
146
- response: {
147
- status: 200,
148
- headers: {
149
- "content-disposition": []
150
- // disable auto-gen header
151
- },
152
- body: htmlBlob
153
- }
154
- };
155
- }
156
- ]
157
- };
158
- }
159
- }
160
- function escapeHtmlEntities(s) {
161
- return s.replace(/&/g, "&amp;").replace(/"/g, "&quot;").replace(/</g, "&lt;").replace(/>/g, "&gt;");
162
- }
163
- function escapeJsonForHtml(obj) {
164
- return stringifyJSON(obj).replace(/&/g, "\\u0026").replace(/'/g, "\\u0027").replace(/</g, "\\u003C").replace(/>/g, "\\u003E").replace(/\//g, "\\u002F");
165
- }
166
-
167
- export { OpenAPIReferenceHandlerPlugin };
@@ -1,49 +0,0 @@
1
- import { mergeHttpPath } from '@orpc/shared';
2
-
3
- const openapi = (incoming) => ({
4
- name: "~openapi",
5
- init(meta) {
6
- const existing = meta["~openapi"];
7
- const tags = existing?.tags && incoming.tags ? [...existing.tags, ...incoming.tags] : "tags" in incoming ? incoming.tags : existing?.tags;
8
- const queryStyles = existing?.queryStyles && incoming.queryStyles ? { ...existing.queryStyles, ...incoming.queryStyles } : "queryStyles" in incoming ? incoming.queryStyles : existing?.queryStyles;
9
- const paramsStyles = existing?.paramsStyles && incoming.paramsStyles ? { ...existing.paramsStyles, ...incoming.paramsStyles } : "paramsStyles" in incoming ? incoming.paramsStyles : existing?.paramsStyles;
10
- const existingSpec = existing?.spec;
11
- const incomingSpec = incoming.spec;
12
- const spec = typeof existingSpec === "function" && typeof incomingSpec === "function" ? (current) => incomingSpec(existingSpec(current)) : typeof existingSpec === "function" && typeof incomingSpec === "object" ? existingSpec(incomingSpec) : typeof existingSpec === "object" && typeof incomingSpec === "function" ? incomingSpec(existingSpec) : "spec" in incoming ? incomingSpec : existingSpec;
13
- const prefix = existing?.prefix && incoming.prefix ? mergeHttpPath(existing.prefix, incoming.prefix) : "prefix" in incoming ? incoming.prefix : existing?.prefix;
14
- const merged = {
15
- ...existing,
16
- ...incoming,
17
- tags,
18
- queryStyles,
19
- paramsStyles,
20
- spec,
21
- prefix
22
- };
23
- return {
24
- ...meta,
25
- "~openapi": merged
26
- };
27
- }
28
- });
29
- openapi.method = (method) => ({
30
- ...openapi({ method }),
31
- name: "~openapi/method"
32
- });
33
- openapi.path = (path) => ({
34
- ...openapi({ path }),
35
- name: "~openapi/path"
36
- });
37
- openapi.spec = (spec) => ({
38
- ...openapi({ spec }),
39
- name: "~openapi/spec"
40
- });
41
- openapi.prefix = (prefix) => ({
42
- ...openapi({ prefix }),
43
- name: "~openapi/prefix"
44
- });
45
- function getOpenAPIMeta(procedureOrLazy) {
46
- return procedureOrLazy["~orpc"].meta["~openapi"];
47
- }
48
-
49
- export { getOpenAPIMeta as g, openapi as o };
@@ -1,366 +0,0 @@
1
- import { MalformedResponseError, isORPCErrorJson, createORPCErrorFromJson, ResponseError } from '@orpc/client';
2
- import { getRouterContract, ProcedureContract } from '@orpc/contract';
3
- import { unlazy } from '@orpc/server';
4
- import { value, pathToHttpPath, mergeHttpPath, isTypescriptObject, stringifyJSON, safeEncodeURIComponent } from '@orpc/shared';
5
- import { mergeStandardHeaders, parseStandardUrl, flattenStandardHeader } from '@standard-server/core';
6
- import { toStandardHeaders } from '@standard-server/fetch';
7
- import { O as OpenAPISerializer, D as DEFAULT_OPENAPI_METHOD, a as DEFAULT_OPENAPI_INPUT_STRUCTURE, g as getDynamicPathParams, i as isBodylessMethod, b as DEFAULT_OPENAPI_OUTPUT_STRUCTURE } from './openapi.E3ZBiweM.mjs';
8
- import { g as getOpenAPIMeta } from './openapi.B9PQzqBn.mjs';
9
- import { s as serializeHeaders } from './openapi.g7ucL05o.mjs';
10
-
11
- const END_SLASH_REGEX = /\/$/;
12
- const DOT_SEGMENT_REGEX = /(?:^|\/)\.{1,2}(?:\/|$)/;
13
- class OpenAPILinkCodec {
14
- constructor(router, options = {}) {
15
- this.router = router;
16
- this.baseUrl = options.url ?? "/";
17
- this.headers = options.headers ?? {};
18
- this.serializer = options.serializer ?? new OpenAPISerializer();
19
- this.errorResponseBodyDecoder = options.errorResponseBodyDecoder;
20
- this.errorResponseMediaType = toMediaType(options.errorResponseContentType);
21
- }
22
- baseUrl;
23
- headers;
24
- serializer;
25
- errorResponseBodyDecoder;
26
- errorResponseMediaType;
27
- async encodeInput(input, path, options) {
28
- let headers = toResolvedStandardHeaders(await value(this.headers, options, path, input));
29
- if (options.lastEventId !== void 0) {
30
- headers = mergeStandardHeaders(headers, { "last-event-id": options.lastEventId });
31
- }
32
- const baseUrl = await value(this.baseUrl, options, path, input);
33
- const procedure = await this.resolveProcedure(path);
34
- const meta = getOpenAPIMeta(procedure);
35
- const method = meta?.method ?? DEFAULT_OPENAPI_METHOD;
36
- const inputStructure = meta?.inputStructure ?? DEFAULT_OPENAPI_INPUT_STRUCTURE;
37
- let pathname = meta?.path ?? pathToHttpPath(path);
38
- if (meta?.prefix) {
39
- pathname = mergeHttpPath(meta.prefix, pathname);
40
- }
41
- const [basePathname, baseSearch, baseHash] = parseStandardUrl(baseUrl);
42
- const dynamicParams = getDynamicPathParams(pathname);
43
- if (inputStructure === "compact") {
44
- let data = input;
45
- if (dynamicParams?.length) {
46
- if (!isTypescriptObject(input)) {
47
- throw new TypeError(
48
- `Input must be an object with "compact" input structure when the path has dynamic params (${dynamicParams.map((p) => p.parameterName).join(", ")}) in call to procedure (${path.join(".")}).`
49
- );
50
- }
51
- const remaining = { ...input };
52
- for (let i = dynamicParams.length - 1; i >= 0; i--) {
53
- const param = dynamicParams[i];
54
- const encoded = this.encodePathParam(input[param.parameterName], param, meta?.paramsStyles?.[param.parameterName], path);
55
- pathname = `${pathname.slice(0, param.startIndex)}${encoded}${pathname.slice(param.startIndex + param.segment.length)}`;
56
- delete remaining[param.parameterName];
57
- }
58
- data = Object.keys(remaining).length > 0 ? remaining : void 0;
59
- }
60
- pathname = `${basePathname.replace(END_SLASH_REGEX, "")}${pathname}`;
61
- if (isBodylessMethod(method)) {
62
- const queryString2 = this.serializeQueryString(data, meta?.queryStyles);
63
- const search2 = combineSearch(baseSearch, queryString2);
64
- const url3 = `${pathname}${search2 ?? ""}${baseHash ?? ""}`;
65
- return {
66
- body: void 0,
67
- method,
68
- headers,
69
- url: url3,
70
- signal: options.signal
71
- };
72
- }
73
- const url2 = `${pathname}${baseSearch ?? ""}${baseHash ?? ""}`;
74
- return {
75
- url: url2,
76
- method,
77
- headers,
78
- body: this.serializer.serialize(data),
79
- signal: options.signal
80
- };
81
- }
82
- if (!isValidDetailedInput(input)) {
83
- throw new TypeError(`
84
- Invalid "detailed" input structure in call to procedure (${path.join(".")}):
85
- \u2022 Expected an object or undefined with optional properties:
86
- - params (object, required when the path has dynamic params)
87
- - query (object)
88
- - headers (object)
89
- - body (any)
90
-
91
- Actual value:
92
- ${stringifyJSON(input)}
93
- `);
94
- }
95
- if (dynamicParams?.length) {
96
- if (!input?.params) {
97
- throw new TypeError(
98
- `The "params" property is required for "detailed" input when the path has dynamic params (${dynamicParams.map((p) => p.parameterName).join(", ")}) in call to procedure (${path.join(".")}).`
99
- );
100
- }
101
- for (let i = dynamicParams.length - 1; i >= 0; i--) {
102
- const param = dynamicParams[i];
103
- const val = input.params[param.parameterName];
104
- const encoded = this.encodePathParam(val, param, meta?.paramsStyles?.[param.parameterName], path);
105
- pathname = `${pathname.slice(0, param.startIndex)}${encoded}${pathname.slice(param.startIndex + param.segment.length)}`;
106
- }
107
- }
108
- if (input?.headers) {
109
- headers = mergeStandardHeaders(headers, serializeHeaders(input.headers, this.serializer));
110
- }
111
- pathname = `${basePathname.replace(END_SLASH_REGEX, "")}${pathname}`;
112
- const queryString = this.serializeQueryString(input?.query, meta?.queryStyles);
113
- const search = combineSearch(baseSearch, queryString);
114
- const url = `${pathname}${search ?? ""}${baseHash ?? ""}`;
115
- if (isBodylessMethod(method)) {
116
- return {
117
- body: void 0,
118
- method,
119
- headers,
120
- url,
121
- signal: options.signal
122
- };
123
- }
124
- return {
125
- url,
126
- method,
127
- headers,
128
- body: this.serializer.serialize(input?.body),
129
- signal: options.signal
130
- };
131
- }
132
- encodePathParam(val, param, style, path) {
133
- let encoded;
134
- if (style === "comma-delimited-array" && Array.isArray(val)) {
135
- encoded = val.map((val2) => this.serializer.serialize(val2)).filter((val2) => val2 !== void 0 && val2 !== null).map((val2) => safeEncodeURIComponent(String(val2))).join(",");
136
- } else if (style === "comma-delimited-object" && isTypescriptObject(val)) {
137
- encoded = Object.entries(val).map(([key, val2]) => [key, this.serializer.serialize(val2)]).filter(([, val2]) => val2 !== void 0 && val2 !== null).map(([key, val2]) => `${safeEncodeURIComponent(String(key))},${safeEncodeURIComponent(String(val2))}`).join(",");
138
- } else {
139
- const serialized = this.serializer.serialize(val);
140
- if (serialized !== void 0 && serialized !== null) {
141
- if (param.allowsSlash) {
142
- encoded = String(serialized).split("/").map(safeEncodeURIComponent).join("/");
143
- } else {
144
- encoded = safeEncodeURIComponent(String(serialized));
145
- }
146
- }
147
- }
148
- if (!encoded) {
149
- throw new TypeError(`Path param "${param.parameterName}" cannot be empty in call to procedure (${path.join(".")}).`);
150
- }
151
- if (DOT_SEGMENT_REGEX.test(encoded)) {
152
- throw new TypeError(`Path param "${param.parameterName}" cannot contain "." or ".." segments in call to procedure (${path.join(".")}).`);
153
- }
154
- if (encoded.startsWith("/")) {
155
- encoded = `%2F${encoded.slice(1)}`;
156
- }
157
- return encoded;
158
- }
159
- serializeQueryString(data, queryStyles) {
160
- if (!queryStyles || !isTypescriptObject(data)) {
161
- return toURLSearchParams(
162
- this.serializer.serialize(data, { asFormData: true })
163
- ).toString();
164
- }
165
- const remaining = { ...data };
166
- let query = "";
167
- Object.entries(queryStyles).forEach(([key, style]) => {
168
- if (style === void 0) {
169
- return;
170
- }
171
- const value2 = remaining[key];
172
- delete remaining[key];
173
- if (style === "primitive") {
174
- const serialized = this.serializer.serialize(value2);
175
- if (serialized !== void 0 && serialized !== null) {
176
- query += `&${encodeURLSearchParamComponent(key)}=${encodeURLSearchParamComponent(String(serialized))}`;
177
- }
178
- } else if (style === "array" && Array.isArray(value2)) {
179
- const encodedKey = encodeURLSearchParamComponent(key);
180
- value2.forEach((v) => {
181
- const s = this.serializer.serialize(v);
182
- if (s !== void 0 && s !== null) {
183
- query += `&${encodedKey}=${encodeURLSearchParamComponent(String(s))}`;
184
- }
185
- });
186
- } else if (style === "json") {
187
- const serialized = this.serializer.serialize(value2);
188
- if (serialized !== void 0) {
189
- query += `&${encodeURLSearchParamComponent(key)}=${encodeURLSearchParamComponent(stringifyJSON(serialized))}`;
190
- }
191
- } else if (style === "comma-delimited-array" && Array.isArray(value2)) {
192
- const encodedValue = encodeDelimitedArray(
193
- value2.map((v) => this.serializer.serialize(v)),
194
- ","
195
- );
196
- if (encodedValue !== void 0) {
197
- query += `&${encodeURLSearchParamComponent(key)}=${encodedValue}`;
198
- }
199
- } else if (style === "comma-delimited-object" && isTypescriptObject(value2)) {
200
- const encodedValue = encodeDelimitedObject(
201
- Object.entries(value2).map(([key2, value3]) => [key2, this.serializer.serialize(value3)]),
202
- ","
203
- );
204
- if (encodedValue !== void 0) {
205
- query += `&${encodeURLSearchParamComponent(key)}=${encodedValue}`;
206
- }
207
- } else if (style === "pipe-delimited-array" && Array.isArray(value2)) {
208
- const encodedValue = encodeDelimitedArray(
209
- value2.map((v) => this.serializer.serialize(v)),
210
- "%7C"
211
- );
212
- if (encodedValue !== void 0) {
213
- query += `&${encodeURLSearchParamComponent(key)}=${encodedValue}`;
214
- }
215
- } else if (style === "pipe-delimited-object" && isTypescriptObject(value2)) {
216
- const encodedValue = encodeDelimitedObject(
217
- Object.entries(value2).map(([key2, value3]) => [key2, this.serializer.serialize(value3)]),
218
- "%7C"
219
- );
220
- if (encodedValue !== void 0) {
221
- query += `&${encodeURLSearchParamComponent(key)}=${encodedValue}`;
222
- }
223
- } else if (style === "space-delimited-array" && Array.isArray(value2)) {
224
- const encodedValue = encodeDelimitedArray(
225
- value2.map((v) => this.serializer.serialize(v)),
226
- "%20"
227
- );
228
- if (encodedValue !== void 0) {
229
- query += `&${encodeURLSearchParamComponent(key)}=${encodedValue}`;
230
- }
231
- } else if (style === "space-delimited-object" && isTypescriptObject(value2)) {
232
- const encodedValue = encodeDelimitedObject(
233
- Object.entries(value2).map(([key2, value3]) => [key2, this.serializer.serialize(value3)]),
234
- "%20"
235
- );
236
- if (encodedValue !== void 0) {
237
- query += `&${encodeURLSearchParamComponent(key)}=${encodedValue}`;
238
- }
239
- } else {
240
- const serialized = this.serializer.serialize(value2);
241
- if (serialized !== void 0 && serialized !== null) {
242
- query += `&${encodeURLSearchParamComponent(key)}=${encodeURLSearchParamComponent(String(serialized))}`;
243
- }
244
- }
245
- });
246
- const form = this.serializer.serialize(remaining, { asFormData: true });
247
- query = `${toURLSearchParams(form).toString()}${query}`;
248
- if (query.startsWith("&")) {
249
- query = query.slice(1);
250
- }
251
- return query || void 0;
252
- }
253
- async decodeResponse(response, path, _options) {
254
- const isOk = response.status < 400;
255
- const procedure = await this.resolveProcedure(path);
256
- const meta = getOpenAPIMeta(procedure);
257
- const errorBodyHint = !isOk && this.errorResponseMediaType !== void 0 && toMediaType(flattenStandardHeader(response.headers["content-type"])) === this.errorResponseMediaType ? "json" : void 0;
258
- const body = await response.resolveBody(isOk ? meta?.responseBodyHint : errorBodyHint);
259
- const deserialized = await (async () => {
260
- try {
261
- return this.serializer.deserialize(body);
262
- } catch (error) {
263
- throw new MalformedResponseError({
264
- message: "Invalid OpenAPI response format.",
265
- response: { status: response.status, headers: response.headers, body },
266
- cause: error
267
- });
268
- }
269
- })();
270
- if (!isOk) {
271
- const customError = this.errorResponseBodyDecoder?.(deserialized, response);
272
- if (customError !== void 0 && customError !== null) {
273
- return { kind: "error", error: customError };
274
- }
275
- if (isORPCErrorJson(deserialized)) {
276
- return {
277
- kind: "error",
278
- error: createORPCErrorFromJson(deserialized, {
279
- cause: new ResponseError({ response: { status: response.status, headers: response.headers, body } })
280
- })
281
- };
282
- }
283
- throw new MalformedResponseError({ response: { headers: response.headers, status: response.status, body } });
284
- }
285
- const outputStructure = meta?.outputStructure ?? DEFAULT_OPENAPI_OUTPUT_STRUCTURE;
286
- return outputStructure === "compact" ? { kind: "output", output: deserialized } : {
287
- kind: "output",
288
- output: {
289
- status: response.status,
290
- headers: response.headers,
291
- body: deserialized
292
- }
293
- };
294
- }
295
- async resolveProcedure(path) {
296
- const { default: maybeProcedure } = await unlazy(getRouterContract(this.router, path));
297
- if (!(maybeProcedure instanceof ProcedureContract)) {
298
- throw new TypeError(`Expected a procedure or contract at path (${path.join(".")})`);
299
- }
300
- return maybeProcedure;
301
- }
302
- }
303
- function combineSearch(baseSearch, additionalSearch) {
304
- if (!baseSearch && !additionalSearch) {
305
- return void 0;
306
- }
307
- if (!additionalSearch) {
308
- return baseSearch;
309
- }
310
- if (!baseSearch) {
311
- return `?${additionalSearch}`;
312
- }
313
- return `${baseSearch}&${additionalSearch}`;
314
- }
315
- function toMediaType(contentType) {
316
- return contentType?.split(";")[0]?.trim().toLowerCase();
317
- }
318
- function toResolvedStandardHeaders(headers) {
319
- if (typeof headers.forEach === "function") {
320
- return toStandardHeaders(headers);
321
- }
322
- return headers;
323
- }
324
- function isValidDetailedInput(input) {
325
- if (!isTypescriptObject(input)) {
326
- return input === void 0;
327
- }
328
- if (input.params !== void 0 && !isTypescriptObject(input.params)) {
329
- return false;
330
- }
331
- if (input.query !== void 0 && !isTypescriptObject(input.query)) {
332
- return false;
333
- }
334
- if (input.headers !== void 0 && !isTypescriptObject(input.headers)) {
335
- return false;
336
- }
337
- return true;
338
- }
339
- function encodeURLSearchParamComponent(value2) {
340
- return new URLSearchParams({ "": value2 }).toString().slice(1);
341
- }
342
- function toURLSearchParams(form) {
343
- const params = new URLSearchParams();
344
- for (const [key, value2] of form) {
345
- params.append(key, String(value2));
346
- }
347
- return params;
348
- }
349
- function encodeDelimitedArray(serializedValues, encodedDelimiter) {
350
- const strings = serializedValues.filter((v) => v !== null && v !== void 0).map(String);
351
- if (!strings.length) {
352
- return void 0;
353
- }
354
- return strings.map(encodeURLSearchParamComponent).join(encodedDelimiter);
355
- }
356
- function encodeDelimitedObject(entries, encodedDelimiter) {
357
- const strings = entries.filter(([, v]) => v !== null && v !== void 0).map(([k, v]) => [k, String(v)]);
358
- if (!strings.length) {
359
- return void 0;
360
- }
361
- return strings.map(
362
- ([key, value2]) => `${encodeURLSearchParamComponent(key)}${encodedDelimiter}${encodeURLSearchParamComponent(value2)}`
363
- ).join(encodedDelimiter);
364
- }
365
-
366
- export { OpenAPILinkCodec as O };
@@ -1,33 +0,0 @@
1
- import * as OpenAPIV3_0 from '@openapi-spec/types/v3.0';
2
- import * as OpenAPIV3_1 from '@openapi-spec/types/v3.1';
3
- import * as OpenAPIV3_2 from '@openapi-spec/types/v3.2';
4
- import { AnyNestedClient, Client, ORPCError } from '@orpc/client';
5
- import { AsyncIteratorClass } from '@orpc/shared';
6
-
7
- /**
8
- * An OpenAPI version `OpenAPIGenerator` can target: any `3.0.x`, `3.1.x`, or `3.2.x` value.
9
- *
10
- * @see {@link https://orpc.dev/docs/openapi/specification#openapi-version | OpenAPI Specification - OpenAPI Version}
11
- */
12
- type OpenAPIVersion = `3.0.${number}` | `3.1.${number}` | `3.2.${number}`;
13
- /**
14
- * The OpenAPI document of the given version.
15
- *
16
- * @see {@link https://orpc.dev/docs/openapi/specification#openapi-version | OpenAPI Specification - OpenAPI Version}
17
- */
18
- type OpenAPIDocument<TVersion extends OpenAPIVersion> = TVersion extends `3.0.${string}` ? OpenAPIV3_0.OpenAPIObject : TVersion extends `3.1.${string}` ? OpenAPIV3_1.OpenAPIObject : OpenAPIV3_2.OpenAPIObject;
19
- type JsonifiedValue<T> = T extends string | number | boolean | null | undefined ? T : T extends Date | bigint | URL ? string : T extends ReadonlyArray<unknown> ? JsonifiedArray<T> : T extends Blob | ReadonlyMap<any, any> | ReadonlySet<any> | AsyncIteratorObject<any, any, any> | Function ? T extends File ? File : T extends Blob ? Blob : T extends ReadonlyMap<infer K, infer V> ? JsonifiedArray<[K, V][]> : T extends ReadonlySet<infer U> ? JsonifiedArray<U[]> : T extends AsyncIteratorClass<infer U, infer V> ? AsyncIteratorClass<JsonifiedValue<U>, JsonifiedValue<V>> : T extends AsyncGenerator<infer U, infer V> ? AsyncGenerator<JsonifiedValue<U>, JsonifiedValue<V>> : T extends AsyncIteratorObject<infer U, infer V> ? AsyncIteratorObject<JsonifiedValue<U>, JsonifiedValue<V>> : unknown : T extends object ? {
20
- [K in keyof T]: JsonifiedValue<T[K]>;
21
- } : unknown;
22
- type JsonifiedArray<T extends ReadonlyArray<unknown>> = T extends readonly [] ? [] : T extends readonly [infer U, ...infer V] ? [U extends undefined ? null : JsonifiedValue<U>, ...JsonifiedArray<V>] : T extends ReadonlyArray<infer U> ? Array<JsonifiedValue<U>> : unknown;
23
- type JsonifiedClientError<T> = T extends ORPCError<infer UCode, infer UData> ? ORPCError<UCode, JsonifiedValue<UData>> : T;
24
- /**
25
- * Client type whose outputs and error data replace types JSON cannot represent with their JSON equivalents.
26
- *
27
- * @see {@link https://orpc.dev/docs/openapi/link | OpenAPI Link}
28
- */
29
- type JsonifiedClient<T extends AnyNestedClient> = T extends Client<infer UClientContext, infer UInput, infer UOutput, infer UError> ? Client<UClientContext, UInput, JsonifiedValue<UOutput>, JsonifiedClientError<UError>> : {
30
- [K in keyof T]: T[K] extends AnyNestedClient ? JsonifiedClient<T[K]> : T[K];
31
- };
32
-
33
- export type { JsonifiedClient as J, OpenAPIDocument as O, OpenAPIVersion as a, JsonifiedArray as b, JsonifiedClientError as c, JsonifiedValue as d };
@@ -1,33 +0,0 @@
1
- import * as OpenAPIV3_0 from '@openapi-spec/types/v3.0';
2
- import * as OpenAPIV3_1 from '@openapi-spec/types/v3.1';
3
- import * as OpenAPIV3_2 from '@openapi-spec/types/v3.2';
4
- import { AnyNestedClient, Client, ORPCError } from '@orpc/client';
5
- import { AsyncIteratorClass } from '@orpc/shared';
6
-
7
- /**
8
- * An OpenAPI version `OpenAPIGenerator` can target: any `3.0.x`, `3.1.x`, or `3.2.x` value.
9
- *
10
- * @see {@link https://orpc.dev/docs/openapi/specification#openapi-version | OpenAPI Specification - OpenAPI Version}
11
- */
12
- type OpenAPIVersion = `3.0.${number}` | `3.1.${number}` | `3.2.${number}`;
13
- /**
14
- * The OpenAPI document of the given version.
15
- *
16
- * @see {@link https://orpc.dev/docs/openapi/specification#openapi-version | OpenAPI Specification - OpenAPI Version}
17
- */
18
- type OpenAPIDocument<TVersion extends OpenAPIVersion> = TVersion extends `3.0.${string}` ? OpenAPIV3_0.OpenAPIObject : TVersion extends `3.1.${string}` ? OpenAPIV3_1.OpenAPIObject : OpenAPIV3_2.OpenAPIObject;
19
- type JsonifiedValue<T> = T extends string | number | boolean | null | undefined ? T : T extends Date | bigint | URL ? string : T extends ReadonlyArray<unknown> ? JsonifiedArray<T> : T extends Blob | ReadonlyMap<any, any> | ReadonlySet<any> | AsyncIteratorObject<any, any, any> | Function ? T extends File ? File : T extends Blob ? Blob : T extends ReadonlyMap<infer K, infer V> ? JsonifiedArray<[K, V][]> : T extends ReadonlySet<infer U> ? JsonifiedArray<U[]> : T extends AsyncIteratorClass<infer U, infer V> ? AsyncIteratorClass<JsonifiedValue<U>, JsonifiedValue<V>> : T extends AsyncGenerator<infer U, infer V> ? AsyncGenerator<JsonifiedValue<U>, JsonifiedValue<V>> : T extends AsyncIteratorObject<infer U, infer V> ? AsyncIteratorObject<JsonifiedValue<U>, JsonifiedValue<V>> : unknown : T extends object ? {
20
- [K in keyof T]: JsonifiedValue<T[K]>;
21
- } : unknown;
22
- type JsonifiedArray<T extends ReadonlyArray<unknown>> = T extends readonly [] ? [] : T extends readonly [infer U, ...infer V] ? [U extends undefined ? null : JsonifiedValue<U>, ...JsonifiedArray<V>] : T extends ReadonlyArray<infer U> ? Array<JsonifiedValue<U>> : unknown;
23
- type JsonifiedClientError<T> = T extends ORPCError<infer UCode, infer UData> ? ORPCError<UCode, JsonifiedValue<UData>> : T;
24
- /**
25
- * Client type whose outputs and error data replace types JSON cannot represent with their JSON equivalents.
26
- *
27
- * @see {@link https://orpc.dev/docs/openapi/link | OpenAPI Link}
28
- */
29
- type JsonifiedClient<T extends AnyNestedClient> = T extends Client<infer UClientContext, infer UInput, infer UOutput, infer UError> ? Client<UClientContext, UInput, JsonifiedValue<UOutput>, JsonifiedClientError<UError>> : {
30
- [K in keyof T]: T[K] extends AnyNestedClient ? JsonifiedClient<T[K]> : T[K];
31
- };
32
-
33
- export type { JsonifiedClient as J, OpenAPIDocument as O, OpenAPIVersion as a, JsonifiedArray as b, JsonifiedClientError as c, JsonifiedValue as d };