@orpc/openapi 2.0.0-beta.48 → 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.
- package/README.md +4 -4
- package/dist/adapters/aws-lambda/index.d.ts +15 -0
- package/dist/adapters/aws-lambda/index.js +1 -0
- package/dist/adapters/aws-lambda/openapi-handler.d.ts +18 -0
- package/dist/adapters/aws-lambda/openapi-handler.js +18 -0
- package/dist/adapters/fastify/index.d.ts +1 -0
- package/dist/adapters/fastify/index.js +1 -0
- package/dist/adapters/fastify/openapi-handler.d.ts +15 -0
- package/dist/adapters/fastify/openapi-handler.js +15 -0
- package/dist/adapters/fetch/index.d.ts +2 -0
- package/dist/adapters/fetch/index.js +2 -0
- package/dist/adapters/fetch/openapi-handler.d.ts +15 -0
- package/dist/adapters/fetch/openapi-handler.js +15 -0
- package/dist/adapters/fetch/openapi-link.d.ts +21 -0
- package/dist/adapters/fetch/openapi-link.js +20 -0
- package/dist/adapters/node/index.d.ts +1 -0
- package/dist/adapters/node/index.js +1 -0
- package/dist/adapters/node/openapi-handler.d.ts +15 -0
- package/dist/adapters/node/openapi-handler.js +15 -0
- package/dist/adapters/standard/index.d.ts +3 -0
- package/dist/adapters/standard/index.js +3 -0
- package/dist/adapters/standard/openapi-handler-codec.d.ts +62 -0
- package/dist/adapters/standard/openapi-handler-codec.js +220 -0
- package/dist/adapters/standard/openapi-link-codec.d.ts +62 -0
- package/dist/adapters/standard/openapi-link-codec.js +405 -0
- package/dist/adapters/standard/openapi-matcher.d.ts +29 -0
- package/dist/adapters/standard/openapi-matcher.js +108 -0
- package/dist/adapters/standard/utils.d.ts +4 -0
- package/dist/adapters/standard/utils.js +47 -0
- package/dist/bracket-notation.d.ts +26 -0
- package/dist/bracket-notation.js +185 -0
- package/dist/client-factory.d.ts +24 -0
- package/dist/client-factory.js +13 -0
- package/dist/constants.js +4 -0
- package/dist/extensions/route.d.ts +37 -0
- package/dist/extensions/route.js +12 -0
- package/dist/helpers/form-data.d.ts +57 -0
- package/dist/helpers/form-data.js +90 -0
- package/dist/helpers/index.d.ts +1 -0
- package/dist/helpers/index.js +1 -0
- package/dist/index.d.ts +13 -0
- package/dist/index.js +11 -0
- package/dist/meta.d.ts +325 -0
- package/dist/meta.js +84 -0
- package/dist/openapi-generator-components.d.ts +31 -0
- package/dist/openapi-generator-components.js +275 -0
- package/dist/openapi-generator-operation.d.ts +34 -0
- package/dist/openapi-generator-operation.js +469 -0
- package/dist/openapi-generator.d.ts +92 -0
- package/dist/openapi-generator.js +147 -0
- package/dist/openapi-json-serializer.d.ts +79 -0
- package/dist/openapi-json-serializer.js +260 -0
- package/dist/openapi-serializer.d.ts +43 -0
- package/dist/openapi-serializer.js +93 -0
- package/dist/plugins/index.d.ts +1 -0
- package/dist/plugins/index.js +1 -0
- package/dist/plugins/openapi-reference.d.ts +115 -0
- package/dist/plugins/openapi-reference.js +187 -0
- package/dist/router-utils.d.ts +20 -0
- package/dist/router-utils.js +36 -0
- package/dist/{types.d.mts → types.d.ts} +23 -19
- package/dist/utils.d.ts +14 -0
- package/dist/utils.js +47 -0
- package/package.json +69 -71
- package/dist/adapters/aws-lambda/index.d.mts +0 -15
- package/dist/adapters/aws-lambda/index.mjs +0 -1
- package/dist/adapters/aws-lambda/openapi-handler.d.mts +0 -17
- package/dist/adapters/aws-lambda/openapi-handler.mjs +0 -11
- package/dist/adapters/fastify/index.d.mts +0 -1
- package/dist/adapters/fastify/index.mjs +0 -1
- package/dist/adapters/fastify/openapi-handler.d.mts +0 -14
- package/dist/adapters/fastify/openapi-handler.mjs +0 -11
- package/dist/adapters/fetch/index.d.mts +0 -2
- package/dist/adapters/fetch/index.mjs +0 -2
- package/dist/adapters/fetch/openapi-handler.d.mts +0 -14
- package/dist/adapters/fetch/openapi-handler.mjs +0 -11
- package/dist/adapters/fetch/openapi-link.d.mts +0 -15
- package/dist/adapters/fetch/openapi-link.mjs +0 -11
- package/dist/adapters/node/index.d.mts +0 -1
- package/dist/adapters/node/index.mjs +0 -1
- package/dist/adapters/node/openapi-handler.d.mts +0 -14
- package/dist/adapters/node/openapi-handler.mjs +0 -11
- package/dist/adapters/standard/index.d.mts +0 -3
- package/dist/adapters/standard/index.mjs +0 -3
- package/dist/adapters/standard/openapi-handler-codec.d.mts +0 -61
- package/dist/adapters/standard/openapi-handler-codec.mjs +0 -203
- package/dist/adapters/standard/openapi-link-codec.d.mts +0 -53
- package/dist/adapters/standard/openapi-link-codec.mjs +0 -356
- package/dist/adapters/standard/openapi-matcher.d.mts +0 -29
- package/dist/adapters/standard/openapi-matcher.mjs +0 -105
- package/dist/adapters/standard/utils.d.mts +0 -4
- package/dist/adapters/standard/utils.mjs +0 -36
- package/dist/bracket-notation.d.mts +0 -26
- package/dist/bracket-notation.mjs +0 -156
- package/dist/client-factory.d.mts +0 -24
- package/dist/client-factory.mjs +0 -5
- package/dist/constants.mjs +0 -4
- package/dist/extensions/route.d.mts +0 -76
- package/dist/extensions/route.mjs +0 -12
- package/dist/helpers/form-data.d.mts +0 -57
- package/dist/helpers/form-data.mjs +0 -36
- package/dist/helpers/index.d.mts +0 -1
- package/dist/helpers/index.mjs +0 -1
- package/dist/index.d.mts +0 -13
- package/dist/index.mjs +0 -11
- package/dist/meta.d.mts +0 -345
- package/dist/meta.mjs +0 -56
- package/dist/openapi-generator-components.d.mts +0 -24
- package/dist/openapi-generator-components.mjs +0 -227
- package/dist/openapi-generator-operation.d.mts +0 -29
- package/dist/openapi-generator-operation.mjs +0 -447
- package/dist/openapi-generator.d.mts +0 -87
- package/dist/openapi-generator.mjs +0 -115
- package/dist/openapi-json-serializer.d.mts +0 -86
- package/dist/openapi-json-serializer.mjs +0 -229
- package/dist/openapi-serializer.d.mts +0 -43
- package/dist/openapi-serializer.mjs +0 -87
- package/dist/plugins/index.d.mts +0 -1
- package/dist/plugins/index.mjs +0 -1
- package/dist/plugins/openapi-reference.d.mts +0 -118
- package/dist/plugins/openapi-reference.mjs +0 -157
- package/dist/router-utils.d.mts +0 -18
- package/dist/router-utils.mjs +0 -29
- package/dist/utils.d.mts +0 -14
- package/dist/utils.mjs +0 -40
- /package/dist/{constants.d.mts → constants.d.ts} +0 -0
- /package/dist/{types.mjs → types.js} +0 -0
|
@@ -0,0 +1,405 @@
|
|
|
1
|
+
import { createORPCErrorFromJson, isORPCErrorJson, MalformedResponseError, ResponseError, } from '@orpc/client';
|
|
2
|
+
import { getRouterContract, ProcedureContract } from '@orpc/contract';
|
|
3
|
+
import { unlazy } from '@orpc/server';
|
|
4
|
+
import { isNonPrimitive, mergeHttpPath, pathToHttpPath, safeEncodeURIComponent, stringifyJSON, value, } from '@orpc/shared';
|
|
5
|
+
import { flattenStandardHeader, mergeStandardHeaders, parseStandardUrl, } from '@standard-server/core';
|
|
6
|
+
import { toStandardHeaders } from '@standard-server/fetch';
|
|
7
|
+
import { DEFAULT_OPENAPI_INPUT_STRUCTURE, DEFAULT_OPENAPI_METHOD, DEFAULT_OPENAPI_OUTPUT_STRUCTURE, } from '../../constants.js';
|
|
8
|
+
import { getOpenAPIMeta } from '../../meta.js';
|
|
9
|
+
import { OpenAPISerializer } from '../../openapi-serializer.js';
|
|
10
|
+
import { getDynamicPathParams, isBodylessMethod } from '../../utils.js';
|
|
11
|
+
import { serializeHeaders } from './utils.js';
|
|
12
|
+
const END_SLASH_REGEX = /\/$/;
|
|
13
|
+
const DOT_SEGMENT_REGEX = /(?:^|\/)\.{1,2}(?:\/|$)/;
|
|
14
|
+
export class OpenAPILinkCodec {
|
|
15
|
+
router;
|
|
16
|
+
baseUrl;
|
|
17
|
+
headers;
|
|
18
|
+
serializer;
|
|
19
|
+
errorResponseBodyDecoder;
|
|
20
|
+
errorResponseMediaType;
|
|
21
|
+
constructor(router, options = {}) {
|
|
22
|
+
this.router = router;
|
|
23
|
+
this.baseUrl = options.url ?? '/';
|
|
24
|
+
this.headers = options.headers ?? {};
|
|
25
|
+
this.serializer = options.serializer ?? new OpenAPISerializer();
|
|
26
|
+
this.errorResponseBodyDecoder =
|
|
27
|
+
options.errorResponseBodyDecoder ?? ((_body, _response, defaultError) => defaultError());
|
|
28
|
+
this.errorResponseMediaType = toMediaType(options.errorResponseContentType);
|
|
29
|
+
}
|
|
30
|
+
async encodeInput(input, path, options) {
|
|
31
|
+
let headers = toResolvedStandardHeaders(await value(this.headers, options, path, input));
|
|
32
|
+
if (options.lastEventId !== undefined) {
|
|
33
|
+
headers = mergeStandardHeaders(headers, { 'last-event-id': options.lastEventId });
|
|
34
|
+
}
|
|
35
|
+
const baseUrl = await value(this.baseUrl, options, path, input);
|
|
36
|
+
const procedure = await this.resolveProcedure(path);
|
|
37
|
+
const meta = getOpenAPIMeta(procedure);
|
|
38
|
+
const method = meta?.method ?? DEFAULT_OPENAPI_METHOD;
|
|
39
|
+
const inputStructure = meta?.inputStructure ?? DEFAULT_OPENAPI_INPUT_STRUCTURE;
|
|
40
|
+
let pathname = meta?.path ?? pathToHttpPath(path);
|
|
41
|
+
if (meta?.prefix) {
|
|
42
|
+
pathname = mergeHttpPath(meta.prefix, pathname);
|
|
43
|
+
}
|
|
44
|
+
const [basePathname, baseSearch, baseHash] = parseStandardUrl(baseUrl);
|
|
45
|
+
const dynamicParams = getDynamicPathParams(pathname);
|
|
46
|
+
if (inputStructure === 'compact') {
|
|
47
|
+
let data = input;
|
|
48
|
+
if (dynamicParams?.length) {
|
|
49
|
+
if (!isNonPrimitive(input)) {
|
|
50
|
+
throw new TypeError(`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('.')}).`);
|
|
51
|
+
}
|
|
52
|
+
const remaining = { ...input };
|
|
53
|
+
for (let i = dynamicParams.length - 1; i >= 0; i--) {
|
|
54
|
+
const param = dynamicParams[i];
|
|
55
|
+
const encoded = this.encodePathParam(input[param.parameterName], param, meta?.paramsStyles?.[param.parameterName], path);
|
|
56
|
+
pathname =
|
|
57
|
+
`${pathname.slice(0, param.startIndex)}${encoded}${pathname.slice(param.startIndex + param.segment.length)}`;
|
|
58
|
+
delete remaining[param.parameterName];
|
|
59
|
+
}
|
|
60
|
+
data = Object.keys(remaining).length > 0 ? remaining : undefined;
|
|
61
|
+
}
|
|
62
|
+
pathname = `${basePathname.replace(END_SLASH_REGEX, '')}${pathname}`;
|
|
63
|
+
if (isBodylessMethod(method)) {
|
|
64
|
+
const queryString = this.serializeQueryString(data, meta?.queryStyles);
|
|
65
|
+
const search = combineSearch(baseSearch, queryString);
|
|
66
|
+
const url = `${pathname}${search ?? ''}${baseHash ?? ''}`;
|
|
67
|
+
return {
|
|
68
|
+
body: undefined,
|
|
69
|
+
method,
|
|
70
|
+
headers,
|
|
71
|
+
url,
|
|
72
|
+
signal: options.signal,
|
|
73
|
+
};
|
|
74
|
+
}
|
|
75
|
+
const url = `${pathname}${baseSearch ?? ''}${baseHash ?? ''}`;
|
|
76
|
+
return {
|
|
77
|
+
url,
|
|
78
|
+
method,
|
|
79
|
+
headers,
|
|
80
|
+
body: this.serializer.serialize(data),
|
|
81
|
+
signal: options.signal,
|
|
82
|
+
};
|
|
83
|
+
}
|
|
84
|
+
if (!isValidDetailedInput(input)) {
|
|
85
|
+
throw new TypeError(`
|
|
86
|
+
Invalid "detailed" input structure in call to procedure (${path.join('.')}):
|
|
87
|
+
• Expected an object or undefined with optional properties:
|
|
88
|
+
- params (object, required when the path has dynamic params)
|
|
89
|
+
- query (object)
|
|
90
|
+
- headers (object)
|
|
91
|
+
- body (any)
|
|
92
|
+
|
|
93
|
+
Actual value:
|
|
94
|
+
${stringifyJSON(input)}
|
|
95
|
+
`);
|
|
96
|
+
}
|
|
97
|
+
if (dynamicParams?.length) {
|
|
98
|
+
if (!input?.params) {
|
|
99
|
+
throw new TypeError(`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('.')}).`);
|
|
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 =
|
|
106
|
+
`${pathname.slice(0, param.startIndex)}${encoded}${pathname.slice(param.startIndex + param.segment.length)}`;
|
|
107
|
+
}
|
|
108
|
+
}
|
|
109
|
+
if (input?.headers) {
|
|
110
|
+
headers = mergeStandardHeaders(headers, serializeHeaders(input.headers, this.serializer));
|
|
111
|
+
}
|
|
112
|
+
pathname = `${basePathname.replace(END_SLASH_REGEX, '')}${pathname}`;
|
|
113
|
+
const queryString = this.serializeQueryString(input?.query, meta?.queryStyles);
|
|
114
|
+
const search = combineSearch(baseSearch, queryString);
|
|
115
|
+
const url = `${pathname}${search ?? ''}${baseHash ?? ''}`;
|
|
116
|
+
if (isBodylessMethod(method)) {
|
|
117
|
+
return {
|
|
118
|
+
body: undefined,
|
|
119
|
+
method,
|
|
120
|
+
headers,
|
|
121
|
+
url,
|
|
122
|
+
signal: options.signal,
|
|
123
|
+
};
|
|
124
|
+
}
|
|
125
|
+
return {
|
|
126
|
+
url,
|
|
127
|
+
method,
|
|
128
|
+
headers,
|
|
129
|
+
body: this.serializer.serialize(input?.body),
|
|
130
|
+
signal: options.signal,
|
|
131
|
+
};
|
|
132
|
+
}
|
|
133
|
+
encodePathParam(val, param, style, path) {
|
|
134
|
+
let encoded;
|
|
135
|
+
if (style === 'comma-delimited-array' && Array.isArray(val)) {
|
|
136
|
+
encoded = val
|
|
137
|
+
.map((val) => this.serializeURLValue(val))
|
|
138
|
+
.filter((val) => val !== undefined && val !== null)
|
|
139
|
+
// oxlint-disable-next-line typescript/no-base-to-string
|
|
140
|
+
.map((val) => safeEncodeURIComponent(String(val)))
|
|
141
|
+
.join(',');
|
|
142
|
+
}
|
|
143
|
+
else if (style === 'comma-delimited-object' && isNonPrimitive(val)) {
|
|
144
|
+
encoded = Object.entries(val)
|
|
145
|
+
.map(([key, val]) => [key, this.serializeURLValue(val)])
|
|
146
|
+
.filter(([, val]) => val !== undefined && val !== null)
|
|
147
|
+
.map(([key, val]) => `${safeEncodeURIComponent(String(key))},${safeEncodeURIComponent(String(val))}`)
|
|
148
|
+
.join(',');
|
|
149
|
+
}
|
|
150
|
+
else {
|
|
151
|
+
const serialized = this.serializeURLValue(val);
|
|
152
|
+
if (serialized !== undefined && serialized !== null) {
|
|
153
|
+
if (param.allowsSlash) {
|
|
154
|
+
// oxlint-disable-next-line typescript/no-base-to-string
|
|
155
|
+
encoded = String(serialized).split('/').map(safeEncodeURIComponent).join('/');
|
|
156
|
+
}
|
|
157
|
+
else {
|
|
158
|
+
// oxlint-disable-next-line typescript/no-base-to-string
|
|
159
|
+
encoded = safeEncodeURIComponent(String(serialized));
|
|
160
|
+
}
|
|
161
|
+
}
|
|
162
|
+
}
|
|
163
|
+
if (!encoded) {
|
|
164
|
+
throw new TypeError(`Path param "${param.parameterName}" cannot be empty in call to procedure (${path.join('.')}).`);
|
|
165
|
+
}
|
|
166
|
+
// URL parsing (e.g. in fetch) resolves "." and ".." segments, which would send the request to a different endpoint
|
|
167
|
+
if (DOT_SEGMENT_REGEX.test(encoded)) {
|
|
168
|
+
throw new TypeError(`Path param "${param.parameterName}" cannot contain "." or ".." segments in call to procedure (${path.join('.')}).`);
|
|
169
|
+
}
|
|
170
|
+
if (encoded.startsWith('/')) {
|
|
171
|
+
encoded = `%2F${encoded.slice(1)}`;
|
|
172
|
+
}
|
|
173
|
+
return encoded;
|
|
174
|
+
}
|
|
175
|
+
/**
|
|
176
|
+
* Serializes a single path/query value, like header values, so body-level
|
|
177
|
+
* serialize defaults (e.g. `asFormData`) never apply to URLs.
|
|
178
|
+
*/
|
|
179
|
+
serializeURLValue(value) {
|
|
180
|
+
return value === undefined ? undefined : this.serializer.serializeJson(value).json;
|
|
181
|
+
}
|
|
182
|
+
serializeQueryString(data, queryStyles) {
|
|
183
|
+
if (!queryStyles || !isNonPrimitive(data)) {
|
|
184
|
+
return toURLSearchParams(this.serializer.serialize(data, { asFormData: true })).toString();
|
|
185
|
+
}
|
|
186
|
+
const remaining = { ...data };
|
|
187
|
+
let query = '';
|
|
188
|
+
Object.entries(queryStyles).forEach(([key, style]) => {
|
|
189
|
+
if (style === undefined) {
|
|
190
|
+
return;
|
|
191
|
+
}
|
|
192
|
+
const value = remaining[key];
|
|
193
|
+
delete remaining[key];
|
|
194
|
+
if (style === 'primitive') {
|
|
195
|
+
const serialized = this.serializeURLValue(value);
|
|
196
|
+
if (serialized !== undefined && serialized !== null) {
|
|
197
|
+
// oxlint-disable-next-line typescript/no-base-to-string
|
|
198
|
+
query += `&${encodeURLSearchParamComponent(key)}=${encodeURLSearchParamComponent(String(serialized))}`;
|
|
199
|
+
}
|
|
200
|
+
}
|
|
201
|
+
else if (style === 'array' && Array.isArray(value)) {
|
|
202
|
+
const encodedKey = encodeURLSearchParamComponent(key);
|
|
203
|
+
value.forEach((v) => {
|
|
204
|
+
const s = this.serializeURLValue(v);
|
|
205
|
+
if (s !== undefined && s !== null) {
|
|
206
|
+
// oxlint-disable-next-line typescript/no-base-to-string
|
|
207
|
+
query += `&${encodedKey}=${encodeURLSearchParamComponent(String(s))}`;
|
|
208
|
+
}
|
|
209
|
+
});
|
|
210
|
+
}
|
|
211
|
+
else if (style === 'json') {
|
|
212
|
+
const serialized = this.serializeURLValue(value);
|
|
213
|
+
if (serialized !== undefined) {
|
|
214
|
+
query += `&${encodeURLSearchParamComponent(key)}=${encodeURLSearchParamComponent(stringifyJSON(serialized))}`;
|
|
215
|
+
}
|
|
216
|
+
}
|
|
217
|
+
else if (style === 'comma-delimited-array' && Array.isArray(value)) {
|
|
218
|
+
const encodedValue = encodeDelimitedArray(value.map((v) => this.serializeURLValue(v)), ',');
|
|
219
|
+
if (encodedValue !== undefined) {
|
|
220
|
+
query += `&${encodeURLSearchParamComponent(key)}=${encodedValue}`;
|
|
221
|
+
}
|
|
222
|
+
}
|
|
223
|
+
else if (style === 'comma-delimited-object' && isNonPrimitive(value)) {
|
|
224
|
+
const encodedValue = encodeDelimitedObject(Object.entries(value).map(([key, value]) => [key, this.serializeURLValue(value)]), ',');
|
|
225
|
+
if (encodedValue !== undefined) {
|
|
226
|
+
query += `&${encodeURLSearchParamComponent(key)}=${encodedValue}`;
|
|
227
|
+
}
|
|
228
|
+
}
|
|
229
|
+
else if (style === 'pipe-delimited-array' && Array.isArray(value)) {
|
|
230
|
+
const encodedValue = encodeDelimitedArray(value.map((v) => this.serializeURLValue(v)), '%7C' /* '/' */);
|
|
231
|
+
if (encodedValue !== undefined) {
|
|
232
|
+
query += `&${encodeURLSearchParamComponent(key)}=${encodedValue}`;
|
|
233
|
+
}
|
|
234
|
+
}
|
|
235
|
+
else if (style === 'pipe-delimited-object' && isNonPrimitive(value)) {
|
|
236
|
+
const encodedValue = encodeDelimitedObject(Object.entries(value).map(([key, value]) => [key, this.serializeURLValue(value)]), '%7C' /* '/' */);
|
|
237
|
+
if (encodedValue !== undefined) {
|
|
238
|
+
query += `&${encodeURLSearchParamComponent(key)}=${encodedValue}`;
|
|
239
|
+
}
|
|
240
|
+
}
|
|
241
|
+
else if (style === 'space-delimited-array' && Array.isArray(value)) {
|
|
242
|
+
const encodedValue = encodeDelimitedArray(value.map((v) => this.serializeURLValue(v)), '%20' /* ' ' */);
|
|
243
|
+
if (encodedValue !== undefined) {
|
|
244
|
+
query += `&${encodeURLSearchParamComponent(key)}=${encodedValue}`;
|
|
245
|
+
}
|
|
246
|
+
}
|
|
247
|
+
else if (style === 'space-delimited-object' && isNonPrimitive(value)) {
|
|
248
|
+
const encodedValue = encodeDelimitedObject(Object.entries(value).map(([key, value]) => [key, this.serializeURLValue(value)]), '%20' /* ' ' */);
|
|
249
|
+
if (encodedValue !== undefined) {
|
|
250
|
+
query += `&${encodeURLSearchParamComponent(key)}=${encodedValue}`;
|
|
251
|
+
}
|
|
252
|
+
}
|
|
253
|
+
else {
|
|
254
|
+
const serialized = this.serializeURLValue(value);
|
|
255
|
+
if (serialized !== undefined && serialized !== null) {
|
|
256
|
+
// oxlint-disable-next-line typescript/no-base-to-string
|
|
257
|
+
query += `&${encodeURLSearchParamComponent(key)}=${encodeURLSearchParamComponent(String(serialized))}`;
|
|
258
|
+
}
|
|
259
|
+
}
|
|
260
|
+
});
|
|
261
|
+
const form = this.serializer.serialize(remaining, { asFormData: true });
|
|
262
|
+
query = `${toURLSearchParams(form).toString()}${query}`;
|
|
263
|
+
if (query.startsWith('&')) {
|
|
264
|
+
query = query.slice(1);
|
|
265
|
+
}
|
|
266
|
+
return query || undefined;
|
|
267
|
+
}
|
|
268
|
+
async decodeResponse(response, path, _options) {
|
|
269
|
+
const isOk = response.status < 400;
|
|
270
|
+
const procedure = await this.resolveProcedure(path);
|
|
271
|
+
const meta = getOpenAPIMeta(procedure);
|
|
272
|
+
const errorBodyHint = !isOk &&
|
|
273
|
+
this.errorResponseMediaType !== undefined &&
|
|
274
|
+
toMediaType(flattenStandardHeader(response.headers['content-type'])) ===
|
|
275
|
+
this.errorResponseMediaType
|
|
276
|
+
? 'json'
|
|
277
|
+
: undefined;
|
|
278
|
+
const body = await response.resolveBody(isOk ? meta?.responseBodyHint : errorBodyHint);
|
|
279
|
+
const deserialized = await (async () => {
|
|
280
|
+
try {
|
|
281
|
+
return this.serializer.deserialize(body);
|
|
282
|
+
}
|
|
283
|
+
catch (error) {
|
|
284
|
+
throw new MalformedResponseError({
|
|
285
|
+
message: 'Invalid OpenAPI response format.',
|
|
286
|
+
response: { status: response.status, headers: response.headers, body },
|
|
287
|
+
cause: error,
|
|
288
|
+
});
|
|
289
|
+
}
|
|
290
|
+
})();
|
|
291
|
+
if (!isOk) {
|
|
292
|
+
const defaultError = () => {
|
|
293
|
+
if (isORPCErrorJson(deserialized)) {
|
|
294
|
+
return createORPCErrorFromJson(deserialized, {
|
|
295
|
+
cause: new ResponseError({
|
|
296
|
+
response: { status: response.status, headers: response.headers, body },
|
|
297
|
+
}),
|
|
298
|
+
});
|
|
299
|
+
}
|
|
300
|
+
return new MalformedResponseError({
|
|
301
|
+
response: { headers: response.headers, status: response.status, body },
|
|
302
|
+
});
|
|
303
|
+
};
|
|
304
|
+
return {
|
|
305
|
+
kind: 'error',
|
|
306
|
+
error: this.errorResponseBodyDecoder(deserialized, response, defaultError),
|
|
307
|
+
};
|
|
308
|
+
}
|
|
309
|
+
const outputStructure = meta?.outputStructure ?? DEFAULT_OPENAPI_OUTPUT_STRUCTURE;
|
|
310
|
+
return outputStructure === 'compact'
|
|
311
|
+
? { kind: 'output', output: deserialized }
|
|
312
|
+
: {
|
|
313
|
+
kind: 'output',
|
|
314
|
+
output: {
|
|
315
|
+
status: response.status,
|
|
316
|
+
headers: response.headers,
|
|
317
|
+
body: deserialized,
|
|
318
|
+
},
|
|
319
|
+
};
|
|
320
|
+
}
|
|
321
|
+
async resolveProcedure(path) {
|
|
322
|
+
const { default: maybeProcedure } = await unlazy(getRouterContract(this.router, path));
|
|
323
|
+
if (!(maybeProcedure instanceof ProcedureContract)) {
|
|
324
|
+
throw new TypeError(`Expected a procedure or contract at path (${path.join('.')})`);
|
|
325
|
+
}
|
|
326
|
+
return maybeProcedure;
|
|
327
|
+
}
|
|
328
|
+
}
|
|
329
|
+
function combineSearch(baseSearch, additionalSearch) {
|
|
330
|
+
if (!baseSearch && !additionalSearch) {
|
|
331
|
+
return undefined;
|
|
332
|
+
}
|
|
333
|
+
if (!additionalSearch) {
|
|
334
|
+
return baseSearch;
|
|
335
|
+
}
|
|
336
|
+
if (!baseSearch) {
|
|
337
|
+
return `?${additionalSearch}`;
|
|
338
|
+
}
|
|
339
|
+
return `${baseSearch}&${additionalSearch}`;
|
|
340
|
+
}
|
|
341
|
+
/**
|
|
342
|
+
* Strips parameters and normalizes case, e.g. `Application/Problem+JSON; charset=utf-8` -> `application/problem+json`.
|
|
343
|
+
*/
|
|
344
|
+
function toMediaType(contentType) {
|
|
345
|
+
return contentType?.split(';')[0]?.trim().toLowerCase();
|
|
346
|
+
}
|
|
347
|
+
function toResolvedStandardHeaders(headers) {
|
|
348
|
+
/**
|
|
349
|
+
* Headers class might not be available in some environments,
|
|
350
|
+
* so we check for the existence of `forEach` and `get`
|
|
351
|
+
* methods to determine if it's a Headers instance.
|
|
352
|
+
*/
|
|
353
|
+
if (typeof headers.forEach === 'function') {
|
|
354
|
+
return toStandardHeaders(headers);
|
|
355
|
+
}
|
|
356
|
+
return headers;
|
|
357
|
+
}
|
|
358
|
+
function isValidDetailedInput(input) {
|
|
359
|
+
if (!isNonPrimitive(input)) {
|
|
360
|
+
return input === undefined;
|
|
361
|
+
}
|
|
362
|
+
if (input.params !== undefined && !isNonPrimitive(input.params)) {
|
|
363
|
+
return false;
|
|
364
|
+
}
|
|
365
|
+
if (input.query !== undefined && !isNonPrimitive(input.query)) {
|
|
366
|
+
return false;
|
|
367
|
+
}
|
|
368
|
+
if (input.headers !== undefined && !isNonPrimitive(input.headers)) {
|
|
369
|
+
return false;
|
|
370
|
+
}
|
|
371
|
+
return true;
|
|
372
|
+
}
|
|
373
|
+
/**
|
|
374
|
+
* Encode a query parameter value using URLSearchParams semantics.
|
|
375
|
+
* Prefer this over safeEncodeURIComponent for query-string values.
|
|
376
|
+
*/
|
|
377
|
+
function encodeURLSearchParamComponent(value) {
|
|
378
|
+
return new URLSearchParams({ '': value }).toString().slice(1);
|
|
379
|
+
}
|
|
380
|
+
function toURLSearchParams(form) {
|
|
381
|
+
const params = new URLSearchParams();
|
|
382
|
+
for (const [key, value] of form) {
|
|
383
|
+
// oxlint-disable-next-line typescript/no-base-to-string
|
|
384
|
+
params.append(key, String(value));
|
|
385
|
+
}
|
|
386
|
+
return params;
|
|
387
|
+
}
|
|
388
|
+
function encodeDelimitedArray(serializedValues, encodedDelimiter) {
|
|
389
|
+
const strings = serializedValues.filter((v) => v !== null && v !== undefined).map(String);
|
|
390
|
+
if (!strings.length) {
|
|
391
|
+
return undefined;
|
|
392
|
+
}
|
|
393
|
+
return strings.map(encodeURLSearchParamComponent).join(encodedDelimiter);
|
|
394
|
+
}
|
|
395
|
+
function encodeDelimitedObject(entries, encodedDelimiter) {
|
|
396
|
+
const strings = entries
|
|
397
|
+
.filter(([, v]) => v !== null && v !== undefined)
|
|
398
|
+
.map(([k, v]) => [k, String(v)]);
|
|
399
|
+
if (!strings.length) {
|
|
400
|
+
return undefined;
|
|
401
|
+
}
|
|
402
|
+
return strings
|
|
403
|
+
.map(([key, value]) => `${encodeURLSearchParamComponent(key)}${encodedDelimiter}${encodeURLSearchParamComponent(value)}`)
|
|
404
|
+
.join(encodedDelimiter);
|
|
405
|
+
}
|
|
@@ -0,0 +1,29 @@
|
|
|
1
|
+
import type { AnyProcedureContract } from '@orpc/contract';
|
|
2
|
+
import type { AnyProcedure, AnyRouter } from '@orpc/server';
|
|
3
|
+
import type { Value } from '@orpc/shared';
|
|
4
|
+
export interface OpenAPIMatcherOptions {
|
|
5
|
+
/**
|
|
6
|
+
* Filter which procedures are exposed for matching. Return `false` to exclude.
|
|
7
|
+
*
|
|
8
|
+
* @default true
|
|
9
|
+
*/
|
|
10
|
+
filter?: Value<boolean, [contract: AnyProcedureContract | AnyProcedure, path: string[]]> | undefined;
|
|
11
|
+
}
|
|
12
|
+
export declare class OpenAPIMatcher {
|
|
13
|
+
private readonly filter;
|
|
14
|
+
private readonly rootRouter;
|
|
15
|
+
private readonly tree;
|
|
16
|
+
private readonly pendingLazyRouters;
|
|
17
|
+
constructor(router: AnyRouter, options?: OpenAPIMatcherOptions);
|
|
18
|
+
private index;
|
|
19
|
+
match(method: string, pathname: `/${string}`, prefix: `/${string}` | undefined): Promise<{
|
|
20
|
+
path: string[];
|
|
21
|
+
procedure: AnyProcedure;
|
|
22
|
+
params?: Record<string, string> | undefined;
|
|
23
|
+
} | undefined>;
|
|
24
|
+
private resolvePendingLazyRouters;
|
|
25
|
+
private loadPendingLazyRouters;
|
|
26
|
+
private loadPendingLazyRouter;
|
|
27
|
+
private indexPendingLazyRouter;
|
|
28
|
+
private resolveProcedure;
|
|
29
|
+
}
|
|
@@ -0,0 +1,108 @@
|
|
|
1
|
+
import { createPrefixMatcher, Router } from '@openapi-spec/router';
|
|
2
|
+
import { Procedure, resolveContractProcedure, unlazy, walkProcedureContractsSync, } from '@orpc/server';
|
|
3
|
+
import { mergeHttpPath, pathToHttpPath, value } from '@orpc/shared';
|
|
4
|
+
import { DEFAULT_OPENAPI_METHOD } from '../../constants.js';
|
|
5
|
+
import { getOpenAPIMeta } from '../../meta.js';
|
|
6
|
+
export class OpenAPIMatcher {
|
|
7
|
+
filter;
|
|
8
|
+
rootRouter;
|
|
9
|
+
tree = new Router();
|
|
10
|
+
pendingLazyRouters = new Set();
|
|
11
|
+
constructor(router, options = {}) {
|
|
12
|
+
this.filter = options.filter ?? true;
|
|
13
|
+
this.rootRouter = router;
|
|
14
|
+
this.index(router);
|
|
15
|
+
}
|
|
16
|
+
index(router, path = []) {
|
|
17
|
+
const lazyResults = walkProcedureContractsSync(router, (contract, path) => {
|
|
18
|
+
if (!value(this.filter, contract, path)) {
|
|
19
|
+
return;
|
|
20
|
+
}
|
|
21
|
+
const meta = getOpenAPIMeta(contract);
|
|
22
|
+
const method = meta?.method ?? DEFAULT_OPENAPI_METHOD;
|
|
23
|
+
const postHttpPath = meta?.path ?? pathToHttpPath(path);
|
|
24
|
+
const httpPath = meta?.prefix ? mergeHttpPath(meta.prefix, postHttpPath) : postHttpPath;
|
|
25
|
+
this.tree.add(method, httpPath, {
|
|
26
|
+
path,
|
|
27
|
+
contract,
|
|
28
|
+
procedure: contract instanceof Procedure ? contract : undefined,
|
|
29
|
+
});
|
|
30
|
+
}, path);
|
|
31
|
+
for (const result of lazyResults) {
|
|
32
|
+
const prefix = getOpenAPIMeta(result.router)?.prefix;
|
|
33
|
+
this.pendingLazyRouters.add({
|
|
34
|
+
...result,
|
|
35
|
+
matcher: prefix ? createPrefixMatcher(prefix) : undefined,
|
|
36
|
+
});
|
|
37
|
+
}
|
|
38
|
+
}
|
|
39
|
+
async match(method, pathname, prefix) {
|
|
40
|
+
if (prefix) {
|
|
41
|
+
if (!pathname.startsWith(prefix)) {
|
|
42
|
+
return undefined;
|
|
43
|
+
}
|
|
44
|
+
const charAfterPrefix = pathname[prefix.length];
|
|
45
|
+
if (charAfterPrefix === '/') {
|
|
46
|
+
pathname = pathname.slice(prefix.length);
|
|
47
|
+
}
|
|
48
|
+
else if (charAfterPrefix === undefined) {
|
|
49
|
+
pathname = '/';
|
|
50
|
+
}
|
|
51
|
+
else if (prefix[prefix.length - 1] === '/') {
|
|
52
|
+
pathname = pathname.slice(prefix.length - 1);
|
|
53
|
+
}
|
|
54
|
+
else {
|
|
55
|
+
return undefined;
|
|
56
|
+
}
|
|
57
|
+
}
|
|
58
|
+
// most requests `await undefined` so conditionally await it to save a microtask turn
|
|
59
|
+
const loading = this.resolvePendingLazyRouters(pathname);
|
|
60
|
+
if (loading !== undefined) {
|
|
61
|
+
await loading;
|
|
62
|
+
}
|
|
63
|
+
const match = this.tree.match(method, pathname);
|
|
64
|
+
if (match === undefined) {
|
|
65
|
+
return undefined;
|
|
66
|
+
}
|
|
67
|
+
const entry = match.data;
|
|
68
|
+
return {
|
|
69
|
+
path: entry.path,
|
|
70
|
+
procedure: entry.procedure ?? (await this.resolveProcedure(entry)),
|
|
71
|
+
params: match.params,
|
|
72
|
+
};
|
|
73
|
+
}
|
|
74
|
+
resolvePendingLazyRouters(pathname) {
|
|
75
|
+
for (const pending of this.pendingLazyRouters) {
|
|
76
|
+
if (pending.matcher === undefined || pending.matcher(pathname)) {
|
|
77
|
+
return this.loadPendingLazyRouters(pathname);
|
|
78
|
+
}
|
|
79
|
+
}
|
|
80
|
+
}
|
|
81
|
+
async loadPendingLazyRouters(pathname) {
|
|
82
|
+
for (const pending of this.pendingLazyRouters) {
|
|
83
|
+
if (pending.matcher === undefined || pending.matcher(pathname)) {
|
|
84
|
+
await this.loadPendingLazyRouter(pending);
|
|
85
|
+
}
|
|
86
|
+
}
|
|
87
|
+
}
|
|
88
|
+
loadPendingLazyRouter(pending) {
|
|
89
|
+
if (pending.loading === undefined) {
|
|
90
|
+
pending.loading = this.indexPendingLazyRouter(pending).catch((error) => {
|
|
91
|
+
pending.loading = undefined;
|
|
92
|
+
throw error;
|
|
93
|
+
});
|
|
94
|
+
}
|
|
95
|
+
return pending.loading;
|
|
96
|
+
}
|
|
97
|
+
async indexPendingLazyRouter(pending) {
|
|
98
|
+
const { default: router } = await unlazy(pending.router);
|
|
99
|
+
this.index(router, pending.path);
|
|
100
|
+
// removed only once indexed, so a concurrent match never observes this router as
|
|
101
|
+
// neither pending nor indexed
|
|
102
|
+
this.pendingLazyRouters.delete(pending);
|
|
103
|
+
}
|
|
104
|
+
async resolveProcedure(entry) {
|
|
105
|
+
entry.procedure = await resolveContractProcedure(this.rootRouter, entry.contract, entry.path);
|
|
106
|
+
return entry.procedure;
|
|
107
|
+
}
|
|
108
|
+
}
|
|
@@ -0,0 +1,4 @@
|
|
|
1
|
+
import type { Public } from '@orpc/shared';
|
|
2
|
+
import type { StandardHeaders } from '@standard-server/core';
|
|
3
|
+
import type { OpenAPIJsonSerializer } from '../../openapi-json-serializer.ts';
|
|
4
|
+
export declare function serializeHeaders(headers: object, serializer: Public<OpenAPIJsonSerializer>): StandardHeaders;
|
|
@@ -0,0 +1,47 @@
|
|
|
1
|
+
import { isNonPrimitive, NullProtoObj } from '@orpc/shared';
|
|
2
|
+
export function serializeHeaders(headers, serializer) {
|
|
3
|
+
const result = new NullProtoObj();
|
|
4
|
+
for (const [key, value] of Object.entries(headers)) {
|
|
5
|
+
/**
|
|
6
|
+
* Only an actual array value represents a multi-value header (sent as multiple lines).
|
|
7
|
+
* Serialization can turn non-array values into arrays (e.g. Set, Map, custom handlers),
|
|
8
|
+
* and those must stay a single line, so the structure is checked before serializing.
|
|
9
|
+
*/
|
|
10
|
+
if (Array.isArray(value)) {
|
|
11
|
+
const lines = [];
|
|
12
|
+
for (const item of value) {
|
|
13
|
+
const line = serializeHeaderValue(item, serializer);
|
|
14
|
+
if (line !== undefined) {
|
|
15
|
+
lines.push(line);
|
|
16
|
+
}
|
|
17
|
+
}
|
|
18
|
+
result[key] = lines;
|
|
19
|
+
continue;
|
|
20
|
+
}
|
|
21
|
+
const line = serializeHeaderValue(value, serializer);
|
|
22
|
+
if (line !== undefined) {
|
|
23
|
+
result[key] = line;
|
|
24
|
+
}
|
|
25
|
+
}
|
|
26
|
+
return result;
|
|
27
|
+
}
|
|
28
|
+
function serializeHeaderValue(value, serializer) {
|
|
29
|
+
const serialized = serializer.serializeJson(value).json;
|
|
30
|
+
if (Array.isArray(serialized)) {
|
|
31
|
+
return serialized
|
|
32
|
+
.filter((item) => item !== undefined && item !== null)
|
|
33
|
+
.map(String)
|
|
34
|
+
.join(',');
|
|
35
|
+
}
|
|
36
|
+
if (isNonPrimitive(serialized)) {
|
|
37
|
+
return Object.entries(serialized)
|
|
38
|
+
.filter(([, val]) => val !== undefined && val !== null)
|
|
39
|
+
.map(([key, val]) => `${key},${String(val)}`)
|
|
40
|
+
.join(',');
|
|
41
|
+
}
|
|
42
|
+
if (serialized !== undefined && serialized !== null) {
|
|
43
|
+
// oxlint-disable-next-line typescript/no-base-to-string
|
|
44
|
+
return String(serialized);
|
|
45
|
+
}
|
|
46
|
+
return undefined;
|
|
47
|
+
}
|
|
@@ -0,0 +1,26 @@
|
|
|
1
|
+
import type { Segment } from '@orpc/shared';
|
|
2
|
+
export type BracketNotationSerializeResult = [string, unknown][];
|
|
3
|
+
export interface BracketNotationSerializerOptions {
|
|
4
|
+
/**
|
|
5
|
+
* Maximum number of empty slots that explicit array indexes may leave in total during deserialization
|
|
6
|
+
* (e.g., `a[0]=x&a[3]=y` leaves 2). An index that would exceed it turns its array into an object
|
|
7
|
+
* instead (e.g., `?arr[5000]=x` becomes `{ arr: { 5000: 'x' } }`).
|
|
8
|
+
*
|
|
9
|
+
* Empty slots take memory (a lone `?arr[999]=x` takes ~12KB in V8), and code iterating an array walks
|
|
10
|
+
* every one of them, so this keeps both in line with the input.
|
|
11
|
+
*
|
|
12
|
+
* NOTE: Append-style notation (e.g., `arr[]`) never leaves empty slots.
|
|
13
|
+
*
|
|
14
|
+
* @default 1_000
|
|
15
|
+
*/
|
|
16
|
+
maxDeserializingEmptySlots?: number | undefined;
|
|
17
|
+
}
|
|
18
|
+
export declare class BracketNotationSerializer {
|
|
19
|
+
private readonly maxDeserializingEmptySlots;
|
|
20
|
+
constructor(options?: BracketNotationSerializerOptions);
|
|
21
|
+
serialize(data: unknown): BracketNotationSerializeResult;
|
|
22
|
+
private internalSerialize;
|
|
23
|
+
deserialize(serialized: BracketNotationSerializeResult): Record<string, unknown>;
|
|
24
|
+
stringifyPath(segments: readonly Segment[]): string;
|
|
25
|
+
parsePath(path: string): string[];
|
|
26
|
+
}
|