@wooksjs/event-http 0.2.12 → 0.2.14

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/dist/index.cjs CHANGED
@@ -6,9 +6,10 @@ var stream = require('stream');
6
6
  var wooks = require('wooks');
7
7
  var http = require('http');
8
8
 
9
- function createHttpContext(data) {
9
+ function createHttpContext(data, options) {
10
10
  return eventCore.createEventContext({
11
11
  event: Object.assign(Object.assign({}, data), { type: 'HTTP' }),
12
+ options,
12
13
  });
13
14
  }
14
15
  function useHttpContext() {
@@ -183,28 +184,6 @@ const units = {
183
184
  Y: 1000 * 60 * 60 * 24 * 365,
184
185
  };
185
186
 
186
- const banner = () => `[${"@wooksjs/event-http"}][${new Date().toISOString().replace('T', ' ').replace(/\.\d{3}z$/i, '')}] `;
187
-
188
- /* istanbul ignore file */
189
- function warn(text) {
190
- console.warn('' + banner() + text + '');
191
- }
192
- function logError(error) {
193
- console.error('' + '' + banner() + error + '');
194
- }
195
- function traceError(expl, e) {
196
- logError(expl);
197
- logError(e.message);
198
- if (e.stack) {
199
- warn(e.stack);
200
- }
201
- }
202
-
203
- function panic(error) {
204
- logError(error);
205
- return new Error(error);
206
- }
207
-
208
187
  function renderCacheControl(data) {
209
188
  let attrs = '';
210
189
  for (const [a, v] of Object.entries(data)) {
@@ -218,7 +197,7 @@ function renderCacheControl(data) {
218
197
  }
219
198
  }
220
199
  else {
221
- panic('Unknown Cache-Control attribute ' + a);
200
+ throw new Error('Unknown Cache-Control attribute ' + a);
222
201
  }
223
202
  }
224
203
  return attrs;
@@ -299,7 +278,7 @@ function renderCookie(key, data) {
299
278
  attrs += val ? '; ' + val : '';
300
279
  }
301
280
  else {
302
- panic('Unknown Set-Cookie attribute ' + a);
281
+ throw new Error('Unknown Set-Cookie attribute ' + a);
303
282
  }
304
283
  }
305
284
  return `${key}=${encodeURIComponent(data.value)}${attrs}`;
@@ -482,7 +461,7 @@ class BaseHttpResponseRenderer {
482
461
  response.setContentType('application/json');
483
462
  return JSON.stringify(response.body);
484
463
  }
485
- throw panic('Unsupported body format "' + typeof response.body + '"');
464
+ throw new Error('Unsupported body format "' + typeof response.body + '"');
486
465
  }
487
466
  }
488
467
 
@@ -708,12 +687,21 @@ class BaseHttpResponse {
708
687
  }
709
688
  return this;
710
689
  }
