@orpc/openapi 2.0.0-beta.5 → 2.0.0-beta.51
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 +139 -102
- package/dist/adapters/aws-lambda/index.d.ts +3 -0
- package/dist/adapters/aws-lambda/index.js +1 -0
- package/dist/adapters/aws-lambda/openapi-handler.d.ts +17 -0
- package/dist/adapters/aws-lambda/openapi-handler.js +20 -0
- package/dist/adapters/fastify/index.d.ts +2 -0
- package/dist/adapters/fastify/index.js +1 -0
- package/dist/adapters/fastify/openapi-handler.d.ts +14 -0
- package/dist/adapters/fastify/openapi-handler.js +17 -0
- package/dist/adapters/fetch/index.d.ts +3 -27
- package/dist/adapters/fetch/index.js +2 -0
- package/dist/adapters/fetch/openapi-handler.d.ts +14 -0
- package/dist/adapters/fetch/openapi-handler.js +17 -0
- package/dist/adapters/fetch/openapi-link.d.ts +20 -0
- package/dist/adapters/fetch/openapi-link.js +22 -0
- package/dist/adapters/node/index.d.ts +2 -18
- package/dist/adapters/node/index.js +1 -0
- package/dist/adapters/node/openapi-handler.d.ts +14 -0
- package/dist/adapters/node/openapi-handler.js +17 -0
- package/dist/adapters/standard/index.d.ts +4 -50
- package/dist/adapters/standard/index.js +3 -0
- package/dist/adapters/standard/openapi-handler-codec.d.ts +61 -0
- package/dist/adapters/standard/openapi-handler-codec.js +158 -0
- package/dist/adapters/standard/openapi-link-codec.d.ts +58 -0
- package/dist/adapters/standard/openapi-link-codec.js +290 -0
- package/dist/adapters/standard/openapi-matcher.d.ts +29 -0
- package/dist/adapters/standard/openapi-matcher.js +78 -0
- package/dist/adapters/standard/utils.js +31 -0
- package/dist/bracket-notation.d.ts +26 -0
- package/dist/bracket-notation.js +135 -0
- package/dist/client-factory.d.ts +24 -0
- package/dist/client-factory.js +15 -0
- package/dist/constants.d.ts +1 -0
- package/dist/constants.js +5 -0
- package/dist/extensions/route.d.ts +36 -42
- package/dist/extensions/route.js +13 -0
- package/dist/helpers/{index.d.mts → form-data.d.ts} +11 -5
- package/dist/helpers/form-data.js +78 -0
- package/dist/helpers/index.d.ts +2 -51
- package/dist/helpers/index.js +1 -0
- package/dist/index.d.ts +15 -120
- package/dist/index.js +11 -0
- package/dist/meta.d.ts +327 -0
- package/dist/meta.js +66 -0
- package/dist/openapi-generator-components.d.ts +2 -0
- package/dist/openapi-generator-components.js +318 -0
- package/dist/openapi-generator-operation.d.ts +13 -0
- package/dist/openapi-generator-operation.js +459 -0
- package/dist/openapi-generator.d.ts +87 -0
- package/dist/openapi-generator.js +119 -0
- package/dist/openapi-json-serializer.d.ts +79 -0
- package/dist/openapi-json-serializer.js +221 -0
- package/dist/openapi-serializer.d.ts +42 -0
- package/dist/openapi-serializer.js +69 -0
- package/dist/plugins/index.d.ts +2 -90
- package/dist/plugins/index.js +1 -0
- package/dist/plugins/openapi-reference.d.ts +112 -0
- package/dist/plugins/openapi-reference.js +164 -0
- package/dist/router-utils.d.ts +18 -0
- package/dist/router-utils.js +32 -0
- package/dist/types.d.ts +28 -0
- package/dist/utils.d.ts +9 -0
- package/dist/utils.js +44 -0
- package/package.json +87 -49
- package/dist/adapters/fetch/index.d.mts +0 -27
- package/dist/adapters/fetch/index.mjs +0 -34
- package/dist/adapters/node/index.d.mts +0 -18
- package/dist/adapters/node/index.mjs +0 -21
- package/dist/adapters/standard/index.d.mts +0 -50
- package/dist/adapters/standard/index.mjs +0 -12
- package/dist/extensions/route.d.mts +0 -43
- package/dist/extensions/route.mjs +0 -14
- package/dist/helpers/index.mjs +0 -39
- package/dist/index.d.mts +0 -120
- package/dist/index.mjs +0 -930
- package/dist/plugins/index.d.mts +0 -90
- package/dist/plugins/index.mjs +0 -162
- package/dist/shared/openapi.7vgmPxca.d.ts +0 -82
- package/dist/shared/openapi.B2SK0ZAr.mjs +0 -359
- package/dist/shared/openapi.B9PQzqBn.mjs +0 -49
- package/dist/shared/openapi.BQzzr4-4.d.ts +0 -299
- package/dist/shared/openapi.BcEtAxQj.d.mts +0 -299
- package/dist/shared/openapi.Bt87OzTt.mjs +0 -131
- package/dist/shared/openapi.C7m7NAmH.d.mts +0 -142
- package/dist/shared/openapi.C7m7NAmH.d.ts +0 -142
- package/dist/shared/openapi.CTlpLuKN.mjs +0 -318
- package/dist/shared/openapi.CX6Ri5dP.d.mts +0 -82
- package/dist/shared/openapi.CYgMBSUF.d.mts +0 -18
- package/dist/shared/openapi.CYgMBSUF.d.ts +0 -18
- package/dist/shared/openapi.DmAa7YPO.mjs +0 -275
|
@@ -0,0 +1,290 @@
|
|
|
1
|
+
import "../../constants.js";
|
|
2
|
+
import { getOpenAPIMeta } from "../../meta.js";
|
|
3
|
+
import { OpenAPISerializer } from "../../openapi-serializer.js";
|
|
4
|
+
import { getDynamicPathParams, isBodylessMethod } from "../../utils.js";
|
|
5
|
+
import { serializeHeaders } from "./utils.js";
|
|
6
|
+
import { isNonPrimitive, mergeHttpPath, pathToHttpPath, safeEncodeURIComponent, stringifyJSON, value } from "@orpc/shared";
|
|
7
|
+
import { ProcedureContract, getRouterContract } from "@orpc/contract";
|
|
8
|
+
import { MalformedResponseError, ResponseError, createORPCErrorFromJson, isORPCErrorJson } from "@orpc/client";
|
|
9
|
+
import { unlazy } from "@orpc/server";
|
|
10
|
+
import { flattenStandardHeader, mergeStandardHeaders, parseStandardUrl } from "@standard-server/core";
|
|
11
|
+
import { toStandardHeaders } from "@standard-server/fetch";
|
|
12
|
+
// src/adapters/standard/openapi-link-codec.ts
|
|
13
|
+
const DOT_SEGMENT_REGEX = /(?:^|\/)\.{1,2}(?:\/|$)/;
|
|
14
|
+
var OpenAPILinkCodec = class {
|
|
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 !== void 0) headers = mergeStandardHeaders(headers, { "last-event-id": options.lastEventId });
|
|
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 ?? "POST";
|
|
36
|
+
const inputStructure = meta?.inputStructure ?? "compact";
|
|
37
|
+
let pathname = meta?.path ?? pathToHttpPath(path);
|
|
38
|
+
if (meta?.prefix) pathname = mergeHttpPath(meta.prefix, pathname);
|
|
39
|
+
const [basePathname, baseSearch, baseHash] = parseStandardUrl(baseUrl);
|
|
40
|
+
const dynamicParams = getDynamicPathParams(pathname);
|
|
41
|
+
if (inputStructure === "compact") {
|
|
42
|
+
let data = input;
|
|
43
|
+
if (dynamicParams?.length) {
|
|
44
|
+
if (!isNonPrimitive(input)) 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(".")}).`);
|
|
45
|
+
const remaining = { ...input };
|
|
46
|
+
for (let i = dynamicParams.length - 1; i >= 0; i--) {
|
|
47
|
+
const param = dynamicParams[i];
|
|
48
|
+
const encoded = this.encodePathParam(input[param.parameterName], param, meta?.paramsStyles?.[param.parameterName], path);
|
|
49
|
+
pathname = `${pathname.slice(0, param.startIndex)}${encoded}${pathname.slice(param.startIndex + param.segment.length)}`;
|
|
50
|
+
delete remaining[param.parameterName];
|
|
51
|
+
}
|
|
52
|
+
data = Object.keys(remaining).length > 0 ? remaining : void 0;
|
|
53
|
+
}
|
|
54
|
+
pathname = mergeHttpPath(basePathname, pathname);
|
|
55
|
+
if (isBodylessMethod(method)) {
|
|
56
|
+
const search = combineSearch(baseSearch, this.serializeQueryString(data, meta?.queryStyles));
|
|
57
|
+
const url = `${pathname}${search ?? ""}${baseHash ?? ""}`;
|
|
58
|
+
return {
|
|
59
|
+
body: void 0,
|
|
60
|
+
method,
|
|
61
|
+
headers,
|
|
62
|
+
url,
|
|
63
|
+
signal: options.signal
|
|
64
|
+
};
|
|
65
|
+
}
|
|
66
|
+
return {
|
|
67
|
+
url: `${pathname}${baseSearch ?? ""}${baseHash ?? ""}`,
|
|
68
|
+
method,
|
|
69
|
+
headers,
|
|
70
|
+
body: this.serializer.serialize(data),
|
|
71
|
+
signal: options.signal
|
|
72
|
+
};
|
|
73
|
+
}
|
|
74
|
+
if (!isValidDetailedInput(input)) throw new TypeError(`
|
|
75
|
+
Invalid "detailed" input structure in call to procedure (${path.join(".")}):
|
|
76
|
+
• Expected an object or undefined with optional properties:
|
|
77
|
+
- params (object, required when the path has dynamic params)
|
|
78
|
+
- query (object)
|
|
79
|
+
- headers (object)
|
|
80
|
+
- body (any)
|
|
81
|
+
|
|
82
|
+
Actual value:
|
|
83
|
+
${stringifyJSON(input)}
|
|
84
|
+
`);
|
|
85
|
+
if (dynamicParams?.length) {
|
|
86
|
+
if (!input?.params) 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(".")}).`);
|
|
87
|
+
for (let i = dynamicParams.length - 1; i >= 0; i--) {
|
|
88
|
+
const param = dynamicParams[i];
|
|
89
|
+
const val = input.params[param.parameterName];
|
|
90
|
+
const encoded = this.encodePathParam(val, param, meta?.paramsStyles?.[param.parameterName], path);
|
|
91
|
+
pathname = `${pathname.slice(0, param.startIndex)}${encoded}${pathname.slice(param.startIndex + param.segment.length)}`;
|
|
92
|
+
}
|
|
93
|
+
}
|
|
94
|
+
if (input?.headers) headers = mergeStandardHeaders(headers, serializeHeaders(input.headers, this.serializer));
|
|
95
|
+
pathname = mergeHttpPath(basePathname, pathname);
|
|
96
|
+
const search = combineSearch(baseSearch, this.serializeQueryString(input?.query, meta?.queryStyles));
|
|
97
|
+
const url = `${pathname}${search ?? ""}${baseHash ?? ""}`;
|
|
98
|
+
if (isBodylessMethod(method)) return {
|
|
99
|
+
body: void 0,
|
|
100
|
+
method,
|
|
101
|
+
headers,
|
|
102
|
+
url,
|
|
103
|
+
signal: options.signal
|
|
104
|
+
};
|
|
105
|
+
return {
|
|
106
|
+
url,
|
|
107
|
+
method,
|
|
108
|
+
headers,
|
|
109
|
+
body: this.serializer.serialize(input?.body),
|
|
110
|
+
signal: options.signal
|
|
111
|
+
};
|
|
112
|
+
}
|
|
113
|
+
encodePathParam(val, param, style, path) {
|
|
114
|
+
let encoded;
|
|
115
|
+
if (style === "comma-delimited-array" && Array.isArray(val)) encoded = val.map((val) => this.serializeURLValue(val)).filter((val) => val !== void 0 && val !== null).map((val) => safeEncodeURIComponent(String(val))).join(",");
|
|
116
|
+
else if (style === "comma-delimited-object" && isNonPrimitive(val)) encoded = Object.entries(val).map(([key, val]) => [key, this.serializeURLValue(val)]).filter(([, val]) => val !== void 0 && val !== null).map(([key, val]) => `${safeEncodeURIComponent(String(key))},${safeEncodeURIComponent(String(val))}`).join(",");
|
|
117
|
+
else {
|
|
118
|
+
const serialized = this.serializeURLValue(val);
|
|
119
|
+
if (serialized !== void 0 && serialized !== null) {
|
|
120
|
+
if (param.allowsSlash) encoded = String(serialized).split("/").map(safeEncodeURIComponent).join("/");
|
|
121
|
+
else encoded = safeEncodeURIComponent(String(serialized));
|
|
122
|
+
}
|
|
123
|
+
}
|
|
124
|
+
if (!encoded) throw new TypeError(`Path param "${param.parameterName}" cannot be empty in call to procedure (${path.join(".")}).`);
|
|
125
|
+
if (DOT_SEGMENT_REGEX.test(encoded)) throw new TypeError(`Path param "${param.parameterName}" cannot contain "." or ".." segments in call to procedure (${path.join(".")}).`);
|
|
126
|
+
if (encoded.startsWith("/")) encoded = `%2F${encoded.slice(1)}`;
|
|
127
|
+
return encoded;
|
|
128
|
+
}
|
|
129
|
+
/**
|
|
130
|
+
* Serializes a single path/query value, like header values, so body-level
|
|
131
|
+
* serialize defaults (e.g. `asFormData`) never apply to URLs.
|
|
132
|
+
*/
|
|
133
|
+
serializeURLValue(value) {
|
|
134
|
+
return value === void 0 ? void 0 : this.serializer.serializeJson(value).json;
|
|
135
|
+
}
|
|
136
|
+
serializeQueryString(data, queryStyles) {
|
|
137
|
+
if (!queryStyles || !isNonPrimitive(data)) return toURLSearchParams(this.serializer.serialize(data, { asFormData: true })).toString();
|
|
138
|
+
const remaining = { ...data };
|
|
139
|
+
let query = "";
|
|
140
|
+
Object.entries(queryStyles).forEach(([key, style]) => {
|
|
141
|
+
if (style === void 0) return;
|
|
142
|
+
const value = remaining[key];
|
|
143
|
+
delete remaining[key];
|
|
144
|
+
if (style === "primitive") {
|
|
145
|
+
const serialized = this.serializeURLValue(value);
|
|
146
|
+
if (serialized !== void 0 && serialized !== null) query += `&${encodeURLSearchParamComponent(key)}=${encodeURLSearchParamComponent(String(serialized))}`;
|
|
147
|
+
} else if (style === "array" && Array.isArray(value)) {
|
|
148
|
+
const encodedKey = encodeURLSearchParamComponent(key);
|
|
149
|
+
value.forEach((v) => {
|
|
150
|
+
const s = this.serializeURLValue(v);
|
|
151
|
+
if (s !== void 0 && s !== null) query += `&${encodedKey}=${encodeURLSearchParamComponent(String(s))}`;
|
|
152
|
+
});
|
|
153
|
+
} else if (style === "json") {
|
|
154
|
+
const serialized = this.serializeURLValue(value);
|
|
155
|
+
if (serialized !== void 0) query += `&${encodeURLSearchParamComponent(key)}=${encodeURLSearchParamComponent(stringifyJSON(serialized))}`;
|
|
156
|
+
} else if (style === "comma-delimited-array" && Array.isArray(value)) {
|
|
157
|
+
const encodedValue = encodeDelimitedArray(value.map((v) => this.serializeURLValue(v)), ",");
|
|
158
|
+
if (encodedValue !== void 0) query += `&${encodeURLSearchParamComponent(key)}=${encodedValue}`;
|
|
159
|
+
} else if (style === "comma-delimited-object" && isNonPrimitive(value)) {
|
|
160
|
+
const encodedValue = encodeDelimitedObject(Object.entries(value).map(([key, value]) => [key, this.serializeURLValue(value)]), ",");
|
|
161
|
+
if (encodedValue !== void 0) query += `&${encodeURLSearchParamComponent(key)}=${encodedValue}`;
|
|
162
|
+
} else if (style === "pipe-delimited-array" && Array.isArray(value)) {
|
|
163
|
+
const encodedValue = encodeDelimitedArray(value.map((v) => this.serializeURLValue(v)), "%7C");
|
|
164
|
+
if (encodedValue !== void 0) query += `&${encodeURLSearchParamComponent(key)}=${encodedValue}`;
|
|
165
|
+
} else if (style === "pipe-delimited-object" && isNonPrimitive(value)) {
|
|
166
|
+
const encodedValue = encodeDelimitedObject(Object.entries(value).map(([key, value]) => [key, this.serializeURLValue(value)]), "%7C");
|
|
167
|
+
if (encodedValue !== void 0) query += `&${encodeURLSearchParamComponent(key)}=${encodedValue}`;
|
|
168
|
+
} else if (style === "space-delimited-array" && Array.isArray(value)) {
|
|
169
|
+
const encodedValue = encodeDelimitedArray(value.map((v) => this.serializeURLValue(v)), "%20");
|
|
170
|
+
if (encodedValue !== void 0) query += `&${encodeURLSearchParamComponent(key)}=${encodedValue}`;
|
|
171
|
+
} else if (style === "space-delimited-object" && isNonPrimitive(value)) {
|
|
172
|
+
const encodedValue = encodeDelimitedObject(Object.entries(value).map(([key, value]) => [key, this.serializeURLValue(value)]), "%20");
|
|
173
|
+
if (encodedValue !== void 0) query += `&${encodeURLSearchParamComponent(key)}=${encodedValue}`;
|
|
174
|
+
} else {
|
|
175
|
+
const serialized = this.serializeURLValue(value);
|
|
176
|
+
if (serialized !== void 0 && serialized !== null) query += `&${encodeURLSearchParamComponent(key)}=${encodeURLSearchParamComponent(String(serialized))}`;
|
|
177
|
+
}
|
|
178
|
+
});
|
|
179
|
+
query = `${toURLSearchParams(this.serializer.serialize(remaining, { asFormData: true })).toString()}${query}`;
|
|
180
|
+
if (query.startsWith("&")) query = query.slice(1);
|
|
181
|
+
return query || void 0;
|
|
182
|
+
}
|
|
183
|
+
async decodeResponse(response, path, _options) {
|
|
184
|
+
const isOk = response.status < 400;
|
|
185
|
+
const procedure = await this.resolveProcedure(path);
|
|
186
|
+
const meta = getOpenAPIMeta(procedure);
|
|
187
|
+
const errorBodyHint = !isOk && this.errorResponseMediaType !== void 0 && toMediaType(flattenStandardHeader(response.headers["content-type"])) === this.errorResponseMediaType ? "json" : void 0;
|
|
188
|
+
const body = await response.resolveBody(isOk ? meta?.responseBodyHint : errorBodyHint);
|
|
189
|
+
const deserialized = await (async () => {
|
|
190
|
+
try {
|
|
191
|
+
return this.serializer.deserialize(body);
|
|
192
|
+
} catch (error) {
|
|
193
|
+
throw new MalformedResponseError({
|
|
194
|
+
message: "Invalid OpenAPI response format.",
|
|
195
|
+
response: {
|
|
196
|
+
status: response.status,
|
|
197
|
+
headers: response.headers,
|
|
198
|
+
body
|
|
199
|
+
},
|
|
200
|
+
cause: error
|
|
201
|
+
});
|
|
202
|
+
}
|
|
203
|
+
})();
|
|
204
|
+
if (!isOk) {
|
|
205
|
+
const defaultError = () => {
|
|
206
|
+
if (isORPCErrorJson(deserialized)) return createORPCErrorFromJson(deserialized, { cause: new ResponseError({ response: {
|
|
207
|
+
status: response.status,
|
|
208
|
+
headers: response.headers,
|
|
209
|
+
body
|
|
210
|
+
} }) });
|
|
211
|
+
return new MalformedResponseError({ response: {
|
|
212
|
+
headers: response.headers,
|
|
213
|
+
status: response.status,
|
|
214
|
+
body
|
|
215
|
+
} });
|
|
216
|
+
};
|
|
217
|
+
return {
|
|
218
|
+
kind: "error",
|
|
219
|
+
error: this.errorResponseBodyDecoder(deserialized, response, defaultError)
|
|
220
|
+
};
|
|
221
|
+
}
|
|
222
|
+
return (meta?.outputStructure ?? "compact") === "compact" ? {
|
|
223
|
+
kind: "output",
|
|
224
|
+
output: deserialized
|
|
225
|
+
} : {
|
|
226
|
+
kind: "output",
|
|
227
|
+
output: {
|
|
228
|
+
status: response.status,
|
|
229
|
+
headers: response.headers,
|
|
230
|
+
body: deserialized
|
|
231
|
+
}
|
|
232
|
+
};
|
|
233
|
+
}
|
|
234
|
+
async resolveProcedure(path) {
|
|
235
|
+
const { default: maybeProcedure } = await unlazy(getRouterContract(this.router, path));
|
|
236
|
+
if (!(maybeProcedure instanceof ProcedureContract)) throw new TypeError(`Expected a procedure or contract at path (${path.join(".")})`);
|
|
237
|
+
return maybeProcedure;
|
|
238
|
+
}
|
|
239
|
+
};
|
|
240
|
+
function combineSearch(baseSearch, additionalSearch) {
|
|
241
|
+
if (!baseSearch && !additionalSearch) return;
|
|
242
|
+
if (!additionalSearch) return baseSearch;
|
|
243
|
+
if (!baseSearch) return `?${additionalSearch}`;
|
|
244
|
+
return `${baseSearch}&${additionalSearch}`;
|
|
245
|
+
}
|
|
246
|
+
/**
|
|
247
|
+
* Strips parameters and normalizes case, e.g. `Application/Problem+JSON; charset=utf-8` -> `application/problem+json`.
|
|
248
|
+
*/
|
|
249
|
+
function toMediaType(contentType) {
|
|
250
|
+
return contentType?.split(";")[0]?.trim().toLowerCase();
|
|
251
|
+
}
|
|
252
|
+
function toResolvedStandardHeaders(headers) {
|
|
253
|
+
/**
|
|
254
|
+
* Headers class might not be available in some environments,
|
|
255
|
+
* so we check for the existence of `forEach` and `get`
|
|
256
|
+
* methods to determine if it's a Headers instance.
|
|
257
|
+
*/
|
|
258
|
+
if (typeof headers.forEach === "function") return toStandardHeaders(headers);
|
|
259
|
+
return headers;
|
|
260
|
+
}
|
|
261
|
+
function isValidDetailedInput(input) {
|
|
262
|
+
if (!isNonPrimitive(input)) return input === void 0;
|
|
263
|
+
if (input.params !== void 0 && !isNonPrimitive(input.params)) return false;
|
|
264
|
+
if (input.query !== void 0 && !isNonPrimitive(input.query)) return false;
|
|
265
|
+
if (input.headers !== void 0 && !isNonPrimitive(input.headers)) return false;
|
|
266
|
+
return true;
|
|
267
|
+
}
|
|
268
|
+
/**
|
|
269
|
+
* Encode a query parameter value using URLSearchParams semantics.
|
|
270
|
+
* Prefer this over safeEncodeURIComponent for query-string values.
|
|
271
|
+
*/
|
|
272
|
+
function encodeURLSearchParamComponent(value) {
|
|
273
|
+
return new URLSearchParams({ "": value }).toString().slice(1);
|
|
274
|
+
}
|
|
275
|
+
function toURLSearchParams(form) {
|
|
276
|
+
const params = new URLSearchParams();
|
|
277
|
+
for (const [key, value] of form) params.append(key, String(value));
|
|
278
|
+
return params;
|
|
279
|
+
}
|
|
280
|
+
function encodeDelimitedArray(serializedValues, encodedDelimiter) {
|
|
281
|
+
const strings = serializedValues.filter((v) => v !== null && v !== void 0).map(String);
|
|
282
|
+
if (!strings.length) return;
|
|
283
|
+
return strings.map(encodeURLSearchParamComponent).join(encodedDelimiter);
|
|
284
|
+
}
|
|
285
|
+
function encodeDelimitedObject(entries, encodedDelimiter) {
|
|
286
|
+
const strings = entries.filter(([, v]) => v !== null && v !== void 0).map(([k, v]) => [k, String(v)]);
|
|
287
|
+
if (!strings.length) return;
|
|
288
|
+
return strings.map(([key, value]) => `${encodeURLSearchParamComponent(key)}${encodedDelimiter}${encodeURLSearchParamComponent(value)}`).join(encodedDelimiter);
|
|
289
|
+
}
|
|
290
|
+
export { OpenAPILinkCodec };
|
|
@@ -0,0 +1,29 @@
|
|
|
1
|
+
import { Value } from "@orpc/shared";
|
|
2
|
+
import { AnyProcedureContract } from "@orpc/contract";
|
|
3
|
+
import { AnyProcedure, AnyRouter } from "@orpc/server";
|
|
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,78 @@
|
|
|
1
|
+
import "../../constants.js";
|
|
2
|
+
import { getOpenAPIMeta } from "../../meta.js";
|
|
3
|
+
import { mergeHttpPath, pathToHttpPath, stripHttpPathPrefix, value } from "@orpc/shared";
|
|
4
|
+
import { Procedure, resolveContractProcedure, unlazy, walkProcedureContractsSync } from "@orpc/server";
|
|
5
|
+
import { Router as Router$1, createPrefixMatcher } from "@openapi-spec/router";
|
|
6
|
+
// src/adapters/standard/openapi-matcher.ts
|
|
7
|
+
var OpenAPIMatcher = class {
|
|
8
|
+
filter;
|
|
9
|
+
rootRouter;
|
|
10
|
+
tree = new Router$1();
|
|
11
|
+
pendingLazyRouters = /* @__PURE__ */ new Set();
|
|
12
|
+
constructor(router, options = {}) {
|
|
13
|
+
this.filter = options.filter ?? true;
|
|
14
|
+
this.rootRouter = router;
|
|
15
|
+
this.index(router);
|
|
16
|
+
}
|
|
17
|
+
index(router, path = []) {
|
|
18
|
+
const lazyResults = walkProcedureContractsSync(router, (contract, path) => {
|
|
19
|
+
if (!value(this.filter, contract, path)) return;
|
|
20
|
+
const meta = getOpenAPIMeta(contract);
|
|
21
|
+
const method = meta?.method ?? "POST";
|
|
22
|
+
const postHttpPath = meta?.path ?? pathToHttpPath(path);
|
|
23
|
+
const httpPath = meta?.prefix ? mergeHttpPath(meta.prefix, postHttpPath) : postHttpPath;
|
|
24
|
+
this.tree.add(method, httpPath, {
|
|
25
|
+
path,
|
|
26
|
+
contract,
|
|
27
|
+
procedure: contract instanceof Procedure ? contract : void 0
|
|
28
|
+
});
|
|
29
|
+
}, path);
|
|
30
|
+
for (const result of lazyResults) {
|
|
31
|
+
const prefix = getOpenAPIMeta(result.router)?.prefix;
|
|
32
|
+
this.pendingLazyRouters.add({
|
|
33
|
+
...result,
|
|
34
|
+
matcher: prefix ? createPrefixMatcher(prefix) : void 0
|
|
35
|
+
});
|
|
36
|
+
}
|
|
37
|
+
}
|
|
38
|
+
async match(method, pathname, prefix) {
|
|
39
|
+
if (prefix) {
|
|
40
|
+
const stripped = stripHttpPathPrefix(pathname, prefix);
|
|
41
|
+
if (stripped === void 0) return;
|
|
42
|
+
pathname = stripped;
|
|
43
|
+
}
|
|
44
|
+
const loading = this.resolvePendingLazyRouters(pathname);
|
|
45
|
+
if (loading !== void 0) await loading;
|
|
46
|
+
const match = this.tree.match(method, pathname);
|
|
47
|
+
if (match === void 0) return;
|
|
48
|
+
const entry = match.data;
|
|
49
|
+
return {
|
|
50
|
+
path: entry.path,
|
|
51
|
+
procedure: entry.procedure ?? await this.resolveProcedure(entry),
|
|
52
|
+
params: match.params
|
|
53
|
+
};
|
|
54
|
+
}
|
|
55
|
+
resolvePendingLazyRouters(pathname) {
|
|
56
|
+
for (const pending of this.pendingLazyRouters) if (pending.matcher === void 0 || pending.matcher(pathname)) return this.loadPendingLazyRouters(pathname);
|
|
57
|
+
}
|
|
58
|
+
async loadPendingLazyRouters(pathname) {
|
|
59
|
+
for (const pending of this.pendingLazyRouters) if (pending.matcher === void 0 || pending.matcher(pathname)) await this.loadPendingLazyRouter(pending);
|
|
60
|
+
}
|
|
61
|
+
loadPendingLazyRouter(pending) {
|
|
62
|
+
if (pending.loading === void 0) pending.loading = this.indexPendingLazyRouter(pending).catch((error) => {
|
|
63
|
+
pending.loading = void 0;
|
|
64
|
+
throw error;
|
|
65
|
+
});
|
|
66
|
+
return pending.loading;
|
|
67
|
+
}
|
|
68
|
+
async indexPendingLazyRouter(pending) {
|
|
69
|
+
const { default: router } = await unlazy(pending.router);
|
|
70
|
+
this.index(router, pending.path);
|
|
71
|
+
this.pendingLazyRouters.delete(pending);
|
|
72
|
+
}
|
|
73
|
+
async resolveProcedure(entry) {
|
|
74
|
+
entry.procedure = await resolveContractProcedure(this.rootRouter, entry.contract, entry.path);
|
|
75
|
+
return entry.procedure;
|
|
76
|
+
}
|
|
77
|
+
};
|
|
78
|
+
export { OpenAPIMatcher };
|
|
@@ -0,0 +1,31 @@
|
|
|
1
|
+
import { NullProtoObj, isNonPrimitive } from "@orpc/shared";
|
|
2
|
+
// src/adapters/standard/utils.ts
|
|
3
|
+
function serializeHeaders(headers, serializer) {
|
|
4
|
+
const result = new NullProtoObj();
|
|
5
|
+
for (const [key, value] of Object.entries(headers)) {
|
|
6
|
+
/**
|
|
7
|
+
* Only an actual array value represents a multi-value header (sent as multiple lines).
|
|
8
|
+
* Serialization can turn non-array values into arrays (e.g. Set, Map, custom handlers),
|
|
9
|
+
* and those must stay a single line, so the structure is checked before serializing.
|
|
10
|
+
*/
|
|
11
|
+
if (Array.isArray(value)) {
|
|
12
|
+
const lines = [];
|
|
13
|
+
for (const item of value) {
|
|
14
|
+
const line = serializeHeaderValue(item, serializer);
|
|
15
|
+
if (line !== void 0) lines.push(line);
|
|
16
|
+
}
|
|
17
|
+
result[key] = lines;
|
|
18
|
+
continue;
|
|
19
|
+
}
|
|
20
|
+
const line = serializeHeaderValue(value, serializer);
|
|
21
|
+
if (line !== void 0) result[key] = line;
|
|
22
|
+
}
|
|
23
|
+
return result;
|
|
24
|
+
}
|
|
25
|
+
function serializeHeaderValue(value, serializer) {
|
|
26
|
+
const serialized = serializer.serializeJson(value).json;
|
|
27
|
+
if (Array.isArray(serialized)) return serialized.filter((item) => item !== void 0 && item !== null).map(String).join(",");
|
|
28
|
+
if (isNonPrimitive(serialized)) return Object.entries(serialized).filter(([, val]) => val !== void 0 && val !== null).map(([key, val]) => `${key},${String(val)}`).join(",");
|
|
29
|
+
if (serialized !== void 0 && serialized !== null) return String(serialized);
|
|
30
|
+
}
|
|
31
|
+
export { serializeHeaders };
|
|
@@ -0,0 +1,26 @@
|
|
|
1
|
+
import { 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
|
+
}
|
|
@@ -0,0 +1,135 @@
|
|
|
1
|
+
import { NullProtoObj, isPlainObject, setOwn } from "@orpc/shared";
|
|
2
|
+
// src/bracket-notation.ts
|
|
3
|
+
var BracketNotationSerializer = class {
|
|
4
|
+
maxDeserializingEmptySlots;
|
|
5
|
+
constructor(options = {}) {
|
|
6
|
+
this.maxDeserializingEmptySlots = options.maxDeserializingEmptySlots ?? 1e3;
|
|
7
|
+
}
|
|
8
|
+
serialize(data) {
|
|
9
|
+
const result = [];
|
|
10
|
+
this.internalSerialize(data, "", true, result);
|
|
11
|
+
return result;
|
|
12
|
+
}
|
|
13
|
+
internalSerialize(data, path, isRoot, result) {
|
|
14
|
+
if (Array.isArray(data)) data.forEach((item, i) => {
|
|
15
|
+
this.internalSerialize(item, isRoot ? i.toString() : `${path}[${i}]`, false, result);
|
|
16
|
+
});
|
|
17
|
+
else if (isPlainObject(data)) for (const key of Object.keys(data)) this.internalSerialize(data[key], isRoot ? key : `${path}[${key}]`, false, result);
|
|
18
|
+
else result.push([path, data]);
|
|
19
|
+
}
|
|
20
|
+
deserialize(serialized) {
|
|
21
|
+
let arrayPushStyles;
|
|
22
|
+
const root = new NullProtoObj();
|
|
23
|
+
let emptySlotsLeft = this.maxDeserializingEmptySlots;
|
|
24
|
+
for (const [path, value] of serialized) {
|
|
25
|
+
const segments = this.parsePath(path);
|
|
26
|
+
let currentRef = root;
|
|
27
|
+
let nextSegment = segments[0];
|
|
28
|
+
for (let i = 1; i < segments.length; i++) {
|
|
29
|
+
const segment = segments[i];
|
|
30
|
+
const isLast = i === segments.length - 1;
|
|
31
|
+
const hasExisting = Object.hasOwn(currentRef, nextSegment);
|
|
32
|
+
const existing = hasExisting ? currentRef[nextSegment] : void 0;
|
|
33
|
+
let child = existing;
|
|
34
|
+
let key = segment;
|
|
35
|
+
if (Array.isArray(child) || !isPlainObject(child)) {
|
|
36
|
+
if (hasExisting && !Array.isArray(child)) child = [child];
|
|
37
|
+
const isArray = Array.isArray(child);
|
|
38
|
+
const isPushStyle = isArray && !!arrayPushStyles?.has(child);
|
|
39
|
+
const length = isArray ? child.length : 0;
|
|
40
|
+
const index = internalToArrayIndex(segment);
|
|
41
|
+
const emptySlots = index === void 0 ? 0 : Math.max(0, index - length);
|
|
42
|
+
if (segment === "" ? isLast && (isPushStyle || length === 0) : index !== void 0 && !(isLast && isPushStyle) && emptySlots <= emptySlotsLeft) {
|
|
43
|
+
emptySlotsLeft -= emptySlots;
|
|
44
|
+
child = isArray ? child : [];
|
|
45
|
+
key = index ?? segment;
|
|
46
|
+
} else if (isArray) {
|
|
47
|
+
arrayPushStyles?.delete(child);
|
|
48
|
+
child = isPushStyle ? internalPushStyleArrayToObject(child) : internalArrayToObject(child);
|
|
49
|
+
} else child = new NullProtoObj();
|
|
50
|
+
}
|
|
51
|
+
if (child !== existing) internalSetOwn(currentRef, nextSegment, child);
|
|
52
|
+
currentRef = child;
|
|
53
|
+
nextSegment = key;
|
|
54
|
+
}
|
|
55
|
+
if (Array.isArray(currentRef) && nextSegment === "") {
|
|
56
|
+
arrayPushStyles ??= /* @__PURE__ */ new WeakSet();
|
|
57
|
+
arrayPushStyles.add(currentRef);
|
|
58
|
+
currentRef.push(value);
|
|
59
|
+
} else if (Object.hasOwn(currentRef, nextSegment)) {
|
|
60
|
+
const current = currentRef[nextSegment];
|
|
61
|
+
if (Array.isArray(current)) current.push(value);
|
|
62
|
+
else internalSetOwn(currentRef, nextSegment, [current, value]);
|
|
63
|
+
} else internalSetOwn(currentRef, nextSegment, value);
|
|
64
|
+
}
|
|
65
|
+
return root;
|
|
66
|
+
}
|
|
67
|
+
stringifyPath(segments) {
|
|
68
|
+
if (segments.length === 0) return "";
|
|
69
|
+
let result = segments[0].toString();
|
|
70
|
+
for (let i = 1; i < segments.length; i++) result += `[${segments[i]}]`;
|
|
71
|
+
return result;
|
|
72
|
+
}
|
|
73
|
+
parsePath(path) {
|
|
74
|
+
const start = path.indexOf("[");
|
|
75
|
+
if (start === -1 || path[path.length - 1] !== "]") return [path];
|
|
76
|
+
const segments = [path.slice(0, start)];
|
|
77
|
+
let from = start + 1;
|
|
78
|
+
let to = path.indexOf("][", from);
|
|
79
|
+
while (to !== -1) {
|
|
80
|
+
segments.push(path.slice(from, to));
|
|
81
|
+
from = to + 2;
|
|
82
|
+
to = path.indexOf("][", from);
|
|
83
|
+
}
|
|
84
|
+
segments.push(path.slice(from, -1));
|
|
85
|
+
return segments;
|
|
86
|
+
}
|
|
87
|
+
};
|
|
88
|
+
/**
|
|
89
|
+
* The largest array index. Larger integer keys are ordinary properties.
|
|
90
|
+
*/
|
|
91
|
+
const MAX_ARRAY_INDEX = 2 ** 32 - 2;
|
|
92
|
+
/**
|
|
93
|
+
* Returns `key` as an array index (no sign, no leading zeros), which is also how engines store the
|
|
94
|
+
* integer keys of objects, or `undefined` if it is not one.
|
|
95
|
+
*/
|
|
96
|
+
function internalToArrayIndex(key) {
|
|
97
|
+
if (key.length === 0 || key.length > 10) return;
|
|
98
|
+
let index = key.charCodeAt(0) - 48;
|
|
99
|
+
if (index < 0 || index > 9 || index === 0 && key.length > 1) return;
|
|
100
|
+
for (let i = 1; i < key.length; i++) {
|
|
101
|
+
const digit = key.charCodeAt(i) - 48;
|
|
102
|
+
if (digit < 0 || digit > 9) return;
|
|
103
|
+
index = index * 10 + digit;
|
|
104
|
+
}
|
|
105
|
+
return index <= MAX_ARRAY_INDEX ? index : void 0;
|
|
106
|
+
}
|
|
107
|
+
function internalArrayToObject(array) {
|
|
108
|
+
const obj = new NullProtoObj();
|
|
109
|
+
array.forEach((item, i) => {
|
|
110
|
+
obj[i] = item;
|
|
111
|
+
});
|
|
112
|
+
return obj;
|
|
113
|
+
}
|
|
114
|
+
function internalPushStyleArrayToObject(array) {
|
|
115
|
+
const obj = new NullProtoObj();
|
|
116
|
+
obj[""] = array.length === 1 ? array[0] : array;
|
|
117
|
+
return obj;
|
|
118
|
+
}
|
|
119
|
+
/**
|
|
120
|
+
* Like `setOwn`, but first switches an object created during deserialization to sparse storage when an
|
|
121
|
+
* integer key would leave a gap. Engines keep integer keys in a flat backing store sized by the largest one,
|
|
122
|
+
* so a lone `{ 999: x }` takes ~12KB in V8. Holding `MAX_ARRAY_INDEX` switches an object to sparse storage
|
|
123
|
+
* for good (V8 and JSC), so writing and deleting it keeps the object's integer keys cheap without a trace.
|
|
124
|
+
*/
|
|
125
|
+
function internalSetOwn(container, key, value) {
|
|
126
|
+
if (typeof key === "string" && container instanceof NullProtoObj) {
|
|
127
|
+
const index = internalToArrayIndex(key);
|
|
128
|
+
if (index !== void 0 && index !== 0 && !Object.hasOwn(container, index - 1) && !Object.hasOwn(container, MAX_ARRAY_INDEX)) {
|
|
129
|
+
container[MAX_ARRAY_INDEX] = void 0;
|
|
130
|
+
delete container[MAX_ARRAY_INDEX];
|
|
131
|
+
}
|
|
132
|
+
}
|
|
133
|
+
setOwn(container, key, value);
|
|
134
|
+
}
|
|
135
|
+
export { BracketNotationSerializer };
|
|
@@ -0,0 +1,24 @@
|
|
|
1
|
+
import { JsonifiedClient } from "./types.js";
|
|
2
|
+
import { RouterContract, RouterContractClient } from "@orpc/contract";
|
|
3
|
+
import { ClientContext, ClientLink, ORPCClientOptions } from "@orpc/client";
|
|
4
|
+
export interface ContractJsonifiedClientFactory<TClientContext extends ClientContext> {
|
|
5
|
+
<T extends RouterContract>(contract: T): JsonifiedClient<RouterContractClient<T, TClientContext>>;
|
|
6
|
+
}
|
|
7
|
+
export interface ContractJsonifiedClientFactoryOptions<TClientContext extends ClientContext> extends Pick<ORPCClientOptions<JsonifiedClient<RouterContractClient<RouterContract, TClientContext>>>, "interceptors" | "scoped"> {
|
|
8
|
+
/**
|
|
9
|
+
* An optional reference to the root router-contract.
|
|
10
|
+
* When provided, the client factory will automatically register the passed contract
|
|
11
|
+
* into the router at the path defined by `meta.path`.
|
|
12
|
+
*/
|
|
13
|
+
contractRef?: RouterContract | undefined;
|
|
14
|
+
}
|
|
15
|
+
/**
|
|
16
|
+
* Like `createContractClientFactory`, but the clients it builds are typed as `JsonifiedClient`,
|
|
17
|
+
* for links that require it, such as OpenAPI Link.
|
|
18
|
+
*
|
|
19
|
+
* @remarks
|
|
20
|
+
* **Warning**: Every procedure contract passed to the factory must define `meta.path` matching its location in the root contract.
|
|
21
|
+
*
|
|
22
|
+
* @see {@link https://orpc.dev/docs/contract/client-factory | Contract Client Factory}
|
|
23
|
+
*/
|
|
24
|
+
export declare function createContractJsonifiedClientFactory<TClientContext extends ClientContext>(link: ClientLink<TClientContext>, options?: ContractJsonifiedClientFactoryOptions<TClientContext>): ContractJsonifiedClientFactory<TClientContext>;
|
|
@@ -0,0 +1,15 @@
|
|
|
1
|
+
import { createContractClientFactory } from "@orpc/contract";
|
|
2
|
+
// src/client-factory.ts
|
|
3
|
+
/**
|
|
4
|
+
* Like `createContractClientFactory`, but the clients it builds are typed as `JsonifiedClient`,
|
|
5
|
+
* for links that require it, such as OpenAPI Link.
|
|
6
|
+
*
|
|
7
|
+
* @remarks
|
|
8
|
+
* **Warning**: Every procedure contract passed to the factory must define `meta.path` matching its location in the root contract.
|
|
9
|
+
*
|
|
10
|
+
* @see {@link https://orpc.dev/docs/contract/client-factory | Contract Client Factory}
|
|
11
|
+
*/
|
|
12
|
+
function createContractJsonifiedClientFactory(link, options = {}) {
|
|
13
|
+
return createContractClientFactory(link, options);
|
|
14
|
+
}
|
|
15
|
+
export { createContractJsonifiedClientFactory };
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
export declare const DEFAULT_OPENAPI_METHOD = "POST";
|