@yopdev/dev-server 1.3.17 → 1.4.0-alpha.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -2,7 +2,6 @@ import { Sqs } from "./sqs";
2
2
  import { Sns } from "./sns";
3
3
  import { DynamoDb } from "./dynamodb";
4
4
  import { StartedNetwork } from "testcontainers";
5
- import { S3 } from "./s3";
6
5
  export type Config = {
7
6
  boundServicesPort?: number;
8
7
  localStackDockerImage?: string;
@@ -21,7 +20,6 @@ export type DevServerConfig = {
21
20
  network: StartedNetwork;
22
21
  sqs: Sqs;
23
22
  sns: Sns;
24
- s3: S3;
25
23
  dynamo: DynamoDb;
26
24
  eventsProxy: {
27
25
  topic: {
@@ -95,9 +95,13 @@ var Promised = /** @class */ (function () {
95
95
  .then(function () { return _this.service.start(config); })];
96
96
  });
97
97
  }); };
98
- this.stop = function () { return __awaiter(_this, void 0, void 0, function () { return __generator(this, function (_a) {
99
- return [2 /*return*/, this.service.stop()];
100
- }); }); };
98
+ this.stop = function () { return __awaiter(_this, void 0, void 0, function () {
99
+ var _this = this;
100
+ return __generator(this, function (_a) {
101
+ return [2 /*return*/, Promise.resolve(this.LOGGER.info('stopped'))
102
+ .then(function () { return _this.service.stop(); })];
103
+ });
104
+ }); };
101
105
  this.name = (0, crypto_1.randomUUID)();
102
106
  this.LOGGER = logging_1.LoggerFactory.create("PROMISED[".concat(this.name, "]"));
103
107
  }
@@ -7,8 +7,6 @@ var sqs_1 = require("./sqs");
7
7
  var dynamodb_1 = require("./dynamodb");
8
8
  var logging_1 = require("@yopdev/logging");
9
9
  var sns_1 = require("./sns");
10
- var tunnel_1 = require("./tunnel");
11
- var s3_1 = require("./s3");
12
10
  var DevServer = /** @class */ (function () {
13
11
  function DevServer(name, service, config) {
14
12
  var _this = this;
@@ -34,7 +32,6 @@ var DevServer = /** @class */ (function () {
34
32
  network: infra.network,
35
33
  sqs: new sqs_1.Sqs(infra.aws),
36
34
  sns: new sns_1.Sns(infra.aws),
37
- s3: new s3_1.S3(infra.aws),
38
35
  dynamo: new dynamodb_1.DynamoDb(infra.aws),
39
36
  eventsProxy: {
40
37
  topic: {
@@ -42,13 +39,12 @@ var DevServer = /** @class */ (function () {
42
39
  }
43
40
  },
44
41
  }); }); }); })
45
- .tap(function (config) { return _this.LOGGER.debug('config is %o', config); })
42
+ .then(function (config) { _this.LOGGER.debug('starting. config is %o', config); return config; })
46
43
  .then(function (aws) { return _this.service.start(aws); })
47
44
  .then(function () { return _this.LOGGER.info('started'); })
48
45
  .then(function () { return _this; });
49
46
  };
50
47
  this.stop = function () { return _this.service.stop()
51
- .then(tunnel_1.terminate)
52
48
  .then(function () { var _a; return (_a = _this.localStack) === null || _a === void 0 ? void 0 : _a.stop(); })
53
49
  .then(function () { return _this.LOGGER.info('stopped'); }); };
54
50
  this.LOGGER = logging_1.LoggerFactory.create("DEVSERVER[".concat(name, "]"));
@@ -40,7 +40,6 @@ exports.DynamoDb = exports.newDynamoDbTable = void 0;
40
40
  var client_dynamodb_1 = require("@aws-sdk/client-dynamodb");
41
41
  var logging_1 = require("@yopdev/logging");
42
42
  var services_1 = require("./services");
43
- var assert_1 = require("./assert");
44
43
  var newDynamoDbTable = function (name, config, callback) { return new services_1.Service(new DynamoDbTableCreator(name, config.command), callback); };
45
44
  exports.newDynamoDbTable = newDynamoDbTable;
46
45
  var DynamoDbTableCreator = /** @class */ (function () {
@@ -52,11 +51,12 @@ var DynamoDbTableCreator = /** @class */ (function () {
52
51
  var _this = this;
53
52
  return __generator(this, function (_a) {
54
53
  return [2 /*return*/, config.dynamo.createTable(this.command)
55
- .tap(function (output) { return _this.LOGGER.debug(output); })
54
+ .then(function () { return _this.LOGGER.info('created'); })
56
55
  .then(function () { return _this.name; })];
57
56
  });
58
57
  }); };
59
- this.stop = function () { return Promise.resolve(); };
58
+ this.stop = function () { return Promise.resolve()
59
+ .then(function () { return _this.LOGGER.info('stopped'); }); };
60
60
  this.LOGGER = logging_1.LoggerFactory.create("TABLE[".concat(name, "]"));
61
61
  }
