idea-aws 3.11.8 → 3.12.1

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.
File without changes
package/dist/index.js CHANGED
@@ -1,13 +1,29 @@
1
- export * from './src/genericController';
2
- export * from './src/resourceController';
3
- export * from './src/streamController';
4
- export * from './src/dynamoDB';
5
- export * from './src/cognito';
6
- export * from './src/comprehend';
7
- export * from './src/s3';
8
- export * from './src/secretsManager';
9
- export * from './src/ses';
10
- export * from './src/sns';
11
- export * from './src/translate';
12
- export * from './src/attachments';
13
- export * from './src/logger';
1
+ "use strict";
2
+ var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
3
+ if (k2 === undefined) k2 = k;
4
+ var desc = Object.getOwnPropertyDescriptor(m, k);
5
+ if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
6
+ desc = { enumerable: true, get: function() { return m[k]; } };
7
+ }
8
+ Object.defineProperty(o, k2, desc);
9
+ }) : (function(o, m, k, k2) {
10
+ if (k2 === undefined) k2 = k;
11
+ o[k2] = m[k];
12
+ }));
13
+ var __exportStar = (this && this.__exportStar) || function(m, exports) {
14
+ for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports, p)) __createBinding(exports, m, p);
15
+ };
16
+ Object.defineProperty(exports, "__esModule", { value: true });
17
+ __exportStar(require("./src/genericController"), exports);
18
+ __exportStar(require("./src/resourceController"), exports);
19
+ __exportStar(require("./src/streamController"), exports);
20
+ __exportStar(require("./src/dynamoDB"), exports);
21
+ __exportStar(require("./src/cognito"), exports);
22
+ __exportStar(require("./src/comprehend"), exports);
23
+ __exportStar(require("./src/s3"), exports);
24
+ __exportStar(require("./src/secretsManager"), exports);
25
+ __exportStar(require("./src/ses"), exports);
26
+ __exportStar(require("./src/sns"), exports);
27
+ __exportStar(require("./src/translate"), exports);
28
+ __exportStar(require("./src/attachments"), exports);
29
+ __exportStar(require("./src/logger"), exports);
@@ -1,17 +1,20 @@
1
- import { DynamoDB } from './dynamoDB';
2
- import { S3 } from './s3';
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.Attachments = void 0;
4
+ const dynamoDB_1 = require("./dynamoDB");
5
+ const s3_1 = require("./s3");
3
6
  /**
4
7
  * A custom class that takes advantage of DynamoDB and S3 to easily manage attachments.
5
8
  */
