@opra/core 0.33.13 → 1.0.0-alpha.10

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 (155) hide show
  1. package/cjs/augmentation/18n.augmentation.js +18 -5
  2. package/cjs/augmentation/http-controller.augmentation.js +25 -0
  3. package/cjs/constants.js +5 -0
  4. package/cjs/execution-context.js +24 -12
  5. package/cjs/{services → helpers}/logger.js +1 -2
  6. package/cjs/{services/api-service.js → helpers/service-base.js} +8 -8
  7. package/cjs/http/express-adapter.js +153 -0
  8. package/cjs/http/http-adapter.js +27 -0
  9. package/cjs/http/http-context.js +119 -0
  10. package/cjs/http/impl/asset-cache.js +21 -0
  11. package/cjs/http/impl/http-handler.js +584 -0
  12. package/cjs/http/{http-server-request.js → impl/http-incoming.host.js} +24 -49
  13. package/cjs/http/{http-server-response.js → impl/http-outgoing.host.js} +9 -28
  14. package/cjs/http/{helpers/multipart-helper.js → impl/multipart-reader.js} +23 -27
  15. package/cjs/http/impl/{http-incoming-message.host.js → node-incoming-message.host.js} +18 -57
  16. package/cjs/http/impl/{http-outgoing-message.host.js → node-outgoing-message.host.js} +11 -14
  17. package/cjs/http/interfaces/http-incoming.interface.js +25 -0
  18. package/cjs/http/interfaces/http-outgoing.interface.js +22 -0
  19. package/cjs/http/interfaces/node-incoming-message.interface.js +64 -0
  20. package/cjs/http/interfaces/node-outgoing-message.interface.js +15 -0
  21. package/cjs/http/utils/body-reader.js +217 -0
  22. package/cjs/http/{helpers → utils}/common.js +2 -1
  23. package/cjs/http/{helpers → utils}/convert-to-raw-headers.js +1 -2
  24. package/cjs/http/{helpers → utils}/match-known-fields.js +11 -9
  25. package/cjs/http/utils/wrap-exception.js +34 -0
  26. package/cjs/index.js +26 -26
  27. package/cjs/platform-adapter.js +21 -0
  28. package/cjs/type-guards.js +23 -0
  29. package/esm/augmentation/18n.augmentation.js +20 -7
  30. package/esm/augmentation/http-controller.augmentation.js +23 -0
  31. package/esm/constants.js +2 -0
  32. package/esm/execution-context.js +24 -13
  33. package/esm/{services → helpers}/logger.js +1 -2
  34. package/esm/{services/api-service.js → helpers/service-base.js} +6 -6
  35. package/esm/http/express-adapter.js +148 -0
  36. package/esm/http/http-adapter.js +23 -0
  37. package/esm/http/http-context.js +114 -0
  38. package/esm/http/impl/asset-cache.js +17 -0
  39. package/esm/http/impl/http-handler.js +579 -0
  40. package/esm/http/{http-server-request.js → impl/http-incoming.host.js} +20 -46
  41. package/esm/http/{http-server-response.js → impl/http-outgoing.host.js} +7 -27
  42. package/esm/http/{helpers/multipart-helper.js → impl/multipart-reader.js} +21 -25
  43. package/esm/http/impl/{http-incoming-message.host.js → node-incoming-message.host.js} +16 -55
  44. package/esm/http/impl/{http-outgoing-message.host.js → node-outgoing-message.host.js} +9 -12
  45. package/esm/http/interfaces/http-incoming.interface.js +22 -0
  46. package/esm/http/interfaces/http-outgoing.interface.js +19 -0
  47. package/esm/http/interfaces/node-incoming-message.interface.js +61 -0
  48. package/esm/http/interfaces/node-outgoing-message.interface.js +12 -0
  49. package/esm/http/utils/body-reader.js +212 -0
  50. package/esm/http/{helpers → utils}/common.js +2 -1
  51. package/esm/http/{helpers → utils}/convert-to-headers.js +1 -1
  52. package/esm/http/{helpers → utils}/convert-to-raw-headers.js +2 -3
  53. package/esm/http/{helpers → utils}/match-known-fields.js +11 -9
  54. package/esm/http/utils/wrap-exception.js +30 -0
  55. package/esm/index.js +26 -27
  56. package/esm/platform-adapter.js +19 -1
  57. package/esm/type-guards.js +16 -0
  58. package/package.json +31 -13
  59. package/types/augmentation/18n.augmentation.d.ts +31 -1
  60. package/types/augmentation/http-controller.augmentation.d.ts +21 -0
  61. package/types/constants.d.ts +2 -0
  62. package/types/execution-context.d.ts +22 -26
  63. package/types/helpers/service-base.d.ts +10 -0
  64. package/types/http/express-adapter.d.ts +13 -0
  65. package/types/http/http-adapter.d.ts +27 -0
  66. package/types/http/http-context.d.ts +44 -0
  67. package/types/http/impl/asset-cache.d.ts +5 -0
  68. package/types/http/impl/http-handler.d.ts +73 -0
  69. package/types/http/impl/http-incoming.host.d.ts +23 -0
  70. package/types/http/impl/http-outgoing.host.d.ts +17 -0
  71. package/types/http/{helpers/multipart-helper.d.ts → impl/multipart-reader.d.ts} +8 -6
  72. package/types/http/impl/{http-incoming-message.host.d.ts → node-incoming-message.host.d.ts} +10 -23
  73. package/types/http/impl/{http-outgoing-message.host.d.ts → node-outgoing-message.host.d.ts} +11 -27
  74. package/types/http/{http-server-request.d.ts → interfaces/http-incoming.interface.d.ts} +28 -17
  75. package/types/http/{http-server-response.d.ts → interfaces/http-outgoing.interface.d.ts} +17 -10
  76. package/types/http/interfaces/node-incoming-message.interface.d.ts +38 -0
  77. package/types/http/interfaces/node-outgoing-message.interface.d.ts +29 -0
  78. package/types/http/utils/body-reader.d.ts +41 -0
  79. package/types/http/utils/wrap-exception.d.ts +2 -0
  80. package/types/index.d.ts +25 -27
  81. package/types/platform-adapter.d.ts +20 -48
  82. package/types/type-guards.d.ts +8 -0
  83. package/cjs/augmentation/collection.augmentation.js +0 -2
  84. package/cjs/augmentation/container.augmentation.js +0 -2
  85. package/cjs/augmentation/resource.augmentation.js +0 -26
  86. package/cjs/augmentation/singleton.augmentation.js +0 -2
  87. package/cjs/augmentation/storage.augmentation.js +0 -2
  88. package/cjs/execution-context.host.js +0 -46
  89. package/cjs/http/adapters/express-adapter.host.js +0 -34
  90. package/cjs/http/adapters/express-adapter.js +0 -14
  91. package/cjs/http/adapters/node-http-adapter.host.js +0 -70
  92. package/cjs/http/adapters/node-http-adapter.js +0 -14
  93. package/cjs/http/helpers/json-body-loader.js +0 -29
  94. package/cjs/http/helpers/query-parsers.js +0 -16
  95. package/cjs/http/http-adapter-host.js +0 -715
  96. package/cjs/interfaces/interceptor.interface.js +0 -2
  97. package/cjs/interfaces/request-handler.interface.js +0 -2
  98. package/cjs/platform-adapter.host.js +0 -154
  99. package/cjs/request-context.js +0 -25
  100. package/cjs/request.host.js +0 -24
  101. package/cjs/request.js +0 -2
  102. package/cjs/response.host.js +0 -22
  103. package/cjs/response.js +0 -2
  104. package/esm/augmentation/collection.augmentation.js +0 -1
  105. package/esm/augmentation/container.augmentation.js +0 -1
  106. package/esm/augmentation/resource.augmentation.js +0 -24
  107. package/esm/augmentation/singleton.augmentation.js +0 -1
  108. package/esm/augmentation/storage.augmentation.js +0 -1
  109. package/esm/execution-context.host.js +0 -42
  110. package/esm/http/adapters/express-adapter.host.js +0 -30
  111. package/esm/http/adapters/express-adapter.js +0 -11
  112. package/esm/http/adapters/node-http-adapter.host.js +0 -65
  113. package/esm/http/adapters/node-http-adapter.js +0 -11
  114. package/esm/http/helpers/json-body-loader.js +0 -24
  115. package/esm/http/helpers/query-parsers.js +0 -12
  116. package/esm/http/http-adapter-host.js +0 -710
  117. package/esm/interfaces/interceptor.interface.js +0 -1
  118. package/esm/interfaces/request-handler.interface.js +0 -1
  119. package/esm/platform-adapter.host.js +0 -149
  120. package/esm/request-context.js +0 -22
  121. package/esm/request.host.js +0 -20
  122. package/esm/request.js +0 -1
  123. package/esm/response.host.js +0 -18
  124. package/esm/response.js +0 -1
  125. package/types/augmentation/collection.augmentation.d.ts +0 -146
  126. package/types/augmentation/container.augmentation.d.ts +0 -14
  127. package/types/augmentation/resource.augmentation.d.ts +0 -38
  128. package/types/augmentation/singleton.augmentation.d.ts +0 -83
  129. package/types/augmentation/storage.augmentation.d.ts +0 -50
  130. package/types/execution-context.host.d.ts +0 -25
  131. package/types/http/adapters/express-adapter.d.ts +0 -15
  132. package/types/http/adapters/express-adapter.host.d.ts +0 -12
  133. package/types/http/adapters/node-http-adapter.d.ts +0 -17
  134. package/types/http/adapters/node-http-adapter.host.d.ts +0 -19
  135. package/types/http/helpers/json-body-loader.d.ts +0 -5
  136. package/types/http/helpers/query-parsers.d.ts +0 -1
  137. package/types/http/http-adapter-host.d.ts +0 -34
  138. package/types/interfaces/interceptor.interface.d.ts +0 -2
  139. package/types/interfaces/request-handler.interface.d.ts +0 -4
  140. package/types/platform-adapter.host.d.ts +0 -43
  141. package/types/request-context.d.ts +0 -13
  142. package/types/request.d.ts +0 -14
  143. package/types/request.host.d.ts +0 -27
  144. package/types/response.d.ts +0 -22
  145. package/types/response.host.d.ts +0 -22
  146. package/types/services/api-service.d.ts +0 -10
  147. /package/cjs/http/{helpers → utils}/concat-readable.js +0 -0
  148. /package/cjs/http/{helpers → utils}/convert-to-headers.js +0 -0
  149. /package/esm/http/{helpers → utils}/concat-readable.js +0 -0
  150. /package/types/{services → helpers}/logger.d.ts +0 -0
  151. /package/types/http/{helpers → utils}/common.d.ts +0 -0
  152. /package/types/http/{helpers → utils}/concat-readable.d.ts +0 -0
  153. /package/types/http/{helpers → utils}/convert-to-headers.d.ts +0 -0
  154. /package/types/http/{helpers → utils}/convert-to-raw-headers.d.ts +0 -0
  155. /package/types/http/{helpers → utils}/match-known-fields.d.ts +0 -0
