@appinventiv/aws-ses 0.0.0-stage → 1.0.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.
@@ -0,0 +1,127 @@
1
+ /**
2
+ * @description AWS SES client initialization options
3
+ */
4
+ export interface ISESInitOptions {
5
+ region: string;
6
+ credentials?: {
7
+ accessKeyId: string;
8
+ secretAccessKey: string;
9
+ sessionToken?: string;
10
+ };
11
+ /** Used when send methods omit `from` */
12
+ defaultFrom?: string;
13
+ /** Optional SES configuration set applied to sends */
14
+ configurationSetName?: string;
15
+ }
16
+
17
+ /**
18
+ * @description Email attachment (raw MIME path)
19
+ */
20
+ export interface ISESAttachment {
21
+ filename: string;
22
+ content: Buffer | string;
23
+ contentType?: string;
24
+ /** Content-ID for inline images */
25
+ cid?: string;
26
+ }
27
+
28
+ /**
29
+ * @description App-owned HTML / text send (+ optional attachments)
30
+ */
31
+ export interface ISESSendMailOptions {
32
+ to: string | string[];
33
+ subject: string;
34
+ html?: string;
35
+ text?: string;
36
+ from?: string;
37
+ cc?: string | string[];
38
+ bcc?: string | string[];
39
+ replyTo?: string | string[];
40
+ attachments?: ISESAttachment[];
41
+ }
42
+
43
+ /**
44
+ * @description SES stored template send.
45
+ * Attachments force hydrate + Raw MIME because Content.Template cannot carry files.
46
+ */
47
+ export interface ISESSendTemplatedMailOptions {
48
+ to: string | string[];
49
+ templateName: string;
50
+ /** Object serialized to TemplateData JSON for {{placeholders}} */
51
+ templateData: Record<string, unknown>;
52
+ from?: string;
53
+ cc?: string | string[];
54
+ bcc?: string | string[];
55
+ replyTo?: string | string[];
56
+ attachments?: ISESAttachment[];
57
+ }
58
+
59
+ /**
60
+ * @description Create / update template body stored in SES
61
+ */
62
+ export interface ISESTemplateDefinition {
63
+ templateName: string;
64
+ subject: string;
65
+ html?: string;
66
+ text?: string;
67
+ }
68
+
69
+ /**
70
+ * @description One destination in a bulk send
71
+ */
72
+ export interface ISESBulkDestination {
73
+ to: string | string[];
74
+ cc?: string | string[];
75
+ bcc?: string | string[];
76
+ /** Per-recipient template data (merged over defaultTemplateData) */
77
+ templateData?: Record<string, unknown>;
78
+ html?: string;
79
+ text?: string;
80
+ subject?: string;
81
+ }
82
+
83
+ /**
84
+ * @description Bulk raw / simple HTML send
85
+ */
86
+ export interface ISESSendBulkMailOptions {
87
+ defaultSubject: string;
88
+ defaultHtml?: string;
89
+ defaultText?: string;
90
+ from?: string;
91
+ replyTo?: string | string[];
92
+ attachments?: ISESAttachment[];
93
+ destinations: ISESBulkDestination[];
94
+ /** Max destinations processed per batch (default 50) */
95
+ batchSize?: number;
96
+ }
97
+
98
+ /**
99
+ * @description Bulk templated send
100
+ */
101
+ export interface ISESSendBulkTemplatedMailOptions {
102
+ templateName: string;
103
+ defaultTemplateData?: Record<string, unknown>;
104
+ from?: string;
105
+ replyTo?: string | string[];
106
+ destinations: ISESBulkDestination[];
107
+ batchSize?: number;
108
+ /**
109
+ * Shared attachments. When set, each destination is hydrated and sent as Raw MIME
110
+ * because SendBulkEmail template content cannot carry MIME attachments.
111
+ */
112
+ attachments?: ISESAttachment[];
113
+ }
114
+
115
+ /**
116
+ * @description Result of a send operation
117
+ */
118
+ export interface ISESSendResult {
119
+ messageId: string;
120
+ }
121
+
122
+ /**
123
+ * @description Result of a bulk send
124
+ */
125
+ export interface ISESBulkSendResult {
126
+ messageIds: string[];
127
+ }
package/src/mime.ts ADDED
@@ -0,0 +1,30 @@
1
+ import MailComposer from 'nodemailer/lib/mail-composer';
2
+ import { ISESAttachment, ISESSendMailOptions } from './interface';
3
+
4
+ /**
5
+ * @description Build an RFC822 message buffer for SES Content.Raw
6
+ */
7
+ export async function buildRawMessage(options: ISESSendMailOptions & { from: string }): Promise<Buffer> {
8
+ const composer = new MailComposer({
9
+ from: options.from,
10
+ to: options.to,
11
+ cc: options.cc,
12
+ bcc: options.bcc,
13
+ replyTo: options.replyTo,
14
+ subject: options.subject,
15
+ html: options.html,
16
+ text: options.text,
17
+ attachments: (options.attachments || []).map(toNodemailerAttachment)
18
+ });
19
+
20
+ return composer.compile().build();
21
+ }
22
+
23
+ function toNodemailerAttachment(attachment: ISESAttachment) {
24
+ return {
25
+ filename: attachment.filename,
26
+ content: attachment.content,
27
+ contentType: attachment.contentType,
28
+ cid: attachment.cid
29
+ };
30
+ }
package/src/ses.ts ADDED
@@ -0,0 +1,420 @@
1
+ import {
2
+ CreateEmailTemplateCommand,
3
+ DeleteEmailTemplateCommand,
4
+ GetEmailTemplateCommand,
5
+ SESv2Client,
6
+ SESv2ClientConfig,
7
+ SendBulkEmailCommand,
8
+ SendEmailCommand,
9
+ UpdateEmailTemplateCommand
10
+ } from '@aws-sdk/client-sesv2';
11
+ import { SESException } from './exception-handler';
12
+ import {
13
+ ISESBulkSendResult,
14
+ ISESInitOptions,
15
+ ISESSendBulkMailOptions,
16
+ ISESSendBulkTemplatedMailOptions,
17
+ ISESSendMailOptions,
18
+ ISESSendResult,
19
+ ISESSendTemplatedMailOptions,
20
+ ISESTemplateDefinition
21
+ } from './interface';
22
+ import { buildRawMessage } from './mime';
23
+ import { hydrateDefinition } from './template';
24
+
25
+ const DEFAULT_BATCH_SIZE = 50;
26
+ const RAW_CONCURRENCY = 8;
27
+
28
+ /**
29
+ * @description AWS SES provider for raw HTML, stored templates, attachments, and bulk sends
30
+ */
31
+ export class AWSSESProvider {
32
+ private client: SESv2Client | null = null;
33
+ private defaultFrom?: string;
34
+ private configurationSetName?: string;
35
+ private region?: string;
36
+
37
+ /**
38
+ * @description Initialize SESv2 client once
39
+ * @param {ISESInitOptions} config - Region, optional credentials, defaultFrom, configuration set
40
+ */
41
+ initiateSES(config: ISESInitOptions): void {
42
+ if (this.client) {
43
+ console.info('SES client already initialized; skipping initiateSES.');
44
+ return;
45
+ }
46
+
47
+ try {
48
+ const clientConfig: SESv2ClientConfig = { region: config.region };
49
+ if (config.credentials) {
50
+ clientConfig.credentials = config.credentials;
51
+ }
52
+ this.client = new SESv2Client(clientConfig);
53
+ this.defaultFrom = config.defaultFrom;
54
+ this.configurationSetName = config.configurationSetName;
55
+ this.region = config.region;
56
+ console.info('SES client initialized successfully', JSON.stringify({ region: config.region }));
57
+ } catch (error: unknown) {
58
+ console.error('SES initiateSES failed:', errorMessage(error));
59
+ throw new SESException(error, { operation: 'initiateSES' }).getError();
60
+ }
61
+ }
62
+
63
+ /**
64
+ * @description Send app-owned HTML/text, optionally with attachments, via Content.Raw
65
+ */
66
+ async sendMail(options: ISESSendMailOptions): Promise<ISESSendResult> {
67
+ const from = this.resolveFrom(options.from);
68
+ this.assertContent(options.html, options.text);
69
+ this.assertAddresses(options.to);
70
+
71
+ try {
72
+ const raw = await buildRawMessage({ ...options, from });
73
+ const response = await this.getClient().send(
74
+ new SendEmailCommand({
75
+ FromEmailAddress: from,
76
+ Destination: destinationOf(options.to, options.cc, options.bcc),
77
+ ReplyToAddresses: asAddressList(options.replyTo),
78
+ ConfigurationSetName: this.configurationSetName,
79
+ Content: { Raw: { Data: raw } }
80
+ })
81
+ );
82
+ const messageId = response.MessageId || '';
83
+ console.info('SES mail sent successfully', JSON.stringify({ messageId, region: this.region }));
84
+ return { messageId };
85
+ } catch (error: unknown) {
86
+ console.error('SES sendMail failed:', errorMessage(error));
87
+ throw new SESException(error, { operation: 'sendMail' }).getError();
88
+ }
89
+ }
90
+
91
+ /**
92
+ * @description Send a stored SES template.
93
+ * Without attachments uses Content.Template. With attachments hydrates the template and sends Raw MIME.
94
+ */
95
+ async sendTemplatedMail(options: ISESSendTemplatedMailOptions): Promise<ISESSendResult> {
96
+ const from = this.resolveFrom(options.from);
97
+ this.assertAddresses(options.to);
98
+ if (!options.templateName) {
99
+ throw new SESException(new Error('templateName is required'), { operation: 'sendTemplatedMail' }).getError();
100
+ }
101
+
102
+ if (options.attachments?.length) {
103
+ const hydrated = hydrateDefinition(await this.getTemplate(options.templateName), options.templateData || {});
104
+ return this.sendMail({
105
+ to: options.to,
106
+ cc: options.cc,
107
+ bcc: options.bcc,
108
+ replyTo: options.replyTo,
109
+ from,
110
+ subject: hydrated.subject,
111
+ html: hydrated.html,
112
+ text: hydrated.text,
113
+ attachments: options.attachments
114
+ });
115
+ }
116
+
117
+ try {
118
+ const response = await this.getClient().send(
119
+ new SendEmailCommand({
120
+ FromEmailAddress: from,
121
+ Destination: destinationOf(options.to, options.cc, options.bcc),
122
+ ReplyToAddresses: asAddressList(options.replyTo),
123
+ ConfigurationSetName: this.configurationSetName,
124
+ Content: {
125
+ Template: {
126
+ TemplateName: options.templateName,
127
+ TemplateData: JSON.stringify(options.templateData || {})
128
+ }
129
+ }
130
+ })
131
+ );
132
+ const messageId = response.MessageId || '';
133
+ console.info(
134
+ 'SES templated mail sent successfully',
135
+ JSON.stringify({ messageId, templateName: options.templateName, region: this.region })
136
+ );
137
+ return { messageId };
138
+ } catch (error: unknown) {
139
+ console.error('SES sendTemplatedMail failed:', errorMessage(error));
140
+ throw new SESException(error, { operation: 'sendTemplatedMail', templateName: options.templateName }).getError();
141
+ }
142
+ }
143
+
144
+ /**
145
+ * @description Send the same HTML/text (and optional shared attachments) to many destinations in batches
146
+ */
147
+ async sendBulkMail(options: ISESSendBulkMailOptions): Promise<ISESBulkSendResult> {
148
+ if (!options.destinations?.length) {
149
+ throw new SESException(new Error('destinations is required'), { operation: 'sendBulkMail' }).getError();
150
+ }
151
+
152
+ const messageIds: string[] = [];
153
+ const batches = chunk(options.destinations, options.batchSize || DEFAULT_BATCH_SIZE);
154
+
155
+ for (const batch of batches) {
156
+ const ids = await mapWithConcurrency(batch, RAW_CONCURRENCY, async (destination) => {
157
+ const result = await this.sendMail({
158
+ to: destination.to,
159
+ cc: destination.cc,
160
+ bcc: destination.bcc,
161
+ from: options.from,
162
+ replyTo: options.replyTo,
163
+ subject: destination.subject || options.defaultSubject,
164
+ html: destination.html || options.defaultHtml,
165
+ text: destination.text || options.defaultText,
166
+ attachments: options.attachments
167
+ });
168
+ return result.messageId;
169
+ });
170
+ messageIds.push(...ids);
171
+ }
172
+
173
+ return { messageIds };
174
+ }
175
+
176
+ /**
177
+ * @description Bulk templated send.
178
+ * Without attachments uses SendBulkEmail. With attachments hydrates each destination and sends Raw MIME.
179
+ */
180
+ async sendBulkTemplatedMail(options: ISESSendBulkTemplatedMailOptions): Promise<ISESBulkSendResult> {
181
+ if (!options.templateName) {
182
+ throw new SESException(new Error('templateName is required'), { operation: 'sendBulkTemplatedMail' }).getError();
183
+ }
184
+ if (!options.destinations?.length) {
185
+ throw new SESException(new Error('destinations is required'), { operation: 'sendBulkTemplatedMail' }).getError();
186
+ }
187
+
188
+ if (options.attachments?.length) {
189
+ const definition = await this.getTemplate(options.templateName);
190
+ const messageIds: string[] = [];
191
+ const batches = chunk(options.destinations, options.batchSize || DEFAULT_BATCH_SIZE);
192
+
193
+ for (const batch of batches) {
194
+ const ids = await mapWithConcurrency(batch, RAW_CONCURRENCY, async (destination) => {
195
+ const data = { ...(options.defaultTemplateData || {}), ...(destination.templateData || {}) };
196
+ const hydrated = hydrateDefinition(definition, data);
197
+ const result = await this.sendMail({
198
+ to: destination.to,
199
+ cc: destination.cc,
200
+ bcc: destination.bcc,
201
+ from: options.from,
202
+ replyTo: options.replyTo,
203
+ subject: hydrated.subject,
204
+ html: hydrated.html,
205
+ text: hydrated.text,
206
+ attachments: options.attachments
207
+ });
208
+ return result.messageId;
209
+ });
210
+ messageIds.push(...ids);
211
+ }
212
+
213
+ return { messageIds };
214
+ }
215
+
216
+ const from = this.resolveFrom(options.from);
217
+ const messageIds: string[] = [];
218
+ const batches = chunk(options.destinations, options.batchSize || DEFAULT_BATCH_SIZE);
219
+
220
+ try {
221
+ for (const batch of batches) {
222
+ const response = await this.getClient().send(
223
+ new SendBulkEmailCommand({
224
+ FromEmailAddress: from,
225
+ ReplyToAddresses: asAddressList(options.replyTo),
226
+ ConfigurationSetName: this.configurationSetName,
227
+ DefaultContent: {
228
+ Template: {
229
+ TemplateName: options.templateName,
230
+ TemplateData: JSON.stringify(options.defaultTemplateData || {})
231
+ }
232
+ },
233
+ BulkEmailEntries: batch.map((destination) => ({
234
+ Destination: destinationOf(destination.to, destination.cc, destination.bcc),
235
+ ReplacementEmailContent: {
236
+ ReplacementTemplate: {
237
+ ReplacementTemplateData: JSON.stringify({
238
+ ...(options.defaultTemplateData || {}),
239
+ ...(destination.templateData || {})
240
+ })
241
+ }
242
+ }
243
+ }))
244
+ })
245
+ );
246
+
247
+ for (const entry of response.BulkEmailEntryResults || []) {
248
+ if (entry.Status && entry.Status !== 'SUCCESS') {
249
+ throw new Error(`Bulk entry failed: ${entry.Status} ${entry.Error || ''}`.trim());
250
+ }
251
+ if (entry.MessageId) {
252
+ messageIds.push(entry.MessageId);
253
+ }
254
+ }
255
+ }
256
+
257
+ console.info(
258
+ 'SES bulk templated mail sent successfully',
259
+ JSON.stringify({ count: messageIds.length, templateName: options.templateName, region: this.region })
260
+ );
261
+ return { messageIds };
262
+ } catch (error: unknown) {
263
+ console.error('SES sendBulkTemplatedMail failed:', errorMessage(error));
264
+ throw new SESException(error, { operation: 'sendBulkTemplatedMail', templateName: options.templateName }).getError();
265
+ }
266
+ }
267
+
268
+ /**
269
+ * @description Create an email template in SES
270
+ */
271
+ async createTemplate(definition: ISESTemplateDefinition): Promise<void> {
272
+ try {
273
+ await this.getClient().send(
274
+ new CreateEmailTemplateCommand({
275
+ TemplateName: definition.templateName,
276
+ TemplateContent: templateContent(definition)
277
+ })
278
+ );
279
+ console.info('SES template created', JSON.stringify({ templateName: definition.templateName }));
280
+ } catch (error: unknown) {
281
+ console.error('SES createTemplate failed:', errorMessage(error));
282
+ throw new SESException(error, { operation: 'createTemplate', templateName: definition.templateName }).getError();
283
+ }
284
+ }
285
+
286
+ /**
287
+ * @description Update an existing SES email template
288
+ */
289
+ async updateTemplate(definition: ISESTemplateDefinition): Promise<void> {
290
+ try {
291
+ await this.getClient().send(
292
+ new UpdateEmailTemplateCommand({
293
+ TemplateName: definition.templateName,
294
+ TemplateContent: templateContent(definition)
295
+ })
296
+ );
297
+ console.info('SES template updated', JSON.stringify({ templateName: definition.templateName }));
298
+ } catch (error: unknown) {
299
+ console.error('SES updateTemplate failed:', errorMessage(error));
300
+ throw new SESException(error, { operation: 'updateTemplate', templateName: definition.templateName }).getError();
301
+ }
302
+ }
303
+
304
+ /**
305
+ * @description Delete an SES email template
306
+ */
307
+ async deleteTemplate(templateName: string): Promise<void> {
308
+ try {
309
+ await this.getClient().send(new DeleteEmailTemplateCommand({ TemplateName: templateName }));
310
+ console.info('SES template deleted', JSON.stringify({ templateName }));
311
+ } catch (error: unknown) {
312
+ console.error('SES deleteTemplate failed:', errorMessage(error));
313
+ throw new SESException(error, { operation: 'deleteTemplate', templateName }).getError();
314
+ }
315
+ }
316
+
317
+ /**
318
+ * @description Load an SES email template
319
+ */
320
+ async getTemplate(templateName: string): Promise<ISESTemplateDefinition> {
321
+ try {
322
+ const response = await this.getClient().send(new GetEmailTemplateCommand({ TemplateName: templateName }));
323
+ return {
324
+ templateName: response.TemplateName || templateName,
325
+ subject: response.TemplateContent?.Subject || '',
326
+ html: response.TemplateContent?.Html,
327
+ text: response.TemplateContent?.Text
328
+ };
329
+ } catch (error: unknown) {
330
+ console.error('SES getTemplate failed:', errorMessage(error));
331
+ throw new SESException(error, { operation: 'getTemplate', templateName }).getError();
332
+ }
333
+ }
334
+
335
+ /**
336
+ * @description Underlying SESv2 client (throws if not initialized)
337
+ */
338
+ getClient(): SESv2Client {
339
+ if (!this.client) {
340
+ throw new Error('SES is not configured. Call initiateSES(config) before sending mail.');
341
+ }
342
+ return this.client;
343
+ }
344
+
345
+ private resolveFrom(from?: string): string {
346
+ const resolved = from ?? this.defaultFrom;
347
+ if (!resolved) {
348
+ throw new Error('Missing "from". Pass `from` or set `defaultFrom` in initiateSES config.');
349
+ }
350
+ return resolved;
351
+ }
352
+
353
+ private assertContent(html?: string, text?: string): void {
354
+ if (!html && !text) {
355
+ throw new Error('Provide at least one of html or text.');
356
+ }
357
+ }
358
+
359
+ private assertAddresses(to: string | string[]): void {
360
+ if (!asAddressList(to)?.length) {
361
+ throw new Error('At least one "to" address is required.');
362
+ }
363
+ }
364
+ }
365
+
366
+ /** Pre-configured SES provider singleton */
367
+ export const ses = new AWSSESProvider();
368
+
369
+ function asAddressList(value?: string | string[]): string[] | undefined {
370
+ if (!value) {
371
+ return undefined;
372
+ }
373
+ const list = (Array.isArray(value) ? value : [value]).map((item) => item.trim()).filter(Boolean);
374
+ return list.length ? list : undefined;
375
+ }
376
+
377
+ function destinationOf(to: string | string[], cc?: string | string[], bcc?: string | string[]) {
378
+ return {
379
+ ToAddresses: asAddressList(to),
380
+ CcAddresses: asAddressList(cc),
381
+ BccAddresses: asAddressList(bcc)
382
+ };
383
+ }
384
+
385
+ function templateContent(definition: ISESTemplateDefinition) {
386
+ return {
387
+ Subject: definition.subject,
388
+ Html: definition.html,
389
+ Text: definition.text
390
+ };
391
+ }
392
+
393
+ function chunk<T>(items: T[], size: number): T[][] {
394
+ const batches: T[][] = [];
395
+ for (let index = 0; index < items.length; index += size) {
396
+ batches.push(items.slice(index, index + size));
397
+ }
398
+ return batches;
399
+ }
400
+
401
+ async function mapWithConcurrency<T, R>(items: T[], limit: number, worker: (item: T) => Promise<R>): Promise<R[]> {
402
+ const results: R[] = new Array(items.length);
403
+ let cursor = 0;
404
+
405
+ async function run(): Promise<void> {
406
+ while (cursor < items.length) {
407
+ const index = cursor;
408
+ cursor += 1;
409
+ results[index] = await worker(items[index]);
410
+ }
411
+ }
412
+
413
+ const runners = Array.from({ length: Math.min(limit, items.length) }, () => run());
414
+ await Promise.all(runners);
415
+ return results;
416
+ }
417
+
418
+ function errorMessage(error: unknown): string {
419
+ return error instanceof Error ? error.message : String(error);
420
+ }
@@ -0,0 +1,37 @@
1
+ import { ISESTemplateDefinition } from './interface';
2
+
3
+ /**
4
+ * @description Replace {{token}} and {{nested.key}} placeholders with data values
5
+ * @param {string} template - Subject, HTML, or text body
6
+ * @param {Record<string, unknown>} data - Placeholder values
7
+ */
8
+ export function hydrateTemplate(template: string, data: Record<string, unknown>): string {
9
+ return template.replace(/\{\{\s*([a-zA-Z0-9_.]+)\s*\}\}/g, (_match, token: string) => {
10
+ const value = resolvePath(data, token);
11
+ return value === undefined || value === null ? '' : String(value);
12
+ });
13
+ }
14
+
15
+ /**
16
+ * @description Apply template data to a stored SES template definition
17
+ */
18
+ export function hydrateDefinition(
19
+ definition: ISESTemplateDefinition,
20
+ data: Record<string, unknown>
21
+ ): ISESTemplateDefinition {
22
+ return {
23
+ templateName: definition.templateName,
24
+ subject: hydrateTemplate(definition.subject || '', data),
25
+ html: definition.html ? hydrateTemplate(definition.html, data) : undefined,
26
+ text: definition.text ? hydrateTemplate(definition.text, data) : undefined
27
+ };
28
+ }
29
+
30
+ function resolvePath(data: Record<string, unknown>, token: string): unknown {
31
+ return token.split('.').reduce<unknown>((current, key) => {
32
+ if (current && typeof current === 'object' && key in (current as Record<string, unknown>)) {
33
+ return (current as Record<string, unknown>)[key];
34
+ }
35
+ return undefined;
36
+ }, data);
37
+ }
package/tsconfig.json ADDED
@@ -0,0 +1,20 @@
1
+ {
2
+ "compilerOptions": {
3
+ "declaration": true,
4
+ "target": "es2022",
5
+ "module": "commonjs",
6
+ "incremental": true,
7
+ "noEmit": false,
8
+ "outDir": "./dist",
9
+ "esModuleInterop": true,
10
+ "forceConsistentCasingInFileNames": true,
11
+ "strict": true,
12
+ "skipLibCheck": true,
13
+ "strictPropertyInitialization": false,
14
+ "sourceMap": true,
15
+ "resolveJsonModule": true,
16
+ "experimentalDecorators": true,
17
+ "emitDecoratorMetadata": true,
18
+ "baseUrl": "."
19
+ }
20
+ }