@adaptivestone/framework 5.0.1 → 5.1.1
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/CHANGELOG.md +32 -0
- package/dist/commands/OpenApi.d.ts +26 -0
- package/dist/commands/OpenApi.js +101 -0
- package/dist/commands/OpenApi.js.map +1 -0
- package/dist/commands/Routes.d.ts +17 -0
- package/dist/commands/Routes.js +35 -0
- package/dist/commands/Routes.js.map +1 -0
- package/dist/config/cache.d.ts +14 -0
- package/dist/config/cache.js +14 -0
- package/dist/config/cache.js.map +1 -0
- package/dist/controllers/index.js +34 -4
- package/dist/controllers/index.js.map +1 -1
- package/dist/helpers/appInstance.d.ts +6 -0
- package/dist/helpers/appInstance.js +13 -0
- package/dist/helpers/appInstance.js.map +1 -1
- package/dist/modules/BaseModel.d.ts +10 -0
- package/dist/modules/BaseModel.js +25 -0
- package/dist/modules/BaseModel.js.map +1 -1
- package/dist/server.d.ts +20 -1
- package/dist/server.js +24 -1
- package/dist/server.js.map +1 -1
- package/dist/services/cache/Cache.d.ts +3 -4
- package/dist/services/cache/Cache.js +43 -34
- package/dist/services/cache/Cache.js.map +1 -1
- package/dist/services/cache/CacheDriver.d.ts +19 -0
- package/dist/services/cache/CacheDriver.js +2 -0
- package/dist/services/cache/CacheDriver.js.map +1 -0
- package/dist/services/cache/drivers/MemoryDriver.d.ts +14 -0
- package/dist/services/cache/drivers/MemoryDriver.js +40 -0
- package/dist/services/cache/drivers/MemoryDriver.js.map +1 -0
- package/dist/services/cache/drivers/RedisDriver.d.ts +22 -0
- package/dist/services/cache/drivers/RedisDriver.js +44 -0
- package/dist/services/cache/drivers/RedisDriver.js.map +1 -0
- package/dist/services/documentation/OpenApiGenerator.d.ts +39 -0
- package/dist/services/documentation/OpenApiGenerator.js +296 -0
- package/dist/services/documentation/OpenApiGenerator.js.map +1 -0
- package/dist/services/http/HttpServer.d.ts +23 -0
- package/dist/services/http/HttpServer.js +57 -0
- package/dist/services/http/HttpServer.js.map +1 -1
- package/dist/services/http/builtinErrorHandlers.d.ts +53 -0
- package/dist/services/http/builtinErrorHandlers.js +188 -0
- package/dist/services/http/builtinErrorHandlers.js.map +1 -0
- package/dist/services/http/httpErrors.d.ts +30 -0
- package/dist/services/http/httpErrors.js +46 -0
- package/dist/services/http/httpErrors.js.map +1 -0
- package/dist/services/http/middleware/AbstractMiddleware.d.ts +25 -7
- package/dist/services/http/middleware/AbstractMiddleware.js +14 -0
- package/dist/services/http/middleware/AbstractMiddleware.js.map +1 -1
- package/dist/services/http/middleware/GetUserByToken.d.ts +13 -0
- package/dist/services/http/middleware/GetUserByToken.js +5 -1
- package/dist/services/http/middleware/GetUserByToken.js.map +1 -1
- package/dist/services/http/middleware/RateLimiter.d.ts +8 -2
- package/dist/services/http/middleware/RateLimiter.js +38 -13
- package/dist/services/http/middleware/RateLimiter.js.map +1 -1
- package/dist/services/http/routing/RouteNode.d.ts +2 -0
- package/dist/services/validate/drivers/StandardSchemaDriver.d.ts +5 -2
- package/dist/services/validate/drivers/StandardSchemaDriver.js +24 -3
- package/dist/services/validate/drivers/StandardSchemaDriver.js.map +1 -1
- package/dist/services/validate/drivers/YupDriver.js +91 -2
- package/dist/services/validate/drivers/YupDriver.js.map +1 -1
- package/dist/services/validate/types.d.ts +7 -4
- package/dist/tests/globalSetupNodeTest.d.ts +2 -0
- package/dist/tests/globalSetupNodeTest.js +23 -0
- package/dist/tests/globalSetupNodeTest.js.map +1 -0
- package/dist/tests/globalSetupVitest.js +6 -13
- package/dist/tests/globalSetupVitest.js.map +1 -1
- package/dist/tests/nodeRunner.node-test.d.ts +14 -0
- package/dist/tests/nodeRunner.node-test.js +41 -0
- package/dist/tests/nodeRunner.node-test.js.map +1 -0
- package/dist/tests/nodeRunnerShared.node-test.d.ts +14 -0
- package/dist/tests/nodeRunnerShared.node-test.js +39 -0
- package/dist/tests/nodeRunnerShared.node-test.js.map +1 -0
- package/dist/tests/setupFramework.d.ts +33 -0
- package/dist/tests/setupFramework.js +134 -0
- package/dist/tests/setupFramework.js.map +1 -0
- package/dist/tests/setupNodeTest.d.ts +1 -0
- package/dist/tests/setupNodeTest.js +16 -0
- package/dist/tests/setupNodeTest.js.map +1 -0
- package/dist/tests/setupVitest.js +8 -99
- package/dist/tests/setupVitest.js.map +1 -1
- package/package.json +10 -3
|
@@ -0,0 +1,188 @@
|
|
|
1
|
+
import mongoose from 'mongoose';
|
|
2
|
+
import { HttpError } from "./httpErrors.js";
|
|
3
|
+
/** A numeric/Date schema bound (both are constants, never input) → text. */
|
|
4
|
+
function renderBound(bound) {
|
|
5
|
+
if (typeof bound === 'number') {
|
|
6
|
+
return String(bound);
|
|
7
|
+
}
|
|
8
|
+
if (bound instanceof Date) {
|
|
9
|
+
return bound.toISOString();
|
|
10
|
+
}
|
|
11
|
+
return undefined;
|
|
12
|
+
}
|
|
13
|
+
/**
|
|
14
|
+
* Build a client-safe message for one failing Mongoose path, rebuilt from the
|
|
15
|
+
* error's STRUCTURED fields (`kind` + the constraint on `properties`) only —
|
|
16
|
+
* never from `err.message`. Mongoose's default templates interpolate the
|
|
17
|
+
* rejected `{VALUE}` (`Path \`title\` (\`<300 chars>\`) is longer than …`,
|
|
18
|
+
* `Cast to Number failed for value "<PII>" …`), so echoing `.message` would
|
|
19
|
+
* leak the submission into the 400 body AND the warn-level log. Rebuilding from
|
|
20
|
+
* `kind` mirrors the `YupDriver`, which strips `value`/`originalValue` for the
|
|
21
|
+
* same reason.
|
|
22
|
+
*
|
|
23
|
+
* Model-defined CUSTOM messages (`maxlength: [50, 'Name too long']`) are NOT
|
|
24
|
+
* passed through: a custom string is indistinguishable from a templated default
|
|
25
|
+
* that embedded the value, so ALL messages are rebuilt generically. Deliberate
|
|
26
|
+
* trade-off — the route validator owns user-facing/i18n wording; this is only a
|
|
27
|
+
* last-resort fallback for a schema gap, and plain English by design.
|
|
28
|
+
*/
|
|
29
|
+
function safeValidationMessage(error) {
|
|
30
|
+
// CastError: `kind` is the target type the value could not become (mixed
|
|
31
|
+
// casing at runtime — `Number`, `ObjectId`, but `date`). No constraint to
|
|
32
|
+
// surface; the stringified value lives on `stringValue`, left untouched.
|
|
33
|
+
if (error.name === 'CastError') {
|
|
34
|
+
switch (error.kind?.toLowerCase()) {
|
|
35
|
+
case 'number':
|
|
36
|
+
case 'decimal128':
|
|
37
|
+
return 'Must be a number';
|
|
38
|
+
case 'date':
|
|
39
|
+
return 'Must be a valid date';
|
|
40
|
+
case 'objectid':
|
|
41
|
+
return 'Must be a valid id';
|
|
42
|
+
case 'boolean':
|
|
43
|
+
return 'Must be a boolean';
|
|
44
|
+
case 'string':
|
|
45
|
+
return 'Must be a string';
|
|
46
|
+
case 'buffer':
|
|
47
|
+
return 'Must be a valid binary value';
|
|
48
|
+
default:
|
|
49
|
+
return 'Invalid value';
|
|
50
|
+
}
|
|
51
|
+
}
|
|
52
|
+
const props = error.properties;
|
|
53
|
+
switch (error.kind) {
|
|
54
|
+
case 'required':
|
|
55
|
+
return 'Required';
|
|
56
|
+
case 'enum': {
|
|
57
|
+
// enum values are API-contract constants (the allowed set), safe to name.
|
|
58
|
+
const values = props.enumValues;
|
|
59
|
+
return values && values.length > 0
|
|
60
|
+
? `Must be one of: ${values.map(String).join(', ')}`
|
|
61
|
+
: 'Invalid value';
|
|
62
|
+
}
|
|
63
|
+
case 'min': {
|
|
64
|
+
const bound = renderBound(props.min);
|
|
65
|
+
return bound === undefined
|
|
66
|
+
? 'Value is too small'
|
|
67
|
+
: `Must be at least ${bound}`;
|
|
68
|
+
}
|
|
69
|
+
case 'max': {
|
|
70
|
+
const bound = renderBound(props.max);
|
|
71
|
+
return bound === undefined
|
|
72
|
+
? 'Value is too large'
|
|
73
|
+
: `Must be at most ${bound}`;
|
|
74
|
+
}
|
|
75
|
+
case 'minlength':
|
|
76
|
+
return typeof props.minlength === 'number'
|
|
77
|
+
? `Must be at least ${props.minlength} characters`
|
|
78
|
+
: 'Too short';
|
|
79
|
+
case 'maxlength':
|
|
80
|
+
return typeof props.maxlength === 'number'
|
|
81
|
+
? `Must be at most ${props.maxlength} characters`
|
|
82
|
+
: 'Too long';
|
|
83
|
+
case 'regexp':
|
|
84
|
+
return 'Invalid format';
|
|
85
|
+
default:
|
|
86
|
+
// `user` (custom validator fns, whose message we can't trust) and any
|
|
87
|
+
// kind we don't model land on the generic fallback.
|
|
88
|
+
return 'Invalid value';
|
|
89
|
+
}
|
|
90
|
+
}
|
|
91
|
+
/**
|
|
92
|
+
* Sanitize an error for the RESOLVED-branch log line. A raw Mongoose
|
|
93
|
+
* `ValidationError`'s `.message` (and `.stack` header) interpolates the
|
|
94
|
+
* rejected `{VALUE}`, so `logger.warn(err)` would leak the submission into
|
|
95
|
+
* logs — and whatever ships them (Sentry, retention) — even after the 400
|
|
96
|
+
* body was sanitized. Rebuild a fresh `Error` that reuses the per-path
|
|
97
|
+
* `safeValidationMessage` texts under the safe static prefix
|
|
98
|
+
* (`<ModelName> validation failed`); its stack is minted here, input-free.
|
|
99
|
+
* Anything else passes through untouched. The UNRESOLVED 500 path deliberately
|
|
100
|
+
* keeps logging the original error in full: that branch is a server-side
|
|
101
|
+
* defect, and the developer needs every detail.
|
|
102
|
+
*/
|
|
103
|
+
export function toLoggableError(err) {
|
|
104
|
+
if (!(err instanceof mongoose.Error.ValidationError)) {
|
|
105
|
+
return err;
|
|
106
|
+
}
|
|
107
|
+
const parts = Object.entries(err.errors).map(([path, fieldError]) => `${path}: ${safeValidationMessage(fieldError)}`);
|
|
108
|
+
// Mongoose keeps the static, value-free prefix (`<ModelName> validation
|
|
109
|
+
// failed`) on `_message` — a runtime field its published types omit.
|
|
110
|
+
const rawPrefix = err._message;
|
|
111
|
+
const prefix = typeof rawPrefix === 'string' ? rawPrefix : 'Validation failed';
|
|
112
|
+
const sanitized = new Error(`${prefix} (safety net, sanitized): ${parts.join(', ')}`);
|
|
113
|
+
sanitized.name = 'ValidationError';
|
|
114
|
+
return sanitized;
|
|
115
|
+
}
|
|
116
|
+
/**
|
|
117
|
+
* Safety net for an escaped Mongoose `ValidationError`: returns a per-field
|
|
118
|
+
* `{ <path>: message }` map ONLY when every failing model path is a field the
|
|
119
|
+
* client actually sent — the keys of the validated `request` ∪ `query`, minus
|
|
120
|
+
* the framework-injected `contentType` discriminant (see
|
|
121
|
+
* `ControllerManager.#wrapHandlerEntry`). A nested path (`profile.name`)
|
|
122
|
+
* matches on its first segment and is reported under the full path (the
|
|
123
|
+
* client owns that subtree). Any renamed/internal path → `null`, so the
|
|
124
|
+
* caller keeps the honest 500 and never leaks a non-public field name.
|
|
125
|
+
*
|
|
126
|
+
* Each message is rebuilt by `safeValidationMessage` from the validation
|
|
127
|
+
* `kind` + constraint — the raw `err.errors[path].message` is NEVER used, so
|
|
128
|
+
* the submitted value can't ride into the response or the log.
|
|
129
|
+
*/
|
|
130
|
+
export function matchedClientValidationErrors(err, req) {
|
|
131
|
+
const failingPaths = Object.keys(err.errors);
|
|
132
|
+
if (failingPaths.length === 0) {
|
|
133
|
+
return null;
|
|
134
|
+
}
|
|
135
|
+
const inputKeys = new Set();
|
|
136
|
+
for (const source of [req.appInfo.request, req.appInfo.query]) {
|
|
137
|
+
if (source) {
|
|
138
|
+
for (const key of Object.keys(source)) {
|
|
139
|
+
inputKeys.add(key);
|
|
140
|
+
}
|
|
141
|
+
}
|
|
142
|
+
}
|
|
143
|
+
inputKeys.delete('contentType');
|
|
144
|
+
const errors = {};
|
|
145
|
+
for (const failingPath of failingPaths) {
|
|
146
|
+
if (!inputKeys.has(failingPath.split('.')[0])) {
|
|
147
|
+
return null;
|
|
148
|
+
}
|
|
149
|
+
errors[failingPath] = safeValidationMessage(err.errors[failingPath]);
|
|
150
|
+
}
|
|
151
|
+
return errors;
|
|
152
|
+
}
|
|
153
|
+
/**
|
|
154
|
+
* Framework built-in registry entries, checked AFTER any consumer-registered
|
|
155
|
+
* handlers ("yours win"):
|
|
156
|
+
* 1. `HttpError` → its own status / `body ?? { message }`; `verbose`
|
|
157
|
+
* (deliberate control flow, not a defect).
|
|
158
|
+
* 2. Escaped Mongoose `ValidationError` → the safety net above; `warn`
|
|
159
|
+
* (signals a route schema missing a constraint the model enforces).
|
|
160
|
+
*/
|
|
161
|
+
export function builtInErrorHandlers() {
|
|
162
|
+
return [
|
|
163
|
+
{
|
|
164
|
+
errorClass: HttpError,
|
|
165
|
+
// Entries are stored type-erased (`ErrorHandlerFn`); `resolveError`
|
|
166
|
+
// guarantees `instanceof errorClass` before the call.
|
|
167
|
+
handler: (err) => {
|
|
168
|
+
const httpErr = err;
|
|
169
|
+
return {
|
|
170
|
+
status: httpErr.status,
|
|
171
|
+
body: httpErr.body ?? { message: httpErr.message },
|
|
172
|
+
};
|
|
173
|
+
},
|
|
174
|
+
logLevel: 'verbose',
|
|
175
|
+
},
|
|
176
|
+
{
|
|
177
|
+
errorClass: mongoose.Error.ValidationError,
|
|
178
|
+
handler: (err, req) => {
|
|
179
|
+
const clientErrors = matchedClientValidationErrors(err, req);
|
|
180
|
+
return clientErrors
|
|
181
|
+
? { status: 400, body: { errors: clientErrors } }
|
|
182
|
+
: null;
|
|
183
|
+
},
|
|
184
|
+
logLevel: 'warn',
|
|
185
|
+
},
|
|
186
|
+
];
|
|
187
|
+
}
|
|
188
|
+
//# sourceMappingURL=builtinErrorHandlers.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"builtinErrorHandlers.js","sourceRoot":"","sources":["../../../src/services/http/builtinErrorHandlers.ts"],"names":[],"mappings":"AAAA,OAAO,QAAQ,MAAM,UAAU,CAAC;AAEhC,OAAO,EAAE,SAAS,EAAE,MAAM,iBAAiB,CAAC;AAsD5C,4EAA4E;AAC5E,SAAS,WAAW,CAAC,KAAc;IACjC,IAAI,OAAO,KAAK,KAAK,QAAQ,EAAE,CAAC;QAC9B,OAAO,MAAM,CAAC,KAAK,CAAC,CAAC;IACvB,CAAC;IACD,IAAI,KAAK,YAAY,IAAI,EAAE,CAAC;QAC1B,OAAO,KAAK,CAAC,WAAW,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O,MAAM,CAAC;AAChB,CAAC;AAED;;;;;;;GAOG;AACH,MAAM,UAAU,oBAAoB;IAClC,OAAO;QACL;YACE,UAAU,EAAE,SAAS;YACrB,oEAAoE;YACpE,sDAAsD;YACtD,OAAO,EAAE,CAAC,GAAG,EAAE,EAAE;gBACf,MAAM,OAAO,GAAG,GAAgB,CAAC;gBACjC,OAAO;oBACL,MAAM,EAAE,OAAO,CAAC,MAAM;oBACtB,IAAI,EAAE,OAAO,CAAC,IAAI,IAAI,EAAE,OAAO,EAAE,OAAO,CAAC,OAAO,EAAE;iBACnD,CAAC;YACJ,CAAC;YACD,QAAQ,EAAE,SAAS;SACpB;QACD;YACE,UAAU,EAAE,QAAQ,CAAC,KAAK,CAAC,eAAe;YAC1C,OAAO,EAAE,CAAC,GAAG,EAAE,GAAG,EAAE,EAAE;gBACpB,MAAM,YAAY,GAAG,6BAA6B,CAChD,GAAqC,EACrC,GAAG,CACJ,CAAC;gBACF,OAAO,YAAY;oBACjB,CAAC,CAAC,EAAE,MAAM,EAAE,GAAG,EAAE,IAAI,EAAE,EAAE,MAAM,EAAE,YAAY,EAAE,EAAE;oBACjD,CAAC,CAAC,IAAI,CAAC;YACX,CAAC;YACD,QAAQ,EAAE,MAAM;SACjB;KACF,CAAC;AACJ,CAAC"}
|
|
@@ -0,0 +1,30 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Throwable HTTP errors — the deliberate way to produce a status from deep
|
|
3
|
+
* business logic without threading `res`. Thrown under a route handler, they
|
|
4
|
+
* resolve through the error-handler registry
|
|
5
|
+
* (`HttpServer.registerErrorHandler`) via a built-in mapper:
|
|
6
|
+
* `status` + `body ?? { message }`, logged at `verbose` (control flow, not a
|
|
7
|
+
* defect). Subclass for other statuses, or construct the base directly:
|
|
8
|
+
* `new HttpError(422, 'Unprocessable')`.
|
|
9
|
+
*/
|
|
10
|
+
export declare class HttpError extends Error {
|
|
11
|
+
readonly status: number;
|
|
12
|
+
/** Optional response-body override; the mapper falls back to `{ message }`. */
|
|
13
|
+
readonly body?: unknown;
|
|
14
|
+
constructor(status: number, message: string, body?: unknown);
|
|
15
|
+
}
|
|
16
|
+
export declare class BadRequestError extends HttpError {
|
|
17
|
+
constructor(message?: string, body?: unknown);
|
|
18
|
+
}
|
|
19
|
+
export declare class UnauthorizedError extends HttpError {
|
|
20
|
+
constructor(message?: string, body?: unknown);
|
|
21
|
+
}
|
|
22
|
+
export declare class ForbiddenError extends HttpError {
|
|
23
|
+
constructor(message?: string, body?: unknown);
|
|
24
|
+
}
|
|
25
|
+
export declare class NotFoundError extends HttpError {
|
|
26
|
+
constructor(message?: string, body?: unknown);
|
|
27
|
+
}
|
|
28
|
+
export declare class ConflictError extends HttpError {
|
|
29
|
+
constructor(message?: string, body?: unknown);
|
|
30
|
+
}
|
|
@@ -0,0 +1,46 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Throwable HTTP errors — the deliberate way to produce a status from deep
|
|
3
|
+
* business logic without threading `res`. Thrown under a route handler, they
|
|
4
|
+
* resolve through the error-handler registry
|
|
5
|
+
* (`HttpServer.registerErrorHandler`) via a built-in mapper:
|
|
6
|
+
* `status` + `body ?? { message }`, logged at `verbose` (control flow, not a
|
|
7
|
+
* defect). Subclass for other statuses, or construct the base directly:
|
|
8
|
+
* `new HttpError(422, 'Unprocessable')`.
|
|
9
|
+
*/
|
|
10
|
+
export class HttpError extends Error {
|
|
11
|
+
status;
|
|
12
|
+
/** Optional response-body override; the mapper falls back to `{ message }`. */
|
|
13
|
+
body;
|
|
14
|
+
constructor(status, message, body) {
|
|
15
|
+
super(message);
|
|
16
|
+
this.name = new.target.name;
|
|
17
|
+
this.status = status;
|
|
18
|
+
this.body = body;
|
|
19
|
+
}
|
|
20
|
+
}
|
|
21
|
+
export class BadRequestError extends HttpError {
|
|
22
|
+
constructor(message = 'Bad request', body) {
|
|
23
|
+
super(400, message, body);
|
|
24
|
+
}
|
|
25
|
+
}
|
|
26
|
+
export class UnauthorizedError extends HttpError {
|
|
27
|
+
constructor(message = 'Unauthorized', body) {
|
|
28
|
+
super(401, message, body);
|
|
29
|
+
}
|
|
30
|
+
}
|
|
31
|
+
export class ForbiddenError extends HttpError {
|
|
32
|
+
constructor(message = 'Forbidden', body) {
|
|
33
|
+
super(403, message, body);
|
|
34
|
+
}
|
|
35
|
+
}
|
|
36
|
+
export class NotFoundError extends HttpError {
|
|
37
|
+
constructor(message = 'Not found', body) {
|
|
38
|
+
super(404, message, body);
|
|
39
|
+
}
|
|
40
|
+
}
|
|
41
|
+
export class ConflictError extends HttpError {
|
|
42
|
+
constructor(message = 'Conflict', body) {
|
|
43
|
+
super(409, message, body);
|
|
44
|
+
}
|
|
45
|
+
}
|
|
46
|
+
//# sourceMappingURL=httpErrors.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"httpErrors.js","sourceRoot":"","sources":["../../../src/services/http/httpErrors.ts"],"names":[],"mappings":"AAAA;;;;;;;;GAQG;AACH,MAAM,OAAO,SAAU,SAAQ,KAAK;IACzB,MAAM,CAAS;IAExB,+EAA+E;IACtE,IAAI,CAAW;IAExB,YAAY,MAAc,EAAE,OAAe,EAAE,IAAc;QACzD,KAAK,CAAC,OAAO,CAAC,CAAC;QACf,IAAI,CAAC,IAAI,GAAG,GAAG,CAAC,MAAM,CAAC,IAAI,CAAC;QAC5B,IAAI,CAAC,MAAM,GAAG,MAAM,CAAC;QACrB,IAAI,CAAC,IAAI,GAAG,IAAI,CAAC;IACnB,CAAC;CACF;AAED,MAAM,OAAO,eAAgB,SAAQ,SAAS;IAC5C,YAAY,OAAO,GAAG,aAAa,EAAE,IAAc;QACjD,KAAK,CAAC,GAAG,EAAE,OAAO,EAAE,IAAI,CAAC,CAAC;IAC5B,CAAC;CACF;AAED,MAAM,OAAO,iBAAkB,SAAQ,SAAS;IAC9C,YAAY,OAAO,GAAG,cAAc,EAAE,IAAc;QAClD,KAAK,CAAC,GAAG,EAAE,OAAO,EAAE,IAAI,CAAC,CAAC;IAC5B,CAAC;CACF;AAED,MAAM,OAAO,cAAe,SAAQ,SAAS;IAC3C,YAAY,OAAO,GAAG,WAAW,EAAE,IAAc;QAC/C,KAAK,CAAC,GAAG,EAAE,OAAO,EAAE,IAAI,CAAC,CAAC;IAC5B,CAAC;CACF;AAED,MAAM,OAAO,aAAc,SAAQ,SAAS;IAC1C,YAAY,OAAO,GAAG,WAAW,EAAE,IAAc;QAC/C,KAAK,CAAC,GAAG,EAAE,OAAO,EAAE,IAAI,CAAC,CAAC;IAC5B,CAAC;CACF;AAED,MAAM,OAAO,aAAc,SAAQ,SAAS;IAC1C,YAAY,OAAO,GAAG,UAAU,EAAE,IAAc;QAC9C,KAAK,CAAC,GAAG,EAAE,OAAO,EAAE,IAAI,CAAC,CAAC;IAC5B,CAAC;CACF"}
|
|
@@ -3,17 +3,35 @@ import Base from '../../../modules/Base.ts';
|
|
|
3
3
|
import type { IApp } from '../../../server.ts';
|
|
4
4
|
import type { StandardSchemaV1 } from '../../validate/types.ts';
|
|
5
5
|
import type { FrameworkRequest } from '../HttpServer.ts';
|
|
6
|
+
/**
|
|
7
|
+
* One security scheme a middleware contributes to the OpenAPI document
|
|
8
|
+
* (`components.securitySchemes`). Mirrors the OpenAPI Security Scheme Object:
|
|
9
|
+
* `type: 'apiKey'` uses `name` + `in`; `type: 'http'` uses `scheme`.
|
|
10
|
+
*/
|
|
11
|
+
export interface AuthParameter {
|
|
12
|
+
name: string;
|
|
13
|
+
type: string;
|
|
14
|
+
in?: string;
|
|
15
|
+
scheme?: string;
|
|
16
|
+
description: string;
|
|
17
|
+
}
|
|
6
18
|
declare class AbstractMiddleware extends Base {
|
|
7
19
|
params?: Record<string, unknown>;
|
|
8
20
|
constructor(app: IApp, params?: Record<string, unknown>);
|
|
9
21
|
static get description(): string;
|
|
10
|
-
|
|
11
|
-
|
|
12
|
-
|
|
13
|
-
|
|
14
|
-
|
|
15
|
-
|
|
16
|
-
|
|
22
|
+
/**
|
|
23
|
+
* Security schemes this middleware enforces, declared **statically** so the
|
|
24
|
+
* OpenAPI generator can read them off the class with zero instantiation.
|
|
25
|
+
* Default `[]` (the middleware contributes no auth requirement). Override on
|
|
26
|
+
* subclasses that gate requests (e.g. token/bearer auth).
|
|
27
|
+
*/
|
|
28
|
+
static get usedAuthParameters(): AuthParameter[];
|
|
29
|
+
/**
|
|
30
|
+
* @deprecated Since 5.0.0 — declare auth schemes **statically**
|
|
31
|
+
* (`static get usedAuthParameters()`). The instance form is read only as a
|
|
32
|
+
* fallback and will be removed in v6.
|
|
33
|
+
*/
|
|
34
|
+
get usedAuthParameters(): AuthParameter[];
|
|
17
35
|
/**
|
|
18
36
|
* Schema describing query parameters this middleware consumes. Declared
|
|
19
37
|
* **statically** so the framework (and codegen) can read it without
|
|
@@ -8,6 +8,20 @@ class AbstractMiddleware extends Base {
|
|
|
8
8
|
static get description() {
|
|
9
9
|
return 'Middleware description. Please provide own';
|
|
10
10
|
}
|
|
11
|
+
/**
|
|
12
|
+
* Security schemes this middleware enforces, declared **statically** so the
|
|
13
|
+
* OpenAPI generator can read them off the class with zero instantiation.
|
|
14
|
+
* Default `[]` (the middleware contributes no auth requirement). Override on
|
|
15
|
+
* subclasses that gate requests (e.g. token/bearer auth).
|
|
16
|
+
*/
|
|
17
|
+
static get usedAuthParameters() {
|
|
18
|
+
return [];
|
|
19
|
+
}
|
|
20
|
+
/**
|
|
21
|
+
* @deprecated Since 5.0.0 — declare auth schemes **statically**
|
|
22
|
+
* (`static get usedAuthParameters()`). The instance form is read only as a
|
|
23
|
+
* fallback and will be removed in v6.
|
|
24
|
+
*/
|
|
11
25
|
get usedAuthParameters() {
|
|
12
26
|
return [];
|
|
13
27
|
}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"AbstractMiddleware.js","sourceRoot":"","sources":["../../../../src/services/http/middleware/AbstractMiddleware.ts"],"names":[],"mappings":"AACA,OAAO,IAAI,MAAM,0BAA0B,CAAC;
|
|
1
|
+
{"version":3,"file":"AbstractMiddleware.js","sourceRoot":"","sources":["../../../../src/services/http/middleware/AbstractMiddleware.ts"],"names":[],"mappings":"AACA,OAAO,IAAI,MAAM,0BAA0B,CAAC;AAkB5C,MAAM,kBAAmB,SAAQ,IAAI;IACnC,MAAM,CAA2B;IAEjC,YAAY,GAAS,EAAE,MAAgC;QACrD,KAAK,CAAC,GAAG,CAAC,CAAC;QACX,IAAI,CAAC,MAAM,GAAG,MAAM,CAAC;IACvB,CAAC;IAED,MAAM,KAAK,WAAW;QACpB,OAAO,4CAA4C,CAAC;IACtD,CAAC;IAED;;;;;OAKG;IACH,MAAM,KAAK,kBAAkB;QAC3B,OAAO,EAAE,CAAC;IACZ,CAAC;IAED;;;;OAIG;IACH,IAAI,kBAAkB;QACpB,OAAO,EAAE,CAAC;IACZ,CAAC;IAED;;;;;;;;;;OAUG;IACH,MAAM,KAAK,sBAAsB;QAC/B,OAAO,IAAI,CAAC;IACd,CAAC;IAED;;;OAGG;IACH,MAAM,KAAK,wBAAwB;QACjC,OAAO,IAAI,CAAC;IACd,CAAC;IAED;;;;;OAKG;IACH,IAAI,sBAAsB;QACxB,OAAO,IAAI,CAAC;IACd,CAAC;IAED;;;OAGG;IACH,IAAI,wBAAwB;QAC1B,OAAO,IAAI,CAAC;IACd,CAAC;IAED;;;OAGG;IACH,IAAI,oBAAoB;QACtB,OAAO;YACL,OAAO,EAAE,IAAI,CAAC,wBAAwB;YACtC,KAAK,EAAE,IAAI,CAAC,sBAAsB;SACnC,CAAC;IACJ,CAAC;IAED,KAAK,CAAC,UAAU,CACd,IAAsB,EACtB,IAAc,EACd,IAAkB;QAGlB,IAAI,CAAC,MAAM,EAAE,IAAI,CAAC,+BAA+B,CAAC,CAAC;QACnD,OAAO,IAAI,EAAE,CAAC;IAChB,CAAC;IAED,aAAa;QACX,OAAO,IAAI,CAAC,UAAU,CAAC,IAAI,CAAC,IAAI,CAAC,CAAC;IACpC,CAAC;IAED,MAAM,KAAK,WAAW;QACpB,OAAO,YAAY,CAAC;IACtB,CAAC;CACF;AAED,eAAe,kBAAkB,CAAC"}
|
|
@@ -18,6 +18,19 @@ declare class GetUserByToken extends AbstractMiddleware {
|
|
|
18
18
|
static get provides(): {
|
|
19
19
|
user?: AppUser;
|
|
20
20
|
};
|
|
21
|
+
static get usedAuthParameters(): ({
|
|
22
|
+
name: string;
|
|
23
|
+
type: string;
|
|
24
|
+
in: string;
|
|
25
|
+
description: string;
|
|
26
|
+
scheme?: undefined;
|
|
27
|
+
} | {
|
|
28
|
+
name: string;
|
|
29
|
+
type: string;
|
|
30
|
+
scheme: string;
|
|
31
|
+
description: string;
|
|
32
|
+
in?: undefined;
|
|
33
|
+
})[];
|
|
21
34
|
get usedAuthParameters(): ({
|
|
22
35
|
name: string;
|
|
23
36
|
type: string;
|
|
@@ -12,7 +12,7 @@ class GetUserByToken extends AbstractMiddleware {
|
|
|
12
12
|
static get provides() {
|
|
13
13
|
return {};
|
|
14
14
|
}
|
|
15
|
-
get usedAuthParameters() {
|
|
15
|
+
static get usedAuthParameters() {
|
|
16
16
|
return [
|
|
17
17
|
{
|
|
18
18
|
name: 'Authorization',
|
|
@@ -28,6 +28,10 @@ class GetUserByToken extends AbstractMiddleware {
|
|
|
28
28
|
},
|
|
29
29
|
];
|
|
30
30
|
}
|
|
31
|
+
// Back-compat for any runtime reader of the instance form (removed in v6).
|
|
32
|
+
get usedAuthParameters() {
|
|
33
|
+
return GetUserByToken.usedAuthParameters;
|
|
34
|
+
}
|
|
31
35
|
async middleware(req, _res, next) {
|
|
32
36
|
if (req.appInfo.user) {
|
|
33
37
|
this.logger?.warn('You call GetUserByToken more then once');
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"GetUserByToken.js","sourceRoot":"","sources":["../../../../src/services/http/middleware/GetUserByToken.ts"],"names":[],"mappings":"AAGA,OAAO,kBAAkB,MAAM,yBAAyB,CAAC;AAQzD,MAAM,cAAe,SAAQ,kBAAkB;IAC7C,MAAM,KAAK,WAAW;QACpB,OAAO,kGAAkG,CAAC;IAC5G,CAAC;IAED;;;;;OAKG;IACH,MAAM,KAAK,QAAQ;QACjB,OAAO,EAAwB,CAAC;IAClC,CAAC;IAED,
|
|
1
|
+
{"version":3,"file":"GetUserByToken.js","sourceRoot":"","sources":["../../../../src/services/http/middleware/GetUserByToken.ts"],"names":[],"mappings":"AAGA,OAAO,kBAAkB,MAAM,yBAAyB,CAAC;AAQzD,MAAM,cAAe,SAAQ,kBAAkB;IAC7C,MAAM,KAAK,WAAW;QACpB,OAAO,kGAAkG,CAAC;IAC5G,CAAC;IAED;;;;;OAKG;IACH,MAAM,KAAK,QAAQ;QACjB,OAAO,EAAwB,CAAC;IAClC,CAAC;IAED,MAAM,KAAK,kBAAkB;QAC3B,OAAO;YACL;gBACE,IAAI,EAAE,eAAe;gBACrB,IAAI,EAAE,QAAQ;gBACd,EAAE,EAAE,QAAQ;gBACZ,WAAW,EAAE,cAAc,CAAC,WAAW;aACxC;YACD;gBACE,IAAI,EAAE,YAAY;gBAClB,IAAI,EAAE,MAAM;gBACZ,MAAM,EAAE,QAAQ;gBAChB,WAAW,EAAE,cAAc,CAAC,WAAW;aACxC;SACF,CAAC;IACJ,CAAC;IAED,2EAA2E;IAC3E,IAAI,kBAAkB;QACpB,OAAO,cAAc,CAAC,kBAAkB,CAAC;IAC3C,CAAC;IAED,KAAK,CAAC,UAAU,CACd,GAA6C,EAC7C,IAAc,EACd,IAAkB;QAElB,IAAI,GAAG,CAAC,OAAO,CAAC,IAAI,EAAE,CAAC;YACrB,IAAI,CAAC,MAAM,EAAE,IAAI,CAAC,wCAAwC,CAAC,CAAC;YAC5D,OAAO,IAAI,EAAE,CAAC;QAChB,CAAC;QACD,IAAI,EAAE,KAAK,EAAE,GAAG,GAAG,CAAC,IAAI,IAAI,EAAE,CAAC;QAC/B,wEAAwE;QACxE,sCAAsC;QACtC,IAAI,CAAC,MAAM,EAAE,OAAO,CAClB,8BACE,KAAK,CAAC,CAAC,CAAC,SAAS,CAAC,CAAC,CAAC,QACtB,0BAA0B,GAAG,CAAC,GAAG,CAAC,eAAe,CAAC,CAAC,CAAC,CAAC,SAAS,CAAC,CAAC,CAAC,QAAQ,EAAE,CAC5E,CAAC;QACF,IAAI,CAAC,KAAK,EAAE,CAAC;YACX,KAAK,GAAG,GAAG,CAAC,GAAG,CAAC,eAAe,CAAC,CAAC;YACjC,sEAAsE;YACtE,yEAAyE;YACzE,IAAI,CAAC,KAAK,IAAI,KAAK,KAAK,MAAM,EAAE,CAAC;gBAC/B,OAAO,IAAI,EAAE,CAAC;YAChB,CAAC;QACH,CAAC;QACD,gBAAgB;QAChB,KAAK,GAAG,KAAK,CAAC,OAAO,CAAC,aAAa,EAAE,EAAE,CAAC,CAAC,IAAI,EAAE,CAAC;QAChD,MAAM,IAAI,GAAG,IAAI,CAAC,GAAG,CAAC,QAAQ,CAAC,MAAM,CAAqB,CAAC;QAC3D,MAAM,IAAI,GAAG,CAAC,MAAM,IAAI,CAAC,cAAc,CACrC,KAAK,CACN,CAAmC,CAAC;QACrC,IAAI,IAAI,EAAE,CAAC;YACT,GAAG,CAAC,OAAO,CAAC,IAAI,GAAG,IAAI,CAAC;QAC1B,CAAC;QACD,OAAO,IAAI,EAAE,CAAC;IAChB,CAAC;CACF;AAED,eAAe,cAAc,CAAC"}
|
|
@@ -1,6 +1,5 @@
|
|
|
1
1
|
import type { NextFunction, Response } from 'express';
|
|
2
2
|
import type { RateLimiterAbstract } from 'rate-limiter-flexible';
|
|
3
|
-
import { RateLimiterRedis } from 'rate-limiter-flexible';
|
|
4
3
|
import type rateLimiterConfig from '../../../config/rateLimiter.js';
|
|
5
4
|
import type { IApp } from '../../../server.ts';
|
|
6
5
|
import type { FrameworkRequest } from '../HttpServer.ts';
|
|
@@ -10,8 +9,15 @@ declare class RateLimiter extends AbstractMiddleware {
|
|
|
10
9
|
static get description(): string;
|
|
11
10
|
finalOptions: typeof rateLimiterConfig;
|
|
12
11
|
limiter: RateLimiterAbstract;
|
|
12
|
+
/**
|
|
13
|
+
* Resolves once the limiter is built. Only the redis driver is async (it
|
|
14
|
+
* lazy-loads `@redis/client`); memory/mongo build synchronously, so this stays
|
|
15
|
+
* an already-resolved promise for them. `middleware()` awaits it before the
|
|
16
|
+
* first request.
|
|
17
|
+
*/
|
|
18
|
+
whenReady: Promise<void>;
|
|
13
19
|
constructor(app: IApp, params?: Record<string, unknown>);
|
|
14
|
-
initRedisLimiter():
|
|
20
|
+
initRedisLimiter(): Promise<void>;
|
|
15
21
|
gerenateConsumeKey(req: FrameworkRequest & GetUserByTokenAppInfo): string;
|
|
16
22
|
consumeResult(consumeKey: string, consumePoints?: number): Promise<{
|
|
17
23
|
msBeforeNext: number;
|
|
@@ -1,7 +1,6 @@
|
|
|
1
1
|
import merge from 'deepmerge';
|
|
2
2
|
import mongoose from 'mongoose';
|
|
3
3
|
import { RateLimiterMemory, RateLimiterMongo, RateLimiterRedis, } from 'rate-limiter-flexible';
|
|
4
|
-
import { getRedisClientSync } from "../../../helpers/redis/redisConnection.js";
|
|
5
4
|
import AbstractMiddleware from "./AbstractMiddleware.js";
|
|
6
5
|
class RateLimiter extends AbstractMiddleware {
|
|
7
6
|
static get description() {
|
|
@@ -9,6 +8,13 @@ class RateLimiter extends AbstractMiddleware {
|
|
|
9
8
|
}
|
|
10
9
|
finalOptions;
|
|
11
10
|
limiter;
|
|
11
|
+
/**
|
|
12
|
+
* Resolves once the limiter is built. Only the redis driver is async (it
|
|
13
|
+
* lazy-loads `@redis/client`); memory/mongo build synchronously, so this stays
|
|
14
|
+
* an already-resolved promise for them. `middleware()` awaits it before the
|
|
15
|
+
* first request.
|
|
16
|
+
*/
|
|
17
|
+
whenReady = Promise.resolve();
|
|
12
18
|
constructor(app, params) {
|
|
13
19
|
super(app, params);
|
|
14
20
|
const limiterOptions = this.app.getConfig('rateLimiter');
|
|
@@ -18,7 +24,10 @@ class RateLimiter extends AbstractMiddleware {
|
|
|
18
24
|
this.limiter = new RateLimiterMemory(this.finalOptions.limiterOptions);
|
|
19
25
|
break;
|
|
20
26
|
case 'redis':
|
|
21
|
-
|
|
27
|
+
// Defer: the redis path lazy-loads `@redis/client` so the package only
|
|
28
|
+
// loads when the redis driver is actually used. memory/mongo never reach
|
|
29
|
+
// here, so importing RateLimiter no longer forces redis into the graph.
|
|
30
|
+
this.whenReady = this.initRedisLimiter();
|
|
22
31
|
break;
|
|
23
32
|
case 'mongo':
|
|
24
33
|
this.limiter = new RateLimiterMongo({
|
|
@@ -34,17 +43,30 @@ class RateLimiter extends AbstractMiddleware {
|
|
|
34
43
|
break;
|
|
35
44
|
}
|
|
36
45
|
}
|
|
37
|
-
initRedisLimiter() {
|
|
38
|
-
|
|
39
|
-
|
|
40
|
-
|
|
41
|
-
|
|
42
|
-
//
|
|
43
|
-
//
|
|
44
|
-
|
|
45
|
-
|
|
46
|
-
|
|
47
|
-
|
|
46
|
+
async initRedisLimiter() {
|
|
47
|
+
try {
|
|
48
|
+
// Dynamic-import the helper so `@redis/client` only loads on the redis
|
|
49
|
+
// path. `getRedisClientSync` returns immediately (connect runs in the
|
|
50
|
+
// background) — like the old static import, so the limiter builds without
|
|
51
|
+
// blocking, and a down redis is absorbed by the memory insurance below
|
|
52
|
+
// rather than leaving `this.limiter` unbuilt.
|
|
53
|
+
const { getRedisClientSync } = await import("../../../helpers/redis/redisConnection.js");
|
|
54
|
+
const redisClient = getRedisClientSync();
|
|
55
|
+
this.limiter = new RateLimiterRedis({
|
|
56
|
+
storeClient: redisClient,
|
|
57
|
+
useRedisPackage: true,
|
|
58
|
+
// Memory fallback so a Redis outage doesn't drop limiting entirely; the
|
|
59
|
+
// library serves from this when the store errors, and doc-10's fail-open
|
|
60
|
+
// in `consumeResult` is the last resort.
|
|
61
|
+
insuranceLimiter: new RateLimiterMemory(this.finalOptions.limiterOptions),
|
|
62
|
+
...this.finalOptions.limiterOptions,
|
|
63
|
+
});
|
|
64
|
+
}
|
|
65
|
+
catch (e) {
|
|
66
|
+
// Leave `this.limiter` undefined so `middleware()` returns 500 (same as an
|
|
67
|
+
// unknown driver) rather than crashing — e.g. `@redis/client` not installed.
|
|
68
|
+
this.logger?.error(`RateLimiter redis init failed (is '@redis/client' installed?): ${e}`);
|
|
69
|
+
}
|
|
48
70
|
}
|
|
49
71
|
gerenateConsumeKey(req) {
|
|
50
72
|
const { ip, route, user, request } = this.finalOptions.consumeKeyComponents;
|
|
@@ -95,6 +117,9 @@ class RateLimiter extends AbstractMiddleware {
|
|
|
95
117
|
}
|
|
96
118
|
}
|
|
97
119
|
async middleware(req, res, next) {
|
|
120
|
+
// No-op for memory/mongo (already resolved); awaits the lazy redis build on
|
|
121
|
+
// the first request only.
|
|
122
|
+
await this.whenReady;
|
|
98
123
|
if (!this.limiter) {
|
|
99
124
|
this.logger?.info(`RateLimiter not inited correclty! Please check init logs `);
|
|
100
125
|
return res.status(500).json({ message: 'RateLimiter error' });
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"RateLimiter.js","sourceRoot":"","sources":["../../../../src/services/http/middleware/RateLimiter.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,MAAM,WAAW,CAAC;AAE9B,OAAO,QAAQ,MAAM,UAAU,CAAC;AAKhC,OAAO,EACL,iBAAiB,EACjB,gBAAgB,EAChB,gBAAgB,GACjB,MAAM,uBAAuB,CAAC;
|
|
1
|
+
{"version":3,"file":"RateLimiter.js","sourceRoot":"","sources":["../../../../src/services/http/middleware/RateLimiter.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,MAAM,WAAW,CAAC;AAE9B,OAAO,QAAQ,MAAM,UAAU,CAAC;AAKhC,OAAO,EACL,iBAAiB,EACjB,gBAAgB,EAChB,gBAAgB,GACjB,MAAM,uBAAuB,CAAC;AAI/B,OAAO,kBAAkB,MAAM,yBAAyB,CAAC;AAGzD,MAAM,WAAY,SAAQ,kBAAkB;IAC1C,MAAM,KAAK,WAAW;QACpB,OAAO,iFAAiF,CAAC;IAC3F,CAAC;IAED,YAAY,CAA2B;IACvC,OAAO,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,10 @@ import type { ValidatorDriver } from '../types.ts';
|
|
|
9
9
|
* Schema validate (zod, valibot, arktype). Yup is the outlier — see
|
|
10
10
|
* `YupDriver.ts` for the strip-preserving fast path.
|
|
11
11
|
*
|
|
12
|
-
* `toJsonSchema`
|
|
13
|
-
*
|
|
12
|
+
* `toJsonSchema` is vendor-generic: Standard Schema itself carries no shape, so
|
|
13
|
+
* conversion delegates to each lib's native exporter — a `.toJsonSchema()`
|
|
14
|
+
* method on the schema (arktype, …), else zod's `z.toJSONSchema` (lazy-imported
|
|
15
|
+
* so zod stays an optional peer). Vendors with no introspection return null and
|
|
16
|
+
* the caller (OpenAPI generator) degrades to a placeholder.
|
|
14
17
|
*/
|
|
15
18
|
export declare const standardSchemaDriver: ValidatorDriver;
|
|
@@ -9,8 +9,11 @@ import { ValidationError } from "../ValidationError.js";
|
|
|
9
9
|
* Schema validate (zod, valibot, arktype). Yup is the outlier — see
|
|
10
10
|
* `YupDriver.ts` for the strip-preserving fast path.
|
|
11
11
|
*
|
|
12
|
-
* `toJsonSchema`
|
|
13
|
-
*
|
|
12
|
+
* `toJsonSchema` is vendor-generic: Standard Schema itself carries no shape, so
|
|
13
|
+
* conversion delegates to each lib's native exporter — a `.toJsonSchema()`
|
|
14
|
+
* method on the schema (arktype, …), else zod's `z.toJSONSchema` (lazy-imported
|
|
15
|
+
* so zod stays an optional peer). Vendors with no introspection return null and
|
|
16
|
+
* the caller (OpenAPI generator) degrades to a placeholder.
|
|
14
17
|
*/
|
|
15
18
|
export const standardSchemaDriver = {
|
|
16
19
|
canHandle(body) {
|
|
@@ -31,7 +34,25 @@ export const standardSchemaDriver = {
|
|
|
31
34
|
}
|
|
32
35
|
return result.value;
|
|
33
36
|
},
|
|
34
|
-
toJsonSchema() {
|
|
37
|
+
async toJsonSchema(body) {
|
|
38
|
+
// 1. A native instance method (arktype's `.toJsonSchema()`, and any future
|
|
39
|
+
// lib that exposes one). Covers the general case without a per-vendor branch.
|
|
40
|
+
const native = body.toJsonSchema;
|
|
41
|
+
if (typeof native === 'function') {
|
|
42
|
+
return native.call(body);
|
|
43
|
+
}
|
|
44
|
+
// 2. zod (≥4) — converter lives on the `zod` module, not the schema. Lazy
|
|
45
|
+
// import keeps zod an optional peer; only reached when a zod schema is used.
|
|
46
|
+
const vendor = body['~standard']?.vendor;
|
|
47
|
+
if (vendor === 'zod') {
|
|
48
|
+
const mod = (await import('zod'));
|
|
49
|
+
const toJSONSchema = mod.toJSONSchema ?? mod.z?.toJSONSchema;
|
|
50
|
+
if (typeof toJSONSchema === 'function') {
|
|
51
|
+
// draft-2020-12 is what OpenAPI 3.1 expects.
|
|
52
|
+
return toJSONSchema(body, { target: 'draft-2020-12' });
|
|
53
|
+
}
|
|
54
|
+
}
|
|
55
|
+
// 3. valibot / older zod / anything else with no introspection → degrade.
|
|
35
56
|
return null;
|
|
36
57
|
},
|
|
37
58
|
};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"StandardSchemaDriver.js","sourceRoot":"","sources":["../../../../src/services/validate/drivers/StandardSchemaDriver.ts"],"names":[],"mappings":"
|
|
1
|
+
{"version":3,"file":"StandardSchemaDriver.js","sourceRoot":"","sources":["../../../../src/services/validate/drivers/StandardSchemaDriver.ts"],"names":[],"mappings":"AAKA,OAAO,EAAE,eAAe,EAAE,MAAM,uBAAuB,CAAC;AAExD;;;;;;;;;;;;;;;GAeG;AACH,MAAM,CAAC,MAAM,oBAAoB,GAAoB;IACnD,SAAS,CAAC,IAAa;QACrB,OAAO,CACL,OAAO,IAAI,KAAK,QAAQ;YACxB,IAAI,KAAK,IAAI;YACb,WAAW,IAAI,IAAI;YACnB,OAAQ,IAAkC,CAAC,WAAW,CAAC,KAAK,QAAQ,CACrE,CAAC;IACJ,CAAC;IAED,KAAK,CAAC,QAAQ,CAAC,IAAa,EAAE,IAAa;QACzC,MAAM,GAAG,GAAI,IAAyB,CAAC,WAAW,CAAC,CAAC;QACpD,MAAM,MAAM,GAAG,MAAM,GAAG,CA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