6
- export class Attachments {
9
+ class Attachments {
7
10
  constructor() {
8
11
  /**
9
12
  * The bucket where from to retrieve the attachments. Fallback to IDEA's default one.
10
13
  */
11
14
  this.S3_ATTACHMENTS_BUCKET = process.env['S3_ATTACHMENTS_BUCKET'] || 'idea-attachments';
12
15
  this.IUID_ATTACHMENTS_PREFIX = process.env['IUID_ATTACHMENTS_PREFIX'] || 'ATT';
13
- this.dynamo = new DynamoDB();
14
- this.s3 = new S3();
16
+ this.dynamo = new dynamoDB_1.DynamoDB();
17
+ this.s3 = new s3_1.S3();
15
18
  }
16
19
  /**
17
20
  * Get a signedURL to put an attachment.
@@ -32,3 +35,4 @@ export class Attachments {
32
35
  return signedURL;
33
36
  }
34
37
  }
38
+ exports.Attachments = Attachments;
@@ -33,12 +33,17 @@ export declare class Cognito {
33
33
  */
34
34
  getUserBySub(sub: string, cognitoUserPoolId: string): Promise<CognitoUserGeneric>;
35
35
  /**
36
- * Get all the users of the pool.
36
+ * List all the users of the pool.
37
37
  */
38
- getAllUsers(cognitoUserPoolId: string, options?: {
38
+ listUsers(cognitoUserPoolId: string, options?: {
39
39
  pagination?: string;
40
40
  users: CognitoUser[];
41
41
  }): Promise<CognitoUser[]>;
42
+ /**
43
+ * List all the users of the pool, including the information about the groups they're in.
44
+ * Note: it's slower than the alternative `getAllUsers`: use it only when needed.
45
+ */
46
+ listUsersWithGroupsDetail(cognitoUserPoolId: string): Promise<CognitoUser[]>;
42
47
  /**
43
48
  * Create a new user (by its email) in the pool specified.
44
49
  * @return userId of the new user
@@ -83,7 +88,10 @@ export declare class Cognito {
83
88
  /**
84
89
  * List the groups of the user pool.
85
90
  */
86
- listGroups(cognitoUserPoolId: string): Promise<CognitoGroup[]>;
91
+ listGroups(cognitoUserPoolId: string, options?: {
92
+ pagination?: string;
93
+ groups: CognitoGroup[];
94
+ }): Promise<CognitoGroup[]>;
87
95
  /**
88
96
  * Create a new group in the user pool.
89
97
  */
@@ -95,7 +103,10 @@ export declare class Cognito {
95
103
  /**
96
104
  * List the users part of a group in the user pool.
97
105
  */
98
- listUsersInGroup(group: string, cognitoUserPoolId: string): Promise<CognitoUser[]>;
106
+ listUsersInGroup(group: string, cognitoUserPoolId: string, options?: {
107
+ pagination?: string;
108
+ users: CognitoUser[];
109
+ }): Promise<CognitoUser[]>;
99
110
  /**
100
111
  * Add a user (by email) to a group in the user pool.
101
112
  */
@@ -1,11 +1,14 @@
1
- import { CognitoIdentityServiceProvider } from 'aws-sdk';
2
- import { CognitoUser, isEmpty } from 'idea-toolbox';
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.Cognito = void 0;
4
+ const aws_sdk_1 = require("aws-sdk");
5
+ const idea_toolbox_1 = require("idea-toolbox");
3
6
  /**
4
7
  * A wrapper for AWS Cognito.
5
8
  */
6
- export class Cognito {
9
+ class Cognito {
7
10
  constructor(params = {}) {
8
- this.cognito = new CognitoIdentityServiceProvider({ apiVersion: '2016-04-18', region: params.region });
11
+ this.cognito = new aws_sdk_1.CognitoIdentityServiceProvider({ apiVersion: '2016-04-18', region: params.region });
9
12
  }
10
13
  /**
11
14
  * Change the region in which to find the user pool.
@@ -13,7 +16,7 @@ export class Cognito {
13
16
  */
14
17
  setRegion(region) {
15
18
  // there is no quick way to change the region without re-creating the object
16
- this.cognito = new CognitoIdentityServiceProvider({ apiVersion: this.cognito.config.apiVersion, region });
19
+ this.cognito = new aws_sdk_1.CognitoIdentityServiceProvider({ apiVersion: this.cognito.config.apiVersion, region });
17
20
  }
18
21
  /**
19
22
  * Get the attributes of the user, from the authorizer claims.
@@ -67,20 +70,41 @@ export class Cognito {
67
70
  return this.mapCognitoUserAttributesAsPlainObject(user);
68
71
  }
69
72
  /**
70
- * Get all the users of the pool.
73
+ * List all the users of the pool.
71
74
  */
72
- async getAllUsers(cognitoUserPoolId, options = { users: [] }) {
75
+ async listUsers(cognitoUserPoolId, options = { users: [] }) {
73
76
  const params = { UserPoolId: cognitoUserPoolId };
74
77
  if (options.pagination)
75
78
  params.PaginationToken = options.pagination;
76
79
  const res = await this.cognito.listUsers(params).promise();
77
80
  const pagination = res.PaginationToken;
78
- const users = options.users.concat(res.Users.map(u => new CognitoUser(this.mapCognitoUserAttributesAsPlainObject(u))));
81
+ const users = options.users.concat(res.Users.map(u => new idea_toolbox_1.CognitoUser(this.mapCognitoUserAttributesAsPlainObject(u))));
79
82
  if (pagination)
80
- return await this.getAllUsers(cognitoUserPoolId, { pagination, users });
83
+ return await this.listUsers(cognitoUserPoolId, { pagination, users });
81
84
  else
82
85
  return users;
83
86
  }
87
+ /**
88
+ * List all the users of the pool, including the information about the groups they're in.
89
+ * Note: it's slower than the alternative `getAllUsers`: use it only when needed.
90
+ */
91
+ async listUsersWithGroupsDetail(cognitoUserPoolId) {
92
+ const groups = await this.listGroups(cognitoUserPoolId);
93
+ const users = [];
94
+ for (const group of groups) {
95
+ const usersOfGroup = await this.listUsersInGroup(group.name, cognitoUserPoolId);
96
+ usersOfGroup.forEach(userInGroup => {
97
+ const userAlreadyInOutputList = users.find(u => u.userId === userInGroup.userId);
98
+ if (userAlreadyInOutputList)
99
+ userAlreadyInOutputList.groups.push(group.name);
100
+ else {
101
+ userInGroup.groups.push(group.name);
102
+ users.push(userInGroup);
103
+ }
104
+ });
105
+ }
106
+ return users;
107
+ }
84
108
  /**
85
109
  * Create a new user (by its email) in the pool specified.
86
110
  * @return userId of the new user
@@ -89,7 +113,7 @@ export class Cognito {
89
113
  const email = typeof cognitoUserOrEmail === 'string'
90
114
  ? cognitoUserOrEmail
91
115
  : cognitoUserOrEmail.email;
92
- if (isEmpty(email, 'email'))
116
+ if ((0, idea_toolbox_1.isEmpty)(email, 'email'))
93
117
  throw new Error('INVALID_EMAIL');
94
118
  const UserAttributes = [
95
119
  { Name: 'email', Value: email },
@@ -121,7 +145,7 @@ export class Cognito {
121
145
  * Resend the password to a user who never logged in.
122
146
  */
123
147
  async resendPassword(email, cognitoUserPoolId, options = {}) {
124
- if (isEmpty(email, 'email'))
148
+ if ((0, idea_toolbox_1.isEmpty)(email, 'email'))
125
149
  throw new Error('Invalid email');
126
150
  const params = {
127
151
  UserPoolId: cognitoUserPoolId,
@@ -136,7 +160,7 @@ export class Cognito {
136
160
  * Delete a user by its email (username), in the pool specified.
137
161
  */
138
162
  async deleteUser(email, cognitoUserPoolId) {
139
- if (isEmpty(email, 'email'))
163
+ if ((0, idea_toolbox_1.isEmpty)(email, 'email'))
140
164
  throw new Error('Invalid email');
141
165
  await this.cognito.adminDeleteUser({ UserPoolId: cognitoUserPoolId, Username: email }).promise();
142
166
  }
@@ -178,7 +202,7 @@ export class Cognito {
178
202
  * Change the email address (== username) associated to a user.
179
203
  */
180
204
  async updateEmail(email, newEmail, cognitoUserPoolId) {
181
- if (isEmpty(newEmail, 'email'))
205
+ if ((0, idea_toolbox_1.isEmpty)(newEmail, 'email'))
182
206
  throw new Error('Invalid new email');
183
207
  await this.cognito
184
208
  .adminUpdateUserAttributes({
@@ -247,10 +271,17 @@ export class Cognito {
247
271
  /**
248
272
  * List the groups of the user pool.
249
273
  */
250
- async listGroups(cognitoUserPoolId) {
251
- const groupsList = await this.cognito.listGroups({ UserPoolId: cognitoUserPoolId }).promise();
252
- const groups = groupsList.Groups.map(g => ({ name: g.GroupName, description: g.Description }));
253
- return groups;
274
+ async listGroups(cognitoUserPoolId, options = { groups: [] }) {
275
+ const params = { UserPoolId: cognitoUserPoolId };
276
+ if (options.pagination)
277
+ params.NextToken = options.pagination;
278
+ const res = await this.cognito.listGroups(params).promise();
279
+ const pagination = res.NextToken;
280
+ const groups = options.groups.concat(res.Groups.map(g => ({ name: g.GroupName, description: g.Description })));
281
+ if (pagination)
282
+ return await this.listGroups(cognitoUserPoolId, { pagination, groups });
283
+ else
284
+ return groups;
254
285
  }
255
286
  /**
256
287
  * Create a new group in the user pool.
@@ -267,18 +298,26 @@ export class Cognito {
267
298
  /**
268
299
  * List the users part of a group in the user pool.
269
300
  */
270
- async listUsersInGroup(group, cognitoUserPoolId) {
271
- const usersInGroupList = await this.cognito
272
- .listUsersInGroup({ UserPoolId: cognitoUserPoolId, GroupName: group })
273
- .promise();
274
- const users = usersInGroupList.Users.map(u => new CognitoUser(this.mapCognitoUserAttributesAsPlainObject(u)));
275
- return users;
301
+ async listUsersInGroup(group, cognitoUserPoolId, options = { users: [] }) {
302
+ const params = {
303
+ UserPoolId: cognitoUserPoolId,
304
+ GroupName: group
305
+ };
306
+ if (options.pagination)
307
+ params.NextToken = options.pagination;
308
+ const res = await this.cognito.listUsersInGroup(params).promise();
309
+ const pagination = res.NextToken;
310
+ const users = options.users.concat(res.Users.map(u => new idea_toolbox_1.CognitoUser(this.mapCognitoUserAttributesAsPlainObject(u))));
311
+ if (pagination)
312
+ return await this.listUsersInGroup(group, cognitoUserPoolId, { pagination, users });
313
+ else
314
+ return users;
276
315
  }
277
316
  /**
278
317
  * Add a user (by email) to a group in the user pool.
279
318
  */
280
319
  async addUserToGroup(email, group, cognitoUserPoolId) {
281
- const user = new CognitoUser(await this.getUserByEmail(email, cognitoUserPoolId));
320
+ const user = new idea_toolbox_1.CognitoUser(await this.getUserByEmail(email, cognitoUserPoolId));
282
321
  await this.cognito
283
322
  .adminAddUserToGroup({ UserPoolId: cognitoUserPoolId, GroupName: group, Username: user.userId })
284
323
  .promise();
@@ -287,9 +326,10 @@ export class Cognito {
287
326
  * Remove a user (by email) from a group in the user pool.
288
327
  */
289
328
  async removeUserFromGroup(email, group, cognitoUserPoolId) {
290
- const user = new CognitoUser(await this.getUserByEmail(email, cognitoUserPoolId));
329
+ const user = new idea_toolbox_1.CognitoUser(await this.getUserByEmail(email, cognitoUserPoolId));
291
330
  await this.cognito
292
331
  .adminRemoveUserFromGroup({ UserPoolId: cognitoUserPoolId, GroupName: group, Username: user.userId })
293
332
  .promise();
294
333
  }
295
334
  }
335
+ exports.Cognito = Cognito;
@@ -1,10 +1,13 @@
1
- import { Comprehend as AmazonComprehend } from 'aws-sdk';
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.Comprehend = void 0;
4
+ const aws_sdk_1 = require("aws-sdk");
2
5
  /**
3
6
  * A wrapper for Amazon Comprehend.
4
7
  */
5
- export class Comprehend {
8
+ class Comprehend {
6
9
  constructor() {
7
- this.comprehend = new AmazonComprehend({ apiVersion: '2017-11-27' });
10
+ this.comprehend = new aws_sdk_1.Comprehend({ apiVersion: '2017-11-27' });
8
11
  }
9
12
  /**
10
13
  * Inspects text and returns an inference of the prevailing sentiment (POSITIVE, NEUTRAL, MIXED, or NEGATIVE).
@@ -18,3 +21,4 @@ export class Comprehend {
18
21
  return result.Sentiment;
19
22
  }
20
23
  }
24
+ exports.Comprehend = Comprehend;
@@ -1,22 +1,25 @@
1
- import { DynamoDB as DDB } from 'aws-sdk';
2
- import { v4 as UUIDV4 } from 'uuid';
3
- import { customAlphabet as AlphabetNanoID } from 'nanoid';
4
- const NanoID = AlphabetNanoID('0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz', 25);
5
- import { characters as ShortIdCharacters, generate as ShortIdGenerate } from 'shortid';
6
- import { Logger } from './logger';
7
- const logger = new Logger();
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.DynamoDB = void 0;
4
+ const aws_sdk_1 = require("aws-sdk");
5
+ const uuid_1 = require("uuid");
6
+ const nanoid_1 = require("nanoid");
7
+ const NanoID = (0, nanoid_1.customAlphabet)('0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz', 25);
8
+ const shortid_1 = require("shortid");
9
+ const logger_1 = require("./logger");
10
+ const logger = new logger_1.Logger();
8
11
  /**
9
12
  * A wrapper for AWS DynamoDB.
10
13
  */
11
- export class DynamoDB {
14
+ class DynamoDB {
12
15
  constructor() {
13
- this.dynamo = new DDB.DocumentClient();
16
+ this.dynamo = new aws_sdk_1.DynamoDB.DocumentClient();
14
17
  }
15
18
  /**
16
19
  * Convert a JSON object from dynamoDB format to simple JSON.
17
20
  */
18
21
  unmarshall(data, options) {
19
- return DDB.Converter.unmarshall(data, options);
22
+ return aws_sdk_1.DynamoDB.Converter.unmarshall(data, options);
20
23
  }
21
24
  /**
22
25
  * Returns an IUID: IDEA's Unique IDentifier, which is an id unique through all IDEA's projects.
@@ -67,13 +70,13 @@ export class DynamoDB {
67
70
  result = `${project}_${id}`;
68
71
  break;
69
72
  case 'IUID':
70
- id = UUIDV4();
73
+ id = (0, uuid_1.v4)();
71
74
  result = `${project}_${id}`;
72
75
  break;
73
76
  case 'ISID':
74
77
  // avoid _ characters (to avoid concatenation problems with ids) -- it must be anyway 64 chars-long
75
- ShortIdCharacters('0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ-@');
76
- id = ShortIdGenerate();
78
+ (0, shortid_1.characters)('0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ-@');
79
+ id = (0, shortid_1.generate)();
77
80
  result = id;
78
81
  break;
79
82
  }
@@ -302,3 +305,4 @@ export class DynamoDB {
302
305
  return this.dynamo.createSet(array, options);
303
306
  }
304
307
  }
308
+ exports.DynamoDB = DynamoDB;
@@ -1,24 +1,27 @@
1
- import { DynamoDB } from './dynamoDB';
2
- import { Cognito } from './cognito';
3
- import { S3 } from './s3';
4
- import { SES } from './ses';
5
- import { SNS } from './sns';
6
- import { Translate } from './translate';
7
- import { Comprehend } from './comprehend';
8
- import { SecretsManager } from './secretsManager';
9
- import { Attachments } from './attachments';
10
- import { Logger } from './logger';
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.GenericController = void 0;
4
+ const dynamoDB_1 = require("./dynamoDB");
5
+ const cognito_1 = require("./cognito");
6
+ const s3_1 = require("./s3");
7
+ const ses_1 = require("./ses");
8
+ const sns_1 = require("./sns");
9
+ const translate_1 = require("./translate");
10
+ const comprehend_1 = require("./comprehend");
11
+ const secretsManager_1 = require("./secretsManager");
12
+ const attachments_1 = require("./attachments");
13
+ const logger_1 = require("./logger");
11
14
  /**
12
15
  * An abstract class to inherit to manage some resources with an AWS Lambda function.
13
16
  */
14
- export class GenericController {
17
+ class GenericController {
15
18
  /**
16
19
  * Initialize a new GenericController helper object.
17
20
  * @param event the event that invoked the AWS lambda function
18
21
  * @param callback the callback to resolve or reject the execution
19
22
  */
20
23
  constructor(event, callback, options = {}) {
21
- this.logger = new Logger();
24
+ this.logger = new logger_1.Logger();
22
25
  this.event = event;
23
26
  this.callback = callback;
24
27
  this.tables = options.tables || {};
@@ -41,7 +44,7 @@ export class GenericController {
41
44
  */
42
45
  get dynamoDB() {
43
46
  if (!this._dynamoDB)
44
- this._dynamoDB = new DynamoDB();
47
+ this._dynamoDB = new dynamoDB_1.DynamoDB();
45
48
  return this._dynamoDB;
46
49
  }
47
50
  set dynamoDB(dynamoDB) {
@@ -52,7 +55,7 @@ export class GenericController {
52
55
  */
53
56
  get cognito() {
54
57
  if (!this._cognito)
55
- this._cognito = new Cognito();
58
+ this._cognito = new cognito_1.Cognito();
56
59
  return this._cognito;
57
60
  }
58
61
  set cognito(cognito) {
@@ -63,7 +66,7 @@ export class GenericController {
63
66
  */
64
67
  get s3() {
65
68
  if (!this._s3)
66
- this._s3 = new S3();
69
+ this._s3 = new s3_1.S3();
67
70
  return this._s3;
68
71
  }
69
72
  set s3(s3) {
@@ -74,7 +77,7 @@ export class GenericController {
74
77
  */
75
78
  get ses() {
76
79
  if (!this._ses)
77
- this._ses = new SES();
80
+ this._ses = new ses_1.SES();
78
81
  return this._ses;
79
82
  }
80
83
  set ses(ses) {
@@ -85,7 +88,7 @@ export class GenericController {
85
88
  */
86
89
  get sns() {
87
90
  if (!this._sns)
88
- this._sns = new SNS();
91
+ this._sns = new sns_1.SNS();
89
92
  return this._sns;
90
93
  }
91
94
  set sns(sns) {
@@ -96,7 +99,7 @@ export class GenericController {
96
99
  */
97
100
  get translate() {
98
101
  if (!this._translate)
99
- this._translate = new Translate();
102
+ this._translate = new translate_1.Translate();
100
103
  return this._translate;
101
104
  }
102
105
  set translate(translate) {
@@ -107,7 +110,7 @@ export class GenericController {
107
110
  */
108
111
  get comprehend() {
109
112
  if (!this._comprehend)
110
- this._comprehend = new Comprehend();
113
+ this._comprehend = new comprehend_1.Comprehend();
111
114
  return this._comprehend;
112
115
  }
113
116
  set comprehend(comprehend) {
@@ -118,7 +121,7 @@ export class GenericController {
118
121
  */
119
122
  get secrets() {
120
123
  if (!this._secrets)
121
- this._secrets = new SecretsManager();
124
+ this._secrets = new secretsManager_1.SecretsManager();
122
125
  return this._secrets;
123
126
  }
124
127
  set secrets(secrets) {
@@ -133,10 +136,11 @@ export class GenericController {
133
136
  */
134
137
  get attachments() {
135
138
  if (!this._attachments)
136
- this._attachments = new Attachments();
139
+ this._attachments = new attachments_1.Attachments();
137
140
  return this._attachments;
138
141
  }
139
142
  set attachments(attachments) {
140
143
  this._attachments = attachments;
141
144
  }
142
145
  }
146
+ exports.GenericController = GenericController;
@@ -1,7 +1,10 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.Logger = void 0;
1
4
  /**
2
5
  * Manage structured logging.
3
6
  */
4
- export class Logger {
7
+ class Logger {
5
8
  constructor({ level = process.env.LOG_LEVEL } = {}) {
6
9
  this.level = (level || 'DEBUG').toUpperCase();
7
10
  this.originalLevel = this.level;
@@ -45,5 +48,6 @@ export class Logger {
45
48
  this.level = this.originalLevel;
46
49
  }
47
50
  }
51
+ exports.Logger = Logger;
48
52
  // levels here are identical to bunyan practices (https://github.com/trentm/node-bunyan#levels)
49
53
  const LogLevels = { DEBUG: 20, INFO: 30, WARN: 40, ERROR: 50 };
@@ -1,16 +1,19 @@
1
- import 'source-map-support/register';
2
- import { existsSync, readFileSync } from 'fs';
3
- import { Lambda, EventBridge } from 'aws-sdk';
4
- import { APIRequestLog, CognitoUser } from 'idea-toolbox';
5
- import { Logger } from './logger';
6
- import { GenericController } from './genericController';
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.RCError = exports.ResourceController = void 0;
4
+ require("source-map-support/register");
5
+ const fs_1 = require("fs");
6
+ const aws_sdk_1 = require("aws-sdk");
7
+ const idea_toolbox_1 = require("idea-toolbox");
8
+ const logger_1 = require("./logger");
9
+ const genericController_1 = require("./genericController");
7
10
  /**
8
11
  * An abstract class to inherit to manage API requests (AWS API Gateway) in an AWS Lambda function.
9
12
  */
10
- export class ResourceController extends GenericController {
13
+ class ResourceController extends genericController_1.GenericController {
11
14
  constructor(event, callback, options = {}) {
12
15
  super(event, callback, options);
13
- this.logger = new Logger();
16
+ this.logger = new logger_1.Logger();
14
17
  this.templateMatcher = /{{\s?([^{}\s]*)\s?}}/g;
15
18
  ///
16
19
  /// REQUEST HANDLERS
@@ -106,7 +109,7 @@ export class ResourceController extends GenericController {
106
109
  const authorizer = event.requestContext?.authorizer ?? {};
107
110
  const contextFromAuthorizer = authorizer.lambda ?? authorizer.jwt?.claims ?? {};
108
111
  this.principalId = contextFromAuthorizer.principalId ?? contextFromAuthorizer.sub ?? null;
109
- this.cognitoUser = authorizer.jwt?.claims ? new CognitoUser(authorizer.jwt?.claims) : null;
112
+ this.cognitoUser = authorizer.jwt?.claims ? new idea_toolbox_1.CognitoUser(authorizer.jwt?.claims) : null;
110
113
  this.stage = event.requestContext.stage;
111
114
  this.httpMethod = event.requestContext.http.method;
112
115
  this.resource = event.routeKey.replace('+', ''); // {proxy+} -> {proxy}
@@ -122,7 +125,7 @@ export class ResourceController extends GenericController {
122
125
  this.authorization = event.headers.Authorization;
123
126
  this.claims = event.requestContext.authorizer?.claims || {};
124
127
  this.principalId = this.claims.sub;
125
- this.cognitoUser = this.principalId ? new CognitoUser(this.claims) : null;
128
+ this.cognitoUser = this.principalId ? new idea_toolbox_1.CognitoUser(this.claims) : null;
126
129
  this.stage = event.requestContext.stage;
127
130
  this.httpMethod = event.httpMethod;
128
131
  this.resource = event.resource.replace('+', ''); // {proxy+} -> {proxy}
@@ -239,7 +242,7 @@ export class ResourceController extends GenericController {
239
242
  * Store the log associated to the request (no response/error handling).
240
243
  */
241
244
  storeLog(succeeded) {
242
- const log = new APIRequestLog({
245
+ const log = new idea_toolbox_1.APIRequestLog({
243
246
  logId: this.logRequestsWithKey,
244
247
  userId: this.principalId,
245
248
  resource: this.resource,
@@ -260,7 +263,7 @@ export class ResourceController extends GenericController {
260
263
  * Search for the specified file path in both the Lambda function's main folder and the layers folder.
261
264
  */
262
265
  sharedResourceExists(filePath) {
263
- return existsSync(`assets/${filePath}`) || existsSync(`/opt/nodejs/assets/${filePath}`);
266
+ return (0, fs_1.existsSync)(`assets/${filePath}`) || (0, fs_1.existsSync)(`/opt/nodejs/assets/${filePath}`);
264
267
  }
265
268
  /**
266
269
  * Load a shared resource in the back-end (translation, template, etc.).
@@ -268,11 +271,11 @@ export class ResourceController extends GenericController {
268
271
  */
269
272
  loadSharedResource(filePath) {
270
273
  let path = null;
271
- if (existsSync(`assets/${filePath}`))
274
+ if ((0, fs_1.existsSync)(`assets/${filePath}`))
272
275
  path = `assets/${filePath}`;
273
- else if (existsSync(`/opt/nodejs/assets/${filePath}`))
276
+ else if ((0, fs_1.existsSync)(`/opt/nodejs/assets/${filePath}`))
274
277
  path = `/opt/nodejs/assets/${filePath}`;
275
- return path ? readFileSync(path, { encoding: 'utf-8' }) : null;
278
+ return path ? (0, fs_1.readFileSync)(path, { encoding: 'utf-8' }) : null;
276
279
  }
277
280
  ///
278
281
  /// MANAGE INTERNAL API REQUESTS (lambda invokes masked as API requests)
@@ -296,7 +299,7 @@ export class ResourceController extends GenericController {
296
299
  Payload: this.mapEventForInternalApiRequest(params),
297
300
  Qualifier: params.stage || this.stage
298
301
  };
299
- const res = await new Lambda().invoke(lambdaInvokeParams).promise();
302
+ const res = await new aws_sdk_1.Lambda().invoke(lambdaInvokeParams).promise();
300
303
  const payload = JSON.parse(res.Payload);
301
304
  const body = JSON.parse(payload.body);
302
305
  if (Number(payload.statusCode) !== 200)
@@ -310,7 +313,7 @@ export class ResourceController extends GenericController {
310
313
  DetailType: params.eventBridge.target,
311
314
  Detail: this.mapEventForInternalApiRequest(params)
312
315
  };
313
- return await new EventBridge().putEvents({ Entries: [request] }).promise();
316
+ return await new aws_sdk_1.EventBridge().putEvents({ Entries: [request] }).promise();
314
317
  }
315
318
  mapEventForInternalApiRequest(params) {
316
319
  const event = JSON.parse(JSON.stringify(this.event));
@@ -413,12 +416,14 @@ export class ResourceController extends GenericController {
413
416
  return value !== undefined && value !== null;
414
417
  }
415
418
  }
419
+ exports.ResourceController = ResourceController;
416
420
  /**
417
421
  * Explicitly define a specific type of error to use in the RC's handler, to distinguish it from the normal errors.
418
422
  */
419
- export class RCError extends Error {
423
+ class RCError extends Error {
420
424
  constructor(message) {
421
425
  super(message);
422
426
  Object.setPrototypeOf(this, RCError.prototype);
423
427
  }
424
428
  }
429
+ exports.RCError = RCError;
package/dist/src/s3.js CHANGED
@@ -1,11 +1,14 @@
1
- import { S3 as AWSS3 } from 'aws-sdk';
2
- import { SignedURL } from 'idea-toolbox';
3
- import { Logger } from './logger';
4
- const logger = new Logger();
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.GetObjectTypes = exports.S3 = void 0;
4
+ const aws_sdk_1 = require("aws-sdk");
5
+ const idea_toolbox_1 = require("idea-toolbox");
6
+ const logger_1 = require("./logger");
7
+ const logger = new logger_1.Logger();
5
8
  /**
6
9
  * A wrapper for AWS Simple Storage Service.
7
10
  */
8
- export class S3 {
11
+ class S3 {
9
12
  /**
10
13
  * Initialize a new S3 helper object.
11
14
  */
@@ -14,7 +17,7 @@ export class S3 {
14
17
  this.DEFAULT_DOWNLOAD_BUCKET = 'idea-downloads';
15
18
  this.DEFAULT_DOWNLOAD_BUCKET_SEC_TO_EXP = 180;
16
19
  this.DEFAULT_UPLOAD_BUCKET_SEC_TO_EXP = 300;
17
- this.s3 = new AWSS3({ apiVersion: '2006-03-01', signatureVersion: 'v4' });
20
+ this.s3 = new aws_sdk_1.S3({ apiVersion: '2006-03-01', signatureVersion: 'v4' });
18
21
  }
19
22
  /**
20
23
  * Create a download link of a piece of data (through S3).
@@ -37,7 +40,7 @@ export class S3 {
37
40
  * @param expires seconds after which the signed URL expires
38
41
  */
39
42
  signedURLPut(bucket, key, expires) {
40
- return new SignedURL({
43
+ return new idea_toolbox_1.SignedURL({
41
44
  url: this.s3.getSignedUrl('putObject', {
42
45
  Bucket: bucket,
43
46
  Key: key,
@@ -50,7 +53,7 @@ export class S3 {
50
53
  * @param expires seconds after which the signed URL expires
51
54
  */
52
55
  signedURLGet(bucket, key, expires) {
53
- return new SignedURL({
56
+ return new idea_toolbox_1.SignedURL({
54
57
  url: this.s3.getSignedUrl('getObject', {
55
58
  Bucket: bucket,
56
59
  Key: key,
@@ -128,11 +131,12 @@ export class S3 {
128
131
  }
129
132
  }
130
133
  }
134
+ exports.S3 = S3;
131
135
  /**
132
136
  * The managed types to convert objects coming from an S3 bucket.
133
137
  */
134
- export var GetObjectTypes;
138
+ var GetObjectTypes;
135
139
  (function (GetObjectTypes) {
136
140
  GetObjectTypes["JSON"] = "JSON";
137
141
  GetObjectTypes["TEXT"] = "TEXT";
138
- })(GetObjectTypes || (GetObjectTypes = {}));
142
+ })(GetObjectTypes = exports.GetObjectTypes || (exports.GetObjectTypes = {}));
@@ -1,10 +1,13 @@
1
- import { SecretsManager as AWSSecretsManager } from 'aws-sdk';
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.SecretsManager = void 0;
4
+ const aws_sdk_1 = require("aws-sdk");
2
5
  /**
3
6
  * A wrapper for AWS Secrets manager.
4
7
  */
5
- export class SecretsManager {
8
+ class SecretsManager {
6
9
  constructor() {
7
- this.sm = new AWSSecretsManager();
10
+ this.sm = new aws_sdk_1.SecretsManager();
8
11
  }
9
12
  /**
10
13
  * Get a secret string from the Secret Manager by its id.
@@ -14,3 +17,4 @@ export class SecretsManager {
14
17
  return result.SecretString;
15
18
  }
16
19
  }
20
+ exports.SecretsManager = SecretsManager;
package/dist/src/ses.js CHANGED
@@ -1,14 +1,17 @@
1
- import { SES as AWSSES } from 'aws-sdk';
2
- import { createTransport as NodemailerCreateTransport } from 'nodemailer';
3
- import { DynamoDB } from './dynamoDB';
4
- import { Logger } from './logger';
5
- const logger = new Logger();
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.SES = void 0;
4
+ const aws_sdk_1 = require("aws-sdk");
5
+ const nodemailer_1 = require("nodemailer");
6
+ const dynamoDB_1 = require("./dynamoDB");
7
+ const logger_1 = require("./logger");
8
+ const logger = new logger_1.Logger();
6
9
  /**
7
10
  * A wrapper for AWS Simple Email Service.
8
11
  */
9
- export class SES {
12
+ class SES {
10
13
  constructor(params = {}) {
11
- this.ses = new AWSSES({ region: params.region });
14
+ this.ses = new aws_sdk_1.SES({ region: params.region });
12
15
  }
13
16
  //
14
17
  // CONFIG
@@ -60,7 +63,7 @@ export class SES {
60
63
  if (this.ses.config.region === sesParams.region)
61
64
  ses = this.ses;
62
65
  else
63
- ses = new AWSSES({ region: sesParams.region });
66
+ ses = new aws_sdk_1.SES({ region: sesParams.region });
64
67
  logger.debug('SES send templated email');
65
68
  return await ses.sendTemplatedEmail(request).promise();
66
69
  }
@@ -82,7 +85,7 @@ export class SES {
82
85
  if (!teamId)
83
86
  return null;
84
87
  try {
85
- return await new DynamoDB().get({ TableName: 'idea_teamsSES', Key: { teamId } });
88
+ return await new dynamoDB_1.DynamoDB().get({ TableName: 'idea_teamsSES', Key: { teamId } });
86
89
  }
87
90
  catch (err) {
88
91
  return null;
@@ -100,7 +103,7 @@ export class SES {
100
103
  if (this.ses.config.region === sesParams.region)
101
104
  ses = this.ses;
102
105
  else
103
- ses = new AWSSES({ region: sesParams.region });
106
+ ses = new aws_sdk_1.SES({ region: sesParams.region });
104
107
  logger.debug('SES send email');
105
108
  return await ses.sendEmail(request).promise();
106
109
  }
@@ -124,9 +127,9 @@ export class SES {
124
127
  if (this.ses.config.region === sesParams.region)
125
128
  ses = this.ses;
126
129
  else
127
- ses = new AWSSES({ region: sesParams.region });
130
+ ses = new aws_sdk_1.SES({ region: sesParams.region });
128
131
  logger.debug('SES send email (Nodemailer)');
129
- return await NodemailerCreateTransport({ SES: ses }).sendMail(mailOptions);
132
+ return await (0, nodemailer_1.createTransport)({ SES: ses }).sendMail(mailOptions);
130
133
  }
131
134
  prepareEmailDestination(emailData) {
132
135
  return {
@@ -149,3 +152,4 @@ export class SES {
149
152
  return message;
150
153
  }
151
154
  }
155
+ exports.SES = SES;
package/dist/src/sns.js CHANGED
@@ -1,9 +1,12 @@
1
- import { SNS as AWSSNS } from 'aws-sdk';
2
- import { PushNotificationsPlatforms, logger } from 'idea-toolbox';
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.SNS = void 0;
4
+ const aws_sdk_1 = require("aws-sdk");
5
+ const idea_toolbox_1 = require("idea-toolbox");
3
6
  /**
4
7
  * A wrapper for AWS Simple Notification Service.
5
8
  */
6
- export class SNS {
9
+ class SNS {
7
10
  /**
8
11
  * Create a new endpoint in the SNS platform specified.
9
12
  * @return platform endpoint ARN
@@ -11,20 +14,20 @@ export class SNS {
11
14
  async createPushPlatormEndpoint(platform, token, snsParams) {
12
15
  let platformARN;
13
16
  switch (platform) {
14
- case PushNotificationsPlatforms.APNS:
17
+ case idea_toolbox_1.PushNotificationsPlatforms.APNS:
15
18
  platformARN = snsParams.appleArn;
16
19
  break;
17
- case PushNotificationsPlatforms.APNS_SANDBOX:
20
+ case idea_toolbox_1.PushNotificationsPlatforms.APNS_SANDBOX:
18
21
  platformARN = snsParams.appleDevArn;
19
22
  break;
20
- case PushNotificationsPlatforms.FCM:
23
+ case idea_toolbox_1.PushNotificationsPlatforms.FCM:
21
24
  platformARN = snsParams.androidArn;
22
25
  break;
23
26
  default:
24
27
  throw new Error('Unsupported platform');
25
28
  }
26
- logger('SNS ADD PLATFORM ENDPOINT');
27
- const result = await new AWSSNS({ apiVersion: '2010-03-31', region: snsParams.region })
29
+ (0, idea_toolbox_1.logger)('SNS ADD PLATFORM ENDPOINT');
30
+ const result = await new aws_sdk_1.SNS({ apiVersion: '2010-03-31', region: snsParams.region })
28
31
  .createPlatformEndpoint({ PlatformApplicationArn: platformARN, Token: token })
29
32
  .promise();
30
33
  return result.EndpointArn;
@@ -38,13 +41,13 @@ export class SNS {
38
41
  structuredMessage = { default: JSON.stringify(snsParams.json) };
39
42
  else
40
43
  switch (snsParams.platform) {
41
- case PushNotificationsPlatforms.APNS:
44
+ case idea_toolbox_1.PushNotificationsPlatforms.APNS:
42
45
  structuredMessage = { APNS: JSON.stringify({ aps: { alert: snsParams.message } }) };
43
46
  break;
44
- case PushNotificationsPlatforms.APNS_SANDBOX:
47
+ case idea_toolbox_1.PushNotificationsPlatforms.APNS_SANDBOX:
45
48
  structuredMessage = { APNS_SANDBOX: JSON.stringify({ aps: { alert: snsParams.message } }) };
46
49
  break;
47
- case PushNotificationsPlatforms.FCM:
50
+ case idea_toolbox_1.PushNotificationsPlatforms.FCM:
48
51
  structuredMessage = {
49
52
  GCM: JSON.stringify({ notification: { body: snsParams.message, title: snsParams.message } })
50
53
  };
@@ -52,9 +55,10 @@ export class SNS {
52
55
  default:
53
56
  throw new Error('Unsupported platform');
54
57
  }
55
- logger('SNS PUBLISH IN TOPIC');
56
- return await new AWSSNS({ apiVersion: '2010-03-31', region: snsParams.region })
58
+ (0, idea_toolbox_1.logger)('SNS PUBLISH IN TOPIC');
59
+ return await new aws_sdk_1.SNS({ apiVersion: '2010-03-31', region: snsParams.region })
57
60
  .publish({ MessageStructure: 'json', Message: JSON.stringify(structuredMessage), TargetArn: snsParams.endpoint })
58
61
  .promise();
59
62
  }
60
63
  }
64
+ exports.SNS = SNS;
@@ -1,13 +1,17 @@
1
- import { GenericController } from './genericController';
2
- import { Logger } from './logger';
3
- const logger = new Logger();
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.StreamController = void 0;
4
+ const genericController_1 = require("./genericController");
5
+ const logger_1 = require("./logger");
6
+ const logger = new logger_1.Logger();
4
7
  /**
5
8
  * An abstract class to inherit to manage AWS DDB streams in an AWS Lambda function.
6
9
  */
7
- export class StreamController extends GenericController {
10
+ class StreamController extends genericController_1.GenericController {
8
11
  constructor(event, callback, options = {}) {
9
12
  super(event, callback, options);
10
13
  this.records = event.Records || [];
11
14
  logger.info(`START STREAM: ${this.records.length || 0} records`);
12
15
  }
13
16
  }
17
+ exports.StreamController = StreamController;
@@ -1,14 +1,17 @@
1
- import { Translate as AWSTranslate } from 'aws-sdk';
2
- import { PDFTemplateSectionTypes } from 'idea-toolbox';
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.Translate = void 0;
4
+ const aws_sdk_1 = require("aws-sdk");
5
+ const idea_toolbox_1 = require("idea-toolbox");
3
6
  /**
4
7
  * A wrapper for Amazon Translate.
5
8
  */
6
- export class Translate {
9
+ class Translate {
7
10
  /**
8
11
  * Initialize a new Translate helper object.
9
12
  */
10
13
  constructor() {
11
- this.translate = new AWSTranslate({ apiVersion: '2017-07-01' });
14
+ this.translate = new aws_sdk_1.Translate({ apiVersion: '2017-07-01' });
12
15
  this.sourceLanguageCode = 'en';
13
16
  this.targetLanguageCode = 'en';
14
17
  this.terminologyNames = new Array();
@@ -69,10 +72,10 @@ export class Translate {
69
72
  const toTranslate = new Set();
70
73
  // gather the terms to translate from contents available on this level
71
74
  template
72
- .filter(s => s.isEither(PDFTemplateSectionTypes.ROW, PDFTemplateSectionTypes.HEADER))
75
+ .filter(s => s.isEither(idea_toolbox_1.PDFTemplateSectionTypes.ROW, idea_toolbox_1.PDFTemplateSectionTypes.HEADER))
73
76
  .forEach(s => {
74
77
  switch (s.type) {
75
- case PDFTemplateSectionTypes.ROW:
78
+ case idea_toolbox_1.PDFTemplateSectionTypes.ROW:
76
79
  s.columns
77
80
  .filter((_, index) => s.doesColumnContainAField(index))
78
81
  .forEach(field => {
@@ -90,7 +93,7 @@ export class Translate {
90
93
  }
91
94
  });
92
95
  break;
93
- case PDFTemplateSectionTypes.HEADER:
96
+ case idea_toolbox_1.PDFTemplateSectionTypes.HEADER:
94
97
  toTranslate.add(s.title[sourceLanguage]);
95
98
  break;
96
99
  }
@@ -98,13 +101,13 @@ export class Translate {
98
101
  // gather inner sections in a flat structure for further elaboraton
99
102
  const innerSections = new Array();
100
103
  template
101
- .filter(s => s.isEither(PDFTemplateSectionTypes.INNER_SECTION, PDFTemplateSectionTypes.REPEATED_INNER_SECTION))
104
+ .filter(s => s.isEither(idea_toolbox_1.PDFTemplateSectionTypes.INNER_SECTION, idea_toolbox_1.PDFTemplateSectionTypes.REPEATED_INNER_SECTION))
102
105
  .forEach(s => {
103
106
  switch (s.type) {
104
- case PDFTemplateSectionTypes.INNER_SECTION:
107
+ case idea_toolbox_1.PDFTemplateSectionTypes.INNER_SECTION:
105
108
  innerSections.push({ data: entity[s.context], template: s.innerTemplate });
106
109
  break;
107
- case PDFTemplateSectionTypes.REPEATED_INNER_SECTION:
110
+ case idea_toolbox_1.PDFTemplateSectionTypes.REPEATED_INNER_SECTION:
108
111
  entity[s.context].forEach((element) => innerSections.push({ data: element, template: s.innerTemplate }));
109
112
  break;
110
113
  }
@@ -118,3 +121,4 @@ export class Translate {
118
121
  return toTranslate;
119
122
  }
120
123
  }
124
+ exports.Translate = Translate;
package/package.json CHANGED
@@ -1,8 +1,7 @@
1
1
  {
2
2
  "name": "idea-aws",
3
- "version": "3.11.8",
3
+ "version": "3.12.1",
4
4
  "description": "AWS wrappers to use in IDEA's back-ends",
5
- "type": "module",
6
5
  "main": "dist/index.js",
7
6
  "types": "dist/index.d.ts",
8
7
  "scripts": {
@@ -36,25 +35,25 @@
36
35
  },
37
36
  "homepage": "https://iter-idea.github.io/IDEA-AWS",
38
37
  "dependencies": {
39
- "idea-toolbox": "^6.5.17",
40
- "nanoid": "^4.0.0",
41
- "nodemailer": "^6.7.5",
38
+ "idea-toolbox": "^6.5.19",
39
+ "nanoid": "^3.3.4",
40
+ "nodemailer": "^6.7.7",
42
41
  "shortid": "^2.2.16",
43
42
  "source-map-support": "^0.5.21",
44
43
  "uuid": "^8.3.2"
45
44
  },
46
45
  "devDependencies": {
47
46
  "@tsconfig/node16": "^1.0.3",
48
- "@types/aws-lambda": "^8.10.91",
49
- "@types/node": "^14.14.26",
47
+ "@types/aws-lambda": "^8.10.101",
48
+ "@types/node": "^18.6.3",
50
49
  "@types/nodemailer": "^6.4.4",
51
50
  "@types/shortid": "^0.0.29",
52
51
  "@types/uuid": "^8.3.4",
53
- "@typescript-eslint/eslint-plugin": "^4.31.1",
54
- "@typescript-eslint/parser": "^4.31.1",
55
- "aws-sdk": "^2.991.0",
56
- "eslint": "^7.32.0",
57
- "typedoc": "^0.23.2",
58
- "typescript": "^4.4.3"
52
+ "@typescript-eslint/eslint-plugin": "^5.32.0",
53
+ "@typescript-eslint/parser": "^5.32.0",
54
+ "aws-sdk": "^2.1187.0",
55
+ "eslint": "^8.21.0",
56
+ "typedoc": "^0.23.10",
57
+ "typescript": "^4.7.4"
59
58
  }
60
59
  }