@@ -0,0 +1,579 @@
1
+ import * as process from 'node:process';
2
+ import typeIs from '@browsery/type-is';
3
+ import { BadRequestError, HttpHeaderCodes, HttpStatusCode, InternalServerError, isBlob, isReadableStream, IssueSeverity, MethodNotAllowedError, MimeTypes, OperationResult, OpraException, OpraSchema, translate, } from '@opra/common';
4
+ import { parse as parseContentType } from 'content-type';
5
+ import { splitString } from 'fast-tokenizer';
6
+ import { asMutable } from 'ts-gems';
7
+ import { toArray, ValidationError, vg } from 'valgen';
8
+ import { kAssetCache } from '../../constants.js';
9
+ import { wrapException } from '../utils/wrap-exception.js';
10
+ /**
11
+ * @class HttpHandler
12
+ */
13
+ export class HttpHandler {
14
+ constructor(adapter) {
15
+ this.adapter = adapter;
16
+ this[kAssetCache] = adapter[kAssetCache];
17
+ }
18
+ /**
19
+ * Main http request handler
20
+ * @param context
21
+ * @protected
22
+ */
23
+ async handleRequest(context) {
24
+ const { response } = context;
25
+ try {
26
+ response.setHeader(HttpHeaderCodes.X_Opra_Version, OpraSchema.SpecVersion);
27
+ // Expose headers if cors enabled
28
+ if (response.getHeader(HttpHeaderCodes.Access_Control_Allow_Origin)) {
29
+ // Expose X-Opra-* headers
30
+ response.appendHeader(HttpHeaderCodes.Access_Control_Expose_Headers, Object.values(HttpHeaderCodes).filter(k => k.toLowerCase().startsWith('x-opra-')));
31
+ }
32
+ // Parse request
33
+ try {
34
+ await this.parseRequest(context);
35
+ }
36
+ catch (e) {
37
+ if (e instanceof OpraException)
38
+ throw e;
39
+ if (e instanceof ValidationError) {
40
+ throw new BadRequestError({
41
+ message: translate('error:RESPONSE_VALIDATION,', 'Response validation failed'),
42
+ code: 'RESPONSE_VALIDATION',
43
+ details: e.issues,
44
+ }, e);
45
+ }
46
+ throw new BadRequestError(e);
47
+ }
48
+ await this.adapter.emitAsync('request', context);
49
+ // Call interceptors than execute request
50
+ if (this.adapter.interceptors) {
51
+ let i = 0;
52
+ const next = async () => {
53
+ const interceptor = this.adapter.interceptors[i++];
54
+ if (interceptor)
55
+ await interceptor(context, next);
56
+ await this._executeRequest(context);
57
+ };
58
+ await next();
59
+ }
60
+ else
61
+ await this._executeRequest(context);
62
+ }
63
+ catch (error) {
64
+ let e = error;
65
+ if (e instanceof ValidationError) {
66
+ e = new InternalServerError({
67
+ message: translate('error:RESPONSE_VALIDATION,', 'Response validation failed'),
68
+ code: 'RESPONSE_VALIDATION',
69
+ details: e.issues,
70
+ }, e);
71
+ }
72
+ else
73
+ e = wrapException(e);
74
+ response.status(e.statusCode || e.status || HttpStatusCode.INTERNAL_SERVER_ERROR);
75
+ response.contentType(MimeTypes.opra_response_json);
76
+ await this._sendResponse(context, new OperationResult({ errors: [e.toJSON()] })).finally(() => {
77
+ if (!response.finished)
78
+ response.end();
79
+ });
80
+ }
81
+ finally {
82
+ await context.emitAsync('finish');
83
+ }
84
+ }
85
+ /**
86
+ *
87
+ * @param context
88
+ */
89
+ async parseRequest(context) {
90
+ await this._parseParameters(context);
91
+ await this._parseContentType(context);
92
+ if (context.operation.requestBody?.immediateFetch)
93
+ await context.getBody();
94
+ /** Set default status code as the first status code between 200 and 299 */
95
+ if (context.operation) {
96
+ for (const r of context.operation.responses) {
97
+ const st = r.statusCode.find(sc => sc.start <= 299 && sc.end >= 200);
98
+ if (st) {
99
+ context.response.status(st.start);
100
+ break;
101
+ }
102
+ }
103
+ }
104
+ }
105
+ /**
106
+ *
107
+ * @param context
108
+ * @protected
109
+ */
110
+ async _parseParameters(context) {
111
+ const { operation, request } = context;
112
+ let key = '';
113
+ try {
114
+ const onFail = (issue) => {
115
+ issue.location = key;
116
+ return issue;
117
+ };
118
+ /** prepare decoders */
119
+ const getDecoder = (prm) => {
120
+ let decode = this[kAssetCache].get(prm, 'decode');
121
+ if (!decode) {
122
+ decode = prm.type?.generateCodec('decode', { ignoreReadonlyFields: true }) || vg.isAny();
123
+ this[kAssetCache].set(prm, 'decode', decode);
124
+ }
125
+ return decode;
126
+ };
127
+ const paramsLeft = new Set([...operation.parameters, ...operation.owner.parameters]);
128
+ /** parse cookie parameters */
129
+ if (request.cookies) {
130
+ for (key of Object.keys(request.cookies)) {
131
+ const oprPrm = operation.findParameter(key, 'cookie');
132
+ const cntPrm = operation.owner.findParameter(key, 'cookie');
133
+ const prm = oprPrm || cntPrm;
134
+ if (!prm)
135
+ continue;
136
+ if (oprPrm)
137
+ paramsLeft.delete(oprPrm);
138
+ if (cntPrm)
139
+ paramsLeft.delete(cntPrm);
140
+ const decode = getDecoder(prm);
141
+ const v = decode(request.cookies[key], { coerce: true, label: key, onFail });
142
+ const prmName = typeof prm.name === 'string' ? prm.name : key;
143
+ if (v !== undefined)
144
+ context.cookies[prmName] = v;
145
+ }
146
+ }
147
+ /** parse headers */
148
+ if (request.headers) {
149
+ for (key of Object.keys(request.headers)) {
150
+ const oprPrm = operation.findParameter(key, 'header');
151
+ const cntPrm = operation.owner.findParameter(key, 'header');
152
+ const prm = oprPrm || cntPrm;
153
+ if (!prm)
154
+ continue;
155
+ if (oprPrm)
156
+ paramsLeft.delete(oprPrm);
157
+ if (cntPrm)
158
+ paramsLeft.delete(cntPrm);
159
+ const decode = getDecoder(prm);
160
+ const v = decode(request.headers[key], { coerce: true, label: key, onFail });
161
+ const prmName = typeof prm.name === 'string' ? prm.name : key;
162
+ if (v !== undefined)
163
+ context.headers[prmName] = v;
164
+ }
165
+ }
166
+ /** parse path parameters */
167
+ if (request.params) {
168
+ for (key of Object.keys(request.params)) {
169
+ const oprPrm = operation.findParameter(key, 'path');
170
+ const cntPrm = operation.owner.findParameter(key, 'path');
171
+ const prm = oprPrm || cntPrm;
172
+ if (!prm)
173
+ continue;
174
+ if (oprPrm)
175
+ paramsLeft.delete(oprPrm);
176
+ if (cntPrm)
177
+ paramsLeft.delete(cntPrm);
178
+ const decode = getDecoder(prm);
179
+ const v = decode(request.params[key], { coerce: true, label: key, onFail });
180
+ if (v !== undefined)
181
+ context.pathParams[key] = v;
182
+ }
183
+ }
184
+ /** parse query parameters */
185
+ const url = new URL(request.originalUrl || request.url || '/', 'http://tempuri.org');
186
+ const { searchParams } = url;
187
+ for (key of searchParams.keys()) {
188
+ const oprPrm = operation.findParameter(key, 'query');
189
+ const cntPrm = operation.owner.findParameter(key, 'query');
190
+ const prm = oprPrm || cntPrm;
191
+ if (!prm)
192
+ continue;
193
+ if (oprPrm)
194
+ paramsLeft.delete(oprPrm);
195
+ if (cntPrm)
196
+ paramsLeft.delete(cntPrm);
197
+ const decode = getDecoder(prm);
198
+ let values = searchParams?.getAll(key);
199
+ const prmName = typeof prm.name === 'string' ? prm.name : key;
200
+ if (values?.length && prm.isArray) {
201
+ values = values.map(v => splitString(v, { delimiters: prm.arraySeparator, quotes: true })).flat();
202
+ values = values.map(v => decode(v, { coerce: true, label: key, onFail }));
203
+ if (values.length)
204
+ context.queryParams[prmName] = values;
205
+ }
206
+ else {
207
+ const v = decode(values[0], { coerce: true, label: key, onFail });
208
+ if (values.length)
209
+ context.queryParams[prmName] = v;
210
+ }
211
+ }
212
+ for (const prm of paramsLeft) {
213
+ // Throw error for required parameters
214
+ if (prm.required) {
215
+ const decode = getDecoder(prm);
216
+ decode(undefined, { coerce: true, label: String(prm.name), onFail });
217
+ }
218
+ }
219
+ }
220
+ catch (e) {
221
+ if (e instanceof ValidationError) {
222
+ throw new BadRequestError({
223
+ message: `Invalid parameter (${key}) value. ` + e.message,
224
+ code: 'REQUEST_VALIDATION',
225
+ details: e.issues,
226
+ }, e);
227
+ }
228
+ throw e;
229
+ }
230
+ }
231
+ /**
232
+ *
233
+ * @param context
234
+ * @protected
235
+ */
236
+ async _parseContentType(context) {
237
+ const { request, operation } = context;
238
+ if (operation.requestBody?.content.length) {
239
+ let mediaType;
240
+ let contentType = request.header('content-type');
241
+ if (contentType) {
242
+ contentType = parseContentType(contentType).type;
243
+ mediaType = operation.requestBody.content.find(mc => mc.contentType &&
244
+ typeIs.is(contentType, Array.isArray(mc.contentType) ? mc.contentType : [mc.contentType]));
245
+ }
246
+ if (!mediaType) {
247
+ const contentTypes = operation.requestBody.content.map(mc => mc.contentType).flat();
248
+ throw new BadRequestError(`Request body should be one of required content types (${contentTypes.join(', ')})`);
249
+ }
250
+ asMutable(context).mediaType = mediaType;
251
+ }
252
+ }
253
+ /**
254
+ *
255
+ * @param context
256
+ * @protected
257
+ */
258
+ async _executeRequest(context) {
259
+ if (!context.operationHandler)
260
+ throw new MethodNotAllowedError();
261
+ const responseValue = await context.operationHandler.call(context.controllerInstance, context);
262
+ const { response } = context;
263
+ if (!response.writableEnded) {
264
+ await this._sendResponse(context, responseValue).finally(() => {
265
+ if (!response.writableEnded)
266
+ response.end();
267
+ });
268
+ }
269
+ }
270
+ /**
271
+ *
272
+ * @param context
273
+ * @param responseValue
274
+ * @protected
275
+ */
276
+ async _sendResponse(context, responseValue) {
277
+ const { response } = context;
278
+ const { document } = this.adapter;
279
+ const responseArgs = this._determineResponseArgs(context, responseValue);
280
+ const { operationResponse, statusCode } = responseArgs;
281
+ let { contentType, body } = responseArgs;
282
+ const operationResultType = document.node.getDataType(OperationResult);
283
+ let operationResultEncoder = this[kAssetCache].get(operationResultType, 'encode');
284
+ if (!operationResultEncoder) {
285
+ operationResultEncoder = operationResultType.generateCodec('encode', { ignoreWriteonlyFields: true });
286
+ this[kAssetCache].set(operationResultType, 'encode', operationResultEncoder);
287
+ }
288
+ /** Validate response */
289
+ if (operationResponse?.type) {
290
+ if (!(body == null && statusCode === HttpStatusCode.NO_CONTENT)) {
291
+ /** Generate encoder */
292
+ let encode = this[kAssetCache].get(operationResponse, 'encode');
293
+ if (!encode) {
294
+ encode = operationResponse.type.generateCodec('encode', {
295
+ partial: operationResponse.partial,
296
+ projection: '*',
297
+ ignoreWriteonlyFields: true,
298
+ });
299
+ if (operationResponse) {
300
+ if (operationResponse.isArray)
301
+ encode = vg.isArray(encode);
302
+ this[kAssetCache].set(operationResponse, 'encode', encode);
303
+ }
304
+ }
305
+ /** Encode body */
306
+ if (operationResponse.type.extendsFrom(operationResultType)) {
307
+ if (body instanceof OperationResult)
308
+ body = encode(body);
309
+ else {
310
+ body.payload = encode(body.payload);
311
+ body = operationResultEncoder(body);
312
+ }
313
+ }
314
+ else {
315
+ if (body instanceof OperationResult &&
316
+ contentType &&
317
+ typeIs.is(contentType, [MimeTypes.opra_response_json])) {
318
+ body.payload = encode(body.payload);
319
+ body = operationResultEncoder(body);
320
+ }
321
+ else
322
+ body = encode(body);
323
+ }
324
+ if (body instanceof OperationResult && operationResponse.type) {
325
+ body.type = operationResponse.type.name ? operationResponse.type.name : '#embedded';
326
+ }
327
+ }
328
+ }
329
+ else if (body != null) {
330
+ if (body instanceof OperationResult) {
331
+ body = operationResultEncoder(body);
332
+ contentType = MimeTypes.opra_response_json;
333
+ }
334
+ else if (Buffer.isBuffer(body))
335
+ contentType = MimeTypes.binary;
336
+ else if (typeof body === 'object') {
337
+ contentType = contentType || MimeTypes.json;
338
+ if (typeof body.toJSON === 'function')
339
+ body = body.toJSON();
340
+ }
341
+ else {
342
+ contentType = contentType || MimeTypes.text;
343
+ body = String(body);
344
+ }
345
+ }
346
+ /** Set content-type header value if not set */
347
+ if (contentType && contentType !== responseArgs.contentType)
348
+ response.setHeader('content-type', contentType);
349
+ response.status(statusCode);
350
+ if (body == null) {
351
+ response.end();
352
+ return;
353
+ }
354
+ let x;
355
+ if (Buffer.isBuffer(body) || isReadableStream(body))
356
+ x = body;
357
+ else if (isBlob(body))
358
+ x = body.stream();
359
+ else if (typeof body === 'object')
360
+ x = JSON.stringify(body);
361
+ else
362
+ x = String(body);
363
+ response.end(x);
364
+ }
365
+ /**
366
+ *
367
+ * @param context
368
+ * @param body
369
+ * @protected
370
+ */
371
+ _determineResponseArgs(context, body) {
372
+ const { response, operation } = context;
373
+ const hasBody = body != null;
374
+ const statusCode = !hasBody && response.statusCode === HttpStatusCode.OK ? HttpStatusCode.NO_CONTENT : response.statusCode;
375
+ /** Parse content-type header */
376
+ const parsedContentType = hasBody && response.hasHeader('content-type') ? parseContentType(response) : undefined;
377
+ let contentType = parsedContentType?.type;
378
+ /** Estimate content type if not defined */
379
+ if (hasBody && !contentType) {
380
+ if (body instanceof OperationResult)
381
+ contentType = MimeTypes.opra_response_json;
382
+ else if (Buffer.isBuffer(body))
383
+ contentType = MimeTypes.binary;
384
+ }
385
+ let operationResponse;
386
+ const cacheKey = `HttpOperationResponse:${statusCode}${contentType ? ':' + contentType : ''}`;
387
+ let responseArgs = this[kAssetCache].get(response, cacheKey);
388
+ if (!responseArgs) {
389
+ responseArgs = { statusCode, contentType };
390
+ if (operation.responses.length) {
391
+ /** Filter available HttpOperationResponse instances according to status code. */
392
+ const filteredResponses = operation.responses.filter(r => r.statusCode.find(sc => sc.start <= statusCode && sc.end >= statusCode));
393
+ /** Throw InternalServerError if controller returns non-configured status code */
394
+ if (!filteredResponses.length && statusCode < 400) {
395
+ throw new InternalServerError(`No responses defined for status code ${statusCode} in operation "${operation.name}"`);
396
+ }
397
+ /** We search for content-type in filtered HttpOperationResponse array */
398
+ if (filteredResponses.length) {
399
+ /** If no response returned, and content-type has not been set (No response wants to be returned by operation) */
400
+ if (!hasBody) {
401
+ /** Find HttpOperationResponse with no content-type */
402
+ operationResponse = filteredResponses.find(r => !r.contentType);
403
+ }
404
+ if (!operationResponse) {
405
+ /** Find HttpOperationResponse according to content-type */
406
+ if (contentType) {
407
+ // Find HttpEndpointResponse instance according to content-type header
408
+ operationResponse = filteredResponses.find(r => typeIs.is(contentType, toArray(r.contentType)));
409
+ if (!operationResponse) {
410
+ throw new InternalServerError(`Operation didn't configured to return "${contentType}" content`);
411
+ }
412
+ }
413
+ else {
414
+ /** Select first HttpOperationResponse if content-type header has not been set */
415
+ operationResponse = filteredResponses[0];
416
+ if (operationResponse.contentType) {
417
+ const ct = typeIs.normalize(Array.isArray(operationResponse.contentType)
418
+ ? operationResponse.contentType[0]
419
+ : operationResponse.contentType);
420
+ if (typeof ct === 'string')
421
+ responseArgs.contentType = contentType = ct;
422
+ }
423
+ }
424
+ }
425
+ responseArgs.operationResponse = operationResponse;
426
+ if (!operationResponse.statusCode.find(sc => sc.start <= statusCode && sc.end >= statusCode)) {
427
+ responseArgs.statusCode = operationResponse.statusCode[0].start;
428
+ }
429
+ }
430
+ }
431
+ if (!hasBody)
432
+ delete responseArgs.contentType;
433
+ this[kAssetCache].set(response, cacheKey, { ...responseArgs });
434
+ }
435
+ /** Fix response value according to composition */
436
+ const composition = operationResponse?.owner.composition;
437
+ if (composition && body != null) {
438
+ switch (composition) {
439
+ case 'Entity.Create':
440
+ case 'Entity.Get':
441
+ case 'Entity.FindMany':
442
+ case 'Entity.Update': {
443
+ if (!(body instanceof OperationResult)) {
444
+ body = new OperationResult({
445
+ payload: body,
446
+ });
447
+ }
448
+ if ((composition === 'Entity.Create' || composition === 'Entity.Update') &&
449
+ composition &&
450
+ body.affected == null) {
451
+ body.affected = 1;
452
+ }
453
+ break;
454
+ }
455
+ case 'Entity.Delete':
456
+ case 'Entity.DeleteMany':
457
+ case 'Entity.UpdateMany': {
458
+ if (!(body instanceof OperationResult)) {
459
+ body = new OperationResult({
460
+ affected: body,
461
+ });
462
+ }
463
+ body.affected =
464
+ typeof body.affected === 'number'
465
+ ? body.affected
466
+ : typeof body.affected === 'boolean'
467
+ ? body.affected
468
+ ? 1
469
+ : 0
470
+ : undefined;
471
+ break;
472
+ }
473
+ default:
474
+ break;
475
+ }
476
+ }
477
+ if (responseArgs.contentType && responseArgs.contentType !== parsedContentType?.type) {
478
+ response.setHeader('content-type', responseArgs.contentType);
479
+ }
480
+ if (responseArgs.contentType &&
481
+ body != null &&
482
+ !(body instanceof OperationResult) &&
483
+ typeIs.is(responseArgs.contentType, [MimeTypes.opra_response_json])) {
484
+ body = new OperationResult({ payload: body });
485
+ }
486
+ if (hasBody)
487
+ responseArgs.body = body;
488
+ return responseArgs;
489
+ }
490
+ async sendDocumentSchema(context) {
491
+ const { request, response } = context;
492
+ const { document } = this.adapter;
493
+ response.setHeader('content-type', MimeTypes.json);
494
+ const url = new URL(request.originalUrl || request.url || '/', 'http://tempuri.org');
495
+ const { searchParams } = url;
496
+ const documentId = searchParams.get('id');
497
+ const doc = documentId ? document.findDocument(documentId) : document;
498
+ if (!doc) {
499
+ return this.sendErrorResponse(response, [
500
+ new BadRequestError({
501
+ message: `Document with given id [${documentId}] does not exists`,
502
+ }),
503
+ ]);
504
+ }
505
+ /** Check if response cache exists */
506
+ let responseBody = this[kAssetCache].get(doc, `$schema`);
507
+ /** Create response if response cache does not exists */
508
+ if (!responseBody) {
509
+ const schema = doc.export();
510
+ responseBody = JSON.stringify(schema);
511
+ this[kAssetCache].set(doc, `$schema`, responseBody);
512
+ }
513
+ response.end(responseBody);
514
+ }
515
+ async sendErrorResponse(response, errors) {
516
+ if (response.headersSent) {
517
+ response.end();
518
+ return;
519
+ }
520
+ if (!errors.length)
521
+ errors.push(wrapException({ status: response.statusCode || 500 }));
522
+ const { logger } = this.adapter;
523
+ errors.forEach(x => {
524
+ if (x instanceof OpraException) {
525
+ switch (x.severity) {
526
+ case 'fatal':
527
+ logger.fatal(x);
528
+ break;
529
+ case 'warning':
530
+ logger.warn(x);
531
+ break;
532
+ default:
533
+ logger.error(x);
534
+ }
535
+ }
536
+ else
537
+ logger.fatal(x);
538
+ });
539
+ const wrappedErrors = errors.map(wrapException);
540
+ // Sort errors from fatal to info
541
+ wrappedErrors.sort((a, b) => {
542
+ const i = IssueSeverity.Keys.indexOf(a.severity) - IssueSeverity.Keys.indexOf(b.severity);
543
+ if (i === 0)
544
+ return b.status - a.status;
545
+ return i;
546
+ });
547
+ let status = response.statusCode || 0;
548
+ if (!status || status < Number(HttpStatusCode.BAD_REQUEST)) {
549
+ status = wrappedErrors[0].status;
550
+ if (status < Number(HttpStatusCode.BAD_REQUEST))
551
+ status = HttpStatusCode.INTERNAL_SERVER_ERROR;
552
+ }
553
+ response.statusCode = status;
554
+ const { document } = this.adapter;
555
+ const dt = document.node.getComplexType('OperationResult');
556
+ let encode = this[kAssetCache].get(dt, 'encode');
557
+ if (!encode) {
558
+ encode = dt.generateCodec('encode', { ignoreWriteonlyFields: true });
559
+ this[kAssetCache].set(dt, 'encode', encode);
560
+ }
561
+ const { i18n } = this.adapter;
562
+ const bodyObject = new OperationResult({
563
+ errors: wrappedErrors.map(x => {
564
+ const o = x.toJSON();
565
+ if (!(process.env.NODE_ENV === 'dev' || process.env.NODE_ENV === 'development'))
566
+ delete o.stack;
567
+ return i18n.deep(o);
568
+ }),
569
+ });
570
+ const body = encode(bodyObject);
571
+ response.setHeader(HttpHeaderCodes.Content_Type, MimeTypes.opra_response_json + '; charset=utf-8');
572
+ response.setHeader(HttpHeaderCodes.Cache_Control, 'no-cache');
573
+ response.setHeader(HttpHeaderCodes.Pragma, 'no-cache');
574
+ response.setHeader(HttpHeaderCodes.Expires, '-1');
575
+ response.setHeader(HttpHeaderCodes.X_Opra_Version, OpraSchema.SpecVersion);
576
+ response.send(JSON.stringify(body));
577
+ response.end();
578
+ }
579
+ }
@@ -2,44 +2,16 @@
2
2
  Some parts of this file contains codes from open source express library
