@temporary-name/server 1.9.3-alpha.26612c2cf6a7177d2b500d984d282309d8320ca3 → 1.9.3-alpha.2957dbc009ec31fa21575f028b83c96651cba827
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/dist/adapters/aws-lambda/index.d.mts +3 -5
- package/dist/adapters/aws-lambda/index.d.ts +3 -5
- package/dist/adapters/aws-lambda/index.mjs +3 -3
- package/dist/adapters/fetch/index.d.mts +7 -85
- package/dist/adapters/fetch/index.d.ts +7 -85
- package/dist/adapters/fetch/index.mjs +15 -154
- package/dist/adapters/node/index.d.mts +7 -62
- package/dist/adapters/node/index.d.ts +7 -62
- package/dist/adapters/node/index.mjs +13 -119
- package/dist/adapters/standard/index.d.mts +9 -6
- package/dist/adapters/standard/index.d.ts +9 -6
- package/dist/adapters/standard/index.mjs +4 -4
- package/dist/helpers/index.mjs +3 -29
- package/dist/index.d.mts +72 -195
- package/dist/index.d.ts +72 -195
- package/dist/index.mjs +131 -114
- package/dist/openapi/index.d.mts +10 -27
- package/dist/openapi/index.d.ts +10 -27
- package/dist/openapi/index.mjs +57 -108
- package/dist/shared/{server.CjkiSCui.mjs → server.B7tjiDal.mjs} +73 -115
- package/dist/shared/server.C1RJffw4.mjs +30 -0
- package/dist/shared/server.CQIFwyhc.mjs +40 -0
- package/dist/shared/server.CpS0m3at.mjs +403 -0
- package/dist/shared/server.DPD7R7h_.d.mts +226 -0
- package/dist/shared/server.DPD7R7h_.d.ts +226 -0
- package/dist/shared/server.DfUs5c4R.d.ts +41 -0
- package/dist/shared/server.L8lRAYBR.d.mts +41 -0
- package/package.json +10 -27
- package/dist/plugins/index.d.mts +0 -160
- package/dist/plugins/index.d.ts +0 -160
- package/dist/plugins/index.mjs +0 -288
- package/dist/shared/server.BYnDyuDL.d.mts +0 -23
- package/dist/shared/server.BlJrjUA9.d.mts +0 -56
- package/dist/shared/server.C-tNYmY_.d.ts +0 -56
- package/dist/shared/server.DdHBdcen.mjs +0 -262
- package/dist/shared/server.JI4dqTgD.d.ts +0 -23
- package/dist/shared/server.Kxw442A9.mjs +0 -247
- package/dist/shared/server.WsFQIubj.d.mts +0 -235
- package/dist/shared/server.WsFQIubj.d.ts +0 -235
|
@@ -0,0 +1,403 @@
|
|
|
1
|
+
import { isObject, NullProtoObj, isAsyncIteratorObject, isORPCErrorJson, createORPCErrorFromJson, toORPCError, stringifyJSON, isORPCErrorStatus, tryDecodeURIComponent, toHttpPath, runWithSpan, ORPC_NAME, asyncIteratorWithSpan, setSpanError, ORPCError } from '@temporary-name/shared';
|
|
2
|
+
import { c as createProcedureClient } from './server.B7tjiDal.mjs';
|
|
3
|
+
import { fallbackContractConfig, standardizeHTTPPath } from '@temporary-name/contract';
|
|
4
|
+
import { mapEventIterator, ErrorEvent } from '@temporary-name/standard-server';
|
|
5
|
+
import { j as jsonSerialize } from './server.CQIFwyhc.mjs';
|
|
6
|
+
import { traverseContractProcedures, getLazyMeta, unlazy } from '@temporary-name/server';
|
|
7
|
+
import { createRouter, addRoute, findRoute } from 'rou3';
|
|
8
|
+
|
|
9
|
+
function bracketNotationSerialize(data, segments = [], result = []) {
|
|
10
|
+
if (Array.isArray(data)) {
|
|
11
|
+
data.forEach((item, i) => {
|
|
12
|
+
bracketNotationSerialize(item, [...segments, i], result);
|
|
13
|
+
});
|
|
14
|
+
} else if (isObject(data)) {
|
|
15
|
+
for (const key in data) {
|
|
16
|
+
bracketNotationSerialize(data[key], [...segments, key], result);
|
|
17
|
+
}
|
|
18
|
+
} else {
|
|
19
|
+
result.push([stringifyPath(segments), data]);
|
|
20
|
+
}
|
|
21
|
+
return result;
|
|
22
|
+
}
|
|
23
|
+
function bracketNotationDeserialize(serialized, { maxArrayIndex = 9999 } = {}) {
|
|
24
|
+
if (serialized.length === 0) {
|
|
25
|
+
return {};
|
|
26
|
+
}
|
|
27
|
+
const arrayPushStyles = /* @__PURE__ */ new WeakSet();
|
|
28
|
+
const ref = { value: [] };
|
|
29
|
+
for (const [path, value] of serialized) {
|
|
30
|
+
const segments = parsePath(path);
|
|
31
|
+
let currentRef = ref;
|
|
32
|
+
let nextSegment = "value";
|
|
33
|
+
segments.forEach((segment, i) => {
|
|
34
|
+
if (!Array.isArray(currentRef[nextSegment]) && !isObject(currentRef[nextSegment])) {
|
|
35
|
+
currentRef[nextSegment] = [];
|
|
36
|
+
}
|
|
37
|
+
if (i !== segments.length - 1) {
|
|
38
|
+
if (Array.isArray(currentRef[nextSegment]) && !isValidArrayIndex(segment, maxArrayIndex)) {
|
|
39
|
+
if (arrayPushStyles.has(currentRef[nextSegment])) {
|
|
40
|
+
arrayPushStyles.delete(currentRef[nextSegment]);
|
|
41
|
+
currentRef[nextSegment] = pushStyleArrayToObject(currentRef[nextSegment]);
|
|
42
|
+
} else {
|
|
43
|
+
currentRef[nextSegment] = arrayToObject(currentRef[nextSegment]);
|
|
44
|
+
}
|
|
45
|
+
}
|
|
46
|
+
} else {
|
|
47
|
+
if (Array.isArray(currentRef[nextSegment])) {
|
|
48
|
+
if (segment === "") {
|
|
49
|
+
if (currentRef[nextSegment].length && !arrayPushStyles.has(currentRef[nextSegment])) {
|
|
50
|
+
currentRef[nextSegment] = arrayToObject(currentRef[nextSegment]);
|
|
51
|
+
}
|
|
52
|
+
} else {
|
|
53
|
+
if (arrayPushStyles.has(currentRef[nextSegment])) {
|
|
54
|
+
arrayPushStyles.delete(currentRef[nextSegment]);
|
|
55
|
+
currentRef[nextSegment] = pushStyleArrayToObject(currentRef[nextSegment]);
|
|
56
|
+
} else if (!isValidArrayIndex(segment, maxArrayIndex)) {
|
|
57
|
+
currentRef[nextSegment] = arrayToObject(currentRef[nextSegment]);
|
|
58
|
+
}
|
|
59
|
+
}
|
|
60
|
+
}
|
|
61
|
+
}
|
|
62
|
+
currentRef = currentRef[nextSegment];
|
|
63
|
+
nextSegment = segment;
|
|
64
|
+
});
|
|
65
|
+
if (Array.isArray(currentRef) && nextSegment === "") {
|
|
66
|
+
arrayPushStyles.add(currentRef);
|
|
67
|
+
currentRef.push(value);
|
|
68
|
+
} else if (nextSegment in currentRef) {
|
|
69
|
+
if (Array.isArray(currentRef[nextSegment])) {
|
|
70
|
+
currentRef[nextSegment].push(value);
|
|
71
|
+
} else {
|
|
72
|
+
currentRef[nextSegment] = [currentRef[nextSegment], value];
|
|
73
|
+
}
|
|
74
|
+
} else {
|
|
75
|
+
currentRef[nextSegment] = value;
|
|
76
|
+
}
|
|
77
|
+
}
|
|
78
|
+
return ref.value;
|
|
79
|
+
}
|
|
80
|
+
function stringifyPath(segments) {
|
|
81
|
+
return segments.map((segment) => {
|
|
82
|
+
return segment.toString().replace(/[\\[\]]/g, (match) => {
|
|
83
|
+
switch (match) {
|
|
84
|
+
case "\\":
|
|
85
|
+
return "\\\\";
|
|
86
|
+
case "[":
|
|
87
|
+
return "\\[";
|
|
88
|
+
case "]":
|
|
89
|
+
return "\\]";
|
|
90
|
+
/* v8 ignore next 2 */
|
|
91
|
+
default:
|
|
92
|
+
return match;
|
|
93
|
+
}
|
|
94
|
+
});
|
|
95
|
+
}).reduce((result, segment, i) => {
|
|
96
|
+
if (i === 0) {
|
|
97
|
+
return segment;
|
|
98
|
+
}
|
|
99
|
+
return `${result}[${segment}]`;
|
|
100
|
+
}, "");
|
|
101
|
+
}
|
|
102
|
+
function parsePath(path) {
|
|
103
|
+
const segments = [];
|
|
104
|
+
let inBrackets = false;
|
|
105
|
+
let currentSegment = "";
|
|
106
|
+
let backslashCount = 0;
|
|
107
|
+
for (let i = 0; i < path.length; i++) {
|
|
108
|
+
const char = path[i];
|
|
109
|
+
const nextChar = path[i + 1];
|
|
110
|
+
if (inBrackets && char === "]" && (nextChar === void 0 || nextChar === "[") && backslashCount % 2 === 0) {
|
|
111
|
+
if (nextChar === void 0) {
|
|
112
|
+
inBrackets = false;
|
|
113
|
+
}
|
|
114
|
+
segments.push(currentSegment);
|
|
115
|
+
currentSegment = "";
|
|
116
|
+
i++;
|
|
117
|
+
} else if (segments.length === 0 && char === "[" && backslashCount % 2 === 0) {
|
|
118
|
+
inBrackets = true;
|
|
119
|
+
segments.push(currentSegment);
|
|
120
|
+
currentSegment = "";
|
|
121
|
+
} else if (char === "\\") {
|
|
122
|
+
backslashCount++;
|
|
123
|
+
} else {
|
|
124
|
+
currentSegment += "\\".repeat(backslashCount / 2) + char;
|
|
125
|
+
backslashCount = 0;
|
|
126
|
+
}
|
|
127
|
+
}
|
|
128
|
+
return inBrackets || segments.length === 0 ? [path] : segments;
|
|
129
|
+
}
|
|
130
|
+
function isValidArrayIndex(value, maxIndex) {
|
|
131
|
+
return /^0$|^[1-9]\d*$/.test(value) && Number(value) <= maxIndex;
|
|
132
|
+
}
|
|
133
|
+
function arrayToObject(array) {
|
|
134
|
+
const obj = new NullProtoObj();
|
|
135
|
+
array.forEach((item, i) => {
|
|
136
|
+
obj[i] = item;
|
|
137
|
+
});
|
|
138
|
+
return obj;
|
|
139
|
+
}
|
|
140
|
+
function pushStyleArrayToObject(array) {
|
|
141
|
+
const obj = new NullProtoObj();
|
|
142
|
+
obj[""] = array.length === 1 ? array[0] : array;
|
|
143
|
+
return obj;
|
|
144
|
+
}
|
|
145
|
+
|
|
146
|
+
function serialize(data, options = {}) {
|
|
147
|
+
if (isAsyncIteratorObject(data) && !options.outputFormat) {
|
|
148
|
+
return mapEventIterator(data, {
|
|
149
|
+
value: async (value) => _serialize(value, { outputFormat: "plain" }),
|
|
150
|
+
error: async (e) => {
|
|
151
|
+
return new ErrorEvent({
|
|
152
|
+
data: _serialize(toORPCError(e).toJSON(), { outputFormat: "plain" }),
|
|
153
|
+
cause: e
|
|
154
|
+
});
|
|
155
|
+
}
|
|
156
|
+
});
|
|
157
|
+
}
|
|
158
|
+
return _serialize(data, options);
|
|
159
|
+
}
|
|
160
|
+
function _serialize(data, options) {
|
|
161
|
+
const [json, hasBlob] = jsonSerialize(data);
|
|
162
|
+
if (options.outputFormat === "plain") {
|
|
163
|
+
return json;
|
|
164
|
+
}
|
|
165
|
+
if (options.outputFormat === "URLSearchParams") {
|
|
166
|
+
const params = new URLSearchParams();
|
|
167
|
+
for (const [path, value] of bracketNotationSerialize(json)) {
|
|
168
|
+
if (typeof value === "string" || typeof value === "number" || typeof value === "boolean") {
|
|
169
|
+
params.append(path, value.toString());
|
|
170
|
+
}
|
|
171
|
+
}
|
|
172
|
+
return params;
|
|
173
|
+
}
|
|
174
|
+
if (json instanceof Blob || json === void 0 || !hasBlob) {
|
|
175
|
+
return json;
|
|
176
|
+
}
|
|
177
|
+
const form = new FormData();
|
|
178
|
+
for (const [path, value] of bracketNotationSerialize(json)) {
|
|
179
|
+
if (typeof value === "string" || typeof value === "number" || typeof value === "boolean") {
|
|
180
|
+
form.append(path, value.toString());
|
|
181
|
+
} else if (value instanceof Blob) {
|
|
182
|
+
form.append(path, value);
|
|
183
|
+
}
|
|
184
|
+
}
|
|
185
|
+
return form;
|
|
186
|
+
}
|
|
187
|
+
function deserialize(data) {
|
|
188
|
+
if (data instanceof URLSearchParams || data instanceof FormData) {
|
|
189
|
+
return bracketNotationDeserialize(Array.from(data.entries()));
|
|
190
|
+
}
|
|
191
|
+
if (isAsyncIteratorObject(data)) {
|
|
192
|
+
return mapEventIterator(data, {
|
|
193
|
+
value: async (value) => value,
|
|
194
|
+
error: async (e) => {
|
|
195
|
+
if (e instanceof ErrorEvent && isORPCErrorJson(e.data)) {
|
|
196
|
+
return createORPCErrorFromJson(e.data, { cause: e });
|
|
197
|
+
}
|
|
198
|
+
return e;
|
|
199
|
+
}
|
|
200
|
+
});
|
|
201
|
+
}
|
|
202
|
+
return data;
|
|
203
|
+
}
|
|
204
|
+
|
|
205
|
+
async function decode(request, pathParams) {
|
|
206
|
+
return {
|
|
207
|
+
path: pathParams ?? {},
|
|
208
|
+
query: bracketNotationDeserialize(Array.from(request.url.searchParams.entries())),
|
|
209
|
+
headers: request.headers,
|
|
210
|
+
body: deserialize(await request.body()) ?? {}
|
|
211
|
+
};
|
|
212
|
+
}
|
|
213
|
+
function encode(output, procedure) {
|
|
214
|
+
const successStatus = fallbackContractConfig(
|
|
215
|
+
"defaultSuccessStatus",
|
|
216
|
+
procedure["~orpc"].route.successStatus
|
|
217
|
+
);
|
|
218
|
+
const outputStructure = fallbackContractConfig(
|
|
219
|
+
"defaultOutputStructure",
|
|
220
|
+
procedure["~orpc"].route.outputStructure
|
|
221
|
+
);
|
|
222
|
+
if (outputStructure === "compact") {
|
|
223
|
+
return {
|
|
224
|
+
status: successStatus,
|
|
225
|
+
headers: new Headers(),
|
|
226
|
+
body: serialize(output)
|
|
227
|
+
};
|
|
228
|
+
}
|
|
229
|
+
if (!isDetailedOutput(output)) {
|
|
230
|
+
throw new Error(`
|
|
231
|
+
Invalid "detailed" output structure:
|
|
232
|
+
\u2022 Expected an object with optional properties:
|
|
233
|
+
- status (number 200-399)
|
|
234
|
+
- headers (Record<string, string | string[]>)
|
|
235
|
+
- body (any)
|
|
236
|
+
\u2022 No extra keys allowed.
|
|
237
|
+
|
|
238
|
+
Actual value:
|
|
239
|
+
${stringifyJSON(output)}
|
|
240
|
+
`);
|
|
241
|
+
}
|
|
242
|
+
return {
|
|
243
|
+
status: output.status ?? successStatus,
|
|
244
|
+
headers: output.headers ?? new Headers(),
|
|
245
|
+
body: serialize(output.body)
|
|
246
|
+
};
|
|
247
|
+
}
|
|
248
|
+
function encodeError(error) {
|
|
249
|
+
return {
|
|
250
|
+
status: error.status,
|
|
251
|
+
headers: new Headers(),
|
|
252
|
+
body: serialize(error.toJSON(), { outputFormat: "plain" })
|
|
253
|
+
};
|
|
254
|
+
}
|
|
255
|
+
function isDetailedOutput(output) {
|
|
256
|
+
if (!isObject(output)) {
|
|
257
|
+
return false;
|
|
258
|
+
}
|
|
259
|
+
if (output.headers && !isObject(output.headers)) {
|
|
260
|
+
return false;
|
|
261
|
+
}
|
|
262
|
+
if (output.status !== void 0 && (typeof output.status !== "number" || !Number.isInteger(output.status) || isORPCErrorStatus(output.status))) {
|
|
263
|
+
return false;
|
|
264
|
+
}
|
|
265
|
+
return true;
|
|
266
|
+
}
|
|
267
|
+
|
|
268
|
+
function resolveFriendlyStandardHandleOptions(options) {
|
|
269
|
+
return {
|
|
270
|
+
...options,
|
|
271
|
+
context: options.context ?? {}
|
|
272
|
+
// Context only optional if all fields are optional
|
|
273
|
+
};
|
|
274
|
+
}
|
|
275
|
+
function toRou3Pattern(path) {
|
|
276
|
+
return standardizeHTTPPath(path).replace(/\/\{\+([^}]+)\}/g, "/**:$1").replace(/\/\{([^}]+)\}/g, "/:$1");
|
|
277
|
+
}
|
|
278
|
+
function decodeParams(params) {
|
|
279
|
+
return Object.fromEntries(
|
|
280
|
+
Object.entries(params).map(([key, value]) => [key, tryDecodeURIComponent(value)])
|
|
281
|
+
);
|
|
282
|
+
}
|
|
283
|
+
|
|
284
|
+
class StandardOpenAPIMatcher {
|
|
285
|
+
tree = createRouter();
|
|
286
|
+
pendingRouters = [];
|
|
287
|
+
init(router, path = []) {
|
|
288
|
+
const laziedOptions = traverseContractProcedures({ router, path }, (traverseOptions) => {
|
|
289
|
+
const { path: path2, contract } = traverseOptions;
|
|
290
|
+
const method = fallbackContractConfig("defaultMethod", contract["~orpc"].route.method);
|
|
291
|
+
const httpPath = toRou3Pattern(contract["~orpc"].route.path ?? toHttpPath(path2));
|
|
292
|
+
addRoute(this.tree, method, httpPath, {
|
|
293
|
+
path: path2,
|
|
294
|
+
// cast is safe because router is typed as Router (not ContractRouter)
|
|
295
|
+
procedure: contract,
|
|
296
|
+
router
|
|
297
|
+
});
|
|
298
|
+
});
|
|
299
|
+
this.pendingRouters.push(
|
|
300
|
+
...laziedOptions.map((option) => ({
|
|
301
|
+
...option,
|
|
302
|
+
httpPathPrefix: toHttpPath(option.path),
|
|
303
|
+
laziedPrefix: getLazyMeta(option.router).prefix
|
|
304
|
+
}))
|
|
305
|
+
);
|
|
306
|
+
}
|
|
307
|
+
async match(method, pathname) {
|
|
308
|
+
if (this.pendingRouters.length) {
|
|
309
|
+
const newPendingRouters = [];
|
|
310
|
+
for (const pendingRouter of this.pendingRouters) {
|
|
311
|
+
if (!pendingRouter.laziedPrefix || pathname.startsWith(pendingRouter.laziedPrefix) || pathname.startsWith(pendingRouter.httpPathPrefix)) {
|
|
312
|
+
const { default: router } = await unlazy(pendingRouter.router);
|
|
313
|
+
this.init(router, pendingRouter.path);
|
|
314
|
+
} else {
|
|
315
|
+
newPendingRouters.push(pendingRouter);
|
|
316
|
+
}
|
|
317
|
+
}
|
|
318
|
+
this.pendingRouters = newPendingRouters;
|
|
319
|
+
}
|
|
320
|
+
const match = findRoute(this.tree, method, pathname);
|
|
321
|
+
if (!match) {
|
|
322
|
+
return void 0;
|
|
323
|
+
}
|
|
324
|
+
return {
|
|
325
|
+
path: match.data.path,
|
|
326
|
+
procedure: match.data.procedure,
|
|
327
|
+
params: match.params ? decodeParams(match.params) : void 0
|
|
328
|
+
};
|
|
329
|
+
}
|
|
330
|
+
}
|
|
331
|
+
|
|
332
|
+
class StandardHandler {
|
|
333
|
+
matcher;
|
|
334
|
+
constructor(router, _options) {
|
|
335
|
+
this.matcher = new StandardOpenAPIMatcher();
|
|
336
|
+
this.matcher.init(router);
|
|
337
|
+
}
|
|
338
|
+
async handle(request, options) {
|
|
339
|
+
const prefix = options.prefix?.replace(/\/$/, "") || void 0;
|
|
340
|
+
if (prefix && !request.url.pathname.startsWith(`${prefix}/`) && request.url.pathname !== prefix) {
|
|
341
|
+
return { matched: false, response: void 0 };
|
|
342
|
+
}
|
|
343
|
+
return runWithSpan({ name: `${request.method} ${request.url.pathname}` }, async (span) => {
|
|
344
|
+
let step;
|
|
345
|
+
try {
|
|
346
|
+
const context = options.context;
|
|
347
|
+
const method = request.method;
|
|
348
|
+
const url = request.url;
|
|
349
|
+
const pathname = prefix ? url.pathname.replace(prefix, "") : url.pathname;
|
|
350
|
+
const match = await runWithSpan(
|
|
351
|
+
{ name: "find_procedure" },
|
|
352
|
+
() => this.matcher.match(method, `/${pathname.replace(/^\/|\/$/g, "")}`)
|
|
353
|
+
);
|
|
354
|
+
if (!match) {
|
|
355
|
+
return { matched: false, response: void 0 };
|
|
356
|
+
}
|
|
357
|
+
span?.updateName(`${ORPC_NAME}.${match.path.join("/")}`);
|
|
358
|
+
span?.setAttribute("rpc.system", ORPC_NAME);
|
|
359
|
+
span?.setAttribute("rpc.method", match.path.join("."));
|
|
360
|
+
step = "decode_input";
|
|
361
|
+
const input = await runWithSpan({ name: "decode_input" }, () => decode(request, match.params));
|
|
362
|
+
step = void 0;
|
|
363
|
+
if (isAsyncIteratorObject(input.body)) {
|
|
364
|
+
input.body = asyncIteratorWithSpan(
|
|
365
|
+
{ name: "consume_event_iterator_input", signal: request.signal },
|
|
366
|
+
input.body
|
|
367
|
+
);
|
|
368
|
+
}
|
|
369
|
+
const client = createProcedureClient(match.procedure, {
|
|
370
|
+
context,
|
|
371
|
+
path: match.path
|
|
372
|
+
});
|
|
373
|
+
step = "call_procedure";
|
|
374
|
+
const output = await client(input, {
|
|
375
|
+
request,
|
|
376
|
+
signal: request.signal,
|
|
377
|
+
lastEventId: request.headers.get("last-event-id") ?? void 0
|
|
378
|
+
});
|
|
379
|
+
step = void 0;
|
|
380
|
+
const response = encode(output, match.procedure);
|
|
381
|
+
return {
|
|
382
|
+
matched: true,
|
|
383
|
+
response
|
|
384
|
+
};
|
|
385
|
+
} catch (e) {
|
|
386
|
+
if (step !== "call_procedure") {
|
|
387
|
+
setSpanError(span, e);
|
|
388
|
+
}
|
|
389
|
+
const error = step === "decode_input" && !(e instanceof ORPCError) ? new ORPCError("BAD_REQUEST", {
|
|
390
|
+
message: `Malformed request. Ensure the request body is properly formatted and the 'Content-Type' header is set correctly.`,
|
|
391
|
+
cause: e
|
|
392
|
+
}) : toORPCError(e);
|
|
393
|
+
const response = encodeError(error);
|
|
394
|
+
return {
|
|
395
|
+
matched: true,
|
|
396
|
+
response
|
|
397
|
+
};
|
|
398
|
+
}
|
|
399
|
+
});
|
|
400
|
+
}
|
|
401
|
+
}
|
|
402
|
+
|
|
403
|
+
export { StandardHandler as S, encodeError as a, StandardOpenAPIMatcher as b, decodeParams as c, decode as d, encode as e, resolveFriendlyStandardHandleOptions as r, toRou3Pattern as t };
|
|
@@ -0,0 +1,226 @@
|
|
|
1
|
+
import { Promisable, StandardLazyRequest, HTTPPath } from '@temporary-name/shared';
|
|
2
|
+
import { Meta, Schemas, Route, InferProcedureClientInputs, InferSchemaOutput, EnhanceRouteOptions } from '@temporary-name/contract';
|
|
3
|
+
|
|
4
|
+
type Context = Record<PropertyKey, any>;
|
|
5
|
+
type MergedInitialContext<TInitial extends Context, TAdditional extends Context, TCurrent extends Context> = TInitial & Omit<TAdditional, keyof TCurrent>;
|
|
6
|
+
type MergedCurrentContext<T extends Context, U extends Context> = Omit<T, keyof U> & U;
|
|
7
|
+
type BuildContextWithAuth<TContext extends Context, TAuthContext> = MergedCurrentContext<TContext, {
|
|
8
|
+
auth: TAuthContext | ('auth' extends keyof TContext ? TContext['auth'] : never);
|
|
9
|
+
}>;
|
|
10
|
+
declare function mergeCurrentContext<T extends Context, U extends Context>(context: T, other: U): MergedCurrentContext<T, U>;
|
|
11
|
+
|
|
12
|
+
type MiddlewareResult<TOutContext extends Context, TOutput> = Promisable<{
|
|
13
|
+
output: TOutput;
|
|
14
|
+
context: TOutContext;
|
|
15
|
+
}>;
|
|
16
|
+
interface MiddlewareNextFn<TOutput> {
|
|
17
|
+
<U extends Context = {}>(options?: {
|
|
18
|
+
context?: U;
|
|
19
|
+
}): MiddlewareResult<U, TOutput>;
|
|
20
|
+
}
|
|
21
|
+
interface MiddlewareOutputFn<TOutput> {
|
|
22
|
+
(output: TOutput): MiddlewareResult<Record<never, never>, TOutput>;
|
|
23
|
+
}
|
|
24
|
+
interface MiddlewareOptions<TInContext extends Context, TOutput, TMeta extends Meta> extends ProcedureHandlerOptions<TInContext, TMeta> {
|
|
25
|
+
next: MiddlewareNextFn<TOutput>;
|
|
26
|
+
}
|
|
27
|
+
/**
|
|
28
|
+
* A function that represents a middleware.
|
|
29
|
+
*
|
|
30
|
+
* @see {@link https://orpc.unnoq.com/docs/middleware Middleware Docs}
|
|
31
|
+
*/
|
|
32
|
+
interface Middleware<TInContext extends Context, TOutContext extends Context, TInput, TOutput, TMeta extends Meta> {
|
|
33
|
+
(options: MiddlewareOptions<TInContext, TOutput, TMeta>, input: TInput, output: MiddlewareOutputFn<TOutput>): Promisable<MiddlewareResult<TOutContext, TOutput>>;
|
|
34
|
+
}
|
|
35
|
+
type AnyMiddleware = Middleware<any, any, any, any, any>;
|
|
36
|
+
interface MapInputMiddleware<TInput, TMappedInput> {
|
|
37
|
+
(input: TInput): TMappedInput;
|
|
38
|
+
}
|
|
39
|
+
declare function middlewareOutputFn<TOutput>(output: TOutput): MiddlewareResult<Record<never, never>, TOutput>;
|
|
40
|
+
|
|
41
|
+
type DefaultProcedureHandlerOptions = ProcedureHandlerOptions<Context, Meta>;
|
|
42
|
+
interface ProcedureHandlerOptions<TCurrentContext extends Context, TMeta extends Meta> {
|
|
43
|
+
context: TCurrentContext;
|
|
44
|
+
path: readonly string[];
|
|
45
|
+
procedure: Procedure<Context, Context, Schemas, TMeta>;
|
|
46
|
+
signal?: AbortSignal;
|
|
47
|
+
request?: StandardLazyRequest;
|
|
48
|
+
lastEventId: string | undefined;
|
|
49
|
+
}
|
|
50
|
+
interface ProcedureHandler<TCurrentContext extends Context, TInput extends {
|
|
51
|
+
path: any;
|
|
52
|
+
query: any;
|
|
53
|
+
body: any;
|
|
54
|
+
}, THandlerOutput, TMeta extends Meta> {
|
|
55
|
+
(input: TInput, opt: ProcedureHandlerOptions<TCurrentContext, TMeta>): Promisable<THandlerOutput>;
|
|
56
|
+
}
|
|
57
|
+
interface ContractDef<TInitialContext extends Context, TSchemas extends Schemas, TMeta extends Meta> {
|
|
58
|
+
meta: TMeta;
|
|
59
|
+
route: Route;
|
|
60
|
+
schemas: TSchemas;
|
|
61
|
+
middlewares: readonly Middleware<TInitialContext, any, any, any, any>[];
|
|
62
|
+
authConfigs: TypedAuthConfig[];
|
|
63
|
+
inputValidationIndex: number;
|
|
64
|
+
outputValidationIndex: number;
|
|
65
|
+
}
|
|
66
|
+
type AnyContractDef = ContractDef<Context, Schemas, Meta>;
|
|
67
|
+
declare class Contract<TDef extends AnyContractDef = AnyContractDef> {
|
|
68
|
+
/**
|
|
69
|
+
* This property holds the defined options.
|
|
70
|
+
*/
|
|
71
|
+
'~orpc': TDef;
|
|
72
|
+
constructor(def: TDef);
|
|
73
|
+
}
|
|
74
|
+
interface ProcedureDef<TInitialContext extends Context, TCurrentContext extends Context, TSchemas extends Schemas, TMeta extends Meta> extends ContractDef<TInitialContext, TSchemas, TMeta> {
|
|
75
|
+
handler: ProcedureHandler<TCurrentContext, any, any, any>;
|
|
76
|
+
}
|
|
77
|
+
/**
|
|
78
|
+
* This class represents a procedure.
|
|
79
|
+
*
|
|
80
|
+
* @see {@link https://orpc.unnoq.com/docs/procedure Procedure Docs}
|
|
81
|
+
*/
|
|
82
|
+
declare class Procedure<TInitialContext extends Context, TCurrentContext extends Context, TSchemas extends Schemas, TMeta extends Meta> extends Contract<ProcedureDef<TInitialContext, TCurrentContext, TSchemas, TMeta>> {
|
|
83
|
+
}
|
|
84
|
+
type AnyProcedure = Procedure<any, any, Schemas, any>;
|
|
85
|
+
declare function isProcedure(item: unknown): item is AnyProcedure;
|
|
86
|
+
|
|
87
|
+
type ValidatedAuthContext = {};
|
|
88
|
+
interface BasicAuthConfig<TAuthContext extends ValidatedAuthContext, TCurrentContext extends Context, TMeta extends Meta> {
|
|
89
|
+
tokenPrefix?: string;
|
|
90
|
+
validate: (username: string, password: string, options: ProcedureHandlerOptions<TCurrentContext, TMeta>) => Promisable<TAuthContext>;
|
|
91
|
+
}
|
|
92
|
+
interface TokenAuthConfig<TAuthContext extends ValidatedAuthContext, TCurrentContext extends Context, TMeta extends Meta> {
|
|
93
|
+
tokenPrefix?: string;
|
|
94
|
+
validate: (token: string, options: ProcedureHandlerOptions<TCurrentContext, TMeta>) => Promisable<TAuthContext>;
|
|
95
|
+
}
|
|
96
|
+
interface NamedTokenAuthConfig<TAuthContext extends ValidatedAuthContext, TCurrentContext extends Context, TMeta extends Meta> extends TokenAuthConfig<TAuthContext, TCurrentContext, TMeta> {
|
|
97
|
+
name: string;
|
|
98
|
+
}
|
|
99
|
+
type AuthType = 'header' | 'query' | 'cookie' | 'bearer' | 'basic' | 'none';
|
|
100
|
+
type AuthConfig<TAuthType extends AuthType, TAuthContext extends ValidatedAuthContext = ValidatedAuthContext, TCurrentContext extends Context = Context, TMeta extends Meta = Meta> = TAuthType extends 'basic' ? BasicAuthConfig<TAuthContext, TCurrentContext, TMeta> : TAuthType extends 'bearer' ? TokenAuthConfig<TAuthContext, TCurrentContext, TMeta> : TAuthType extends 'header' ? NamedTokenAuthConfig<TAuthContext, TCurrentContext, TMeta> : TAuthType extends 'query' ? NamedTokenAuthConfig<TAuthContext, TCurrentContext, TMeta> : TAuthType extends 'cookie' ? NamedTokenAuthConfig<TAuthContext, TCurrentContext, TMeta> : TAuthType extends 'none' ? {} : never;
|
|
101
|
+
type TypedAuthConfig<TAuthType extends AuthType = AuthType> = {
|
|
102
|
+
type: TAuthType;
|
|
103
|
+
} & AuthConfig<TAuthType, object>;
|
|
104
|
+
|
|
105
|
+
type ContractRouter = Contract | {
|
|
106
|
+
[k: string]: ContractRouter;
|
|
107
|
+
};
|
|
108
|
+
/**
|
|
109
|
+
* Represents a router, which defines a hierarchical structure of procedures.
|
|
110
|
+
*
|
|
111
|
+
* @info A procedure is a router too.
|
|
112
|
+
* @see {@link https://orpc.unnoq.com/docs/contract-first/define-contract#contract-router Contract Router Docs}
|
|
113
|
+
*/
|
|
114
|
+
type Router<TInitialContext extends Context> = Procedure<TInitialContext, any, any, any> | {
|
|
115
|
+
[k: string]: Lazyable<Router<TInitialContext>>;
|
|
116
|
+
};
|
|
117
|
+
type AnyRouter = Router<any>;
|
|
118
|
+
type InferRouterInitialContext<T extends AnyRouter> = T extends Router<infer UInitialContext> ? UInitialContext : never;
|
|
119
|
+
/**
|
|
120
|
+
* Infer all initial context of the router.
|
|
121
|
+
*
|
|
122
|
+
* @info A procedure is a router too.
|
|
123
|
+
* @see {@link https://orpc.unnoq.com/docs/router#utilities Router Utilities Docs}
|
|
124
|
+
*/
|
|
125
|
+
type InferRouterInitialContexts<T extends AnyRouter> = T extends Procedure<infer UInitialContext, any, any, any> ? UInitialContext : {
|
|
126
|
+
[K in keyof T]: T[K] extends Lazyable<infer U extends AnyRouter> ? InferRouterInitialContexts<U> : never;
|
|
127
|
+
};
|
|
128
|
+
/**
|
|
129
|
+
* Infer all current context of the router.
|
|
130
|
+
*
|
|
131
|
+
* @info A procedure is a router too.
|
|
132
|
+
* @see {@link https://orpc.unnoq.com/docs/router#utilities Router Utilities Docs}
|
|
133
|
+
*/
|
|
134
|
+
type InferRouterCurrentContexts<T extends AnyRouter> = T extends Procedure<any, infer UCurrentContext, any, any> ? UCurrentContext : {
|
|
135
|
+
[K in keyof T]: T[K] extends Lazyable<infer U extends AnyRouter> ? InferRouterCurrentContexts<U> : never;
|
|
136
|
+
};
|
|
137
|
+
/**
|
|
138
|
+
* Infer all router inputs
|
|
139
|
+
*
|
|
140
|
+
* @info A procedure is a router too.
|
|
141
|
+
* @see {@link https://orpc.unnoq.com/docs/router#utilities Router Utilities Docs}
|
|
142
|
+
*/
|
|
143
|
+
type InferRouterInputs<T extends AnyRouter> = T extends Procedure<any, any, infer USchemas, any> ? InferProcedureClientInputs<USchemas> : {
|
|
144
|
+
[K in keyof T]: T[K] extends Lazyable<infer U extends AnyRouter> ? InferRouterInputs<U> : never;
|
|
145
|
+
};
|
|
146
|
+
/**
|
|
147
|
+
* Infer all router outputs
|
|
148
|
+
*
|
|
149
|
+
* @info A procedure is a router too.
|
|
150
|
+
* @see {@link https://orpc.unnoq.com/docs/router#utilities Router Utilities Docs}
|
|
151
|
+
*/
|
|
152
|
+
type InferRouterOutputs<T extends AnyRouter> = T extends Procedure<any, any, infer USchemas, any> ? InferSchemaOutput<USchemas['outputSchema']> : {
|
|
153
|
+
[K in keyof T]: T[K] extends Lazyable<infer U extends AnyRouter> ? InferRouterOutputs<U> : never;
|
|
154
|
+
};
|
|
155
|
+
|
|
156
|
+
declare function getRouter<T extends Lazyable<AnyRouter | undefined>>(router: T, path: readonly string[]): T extends Lazy<any> ? Lazy<AnyRouter | undefined> : Lazyable<AnyRouter | undefined>;
|
|
157
|
+
type AccessibleLazyRouter<T extends Lazyable<AnyRouter | undefined>> = T extends Lazy<infer U extends AnyRouter | undefined | Lazy<AnyRouter | undefined>> ? AccessibleLazyRouter<U> : T extends AnyProcedure | undefined ? Lazy<T> : Lazy<T> & {
|
|
158
|
+
[K in keyof T]: T[K] extends Lazyable<AnyRouter> ? AccessibleLazyRouter<T[K]> : never;
|
|
159
|
+
};
|
|
160
|
+
declare function createAccessibleLazyRouter<T extends Lazy<AnyRouter | undefined>>(lazied: T): AccessibleLazyRouter<T>;
|
|
161
|
+
type EnhancedRouter<T extends Lazyable<AnyRouter>, TInitialContext extends Context, TCurrentContext extends Context> = T extends Lazy<infer U extends AnyRouter> ? AccessibleLazyRouter<EnhancedRouter<U, TInitialContext, TCurrentContext>> : T extends Procedure<infer UInitialContext, infer UCurrentContext, infer USchemas, infer UMeta> ? Procedure<MergedInitialContext<TInitialContext, UInitialContext, TCurrentContext>, UCurrentContext, USchemas, UMeta> : {
|
|
162
|
+
[K in keyof T]: T[K] extends Lazyable<AnyRouter> ? EnhancedRouter<T[K], TInitialContext, TCurrentContext> : never;
|
|
163
|
+
};
|
|
164
|
+
interface EnhanceRouterOptions extends EnhanceRouteOptions {
|
|
165
|
+
middlewares: readonly AnyMiddleware[];
|
|
166
|
+
dedupeLeadingMiddlewares: boolean;
|
|
167
|
+
}
|
|
168
|
+
declare function enhanceRouter<T extends Lazyable<AnyRouter>, TInitialContext extends Context, TCurrentContext extends Context>(router: T, options: EnhanceRouterOptions): EnhancedRouter<T, TInitialContext, TCurrentContext>;
|
|
169
|
+
interface TraverseContractProceduresOptions {
|
|
170
|
+
router: ContractRouter | AnyRouter;
|
|
171
|
+
path: readonly string[];
|
|
172
|
+
}
|
|
173
|
+
interface TraverseContractProcedureCallbackOptions {
|
|
174
|
+
contract: Contract;
|
|
175
|
+
path: readonly string[];
|
|
176
|
+
}
|
|
177
|
+
/**
|
|
178
|
+
* @deprecated Use `TraverseContractProcedureCallbackOptions` instead.
|
|
179
|
+
*/
|
|
180
|
+
type ContractProcedureCallbackOptions = TraverseContractProcedureCallbackOptions;
|
|
181
|
+
interface LazyTraverseContractProceduresOptions {
|
|
182
|
+
router: Lazy<AnyRouter>;
|
|
183
|
+
path: readonly string[];
|
|
184
|
+
}
|
|
185
|
+
declare function traverseContractProcedures(options: TraverseContractProceduresOptions, callback: (options: TraverseContractProcedureCallbackOptions) => void, lazyOptions?: LazyTraverseContractProceduresOptions[]): LazyTraverseContractProceduresOptions[];
|
|
186
|
+
declare function resolveContractProcedures(options: TraverseContractProceduresOptions, callback: (options: TraverseContractProcedureCallbackOptions) => void): Promise<void>;
|
|
187
|
+
type UnlaziedRouter<T extends AnyRouter> = T extends AnyProcedure ? T : {
|
|
188
|
+
[K in keyof T]: T[K] extends Lazyable<infer U extends AnyRouter> ? UnlaziedRouter<U> : never;
|
|
189
|
+
};
|
|
190
|
+
declare function unlazyRouter<T extends AnyRouter>(router: T): Promise<UnlaziedRouter<T>>;
|
|
191
|
+
|
|
192
|
+
declare const LAZY_SYMBOL: unique symbol;
|
|
193
|
+
interface LazyMeta {
|
|
194
|
+
prefix?: HTTPPath;
|
|
195
|
+
}
|
|
196
|
+
interface Lazy<T> {
|
|
197
|
+
[LAZY_SYMBOL]: {
|
|
198
|
+
loader: () => Promise<{
|
|
199
|
+
default: T;
|
|
200
|
+
}>;
|
|
201
|
+
meta: LazyMeta;
|
|
202
|
+
};
|
|
203
|
+
}
|
|
204
|
+
type Lazyable<T> = T | Lazy<T>;
|
|
205
|
+
/**
|
|
206
|
+
* @internal
|
|
207
|
+
*/
|
|
208
|
+
declare function lazyInternal<T>(loader: () => Promise<{
|
|
209
|
+
default: T;
|
|
210
|
+
}>, meta?: LazyMeta): Lazy<T>;
|
|
211
|
+
/**
|
|
212
|
+
* Creates a lazy-loaded item.
|
|
213
|
+
*
|
|
214
|
+
* @warning The `prefix` in `meta` only holds metadata and does not apply the prefix to the lazy router, use `os.prefix(...).lazyRoute(...)` instead.
|
|
215
|
+
*/
|
|
216
|
+
declare function lazy<T extends Router<any>>(prefix: HTTPPath, loader: () => Promise<{
|
|
217
|
+
default: T;
|
|
218
|
+
}>): EnhancedRouter<Lazy<T>, {}, {}>;
|
|
219
|
+
declare function isLazy(item: unknown): item is Lazy<any>;
|
|
220
|
+
declare function getLazyMeta(lazied: Lazy<any>): LazyMeta;
|
|
221
|
+
declare function unlazy<T extends Lazyable<any>>(lazied: T): Promise<{
|
|
222
|
+
default: T extends Lazy<infer U> ? U : T;
|
|
223
|
+
}>;
|
|
224
|
+
|
|
225
|
+
export { traverseContractProcedures as $, isProcedure as H, Procedure as P, getRouter as S, createAccessibleLazyRouter as U, enhanceRouter as W, Contract as a, resolveContractProcedures as a0, unlazyRouter as a2, mergeCurrentContext as m, LAZY_SYMBOL as n, lazyInternal as p, lazy as q, isLazy as r, getLazyMeta as s, unlazy as u, middlewareOutputFn as y };
|
|
226
|
+
export type { AuthType as A, BuildContextWithAuth as B, Context as C, DefaultProcedureHandlerOptions as D, EnhanceRouterOptions as E, AnyContractDef as F, ProcedureDef as G, InferRouterInitialContext as I, ContractRouter as J, InferRouterInitialContexts as K, Lazyable as L, Middleware as M, InferRouterCurrentContexts as N, InferRouterInputs as O, InferRouterOutputs as Q, Router as R, AccessibleLazyRouter as T, ValidatedAuthContext as V, TraverseContractProceduresOptions as X, TraverseContractProcedureCallbackOptions as Y, ContractProcedureCallbackOptions as Z, LazyTraverseContractProceduresOptions as _, UnlaziedRouter as a1, MergedInitialContext as b, MergedCurrentContext as c, AuthConfig as d, ProcedureHandler as e, EnhancedRouter as f, MapInputMiddleware as g, ContractDef as h, AnyMiddleware as i, Lazy as j, AnyProcedure as k, AnyRouter as l, LazyMeta as o, MiddlewareResult as t, MiddlewareNextFn as v, MiddlewareOutputFn as w, MiddlewareOptions as x, ProcedureHandlerOptions as z };
|