690
+ mergeFetchStatus(fetchStatus) {
691
+ this.status = this.status || useResponse().status() || fetchStatus;
692
+ }
693
+ panic(text, logger) {
694
+ const error = new Error(text);
695
+ logger.error(error);
696
+ throw error;
697
+ }
711
698
  respond() {
712
699
  return __awaiter(this, void 0, void 0, function* () {
713
700
  const { rawResponse, hasResponded } = useResponse();
714
701
  const { method, rawRequest } = useRequest();
702
+ const logger = eventCore.useEventLogger('http-response');
715
703
  if (hasResponded()) {
716
- throw panic('The response was already sent.');
704
+ this.panic('The response was already sent.', logger);
717
705
  }
718
706
  this.mergeHeaders();
719
707
  const res = rawResponse();
@@ -745,11 +733,19 @@ class BaseHttpResponse {
745
733
  }
746
734
  }
747
735
  else if (globalThis.Response && this.body instanceof Response /* Fetch Response */) {
748
- this.mergeStatus('ok');
736
+ this.mergeFetchStatus(this.body.status);
749
737
  if (method === 'HEAD') {
750
738
  res.end();
751
739
  }
752
740
  else {
741
+ const additionalHeaders = {};
742
+ if (this.body.headers.get('content-length')) {
743
+ additionalHeaders['content-length'] = this.body.headers.get('content-length');
744
+ }
745
+ if (this.body.headers.get('content-type')) {
746
+ additionalHeaders['content-type'] = this.body.headers.get('content-type');
747
+ }
748
+ res.writeHead(this.status, Object.assign(Object.assign({}, additionalHeaders), this._headers));
753
749
  yield respondWithFetch(this.body.body, res);
754
750
  }
755
751
  }
@@ -812,7 +808,7 @@ class HttpErrorRenderer extends BaseHttpResponseRenderer {
812
808
  `<head><title>${data.statusCode} ${httpStatusCodes[data.statusCode]}</title></head>` +
813
809
  `<body><center><h1>${data.statusCode} ${httpStatusCodes[data.statusCode]}</h1></center>` +
814
810
  `<center><h4>${data.message}</h1></center><hr color="#666">` +
815
- `<center style="color: #666;"> Wooks v${"0.2.12"} </center>` +
811
+ `<center style="color: #666;"> Wooks v${"0.2.14"} </center>` +
816
812
  `${keys.length ? `<pre style="${preStyles}">${JSON.stringify(Object.assign(Object.assign({}, data), { statusCode: undefined, message: undefined, error: undefined }), null, ' ')}</pre>` : ''}` +
817
813
  '</body></html>';
818
814
  }
@@ -914,6 +910,7 @@ class WooksHttp extends wooks.WooksAdapterBase {
914
910
  super(wooks);
915
911
  this.opts = opts;
916
912
  this.responder = createWooksResponder();
913
+ this.logger = (opts === null || opts === void 0 ? void 0 : opts.logger) || this.getLogger('wooks-http');
917
914
  }
918
915
  all(path, handler) {
919
916
  return this.on('*', path, handler);
@@ -968,19 +965,20 @@ class WooksHttp extends wooks.WooksAdapterBase {
968
965
  respond(data) {
969
966
  var _a;
970
967
  void ((_a = this.responder.respond(data)) === null || _a === void 0 ? void 0 : _a.catch((e) => {
971
- traceError('Uncought response exception:\n', e);
968
+ this.logger.error('Uncought response exception', e);
972
969
  }));
973
970
  }
974
971
  getServerCb() {
975
972
  return (req, res) => __awaiter(this, void 0, void 0, function* () {
976
- const { restoreCtx, clearCtx } = createHttpContext({ req, res });
973
+ var _a;
974
+ const { restoreCtx, clearCtx } = createHttpContext({ req, res }, ((_a = this.opts) === null || _a === void 0 ? void 0 : _a.eventOptions) || {});
977
975
  const handlers = this.wooks.lookup(req.method, req.url);
978
976
  if (handlers) {
979
977
  try {
980
978
  yield this.processHandlers(handlers);
981
979
  }
982
980
  catch (e) {
983
- traceError('Internal error, please report: ', e);
981
+ this.logger.error('Internal error, please report', e);
984
982
  restoreCtx();
985
983
  this.respond(e);
986
984
  clearCtx();
@@ -1011,7 +1009,7 @@ class WooksHttp extends wooks.WooksAdapterBase {
1011
1009
  break;
1012
1010
  }
1013
1011
  catch (e) {
1014
- traceError(`Uncought route handler exception: ${(store('event').get('req').url || '')}\n`, e);
1012
+ this.logger.error(`Uncought route handler exception: ${(store('event').get('req').url || '')}`, e);
1015
1013
  if (isLastHandler) {
1016
1014
  restoreCtx();
1017
1015
  this.respond(e);
package/dist/index.d.ts CHANGED
@@ -5,6 +5,8 @@ import { IncomingHttpHeaders } from 'http';
5
5
  import { IncomingMessage } from 'http';
6
6
  import { Server } from 'http';
7
7
  import { ServerResponse } from 'http';
8
+ import { TConsoleBase } from '@prostojs/logger';
9
+ import { TEventOptions } from '@wooksjs/event-core';
8
10
  import { TGenericContextStore } from '@wooksjs/event-core';
9
11
  import { TGenericEvent } from '@wooksjs/event-core';
10
12
  import { TProstoRouterPathBuilder } from '@prostojs/router';
@@ -36,6 +38,8 @@ export declare class BaseHttpResponse<BodyType = unknown> {
36
38
  getHeader(name: string): string | string[];
37
39
  protected mergeHeaders(): this;
38
40
  protected mergeStatus(renderedBody: string | Uint8Array): this;
41
+ protected mergeFetchStatus(fetchStatus: number): void;
42
+ protected panic(text: string, logger: TConsoleBase): void;
39
43
  respond(): Promise<unknown>;
40
44
  }
41
45
 
@@ -45,7 +49,7 @@ export declare class BaseHttpResponseRenderer<T = unknown> implements TWooksResp
45
49
 
46
50
  export declare function createHttpApp(opts?: TWooksHttpOptions, wooks?: Wooks | WooksAdapterBase): WooksHttp;
47
51
 
48
- export declare function createHttpContext(data: THttpEventData): {
52
+ export declare function createHttpContext(data: THttpEventData, options: TEventOptions): {
49
53
  getCtx: () => THttpContextStore;
50
54
  restoreCtx: () => THttpContextStore;
51
55
  clearCtx: () => null;
@@ -343,6 +347,8 @@ export declare interface TWooksErrorBodyExt extends TWooksErrorBody {
343
347
  }
344
348
 
345
349
  export declare interface TWooksHttpOptions {
350
+ logger?: TConsoleBase;
351
+ eventOptions?: TEventOptions;
346
352
  }
347
353
 
348
354
  export declare interface TWooksResponseRenderer<T = unknown> {
@@ -480,6 +486,7 @@ export declare function useStatus(): {
480
486
 
481
487
  export declare class WooksHttp extends WooksAdapterBase {
482
488
  protected opts?: TWooksHttpOptions | undefined;
489
+ protected logger: TConsoleBase;
483
490
  constructor(opts?: TWooksHttpOptions | undefined, wooks?: Wooks | WooksAdapterBase);
484
491
  all<ResType = unknown, ParamsType = Record<string, string | string[]>>(path: string, handler: TWooksHandler<ResType>): TProstoRouterPathBuilder<ParamsType>;
485
492
  get<ResType = unknown, ParamsType = Record<string, string | string[]>>(path: string, handler: TWooksHandler<ResType>): TProstoRouterPathBuilder<ParamsType>;
package/dist/index.mjs CHANGED
@@ -1,12 +1,13 @@
1
- import { createEventContext, useEventContext, useEventId, attachHook } from '@wooksjs/event-core';
1
+ import { createEventContext, useEventContext, useEventId, attachHook, useEventLogger } from '@wooksjs/event-core';
2
2
  import { URLSearchParams } from 'url';
3
3
  import { Readable } from 'stream';
4
4
  import { WooksAdapterBase } from 'wooks';
5
5
  import http from 'http';
6
6
 
7
- function createHttpContext(data) {
7
+ function createHttpContext(data, options) {
8
8
  return createEventContext({
9
9
  event: Object.assign(Object.assign({}, data), { type: 'HTTP' }),
10
+ options,
10
11
  });
11
12
  }
12
13
  function useHttpContext() {
@@ -181,28 +182,6 @@ const units = {
181
182
  Y: 1000 * 60 * 60 * 24 * 365,
182
183
  };
183
184
 
184
- const banner = () => `[${"@wooksjs/event-http"}][${new Date().toISOString().replace('T', ' ').replace(/\.\d{3}z$/i, '')}] `;
185
-
186
- /* istanbul ignore file */
187
- function warn(text) {
188
- console.warn('' + banner() + text + '');
189
- }
190
- function logError(error) {
191
- console.error('' + '' + banner() + error + '');
192
- }
193
- function traceError(expl, e) {
194
- logError(expl);
195
- logError(e.message);
196
- if (e.stack) {
197
- warn(e.stack);
198
- }
199
- }
200
-
201
- function panic(error) {
202
- logError(error);
203
- return new Error(error);
204
- }
205
-
206
185
  function renderCacheControl(data) {
207
186
  let attrs = '';
208
187
  for (const [a, v] of Object.entries(data)) {
@@ -216,7 +195,7 @@ function renderCacheControl(data) {
216
195
  }
217
196
  }
218
197
  else {
219
- panic('Unknown Cache-Control attribute ' + a);
198
+ throw new Error('Unknown Cache-Control attribute ' + a);
220
199
  }
221
200
  }
222
201
  return attrs;
@@ -297,7 +276,7 @@ function renderCookie(key, data) {
297
276
  attrs += val ? '; ' + val : '';
298
277
  }
299
278
  else {
300
- panic('Unknown Set-Cookie attribute ' + a);
279
+ throw new Error('Unknown Set-Cookie attribute ' + a);
301
280
  }
302
281
  }
303
282
  return `${key}=${encodeURIComponent(data.value)}${attrs}`;
@@ -480,7 +459,7 @@ class BaseHttpResponseRenderer {
480
459
  response.setContentType('application/json');
481
460
  return JSON.stringify(response.body);
482
461
  }
483
- throw panic('Unsupported body format "' + typeof response.body + '"');
462
+ throw new Error('Unsupported body format "' + typeof response.body + '"');
484
463
  }
485
464
  }
486
465
 
@@ -706,12 +685,21 @@ class BaseHttpResponse {
706
685
  }
707
686
  return this;
708
687
  }
688
+ mergeFetchStatus(fetchStatus) {
689
+ this.status = this.status || useResponse().status() || fetchStatus;
690
+ }
691
+ panic(text, logger) {
692
+ const error = new Error(text);
693
+ logger.error(error);
694
+ throw error;
695
+ }
709
696
  respond() {
710
697
  return __awaiter(this, void 0, void 0, function* () {
711
698
  const { rawResponse, hasResponded } = useResponse();
712
699
  const { method, rawRequest } = useRequest();
700
+ const logger = useEventLogger('http-response');
713
701
  if (hasResponded()) {
714
- throw panic('The response was already sent.');
702
+ this.panic('The response was already sent.', logger);
715
703
  }
716
704
  this.mergeHeaders();
717
705
  const res = rawResponse();
@@ -743,11 +731,19 @@ class BaseHttpResponse {
743
731
  }
744
732
  }
745
733
  else if (globalThis.Response && this.body instanceof Response /* Fetch Response */) {
746
- this.mergeStatus('ok');
734
+ this.mergeFetchStatus(this.body.status);
747
735
  if (method === 'HEAD') {
748
736
  res.end();
749
737
  }
750
738
  else {
739
+ const additionalHeaders = {};
740
+ if (this.body.headers.get('content-length')) {
741
+ additionalHeaders['content-length'] = this.body.headers.get('content-length');
742
+ }
743
+ if (this.body.headers.get('content-type')) {
744
+ additionalHeaders['content-type'] = this.body.headers.get('content-type');
745
+ }
746
+ res.writeHead(this.status, Object.assign(Object.assign({}, additionalHeaders), this._headers));
751
747
  yield respondWithFetch(this.body.body, res);
752
748
  }
753
749
  }
@@ -810,7 +806,7 @@ class HttpErrorRenderer extends BaseHttpResponseRenderer {
810
806
  `<head><title>${data.statusCode} ${httpStatusCodes[data.statusCode]}</title></head>` +
811
807
  `<body><center><h1>${data.statusCode} ${httpStatusCodes[data.statusCode]}</h1></center>` +
812
808
  `<center><h4>${data.message}</h1></center><hr color="#666">` +
813
- `<center style="color: #666;"> Wooks v${"0.2.12"} </center>` +
809
+ `<center style="color: #666;"> Wooks v${"0.2.14"} </center>` +
814
810
  `${keys.length ? `<pre style="${preStyles}">${JSON.stringify(Object.assign(Object.assign({}, data), { statusCode: undefined, message: undefined, error: undefined }), null, ' ')}</pre>` : ''}` +
815
811
  '</body></html>';
816
812
  }
@@ -912,6 +908,7 @@ class WooksHttp extends WooksAdapterBase {
912
908
  super(wooks);
913
909
  this.opts = opts;
914
910
  this.responder = createWooksResponder();
911
+ this.logger = (opts === null || opts === void 0 ? void 0 : opts.logger) || this.getLogger('wooks-http');
915
912
  }
916
913
  all(path, handler) {
917
914
  return this.on('*', path, handler);
@@ -966,19 +963,20 @@ class WooksHttp extends WooksAdapterBase {
966
963
  respond(data) {
967
964
  var _a;
968
965
  void ((_a = this.responder.respond(data)) === null || _a === void 0 ? void 0 : _a.catch((e) => {
969
- traceError('Uncought response exception:\n', e);
966
+ this.logger.error('Uncought response exception', e);
970
967
  }));
971
968
  }
972
969
  getServerCb() {
973
970
  return (req, res) => __awaiter(this, void 0, void 0, function* () {
974
- const { restoreCtx, clearCtx } = createHttpContext({ req, res });
971
+ var _a;
972
+ const { restoreCtx, clearCtx } = createHttpContext({ req, res }, ((_a = this.opts) === null || _a === void 0 ? void 0 : _a.eventOptions) || {});
975
973
  const handlers = this.wooks.lookup(req.method, req.url);
976
974
  if (handlers) {
977
975
  try {
978
976
  yield this.processHandlers(handlers);
979
977
  }
980
978
  catch (e) {
981
- traceError('Internal error, please report: ', e);
979
+ this.logger.error('Internal error, please report', e);
982
980
  restoreCtx();
983
981
  this.respond(e);
984
982
  clearCtx();
@@ -1009,7 +1007,7 @@ class WooksHttp extends WooksAdapterBase {
1009
1007
  break;
1010
1008
  }
1011
1009
  catch (e) {
1012
- traceError(`Uncought route handler exception: ${(store('event').get('req').url || '')}\n`, e);
1010
+ this.logger.error(`Uncought route handler exception: ${(store('event').get('req').url || '')}`, e);
1013
1011
  if (isLastHandler) {
1014
1012
  restoreCtx();
1015
1013
  this.respond(e);
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@wooksjs/event-http",
3
- "version": "0.2.12",
3
+ "version": "0.2.14",
4
4
  "description": "@wooksjs/event-http",
5
5
  "main": "dist/index.cjs",
6
6
  "module": "dist/index.mjs",
@@ -31,9 +31,12 @@
31
31
  "url": "https://github.com/wooksjs/wooksjs/issues"
32
32
  },
33
33
  "peerDependencies": {
34
- "wooks": "0.2.12",
34
+ "wooks": "0.2.14",
35
35
  "@prostojs/router": "^0.0.16",
36
- "@wooksjs/event-core": "0.2.12"
36
+ "@wooksjs/event-core": "0.2.14"
37
+ },
38
+ "dependencies": {
39
+ "@prostojs/logger": "^0.3.2"
37
40
  },
38
41
  "homepage": "https://github.com/wooksjs/wooksjs/tree/main/packages/event-http#readme"
39
42
  }