3
3
  https://github.com/expressjs
4
4
  */
5
+ import typeIs from '@browsery/type-is';
5
6
  import accepts from 'accepts';
6
7
  import fresh from 'fresh';
7
8
  import parseRange from 'range-parser';
8
- import typeIs from '@browsery/type-is';
9
- import { isReadable, mergePrototype, OpraURL } from '@opra/common';
10
- import { HttpIncomingMessageHost } from './impl/http-incoming-message.host.js';
11
- function isHttpIncomingMessage(v) {
12
- return v && Array.isArray(v.rawHeaders) && isReadable(v);
13
- }
14
- export var HttpServerRequest;
15
- (function (HttpServerRequest) {
16
- function from(instance) {
17
- if (!isHttpIncomingMessage(instance))
18
- instance = HttpIncomingMessageHost.from(instance);
19
- mergePrototype(instance, HttpServerRequestHost.prototype);
20
- const req = instance;
21
- req.baseUrl = req.baseUrl || '';
22
- req.parsedUrl = req.parsedUrl || new OpraURL(req.url);
23
- if (!req.searchParams)
24
- Object.defineProperty(req, 'searchParams', {
25
- get() {
26
- return req.parsedUrl.searchParams;
27
- }
28
- });
29
- return req;
30
- }
31
- HttpServerRequest.from = from;
32
- })(HttpServerRequest || (HttpServerRequest = {}));
33
- class HttpServerRequestHost {
34
- constructor() {
35
- this.basePath = '/';
36
- }
9
+ import { BodyReader } from '../utils/body-reader.js';
10
+ export class HttpIncomingHost {
37
11
  get protocol() {
38
12
  const proto = this.header('X-Forwarded-Proto') || 'http';
39
13
  const index = proto.indexOf(',');
40
- return index !== -1
41
- ? proto.substring(0, index).trim()
42
- : proto.trim();
14
+ return index !== -1 ? proto.substring(0, index).trim() : proto.trim();
43
15
  }
44
16
  get secure() {
45
17
  return this.protocol === 'https';
@@ -54,28 +26,25 @@ class HttpServerRequestHost {
54
26
  // single value, but this is to be safe.
55
27
  host = host.substring(0, host.indexOf(',')).trim();
56
28
  }
57
- if (!host)
58
- return;
59
- // IPv6 literal support
60
- const offset = host[0] === '['
61
- ? host.indexOf(']') + 1
62
- : 0;
63
- const index = host.indexOf(':', offset);
64
- return index !== -1
65
- ? host.substring(0, index)
66
- : host;
29
+ if (host) {
30
+ // IPv6 literal support
31
+ const offset = host[0] === '[' ? host.indexOf(']') + 1 : 0;
32
+ const index = host.indexOf(':', offset);
33
+ return index !== -1 ? host.substring(0, index) : host;
34
+ }
35
+ return '';
67
36
  }
68
37
  get fresh() {
69
38
  const method = this.method;
70
39
  // GET or HEAD for weak freshness validation only
71
- if ('GET' !== method && 'HEAD' !== method)
40
+ if (method !== 'GET' && method !== 'HEAD')
72
41
  return false;
73
42
  const status = this.res?.statusCode;
74
43
  // 2xx or 304 as per rfc2616 14.26
75
- if ((status >= 200 && status < 300) || 304 === status) {
44
+ if ((status >= 200 && status < 300) || status === 304) {
76
45
  return fresh(this.headers, {
77
- 'etag': this.res.getHeader('ETag'),
78
- 'last-modified': this.res.getHeader('Last-Modified')
46
+ etag: this.res.getHeader('ETag'),
47
+ 'last-modified': this.res.getHeader('Last-Modified'),
79
48
  });
80
49
  }
81
50
  return false;
@@ -130,4 +99,9 @@ class HttpServerRequestHost {
130
99
  return;
131
100
  return parseRange(size, range, options);
132
101
  }
102
+ async readBody(options) {
103
+ if (!this.complete)
104
+ this.body = await BodyReader.read(this, options);
105
+ return this.body;
106
+ }
133
107
  }