@adaptivestone/framework 5.6.0 → 5.7.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 +78 -1
- package/README.md +98 -0
- package/dist/clusterRunner.js +9 -4
- package/dist/clusterRunner.js.map +1 -1
- package/dist/codegen/appTypes.js +9 -6
- package/dist/codegen/appTypes.js.map +1 -1
- package/dist/codegen/astEmit.js +7 -0
- package/dist/codegen/astEmit.js.map +1 -1
- package/dist/codegen/astExtract.d.ts +3 -0
- package/dist/codegen/astExtract.js +1 -0
- package/dist/codegen/astExtract.js.map +1 -1
- package/dist/codegen/astResolve.d.ts +2 -0
- package/dist/codegen/astResolve.js +1 -0
- package/dist/codegen/astResolve.js.map +1 -1
- package/dist/codegen/emit.js +1 -1
- package/dist/codegen/index.js +1 -1
- package/dist/codegen/index.js.map +1 -1
- package/dist/commands/CreateUser.d.ts +1 -0
- package/dist/commands/CreateUser.js +1 -0
- package/dist/commands/CreateUser.js.map +1 -1
- package/dist/commands/SyncIndexes.js +4 -12
- package/dist/commands/SyncIndexes.js.map +1 -1
- package/dist/commands/migration/Migrate.js +3 -2
- package/dist/commands/migration/Migrate.js.map +1 -1
- package/dist/config/http.d.ts +1 -0
- package/dist/config/http.js +13 -2
- package/dist/config/http.js.map +1 -1
- package/dist/controllers/Auth.d.ts +22 -14
- package/dist/controllers/Auth.js +38 -72
- package/dist/controllers/Auth.js.map +1 -1
- package/dist/controllers/Auth.routes.gen.d.ts +1 -1
- package/dist/controllers/Auth.routes.gen.js +1 -1
- package/dist/controllers/Health.d.ts +8 -5
- package/dist/controllers/Health.js +11 -6
- package/dist/controllers/Health.js.map +1 -1
- package/dist/controllers/Health.routes.gen.d.ts +1 -1
- package/dist/controllers/Health.routes.gen.js +1 -1
- package/dist/controllers/Home.d.ts +3 -2
- package/dist/controllers/Home.js +6 -2
- package/dist/controllers/Home.js.map +1 -1
- package/dist/controllers/Home.routes.gen.d.ts +1 -1
- package/dist/controllers/Home.routes.gen.js +1 -1
- package/dist/controllers/index.js +83 -42
- package/dist/controllers/index.js.map +1 -1
- package/dist/helpers/crypto.d.ts +6 -0
- package/dist/helpers/crypto.js +21 -4
- package/dist/helpers/crypto.js.map +1 -1
- package/dist/helpers/logger.d.ts +3 -1
- package/dist/helpers/logger.js +11 -1
- package/dist/helpers/logger.js.map +1 -1
- package/dist/helpers/passwordPolicy.d.ts +23 -0
- package/dist/helpers/passwordPolicy.js +62 -0
- package/dist/helpers/passwordPolicy.js.map +1 -0
- package/dist/helpers/redis/redisConnection.d.ts +1 -0
- package/dist/helpers/redis/redisConnection.js +1 -0
- package/dist/helpers/redis/redisConnection.js.map +1 -1
- package/dist/helpers/yup.d.ts +11 -5
- package/dist/helpers/yup.js +12 -6
- package/dist/helpers/yup.js.map +1 -1
- package/dist/locales/ru/translation.json +31 -0
- package/dist/models/Lock.d.ts +2 -2
- package/dist/models/Lock.js +64 -15
- package/dist/models/Lock.js.map +1 -1
- package/dist/models/User.d.ts +5 -4
- package/dist/models/User.js +4 -4
- package/dist/models/User.js.map +1 -1
- package/dist/models/UserOld.d.ts +2 -0
- package/dist/models/UserOld.js +9 -3
- package/dist/models/UserOld.js.map +1 -1
- package/dist/modules/BaseCli.d.ts +5 -0
- package/dist/modules/BaseCli.js +10 -1
- package/dist/modules/BaseCli.js.map +1 -1
- package/dist/server.d.ts +22 -2
- package/dist/server.js +127 -18
- package/dist/server.js.map +1 -1
- package/dist/services/cache/Cache.js +16 -8
- package/dist/services/cache/Cache.js.map +1 -1
- package/dist/services/cache/drivers/RedisDriver.js +15 -11
- package/dist/services/cache/drivers/RedisDriver.js.map +1 -1
- package/dist/services/http/ExpressResponseWriter.d.ts +30 -0
- package/dist/services/http/ExpressResponseWriter.js +447 -0
- package/dist/services/http/ExpressResponseWriter.js.map +1 -0
- package/dist/services/http/HttpServer.d.ts +17 -11
- package/dist/services/http/HttpServer.js +71 -23
- package/dist/services/http/HttpServer.js.map +1 -1
- package/dist/services/http/ResponseWriter.d.ts +11 -0
- package/dist/services/http/ResponseWriter.js +2 -0
- package/dist/services/http/ResponseWriter.js.map +1 -0
- package/dist/services/http/builtInResponse.d.ts +26 -0
- package/dist/services/http/builtInResponse.js +70 -0
- package/dist/services/http/builtInResponse.js.map +1 -0
- package/dist/services/http/builtinErrorHandlers.d.ts +60 -7
- package/dist/services/http/builtinErrorHandlers.js +86 -5
- package/dist/services/http/builtinErrorHandlers.js.map +1 -1
- package/dist/services/http/files.d.ts +21 -8
- package/dist/services/http/files.js +2 -18
- package/dist/services/http/files.js.map +1 -1
- package/dist/services/http/httpErrors.d.ts +40 -2
- package/dist/services/http/httpErrors.js +50 -2
- package/dist/services/http/httpErrors.js.map +1 -1
- package/dist/services/http/middleware/Cors.js +5 -0
- package/dist/services/http/middleware/Cors.js.map +1 -1
- package/dist/services/http/middleware/IpDetector.js +23 -4
- package/dist/services/http/middleware/IpDetector.js.map +1 -1
- package/dist/services/http/middleware/Pagination.js +4 -2
- package/dist/services/http/middleware/Pagination.js.map +1 -1
- package/dist/services/http/middleware/RateLimiter.d.ts +1 -0
- package/dist/services/http/middleware/RateLimiter.js +37 -13
- package/dist/services/http/middleware/RateLimiter.js.map +1 -1
- package/dist/services/http/middleware/RequestParser.d.ts +9 -3
- package/dist/services/http/middleware/RequestParser.js +108 -36
- package/dist/services/http/middleware/RequestParser.js.map +1 -1
- package/dist/services/http/responses.d.ts +114 -0
- package/dist/services/http/responses.js +191 -0
- package/dist/services/http/responses.js.map +1 -0
- package/dist/services/http/routing/ExpressAdapter.d.ts +4 -1
- package/dist/services/http/routing/ExpressAdapter.js +82 -9
- package/dist/services/http/routing/ExpressAdapter.js.map +1 -1
- package/dist/services/http/routing/RouteRegistry.js +21 -10
- package/dist/services/http/routing/RouteRegistry.js.map +1 -1
- package/dist/services/i18n/I18n.js.map +1 -1
- package/dist/services/i18n/types.d.ts +2 -1
- package/dist/services/validate/ValidationError.d.ts +8 -1
- package/dist/services/validate/ValidationError.js +10 -2
- package/dist/services/validate/ValidationError.js.map +1 -1
- package/dist/services/validate/drivers/YupDriver.js +44 -6
- package/dist/services/validate/drivers/YupDriver.js.map +1 -1
- package/dist/tests/setupFramework.d.ts +4 -1
- package/dist/tests/setupFramework.js +15 -9
- package/dist/tests/setupFramework.js.map +1 -1
- package/package.json +5 -5
|
@@ -1,13 +1,59 @@
|
|
|
1
1
|
import { unlink } from 'node:fs/promises';
|
|
2
2
|
import formidable, { json, multipart, octetstream, querystring, } from 'formidable';
|
|
3
3
|
import { normalizeContentType } from '../../validate/contentType.js';
|
|
4
|
+
import { FRAMEWORK_ERROR_CODES, HttpError } from '../httpErrors.js';
|
|
4
5
|
import AbstractMiddleware from './AbstractMiddleware.js';
|
|
6
|
+
const bodyFormats = {
|
|
7
|
+
json: { plugin: json, mediaType: 'application/json' },
|
|
8
|
+
urlencoded: {
|
|
9
|
+
plugin: querystring,
|
|
10
|
+
mediaType: 'application/x-www-form-urlencoded',
|
|
11
|
+
},
|
|
12
|
+
};
|
|
13
|
+
/**
|
|
14
|
+
* The body format `config.http.requestParser.mediaTypes` assigns to a media
|
|
15
|
+
* type. Keys match case-insensitively; unknown formats are ignored.
|
|
16
|
+
*/
|
|
17
|
+
function findBodyFormat(mediaType, mediaTypes) {
|
|
18
|
+
if (!mediaType || typeof mediaTypes !== 'object' || mediaTypes === null) {
|
|
19
|
+
return undefined;
|
|
20
|
+
}
|
|
21
|
+
let format;
|
|
22
|
+
for (const [key, value] of Object.entries(mediaTypes)) {
|
|
23
|
+
if (key.toLowerCase() === mediaType) {
|
|
24
|
+
format = value;
|
|
25
|
+
}
|
|
26
|
+
}
|
|
27
|
+
return typeof format === 'string' && Object.hasOwn(bodyFormats, format)
|
|
28
|
+
? bodyFormats[format]
|
|
29
|
+
: undefined;
|
|
30
|
+
}
|
|
31
|
+
/**
|
|
32
|
+
* Formidable's plugins check the `Content-Type` header themselves. Show the
|
|
33
|
+
* plugin its own media type so a mapped type reaches that parser.
|
|
34
|
+
*/
|
|
35
|
+
function asMediaType(plugin, mediaType) {
|
|
36
|
+
return (form, options) => {
|
|
37
|
+
const target = form;
|
|
38
|
+
const { headers } = target;
|
|
39
|
+
target.headers = { ...headers, 'content-type': mediaType };
|
|
40
|
+
try {
|
|
41
|
+
plugin(form, options);
|
|
42
|
+
}
|
|
43
|
+
finally {
|
|
44
|
+
target.headers = headers;
|
|
45
|
+
}
|
|
46
|
+
};
|
|
47
|
+
}
|
|
5
48
|
/**
|
|
6
49
|
* Parses multipart / urlencoded / json request bodies (via formidable) into
|
|
7
50
|
* `req.body`. Size and count limits come from `config.http.requestParser`
|
|
8
|
-
* (explicit per-mount params override them)
|
|
51
|
+
* (explicit per-mount params override them), and so do extra media types to
|
|
52
|
+
* parse as JSON or urlencoded (`mediaTypes`). Spooled upload temp files are
|
|
9
53
|
* unlinked once the response finishes — a handler that needs to keep an upload
|
|
10
|
-
* MUST move or copy it (e.g. `fs.rename`) before responding.
|
|
54
|
+
* MUST move or copy it (e.g. `fs.rename`) before responding. An oversized body
|
|
55
|
+
* (413) or an unparsable one (400) is passed on as an `HttpError`, so the
|
|
56
|
+
* error-handler registry answers it.
|
|
11
57
|
*/
|
|
12
58
|
class RequestParser extends AbstractMiddleware {
|
|
13
59
|
static get description() {
|
|
@@ -18,56 +64,66 @@ class RequestParser extends AbstractMiddleware {
|
|
|
18
64
|
this.logger?.verbose(`Parsing request`);
|
|
19
65
|
const { requestParser } = this.app.getConfig('http');
|
|
20
66
|
// Config defaults bound unauthenticated uploads; explicit per-mount params win.
|
|
21
|
-
const
|
|
67
|
+
const { mediaTypes, ...parserOptions } = {
|
|
68
|
+
...requestParser,
|
|
69
|
+
...this.params,
|
|
70
|
+
};
|
|
22
71
|
const mediaType = normalizeContentType(req.headers?.['content-type']);
|
|
23
|
-
const
|
|
72
|
+
const mapped = findBodyFormat(mediaType, mediaTypes);
|
|
73
|
+
const isMultipart = !mapped &&
|
|
74
|
+
(mediaType === 'multipart/form-data' ||
|
|
75
|
+
mediaType === 'multipart/related');
|
|
76
|
+
const isOctetStream = !mapped && mediaType === 'application/octet-stream';
|
|
24
77
|
// Formidable's default plugins inspect the entire header. Select one for
|
|
25
78
|
// known media types so parameter text cannot switch the parser.
|
|
26
|
-
const plugin =
|
|
27
|
-
?
|
|
28
|
-
:
|
|
29
|
-
?
|
|
30
|
-
: mediaType === 'application/
|
|
31
|
-
?
|
|
32
|
-
: mediaType === 'application/
|
|
33
|
-
?
|
|
34
|
-
:
|
|
79
|
+
const plugin = mapped
|
|
80
|
+
? asMediaType(mapped.plugin, mapped.mediaType)
|
|
81
|
+
: isMultipart
|
|
82
|
+
? multipart
|
|
83
|
+
: mediaType === 'application/json' || mediaType?.endsWith('+json')
|
|
84
|
+
? json
|
|
85
|
+
: mediaType === 'application/x-www-form-urlencoded'
|
|
86
|
+
? querystring
|
|
87
|
+
: isOctetStream
|
|
88
|
+
? octetstream
|
|
89
|
+
: undefined;
|
|
35
90
|
const form = formidable({
|
|
36
91
|
...parserOptions,
|
|
37
92
|
...(plugin ? { enabledPlugins: [plugin] } : {}),
|
|
38
93
|
});
|
|
39
|
-
// JSON/urlencoded parsing buffers the body
|
|
40
|
-
//
|
|
41
|
-
|
|
42
|
-
|
|
43
|
-
|
|
94
|
+
// JSON/urlencoded parsing buffers the body, bounded by maxFieldsSize, and
|
|
95
|
+
// unknown media types retain the v5 fallback. Multipart uses Formidable's
|
|
96
|
+
// file limits. An octet-stream body is one file, but Formidable checks
|
|
97
|
+
// those limits only on multipart parts, so it is bounded here by them.
|
|
98
|
+
const { maxFileSize, maxTotalFileSize } = form.options;
|
|
99
|
+
const limitName = isOctetStream ? 'maxFileSize' : 'maxFieldsSize';
|
|
100
|
+
const maxBodySize = isOctetStream
|
|
101
|
+
? Math.min(maxFileSize, maxTotalFileSize)
|
|
102
|
+
: typeof parserOptions.maxFieldsSize === 'number'
|
|
103
|
+
? parserOptions.maxFieldsSize
|
|
104
|
+
: 2 * 1024 * 1024;
|
|
44
105
|
let bodyTooLarge = false;
|
|
45
106
|
if (!isMultipart) {
|
|
46
107
|
const declaredLength = Number(req.headers?.['content-length']);
|
|
47
108
|
if (Number.isFinite(declaredLength) && declaredLength > maxBodySize) {
|
|
48
|
-
this.logger?.error(`Request body ${declaredLength}B exceeds
|
|
109
|
+
this.logger?.error(`Request body ${declaredLength}B exceeds ${limitName} ${maxBodySize}B`);
|
|
49
110
|
// Close after the 413 instead of draining the unread body.
|
|
50
111
|
res.setHeader('Connection', 'close');
|
|
51
|
-
return
|
|
52
|
-
message: this.translate(req, 'middleware.requestParser.entityTooLarge', 'Request entity too large. Your upload exceeds the allowed size or count limits.'),
|
|
53
|
-
});
|
|
112
|
+
return next(this.#entityTooLarge(req));
|
|
54
113
|
}
|
|
55
114
|
}
|
|
56
|
-
// Also guard chunked bodies.
|
|
57
|
-
//
|
|
58
|
-
//
|
|
59
|
-
// `Connection: close` then ends the connection.
|
|
115
|
+
// Also guard chunked bodies. Multipart enforces its own file limits. Pausing (not destroying) the request keeps the socket writable,
|
|
116
|
+
// so the client receives the 413; its `Connection: close` then ends the
|
|
117
|
+
// connection.
|
|
60
118
|
let rejectOversized = () => { };
|
|
61
119
|
const oversized = new Promise((_resolve, reject) => {
|
|
62
120
|
rejectOversized = reject;
|
|
63
121
|
});
|
|
64
122
|
form.on('progress', (bytesReceived) => {
|
|
65
|
-
if (!bodyTooLarge &&
|
|
66
|
-
form.type !== 'multipart' &&
|
|
67
|
-
bytesReceived > maxBodySize) {
|
|
123
|
+
if (!bodyTooLarge && !isMultipart && bytesReceived > maxBodySize) {
|
|
68
124
|
bodyTooLarge = true;
|
|
69
125
|
req.pause();
|
|
70
|
-
rejectOversized(new Error(
|
|
126
|
+
rejectOversized(new Error(`Request body exceeds ${limitName}`));
|
|
71
127
|
}
|
|
72
128
|
});
|
|
73
129
|
// Track every temp file formidable opens (via fileBegin, so a file that
|
|
@@ -77,6 +133,12 @@ class RequestParser extends AbstractMiddleware {
|
|
|
77
133
|
const openedFiles = [];
|
|
78
134
|
form.on('fileBegin', (_name, file) => {
|
|
79
135
|
openedFiles.push(file);
|
|
136
|
+
// Formidable handles a temp-file write error (disk full, missing
|
|
137
|
+
// uploadDir) for multipart parts only; for an octet-stream body it was
|
|
138
|
+
// an uncaught error that crashed the process. Fail the parse instead.
|
|
139
|
+
if (isOctetStream) {
|
|
140
|
+
file.on('error', (err) => form.emit('error', err));
|
|
141
|
+
}
|
|
80
142
|
});
|
|
81
143
|
let cleaned = false;
|
|
82
144
|
const cleanup = () => {
|
|
@@ -97,7 +159,7 @@ class RequestParser extends AbstractMiddleware {
|
|
|
97
159
|
// Pausing the stream cannot cancel a chunk already inside the parser.
|
|
98
160
|
// Even if that chunk completes parsing, an oversized body must not advance.
|
|
99
161
|
if (bodyTooLarge) {
|
|
100
|
-
throw new Error(
|
|
162
|
+
throw new Error(`Request body exceeds ${limitName}`);
|
|
101
163
|
}
|
|
102
164
|
}
|
|
103
165
|
catch (err) {
|
|
@@ -110,13 +172,12 @@ class RequestParser extends AbstractMiddleware {
|
|
|
110
172
|
// The rest of the body stays unread; close rather than drain it.
|
|
111
173
|
res.setHeader('Connection', 'close');
|
|
112
174
|
}
|
|
113
|
-
return
|
|
114
|
-
message: this.translate(req, 'middleware.requestParser.entityTooLarge', 'Request entity too large. Your upload exceeds the allowed size or count limits.'),
|
|
115
|
-
});
|
|
175
|
+
return next(this.#entityTooLarge(req));
|
|
116
176
|
}
|
|
117
|
-
return
|
|
177
|
+
return next(new HttpError(400, {
|
|
178
|
+
code: FRAMEWORK_ERROR_CODES.malformedBody,
|
|
118
179
|
message: this.translate(req, 'middleware.requestParser.parseError', `Error to parse your request. You provided invalid content type or content-length. Please check your request headers and content type.`),
|
|
119
|
-
});
|
|
180
|
+
}));
|
|
120
181
|
}
|
|
121
182
|
this.logger?.verbose(`Parsing multipart/formdata request DONE ${Date.now() - time}ms`);
|
|
122
183
|
// formidable wraps multipart/urlencoded fields in arrays (one entry per
|
|
@@ -132,6 +193,11 @@ class RequestParser extends AbstractMiddleware {
|
|
|
132
193
|
? [key, value[0]]
|
|
133
194
|
: [key, value]))
|
|
134
195
|
: fields;
|
|
196
|
+
// Formidable lists a field's files as their writes finish; keep the order
|
|
197
|
+
// they were sent, which is the order they began.
|
|
198
|
+
for (const list of Object.values(files)) {
|
|
199
|
+
list?.sort((a, b) => openedFiles.indexOf(a) - openedFiles.indexOf(b));
|
|
200
|
+
}
|
|
135
201
|
req.body = {
|
|
136
202
|
// todo avoid body in next versions
|
|
137
203
|
...(req.body || {}),
|
|
@@ -140,6 +206,12 @@ class RequestParser extends AbstractMiddleware {
|
|
|
140
206
|
};
|
|
141
207
|
return next();
|
|
142
208
|
}
|
|
209
|
+
#entityTooLarge(req) {
|
|
210
|
+
return new HttpError(413, {
|
|
211
|
+
code: FRAMEWORK_ERROR_CODES.payloadTooLarge,
|
|
212
|
+
message: this.translate(req, 'middleware.requestParser.entityTooLarge', 'Request entity too large. Your upload exceeds the allowed size or count limits.'),
|
|
213
|
+
});
|
|
214
|
+
}
|
|
143
215
|
}
|
|
144
216
|
export default RequestParser;
|
|
145
217
|
//# sourceMappingURL=RequestParser.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"RequestParser.js","sourceRoot":"","sources":["../../../../src/services/http/middleware/RequestParser.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,MAAM,EAAE,MAAM,kBAAkB,CAAC;
|
|
1
|
+
{"version":3,"file":"RequestParser.js","sourceRoot":"","sources":["../../../../src/services/http/middleware/RequestParser.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,MAAM,EAAE,MAAM,kBAAkB,CAAC;AAG1C,OAAO,UAAU,EAAE,EACjB,IAAI,EACJ,SAAS,EACT,WAAW,EACX,WAAW,GACZ,MAAM,YAAY,CAAC;AAEpB,OAAO,EAAE,oBAAoB,EAAE,MAAM,+BAA+B,CAAC;AAErE,OAAO,EAAE,qBAAqB,EAAE,SAAS,EAAE,MAAM,kBAAkB,CAA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Ae,CAAC,GAAqB;QACnC,OAAO,IAAI,SAAS,CAAC,GAAG,EAAE;YACxB,IAAI,EAAE,qBAAqB,CAAC,eAAe;YAC3C,OAAO,EAAE,IAAI,CAAC,SAAS,CACrB,GAAG,EACH,yCAAyC,EACzC,iFAAiF,CAClF;SACF,CAAC,CAAC;IACL,CAAC;CACF;AAED,eAAe,aAAa,CAAC"}
|
|
@@ -0,0 +1,114 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Typed response values. A route handler returns one instead of writing to
|
|
3
|
+
* Express `res`; the framework renders it. Descriptors are immutable data:
|
|
4
|
+
* build them with the `HttpResponse` factories, never by hand.
|
|
5
|
+
*
|
|
6
|
+
* @example
|
|
7
|
+
* async create(req: CreateUserRequest): Promise<JsonResponse<201, UserDto>> {
|
|
8
|
+
* const user = await this.app.getModel('User').create(req.appInfo.request);
|
|
9
|
+
* return HttpResponse.json(201, user);
|
|
10
|
+
* }
|
|
11
|
+
*/
|
|
12
|
+
/** Registered, not module-private, so two installed copies of the framework recognize each other's responses. */
|
|
13
|
+
declare const BRAND: unique symbol;
|
|
14
|
+
/** Statuses that never carry a body; only `HttpResponse.empty` accepts them. */
|
|
15
|
+
export type NoBodyStatus = 204 | 205 | 304;
|
|
16
|
+
/** Statuses accepted by `HttpResponse.redirect`. */
|
|
17
|
+
export type RedirectStatus = 301 | 302 | 303 | 307 | 308;
|
|
18
|
+
/** A literal status a body response cannot use (1xx, 204/205/304, 206) becomes `never`. */
|
|
19
|
+
type BodyStatus<S extends number> = S extends NoBodyStatus | 206 ? never : `${S}` extends `1${string}` ? never : S;
|
|
20
|
+
/** A literal status `HttpResponse.empty` cannot use (1xx, 206) becomes `never`. */
|
|
21
|
+
type EmptyStatus<S extends number> = S extends 206 ? never : `${S}` extends `1${string}` ? never : S;
|
|
22
|
+
/** Response headers: lower-case names, one entry per `set-cookie` value. */
|
|
23
|
+
export type ResponseHeaders = ReadonlyArray<readonly [name: string, value: string]>;
|
|
24
|
+
/** Anything the Web `Headers` constructor accepts, including a descriptor's `headers`. */
|
|
25
|
+
export type ResponseHeadersInit = Headers | Record<string, string> | ReadonlyArray<readonly [string, string]>;
|
|
26
|
+
/** A byte source for `HttpResponse.stream`; a Node `Readable` is an async iterable too. */
|
|
27
|
+
export type ByteStream = ReadableStream<Uint8Array> | AsyncIterable<Uint8Array>;
|
|
28
|
+
export interface ResponseOptions {
|
|
29
|
+
headers?: ResponseHeadersInit;
|
|
30
|
+
}
|
|
31
|
+
export interface BodyResponseOptions<M extends string> extends ResponseOptions {
|
|
32
|
+
/** Media type; set it here, not as a `content-type` header. */
|
|
33
|
+
contentType?: M;
|
|
34
|
+
}
|
|
35
|
+
interface ResponseBase<K extends string, S extends number> {
|
|
36
|
+
readonly [BRAND]: true;
|
|
37
|
+
readonly kind: K;
|
|
38
|
+
readonly status: S;
|
|
39
|
+
readonly headers: ResponseHeaders;
|
|
40
|
+
}
|
|
41
|
+
export interface JsonResponse<S extends number = number, B = unknown, M extends string = 'application/json'> extends ResponseBase<'json', S> {
|
|
42
|
+
readonly contentType: M;
|
|
43
|
+
readonly body: B;
|
|
44
|
+
}
|
|
45
|
+
export interface TextResponse<S extends number = number, M extends string = 'text/plain'> extends ResponseBase<'text', S> {
|
|
46
|
+
readonly contentType: M;
|
|
47
|
+
readonly body: string;
|
|
48
|
+
}
|
|
49
|
+
export interface BytesResponse<S extends number = number, M extends string = 'application/octet-stream'> extends ResponseBase<'bytes', S> {
|
|
50
|
+
readonly contentType: M;
|
|
51
|
+
readonly body: Uint8Array;
|
|
52
|
+
}
|
|
53
|
+
export interface StreamResponse<S extends number = number, M extends string = 'application/octet-stream'> extends ResponseBase<'stream', S> {
|
|
54
|
+
readonly contentType: M;
|
|
55
|
+
readonly body: ByteStream;
|
|
56
|
+
}
|
|
57
|
+
export interface RedirectResponse<S extends RedirectStatus = RedirectStatus> extends ResponseBase<'redirect', S> {
|
|
58
|
+
readonly location: string;
|
|
59
|
+
}
|
|
60
|
+
export interface EmptyResponse<S extends number = number> extends ResponseBase<'empty', S> {
|
|
61
|
+
}
|
|
62
|
+
/** A Web `Response` passed through as-is; its status and body types are not tracked. */
|
|
63
|
+
export interface NativeResponse extends ResponseBase<'native', number> {
|
|
64
|
+
readonly response: Response;
|
|
65
|
+
}
|
|
66
|
+
/** Statuses that never carry a body, as a runtime set. */
|
|
67
|
+
export declare const NO_BODY_STATUSES: ReadonlySet<number>;
|
|
68
|
+
declare function json<S extends number, B, M extends string = 'application/json'>(status: BodyStatus<S>, body: B, options?: BodyResponseOptions<M>): JsonResponse<S, B, M>;
|
|
69
|
+
declare function text<S extends number, M extends string = 'text/plain'>(status: BodyStatus<S>, body: string, options?: BodyResponseOptions<M>): TextResponse<S, M>;
|
|
70
|
+
declare function bytes<S extends number, M extends string = 'application/octet-stream'>(status: BodyStatus<S>, body: Uint8Array, options?: BodyResponseOptions<M>): BytesResponse<S, M>;
|
|
71
|
+
/**
|
|
72
|
+
* Stream bytes. The status and headers are sent with the first chunk, so an
|
|
73
|
+
* error before it is answered like a thrown error; a later error aborts the
|
|
74
|
+
* response. A client that disconnects stops the source (`return()` on the
|
|
75
|
+
* iterator, `cancel()` on a `ReadableStream`).
|
|
76
|
+
*/
|
|
77
|
+
declare function stream<S extends number, M extends string = 'application/octet-stream'>(status: BodyStatus<S>, body: ByteStream, options?: BodyResponseOptions<M>): StreamResponse<S, M>;
|
|
78
|
+
declare function redirect<S extends RedirectStatus>(status: S, location: string | URL, options?: ResponseOptions): RedirectResponse<S>;
|
|
79
|
+
declare function empty<S extends number>(status: EmptyStatus<S>, options?: ResponseOptions): EmptyResponse<S>;
|
|
80
|
+
/**
|
|
81
|
+
* Pass a Web `Response` through: its status, status text, headers and body
|
|
82
|
+
* are sent as they are, except the framing headers the server sets itself
|
|
83
|
+
* (`connection`, `transfer-encoding`, …). A `fetch()` response (non-empty
|
|
84
|
+
* `url`) with a body, a status other than 206 and only codings `fetch` decodes
|
|
85
|
+
* (`gzip`, `deflate`, `br`, `zstd`; under Bun a single one) also loses its
|
|
86
|
+
* upstream `content-encoding`, `content-length` and digest headers, which
|
|
87
|
+
* describe the encoded bytes; any other response is passed on as received,
|
|
88
|
+
* headers intact.
|
|
89
|
+
* To forward the upstream bytes exactly as received (for example fetched with
|
|
90
|
+
* decoding turned off), pass `new Response(upstream.body, upstream)`, which
|
|
91
|
+
* has no `url`.
|
|
92
|
+
*/
|
|
93
|
+
declare function native(response: Response): NativeResponse;
|
|
94
|
+
/** Is `value` a response built by an `HttpResponse` factory? */
|
|
95
|
+
declare function is(value: unknown): value is HttpResponse;
|
|
96
|
+
/**
|
|
97
|
+
* Response factories. Status is always the first argument. Statuses a kind
|
|
98
|
+
* cannot use fail to compile when written as literals and throw a
|
|
99
|
+
* `RangeError` at runtime: 1xx everywhere; 204, 205 and 304 everywhere but
|
|
100
|
+
* `empty`; 206 (reserved for range-aware file responses) everywhere.
|
|
101
|
+
*/
|
|
102
|
+
export declare const HttpResponse: Readonly<{
|
|
103
|
+
json: typeof json;
|
|
104
|
+
text: typeof text;
|
|
105
|
+
bytes: typeof bytes;
|
|
106
|
+
stream: typeof stream;
|
|
107
|
+
redirect: typeof redirect;
|
|
108
|
+
empty: typeof empty;
|
|
109
|
+
native: typeof native;
|
|
110
|
+
is: typeof is;
|
|
111
|
+
}>;
|
|
112
|
+
/** Any response a handler can return. */
|
|
113
|
+
export type HttpResponse = JsonResponse<number, unknown, string> | TextResponse<number, string> | BytesResponse<number, string> | StreamResponse<number, string> | RedirectResponse | EmptyResponse | NativeResponse;
|
|
114
|
+
export {};
|
|
@@ -0,0 +1,191 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Typed response values. A route handler returns one instead of writing to
|
|
3
|
+
* Express `res`; the framework renders it. Descriptors are immutable data:
|
|
4
|
+
* build them with the `HttpResponse` factories, never by hand.
|
|
5
|
+
*
|
|
6
|
+
* @example
|
|
7
|
+
* async create(req: CreateUserRequest): Promise<JsonResponse<201, UserDto>> {
|
|
8
|
+
* const user = await this.app.getModel('User').create(req.appInfo.request);
|
|
9
|
+
* return HttpResponse.json(201, user);
|
|
10
|
+
* }
|
|
11
|
+
*/
|
|
12
|
+
/** Registered, not module-private, so two installed copies of the framework recognize each other's responses. */
|
|
13
|
+
const BRAND = Symbol.for('@adaptivestone/framework/HttpResponse');
|
|
14
|
+
/** Statuses that never carry a body, as a runtime set. */
|
|
15
|
+
export const NO_BODY_STATUSES = new Set([204, 205, 304]);
|
|
16
|
+
const REDIRECT_STATUSES = new Set([
|
|
17
|
+
301, 302, 303, 307, 308,
|
|
18
|
+
]);
|
|
19
|
+
const NO_HEADERS = Object.freeze([]);
|
|
20
|
+
function assertFinalStatus(factory, status) {
|
|
21
|
+
if (!Number.isInteger(status) || status < 200 || status > 599) {
|
|
22
|
+
throw new RangeError(`HttpResponse.${factory}: status must be an integer from 200 to 599, got ${status}`);
|
|
23
|
+
}
|
|
24
|
+
}
|
|
25
|
+
function assertBodyStatus(factory, status) {
|
|
26
|
+
assertFinalStatus(factory, status);
|
|
27
|
+
if (NO_BODY_STATUSES.has(status)) {
|
|
28
|
+
throw new RangeError(`HttpResponse.${factory}: status ${status} never carries a body; use HttpResponse.empty(${status})`);
|
|
29
|
+
}
|
|
30
|
+
if (status === 206) {
|
|
31
|
+
throw new RangeError(`HttpResponse.${factory}: status 206 is reserved for range-aware file responses`);
|
|
32
|
+
}
|
|
33
|
+
}
|
|
34
|
+
/** Normalize through Web `Headers` (validates names and values) into frozen pairs. */
|
|
35
|
+
function toHeaders(factory, init, owned) {
|
|
36
|
+
if (init === undefined) {
|
|
37
|
+
return NO_HEADERS;
|
|
38
|
+
}
|
|
39
|
+
// Headers accepts any sequence of pairs; its type only lists mutable ones.
|
|
40
|
+
const headers = new Headers(init);
|
|
41
|
+
if (owned && headers.has(owned)) {
|
|
42
|
+
throw new TypeError(owned === 'location'
|
|
43
|
+
? `HttpResponse.${factory}: pass the location as the second argument, not as a location header`
|
|
44
|
+
: `HttpResponse.${factory}: pass the media type as options.contentType, not as a content-type header`);
|
|
45
|
+
}
|
|
46
|
+
return Object.freeze([...headers].map(([name, value]) => Object.freeze([name, value])));
|
|
47
|
+
}
|
|
48
|
+
function json(status, body, options) {
|
|
49
|
+
assertBodyStatus('json', status);
|
|
50
|
+
if (body === undefined) {
|
|
51
|
+
throw new TypeError('HttpResponse.json: body is undefined; use HttpResponse.empty(status) for a response without a body');
|
|
52
|
+
}
|
|
53
|
+
return Object.freeze({
|
|
54
|
+
[BRAND]: true,
|
|
55
|
+
kind: 'json',
|
|
56
|
+
status: status,
|
|
57
|
+
headers: toHeaders('json', options?.headers, 'content-type'),
|
|
58
|
+
contentType: (options?.contentType ?? 'application/json'),
|
|
59
|
+
body,
|
|
60
|
+
});
|
|
61
|
+
}
|
|
62
|
+
function text(status, body, options) {
|
|
63
|
+
assertBodyStatus('text', status);
|
|
64
|
+
if (typeof body !== 'string') {
|
|
65
|
+
throw new TypeError('HttpResponse.text: body must be a string');
|
|
66
|
+
}
|
|
67
|
+
return Object.freeze({
|
|
68
|
+
[BRAND]: true,
|
|
69
|
+
kind: 'text',
|
|
70
|
+
status: status,
|
|
71
|
+
headers: toHeaders('text', options?.headers, 'content-type'),
|
|
72
|
+
contentType: (options?.contentType ?? 'text/plain'),
|
|
73
|
+
body,
|
|
74
|
+
});
|
|
75
|
+
}
|
|
76
|
+
function bytes(status, body, options) {
|
|
77
|
+
assertBodyStatus('bytes', status);
|
|
78
|
+
if (!(body instanceof Uint8Array)) {
|
|
79
|
+
throw new TypeError('HttpResponse.bytes: body must be a Uint8Array');
|
|
80
|
+
}
|
|
81
|
+
return Object.freeze({
|
|
82
|
+
[BRAND]: true,
|
|
83
|
+
kind: 'bytes',
|
|
84
|
+
status: status,
|
|
85
|
+
headers: toHeaders('bytes', options?.headers, 'content-type'),
|
|
86
|
+
contentType: (options?.contentType ?? 'application/octet-stream'),
|
|
87
|
+
body,
|
|
88
|
+
});
|
|
89
|
+
}
|
|
90
|
+
/**
|
|
91
|
+
* Stream bytes. The status and headers are sent with the first chunk, so an
|
|
92
|
+
* error before it is answered like a thrown error; a later error aborts the
|
|
93
|
+
* response. A client that disconnects stops the source (`return()` on the
|
|
94
|
+
* iterator, `cancel()` on a `ReadableStream`).
|
|
95
|
+
*/
|
|
96
|
+
function stream(status, body, options) {
|
|
97
|
+
assertBodyStatus('stream', status);
|
|
98
|
+
if (typeof body?.[Symbol.asyncIterator] !== 'function') {
|
|
99
|
+
throw new TypeError('HttpResponse.stream: body must be a ReadableStream or an async iterable of bytes');
|
|
100
|
+
}
|
|
101
|
+
return Object.freeze({
|
|
102
|
+
[BRAND]: true,
|
|
103
|
+
kind: 'stream',
|
|
104
|
+
status: status,
|
|
105
|
+
headers: toHeaders('stream', options?.headers, 'content-type'),
|
|
106
|
+
contentType: (options?.contentType ?? 'application/octet-stream'),
|
|
107
|
+
body,
|
|
108
|
+
});
|
|
109
|
+
}
|
|
110
|
+
function redirect(status, location, options) {
|
|
111
|
+
if (!REDIRECT_STATUSES.has(status)) {
|
|
112
|
+
throw new RangeError(`HttpResponse.redirect: status must be 301, 302, 303, 307 or 308, got ${status}`);
|
|
113
|
+
}
|
|
114
|
+
const target = String(location);
|
|
115
|
+
if (target === '') {
|
|
116
|
+
throw new TypeError('HttpResponse.redirect: location must not be empty');
|
|
117
|
+
}
|
|
118
|
+
return Object.freeze({
|
|
119
|
+
[BRAND]: true,
|
|
120
|
+
kind: 'redirect',
|
|
121
|
+
status,
|
|
122
|
+
headers: toHeaders('redirect', options?.headers, 'location'),
|
|
123
|
+
location: target,
|
|
124
|
+
});
|
|
125
|
+
}
|
|
126
|
+
function empty(status, options) {
|
|
127
|
+
assertFinalStatus('empty', status);
|
|
128
|
+
if (status === 206) {
|
|
129
|
+
throw new RangeError('HttpResponse.empty: status 206 is reserved for range-aware file responses');
|
|
130
|
+
}
|
|
131
|
+
return Object.freeze({
|
|
132
|
+
[BRAND]: true,
|
|
133
|
+
kind: 'empty',
|
|
134
|
+
status: status,
|
|
135
|
+
headers: toHeaders('empty', options?.headers, null),
|
|
136
|
+
});
|
|
137
|
+
}
|
|
138
|
+
/**
|
|
139
|
+
* Pass a Web `Response` through: its status, status text, headers and body
|
|
140
|
+
* are sent as they are, except the framing headers the server sets itself
|
|
141
|
+
* (`connection`, `transfer-encoding`, …). A `fetch()` response (non-empty
|
|
142
|
+
* `url`) with a body, a status other than 206 and only codings `fetch` decodes
|
|
143
|
+
* (`gzip`, `deflate`, `br`, `zstd`; under Bun a single one) also loses its
|
|
144
|
+
* upstream `content-encoding`, `content-length` and digest headers, which
|
|
145
|
+
* describe the encoded bytes; any other response is passed on as received,
|
|
146
|
+
* headers intact.
|
|
147
|
+
* To forward the upstream bytes exactly as received (for example fetched with
|
|
148
|
+
* decoding turned off), pass `new Response(upstream.body, upstream)`, which
|
|
149
|
+
* has no `url`.
|
|
150
|
+
*/
|
|
151
|
+
function native(response) {
|
|
152
|
+
if (!(response instanceof Response)) {
|
|
153
|
+
throw new TypeError('HttpResponse.native: expected a Web Response');
|
|
154
|
+
}
|
|
155
|
+
if (response.type === 'error') {
|
|
156
|
+
throw new TypeError('HttpResponse.native: a network-error Response (Response.error()) has no status to send');
|
|
157
|
+
}
|
|
158
|
+
if (response.bodyUsed) {
|
|
159
|
+
throw new TypeError('HttpResponse.native: the Response body was already read');
|
|
160
|
+
}
|
|
161
|
+
return Object.freeze({
|
|
162
|
+
[BRAND]: true,
|
|
163
|
+
kind: 'native',
|
|
164
|
+
status: response.status,
|
|
165
|
+
headers: NO_HEADERS,
|
|
166
|
+
response,
|
|
167
|
+
});
|
|
168
|
+
}
|
|
169
|
+
/** Is `value` a response built by an `HttpResponse` factory? */
|
|
170
|
+
function is(value) {
|
|
171
|
+
return (typeof value === 'object' &&
|
|
172
|
+
value !== null &&
|
|
173
|
+
value[BRAND] === true);
|
|
174
|
+
}
|
|
175
|
+
/**
|
|
176
|
+
* Response factories. Status is always the first argument. Statuses a kind
|
|
177
|
+
* cannot use fail to compile when written as literals and throw a
|
|
178
|
+
* `RangeError` at runtime: 1xx everywhere; 204, 205 and 304 everywhere but
|
|
179
|
+
* `empty`; 206 (reserved for range-aware file responses) everywhere.
|
|
180
|
+
*/
|
|
181
|
+
export const HttpResponse = Object.freeze({
|
|
182
|
+
json,
|
|
183
|
+
text,
|
|
184
|
+
bytes,
|
|
185
|
+
stream,
|
|
186
|
+
redirect,
|
|
187
|
+
empty,
|
|
188
|
+
native,
|
|
189
|
+
is,
|
|
190
|
+
});
|
|
191
|
+
//# sourceMappingURL=responses.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"responses.js","sourceRoot":"","sources":["../../../src/services/http/responses.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;GAUG;AAEH,iHAAiH;AACjH,MAAM,KAAK,GAAkB,MAAM,CAAC,GAAG,CACrC,uCAAuC,CACxC,CAAC;AAkGF,0DAA0D;AAC1D,MAAM,CAAC,MAAM,gBAAgB,GAAwB,IAAI,GAAG,CAAC,CAAC,GAAG,EAAE,GAAG,EAAE,GAAG,CAAC,CAAC,CAAC;AAC9E,MAAM,iBAAiB,GAAwB,IAAI,GAAG,CAAC;IACrD,GAAG,EAAE,GAAG,EAAE,GAAG,EAAE,GAAG,EAAE,GAAG;CACxB,CAAC,CAAC;AACH,MAAM,UAAU,GAAoB,MAAM,CAAC,MAAM,CAAC,EAAE,CAAC,CAAC;AAEtD,SAAS,iBAAiB,CAAC,OAAe,EAAE,MAAc;IACxD,IAAI,CAAC,MAAM,CAAC,SAAS,CAAC,MAAM,CAAC,IAAI,MAAM,GAAG,GAAG,IAAI,MAAM,GAAG,GAAG,EAAE,CAAC;QAC9D,MAAM,IAAI,UAAU,CAClB,gBAAgB,OAAO,oDAAoD,MAAM,EAAE,CACpF,CAAC;IACJ,CAAC;AACH,CAAC;AAED,SAAS,gBAAgB,CAAC,OAAe,EAAE,MAAc;IACvD,iBAAiB,CAAC,OAAO,EAAE,MAAM,CAAC,CAAC;IACnC,IAAI,gBAAgB,CAAC,GAAG,CAAC,M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CAAC,MAAM,CAAC;IACxC,IAAI;IACJ,IAAI;IACJ,KAAK;IACL,MAAM;IACN,QAAQ;IACR,KAAK;IACL,MAAM;IACN,EAAE;CACH,CAAC,CAAC"}
|
|
@@ -7,6 +7,9 @@
|
|
|
7
7
|
*/
|
|
8
8
|
import type { NextFunction, Request, Response } from 'express';
|
|
9
9
|
import type { IApp } from '../../../server.ts';
|
|
10
|
+
import type { ResponseWriter } from '../ResponseWriter.ts';
|
|
10
11
|
import type { RouteRegistry } from './RouteRegistry.ts';
|
|
12
|
+
/** @internal A failure for `next`: a falsy one would fall through to the 404. */
|
|
13
|
+
export declare function failure(reason: unknown): unknown;
|
|
11
14
|
export type ExpressAdapter = (req: Request, res: Response, next: NextFunction) => Promise<void>;
|
|
12
|
-
export declare function createExpressAdapter(registry: RouteRegistry, app: IApp): ExpressAdapter;
|
|
15
|
+
export declare function createExpressAdapter(registry: RouteRegistry, app: IApp, writer?: ResponseWriter<Request, Response>): ExpressAdapter;
|