@orpc/openapi 2.0.0-beta.47 → 2.0.0-beta.48
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 +2 -3
- package/dist/adapters/aws-lambda/index.d.mts +14 -26
- package/dist/adapters/aws-lambda/index.mjs +1 -21
- package/dist/adapters/aws-lambda/openapi-handler.d.mts +17 -0
- package/dist/adapters/aws-lambda/openapi-handler.mjs +11 -0
- package/dist/adapters/fastify/index.d.mts +1 -23
- package/dist/adapters/fastify/index.mjs +1 -21
- package/dist/adapters/fastify/openapi-handler.d.mts +14 -0
- package/dist/adapters/fastify/openapi-handler.mjs +11 -0
- package/dist/adapters/fetch/index.d.mts +2 -37
- package/dist/adapters/fetch/index.mjs +2 -34
- package/dist/adapters/fetch/openapi-handler.d.mts +14 -0
- package/dist/adapters/fetch/openapi-handler.mjs +11 -0
- package/dist/adapters/fetch/openapi-link.d.mts +15 -0
- package/dist/adapters/fetch/openapi-link.mjs +11 -0
- package/dist/adapters/node/index.d.mts +1 -23
- package/dist/adapters/node/index.mjs +1 -21
- package/dist/adapters/node/openapi-handler.d.mts +14 -0
- package/dist/adapters/node/openapi-handler.mjs +11 -0
- package/dist/adapters/standard/index.d.mts +3 -56
- package/dist/adapters/standard/index.mjs +3 -12
- package/dist/adapters/standard/openapi-handler-codec.d.mts +61 -0
- package/dist/adapters/standard/openapi-handler-codec.mjs +203 -0
- package/dist/adapters/standard/openapi-link-codec.d.mts +53 -0
- package/dist/adapters/standard/openapi-link-codec.mjs +356 -0
- package/dist/adapters/standard/openapi-matcher.d.mts +29 -0
- package/dist/adapters/standard/openapi-matcher.mjs +105 -0
- package/dist/adapters/standard/utils.d.mts +4 -0
- package/dist/adapters/standard/utils.mjs +36 -0
- package/dist/bracket-notation.d.mts +26 -0
- package/dist/bracket-notation.mjs +156 -0
- package/dist/client-factory.d.mts +24 -0
- package/dist/client-factory.mjs +5 -0
- package/dist/constants.d.mts +4 -0
- package/dist/constants.mjs +4 -0
- package/dist/extensions/route.d.mts +74 -39
- package/dist/extensions/route.mjs +8 -10
- package/dist/helpers/form-data.d.mts +57 -0
- package/dist/helpers/form-data.mjs +36 -0
- package/dist/helpers/index.d.mts +1 -59
- package/dist/helpers/index.mjs +1 -39
- package/dist/index.d.mts +13 -166
- package/dist/index.mjs +11 -780
- package/dist/meta.d.mts +345 -0
- package/dist/meta.mjs +56 -0
- package/dist/openapi-generator-components.d.mts +24 -0
- package/dist/openapi-generator-components.mjs +227 -0
- package/dist/openapi-generator-operation.d.mts +29 -0
- package/dist/openapi-generator-operation.mjs +447 -0
- package/dist/openapi-generator.d.mts +87 -0
- package/dist/openapi-generator.mjs +115 -0
- package/dist/openapi-json-serializer.d.mts +86 -0
- package/dist/openapi-json-serializer.mjs +229 -0
- package/dist/openapi-serializer.d.mts +43 -0
- package/dist/openapi-serializer.mjs +87 -0
- package/dist/plugins/index.d.mts +1 -121
- package/dist/plugins/index.mjs +1 -167
- package/dist/plugins/openapi-reference.d.mts +118 -0
- package/dist/plugins/openapi-reference.mjs +157 -0
- package/dist/router-utils.d.mts +18 -0
- package/dist/router-utils.mjs +29 -0
- package/dist/types.d.mts +27 -0
- package/dist/types.mjs +1 -0
- package/dist/utils.d.mts +14 -0
- package/dist/utils.mjs +40 -0
- package/package.json +15 -15
- package/dist/adapters/aws-lambda/index.d.ts +0 -27
- package/dist/adapters/fastify/index.d.ts +0 -23
- package/dist/adapters/fetch/index.d.ts +0 -37
- package/dist/adapters/node/index.d.ts +0 -23
- package/dist/adapters/standard/index.d.ts +0 -56
- package/dist/extensions/route.d.ts +0 -41
- package/dist/helpers/index.d.ts +0 -59
- package/dist/index.d.ts +0 -166
- package/dist/plugins/index.d.ts +0 -121
- package/dist/shared/openapi.B9PQzqBn.mjs +0 -49
- package/dist/shared/openapi.CQkXu1nY.mjs +0 -366
- package/dist/shared/openapi.Covi8zVE.d.mts +0 -33
- package/dist/shared/openapi.Covi8zVE.d.ts +0 -33
- package/dist/shared/openapi.DfmCR1pB.d.mts +0 -94
- package/dist/shared/openapi.DtEVcxuW.mjs +0 -149
- package/dist/shared/openapi.E3ZBiweM.mjs +0 -353
- package/dist/shared/openapi.Y4K_-I5W.d.ts +0 -94
- package/dist/shared/openapi.YMRD3b4R.d.mts +0 -157
- package/dist/shared/openapi.YMRD3b4R.d.ts +0 -157
- package/dist/shared/openapi.g7ucL05o.mjs +0 -410
- package/dist/shared/openapi.zGZlCOwp.d.mts +0 -329
- package/dist/shared/openapi.zGZlCOwp.d.ts +0 -329
|
@@ -0,0 +1,203 @@
|
|
|
1
|
+
import { COMMON_ERROR_STATUS_MAP } from "@orpc/client";
|
|
2
|
+
import { DEFAULT_ERROR_STATUS, DEFAULT_SUCCESS_STATUS } from "@orpc/server";
|
|
3
|
+
import { getOwn, isPlainObject, isTypescriptObject, NullProtoObj, parseEmptyableJSON, stringifyJSON } from "@orpc/shared";
|
|
4
|
+
import { parseStandardUrl } from "@standard-server/core";
|
|
5
|
+
import { DEFAULT_OPENAPI_INPUT_STRUCTURE, DEFAULT_OPENAPI_OUTPUT_STRUCTURE } from "../../constants.mjs";
|
|
6
|
+
import { getOpenAPIMeta } from "../../meta.mjs";
|
|
7
|
+
import { OpenAPISerializer } from "../../openapi-serializer.mjs";
|
|
8
|
+
import { isBodylessMethod } from "../../utils.mjs";
|
|
9
|
+
import { OpenAPIMatcher } from "./openapi-matcher.mjs";
|
|
10
|
+
import { serializeHeaders } from "./utils.mjs";
|
|
11
|
+
export class OpenAPIHandlerCodecCore {
|
|
12
|
+
serializer;
|
|
13
|
+
errorStatusMap;
|
|
14
|
+
errorResponseBodyEncoder;
|
|
15
|
+
errorResponseContentType;
|
|
16
|
+
constructor(options = {}) {
|
|
17
|
+
this.serializer = options.serializer ?? new OpenAPISerializer();
|
|
18
|
+
this.errorStatusMap = options.errorStatusMap ?? COMMON_ERROR_STATUS_MAP;
|
|
19
|
+
this.errorResponseBodyEncoder = options.errorResponseBodyEncoder ?? ((e) => e.toJSON());
|
|
20
|
+
this.errorResponseContentType = options.errorResponseContentType;
|
|
21
|
+
}
|
|
22
|
+
async decodeInput(matched, request) {
|
|
23
|
+
const meta = getOpenAPIMeta(matched.procedure);
|
|
24
|
+
const inputStructure = meta?.inputStructure ?? DEFAULT_OPENAPI_INPUT_STRUCTURE;
|
|
25
|
+
const params = this.deserializeParams(matched.params, meta?.paramsStyles);
|
|
26
|
+
if (inputStructure === "compact") {
|
|
27
|
+
const data = isBodylessMethod(request.method) ? this.deserializeQuery(request.url, meta?.queryStyles) : this.serializer.deserialize(await request.resolveBody(meta?.requestBodyHint));
|
|
28
|
+
if (data === undefined) {
|
|
29
|
+
return params;
|
|
30
|
+
}
|
|
31
|
+
if (!params || Object.keys(params).length < 1) {
|
|
32
|
+
return data;
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
|
|
36
|
+
if (!isPlainObject(data)) {
|
|
37
|
+
return params;
|
|
38
|
+
}
|
|
39
|
+
return {
|
|
40
|
+
...data,
|
|
41
|
+
...params
|
|
42
|
+
};
|
|
43
|
+
}
|
|
44
|
+
return {
|
|
45
|
+
params,
|
|
46
|
+
query: this.deserializeQuery(request.url, meta?.queryStyles),
|
|
47
|
+
headers: request.headers,
|
|
48
|
+
body: this.serializer.deserialize(await request.resolveBody(meta?.requestBodyHint))
|
|
49
|
+
};
|
|
50
|
+
}
|
|
51
|
+
|
|
52
|
+
encodeOutput(output, procedure, path) {
|
|
53
|
+
const meta = getOpenAPIMeta(procedure);
|
|
54
|
+
const successStatus = meta?.successStatus ?? DEFAULT_SUCCESS_STATUS;
|
|
55
|
+
const outputStructure = meta?.outputStructure ?? DEFAULT_OPENAPI_OUTPUT_STRUCTURE;
|
|
56
|
+
if (outputStructure === "compact") {
|
|
57
|
+
return {
|
|
58
|
+
status: successStatus,
|
|
59
|
+
headers: {},
|
|
60
|
+
body: this.serializer.serialize(output)
|
|
61
|
+
};
|
|
62
|
+
}
|
|
63
|
+
if (!isValidDetailedOutput(output)) {
|
|
64
|
+
throw new TypeError(`
|
|
65
|
+
Invalid "detailed" output structure returned by procedure (${path.join(".")}):
|
|
66
|
+
• Expected an object with optional properties:
|
|
67
|
+
- status (number <400)
|
|
68
|
+
- headers (object)
|
|
69
|
+
- body (any)
|
|
70
|
+
• No extra keys allowed.
|
|
71
|
+
|
|
72
|
+
Actual value:
|
|
73
|
+
${stringifyJSON(output)}
|
|
74
|
+
`);
|
|
75
|
+
}
|
|
76
|
+
return {
|
|
77
|
+
status: output.status ?? successStatus,
|
|
78
|
+
headers: output.headers !== undefined ? serializeHeaders(output.headers, this.serializer) : {},
|
|
79
|
+
body: this.serializer.serialize(output.body)
|
|
80
|
+
};
|
|
81
|
+
}
|
|
82
|
+
encodeError(error) {
|
|
83
|
+
const status = getOwn(this.errorStatusMap, error.code) ?? DEFAULT_ERROR_STATUS;
|
|
84
|
+
return {
|
|
85
|
+
status,
|
|
86
|
+
headers: this.errorResponseContentType !== undefined ? { "content-type": this.errorResponseContentType } : {},
|
|
87
|
+
body: this.serializer.serialize(this.errorResponseBodyEncoder(error))
|
|
88
|
+
};
|
|
89
|
+
}
|
|
90
|
+
deserializeQuery(url, styles) {
|
|
91
|
+
const [, search] = parseStandardUrl(url);
|
|
92
|
+
const searchParams = new URLSearchParams(search);
|
|
93
|
+
const parsed = this.serializer.deserialize(searchParams);
|
|
94
|
+
if (!styles || !isPlainObject(parsed)) {
|
|
95
|
+
return parsed;
|
|
96
|
+
}
|
|
97
|
+
Object.entries(styles).forEach(([key, hint]) => {
|
|
98
|
+
if (hint === undefined) {
|
|
99
|
+
return;
|
|
100
|
+
}
|
|
101
|
+
const values = searchParams.getAll(key);
|
|
102
|
+
let parsedValue;
|
|
103
|
+
if (hint === "primitive") {
|
|
104
|
+
parsedValue = values.at(-1);
|
|
105
|
+
} else if (hint === "array") {
|
|
106
|
+
parsedValue = values;
|
|
107
|
+
} else if (hint === "comma-delimited-array") {
|
|
108
|
+
parsedValue = decodeDelimitedArray(values.at(-1), ",");
|
|
109
|
+
} else if (hint === "comma-delimited-object") {
|
|
110
|
+
parsedValue = decodeDelimitedObject(values.at(-1), ",");
|
|
111
|
+
} else if (hint === "space-delimited-array") {
|
|
112
|
+
parsedValue = decodeDelimitedArray(values.at(-1), " ");
|
|
113
|
+
} else if (hint === "space-delimited-object") {
|
|
114
|
+
parsedValue = decodeDelimitedObject(values.at(-1), " ");
|
|
115
|
+
} else if (hint === "pipe-delimited-array") {
|
|
116
|
+
parsedValue = decodeDelimitedArray(values.at(-1), "|");
|
|
117
|
+
} else if (hint === "pipe-delimited-object") {
|
|
118
|
+
parsedValue = decodeDelimitedObject(values.at(-1), "|");
|
|
119
|
+
} else {
|
|
120
|
+
const _expect = hint;
|
|
121
|
+
const last = values.at(-1);
|
|
122
|
+
try {
|
|
123
|
+
parsedValue = parseEmptyableJSON(last);
|
|
124
|
+
} catch {
|
|
125
|
+
parsedValue = last;
|
|
126
|
+
}
|
|
127
|
+
}
|
|
128
|
+
parsed[key] = this.serializer.deserialize(parsedValue);
|
|
129
|
+
});
|
|
130
|
+
return parsed;
|
|
131
|
+
}
|
|
132
|
+
deserializeParams(params, styles) {
|
|
133
|
+
if (!params || !styles) {
|
|
134
|
+
return params;
|
|
135
|
+
}
|
|
136
|
+
const parsed = { ...params };
|
|
137
|
+
Object.entries(styles).forEach(([key, hint]) => {
|
|
138
|
+
const value = getOwn(params, key);
|
|
139
|
+
if (hint === undefined || hint === "primitive" || value === undefined) {
|
|
140
|
+
return;
|
|
141
|
+
}
|
|
142
|
+
if (hint === "comma-delimited-array") {
|
|
143
|
+
parsed[key] = decodeDelimitedArray(value, ",");
|
|
144
|
+
} else {
|
|
145
|
+
const _expect = hint;
|
|
146
|
+
parsed[key] = decodeDelimitedObject(value, ",");
|
|
147
|
+
}
|
|
148
|
+
});
|
|
149
|
+
return parsed;
|
|
150
|
+
}
|
|
151
|
+
}
|
|
152
|
+
export class OpenAPIHandlerCodec extends OpenAPIHandlerCodecCore {
|
|
153
|
+
matcher;
|
|
154
|
+
constructor(router, options = {}) {
|
|
155
|
+
super(options);
|
|
156
|
+
this.matcher = new OpenAPIMatcher(router, options);
|
|
157
|
+
}
|
|
158
|
+
async resolveProcedure(request, options) {
|
|
159
|
+
const [pathname] = parseStandardUrl(request.url);
|
|
160
|
+
const matched = await this.matcher.match(request.method, pathname, options.prefix);
|
|
161
|
+
if (!matched) {
|
|
162
|
+
return undefined;
|
|
163
|
+
}
|
|
164
|
+
return {
|
|
165
|
+
procedure: matched.procedure,
|
|
166
|
+
path: matched.path,
|
|
167
|
+
decodeInput: () => this.decodeInput(matched, request)
|
|
168
|
+
};
|
|
169
|
+
}
|
|
170
|
+
}
|
|
171
|
+
function isValidDetailedOutput(output) {
|
|
172
|
+
if (!isTypescriptObject(output)) {
|
|
173
|
+
return false;
|
|
174
|
+
}
|
|
175
|
+
if (Object.keys(output).some((key) => key !== "status" && key !== "headers" && key !== "body")) {
|
|
176
|
+
return false;
|
|
177
|
+
}
|
|
178
|
+
if (output.status !== undefined && (typeof output.status !== "number" || !Number.isInteger(output.status) || output.status > 399)) {
|
|
179
|
+
return false;
|
|
180
|
+
}
|
|
181
|
+
if (output.headers !== undefined && !isTypescriptObject(output.headers)) {
|
|
182
|
+
return false;
|
|
183
|
+
}
|
|
184
|
+
return true;
|
|
185
|
+
}
|
|
186
|
+
function decodeDelimitedArray(value, delimiter) {
|
|
187
|
+
if (value === undefined) {
|
|
188
|
+
return undefined;
|
|
189
|
+
}
|
|
190
|
+
return value.split(delimiter);
|
|
191
|
+
}
|
|
192
|
+
function decodeDelimitedObject(value, delimiter) {
|
|
193
|
+
if (value === undefined) {
|
|
194
|
+
return undefined;
|
|
195
|
+
}
|
|
196
|
+
const obj = new NullProtoObj();
|
|
197
|
+
const parts = value.split(delimiter);
|
|
198
|
+
for (let i = 0; i < parts.length; i += 2) {
|
|
199
|
+
const key = parts[i];
|
|
200
|
+
obj[key] = parts[i + 1];
|
|
201
|
+
}
|
|
202
|
+
return obj;
|
|
203
|
+
}
|
|
@@ -0,0 +1,53 @@
|
|
|
1
|
+
import type { ClientContext, ClientOptions } from "@orpc/client";
|
|
2
|
+
import type { StandardLinkCodec, StandardLinkCodecDecodedResponse } from "@orpc/client/standard";
|
|
3
|
+
import type { RouterContract } from "@orpc/contract";
|
|
4
|
+
import type { Promisable, Public, Value } from "@orpc/shared";
|
|
5
|
+
import type { StandardHeaders, StandardLazyResponse, StandardRequest, StandardUrl } from "@standard-server/core";
|
|
6
|
+
import { OpenAPISerializer } from "../../openapi-serializer.mjs";
|
|
7
|
+
export interface OpenAPILinkCodecOptions<T extends ClientContext> {
|
|
8
|
+
/**
|
|
9
|
+
* Base URL for all requests, without origin. Should match the OpenAPI handler mount path.
|
|
10
|
+
*
|
|
11
|
+
* @example '/api'
|
|
12
|
+
* @default '/'
|
|
13
|
+
*/
|
|
14
|
+
url?: Value<Promisable<StandardUrl>, [options: ClientOptions<T>, path: string[], input: unknown]> | undefined;
|
|
15
|
+
/**
|
|
16
|
+
* Inject headers into the request.
|
|
17
|
+
*/
|
|
18
|
+
headers?: Value<Promisable<StandardHeaders | Headers>, [options: ClientOptions<T>, path: string[], input: unknown]> | undefined;
|
|
19
|
+
/**
|
|
20
|
+
* Override the default OpenAPI serializer.
|
|
21
|
+
*/
|
|
22
|
+
serializer?: Public<OpenAPISerializer> | undefined;
|
|
23
|
+
/**
|
|
24
|
+
* Customize how an error response body is converted into the error thrown by the client.
|
|
25
|
+
*
|
|
26
|
+
* @remarks
|
|
27
|
+
* - Return `defaultError()` to keep the default decoding (a `MalformedResponseError` for bodies that are not ORPC errors)
|
|
28
|
+
*
|
|
29
|
+
* @default ((body, response, defaultError) => defaultError())
|
|
30
|
+
*/
|
|
31
|
+
errorResponseBodyDecoder?: ((deserializedBody: unknown, response: StandardLazyResponse, defaultError: () => Error) => Error) | undefined;
|
|
32
|
+
/**
|
|
33
|
+
* Parse error responses with this `content-type` as JSON, ignoring case and parameters such as `charset`.
|
|
34
|
+
* Should match the handler's `errorResponseContentType`.
|
|
35
|
+
*
|
|
36
|
+
* @example 'application/problem+json'
|
|
37
|
+
*/
|
|
38
|
+
errorResponseContentType?: string | undefined;
|
|
39
|
+
}
|
|
40
|
+
export declare class OpenAPILinkCodec<T extends ClientContext> implements StandardLinkCodec<T> {
|
|
41
|
+
private readonly router;
|
|
42
|
+
private readonly baseUrl;
|
|
43
|
+
private readonly headers;
|
|
44
|
+
private readonly serializer;
|
|
45
|
+
private readonly errorResponseBodyDecoder;
|
|
46
|
+
private readonly errorResponseMediaType;
|
|
47
|
+
constructor(router: RouterContract, options?: OpenAPILinkCodecOptions<T>);
|
|
48
|
+
encodeInput(input: unknown, path: string[], options: ClientOptions<T>): Promise<StandardRequest>;
|
|
49
|
+
private encodePathParam;
|
|
50
|
+
private serializeQueryString;
|
|
51
|
+
decodeResponse(response: StandardLazyResponse, path: string[], _options: ClientOptions<T>): Promise<StandardLinkCodecDecodedResponse>;
|
|
52
|
+
private resolveProcedure;
|
|
53
|
+
}
|
|
@@ -0,0 +1,356 @@
|
|
|
1
|
+
import { createORPCErrorFromJson, isORPCErrorJson, MalformedResponseError, ResponseError } from "@orpc/client";
|
|
2
|
+
import { getRouterContract, ProcedureContract } from "@orpc/contract";
|
|
3
|
+
import { unlazy } from "@orpc/server";
|
|
4
|
+
import { isTypescriptObject, 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.mjs";
|
|
8
|
+
import { getOpenAPIMeta } from "../../meta.mjs";
|
|
9
|
+
import { OpenAPISerializer } from "../../openapi-serializer.mjs";
|
|
10
|
+
import { getDynamicPathParams, isBodylessMethod } from "../../utils.mjs";
|
|
11
|
+
import { serializeHeaders } from "./utils.mjs";
|
|
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 = options.errorResponseBodyDecoder ?? ((_body, _response, defaultError) => defaultError());
|
|
27
|
+
this.errorResponseMediaType = toMediaType(options.errorResponseContentType);
|
|
28
|
+
}
|
|
29
|
+
async encodeInput(input, path, options) {
|
|
30
|
+
let headers = toResolvedStandardHeaders(await value(this.headers, options, path, input));
|
|
31
|
+
if (options.lastEventId !== undefined) {
|
|
32
|
+
headers = mergeStandardHeaders(headers, { "last-event-id": options.lastEventId });
|
|
33
|
+
}
|
|
34
|
+
const baseUrl = await value(this.baseUrl, options, path, input);
|
|
35
|
+
const procedure = await this.resolveProcedure(path);
|
|
36
|
+
const meta = getOpenAPIMeta(procedure);
|
|
37
|
+
const method = meta?.method ?? DEFAULT_OPENAPI_METHOD;
|
|
38
|
+
const inputStructure = meta?.inputStructure ?? DEFAULT_OPENAPI_INPUT_STRUCTURE;
|
|
39
|
+
let pathname = meta?.path ?? pathToHttpPath(path);
|
|
40
|
+
if (meta?.prefix) {
|
|
41
|
+
pathname = mergeHttpPath(meta.prefix, pathname);
|
|
42
|
+
}
|
|
43
|
+
const [basePathname, baseSearch, baseHash] = parseStandardUrl(baseUrl);
|
|
44
|
+
const dynamicParams = getDynamicPathParams(pathname);
|
|
45
|
+
if (inputStructure === "compact") {
|
|
46
|
+
let data = input;
|
|
47
|
+
if (dynamicParams?.length) {
|
|
48
|
+
if (!isTypescriptObject(input)) {
|
|
49
|
+
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(".")}).`);
|
|
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 : undefined;
|
|
59
|
+
}
|
|
60
|
+
pathname = `${basePathname.replace(END_SLASH_REGEX, "")}${pathname}`;
|
|
61
|
+
if (isBodylessMethod(method)) {
|
|
62
|
+
const queryString = this.serializeQueryString(data, meta?.queryStyles);
|
|
63
|
+
const search = combineSearch(baseSearch, queryString);
|
|
64
|
+
const url = `${pathname}${search ?? ""}${baseHash ?? ""}`;
|
|
65
|
+
return {
|
|
66
|
+
body: undefined,
|
|
67
|
+
method,
|
|
68
|
+
headers,
|
|
69
|
+
url,
|
|
70
|
+
signal: options.signal
|
|
71
|
+
};
|
|
72
|
+
}
|
|
73
|
+
const url = `${pathname}${baseSearch ?? ""}${baseHash ?? ""}`;
|
|
74
|
+
return {
|
|
75
|
+
url,
|
|
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
|
+
• 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(`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(".")}).`);
|
|
98
|
+
}
|
|
99
|
+
for (let i = dynamicParams.length - 1; i >= 0; i--) {
|
|
100
|
+
const param = dynamicParams[i];
|
|
101
|
+
const val = input.params[param.parameterName];
|
|
102
|
+
const encoded = this.encodePathParam(val, param, meta?.paramsStyles?.[param.parameterName], path);
|
|
103
|
+
pathname = `${pathname.slice(0, param.startIndex)}${encoded}${pathname.slice(param.startIndex + param.segment.length)}`;
|
|
104
|
+
}
|
|
105
|
+
}
|
|
106
|
+
if (input?.headers) {
|
|
107
|
+
headers = mergeStandardHeaders(headers, serializeHeaders(input.headers, this.serializer));
|
|
108
|
+
}
|
|
109
|
+
pathname = `${basePathname.replace(END_SLASH_REGEX, "")}${pathname}`;
|
|
110
|
+
const queryString = this.serializeQueryString(input?.query, meta?.queryStyles);
|
|
111
|
+
const search = combineSearch(baseSearch, queryString);
|
|
112
|
+
const url = `${pathname}${search ?? ""}${baseHash ?? ""}`;
|
|
113
|
+
if (isBodylessMethod(method)) {
|
|
114
|
+
return {
|
|
115
|
+
body: undefined,
|
|
116
|
+
method,
|
|
117
|
+
headers,
|
|
118
|
+
url,
|
|
119
|
+
signal: options.signal
|
|
120
|
+
};
|
|
121
|
+
}
|
|
122
|
+
return {
|
|
123
|
+
url,
|
|
124
|
+
method,
|
|
125
|
+
headers,
|
|
126
|
+
body: this.serializer.serialize(input?.body),
|
|
127
|
+
signal: options.signal
|
|
128
|
+
};
|
|
129
|
+
}
|
|
130
|
+
encodePathParam(val, param, style, path) {
|
|
131
|
+
let encoded;
|
|
132
|
+
if (style === "comma-delimited-array" && Array.isArray(val)) {
|
|
133
|
+
encoded = val.map((val) => this.serializer.serialize(val)).filter((val) => val !== undefined && val !== null).map((val) => safeEncodeURIComponent(String(val))).join(",");
|
|
134
|
+
} else if (style === "comma-delimited-object" && isTypescriptObject(val)) {
|
|
135
|
+
encoded = Object.entries(val).map(([key, val]) => [key, this.serializer.serialize(val)]).filter(([, val]) => val !== undefined && val !== null).map(([key, val]) => `${safeEncodeURIComponent(String(key))},${safeEncodeURIComponent(String(val))}`).join(",");
|
|
136
|
+
} else {
|
|
137
|
+
const serialized = this.serializer.serialize(val);
|
|
138
|
+
if (serialized !== undefined && serialized !== null) {
|
|
139
|
+
if (param.allowsSlash) {
|
|
140
|
+
encoded = String(serialized).split("/").map(safeEncodeURIComponent).join("/");
|
|
141
|
+
} else {
|
|
142
|
+
encoded = safeEncodeURIComponent(String(serialized));
|
|
143
|
+
}
|
|
144
|
+
}
|
|
145
|
+
}
|
|
146
|
+
if (!encoded) {
|
|
147
|
+
throw new TypeError(`Path param "${param.parameterName}" cannot be empty in call to procedure (${path.join(".")}).`);
|
|
148
|
+
}
|
|
149
|
+
|
|
150
|
+
if (DOT_SEGMENT_REGEX.test(encoded)) {
|
|
151
|
+
throw new TypeError(`Path param "${param.parameterName}" cannot contain "." or ".." segments in call to procedure (${path.join(".")}).`);
|
|
152
|
+
}
|
|
153
|
+
if (encoded.startsWith("/")) {
|
|
154
|
+
encoded = `%2F${encoded.slice(1)}`;
|
|
155
|
+
}
|
|
156
|
+
return encoded;
|
|
157
|
+
}
|
|
158
|
+
serializeQueryString(data, queryStyles) {
|
|
159
|
+
if (!queryStyles || !isTypescriptObject(data)) {
|
|
160
|
+
return toURLSearchParams(this.serializer.serialize(data, { asFormData: true })).toString();
|
|
161
|
+
}
|
|
162
|
+
const remaining = { ...data };
|
|
163
|
+
let query = "";
|
|
164
|
+
Object.entries(queryStyles).forEach(([key, style]) => {
|
|
165
|
+
if (style === undefined) {
|
|
166
|
+
return;
|
|
167
|
+
}
|
|
168
|
+
const value = remaining[key];
|
|
169
|
+
delete remaining[key];
|
|
170
|
+
if (style === "primitive") {
|
|
171
|
+
const serialized = this.serializer.serialize(value);
|
|
172
|
+
if (serialized !== undefined && serialized !== null) {
|
|
173
|
+
query += `&${encodeURLSearchParamComponent(key)}=${encodeURLSearchParamComponent(String(serialized))}`;
|
|
174
|
+
}
|
|
175
|
+
} else if (style === "array" && Array.isArray(value)) {
|
|
176
|
+
const encodedKey = encodeURLSearchParamComponent(key);
|
|
177
|
+
value.forEach((v) => {
|
|
178
|
+
const s = this.serializer.serialize(v);
|
|
179
|
+
if (s !== undefined && s !== null) {
|
|
180
|
+
query += `&${encodedKey}=${encodeURLSearchParamComponent(String(s))}`;
|
|
181
|
+
}
|
|
182
|
+
});
|
|
183
|
+
} else if (style === "json") {
|
|
184
|
+
const serialized = this.serializer.serialize(value);
|
|
185
|
+
if (serialized !== undefined) {
|
|
186
|
+
query += `&${encodeURLSearchParamComponent(key)}=${encodeURLSearchParamComponent(stringifyJSON(serialized))}`;
|
|
187
|
+
}
|
|
188
|
+
} else if (style === "comma-delimited-array" && Array.isArray(value)) {
|
|
189
|
+
const encodedValue = encodeDelimitedArray(value.map((v) => this.serializer.serialize(v)), ",");
|
|
190
|
+
if (encodedValue !== undefined) {
|
|
191
|
+
query += `&${encodeURLSearchParamComponent(key)}=${encodedValue}`;
|
|
192
|
+
}
|
|
193
|
+
} else if (style === "comma-delimited-object" && isTypescriptObject(value)) {
|
|
194
|
+
const encodedValue = encodeDelimitedObject(Object.entries(value).map(([key, value]) => [key, this.serializer.serialize(value)]), ",");
|
|
195
|
+
if (encodedValue !== undefined) {
|
|
196
|
+
query += `&${encodeURLSearchParamComponent(key)}=${encodedValue}`;
|
|
197
|
+
}
|
|
198
|
+
} else if (style === "pipe-delimited-array" && Array.isArray(value)) {
|
|
199
|
+
const encodedValue = encodeDelimitedArray(value.map((v) => this.serializer.serialize(v)), "%7C");
|
|
200
|
+
if (encodedValue !== undefined) {
|
|
201
|
+
query += `&${encodeURLSearchParamComponent(key)}=${encodedValue}`;
|
|
202
|
+
}
|
|
203
|
+
} else if (style === "pipe-delimited-object" && isTypescriptObject(value)) {
|
|
204
|
+
const encodedValue = encodeDelimitedObject(Object.entries(value).map(([key, value]) => [key, this.serializer.serialize(value)]), "%7C");
|
|
205
|
+
if (encodedValue !== undefined) {
|
|
206
|
+
query += `&${encodeURLSearchParamComponent(key)}=${encodedValue}`;
|
|
207
|
+
}
|
|
208
|
+
} else if (style === "space-delimited-array" && Array.isArray(value)) {
|
|
209
|
+
const encodedValue = encodeDelimitedArray(value.map((v) => this.serializer.serialize(v)), "%20");
|
|
210
|
+
if (encodedValue !== undefined) {
|
|
211
|
+
query += `&${encodeURLSearchParamComponent(key)}=${encodedValue}`;
|
|
212
|
+
}
|
|
213
|
+
} else if (style === "space-delimited-object" && isTypescriptObject(value)) {
|
|
214
|
+
const encodedValue = encodeDelimitedObject(Object.entries(value).map(([key, value]) => [key, this.serializer.serialize(value)]), "%20");
|
|
215
|
+
if (encodedValue !== undefined) {
|
|
216
|
+
query += `&${encodeURLSearchParamComponent(key)}=${encodedValue}`;
|
|
217
|
+
}
|
|
218
|
+
} else {
|
|
219
|
+
const serialized = this.serializer.serialize(value);
|
|
220
|
+
if (serialized !== undefined && serialized !== null) {
|
|
221
|
+
query += `&${encodeURLSearchParamComponent(key)}=${encodeURLSearchParamComponent(String(serialized))}`;
|
|
222
|
+
}
|
|
223
|
+
}
|
|
224
|
+
});
|
|
225
|
+
const form = this.serializer.serialize(remaining, { asFormData: true });
|
|
226
|
+
query = `${toURLSearchParams(form).toString()}${query}`;
|
|
227
|
+
if (query.startsWith("&")) {
|
|
228
|
+
query = query.slice(1);
|
|
229
|
+
}
|
|
230
|
+
return query || undefined;
|
|
231
|
+
}
|
|
232
|
+
async decodeResponse(response, path, _options) {
|
|
233
|
+
const isOk = response.status < 400;
|
|
234
|
+
const procedure = await this.resolveProcedure(path);
|
|
235
|
+
const meta = getOpenAPIMeta(procedure);
|
|
236
|
+
const errorBodyHint = !isOk && this.errorResponseMediaType !== undefined && toMediaType(flattenStandardHeader(response.headers["content-type"])) === this.errorResponseMediaType ? "json" : undefined;
|
|
237
|
+
const body = await response.resolveBody(isOk ? meta?.responseBodyHint : errorBodyHint);
|
|
238
|
+
const deserialized = await (async () => {
|
|
239
|
+
try {
|
|
240
|
+
return this.serializer.deserialize(body);
|
|
241
|
+
} catch (error) {
|
|
242
|
+
throw new MalformedResponseError({
|
|
243
|
+
message: "Invalid OpenAPI response format.",
|
|
244
|
+
response: {
|
|
245
|
+
status: response.status,
|
|
246
|
+
headers: response.headers,
|
|
247
|
+
body
|
|
248
|
+
},
|
|
249
|
+
cause: error
|
|
250
|
+
});
|
|
251
|
+
}
|
|
252
|
+
})();
|
|
253
|
+
if (!isOk) {
|
|
254
|
+
const defaultError = () => {
|
|
255
|
+
if (isORPCErrorJson(deserialized)) {
|
|
256
|
+
return createORPCErrorFromJson(deserialized, { cause: new ResponseError({ response: {
|
|
257
|
+
status: response.status,
|
|
258
|
+
headers: response.headers,
|
|
259
|
+
body
|
|
260
|
+
} }) });
|
|
261
|
+
}
|
|
262
|
+
return new MalformedResponseError({ response: {
|
|
263
|
+
headers: response.headers,
|
|
264
|
+
status: response.status,
|
|
265
|
+
body
|
|
266
|
+
} });
|
|
267
|
+
};
|
|
268
|
+
return {
|
|
269
|
+
kind: "error",
|
|
270
|
+
error: this.errorResponseBodyDecoder(deserialized, response, defaultError)
|
|
271
|
+
};
|
|
272
|
+
}
|
|
273
|
+
const outputStructure = meta?.outputStructure ?? DEFAULT_OPENAPI_OUTPUT_STRUCTURE;
|
|
274
|
+
return outputStructure === "compact" ? {
|
|
275
|
+
kind: "output",
|
|
276
|
+
output: deserialized
|
|
277
|
+
} : {
|
|
278
|
+
kind: "output",
|
|
279
|
+
output: {
|
|
280
|
+
status: response.status,
|
|
281
|
+
headers: response.headers,
|
|
282
|
+
body: deserialized
|
|
283
|
+
}
|
|
284
|
+
};
|
|
285
|
+
}
|
|
286
|
+
async resolveProcedure(path) {
|
|
287
|
+
const { default: maybeProcedure } = await unlazy(getRouterContract(this.router, path));
|
|
288
|
+
if (!(maybeProcedure instanceof ProcedureContract)) {
|
|
289
|
+
throw new TypeError(`Expected a procedure or contract at path (${path.join(".")})`);
|
|
290
|
+
}
|
|
291
|
+
return maybeProcedure;
|
|
292
|
+
}
|
|
293
|
+
}
|
|
294
|
+
function combineSearch(baseSearch, additionalSearch) {
|
|
295
|
+
if (!baseSearch && !additionalSearch) {
|
|
296
|
+
return undefined;
|
|
297
|
+
}
|
|
298
|
+
if (!additionalSearch) {
|
|
299
|
+
return baseSearch;
|
|
300
|
+
}
|
|
301
|
+
if (!baseSearch) {
|
|
302
|
+
return `?${additionalSearch}`;
|
|
303
|
+
}
|
|
304
|
+
return `${baseSearch}&${additionalSearch}`;
|
|
305
|
+
}
|
|
306
|
+
|
|
307
|
+
function toMediaType(contentType) {
|
|
308
|
+
return contentType?.split(";")[0]?.trim().toLowerCase();
|
|
309
|
+
}
|
|
310
|
+
function toResolvedStandardHeaders(headers) {
|
|
311
|
+
|
|
312
|
+
if (typeof headers.forEach === "function") {
|
|
313
|
+
return toStandardHeaders(headers);
|
|
314
|
+
}
|
|
315
|
+
return headers;
|
|
316
|
+
}
|
|
317
|
+
function isValidDetailedInput(input) {
|
|
318
|
+
if (!isTypescriptObject(input)) {
|
|
319
|
+
return input === undefined;
|
|
320
|
+
}
|
|
321
|
+
if (input.params !== undefined && !isTypescriptObject(input.params)) {
|
|
322
|
+
return false;
|
|
323
|
+
}
|
|
324
|
+
if (input.query !== undefined && !isTypescriptObject(input.query)) {
|
|
325
|
+
return false;
|
|
326
|
+
}
|
|
327
|
+
if (input.headers !== undefined && !isTypescriptObject(input.headers)) {
|
|
328
|
+
return false;
|
|
329
|
+
}
|
|
330
|
+
return true;
|
|
331
|
+
}
|
|
332
|
+
|
|
333
|
+
function encodeURLSearchParamComponent(value) {
|
|
334
|
+
return new URLSearchParams({ "": value }).toString().slice(1);
|
|
335
|
+
}
|
|
336
|
+
function toURLSearchParams(form) {
|
|
337
|
+
const params = new URLSearchParams();
|
|
338
|
+
for (const [key, value] of form) {
|
|
339
|
+
params.append(key, String(value));
|
|
340
|
+
}
|
|
341
|
+
return params;
|
|
342
|
+
}
|
|
343
|
+
function encodeDelimitedArray(serializedValues, encodedDelimiter) {
|
|
344
|
+
const strings = serializedValues.filter((v) => v !== null && v !== undefined).map(String);
|
|
345
|
+
if (!strings.length) {
|
|
346
|
+
return undefined;
|
|
347
|
+
}
|
|
348
|
+
return strings.map(encodeURLSearchParamComponent).join(encodedDelimiter);
|
|
349
|
+
}
|
|
350
|
+
function encodeDelimitedObject(entries, encodedDelimiter) {
|
|
351
|
+
const strings = entries.filter(([, v]) => v !== null && v !== undefined).map(([k, v]) => [k, String(v)]);
|
|
352
|
+
if (!strings.length) {
|
|
353
|
+
return undefined;
|
|
354
|
+
}
|
|
355
|
+
return strings.map(([key, value]) => `${encodeURLSearchParamComponent(key)}${encodedDelimiter}${encodeURLSearchParamComponent(value)}`).join(encodedDelimiter);
|
|
356
|
+
}
|
|
@@ -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
|
+
}
|