@opra/core 1.0.0-beta.1 → 1.0.0-beta.3

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.
Files changed (85) hide show
  1. package/cjs/execution-context.js +2 -14
  2. package/cjs/index.js +3 -25
  3. package/cjs/platform-adapter.js +3 -3
  4. package/esm/execution-context.js +1 -13
  5. package/esm/index.js +3 -24
  6. package/esm/platform-adapter.js +2 -2
  7. package/package.json +5 -39
  8. package/types/execution-context.d.ts +3 -8
  9. package/types/index.d.cts +3 -23
  10. package/types/index.d.ts +3 -23
  11. package/types/interfaces/logger.interface.d.ts +1 -1
  12. package/types/platform-adapter.d.ts +3 -3
  13. package/types/service-base.d.ts +10 -0
  14. package/cjs/augmentation/http-controller.augmentation.js +0 -25
  15. package/cjs/http/express-adapter.js +0 -155
  16. package/cjs/http/http-adapter.js +0 -24
  17. package/cjs/http/http-context.js +0 -104
  18. package/cjs/http/http-handler.js +0 -609
  19. package/cjs/http/impl/http-incoming.host.js +0 -112
  20. package/cjs/http/impl/http-outgoing.host.js +0 -207
  21. package/cjs/http/impl/multipart-reader.js +0 -196
  22. package/cjs/http/impl/node-incoming-message.host.js +0 -109
  23. package/cjs/http/impl/node-outgoing-message.host.js +0 -195
  24. package/cjs/http/interfaces/http-incoming.interface.js +0 -25
  25. package/cjs/http/interfaces/http-outgoing.interface.js +0 -22
  26. package/cjs/http/interfaces/node-incoming-message.interface.js +0 -64
  27. package/cjs/http/interfaces/node-outgoing-message.interface.js +0 -15
  28. package/cjs/http/utils/body-reader.js +0 -216
  29. package/cjs/http/utils/common.js +0 -67
  30. package/cjs/http/utils/concat-readable.js +0 -19
  31. package/cjs/http/utils/convert-to-headers.js +0 -64
  32. package/cjs/http/utils/convert-to-raw-headers.js +0 -23
  33. package/cjs/http/utils/match-known-fields.js +0 -49
  34. package/cjs/http/utils/wrap-exception.js +0 -33
  35. package/cjs/type-guards.js +0 -22
  36. package/esm/augmentation/http-controller.augmentation.js +0 -23
  37. package/esm/http/express-adapter.js +0 -150
  38. package/esm/http/http-adapter.js +0 -20
  39. package/esm/http/http-context.js +0 -99
  40. package/esm/http/http-handler.js +0 -604
  41. package/esm/http/impl/http-incoming.host.js +0 -107
  42. package/esm/http/impl/http-outgoing.host.js +0 -202
  43. package/esm/http/impl/multipart-reader.js +0 -191
  44. package/esm/http/impl/node-incoming-message.host.js +0 -105
  45. package/esm/http/impl/node-outgoing-message.host.js +0 -191
  46. package/esm/http/interfaces/http-incoming.interface.js +0 -22
  47. package/esm/http/interfaces/http-outgoing.interface.js +0 -19
  48. package/esm/http/interfaces/node-incoming-message.interface.js +0 -61
  49. package/esm/http/interfaces/node-outgoing-message.interface.js +0 -12
  50. package/esm/http/utils/body-reader.js +0 -211
  51. package/esm/http/utils/common.js +0 -61
  52. package/esm/http/utils/concat-readable.js +0 -16
  53. package/esm/http/utils/convert-to-headers.js +0 -60
  54. package/esm/http/utils/convert-to-raw-headers.js +0 -20
  55. package/esm/http/utils/match-known-fields.js +0 -45
  56. package/esm/http/utils/wrap-exception.js +0 -30
  57. package/esm/type-guards.js +0 -16
  58. package/types/augmentation/http-controller.augmentation.d.ts +0 -20
  59. package/types/helpers/service-base.d.ts +0 -10
  60. package/types/http/express-adapter.d.ts +0 -13
  61. package/types/http/http-adapter.d.ts +0 -54
  62. package/types/http/http-context.d.ts +0 -44
  63. package/types/http/http-handler.d.ts +0 -75
  64. package/types/http/impl/http-incoming.host.d.ts +0 -22
  65. package/types/http/impl/http-outgoing.host.d.ts +0 -17
  66. package/types/http/impl/multipart-reader.d.ts +0 -46
  67. package/types/http/impl/node-incoming-message.host.d.ts +0 -45
  68. package/types/http/impl/node-outgoing-message.host.d.ts +0 -49
  69. package/types/http/interfaces/http-incoming.interface.d.ts +0 -192
  70. package/types/http/interfaces/http-outgoing.interface.d.ts +0 -144
  71. package/types/http/interfaces/node-incoming-message.interface.d.ts +0 -36
  72. package/types/http/interfaces/node-outgoing-message.interface.d.ts +0 -27
  73. package/types/http/utils/body-reader.d.ts +0 -38
  74. package/types/http/utils/common.d.ts +0 -17
  75. package/types/http/utils/concat-readable.d.ts +0 -2
  76. package/types/http/utils/convert-to-headers.d.ts +0 -2
  77. package/types/http/utils/convert-to-raw-headers.d.ts +0 -2
  78. package/types/http/utils/match-known-fields.d.ts +0 -6
  79. package/types/http/utils/wrap-exception.d.ts +0 -2
  80. package/types/type-guards.d.ts +0 -8
  81. /package/cjs/{http/impl/asset-cache.js → asset-cache.js} +0 -0
  82. /package/cjs/{helpers/service-base.js → service-base.js} +0 -0
  83. /package/esm/{http/impl/asset-cache.js → asset-cache.js} +0 -0
  84. /package/esm/{helpers/service-base.js → service-base.js} +0 -0
  85. /package/types/{http/impl/asset-cache.d.ts → asset-cache.d.ts} +0 -0