62
62
  return DynamoDbTableCreator;
@@ -69,7 +69,7 @@ var DynamoDb = /** @class */ (function () {
69
69
  return __generator(this, function (_a) {
70
70
  return [2 /*return*/, this.client
71
71
  .send(factory) //
72
- .tap(function (table) { return LOGGER.debug('created %s', (0, assert_1.assertNotUndefined)(table.TableDescription).TableName); })
72
+ .then(function (table) { var _a; LOGGER.info('table created %s', (_a = table.TableDescription) === null || _a === void 0 ? void 0 : _a.TableName); return table; })
73
73
  .catch(function (reason) {
74
74
  LOGGER.error('failed to create table');
75
75
  if (reason.name !== 'ResourceInUseException')
@@ -78,6 +78,7 @@ var DynamoDb = /** @class */ (function () {
78
78
  });
79
79
  }); };
80
80
  this.client = new client_dynamodb_1.DynamoDBClient(config);
81
+ LOGGER.debug('initialized');
81
82
  }
82
83
  return DynamoDb;
83
84
  }());
@@ -1,13 +1,9 @@
1
- import { SNSMessageAttributes, SQSEvent, SQSRecord } from 'aws-lambda';
2
- import { Message } from '@aws-sdk/client-sqs';
1
+ import { SQSEvent } from 'aws-lambda';
3
2
  import { Service } from './services';
4
3
  export declare const newEventsProxy: (name: string, config: {
5
4
  handlers: EventHandler[];
6
- topic?: string;
7
- mapper?: (message: Message) => SQSRecord;
8
- }) => Service<void>;
5
+ }) => Service<any>;
9
6
  export type EventHandler = {
10
- name: string;
11
7
  handler: (event: SQSEvent) => Promise<unknown>;
12
- matcher: (subject: string, attributes: SNSMessageAttributes) => boolean;
8
+ matcher: (subject: string) => boolean;
13
9
  };
@@ -43,31 +43,28 @@ var logging_1 = require("@yopdev/logging");
43
43
  var stoppable_1 = require("./stoppable");
44
44
  var assert_1 = require("./assert");
45
45
  var services_1 = require("./services");
46
- var newEventsProxy = function (name, config) { var _a; return new services_1.Service(new EventsProxy(name, config.handlers, (_a = config.mapper) !== null && _a !== void 0 ? _a : mappers_1.mapToLambdaSqsRecord, config.topic)); };
46
+ var newEventsProxy = function (name, config) { return new services_1.Service(new EventsProxy(name, config.handlers)); };
47
47
  exports.newEventsProxy = newEventsProxy;
