@opra/core 1.0.0-alpha.23 → 1.0.0-alpha.25

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.
@@ -2,58 +2,149 @@
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
3
  exports.MultipartReader = void 0;
4
4
  const tslib_1 = require("tslib");
5
+ const node_crypto_1 = require("node:crypto");
6
+ const node_fs_1 = tslib_1.__importDefault(require("node:fs"));
7
+ const node_os_1 = tslib_1.__importDefault(require("node:os"));
8
+ const node_path_1 = tslib_1.__importDefault(require("node:path"));
9
+ const type_is_1 = tslib_1.__importDefault(require("@browsery/type-is"));
10
+ const common_1 = require("@opra/common");
11
+ const busboy_1 = tslib_1.__importDefault(require("busboy"));
5
12
  const events_1 = require("events");
6
- const formidable_1 = tslib_1.__importDefault(require("formidable"));
7
13
  const promises_1 = tslib_1.__importDefault(require("fs/promises"));
14
+ const valgen_1 = require("valgen");
8
15
  class MultipartReader extends events_1.EventEmitter {
9
- constructor(incoming, options) {
16
+ constructor(context, options, mediaType) {
10
17
  super();
18
+ this.context = context;
19
+ this.mediaType = mediaType;
11
20
  this._started = false;
21
+ this._finished = false;
12
22
  this._cancelled = false;
13
23
  this._items = [];
14
24
  this._stack = [];
15
25
  this.setMaxListeners(1000);
16
- this._incoming = incoming;
17
- const form = (this._form = (0, formidable_1.default)({
18
- ...options,
19
- filter: (part) => !this._cancelled && (!options?.filter || options.filter(part)),
20
- }));
21
- form.once('error', () => {
26
+ this.tempDirectory = options?.tempDirectory || node_os_1.default.tmpdir();
27
+ const { request } = context;
28
+ const form = (0, busboy_1.default)({ headers: request.headers });
29
+ this._form = form;
30
+ form.once('error', (e) => {
22
31
  this._cancelled = true;
32
+ this._finished = true;
23
33
  if (this.listenerCount('error') > 0)
24
- this.emit('error');
34
+ this.emit('error', e);
25
35
  });
26
- form.on('field', (fieldName, value) => {
27
- const item = { fieldName, type: 'field', value };
36
+ form.on('close', () => {
37
+ this._finished = true;
38
+ });
39
+ form.on('field', (field, value, info) => {
40
+ const item = {
41
+ kind: 'field',
42
+ field,
43
+ value,
44
+ mimeType: info.mimeType,
45
+ encoding: info.encoding,
46
+ };
28
47
  this._items.push(item);
29
48
  this._stack.push(item);
30
49
  this.emit('field', item);
31
50
  this.emit('item', item);
32
51
  });
33
- form.on('file', (fieldName, file) => {
34
- const item = { fieldName, type: 'file', file };
35
- this._items.push(item);
36
- this._stack.push(item);
37
- this.emit('file', item);
38
- this.emit('item', item);
52
+ form.on('file', (field, file, info) => {
53
+ const saveTo = node_path_1.default.join(this.tempDirectory, `opra-${generateFileName()}`);
54
+ file.pipe(node_fs_1.default.createWriteStream(saveTo));
55
+ file.once('end', () => {
56
+ const item = {
57
+ kind: 'file',
58
+ field,
59
+ storedPath: saveTo,
60
+ filename: info.filename,
61
+ mimeType: info.mimeType,
62
+ encoding: info.encoding,
63
+ };
64
+ this._items.push(item);
65
+ this._stack.push(item);
66
+ this.emit('file', item);
67
+ this.emit('item', item);
68
+ });
39
69
  });
40
70
  }
41
71
  get items() {
42
72
  return this._items;
43
73
  }
44
- getNext() {
45
- if (!this._form.ended)
74
+ async getNext() {
75
+ let item = this._stack.shift();
76
+ if (!item && !this._finished) {
46
77
  this.resume();
47
- return new Promise((resolve, reject) => {
48
- if (this._stack.length)
49
- return resolve(this._stack.shift());
50
- if (this._form.ended)
51
- return resolve(undefined);
52
- this.once('item', () => resolve(this._stack.shift()));
53
- this.once('error', e => reject(e));
54
- });
78
+ item = await new Promise((resolve, reject) => {
79
+ if (this._stack.length)
80
+ return resolve(this._stack.shift());
81
+ if (this._form.ended)
82
+ return resolve(undefined);
83
+ this._form.once('close', () => {
84
+ resolve(this._stack.shift());
85
+ });
86
+ this.once('item', () => {
87
+ this.pause();
88
+ resolve(this._stack.shift());
89
+ });
90
+ this.once('error', e => reject(e));
91
+ });
92
+ }
93
+ if (item && this.mediaType) {
94
+ const field = this.mediaType.findMultipartField(item.field);
95
+ if (!field)
96
+ throw new common_1.BadRequestError(`Unknown multipart field (${item.field})`);
97
+ if (item.kind === 'field') {
98
+ const decode = field.generateCodec('decode');
99
+ item.value = decode(item.value, {
100
+ onFail: issue => `Multipart field (${item.field}) validation failed: ` + issue.message,
101
+ });
102
+ }
103
+ else if (item.kind === 'file') {
104
+ if (field.contentType) {
105
+ const arr = Array.isArray(field.contentType) ? field.contentType : [field.contentType];
106
+ if (!(item.mimeType && arr.find(ct => type_is_1.default.is(item.mimeType, [ct])))) {
107
+ throw new common_1.BadRequestError(`Multipart field (${item.field}) do not accept this content type`);
108
+ }
109
+ }
110
+ }
111
+ }
112
+ /** if all items received we check for required items */
113
+ if (this._finished && this.mediaType && this.mediaType.multipartFields?.length > 0) {
114
+ const fieldsLeft = new Set(this.mediaType.multipartFields);
115
+ for (const x of this._items) {
116
+ const field = this.mediaType.findMultipartField(x.field);
117
+ if (field)
118
+ fieldsLeft.delete(field);
119
+ }
120
+ let issues;
121
+ for (const field of fieldsLeft) {
122
+ try {
123
+ (0, valgen_1.isNotNullish)(null, { onFail: () => `Multi part field "${String(field.fieldName)}" is required` });
124
+ }
125
+ catch (e) {
126
+ if (!issues) {
127
+ issues = e.issues;
128
+ this.context.errors.push(e);
129
+ }
130
+ else
131
+ issues.push(...e.issues);
132
+ }
133
+ }
134
+ if (this.context.errors.length)
135
+ throw this.context.errors[0];
136
+ }
137
+ return item;
138
+ }
139
+ async getAll() {
140
+ const items = [];
141
+ let item;
142
+ while (!this._cancelled && (item = await this.getNext())) {
143
+ items.push(item);
144
+ }
145
+ return items;
55
146
  }
56
- getAll() {
147
+ getAll_() {
57
148
  if (this._form.ended)
58
149
  return Promise.resolve([...this._items]);
59
150
  this.resume();
@@ -70,30 +161,27 @@ class MultipartReader extends events_1.EventEmitter {
70
161
  this.resume();
71
162
  }
72
163
  resume() {
73
- if (!this._started)
74
- this._form.parse(this._incoming, () => undefined);
75
- if (this._form.req)
76
- this._form.resume();
164
+ if (!this._started) {
165
+ this._started = true;
166
+ this.context.request.pipe(this._form);
167
+ }
168
+ this.context.request.resume();
77
169
  }
78
170
  pause() {
79
- if (this._form.req)
80
- this._form.pause();
171
+ this.context.request.pause();
81
172
  }
82
- async deleteTempFiles() {
173
+ async purge() {
83
174
  const promises = [];
84
175
  this._items.forEach(item => {
85
- if (!item.file)
176
+ if (item.kind !== 'file')
86
177
  return;
87
- const file = item.file;
88
- promises.push(new Promise(resolve => {
89
- if (file._writeStream.closed)
90
- return resolve();
91
- file._writeStream.once('close', resolve);
92
- })
93
- .then(() => promises_1.default.unlink(file.filepath))
94
- .then(() => 0));
178
+ promises.push(promises_1.default.unlink(item.storedPath));
95
179
  });
96
180
  return Promise.allSettled(promises);
97
181
  }
98
182
  }
99
183
  exports.MultipartReader = MultipartReader;
184
+ function generateFileName() {
185
+ const buf = Buffer.alloc(10);
186
+ return new Date().toISOString().substring(0, 10).replaceAll('-', '') + (0, node_crypto_1.randomFillSync)(buf).toString('hex');
187
+ }
package/cjs/index.js CHANGED
@@ -10,11 +10,11 @@ const HttpOutgoingHost_ = tslib_1.__importStar(require("./http/impl/http-outgoin
10
10
  const NodeIncomingMessageHost_ = tslib_1.__importStar(require("./http/impl/node-incoming-message.host.js"));
11
11
  const NodeOutgoingMessageHost_ = tslib_1.__importStar(require("./http/impl/node-outgoing-message.host.js"));
12
12
  tslib_1.__exportStar(require("./execution-context.js"), exports);
13
- tslib_1.__exportStar(require("./helpers/logger.js"), exports);
14
13
  tslib_1.__exportStar(require("./helpers/service-base.js"), exports);
15
14
  tslib_1.__exportStar(require("./http/express-adapter.js"), exports);
16
15
  tslib_1.__exportStar(require("./http/http-adapter.js"), exports);
17
16
  tslib_1.__exportStar(require("./http/http-context.js"), exports);
17
+ tslib_1.__exportStar(require("./http/http-handler.js"), exports);
18
18
  tslib_1.__exportStar(require("./http/impl/multipart-reader.js"), exports);
19
19
  tslib_1.__exportStar(require("./http/interfaces/http-incoming.interface.js"), exports);
20
20
  tslib_1.__exportStar(require("./http/interfaces/http-outgoing.interface.js"), exports);
@@ -5,7 +5,6 @@ require("./augmentation/18n.augmentation.js");
5
5
  const common_1 = require("@opra/common");
6
6
  const strict_typed_events_1 = require("strict-typed-events");
7
7
  const constants_js_1 = require("./constants.js");
8
- const logger_js_1 = require("./helpers/logger.js");
9
8
  const asset_cache_js_1 = require("./http/impl/asset-cache.js");
10
9
  /**
11
10
  * @class PlatformAdapter
@@ -15,8 +14,6 @@ class PlatformAdapter extends strict_typed_events_1.AsyncEventEmitter {
15
14
  super();
16
15
  this[constants_js_1.kAssetCache] = new asset_cache_js_1.AssetCache();
17
16
  this.document = document;
18
- this.logger =
19
- options?.logger && options.logger instanceof logger_js_1.Logger ? options.logger : new logger_js_1.Logger({ instance: options?.logger });
20
17
  this.i18n = options?.i18n || common_1.I18n.defaultInstance;
21
18
  }
22
19
  }
package/esm/constants.js CHANGED
@@ -1,2 +1 @@
1
- export const kHandler = Symbol.for('kHandler');
2
1
  export const kAssetCache = Symbol.for('kAssetCache');
@@ -5,6 +5,7 @@ import { AsyncEventEmitter } from 'strict-typed-events';
5
5
  export class ExecutionContext extends AsyncEventEmitter {
6
6
  constructor(init) {
7
7
  super();
8
+ this.errors = [];
8
9
  this.document = init.document;
9
10
  this.protocol = init.protocol;
10
11
  this.platform = init.platform;
@@ -1,11 +1,11 @@
1
1
  import { HttpApi, NotFoundError } from '@opra/common';
2
2
  import { Router } from 'express';
3
3
  import * as nodePath from 'path';
4
- import { kHandler } from '../constants.js';
5
4
  import { HttpAdapter } from './http-adapter.js';
6
5
  import { HttpContext } from './http-context.js';
7
6
  import { HttpIncoming } from './interfaces/http-incoming.interface.js';
8
7
  import { HttpOutgoing } from './interfaces/http-outgoing.interface.js';
8
+ import { wrapException } from './utils/wrap-exception';
9
9
  export class ExpressAdapter extends HttpAdapter {
10
10
  constructor(app, document, options) {
11
11
  super(document, options);
@@ -36,7 +36,8 @@ export class ExpressAdapter extends HttpAdapter {
36
36
  await resource.onShutdown.call(instance, resource);
37
37
  }
38
38
  catch (e) {
39
- this.logger.error(e);
39
+ if (this.listenerCount('error'))
40
+ this.emit('error', wrapException(e));
40
41
  }
41
42
  }
42
43
  }
@@ -76,7 +77,7 @@ export class ExpressAdapter extends HttpAdapter {
76
77
  /** Add an endpoint that returns document schema */
77
78
  router.get('/\\$schema', (_req, _res, next) => {
78
79
  const context = createContext(_req, _res);
79
- this[kHandler].sendDocumentSchema(context).catch(next);
80
+ this.handler.sendDocumentSchema(context).catch(next);
80
81
  });
81
82
  /** Add operation endpoints */
82
83
  if (this.api.controllers.size) {
@@ -96,13 +97,13 @@ export class ExpressAdapter extends HttpAdapter {
96
97
  operation,
97
98
  operationHandler,
98
99
  });
99
- this[kHandler]
100
+ this.handler
100
101
  .handleRequest(context)
101
102
  .then(() => {
102
103
  if (!_res.headersSent)
103
104
  _next();
104
105
  })
105
- .catch((e) => this.logger.fatal(e));
106
+ .catch((e) => this.emit('error', e));
106
107
  });
107
108
  }
108
109
  if (controller.controllers.size) {
@@ -115,19 +116,15 @@ export class ExpressAdapter extends HttpAdapter {
115
116
  }
116
117
  /** Add an endpoint that returns 404 error at last */
117
118
  router.use('*', (_req, _res, next) => {
118
- const res = HttpOutgoing.from(_res);
119
- // const url = new URL(_req.originalUrl, '')
120
- this[kHandler]
121
- .sendErrorResponse(res, [
122
- new NotFoundError({
123
- message: `No endpoint found for [${_req.method}]${_req.baseUrl}`,
124
- details: {
125
- path: _req.baseUrl,
126
- method: _req.method,
127
- },
128
- }),
129
- ])
130
- .catch(next);
119
+ const context = createContext(_req, _res);
120
+ context.errors.push(new NotFoundError({
121
+ message: `No endpoint found at [${_req.method}]${_req.baseUrl}`,
122
+ details: {
123
+ path: _req.baseUrl,
124
+ method: _req.method,
125
+ },
126
+ }));
127
+ this.handler.sendResponse(context).catch(next);
131
128
  });
132
129
  }
133
130
  _createControllers(controller) {
@@ -1,7 +1,6 @@
1
1
  import { HttpApi } from '@opra/common';
2
- import { kHandler } from '../constants.js';
3
2
  import { PlatformAdapter } from '../platform-adapter.js';
4
- import { HttpHandler } from './impl/http-handler.js';
3
+ import { HttpHandler } from './http-handler.js';
5
4
  /**
6
5
  *
7
6
  * @class HttpAdapter
@@ -12,10 +11,8 @@ export class HttpAdapter extends PlatformAdapter {
12
11
  this.protocol = 'http';
13
12
  if (!(document.api instanceof HttpApi))
14
13
  throw new TypeError(`The document does not expose an HTTP Api`);
15
- this[kHandler] = new HttpHandler(this);
14
+ this.handler = new HttpHandler(this);
16
15
  this.interceptors = [...(options?.interceptors || [])];
17
- if (options?.onRequest)
18
- this.on('request', options.onRequest);
19
16
  }
20
17
  get api() {
21
18
  return this.document.api;
@@ -25,6 +25,10 @@ export class HttpContext extends ExecutionContext {
25
25
  this.pathParams = init.pathParams || {};
26
26
  this.queryParams = init.queryParams || {};
27
27
  this._body = init.body;
28
+ this.on('finish', () => {
29
+ if (this._multipartReader)
30
+ this._multipartReader.purge().catch(() => undefined);
31
+ });
28
32
  }
29
33
  get isMultipart() {
30
34
  return !!this.request.is('multipart');
@@ -34,21 +38,21 @@ export class HttpContext extends ExecutionContext {
34
38
  throw new InternalServerError('Request content is not a multipart content');
35
39
  if (this._multipartReader)
36
40
  return this._multipartReader;
37
- const { request, mediaType } = this;
41
+ const { mediaType } = this;
38
42
  if (mediaType?.contentType) {
39
43
  const arr = Array.isArray(mediaType.contentType) ? mediaType.contentType : [mediaType.contentType];
40
44
  const contentType = arr.find(ct => typeIs.is(ct, ['multipart']));
41
45
  if (!contentType)
42
46
  throw new NotAcceptableError('This endpoint does not accept multipart requests');
43
47
  }
44
- const reader = new MultipartReader(request, {
45
- maxFields: mediaType?.maxFields,
46
- maxFieldsSize: mediaType?.maxFieldsSize,
47
- maxFiles: mediaType?.maxFiles,
48
- maxFileSize: mediaType?.maxFileSize,
49
- maxTotalFileSize: mediaType?.maxTotalFileSize,
50
- minFileSize: mediaType?.minFileSize,
51
- });
48
+ const reader = new MultipartReader(this, {
49
+ limits: {
50
+ fields: mediaType?.maxFields,
51
+ fieldSize: mediaType?.maxFieldsSize,
52
+ files: mediaType?.maxFiles,
53
+ fileSize: mediaType?.maxFileSize,
54
+ },
55
+ }, mediaType);
52
56
  this._multipartReader = reader;
53
57
  return reader;
54
58
  }
@@ -66,7 +70,7 @@ export class HttpContext extends ExecutionContext {
66
70
  if (mediaType && multipartFields?.length) {
67
71
  const fieldsFound = new Map();
68
72
  for (const item of parts) {
69
- const field = mediaType.findMultipartField(item.fieldName, item.type);
73
+ const field = mediaType.findMultipartField(item.field, item.kind);
70
74
  if (field) {
71
75
  fieldsFound.set(field, true);
72
76
  this._body.push(item);