@adaptivestone/framework 5.0.1 → 5.1.0
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 +26 -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 +28 -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 +36 -0
- package/dist/services/http/builtinErrorHandlers.js +71 -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,296 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* OpenAPI 3.1 generator.
|
|
3
|
+
*
|
|
4
|
+
* Pure function: takes the flattened route list (`RouteRegistry.flatten()`) and
|
|
5
|
+
* emits an OpenAPI document. No CLI, no fs, no app boot — the `openapi` command
|
|
6
|
+
* (`src/commands/OpenApi.ts`) populates the registry and hands the routes here.
|
|
7
|
+
*
|
|
8
|
+
* Schema → JSON Schema goes through the validator driver seam
|
|
9
|
+
* (`ValidateService.resolve(schema).toJsonSchema`), so any vendor with
|
|
10
|
+
* introspection (zod native, yup `describe()`, arktype, or a user-registered
|
|
11
|
+
* driver) is documented; vendors without it degrade to a placeholder + warning.
|
|
12
|
+
* The same seam powers the future MCP surface — nothing here is OpenAPI-only
|
|
13
|
+
* throwaway.
|
|
14
|
+
*/
|
|
15
|
+
import { isContentTypeRequestMap } from "../validate/contentType.js";
|
|
16
|
+
import ValidateService from "../validate/ValidateService.js";
|
|
17
|
+
/**
|
|
18
|
+
* Build an OpenAPI 3.1 document from flattened routes.
|
|
19
|
+
*/
|
|
20
|
+
export async function generateOpenApi(routes, opts) {
|
|
21
|
+
const warn = opts.onWarning ?? (() => { });
|
|
22
|
+
const paths = {};
|
|
23
|
+
const securitySchemes = {};
|
|
24
|
+
const tagNames = new Set();
|
|
25
|
+
for (const route of routes) {
|
|
26
|
+
const { path, params: pathParams, hadSplat } = convertPath(route.path);
|
|
27
|
+
if (hadSplat) {
|
|
28
|
+
warn(`${route.method} ${route.path}: catch-all (*) approximated as a path parameter — OpenAPI has no catch-all.`);
|
|
29
|
+
}
|
|
30
|
+
const meta = route.entry.meta ?? {};
|
|
31
|
+
const tag = (meta.controllerClass ?? 'default').split('/')[0];
|
|
32
|
+
tagNames.add(tag);
|
|
33
|
+
const parameters = pathParams.map((name) => ({
|
|
34
|
+
name,
|
|
35
|
+
in: 'path',
|
|
36
|
+
required: true,
|
|
37
|
+
schema: { type: 'string' },
|
|
38
|
+
}));
|
|
39
|
+
const ctx = `${route.method} ${path}`;
|
|
40
|
+
parameters.push(...(await buildQueryParameters(route, warn, ctx)));
|
|
41
|
+
const operation = {
|
|
42
|
+
operationId: operationId(route, path),
|
|
43
|
+
tags: [tag],
|
|
44
|
+
responses: defaultResponses(),
|
|
45
|
+
};
|
|
46
|
+
if (meta.description) {
|
|
47
|
+
operation.summary = meta.description;
|
|
48
|
+
}
|
|
49
|
+
if (parameters.length > 0) {
|
|
50
|
+
operation.parameters = parameters;
|
|
51
|
+
}
|
|
52
|
+
const requestBody = await buildRequestBody(route, warn, ctx);
|
|
53
|
+
if (requestBody) {
|
|
54
|
+
operation.requestBody = requestBody;
|
|
55
|
+
}
|
|
56
|
+
const security = collectSecurity(route.middlewares, securitySchemes);
|
|
57
|
+
if (security.length > 0) {
|
|
58
|
+
operation.security = security;
|
|
59
|
+
}
|
|
60
|
+
let pathItem = paths[path];
|
|
61
|
+
if (!pathItem) {
|
|
62
|
+
pathItem = {};
|
|
63
|
+
paths[path] = pathItem;
|
|
64
|
+
}
|
|
65
|
+
pathItem[route.method.toLowerCase()] = operation;
|
|
66
|
+
}
|
|
67
|
+
const doc = {
|
|
68
|
+
openapi: '3.1.0',
|
|
69
|
+
info: opts.info,
|
|
70
|
+
paths,
|
|
71
|
+
tags: [...tagNames].sort().map((name) => ({ name })),
|
|
72
|
+
components: { securitySchemes },
|
|
73
|
+
};
|
|
74
|
+
if (opts.servers && opts.servers.length > 0) {
|
|
75
|
+
doc.servers = opts.servers;
|
|
76
|
+
}
|
|
77
|
+
return doc;
|
|
78
|
+
}
|
|
79
|
+
// ── path ──────────────────────────────────────────────────────────────────────
|
|
80
|
+
/** `:id` → `{id}`, trailing `*rest` → `{rest}` (splat approximated). */
|
|
81
|
+
function convertPath(internalPath) {
|
|
82
|
+
const params = [];
|
|
83
|
+
let hadSplat = false;
|
|
84
|
+
const out = internalPath
|
|
85
|
+
.split('/')
|
|
86
|
+
.map((seg) => {
|
|
87
|
+
if (seg.startsWith(':')) {
|
|
88
|
+
const name = seg.slice(1);
|
|
89
|
+
params.push(name);
|
|
90
|
+
return `{${name}}`;
|
|
91
|
+
}
|
|
92
|
+
if (seg.startsWith('*')) {
|
|
93
|
+
hadSplat = true;
|
|
94
|
+
const name = seg.slice(1) || 'splat';
|
|
95
|
+
params.push(name);
|
|
96
|
+
return `{${name}}`;
|
|
97
|
+
}
|
|
98
|
+
return seg;
|
|
99
|
+
})
|
|
100
|
+
.join('/');
|
|
101
|
+
return { path: out || '/', params, hadSplat };
|
|
102
|
+
}
|
|
103
|
+
function operationId(route, path) {
|
|
104
|
+
const name = route.entry.meta?.methodName;
|
|
105
|
+
if (name) {
|
|
106
|
+
return name;
|
|
107
|
+
}
|
|
108
|
+
const slug = path.replace(/[^a-zA-Z0-9]+/g, '_').replace(/^_|_$/g, '');
|
|
109
|
+
return `${route.method.toLowerCase()}_${slug || 'root'}`;
|
|
110
|
+
}
|
|
111
|
+
// ── schema conversion ──────────────────────────────────────────────────────────
|
|
112
|
+
/** Resolve a schema's driver and emit JSON Schema; null when not introspectable. */
|
|
113
|
+
async function schemaToJson(schema) {
|
|
114
|
+
const driver = ValidateService.resolve(schema);
|
|
115
|
+
if (!driver?.toJsonSchema) {
|
|
116
|
+
return null;
|
|
117
|
+
}
|
|
118
|
+
const result = await driver.toJsonSchema(schema);
|
|
119
|
+
if (!result) {
|
|
120
|
+
return null;
|
|
121
|
+
}
|
|
122
|
+
// `$schema` is a standalone-document marker; invalid when embedded in OpenAPI.
|
|
123
|
+
const { $schema, ...rest } = result;
|
|
124
|
+
return rest;
|
|
125
|
+
}
|
|
126
|
+
function placeholderSchema() {
|
|
127
|
+
return {
|
|
128
|
+
type: 'object',
|
|
129
|
+
description: 'Schema introspection unavailable for this validator (no toJsonSchema). Body shape not documented.',
|
|
130
|
+
};
|
|
131
|
+
}
|
|
132
|
+
/**
|
|
133
|
+
* Combine body schemas. A single schema passes through untouched (keeps its
|
|
134
|
+
* top-level keys — `description`, `additionalProperties`, non-object types).
|
|
135
|
+
* Multiple are shallow-merged into one object schema (route body + middleware
|
|
136
|
+
* params), mirroring the runtime's `Object.assign` of validated parts.
|
|
137
|
+
*/
|
|
138
|
+
function combineSchemas(schemas) {
|
|
139
|
+
return schemas.length === 1 ? schemas[0] : mergeObjectSchemas(schemas);
|
|
140
|
+
}
|
|
141
|
+
/** Shallow-merge object JSON Schemas: union `properties` + `required`. */
|
|
142
|
+
function mergeObjectSchemas(schemas) {
|
|
143
|
+
const properties = {};
|
|
144
|
+
const required = new Set();
|
|
145
|
+
for (const schema of schemas) {
|
|
146
|
+
const props = schema.properties;
|
|
147
|
+
if (props && typeof props === 'object') {
|
|
148
|
+
Object.assign(properties, props);
|
|
149
|
+
}
|
|
150
|
+
if (Array.isArray(schema.required)) {
|
|
151
|
+
for (const key of schema.required) {
|
|
152
|
+
required.add(key);
|
|
153
|
+
}
|
|
154
|
+
}
|
|
155
|
+
}
|
|
156
|
+
const out = { type: 'object', properties };
|
|
157
|
+
if (required.size > 0) {
|
|
158
|
+
out.required = [...required];
|
|
159
|
+
}
|
|
160
|
+
return out;
|
|
161
|
+
}
|
|
162
|
+
function hasBinaryField(schema) {
|
|
163
|
+
const props = schema.properties;
|
|
164
|
+
if (!props || typeof props !== 'object') {
|
|
165
|
+
return false;
|
|
166
|
+
}
|
|
167
|
+
return Object.values(props).some((p) => p != null && typeof p === 'object' && p.format === 'binary');
|
|
168
|
+
}
|
|
169
|
+
// ── middleware-contributed schemas ──────────────────────────────────────────────
|
|
170
|
+
/** Read static `relatedRequestParameters` / `relatedQueryParameters` off classes. */
|
|
171
|
+
function collectMiddlewareSchemas(middlewares, kind) {
|
|
172
|
+
const prop = kind === 'request' ? 'relatedRequestParameters' : 'relatedQueryParameters';
|
|
173
|
+
const out = [];
|
|
174
|
+
for (const mw of middlewares) {
|
|
175
|
+
const schema = mw.Class[prop];
|
|
176
|
+
if (schema) {
|
|
177
|
+
out.push(schema);
|
|
178
|
+
}
|
|
179
|
+
}
|
|
180
|
+
return out;
|
|
181
|
+
}
|
|
182
|
+
// ── query / body / security ─────────────────────────────────────────────────────
|
|
183
|
+
async function buildQueryParameters(route, warn, ctx) {
|
|
184
|
+
const schemas = [
|
|
185
|
+
...(route.entry.query ? [route.entry.query] : []),
|
|
186
|
+
...collectMiddlewareSchemas(route.middlewares, 'query'),
|
|
187
|
+
];
|
|
188
|
+
const params = [];
|
|
189
|
+
for (const schema of schemas) {
|
|
190
|
+
const json = await schemaToJson(schema);
|
|
191
|
+
if (!json) {
|
|
192
|
+
warn(`${ctx} query: schema introspection unavailable — params omitted.`);
|
|
193
|
+
continue;
|
|
194
|
+
}
|
|
195
|
+
const props = json.properties ?? {};
|
|
196
|
+
const required = new Set(Array.isArray(json.required) ? json.required : []);
|
|
197
|
+
for (const [name, propSchema] of Object.entries(props)) {
|
|
198
|
+
params.push({
|
|
199
|
+
name,
|
|
200
|
+
in: 'query',
|
|
201
|
+
required: required.has(name),
|
|
202
|
+
schema: propSchema,
|
|
203
|
+
});
|
|
204
|
+
}
|
|
205
|
+
}
|
|
206
|
+
return params;
|
|
207
|
+
}
|
|
208
|
+
async function buildRequestBody(route, warn, ctx) {
|
|
209
|
+
const req = route.entry.request;
|
|
210
|
+
const mwSchemas = collectMiddlewareSchemas(route.middlewares, 'request');
|
|
211
|
+
const mwParts = (await Promise.all(mwSchemas.map((s) => schemaToJson(s)))).filter((s) => s != null);
|
|
212
|
+
// Content-type map → one media type per declared key (native multipart support).
|
|
213
|
+
if (req && isContentTypeRequestMap(req)) {
|
|
214
|
+
const content = {};
|
|
215
|
+
for (const [mediaType, schema] of Object.entries(req)) {
|
|
216
|
+
const converted = await schemaToJson(schema);
|
|
217
|
+
if (!converted) {
|
|
218
|
+
warn(`${ctx} body (${mediaType}): schema introspection unavailable.`);
|
|
219
|
+
}
|
|
220
|
+
const merged = combineSchemas([
|
|
221
|
+
converted ?? placeholderSchema(),
|
|
222
|
+
...mwParts,
|
|
223
|
+
]);
|
|
224
|
+
content[mediaType] = { schema: merged };
|
|
225
|
+
}
|
|
226
|
+
return { content };
|
|
227
|
+
}
|
|
228
|
+
// Single schema (or none).
|
|
229
|
+
let routeObj = null;
|
|
230
|
+
if (req) {
|
|
231
|
+
routeObj = await schemaToJson(req);
|
|
232
|
+
if (!routeObj) {
|
|
233
|
+
warn(`${ctx} body: schema introspection unavailable — placeholder emitted.`);
|
|
234
|
+
}
|
|
235
|
+
}
|
|
236
|
+
const parts = [
|
|
237
|
+
...(routeObj ? [routeObj] : req ? [placeholderSchema()] : []),
|
|
238
|
+
...mwParts,
|
|
239
|
+
];
|
|
240
|
+
if (parts.length === 0) {
|
|
241
|
+
return undefined; // no declared body
|
|
242
|
+
}
|
|
243
|
+
const schema = combineSchemas(parts);
|
|
244
|
+
const mediaType = hasBinaryField(schema)
|
|
245
|
+
? 'multipart/form-data'
|
|
246
|
+
: 'application/json';
|
|
247
|
+
return { content: { [mediaType]: { schema } } };
|
|
248
|
+
}
|
|
249
|
+
function collectSecurity(middlewares, securitySchemes) {
|
|
250
|
+
const requirements = [];
|
|
251
|
+
const seen = new Set();
|
|
252
|
+
for (const mw of middlewares) {
|
|
253
|
+
const params = mw.Class
|
|
254
|
+
.usedAuthParameters;
|
|
255
|
+
if (!Array.isArray(params)) {
|
|
256
|
+
continue;
|
|
257
|
+
}
|
|
258
|
+
for (const param of params) {
|
|
259
|
+
if (!securitySchemes[param.name]) {
|
|
260
|
+
securitySchemes[param.name] = toSecurityScheme(param);
|
|
261
|
+
}
|
|
262
|
+
if (!seen.has(param.name)) {
|
|
263
|
+
seen.add(param.name);
|
|
264
|
+
requirements.push({ [param.name]: [] });
|
|
265
|
+
}
|
|
266
|
+
}
|
|
267
|
+
}
|
|
268
|
+
return requirements;
|
|
269
|
+
}
|
|
270
|
+
function toSecurityScheme(param) {
|
|
271
|
+
if (param.type === 'apiKey') {
|
|
272
|
+
return {
|
|
273
|
+
type: 'apiKey',
|
|
274
|
+
name: param.name,
|
|
275
|
+
in: param.in ?? 'header',
|
|
276
|
+
description: param.description,
|
|
277
|
+
};
|
|
278
|
+
}
|
|
279
|
+
if (param.type === 'http') {
|
|
280
|
+
return {
|
|
281
|
+
type: 'http',
|
|
282
|
+
scheme: param.scheme ?? 'bearer',
|
|
283
|
+
description: param.description,
|
|
284
|
+
};
|
|
285
|
+
}
|
|
286
|
+
return { type: param.type, description: param.description };
|
|
287
|
+
}
|
|
288
|
+
function defaultResponses() {
|
|
289
|
+
return {
|
|
290
|
+
'200': { description: 'Successful response' },
|
|
291
|
+
'400': { description: 'Validation error' },
|
|
292
|
+
'401': { description: 'Unauthorized' },
|
|
293
|
+
'404': { description: 'Not found' },
|
|
294
|
+
};
|
|
295
|
+
}
|
|
296
|
+
//# sourceMappingURL=OpenApiGenerator.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"OpenApiGenerator.js","sourceRoot":"","sources":["../../../src/services/documentation/OpenApiGenerator.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;GAaG;AAIH,OAAO,EAAE,uBAAuB,EAAE,MAAM,4BAA4B,CAAC;AAErE,OAAO,eAAe,MAAM,gCAAgC,CAAC;AAuB7D;;GAEG;AACH,MAAM,CAAC,KAAK,UAAU,eAAe,CACnC,MAAmB,EACnB,IAA4B;IAE5B,MAAM,IAAI,GAAG,IAAI,CAAC,SAAS,IAAI,CAAC,GAAG,EAAE,GAAE,CAAC,CAAC,CAAC;IAC1C,MAAM,KAAK,GAAQ,EAAE,CAAC;IACtB,MAAM,eAAe,GAAQ,EAAE,CAAC;IAChC,MAAM,QAAQ,GAAG,IAAI,GAAG,EAAU,CAAC;IAEnC,KAAK,MA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AAC,IAAI,CAAC,CAAC;gBACrB,YAAY,CAAC,IAAI,CAAC,EAAE,CAAC,KAAK,CAAC,IAAI,CAAC,EAAE,EAAE,EAAE,CAAC,CAAC;YAC1C,CAAC;QACH,CAAC;IACH,CAAC;IACD,OAAO,YAAY,CAAC;AACtB,CAAC;AAED,SAAS,gBAAgB,CAAC,KAAoB;IAC5C,IAAI,KAAK,CAAC,IAAI,KAAK,QAAQ,EAAE,CAAC;QAC5B,OAAO;YACL,IAAI,EAAE,QAAQ;YACd,IAAI,EAAE,KAAK,CAAC,IAAI;YAChB,EAAE,EAAE,KAAK,CAAC,EAAE,IAAI,QAAQ;YACxB,WAAW,EAAE,KAAK,CAAC,WAAW;SAC/B,CAAC;IACJ,CAAC;IACD,IAAI,KAAK,CAAC,IAAI,KAAK,MAAM,EAAE,CAAC;QAC1B,OAAO;YACL,IAAI,EAAE,MAAM;YACZ,MAAM,EAAE,KAAK,CAAC,MAAM,IAAI,QAAQ;YAChC,WAAW,EAAE,KAAK,CAAC,WAAW;SAC/B,CAAC;IACJ,CAAC;IACD,OAAO,EAAE,IAAI,EAAE,KAAK,CAAC,IAAI,EAAE,WAAW,EAAE,KAAK,CAAC,WAAW,EAAE,CAAC;AAC9D,CAAC;AAED,SAAS,gBAAgB;IACvB,OAAO;QACL,KAAK,EAAE,EAAE,WAAW,EAAE,qBAAqB,EAAE;QAC7C,KAAK,EAAE,EAAE,WAAW,EAAE,kBAAkB,EAAE;QAC1C,KAAK,EAAE,EAAE,WAAW,EAAE,cAAc,EAAE;QACtC,KAAK,EAAE,EAAE,WAAW,EAAE,WAAW,EAAE;KACpC,CAAC;AACJ,CAAC"}
|
|
@@ -3,6 +3,7 @@ import type { Express, Request } from 'express';
|
|
|
3
3
|
import type { TFunction } from 'i18next';
|
|
4
4
|
import Base from '../../modules/Base.ts';
|
|
5
5
|
import type { IApp } from '../../server.ts';
|
|
6
|
+
import { type ErrorHandlerFn, type ErrorHandlerResult, type ErrorLogLevel } from './builtinErrorHandlers.ts';
|
|
6
7
|
import { RouteRegistry } from './routing/RouteRegistry.ts';
|
|
7
8
|
export interface FrameworkRequest extends Request {
|
|
8
9
|
appInfo: {
|
|
@@ -20,12 +21,34 @@ export interface FrameworkRequest extends Request {
|
|
|
20
21
|
* HTTP server based on Express
|
|
21
22
|
*/
|
|
22
23
|
declare class HttpServer extends Base {
|
|
24
|
+
#private;
|
|
23
25
|
express: Express;
|
|
24
26
|
httpServer: Server;
|
|
25
27
|
routeRegistry: RouteRegistry;
|
|
26
28
|
constructor(app: IApp);
|
|
27
29
|
/** Mount the route adapter — single entry to the registry. */
|
|
28
30
|
mountAdapter(): void;
|
|
31
|
+
/**
|
|
32
|
+
* Register a handler mapping a thrown error class to an HTTP response.
|
|
33
|
+
* Consumer handlers are checked before the built-ins (`HttpError` mapper,
|
|
34
|
+
* mongoose validation safety net) in registration order — the first
|
|
35
|
+
* `instanceof` match whose handler returns non-null wins; return `null` to
|
|
36
|
+
* pass to the next entry. Typical registration point is the project's
|
|
37
|
+
* `bootHttp` hook. Returns an unregister function.
|
|
38
|
+
*/
|
|
39
|
+
registerErrorHandler<E extends Error>(errorClass: abstract new (...args: never[]) => E, handler: ErrorHandlerFn<E>, opts?: {
|
|
40
|
+
logLevel?: ErrorLogLevel;
|
|
41
|
+
}): () => void;
|
|
42
|
+
/**
|
|
43
|
+
* Resolve a handler-thrown error through the registry: consumer tier first,
|
|
44
|
+
* then built-ins; first `instanceof` match returning non-null wins. A
|
|
45
|
+
* handler that itself throws aborts the walk (logged here at `error`; the
|
|
46
|
+
* caller falls through to its 500) — never a crash loop. Returns null when
|
|
47
|
+
* no entry produced a response.
|
|
48
|
+
*/
|
|
49
|
+
resolveError(err: unknown, req: FrameworkRequest): Promise<(ErrorHandlerResult & {
|
|
50
|
+
logLevel: ErrorLogLevel;
|
|
51
|
+
}) | null>;
|
|
29
52
|
/**
|
|
30
53
|
* Add handle for 404 error
|
|
31
54
|
*/
|
|
@@ -1,6 +1,7 @@
|
|
|
1
1
|
import http from 'node:http';
|
|
2
2
|
import express from 'express';
|
|
3
3
|
import Base from "../../modules/Base.js";
|
|
4
|
+
import { builtInErrorHandlers, } from "./builtinErrorHandlers.js";
|
|
4
5
|
import Cors from "./middleware/Cors.js";
|
|
5
6
|
import I18nMiddleware from "./middleware/I18n.js";
|
|
6
7
|
import IpDetector from "./middleware/IpDetector.js";
|
|
@@ -16,6 +17,9 @@ class HttpServer extends Base {
|
|
|
16
17
|
express;
|
|
17
18
|
httpServer;
|
|
18
19
|
routeRegistry;
|
|
20
|
+
/** Consumer-registered error handlers — checked before the built-ins. */
|
|
21
|
+
#errorHandlers = [];
|
|
22
|
+
#builtInHandlers = builtInErrorHandlers();
|
|
19
23
|
constructor(app) {
|
|
20
24
|
super(app);
|
|
21
25
|
this.express = express();
|
|
@@ -68,6 +72,59 @@ class HttpServer extends Base {
|
|
|
68
72
|
mountAdapter() {
|
|
69
73
|
this.express.use(createExpressAdapter(this.routeRegistry, this.app));
|
|
70
74
|
}
|
|
75
|
+
/**
|
|
76
|
+
* Register a handler mapping a thrown error class to an HTTP response.
|
|
77
|
+
* Consumer handlers are checked before the built-ins (`HttpError` mapper,
|
|
78
|
+
* mongoose validation safety net) in registration order — the first
|
|
79
|
+
* `instanceof` match whose handler returns non-null wins; return `null` to
|
|
80
|
+
* pass to the next entry. Typical registration point is the project's
|
|
81
|
+
* `bootHttp` hook. Returns an unregister function.
|
|
82
|
+
*/
|
|
83
|
+
registerErrorHandler(errorClass, handler, opts) {
|
|
84
|
+
const entry = {
|
|
85
|
+
errorClass,
|
|
86
|
+
// Stored type-erased; `resolveError` guarantees `instanceof errorClass`
|
|
87
|
+
// before the call, so the narrower parameter type is safe.
|
|
88
|
+
handler: handler,
|
|
89
|
+
logLevel: opts?.logLevel ?? 'warn',
|
|
90
|
+
};
|
|
91
|
+
this.#errorHandlers.push(entry);
|
|
92
|
+
return () => {
|
|
93
|
+
const i = this.#errorHandlers.indexOf(entry);
|
|
94
|
+
if (i !== -1) {
|
|
95
|
+
this.#errorHandlers.splice(i, 1);
|
|
96
|
+
}
|
|
97
|
+
};
|
|
98
|
+
}
|
|
99
|
+
/**
|
|
100
|
+
* Resolve a handler-thrown error through the registry: consumer tier first,
|
|
101
|
+
* then built-ins; first `instanceof` match returning non-null wins. A
|
|
102
|
+
* handler that itself throws aborts the walk (logged here at `error`; the
|
|
103
|
+
* caller falls through to its 500) — never a crash loop. Returns null when
|
|
104
|
+
* no entry produced a response.
|
|
105
|
+
*/
|
|
106
|
+
async resolveError(err, req) {
|
|
107
|
+
for (const entry of [...this.#errorHandlers, ...this.#builtInHandlers]) {
|
|
108
|
+
if (err instanceof entry.errorClass) {
|
|
109
|
+
let result;
|
|
110
|
+
try {
|
|
111
|
+
result = await entry.handler(err, req);
|
|
112
|
+
}
|
|
113
|
+
catch (handlerErr) {
|
|
114
|
+
// Keep the stack — a broken consumer handler is exactly the case
|
|
115
|
+
// where `${err}` (message-only) isn't enough to debug.
|
|
116
|
+
this.logger?.error(`Error handler for ${entry.errorClass.name} threw: ${handlerErr instanceof Error
|
|
117
|
+
? (handlerErr.stack ?? handlerErr.message)
|
|
118
|
+
: handlerErr}`);
|
|
119
|
+
return null;
|
|
120
|
+
}
|
|
121
|
+
if (result != null) {
|
|
122
|
+
return { ...result, logLevel: entry.logLevel };
|
|
123
|
+
}
|
|
124
|
+
}
|
|
125
|
+
}
|
|
126
|
+
return null;
|
|
127
|
+
}
|
|
71
128
|
/**
|
|
72
129
|
* Add handle for 404 error
|
|
73
130
|
*/
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"HttpServer.js","sourceRoot":"","sources":["../../../src/services/http/HttpServer.ts"],"names":[],"mappings":"AACA,OAAO,IAAI,MAAM,WAAW,CAAC;AAQ7B,OAAO,OAAO,MAAM,SAAS,CAAC;AAG9B,OAAO,IAAI,MAAM,uBAAuB,CAAC;AAEzC,OAAO,IAAI,MAAM,sBAAsB,CAAC;AACxC,OAAO,cAAc,MAAM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3C,CAAC,CAAC,CAAC;IACL,CAAC;IAED;;;OAGG;IACH,eAAe;QACb,IAAI,CAAC,OAAO,CAAC,GAAG,CACd,CAAC,GAAU,EAAE,IAAa,EAAE,GAAa,EAAE,IAAkB,EAAE,EAAE;YAC/D,IAAI,CAAC,MAAM,EAAE,KAAK,CAAC,4BAA4B,GAAG,CAAC,KAAK,IAAI,GAAG,EAAE,CAAC,CAAC;YACnE,0EAA0E;YAC1E,uEAAuE;YACvE,0CAA0C;YAC1C,IAAI,GAAG,CAAC,WAAW,EAAE,CAAC;gBACpB,OAAO,IAAI,CAAC,GAAG,CAAC,CAAC;YACnB,CAAC;YACD,GAAG,CAAC,MAAM,CAAC,GAAG,CAAC,CAAC,IAAI,CAAC,EAAE,OAAO,EAAE,kBAAkB,EAAE,CAAC,CAAC;QACxD,CAAC,CACF,CAAC;IACJ,CAAC;IAED,MAAM,KAAK,WAAW;QACpB,OAAO,SAAS,CAAC;IACnB,CAAC;IAED;;;;OAIG;IACH,QAAQ;QACN,OAAO,IAAI,OAAO,CAAC,CAAC,OAAO,EAAE,EAAE;YAC7B,IAAI,CAAC,UAAU,CAAC,KAAK,CAAC,GAAG,EAAE,CAAC,OAAO,EAAE,CAAC,CAAC;YACvC,wEAAwE;YACxE,qDAAqD;YACrD,IAAI,CAAC,UAAU,CAAC,oBAAoB,EAAE,CAAC;QACzC,CAAC,CAAC,CAAC;IACL,CAAC;CACF;AAED,eAAe,UAAU,CAAC"}
|
|
@@ -0,0 +1,36 @@
|
|
|
1
|
+
import mongoose from 'mongoose';
|
|
2
|
+
import type { FrameworkRequest } from './HttpServer.ts';
|
|
3
|
+
/** Levels the registry may log a handled error at (winston leveled methods). */
|
|
4
|
+
export type ErrorLogLevel = 'error' | 'warn' | 'info' | 'http' | 'verbose' | 'debug' | 'silly';
|
|
5
|
+
/** What a handler returns to produce a response; `null`/`undefined` = pass. */
|
|
6
|
+
export interface ErrorHandlerResult {
|
|
7
|
+
status: number;
|
|
8
|
+
body: unknown;
|
|
9
|
+
}
|
|
10
|
+
export type ErrorHandlerFn<E extends Error = Error> = (err: E, req: FrameworkRequest) => ErrorHandlerResult | null | undefined | Promise<ErrorHandlerResult | null | undefined>;
|
|
11
|
+
/** A registered (class, handler, level) triple as stored by the registry. */
|
|
12
|
+
export interface RegisteredErrorHandler {
|
|
13
|
+
errorClass: abstract new (...args: never[]) => Error;
|
|
14
|
+
handler: ErrorHandlerFn;
|
|
15
|
+
logLevel: ErrorLogLevel;
|
|
16
|
+
}
|
|
17
|
+
/**
|
|
18
|
+
* Safety net for an escaped Mongoose `ValidationError`: returns a per-field
|
|
19
|
+
* `{ <path>: message }` map ONLY when every failing model path is a field the
|
|
20
|
+
* client actually sent — the keys of the validated `request` ∪ `query`, minus
|
|
21
|
+
* the framework-injected `contentType` discriminant (see
|
|
22
|
+
* `ControllerManager.#wrapHandlerEntry`). A nested path (`profile.name`)
|
|
23
|
+
* matches on its first segment and is reported under the full path (the
|
|
24
|
+
* client owns that subtree). Any renamed/internal path → `null`, so the
|
|
25
|
+
* caller keeps the honest 500 and never leaks a non-public field name.
|
|
26
|
+
*/
|
|
27
|
+
export declare function matchedClientValidationErrors(err: mongoose.Error.ValidationError, req: FrameworkRequest): Record<string, string> | null;
|
|
28
|
+
/**
|
|
29
|
+
* Framework built-in registry entries, checked AFTER any consumer-registered
|
|
30
|
+
* handlers ("yours win"):
|
|
31
|
+
* 1. `HttpError` → its own status / `body ?? { message }`; `verbose`
|
|
32
|
+
* (deliberate control flow, not a defect).
|
|
33
|
+
* 2. Escaped Mongoose `ValidationError` → the safety net above; `warn`
|
|
34
|
+
* (signals a route schema missing a constraint the model enforces).
|
|
35
|
+
*/
|
|
36
|
+
export declare function builtInErrorHandlers(): RegisteredErrorHandler[];
|
|
@@ -0,0 +1,71 @@
|
|
|
1
|
+
import mongoose from 'mongoose';
|
|
2
|
+
import { HttpError } from "./httpErrors.js";
|
|
3
|
+
/**
|
|
4
|
+
* Safety net for an escaped Mongoose `ValidationError`: returns a per-field
|
|
5
|
+
* `{ <path>: message }` map ONLY when every failing model path is a field the
|
|
6
|
+
* client actually sent — the keys of the validated `request` ∪ `query`, minus
|
|
7
|
+
* the framework-injected `contentType` discriminant (see
|
|
8
|
+
* `ControllerManager.#wrapHandlerEntry`). A nested path (`profile.name`)
|
|
9
|
+
* matches on its first segment and is reported under the full path (the
|
|
10
|
+
* client owns that subtree). Any renamed/internal path → `null`, so the
|
|
11
|
+
* caller keeps the honest 500 and never leaks a non-public field name.
|
|
12
|
+
*/
|
|
13
|
+
export function matchedClientValidationErrors(err, req) {
|
|
14
|
+
const failingPaths = Object.keys(err.errors);
|
|
15
|
+
if (failingPaths.length === 0) {
|
|
16
|
+
return null;
|
|
17
|
+
}
|
|
18
|
+
const inputKeys = new Set();
|
|
19
|
+
for (const source of [req.appInfo.request, req.appInfo.query]) {
|
|
20
|
+
if (source) {
|
|
21
|
+
for (const key of Object.keys(source)) {
|
|
22
|
+
inputKeys.add(key);
|
|
23
|
+
}
|
|
24
|
+
}
|
|
25
|
+
}
|
|
26
|
+
inputKeys.delete('contentType');
|
|
27
|
+
const errors = {};
|
|
28
|
+
for (const failingPath of failingPaths) {
|
|
29
|
+
if (!inputKeys.has(failingPath.split('.')[0])) {
|
|
30
|
+
return null;
|
|
31
|
+
}
|
|
32
|
+
errors[failingPath] = err.errors[failingPath].message;
|
|
33
|
+
}
|
|
34
|
+
return errors;
|
|
35
|
+
}
|
|
36
|
+
/**
|
|
37
|
+
* Framework built-in registry entries, checked AFTER any consumer-registered
|
|
38
|
+
* handlers ("yours win"):
|
|
39
|
+
* 1. `HttpError` → its own status / `body ?? { message }`; `verbose`
|
|
40
|
+
* (deliberate control flow, not a defect).
|
|
41
|
+
* 2. Escaped Mongoose `ValidationError` → the safety net above; `warn`
|
|
42
|
+
* (signals a route schema missing a constraint the model enforces).
|
|
43
|
+
*/
|
|
44
|
+
export function builtInErrorHandlers() {
|
|
45
|
+
return [
|
|
46
|
+
{
|
|
47
|
+
errorClass: HttpError,
|
|
48
|
+
// Entries are stored type-erased (`ErrorHandlerFn`); `resolveError`
|
|
49
|
+
// guarantees `instanceof errorClass` before the call.
|
|
50
|
+
handler: (err) => {
|
|
51
|
+
const httpErr = err;
|
|
52
|
+
return {
|
|
53
|
+
status: httpErr.status,
|
|
54
|
+
body: httpErr.body ?? { message: httpErr.message },
|
|
55
|
+
};
|
|
56
|
+
},
|
|
57
|
+
logLevel: 'verbose',
|
|
58
|
+
},
|
|
59
|
+
{
|
|
60
|
+
errorClass: mongoose.Error.ValidationError,
|
|
61
|
+
handler: (err, req) => {
|
|
62
|
+
const clientErrors = matchedClientValidationErrors(err, req);
|
|
63
|
+
return clientErrors
|
|
64
|
+
? { status: 400, body: { errors: clientErrors } }
|
|
65
|
+
: null;
|
|
66
|
+
},
|
|
67
|
+
logLevel: 'warn',
|
|
68
|
+
},
|
|
69
|
+
];
|
|
70
|
+
}
|
|
71
|
+
//# 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;AAkC5C;;;;;;;;;GASG;AACH,MAAM,UAAU,6BAA6B,CAC3C,GAAmC,EACnC,GAAqB;IAErB,MAAM,YAAY,GAAG,MAAM,CAAC,IAAI,CAAC,GAAG,CAAC,MAAM,CAAC,CAAC;IAC7C,IAAI,YAAY,CAAC,MAAM,KAAK,CAAC,EAAE,CAAC;QAC9B,OAAO,IAAI,CAAC;IACd,CAAC;IACD,MAAM,SAAS,GAAG,IAAI,GAAG,EAAU,CAAC;IACpC,KAAK,MAAM,MAAM,IAAI,CAAC,GAAG,CAAC,OAAO,CAAC,OAAO,EAAE,GAAG,CAAC,OAAO,CAAC,KAAK,CAAC,EAAE,CAAC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AG,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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