48
48
  var EventsProxy = /** @class */ (function () {
49
- function EventsProxy(name, handlers, mapper, topic) {
49
+ function EventsProxy(name, handlers) {
50
50
  var _this = this;
51
51
  this.name = name;
52
52
  this.handlers = handlers;
53
- this.mapper = mapper;
54
- this.topic = topic;
55
53
  this.pollingFrequency = 1;
56
54
  this.stopped = true;
57
55
  this.queueName = function () { return "EventProxyQueue".concat(Buffer.from(_this.name).toString('hex').substring(0, 64)); };
58
56
  this.start = function (config) { return __awaiter(_this, void 0, void 0, function () {
59
57
  var _this = this;
60
- var _a;
61
- return __generator(this, function (_b) {
62
- return [2 /*return*/, this.queueConnectedToTopic(config.sns, (_a = this.topic) !== null && _a !== void 0 ? _a : config.eventsProxy.topic.arn, config.sqs, this.queueName())
58
+ return __generator(this, function (_a) {
59
+ return [2 /*return*/, this.queueConnectedToTopic(config.sns, config.eventsProxy.topic.arn, config.sqs, this.queueName())
63
60
  .then(function (url) { return _this.startEventsConsumer(config.sqs.client, url); })
64
- .tap(function () { return _this.stopped = false; })
65
- .then(function (consumer) { return _this.LOGGER.debug(consumer); })];
61
+ .then(function () { return _this.stopped = false; })
62
+ .then(function () { return undefined; })];
66
63
  });
67
64
  }); };
68
65
  this.queueConnectedToTopic = function (sns, topic, sqs, queue) { return __awaiter(_this, void 0, void 0, function () {
69
66
  return __generator(this, function (_a) {
70
- return [2 /*return*/, sqs.createStandardQueue(queue)
67
+ return [2 /*return*/, sqs.createNamedQueue(queue)
71
68
  .then(function (queue) { return sns
72
69
  .createSubscription({ arn: topic }, { arn: queue.arn })
73
70
  .then(function () { return queue.url; }); })];
@@ -90,36 +87,41 @@ var EventsProxy = /** @class */ (function () {
90
87
  }); };
91
88
  this.extractErrorMessage = function (e) { return typeof e === 'string' ? e : e.message !== undefined && typeof e.message === 'string' ? e.message : ''; };
92
89
  this.onEachMessage = function (message) {
90
+ var body = (0, assert_1.assertNotUndefined)(message.Body, 'body is not present');
91
+ var subject = JSON.parse(body).Subject;
93
92
  if (_this.stopped) {
94
- _this.LOGGER.warn('stopped events proxy received message %o', message);
93
+ _this.LOGGER.warn('stopped events proxy received message with subject %s', subject);
95
94
  return;
96
95
  }
97
- var body = (0, assert_1.assertNotUndefined)(message.Body, 'body is not present');
98
- var json = JSON.parse(body);
99
- var attributes = json.MessageAttributes;
100
- var subject = json.Subject;
101
- var handlers = _this.handlers.filter(function (handler) { return handler.matcher(subject, attributes); });
96
+ var handlers = _this.handlers.filter(function (handler) { return handler.matcher(subject); });
102
97
  if (handlers.length === 0) {
103
- _this.LOGGER.warn('no handlers found for message %o', message);
98
+ _this.LOGGER.warn('no handlers found for subject %s, message %o', subject, message);
104
99
  }
105
- var record = _this.mapper(message);
106
100
  handlers.forEach(function (handler) {
107
- return handler
101
+ var record = (0, mappers_1.mapToLambdaSqsRecord)(message);
102
+ handler
108
103
  .handler({ Records: [record] })
109
104
  .then(function () {
110
- _this.LOGGER.debug('handler %s accepted message', handler.name);
105
+ var _a;
106
+ var json = JSON.parse(record.body);
107
+ var subject = json.Subject || ((_a = json.Message) === null || _a === void 0 ? void 0 : _a.eventname) || 'unknown';
108
+ _this.LOGGER.debug('subject accepted %s', subject);
111
109
  })
112
110
  .catch(function (e) {
113
111
  var error = _this.extractErrorMessage(e);
114
- _this.LOGGER.error(e, 'handler %s failed with %s', handler.name, error);
112
+ _this.LOGGER.error(e, 'failed %s with %s', subject, error);
115
113
  });
116
114
  });
117
115
  };
118
- this.stop = function () { return __awaiter(_this, void 0, void 0, function () { return __generator(this, function (_a) {
119
- return [2 /*return*/, (0, stoppable_1.stopConsumer)(this.pollingFrequency, this.consumer)];
120
- }); }); };
116
+ this.stop = function () { return __awaiter(_this, void 0, void 0, function () {
117
+ var _this = this;
118
+ return __generator(this, function (_a) {
119
+ return [2 /*return*/, Promise.resolve(this.consumer)
120
+ .then(function (consumer) { return consumer !== undefined ? (0, stoppable_1.stopConsumer)(consumer, _this.pollingFrequency).then(function () { return 'stopped'; }) : 'not started'; })
121
+ .then(function (status) { return _this.LOGGER.info(status); })];
122
+ });
123
+ }); };
121
124
  this.LOGGER = logging_1.LoggerFactory.create("SNS->SQS[".concat(name, "]"));
122
- this.LOGGER.debug('handling events from %s', topic !== null && topic !== void 0 ? topic : 'the event bus');
123
125
  }
124
126
  return EventsProxy;
125
127
  }());
@@ -16,7 +16,7 @@ export declare class HttpServer implements Lifecycle<string> {
16
16
  constructor(name: string, settings: HttpSettings, handler: (request: IncomingMessage, requestBody: string, response: ServerResponse) => void);
17
17
  start: () => Promise<string>;
18
18
  private endpointUrl;
19
- stop: () => Promise<any>;
19
+ stop: () => Promise<void>;
20
20
  }
21
21
  export type HttpSettings = {
22
22
  protocol: string;
@@ -15,13 +15,14 @@ var HttpServer = /** @class */ (function () {
15
15
  this.settings = settings;
16
16
  this.handler = handler;
17
17
  this.start = function () { return _this.server
18
- .then(function () { return _this.LOGGER.debug('listening [%s]', (0, assert_1.assertNotUndefined)(_this.address).port); })
18
+ .then(function () { return _this.LOGGER.info('listening on %s', (0, assert_1.assertNotUndefined)(_this.address).port); })
19
19
  .then(function () { return _this.endpointUrl(); }); };
20
20
  this.endpointUrl = function () {
21
21
  var address = (0, assert_1.assertNotUndefined)(_this.address, 'server not started');
22
22
  return "".concat(_this.protocol, "//").concat(address.address, ":").concat(address.port, "/");
23
23
  };
24
- this.stop = function () { return _this.server.then(function (server) { return server.close(); }).then(function () { return undefined; }); };
24
+ this.stop = function () { return _this.server.then(function (server) { return server.close(); })
25
+ .then(function () { return _this.LOGGER.info('stop %s', (0, assert_1.assertNotUndefined)(_this.address).port); }); };
25
26
  var server = (0, http_1.createServer)(function (req, res) {
26
27
  req.setEncoding('utf-8');
27
28
  var body = '';
@@ -1,22 +1,11 @@
1
1
  export { DevServer } from './dev-server';
2
2
  export { newHttpServer as httpServer } from './http-server';
3
- export { newLambdaHttpProxy as lambdaHttpProxy, UNAUTHORIZED } from './lambda-http-proxy';
3
+ export { newLambdaHttpProxy as lambdaHttpProxy } from './lambda-http-proxy';
4
4
  export { newSnsHttpProxy as snsHttpProxy } from './sns-http-proxy';
5
5
  export { newInternalQueue as internalQueue } from './internal-queue';
6
6
  export { newEventsProxy as eventsProxy } from './event-proxy';
7
7
  export { newScheduledTasks as scheduledTasks } from './scheduled-tasks';
8
8
  export { newPreTrafficHooks as preTrafficHooks } from './pre-traffic-hooks';
9
9
  export { newDynamoDbTable as dynamoDbTable } from './dynamodb';
10
- export { newContainer as container } from './container';
11
- export { newTunnel as tunnel } from './tunnel';
12
10
  export { all as allOf, oneThenOther } from './factories';
13
11
  export { lazy, promised } from './deferred';
14
- export { Lifecycle, Service } from './services';
15
- export { DevServerConfig } from './config';
16
- export { Route } from './lambda-http-proxy';
17
- export { mapToLambdaEvent as defaultApiGatewayLambdaMapper, mapToLambdaSqsRecord as defaultSqsLambdaMapper } from './mappers';
18
- declare global {
19
- interface Promise<T> {
20
- tap(onfulfilled?: (value: T) => void, onrejected?: (reason: unknown) => void): Promise<T>;
21
- }
22
- }
package/dist/src/index.js CHANGED
@@ -1,49 +1,12 @@
1
1
  "use strict";
2
- var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
3
- function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
4
- return new (P || (P = Promise))(function (resolve, reject) {
5
- function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
6
- function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
7
- function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
8
- step((generator = generator.apply(thisArg, _arguments || [])).next());
9
- });
10
- };
11
- var __generator = (this && this.__generator) || function (thisArg, body) {
12
- var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g;
13
- return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g;
14
- function verb(n) { return function (v) { return step([n, v]); }; }
15
- function step(op) {
16
- if (f) throw new TypeError("Generator is already executing.");
17
- while (g && (g = 0, op[0] && (_ = 0)), _) try {
18
- if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t;
19
- if (y = 0, t) op = [op[0] & 2, t.value];
20
- switch (op[0]) {
21
- case 0: case 1: t = op; break;
22
- case 4: _.label++; return { value: op[1], done: false };
23
- case 5: _.label++; y = op[1]; op = [0]; continue;
24
- case 7: op = _.ops.pop(); _.trys.pop(); continue;
25
- default:
26
- if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; }
27
- if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; }
28
- if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; }
29
- if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; }
30
- if (t[2]) _.ops.pop();
31
- _.trys.pop(); continue;
32
- }
33
- op = body.call(thisArg, _);
34
- } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; }
35
- if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };
36
- }
37
- };
38
2
  Object.defineProperty(exports, "__esModule", { value: true });
39
- exports.defaultSqsLambdaMapper = exports.defaultApiGatewayLambdaMapper = exports.Service = exports.promised = exports.lazy = exports.oneThenOther = exports.allOf = exports.tunnel = exports.container = exports.dynamoDbTable = exports.preTrafficHooks = exports.scheduledTasks = exports.eventsProxy = exports.internalQueue = exports.snsHttpProxy = exports.UNAUTHORIZED = exports.lambdaHttpProxy = exports.httpServer = exports.DevServer = void 0;
3
+ exports.promised = exports.lazy = exports.oneThenOther = exports.allOf = exports.dynamoDbTable = exports.preTrafficHooks = exports.scheduledTasks = exports.eventsProxy = exports.internalQueue = exports.snsHttpProxy = exports.lambdaHttpProxy = exports.httpServer = exports.DevServer = void 0;
40
4
  var dev_server_1 = require("./dev-server");
41
5
  Object.defineProperty(exports, "DevServer", { enumerable: true, get: function () { return dev_server_1.DevServer; } });
42
6
  var http_server_1 = require("./http-server");
43
7
  Object.defineProperty(exports, "httpServer", { enumerable: true, get: function () { return http_server_1.newHttpServer; } });
44
8
  var lambda_http_proxy_1 = require("./lambda-http-proxy");
45
9
  Object.defineProperty(exports, "lambdaHttpProxy", { enumerable: true, get: function () { return lambda_http_proxy_1.newLambdaHttpProxy; } });
46
- Object.defineProperty(exports, "UNAUTHORIZED", { enumerable: true, get: function () { return lambda_http_proxy_1.UNAUTHORIZED; } });
47
10
  var sns_http_proxy_1 = require("./sns-http-proxy");
48
11
  Object.defineProperty(exports, "snsHttpProxy", { enumerable: true, get: function () { return sns_http_proxy_1.newSnsHttpProxy; } });
49
12
  var internal_queue_1 = require("./internal-queue");
@@ -56,28 +19,9 @@ var pre_traffic_hooks_1 = require("./pre-traffic-hooks");
56
19
  Object.defineProperty(exports, "preTrafficHooks", { enumerable: true, get: function () { return pre_traffic_hooks_1.newPreTrafficHooks; } });
57
20
  var dynamodb_1 = require("./dynamodb");
58
21
  Object.defineProperty(exports, "dynamoDbTable", { enumerable: true, get: function () { return dynamodb_1.newDynamoDbTable; } });
59
- var container_1 = require("./container");
60
- Object.defineProperty(exports, "container", { enumerable: true, get: function () { return container_1.newContainer; } });
61
- var tunnel_1 = require("./tunnel");
62
- Object.defineProperty(exports, "tunnel", { enumerable: true, get: function () { return tunnel_1.newTunnel; } });
63
22
  var factories_1 = require("./factories");
64
23
  Object.defineProperty(exports, "allOf", { enumerable: true, get: function () { return factories_1.all; } });
65
24
  Object.defineProperty(exports, "oneThenOther", { enumerable: true, get: function () { return factories_1.oneThenOther; } });
66
25
  var deferred_1 = require("./deferred");
67
26
  Object.defineProperty(exports, "lazy", { enumerable: true, get: function () { return deferred_1.lazy; } });
68
27
  Object.defineProperty(exports, "promised", { enumerable: true, get: function () { return deferred_1.promised; } });
69
- var services_1 = require("./services");
70
- Object.defineProperty(exports, "Service", { enumerable: true, get: function () { return services_1.Service; } });
71
- var mappers_1 = require("./mappers");
72
- Object.defineProperty(exports, "defaultApiGatewayLambdaMapper", { enumerable: true, get: function () { return mappers_1.mapToLambdaEvent; } });
73
- Object.defineProperty(exports, "defaultSqsLambdaMapper", { enumerable: true, get: function () { return mappers_1.mapToLambdaSqsRecord; } });
74
- Promise.prototype.tap = function (onfulfilled, onrejected) {
75
- return __awaiter(this, void 0, void 0, function () {
76
- var _this = this;
77
- return __generator(this, function (_a) {
78
- return [2 /*return*/, this.then(onfulfilled, onrejected).then(function () { return __awaiter(_this, void 0, void 0, function () { return __generator(this, function (_a) {
79
- return [2 /*return*/, this];
80
- }); }); })];
81
- });
82
- });
83
- };
@@ -1,11 +1,8 @@
1
1
  import { Queue } from "./sqs";
2
- import { SQSEvent, SQSRecord } from "aws-lambda";
2
+ import { SQSEvent } from "aws-lambda";
3
3
  import { Service, Callback } from "./services";
4
- import { Message } from "@aws-sdk/client-sqs";
5
4
  export declare const newInternalQueue: (name: string, config: {
6
5
  index: number;
7
6
  visibility: number;
8
7
  handler: (queue: Queue) => (e: SQSEvent) => Promise<void>;
9
- fifo: boolean;
10
- mapper?: (message: Message) => SQSRecord;
11
8
  }, callback?: Callback<string>) => Service<string>;
@@ -42,19 +42,14 @@ var sqs_consumer_1 = require("sqs-consumer");
42
42
  var stoppable_1 = require("./stoppable");
43
43
  var mappers_1 = require("./mappers");
44
44
  var services_1 = require("./services");
45
- var newInternalQueue = function (name, config, callback) {
46
- var _a;
47
- return new services_1.Service(new InternalQueue(name, config.visibility, config.handler, config.index, function (sqs) { return config.fifo ? sqs.createFifoQueue : sqs.createStandardQueue; }, (_a = config.mapper) !== null && _a !== void 0 ? _a : mappers_1.mapToLambdaSqsRecord), callback);
48
- };
45
+ var newInternalQueue = function (name, config, callback) { return new services_1.Service(new InternalQueue(name, config.visibility, config.handler, config.index), callback); };
49
46
  exports.newInternalQueue = newInternalQueue;
50
47
  var InternalQueue = /** @class */ (function () {
51
- function InternalQueue(name, visibility, handler, index, creator, mapper) {
48
+ function InternalQueue(name, visibility, handler, index) {
52
49
  var _this = this;
53
50
  this.name = name;
54
51
  this.visibility = visibility;
55
52
  this.handler = handler;
56
- this.creator = creator;
57
- this.mapper = mapper;
58
53
  this.start = function (config) { return _this.create(config.sqs); };
59
54
  this.create = function (sqs) { return __awaiter(_this, void 0, void 0, function () {
60
55
  var _this = this;
@@ -73,7 +68,7 @@ var InternalQueue = /** @class */ (function () {
73
68
  waitTimeSeconds: visibility,
74
69
  sqs: sqs,
75
70
  handleMessage: function (message) { return __awaiter(_this, void 0, void 0, function () { return __generator(this, function (_a) {
76
- return [2 /*return*/, handler({ Records: [this.mapper(message)] })];
71
+ return [2 /*return*/, handler({ Records: [(0, mappers_1.mapToLambdaSqsRecord)(message)] })];
77
72
  }); }); },
78
73
  }))
79
74
  .then(function (consumer) {
@@ -94,7 +89,9 @@ var InternalQueue = /** @class */ (function () {
94
89
  .then(function () { return _this; })];
95
90
  });
96
91
  }); };
97
- this.stop = function () { return (0, stoppable_1.stopConsumer)(_this.state.visibility, _this.state.consumer); };
92
+ this.stop = function () { return Promise.resolve(_this.state)
93
+ .then(function (state) { return state !== undefined ? (0, stoppable_1.stopConsumer)(state.consumer, state.visibility).then(function () { return 'stopped'; }) : 'not started'; })
94
+ .then(function (status) { return _this.LOGGER.info(status); }); };
98
95
  this.queueName = (index + 1000).toString().padStart(10, '0');
99
96
  this.LOGGER = logging_1.LoggerFactory.create("INTERNALQUEUE[".concat(name, "]"));
100
97
  }
@@ -102,7 +99,8 @@ var InternalQueue = /** @class */ (function () {
102
99
  return __awaiter(this, void 0, void 0, function () {
103
100
  var _this = this;
104
101
  return __generator(this, function (_a) {
105
- return [2 /*return*/, this.creator(sqs)(name) //
102
+ return [2 /*return*/, sqs
103
+ .createNamedQueue(name) //
106
104
  .then(function (queue) {
107
105
  _this.LOGGER.info('created: %s', queue.url);
108
106
  return queue;
@@ -1,20 +1,13 @@
1
1
  import { HttpSettings } from "./http-server";
2
- import { APIGatewayEventDefaultAuthorizerContext, APIGatewayProxyEvent, APIGatewayProxyResult } from "aws-lambda";
3
- import { IncomingMessage } from "http";
2
+ import { APIGatewayProxyEvent, APIGatewayProxyResult } from "aws-lambda";
4
3
  import { Service, Callback } from "./services";
5
- export declare const UNAUTHORIZED: Error;
6
4
  export declare const newLambdaHttpProxy: (name: string, config: {
7
5
  settings: HttpSettings;
8
6
  routes: Route[];
9
- mapper?: (request: IncomingMessage, body: string) => Promise<APIGatewayProxyEvent>;
10
- authorizer?: Authorizer;
11
7
  }, callback?: Callback<string>) => Service<string>;
12
- export type Route = {
8
+ type Route = {
13
9
  method: RegExp;
14
10
  path: RegExp;
15
- weight: number;
16
- authorizer?: Authorizer;
17
11
  handler: (event: APIGatewayProxyEvent) => Promise<APIGatewayProxyResult>;
18
12
  };
19
- type Authorizer = (authorization: string) => Promise<APIGatewayEventDefaultAuthorizerContext | undefined>;
20
13
  export {};
@@ -36,51 +36,33 @@ var __generator = (this && this.__generator) || function (thisArg, body) {
36
36
  }
37
37
  };
38
38
  Object.defineProperty(exports, "__esModule", { value: true });
39
- exports.newLambdaHttpProxy = exports.UNAUTHORIZED = void 0;
39
+ exports.newLambdaHttpProxy = void 0;
40
40
  var logging_1 = require("@yopdev/logging");
41
41
  var http_server_1 = require("./http-server");
42
42
  var mappers_1 = require("./mappers");
43
43
  var responses_1 = require("./responses");
44
44
  var services_1 = require("./services");
45
- exports.UNAUTHORIZED = new Error('UNAUTHORIZED');
46
- var newLambdaHttpProxy = function (name, config, callback) {
47
- var _a, _b;
48
- return new services_1.Service(new LambdaHttpProxy(name, config.settings, config.routes, (_a = config.mapper) !== null && _a !== void 0 ? _a : mappers_1.mapToLambdaEvent, (_b = config.authorizer) !== null && _b !== void 0 ? _b : (function () { return Promise.resolve(undefined); })), callback);
49
- };
45
+ var newLambdaHttpProxy = function (name, config, callback) { return new services_1.Service(new LambdaHttpProxy(name, config.settings, config.routes), callback); };
50
46
  exports.newLambdaHttpProxy = newLambdaHttpProxy;
51
47
  var LambdaHttpProxy = /** @class */ (function () {
52
- function LambdaHttpProxy(name, settings, routes, mapper, defaultAuthorizer) {
48
+ function LambdaHttpProxy(name, settings, routes) {
53
49
  var _this = this;
54
50
  this.name = name;
55
51
  this.routes = routes;
56
- this.mapper = mapper;
57
- this.defaultAuthorizer = defaultAuthorizer;
58
52
  this.start = function () { return _this.server.start(); };
59
- this.stop = function () { return _this.server.stop(); };
60
- this.handler = function (authorizer, lambdaHandler) {
53
+ this.stop = function () { return _this.server.stop()
54
+ .then(function () { return _this.LOGGER.info('stopped'); }); };
55
+ this.handler = function (lambdaHandler) {
61
56
  return function (request, body, response) {
62
- return _this.mapper(request, body)
63
- .then(function (proxyEvent) { return __awaiter(_this, void 0, void 0, function () {
64
- var _this = this;
65
- return __generator(this, function (_a) {
66
- return [2 /*return*/, authorizer(proxyEvent.headers['authorization'])
67
- .then(function (context) { return __awaiter(_this, void 0, void 0, function () {
68
- var _this = this;
69
- return __generator(this, function (_a) {
70
- proxyEvent.requestContext.authorizer = context;
71
- return [2 /*return*/, lambdaHandler(proxyEvent)
72
- .then(function (lambda) {
73
- var _a, _b, _c, _d, _e, _f;
74
- return (0, responses_1.writeResponse)(response, lambda.statusCode, lambda.body, (_c = (_b = (_a = lambda.headers) === null || _a === void 0 ? void 0 : _a['Content-Type']) === null || _b === void 0 ? void 0 : _b.toString()) !== null && _c !== void 0 ? _c : undefined, (_f = (_e = (_d = lambda.headers) === null || _d === void 0 ? void 0 : _d['Location']) === null || _e === void 0 ? void 0 : _e.toString()) !== null && _f !== void 0 ? _f : undefined);
75
- })
76
- .catch(function (e) {
77
- _this.LOGGER.error(e, 'request failed to execute');
78
- (0, responses_1.internalServerError)(response, e.body);
79
- })];
80
- });
81
- }); }, function (e) { return e === exports.UNAUTHORIZED ? (0, responses_1.writeResponse)(response, 401, '') : (0, responses_1.internalServerError)(response, e); })];
82
- });
83
- }); });
57
+ return lambdaHandler((0, mappers_1.mapToLambdaEvent)(request, body))
58
+ .then(function (lambda) {
59
+ var _a, _b, _c, _d, _e, _f;
60
+ return (0, responses_1.writeResponse)(response, lambda.statusCode, lambda.body, (_c = (_b = (_a = lambda.headers) === null || _a === void 0 ? void 0 : _a['Content-Type']) === null || _b === void 0 ? void 0 : _b.toString()) !== null && _c !== void 0 ? _c : undefined, (_f = (_e = (_d = lambda.headers) === null || _d === void 0 ? void 0 : _d['Location']) === null || _e === void 0 ? void 0 : _e.toString()) !== null && _f !== void 0 ? _f : undefined);
61
+ })
62
+ .catch(function (e) {
63
+ _this.LOGGER.error(e, 'request failed to execute');
64
+ (0, responses_1.internalServerError)(response, e.body);
65
+ });
84
66
  };
85
67
  };
86
68
  this.fallback = function (request, _, response) { return __awaiter(_this, void 0, void 0, function () {
@@ -94,13 +76,12 @@ var LambdaHttpProxy = /** @class */ (function () {
94
76
  var _a;
95
77
  return ((_a = _this.routes.filter(function (r) { return request.method.match(r.method); })
96
78
  .filter(function (r) { return request.url.match(r.path); })
97
- .sort(function (r1, r2) { return r2.weight - r1.weight; })
98
- .map(function (r) { var _a; return _this.handler((_a = r.authorizer) !== null && _a !== void 0 ? _a : _this.defaultAuthorizer, r.handler); })
79
+ .sort(function (r1, r2) { return r2.path.source.length - r1.path.source.length; })
80
+ .map(function (r) { return _this.handler(r.handler); })
99
81
  .find(function () { return true; })) !== null && _a !== void 0 ? _a : _this.fallback)(request, body, response);
100
82
  };
101
83
  this.server = new http_server_1.HttpServer(name, settings, this.resolveRoute);
102
84
  this.LOGGER = logging_1.LoggerFactory.create("HTTP->LAMBDA[".concat(this.name, "]"));
103
- this.LOGGER.info('registered %i routes', routes.length);
104
85
  }
105
86
  return LambdaHttpProxy;
106
87
  }());
@@ -57,13 +57,12 @@ var LocalStack = /** @class */ (function () {
57
57
  accessKeyId: 'dummy',
58
58
  secretAccessKey: 'dummy'
59
59
  }
60
- }); })
61
- .tap(function () { return LOGGER.debug('started'); })];
60
+ }); })];
62
61
  });
63
62
  }); };
64
63
  this.stop = function () { return Promise.resolve(_this.started)
65
64
  .then(function (container) { return container ? container.stop().then(function () { return 'stopped'; }) : 'not started'; })
66
- .then(function (status) { return LOGGER.debug(status); }); };
65
+ .then(function (status) { return LOGGER.info(status); }); };
67
66
  var concreteConfig = this.configOrDefaults(config);
68
67
  var container = new testcontainers_1.GenericContainer(concreteConfig.localStackDockerImage);
69
68
  var localStatePath = concreteConfig.localStateBindMount;
@@ -84,6 +83,7 @@ var LocalStack = /** @class */ (function () {
84
83
  .start()
85
84
  .then(function (container) { return _this.started = container; })
86
85
  .then(function (container) { return "".concat(PROTOCOL, "://").concat(container.getHost(), ":").concat(container.getMappedPort(SERVICES_PORT)); }); };
86
+ LOGGER.debug('initialized');
87
87
  }
88
88
  LocalStack.prototype.configOrDefaults = function (config) {
89
89
  var selectedServicesPort = config === null || config === void 0 ? void 0 : config.boundServicesPort;
@@ -3,4 +3,4 @@ import { Message } from "@aws-sdk/client-sqs";
3
3
  import { APIGatewayProxyEvent, SQSRecord } from "aws-lambda";
4
4
  import { IncomingMessage } from "http";
5
5
  export declare const mapToLambdaSqsRecord: (message: Message) => SQSRecord;
6
- export declare function mapToLambdaEvent(req: IncomingMessage, requestBody: string): Promise<APIGatewayProxyEvent>;
6
+ export declare function mapToLambdaEvent(req: IncomingMessage, requestBody: string): APIGatewayProxyEvent;
@@ -1,10 +1,12 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
3
  exports.mapToLambdaEvent = exports.mapToLambdaSqsRecord = void 0;
4
+ var logging_1 = require("@yopdev/logging");
4
5
  var url_1 = require("url");
6
+ var LOGGER = logging_1.LoggerFactory.create('MAPPERS');
5
7
  var mapToLambdaSqsRecord = function (message) {
6
8
  if (!message.Body)
7
- throw new Error('message Body must be present');
9
+ throw new Error("message Body must be present: ".concat(message.Body));
8
10
  return {
9
11
  messageId: 'N/A',
10
12
  receiptHandle: 'N/A',
@@ -26,17 +28,16 @@ exports.mapToLambdaSqsRecord = mapToLambdaSqsRecord;
26
28
  function mapToLambdaEvent(req, requestBody) {
27
29
  if (!req.url || !req.method)
28
30
  throw new Error('url and method are required');
29
- var url = new url_1.URL(req.url, "http://".concat(req.headers.host));
31
+ var url = new url_1.URL(decodeURIComponent(req.url), "http://".concat(req.headers.host));
30
32
  var qsp = {};
31
- url.searchParams.forEach(function (v, k) { return (qsp[k] = decodeURIComponent(v)); });
33
+ url.searchParams.forEach(function (v, k) { return (qsp[k] = v); });
34
+ var claims = extractClaims(req);
32
35
  var headers = {};
33
36
  if (req.headers['content-type'])
34
- headers['content-type'] = req.headers['content-type'];
37
+ headers['Content-Type'] = req.headers['content-type'];
35
38
  if (req.headers['accept'])
36
- headers['accept'] = req.headers['accept'];
37
- if (req.headers['authorization'])
38
- headers['authorization'] = req.headers['authorization'];
39
- return Promise.resolve({
39
+ headers['Accept'] = req.headers['accept'];
40
+ return {
40
41
  httpMethod: req.method,
41
42
  body: requestBody,
42
43
  headers: headers,
@@ -51,7 +52,7 @@ function mapToLambdaEvent(req, requestBody) {
51
52
  requestContext: {
52
53
  accountId: '',
53
54
  apiId: '',
54
- authorizer: undefined,
55
+ authorizer: { claims: claims },
55
56
  httpMethod: '',
56
57
  identity: {
57
58
  accessKey: '',
@@ -84,6 +85,17 @@ function mapToLambdaEvent(req, requestBody) {
84
85
  resourcePath: '',
85
86
  stage: '',
86
87
  },
87
- });
88
+ };
88
89
  }
89
90
  exports.mapToLambdaEvent = mapToLambdaEvent;
91
+ function extractClaims(req) {
92
+ var _a;
93
+ var jwt = (_a = req.headers['authorization']) === null || _a === void 0 ? void 0 : _a.replace('Bearer ', '');
94
+ try {
95
+ return jwt ? JSON.parse(atob(jwt.split('.')[1])) : null;
96
+ }
97
+ catch (e) {
98
+ LOGGER.warn('Invalid token, claims could not be extracted: %O', jwt);
99
+ return undefined;
100
+ }
101
+ }