@temporary-name/server 1.9.3-alpha.03e17aa3340f4b261a549bf9e3fe948b084e2309
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/LICENSE +21 -0
- package/README.md +31 -0
- package/dist/adapters/aws-lambda/index.d.mts +30 -0
- package/dist/adapters/aws-lambda/index.d.ts +30 -0
- package/dist/adapters/aws-lambda/index.mjs +33 -0
- package/dist/adapters/fetch/index.d.mts +108 -0
- package/dist/adapters/fetch/index.d.ts +108 -0
- package/dist/adapters/fetch/index.mjs +174 -0
- package/dist/adapters/node/index.d.mts +83 -0
- package/dist/adapters/node/index.d.ts +83 -0
- package/dist/adapters/node/index.mjs +139 -0
- package/dist/adapters/standard/index.d.mts +42 -0
- package/dist/adapters/standard/index.d.ts +42 -0
- package/dist/adapters/standard/index.mjs +11 -0
- package/dist/helpers/index.d.mts +149 -0
- package/dist/helpers/index.d.ts +149 -0
- package/dist/helpers/index.mjs +168 -0
- package/dist/index.d.mts +603 -0
- package/dist/index.d.ts +603 -0
- package/dist/index.mjs +617 -0
- package/dist/openapi/index.d.mts +220 -0
- package/dist/openapi/index.d.ts +220 -0
- package/dist/openapi/index.mjs +776 -0
- package/dist/plugins/index.d.mts +160 -0
- package/dist/plugins/index.d.ts +160 -0
- package/dist/plugins/index.mjs +288 -0
- package/dist/shared/server.BEHw7Eyx.mjs +247 -0
- package/dist/shared/server.BKSOrA6h.d.mts +192 -0
- package/dist/shared/server.BKSOrA6h.d.ts +192 -0
- package/dist/shared/server.BKh8I1Ny.mjs +239 -0
- package/dist/shared/server.BeuTpcmO.d.mts +23 -0
- package/dist/shared/server.C1fnTLq0.d.mts +57 -0
- package/dist/shared/server.CQyYNJ1H.d.ts +57 -0
- package/dist/shared/server.DLsti1Pv.mjs +293 -0
- package/dist/shared/server.SLLuK6_v.d.ts +23 -0
- package/package.json +95 -0
|
@@ -0,0 +1,239 @@
|
|
|
1
|
+
import { validateORPCError, ValidationError } from '@temporary-name/contract';
|
|
2
|
+
import { resolveMaybeOptionalOptions, ORPCError, toArray, value, runWithSpan, intercept, isAsyncIteratorObject, overlayProxy, asyncIteratorWithSpan } from '@temporary-name/shared';
|
|
3
|
+
import { HibernationEventIterator, mapEventIterator } from '@temporary-name/standard-server';
|
|
4
|
+
import { AsyncLocalStorage } from 'node:async_hooks';
|
|
5
|
+
import 'zod';
|
|
6
|
+
import * as z4 from 'zod/v4/core';
|
|
7
|
+
|
|
8
|
+
const gatingContext = new AsyncLocalStorage();
|
|
9
|
+
function withoutGatedFields(data, schema, isGateEnabled) {
|
|
10
|
+
const filtered = { ...data };
|
|
11
|
+
const gatedFields = getGatedFields(schema);
|
|
12
|
+
for (const [fieldName, gate] of gatedFields) {
|
|
13
|
+
if (!isGateEnabled(gate)) {
|
|
14
|
+
delete filtered[fieldName];
|
|
15
|
+
}
|
|
16
|
+
}
|
|
17
|
+
return filtered;
|
|
18
|
+
}
|
|
19
|
+
function getGatedFields(schema) {
|
|
20
|
+
if (!schema || schema["~standard"].vendor !== "zod") {
|
|
21
|
+
return [];
|
|
22
|
+
}
|
|
23
|
+
const gatedFields = [];
|
|
24
|
+
const zodDef = schema._zod.def;
|
|
25
|
+
if (zodDef.type === "object") {
|
|
26
|
+
const shape = zodDef.shape;
|
|
27
|
+
for (const fieldName in shape) {
|
|
28
|
+
const fieldSchema = shape[fieldName];
|
|
29
|
+
const gate = z4.globalRegistry.get(fieldSchema)?.gate;
|
|
30
|
+
if (gate) {
|
|
31
|
+
gatedFields.push([fieldName, gate]);
|
|
32
|
+
}
|
|
33
|
+
}
|
|
34
|
+
}
|
|
35
|
+
return gatedFields;
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
const LAZY_SYMBOL = Symbol("ORPC_LAZY_SYMBOL");
|
|
39
|
+
function lazy(loader, meta = {}) {
|
|
40
|
+
return {
|
|
41
|
+
[LAZY_SYMBOL]: {
|
|
42
|
+
loader,
|
|
43
|
+
meta
|
|
44
|
+
}
|
|
45
|
+
};
|
|
46
|
+
}
|
|
47
|
+
function isLazy(item) {
|
|
48
|
+
return (typeof item === "object" || typeof item === "function") && item !== null && LAZY_SYMBOL in item;
|
|
49
|
+
}
|
|
50
|
+
function getLazyMeta(lazied) {
|
|
51
|
+
return lazied[LAZY_SYMBOL].meta;
|
|
52
|
+
}
|
|
53
|
+
function unlazy(lazied) {
|
|
54
|
+
return isLazy(lazied) ? lazied[LAZY_SYMBOL].loader() : Promise.resolve({ default: lazied });
|
|
55
|
+
}
|
|
56
|
+
|
|
57
|
+
function mergeCurrentContext(context, other) {
|
|
58
|
+
return { ...context, ...other };
|
|
59
|
+
}
|
|
60
|
+
|
|
61
|
+
function createORPCErrorConstructorMap(errors) {
|
|
62
|
+
const proxy = new Proxy(errors, {
|
|
63
|
+
get(target, code) {
|
|
64
|
+
if (typeof code !== "string") {
|
|
65
|
+
return Reflect.get(target, code);
|
|
66
|
+
}
|
|
67
|
+
const item = (...rest) => {
|
|
68
|
+
const options = resolveMaybeOptionalOptions(rest);
|
|
69
|
+
const config = errors[code];
|
|
70
|
+
return new ORPCError(code, {
|
|
71
|
+
defined: Boolean(config),
|
|
72
|
+
status: config?.status,
|
|
73
|
+
message: options.message ?? config?.message,
|
|
74
|
+
data: options.data,
|
|
75
|
+
cause: options.cause
|
|
76
|
+
});
|
|
77
|
+
};
|
|
78
|
+
return item;
|
|
79
|
+
}
|
|
80
|
+
});
|
|
81
|
+
return proxy;
|
|
82
|
+
}
|
|
83
|
+
|
|
84
|
+
function middlewareOutputFn(output) {
|
|
85
|
+
return { output, context: {} };
|
|
86
|
+
}
|
|
87
|
+
|
|
88
|
+
function createProcedureClient(lazyableProcedure, ...rest) {
|
|
89
|
+
const options = resolveMaybeOptionalOptions(rest);
|
|
90
|
+
return async (...[input, callerOptions]) => {
|
|
91
|
+
const path = toArray(options.path);
|
|
92
|
+
const { default: procedure } = await unlazy(lazyableProcedure);
|
|
93
|
+
const clientContext = callerOptions?.context ?? {};
|
|
94
|
+
const context = await value(options.context ?? {}, clientContext);
|
|
95
|
+
const errors = createORPCErrorConstructorMap(procedure["~orpc"].errorMap);
|
|
96
|
+
const validateError = async (e) => {
|
|
97
|
+
if (e instanceof ORPCError) {
|
|
98
|
+
return await validateORPCError(procedure["~orpc"].errorMap, e);
|
|
99
|
+
}
|
|
100
|
+
return e;
|
|
101
|
+
};
|
|
102
|
+
try {
|
|
103
|
+
const output = await runWithSpan({ name: "call_procedure", signal: callerOptions?.signal }, (span) => {
|
|
104
|
+
span?.setAttribute("procedure.path", [...path]);
|
|
105
|
+
return intercept(
|
|
106
|
+
toArray(options.interceptors),
|
|
107
|
+
{
|
|
108
|
+
context,
|
|
109
|
+
input,
|
|
110
|
+
// input only optional when it undefinable so we can safely cast it
|
|
111
|
+
errors,
|
|
112
|
+
path,
|
|
113
|
+
procedure,
|
|
114
|
+
signal: callerOptions?.signal,
|
|
115
|
+
lastEventId: callerOptions?.lastEventId
|
|
116
|
+
},
|
|
117
|
+
(interceptorOptions) => executeProcedureInternal(interceptorOptions.procedure, interceptorOptions)
|
|
118
|
+
);
|
|
119
|
+
});
|
|
120
|
+
if (isAsyncIteratorObject(output)) {
|
|
121
|
+
if (output instanceof HibernationEventIterator) {
|
|
122
|
+
return output;
|
|
123
|
+
}
|
|
124
|
+
return overlayProxy(
|
|
125
|
+
output,
|
|
126
|
+
mapEventIterator(
|
|
127
|
+
asyncIteratorWithSpan(
|
|
128
|
+
{ name: "consume_event_iterator_output", signal: callerOptions?.signal },
|
|
129
|
+
output
|
|
130
|
+
),
|
|
131
|
+
{
|
|
132
|
+
value: (v) => v,
|
|
133
|
+
error: (e) => validateError(e)
|
|
134
|
+
}
|
|
135
|
+
)
|
|
136
|
+
);
|
|
137
|
+
}
|
|
138
|
+
return output;
|
|
139
|
+
} catch (e) {
|
|
140
|
+
throw await validateError(e);
|
|
141
|
+
}
|
|
142
|
+
};
|
|
143
|
+
}
|
|
144
|
+
async function validateInput(procedure, input) {
|
|
145
|
+
const schema = procedure["~orpc"].inputSchema;
|
|
146
|
+
if (!schema) {
|
|
147
|
+
return input;
|
|
148
|
+
}
|
|
149
|
+
return runWithSpan({ name: "validate_input" }, async () => {
|
|
150
|
+
const result = await schema["~standard"].validate(input);
|
|
151
|
+
if (result.issues) {
|
|
152
|
+
throw new ORPCError("BAD_REQUEST", {
|
|
153
|
+
message: "Input validation failed",
|
|
154
|
+
data: {
|
|
155
|
+
issues: result.issues
|
|
156
|
+
},
|
|
157
|
+
cause: new ValidationError({
|
|
158
|
+
message: "Input validation failed",
|
|
159
|
+
issues: result.issues,
|
|
160
|
+
data: input
|
|
161
|
+
})
|
|
162
|
+
});
|
|
163
|
+
}
|
|
164
|
+
return result.value;
|
|
165
|
+
});
|
|
166
|
+
}
|
|
167
|
+
async function validateOutput(schema, output) {
|
|
168
|
+
return runWithSpan({ name: "validate_output" }, async () => {
|
|
169
|
+
const result = await schema["~standard"].validate(output);
|
|
170
|
+
if (result.issues) {
|
|
171
|
+
throw new ORPCError("INTERNAL_SERVER_ERROR", {
|
|
172
|
+
message: "Output validation failed",
|
|
173
|
+
cause: new ValidationError({
|
|
174
|
+
message: "Output validation failed",
|
|
175
|
+
issues: result.issues,
|
|
176
|
+
data: output
|
|
177
|
+
})
|
|
178
|
+
});
|
|
179
|
+
}
|
|
180
|
+
return result.value;
|
|
181
|
+
});
|
|
182
|
+
}
|
|
183
|
+
async function executeProcedureInternal(procedure, options) {
|
|
184
|
+
const middlewares = procedure["~orpc"].middlewares;
|
|
185
|
+
const inputValidationIndex = Math.min(
|
|
186
|
+
Math.max(0, procedure["~orpc"].inputValidationIndex),
|
|
187
|
+
middlewares.length
|
|
188
|
+
);
|
|
189
|
+
const outputValidationIndex = Math.min(
|
|
190
|
+
Math.max(0, procedure["~orpc"].outputValidationIndex),
|
|
191
|
+
middlewares.length
|
|
192
|
+
);
|
|
193
|
+
const next = async (index, context, input) => {
|
|
194
|
+
let currentInput = input;
|
|
195
|
+
if (index === inputValidationIndex) {
|
|
196
|
+
currentInput = await validateInput(procedure, currentInput);
|
|
197
|
+
}
|
|
198
|
+
const mid = middlewares[index];
|
|
199
|
+
const output = mid ? await runWithSpan({ name: `middleware.${mid.name}`, signal: options.signal }, async (span) => {
|
|
200
|
+
span?.setAttribute("middleware.index", index);
|
|
201
|
+
span?.setAttribute("middleware.name", mid.name);
|
|
202
|
+
const result = await mid(
|
|
203
|
+
{
|
|
204
|
+
...options,
|
|
205
|
+
context,
|
|
206
|
+
next: async (...[nextOptions]) => {
|
|
207
|
+
const nextContext = nextOptions?.context ?? {};
|
|
208
|
+
return {
|
|
209
|
+
output: await next(index + 1, mergeCurrentContext(context, nextContext), currentInput),
|
|
210
|
+
context: nextContext
|
|
211
|
+
};
|
|
212
|
+
}
|
|
213
|
+
},
|
|
214
|
+
currentInput,
|
|
215
|
+
middlewareOutputFn
|
|
216
|
+
);
|
|
217
|
+
return result.output;
|
|
218
|
+
}) : await runWithSpan(
|
|
219
|
+
{ name: "handler", signal: options.signal },
|
|
220
|
+
() => procedure["~orpc"].handler({ ...options, context, input: currentInput })
|
|
221
|
+
);
|
|
222
|
+
if (index === outputValidationIndex) {
|
|
223
|
+
const schema = procedure["~orpc"].outputSchema;
|
|
224
|
+
if (!schema) {
|
|
225
|
+
return output;
|
|
226
|
+
}
|
|
227
|
+
const validated = await validateOutput(schema, output);
|
|
228
|
+
const isGateEnabled = gatingContext.getStore();
|
|
229
|
+
if (!validated || !isGateEnabled) {
|
|
230
|
+
return validated;
|
|
231
|
+
}
|
|
232
|
+
return withoutGatedFields(validated, schema, isGateEnabled);
|
|
233
|
+
}
|
|
234
|
+
return output;
|
|
235
|
+
};
|
|
236
|
+
return next(0, options.context, options.input);
|
|
237
|
+
}
|
|
238
|
+
|
|
239
|
+
export { LAZY_SYMBOL as L, gatingContext as a, createORPCErrorConstructorMap as b, createProcedureClient as c, middlewareOutputFn as d, getLazyMeta as g, isLazy as i, lazy as l, mergeCurrentContext as m, unlazy as u };
|
|
@@ -0,0 +1,23 @@
|
|
|
1
|
+
import { HTTPPath } from '@temporary-name/shared';
|
|
2
|
+
import { C as Context } from './server.BKSOrA6h.mjs';
|
|
3
|
+
import { c as StandardHandleOptions } from './server.C1fnTLq0.mjs';
|
|
4
|
+
|
|
5
|
+
type FriendlyStandardHandleOptions<T extends Context> = Omit<StandardHandleOptions<T>, 'context'> & (Record<never, never> extends T ? {
|
|
6
|
+
context?: T;
|
|
7
|
+
} : {
|
|
8
|
+
context: T;
|
|
9
|
+
});
|
|
10
|
+
declare function resolveFriendlyStandardHandleOptions<T extends Context>(options: FriendlyStandardHandleOptions<T>): StandardHandleOptions<T>;
|
|
11
|
+
/**
|
|
12
|
+
* {@link https://github.com/unjs/rou3}
|
|
13
|
+
*
|
|
14
|
+
* @internal
|
|
15
|
+
*/
|
|
16
|
+
declare function toRou3Pattern(path: HTTPPath): string;
|
|
17
|
+
/**
|
|
18
|
+
* @internal
|
|
19
|
+
*/
|
|
20
|
+
declare function decodeParams(params: Record<string, string>): Record<string, string>;
|
|
21
|
+
|
|
22
|
+
export { decodeParams as d, resolveFriendlyStandardHandleOptions as r, toRou3Pattern as t };
|
|
23
|
+
export type { FriendlyStandardHandleOptions as F };
|
|
@@ -0,0 +1,57 @@
|
|
|
1
|
+
import { Meta } from '@temporary-name/contract';
|
|
2
|
+
import { HTTPPath, Interceptor } from '@temporary-name/shared';
|
|
3
|
+
import { StandardLazyRequest, StandardResponse } from '@temporary-name/standard-server';
|
|
4
|
+
import { C as Context, R as Router, E as ProcedureClientInterceptorOptions } from './server.BKSOrA6h.mjs';
|
|
5
|
+
|
|
6
|
+
interface StandardHandlerPlugin<T extends Context> {
|
|
7
|
+
order?: number;
|
|
8
|
+
init?(options: StandardHandlerOptions<T>, router: Router<any, T>): void;
|
|
9
|
+
}
|
|
10
|
+
declare class CompositeStandardHandlerPlugin<T extends Context, TPlugin extends StandardHandlerPlugin<T>> implements StandardHandlerPlugin<T> {
|
|
11
|
+
protected readonly plugins: TPlugin[];
|
|
12
|
+
constructor(plugins?: readonly TPlugin[]);
|
|
13
|
+
init(options: StandardHandlerOptions<T>, router: Router<any, T>): void;
|
|
14
|
+
}
|
|
15
|
+
|
|
16
|
+
interface StandardHandleOptions<T extends Context> {
|
|
17
|
+
prefix?: HTTPPath;
|
|
18
|
+
context: T;
|
|
19
|
+
}
|
|
20
|
+
type StandardHandleResult = {
|
|
21
|
+
matched: true;
|
|
22
|
+
response: StandardResponse;
|
|
23
|
+
} | {
|
|
24
|
+
matched: false;
|
|
25
|
+
response: undefined;
|
|
26
|
+
};
|
|
27
|
+
interface StandardHandlerInterceptorOptions<T extends Context> extends StandardHandleOptions<T> {
|
|
28
|
+
request: StandardLazyRequest;
|
|
29
|
+
}
|
|
30
|
+
interface StandardHandlerOptions<TContext extends Context> {
|
|
31
|
+
plugins?: StandardHandlerPlugin<TContext>[];
|
|
32
|
+
/**
|
|
33
|
+
* Interceptors at the request level, helpful when you want catch errors
|
|
34
|
+
*/
|
|
35
|
+
interceptors?: Interceptor<StandardHandlerInterceptorOptions<TContext>, Promise<StandardHandleResult>>[];
|
|
36
|
+
/**
|
|
37
|
+
* Interceptors at the root level, helpful when you want override the request/response
|
|
38
|
+
*/
|
|
39
|
+
rootInterceptors?: Interceptor<StandardHandlerInterceptorOptions<TContext>, Promise<StandardHandleResult>>[];
|
|
40
|
+
/**
|
|
41
|
+
*
|
|
42
|
+
* Interceptors for procedure client.
|
|
43
|
+
*/
|
|
44
|
+
clientInterceptors?: Interceptor<ProcedureClientInterceptorOptions<TContext, Record<never, never>, Meta>, Promise<unknown>>[];
|
|
45
|
+
}
|
|
46
|
+
declare class StandardHandler<T extends Context> {
|
|
47
|
+
private readonly interceptors;
|
|
48
|
+
private readonly clientInterceptors;
|
|
49
|
+
private readonly rootInterceptors;
|
|
50
|
+
private readonly matcher;
|
|
51
|
+
private readonly codec;
|
|
52
|
+
constructor(router: Router<any, T>, options: NoInfer<StandardHandlerOptions<T>>);
|
|
53
|
+
handle(request: StandardLazyRequest, options: StandardHandleOptions<T>): Promise<StandardHandleResult>;
|
|
54
|
+
}
|
|
55
|
+
|
|
56
|
+
export { CompositeStandardHandlerPlugin as C, StandardHandler as e };
|
|
57
|
+
export type { StandardHandlerInterceptorOptions as S, StandardHandlerPlugin as a, StandardHandlerOptions as b, StandardHandleOptions as c, StandardHandleResult as d };
|
|
@@ -0,0 +1,57 @@
|
|
|
1
|
+
import { Meta } from '@temporary-name/contract';
|
|
2
|
+
import { HTTPPath, Interceptor } from '@temporary-name/shared';
|
|
3
|
+
import { StandardLazyRequest, StandardResponse } from '@temporary-name/standard-server';
|
|
4
|
+
import { C as Context, R as Router, E as ProcedureClientInterceptorOptions } from './server.BKSOrA6h.js';
|
|
5
|
+
|
|
6
|
+
interface StandardHandlerPlugin<T extends Context> {
|
|
7
|
+
order?: number;
|
|
8
|
+
init?(options: StandardHandlerOptions<T>, router: Router<any, T>): void;
|
|
9
|
+
}
|
|
10
|
+
declare class CompositeStandardHandlerPlugin<T extends Context, TPlugin extends StandardHandlerPlugin<T>> implements StandardHandlerPlugin<T> {
|
|
11
|
+
protected readonly plugins: TPlugin[];
|
|
12
|
+
constructor(plugins?: readonly TPlugin[]);
|
|
13
|
+
init(options: StandardHandlerOptions<T>, router: Router<any, T>): void;
|
|
14
|
+
}
|
|
15
|
+
|
|
16
|
+
interface StandardHandleOptions<T extends Context> {
|
|
17
|
+
prefix?: HTTPPath;
|
|
18
|
+
context: T;
|
|
19
|
+
}
|
|
20
|
+
type StandardHandleResult = {
|
|
21
|
+
matched: true;
|
|
22
|
+
response: StandardResponse;
|
|
23
|
+
} | {
|
|
24
|
+
matched: false;
|
|
25
|
+
response: undefined;
|
|
26
|
+
};
|
|
27
|
+
interface StandardHandlerInterceptorOptions<T extends Context> extends StandardHandleOptions<T> {
|
|
28
|
+
request: StandardLazyRequest;
|
|
29
|
+
}
|
|
30
|
+
interface StandardHandlerOptions<TContext extends Context> {
|
|
31
|
+
plugins?: StandardHandlerPlugin<TContext>[];
|
|
32
|
+
/**
|
|
33
|
+
* Interceptors at the request level, helpful when you want catch errors
|
|
34
|
+
*/
|
|
35
|
+
interceptors?: Interceptor<StandardHandlerInterceptorOptions<TContext>, Promise<StandardHandleResult>>[];
|
|
36
|
+
/**
|
|
37
|
+
* Interceptors at the root level, helpful when you want override the request/response
|
|
38
|
+
*/
|
|
39
|
+
rootInterceptors?: Interceptor<StandardHandlerInterceptorOptions<TContext>, Promise<StandardHandleResult>>[];
|
|
40
|
+
/**
|
|
41
|
+
*
|
|
42
|
+
* Interceptors for procedure client.
|
|
43
|
+
*/
|
|
44
|
+
clientInterceptors?: Interceptor<ProcedureClientInterceptorOptions<TContext, Record<never, never>, Meta>, Promise<unknown>>[];
|
|
45
|
+
}
|
|
46
|
+
declare class StandardHandler<T extends Context> {
|
|
47
|
+
private readonly interceptors;
|
|
48
|
+
private readonly clientInterceptors;
|
|
49
|
+
private readonly rootInterceptors;
|
|
50
|
+
private readonly matcher;
|
|
51
|
+
private readonly codec;
|
|
52
|
+
constructor(router: Router<any, T>, options: NoInfer<StandardHandlerOptions<T>>);
|
|
53
|
+
handle(request: StandardLazyRequest, options: StandardHandleOptions<T>): Promise<StandardHandleResult>;
|
|
54
|
+
}
|
|
55
|
+
|
|
56
|
+
export { CompositeStandardHandlerPlugin as C, StandardHandler as e };
|
|
57
|
+
export type { StandardHandlerInterceptorOptions as S, StandardHandlerPlugin as a, StandardHandlerOptions as b, StandardHandleOptions as c, StandardHandleResult as d };
|
|
@@ -0,0 +1,293 @@
|
|
|
1
|
+
import { isObject, stringifyJSON, isORPCErrorStatus, tryDecodeURIComponent, value, toHttpPath, toArray, intercept, runWithSpan, ORPC_NAME, isAsyncIteratorObject, asyncIteratorWithSpan, setSpanError, ORPCError, toORPCError } from '@temporary-name/shared';
|
|
2
|
+
import { flattenHeader } from '@temporary-name/standard-server';
|
|
3
|
+
import { c as createProcedureClient } from './server.BKh8I1Ny.mjs';
|
|
4
|
+
import { fallbackContractConfig } from '@temporary-name/contract';
|
|
5
|
+
import { d as deserialize, s as serialize, a as standardizeHTTPPath } from './server.BEHw7Eyx.mjs';
|
|
6
|
+
import { traverseContractProcedures, isProcedure, getLazyMeta, unlazy, getRouter, createContractedProcedure } from '@temporary-name/server';
|
|
7
|
+
import { createRouter, addRoute, findRoute } from 'rou3';
|
|
8
|
+
|
|
9
|
+
class StandardOpenAPICodec {
|
|
10
|
+
constructor() {
|
|
11
|
+
}
|
|
12
|
+
async decode(request, params, procedure) {
|
|
13
|
+
const inputStructure = fallbackContractConfig(
|
|
14
|
+
"defaultInputStructure",
|
|
15
|
+
procedure["~orpc"].route.inputStructure
|
|
16
|
+
);
|
|
17
|
+
if (inputStructure === "compact") {
|
|
18
|
+
const data = request.method === "GET" ? deserialize(request.url.searchParams) : deserialize(await request.body());
|
|
19
|
+
if (data === void 0) {
|
|
20
|
+
return params;
|
|
21
|
+
}
|
|
22
|
+
if (isObject(data)) {
|
|
23
|
+
return {
|
|
24
|
+
...params,
|
|
25
|
+
...data
|
|
26
|
+
};
|
|
27
|
+
}
|
|
28
|
+
return data;
|
|
29
|
+
}
|
|
30
|
+
const deserializeSearchParams = () => {
|
|
31
|
+
return deserialize(request.url.searchParams);
|
|
32
|
+
};
|
|
33
|
+
return {
|
|
34
|
+
params,
|
|
35
|
+
get query() {
|
|
36
|
+
const value = deserializeSearchParams();
|
|
37
|
+
Object.defineProperty(this, "query", { value, writable: true });
|
|
38
|
+
return value;
|
|
39
|
+
},
|
|
40
|
+
set query(value) {
|
|
41
|
+
Object.defineProperty(this, "query", { value, writable: true });
|
|
42
|
+
},
|
|
43
|
+
headers: request.headers,
|
|
44
|
+
body: deserialize(await request.body())
|
|
45
|
+
};
|
|
46
|
+
}
|
|
47
|
+
encode(output, procedure) {
|
|
48
|
+
const successStatus = fallbackContractConfig(
|
|
49
|
+
"defaultSuccessStatus",
|
|
50
|
+
procedure["~orpc"].route.successStatus
|
|
51
|
+
);
|
|
52
|
+
const outputStructure = fallbackContractConfig(
|
|
53
|
+
"defaultOutputStructure",
|
|
54
|
+
procedure["~orpc"].route.outputStructure
|
|
55
|
+
);
|
|
56
|
+
if (outputStructure === "compact") {
|
|
57
|
+
return {
|
|
58
|
+
status: successStatus,
|
|
59
|
+
headers: {},
|
|
60
|
+
body: serialize(output)
|
|
61
|
+
};
|
|
62
|
+
}
|
|
63
|
+
if (!this.#isDetailedOutput(output)) {
|
|
64
|
+
throw new Error(`
|
|
65
|
+
Invalid "detailed" output structure:
|
|
66
|
+
\u2022 Expected an object with optional properties:
|
|
67
|
+
- status (number 200-399)
|
|
68
|
+
- headers (Record<string, string | string[]>)
|
|
69
|
+
- body (any)
|
|
70
|
+
\u2022 No extra keys allowed.
|
|
71
|
+
|
|
72
|
+
Actual value:
|
|
73
|
+
${stringifyJSON(output)}
|
|
74
|
+
`);
|
|
75
|
+
}
|
|
76
|
+
return {
|
|
77
|
+
status: output.status ?? successStatus,
|
|
78
|
+
headers: output.headers ?? {},
|
|
79
|
+
body: serialize(output.body)
|
|
80
|
+
};
|
|
81
|
+
}
|
|
82
|
+
encodeError(error) {
|
|
83
|
+
return {
|
|
84
|
+
status: error.status,
|
|
85
|
+
headers: {},
|
|
86
|
+
body: serialize(error.toJSON(), { outputFormat: "plain" })
|
|
87
|
+
};
|
|
88
|
+
}
|
|
89
|
+
#isDetailedOutput(output) {
|
|
90
|
+
if (!isObject(output)) {
|
|
91
|
+
return false;
|
|
92
|
+
}
|
|
93
|
+
if (output.headers && !isObject(output.headers)) {
|
|
94
|
+
return false;
|
|
95
|
+
}
|
|
96
|
+
if (output.status !== void 0 && (typeof output.status !== "number" || !Number.isInteger(output.status) || isORPCErrorStatus(output.status))) {
|
|
97
|
+
return false;
|
|
98
|
+
}
|
|
99
|
+
return true;
|
|
100
|
+
}
|
|
101
|
+
}
|
|
102
|
+
|
|
103
|
+
function resolveFriendlyStandardHandleOptions(options) {
|
|
104
|
+
return {
|
|
105
|
+
...options,
|
|
106
|
+
context: options.context ?? {}
|
|
107
|
+
// Context only optional if all fields are optional
|
|
108
|
+
};
|
|
109
|
+
}
|
|
110
|
+
function toRou3Pattern(path) {
|
|
111
|
+
return standardizeHTTPPath(path).replace(/\/\{\+([^}]+)\}/g, "/**:$1").replace(/\/\{([^}]+)\}/g, "/:$1");
|
|
112
|
+
}
|
|
113
|
+
function decodeParams(params) {
|
|
114
|
+
return Object.fromEntries(
|
|
115
|
+
Object.entries(params).map(([key, value]) => [key, tryDecodeURIComponent(value)])
|
|
116
|
+
);
|
|
117
|
+
}
|
|
118
|
+
|
|
119
|
+
class StandardOpenAPIMatcher {
|
|
120
|
+
tree = createRouter();
|
|
121
|
+
pendingRouters = [];
|
|
122
|
+
init(router, path = []) {
|
|
123
|
+
const laziedOptions = traverseContractProcedures({ router, path }, (traverseOptions) => {
|
|
124
|
+
if (!value(true, traverseOptions)) {
|
|
125
|
+
return;
|
|
126
|
+
}
|
|
127
|
+
const { path: path2, contract } = traverseOptions;
|
|
128
|
+
const method = fallbackContractConfig("defaultMethod", contract["~orpc"].route.method);
|
|
129
|
+
const httpPath = toRou3Pattern(contract["~orpc"].route.path ?? toHttpPath(path2));
|
|
130
|
+
if (isProcedure(contract)) {
|
|
131
|
+
addRoute(this.tree, method, httpPath, {
|
|
132
|
+
path: path2,
|
|
133
|
+
contract,
|
|
134
|
+
procedure: contract,
|
|
135
|
+
// this mean dev not used contract-first so we can used contract as procedure directly
|
|
136
|
+
router
|
|
137
|
+
});
|
|
138
|
+
} else {
|
|
139
|
+
addRoute(this.tree, method, httpPath, {
|
|
140
|
+
path: path2,
|
|
141
|
+
contract,
|
|
142
|
+
procedure: void 0,
|
|
143
|
+
router
|
|
144
|
+
});
|
|
145
|
+
}
|
|
146
|
+
});
|
|
147
|
+
this.pendingRouters.push(
|
|
148
|
+
...laziedOptions.map((option) => ({
|
|
149
|
+
...option,
|
|
150
|
+
httpPathPrefix: toHttpPath(option.path),
|
|
151
|
+
laziedPrefix: getLazyMeta(option.router).prefix
|
|
152
|
+
}))
|
|
153
|
+
);
|
|
154
|
+
}
|
|
155
|
+
async match(method, pathname) {
|
|
156
|
+
if (this.pendingRouters.length) {
|
|
157
|
+
const newPendingRouters = [];
|
|
158
|
+
for (const pendingRouter of this.pendingRouters) {
|
|
159
|
+
if (!pendingRouter.laziedPrefix || pathname.startsWith(pendingRouter.laziedPrefix) || pathname.startsWith(pendingRouter.httpPathPrefix)) {
|
|
160
|
+
const { default: router } = await unlazy(pendingRouter.router);
|
|
161
|
+
this.init(router, pendingRouter.path);
|
|
162
|
+
} else {
|
|
163
|
+
newPendingRouters.push(pendingRouter);
|
|
164
|
+
}
|
|
165
|
+
}
|
|
166
|
+
this.pendingRouters = newPendingRouters;
|
|
167
|
+
}
|
|
168
|
+
const match = findRoute(this.tree, method, pathname);
|
|
169
|
+
if (!match) {
|
|
170
|
+
return void 0;
|
|
171
|
+
}
|
|
172
|
+
if (!match.data.procedure) {
|
|
173
|
+
const { default: maybeProcedure } = await unlazy(getRouter(match.data.router, match.data.path));
|
|
174
|
+
if (!isProcedure(maybeProcedure)) {
|
|
175
|
+
throw new Error(`
|
|
176
|
+
[Contract-First] Missing or invalid implementation for procedure at path: ${toHttpPath(match.data.path)}.
|
|
177
|
+
Ensure that the procedure is correctly defined and matches the expected contract.
|
|
178
|
+
`);
|
|
179
|
+
}
|
|
180
|
+
match.data.procedure = createContractedProcedure(maybeProcedure, match.data.contract);
|
|
181
|
+
}
|
|
182
|
+
return {
|
|
183
|
+
path: match.data.path,
|
|
184
|
+
procedure: match.data.procedure,
|
|
185
|
+
params: match.params ? decodeParams(match.params) : void 0
|
|
186
|
+
};
|
|
187
|
+
}
|
|
188
|
+
}
|
|
189
|
+
|
|
190
|
+
class CompositeStandardHandlerPlugin {
|
|
191
|
+
plugins;
|
|
192
|
+
constructor(plugins = []) {
|
|
193
|
+
this.plugins = [...plugins].sort((a, b) => (a.order ?? 0) - (b.order ?? 0));
|
|
194
|
+
}
|
|
195
|
+
init(options, router) {
|
|
196
|
+
for (const plugin of this.plugins) {
|
|
197
|
+
plugin.init?.(options, router);
|
|
198
|
+
}
|
|
199
|
+
}
|
|
200
|
+
}
|
|
201
|
+
|
|
202
|
+
class StandardHandler {
|
|
203
|
+
interceptors;
|
|
204
|
+
clientInterceptors;
|
|
205
|
+
rootInterceptors;
|
|
206
|
+
matcher;
|
|
207
|
+
codec;
|
|
208
|
+
constructor(router, options) {
|
|
209
|
+
this.matcher = new StandardOpenAPIMatcher();
|
|
210
|
+
this.codec = new StandardOpenAPICodec();
|
|
211
|
+
const plugins = new CompositeStandardHandlerPlugin(options.plugins);
|
|
212
|
+
plugins.init(options, router);
|
|
213
|
+
this.interceptors = toArray(options.interceptors);
|
|
214
|
+
this.clientInterceptors = toArray(options.clientInterceptors);
|
|
215
|
+
this.rootInterceptors = toArray(options.rootInterceptors);
|
|
216
|
+
this.matcher.init(router);
|
|
217
|
+
}
|
|
218
|
+
async handle(request, options) {
|
|
219
|
+
const prefix = options.prefix?.replace(/\/$/, "") || void 0;
|
|
220
|
+
if (prefix && !request.url.pathname.startsWith(`${prefix}/`) && request.url.pathname !== prefix) {
|
|
221
|
+
return { matched: false, response: void 0 };
|
|
222
|
+
}
|
|
223
|
+
return intercept(this.rootInterceptors, { ...options, request, prefix }, async (interceptorOptions) => {
|
|
224
|
+
return runWithSpan({ name: `${request.method} ${request.url.pathname}` }, async (span) => {
|
|
225
|
+
let step;
|
|
226
|
+
try {
|
|
227
|
+
return await intercept(
|
|
228
|
+
this.interceptors,
|
|
229
|
+
interceptorOptions,
|
|
230
|
+
async ({ request: request2, context, prefix: prefix2 }) => {
|
|
231
|
+
const method = request2.method;
|
|
232
|
+
const url = request2.url;
|
|
233
|
+
const pathname = prefix2 ? url.pathname.replace(prefix2, "") : url.pathname;
|
|
234
|
+
const match = await runWithSpan(
|
|
235
|
+
{ name: "find_procedure" },
|
|
236
|
+
() => this.matcher.match(method, `/${pathname.replace(/^\/|\/$/g, "")}`)
|
|
237
|
+
);
|
|
238
|
+
if (!match) {
|
|
239
|
+
return { matched: false, response: void 0 };
|
|
240
|
+
}
|
|
241
|
+
span?.updateName(`${ORPC_NAME}.${match.path.join("/")}`);
|
|
242
|
+
span?.setAttribute("rpc.system", ORPC_NAME);
|
|
243
|
+
span?.setAttribute("rpc.method", match.path.join("."));
|
|
244
|
+
step = "decode_input";
|
|
245
|
+
let input = await runWithSpan(
|
|
246
|
+
{ name: "decode_input" },
|
|
247
|
+
() => this.codec.decode(request2, match.params, match.procedure)
|
|
248
|
+
);
|
|
249
|
+
step = void 0;
|
|
250
|
+
if (isAsyncIteratorObject(input)) {
|
|
251
|
+
input = asyncIteratorWithSpan(
|
|
252
|
+
{ name: "consume_event_iterator_input", signal: request2.signal },
|
|
253
|
+
input
|
|
254
|
+
);
|
|
255
|
+
}
|
|
256
|
+
const client = createProcedureClient(match.procedure, {
|
|
257
|
+
context,
|
|
258
|
+
path: match.path,
|
|
259
|
+
interceptors: this.clientInterceptors
|
|
260
|
+
});
|
|
261
|
+
step = "call_procedure";
|
|
262
|
+
const output = await client(input, {
|
|
263
|
+
signal: request2.signal,
|
|
264
|
+
lastEventId: flattenHeader(request2.headers["last-event-id"])
|
|
265
|
+
});
|
|
266
|
+
step = void 0;
|
|
267
|
+
const response = this.codec.encode(output, match.procedure);
|
|
268
|
+
return {
|
|
269
|
+
matched: true,
|
|
270
|
+
response
|
|
271
|
+
};
|
|
272
|
+
}
|
|
273
|
+
);
|
|
274
|
+
} catch (e) {
|
|
275
|
+
if (step !== "call_procedure") {
|
|
276
|
+
setSpanError(span, e);
|
|
277
|
+
}
|
|
278
|
+
const error = step === "decode_input" && !(e instanceof ORPCError) ? new ORPCError("BAD_REQUEST", {
|
|
279
|
+
message: `Malformed request. Ensure the request body is properly formatted and the 'Content-Type' header is set correctly.`,
|
|
280
|
+
cause: e
|
|
281
|
+
}) : toORPCError(e);
|
|
282
|
+
const response = this.codec.encodeError(error);
|
|
283
|
+
return {
|
|
284
|
+
matched: true,
|
|
285
|
+
response
|
|
286
|
+
};
|
|
287
|
+
}
|
|
288
|
+
});
|
|
289
|
+
});
|
|
290
|
+
}
|
|
291
|
+
}
|
|
292
|
+
|
|
293
|
+
export { CompositeStandardHandlerPlugin as C, StandardHandler as S, StandardOpenAPICodec as a, StandardOpenAPIMatcher as b, decodeParams as d, resolveFriendlyStandardHandleOptions as r, toRou3Pattern as t };
|
|
@@ -0,0 +1,23 @@
|
|
|
1
|
+
import { HTTPPath } from '@temporary-name/shared';
|
|
2
|
+
import { C as Context } from './server.BKSOrA6h.js';
|
|
3
|
+
import { c as StandardHandleOptions } from './server.CQyYNJ1H.js';
|
|
4
|
+
|
|
5
|
+
type FriendlyStandardHandleOptions<T extends Context> = Omit<StandardHandleOptions<T>, 'context'> & (Record<never, never> extends T ? {
|
|
6
|
+
context?: T;
|
|
7
|
+
} : {
|
|
8
|
+
context: T;
|
|
9
|
+
});
|
|
10
|
+
declare function resolveFriendlyStandardHandleOptions<T extends Context>(options: FriendlyStandardHandleOptions<T>): StandardHandleOptions<T>;
|
|
11
|
+
/**
|
|
12
|
+
* {@link https://github.com/unjs/rou3}
|
|
13
|
+
*
|
|
14
|
+
* @internal
|
|
15
|
+
*/
|
|
16
|
+
declare function toRou3Pattern(path: HTTPPath): string;
|
|
17
|
+
/**
|
|
18
|
+
* @internal
|
|
19
|
+
*/
|
|
20
|
+
declare function decodeParams(params: Record<string, string>): Record<string, string>;
|
|
21
|
+
|
|
22
|
+
export { decodeParams as d, resolveFriendlyStandardHandleOptions as r, toRou3Pattern as t };
|
|
23
|
+
export type { FriendlyStandardHandleOptions as F };
|