@temporary-name/server 0.0.1-alpha.123c4256a169035efa84c708de3e315d2a7f5ae1
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 +29 -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 +29 -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 +31 -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 +29 -0
- package/dist/handler/index.d.mts +27 -0
- package/dist/handler/index.d.ts +27 -0
- package/dist/handler/index.mjs +7 -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 +414 -0
- package/dist/index.d.ts +414 -0
- package/dist/index.mjs +696 -0
- package/dist/openapi/index.d.mts +166 -0
- package/dist/openapi/index.d.ts +166 -0
- package/dist/openapi/index.mjs +834 -0
- package/dist/shared/server.7EG6rqbI.mjs +496 -0
- package/dist/shared/server.B3SSI6V6.d.mts +3026 -0
- package/dist/shared/server.B3SSI6V6.d.ts +3026 -0
- package/dist/shared/server.BwXNcNk_.mjs +275 -0
- package/dist/shared/server.C1RJffw4.mjs +30 -0
- package/dist/shared/server.CjPiuQYH.d.mts +51 -0
- package/dist/shared/server.CjPiuQYH.d.ts +51 -0
- package/dist/shared/server.Cuq0WHVy.mjs +529 -0
- package/dist/shared/server.DmZlW6xR.d.ts +39 -0
- package/dist/shared/server.KW5uPnMg.d.mts +39 -0
- package/package.json +86 -0
package/dist/index.mjs
ADDED
|
@@ -0,0 +1,696 @@
|
|
|
1
|
+
import { U as UnauthorizedError, I as InternalServerError, N as NotFoundError, F as ForbiddenError, B as BadRequestError, p as parseEndpointDefinition, u as unlazyResources } from './shared/server.BwXNcNk_.mjs';
|
|
2
|
+
export { A as ApiError, k as BadGatewayError, C as ConflictError, d as ContentTooLargeError, G as GatewayTimeoutError, M as MethodNotAllowedError, c as NotAcceptableError, j as NotImplementedError, P as PreconditionFailedError, R as RequestTimeoutError, S as ServiceUnavailableError, T as TooManyRequestsError, h as UnprocessableContentError, f as UnsupportedMediaTypeError, V as ValidationError, b as apiResource, e as encodeError, m as endpointRegex, g as getDynamicParams, i as isApiErrorStatus, n as isDevelopment, a as isLazyResource, l as lazyResource, s as standardizeHTTPPath, t as toApiError, v as validateLazyLoadedResource } from './shared/server.BwXNcNk_.mjs';
|
|
3
|
+
import { assertNever, splitFirst, onError, isObject, toArray, guard, isTypescriptObject, isPropertyKey, clone } from '@temporary-name/shared';
|
|
4
|
+
export { AsyncIteratorClass, EventPublisher, asyncIteratorToStream as eventIteratorToStream, onError, onFinish, onStart, onSuccess, streamToAsyncIteratorClass as streamToEventIterator } from '@temporary-name/shared';
|
|
5
|
+
import * as z from '@temporary-name/zod';
|
|
6
|
+
import { g as getCookie } from './shared/server.C1RJffw4.mjs';
|
|
7
|
+
export { S as StandardHandler, a as StandardOpenAPIMatcher, h as call, f as createProcedureClient, d as decode, b as decodeParams, e as encode, g as getEndpointId, m as mergeContext, c as middlewareOutputFn, r as resolveFriendlyStandardHandleOptions, t as toRou3Pattern } from './shared/server.7EG6rqbI.mjs';
|
|
8
|
+
import { J as JsonSchemaXNativeType } from './shared/server.Cuq0WHVy.mjs';
|
|
9
|
+
export { b as JSON_SCHEMA_INPUT_REGISTRY, c as JSON_SCHEMA_OUTPUT_REGISTRY, a as JSON_SCHEMA_REGISTRY, Z as ZodToJsonSchemaConverter, e as eventIterator, g as getEventIteratorSchemaDetails } from './shared/server.Cuq0WHVy.mjs';
|
|
10
|
+
export { getEventMeta, withEventMeta } from '@temporary-name/standard-server';
|
|
11
|
+
import 'cookie';
|
|
12
|
+
import '@temporary-name/server';
|
|
13
|
+
import 'rou3';
|
|
14
|
+
import '@temporary-name/server/openapi';
|
|
15
|
+
import 'zod/v4/core';
|
|
16
|
+
|
|
17
|
+
function validateTokenPrefix(prefix, token) {
|
|
18
|
+
if (prefix && !token.startsWith(prefix)) {
|
|
19
|
+
throw new UnauthorizedError({ message: `Invalid auth token. It must start with "${prefix}"` });
|
|
20
|
+
}
|
|
21
|
+
}
|
|
22
|
+
function validateTokenAuth(config, token, options) {
|
|
23
|
+
const { tokenPrefix, validate } = config;
|
|
24
|
+
validateTokenPrefix(tokenPrefix, token);
|
|
25
|
+
return validate(token, options);
|
|
26
|
+
}
|
|
27
|
+
function runAuth(config, options) {
|
|
28
|
+
switch (config.type) {
|
|
29
|
+
case "header": {
|
|
30
|
+
const authHeader = options.request.headers.get(config.name);
|
|
31
|
+
return authHeader ? validateTokenAuth(config, authHeader, options) : void 0;
|
|
32
|
+
}
|
|
33
|
+
case "query": {
|
|
34
|
+
const { name, tokenPrefix, validate } = config;
|
|
35
|
+
const query = options.request.url.searchParams;
|
|
36
|
+
const token = query.get(name);
|
|
37
|
+
if (!token) return void 0;
|
|
38
|
+
validateTokenPrefix(tokenPrefix, token);
|
|
39
|
+
return validate(token, options);
|
|
40
|
+
}
|
|
41
|
+
case "cookie": {
|
|
42
|
+
const cookie = getCookie(options.request.headers, config.name);
|
|
43
|
+
return cookie ? validateTokenAuth(config, cookie, options) : void 0;
|
|
44
|
+
}
|
|
45
|
+
case "bearer": {
|
|
46
|
+
const authHeader = options.request.headers.get("Authorization");
|
|
47
|
+
if (!authHeader) return void 0;
|
|
48
|
+
const [authType, bearer] = splitFirst(authHeader, " ");
|
|
49
|
+
return authType === "Bearer" ? validateTokenAuth(config, bearer, options) : void 0;
|
|
50
|
+
}
|
|
51
|
+
case "basic": {
|
|
52
|
+
const authHeader = options.request.headers.get("Authorization");
|
|
53
|
+
if (!authHeader) return void 0;
|
|
54
|
+
const [authType, encoded] = splitFirst(authHeader, " ");
|
|
55
|
+
if (authType !== "Basic") return void 0;
|
|
56
|
+
const decoded = Buffer.from(encoded, "base64").toString("utf-8");
|
|
57
|
+
const [username, password] = splitFirst(decoded, ":");
|
|
58
|
+
validateTokenPrefix(config.tokenPrefix, password);
|
|
59
|
+
return config.validate(username, password, options);
|
|
60
|
+
}
|
|
61
|
+
case "none": {
|
|
62
|
+
return false;
|
|
63
|
+
}
|
|
64
|
+
default: {
|
|
65
|
+
assertNever(config);
|
|
66
|
+
}
|
|
67
|
+
}
|
|
68
|
+
}
|
|
69
|
+
function authDescription(config) {
|
|
70
|
+
const { type } = config;
|
|
71
|
+
return type === "basic" ? "a Basic Authentication header" : type === "bearer" ? "a Bearer Authentication header" : type === "header" ? `a header named "${config.name}"` : type === "query" ? `a query parameter named "${config.name}"` : type === "cookie" ? `a cookie named "${config.name}"` : type === "none" ? "no authentication" : assertNever(type);
|
|
72
|
+
}
|
|
73
|
+
|
|
74
|
+
function mergeMeta(meta1, meta2) {
|
|
75
|
+
return { ...meta1, ...meta2 };
|
|
76
|
+
}
|
|
77
|
+
|
|
78
|
+
function decorateMiddleware(middleware) {
|
|
79
|
+
const decorated = ((...args) => middleware(...args));
|
|
80
|
+
decorated.mapInput = (mapInput) => {
|
|
81
|
+
const mapped = decorateMiddleware(
|
|
82
|
+
(options, input, ...rest) => middleware(options, mapInput(input), ...rest)
|
|
83
|
+
);
|
|
84
|
+
return mapped;
|
|
85
|
+
};
|
|
86
|
+
return decorated;
|
|
87
|
+
}
|
|
88
|
+
|
|
89
|
+
function isStartWithMiddlewares(middlewares, compare) {
|
|
90
|
+
if (compare.length > middlewares.length) {
|
|
91
|
+
return false;
|
|
92
|
+
}
|
|
93
|
+
for (let i = 0; i < middlewares.length; i++) {
|
|
94
|
+
if (compare[i] === void 0) {
|
|
95
|
+
return true;
|
|
96
|
+
}
|
|
97
|
+
if (middlewares[i] !== compare[i]) {
|
|
98
|
+
return false;
|
|
99
|
+
}
|
|
100
|
+
}
|
|
101
|
+
return true;
|
|
102
|
+
}
|
|
103
|
+
function mergeMiddlewares(first, second, options) {
|
|
104
|
+
if (options.dedupeLeading && isStartWithMiddlewares(second, first)) {
|
|
105
|
+
return second;
|
|
106
|
+
}
|
|
107
|
+
return [...first, ...second];
|
|
108
|
+
}
|
|
109
|
+
function addMiddleware(middlewares, addition) {
|
|
110
|
+
return [...middlewares, addition];
|
|
111
|
+
}
|
|
112
|
+
|
|
113
|
+
class HasDef {
|
|
114
|
+
/**
|
|
115
|
+
* This property holds the defined options.
|
|
116
|
+
*/
|
|
117
|
+
"~def";
|
|
118
|
+
constructor(def) {
|
|
119
|
+
this["~def"] = def;
|
|
120
|
+
}
|
|
121
|
+
}
|
|
122
|
+
class Contract extends HasDef {
|
|
123
|
+
}
|
|
124
|
+
class Procedure extends HasDef {
|
|
125
|
+
}
|
|
126
|
+
|
|
127
|
+
const VERSION_HEADER_DEFAULT = "Api-Version";
|
|
128
|
+
|
|
129
|
+
function wrapShape(schema) {
|
|
130
|
+
return schema instanceof z.core.$ZodType ? schema : z.strictObject(schema);
|
|
131
|
+
}
|
|
132
|
+
class Builder {
|
|
133
|
+
#def;
|
|
134
|
+
z;
|
|
135
|
+
constructor(def) {
|
|
136
|
+
this.#def = def;
|
|
137
|
+
this.z = new z.SchemaClass();
|
|
138
|
+
}
|
|
139
|
+
/**
|
|
140
|
+
* Adds context fields to the builder that will be passed to middleware and the handler. These fields
|
|
141
|
+
* (unless already provided by earlier middleware) are passed in when calling `handle` on the server adapter
|
|
142
|
+
* (e.g. `NodeHttpHandler`).
|
|
143
|
+
*
|
|
144
|
+
* When calling `use` with a middleware that has required context, the builder must already have that
|
|
145
|
+
* context, either by calling `requireContext` or by using another middleware that provides it.
|
|
146
|
+
*/
|
|
147
|
+
// NB: The CompatibleContext constraint ensures that any overlapping fields between U and TCurrentContext
|
|
148
|
+
// are compatible. This is necessary because fields in TInitialContext can get overwritten in middleware
|
|
149
|
+
// by fields in TCurrentContext.
|
|
150
|
+
requireContext() {
|
|
151
|
+
return this;
|
|
152
|
+
}
|
|
153
|
+
/**
|
|
154
|
+
* Creates a middleware.
|
|
155
|
+
*/
|
|
156
|
+
middleware(middleware) {
|
|
157
|
+
return decorateMiddleware(middleware);
|
|
158
|
+
}
|
|
159
|
+
/**
|
|
160
|
+
* Sets or updates the metadata for the contract.
|
|
161
|
+
* The provided metadata is spared-merged with any existing metadata in the contract.
|
|
162
|
+
*/
|
|
163
|
+
meta(meta) {
|
|
164
|
+
return new Builder({
|
|
165
|
+
...this.#def,
|
|
166
|
+
meta: mergeMeta(this.#def.meta, meta)
|
|
167
|
+
});
|
|
168
|
+
}
|
|
169
|
+
/**
|
|
170
|
+
* Prefixes all procedures in the router.
|
|
171
|
+
* The provided prefix is post-appended to any existing router prefix.
|
|
172
|
+
*
|
|
173
|
+
* @note This option does not affect procedures that do not define a path in their route definition.
|
|
174
|
+
*/
|
|
175
|
+
prefix(prefix) {
|
|
176
|
+
return new this.constructor({
|
|
177
|
+
...this.#def,
|
|
178
|
+
prefix: this.#def.prefix ? `${this.#def.prefix}${prefix}` : prefix
|
|
179
|
+
});
|
|
180
|
+
}
|
|
181
|
+
endpoint(endpoint, options) {
|
|
182
|
+
const contract = this.contract(endpoint, options);
|
|
183
|
+
return new Procedure(Object.assign(contract["~def"], { handler: options.handler }));
|
|
184
|
+
}
|
|
185
|
+
contract(endpoint, options) {
|
|
186
|
+
const { method, path, pathSchema } = parseEndpointDefinition(endpoint, options.path);
|
|
187
|
+
const prefixedPath = (this.#def.prefix ?? "") + path;
|
|
188
|
+
return new Contract({
|
|
189
|
+
...this.#def,
|
|
190
|
+
endpoint: { ...options, method, path: prefixedPath },
|
|
191
|
+
schemas: {
|
|
192
|
+
pathSchema,
|
|
193
|
+
querySchema: wrapShape(options.query ?? {}),
|
|
194
|
+
bodySchema: wrapShape(options.body ?? {}),
|
|
195
|
+
outputSchema: wrapShape(options.response)
|
|
196
|
+
}
|
|
197
|
+
});
|
|
198
|
+
}
|
|
199
|
+
/**
|
|
200
|
+
* Adds a middleware to the pipeline. This builder's current context must satisfy the middleware's required
|
|
201
|
+
* context. If it doesn't, you can call `requireContext` on the builder to add it, or call `use` with
|
|
202
|
+
* another middleware that provides it.
|
|
203
|
+
*/
|
|
204
|
+
// Implementation note: We could automatically add any context from the middleware that's missing in the
|
|
205
|
+
// builder to TInitialContext here, but we don't because:
|
|
206
|
+
//
|
|
207
|
+
// 1. The caller might be expecting that the context is already satisfied. The current design immediately
|
|
208
|
+
// surfaces that as a type error, whereas automatic merging would result in a distant type error at the
|
|
209
|
+
// server's entrypoint where `.handle()` (on NodeHttpHandler or equivalent) is called, and it could be a
|
|
210
|
+
// pain to track that down to the individual middleware that added it (especially if that middleware comes
|
|
211
|
+
// from a third-party library).
|
|
212
|
+
//
|
|
213
|
+
// 2. This approach is more explicit, and results in all the required context generally being added in a
|
|
214
|
+
// a single location (whereever the main `api` builder is created).
|
|
215
|
+
//
|
|
216
|
+
// 3. There are some tricky type safety issues around automatically merging contexts, because fields on
|
|
217
|
+
// TInitialContext can be overwritten by other middleware. There are ways to make it work but this is much
|
|
218
|
+
// simpler.
|
|
219
|
+
use(middleware) {
|
|
220
|
+
return new this.constructor({
|
|
221
|
+
...this.#def,
|
|
222
|
+
middlewares: addMiddleware(this.#def.middlewares, middleware)
|
|
223
|
+
});
|
|
224
|
+
}
|
|
225
|
+
useErrors(errorMap) {
|
|
226
|
+
return new this.constructor({
|
|
227
|
+
...this.#def,
|
|
228
|
+
errorMap: { ...this.#def.errorMap, ...errorMap }
|
|
229
|
+
});
|
|
230
|
+
}
|
|
231
|
+
// The default of false for ValidatedAuthContext is used when you pass in the type 'none'. We use false
|
|
232
|
+
// because we can't use null or undefined (see ValidatedAuthContext) but we still want it to be falsy.
|
|
233
|
+
useAuth(config) {
|
|
234
|
+
const middleware = this.middleware(async (options) => {
|
|
235
|
+
const { next, context } = options;
|
|
236
|
+
const contextAuth = context.auth;
|
|
237
|
+
if (contextAuth) return next();
|
|
238
|
+
const auth = await runAuth(config, options);
|
|
239
|
+
if (auth === void 0) {
|
|
240
|
+
const { authConfigs } = options.procedure["~def"];
|
|
241
|
+
if (contextAuth !== false && config === authConfigs.at(-1)) {
|
|
242
|
+
let authDescriptions = authConfigs.map(authDescription).join(", ");
|
|
243
|
+
if (authConfigs.length > 1) {
|
|
244
|
+
authDescriptions = `one of: ${authDescriptions}`;
|
|
245
|
+
}
|
|
246
|
+
throw new UnauthorizedError({
|
|
247
|
+
message: `Authentication required. You must provide ${authDescriptions}`
|
|
248
|
+
});
|
|
249
|
+
}
|
|
250
|
+
return next();
|
|
251
|
+
}
|
|
252
|
+
return next({ context: { auth } });
|
|
253
|
+
});
|
|
254
|
+
return new this.constructor({
|
|
255
|
+
...this.#def,
|
|
256
|
+
authConfigs: [...this.#def.authConfigs, config],
|
|
257
|
+
middlewares: addMiddleware(this.#def.middlewares, middleware)
|
|
258
|
+
});
|
|
259
|
+
}
|
|
260
|
+
useVersioning(config) {
|
|
261
|
+
const versionHeaderName = config?.headerName ?? VERSION_HEADER_DEFAULT;
|
|
262
|
+
const validate = config && "validate" in config && config.validate ? config.validate : (version) => {
|
|
263
|
+
if (!version) {
|
|
264
|
+
throw new BadRequestError({
|
|
265
|
+
code: "version_header",
|
|
266
|
+
message: `Version header '${versionHeaderName}' is required.`
|
|
267
|
+
});
|
|
268
|
+
}
|
|
269
|
+
if (config && "versions" in config && config.versions && !config.versions.includes(version)) {
|
|
270
|
+
throw new BadRequestError({
|
|
271
|
+
code: "version_header",
|
|
272
|
+
message: `Version header '${versionHeaderName}: ${version}' is unknown. Known versions are ${config.versions.map((version2) => JSON.stringify(version2)).join(", ")}`
|
|
273
|
+
});
|
|
274
|
+
}
|
|
275
|
+
return version;
|
|
276
|
+
};
|
|
277
|
+
const middleware = this.middleware(async (options) => {
|
|
278
|
+
const { next } = options;
|
|
279
|
+
const versionHeaderValue = options.request?.headers.get(versionHeaderName);
|
|
280
|
+
const version = await validate(versionHeaderValue ?? void 0, options);
|
|
281
|
+
return next({ context: { version } });
|
|
282
|
+
});
|
|
283
|
+
return new this.constructor({
|
|
284
|
+
...this.#def,
|
|
285
|
+
middlewares: addMiddleware(this.#def.middlewares, middleware)
|
|
286
|
+
});
|
|
287
|
+
}
|
|
288
|
+
useGating(gates, isGateEnabled) {
|
|
289
|
+
return this.use(({ next, context }) => {
|
|
290
|
+
return z.gatingContext.run(
|
|
291
|
+
(gate) => isGateEnabled(gate, context),
|
|
292
|
+
() => next({ context: { isGateEnabled } })
|
|
293
|
+
);
|
|
294
|
+
});
|
|
295
|
+
}
|
|
296
|
+
}
|
|
297
|
+
const baseApi = new Builder({
|
|
298
|
+
meta: {},
|
|
299
|
+
errorMap: { BadRequestError, UnauthorizedError, ForbiddenError, NotFoundError, InternalServerError },
|
|
300
|
+
middlewares: [
|
|
301
|
+
onError((error, _options) => {
|
|
302
|
+
console.dir(error, { depth: null });
|
|
303
|
+
})
|
|
304
|
+
],
|
|
305
|
+
authConfigs: []
|
|
306
|
+
});
|
|
307
|
+
|
|
308
|
+
const FLEXIBLE_DATE_FORMAT_REGEX = /^[^-]+-[^-]+-[^-]+$/;
|
|
309
|
+
class experimental_JsonSchemaCoercer {
|
|
310
|
+
coerce(schema, value, options = {}) {
|
|
311
|
+
const [, coerced] = this.#coerce(schema, value, options);
|
|
312
|
+
return coerced;
|
|
313
|
+
}
|
|
314
|
+
#coerce(schema, originalValue, options) {
|
|
315
|
+
if (typeof schema === "boolean") {
|
|
316
|
+
return [schema, originalValue];
|
|
317
|
+
}
|
|
318
|
+
if (Array.isArray(schema.type)) {
|
|
319
|
+
return this.#coerce(
|
|
320
|
+
{
|
|
321
|
+
anyOf: schema.type.map((type) => ({ ...schema, type }))
|
|
322
|
+
},
|
|
323
|
+
originalValue,
|
|
324
|
+
options
|
|
325
|
+
);
|
|
326
|
+
}
|
|
327
|
+
let coerced = originalValue;
|
|
328
|
+
let satisfied = true;
|
|
329
|
+
if (typeof schema.$ref === "string") {
|
|
330
|
+
const refSchema = options?.components?.[schema.$ref];
|
|
331
|
+
if (refSchema !== void 0) {
|
|
332
|
+
const [subSatisfied, subCoerced] = this.#coerce(refSchema, coerced, options);
|
|
333
|
+
coerced = subCoerced;
|
|
334
|
+
satisfied = subSatisfied;
|
|
335
|
+
}
|
|
336
|
+
}
|
|
337
|
+
const enumValues = schema.const !== void 0 ? [schema.const] : schema.enum;
|
|
338
|
+
if (enumValues !== void 0 && !enumValues.includes(coerced)) {
|
|
339
|
+
if (typeof coerced === "string") {
|
|
340
|
+
const numberValue = this.#stringToNumber(coerced);
|
|
341
|
+
if (enumValues.includes(numberValue)) {
|
|
342
|
+
coerced = numberValue;
|
|
343
|
+
} else {
|
|
344
|
+
const booleanValue = this.#stringToBoolean(coerced);
|
|
345
|
+
if (enumValues.includes(booleanValue)) {
|
|
346
|
+
coerced = booleanValue;
|
|
347
|
+
} else {
|
|
348
|
+
satisfied = false;
|
|
349
|
+
}
|
|
350
|
+
}
|
|
351
|
+
} else {
|
|
352
|
+
satisfied = false;
|
|
353
|
+
}
|
|
354
|
+
}
|
|
355
|
+
if (typeof schema.type === "string") {
|
|
356
|
+
switch (schema.type) {
|
|
357
|
+
case "null": {
|
|
358
|
+
if (coerced !== null) {
|
|
359
|
+
satisfied = false;
|
|
360
|
+
}
|
|
361
|
+
break;
|
|
362
|
+
}
|
|
363
|
+
case "string": {
|
|
364
|
+
if (typeof coerced !== "string") {
|
|
365
|
+
satisfied = false;
|
|
366
|
+
}
|
|
367
|
+
break;
|
|
368
|
+
}
|
|
369
|
+
case "number": {
|
|
370
|
+
if (typeof coerced === "string") {
|
|
371
|
+
coerced = this.#stringToNumber(coerced);
|
|
372
|
+
}
|
|
373
|
+
if (typeof coerced !== "number") {
|
|
374
|
+
satisfied = false;
|
|
375
|
+
}
|
|
376
|
+
break;
|
|
377
|
+
}
|
|
378
|
+
case "integer": {
|
|
379
|
+
if (typeof coerced === "string") {
|
|
380
|
+
coerced = this.#stringToInteger(coerced);
|
|
381
|
+
}
|
|
382
|
+
if (typeof coerced !== "number" || !Number.isInteger(coerced)) {
|
|
383
|
+
satisfied = false;
|
|
384
|
+
}
|
|
385
|
+
break;
|
|
386
|
+
}
|
|
387
|
+
case "boolean": {
|
|
388
|
+
if (typeof coerced === "string") {
|
|
389
|
+
coerced = this.#stringToBoolean(coerced);
|
|
390
|
+
}
|
|
391
|
+
if (typeof coerced !== "boolean") {
|
|
392
|
+
satisfied = false;
|
|
393
|
+
}
|
|
394
|
+
break;
|
|
395
|
+
}
|
|
396
|
+
case "array": {
|
|
397
|
+
if (Array.isArray(coerced)) {
|
|
398
|
+
const prefixItemSchemas = "prefixItems" in schema ? toArray(schema.prefixItems) : Array.isArray(schema.items) ? schema.items : [];
|
|
399
|
+
const itemSchema = Array.isArray(schema.items) ? schema.additionalItems : schema.items;
|
|
400
|
+
let shouldUseCoercedItems = false;
|
|
401
|
+
const coercedItems = coerced.map((item, i) => {
|
|
402
|
+
const subSchema = prefixItemSchemas[i] ?? itemSchema;
|
|
403
|
+
if (subSchema === void 0) {
|
|
404
|
+
satisfied = false;
|
|
405
|
+
return item;
|
|
406
|
+
}
|
|
407
|
+
const [subSatisfied, subCoerced] = this.#coerce(subSchema, item, options);
|
|
408
|
+
if (!subSatisfied) {
|
|
409
|
+
satisfied = false;
|
|
410
|
+
}
|
|
411
|
+
if (subCoerced !== item) {
|
|
412
|
+
shouldUseCoercedItems = true;
|
|
413
|
+
}
|
|
414
|
+
return subCoerced;
|
|
415
|
+
});
|
|
416
|
+
if (coercedItems.length < prefixItemSchemas.length) {
|
|
417
|
+
satisfied = false;
|
|
418
|
+
}
|
|
419
|
+
if (shouldUseCoercedItems) {
|
|
420
|
+
coerced = coercedItems;
|
|
421
|
+
}
|
|
422
|
+
} else {
|
|
423
|
+
satisfied = false;
|
|
424
|
+
}
|
|
425
|
+
break;
|
|
426
|
+
}
|
|
427
|
+
case "object": {
|
|
428
|
+
if (Array.isArray(coerced)) {
|
|
429
|
+
coerced = { ...coerced };
|
|
430
|
+
}
|
|
431
|
+
if (isObject(coerced)) {
|
|
432
|
+
let shouldUseCoercedItems = false;
|
|
433
|
+
const coercedItems = {};
|
|
434
|
+
const patternProperties = Object.entries(schema.patternProperties ?? {}).map(
|
|
435
|
+
([key, value]) => [new RegExp(key), value]
|
|
436
|
+
);
|
|
437
|
+
for (const key in coerced) {
|
|
438
|
+
const value = coerced[key];
|
|
439
|
+
const subSchema = schema.properties?.[key] ?? patternProperties.find(([pattern]) => pattern.test(key))?.[1] ?? schema.additionalProperties;
|
|
440
|
+
if (value === void 0 && !schema.required?.includes(key)) {
|
|
441
|
+
coercedItems[key] = value;
|
|
442
|
+
} else if (subSchema === void 0) {
|
|
443
|
+
coercedItems[key] = value;
|
|
444
|
+
satisfied = false;
|
|
445
|
+
} else {
|
|
446
|
+
const [subSatisfied, subCoerced] = this.#coerce(subSchema, value, options);
|
|
447
|
+
coercedItems[key] = subCoerced;
|
|
448
|
+
if (!subSatisfied) {
|
|
449
|
+
satisfied = false;
|
|
450
|
+
}
|
|
451
|
+
if (subCoerced !== value) {
|
|
452
|
+
shouldUseCoercedItems = true;
|
|
453
|
+
}
|
|
454
|
+
}
|
|
455
|
+
}
|
|
456
|
+
if (schema.required?.some((key) => !Object.hasOwn(coercedItems, key))) {
|
|
457
|
+
satisfied = false;
|
|
458
|
+
}
|
|
459
|
+
if (shouldUseCoercedItems) {
|
|
460
|
+
coerced = coercedItems;
|
|
461
|
+
}
|
|
462
|
+
} else {
|
|
463
|
+
satisfied = false;
|
|
464
|
+
}
|
|
465
|
+
break;
|
|
466
|
+
}
|
|
467
|
+
}
|
|
468
|
+
}
|
|
469
|
+
if ("x-native-type" in schema && typeof schema["x-native-type"] === "string") {
|
|
470
|
+
switch (schema["x-native-type"]) {
|
|
471
|
+
case JsonSchemaXNativeType.Date: {
|
|
472
|
+
if (typeof coerced === "string") {
|
|
473
|
+
coerced = this.#stringToDate(coerced);
|
|
474
|
+
}
|
|
475
|
+
if (!(coerced instanceof Date)) {
|
|
476
|
+
satisfied = false;
|
|
477
|
+
}
|
|
478
|
+
break;
|
|
479
|
+
}
|
|
480
|
+
case JsonSchemaXNativeType.BigInt: {
|
|
481
|
+
switch (typeof coerced) {
|
|
482
|
+
case "string":
|
|
483
|
+
coerced = this.#stringToBigInt(coerced);
|
|
484
|
+
break;
|
|
485
|
+
case "number":
|
|
486
|
+
coerced = this.#numberToBigInt(coerced);
|
|
487
|
+
break;
|
|
488
|
+
}
|
|
489
|
+
if (typeof coerced !== "bigint") {
|
|
490
|
+
satisfied = false;
|
|
491
|
+
}
|
|
492
|
+
break;
|
|
493
|
+
}
|
|
494
|
+
case JsonSchemaXNativeType.RegExp: {
|
|
495
|
+
if (typeof coerced === "string") {
|
|
496
|
+
coerced = this.#stringToRegExp(coerced);
|
|
497
|
+
}
|
|
498
|
+
if (!(coerced instanceof RegExp)) {
|
|
499
|
+
satisfied = false;
|
|
500
|
+
}
|
|
501
|
+
break;
|
|
502
|
+
}
|
|
503
|
+
case JsonSchemaXNativeType.Url: {
|
|
504
|
+
if (typeof coerced === "string") {
|
|
505
|
+
coerced = this.#stringToURL(coerced);
|
|
506
|
+
}
|
|
507
|
+
if (!(coerced instanceof URL)) {
|
|
508
|
+
satisfied = false;
|
|
509
|
+
}
|
|
510
|
+
break;
|
|
511
|
+
}
|
|
512
|
+
case JsonSchemaXNativeType.Set: {
|
|
513
|
+
if (Array.isArray(coerced)) {
|
|
514
|
+
coerced = this.#arrayToSet(coerced);
|
|
515
|
+
}
|
|
516
|
+
if (!(coerced instanceof Set)) {
|
|
517
|
+
satisfied = false;
|
|
518
|
+
}
|
|
519
|
+
break;
|
|
520
|
+
}
|
|
521
|
+
case JsonSchemaXNativeType.Map: {
|
|
522
|
+
if (Array.isArray(coerced)) {
|
|
523
|
+
coerced = this.#arrayToMap(coerced);
|
|
524
|
+
}
|
|
525
|
+
if (!(coerced instanceof Map)) {
|
|
526
|
+
satisfied = false;
|
|
527
|
+
}
|
|
528
|
+
break;
|
|
529
|
+
}
|
|
530
|
+
}
|
|
531
|
+
}
|
|
532
|
+
if (schema.allOf) {
|
|
533
|
+
for (const subSchema of schema.allOf) {
|
|
534
|
+
const [subSatisfied, subCoerced] = this.#coerce(subSchema, coerced, options);
|
|
535
|
+
coerced = subCoerced;
|
|
536
|
+
if (!subSatisfied) {
|
|
537
|
+
satisfied = false;
|
|
538
|
+
}
|
|
539
|
+
}
|
|
540
|
+
}
|
|
541
|
+
for (const key of ["anyOf", "oneOf"]) {
|
|
542
|
+
if (schema[key]) {
|
|
543
|
+
let bestOptions;
|
|
544
|
+
for (const subSchema of schema[key]) {
|
|
545
|
+
const [subSatisfied, subCoerced] = this.#coerce(subSchema, coerced, options);
|
|
546
|
+
if (subSatisfied) {
|
|
547
|
+
if (!bestOptions || subCoerced === coerced) {
|
|
548
|
+
bestOptions = { coerced: subCoerced, satisfied: subSatisfied };
|
|
549
|
+
}
|
|
550
|
+
if (subCoerced === coerced) {
|
|
551
|
+
break;
|
|
552
|
+
}
|
|
553
|
+
}
|
|
554
|
+
}
|
|
555
|
+
coerced = bestOptions ? bestOptions.coerced : coerced;
|
|
556
|
+
satisfied = bestOptions ? bestOptions.satisfied : false;
|
|
557
|
+
}
|
|
558
|
+
}
|
|
559
|
+
if (typeof schema.not !== "undefined") {
|
|
560
|
+
const [notSatisfied] = this.#coerce(schema.not, coerced, options);
|
|
561
|
+
if (notSatisfied) {
|
|
562
|
+
satisfied = false;
|
|
563
|
+
}
|
|
564
|
+
}
|
|
565
|
+
return [satisfied, coerced];
|
|
566
|
+
}
|
|
567
|
+
#stringToNumber(value) {
|
|
568
|
+
const num = Number.parseFloat(value);
|
|
569
|
+
if (Number.isNaN(num) || num !== Number(value)) {
|
|
570
|
+
return value;
|
|
571
|
+
}
|
|
572
|
+
return num;
|
|
573
|
+
}
|
|
574
|
+
#stringToInteger(value) {
|
|
575
|
+
const num = Number.parseInt(value);
|
|
576
|
+
if (Number.isNaN(num) || num !== Number(value)) {
|
|
577
|
+
return value;
|
|
578
|
+
}
|
|
579
|
+
return num;
|
|
580
|
+
}
|
|
581
|
+
#stringToBoolean(value) {
|
|
582
|
+
const lower = value.toLowerCase();
|
|
583
|
+
if (lower === "false" || lower === "off") {
|
|
584
|
+
return false;
|
|
585
|
+
}
|
|
586
|
+
if (lower === "true" || lower === "on") {
|
|
587
|
+
return true;
|
|
588
|
+
}
|
|
589
|
+
return value;
|
|
590
|
+
}
|
|
591
|
+
#stringToBigInt(value) {
|
|
592
|
+
return guard(() => BigInt(value)) ?? value;
|
|
593
|
+
}
|
|
594
|
+
#numberToBigInt(value) {
|
|
595
|
+
return guard(() => BigInt(value)) ?? value;
|
|
596
|
+
}
|
|
597
|
+
#stringToDate(value) {
|
|
598
|
+
const date = new Date(value);
|
|
599
|
+
if (Number.isNaN(date.getTime()) || !FLEXIBLE_DATE_FORMAT_REGEX.test(value)) {
|
|
600
|
+
return value;
|
|
601
|
+
}
|
|
602
|
+
return date;
|
|
603
|
+
}
|
|
604
|
+
#stringToRegExp(value) {
|
|
605
|
+
const match = value.match(/^\/(.*)\/([a-z]*)$/);
|
|
606
|
+
if (match) {
|
|
607
|
+
const [, pattern, flags] = match;
|
|
608
|
+
return guard(() => new RegExp(pattern, flags)) ?? value;
|
|
609
|
+
}
|
|
610
|
+
return value;
|
|
611
|
+
}
|
|
612
|
+
#stringToURL(value) {
|
|
613
|
+
return guard(() => new URL(value)) ?? value;
|
|
614
|
+
}
|
|
615
|
+
#arrayToSet(value) {
|
|
616
|
+
const set = new Set(value);
|
|
617
|
+
if (set.size !== value.length) {
|
|
618
|
+
return value;
|
|
619
|
+
}
|
|
620
|
+
return set;
|
|
621
|
+
}
|
|
622
|
+
#arrayToMap(value) {
|
|
623
|
+
if (value.some((item) => !Array.isArray(item) || item.length !== 2)) {
|
|
624
|
+
return value;
|
|
625
|
+
}
|
|
626
|
+
const result = new Map(value);
|
|
627
|
+
if (result.size !== value.length) {
|
|
628
|
+
return value;
|
|
629
|
+
}
|
|
630
|
+
return result;
|
|
631
|
+
}
|
|
632
|
+
}
|
|
633
|
+
|
|
634
|
+
const initialSchemas = {
|
|
635
|
+
pathSchema: z.strictObject({}),
|
|
636
|
+
querySchema: z.strictObject({}),
|
|
637
|
+
bodySchema: z.strictObject({}),
|
|
638
|
+
outputSchema: z.unknown()
|
|
639
|
+
};
|
|
640
|
+
|
|
641
|
+
function isSchemaIssue(issue) {
|
|
642
|
+
if (!isTypescriptObject(issue) || typeof issue.message !== "string") {
|
|
643
|
+
return false;
|
|
644
|
+
}
|
|
645
|
+
if (issue.path !== void 0) {
|
|
646
|
+
if (!Array.isArray(issue.path)) {
|
|
647
|
+
return false;
|
|
648
|
+
}
|
|
649
|
+
if (!issue.path.every(
|
|
650
|
+
(segment) => isPropertyKey(segment) || isTypescriptObject(segment) && isPropertyKey(segment.key)
|
|
651
|
+
)) {
|
|
652
|
+
return false;
|
|
653
|
+
}
|
|
654
|
+
}
|
|
655
|
+
return true;
|
|
656
|
+
}
|
|
657
|
+
|
|
658
|
+
async function generateStainlessConfig(resources, baseConfig) {
|
|
659
|
+
const config = Object.assign({ resources: {} }, clone(baseConfig));
|
|
660
|
+
const inputResources = await unlazyResources(resources);
|
|
661
|
+
for (const inputResource of inputResources) {
|
|
662
|
+
const configResource = getResourceFromName(inputResource.name, config.resources);
|
|
663
|
+
Object.assign(configResource, inputResource.config);
|
|
664
|
+
for (const [methodName, contract] of Object.entries(inputResource.endpoints)) {
|
|
665
|
+
const def = contract["~def"];
|
|
666
|
+
const methods = configResource.methods ??= {};
|
|
667
|
+
if (methods[methodName] !== void 0) {
|
|
668
|
+
throw new Error(
|
|
669
|
+
`The baseConfig passed to generateStainlessConfig must not specify resource methods. Those should be configured via the .endpointOpts builder method`
|
|
670
|
+
);
|
|
671
|
+
}
|
|
672
|
+
methods[methodName] = makeMethod(def);
|
|
673
|
+
}
|
|
674
|
+
}
|
|
675
|
+
return config;
|
|
676
|
+
}
|
|
677
|
+
function getResourceFromName(name, resources) {
|
|
678
|
+
const nameParts = name.split(".");
|
|
679
|
+
let i = 0;
|
|
680
|
+
for (; i < nameParts.length - 1; i++) {
|
|
681
|
+
resources = (resources[nameParts[i]] ??= {}).subresources ??= {};
|
|
682
|
+
}
|
|
683
|
+
const finalPart = nameParts[i];
|
|
684
|
+
const existingResource = resources[finalPart];
|
|
685
|
+
if (existingResource?.methods !== void 0) {
|
|
686
|
+
throw new Error(`Multiple ApiResources have the same name: "${name}"`);
|
|
687
|
+
}
|
|
688
|
+
resources[finalPart] = existingResource ?? {};
|
|
689
|
+
return resources[finalPart];
|
|
690
|
+
}
|
|
691
|
+
function makeMethod(def) {
|
|
692
|
+
const { endpoint } = def;
|
|
693
|
+
return `${endpoint.method?.toLowerCase()} ${endpoint.path}`;
|
|
694
|
+
}
|
|
695
|
+
|
|
696
|
+
export { BadRequestError, Builder, Contract, ForbiddenError, InternalServerError, JsonSchemaXNativeType, NotFoundError, Procedure, UnauthorizedError, addMiddleware, baseApi, decorateMiddleware, experimental_JsonSchemaCoercer, generateStainlessConfig, initialSchemas, isSchemaIssue, isStartWithMiddlewares, mergeMeta, mergeMiddlewares, parseEndpointDefinition, unlazyResources };
|