@temporary-name/server 0.0.1-alpha.0cb08cf84b740850e7d8dcd1d8b87f78af26071b
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 +26 -0
- package/dist/adapters/aws-lambda/index.d.ts +26 -0
- package/dist/adapters/aws-lambda/index.mjs +30 -0
- package/dist/adapters/fastify/index.d.mts +23 -0
- package/dist/adapters/fastify/index.d.ts +23 -0
- package/dist/adapters/fastify/index.mjs +30 -0
- package/dist/adapters/fetch/index.d.mts +28 -0
- package/dist/adapters/fetch/index.d.ts +28 -0
- package/dist/adapters/fetch/index.mjs +32 -0
- package/dist/adapters/node/index.d.mts +26 -0
- package/dist/adapters/node/index.d.ts +26 -0
- package/dist/adapters/node/index.mjs +30 -0
- package/dist/handler/index.d.mts +22 -0
- package/dist/handler/index.d.ts +22 -0
- package/dist/handler/index.mjs +8 -0
- package/dist/helpers/index.d.mts +149 -0
- package/dist/helpers/index.d.ts +149 -0
- package/dist/helpers/index.mjs +142 -0
- package/dist/index.d.mts +395 -0
- package/dist/index.d.ts +395 -0
- package/dist/index.mjs +831 -0
- package/dist/openapi/index.d.mts +167 -0
- package/dist/openapi/index.d.ts +167 -0
- package/dist/openapi/index.mjs +15 -0
- package/dist/shared/server.BOkueCuE.d.ts +39 -0
- package/dist/shared/server.BTVDgKdb.d.mts +9552 -0
- package/dist/shared/server.BTVDgKdb.d.ts +9552 -0
- package/dist/shared/server.C1RJffw4.mjs +30 -0
- package/dist/shared/server.CWiZN27E.d.mts +39 -0
- package/dist/shared/server.CjPiuQYH.d.mts +51 -0
- package/dist/shared/server.CjPiuQYH.d.ts +51 -0
- package/dist/shared/server.D7jtfDRy.mjs +288 -0
- package/dist/shared/server.JwVIEHL6.mjs +386 -0
- package/dist/shared/server.RQr7F4gX.mjs +1292 -0
- package/package.json +87 -0
|
@@ -0,0 +1,386 @@
|
|
|
1
|
+
import { runWithSpan, isAsyncIteratorObject, overlayProxy, asyncIteratorWithSpan, fallbackContractConfig, tryDecodeURIComponent, parseHTTPEndpoint, KRUSTY_NAME, setSpanError } from '@temporary-name/shared';
|
|
2
|
+
import { N as NotFoundError, V as ValidationError, B as BadRequestError, I as InternalServerError, e as encodeError, s as standardizeHTTPPath, i as isLazyResource, v as validateLazyLoadedResource, A as ApiError, t as toApiError$1 } from './server.D7jtfDRy.mjs';
|
|
3
|
+
import { mapEventIterator, ErrorEvent } from '@temporary-name/standard-server';
|
|
4
|
+
import * as z from '@temporary-name/zod';
|
|
5
|
+
import { safeDecodeAsync, safeEncodeAsync } from '@temporary-name/zod';
|
|
6
|
+
import { toApiError } from '@temporary-name/server';
|
|
7
|
+
import { parse } from 'neoqs';
|
|
8
|
+
import { createRouter, addRoute, findRoute } from 'rou3';
|
|
9
|
+
|
|
10
|
+
function mergeContext(context, other) {
|
|
11
|
+
return { ...context, ...other };
|
|
12
|
+
}
|
|
13
|
+
|
|
14
|
+
function getEndpointId(config) {
|
|
15
|
+
return `${config.method}:${config.path}`;
|
|
16
|
+
}
|
|
17
|
+
|
|
18
|
+
async function callMethod(method, ...[input, options]) {
|
|
19
|
+
const context = options?.context ?? {};
|
|
20
|
+
const output = await runWithSpan({ name: "call_method", signal: options?.signal }, (span) => {
|
|
21
|
+
span?.setAttribute("method.path", getEndpointId(method["~def"].methodConfig));
|
|
22
|
+
return executeMethodInternal(
|
|
23
|
+
method,
|
|
24
|
+
{
|
|
25
|
+
query: input?.query ?? {},
|
|
26
|
+
headers: new Headers(input?.headers),
|
|
27
|
+
body: input?.body ?? {},
|
|
28
|
+
path: input?.path ?? {}
|
|
29
|
+
},
|
|
30
|
+
{
|
|
31
|
+
context,
|
|
32
|
+
method,
|
|
33
|
+
request: options?.request,
|
|
34
|
+
signal: options?.signal,
|
|
35
|
+
lastEventId: options?.lastEventId
|
|
36
|
+
}
|
|
37
|
+
);
|
|
38
|
+
});
|
|
39
|
+
if (isAsyncIteratorObject(output)) {
|
|
40
|
+
return overlayProxy(
|
|
41
|
+
output,
|
|
42
|
+
mapEventIterator(
|
|
43
|
+
asyncIteratorWithSpan({ name: "consume_event_iterator_output", signal: options?.signal }, output),
|
|
44
|
+
{
|
|
45
|
+
value: (v) => v,
|
|
46
|
+
error: async (e) => e
|
|
47
|
+
}
|
|
48
|
+
)
|
|
49
|
+
);
|
|
50
|
+
}
|
|
51
|
+
return output;
|
|
52
|
+
}
|
|
53
|
+
function validateInput(schemas, input, config) {
|
|
54
|
+
return runWithSpan({ name: "validate_input" }, async () => {
|
|
55
|
+
const { strictParams, method } = config;
|
|
56
|
+
if (method) {
|
|
57
|
+
const { middlewareOnlyKeys } = method["~def"];
|
|
58
|
+
for (const key of middlewareOnlyKeys.query) {
|
|
59
|
+
delete input.query[key];
|
|
60
|
+
}
|
|
61
|
+
if (input.body) {
|
|
62
|
+
for (const key of middlewareOnlyKeys.body) {
|
|
63
|
+
delete input.body[key];
|
|
64
|
+
}
|
|
65
|
+
}
|
|
66
|
+
}
|
|
67
|
+
const resultBody = await safeDecodeAsync(schemas.bodySchema, input.body, {
|
|
68
|
+
coerce: false,
|
|
69
|
+
defaultStrictObjects: strictParams
|
|
70
|
+
});
|
|
71
|
+
const resultPath = await safeDecodeAsync(schemas.pathSchema, input.path, {
|
|
72
|
+
coerce: true,
|
|
73
|
+
defaultStrictObjects: strictParams
|
|
74
|
+
});
|
|
75
|
+
const resultQuery = await safeDecodeAsync(schemas.querySchema, input.query, {
|
|
76
|
+
coerce: true,
|
|
77
|
+
defaultStrictObjects: strictParams
|
|
78
|
+
});
|
|
79
|
+
const resultHeaders = await safeDecodeAsync(
|
|
80
|
+
schemas.headersSchema,
|
|
81
|
+
normalizeHeadersForSchema(input.headers, schemas.headersSchema),
|
|
82
|
+
{
|
|
83
|
+
coerce: true,
|
|
84
|
+
// Headers are always non-strict
|
|
85
|
+
defaultStrictObjects: false
|
|
86
|
+
}
|
|
87
|
+
);
|
|
88
|
+
const issues = [];
|
|
89
|
+
if (!resultPath.success) {
|
|
90
|
+
issues.push(...resultPath.error.issues.map((i) => ({ ...i, path: ["path", ...i.path] })));
|
|
91
|
+
throw new NotFoundError({
|
|
92
|
+
cause: new ValidationError({
|
|
93
|
+
issues,
|
|
94
|
+
data: input
|
|
95
|
+
})
|
|
96
|
+
});
|
|
97
|
+
}
|
|
98
|
+
if (!resultBody.success) {
|
|
99
|
+
issues.push(...resultBody.error.issues.map((i) => ({ ...i, path: ["body", ...i.path] })));
|
|
100
|
+
}
|
|
101
|
+
if (!resultQuery.success) {
|
|
102
|
+
issues.push(...resultQuery.error.issues.map((i) => ({ ...i, path: ["query", ...i.path] })));
|
|
103
|
+
}
|
|
104
|
+
if (!resultHeaders.success) {
|
|
105
|
+
issues.push(...resultHeaders.error.issues.map((i) => ({ ...i, path: ["headers", ...i.path] })));
|
|
106
|
+
}
|
|
107
|
+
if (issues.length > 0) {
|
|
108
|
+
throw new BadRequestError({
|
|
109
|
+
code: "input_validation_failed",
|
|
110
|
+
message: "Input validation failed",
|
|
111
|
+
cause: new ValidationError({
|
|
112
|
+
issues,
|
|
113
|
+
data: input
|
|
114
|
+
})
|
|
115
|
+
});
|
|
116
|
+
}
|
|
117
|
+
const results = {
|
|
118
|
+
body: resultBody.data,
|
|
119
|
+
path: resultPath.data,
|
|
120
|
+
query: resultQuery.data,
|
|
121
|
+
headers: resultHeaders.data
|
|
122
|
+
};
|
|
123
|
+
return results;
|
|
124
|
+
});
|
|
125
|
+
}
|
|
126
|
+
async function validateOutput(method, output) {
|
|
127
|
+
const schema = method["~def"].schemas.responseSchema;
|
|
128
|
+
if (!schema) {
|
|
129
|
+
return output;
|
|
130
|
+
}
|
|
131
|
+
return runWithSpan({ name: "validate_output" }, async () => {
|
|
132
|
+
const result = await safeEncodeAsync(schema, output);
|
|
133
|
+
if (!result.success) {
|
|
134
|
+
throw new InternalServerError({
|
|
135
|
+
message: "Output validation failed",
|
|
136
|
+
cause: new ValidationError({
|
|
137
|
+
issues: result.error.issues,
|
|
138
|
+
data: output
|
|
139
|
+
})
|
|
140
|
+
});
|
|
141
|
+
}
|
|
142
|
+
return result.data;
|
|
143
|
+
});
|
|
144
|
+
}
|
|
145
|
+
const respond = (response) => ({ response });
|
|
146
|
+
async function executeMethodInternal(method, input, options) {
|
|
147
|
+
const middlewares = method["~def"].middlewares;
|
|
148
|
+
const next = async (index, context) => {
|
|
149
|
+
const mid = middlewares[index];
|
|
150
|
+
return mid ? await runWithSpan({ name: `middleware.${index}`, signal: options.signal }, async (span) => {
|
|
151
|
+
const validatedInput = await validateInput(mid["~def"].schemas, input, { strictParams: false });
|
|
152
|
+
span?.setAttribute("middleware.index", index);
|
|
153
|
+
const result = await mid.handler({
|
|
154
|
+
...options,
|
|
155
|
+
...validatedInput,
|
|
156
|
+
context,
|
|
157
|
+
respond,
|
|
158
|
+
next: async (nextOptions) => {
|
|
159
|
+
const nextContext = nextOptions?.context ?? {};
|
|
160
|
+
return {
|
|
161
|
+
response: await next(index + 1, mergeContext(context, nextContext))
|
|
162
|
+
};
|
|
163
|
+
}
|
|
164
|
+
});
|
|
165
|
+
return result.response;
|
|
166
|
+
}) : await runWithSpan({ name: "handler", signal: options.signal }, async () => {
|
|
167
|
+
const validatedInput = await validateInput(method["~def"].schemas, input, {
|
|
168
|
+
strictParams: true,
|
|
169
|
+
method
|
|
170
|
+
});
|
|
171
|
+
const response = await method.handler(validatedInput, { ...options, context });
|
|
172
|
+
return validateOutput(method, response);
|
|
173
|
+
});
|
|
174
|
+
};
|
|
175
|
+
return next(0, options.context);
|
|
176
|
+
}
|
|
177
|
+
function normalizeHeadersForSchema(headers, schema) {
|
|
178
|
+
if (!(schema instanceof z.core.$ZodObject)) {
|
|
179
|
+
return Object.fromEntries(headers.entries());
|
|
180
|
+
}
|
|
181
|
+
const { def } = schema._zod;
|
|
182
|
+
const normalized = {};
|
|
183
|
+
for (const key in def.shape) {
|
|
184
|
+
const value = headers.get(key);
|
|
185
|
+
if (value != null) {
|
|
186
|
+
normalized[key] = value;
|
|
187
|
+
}
|
|
188
|
+
}
|
|
189
|
+
if (def.catchall) {
|
|
190
|
+
const lowerShapeKeys = new Set(Object.keys(def.shape).map((k) => k.toLowerCase()));
|
|
191
|
+
for (const [key, value] of headers.entries()) {
|
|
192
|
+
if (!lowerShapeKeys.has(key)) {
|
|
193
|
+
normalized[key] = value;
|
|
194
|
+
}
|
|
195
|
+
}
|
|
196
|
+
}
|
|
197
|
+
return normalized;
|
|
198
|
+
}
|
|
199
|
+
|
|
200
|
+
async function decode(request, pathParams) {
|
|
201
|
+
return {
|
|
202
|
+
path: pathParams ?? {},
|
|
203
|
+
query: parse(request.url.search, { ignoreQueryPrefix: true }),
|
|
204
|
+
headers: request.headers,
|
|
205
|
+
body: await request.body() ?? {}
|
|
206
|
+
};
|
|
207
|
+
}
|
|
208
|
+
function asyncSafeSerialize(data) {
|
|
209
|
+
if (isAsyncIteratorObject(data)) {
|
|
210
|
+
return mapEventIterator(data, {
|
|
211
|
+
value: async (value) => value,
|
|
212
|
+
error: async (e) => {
|
|
213
|
+
return new ErrorEvent({
|
|
214
|
+
data: encodeError(toApiError(e))["body"],
|
|
215
|
+
cause: e
|
|
216
|
+
});
|
|
217
|
+
}
|
|
218
|
+
});
|
|
219
|
+
}
|
|
220
|
+
return data;
|
|
221
|
+
}
|
|
222
|
+
function encode(output, method) {
|
|
223
|
+
const successStatus = fallbackContractConfig(
|
|
224
|
+
"defaultSuccessStatus",
|
|
225
|
+
method["~def"].methodConfig.successStatus
|
|
226
|
+
);
|
|
227
|
+
return {
|
|
228
|
+
status: successStatus,
|
|
229
|
+
headers: new Headers(),
|
|
230
|
+
body: asyncSafeSerialize(output)
|
|
231
|
+
};
|
|
232
|
+
}
|
|
233
|
+
|
|
234
|
+
function resolveFriendlyStandardHandleOptions(options) {
|
|
235
|
+
return {
|
|
236
|
+
...options,
|
|
237
|
+
context: options.context ?? {}
|
|
238
|
+
// Context only optional if all fields are optional
|
|
239
|
+
};
|
|
240
|
+
}
|
|
241
|
+
function toRou3Pattern(path) {
|
|
242
|
+
return standardizeHTTPPath(path).replace(/\/\{\+([^}]+)\}/g, "/**:$1").replace(/\/\{([^}]+)\}/g, "/:$1");
|
|
243
|
+
}
|
|
244
|
+
function decodeParams(params) {
|
|
245
|
+
return Object.fromEntries(
|
|
246
|
+
Object.entries(params).map(([key, value]) => [key, tryDecodeURIComponent(value)])
|
|
247
|
+
);
|
|
248
|
+
}
|
|
249
|
+
|
|
250
|
+
class StandardOpenAPIMatcher {
|
|
251
|
+
tree = createRouter();
|
|
252
|
+
constructor(resources) {
|
|
253
|
+
for (const resource of resources) {
|
|
254
|
+
if (isLazyResource(resource)) {
|
|
255
|
+
const { endpoints } = resource;
|
|
256
|
+
for (const methodName in endpoints) {
|
|
257
|
+
const endpoint = endpoints[methodName];
|
|
258
|
+
const [method, path] = parseHTTPEndpoint(endpoint);
|
|
259
|
+
const httpPath = toRou3Pattern(path);
|
|
260
|
+
addRoute(this.tree, method, httpPath, { lazyResource: resource, methodName });
|
|
261
|
+
}
|
|
262
|
+
} else {
|
|
263
|
+
for (const route of Object.values(resource.methods)) {
|
|
264
|
+
const { methodConfig } = route["~def"];
|
|
265
|
+
const method = methodConfig.method;
|
|
266
|
+
const httpPath = toRou3Pattern(methodConfig.path ?? "/");
|
|
267
|
+
addRoute(this.tree, method, httpPath, { method: route });
|
|
268
|
+
}
|
|
269
|
+
}
|
|
270
|
+
}
|
|
271
|
+
}
|
|
272
|
+
async match(method, pathname) {
|
|
273
|
+
const match = findRoute(this.tree, method, pathname);
|
|
274
|
+
if (!match) {
|
|
275
|
+
return void 0;
|
|
276
|
+
}
|
|
277
|
+
const params = match.params ? decodeParams(match.params) : void 0;
|
|
278
|
+
if ("lazyResource" in match.data) {
|
|
279
|
+
const { lazyResource, methodName } = match.data;
|
|
280
|
+
if (lazyResource.loaderCache === void 0) {
|
|
281
|
+
lazyResource.loaderCache = await lazyResource.loader();
|
|
282
|
+
validateLazyLoadedResource(lazyResource, lazyResource.loaderCache);
|
|
283
|
+
}
|
|
284
|
+
return { method: lazyResource.loaderCache.methods[methodName], params };
|
|
285
|
+
}
|
|
286
|
+
return { method: match.data.method, params };
|
|
287
|
+
}
|
|
288
|
+
}
|
|
289
|
+
|
|
290
|
+
function throwOrLog(error) {
|
|
291
|
+
if (process.env.NODE_ENV !== "production") {
|
|
292
|
+
throw error;
|
|
293
|
+
} else {
|
|
294
|
+
console.error(error);
|
|
295
|
+
}
|
|
296
|
+
}
|
|
297
|
+
class StandardHandler {
|
|
298
|
+
matcher;
|
|
299
|
+
constructor(resources) {
|
|
300
|
+
this.matcher = new StandardOpenAPIMatcher(resources);
|
|
301
|
+
}
|
|
302
|
+
async handle(request, options) {
|
|
303
|
+
const prefix = options.prefix?.replace(/\/$/, "") || void 0;
|
|
304
|
+
if (prefix && !request.url.pathname.startsWith(`${prefix}/`) && request.url.pathname !== prefix) {
|
|
305
|
+
return { matched: false, response: void 0 };
|
|
306
|
+
}
|
|
307
|
+
return runWithSpan({ name: `${request.method} ${request.url.pathname}` }, async (span) => {
|
|
308
|
+
let step;
|
|
309
|
+
let errorMap;
|
|
310
|
+
try {
|
|
311
|
+
const context = options.context;
|
|
312
|
+
const method = request.method;
|
|
313
|
+
const url = request.url;
|
|
314
|
+
const pathname = prefix ? url.pathname.replace(prefix, "") : url.pathname;
|
|
315
|
+
const match = await runWithSpan(
|
|
316
|
+
{ name: "find_method" },
|
|
317
|
+
() => this.matcher.match(method, `/${pathname.replace(/^\/|\/$/g, "")}`)
|
|
318
|
+
);
|
|
319
|
+
if (!match) {
|
|
320
|
+
return { matched: false, response: void 0 };
|
|
321
|
+
}
|
|
322
|
+
errorMap = match.method["~def"].errorMap;
|
|
323
|
+
const endpointId = getEndpointId(match.method["~def"].methodConfig);
|
|
324
|
+
span?.updateName(`${KRUSTY_NAME}.${endpointId}`);
|
|
325
|
+
span?.setAttribute("rpc.system", KRUSTY_NAME);
|
|
326
|
+
span?.setAttribute("rpc.method", endpointId);
|
|
327
|
+
step = "decode_input";
|
|
328
|
+
const input = await runWithSpan({ name: "decode_input" }, () => decode(request, match.params));
|
|
329
|
+
step = void 0;
|
|
330
|
+
if (isAsyncIteratorObject(input.body)) {
|
|
331
|
+
input.body = asyncIteratorWithSpan(
|
|
332
|
+
{ name: "consume_event_iterator_input", signal: request.signal },
|
|
333
|
+
input.body
|
|
334
|
+
);
|
|
335
|
+
}
|
|
336
|
+
step = "call_method";
|
|
337
|
+
const output = await callMethod(match.method, input, {
|
|
338
|
+
request,
|
|
339
|
+
context,
|
|
340
|
+
signal: request.signal,
|
|
341
|
+
lastEventId: request.headers.get("last-event-id") ?? void 0
|
|
342
|
+
});
|
|
343
|
+
step = void 0;
|
|
344
|
+
const response = encode(output, match.method);
|
|
345
|
+
return {
|
|
346
|
+
matched: true,
|
|
347
|
+
response
|
|
348
|
+
};
|
|
349
|
+
} catch (e) {
|
|
350
|
+
if (step !== "call_method") {
|
|
351
|
+
setSpanError(span, e);
|
|
352
|
+
}
|
|
353
|
+
const isApiError = e instanceof ApiError;
|
|
354
|
+
if (isApiError) {
|
|
355
|
+
if (!errorMap) {
|
|
356
|
+
throwOrLog(
|
|
357
|
+
new Error(`Got ApiError but errorMap is undefined. ApiError="{${e.message}"`, { cause: e })
|
|
358
|
+
);
|
|
359
|
+
} else if (!errorMap[e.constructor.name]) {
|
|
360
|
+
throwOrLog(
|
|
361
|
+
new Error(
|
|
362
|
+
`ApiError "${e.constructor.name}" (type "${e.constructor.type}") is not registered. Add it to your API with: baseApi.useErrors({ ${e.constructor.name} })`,
|
|
363
|
+
{ cause: e }
|
|
364
|
+
)
|
|
365
|
+
);
|
|
366
|
+
}
|
|
367
|
+
}
|
|
368
|
+
const error = step === "decode_input" && !(e instanceof ApiError) ? new BadRequestError({
|
|
369
|
+
code: "malformed_request",
|
|
370
|
+
message: `Malformed request. Ensure the request body is properly formatted and the 'Content-Type' header is set correctly.`,
|
|
371
|
+
cause: e
|
|
372
|
+
}) : toApiError$1(e);
|
|
373
|
+
if (error instanceof InternalServerError) {
|
|
374
|
+
console.error(error.cause ?? error);
|
|
375
|
+
}
|
|
376
|
+
const response = encodeError(error);
|
|
377
|
+
return {
|
|
378
|
+
matched: true,
|
|
379
|
+
response
|
|
380
|
+
};
|
|
381
|
+
}
|
|
382
|
+
});
|
|
383
|
+
}
|
|
384
|
+
}
|
|
385
|
+
|
|
386
|
+
export { StandardHandler as S, StandardOpenAPIMatcher as a, decodeParams as b, callMethod as c, decode as d, encode as e, getEndpointId as g, mergeContext as m, resolveFriendlyStandardHandleOptions as r, toRou3Pattern as t };
|