@@ -1,195 +0,0 @@
1
- "use strict";
2
- /*
3
- This file contains code blocks from open source NodeJs project
4
- https://github.com/nodejs/
5
- */
6
- Object.defineProperty(exports, "__esModule", { value: true });
7
- exports.NodeOutgoingMessageHost = exports.kOutTrailers = exports.kOutHeaders = void 0;
8
- const stream_1 = require("stream");
9
- const common_js_1 = require("../utils/common.js");
10
- exports.kOutHeaders = Symbol.for('kOutHeaders');
11
- exports.kOutTrailers = Symbol.for('kOutTrailers');
12
- // noinspection JSUnusedLocalSymbols
13
- /**
14
- *
15
- * @class NodeOutgoingMessageHost
16
- */
17
- class NodeOutgoingMessageHost extends stream_1.Duplex {
18
- constructor(init) {
19
- super();
20
- this._headersSent = false;
21
- this.finished = false;
22
- if (init) {
23
- this.req = init.req;
24
- this.statusCode = init?.statusCode || 0;
25
- this.statusMessage = init?.statusMessage || '';
26
- this.chunkedEncoding = !!init?.chunkedEncoding;
27
- this.sendDate = !!init?.sendDate;
28
- this.strictContentLength = !!init?.strictContentLength;
29
- if (init.headers)
30
- this.setHeaders(Array.isArray(init.headers) ? new Map([init.headers]) : init.headers);
31
- this.body = init.body;
32
- }
33
- }
34
- get httpVersionMajor() {
35
- return this.req?.httpVersionMajor || this._httpVersionMajor;
36
- }
37
- get httpVersionMinor() {
38
- return this.req?.httpVersionMinor || this._httpVersionMinor;
39
- }
40
- get headersSent() {
41
- return this._headersSent;
42
- }
43
- appendHeader(name, value) {
44
- if (this.headersSent)
45
- throw new Error(`Cannot set headers after they are sent to the client`);
46
- (0, common_js_1.validateHeaderName)(name);
47
- (0, common_js_1.validateHeaderValue)(name, value);
48
- const field = name.toLowerCase();
49
- const headers = this[exports.kOutHeaders];
50
- if (headers == null || !headers[field]) {
51
- return this.setHeader(name, value);
52
- }
53
- // Prepare the field for appending, if required
54
- if (!Array.isArray(headers[field][1])) {
55
- headers[field][1] = [headers[field][1]];
56
- }
57
- const existingValues = headers[field][1];
58
- if (Array.isArray(value)) {
59
- for (let i = 0, length = value.length; i < length; i++) {
60
- existingValues.push(value[i]);
61
- }
62
- }
63
- else {
64
- existingValues.push(value);
65
- }
66
- return this;
67
- }
68
- addTrailers(headers) {
69
- if (headers && typeof headers === 'object') {
70
- const entries = typeof headers.entries === 'function' ? headers.entries() : Object.entries(headers);
71
- let trailers = this[exports.kOutTrailers];
72
- if (trailers == null)
73
- this[exports.kOutTrailers] = trailers = { __proto__: null };
74
- for (const [name, value] of entries) {
75
- (0, common_js_1.validateHeaderName)(name);
76
- (0, common_js_1.validateHeaderValue)(name, value);
77
- trailers[String(name).toLowerCase()] = [String(name), value];
78
- }
79
- return;
80
- }
81
- throw new TypeError('Invalid "headers" argument. Value must be an object or raw headers array');
82
- }
83
- flushHeaders() {
84
- // nothing to do
85
- }
86
- setHeader(name, value) {
87
- if (this.headersSent)
88
- throw new Error(`Cannot set headers after they are sent to the client`);
89
- (0, common_js_1.validateHeaderName)(name);
90
- (0, common_js_1.validateHeaderValue)(name, value);
91
- let headers = this[exports.kOutHeaders];
92
- if (headers == null)
93
- this[exports.kOutHeaders] = headers = { __proto__: null };
94
- headers[name.toLowerCase()] = [name, value];
95
- return this;
96
- }
97
- setHeaders(headers) {
98
- if (this.headersSent)
99
- throw new Error(`Cannot set headers after they are sent to the client`);
100
- if (headers && typeof headers === 'object' && !Array.isArray(headers)) {
101
- const entries = typeof headers.entries === 'function' ? headers.entries() : Object.entries(headers);
102
- for (const entry of entries) {
103
- this.setHeader(entry[0], entry[1]);
104
- }
105
- return this;
106
- }
107
- throw new TypeError('Invalid "headers" argument. Value must be an instance of "Headers" or "Map"');
108
- }
109
- getHeader(name) {
110
- (0, common_js_1.validateString)(name);
111
- const headers = this[exports.kOutHeaders];
112
- if (headers == null)
113
- return;
114
- const entry = headers[name.toLowerCase()];
115
- return entry && entry[1];
116
- }
117
- getHeaderNames() {
118
- return this[exports.kOutHeaders] != null ? Object.keys(this[exports.kOutHeaders]) : [];
119
- }
120
- getRawHeaderNames() {
121
- const headersMap = this[exports.kOutHeaders];
122
- if (!headersMap)
123
- return [];
124
- const values = Object.values(headersMap);
125
- const headers = Array(values.length);
126
- for (let i = 0, l = values.length; i < l; i++) {
127
- headers[i] = values[i][0];
128
- }
129
- return headers;
130
- }
131
- getHeaders() {
132
- const headers = this[exports.kOutHeaders];
133
- // @ts-ignore
134
- const ret = { __proto__: null };
135
- if (headers) {
136
- const keys = Object.keys(headers);
137
- let key;
138
- let val;
139
- for (let i = 0; i < keys.length; ++i) {
140
- key = keys[i];
141
- val = headers[key][1];
142
- ret[key] = val;
143
- }
144
- }
145
- return ret;
146
- }
147
- hasHeader(name) {
148
- (0, common_js_1.validateString)(name);
149
- return this[exports.kOutHeaders] != null && !!this[exports.kOutHeaders][name.toLowerCase()];
150
- }
151
- removeHeader(name) {
152
- (0, common_js_1.validateString)(name);
153
- if (this.headersSent)
154
- throw new Error(`Cannot remove headers after they are sent to the client`);
155
- const key = name.toLowerCase();
156
- // switch (key) {
157
- // case 'connection':
158
- // this._removedConnection = true;
159
- // break;
160
- // case 'content-length':
161
- // this._removedContLen = true;
162
- // break;
163
- // case 'transfer-encoding':
164
- // this._removedTE = true;
165
- // break;
166
- // case 'date':
167
- // this.sendDate = false;
168
- // break;
169
- // }
170
- if (this[exports.kOutHeaders] != null) {
171
- delete this[exports.kOutHeaders][key];
172
- }
173
- }
174
- // eslint-disable-next-line @typescript-eslint/no-unused-vars
175
- end(arg0, arg1, arg2) {
176
- // let cb: (() => void) | undefined;
177
- // let chunk: any;
178
- // let encoding: BufferEncoding | undefined;
179
- //
180
- // if (typeof arg0 === 'function')
181
- // cb = arg0;
182
- // else {
183
- // chunk = arg0;
184
- // if (typeof arg1 === 'function')
185
- // cb = arg1;
186
- // else {
187
- // encoding = arg1;
188
- // cb = arg2;
189
- // }
190
- // }
191
- //
192
- return this;
193
- }
194
- }
195
- exports.NodeOutgoingMessageHost = NodeOutgoingMessageHost;
@@ -1,25 +0,0 @@
1
- "use strict";
2
- Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.HttpIncoming = void 0;
4
- const common_1 = require("@opra/common");
5
- const type_guards_js_1 = require("../../type-guards.js");
6
- const http_incoming_host_js_1 = require("../impl/http-incoming.host.js");
7
- const node_incoming_message_interface_js_1 = require("./node-incoming-message.interface.js");
8
- /**
9
- * @namespace HttpIncoming
10
- */
11
- var HttpIncoming;
12
- (function (HttpIncoming) {
13
- function from(instance) {
14
- if ((0, type_guards_js_1.isHttpIncoming)(instance))
15
- return instance;
16
- if (!(0, type_guards_js_1.isNodeIncomingMessage)(instance))
17
- instance = node_incoming_message_interface_js_1.NodeIncomingMessage.from(instance);
18
- (0, common_1.mergePrototype)(instance, http_incoming_host_js_1.HttpIncomingHost.prototype);
19
- const req = instance;
20
- req.baseUrl = req.baseUrl || '';
21
- req.params = req.params || {};
22
- return req;
23
- }
24
- HttpIncoming.from = from;
25
- })(HttpIncoming || (exports.HttpIncoming = HttpIncoming = {}));
@@ -1,22 +0,0 @@
1
- "use strict";
2
- Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.HttpOutgoing = void 0;
4
- const common_1 = require("@opra/common");
5
- const type_guards_js_1 = require("../../type-guards.js");
6
- const http_outgoing_host_js_1 = require("../impl/http-outgoing.host.js");
7
- const node_outgoing_message_interface_js_1 = require("./node-outgoing-message.interface.js");
8
- /**
9
- * @namespace HttpIncoming
10
- */
11
- var HttpOutgoing;
12
- (function (HttpOutgoing) {
13
- function from(instance) {
14
- if ((0, type_guards_js_1.isHttpOutgoing)(instance))
15
- return instance;
16
- if (!(0, type_guards_js_1.isNodeOutgoingMessage)(instance))
17
- instance = node_outgoing_message_interface_js_1.NodeOutgoingMessage.from(instance);
18
- (0, common_1.mergePrototype)(instance, http_outgoing_host_js_1.HttpOutgoingHost.prototype);
19
- return instance;
20
- }
21
- HttpOutgoing.from = from;
22
- })(HttpOutgoing || (exports.HttpOutgoing = HttpOutgoing = {}));
@@ -1,64 +0,0 @@
1
- "use strict";
2
- Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.NodeIncomingMessage = void 0;
4
- const http_parser_1 = require("@browsery/http-parser");
5
- const common_1 = require("@opra/common");
6
- const stream_1 = require("stream");
7
- const node_incoming_message_host_js_1 = require("../impl/node-incoming-message.host.js");
8
- const concat_readable_js_1 = require("../utils/concat-readable.js");
9
- /**
10
- *
11
- * @namespace NodeIncomingMessage
12
- */
13
- var NodeIncomingMessage;
14
- (function (NodeIncomingMessage) {
15
- /**
16
- * Creates a new NodeIncomingMessage from given argument
17
- * @param iterable
18
- */
19
- function from(iterable) {
20
- if (typeof iterable === 'object' && !((0, common_1.isIterable)(iterable) || (0, common_1.isAsyncIterable)(iterable))) {
21
- return new node_incoming_message_host_js_1.NodeIncomingMessageHost(iterable);
22
- }
23
- const msg = new node_incoming_message_host_js_1.NodeIncomingMessageHost();
24
- const parser = (msg[node_incoming_message_host_js_1.kHttpParser] = new http_parser_1.HTTPParser(http_parser_1.HTTPParser.REQUEST));
25
- let bodyChunks;
26
- parser[http_parser_1.HTTPParser.kOnHeadersComplete] = (info) => {
27
- msg.httpVersionMajor = info.versionMajor;
28
- msg.httpVersionMinor = info.versionMinor;
29
- msg.rawHeaders = info.headers;
30
- msg.method = http_parser_1.HTTPParser.methods[info.method];
31
- msg.url = info.url;
32
- msg.emit('headers');
33
- };
34
- parser[http_parser_1.HTTPParser.kOnHeaders] = (trailers) => {
35
- msg.rawTrailers = trailers;
36
- };
37
- parser[http_parser_1.HTTPParser.kOnBody] = (chunk, offset, length) => {
38
- bodyChunks = bodyChunks || [];
39
- bodyChunks.push(chunk.subarray(offset, offset + length));
40
- };
41
- const readable = (0, concat_readable_js_1.concatReadable)(stream_1.Readable.from(iterable), stream_1.Readable.from(node_incoming_message_host_js_1.CRLF));
42
- msg.once('finish', () => {
43
- parser.finish();
44
- msg.complete = true;
45
- if (bodyChunks)
46
- msg.body = Buffer.concat(bodyChunks);
47
- });
48
- readable.pipe(msg);
49
- return msg;
50
- }
51
- NodeIncomingMessage.from = from;
52
- /**
53
- * Creates a new NodeIncomingMessage from given argument
54
- * @param iterable
55
- */
56
- async function fromAsync(iterable) {
57
- return new Promise((resolve, reject) => {
58
- const msg = from(iterable);
59
- msg.once('finish', () => resolve(msg));
60
- msg.once('error', error => reject(error));
61
- });
62
- }
63
- NodeIncomingMessage.fromAsync = fromAsync;
64
- })(NodeIncomingMessage || (exports.NodeIncomingMessage = NodeIncomingMessage = {}));
@@ -1,15 +0,0 @@
1
- "use strict";
2
- Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.NodeOutgoingMessage = void 0;
4
- const node_outgoing_message_host_js_1 = require("../impl/node-outgoing-message.host.js");
5
- /**
6
- *
7
- * @namespace NodeOutgoingMessage
8
- */
9
- var NodeOutgoingMessage;
10
- (function (NodeOutgoingMessage) {
11
- function from(init) {
12
- return new node_outgoing_message_host_js_1.NodeOutgoingMessageHost(init);
13
- }
14
- NodeOutgoingMessage.from = from;
15
- })(NodeOutgoingMessage || (exports.NodeOutgoingMessage = NodeOutgoingMessage = {}));
@@ -1,216 +0,0 @@
1
- "use strict";
2
- Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.BodyReader = void 0;
4
- const tslib_1 = require("tslib");
5
- const type_is_1 = tslib_1.__importDefault(require("@browsery/type-is"));
6
- const common_1 = require("@opra/common");
7
- const base64_stream_1 = require("base64-stream");
8
- const bytes_1 = tslib_1.__importDefault(require("bytes"));
9
- const content_type_1 = require("content-type");
10
- const events_1 = require("events");
11
- const iconv_lite_1 = tslib_1.__importDefault(require("iconv-lite"));
12
- const stream_1 = require("stream");
13
- const zlib = tslib_1.__importStar(require("zlib"));
14
- /**
15
- *
16
- * @class BodyReader
17
- */
18
- class BodyReader extends events_1.EventEmitter {
19
- constructor(req, options) {
20
- super();
21
- this.req = req;
22
- this._completed = false;
23
- this._receivedSize = 0;
24
- this.onAborted = () => this._onAborted();
25
- this.onData = (chunk) => this._onData(chunk);
26
- this.onEnd = (err) => this._onEnd(err);
27
- this.cleanup = () => this._cleanup();
28
- this.limit = options?.limit
29
- ? typeof options.limit === 'number'
30
- ? options.limit
31
- : (0, bytes_1.default)(options.limit)
32
- : undefined;
33
- }
34
- async read() {
35
- /* istanbul ignore next */
36
- if (this._completed) {
37
- throw new common_1.InternalServerError({
38
- message: 'Stream already read',
39
- code: 'STREAM_ALREADY_READ',
40
- });
41
- }
42
- if (!this.req.readable) {
43
- throw new common_1.InternalServerError({
44
- message: 'Stream is not readable',
45
- code: 'STREAM_NOT_READABLE',
46
- });
47
- }
48
- return new Promise((resolve, reject) => {
49
- // eslint-disable-next-line prefer-const
50
- let sizeStream;
51
- this.once('finish', (error, data) => {
52
- if (sizeStream)
53
- this.req.unpipe(sizeStream);
54
- if (error)
55
- return reject(error);
56
- resolve(data);
57
- });
58
- /**
59
- * Check if a request has a request body.
60
- * A request with a body __must__ either have `transfer-encoding`
61
- * or `content-length` headers set.
62
- * http://www.w3.org/Protocols/rfc2616/rfc2616-sec4.html#sec4.3
63
- */
64
- const contentLength = parseInt(this.req.headers['content-length'] || '0', 10);
65
- if (this.req.headers['transfer-encoding'] === undefined && !(contentLength && !isNaN(contentLength))) {
66
- return this.onEnd();
67
- }
68
- // check the length and limit options.
69
- // note: we intentionally leave the stream paused,
70
- // so users should handle the stream themselves.
71
- if (this.limit != null && contentLength != null && contentLength > this.limit) {
72
- return this.onEnd(new common_1.OpraHttpError({
73
- message: 'Content Too Large',
74
- code: 'HTTP.CONTENT_TOO_LARGE',
75
- details: {
76
- length: contentLength,
77
- limit: this.limit,
78
- },
79
- }, 413));
80
- }
81
- // Pipe to a Writable stream to count received bytes
82
- const _this = this;
83
- sizeStream = new stream_1.Writable({
84
- write(chunk, encoding, callback) {
85
- if (_this._completed)
86
- return;
87
- _this._receivedSize += chunk.length;
88
- if (_this.limit != null && _this._receivedSize > _this.limit) {
89
- callback(new common_1.OpraHttpError({
90
- message: 'Content Too Large',
91
- code: 'HTTP.CONTENT_TOO_LARGE',
92
- details: {
93
- limit: _this.limit,
94
- received: _this._receivedSize,
95
- },
96
- }, 413));
97
- }
98
- },
99
- });
100
- this.req.pipe(sizeStream);
101
- let stream = BodyReader.encoderPipeline(this.req);
102
- const mediaType = (0, content_type_1.parse)(this.req.headers['content-type'] || '');
103
- let charset = (mediaType.parameters.charset || '').toLowerCase();
104
- if (!charset && type_is_1.default.is(mediaType.type, ['json', 'xml', 'txt']))
105
- charset = 'utf-8';
106
- if (charset) {
107
- const newStream = iconv_lite_1.default.decodeStream(charset);
108
- stream.pipe(newStream);
109
- stream = newStream;
110
- }
111
- this._stream = stream;
112
- // attach listeners
113
- stream.on('aborted', this.onAborted);
114
- stream.on('close', this.cleanup);
115
- stream.on('data', this.onData);
116
- stream.on('end', this.onEnd);
117
- stream.on('error', this.onEnd);
118
- });
119
- }
120
- _onEnd(error) {
121
- if (this._completed)
122
- return;
123
- this._completed = true;
124
- if (error) {
125
- this._stream?.unpipe();
126
- this._stream?.pause();
127
- }
128
- if (error)
129
- this.emit('finish', error);
130
- else if (Array.isArray(this._buffer))
131
- this.emit('finish', error, Buffer.concat(this._buffer));
132
- else
133
- this.emit('finish', error, this._buffer);
134
- this._cleanup();
135
- }
136
- _cleanup() {
137
- if (this._stream) {
138
- this._stream.removeListener('aborted', this.onAborted);
139
- this._stream.removeListener('close', this.cleanup);
140
- this._stream.removeListener('data', this.onData);
141
- this._stream.removeListener('end', this.onEnd);
142
- this._stream.removeListener('error', this.onEnd);
143
- }
144
- }
145
- _onAborted() {
146
- if (this._completed)
147
- return;
148
- this.onEnd(new common_1.BadRequestError({
149
- message: 'request aborted',
150
- code: 'ECONNABORTED',
151
- details: {
152
- received: this._receivedSize,
153
- },
154
- }));
155
- }
156
- _onData(chunk) {
157
- if (this._completed)
158
- return;
159
- if (typeof chunk === 'string') {
160
- this._buffer = this._buffer || '';
161
- this._buffer += chunk;
162
- }
163
- else {
164
- this._buffer = this._buffer || [];
165
- this._buffer.push(chunk);
166
- }
167
- }
168
- static async read(req, options) {
169
- const bodyReady = new BodyReader(req, options);
170
- return bodyReady.read();
171
- }
172
- static encoderPipeline(req) {
173
- const contentEncoding = req.headers['content-encoding'] || 'identity';
174
- const contentEncodings = (Array.isArray(contentEncoding) ? contentEncoding : contentEncoding.split(/\s*,\s*/))
175
- .map(s => s.toLowerCase())
176
- .reverse();
177
- return contentEncodings.reduce((prev, encoding) => {
178
- switch (encoding) {
179
- case 'gzip':
180
- case 'x-gzip': {
181
- const newStream = zlib.createGunzip();
182
- prev.pipe(newStream);
183
- return newStream;
184
- }
185
- case 'deflate':
186
- case 'x-deflate': {
187
- const newStream = zlib.createInflate();
188
- prev.pipe(newStream);
189
- return newStream;
190
- }
191
- case 'br': {
192
- const newStream = zlib.createBrotliDecompress();
193
- prev.pipe(newStream);
194
- return newStream;
195
- }
196
- case 'base64': {
197
- const newStream = new base64_stream_1.Base64Decode();
198
- prev.pipe(newStream);
199
- return newStream;
200
- }
201
- case 'identity':
202
- // prev.length = 0;
203
- return prev;
204
- default:
205
- throw new common_1.BadRequestError({
206
- message: 'unsupported content encoding "' + encoding + '"',
207
- code: '',
208
- details: {
209
- encoding,
210
- },
211
- }, 415);
212
- }
213
- }, req);
214
- }
215
- }
216
- exports.BodyReader = BodyReader;
@@ -1,67 +0,0 @@
1
- "use strict";
2
- /*
3
- This file contains code blocks from open source NodeJs project
4
- https://github.com/nodejs/
5
- */
6
- Object.defineProperty(exports, "__esModule", { value: true });
7
- exports.validateHeaderValue = exports.validateHeaderName = void 0;
8
- exports.checkIsHttpToken = checkIsHttpToken;
9
- exports.hideStackFrames = hideStackFrames;
10
- exports.validateString = validateString;
11
- const tokenRegExp = /^[\^_`a-zA-Z\-0-9!#$%&'*+.|~]+$/;
12
- const nodeInternalPrefix = '__node_internal_';
13
- /**
14
- * Verifies that the given val is a valid HTTP token
15
- * per the rules defined in RFC 7230
16
- * See https://tools.ietf.org/html/rfc7230#section-3.2.6
17
- *
18
- * https://github.com/nodejs/node/blob/main/lib/_http_common.js
19
- */
20
- function checkIsHttpToken(val) {
21
- return typeof val === 'string' && tokenRegExp.exec(val) !== null;
22
- }
23
- const headerCharRegex = /[^\t\x20-\x7e\x80-\xff]/;
24
- /**
25
- * True if val contains an invalid field-vchar
26
- * field-value = *( field-content / obs-fold )
27
- * field-content = field-vchar [ 1*( SP / HTAB ) field-vchar ]
28
- * field-vchar = VCHAR / obs-text
29
- *
30
- * https://github.com/nodejs/node/blob/main/lib/_http_common.js
31
- */
32
- function checkInvalidHeaderChar(val) {
33
- // noinspection SuspiciousTypeOfGuard
34
- return typeof val === 'string' && headerCharRegex.exec(val) !== null;
35
- }
36
- /**
37
- * This function removes unnecessary frames from Node.js core errors.
38
- *
39
- * https://github.com/nodejs/node/blob/main/lib/internal/errors.js
40
- */
41
- function hideStackFrames(fn) {
42
- // We rename the functions that will be hidden to cut off the stacktrace
43
- // at the outermost one
44
- const hidden = nodeInternalPrefix + fn.name;
45
- // @ts-ignore
46
- Object.defineProperty(fn, 'name', { __proto__: null, value: hidden });
47
- return fn;
48
- }
49
- exports.validateHeaderName = hideStackFrames((name, label) => {
50
- // noinspection SuspiciousTypeOfGuard
51
- if (typeof name !== 'string' || !name || !checkIsHttpToken(name)) {
52
- throw new TypeError(`${label || 'Header name'} must be a valid HTTP token ["${name}"]`);
53
- }
54
- });
55
- exports.validateHeaderValue = hideStackFrames((name, value) => {
56
- if (value === undefined) {
57
- throw new TypeError(`Invalid value "${value}" for header "${name}"`);
58
- }
59
- if (checkInvalidHeaderChar(value)) {
60
- throw new TypeError(`Invalid character in header content ["${name}"]`);
61
- }
62
- });
63
- function validateString(value, name) {
64
- if (typeof value !== 'string') {
65
- throw new TypeError(`Invalid ${name ? name + ' ' : ''}argument. Value must be a string`);
66
- }
67
- }
@@ -1,19 +0,0 @@
1
- "use strict";
2
- Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.concatReadable = concatReadable;
4
- const stream_1 = require("stream");
5
- function concatReadable(...streams) {
6
- const out = new stream_1.PassThrough();
7
- const pipeNext = () => {
8
- const nextStream = streams.shift();
9
- if (nextStream) {
10
- nextStream.pipe(out, { end: false });
11
- nextStream.once('end', () => pipeNext());
12
- }
13
- else {
14
- out.end();
15
- }
16
- };
17
- pipeNext();
18
- return out;
19
- }